cuda-driver: wide top-k for long prompt tiles and a decode top-k on a thread-block cluster (upstream 586367cb, d05d26e9, row 2.5), both opt-in

leleka_qsa_topk_wide (also _sample/_wide_failed, measured and not used) in qsa_late.cu; leleka_qsa_topk_cluster in the new sealed asset qsa_cluster.cu (sm_90+,
no sm_86 companion); cuLaunchKernelEx plumbing for KernelModule and the verifier window (Launch.cluster); policy.qsa.cluster_topk. Same ids as qsa_topk_ref in
every model-free case (continuous, heavy tailed, tied, all equal; prompt tiles of 256 rows and decode calls of 1..5 rows up to 261,500 tokens).
LELEKA_QSA_TOPK=wide (prompt, from 10,000 blocks) and LELEKA_QSA_CLUSTER=1 (decode window) switch them on; defaults off until their R gate.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-27 08:52:15 +01:00
co-authored by Claude Sonnet 5.5
parent 68fbd99346
commit 4ace54b773
20 changed files with 11477 additions and 63 deletions
+20 -12
View File
@@ -1648,7 +1648,7 @@
"ptxas": "ok",
"recipe": "precise",
"recipe_confidence": "entries+flag-mode",
"retarget_rejected": "ptxas /home/para/work/q8merge/sm86/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /home/para/work/q8merge/sm86/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors",
"retarget_rejected": "ptxas /tmp/rest-sm86/build/mtp_original_prefill_quant.sm86.ptx, line 34613; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas /tmp/rest-sm86/build/mtp_original_prefill_quant.sm86.ptx, line 36077; error : Feature 'cvt.f16x2.e4m3x2' requires .target sm_89 or higher | ptxas fatal : Ptx assembly aborted due to errors",
"rules": [],
"sm120_bytes": 1343875,
"sm120_nvcc": "13.0.88",
@@ -2207,7 +2207,7 @@
"sm86_sha256": "bfcd7c884462c1e1e28e3f73c7250fbba51bc0c95f037dba184f3224758faa33"
},
{
"entries": 17,
"entries": 18,
"isa": "9.2",
"method": "retarget",
"name": "prefill_stage.ptx",
@@ -2218,13 +2218,13 @@
"count": 1
}
],
"sm120_bytes": 112485,
"sm120_bytes": 157373,
"sm120_nvcc": "13.2.86",
"sm120_path": "crates/cuda-driver/src/prefill_stage.ptx",
"sm120_sha256": "3aacbef45fed661823f9500a568b0d8964ef6a206664ba6a42d374b3e2bb0106",
"sm120_sha256": "2519ccbc131bae4aa468f29fcc1fb818206c662491c4cd553bea46ab2df84e37",
"sm120_stored_nul": false,
"sm86_bytes": 112484,
"sm86_sha256": "0cd1835dc83d3a3186f220439c6777a3a7e7048d8d09dffdbe011b1672d9553d"
"sm86_bytes": 157372,
"sm86_sha256": "71fe021cb0cd1525ae9b8c028dbf894c501dc4b69f57f61b1e74235969ff8c83"
},
{
"entries": 2,
@@ -2387,7 +2387,7 @@
"sm86_sha256": "5ff2931901099c2cfdb6039456522a1e1c26ae32b61fdf69fbeed9c2ca02dd1e"
},
{
"entries": 2,
"entries": 5,
"isa": "9.2",
"method": "retarget",
"name": "qsa_late.ptx",
@@ -2398,13 +2398,13 @@
"count": 1
}
],
"sm120_bytes": 26496,
"sm120_bytes": 213285,
"sm120_nvcc": "13.2.86",
"sm120_path": "crates/cuda-driver/src/qsa_late.ptx",
"sm120_sha256": "6168e052bb23c0544ff29e941006dd873a0bf1c0aef19828091f5663430aeb91",
"sm120_sha256": "ebc8bc0aac1bd4a74540ed246c00960d10159630201133e6d21f306efeb1ba2f",
"sm120_stored_nul": false,
"sm86_bytes": 26495,
"sm86_sha256": "e41db0830ffffd967a142efc0d4cd78efb24ecae7e96f32008f116a7595066e8"
"sm86_bytes": 213284,
"sm86_sha256": "118d2300e67d15420b7ebdb4ee823d91be5855620723853fe9da8def8ae5e98b"
},
{
"entries": 3,
@@ -2691,7 +2691,15 @@
"sm86_sha256": "9747c1be0db52066f1efe8efa9addf1423c5fd12e3174799df853b0f71557655"
}
],
"not_built": [],
"not_built": [
{
"name": "qsa_cluster.ptx",
"sm120_path": "crates/cuda-driver/src/qsa_cluster.ptx",
"problems": [
"retarget rejected and no verified recipe: ptxas /tmp/rest-sm86/build/qsa_cluster.sm86.ptx, line 1179; error : Feature 'barrier.cluster.arrive' requires .target sm_90 or higher | ptxas /tmp/rest-sm86/build/qsa_cluster.sm86.ptx, line 1183; error : Feature 'barrier.cluster.wait' requires .target sm_90 or higher | ptxas fatal : Ptx assembly aborted due to errors"
]
}
],
"portable_no_companion_needed": [
{
"path": "crates/cuda-driver/src/gr_read_guard.ptx",
File diff suppressed because it is too large Load Diff
+48
View File
@@ -0,0 +1,48 @@
//! `cuLaunchKernelEx` ABI pieces shared by the module wrappers (thread-block clusters, sm_90+; docs/upstream-port-plan.md row 2.5).
//! `CUlaunchConfig` / `CUlaunchAttribute` of cuda.h (CUDA 12.x/13.x): the attribute is an enum id, padding to 8 bytes and a 64-byte union.
use std::ffi::{c_int, c_void};
/// `CU_LAUNCH_ATTRIBUTE_CLUSTER_DIMENSION`.
const ATTRIBUTE_CLUSTER_DIMENSION: u32 = 4;
/// `CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES`.
pub(crate) const FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED: c_int = 8;
#[repr(C)]
pub(crate) struct LaunchAttribute {
id: u32,
_pad: u32,
value: [u64; 8],
}
impl LaunchAttribute {
/// A cluster of `x * 1 * 1` CTAs (`value.clusterDim = {x, 1, 1}`).
pub(crate) fn cluster_x(x: u32) -> Self {
let mut value = [0u64; 8];
value[0] = (x as u64) | (1u64 << 32);
value[1] = 1;
Self { id: ATTRIBUTE_CLUSTER_DIMENSION, _pad: 0, value }
}
}
#[repr(C)]
pub(crate) struct LaunchConfig {
pub(crate) grid: [u32; 3],
pub(crate) block: [u32; 3],
pub(crate) smem: u32,
pub(crate) stream: *mut c_void,
pub(crate) attrs: *mut LaunchAttribute,
pub(crate) num_attrs: u32,
}
pub(crate) type LaunchEx = unsafe extern "C" fn(*const LaunchConfig, *mut c_void, *mut *mut c_void, *mut *mut c_void) -> c_int;
pub(crate) type FuncSetAttribute = unsafe extern "C" fn(*mut c_void, c_int, c_int) -> c_int;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_structs_have_the_sizes_of_cuda_h() {
assert_eq!(std::mem::size_of::<LaunchAttribute>(), 72);
assert_eq!(std::mem::align_of::<LaunchAttribute>(), 8);
assert_eq!(std::mem::size_of::<LaunchConfig>(), 56);
let a = LaunchAttribute::cluster_x(8);
assert_eq!((a.id, a.value[0] as u32, (a.value[0] >> 32) as u32, a.value[1] as u32), (4, 8, 1, 1));
}
}
+2
View File
@@ -3243,6 +3243,8 @@ pub use original_sampler::{OriginalSampler, SamplerParams, SamplerPath};
mod native_prompt_device;
mod prefill_stage;
mod launch_ex;
mod qsa_cluster;
mod qsa_late;
pub use qsa_late::set_override as set_qsa_late_override;
pub use native_prompt_device::{
+10 -5
View File
@@ -12,12 +12,14 @@ type DeviceAttr=unsafe extern "C" fn(*mut i32,i32,i32)->i32;
/// `Words` is one by-value kernel struct parameter (e.g. `GrMulti`): its bytes are the little-endian u64 words.
pub(crate) enum Arg{Address(u64),I32(i32),I64(i64),U64(u64),F32(f32),Words(Box<[u64]>)}
impl Arg{fn pointer(&mut self)->*mut c_void{match self{Self::Address(v)|Self::U64(v)=>(v as *mut u64).cast(),Self::I32(v)=>(v as *mut i32).cast(),Self::I64(v)=>(v as *mut i64).cast(),Self::F32(v)=>(v as *mut f32).cast(),Self::Words(v)=>v.as_mut_ptr().cast()}}}
pub(crate) struct Command{pub name:&'static str,pub grid:[u32;3],pub block:[u32;3],pub shared:u32,args:Box<[Arg]>,pointers:Vec<*mut c_void>}
/// `cluster` > 0: launched with `cuLaunchKernelEx` as a thread-block cluster of that many CTAs along x (sm_90+, row 2.5); 0: `cuLaunchKernel`.
pub(crate) struct Command{pub name:&'static str,pub grid:[u32;3],pub block:[u32;3],pub shared:u32,pub cluster:u32,args:Box<[Arg]>,pointers:Vec<*mut c_void>}
impl Command{pub(crate) fn abi_bytes(&self)->Result<usize>{self.args.len().checked_mul(std::mem::size_of::<Arg>()).and_then(|n|self.pointers.capacity().checked_mul(std::mem::size_of::<*mut c_void>()).and_then(|m|n.checked_add(m))).ok_or(Error::InvalidSize)}
pub(crate) fn new(name:&'static str,grid:[u32;3],block:[u32;3],shared:u32,args:Vec<Arg>)->Result<Self>{let mut pointers=Vec::new();pointers.try_reserve_exact(args.len()).map_err(|_|Error::HostAllocation)?;Ok(Self{name,grid,block,shared,args:args.into_boxed_slice(),pointers})}}
pub(crate) fn new(name:&'static str,grid:[u32;3],block:[u32;3],shared:u32,args:Vec<Arg>)->Result<Self>{let mut pointers=Vec::new();pointers.try_reserve_exact(args.len()).map_err(|_|Error::HostAllocation)?;Ok(Self{name,grid,block,shared,cluster:0,args:args.into_boxed_slice(),pointers})}
pub(crate) fn with_cluster(mut self,cluster:u32)->Self{self.cluster=cluster;self}}
struct Library(Handle);
impl Drop for Library{fn drop(&mut self){if !self.0.is_null(){unsafe{libc::dlclose(self.0);}}}}
pub(crate) struct Module{library:Option<Library>,handle:Option<usize>,functions:Vec<(&'static str,usize)>,launch:Launch,unload:Destroy,set_attr:SetAttr,device:DeviceOf,device_attr:DeviceAttr}
pub(crate) struct Module{library:Option<Library>,handle:Option<usize>,functions:Vec<(&'static str,usize)>,launch:Launch,launch_ex:Option<crate::launch_ex::LaunchEx>,unload:Destroy,set_attr:SetAttr,device:DeviceOf,device_attr:DeviceAttr}
fn check(op:&'static str,c:i32)->Result<()>{if c==0{Ok(())}else{Err(Error::Driver{operation:op,code:c})}}
impl Module{
pub(crate) fn load(ptx:&'static[u8],entries:&[&'static str])->Result<Self>{
@@ -26,13 +28,16 @@ impl Module{
fn sym(l:&Library,n:&'static CStr)->Result<Handle>{let p=unsafe{libc::dlsym(l.0,n.as_ptr())};if p.is_null(){Err(Error::MissingSymbol(n.to_str().unwrap_or("OriginalVerify ABI")))}else{Ok(p)}}
macro_rules! symbol{($n:literal,$t:ty)=>{unsafe{std::mem::transmute::<Handle,$t>(sym(&library,$n)?)} };}
let load=symbol!(c"cuModuleLoadData",Load);let function=symbol!(c"cuModuleGetFunction",Function);
let mut owner=Self{launch:symbol!(c"cuLaunchKernel",Launch),unload:symbol!(c"cuModuleUnload",Destroy),set_attr:symbol!(c"cuFuncSetAttribute",SetAttr),device:symbol!(c"cuCtxGetDevice",DeviceOf),device_attr:symbol!(c"cuDeviceGetAttribute",DeviceAttr),library:Some(library),handle:None,functions:Vec::new()};
let launch_ex=sym(&library,c"cuLaunchKernelEx").ok().map(|p|unsafe{std::mem::transmute::<Handle,crate::launch_ex::LaunchEx>(p)});
let mut owner=Self{launch:symbol!(c"cuLaunchKernel",Launch),launch_ex,unload:symbol!(c"cuModuleUnload",Destroy),set_attr:symbol!(c"cuFuncSetAttribute",SetAttr),device:symbol!(c"cuCtxGetDevice",DeviceOf),device_attr:symbol!(c"cuDeviceGetAttribute",DeviceAttr),library:Some(library),handle:None,functions:Vec::new()};
owner.functions.try_reserve_exact(entries.len()).map_err(|_|Error::HostAllocation)?;
let operation=(||{let mut h=std::ptr::null_mut();check("cuModuleLoadData",unsafe{load(&mut h,crate::arch_ptx::image(ptx).as_ptr().cast())})?;if h.is_null(){return Err(Error::InvalidDriverValue("cuModuleLoadData"));}owner.handle=Some(h as usize);for &name in entries{let c=std::ffi::CString::new(name).map_err(|_|Error::InvalidSize)?;let mut f=std::ptr::null_mut();check("cuModuleGetFunction",unsafe{function(&mut f,h,c.as_ptr())})?;if f.is_null(){return Err(Error::InvalidDriverValue("cuModuleGetFunction"));}owner.functions.push((name,f as usize));}Ok(())})();
if let Err(primary)=operation{return combine(Err(primary),owner.close());}Ok(owner)
}
pub(crate) fn admit(&self,c:&Command)->Result<()>{if self.handle.is_none()||!self.functions.iter().any(|(n,_)|*n==c.name)||c.grid.contains(&0)||c.block.contains(&0){return Err(Error::InvalidQwenShape);}Ok(())}
pub(crate) fn launch(&self,stream:usize,c:&mut Command)->Result<()>{self.admit(c)?;let f=self.functions.iter().find(|(n,_)|*n==c.name).ok_or(Error::UnsupportedQwenOperation)?.1;c.pointers.clear();for arg in c.args.iter_mut(){c.pointers.push(arg.pointer());}check("cuLaunchKernel",unsafe{(self.launch)(f as Handle,c.grid[0],c.grid[1],c.grid[2],c.block[0],c.block[1],c.block[2],c.shared,stream as Handle,c.pointers.as_mut_ptr(),std::ptr::null_mut())})}
pub(crate) fn launch(&self,stream:usize,c:&mut Command)->Result<()>{self.admit(c)?;let f=self.functions.iter().find(|(n,_)|*n==c.name).ok_or(Error::UnsupportedQwenOperation)?.1;c.pointers.clear();for arg in c.args.iter_mut(){c.pointers.push(arg.pointer());}
if c.cluster>0{let launch_ex=self.launch_ex.ok_or(Error::MissingSymbol("cuLaunchKernelEx"))?;if c.grid[0]%c.cluster!=0{return Err(Error::InvalidQwenShape);}let mut attribute=crate::launch_ex::LaunchAttribute::cluster_x(c.cluster);let config=crate::launch_ex::LaunchConfig{grid:c.grid,block:c.block,smem:c.shared,stream:stream as Handle,attrs:&mut attribute,num_attrs:1};return check("cuLaunchKernelEx",unsafe{launch_ex(&config,f as Handle,c.pointers.as_mut_ptr(),std::ptr::null_mut())});}
check("cuLaunchKernel",unsafe{(self.launch)(f as Handle,c.grid[0],c.grid[1],c.grid[2],c.block[0],c.block[1],c.block[2],c.shared,stream as Handle,c.pointers.as_mut_ptr(),std::ptr::null_mut())})}
/// `cuFuncSetAttribute(CU_FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED_SIZE_BYTES)` of one loaded entry (Original sets it once
/// before any launch/capture for kernels that stage more than 48 KiB).
pub(crate) fn set_max_dynamic_shared(&self,name:&str,bytes:usize)->Result<()>{let f=self.functions.iter().find(|(n,_)|*n==name).ok_or(Error::UnsupportedQwenOperation)?.1;check("cuFuncSetAttribute",unsafe{(self.set_attr)(f as Handle,8,i32::try_from(bytes).map_err(|_|Error::InvalidSize)?)})}
@@ -130,6 +130,8 @@ pub(crate) struct Launch {
pub block: [u32; 3],
pub shared: u32,
pub args: Vec<A>,
/// > 0: a thread-block cluster of this many CTAs along x (`cuLaunchKernelEx`, sm_90+); 0: a plain launch.
pub cluster: u32,
}
impl PartialEq for Launch {
fn eq(&self, o: &Self) -> bool {
@@ -138,6 +140,7 @@ impl PartialEq for Launch {
&& self.grid == o.grid
&& self.block == o.block
&& self.shared == o.shared
&& self.cluster == o.cluster
&& self.args == o.args
}
}
@@ -154,10 +157,15 @@ impl Launch {
if !asset.has_entry(entry) || grid.contains(&0) || block.contains(&0) {
return Err(Error::InvalidQwenShape);
}
Ok(Self { asset, entry, grid, block, shared, args })
Ok(Self { asset, entry, grid, block, shared, args, cluster: 0 })
}
/// The same launch as a cluster of `cluster` CTAs along x (the grid x extent must be a multiple of it).
pub(crate) fn clustered(mut self, cluster: u32) -> Self {
self.cluster = cluster;
self
}
pub(crate) fn command(&self) -> Result<Command> {
Command::new(self.entry, self.grid, self.block, self.shared, self.args.iter().map(A::abi).collect())
Command::new(self.entry, self.grid, self.block, self.shared, self.args.iter().map(A::abi).collect()).map(|c| c.with_cluster(self.cluster))
}
/// Short text used by unit tests and by diagnostics: `asset:entry <<<g,b,s>>>`.
pub(crate) fn label(&self) -> String {
@@ -43,7 +43,7 @@ pub const UNBOUND_PRODUCERS: &[&str] = &[];
pub(super) fn all_window_assets() -> Vec<&'static AssetSpec> {
let mut all = Vec::new();
all.extend(proj::mmvq_assets());
for family in [gr::assets(), qsa::assets(), moe::assets()] {
for family in [gr::assets(), qsa::assets(), qsa::cluster_assets(&qsa::OriginalVerifyQsaPolicy { cluster_topk: true, ..qsa::OriginalVerifyQsaPolicy::mode17() }), moe::assets()] {
for spec in family {
if !all.iter().any(|a: &&AssetSpec| std::ptr::eq(*a, spec)) {
all.push(spec);
@@ -198,7 +198,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
}
/// Every sealed asset the attached producers may launch from. Loaded once, BEFORE capture
/// (module loading is not capturable); a missing/unsealed asset fails closed by name.
fn required_assets(&self) -> Vec<&'static AssetSpec> {
fn required_assets(&self, policy: &WindowPolicy) -> Vec<&'static AssetSpec> {
let mut assets: Vec<&'static AssetSpec> = Vec::new();
if let Some(proj) = &self.proj {
assets.extend(proj.assets());
@@ -208,6 +208,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
}
if self.qsa.is_some() {
assets.extend(qsa::assets());
assets.extend(qsa::cluster_assets(&policy.qsa));
}
if self.moe.is_some() {
assets.extend(moe::assets());
@@ -218,14 +219,14 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
/// Pre-capture work: load the sealed modules, read the card's fused-GR decisions, raise the dynamic
/// shared-memory limits Original raises once. Any failure leaves the window unrecorded.
fn prepare(&mut self, policy: &WindowPolicy) -> Result<()> {
self.base.journal.ensure_window_assets(&self.required_assets())?;
self.base.journal.ensure_window_assets(&self.required_assets(policy))?;
let cfg = GrConfig::query(&self.base.journal, policy.gr_variant, policy.native_mmvf)?;
let mut attributes = Vec::new();
if self.gr.is_some() {
attributes.extend(gr::shared_attributes(&cfg));
}
if self.qsa.is_some() {
attributes.extend(qsa::shared_attributes(&policy.qsa));
attributes.extend(qsa::shared_attributes(&policy.qsa, &self.base.journal.geometry()));
}
if self.moe.is_some() {
attributes.extend(moe::shared_attributes(&Planner::moe_knobs_of(policy)));
@@ -622,6 +623,12 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
if resources.rows() != t {
return Err(Error::InvalidQwenShape);
}
// the cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref
let mut policy = policy;
if policy.qsa.cluster_topk {
let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok();
}
let ple = resources.verifier_journal().has_ple();
let roles = if policy.pcie_mode == 2 {
let mut roles = [[0usize; 3]; WINDOW_LAYERS];
@@ -122,15 +122,38 @@ pub(crate) static GATE: AssetSpec = AssetSpec {
unsealed: "Original verifier asset unsealed: original_verify_window_qsa_gate.ptx (QSA output gate, native_qsa.cu --use_fast_math)",
};
/// Every module a QSA producer may launch from; the lead preloads them before capture.
/// The decode top-k on a thread-block cluster (`qsa_cluster.cu`, Strata `block_topk_cluster_kernel`; row 2.5 of docs/upstream-port-plan.md): the
/// same ids as `qsa_topk_ref`, 8 CTAs of 1,024 threads per query instead of one CTA of 256. sm_90+ only, launched with `cuLaunchKernelEx`.
pub(crate) static CLUSTER: AssetSpec = AssetSpec {
name: "qsa_cluster.ptx",
ptx: crate::qsa_cluster::PTX,
sha: crate::qsa_cluster::PIN.ptx_sha256,
entries: CLUSTER_ENTRIES,
unsealed: "Original verifier asset unsealed: qsa_cluster.ptx (decode QSA top-k on a thread-block cluster)",
};
const CLUSTER_ENTRIES: &[&str] = &["leleka_qsa_topk_cluster"];
/// The queries a cluster launch takes (upstream `CL_MAXQ`); a window has at most 8.
const CLUSTER_MAX_QUERIES: usize = 16;
/// Every module a QSA producer may launch from; the lead preloads them before capture. The cluster module is not in this list: it is
/// loaded only when the policy asks for the cluster top-k (`cluster_assets`), since a card below sm_90 cannot load it.
pub(crate) fn assets() -> Vec<&'static AssetSpec> {
vec![&proj::BF16, &DECODE_POSTOPS, &SPLIT, &KV_APPEND, &SELECT, &RESOLVER, &ATTENTION, &GATE]
}
/// The modules of the cluster top-k, when the policy uses it.
pub(crate) fn cluster_assets(policy: &OriginalVerifyQsaPolicy) -> Vec<&'static AssetSpec> {
if policy.cluster_topk { vec![&CLUSTER] } else { Vec::new() }
}
/// No QSA kernel needs more than the 48 KiB static shared memory (chunk kernel: 15.5 KiB, multi-query
/// scores: 16.5 KiB), so no `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` is required.
pub(crate) fn shared_attributes(_policy: &OriginalVerifyQsaPolicy) -> Vec<(&'static AssetSpec, &'static str, usize)> {
Vec::new()
/// scores: 16.5 KiB), so no `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` is required; the cluster top-k holds the keys of
/// ceil(max_blocks / 8) blocks in dynamic shared memory next to ~19 KiB of static, past the 48 KiB limit, and opts in once here.
pub(crate) fn shared_attributes(policy: &OriginalVerifyQsaPolicy, g: &OriginalVerifyGeometry) -> Vec<(&'static AssetSpec, &'static str, usize)> {
if policy.cluster_topk {
vec![(&CLUSTER, CLUSTER_ENTRIES[0], crate::qsa_cluster::dynamic_smem(max_blocks(g)) as usize)]
} else {
Vec::new()
}
}
macro_rules! refuse {
@@ -163,6 +186,10 @@ pub struct OriginalVerifyQsaPolicy {
pub kv_streamed: bool,
/// `STRATA_SCORES_MULTI` (default on): the multi-query block score kernel for at most 8 queries.
pub scores_multi: bool,
/// The decode top-k as a cluster of 8 CTAs per query (`qsa_cluster.cu`, sm_90+; upstream `STRATA_QSA_CLUSTER`): the same ids as
/// `qsa_topk_ref`. Off in `mode17()` (the Original's launch list); the serve stack turns it on and `record_literal_window` turns it
/// off again on a card below sm_90.
pub cluster_topk: bool,
}
impl OriginalVerifyQsaPolicy {
pub const fn mode17() -> Self {
@@ -177,6 +204,7 @@ impl OriginalVerifyQsaPolicy {
trace: false,
kv_streamed: true,
scores_multi: true,
cluster_topk: false,
}
}
/// Refuse every variant that has no genuine sealed owner, with its reason.
@@ -656,14 +684,27 @@ impl<'a> QsaWindow<'a> {
// Original dispatches the register-resident top-k (`block_topk_reg_kernel`) while max_blocks <=
// 1024 * 33; Original documents it as selecting the identical ids (same radix rule, ties to the
// lowest index), and only `block_topk_kernel` is sealed, so that one is always launched.
let topk = Launch::new(
&SELECT,
"qsa_topk_ref",
[grid_u32(s.n)?, 1, 1],
[256, 1, 1],
0,
vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)],
)?;
let topk = if self.policy.cluster_topk && s.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
Launch::new(
&CLUSTER,
CLUSTER_ENTRIES[0],
[crate::qsa_cluster::CLUSTER_CTAS, grid_u32(s.n)?, 1],
[crate::qsa_cluster::BLOCK, 1, 1],
crate::qsa_cluster::dynamic_smem(mb),
vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)],
)?
.clustered(crate::qsa_cluster::CLUSTER_CTAS)
} else {
Launch::new(
&SELECT,
"qsa_topk_ref",
[grid_u32(s.n)?, 1, 1],
[256, 1, 1],
0,
vec![A::P(scores), A::P(steps), A::I64(mb as i64), A::I64(cap as i64), A::P(sel)],
)?
};
Ok(vec![scored, topk])
}
@@ -866,7 +907,35 @@ mod tests {
names.dedup();
assert_eq!(names.len(), a.len());
assert!(a.iter().any(|s| std::ptr::eq(*s, &proj::BF16)));
assert!(shared_attributes(&OriginalVerifyQsaPolicy::mode17()).is_empty());
let g = test_geometry();
assert!(shared_attributes(&OriginalVerifyQsaPolicy::mode17(), &g).is_empty());
assert!(cluster_assets(&OriginalVerifyQsaPolicy::mode17()).is_empty());
// the cluster top-k: its module is loaded only on request and opts into the dynamic shared memory of its keys
let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() };
assert!(cluster_assets(&p).iter().any(|s| std::ptr::eq(*s, &CLUSTER)));
assert!(!a.iter().any(|s| std::ptr::eq(*s, &CLUSTER)), "the cluster module is not in the always-loaded list");
let attributes = shared_attributes(&p, &g);
assert_eq!(attributes.len(), 1);
assert!(std::ptr::eq(attributes[0].0, &CLUSTER));
assert_eq!((attributes[0].1, attributes[0].2), ("leleka_qsa_topk_cluster", max_blocks(&g).div_ceil(8) * 4));
CLUSTER.assert_sealed_and_fail_closed();
}
#[test]
fn the_cluster_policy_replaces_only_the_topk_launch_and_keeps_its_arguments() {
let (m, g) = setup();
let reference = window(&m, g).block_scores_topk(0, &layer(), rows(0, 3)).unwrap();
let p = OriginalVerifyQsaPolicy { cluster_topk: true, ..OriginalVerifyQsaPolicy::mode17() };
let w = QsaWindow::new(&m, g, p, identity()).unwrap();
let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap();
assert_eq!(l.len(), 2);
assert_eq!(l[0], reference[0], "the scores launch is untouched");
assert_eq!(l[1].entry, "leleka_qsa_topk_cluster");
assert_eq!((l[1].grid, l[1].block, l[1].cluster), ([8, 3, 1], [1024, 1, 1], 8));
assert_eq!(l[1].shared as usize, max_blocks(&g).div_ceil(8) * 4);
assert_eq!(l[1].args, reference[1].args, "scores, steps, max_blocks, cap, ids as qsa_topk_ref");
assert_eq!(reference[1].cluster, 0);
assert_abi(&l[1]);
}
#[test]
+61
View File
@@ -84,6 +84,7 @@ mod enabled {
*mut *mut c_void,
*mut *mut c_void,
) -> c_int;
use crate::launch_ex::{FuncSetAttribute, LaunchAttribute, LaunchConfig, LaunchEx};
struct Library(*mut c_void);
impl Library {
fn open(name: &'static CStr) -> Result<Self> {
@@ -532,6 +533,62 @@ mod enabled {
)
})
}
/// `cuLaunchKernelEx` with a thread-block cluster (sm_90+): grid `[x, y, 1]`, `block` threads, cluster `[cx, 1, 1]`,
/// `smem` bytes of dynamic shared memory (opted in first with `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES)`).
/// Row 2.5 (`qsa_cluster.cu`). Capturable into a graph like any launch.
pub(crate) fn launch_cluster(
&self,
index: usize,
grid: [u32; 2],
block: u32,
cluster_x: u32,
smem: u32,
stream: usize,
args: &mut KernelArguments,
) -> Result<()> {
if grid[0] == 0 || grid[1] == 0 || block == 0 || block > 1024 || cluster_x == 0 || grid[0] % cluster_x != 0 || stream == 0 {
return Err(Error::InvalidQwenShape);
}
let function = *self.functions.get(index).ok_or(Error::UnsupportedQwenOperation)?;
let library = self._library.as_ref().ok_or(Error::LibraryUnavailable)?;
let launch_ex = symbol!(library, c"cuLaunchKernelEx", LaunchEx);
let set_attribute = symbol!(library, c"cuFuncSetAttribute", FuncSetAttribute);
args.pointers.clear();
args.pointers.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
args.addresses.clear();
args.addresses.try_reserve_exact(args.values.len()).map_err(|_| Error::HostAllocation)?;
args.addresses.resize(args.values.len(), 0);
for (index, arg) in args.values.iter_mut().enumerate() {
args.pointers.push(match arg {
BatchArg::Address(x) => {
args.addresses[index] = x.qwen_address();
(&mut args.addresses[index] as *mut u64).cast()
}
BatchArg::NullAddress => (&mut args.null as *mut u64).cast(),
BatchArg::I32(x) => (x as *mut i32).cast(),
BatchArg::I64(x) => (x as *mut i64).cast(),
BatchArg::U32(x) => (x as *mut u32).cast(),
BatchArg::F32(x) => (x as *mut f32).cast(),
});
}
check("cuFuncSetAttribute", unsafe {
set_attribute(function as *mut c_void, crate::launch_ex::FUNC_ATTRIBUTE_MAX_DYNAMIC_SHARED, smem as c_int)
})?;
let mut attribute = LaunchAttribute::cluster_x(cluster_x);
let config = LaunchConfig {
grid: [grid[0], grid[1], 1],
block: [block, 1, 1],
smem,
stream: stream as *mut c_void,
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.
check("cuLaunchKernelEx", unsafe {
launch_ex(&config, function as *mut c_void, args.pointers.as_mut_ptr(), std::ptr::null_mut())
})
}
pub(crate) fn close(mut self) -> Result<()> {
self.close_inner()
}
@@ -659,6 +716,10 @@ impl KernelModule {
let _ = (&args.values, &args.null, &args.pointers, &args.addresses);
Err(Error::UnsupportedPlatform)
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn launch_cluster(&self, _: usize, _: [u32; 2], _: u32, _: u32, _: u32, _: usize, _: &mut KernelArguments) -> Result<()> {
Err(Error::UnsupportedPlatform)
}
pub(crate) fn close(self) -> Result<()> {
Ok(())
}
+227
View File
@@ -0,0 +1,227 @@
// Offline compilation source; not a runtime/toolkit dependency.
// Decode QSA top-k on a thread-block cluster (Strata 41cf05a0 `qsa_select.cu` block_topk_cluster_kernel, upstream 586367cb /
// d05d26e9, docs/upstream-port-plan.md row 2.5). sm_90+ only (barrier.cluster, distributed shared memory), so it is a file of its own:
// qsa_late.cu has an sm_86 companion, this one has none (the loader refuses it below sm_90 and the caller keeps qsa_topk_ref).
// Launch: grid (8, nq), cluster (8, 1, 1), 1,024 threads, dynamic shared memory ceil(max_blocks / 8) * 4 bytes (cuLaunchKernelEx with the
// cluster-dimension attribute; cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE_BYTES) first). Arguments as qsa_topk_ref:
// (scores, steps, max_blocks, cap, ids); steps rows are (position, n_kv, n_bid, width). IDENTICAL ids to qsa_topk_ref.
// Recipe of the other precise assets (integer and comparison arithmetic only).
#include <stdint.h>
namespace {
__device__ __forceinline__ uint32_t order_key(float s) {
const float v = s + 0.0f;
if (!(v == v)) return 0u;
const uint32_t b = __float_as_uint(v);
return (b & 0x80000000u) ? ~b : (b | 0x80000000u);
}
constexpr int R = 4; // cells per indexer block
constexpr int CL_N = 8; // CTAs per query (the portable cluster size)
constexpr int CL_T = 1024; // threads per CTA
__device__ __forceinline__ void cl_arrive_relaxed() {
asm volatile("barrier.cluster.arrive.relaxed.aligned;\n" ::: "memory");
}
__device__ __forceinline__ void cl_arrive() { asm volatile("barrier.cluster.arrive.release.aligned;\n" ::: "memory"); }
__device__ __forceinline__ void cl_wait() { asm volatile("barrier.cluster.wait.acquire.aligned;\n" ::: "memory"); }
__device__ __forceinline__ unsigned cl_rank() {
unsigned r;
asm volatile("mov.u32 %0, %%cluster_ctarank;\n" : "=r"(r));
return r;
}
template <typename T> __device__ __forceinline__ T* cl_map(T* p, unsigned rank) { // p in CTA `rank`'s shared memory
uint64_t o;
asm volatile("mapa.u64 %0, %1, %2;\n" : "=l"(o) : "l"((uint64_t) p), "r"(rank));
return reinterpret_cast<T*>(o);
}
// exclusive block scan of a 64-bit value over CL_T threads; `total` = the CTA's sum
__device__ __forceinline__ unsigned long long cl_excl_scan64(unsigned long long v, unsigned long long* s_warp,
unsigned long long& total) {
const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5;
unsigned long long x = v;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const unsigned long long y = __shfl_up_sync(0xffffffffu, x, o);
if (lane >= o) x += y;
}
if (lane == 31) s_warp[warp] = x;
__syncthreads();
if (warp == 0) {
const unsigned long long w = s_warp[lane];
unsigned long long z = w;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const unsigned long long y = __shfl_up_sync(0xffffffffu, z, o);
if (lane >= o) z += y;
}
s_warp[lane] = z - w;
if (lane == 31) s_warp[32] = z;
}
__syncthreads();
total = s_warp[32];
return s_warp[warp] + x - v;
}
} // namespace
// ---- the decode top-k on a thread-block cluster (sm_90+; S19). One CTA per query (block_topk_reg_kernel, or
// block_topk_kernel above 33,792 blocks: a --max-context over ~135K) makes four radix passes and two scans over up to
// 65,538 blocks on ONE SM while the rest of the GPU idles - a decode window has 1-5 queries. Here a cluster of CL_N
// CTAs shares a query: CTA r holds the keys of blocks [r * per, (r + 1) * per) in shared memory, builds the digit
// histogram of its keys, and PUSHES it into slot r of every CTA's `hin` (distributed shared memory); after one cluster
// barrier each CTA sums the CL_N slots itself, so all of them take the same digit. The emit pass needs each CTA's
// cells above / at the threshold: pushed the same way, then each CTA offsets its own by the ranks before it.
// RTX 5070, per call at capacity = context (decode_cluster_parity --bench): 21.9 -> 15.6 us at 32K, 58 -> 18 at 128K,
// 200 -> 22 at 262K (the one-CTA kernels' digit search was serial, too: one thread over 256 bins per pass).
//
// IDENTICAL IDS, by construction rather than by luck: the threshold thr (the width-th largest key, cells counted with
// their weights) and `above` (cells with a larger key) are pure functions of the multiset of (key, weight) - integer
// histograms, summed in any order - and the digit rule is block_topk_kernel's, written as a scan (the largest digit d
// whose cells at or above it reach `need`; 0 when none). The cells emitted are then fixed: every cell of a block with
// key > thr, and the first eq_budget = width - above cells at thr in ascending order (a block at thr may be cut),
// written in ascending cell order. Position of a thread's first cell = (cells above thr before it) + min(cells at thr
// before it, eq_budget): the telescoped sum of the reference's per-thread clamp. NaN keys are 0 (order_key) as there.
//
// Barriers: barrier.cluster arrive / wait (each CTA's threads all take part; it also orders the CTA's own shared
// memory, so it doubles as __syncthreads). Phase 0 is a relaxed arrive at entry, waited before the first remote store
// (a CTA's shared memory exists once it runs). Pushes go out before the arrive that releases them, and nothing reads
// another CTA's memory after the last wait - so a CTA may exit without a closing barrier (a wait counts the threads
// that have not exited). `hin` alternates by pass parity: CTA x reads slot buffer p&1 in pass p before arriving at
// pass p+1's barrier, and nobody writes buffer p&1 again (pass p+2) before waiting on that barrier.
// grid (CL_N, nq), cluster (CL_N, 1, 1), CL_T threads, dynamic shared memory: ceil(max_blocks / CL_N) keys
extern "C" __global__ void __launch_bounds__(CL_T) leleka_qsa_topk_cluster(const float* __restrict__ scores,
const int32_t* __restrict__ steps, int64_t max_blocks,
int64_t cap, int32_t* __restrict__ ids) {
extern __shared__ uint32_t keys[]; // this CTA's blocks' keys
__shared__ __align__(16) int hin[2][CL_N][256]; // the cluster's histograms, slot = the pushing rank
__shared__ __align__(16) int hloc[2][256]; // this CTA's histogram
__shared__ unsigned long long cnt[CL_N]; // per rank: its cells above thr (low 32 bits) and at it (high)
__shared__ unsigned long long s_warp[33];
__shared__ uint32_t s_prefix;
__shared__ int s_above;
const unsigned rank = cl_rank();
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
cl_arrive_relaxed(); // phase 0: this CTA runs
const int64_t qi = blockIdx.y;
const int32_t* st = steps + qi * 4;
const int64_t n_kv = st[1], n_bid = st[2], width = st[3];
int32_t* out = ids + qi * cap;
if (n_kv <= width) { // the identity, split over the cluster; no remote access
for (int64_t j = (int64_t) rank * CL_T + t; j < n_kv; j += (int64_t) CL_N * CL_T) out[j] = (int32_t) j;
return;
}
// the tail block n_bid weighs its cells (0..3); with none it is not a candidate (the reference skips w == 0)
const int wtail = (int) (n_kv - n_bid * R);
const int64_t nbe = n_bid + (wtail > 0 ? 1 : 0);
const int64_t per = (nbe + CL_N - 1) / CL_N; // <= ceil(max_blocks / CL_N), the keys the host sized
const int64_t lo = (int64_t) rank * per < nbe ? (int64_t) rank * per : nbe;
const int64_t hi = lo + per < nbe ? lo + per : nbe;
const int n = (int) (hi - lo);
const int tail_i = (wtail > 0 && n_bid >= lo && n_bid < hi) ? (int) (n_bid - lo) : -1;
const float* sc = scores + qi * max_blocks + lo;
for (int i = t; i < n; i += CL_T) keys[i] = order_key(sc[i]);
for (int i = t; i < 2 * 256; i += CL_T) (&hloc[0][0])[i] = 0;
__syncthreads();
uint32_t prefix = 0;
int above = 0; // cells strictly above the digits fixed so far
for (int pass = 0; pass < 4; ++pass) {
const int shift = 24 - 8 * pass;
const uint32_t hmask = pass == 0 ? 0u : (0xffffffffu << (shift + 8));
int* hl = hloc[pass & 1];
// warp-aggregated: the scores share their top bits, so plain atomics would queue on a few bins
for (int i0 = 0; i0 < n; i0 += CL_T) {
const int i = i0 + t;
int bin = -1;
if (i < n) {
const uint32_t k = keys[i];
if ((k & hmask) == prefix) bin = (int) ((k >> shift) & 255);
}
const unsigned same = __match_any_sync(0xffffffffu, bin);
if (bin >= 0 && lane == __ffs(same) - 1) atomicAdd(&hl[bin], __popc(same) * R);
if (bin >= 0 && i == tail_i) atomicAdd(&hl[bin], wtail - R);
}
__syncthreads();
if (pass == 0) cl_wait(); // phase 0 done: every CTA's shared memory is there
for (int i = t; i < CL_N * 64; i += CL_T) { // the histogram into slot `rank` of every CTA, as int4
const int dst = i >> 6, c = i & 63;
*cl_map(reinterpret_cast<int4*>(&hin[pass & 1][rank][0]) + c, (unsigned) dst) =
reinterpret_cast<const int4*>(hl)[c];
}
for (int i = t; i < 256; i += CL_T) hloc[(pass + 1) & 1][i] = 0;
cl_arrive();
cl_wait();
if (warp == 0) {
// lane L owns digits 255 - 8L down to 248 - 8L; the digit holding the need-th cell from the top
const int need = (int) width - above;
int tot[8], part = 0;
#pragma unroll
for (int k = 0; k < 8; ++k) {
const int d = 255 - 8 * lane - k;
int v = 0;
#pragma unroll
for (int r = 0; r < CL_N; ++r) v += hin[pass & 1][r][d];
tot[k] = v;
part += v;
}
int incl = part;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const int y = __shfl_up_sync(0xffffffffu, incl, o);
if (lane >= o) incl += y;
}
const int excl = incl - part;
const unsigned hit = __ballot_sync(0xffffffffu, excl < need && incl >= need);
// no hit cannot happen (the cells total n_kv > width); the reference would then take digit 0
const int who = hit ? __ffs(hit) - 1 : 31;
if (lane == who) {
int acc = excl, k = 0;
for (; k < 7; ++k) {
if (acc + tot[k] >= need) break;
acc += tot[k];
}
s_prefix = prefix | ((uint32_t) (255 - 8 * lane - k) << shift);
s_above = above + acc;
}
}
__syncthreads();
prefix = s_prefix;
above = s_above;
}
const uint32_t thr = prefix;
const int64_t eq_budget = width - above; // cells at thr that fit, lowest index first
// each thread a contiguous run of the CTA's keys; an odd run length keeps the shared reads conflict-free
int seg = (n + CL_T - 1) / CL_T;
if ((seg & 1) == 0 && seg > 0) ++seg;
const int s0 = t * seg < n ? t * seg : n, s1 = s0 + seg < n ? s0 + seg : n;
uint32_t gt = 0, eq = 0;
for (int i = s0; i < s1; ++i) {
const uint32_t k = keys[i], w = i == tail_i ? (uint32_t) wtail : (uint32_t) R;
if (k > thr) gt += w;
else if (k == thr) eq += w;
}
unsigned long long cta;
const unsigned long long before =
cl_excl_scan64((unsigned long long) gt | ((unsigned long long) eq << 32), s_warp, cta);
if (t < CL_N) *cl_map(&cnt[rank], (unsigned) t) = cta;
cl_arrive();
cl_wait();
int64_t gt_off = 0, eq_off = 0;
for (unsigned r = 0; r < rank; ++r) {
gt_off += (int64_t) (cnt[r] & 0xffffffffu);
eq_off += (int64_t) (cnt[r] >> 32);
}
const int64_t eq_before = eq_off + (int64_t) (before >> 32);
int64_t wpos = gt_off + (int64_t) (before & 0xffffffffu) + (eq_before < eq_budget ? eq_before : eq_budget);
int64_t eq_left = eq_budget - eq_before;
if (eq_left < 0) eq_left = 0;
for (int i = s0; i < s1; ++i) {
const uint32_t k = keys[i];
const int w = i == tail_i ? wtail : R;
const int64_t b = lo + i;
if (k > thr) {
for (int c = 0; c < w; ++c) out[wpos++] = (int32_t) (b * R + c);
} else if (k == thr) {
for (int c = 0; c < w && eq_left > 0; ++c, --eq_left) out[wpos++] = (int32_t) (b * R + c);
}
}
}
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
//! Fixed asset `qsa_cluster.cu`: the decode QSA top-k on a thread-block cluster (`leleka_qsa_topk_cluster`, Strata `block_topk_cluster_kernel`,
//! docs/upstream-port-plan.md row 2.5). sm_90+ only. Pure data: PTX bytes, entry name, pin.
use crate::kar_decode_levels::{KarDecodeError, PtxPin, admit_ptx};
use std::ffi::CStr;
pub(crate) const PTX: &[u8] = concat!(include_str!("qsa_cluster.ptx"), "\0").as_bytes();
pub(crate) const ENTRIES: &[&CStr] = &[c"leleka_qsa_topk_cluster"];
pub(crate) const TOPK_CLUSTER: usize = 0;
/// CTAs per query: the cluster size and the grid's x extent.
pub(crate) const CLUSTER_CTAS: u32 = 8;
/// Threads per CTA.
pub(crate) const BLOCK: u32 = 1024;
/// Dynamic shared memory of one CTA: the keys of ceil(max_blocks / 8) blocks.
pub(crate) fn dynamic_smem(max_blocks: usize) -> u32 {
(max_blocks.div_ceil(CLUSTER_CTAS as usize) * 4) as u32
}
/// Frozen by `scripts/gpu-bringup/reseal_own.py` after `compile_assets.py` (extra-seal-plan.json, group qsa-cluster).
pub(crate) const PIN: PtxPin = PtxPin {
source_sha256: [
147, 254, 188, 163, 187, 132, 34, 2, 87, 206, 153, 133, 97, 24, 148, 223, 219, 213, 206,
202, 11, 223, 165, 148, 222, 70, 39, 17, 38, 243, 17, 103,
],
ptx_sha256: [
60, 132, 16, 98, 99, 168, 233, 124, 37, 148, 140, 163, 88, 27, 187, 220, 19, 80, 17, 95,
215, 11, 103, 205, 137, 16, 98, 13, 232, 205, 25, 25,
],
};
pub(crate) fn admit() -> Result<(), KarDecodeError> {
admit_ptx(PTX, &PIN)
}
+342
View File
@@ -137,3 +137,345 @@ extern "C" __global__ void __launch_bounds__(256) leleka_qsa_score_scan_fast(
if (b <= steps[row * 4 + 2] && (__float_as_uint(scores[row * max_blocks + b]) & 0x7f800000u) == 0x7f800000u)
atomicOr(status + slot, 1u);
}
// =====================================================================================================================
// Row 2.5 (docs/upstream-port-plan.md): the position-dependent top-k kernels of Strata 41cf05a0 `src/kernels/cuda/qsa_select.cu`
// (upstream 586367cb, d05d26e9, 6ef23b89), copied with the step-array offsets spelled out (position, n_kv, n_bid, width = 0..3)
// and the two kernels turned into device bodies behind extern "C" entries. Every one of them selects the IDENTICAL ids of
// qsa_topk_ref (the weighted radix threshold, ties to the lowest index, cells in ascending order); qsa_late_gpu compares them with
// the Original's kernel and with leleka_qsa_topk_fast.
// leleka_qsa_topk_wide 1,024 threads, per-warp histograms, each key read from memory on every pass (block_topk_wide_kernel)
// leleka_qsa_topk_sample one read of the scores: a sampled bound, the candidates in shared memory (block_topk_sample_kernel);
// a query it cannot take is flagged in g_tk_fail and run by leleka_qsa_topk_wide_failed
// leleka_qsa_topk_wide_failed block_topk_wide_kernel<true>: only the flagged queries
// =====================================================================================================================
namespace {
constexpr int TK_T = 1024;
constexpr int TS_MAXQ = 4096;
} // namespace
__device__ int g_tk_fail[TS_MAXQ]; // leleka_qsa_topk_sample: 1 = the query is leleka_qsa_topk_wide_failed's
namespace {
// ---- a query with more blocks than the register kernel holds (contexts past 4 * 1024 * TK_PER cells): the register
// kernel's threads, per-warp histograms and warp scans, with each key read from memory again on every pass. A
// histogram has no order, so on the four radix passes thread t reads blocks t, t + 1024, ...: a warp reads 32
// neighbours at a time. The cells are emitted ascending in the order (warp, row, lane): warp w holds the `per` rows
// of 32 consecutive blocks from block w * 32 * per. block_topk_kernel's selection rule (radix threshold, ties to the
// lowest index): identical ids.
// campaign3: also compiled on HIP (gfx11: plain shared/atomic code, no sm_90 features; the dispatch still needs
// reach > fit, i.e. the deep contexts where the ref radix was the only option on AMD).
template <bool ONLY_FAILED = false>
__device__ __forceinline__ void block_topk_wide_body(const float* __restrict__ scores,
const int32_t* __restrict__ steps, int64_t max_blocks,
int64_t cap, int32_t* __restrict__ ids) {
if (ONLY_FAILED && !g_tk_fail[blockIdx.x]) return;
__shared__ int hist[TK_T / 32][256];
__shared__ int s_gt[TK_T / 32], s_eq[TK_T / 32];
__shared__ int s_digit, s_above;
const int64_t qi = blockIdx.x;
const int32_t* st = steps + qi * 4;
const int64_t n_kv = st[1], n_bid = st[2], width = st[3];
int32_t* out = ids + qi * cap;
const int t = threadIdx.x, lane = t & 31, warp = t >> 5;
if (n_kv <= width) {
for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
return;
}
const float* sc = scores + qi * max_blocks;
const int64_t nb = n_bid + 1;
const int64_t per = (nb + TK_T - 1) / TK_T; // rows of 32 blocks per warp
auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
uint32_t prefix = 0;
int above = 0;
for (int shift = 24; shift >= 0; shift -= 8) {
for (int i = lane; i < 256; i += 32) hist[warp][i] = 0;
__syncwarp();
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
for (int64_t b = t; b < nb; b += TK_T) {
const int w = weight(b);
if (w == 0) continue;
const uint32_t k = order_key(sc[b]);
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[warp][(k >> shift) & 255], w);
}
__syncthreads();
if (t < 256) { // fold the warps' histograms into warp 0's
int sum = 0;
for (int w2 = 0; w2 < TK_T / 32; ++w2) sum += hist[w2][t];
hist[0][t] = sum;
}
__syncthreads();
if (t == 0) {
int cum = above, d = 255;
for (; d > 0; --d) {
if (cum + hist[0][d] >= width) break;
cum += hist[0][d];
}
s_digit = d;
s_above = cum;
}
__syncthreads();
prefix |= (uint32_t) s_digit << shift;
above = s_above;
__syncthreads();
}
const uint32_t thr = prefix;
const int eq_budget = (int) (width - above); // cells equal to thr that fit, lowest index first
const int64_t w0 = (int64_t) warp * 32 * per;
int gt = 0, eq = 0;
for (int64_t b = w0 + lane; b < nb && b < w0 + 32 * per; b += 32) {
const int w = weight(b);
if (w == 0) continue;
const uint32_t k = order_key(sc[b]);
if (k > thr) gt += w;
else if (k == thr) eq += w;
}
#pragma unroll
for (int o = 16; o > 0; o >>= 1) {
gt += __shfl_xor_sync(0xffffffffu, gt, o);
eq += __shfl_xor_sync(0xffffffffu, eq, o);
}
if (lane == 0) { s_gt[warp] = gt; s_eq[warp] = eq; }
__syncthreads();
if (t == 0) { // per warp: the selected cells and the tied cells before it
int eb = 0, sb = 0;
for (int w2 = 0; w2 < TK_T / 32; ++w2) {
const int g2 = s_gt[w2], e2 = s_eq[w2];
const int take = eq_budget - eb < 0 ? 0 : (eq_budget - eb > e2 ? e2 : eq_budget - eb);
s_gt[w2] = sb;
s_eq[w2] = eb;
sb += g2 + take;
eb += e2;
}
}
__syncthreads();
int run_sel = s_gt[warp], run_eq = s_eq[warp];
for (int64_t r0 = w0; r0 < nb && r0 < w0 + 32 * per; r0 += 32) {
const int64_t b = r0 + lane;
const int w = b < nb ? weight(b) : 0;
const uint32_t k = w ? order_key(sc[b]) : 0u;
const int my_gt = (w && k > thr) ? w : 0, my_eq = (w && k == thr) ? w : 0;
if (__ballot_sync(0xffffffffu, (my_gt | my_eq) != 0) == 0u) continue; // a row without a selected block
int pe = my_eq; // tied cells up to and with this lane
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const int y = __shfl_up_sync(0xffffffffu, pe, o);
if (lane >= o) pe += y;
}
const int left = eq_budget - (run_eq + pe - my_eq);
const int take = left < 0 ? 0 : (left > my_eq ? my_eq : left);
const int my_sel = my_gt + take;
int ps = my_sel;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) {
const int y = __shfl_up_sync(0xffffffffu, ps, o);
if (lane >= o) ps += y;
}
int32_t* dst = out + run_sel + ps - my_sel;
for (int c = 0; c < my_sel; ++c) dst[c] = (int32_t) (b * R + c);
run_eq += __shfl_sync(0xffffffffu, pe, 31);
run_sel += __shfl_sync(0xffffffffu, ps, 31);
}
}
// ---- the prompt path's top-k with one full read of the scores (Turing). block_topk_wide_kernel reads a query's scores
// six times (four radix passes, a count, the emit); past ~90K cells that is DRAM traffic (256 queries at 400K: 0.6 GB a
// layer, ~1.5 ms on an RTX 2080 Ti). Here a CTA first reads every 32nd block and takes the KS-th largest of those keys
// as a bound LB, then reads all blocks once and keeps the ones with key >= LB in shared memory. When those hold at
// least `width` cells, the width-th largest cell key (block_topk_kernel's threshold) is >= LB, so every block at or
// above the threshold is a candidate: the threshold, `above` and the tie budget computed over the candidates with
// block_topk_kernel's rule are the reference's, and the candidates sorted by block emit the reference's cells in its
// order. Otherwise (too few cells above LB, or more than SM_CAP candidates) the query is flagged and
// leleka_qsa_topk_wide_failed runs it. STRATA_TOPK_SAMPLE=0 keeps the wide kernel alone.
constexpr int TS_STRIDE = 32, TS_CAP = 4096;
__device__ __forceinline__ int ts_block_scan(int v, int* s_w) { // exclusive scan over the CTA's TK_T threads
const int t = threadIdx.x, lane = t & 31, w = t >> 5;
int x = v;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) { const int y = __shfl_up_sync(0xffffffffu, x, o); if (lane >= o) x += y; }
if (lane == 31) s_w[w] = x;
__syncthreads();
if (w == 0) {
int y = lane < TK_T / 32 ? s_w[lane] : 0;
#pragma unroll
for (int o = 1; o < 32; o <<= 1) { const int z = __shfl_up_sync(0xffffffffu, y, o); if (lane >= o) y += z; }
if (lane < TK_T / 32) s_w[lane] = y; // inclusive warp totals
}
__syncthreads();
const int base = w > 0 ? s_w[w - 1] : 0;
const int r = base + x - v;
__syncthreads();
return r;
}
__device__ __forceinline__ void block_topk_sample_body(const float* __restrict__ scores,
const int32_t* __restrict__ steps, int64_t max_blocks,
int64_t cap, int32_t* __restrict__ ids) {
__shared__ uint32_t s_key[TS_CAP];
__shared__ int32_t s_idx[TS_CAP];
__shared__ int hist[256];
__shared__ int s_w[TK_T / 32];
__shared__ int s_cnt, s_cells, s_digit, s_above;
const int64_t qi = blockIdx.x;
const int32_t* st = steps + qi * 4;
const int64_t n_kv = st[1], n_bid = st[2], width = st[3];
int32_t* out = ids + qi * cap;
const int t = threadIdx.x;
if (n_kv <= width) {
if (t == 0) g_tk_fail[qi] = 0;
for (int64_t j = t; j < n_kv; j += TK_T) out[j] = (int32_t) j;
return;
}
const float* sc = scores + qi * max_blocks;
const int64_t nb = n_bid + 1;
auto weight = [&](int64_t b) -> int { return b < n_bid ? R : (int) (n_kv - n_bid * R); };
const int ns = (int) ((nb + TS_STRIDE - 1) / TS_STRIDE);
if (ns > TS_CAP) { if (t == 0) g_tk_fail[qi] = 1; return; }
// 1. the bound: the KS-th largest of every 32nd block's key (a block without cells counts as the smallest key)
for (int i = t; i < ns; i += TK_T) {
const int64_t b = (int64_t) i * TS_STRIDE;
s_key[i] = weight(b) ? order_key(sc[b]) : 0u;
}
const int ks_want = (int) (2 * ((width + R * TS_STRIDE - 1) / (R * TS_STRIDE)) + 16);
int need = ks_want < ns ? ks_want : ns;
uint32_t prefix = 0;
for (int shift = 24; shift >= 0; shift -= 8) {
for (int i = t; i < 256; i += TK_T) hist[i] = 0;
__syncthreads();
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
for (int i = t; i < ns; i += TK_T) {
const uint32_t k = s_key[i];
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], 1);
}
__syncthreads();
if (t == 0) {
int cum = 0, d = 255;
for (; d > 0; --d) {
if (cum + hist[d] >= need) break;
cum += hist[d];
}
s_digit = d;
s_above = need - cum;
}
__syncthreads();
prefix |= (uint32_t) s_digit << shift;
need = s_above;
__syncthreads();
}
const uint32_t lb = prefix;
// 2. one read of every block: the candidates (key >= LB) and their cells
if (t == 0) { s_cnt = 0; s_cells = 0; }
__syncthreads();
for (int64_t b = t; b < nb; b += TK_T) {
const int w = weight(b);
if (w == 0) continue;
const uint32_t k = order_key(sc[b]);
if (k >= lb) {
const int pos = atomicAdd(&s_cnt, 1);
if (pos < TS_CAP) { s_key[pos] = k; s_idx[pos] = (int32_t) b; }
atomicAdd(&s_cells, w);
}
}
__syncthreads();
const int n = s_cnt;
if (n > TS_CAP || s_cells < width) { // the bound was too low or too high: the wide kernel takes this query
if (t == 0) g_tk_fail[qi] = 1;
return;
}
if (t == 0) g_tk_fail[qi] = 0;
// 3. block_topk_kernel's threshold over the candidates (weighted)
prefix = 0;
int above = 0;
for (int shift = 24; shift >= 0; shift -= 8) {
for (int i = t; i < 256; i += TK_T) hist[i] = 0;
__syncthreads();
const uint32_t hi_mask = shift == 24 ? 0u : (0xffffffffu << (shift + 8));
for (int i = t; i < n; i += TK_T) {
const uint32_t k = s_key[i];
if ((k & hi_mask) == (prefix & hi_mask)) atomicAdd(&hist[(k >> shift) & 255], weight(s_idx[i]));
}
__syncthreads();
if (t == 0) {
int cum = above, d = 255;
for (; d > 0; --d) {
if (cum + hist[d] >= width) break;
cum += hist[d];
}
s_digit = d;
s_above = cum;
}
__syncthreads();
prefix |= (uint32_t) s_digit << shift;
above = s_above;
__syncthreads();
}
const uint32_t thr = prefix;
const int eq_budget = (int) (width - above);
// 4. the candidates in block order (bitonic sort; padding sorts last)
int n2 = 1;
while (n2 < n) n2 <<= 1;
for (int i = n + t; i < n2; i += TK_T) { s_idx[i] = 0x7fffffff; s_key[i] = 0u; }
__syncthreads();
for (int kk = 2; kk <= n2; kk <<= 1) {
for (int j = kk >> 1; j > 0; j >>= 1) {
for (int i = t; i < n2; i += TK_T) {
const int p = i ^ j;
if (p > i) {
const bool up = (i & kk) == 0;
const int a = s_idx[i], b = s_idx[p];
if ((a > b) == up) {
s_idx[i] = b; s_idx[p] = a;
const uint32_t ka = s_key[i]; s_key[i] = s_key[p]; s_key[p] = ka;
}
}
}
__syncthreads();
}
}
// 5. the emit: cells above thr, and the first eq_budget cells at thr, in block order
constexpr int PER = TS_CAP / TK_T; // candidates per thread, consecutive
int eqc[PER], gtc[PER];
int my_eq = 0;
#pragma unroll
for (int r = 0; r < PER; ++r) {
const int i = t * PER + r;
const int w = i < n ? weight(s_idx[i]) : 0;
const uint32_t k = s_key[i < n ? i : 0];
gtc[r] = (i < n && k > thr) ? w : 0;
eqc[r] = (i < n && k == thr) ? w : 0;
my_eq += eqc[r];
}
int eq_before = ts_block_scan(my_eq, s_w);
int sel[PER], my_sel = 0;
#pragma unroll
for (int r = 0; r < PER; ++r) {
const int left = eq_budget - eq_before;
const int take = left < 0 ? 0 : (left > eqc[r] ? eqc[r] : left);
sel[r] = gtc[r] + take;
my_sel += sel[r];
eq_before += eqc[r];
}
int pos = ts_block_scan(my_sel, s_w);
#pragma unroll
for (int r = 0; r < PER; ++r) {
const int i = t * PER + r;
if (sel[r] > 0) {
const int64_t b = s_idx[i];
for (int c = 0; c < sel[r]; ++c) out[pos + c] = (int32_t) (b * R + c);
}
pos += sel[r];
}
}
} // namespace
extern "C" __global__ void __launch_bounds__(TK_T) leleka_qsa_topk_wide(
const float* __restrict__ scores, const int32_t* __restrict__ steps, int64_t max_blocks, int64_t cap, int32_t* __restrict__ ids) {
block_topk_wide_body<false>(scores, steps, max_blocks, cap, ids);
}
extern "C" __global__ void __launch_bounds__(TK_T) leleka_qsa_topk_wide_failed(
const float* __restrict__ scores, const int32_t* __restrict__ steps, int64_t max_blocks, int64_t cap, int32_t* __restrict__ ids) {
block_topk_wide_body<true>(scores, steps, max_blocks, cap, ids);
}
extern "C" __global__ void __launch_bounds__(TK_T) leleka_qsa_topk_sample(
const float* __restrict__ scores, const int32_t* __restrict__ steps, int64_t max_blocks, int64_t cap, int32_t* __restrict__ ids) {
block_topk_sample_body(scores, steps, max_blocks, cap, ids);
}
File diff suppressed because it is too large Load Diff
+31 -5
View File
@@ -4,18 +4,29 @@ use crate::kar_decode_levels::{KarDecodeError, PtxPin, admit_ptx};
use std::ffi::CStr;
pub(crate) static PTX: &[u8] = concat!(include_str!("qsa_late.ptx"), "\0").as_bytes();
pub(crate) const ENTRIES: &[&CStr] = &[c"leleka_qsa_topk_fast", c"leleka_qsa_score_scan_fast"];
pub(crate) const ENTRIES: &[&CStr] = &[
c"leleka_qsa_topk_fast",
c"leleka_qsa_score_scan_fast",
c"leleka_qsa_topk_wide",
c"leleka_qsa_topk_wide_failed",
c"leleka_qsa_topk_sample",
];
pub(crate) const TOPK_FAST: usize = 0;
pub(crate) const SCORE_SCAN_FAST: usize = 1;
pub(crate) const TOPK_WIDE: usize = 2;
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) const TOPK_WIDE_FAILED: usize = 3;
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) const TOPK_SAMPLE: usize = 4;
/// Frozen by `scripts/gpu-bringup/seal_pins.py` after `compile_assets.py` (extra-seal-plan.json, group qsa-late).
pub(crate) const PIN: PtxPin = PtxPin {
source_sha256: [
208, 25, 80, 72, 16, 46, 129, 25, 154, 130, 37, 154, 17, 236, 229, 231, 131, 10, 223, 78,
195, 186, 51, 69, 96, 27, 62, 126, 194, 56, 225, 28,
64, 47, 113, 181, 108, 16, 68, 196, 128, 106, 244, 32, 149, 48, 241, 195, 61, 244, 215, 40,
122, 196, 211, 179, 159, 198, 67, 87, 158, 195, 212, 27,
],
ptx_sha256: [
97, 104, 224, 82, 187, 35, 192, 84, 79, 242, 158, 148, 16, 6, 221, 135, 58, 11, 241, 192,
174, 241, 152, 40, 9, 31, 86, 99, 67, 10, 235, 145,
235, 200, 188, 10, 172, 27, 212, 167, 69, 64, 237, 36, 108, 0, 150, 13, 16, 21, 150, 48, 32,
17, 51, 230, 210, 31, 48, 110, 254, 177, 186, 47,
],
};
pub(crate) fn admit() -> Result<(), KarDecodeError> {
@@ -36,6 +47,21 @@ pub(crate) fn enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_QSA_LATE").map_or(true, |v| v != "0"))
}
/// Row 2.5: which top-k kernel a prompt tile of `tile_reach` indexer blocks takes. `LELEKA_QSA_TOPK=fast` keeps `leleka_qsa_topk_fast` (256
/// threads); `wide` takes the 1,024-thread kernel from `TOPK_WIDE_MIN_BLOCKS` on (Strata `block_topk_wide_kernel`: -45 % per launch at 180k
/// tokens and -49 % at 245k on the 5090, equal below ~32k, docs/upstream-port-plan.md); unset: `TOPK_DEFAULT_WIDE`. Same ids either way.
pub(crate) const TOPK_WIDE_MIN_BLOCKS: usize = 10_000;
/// Default of `LELEKA_QSA_TOPK` (flipped after its R gate).
pub(crate) const TOPK_DEFAULT_WIDE: bool = false;
pub(crate) fn topk_entry(tile_reach: usize) -> (usize, u32) {
static WIDE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let wide = *WIDE.get_or_init(|| match std::env::var("LELEKA_QSA_TOPK").ok().as_deref() {
Some("wide") => true,
Some(_) => false,
None => TOPK_DEFAULT_WIDE,
});
if wide && tile_reach >= TOPK_WIDE_MIN_BLOCKS { (TOPK_WIDE, 1024) } else { (TOPK_FAST, 256) }
}
/// The switch is on, the asset is the sealed one and the device can load it: the sealed image is sm_120; a build with `sm86` on a pre-Blackwell
/// card loads the retargeted companion (docs/sm86-assets.md) only with `LELEKA_QSA_LATE_SM86=1` (its identity gate has not run on sm_86 hardware:
/// the cuBLAS-dependent probe `qsa_late::gpu_tests` needs the pinned cuBLAS next to the card) and otherwise keeps the original launches.
+123
View File
@@ -141,3 +141,126 @@ fn selection_kernels_equal_the_originals_at_long_positions() {
}
}
}
/// Row 2.5: every top-k variant (`leleka_qsa_topk_fast`, `_wide`, `_sample` + `_wide_failed`, and the decode cluster kernel) writes the
/// same ids as the Original's `qsa_topk_ref` (the whole output, tail included), on prompt-shaped tiles (256 rows) and decode-shaped
/// calls (1..5 rows) at positions up to 262,000, with continuous, heavy-tailed, tied and all-equal scores; and the per-launch time of
/// each variant (warm, 20 launches drained once) is printed as `QSA-TOPK-BENCH`.
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn topk_variants_equal_the_original_and_are_timed() {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(6usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let max_blocks = crate::serving_context::geometry().max_blocks();
let guard = context.enter().expect("enter");
let select = KernelModule::load(include_bytes!("qsa_prompt_select.ptx"), &[c"qsa_topk_ref"]).expect("select module");
let late = KernelModule::load(PTX, ENTRIES).expect("late module");
let cluster = KernelModule::load(crate::qsa_cluster::PTX, crate::qsa_cluster::ENTRIES).expect("cluster module");
guard.finish().expect("finish");
let mut rng = Rng(0x9e3779b97f4a7c15);
// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum like)
let cases: [(usize, usize, u8, &str); 19] = [
(2_040, 256, 3, "prompt"),
(8_000, 256, 3, "prompt"),
(24_000, 256, 3, "prompt"),
(48_000, 256, 3, "prompt"),
(70_000, 256, 3, "prompt"),
(100_003, 256, 0, "prompt"),
(100_003, 256, 3, "prompt"),
(180_000, 256, 0, "prompt"),
(180_000, 256, 3, "prompt"),
(180_000, 256, 1, "prompt"),
(245_000, 256, 3, "prompt"),
(245_000, 256, 2, "prompt"),
(131_072, 1, 3, "decode"),
(131_072, 4, 3, "decode"),
(245_000, 1, 3, "decode"),
(245_000, 4, 3, "decode"),
(245_000, 5, 0, "decode"),
(245_000, 4, 1, "decode"),
(261_500, 4, 2, "decode"),
];
let reps = 20;
for (case, (p0, rows, style, label)) in cases.into_iter().enumerate() {
let mut steps = Vec::new();
for r in 0..rows {
let pos = p0 + r;
for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] {
steps.extend_from_slice(&(x as i32).to_le_bytes());
}
}
let mut scores = vec![0f32; rows * max_blocks];
for r in 0..rows {
let n_bid = (p0 + r + 1) / 4;
for b in 0..=n_bid.min(max_blocks - 1) {
let u = (rng.next() % 1_000_003) as f32 / 1_000_003.0;
scores[r * max_blocks + b] = match style {
0 => u * 1000.0,
1 => ((rng.next() % 16) as f32) * 0.5 * ((rng.next() % 3 != 0) as u32 as f32),
2 => 0.0,
_ => (-(u.max(1e-6)).ln()) * 40.0 * ((rng.next() % 4 != 0) as u32 as f32) + ((b % 977) as f32) * 0.01,
};
}
if style != 2 && (p0 + r + 1) % 4 != 0 {
scores[r * max_blocks + n_bid] += 1e9;
}
}
let mut raw = Vec::with_capacity(scores.len() * 4);
scores.iter().for_each(|v| raw.extend_from_slice(&v.to_le_bytes()));
let scores_d = upload(&context, &raw);
let steps_d = upload(&context, &steps);
let out_len = rows * CAP * 4;
let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle");
let args_for = |ids: &DeviceBuffer<'_>| {
KernelArguments::new(vec![A::Address(h(&scores_d)), A::Address(h(&steps_d)), A::I64(max_blocks as i64), A::I64(CAP as i64), A::Address(h(ids))])
};
let n = rows as u32;
// one runner per variant: (name, closure launching it once)
type Run<'a> = Box<dyn Fn(&mut KernelArguments) + 'a>;
let smem = crate::qsa_cluster::dynamic_smem(max_blocks);
let variants: Vec<(&str, Run<'_>)> = vec![
("ref", Box::new(|a| select.launch(0, n, 256, stream, a).expect("ref"))),
("fast", Box::new(|a| late.launch(TOPK_FAST, n, 256, stream, a).expect("fast"))),
("wide", Box::new(|a| late.launch(TOPK_WIDE, n, 1024, stream, a).expect("wide"))),
(
"sample+failed",
Box::new(|a| {
late.launch(TOPK_SAMPLE, n, 1024, stream, a).expect("sample");
late.launch(TOPK_WIDE_FAILED, n, 1024, stream, a).expect("failed");
}),
),
("cluster", Box::new(|a| cluster.launch_cluster(crate::qsa_cluster::TOPK_CLUSTER, [8, n], 1024, 8, smem, stream, a).expect("cluster"))),
];
let mut reference: Option<Vec<u8>> = None;
let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:");
for (name, run) in &variants {
if *name == "cluster" && rows > 16 {
continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries)
}
let ids = upload(&context, &vec![0xffu8; out_len]);
let mut a = args_for(&ids);
let guard = context.enter().expect("enter");
// the sample kernel flags its failures in a module global that persists: clear by running sample first inside run
run(&mut a);
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..reps {
run(&mut a);
}
context.driver.api.synchronize().expect("sync");
let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64;
guard.finish().expect("finish");
let got = download(&ids, 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"),
}
line.push_str(&format!(" {name} {us:.1} us;"));
}
eprintln!("{line} ids equal");
}
}
@@ -10,7 +10,7 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx>{
for row in 0..n{let pos=p+row;for x in [pos,pos+1,(pos+1)/4,(pos+1).min(CAP)]{steps.extend((x as i32).to_le_bytes());}}
let zero=vec![0u8;64];let mut flags=vec![0u8;64];let status=self.handle(10,64)?;let mut commands:Vec<(Launch,Arguments)>=Vec::new();commands.try_reserve_exact(32+4*n.div_ceil(256)).map_err(|_|Error::HostAllocation)?;
// (position in `commands` it runs before, grid, qsa_late entry, arguments)
let mut late:Vec<(usize,u32,usize,crate::ple_batch_ffi::KernelArguments)>=Vec::new();
let mut late:Vec<(usize,u32,usize,u32,crate::ple_batch_ffi::KernelArguments)>=Vec::new();
let fast_select=!decode&&crate::qsa_late::usable(self.context);
let pushed=std::cell::Cell::new(0usize);
let mut push=|shape,args|->Result<()>{commands.push((shape,Arguments::for_launch(shape,args)?));pushed.set(pushed.get()+1);Ok(())};
@@ -79,10 +79,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx>{
}
if fast_select&&!decode{
// qsa_late.cu: the same flag over the blocks the tile can hold, and the same ids from coalesced reads
late.push((pushed.get(),(count*tile_reach).div_ceil(256)as u32,crate::qsa_late::SCORE_SCAN_FAST,crate::ple_batch_ffi::KernelArguments::new(vec![
late.push((pushed.get(),(count*tile_reach).div_ceil(256)as u32,crate::qsa_late::SCORE_SCAN_FAST,256,crate::ple_batch_ffi::KernelArguments::new(vec![
crate::ple_batch_ffi::BatchArg::Address(scores),crate::ple_batch_ffi::BatchArg::Address(steps_tile),crate::ple_batch_ffi::BatchArg::I32(count as i32),
crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64),crate::ple_batch_ffi::BatchArg::I64(tile_reach as i64),crate::ple_batch_ffi::BatchArg::Address(status),crate::ple_batch_ffi::BatchArg::U32(4)])));
late.push((pushed.get(),ct,crate::qsa_late::TOPK_FAST,crate::ple_batch_ffi::KernelArguments::new(vec![
let(topk_entry,topk_block)=crate::qsa_late::topk_entry(tile_reach);
late.push((pushed.get(),ct,topk_entry,topk_block,crate::ple_batch_ffi::KernelArguments::new(vec![
crate::ple_batch_ffi::BatchArg::Address(scores),crate::ple_batch_ffi::BatchArg::Address(steps_tile),crate::ple_batch_ffi::BatchArg::I64(max_blocks() as i64),
crate::ple_batch_ffi::BatchArg::I64(CAP as i64),crate::ple_batch_ffi::BatchArg::Address(ids_tile)])));
}else{
@@ -101,10 +102,10 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx>{
if !late.is_empty()&&self.late.is_none(){self.late=Some(crate::ple_batch_ffi::KernelModule::load(crate::qsa_late::PTX,crate::qsa_late::ENTRIES)?);}
let module=self.module.as_ref().ok_or(Error::ContextPoisoned)?;
let mut next=0usize;
let mut run_late=|upto:usize,late:&mut Vec<(usize,u32,usize,crate::ple_batch_ffi::KernelArguments)>,next:&mut usize|->Result<()>{
while *next<late.len()&&late[*next].0<=upto{let started=std::time::Instant::now();let(_,grid,entry,args)=&mut late[*next];
self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch(*entry,*grid,256,blas.stream(),args)?;
if timed{blas.synchronize()?;crate::command_profile::add("qsa-index",if *entry==crate::qsa_late::TOPK_FAST{22}else{21},if *entry==crate::qsa_late::TOPK_FAST{"topk (fast)"}else{"score scan (fast)"},started.elapsed());}
let mut run_late=|upto:usize,late:&mut Vec<(usize,u32,usize,u32,crate::ple_batch_ffi::KernelArguments)>,next:&mut usize|->Result<()>{
while *next<late.len()&&late[*next].0<=upto{let started=std::time::Instant::now();let(_,grid,entry,block,args)=&mut late[*next];
self.late.as_ref().ok_or(Error::ContextPoisoned)?.launch(*entry,*grid,*block,blas.stream(),args)?;
if timed{blas.synchronize()?;let topk=*entry!=crate::qsa_late::SCORE_SCAN_FAST;crate::command_profile::add("qsa-index",if topk{22}else{21},if *entry==crate::qsa_late::TOPK_WIDE{"topk (wide)"}else if topk{"topk (fast)"}else{"score scan (fast)"},started.elapsed());}
*next+=1;}Ok(())};
for(i,(shape,args))in commands.iter_mut().enumerate(){run_late(i,&mut late,&mut next)?;let started=std::time::Instant::now();module.launch(*shape,blas.stream(),args)?;
if timed{blas.synchronize()?;let(i,l)=launch_label(shape);crate::command_profile::add("qsa-index",i,l,started.elapsed());}}
+14 -14
View File
@@ -188,6 +188,13 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0xf6, 0xbe, 0xc9, 0xbb, 0x67, 0xe4, 0x5a, 0xa8, 0x40, 0x4f, 0xaa, 0xfd, 0x44, 0xdc, 0x30, 0xb7, 0x90, 0xbf, 0x29, 0x08, 0xf4, 0x5f, 0x0c, 0x7b, 0xb0, 0xef, 0x86, 0xa0, 0x4e, 0xad, 0x97, 0x23],
ptx: concat!(include_str!("../ptx-sm86/original_verify_window_moe_experts.ptx"), "\0").as_bytes(),
},
Companion {
name: "prefill_stage.ptx",
key: [0x25, 0x19, 0xcc, 0xbc, 0x13, 0x1b, 0xae, 0x4a, 0xa4, 0x68, 0xf2, 0x9f, 0xcc, 0x1f, 0xb8, 0x18, 0x20, 0x6c, 0x66, 0x24, 0x91, 0xc4, 0xcd, 0x55, 0x3b, 0xea, 0x46, 0xab, 0x2d, 0xf8, 0x4e, 0x37],
len: 157373,
sha: [0x71, 0xfe, 0x02, 0x1c, 0xb0, 0xcd, 0x15, 0x25, 0xae, 0x9b, 0x8c, 0x02, 0x8d, 0xbf, 0x89, 0x4c, 0x50, 0x1d, 0xc4, 0xb6, 0x9f, 0x57, 0xf6, 0x1b, 0x1e, 0x74, 0x23, 0x59, 0x69, 0xff, 0x8c, 0x83],
ptx: concat!(include_str!("../ptx-sm86/prefill_stage.ptx"), "\0").as_bytes(),
},
Companion {
name: "q4_k_q8_1.ptx",
key: [0x29, 0x4f, 0x3a, 0xd5, 0xfd, 0xdd, 0xf7, 0x96, 0x94, 0x13, 0x46, 0xc9, 0x14, 0x4f, 0xc4, 0x9d, 0x4c, 0xff, 0x54, 0x78, 0xa8, 0x8d, 0xaa, 0xd6, 0xb8, 0x94, 0x1f, 0xbd, 0x4b, 0xb2, 0x40, 0xcb],
@@ -237,13 +244,6 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0x1c, 0xcf, 0xf9, 0xa5, 0xce, 0x9f, 0x1a, 0xb7, 0x9c, 0xf8, 0xf5, 0xc8, 0x1d, 0xfd, 0x2a, 0x77, 0x5a, 0xd8, 0x38, 0x11, 0x5c, 0x09, 0x41, 0x4e, 0x0e, 0x1c, 0xdb, 0x3f, 0x34, 0x7f, 0x35, 0x6b],
ptx: concat!(include_str!("../ptx-sm86/gr_prompt_device.ptx"), "\0").as_bytes(),
},
Companion {
name: "prefill_stage.ptx",
key: [0x3a, 0xac, 0xbe, 0xf4, 0x5f, 0xed, 0x66, 0x18, 0x23, 0xf9, 0x50, 0x0a, 0x56, 0x8b, 0x0d, 0x89, 0x64, 0xef, 0x6a, 0x20, 0x66, 0x64, 0xba, 0x6a, 0x42, 0xd3, 0x74, 0xb3, 0xe2, 0xbb, 0x01, 0x06],
len: 112485,
sha: [0x0c, 0xd1, 0x83, 0x5d, 0xc8, 0x3d, 0x3a, 0x31, 0x86, 0xf2, 0x20, 0x43, 0x9c, 0x67, 0x77, 0xa3, 0xa7, 0xe7, 0x04, 0x8d, 0x8d, 0x09, 0xdf, 0xfd, 0xbe, 0x01, 0x1b, 0x16, 0x72, 0xd9, 0x55, 0x3d],
ptx: concat!(include_str!("../ptx-sm86/prefill_stage.ptx"), "\0").as_bytes(),
},
Companion {
name: "s_gemv_legacy.ptx",
key: [0x3a, 0xb4, 0xd1, 0x2a, 0x5e, 0x97, 0xc4, 0xe2, 0xf4, 0x60, 0x2c, 0x6c, 0x87, 0x23, 0x72, 0xc5, 0xc0, 0x68, 0x5d, 0x8c, 0xf1, 0xa2, 0x02, 0x60, 0xaf, 0x6e, 0x0f, 0x52, 0x05, 0xac, 0x76, 0xd5],
@@ -391,13 +391,6 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0xf9, 0xa3, 0x97, 0x01, 0xe2, 0xcc, 0xf0, 0xf6, 0xf7, 0x2d, 0x5e, 0xce, 0x56, 0x6b, 0x78, 0x09, 0x33, 0xea, 0xdd, 0xe6, 0x89, 0xe7, 0xff, 0x50, 0x2a, 0xcf, 0x87, 0xdb, 0x63, 0xf5, 0xd8, 0x5f],
ptx: concat!(include_str!("../ptx-sm86/ple_native_batch.ptx"), "\0").as_bytes(),
},
Companion {
name: "qsa_late.ptx",
key: [0x61, 0x68, 0xe0, 0x52, 0xbb, 0x23, 0xc0, 0x54, 0x4f, 0xf2, 0x9e, 0x94, 0x10, 0x06, 0xdd, 0x87, 0x3a, 0x0b, 0xf1, 0xc0, 0xae, 0xf1, 0x98, 0x28, 0x09, 0x1f, 0x56, 0x63, 0x43, 0x0a, 0xeb, 0x91],
len: 26496,
sha: [0xe4, 0x1d, 0xb0, 0x83, 0x0f, 0xff, 0xfd, 0x96, 0x7a, 0x14, 0x2e, 0xfc, 0x0d, 0x4c, 0xd7, 0x8e, 0xfb, 0x24, 0xec, 0xae, 0x7e, 0x96, 0xf3, 0x20, 0x08, 0xf1, 0x16, 0xa7, 0x59, 0x50, 0x66, 0xe8],
ptx: concat!(include_str!("../ptx-sm86/qsa_late.ptx"), "\0").as_bytes(),
},
Companion {
name: "ple_value_full_fixed.ptx",
key: [0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, 0xac, 0x6c, 0x15, 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, 0x25, 0xd0],
@@ -867,6 +860,13 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0x67, 0x25, 0x8f, 0xde, 0x60, 0xe2, 0xe5, 0xd0, 0xe5, 0x0b, 0xe8, 0xcb, 0xd6, 0x3b, 0x0d, 0xe4, 0x2e, 0x33, 0xf7, 0x22, 0xb1, 0x61, 0x40, 0xe1, 0xb0, 0x71, 0x85, 0x7b, 0x47, 0xaa, 0xa8, 0xbe],
ptx: concat!(include_str!("../ptx-sm86/moe_fixed.ptx"), "\0").as_bytes(),
},
Companion {
name: "qsa_late.ptx",
key: [0xeb, 0xc8, 0xbc, 0x0a, 0xac, 0x1b, 0xd4, 0xa7, 0x45, 0x40, 0xed, 0x24, 0x6c, 0x00, 0x96, 0x0d, 0x10, 0x15, 0x96, 0x30, 0x20, 0x11, 0x33, 0xe6, 0xd2, 0x1f, 0x30, 0x6e, 0xfe, 0xb1, 0xba, 0x2f],
len: 213285,
sha: [0x11, 0x8d, 0x23, 0x00, 0xe6, 0x7d, 0x15, 0x42, 0x0b, 0x7e, 0xbd, 0xb4, 0xee, 0x82, 0x3d, 0x91, 0xbe, 0x58, 0x55, 0x62, 0x07, 0x23, 0x85, 0x3f, 0xe9, 0xda, 0x8d, 0xef, 0x8a, 0xe5, 0xe9, 0x8b],
ptx: concat!(include_str!("../ptx-sm86/qsa_late.ptx"), "\0").as_bytes(),
},
Companion {
name: "kar_decode_levels.ptx",
key: [0xec, 0x69, 0x77, 0x87, 0xe0, 0x00, 0x53, 0x10, 0x00, 0x5e, 0xb1, 0x69, 0xa7, 0x58, 0x31, 0x5e, 0xb5, 0x50, 0x3a, 0xc7, 0x67, 0x1a, 0x38, 0x49, 0x5e, 0xea, 0xea, 0xf4, 0xfb, 0x2a, 0x8e, 0xc9],
@@ -28,6 +28,9 @@ use std::rc::Rc;
const PLE_HISTORY_VALUES: usize = 9 * 10240;
pub(in crate::qwen_forward) const PLE_HISTORY_BYTES: usize = PLE_HISTORY_VALUES * 4;
/// Default of `LELEKA_QSA_CLUSTER` (the cluster top-k of the decode window; flipped after its gates, docs/upstream-port-plan.md row 2.5).
const QSA_CLUSTER_DEFAULT: bool = false;
/// A refusal with the driver's own words when it has them (an unbound producer, an unsealed asset).
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct ServeFailure {
@@ -265,6 +268,9 @@ pub(in crate::qwen_forward) fn assemble<'a, 'ctx>(
// `Verifier::set_pcie_mode`: the copy kernel stages the PCIe share inside the graph (2), or DMA (0).
let mut policy = OriginalVerifyWindowPolicy::mode17();
policy.pcie_mode = pcie_mode;
// docs/upstream-port-plan.md row 2.5: the decode top-k as a thread-block cluster (same ids as qsa_topk_ref; sm_90+, the driver
// turns it off again on an older card). `LELEKA_QSA_CLUSTER=1` / `0`; unset: QSA_CLUSTER_DEFAULT.
policy.qsa.cluster_topk = std::env::var("LELEKA_QSA_CLUSTER").map_or(QSA_CLUSTER_DEFAULT, |v| v == "1");
let recorded = verifier.record_all(
policy,
|t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape),
+31 -1
View File
@@ -776,7 +776,10 @@
"policy": "precise (integer and comparison arithmetic only; the recipe of prefill_stage)",
"entries": [
"leleka_qsa_topk_fast",
"leleka_qsa_score_scan_fast"
"leleka_qsa_score_scan_fast",
"leleka_qsa_topk_wide",
"leleka_qsa_topk_wide_failed",
"leleka_qsa_topk_sample"
],
"encoding": "concat_include_str",
"rust_fields_to_fill": {
@@ -787,6 +790,33 @@
},
"group": "qsa-late",
"optional": false
},
{
"cu": "crates/cuda-driver/src/qsa_cluster.cu",
"ptx": "crates/cuda-driver/src/qsa_cluster.ptx",
"flags": [
"-ptx",
"-O3",
"-arch=sm_120",
"-std=c++17",
"--ftz=false",
"--prec-div=true",
"--prec-sqrt=true",
"--fmad=true"
],
"policy": "precise (integer and comparison arithmetic only; sm_90+ cluster barriers, no sm_86 companion)",
"entries": [
"leleka_qsa_topk_cluster"
],
"encoding": "concat_include_str",
"rust_fields_to_fill": {
"qsa_cluster.rs": [
"PIN.source_sha256",
"PIN.ptx_sha256"
]
},
"group": "qsa-cluster",
"optional": false
}
]
}