feat(cuda): add closed QSA dispatch interfaces

This commit is contained in:
Pavlo Ratushnyi
2026-10-09 20:36:07 +02:00
parent af7437321c
commit c4c6b7776b
3 changed files with 881 additions and 7 deletions
+2 -2
View File
@@ -605,12 +605,12 @@ mod enabled {
(self.launch_kernel)(
function.0 as *mut c_void,
layout.grid,
1,
layout.grid_y,
layout.grid_z,
layout.block,
layout.block_y,
1,
0,
layout.shared_bytes,
std::ptr::null_mut(),
arguments.parameters(),
std::ptr::null_mut(),
+414 -1
View File
@@ -209,6 +209,14 @@ fn ranges_layout(
if (operation != Operation::Bf16 && elements > i32::MAX as usize)
|| layout.grid == 0
|| layout.grid > i32::MAX as u32
|| layout.shared_bytes
!= if operation == Operation::QsaAttend {
8332
} else {
0
}
|| layout.grid_y == 0
|| layout.grid_y > i32::MAX as u32
|| layout.grid_z == 0
|| layout.grid_z > i32::MAX as u32
|| layout.block == 0
@@ -310,6 +318,190 @@ fn admission<'asset>(
Ok((asset, layout, handles))
}
impl Context<'_> {
fn qsa_call(
&self,
operation: Operation,
buffers: &[&DeviceBuffer<'_>],
value: u32,
) -> Result<()> {
let (asset, layout, handles) = admission(
self,
buffers,
Admission {
operation,
layout: qwen_ffi::qsa_layout(operation, value),
asset: qwen_ffi::asset(operation),
epsilon: 0.0,
in_place: false,
},
)?;
execute(
self,
&self.qwen_kernels,
asset,
Arguments::with_layout(operation, layout, handles, 0.0),
)
}
/// Closed QSA split q gate; unqualified assets refuse before mutation.
pub fn qsa_split_q_gate(
&self,
full: &DeviceBuffer<'_>,
query: &mut DeviceBuffer<'_>,
gate: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(Operation::QsaSplit, &[full, query, gate], 0.0, false)
}
/// Closed QSA norm q; unqualified assets refuse before mutation.
pub fn qsa_norm_q(
&self,
input: &DeviceBuffer<'_>,
gamma: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(Operation::QsaNormQ, &[input, gamma, output], 0.0, false)
}
/// Closed QSA norm k; unqualified assets refuse before mutation.
pub fn qsa_norm_k(
&self,
input: &DeviceBuffer<'_>,
gamma: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(Operation::QsaNormK, &[input, gamma, output], 0.0, false)
}
/// Closed QSA norm index q; unqualified assets refuse before mutation.
pub fn qsa_norm_index_q(
&self,
input: &DeviceBuffer<'_>,
gamma: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(
Operation::QsaNormIndexQ,
&[input, gamma, output],
0.0,
false,
)
}
/// Closed QSA rope q; unqualified assets refuse before mutation.
pub fn qsa_rope_q(
&self,
input: &DeviceBuffer<'_>,
position: u32,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qsa_call(Operation::QsaRopeQ, &[input, output], position)
}
/// Closed QSA rope k; unqualified assets refuse before mutation.
pub fn qsa_rope_k(
&self,
input: &DeviceBuffer<'_>,
position: u32,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qsa_call(Operation::QsaRopeK, &[input, output], position)
}
/// Closed QSA rope index q; unqualified assets refuse before mutation.
pub fn qsa_rope_index_q(
&self,
input: &DeviceBuffer<'_>,
position: u32,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qsa_call(Operation::QsaRopeIndexQ, &[input, output], position)
}
/// Closed QSA index append; unqualified assets refuse before mutation.
pub fn qsa_index_append(
&self,
raw: &DeviceBuffer<'_>,
gamma: &DeviceBuffer<'_>,
prior: &DeviceBuffer<'_>,
next: &mut DeviceBuffer<'_>,
position: u32,
) -> Result<()> {
self.qsa_call(
Operation::QsaIndexAppend,
&[raw, gamma, prior, next],
position,
)
}
/// Closed QSA pack kv; unqualified assets refuse before mutation.
pub fn qsa_pack_kv(
&self,
key: &DeviceBuffer<'_>,
value: &DeviceBuffer<'_>,
packed_key: &mut DeviceBuffer<'_>,
packed_value: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(
Operation::QsaPackKv,
&[key, value, packed_key, packed_value],
0.0,
false,
)
}
/// Closed QSA block scores; unqualified assets refuse before mutation.
pub fn qsa_block_scores(
&self,
pooled: &DeviceBuffer<'_>,
dead: &DeviceBuffer<'_>,
index_query: &DeviceBuffer<'_>,
scores: &mut DeviceBuffer<'_>,
position: u32,
) -> Result<()> {
self.qsa_call(
Operation::QsaBlockScores,
&[pooled, dead, index_query, scores],
position,
)
}
/// Closed QSA block topk; unqualified assets refuse before mutation.
pub fn qsa_block_topk(
&self,
scores: &DeviceBuffer<'_>,
ids: &mut DeviceBuffer<'_>,
position: u32,
) -> Result<()> {
self.qsa_call(Operation::QsaBlockTopk, &[scores, ids], position)
}
/// Closed QSA attend; unqualified assets refuse before mutation.
pub fn qsa_attend(
&self,
query: &DeviceBuffer<'_>,
packed_key: &DeviceBuffer<'_>,
packed_value: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
width: u32,
) -> Result<()> {
self.qsa_call(
Operation::QsaAttend,
&[query, packed_key, packed_value, output],
width,
)
}
/// Closed QSA gate f32; unqualified assets refuse before mutation.
pub fn qsa_gate_f32(
&self,
attention: &DeviceBuffer<'_>,
gate: &DeviceBuffer<'_>,
output: &mut DeviceBuffer<'_>,
) -> Result<()> {
self.qwen_call(Operation::QsaGate, &[attention, gate, output], 0.0, false)
}
/// Native quantized-expert SwiGLU on two fixed 640-value F32 vectors.
pub fn moe_swiglu_f32(
&self,
@@ -714,6 +906,117 @@ mod tests {
use super::*;
use std::cell::RefCell;
#[test]
fn qsa_new_preflight_checks_whole_spans_aliases_and_fixed_shared_memory() {
for operation in qwen_ffi::QSA_OPERATIONS {
let value = if operation == Operation::QsaAttend {
2051
} else {
262143
};
let layout = qwen_ffi::qsa_layout(operation, value).unwrap();
let handles =
std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1)));
assert_eq!(
ranges_layout(operation, layout, handles, layout.bytes, false),
Ok(())
);
for output in (0..layout.count).filter(|i| layout.outputs & (1 << i) != 0) {
let mut short = layout.bytes;
short[output] -= 1;
assert_eq!(
ranges_layout(operation, layout, handles, short, false),
Err(Error::InvalidQwenShape)
);
for input in 0..layout.count {
if input == output {
continue;
}
let mut alias = handles;
alias[output] = handles[input];
assert_eq!(
ranges_layout(operation, layout, alias, layout.bytes, false),
Err(Error::OutputAliasesInput)
);
}
}
let mut wrapped = handles;
wrapped[0] = ffi::BufferHandle::synthetic(u64::MAX - 3);
assert_eq!(
ranges_layout(operation, layout, wrapped, layout.bytes, false),
Err(Error::InvalidQwenShape)
);
let mut malformed = layout;
malformed.shared_bytes = if layout.shared_bytes == 0 { 8332 } else { 0 };
assert_eq!(
ranges_layout(operation, malformed, handles, layout.bytes, false),
Err(Error::InvalidQwenShape)
);
assert_eq!(
ranges_layout(operation, layout, handles, layout.bytes, true),
Err(Error::OutputAliasesInput)
);
assert!(qwen_ffi::asset(operation).is_none());
}
}
#[test]
fn qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners() {
for operation in qwen_ffi::QSA_OPERATIONS {
let asset = qwen_ffi::mock_asset(operation);
let backend = Mock::default();
let cache = Cache::new();
execute(&backend, &cache, &asset, arguments(operation)).unwrap();
execute(&backend, &cache, &asset, arguments(operation)).unwrap();
assert_eq!(
*backend.trace.borrow(),
[
"push", "load", "lookup", "launch", "sync", "restore", "push", "launch",
"sync", "restore"
]
);
assert_eq!(ready(&cache), 1);
let failed = Mock::fault(&["lookup", "unload"]);
let cache = Cache::new();
assert_eq!(
execute(&failed, &cache, &asset, arguments(operation)),
Err(nested(error("lookup"), error("unload")))
);
assert_eq!(ready(&cache), 0);
assert!(failed.poison.get());
assert_eq!(
*failed.trace.borrow(),
["push", "load", "lookup", "unload", "restore"]
);
let failed = Mock::fault(&["launch", "sync", "restore"]);
let cache = Cache::new();
let drops = Rc::new(Cell::new(0));
assert_eq!(
execute(
&failed,
&cache,
&asset,
arguments(operation).observe_drop(Rc::clone(&drops))
),
Err(nested(
nested(error("launch"), error("sync")),
error("restore")
))
);
assert_eq!(drops.get(), 0);
assert!(failed.poison.get());
let before = failed.trace.borrow().clone();
assert_eq!(
execute(&failed, &cache, &asset, arguments(operation)),
Err(Error::ContextPoisoned)
);
assert_eq!(*failed.trace.borrow(), before);
unload(&failed, &cache).unwrap();
assert_eq!(*failed.trace.borrow(), before);
assert_eq!(ready(&cache), 0);
}
}
const MOE_OPERATIONS: [Operation; 4] = [
Operation::MoeSwiglu,
Operation::MoeSharedScalar,
@@ -791,6 +1094,113 @@ mod tests {
}
}
#[cfg(not(all(
feature = "cuda-driver",
target_os = "linux",
target_pointer_width = "64"
)))]
#[test]
fn qsa_new_public_slots_refuse_without_native_or_owner_mutation() {
use crate::{Driver, FixedPairKernels, ProjectionKernels};
use std::marker::PhantomData;
let driver = Driver {
api: Rc::new(ffi::Api),
version: 0,
};
let make_context = || Context {
driver: &driver,
handle: Some(ffi::ContextHandle::synthetic(1)),
budget: 1_000_000,
allocated: Cell::new(99),
poisoned: Cell::new(false),
vector_add_kernel: Cell::new(None),
matvec_kernel: Cell::new(None),
q5_k_kernel: Cell::<Option<FixedPairKernels>>::new(None),
q6_k_kernel: Cell::new(None),
common_quantizer: Cell::new(None),
projection_kernels: std::array::from_fn(|_| {
Cell::<Option<ProjectionKernels>>::new(None)
}),
qwen_kernels: Cache::new(),
};
let context = make_context();
let other = make_context();
for operation in qwen_ffi::QSA_OPERATIONS {
let layout = operation.layout();
let mut buffers: Vec<_> = (0..layout.count)
.map(|i| DeviceBuffer {
context: &context,
handle: Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))),
bytes: layout.bytes[i],
_thread: PhantomData,
})
.collect();
let (inputs, outputs) = buffers.split_at_mut(layout.outputs.trailing_zeros() as usize);
let result = match operation {
Operation::QsaSplit => {
let (q, gate) = outputs.split_at_mut(1);
context.qsa_split_q_gate(&inputs[0], &mut q[0], &mut gate[0])
}
Operation::QsaNormQ => context.qsa_norm_q(&inputs[0], &inputs[1], &mut outputs[0]),
Operation::QsaNormK => context.qsa_norm_k(&inputs[0], &inputs[1], &mut outputs[0]),
Operation::QsaNormIndexQ => {
context.qsa_norm_index_q(&inputs[0], &inputs[1], &mut outputs[0])
}
Operation::QsaRopeQ => context.qsa_rope_q(&inputs[0], 0, &mut outputs[0]),
Operation::QsaRopeK => context.qsa_rope_k(&inputs[0], 0, &mut outputs[0]),
Operation::QsaRopeIndexQ => {
context.qsa_rope_index_q(&inputs[0], 0, &mut outputs[0])
}
Operation::QsaIndexAppend => {
context.qsa_index_append(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0)
}
Operation::QsaPackKv => {
let (k, v) = outputs.split_at_mut(1);
context.qsa_pack_kv(&inputs[0], &inputs[1], &mut k[0], &mut v[0])
}
Operation::QsaBlockScores => {
context.qsa_block_scores(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0)
}
Operation::QsaBlockTopk => context.qsa_block_topk(&inputs[0], &mut outputs[0], 0),
Operation::QsaAttend => {
context.qsa_attend(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 1)
}
Operation::QsaGate => context.qsa_gate_f32(&inputs[0], &inputs[1], &mut outputs[0]),
_ => unreachable!("exact thirteen QSA methods"),
};
assert_eq!(result, Err(Error::UnsupportedQwenOperation));
let mut foreign = DeviceBuffer {
context: &other,
handle: Some(ffi::BufferHandle::synthetic(0x90000000)),
bytes: layout.bytes[0],
_thread: PhantomData,
};
assert_eq!(
context.qsa_call(operation, &[&foreign], 0),
Err(Error::ContextMismatch)
);
foreign.handle = None;
context.poisoned.set(true);
let refs: Vec<_> = buffers.iter().collect();
assert_eq!(
context.qsa_call(operation, &refs, 0),
Err(Error::ContextPoisoned)
);
context.poisoned.set(false);
assert_eq!(context.allocated.get(), 99);
assert_eq!(ready(&context.qwen_kernels), 0);
assert!(!context.poisoned.get());
for (i, buffer) in buffers.iter_mut().enumerate() {
assert!(
buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))
);
assert_eq!(buffer.bytes, layout.bytes[i]);
// Synthetic owners have no CUDA allocation to free.
buffer.handle = None;
}
}
}
#[test]
fn moe_new_preflight_requires_exact_disjoint_owner_spans() {
let handles =
@@ -918,7 +1328,10 @@ mod tests {
ranges_layout(operation, layout, handles, shortened, false),
Err(Error::InvalidQwenShape)
);
assert!(qwen_ffi::asset(operation).is_none());
qwen_ffi::asset(operation)
.expect("separately admitted163 component")
.validate(operation)
.unwrap();
}
#[derive(Default)]
+465 -4
View File
@@ -38,8 +38,21 @@ pub(super) enum Operation {
MoeSharedScalar,
MoeSharedScale,
MoeCombine,
QsaSplit,
QsaNormQ,
QsaNormK,
QsaNormIndexQ,
QsaRopeQ,
QsaRopeK,
QsaRopeIndexQ,
QsaIndexAppend,
QsaPackKv,
QsaBlockScores,
QsaBlockTopk,
QsaAttend,
QsaGate,
}
pub(super) const OPERATIONS: [Operation; 26] = [
pub(super) const OPERATIONS: [Operation; 39] = [
Operation::Down,
Operation::Up,
Operation::InjectProjection,
@@ -66,6 +79,34 @@ pub(super) const OPERATIONS: [Operation; 26] = [
Operation::MoeSharedScalar,
Operation::MoeSharedScale,
Operation::MoeCombine,
Operation::QsaSplit,
Operation::QsaNormQ,
Operation::QsaNormK,
Operation::QsaNormIndexQ,
Operation::QsaRopeQ,
Operation::QsaRopeK,
Operation::QsaRopeIndexQ,
Operation::QsaIndexAppend,
Operation::QsaPackKv,
Operation::QsaBlockScores,
Operation::QsaBlockTopk,
Operation::QsaAttend,
Operation::QsaGate,
];
pub(super) const QSA_OPERATIONS: [Operation; 13] = [
Operation::QsaSplit,
Operation::QsaNormQ,
Operation::QsaNormK,
Operation::QsaNormIndexQ,
Operation::QsaRopeQ,
Operation::QsaRopeK,
Operation::QsaRopeIndexQ,
Operation::QsaIndexAppend,
Operation::QsaPackKv,
Operation::QsaBlockScores,
Operation::QsaBlockTopk,
Operation::QsaAttend,
Operation::QsaGate,
];
impl Operation {
@@ -94,9 +135,26 @@ impl Operation {
Self::MoeSharedScalar => c"leleka_moe_shared_gate_f32_bf16",
Self::MoeSharedScale => c"leleka_moe_scale_shared_f32",
Self::MoeCombine => c"leleka_moe_combine_f32",
Self::QsaSplit => c"leleka_qsa_split_q_gate",
Self::QsaNormQ => c"leleka_qsa_norm_q",
Self::QsaNormK => c"leleka_qsa_norm_k",
Self::QsaNormIndexQ => c"leleka_qsa_norm_index_q",
Self::QsaRopeQ => c"leleka_qsa_rope_q",
Self::QsaRopeK => c"leleka_qsa_rope_k",
Self::QsaRopeIndexQ => c"leleka_qsa_rope_index_q",
Self::QsaIndexAppend => c"leleka_qsa_index_append",
Self::QsaPackKv => c"leleka_qsa_pack_kv",
Self::QsaBlockScores => c"leleka_qsa_block_scores",
Self::QsaBlockTopk => c"leleka_qsa_block_topk",
Self::QsaAttend => c"leleka_qsa_attend",
Self::QsaGate => c"leleka_qsa_gate_f32",
}
}
pub(super) fn layout(self) -> Layout {
if QSA_OPERATIONS.contains(&self) {
return qsa_layout(self, u32::from(self == Self::QsaAttend))
.expect("fixed minimum QSA geometry");
}
if let Some(layout) = moe_layout(self) {
return layout;
}
@@ -115,6 +173,9 @@ impl Operation {
rows: 512,
columns: 1,
grid: 1,
grid_y: 1,
shared_bytes: 0,
integer: None,
grid_z: 1,
block: 32,
block_y: 8,
@@ -139,6 +200,19 @@ impl Operation {
// Other entries use their ordered buffer pointers, then epsilon only
// for Norm; fixed N/HC/H live in the qualified executable contract.
let (bytes, align, count, outputs, rows, columns, block) = match self {
Self::QsaSplit
| Self::QsaNormQ
| Self::QsaNormK
| Self::QsaNormIndexQ
| Self::QsaRopeQ
| Self::QsaRopeK
| Self::QsaRopeIndexQ
| Self::QsaIndexAppend
| Self::QsaPackKv
| Self::QsaBlockScores
| Self::QsaBlockTopk
| Self::QsaAttend
| Self::QsaGate => unreachable!("fixed QSA geometry above"),
Self::Down | Self::Up | Self::InjectProjection => {
unreachable!("checked fixed MMVF geometry above")
}
@@ -206,6 +280,9 @@ impl Operation {
rows: rows as u32,
columns: columns as u32,
grid: grid as u32,
grid_y: 1,
shared_bytes: 0,
integer: None,
grid_z: 1,
block: block as u32,
block_y: 1,
@@ -214,6 +291,117 @@ impl Operation {
}
}
/// Closed source-defined QSA extents. Position and selected width are the only
/// semantic scalars; native index/launch calculations never come from callers.
pub(super) fn qsa_layout(operation: Operation, value: u32) -> Result<Layout> {
if !QSA_OPERATIONS.contains(&operation) {
return Err(Error::InvalidQwenShape);
}
if operation == Operation::QsaAttend {
if !(1..=2051).contains(&value) {
return Err(Error::InvalidQwenShape);
}
} else if value > 262143 {
return Err(Error::InvalidQwenShape);
}
let rows = value.checked_add(1).ok_or(Error::InvalidQwenShape)? / 4 + 1;
let pooled = usize::try_from(rows)
.ok()
.and_then(|n| n.checked_mul(512))
.ok_or(Error::InvalidQwenShape)?;
let scores = usize::try_from(rows)
.ok()
.and_then(|n| n.checked_mul(4))
.ok_or(Error::InvalidQwenShape)?;
let packed = usize::try_from(value)
.ok()
.and_then(|n| n.checked_mul(1024))
.ok_or(Error::InvalidQwenShape)?;
let (bytes, count, outputs, grid, grid_y, integer) = match operation {
Operation::QsaSplit => ([49152, 24576, 24576, 0, 0, 0, 0, 0], 3, 6, 24, 1, None),
Operation::QsaNormQ => ([24576, 1024, 24576, 0, 0, 0, 0, 0], 3, 4, 24, 1, None),
Operation::QsaNormK => ([2048, 1024, 2048, 0, 0, 0, 0, 0], 3, 4, 2, 1, None),
Operation::QsaNormIndexQ => ([2048, 512, 2048, 0, 0, 0, 0, 0], 3, 4, 4, 1, None),
Operation::QsaRopeQ => (
[24576, 24576, 0, 0, 0, 0, 0, 0],
2,
2,
1,
24,
Some((value, 1)),
),
Operation::QsaRopeK => ([2048, 2048, 0, 0, 0, 0, 0, 0], 2, 2, 1, 2, Some((value, 1))),
Operation::QsaRopeIndexQ => ([2048, 2048, 0, 0, 0, 0, 0, 0], 2, 2, 1, 4, Some((value, 1))),
Operation::QsaIndexAppend => (
[512, 512, 2048, 2560, 0, 0, 0, 0],
4,
8,
1,
1,
Some((value, 4)),
),
Operation::QsaPackKv => ([2048, 2048, 1024, 1024, 0, 0, 0, 0], 4, 12, 2, 1, None),
Operation::QsaBlockScores => (
[pooled, 512, 2048, scores, 0, 0, 0, 0],
4,
8,
256,
1,
Some((value, 4)),
),
Operation::QsaBlockTopk => (
[scores, 8204, 0, 0, 0, 0, 0, 0],
2,
2,
1,
1,
Some((value, 2)),
),
Operation::QsaAttend => (
[24576, packed, packed, 24576, 0, 0, 0, 0],
4,
8,
24,
1,
Some((value, 4)),
),
Operation::QsaGate => ([24576, 24576, 24576, 0, 0, 0, 0, 0], 3, 4, 24, 1, None),
_ => return Err(Error::InvalidQwenShape),
};
let mut align = [4; 8];
match operation {
Operation::QsaPackKv => {
align[2] = 2;
align[3] = 2;
}
Operation::QsaAttend => {
align[1] = 2;
align[2] = 2;
}
_ => (),
}
Ok(Layout {
bytes,
align,
count,
outputs,
rows: 24,
columns: 256,
grid,
grid_y,
grid_z: 1,
block: 256,
block_y: 1,
projection: false,
integer,
shared_bytes: if operation == Operation::QsaAttend {
8332
} else {
0
},
})
}
fn ple_layout(operation: Operation) -> Option<Layout> {
let (bytes, count, outputs, grid) = match operation {
Operation::PleValue => ([10240, 327680, 256, 0, 0, 0, 0, 0], 3, 4, 1),
@@ -238,6 +426,9 @@ fn ple_layout(operation: Operation) -> Option<Layout> {
rows: 4,
columns: 2560,
grid,
grid_y: 1,
shared_bytes: 0,
integer: None,
grid_z: 1,
block: 256,
block_y: 1,
@@ -265,6 +456,9 @@ fn moe_layout(operation: Operation) -> Option<Layout> {
rows: 10,
columns: 2560,
grid,
grid_y: 1,
shared_bytes: 0,
integer: None,
grid_z: 1,
block: 256,
block_y: 1,
@@ -315,6 +509,9 @@ fn gdn_layout(operation: Operation) -> Option<Layout> {
columns: 48,
grid,
grid_z,
grid_y: 1,
shared_bytes: 0,
integer: None,
block,
block_y,
projection: false,
@@ -363,6 +560,9 @@ pub(super) fn bf16_layout(rows: usize, columns: usize) -> Result<Layout> {
rows: rows as u32,
columns: columns as u32,
grid: rows as u32,
grid_y: 1,
shared_bytes: 0,
integer: None,
grid_z: 1,
block: block as u32,
block_y: 1,
@@ -380,6 +580,10 @@ pub(super) struct Layout {
pub columns: u32,
pub grid: u32,
pub grid_z: u32,
pub grid_y: u32,
pub shared_bytes: u32,
// Fixed ABI scalar (value, parameter index); never caller-controlled geometry.
pub integer: Option<(u32, usize)>,
pub block: u32,
pub block_y: u32,
pub projection: bool,
@@ -707,6 +911,19 @@ pub(super) fn asset(operation: Operation) -> Option<&'static Asset> {
Operation::MoeSharedScalar => Some(&MOE_ASSETS[1]),
Operation::MoeSharedScale => Some(&MOE_ASSETS[2]),
Operation::MoeCombine => Some(&MOE_ASSETS[3]),
Operation::QsaSplit
| Operation::QsaNormQ
| Operation::QsaNormK
| Operation::QsaNormIndexQ
| Operation::QsaRopeQ
| Operation::QsaRopeK
| Operation::QsaRopeIndexQ
| Operation::QsaIndexAppend
| Operation::QsaPackKv
| Operation::QsaBlockScores
| Operation::QsaBlockTopk
| Operation::QsaAttend
| Operation::QsaGate => None,
}
}
@@ -715,6 +932,7 @@ struct Storage {
rows: u32,
columns: u32,
epsilon: f32,
integer: u32,
parameters: [*mut c_void; 9],
}
pub(super) struct Arguments {
@@ -743,13 +961,19 @@ impl Arguments {
rows: layout.rows,
columns: layout.columns,
epsilon,
integer: layout.integer.map_or(0, |(value, _)| value),
parameters: [std::ptr::null_mut(); 9],
}));
// SAFETY: uniquely raw-owned stable allocation. No Box/reference
// retagging occurs after these self-referential field addresses form.
unsafe {
for i in 0..layout.count {
(*storage).parameters[i] = (&raw mut (*storage).addresses[i]).cast();
let parameter =
i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i));
(*storage).parameters[parameter] = (&raw mut (*storage).addresses[i]).cast();
}
if let Some((_, index)) = layout.integer {
(*storage).parameters[index] = (&raw mut (*storage).integer).cast();
}
if layout.projection {
(*storage).parameters[3] = (&raw mut (*storage).rows).cast();
@@ -903,6 +1127,239 @@ pub(super) fn mock_asset(operation: Operation) -> Asset {
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn qsa_new_literal_abi_scalar_order_and_geometry() {
// Independently frozen producer ABI, STRA-172 AD10; no candidate PTX.
for (operation, entry, bytes, outputs, grid, grid_y, shared, index) in [
(
Operation::QsaSplit,
c"leleka_qsa_split_q_gate",
vec![49152, 24576, 24576],
6,
24,
1,
0,
None,
),
(
Operation::QsaNormQ,
c"leleka_qsa_norm_q",
vec![24576, 1024, 24576],
4,
24,
1,
0,
None,
),
(
Operation::QsaNormK,
c"leleka_qsa_norm_k",
vec![2048, 1024, 2048],
4,
2,
1,
0,
None,
),
(
Operation::QsaNormIndexQ,
c"leleka_qsa_norm_index_q",
vec![2048, 512, 2048],
4,
4,
1,
0,
None,
),
(
Operation::QsaRopeQ,
c"leleka_qsa_rope_q",
vec![24576, 24576],
2,
1,
24,
0,
Some(1),
),
(
Operation::QsaRopeK,
c"leleka_qsa_rope_k",
vec![2048, 2048],
2,
1,
2,
0,
Some(1),
),
(
Operation::QsaRopeIndexQ,
c"leleka_qsa_rope_index_q",
vec![2048, 2048],
2,
1,
4,
0,
Some(1),
),
(
Operation::QsaIndexAppend,
c"leleka_qsa_index_append",
vec![512, 512, 2048, 2560],
8,
1,
1,
0,
Some(4),
),
(
Operation::QsaPackKv,
c"leleka_qsa_pack_kv",
vec![2048, 2048, 1024, 1024],
12,
2,
1,
0,
None,
),
(
Operation::QsaBlockScores,
c"leleka_qsa_block_scores",
vec![1024, 512, 2048, 8],
8,
256,
1,
0,
Some(4),
),
(
Operation::QsaBlockTopk,
c"leleka_qsa_block_topk",
vec![8, 8204],
2,
1,
1,
0,
Some(2),
),
(
Operation::QsaAttend,
c"leleka_qsa_attend",
vec![24576, 3072, 3072, 24576],
8,
24,
1,
8332,
Some(4),
),
(
Operation::QsaGate,
c"leleka_qsa_gate_f32",
vec![24576, 24576, 24576],
4,
24,
1,
0,
None,
),
] {
let layout = qsa_layout(operation, 3).unwrap();
assert_eq!(operation.entry(), entry);
assert_eq!(&layout.bytes[..layout.count], bytes);
assert_eq!(
(
layout.outputs,
layout.grid,
layout.grid_y,
layout.grid_z,
layout.block,
layout.block_y,
layout.shared_bytes
),
(outputs, grid, grid_y, 1, 256, 1, shared)
);
assert_eq!(layout.integer, index.map(|i| (3, i)));
assert!(asset(operation).is_none());
let addresses = [101, 202, 303, 404, 505, 606, 707, 808];
let handles = addresses.map(ffi::BufferHandle::synthetic);
let arguments = Arguments::with_layout(operation, layout, handles, 0.0);
// Move the raw allocation owner, then read its initialized fields;
// no Box ownership/reborrow is introduced after pointer formation.
let mut moved = std::hint::black_box(arguments);
let table = moved.parameters();
// SAFETY: table points into one live raw-owned allocation, exact
// parameter types/order are the independent frozen ABI above.
unsafe {
for (i, address) in addresses.iter().take(bytes.len()).enumerate() {
let slot = i + usize::from(index.is_some_and(|j| j <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *address);
}
if let Some(i) = index {
assert_eq!(*(*table.add(i)).cast::<u32>(), 3);
}
assert!((*table.add(bytes.len() + usize::from(index.is_some()))).is_null());
}
for (i, alignment) in layout.align.iter().take(layout.count).enumerate() {
let packed = (operation == Operation::QsaPackKv && i >= 2)
|| (operation == Operation::QsaAttend && (i == 1 || i == 2));
assert_eq!(*alignment, if packed { 2 } else { 4 });
}
}
assert_eq!(OPERATIONS.len(), 39);
for operation in OPERATIONS
.into_iter()
.filter(|op| !QSA_OPERATIONS.contains(op))
{
let old = operation.layout();
assert_eq!((old.grid_y, old.shared_bytes, old.integer), (1, 0, None));
}
}
#[test]
fn qsa_new_position_block_boundaries_and_attention_width_refusals() {
// Literal causal/block boundaries, including one past the context.
for (position, pooled, scores) in [
(0, 512, 4),
(2, 512, 4),
(3, 1024, 8),
(4, 1024, 8),
(2047, 262656, 2052),
(262143, 33554944, 262148),
] {
let score = qsa_layout(Operation::QsaBlockScores, position).unwrap();
assert_eq!((score.bytes[0], score.bytes[3]), (pooled, scores));
let ids = qsa_layout(Operation::QsaBlockTopk, position).unwrap();
assert_eq!((ids.bytes[0], ids.bytes[1]), (scores, 8204));
assert_eq!(score.integer, Some((position, 4)));
}
for operation in QSA_OPERATIONS
.into_iter()
.filter(|op| *op != Operation::QsaAttend)
{
assert!(qsa_layout(operation, 262143).is_ok());
for position in [262144, u32::MAX] {
assert!(matches!(
qsa_layout(operation, position),
Err(Error::InvalidQwenShape)
));
}
}
for (width, extent) in [(1, 1024), (2051, 2100224)] {
let layout = qsa_layout(Operation::QsaAttend, width).unwrap();
assert_eq!((layout.bytes[1], layout.bytes[2]), (extent, extent));
assert_eq!(layout.integer, Some((width, 4)));
}
for width in [0, 2052, u32::MAX] {
assert!(matches!(
qsa_layout(Operation::QsaAttend, width),
Err(Error::InvalidQwenShape)
));
}
assert!(matches!(
qsa_layout(Operation::Norm, 0),
Err(Error::InvalidQwenShape)
));
}
#[test]
fn moe_fixed_pointer_abi_extents_and_qualified_receipts() {
// Literal expectations come from STRA-167 AD v1 / STRA-172 AD v8.
@@ -970,7 +1427,7 @@ mod tests {
assert!((*parameters.add(count)).is_null());
}
}
assert_eq!(OPERATIONS.len(), 26);
assert_eq!(OPERATIONS.len(), 39);
}
#[test]
@@ -1014,7 +1471,11 @@ mod tests {
.enumerate()
.take(layout.count)
{
assert_eq!(*(*table.add(i)).cast::<u64>(), *expected);
let slot = i + usize::from(layout.integer.is_some_and(|(_, index)| index <= i));
assert_eq!(*(*table.add(slot)).cast::<u64>(), *expected);
}
if let Some((value, index)) = layout.integer {
assert_eq!(*(*table.add(index)).cast::<u32>(), value);
}
if layout.projection {
assert_eq!(*(*table.add(3)).cast::<u32>(), layout.rows);