Merge branch 'claude/size3-cd6' into claude/hexagonal-finish-14ee3a
This commit is contained in:
@@ -31,13 +31,7 @@ pub(crate) fn plan_ple_row(
|
||||
a: &PleAddrs,
|
||||
row: usize,
|
||||
) -> Result<Vec<Launch>> {
|
||||
check_geometry(geo)?;
|
||||
if row >= geo.max_t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if !(ple.native_value_bf16 && ple.native_postops) {
|
||||
return Err(refuse("ple_layer1"));
|
||||
}
|
||||
check_ple_row(geo, ple, row)?;
|
||||
let mut out = Vec::with_capacity(14);
|
||||
out.push(write_row(arena, cfg, row, "ple_layer1")?);
|
||||
|
||||
@@ -52,6 +46,17 @@ pub(crate) fn plan_ple_row(
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn check_ple_row(geo: &OriginalVerifyGeometry, ple: &PleConfig, row: usize) -> Result<()> {
|
||||
check_geometry(geo)?;
|
||||
if row >= geo.max_t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if !(ple.native_value_bf16 && ple.native_postops) {
|
||||
return Err(refuse("ple_layer1"));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The `ple_block` workspace addresses carved from the scratch base.
|
||||
struct PleScratch {
|
||||
key: u64,
|
||||
@@ -202,12 +207,8 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
|
||||
}
|
||||
})
|
||||
}
|
||||
pub(crate) fn ple_addrs(&self) -> Result<PleAddrs> {
|
||||
let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?;
|
||||
let c = self.context;
|
||||
let key = self.ple_key_addr(&p.key)?;
|
||||
let scratch = p.scratch;
|
||||
if !std::ptr::eq(c, scratch.context) {
|
||||
fn ple_scratch_addr(&self, scratch: &'a DeviceBuffer<'ctx>) -> Result<u64> {
|
||||
if !std::ptr::eq(self.context, scratch.context) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
if scratch.len() < PLE_SCRATCH_BYTES {
|
||||
@@ -215,6 +216,13 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
|
||||
}
|
||||
let scratch_handle = handle(scratch)?;
|
||||
scratch_handle.validate_projection_extent(PLE_SCRATCH_BYTES, 4)?;
|
||||
Ok(scratch_handle.qwen_address())
|
||||
}
|
||||
pub(crate) fn ple_addrs(&self) -> Result<PleAddrs> {
|
||||
let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?;
|
||||
let c = self.context;
|
||||
let key = self.ple_key_addr(&p.key)?;
|
||||
let scratch = self.ple_scratch_addr(p.scratch)?;
|
||||
Ok(PleAddrs {
|
||||
key,
|
||||
value: admit(c, p.value, PLE_VALUE_BYTES)?,
|
||||
@@ -222,7 +230,7 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
|
||||
norm_query: admit(c, p.norm_query, PLE_NORM_BYTES)?,
|
||||
norm_conv: admit(c, p.norm_conv, PLE_NORM_BYTES)?,
|
||||
conv1d: admit(c, p.conv1d, PLE_CONV_BYTES)?,
|
||||
scratch: scratch_handle.qwen_address(),
|
||||
scratch,
|
||||
history: admit(c, p.history, PLE_HISTORY_BYTES)?,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -9,27 +9,34 @@ use super::*;
|
||||
pub(crate) fn pcie_fast_kernel() -> Option<(&'static str, [u32; 3], [u32; 3])> {
|
||||
static CHOICE: std::sync::OnceLock<Option<(&'static str, [u32; 3], [u32; 3])>> = std::sync::OnceLock::new();
|
||||
*CHOICE.get_or_init(|| {
|
||||
let name = match std::env::var("LELEKA_PCIE_KERNEL").ok()?.as_str() {
|
||||
"k1u4" => "verify_fetch_spans_k1u4_kernel",
|
||||
"k1u8" => "verify_fetch_spans_k1u8_kernel",
|
||||
"k1u16" => "verify_fetch_spans_k1u16_kernel",
|
||||
"k2u4" => "verify_fetch_spans_k2u4_kernel",
|
||||
"k2u8" => "verify_fetch_spans_k2u8_kernel",
|
||||
"k2u16" => "verify_fetch_spans_k2u16_kernel",
|
||||
_ => return None,
|
||||
};
|
||||
let (blocks, threads) = std::env::var("LELEKA_PCIE_GRID")
|
||||
.ok()
|
||||
.and_then(|v| {
|
||||
let (b, t) = v.split_once('x')?;
|
||||
Some((b.parse::<u32>().ok()?, t.parse::<u32>().ok()?))
|
||||
})
|
||||
.filter(|&(b, t)| (1..=4096).contains(&b) && (32..=1024).contains(&t) && t % 32 == 0)
|
||||
.unwrap_or((48 * 8, 256));
|
||||
let name = pcie_kernel_name(std::env::var("LELEKA_PCIE_KERNEL").ok()?.as_str())?;
|
||||
let (blocks, threads) = pcie_grid(std::env::var("LELEKA_PCIE_GRID").ok());
|
||||
Some((name, [blocks, 1, 1], [threads, 1, 1]))
|
||||
})
|
||||
}
|
||||
|
||||
fn pcie_kernel_name(choice: &str) -> Option<&'static str> {
|
||||
Some(match choice {
|
||||
"k1u4" => "verify_fetch_spans_k1u4_kernel",
|
||||
"k1u8" => "verify_fetch_spans_k1u8_kernel",
|
||||
"k1u16" => "verify_fetch_spans_k1u16_kernel",
|
||||
"k2u4" => "verify_fetch_spans_k2u4_kernel",
|
||||
"k2u8" => "verify_fetch_spans_k2u8_kernel",
|
||||
"k2u16" => "verify_fetch_spans_k2u16_kernel",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn pcie_grid(value: Option<String>) -> (u32, u32) {
|
||||
value
|
||||
.and_then(|v| {
|
||||
let (b, t) = v.split_once('x')?;
|
||||
Some((b.parse::<u32>().ok()?, t.parse::<u32>().ok()?))
|
||||
})
|
||||
.filter(|&(b, t)| (1..=4096).contains(&b) && (32..=1024).contains(&t) && t % 32 == 0)
|
||||
.unwrap_or((48 * 8, 256))
|
||||
}
|
||||
|
||||
/// Every module the MoE producers may launch from (the lead loads them all before capture).
|
||||
pub(crate) fn assets() -> Vec<&'static AssetSpec> {
|
||||
vec![
|
||||
@@ -107,8 +114,7 @@ impl ExpertBlob {
|
||||
|
||||
/// `native_expert_supported` + `native_expert_layout`.
|
||||
pub(super) fn expert_blob(gu_type: u32, d_type: u32, n_embd: usize, n_ff: usize) -> Result<ExpertBlob> {
|
||||
let (qg, qd) = (gu_qk(gu_type), d_qk(d_type));
|
||||
if qg == 0 || qd == 0 || n_embd % qg != 0 || n_ff % qd != 0 || n_embd % 256 != 0 || (n_ff * n_embd) % 256 != 0 {
|
||||
if !expert_dims_supported((gu_qk(gu_type), d_qk(d_type)), n_embd, n_ff) {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
let gu_row = native_head_row_bytes(gu_type, n_embd)?;
|
||||
@@ -118,6 +124,9 @@ pub(super) fn expert_blob(gu_type: u32, d_type: u32, n_embd: usize, n_ff: usize)
|
||||
let bytes = n_embd.checked_mul(d_row).and_then(|d| d.checked_add(down_off)).ok_or(Error::InvalidSize)?;
|
||||
Ok(ExpertBlob { gu_type, d_type, n_embd, n_ff, gu_row, d_row, up_off, down_off, bytes })
|
||||
}
|
||||
fn expert_dims_supported((qg, qd): (usize, usize), n_embd: usize, n_ff: usize) -> bool {
|
||||
qg != 0 && qd != 0 && n_embd % qg == 0 && n_ff % qd == 0 && n_embd % 256 == 0 && (n_ff * n_embd) % 256 == 0
|
||||
}
|
||||
impl OriginalVerifyExpertFormats {
|
||||
/// Every pair must be one `native_expert_grouped` has kernels for at these dimensions; anything else
|
||||
/// is refused here, before a window is recorded.
|
||||
@@ -149,11 +158,7 @@ impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> {
|
||||
}
|
||||
let router_bytes = experts.checked_mul(n_embd).and_then(|x| x.checked_mul(2)).ok_or(Error::InvalidSize)?;
|
||||
for layer in &layers {
|
||||
admit(context, layer.router, router_bytes)?;
|
||||
admit(context, layer.gate_inp_shexp, n_embd * 2)?;
|
||||
admit(context, layer.gate_shexp, n_ff * native_head_row_bytes(layer.gate_shexp_type, n_embd)?)?;
|
||||
admit(context, layer.up_shexp, n_ff * native_head_row_bytes(layer.up_shexp_type, n_embd)?)?;
|
||||
admit(context, layer.down_shexp, n_embd * native_head_row_bytes(layer.down_shexp_type, n_ff)?)?;
|
||||
admit_layer(context, layer, (n_embd, n_ff), router_bytes)?;
|
||||
}
|
||||
Ok(Self { layers, formats, n_embd, n_ff, experts })
|
||||
}
|
||||
@@ -174,31 +179,44 @@ impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> {
|
||||
pub(crate) fn addrs(&self, layer: usize) -> Result<MoeLayerAddrs> {
|
||||
let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?;
|
||||
let (n, f) = (self.n_embd, self.n_ff);
|
||||
let address = |b: &DeviceBuffer<'_>, bytes: usize| -> Result<u64> {
|
||||
if b.len() != bytes {
|
||||
return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() });
|
||||
}
|
||||
Ok(handle(b)?.qwen_address())
|
||||
};
|
||||
Ok(MoeLayerAddrs {
|
||||
router: address(l.router, self.experts * n * 2)?,
|
||||
gate_inp_shexp: address(l.gate_inp_shexp, n * 2)?,
|
||||
gate_shexp: NativeWeight {
|
||||
ty: l.gate_shexp_type,
|
||||
data: address(l.gate_shexp, f * native_head_row_bytes(l.gate_shexp_type, n)?)?,
|
||||
},
|
||||
up_shexp: NativeWeight {
|
||||
ty: l.up_shexp_type,
|
||||
data: address(l.up_shexp, f * native_head_row_bytes(l.up_shexp_type, n)?)?,
|
||||
},
|
||||
down_shexp: NativeWeight {
|
||||
ty: l.down_shexp_type,
|
||||
data: address(l.down_shexp, n * native_head_row_bytes(l.down_shexp_type, f)?)?,
|
||||
},
|
||||
router: exact_address(l.router, self.experts * n * 2)?,
|
||||
gate_inp_shexp: exact_address(l.gate_inp_shexp, n * 2)?,
|
||||
gate_shexp: shexp_address(l.gate_shexp, l.gate_shexp_type, (f, n))?,
|
||||
up_shexp: shexp_address(l.up_shexp, l.up_shexp_type, (f, n))?,
|
||||
down_shexp: shexp_address(l.down_shexp, l.down_shexp_type, (n, f))?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The device address of `b` when it holds exactly `bytes`.
|
||||
fn exact_address(b: &DeviceBuffer<'_>, bytes: usize) -> Result<u64> {
|
||||
if b.len() != bytes {
|
||||
return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() });
|
||||
}
|
||||
Ok(handle(b)?.qwen_address())
|
||||
}
|
||||
|
||||
/// A shared-expert weight of `rows` rows of `k` values in ggml type `ty`.
|
||||
fn shexp_address(b: &DeviceBuffer<'_>, ty: u32, (rows, k): (usize, usize)) -> Result<NativeWeight> {
|
||||
Ok(NativeWeight { ty, data: exact_address(b, rows * native_head_row_bytes(ty, k)?)? })
|
||||
}
|
||||
|
||||
/// The `new` admission of one layer's router and shared-expert buffers.
|
||||
fn admit_layer(
|
||||
context: &Context<'_>,
|
||||
layer: &OriginalVerifyMoeLayerWeights<'_, '_>,
|
||||
(n_embd, n_ff): (usize, usize),
|
||||
router_bytes: usize,
|
||||
) -> Result<()> {
|
||||
admit(context, layer.router, router_bytes)?;
|
||||
admit(context, layer.gate_inp_shexp, n_embd * 2)?;
|
||||
admit(context, layer.gate_shexp, n_ff * native_head_row_bytes(layer.gate_shexp_type, n_embd)?)?;
|
||||
admit(context, layer.up_shexp, n_ff * native_head_row_bytes(layer.up_shexp_type, n_embd)?)?;
|
||||
admit(context, layer.down_shexp, n_embd * native_head_row_bytes(layer.down_shexp_type, n_ff)?)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Planner helpers
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
@@ -198,25 +198,30 @@ pub(crate) fn plan_combine(
|
||||
batched: bool,
|
||||
) -> Result<Vec<Launch>> {
|
||||
let n = check_rows(g, rows)?;
|
||||
let (n_embd, k) = (g.n, g.k);
|
||||
if batched {
|
||||
return combine_batched(arena, g, knobs, rows);
|
||||
}
|
||||
let mut out = Vec::with_capacity(n);
|
||||
for t in rows.begin..rows.end {
|
||||
let parts = f32s(arena, "parts", t * k * n_embd, k * n_embd)?;
|
||||
let w = f32s(arena, "w", t * k, k)?;
|
||||
let shared = f32s(arena, "shared", t * n_embd, n_embd)?;
|
||||
let bo = f32s(arena, "bo", t * n_embd, n_embd)?;
|
||||
if knobs.native_combine {
|
||||
out.push(combine_native(g, [parts, w, shared, bo], 1)?);
|
||||
} else {
|
||||
out.push(combine_legacy(g, [parts, w, shared, bo])?);
|
||||
}
|
||||
out.push(combine_row(arena, g, knobs, t)?);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The per-row combine launch of row `t`.
|
||||
fn combine_row(arena: &dyn ArenaMap, g: &OriginalVerifyGeometry, knobs: &MoeKnobs, t: usize) -> Result<Launch> {
|
||||
let (n_embd, k) = (g.n, g.k);
|
||||
let parts = f32s(arena, "parts", t * k * n_embd, k * n_embd)?;
|
||||
let w = f32s(arena, "w", t * k, k)?;
|
||||
let shared = f32s(arena, "shared", t * n_embd, n_embd)?;
|
||||
let bo = f32s(arena, "bo", t * n_embd, n_embd)?;
|
||||
if knobs.native_combine {
|
||||
combine_native(g, [parts, w, shared, bo], 1)
|
||||
} else {
|
||||
combine_legacy(g, [parts, w, shared, bo])
|
||||
}
|
||||
}
|
||||
|
||||
/// `native_moe_combine` over `tokens` rows of `[parts, w, shared, bo]` (`grid.y` = token).
|
||||
fn combine_native(g: &OriginalVerifyGeometry, [parts, w, shared, bo]: [u64; 4], tokens: usize) -> Result<Launch> {
|
||||
let (n_embd, k) = (g.n, g.k);
|
||||
|
||||
@@ -104,23 +104,29 @@ fn router_batched(
|
||||
|
||||
/// `moe_route` of row `t`: the logits GEMV, then the native top-10 or the generic `router_top10_kernel`.
|
||||
fn router_row(spans: &RouterSpans<'_>, knobs: &MoeKnobs, router: u64, t: usize, out: &mut Vec<Launch>) -> Result<()> {
|
||||
let (n_embd, ne, k) = (spans.n_embd, spans.ne, spans.k);
|
||||
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)?);
|
||||
if knobs.native_router {
|
||||
out.push(plan_route(y, spans.ids(t, 1)?, spans.weights(t, 1)?, 1)?);
|
||||
} else {
|
||||
// router_top10(logits, 1, NE, K, ids, weights): threads = min(NE, 512) rounded to a warp,
|
||||
// smem = taken (NE rounded to 16) + NE doubles + NE floats.
|
||||
let smem = ((ne + 15) & !15) + ne * 8 + ne * 4;
|
||||
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)];
|
||||
out.push(Launch::new(&ROUTER_LEGACY, E_ROUTER_TOP10, [1, 1, 1], [threads, 1, 1], smem as u32, args)?);
|
||||
out.push(router_top10_generic(spans, y, t)?);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The generic `router_top10_kernel` launch of row `t` over the logits `y`.
|
||||
fn router_top10_generic(spans: &RouterSpans<'_>, y: u64, t: usize) -> Result<Launch> {
|
||||
let (ne, k) = (spans.ne, spans.k);
|
||||
// router_top10(logits, 1, NE, K, ids, weights): threads = min(NE, 512) rounded to a warp,
|
||||
// smem = taken (NE rounded to 16) + NE doubles + NE floats.
|
||||
let smem = ((ne + 15) & !15) + ne * 8 + ne * 4;
|
||||
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)
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// shared expert
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -196,12 +202,19 @@ impl SharedExpert<'_> {
|
||||
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)?);
|
||||
self.swiglu_down([gate, up, xq, shared], out)?;
|
||||
Ok((gscalar, shared))
|
||||
}
|
||||
|
||||
/// SwiGLU of `gate` and `up` (into `gate`), then the down projection into `shared`.
|
||||
fn swiglu_down(&self, [gate, up, xq, shared]: [u64; 4], out: &mut Vec<Launch>) -> Result<()> {
|
||||
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(plan_quantize_q8_1(gate, xq, n_ff, n)?);
|
||||
out.push(plan_mmvq(&w.down_shexp, xq, shared, n_ff, n_embd, n, dispatch)?);
|
||||
Ok((gscalar, shared))
|
||||
out.push(plan_mmvq(&self.w.down_shexp, xq, shared, n_ff, n_embd, n, self.knobs.dispatch)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn gate_scalar(&self, gscalar: u64, out: &mut Vec<Launch>) -> Result<()> {
|
||||
|
||||
@@ -84,7 +84,8 @@ fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_, '_>, pol
|
||||
static SAID: std::sync::Once = std::sync::Once::new();
|
||||
SAID.call_once(|| {
|
||||
eprintln!(
|
||||
"leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} (compute capability {major}.{minor}, requested {want:?})",
|
||||
"leleka-serve sm120 switches: attn_daily={} gu_swiglu={} side_mixer={} \
|
||||
(compute capability {major}.{minor}, requested {want:?})",
|
||||
policy.qsa.attn_daily, policy.gu_swiglu, policy.side_mixer
|
||||
)
|
||||
});
|
||||
|
||||
@@ -27,6 +27,34 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
|
||||
self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?;
|
||||
self.capture.side_end(1)
|
||||
}
|
||||
/// The first half of `embed`: the verifier's staged tokens are copied (device to device, in capture order) into
|
||||
/// the embedding rows' own staged token bank before the gather.
|
||||
pub(super) fn embed_stage_tokens(&mut self) -> Result<()> {
|
||||
let t = self.t;
|
||||
let tokens = handle(self.resources.embed.tokens_mut()?)?.qwen_address();
|
||||
let source = self.journal().address("tok", 0, t * 4)?;
|
||||
// The embedding rows read their own staged token bank; the verifier's staged tokens are
|
||||
// copied (device to device, in capture order) into it before the gather.
|
||||
self.submit(vec![command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![Arg::Address(tokens), Arg::Address(source), Arg::I32(t as i32)],
|
||||
)?])
|
||||
}
|
||||
/// The second half of `embed`: the embedded row is broadcast over the hyper-connection streams of `R`.
|
||||
pub(super) fn embed_broadcast(&mut self) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let t = self.t;
|
||||
let embedded = handle(self.resources.embed.output_device()?)?.qwen_address();
|
||||
let residual = self.journal().address("R", 0, t * g.hc * g.n * 4)?;
|
||||
self.submit(vec![command(
|
||||
"verify_broadcast_streams_kernel",
|
||||
[(g.n * g.hc).div_ceil(256) as u32, t as u32, 1],
|
||||
[256, 1, 1],
|
||||
vec![Arg::Address(embedded), Arg::Address(residual), Arg::I64(g.n as i64), Arg::I32(g.hc as i32)],
|
||||
)?])
|
||||
}
|
||||
pub(super) fn geometry(&self) -> OriginalVerifyGeometry {
|
||||
self.resources.base.journal.geometry()
|
||||
}
|
||||
|
||||
+4
-21
@@ -5,27 +5,9 @@ use super::*;
|
||||
|
||||
impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
|
||||
fn embed(&mut self) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let t = self.t;
|
||||
let tokens = handle(self.resources.embed.tokens_mut()?)?.qwen_address();
|
||||
let source = self.journal().address("tok", 0, t * 4)?;
|
||||
// The embedding rows read their own staged token bank; the verifier's staged tokens are
|
||||
// copied (device to device, in capture order) into it before the gather.
|
||||
self.submit(vec![command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![Arg::Address(tokens), Arg::Address(source), Arg::I32(t as i32)],
|
||||
)?])?;
|
||||
self.embed_stage_tokens()?;
|
||||
self.resources.embed.capture(self.capture)?;
|
||||
let embedded = handle(self.resources.embed.output_device()?)?.qwen_address();
|
||||
let residual = self.journal().address("R", 0, t * g.hc * g.n * 4)?;
|
||||
self.submit(vec![command(
|
||||
"verify_broadcast_streams_kernel",
|
||||
[(g.n * g.hc).div_ceil(256) as u32, t as u32, 1],
|
||||
[256, 1, 1],
|
||||
vec![Arg::Address(embedded), Arg::Address(residual), Arg::I64(g.n as i64), Arg::I32(g.hc as i32)],
|
||||
)?])
|
||||
self.embed_broadcast()
|
||||
}
|
||||
fn stamp(&mut self, layer: usize, stage: usize) -> Result<()> {
|
||||
self.resources.base.journal.capture_stamp(self.capture, layer, stage)
|
||||
@@ -53,7 +35,8 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
|
||||
fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()> {
|
||||
if self.side_gdn() {
|
||||
match projection {
|
||||
// SIDE_MIXER: the gates and the gate projection of this GDN layer are issued here, beside the qkv projection and the conv
|
||||
// SIDE_MIXER: the gates and the gate projection of this GDN layer are issued here, beside the qkv
|
||||
// projection and the conv
|
||||
Projection::GdnQkv => self.issue_gdn_side(layer, rows)?,
|
||||
// ... and are not issued again where the literal order has them
|
||||
Projection::GdnGate => return Ok(()),
|
||||
|
||||
@@ -48,11 +48,7 @@ pub(crate) fn plan_mmvq(
|
||||
rows: usize,
|
||||
dispatch: NativeHeadDispatch,
|
||||
) -> Result<Launch> {
|
||||
if n_in == 0 || n_in % 32 != 0 || n_out == 0 || !(1..=8).contains(&rows) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let (n_in32, n_out32) =
|
||||
(i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?);
|
||||
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)];
|
||||
if iq {
|
||||
@@ -65,6 +61,14 @@ pub(crate) fn plan_mmvq(
|
||||
Launch::new(mmvq_asset(w.ty), entry, grid, block, 0, args)
|
||||
}
|
||||
|
||||
/// The shape check of `plan_mmvq` and the `i32` kernel extents `(n_in, n_out)`.
|
||||
fn mmvq_extents(n_in: usize, n_out: usize, rows: usize) -> Result<(i32, i32)> {
|
||||
if n_in == 0 || n_in % 32 != 0 || n_out == 0 || !(1..=8).contains(&rows) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok((i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?))
|
||||
}
|
||||
|
||||
/// `mmvf_block_size`: the block (32..=256 in steps of 32) with the fewest weight-row iterations.
|
||||
pub(crate) const fn mmvf_block_size(n_in: usize) -> u32 {
|
||||
let mut best = 32usize;
|
||||
@@ -89,6 +93,10 @@ pub(super) fn single_entry(block: u32) -> Result<&'static str> {
|
||||
BF16_ENTRIES.iter().copied().find(|e| **e == *name).ok_or(Error::UnsupportedQwenOperation)
|
||||
}
|
||||
|
||||
fn bf16_gemv_shape_ok(x: u64, ldx: usize, (n_in, n_out): (usize, usize), n_tok: usize) -> bool {
|
||||
(1..=8).contains(&n_tok) && n_in != 0 && n_in % 2 == 0 && n_out != 0 && ldx % 2 == 0 && x % 8 == 0
|
||||
}
|
||||
|
||||
/// `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)]
|
||||
@@ -102,7 +110,7 @@ pub(crate) fn plan_bf16_gemv(
|
||||
n_out: usize,
|
||||
n_tok: usize,
|
||||
) -> Result<Launch> {
|
||||
if !(1..=8).contains(&n_tok) || n_in == 0 || n_in % 2 != 0 || n_out == 0 || ldx % 2 != 0 || x % 8 != 0 {
|
||||
if !bf16_gemv_shape_ok(x, ldx, (n_in, n_out), n_tok) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let (n_in32, grid) =
|
||||
@@ -164,19 +172,42 @@ pub(super) fn projection_shape(
|
||||
projection: Projection,
|
||||
layer: usize,
|
||||
) -> Result<(usize, usize, &'static str, usize)> {
|
||||
let (n, zv, ch) = (geo.n, geo.value_heads * 128, geo.channels);
|
||||
let gdn = gdn_index(layer);
|
||||
let qsa = qsa_index(layer);
|
||||
match projection {
|
||||
Projection::GdnQkv if gdn.is_some() => Ok((n, ch, "qkv_L", ch)),
|
||||
Projection::GdnGate if gdn.is_some() => Ok((n, zv, "z", zv)),
|
||||
Projection::GdnOut if gdn.is_some() => Ok((zv, n, "bo", n)),
|
||||
Projection::QsaK if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "kcur", geo.kv_heads * geo.head_dim)),
|
||||
Projection::QsaV if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "vcur", geo.kv_heads * geo.head_dim)),
|
||||
Projection::QsaQ if qsa.is_some() => {
|
||||
Ok((n, geo.heads * 2 * geo.head_dim, "qfull", geo.heads * 2 * geo.head_dim))
|
||||
Projection::GdnQkv | Projection::GdnGate | Projection::GdnOut if gdn.is_some() => {
|
||||
gdn_projection_shape(geo, projection)
|
||||
}
|
||||
Projection::QsaOut if qsa.is_some() => Ok((geo.heads * geo.head_dim, n, "bo", n)),
|
||||
Projection::QsaK | Projection::QsaV | Projection::QsaQ | Projection::QsaOut if qsa.is_some() => {
|
||||
qsa_projection_shape(geo, projection)
|
||||
}
|
||||
_ => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
}
|
||||
/// `projection_shape` of a GDN projection on a GDN layer.
|
||||
fn gdn_projection_shape(
|
||||
geo: &OriginalVerifyGeometry,
|
||||
projection: Projection,
|
||||
) -> Result<(usize, usize, &'static str, usize)> {
|
||||
let (n, zv, ch) = (geo.n, geo.value_heads * 128, geo.channels);
|
||||
match projection {
|
||||
Projection::GdnQkv => Ok((n, ch, "qkv_L", ch)),
|
||||
Projection::GdnGate => Ok((n, zv, "z", zv)),
|
||||
Projection::GdnOut => Ok((zv, n, "bo", n)),
|
||||
_ => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
}
|
||||
/// `projection_shape` of a QSA projection on a QSA layer.
|
||||
fn qsa_projection_shape(
|
||||
geo: &OriginalVerifyGeometry,
|
||||
projection: Projection,
|
||||
) -> Result<(usize, usize, &'static str, usize)> {
|
||||
let n = geo.n;
|
||||
match projection {
|
||||
Projection::QsaK => Ok((n, geo.kv_heads * geo.head_dim, "kcur", geo.kv_heads * geo.head_dim)),
|
||||
Projection::QsaV => Ok((n, geo.kv_heads * geo.head_dim, "vcur", geo.kv_heads * geo.head_dim)),
|
||||
Projection::QsaQ => Ok((n, geo.heads * 2 * geo.head_dim, "qfull", geo.heads * 2 * geo.head_dim)),
|
||||
Projection::QsaOut => Ok((geo.heads * geo.head_dim, n, "bo", n)),
|
||||
_ => Err(Error::InvalidQwenShape),
|
||||
}
|
||||
}
|
||||
|
||||
+36
-24
@@ -171,52 +171,64 @@ impl<'a> QsaWindow<'a> {
|
||||
/// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions.
|
||||
pub fn q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
|
||||
let s = self.rows(q, rows, Some(batched))?;
|
||||
let g = &self.g;
|
||||
let (nh, hd) = (g.heads, g.head_dim);
|
||||
let mut out = Vec::new();
|
||||
if batched {
|
||||
out.push(self.split_q(s.tb, s.n)?);
|
||||
let data = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?;
|
||||
let pos = self.span("pos", s.tb * nh * 4, s.n * nh * 4)?;
|
||||
out.extend(self.norm_rope(data, w.weights.q_norm, s.n * nh, hd, pos)?);
|
||||
self.q_chunk(w, (s.tb, s.n), &mut out)?;
|
||||
} else {
|
||||
for t in s.tb..s.tb + s.n {
|
||||
out.push(self.split_q(t, 1)?);
|
||||
let data = self.span("qcur", t * nh * hd * 4, nh * hd * 4)?;
|
||||
let pos = self.span("pos", t * nh * 4, nh * 4)?;
|
||||
out.extend(self.norm_rope(data, w.weights.q_norm, nh, hd, pos)?);
|
||||
self.q_chunk(w, (t, 1), &mut out)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The q path of `count` rows from row `from`: split, then norm + RoPE.
|
||||
fn q_chunk(&self, w: &QsaLayerAddrs, (from, count): (usize, usize), out: &mut Vec<Launch>) -> Result<()> {
|
||||
let (nh, hd) = (self.g.heads, self.g.head_dim);
|
||||
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)?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `qsa_index_q_path`: indexer query projection, RMS norm with `indexer.q_norm.weight`, RoPE.
|
||||
pub fn index_q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
|
||||
let s = self.rows(q, rows, Some(batched))?;
|
||||
let g = &self.g;
|
||||
let (n_in, iq, id, nh) = (g.n, g.index_heads, g.index_dim, g.heads);
|
||||
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("qidx", from * iq * id * 4, count * iq * id * 4)?;
|
||||
plan_bf16_gemv(x, n_in, w.weights.index_q_proj, y, iq * id, n_in, iq * id, count)
|
||||
};
|
||||
let (iq, nh) = (g.index_heads, g.heads);
|
||||
let mut out = Vec::new();
|
||||
if batched {
|
||||
out.push(gemv(s.tb, s.n)?);
|
||||
let data = self.span("qidx", s.tb * iq * id * 4, s.n * iq * id * 4)?;
|
||||
// pos_i = pos_ + MT * (NH + NKV); rows [t][IQ]
|
||||
let pos = self.span("pos", (g.max_t * (nh + g.kv_heads) + s.tb * iq) * 4, s.n * iq * 4)?;
|
||||
out.extend(self.norm_rope(data, w.weights.index_q_norm, s.n * iq, id, pos)?);
|
||||
let pos = ((g.max_t * (nh + g.kv_heads) + s.tb * iq) * 4, s.n * iq * 4);
|
||||
self.index_q_chunk(w, (s.tb, s.n), pos, &mut out)?;
|
||||
} else {
|
||||
for t in s.tb..s.tb + s.n {
|
||||
out.push(gemv(t, 1)?);
|
||||
let data = self.span("qidx", t * iq * id * 4, iq * id * 4)?;
|
||||
let pos = self.span("pos", t * nh * 4, iq * 4)?;
|
||||
out.extend(self.norm_rope(data, w.weights.index_q_norm, iq, id, pos)?);
|
||||
self.index_q_chunk(w, (t, 1), (t * nh * 4, iq * 4), &mut out)?;
|
||||
}
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The indexer q path of `count` rows from row `from`: projection, then norm + RoPE with the `pos` span
|
||||
/// (`(offset, bytes)`).
|
||||
fn index_q_chunk(
|
||||
&self,
|
||||
w: &QsaLayerAddrs,
|
||||
(from, count): (usize, usize),
|
||||
pos: (usize, usize),
|
||||
out: &mut Vec<Launch>,
|
||||
) -> Result<()> {
|
||||
let g = &self.g;
|
||||
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)?);
|
||||
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)?);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One `kv_append_q8_step` into the resident pool (if the page is resident) and the host copy.
|
||||
|
||||
+2
-1
@@ -46,7 +46,8 @@ impl<'a> QsaWindow<'a> {
|
||||
fn topk_launch(&self, n: usize, (mb, cap): (usize, usize), [scores, steps, sel]: [u64; 3]) -> Result<Launch> {
|
||||
let args = vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)];
|
||||
if self.policy.cluster_topk && n <= CLUSTER_MAX_QUERIES {
|
||||
// block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs: the same ids
|
||||
// block_topk_cluster_kernel<<<(8, nq), 1024, ceil(max_blocks / 8) * 4>>> as a cluster of 8 CTAs:
|
||||
// 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)?;
|
||||
|
||||
@@ -202,9 +202,7 @@ pub fn record_window<O: WindowOps>(
|
||||
ple: bool,
|
||||
) -> Result<()> {
|
||||
policy.validate_selected()?;
|
||||
if !(1..=8).contains(&t) || !(1..=2).contains(&groups) || (groups == 2 && t < 2) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
check_window_shape(t, groups)?;
|
||||
ops.embed()?;
|
||||
for step in schedule(groups, WINDOW_LAYERS) {
|
||||
let (begin, end) = group_rows(t, groups, step.group);
|
||||
@@ -219,12 +217,25 @@ pub fn record_window<O: WindowOps>(
|
||||
ops.stamp(WINDOW_LAYERS, 1)
|
||||
}
|
||||
|
||||
fn check_window_shape(t: usize, groups: usize) -> Result<()> {
|
||||
if !(1..=8).contains(&t) || !(1..=2).contains(&groups) || (groups == 2 && t < 2) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stamp<O: WindowOps>(ops: &mut O, layer: usize, stage: usize, rows: Rows) -> Result<()> {
|
||||
if rows.group == 0 { ops.stamp(layer, stage) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn pre<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
pre_read(ops, ple, l, rows)?;
|
||||
pre_mixer(ops, policy, l, rows)?;
|
||||
pre_ffn(ops, policy, l, rows)
|
||||
}
|
||||
|
||||
/// The start of `pre`: the attention half's hyper-connection read (with the layer-1 PLE block when `ple`).
|
||||
fn pre_read<O: WindowOps>(ops: &mut O, ple: bool, l: usize, rows: Rows) -> Result<()> {
|
||||
stamp(ops, l, 0, rows)?;
|
||||
// The previous layer's FFN write, folded into this layer's first read.
|
||||
let mut pending = l > 0;
|
||||
@@ -233,13 +244,22 @@ fn pre<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, ro
|
||||
pending = false;
|
||||
}
|
||||
ops.hc_read(l, HcHalf::Attention, pending, rows)?;
|
||||
stamp(ops, l, 1, rows)?;
|
||||
stamp(ops, l, 1, rows)
|
||||
}
|
||||
|
||||
/// The token mixer of `pre`: the gated delta-net half or the sparse-attention half of the layer.
|
||||
fn pre_mixer<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, l: usize, rows: Rows) -> Result<()> {
|
||||
if !is_qsa_layer(l) {
|
||||
pre_gdn(ops, l, rows)?;
|
||||
} else {
|
||||
pre_qsa(ops, policy, l, rows)?;
|
||||
}
|
||||
stamp(ops, l, 16, rows)?;
|
||||
stamp(ops, l, 16, rows)
|
||||
}
|
||||
|
||||
/// The end of `pre`: the FFN half's read, router, doorbell, shared expert and expert-input quantization.
|
||||
fn pre_ffn<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
ops.hc_read(l, HcHalf::Ffn, true, rows)?;
|
||||
// One router launch pair for the window's rows (NE == 512, K == 10) instead of 2 per token.
|
||||
ops.router(l, rows, policy.dec_batch && n > 1 && policy.native_router)?;
|
||||
@@ -253,13 +273,23 @@ fn pre<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, ro
|
||||
/// The gated delta-net half of `pre`: QKV and gate projections, conv, alpha/beta, recurrence, output projection.
|
||||
fn pre_gdn<O: WindowOps>(ops: &mut O, l: usize, rows: Rows) -> Result<()> {
|
||||
let g = gdn_index(l).ok_or(Error::InvalidQwenShape)?;
|
||||
pre_gdn_front(ops, l, g, rows)?;
|
||||
pre_gdn_back(ops, l, g, rows)
|
||||
}
|
||||
|
||||
/// The QKV projection, conv and alpha/beta of the gated delta-net half.
|
||||
fn pre_gdn_front<O: WindowOps>(ops: &mut O, l: usize, g: usize, rows: Rows) -> Result<()> {
|
||||
ops.quantize_q8_1(l, QuantSource::Mixed, rows)?;
|
||||
ops.mmvq(l, Projection::GdnQkv, rows)?;
|
||||
stamp(ops, l, 2, rows)?;
|
||||
ops.gdn_conv(g, rows)?;
|
||||
stamp(ops, l, 3, rows)?;
|
||||
ops.gdn_alpha_beta(g, rows)?;
|
||||
stamp(ops, l, 4, rows)?;
|
||||
stamp(ops, l, 4, rows)
|
||||
}
|
||||
|
||||
/// The gate projection, recurrence and output projection of the gated delta-net half.
|
||||
fn pre_gdn_back<O: WindowOps>(ops: &mut O, l: usize, g: usize, rows: Rows) -> Result<()> {
|
||||
ops.mmvq(l, Projection::GdnGate, rows)?;
|
||||
stamp(ops, l, 5, rows)?;
|
||||
ops.gdn_recurrence(g, rows)?;
|
||||
@@ -272,20 +302,30 @@ fn pre_gdn<O: WindowOps>(ops: &mut O, l: usize, rows: Rows) -> Result<()> {
|
||||
fn pre_qsa<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, l: usize, rows: Rows) -> Result<()> {
|
||||
let q = qsa_index(l).ok_or(Error::InvalidQwenShape)?;
|
||||
let batched = policy.dec_batch && rows.len() > 1;
|
||||
pre_qsa_project(ops, l, q, (rows, batched))?;
|
||||
pre_qsa_append(ops, l, q, rows)?;
|
||||
pre_qsa_attention(ops, l, q, (rows, batched))
|
||||
}
|
||||
|
||||
/// The K/V and indexer-K projections of the sparse-attention half, up to the K norm and RoPE.
|
||||
fn pre_qsa_project<O: WindowOps>(ops: &mut O, l: usize, q: usize, (rows, batched): (Rows, bool)) -> Result<()> {
|
||||
ops.quantize_q8_1(l, QuantSource::Mixed, rows)?;
|
||||
ops.qsa_index_k(q, rows, batched)?;
|
||||
stamp(ops, l, 7, rows)?;
|
||||
ops.mmvq(l, Projection::QsaK, rows)?;
|
||||
ops.mmvq(l, Projection::QsaV, rows)?;
|
||||
ops.qsa_k_norm_rope(q, rows, batched)?;
|
||||
stamp(ops, l, 8, rows)?;
|
||||
stamp(ops, l, 8, rows)
|
||||
}
|
||||
|
||||
/// The tail snapshot (first group only) and the K/V and indexer appends of the sparse-attention half.
|
||||
fn pre_qsa_append<O: WindowOps>(ops: &mut O, l: usize, q: usize, rows: Rows) -> Result<()> {
|
||||
if rows.group == 0 {
|
||||
ops.qsa_tail_snapshot(q)?;
|
||||
}
|
||||
ops.qsa_kv_append(q, rows)?;
|
||||
ops.qsa_indexer_append(q, rows)?;
|
||||
stamp(ops, l, 9, rows)?;
|
||||
pre_qsa_attention(ops, l, q, (rows, batched))
|
||||
stamp(ops, l, 9, rows)
|
||||
}
|
||||
|
||||
/// The query path, block selection, resolve, decode attention, gate and output projection.
|
||||
@@ -296,6 +336,11 @@ fn pre_qsa_attention<O: WindowOps>(ops: &mut O, l: usize, q: usize, (rows, batch
|
||||
stamp(ops, l, 10, rows)?;
|
||||
ops.qsa_block_scores_topk(q, rows)?;
|
||||
stamp(ops, l, 11, rows)?;
|
||||
pre_qsa_attend(ops, l, q, (rows, batched))
|
||||
}
|
||||
|
||||
/// The resolve, decode attention, gate and output projection of the sparse-attention half.
|
||||
fn pre_qsa_attend<O: WindowOps>(ops: &mut O, l: usize, q: usize, (rows, batched): (Rows, bool)) -> Result<()> {
|
||||
ops.qsa_kv_resolve(q, rows)?;
|
||||
stamp(ops, l, 12, rows)?;
|
||||
ops.qsa_decode_attention(q, rows)?;
|
||||
@@ -307,13 +352,23 @@ fn pre_qsa_attention<O: WindowOps>(ops: &mut O, l: usize, q: usize, (rows, batch
|
||||
}
|
||||
|
||||
fn post<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, groups: usize, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
let ring = ring(l, groups, rows.group);
|
||||
post_vram(ops, ring, l, rows)?;
|
||||
post_pcie(ops, policy, ring, l, rows)?;
|
||||
post_combine(ops, policy, l, rows)
|
||||
}
|
||||
|
||||
/// The start of `post`: wait for the plan, run the VRAM-tier experts, wait for the copies.
|
||||
fn post_vram<O: WindowOps>(ops: &mut O, ring: u32, l: usize, rows: Rows) -> Result<()> {
|
||||
ops.wait_plan(ring, rows)?;
|
||||
stamp(ops, l, 19, rows)?;
|
||||
ops.expert_groups(l, rows, ExpertTier::Vram)?;
|
||||
stamp(ops, l, 20, rows)?;
|
||||
ops.wait_copies(ring)?;
|
||||
ops.wait_copies(ring)
|
||||
}
|
||||
|
||||
/// The PCIe-tier experts of `post` (staged first in the copy-kernel mode), then wait for the CPU experts.
|
||||
fn post_pcie<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, ring: u32, l: usize, rows: Rows) -> Result<()> {
|
||||
if policy.pcie_mode == 2 {
|
||||
ops.pcie_stage(l, rows)?;
|
||||
}
|
||||
@@ -321,7 +376,12 @@ fn post<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, groups: usize, l: usiz
|
||||
ops.expert_groups(l, rows, ExpertTier::Pcie)?;
|
||||
stamp(ops, l, 22, rows)?;
|
||||
ops.wait_cpu(ring)?;
|
||||
stamp(ops, l, 23, rows)?;
|
||||
stamp(ops, l, 23, rows)
|
||||
}
|
||||
|
||||
/// The end of `post`: the CPU rows, the hit add, the combine and (last layer) the final residual write.
|
||||
fn post_combine<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
ops.copy_cpu_rows(rows, policy.dec_batch)?;
|
||||
ops.hit_add(rows)?;
|
||||
ops.combine(l, rows, policy.dec_batch && n > 1 && policy.native_combine)?;
|
||||
|
||||
@@ -105,7 +105,8 @@ impl Sm120Switches {
|
||||
/// The switches for a card of compute capability `major.minor`, from an environment lookup.
|
||||
pub fn resolve(major: i32, minor: i32, get: impl Fn(&str) -> Option<String>) -> Self {
|
||||
let sm120 = major == 12 && minor == 0 && get("LELEKA_SM120_PERF").as_deref().map(str::trim) != Some("0");
|
||||
// the kernels are sm_120 PTX (no sm_86 companion): a card below 12.x never takes a switch, whatever the variable says
|
||||
// the kernels are sm_120 PTX (no sm_86 companion): a card below 12.x never takes a switch, whatever the
|
||||
// variable says
|
||||
let capable = major >= 12;
|
||||
Self {
|
||||
attn_daily: capable && one(&get, "LELEKA_SM120_ATTN_DAILY", sm120 && DEFAULT_ON_ATTN_DAILY),
|
||||
|
||||
@@ -72,27 +72,43 @@ fn copy_bytes(context: &Context<'_>, report: &mut Report) -> Result<()> {
|
||||
Ok(buffer) => buffer,
|
||||
Err(primary) => return combine(Err(primary), original.release()),
|
||||
};
|
||||
let operation = (|| {
|
||||
let bytes: Vec<_> = (0u8..=255).collect();
|
||||
original.copy_from(&bytes)?;
|
||||
let expected = read(&original)?;
|
||||
candidate.copy_from_owned(consumed(&bytes, report))?;
|
||||
compare_bytes(&expected, &read(&candidate)?, report);
|
||||
for actual in [255usize, 257] {
|
||||
let expected = Error::ShapeMismatch { expected: 256, actual };
|
||||
refused(original.copy_from(&vec![0; actual]), expected.clone(), report)?;
|
||||
refused(candidate.copy_from_owned(vec![0; actual]), expected, report)?;
|
||||
compare_bytes(&bytes, &read(&candidate)?, report);
|
||||
}
|
||||
let changed: Vec<_> = bytes.into_iter().rev().collect();
|
||||
original.copy_from(&changed)?;
|
||||
let expected = read(&original)?;
|
||||
candidate.copy_from_owned(consumed(&changed, report))?;
|
||||
compare_bytes(&expected, &read(&candidate)?, report);
|
||||
Ok(())
|
||||
})();
|
||||
let operation = copy_bytes_operation(&mut original, &mut candidate, report);
|
||||
combine(operation, combine(original.release(), candidate.release()))
|
||||
}
|
||||
/// The copies of `copy_bytes` over the two allocated buffers.
|
||||
fn copy_bytes_operation(
|
||||
original: &mut DeviceBuffer<'_>,
|
||||
candidate: &mut DeviceBuffer<'_>,
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
let bytes: Vec<_> = (0u8..=255).collect();
|
||||
original.copy_from(&bytes)?;
|
||||
let expected = read(original)?;
|
||||
candidate.copy_from_owned(consumed(&bytes, report))?;
|
||||
compare_bytes(&expected, &read(candidate)?, report);
|
||||
copy_wrong_sizes(original, candidate, &bytes, report)?;
|
||||
let changed: Vec<_> = bytes.into_iter().rev().collect();
|
||||
original.copy_from(&changed)?;
|
||||
let expected = read(original)?;
|
||||
candidate.copy_from_owned(consumed(&changed, report))?;
|
||||
compare_bytes(&expected, &read(candidate)?, report);
|
||||
Ok(())
|
||||
}
|
||||
/// Both copies refuse a source one byte short and one byte long, and the candidate keeps its bytes.
|
||||
fn copy_wrong_sizes(
|
||||
original: &mut DeviceBuffer<'_>,
|
||||
candidate: &mut DeviceBuffer<'_>,
|
||||
bytes: &[u8],
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
for actual in [255usize, 257] {
|
||||
let expected = Error::ShapeMismatch { expected: 256, actual };
|
||||
refused(original.copy_from(&vec![0; actual]), expected.clone(), report)?;
|
||||
refused(candidate.copy_from_owned(vec![0; actual]), expected, report)?;
|
||||
compare_bytes(bytes, &read(candidate)?, report);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// What one `products` run allocated, released by the caller whatever the operation returned.
|
||||
#[derive(Default)]
|
||||
struct Owners<'c, 'f> {
|
||||
@@ -146,22 +162,43 @@ fn compare_products<'c, 'f>(
|
||||
let activation = owners.activation.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let expected = owners.expected.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let actual = owners.actual.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let others = (&mut owners.other_original, &mut owners.other);
|
||||
let mut work = Work { candidate, activation, expected, actual, others };
|
||||
for pattern in [0usize, 1, 2] {
|
||||
activation.copy_from(&pattern_input(pattern))?;
|
||||
let prepared = context.prepare_routed_gate_up_q8(activation)?;
|
||||
let projected = (|| {
|
||||
let reference = compare_native(original, candidate, &prepared, (expected, actual), report)?;
|
||||
if pattern == 0 {
|
||||
let others = (&mut owners.other_original, &mut owners.other);
|
||||
foreign_refusals(foreign, (kind, bytes), (&prepared, actual), others, report)?;
|
||||
compare_bytes(&reference, &read(actual)?, report);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
combine(projected, prepared.close())?;
|
||||
compare_pattern(pattern, (context, foreign), (kind, bytes), (original, &mut work), report)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// What `compare_products` works on once the owners are allocated.
|
||||
struct Work<'a, 'c, 'f> {
|
||||
candidate: &'a MmqWeights<'c>,
|
||||
activation: &'a mut DeviceBuffer<'c>,
|
||||
expected: &'a mut DeviceBuffer<'c>,
|
||||
actual: &'a mut DeviceBuffer<'c>,
|
||||
others: (&'a mut Option<MmqWeights<'f>>, &'a mut Option<MmqWeights<'f>>),
|
||||
}
|
||||
/// One activation pattern: the old and the owned projection, and (pattern 0) the foreign-context refusals.
|
||||
fn compare_pattern<'c, 'f>(
|
||||
pattern: usize,
|
||||
(context, foreign): (&'c Context<'_>, &'f Context<'_>),
|
||||
(kind, bytes): (MmqFormat, &[u8]),
|
||||
(original, work): (&MmqWeights<'_>, &mut Work<'_, 'c, 'f>),
|
||||
report: &mut Report,
|
||||
) -> Result<()> {
|
||||
work.activation.copy_from(&pattern_input(pattern))?;
|
||||
let prepared = context.prepare_routed_gate_up_q8(work.activation)?;
|
||||
let projected = (|| {
|
||||
let outputs = (&mut *work.expected, &mut *work.actual);
|
||||
let reference = compare_native(original, work.candidate, &prepared, outputs, report)?;
|
||||
if pattern == 0 {
|
||||
let others = (&mut *work.others.0, &mut *work.others.1);
|
||||
foreign_refusals(foreign, (kind, bytes), (&prepared, work.actual), others, report)?;
|
||||
compare_bytes(&reference, &read(work.actual)?, report);
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
combine(projected, prepared.close())
|
||||
}
|
||||
/// The owned constructor over the same bytes: whole readback equal to the old one, layout witness.
|
||||
fn compare_candidate<'c, 'f>(
|
||||
context: &'c Context<'_>,
|
||||
|
||||
@@ -259,22 +259,32 @@ fn gdn_shape_admitted(bf16: bool, (t, n, k): (i32, i32, i32), (ldy, y_offset): (
|
||||
if !(1..=8192).contains(&t) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if bf16 {
|
||||
let interleaved = (n, k, ldy) == (48, 2560, 96) && matches!(y_offset, 0 | 48);
|
||||
let moe = matches!((n, k), (512, 2560) | (1, 2560)) && ldy == n && y_offset == 0;
|
||||
if (!interleaved && !moe) || (*beta != 0.0 && *beta != 1.0) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
} else if !matches!((n, k), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640))
|
||||
|| ldy != n
|
||||
|| y_offset != 0
|
||||
|| *beta != 0.0
|
||||
{
|
||||
let admitted = if bf16 {
|
||||
gdn_bf16_shape_admitted((n, k), (ldy, y_offset), beta)
|
||||
} else {
|
||||
gdn_f16_shape_admitted((n, k), (ldy, y_offset), beta)
|
||||
};
|
||||
if !admitted {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The BF16 layouts of `gdn_shape_admitted`: the interleaved Alpha/Beta and the router / shared scalar.
|
||||
fn gdn_bf16_shape_admitted((n, k): (i32, i32), (ldy, y_offset): (i32, usize), beta: &f32) -> bool {
|
||||
let interleaved = (n, k, ldy) == (48, 2560, 96) && matches!(y_offset, 0 | 48);
|
||||
let moe = matches!((n, k), (512, 2560) | (1, 2560)) && ldy == n && y_offset == 0;
|
||||
(interleaved || moe) && (*beta == 0.0 || *beta == 1.0)
|
||||
}
|
||||
|
||||
/// The F16 layouts of `gdn_shape_admitted`: QKV, Z, Out and the shared expert.
|
||||
fn gdn_f16_shape_admitted((n, k): (i32, i32), (ldy, y_offset): (i32, usize), beta: &f32) -> bool {
|
||||
matches!((n, k), (10240, 2560) | (6144, 2560) | (2560, 6144) | (640, 2560) | (2560, 640))
|
||||
&& ldy == n
|
||||
&& y_offset == 0
|
||||
&& *beta == 0.0
|
||||
}
|
||||
|
||||
/// The driver and cuBLAS entry points `Blas::init_handle` binds.
|
||||
struct HandleSymbols {
|
||||
stream_create: StreamCreate,
|
||||
|
||||
@@ -183,8 +183,8 @@ fn launch_cluster_kernel(
|
||||
attrs: &mut attribute,
|
||||
num_attrs: 1,
|
||||
};
|
||||
// SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during the call);
|
||||
// the config and the attribute live across the call; the function belongs to this module.
|
||||
// SAFETY: owned argument storage persists until the stream drains (the driver copies the parameters during
|
||||
// the call); the config and the attribute live across the call; the function belongs to this module.
|
||||
check("cuLaunchKernelEx", unsafe {
|
||||
launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut())
|
||||
})
|
||||
|
||||
@@ -66,12 +66,7 @@ fn original_products<'c>(
|
||||
[embedding, streams, history]: [&[f32]; 3],
|
||||
buffers: &mut [Option<DeviceBuffer<'c>>; 13],
|
||||
) -> Result<Reference> {
|
||||
for (i, size) in SIZES[..13].iter().enumerate() {
|
||||
buffers[i] = Some(context.allocate(*size)?);
|
||||
}
|
||||
for (slot, values) in [(0, embedding), (1, streams), (2, history)] {
|
||||
buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&float_staging(values)?)?;
|
||||
}
|
||||
allocate_role_buffers(context, buffers, [embedding, streams, history])?;
|
||||
let mut products = Vec::new();
|
||||
products.try_reserve_exact(10).map_err(|_| Error::HostAllocation)?;
|
||||
for role in 0..10 {
|
||||
@@ -82,6 +77,20 @@ fn original_products<'c>(
|
||||
}
|
||||
Ok(Reference { products, refusal: None })
|
||||
}
|
||||
/// The thirteen buffers of the ten operators, with the embedding, stream and history inputs uploaded.
|
||||
fn allocate_role_buffers<'c>(
|
||||
context: &'c Context<'_>,
|
||||
buffers: &mut [Option<DeviceBuffer<'c>>; 13],
|
||||
[embedding, streams, history]: [&[f32]; 3],
|
||||
) -> Result<()> {
|
||||
for (i, size) in SIZES[..13].iter().enumerate() {
|
||||
buffers[i] = Some(context.allocate(*size)?);
|
||||
}
|
||||
for (slot, values) in [(0, embedding), (1, streams), (2, history)] {
|
||||
buffers[slot].as_mut().ok_or(Error::ContextPoisoned)?.copy_from(&float_staging(values)?)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// One operator onto its disjoint true whole output, retaining all original dependencies.
|
||||
fn run_role(
|
||||
context: &Context<'_>,
|
||||
@@ -89,26 +98,63 @@ fn run_role(
|
||||
buffers: &mut [Option<DeviceBuffer<'_>>; 13],
|
||||
role: usize,
|
||||
) -> Result<()> {
|
||||
use crate::Bf16ProjectionShape as Shape;
|
||||
let (inputs, outputs) = buffers.split_at_mut(OUTPUTS[role]);
|
||||
let get = |i: usize| inputs[i].as_ref().ok_or(Error::ContextPoisoned);
|
||||
if role == 7 {
|
||||
return conv_history_role(context, weights[5], (get(2)?, get(9)?), outputs);
|
||||
return conv_history_role(context, weights[5], (role_input(inputs, 2)?, role_input(inputs, 9)?), outputs);
|
||||
}
|
||||
let output = outputs[0].as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
match role {
|
||||
0 => context.bf16_f32(weights[0], get(0)?, output, Shape { rows: 10240, columns: 2560 })?,
|
||||
1 => context.bf16_f32(weights[1], get(0)?, output, Shape { rows: 2560, columns: 2560 })?,
|
||||
2 => context.ple_grouped_norm_f32(get(3)?, weights[2], output)?,
|
||||
3 => context.ple_grouped_norm_f32(get(1)?, weights[3], output)?,
|
||||
4 => context.ple_signed_gate_f32(get(5)?, get(6)?, output)?,
|
||||
5 => context.ple_broadcast_f32(get(4)?, get(7)?, output)?,
|
||||
6 => context.ple_grouped_norm_f32(get(8)?, weights[4], output)?,
|
||||
8 => (),
|
||||
9 => context.ple_residual_f32(get(1)?, get(8)?, get(10)?, output)?,
|
||||
0 | 1 => projection_role(context, weights, inputs, (role, output)),
|
||||
2 | 3 | 6 => grouped_norm_role(context, weights, inputs, (role, output)),
|
||||
4 | 5 => elementwise_role(context, inputs, (role, output)),
|
||||
8 => Ok(()),
|
||||
9 => context.ple_residual_f32(role_input(inputs, 1)?, role_input(inputs, 8)?, role_input(inputs, 10)?, output),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// Input buffer `i` of a role.
|
||||
fn role_input<'a, 'c>(inputs: &'a [Option<DeviceBuffer<'c>>], i: usize) -> Result<&'a DeviceBuffer<'c>> {
|
||||
inputs[i].as_ref().ok_or(Error::ContextPoisoned)
|
||||
}
|
||||
/// Roles 0 and 1: the key and value BF16 projections of the embedding.
|
||||
fn projection_role(
|
||||
context: &Context<'_>,
|
||||
weights: [&DeviceBuffer<'_>; 6],
|
||||
inputs: &[Option<DeviceBuffer<'_>>],
|
||||
(role, output): (usize, &mut DeviceBuffer<'_>),
|
||||
) -> Result<()> {
|
||||
use crate::Bf16ProjectionShape as Shape;
|
||||
match role {
|
||||
0 => context.bf16_f32(weights[0], role_input(inputs, 0)?, output, Shape { rows: 10240, columns: 2560 }),
|
||||
1 => context.bf16_f32(weights[1], role_input(inputs, 0)?, output, Shape { rows: 2560, columns: 2560 }),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// Roles 2, 3 and 6: the grouped norms.
|
||||
fn grouped_norm_role(
|
||||
context: &Context<'_>,
|
||||
weights: [&DeviceBuffer<'_>; 6],
|
||||
inputs: &[Option<DeviceBuffer<'_>>],
|
||||
(role, output): (usize, &mut DeviceBuffer<'_>),
|
||||
) -> Result<()> {
|
||||
match role {
|
||||
2 => context.ple_grouped_norm_f32(role_input(inputs, 3)?, weights[2], output),
|
||||
3 => context.ple_grouped_norm_f32(role_input(inputs, 1)?, weights[3], output),
|
||||
6 => context.ple_grouped_norm_f32(role_input(inputs, 8)?, weights[4], output),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
/// Roles 4 and 5: the signed gate and the broadcast.
|
||||
fn elementwise_role(
|
||||
context: &Context<'_>,
|
||||
inputs: &[Option<DeviceBuffer<'_>>],
|
||||
(role, output): (usize, &mut DeviceBuffer<'_>),
|
||||
) -> Result<()> {
|
||||
match role {
|
||||
4 => context.ple_signed_gate_f32(role_input(inputs, 5)?, role_input(inputs, 6)?, output),
|
||||
5 => context.ple_broadcast_f32(role_input(inputs, 4)?, role_input(inputs, 7)?, output),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// The convolution and the shifted history are two outputs of one operator.
|
||||
fn conv_history_role<'c>(
|
||||
@@ -187,7 +233,8 @@ fn original_first_whole_ple_queue_causal_history_status_reset_and_cleanup() {
|
||||
assert_eq!(tally.differences, 0);
|
||||
assert_eq!(tally.guards, 16);
|
||||
eprintln!(
|
||||
"PLE_CLOSED_QUEUE PASS words={} differences={} guards={} original_first=true causal_history=true allocated0=true",
|
||||
"PLE_CLOSED_QUEUE PASS words={} differences={} guards={} \
|
||||
original_first=true causal_history=true allocated0=true",
|
||||
tally.words, tally.differences, tally.guards
|
||||
);
|
||||
tiny_budget_refused(&device);
|
||||
@@ -249,16 +296,26 @@ fn queue_cases<'c>(
|
||||
let q = queue.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let mut tally = Tally::default();
|
||||
let history = causal_history_cases(context, q, weights, &mut tally)?;
|
||||
refusal_cases(context, foreign, (q, weights, foreign_weight), (&history[..], &mut tally))?;
|
||||
Ok(tally)
|
||||
}
|
||||
/// Everything after the causal history: corrupted weights, invalid inputs, the foreign weight, the alias and the
|
||||
/// status buffer.
|
||||
fn refusal_cases<'c>(
|
||||
context: &'c Context<'c>,
|
||||
foreign: &'c Context<'c>,
|
||||
(q, weights, foreign_weight): (&mut PleClosedQueue<'c>, &mut Vec<DeviceBuffer<'c>>, &mut Option<DeviceBuffer<'c>>),
|
||||
(history, tally): (&[f32], &mut Tally),
|
||||
) -> Result<()> {
|
||||
let embedding = values(2560, 3, false);
|
||||
let streams = values(10240, 5, false);
|
||||
let inputs = (&embedding[..], &streams[..], &history[..]);
|
||||
corrupted_weight_cases(context, q, weights, inputs, &mut tally)?;
|
||||
let inputs = (&embedding[..], &streams[..], history);
|
||||
corrupted_weight_cases(context, q, weights, inputs, tally)?;
|
||||
let before = read(q.buffer(12)?)?;
|
||||
invalid_input_cases(q, weights, inputs, &mut tally);
|
||||
invalid_input_cases(q, weights, inputs, tally);
|
||||
*foreign_weight = Some(foreign.allocate(1024)?);
|
||||
foreign_weight_case(q, weights, foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, inputs, &mut tally);
|
||||
alias_refused_and_status_unchanged(q, &before, &mut tally)?;
|
||||
Ok(tally)
|
||||
foreign_weight_case(q, weights, foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, inputs, tally);
|
||||
alias_refused_and_status_unchanged(q, &before, tally)
|
||||
}
|
||||
/// A weight view of the queue's own buffer is refused, and the status buffer still holds what it held before the
|
||||
/// refusals.
|
||||
@@ -322,9 +379,7 @@ fn corrupted_weight_cases<'c>(
|
||||
tally: &mut Tally,
|
||||
) -> Result<()> {
|
||||
for (weight, offset, bytes) in corruptions() {
|
||||
let mut saved = staging(weights[weight].bytes)?;
|
||||
weights[weight].copy_to(&mut saved)?;
|
||||
weights[weight].copy_from_range(offset, &bytes)?;
|
||||
let saved = corrupt_weight(weights, (weight, offset), &bytes)?;
|
||||
let old = original(context, refs(weights), embedding, streams, history)?;
|
||||
let (refusal, _) = queued(q, refs(weights), embedding, streams, history)?;
|
||||
if old.refusal.is_none() || old.refusal != refusal {
|
||||
@@ -336,6 +391,13 @@ fn corrupted_weight_cases<'c>(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Saves weight `weight` and overwrites `bytes` at `offset`; returns the saved bytes.
|
||||
fn corrupt_weight(weights: &mut [DeviceBuffer<'_>], (weight, offset): (usize, usize), bytes: &[u8]) -> Result<Vec<u8>> {
|
||||
let mut saved = staging(weights[weight].bytes)?;
|
||||
weights[weight].copy_to(&mut saved)?;
|
||||
weights[weight].copy_from_range(offset, bytes)?;
|
||||
Ok(saved)
|
||||
}
|
||||
/// With the weight restored the original and the queue give identical, finite products again.
|
||||
fn restored_weight_case<'c>(
|
||||
context: &Context<'_>,
|
||||
|
||||
@@ -4,6 +4,26 @@
|
||||
use super::*;
|
||||
|
||||
pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result<Q6KShape> {
|
||||
let (rows_abi, columns_abi) = q6_abi_extents(rows, columns)?;
|
||||
let weight_blocks = rows.checked_mul(columns / 256).ok_or(Error::InvalidQ6KProjectionShape)?;
|
||||
let weight_bytes = q6_checked_bytes(weight_blocks, 210)?;
|
||||
let activation_bytes = q6_checked_bytes(columns, 4)?;
|
||||
let output_bytes = q6_checked_bytes(rows, 4)?;
|
||||
let scratch_bytes = q6_checked_bytes(columns / 32, 36)?;
|
||||
let (quant_grid, projection_grid) = q6_grids(rows, columns)?;
|
||||
Ok(Q6KShape {
|
||||
weight_bytes,
|
||||
activation_bytes,
|
||||
output_bytes,
|
||||
scratch_bytes,
|
||||
rows: rows_abi,
|
||||
columns: columns_abi,
|
||||
quant_grid,
|
||||
projection_grid,
|
||||
})
|
||||
}
|
||||
/// The `u32` kernel extents of a Q6_K projection: non-empty, whole 256-value blocks, within `i32`.
|
||||
fn q6_abi_extents(rows: usize, columns: usize) -> Result<(u32, u32)> {
|
||||
if rows == 0 || columns == 0 || !columns.is_multiple_of(256) {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
}
|
||||
@@ -12,22 +32,7 @@ pub(super) fn q6_k_shape(rows: usize, columns: usize) -> Result<Q6KShape> {
|
||||
if rows_abi > i32::MAX as u32 || columns_abi > i32::MAX as u32 {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
}
|
||||
let weight_blocks = rows.checked_mul(columns / 256).ok_or(Error::InvalidQ6KProjectionShape)?;
|
||||
let weight_bytes = q6_checked_bytes(weight_blocks, 210)?;
|
||||
let activation_bytes = q6_checked_bytes(columns, 4)?;
|
||||
let output_bytes = q6_checked_bytes(rows, 4)?;
|
||||
let scratch_bytes = q6_checked_bytes(columns / 32, 36)?;
|
||||
let (quant_grid, projection_ctas) = q6_grids(rows, columns)?;
|
||||
Ok(Q6KShape {
|
||||
weight_bytes,
|
||||
activation_bytes,
|
||||
output_bytes,
|
||||
scratch_bytes,
|
||||
rows: rows_abi,
|
||||
columns: columns_abi,
|
||||
quant_grid: u32::try_from(quant_grid).map_err(|_| Error::InvalidQ6KProjectionShape)?,
|
||||
projection_grid: u32::try_from(projection_ctas).map_err(|_| Error::InvalidQ6KProjectionShape)?,
|
||||
})
|
||||
Ok((rows_abi, columns_abi))
|
||||
}
|
||||
/// `elements * width` bytes, within the context's size limit.
|
||||
fn q6_checked_bytes(elements: usize, width: usize) -> Result<usize> {
|
||||
@@ -36,7 +41,7 @@ fn q6_checked_bytes(elements: usize, width: usize) -> Result<usize> {
|
||||
Ok(bytes)
|
||||
}
|
||||
/// The quantize grid and the projection CTA count (four rows per CTA below four K blocks).
|
||||
fn q6_grids(rows: usize, columns: usize) -> Result<(usize, usize)> {
|
||||
fn q6_grids(rows: usize, columns: usize) -> Result<(u32, u32)> {
|
||||
let quant_grid = columns / 256;
|
||||
if quant_grid == 0 || quant_grid > i32::MAX as usize {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
@@ -46,19 +51,17 @@ fn q6_grids(rows: usize, columns: usize) -> Result<(usize, usize)> {
|
||||
if projection_ctas == 0 || projection_ctas > i32::MAX as usize {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
}
|
||||
Ok((quant_grid, projection_ctas))
|
||||
Ok((
|
||||
u32::try_from(quant_grid).map_err(|_| Error::InvalidQ6KProjectionShape)?,
|
||||
u32::try_from(projection_ctas).map_err(|_| Error::InvalidQ6KProjectionShape)?,
|
||||
))
|
||||
}
|
||||
pub(super) fn matvec_shape(rows: usize, columns: usize) -> Result<MatvecShape> {
|
||||
let rows_abi = u32::try_from(rows).map_err(|_| Error::InvalidMatvecShape)?;
|
||||
let columns_abi = u32::try_from(columns).map_err(|_| Error::InvalidMatvecShape)?;
|
||||
let bytes = |elements: Option<usize>| -> Result<usize> {
|
||||
let bytes = elements.and_then(|v| v.checked_mul(4)).ok_or(Error::InvalidMatvecShape)?;
|
||||
valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?;
|
||||
Ok(bytes)
|
||||
};
|
||||
let matrix_bytes = bytes(rows.checked_mul(columns))?;
|
||||
let vector_bytes = bytes(Some(columns))?;
|
||||
let output_bytes = bytes(Some(rows))?;
|
||||
let matrix_bytes = matvec_bytes(rows.checked_mul(columns))?;
|
||||
let vector_bytes = matvec_bytes(Some(columns))?;
|
||||
let output_bytes = matvec_bytes(Some(rows))?;
|
||||
let grid = u64::from(rows_abi).div_ceil(128);
|
||||
if grid == 0 || grid > i32::MAX as u64 {
|
||||
return Err(Error::InvalidMatvecShape);
|
||||
@@ -73,6 +76,13 @@ pub(super) fn matvec_shape(rows: usize, columns: usize) -> Result<MatvecShape> {
|
||||
})
|
||||
}
|
||||
|
||||
/// `elements * 4` bytes, within the context's size limit.
|
||||
fn matvec_bytes(elements: Option<usize>) -> Result<usize> {
|
||||
let bytes = elements.and_then(|v| v.checked_mul(4)).ok_or(Error::InvalidMatvecShape)?;
|
||||
valid_size(bytes).map_err(|_| Error::InvalidMatvecShape)?;
|
||||
Ok(bytes)
|
||||
}
|
||||
|
||||
pub(super) fn matvec_allocations(
|
||||
matrix: Option<ffi::BufferHandle>,
|
||||
vector: Option<ffi::BufferHandle>,
|
||||
|
||||
@@ -210,16 +210,7 @@ mod installed {
|
||||
pub fn project(&self, w: &DeviceBuffer<'_>, q: &Prepared<'_>, y: &mut DeviceBuffer<'_>) -> Result<()> {
|
||||
self.live()?;
|
||||
let context = self.context;
|
||||
if !std::ptr::eq(context, w.context)
|
||||
|| !std::ptr::eq(context, q.scratch.context)
|
||||
|| !std::ptr::eq(context, y.context)
|
||||
{
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let (s, _, qbytes, ybytes) = shape(q.rows, q.columns, q.tokens)?;
|
||||
if w.bytes != s.weight_bytes || q.scratch.bytes != qbytes || y.bytes != ybytes {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
}
|
||||
let (s, qbytes, ybytes) = self.admit_projection(w, q, y)?;
|
||||
let wh = w.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let qh = q.scratch.handle.ok_or(Error::ContextPoisoned)?;
|
||||
let yh = y.handle.ok_or(Error::ContextPoisoned)?;
|
||||
@@ -231,6 +222,26 @@ mod installed {
|
||||
self.project_attempts.set(self.project_attempts.get() + 1);
|
||||
context.complete_launch(launched, args, guard)
|
||||
}
|
||||
/// The weight, activation and output belong to this context and have the exact sizes of the shape.
|
||||
fn admit_projection(
|
||||
&self,
|
||||
w: &DeviceBuffer<'_>,
|
||||
q: &Prepared<'_>,
|
||||
y: &DeviceBuffer<'_>,
|
||||
) -> Result<(Q6KShape, usize, usize)> {
|
||||
let context = self.context;
|
||||
if !std::ptr::eq(context, w.context)
|
||||
|| !std::ptr::eq(context, q.scratch.context)
|
||||
|| !std::ptr::eq(context, y.context)
|
||||
{
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let (s, _, qbytes, ybytes) = shape(q.rows, q.columns, q.tokens)?;
|
||||
if w.bytes != s.weight_bytes || q.scratch.bytes != qbytes || y.bytes != ybytes {
|
||||
return Err(Error::InvalidQ6KProjectionShape);
|
||||
}
|
||||
Ok((s, qbytes, ybytes))
|
||||
}
|
||||
pub fn close(mut self) -> Result<()> {
|
||||
self.unload()
|
||||
}
|
||||
|
||||
@@ -134,6 +134,12 @@ impl Entry {
|
||||
Self::Split => c"qsa_split_q",
|
||||
Self::Round => c"qsa_round_index_rows",
|
||||
Self::Scan => c"qsa_index_scan",
|
||||
other => other.late_name(),
|
||||
}
|
||||
}
|
||||
/// `name` of the entries after `Scan`.
|
||||
fn late_name(self) -> &'static CStr {
|
||||
match self {
|
||||
Self::ScoreScan => c"qsa_score_scan",
|
||||
Self::Tc => c"qsa_score_tc",
|
||||
Self::ScoreTail => c"qsa_score_tail",
|
||||
@@ -142,6 +148,14 @@ impl Entry {
|
||||
Self::DecodeScores => c"qsa_decode_scores",
|
||||
Self::DecodeRms => c"qsa_decode_rms",
|
||||
Self::DecodeRope => c"qsa_decode_rope",
|
||||
Self::First
|
||||
| Self::Blocks
|
||||
| Self::Tail
|
||||
| Self::Rms
|
||||
| Self::Rope
|
||||
| Self::Split
|
||||
| Self::Round
|
||||
| Self::Scan => unreachable!("named by Entry::name"),
|
||||
}
|
||||
}
|
||||
fn index(self) -> usize {
|
||||
@@ -192,7 +206,15 @@ impl Launch {
|
||||
}
|
||||
fn shape(self) -> Result<(Entry, u32, u32, u32, u32)> {
|
||||
self.check_extents()?;
|
||||
let (entry, x, y, threads, shared) = match self {
|
||||
let (entry, x, y, threads, shared) = self.raw_shape();
|
||||
if x == 0 || y == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok((entry, x, y, threads, shared))
|
||||
}
|
||||
/// `(entry, grid x, grid y, threads, dynamic shared bytes)` before the empty-grid check.
|
||||
fn raw_shape(self) -> (Entry, u32, u32, u32, u32) {
|
||||
match self {
|
||||
Self::First => (Entry::First, 1, 1, 256, 0),
|
||||
Self::Blocks(n) => (Entry::Blocks, n, 1, 256, 0),
|
||||
Self::Tail => (Entry::Tail, 3, 1, 128, 0),
|
||||
@@ -201,6 +223,12 @@ impl Launch {
|
||||
Self::Split(n) => (Entry::Split, n.div_ceil(256), 1, 256, 0),
|
||||
Self::Round(n) => (Entry::Round, n.div_ceil(256), 1, 256, 0),
|
||||
Self::Scan(n) => (Entry::Scan, n.div_ceil(256), 1, 256, 0),
|
||||
other => other.late_raw_shape(),
|
||||
}
|
||||
}
|
||||
/// `raw_shape` of the launches after `Scan`.
|
||||
fn late_raw_shape(self) -> (Entry, u32, u32, u32, u32) {
|
||||
match self {
|
||||
Self::ScoreScan(n) => (Entry::ScoreScan, n.div_ceil(256), 1, 256, 0),
|
||||
Self::Tc { t, reach } => (Entry::Tc, reach.div_ceil(128), t.div_ceil(16), 128, 49920),
|
||||
Self::ScoreTail(t) => (Entry::ScoreTail, t, 1, 32, 0),
|
||||
@@ -209,11 +237,15 @@ impl Launch {
|
||||
Self::DecodeRope(n) => (Entry::DecodeRope, 1, n, 128, 0),
|
||||
Self::DecodeAppend => (Entry::DecodeAppend, 1, 1, 256, 0),
|
||||
Self::DecodeScores => (Entry::DecodeScores, 256, 1, 256, 0),
|
||||
};
|
||||
if x == 0 || y == 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
Self::First
|
||||
| Self::Blocks(_)
|
||||
| Self::Tail
|
||||
| Self::Rms(_)
|
||||
| Self::Rope(_)
|
||||
| Self::Split(_)
|
||||
| Self::Round(_)
|
||||
| Self::Scan(_) => unreachable!("shaped by Launch::raw_shape"),
|
||||
}
|
||||
Ok((entry, x, y, threads, shared))
|
||||
}
|
||||
}
|
||||
#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
|
||||
|
||||
@@ -133,7 +133,8 @@ pub(super) fn topk_matches_original(
|
||||
let (o, n) = (download(&ids_o, out_len), download(&ids_n, out_len));
|
||||
assert!(o == n, "case {case} (p0 {p0}, rows {rows}, style {style}): ids differ");
|
||||
eprintln!(
|
||||
"QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); original {old_ms:.3} ms, fast {new_ms:.3} ms",
|
||||
"QSA-LATE topk case {case} p0={p0} rows={rows} style={style}: ids equal ({} bytes); \
|
||||
original {old_ms:.3} ms, fast {new_ms:.3} ms",
|
||||
out_len
|
||||
);
|
||||
}
|
||||
|
||||
@@ -127,18 +127,27 @@ pub(super) fn bench_case(
|
||||
continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries)
|
||||
}
|
||||
let (got, us) = time_variant(rig, run, (&scores_d, &steps_d), out_len);
|
||||
match &reference {
|
||||
None => reference = Some(got),
|
||||
Some(r) => assert!(
|
||||
*r == got,
|
||||
"case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original"
|
||||
),
|
||||
}
|
||||
match_reference(&mut reference, got, (case, p0, rows, style), name);
|
||||
line.push_str(&format!(" {name} {us:.1} us;"));
|
||||
}
|
||||
eprintln!("{line} ids equal");
|
||||
}
|
||||
|
||||
/// The first variant's ids are the reference; every later variant must write the same ids.
|
||||
fn match_reference(
|
||||
reference: &mut Option<Vec<u8>>,
|
||||
got: Vec<u8>,
|
||||
(case, p0, rows, style): (usize, usize, usize, u8),
|
||||
name: &str,
|
||||
) {
|
||||
match reference {
|
||||
None => *reference = Some(got),
|
||||
Some(r) => {
|
||||
assert!(*r == got, "case {case} (p0 {p0}, rows {rows}, style {style}): {name} ids differ from the original")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs one variant warm, then 20 launches drained once; returns the ids it wrote and the per-launch microseconds.
|
||||
pub(super) fn time_variant(
|
||||
rig: &BenchRig<'_>,
|
||||
|
||||
Reference in New Issue
Block a user