Merge claude/upstream-rest into main
Linux / keyless-cuda-gate (push) Skipped
Rust port / port-typecheck (push) Failing after 9s
Rust port / port-oracles (push) Failing after 13s
Rust port / port-linux-tests (push) Failing after 16s
Rust port / port-fast (push) Failing after 9s
Linux / verify (push) Failing after 18s
Linux / keyless-cuda (push) Skipped
Linux / static-cuda-package (push) Skipped
Linux / hosted-cuda-package (push) Skipped
Linux / linux-static-cli (push) Skipped
Linux / linux-cli-container (push) Skipped
Linux / release-cli (push) Skipped

This commit is contained in:
Pavlo Ratushnyi
2026-10-27 22:11:02 +01:00
32 changed files with 16507 additions and 1524 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": 19,
"isa": "9.2",
"method": "retarget",
"name": "prefill_stage.ptx",
@@ -2218,13 +2218,13 @@
"count": 1
}
],
"sm120_bytes": 112485,
"sm120_bytes": 161928,
"sm120_nvcc": "13.2.86",
"sm120_path": "crates/cuda-driver/src/prefill_stage.ptx",
"sm120_sha256": "3aacbef45fed661823f9500a568b0d8964ef6a206664ba6a42d374b3e2bb0106",
"sm120_sha256": "6f8fb3bbd11171c9390297d5d2c9cb9076d4b651f2a7042bf16f4caf89a5b384",
"sm120_stored_nul": false,
"sm86_bytes": 112484,
"sm86_sha256": "0cd1835dc83d3a3186f220439c6777a3a7e7048d8d09dffdbe011b1672d9553d"
"sm86_bytes": 161927,
"sm86_sha256": "d81a87437b726bcf1a9df0ca6d5ebedf5c06dacee688bdc8fe917891cc0cda4b"
},
{
"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
File diff suppressed because it is too large Load Diff
+5 -4
View File
@@ -530,10 +530,11 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
}
let witness =
status.checked_subspan(STATUS_BYTES, GdnBatchStage::StateSteps.slot() * 4, 4)?;
if crate::prefill_stage::fast_rec() {
if crate::prefill_stage::fast_rec() || crate::prefill_stage::gdn_kh_usable(self.context) {
let kh = !crate::prefill_stage::fast_rec();
commands.push(DeviceCommand::Stage {
index: crate::prefill_stage::GDN_REC,
grid: 192,
index: if kh { crate::prefill_stage::GDN_REC_KH } else { crate::prefill_stage::GDN_REC },
grid: if kh { 64 } else { 192 },
block: 128,
args: KernelArguments::new(vec![
A::Address(sin),
@@ -566,7 +567,7 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
scan(&mut commands, GdnBatchStage::NextState, sout)?;
if fused {
commands.push(DeviceCommand::Stage {
index: crate::prefill_stage::GDN_OUT_NORM,
index: if crate::prefill_stage::gdn_nostore() { crate::prefill_stage::GDN_OUT_NORM_Y16 } else { crate::prefill_stage::GDN_OUT_NORM },
grid: (48 * t).div_ceil(2) as u32,
block: 256,
args: KernelArguments::new(vec![
+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));
}
}
+5
View File
@@ -3245,8 +3245,13 @@ 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 qsa_late::set_topk_override as set_qsa_topk_override;
pub use qsa_cluster::{requested as qsa_cluster_requested, set_override as set_qsa_cluster_override};
pub use prefill_stage::{set_gdn_nostore_override as set_prefill_gdn_nostore_override, set_gdn_override as set_prefill_gdn_override};
pub use native_prompt_device::{
OriginalDeviceBlock, OriginalDeviceGrRead, OriginalDeviceNormedResidual,
OriginalDeviceResidual, OriginalPleHistory, OriginalPromptDevice, PromptInputStage,
+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,14 @@ 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();
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("leleka-serve qsa decode top-k: {} (compute capability {cc})", if policy.qsa.cluster_topk { "thread-block cluster" } else { "qsa_topk_ref (cluster refused)" }));
}
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(())
}
+147 -7
View File
@@ -405,7 +405,8 @@ extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_l2(float* _
// gdn_out_norm_kernel for two (t, head) items per block + the guards of z (read), the readout oc (read), y and its FP16
// image (written). Grid: ceil(T * 48 / 2).
extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_out_norm(
template <bool STORE_Y>
__device__ __forceinline__ void gdn_out_norm_body(
const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y,
uint16_t* __restrict__ y16, int64_t T, unsigned* __restrict__ status_z, unsigned* __restrict__ status_readout,
unsigned* __restrict__ status_y, unsigned* __restrict__ status_y16) {
@@ -424,7 +425,7 @@ extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_out_norm(
const float ss = wsum[half * 4] + wsum[half * 4 + 1] + wsum[half * 4 + 2] + wsum[half * 4 + 3];
const float zz = z[t * GHV * GS + head * GS + col];
const float v = oc * rsqrtf(ss / (float) GS + eps) * gamma[col] * sigm(zz);
y[at] = v;
if (STORE_Y) y[at] = v;
const uint16_t hv = hf(v);
y16[at] = hv;
if (nonfinite(zz)) atomicOr(status_z, 1u);
@@ -434,6 +435,23 @@ extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_out_norm(
}
}
extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_out_norm(
const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y,
uint16_t* __restrict__ y16, int64_t T, unsigned* __restrict__ status_z, unsigned* __restrict__ status_readout,
unsigned* __restrict__ status_y, unsigned* __restrict__ status_y16) {
gdn_out_norm_body<true>(z, gamma, eps, y, y16, T, status_z, status_readout, status_y, status_y16);
}
// Row 2.4 (upstream 4e69f974, "no dead FP32 store in the output norm"): the same kernel without the store of the normalised FP32 values back
// into `y`. Nothing reads them after this launch (the output projection takes the FP16 image y16; the guard of y is taken from the register
// value, status_y), so it writes y16 and the four status words, bit for bit what leleka_prefill_gdn_out_norm writes there, and leaves `y`
// holding the readout. 201 MB less written per layer and 8192 tokens.
extern "C" __global__ __launch_bounds__(256) void leleka_prefill_gdn_out_norm_y16(
const float* __restrict__ z, const float* __restrict__ gamma, float eps, float* __restrict__ y,
uint16_t* __restrict__ y16, int64_t T, unsigned* __restrict__ status_z, unsigned* __restrict__ status_readout,
unsigned* __restrict__ status_y, unsigned* __restrict__ status_y16) {
gdn_out_norm_body<false>(z, gamma, eps, y, y16, T, status_z, status_readout, status_y, status_y16);
}
// gdn_rec_cols_pipe_kernel (the Original's prompt recurrence, interface edits of offline_gdn_prefill_kernel.cu:
// state_in -> state_out, the state witness) with the same arithmetic in the same order, restructured to wait less per
// token: a warp reads only its own 32-row slice of q and k, so the token no longer starts with a block barrier and a
@@ -460,8 +478,6 @@ leleka_prefill_gdn_rec(const float* __restrict__ state_in, float* __restrict__ s
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = base_in[r * rs];
unsigned bad = 0;
#pragma unroll
for (int r = 0; r < RPG; ++r) bad |= (__float_as_uint(s[r]) & 0x7f800000u) == 0x7f800000u;
float nq = 0.0f, nk = 0.0f, nv = 0.0f, ng = 0.0f, nb = 0.0f;
auto fetch = [&](int64_t t) {
const float* ht = h + t * GC;
@@ -493,13 +509,137 @@ leleka_prefill_gdn_rec(const float* __restrict__ state_in, float* __restrict__ s
s[r] = fmaf(g, s[r], sk[par][rg][r] * delta);
o = fmaf(s[r], sq[par][rg][r], o);
}
#pragma unroll
for (int r = 0; r < RPG; ++r) bad |= (__float_as_uint(s[r]) & 0x7f800000u) == 0x7f800000u;
red2[rg][c] = o;
__syncthreads();
if (rg == 0) oc_out[t * GHV * GS + head * GS + col] = (red2[0][c] + red2[1][c] + red2[2][c] + red2[3][c]) * rsqrtf((float) GS);
}
// the witness is read from the FINAL state: a non-finite state value never becomes finite again (see leleka_prefill_gdn_rec_kh)
#pragma unroll
for (int r = 0; r < RPG; ++r) base_out[r * rs] = s[r];
for (int r = 0; r < RPG; ++r) {
base_out[r * rs] = s[r];
bad |= (__float_as_uint(s[r]) & 0x7f800000u) == 0x7f800000u;
}
if (bad) atomicOr(witness, 1u);
}
// ---------------------------------------------------------------------------------------------------------------------
// gdn_rec_kh_kernel (Strata 41cf05a0 `src/prefill/kernels.cu`, upstream 4e69f974): the recurrence with ONE thread for the
// three value heads that share a key head (head % GHK): column c of heads qh, qh + 16 and qh + 32, row group rg. The
// kernel above spends its time in shared memory, not in arithmetic (every thread of a warp needs the same 32 q and k values
// per token and a warp receives one broadcast value per clock); here every q/k value a thread loads feeds three heads and a
// token's k row goes into registers once for both of its uses. The inputs come in blocks of GDN_TB tokens, copied to shared
// memory by cp.async while the block before computes, and the two cross-row-group sums have their own arrays, so a token
// needs 2 __syncthreads instead of 5. 64 blocks instead of 192 (grid 64, block 128 = 4 warps = the 4 row groups): each
// block walks the whole chunk, so it is launched only when the card holds all 64 blocks at once (the host checks the SM
// count). Per value head and column the SAME arithmetic in the SAME order as leleka_prefill_gdn_rec: the same bits
// (state_out, readout and the witness). Interface edits as there: state_in -> state_out and the state witness. The witness
// is read from the FINAL state only: a non-finite state value never becomes finite again (s = fma(g, s, c) with g >= 0:
// inf stays inf or turns NaN, NaN stays NaN), so "non-finite at some token" and "non-finite at the end" are the same
// predicate, and the per-token check of the kernel above (96 extra integer ops per thread and token) is not needed.
__device__ __forceinline__ void gdn_cp4(float* smem, const float* gmem) {
asm volatile("cp.async.ca.shared.global [%0], [%1], 4;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
}
__device__ __forceinline__ void gdn_cp16(float* smem, const float* gmem) {
asm volatile("cp.async.cg.shared.global [%0], [%1], 16;\n" ::"r"((unsigned) __cvta_generic_to_shared(smem)), "l"(gmem));
}
__device__ __forceinline__ void gdn_cp_commit() { asm volatile("cp.async.commit_group;\n" ::); }
__device__ __forceinline__ void gdn_cp_wait_prev() { asm volatile("cp.async.wait_group 1;\n" ::); } // every group but the newest has landed
extern "C" __global__ void __launch_bounds__(128)
leleka_prefill_gdn_rec_kh(const float* __restrict__ state_in, float* __restrict__ state_out, const float* __restrict__ h,
const float* __restrict__ gate, const float* __restrict__ beta, float* __restrict__ oc_out,
int64_t T, unsigned* __restrict__ witness) {
constexpr int RG = 4, RPG = GS / RG, CB = 32, NCB = GS / CB, TB = 8, VPK = GHV / GHK, NT = CB * RG, QKP = GS / 4, VP = CB / 4;
__shared__ __align__(16) float sq[2][TB][GS];
__shared__ __align__(16) float sk[2][TB][GS];
__shared__ __align__(16) float sv[2][TB][VPK][CB];
__shared__ float sg[2][TB][VPK], sb[2][TB][VPK], rkv[VPK][RG][CB], ro[VPK][RG][CB];
const int qh = blockIdx.x / NCB, cb = blockIdx.x % NCB;
const int c = threadIdx.x & 31, rg = threadIdx.x >> 5, tid = threadIdx.x, col = cb * CB + c;
float s[VPK][RPG];
const size_t rs = (size_t) GHV * GS;
unsigned bad = 0;
#pragma unroll
for (int j = 0; j < VPK; ++j) {
const float* base = state_in + ((size_t) (rg * RPG) * GHV + qh + j * GHK) * GS + col;
#pragma unroll
for (int r = 0; r < RPG; ++r) s[j][r] = base[r * rs];
}
const int64_t nblk = (T + TB - 1) / TB;
auto stage = [&](int64_t k) { // tokens [k * TB, k * TB + TB) into buffer k & 1
const int bb = (int) (k & 1);
const int64_t t0 = k * TB;
for (int p = tid; p < TB * 2 * QKP; p += NT) {
const int i = p / (2 * QKP), w = p % (2 * QKP), isk = w / QKP, jj = (w % QKP) * 4;
if (t0 + i < T)
gdn_cp16(isk ? &sk[bb][i][jj] : &sq[bb][i][jj], h + (t0 + i) * GC + (isk ? GHK * GS : 0) + qh * GS + jj);
}
for (int p = tid; p < TB * VPK * VP; p += NT) {
const int i = p / (VPK * VP), w = p % (VPK * VP), j = w / VP, jj = (w % VP) * 4;
if (t0 + i < T)
gdn_cp16(&sv[bb][i][j][jj], h + (t0 + i) * GC + 2 * GHK * GS + (qh + j * GHK) * GS + cb * CB + jj);
}
for (int p = tid; p < 2 * TB * VPK; p += NT) {
const int isb = p / (TB * VPK), w = p % (TB * VPK), i = w / VPK, j = w % VPK;
if (t0 + i < T)
gdn_cp4(isb ? &sb[bb][i][j] : &sg[bb][i][j], (isb ? beta : gate) + (t0 + i) * GHV + qh + j * GHK);
}
};
if (nblk > 0) stage(0);
gdn_cp_commit();
for (int64_t k = 0; k < nblk; ++k) {
// buffer (k + 1) & 1 was read by block k - 1, whose last token's second __syncthreads every thread has passed
if (k + 1 < nblk) stage(k + 1);
gdn_cp_commit();
gdn_cp_wait_prev();
__syncthreads();
const int bb = (int) (k & 1);
const int n = (int) ((T - k * TB) < TB ? (T - k * TB) : TB);
for (int i = 0; i < n; ++i) {
const int64_t t = k * TB + i;
float kc[RPG];
#pragma unroll
for (int r = 0; r < RPG; ++r) kc[r] = sk[bb][i][rg * RPG + r];
float g[VPK], kv[VPK], delta[VPK], o[VPK];
#pragma unroll
for (int j = 0; j < VPK; ++j) { g[j] = __expf(sg[bb][i][j]); kv[j] = 0.0f; o[j] = 0.0f; }
#pragma unroll
for (int r = 0; r < RPG; ++r)
#pragma unroll
for (int j = 0; j < VPK; ++j) kv[j] = fmaf(s[j][r], kc[r], kv[j]);
#pragma unroll
for (int j = 0; j < VPK; ++j) rkv[j][rg][c] = kv[j];
__syncthreads();
#pragma unroll
for (int j = 0; j < VPK; ++j) {
const float kv_col = rkv[j][0][c] + rkv[j][1][c] + rkv[j][2][c] + rkv[j][3][c];
delta[j] = (sv[bb][i][j][c] - g[j] * kv_col) * sb[bb][i][j];
}
#pragma unroll
for (int r = 0; r < RPG; ++r) {
const float qr = sq[bb][i][rg * RPG + r];
#pragma unroll
for (int j = 0; j < VPK; ++j) {
s[j][r] = fmaf(g[j], s[j][r], kc[r] * delta[j]);
o[j] = fmaf(s[j][r], qr, o[j]);
}
}
#pragma unroll
for (int j = 0; j < VPK; ++j) ro[j][rg][c] = o[j];
__syncthreads();
if (rg < VPK) // row group j writes head j's output
oc_out[t * GHV * GS + (qh + rg * GHK) * GS + col] =
(ro[rg][0][c] + ro[rg][1][c] + ro[rg][2][c] + ro[rg][3][c]) * rsqrtf((float) GS);
}
}
#pragma unroll
for (int j = 0; j < VPK; ++j) {
float* base = state_out + ((size_t) (rg * RPG) * GHV + qh + j * GHK) * GS + col;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
base[r * rs] = s[j][r];
bad |= (__float_as_uint(s[j][r]) & 0x7f800000u) == 0x7f800000u;
}
}
if (bad) atomicOr(witness, 1u);
}
File diff suppressed because it is too large Load Diff
+77 -4
View File
@@ -25,6 +25,8 @@ pub(crate) const ENTRIES: &[&CStr] = &[
c"leleka_prefill_gdn_l2",
c"leleka_prefill_gdn_out_norm",
c"leleka_prefill_gdn_rec",
c"leleka_prefill_gdn_rec_kh",
c"leleka_prefill_gdn_out_norm_y16",
];
/// Entry indices (positions in `ENTRIES`).
pub(crate) const GR_NORM_RS: usize = 3;
@@ -36,6 +38,8 @@ pub(crate) const GDN_CONV_TILED: usize = 13;
pub(crate) const GDN_L2: usize = 14;
pub(crate) const GDN_OUT_NORM: usize = 15;
pub(crate) const GDN_REC: usize = 16;
pub(crate) const GDN_REC_KH: usize = 17;
pub(crate) const GDN_OUT_NORM_Y16: usize = 18;
fn switch(name: &'static str, cell: &'static std::sync::OnceLock<bool>) -> bool {
*cell.get_or_init(|| std::env::var(name).map_or(true, |v| v != "0"))
@@ -48,9 +52,78 @@ pub(crate) fn fused_scans() -> bool {
/// `LELEKA_PREFILL_FAST_REC=1` (EXPERIMENTAL, off by default): the two-barrier recurrence kernel. Bit-identical to the
/// original on the 3080 probe but not faster there, so it is not the default until a 5090 A/B shows a gain.
pub(crate) fn fast_rec() -> bool {
match GDN_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 | 1 => return false,
2 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_FAST_REC").is_ok_and(|v| v == "1"))
}
/// Per-arm override of the prompt recurrence for paired A/B passes in one process (-1: none, 0: the sealed Original kernel, 1: the kh kernel,
/// 2: the two-barrier kernel).
static GDN_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
pub fn set_gdn_override(value: i8) {
GDN_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed);
}
/// `LELEKA_PREFILL_GDN_NOSTORE=0` keeps the store of the normalised FP32 values in the GDN output norm (the A/B arm); the default is the kernel without
/// that dead store (`leleka_prefill_gdn_out_norm_y16`, docs/upstream-port-plan.md row 2.4). A per-arm override wins.
pub(crate) fn gdn_nostore() -> bool {
match NOSTORE_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 => return false,
1 => return true,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_GDN_NOSTORE").map_or(GDN_NOSTORE_DEFAULT, |v| v != "0"))
}
/// Default of `LELEKA_PREFILL_GDN_NOSTORE` (flipped after its identity gate).
pub(crate) const GDN_NOSTORE_DEFAULT: bool = true;
static NOSTORE_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
pub fn set_gdn_nostore_override(value: i8) {
NOSTORE_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed);
}
/// `LELEKA_PREFILL_GDN_KH`: the recurrence with one thread for the three value heads of a key head (Strata `gdn_rec_kh_kernel`, upstream
/// 4e69f974; docs/upstream-port-plan.md row 2.4). Bit-identical to the Original's recurrence (`gdn_recurrence_kh_equals_...` probe). `1` on,
/// `0` off; unset: see `GDN_KH_DEFAULT`. It needs all 64 of its blocks resident at once, so it is used only on a native sm_120 device.
pub(crate) fn gdn_kh_requested() -> bool {
match GDN_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
1 => return true,
0 | 2 => return false,
_ => {}
}
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| match std::env::var("LELEKA_PREFILL_GDN_KH").ok().as_deref() {
Some("1") => true,
Some(_) => false,
None => GDN_KH_DEFAULT,
})
}
/// Default of `LELEKA_PREFILL_GDN_KH` (flipped only after its gates, see the plan).
pub(crate) const GDN_KH_DEFAULT: bool = false;
/// The kh recurrence is wanted AND the current device is a native sm_120 card. Needs the context (enters it).
pub(crate) fn gdn_kh_usable(context: &crate::Context<'_>) -> bool {
if !gdn_kh_requested() {
return false;
}
static USABLE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*USABLE.get_or_init(|| {
if admit().is_err() {
return false;
}
#[cfg(feature = "sm86")]
{
let Ok(guard) = context.enter() else { return false };
let native = crate::arch_ptx::native_sm120();
guard.finish().is_ok() && native
}
#[cfg(not(feature = "sm86"))]
{
let _ = context;
true
}
})
}
/// `LELEKA_PREFILL_FAST_DEQUANT=0`: the original one-thread-per-32-values GDN weight dequantization (A/B arm).
pub(crate) fn fast_dequant() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
@@ -59,12 +132,12 @@ pub(crate) fn fast_dequant() -> bool {
/// Frozen by `scripts/gpu-bringup/seal_pins.py` after `compile_assets.py` (extra-seal-plan.json, group prefill-stage).
pub(crate) const PIN: PtxPin = PtxPin {
source_sha256: [
62, 152, 220, 4, 61, 27, 47, 181, 125, 201, 35, 79, 65, 232, 25, 204, 213, 251, 26, 196,
227, 189, 129, 148, 111, 236, 159, 49, 220, 12, 209, 126,
62, 247, 28, 124, 51, 213, 225, 210, 87, 103, 7, 80, 80, 6, 194, 177, 126, 226, 97, 251,
127, 238, 115, 78, 196, 57, 156, 88, 242, 97, 4, 252,
],
ptx_sha256: [
58, 172, 190, 244, 95, 237, 102, 24, 35, 249, 80, 10, 86, 139, 13, 137, 100, 239, 106, 32,
102, 100, 186, 106, 66, 211, 116, 179, 226, 187, 1, 6,
111, 143, 179, 187, 209, 17, 113, 201, 57, 2, 151, 213, 210, 201, 203, 144, 118, 212, 182,
81, 242, 167, 4, 43, 241, 111, 76, 175, 137, 165, 179, 132,
],
};
pub(crate) fn admit() -> Result<(), KarDecodeError> {
@@ -239,6 +239,16 @@ fn gdn_stage_kernels_equal_the_originals_bit_for_bit() {
assert_eq!(download(&y_old, t * 6144 * 4), download(&y_new, t * 6144 * 4), "case {case}: y");
assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_new, t * 6144 * 2), "case {case}: y16");
assert_eq!(words(&so, 4), words(&sn, 4), "case {case}: out-norm status words (z, readout, y, y16)");
// row 2.4: the variant without the dead FP32 store writes the same y16 and status words and leaves y holding the readout
let (y_ns, yh_ns, sns) = (upload(&context, &f32_bytes(&oc)), upload(&context, &vec![0u8; t * 6144 * 2]), upload(&context, &[0u8; 64]));
run_stage(&context, stream, &stage, vec![(
crate::prefill_stage::GDN_OUT_NORM_Y16,
(48 * t).div_ceil(2) as u32,
vec![A::Address(hd(&z_d)), A::Address(hd(&g_d)), A::F32(eps), A::Address(hd(&y_ns)), A::Address(hd(&yh_ns)), A::I64(t as i64), A::Address(word(&sns, 0)), A::Address(word(&sns, 1)), A::Address(word(&sns, 2)), A::Address(word(&sns, 3))],
)]);
assert_eq!(download(&yh_old, t * 6144 * 2), download(&yh_ns, t * 6144 * 2), "case {case}: y16 of the no-store variant");
assert_eq!(words(&so, 4), words(&sns, 4), "case {case}: status words of the no-store variant");
assert_eq!(download(&y_ns, t * 6144 * 4), f32_bytes(&oc), "case {case}: the no-store variant leaves y untouched");
eprintln!("PREFILL-GDN case {case}: conv/L2/out-norm equal; statuses conv {:?} l2 {:?} norm {:?}", words(&status_new, 2), words(&status_l2_new, 1), words(&sn, 4));
}
}
@@ -335,3 +345,125 @@ fn gdn_recurrence_equals_the_original_bit_for_bit() {
eprintln!("PREFILL-GDN rec case {case} t={t}: equal (state {} floats, witness {:?}); original {old_ms:.3} ms, new {new_ms:.3} ms", state_len, words(&wn, 1));
}
}
/// Row 2.4 (upstream 4e69f974): the recurrence with one thread for the three value heads of a key head
/// (`leleka_prefill_gdn_rec_kh`, grid 64 x 128) equals the Original's `gdn_rec_cols_pipe` (state out, readout, witness) bit for bit,
/// for token counts around the staging block (8) and the real chunk sizes, with a state that overflows; and the timing of the three
/// recurrences on warm data (`PREFILL-GDN rec-kh timing`).
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn gdn_recurrence_kh_equals_the_original_bit_for_bit() {
assert_eq!(std::env::var(ENABLE).ok().as_deref(), Some("yes"));
let driver = crate::Driver::load().expect("driver");
let device = driver.device(0).expect("device");
let context = device.create_context(10usize << 30).expect("context");
let workspace = context.native_batch_workspace().expect("workspace");
let stream = workspace.blas().expect("blas").stream();
let batch = context.gdn_prefill_batch_for_prompt(2048).expect("gdn batch");
let funcs = batch.functions.as_ref().expect("functions");
let old = Old { context: &context, stream, funcs };
let guard = context.enter().expect("enter");
let stage = KernelModule::load(crate::prefill_stage::PTX, crate::prefill_stage::ENTRIES).expect("stage module");
guard.finish().expect("finish");
let mut rng = Rng(0x0badc0ffee0ddf00);
let state_len = 128 * 48 * 128;
// (token count, variant): 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow
for (case, (t, variant)) in [(1usize, 0u8), (2, 0), (7, 0), (8, 0), (9, 0), (200, 0), (200, 1), (201, 2), (200, 3), (1500, 0), (2048, 0), (8192, 0)].into_iter().enumerate() {
let mut state: Vec<f32> = (0..state_len).map(|_| rng.f(0.05)).collect();
let mut h: Vec<f32> = (0..t * 10240).map(|_| rng.f(0.2)).collect();
let gate: Vec<f32> = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect();
let beta: Vec<f32> = (0..t * 48).map(|_| (rng.f(0.5) + 0.5).abs()).collect();
if variant == 1 {
state[1234] = f32::INFINITY;
}
if variant == 3 {
state[1234] = 3.0e38;
h[5 * 10240 + 4096 + 300] = 3.0e38;
}
if variant == 2 {
h[100 * 10240 + 2 * 2048 + 777] = f32::NAN;
}
let (sin, h_d, gate_d, beta_d) = (
upload(&context, &f32_bytes(&state)),
upload(&context, &f32_bytes(&h)),
upload(&context, &f32_bytes(&gate)),
upload(&context, &f32_bytes(&beta)),
);
let (sout_o, sout_k) = (upload(&context, &vec![0u8; state_len * 4]), upload(&context, &vec![0u8; state_len * 4]));
let (oc_o, oc_k) = (upload(&context, &vec![0u8; t * 6144 * 4]), upload(&context, &vec![0u8; t * 6144 * 4]));
let (wo, wk) = (upload(&context, &[0u8; 16]), upload(&context, &[0u8; 16]));
let old_launch = |sout: &DeviceBuffer<'_>, oc: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>| {
(
Kernel::RecColsPipe,
[192u32, 1, 1],
[32u32, 4, 1],
vec![
ffi::KernelArg::Pointer(hd(&sin)),
ffi::KernelArg::Pointer(hd(sout)),
ffi::KernelArg::Pointer(hd(&h_d)),
ffi::KernelArg::Pointer(hd(&gate_d)),
ffi::KernelArg::Pointer(hd(&beta_d)),
ffi::KernelArg::Pointer(hd(oc)),
ffi::KernelArg::I64(t as i64),
ffi::KernelArg::Pointer(hd(w)),
],
)
};
let kh_args = |sout: &DeviceBuffer<'_>, oc: &DeviceBuffer<'_>, w: &DeviceBuffer<'_>| {
KernelArguments::new(vec![
A::Address(hd(&sin)),
A::Address(hd(sout)),
A::Address(hd(&h_d)),
A::Address(hd(&gate_d)),
A::Address(hd(&beta_d)),
A::Address(hd(oc)),
A::I64(t as i64),
A::Address(hd(w)),
])
};
old.run(vec![old_launch(&sout_o, &oc_o, &wo)]);
let guard = context.enter().expect("enter");
let mut args = kh_args(&sout_k, &oc_k, &wk);
stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut args).expect("launch kh");
context.driver.api.synchronize().expect("sync");
guard.finish().expect("finish");
// compare the bytes as words: a NaN payload is a value too
assert_eq!(download(&oc_o, t * 6144 * 4), download(&oc_k, t * 6144 * 4), "case {case} (t={t}, variant {variant}): readout");
assert_eq!(download(&sout_o, state_len * 4), download(&sout_k, state_len * 4), "case {case} (t={t}, variant {variant}): next state");
assert_eq!(words(&wo, 1), words(&wk, 1), "case {case}: state witness");
let w = words(&wk, 1)[0];
if variant == 1 || variant == 2 {
assert_ne!(w, 0, "case {case}: the witness must be raised for a non-finite state / input");
} else if variant == 0 {
assert_eq!(w, 0, "case {case}: a clean chunk must not raise the witness");
}
if t >= 1500 && variant == 0 {
// timing on warm data: 20 launches of each, drained once
let reps = 20;
let t0 = std::time::Instant::now();
old.run((0..reps).map(|_| old_launch(&sout_o, &oc_o, &wo)).collect());
let old_ms = t0.elapsed().as_secs_f64() * 1e3 / reps as f64;
let guard = context.enter().expect("enter");
let mut keep = Vec::new();
let t1b = std::time::Instant::now();
for _ in 0..reps {
let mut a = kh_args(&sout_k, &oc_k, &wk);
stage.launch(crate::prefill_stage::GDN_REC_KH, 64, 128, stream, &mut a).expect("launch kh");
keep.push(a);
}
context.driver.api.synchronize().expect("sync");
let kh_ms = t1b.elapsed().as_secs_f64() * 1e3 / reps as f64;
let t2 = std::time::Instant::now();
for _ in 0..reps {
let mut a = kh_args(&sout_k, &oc_k, &wk);
stage.launch(crate::prefill_stage::GDN_REC, 192, 128, stream, &mut a).expect("launch rec");
keep.push(a);
}
context.driver.api.synchronize().expect("sync");
let rec_ms = t2.elapsed().as_secs_f64() * 1e3 / reps as f64;
guard.finish().expect("finish");
eprintln!("PREFILL-GDN rec-kh timing t={t}: original gdn_rec_cols_pipe {old_ms:.3} ms, leleka_prefill_gdn_rec {rec_ms:.3} ms, kh {kh_ms:.3} ms per launch (mean of {reps}, warm)");
}
eprintln!("PREFILL-GDN rec-kh case {case} t={t} variant {variant}: readout, state and witness ({w}) equal the original");
}
}
+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
+59
View File
@@ -0,0 +1,59 @@
//! 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
}
/// Per-arm override of the cluster top-k for paired A/B passes in one process (-1: none, 0: off, 1: on).
static OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
pub fn set_override(value: i8) {
OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed);
}
/// The decode window records the cluster top-k: `LELEKA_QSA_CLUSTER=1` / `0`, the per-arm override first, else `default_on`. Read when a
/// stack records its windows. (The driver turns it off again on a card below sm_90.)
pub fn requested(default_on: bool) -> bool {
match OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 => false,
1 => true,
_ => std::env::var("LELEKA_QSA_CLUSTER").map_or(default_on, |v| v == "1"),
}
}
/// 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)
}
#[cfg(test)]
mod tests {
#[test]
fn the_asset_is_the_sealed_one_and_the_dynamic_shared_memory_holds_one_eighth_of_the_keys() {
assert!(super::admit().is_ok(), "qsa_cluster.ptx does not match its pin (reseal with scripts/gpu-bringup/reseal_own.py)");
let text = std::str::from_utf8(&super::PTX[..super::PTX.len() - 1]).expect("PTX is text");
assert!(text.contains(".visible .entry leleka_qsa_topk_cluster("));
assert!(text.contains("barrier.cluster.arrive") && text.contains("mapa.u64"), "the kernel must use cluster barriers and distributed shared memory");
// 65,538 blocks of a 262,144-cell context: 8,193 keys of 4 bytes per CTA
assert_eq!(super::dynamic_smem(65_538), 8_193 * 4);
assert_eq!(super::dynamic_smem(8), 4);
assert_eq!(super::dynamic_smem(9), 8);
}
}
+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
+57 -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,35 @@ 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;
/// Per-arm override of `LELEKA_QSA_TOPK` (-1: none, 0: fast, 1: wide).
static TOPK_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
pub fn set_topk_override(value: i8) {
TOPK_OVERRIDE.store(value, std::sync::atomic::Ordering::Relaxed);
}
/// Default of `LELEKA_QSA_TOPK` (flipped after its R gate).
pub(crate) const TOPK_DEFAULT_WIDE: bool = true;
pub(crate) fn topk_entry(tile_reach: usize) -> (usize, u32) {
static WIDE: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
let wide = match TOPK_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) {
0 => false,
1 => true,
_ => *WIDE.get_or_init(|| match std::env::var("LELEKA_QSA_TOPK").ok().as_deref() {
Some("wide") => true,
Some(_) => false,
None => TOPK_DEFAULT_WIDE,
}),
};
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("leleka-serve qsa prompt top-k: {} (tiles of {} blocks and more), override {}", if wide { "wide" } else { "fast" }, TOPK_WIDE_MIN_BLOCKS, TOPK_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed)));
topk_choice(wide, tile_reach)
}
fn topk_choice(wide: bool, tile_reach: usize) -> (usize, u32) {
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.
@@ -58,6 +98,18 @@ pub(crate) fn usable(context: &crate::Context<'_>) -> bool {
#[cfg(test)]
mod tests {
#[test]
fn the_wide_topk_takes_only_the_long_tiles_and_only_when_asked() {
assert_eq!(super::topk_choice(false, 60_000), (super::TOPK_FAST, 256));
assert_eq!(super::topk_choice(true, super::TOPK_WIDE_MIN_BLOCKS - 1), (super::TOPK_FAST, 256));
assert_eq!(super::topk_choice(true, super::TOPK_WIDE_MIN_BLOCKS), (super::TOPK_WIDE, 1024));
assert_eq!(super::topk_choice(true, 65_538), (super::TOPK_WIDE, 1024));
// the entry indices are the positions in ENTRIES
for (i, name) in [(super::TOPK_FAST, "leleka_qsa_topk_fast"), (super::SCORE_SCAN_FAST, "leleka_qsa_score_scan_fast"), (super::TOPK_WIDE, "leleka_qsa_topk_wide"), (super::TOPK_WIDE_FAILED, "leleka_qsa_topk_wide_failed"), (super::TOPK_SAMPLE, "leleka_qsa_topk_sample")] {
assert_eq!(super::ENTRIES[i].to_str().unwrap(), name);
}
}
#[test]
fn the_asset_is_the_sealed_one_and_exports_its_entries() {
assert!(super::admit().is_ok(), "qsa_late.ptx does not match its pin (re-seal with scripts/gpu-bringup/seal_pins.py)");
+181
View File
@@ -141,3 +141,184 @@ 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); 24] = [
(100, 4, 3, "decode"),
(2_040, 4, 3, "decode"),
(2_049, 5, 1, "decode"),
(3_000, 4, 3, "decode"),
(9_999, 3, 2, "decode"),
(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");
}
}
/// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its
/// top-k at the same shape, to see what the select costs per QSA layer at depth. Prints `QSA-DECODE-SCORES`.
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn decode_scores_are_timed_next_to_the_topk() {
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_decode_scores", c"qsa_topk_ref"]).expect("select module");
guard.finish().expect("finish");
let mut rng = Rng(0x1234_5678_9abc_def1);
for (pos, nq) in [(131_072usize, 4usize), (245_000, 1), (245_000, 4), (245_000, 5)] {
let n_bid_max = (pos + nq) / 4;
let pooled: Vec<f32> = (0..(max_blocks + 1) * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let dead: Vec<f32> = (0..128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let qidx: Vec<f32> = (0..nq * 4 * 128).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect();
let mut steps = Vec::new();
for r in 0..nq {
let p = pos + r;
for x in [p, p + 1, (p + 1) / 4, (p + 1).min(CAP)] {
steps.extend_from_slice(&(x as i32).to_le_bytes());
}
}
let f = |v: &[f32]| v.iter().flat_map(|x| x.to_le_bytes()).collect::<Vec<u8>>();
let (pooled_d, dead_d, qidx_d, steps_d) = (upload(&context, &f(&pooled)), upload(&context, &f(&dead)), upload(&context, &f(&qidx)), upload(&context, &steps));
let scores_d = upload(&context, &vec![0u8; nq * max_blocks * 4]);
let ids_d = upload(&context, &vec![0xffu8; nq * CAP * 4]);
let h = |b: &DeviceBuffer<'_>| b.handle.expect("handle");
let guard = context.enter().expect("enter");
let time = |run: &mut dyn FnMut()| -> f64 {
run();
context.driver.api.synchronize().expect("sync");
let t0 = std::time::Instant::now();
for _ in 0..20 {
run();
}
context.driver.api.synchronize().expect("sync");
t0.elapsed().as_secs_f64() * 1e6 / 20.0
};
let mut sa = KernelArguments::new(vec![A::Address(h(&pooled_d)), A::Address(h(&dead_d)), A::Address(h(&qidx_d)), A::Address(h(&steps_d)), A::I32(nq as i32), A::I64(max_blocks as i64), A::Address(h(&scores_d))]);
let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores"));
let mut ta = 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_d))]);
let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk"));
guard.finish().expect("finish");
eprintln!("QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)");
}
}
@@ -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
@@ -237,13 +237,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 +384,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],
@@ -433,6 +419,13 @@ pub(crate) static COMPANIONS: &[Companion] = &[
sha: [0xf5, 0x4e, 0xea, 0xa6, 0xeb, 0x53, 0xa4, 0xd5, 0x02, 0x34, 0x4f, 0x90, 0x8f, 0x97, 0x65, 0xaa, 0xdf, 0x44, 0x53, 0x77, 0xd4, 0x3a, 0x70, 0x53, 0x23, 0x59, 0xfe, 0xe2, 0x33, 0xa0, 0x06, 0x73],
ptx: concat!(include_str!("../ptx-sm86/q6_batch_preview.ptx"), "\0").as_bytes(),
},
Companion {
name: "prefill_stage.ptx",
key: [0x6f, 0x8f, 0xb3, 0xbb, 0xd1, 0x11, 0x71, 0xc9, 0x39, 0x02, 0x97, 0xd5, 0xd2, 0xc9, 0xcb, 0x90, 0x76, 0xd4, 0xb6, 0x51, 0xf2, 0xa7, 0x04, 0x2b, 0xf1, 0x6f, 0x4c, 0xaf, 0x89, 0xa5, 0xb3, 0x84],
len: 161928,
sha: [0xd8, 0x1a, 0x87, 0x43, 0x7b, 0x72, 0x6b, 0xcf, 0x1a, 0x9d, 0xf0, 0xca, 0x6d, 0x5e, 0xbe, 0xdf, 0x5c, 0x06, 0xda, 0xce, 0xe6, 0x88, 0xbd, 0xc8, 0xfe, 0x91, 0x78, 0x91, 0xcc, 0x0c, 0xda, 0x4b],
ptx: concat!(include_str!("../ptx-sm86/prefill_stage.ptx"), "\0").as_bytes(),
},
Companion {
name: "original_verify_window_pcie_fast.ptx",
key: [0x74, 0x07, 0x85, 0x9f, 0x8d, 0x88, 0x81, 0x66, 0x3f, 0x3a, 0x64, 0x6e, 0xbe, 0x28, 0x8c, 0x31, 0x13, 0x8c, 0xce, 0x32, 0x27, 0xc1, 0xc5, 0xd9, 0xe2, 0xe5, 0x92, 0x64, 0x8e, 0xd7, 0x7a, 0xea],
@@ -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],
@@ -92,6 +92,7 @@ fn original_serve_replay_smoke() {
// the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, grid = chunk) or `reply@8192/2048`
let mut down_override: i8 = -1;
let mut tail_flag: Option<u32> = None;
let (mut gdn_flag, mut topk_flag, mut cluster_flag, mut nostore_flag, mut sized_flag): (i8, i8, i8, i8, i8) = (-1, -1, -1, -1, -1);
let (arm_mode, arm_capacity, arm_block, arm_tiers): (String, usize, usize, Option<bool>) = match arm.split_once('@') {
Some((mode, shape)) => {
// flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: the stack's), `w8` (the previous
@@ -101,6 +102,14 @@ fn original_serve_replay_smoke() {
down_override = if flags.split('!').any(|f| f == "w8") { 0 } else { -1 };
// `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = off); without it the environment decides
tail_flag = flags.split('!').find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::<u32>().expect("arm flag !tailN"));
// docs/upstream-port-plan.md rows 2.4 / 2.5: `kh` / `rec` / `orig` (the prompt GDN recurrence: the three-value-heads kernel, the two-barrier kernel,
// the sealed Original one), `wide` / `fast` (the prompt top-k), `cluster` / `nocluster` (the decode window's top-k on a thread-block cluster)
let has = |name: &str| flags.split('!').any(|f| f == name);
gdn_flag = if has("kh") { 1 } else if has("rec") { 2 } else if has("orig") { 0 } else { -1 };
topk_flag = if has("wide") { 1 } else if has("fast") { 0 } else { -1 };
cluster_flag = if has("cluster") { 1 } else if has("nocluster") { 0 } else { -1 };
nostore_flag = if has("nostore") { 1 } else if has("store") { 0 } else { -1 };
sized_flag = if has("sized") { 1 } else if has("uniform") { 0 } else { -1 };
let (cap, block) = shape.split_once('/').unwrap_or((shape, "0"));
(mode.to_owned(), cap.parse::<usize>().expect("arm chunk: mode@CAP[/BLOCK]"), block.parse::<usize>().expect("arm grid: mode@CAP[/BLOCK]"), tiers)
}
@@ -108,6 +117,11 @@ fn original_serve_replay_smoke() {
};
let arm = &arm_mode;
leleka_cuda_driver::set_chain_down_override(down_override);
leleka_cuda_driver::set_prefill_gdn_override(gdn_flag);
leleka_cuda_driver::set_qsa_topk_override(topk_flag);
leleka_cuda_driver::set_qsa_cluster_override(cluster_flag);
leleka_cuda_driver::set_prefill_gdn_nostore_override(nostore_flag);
crate::qwen_forward::original_cache_startup::set_sized_override(sized_flag);
crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail_flag);
eprintln!("REPLAY-ARM start label={label} mode={arm} capacity={arm_capacity} block={arm_block} tiers={}", arm_tiers.map_or("default", |on| if on { "on" } else { "off" }));
let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
@@ -55,14 +55,37 @@ impl Geometry {
Ok(Self{layer_bytes,max_blob})
}
}
struct Plan{slots:usize,sizes:Vec<usize>,blob:usize}
/// `layers`: the per-layer plan (`--expert-cache-per-layer` on a native pack, generate.cpp ~6333): `quota` slots of EACH layer's own blob
/// size, in layer order (layer l owns slots l * quota .. (l + 1) * quota, the table's ranges), instead of `slots` slots of the largest blob.
/// Per-arm override of `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED` for paired passes in one process (-1: none, 0: uniform slots, 1: each layer's own blob size).
static SIZED_OVERRIDE:std::sync::atomic::AtomicI8=std::sync::atomic::AtomicI8::new(-1);
pub(crate) fn set_sized_override(value:i8){SIZED_OVERRIDE.store(value,std::sync::atomic::Ordering::Relaxed);}
fn sized_per_layer()->bool{
match SIZED_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed){0=>false,1=>true,_=>std::env::var("LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED").map_or(true,|v|v!="0")}
}
struct Plan{slots:usize,sizes:Vec<usize>,blob:usize,layers:Option<(usize,[usize;48])>}
impl Plan {
fn bytes(&self)->Result<usize>{
if self.sizes.is_empty(){self.slots.checked_mul(self.blob).ok_or(Error::Overflow)}
else{self.sizes.iter().try_fold(0usize,|n,&s|n.checked_add(align(s)?).ok_or(Error::Overflow))}
}
/// The per-layer list for `quota` slots per layer.
fn per_layer_sizes(quota:usize,layer_bytes:&[usize;48])->Result<Vec<usize>>{
let mut sizes=Vec::new();
sizes.try_reserve_exact(quota.checked_mul(48).ok_or(Error::Overflow)?).map_err(|_|Error::InputAllocation)?;
for &b in layer_bytes{for _ in 0..quota{sizes.push(b);}}
Ok(sizes)
}
fn shrink_to(&mut self,keep:usize)->Result<bool>{
if keep==0{self.slots=0;self.sizes.clear();return Ok(false);}
if let Some((quota,layer_bytes))=&mut self.layers{
// the same quota of every layer that fits `keep` (a truncated list would shift the layers' slot ranges)
let sum=layer_bytes.iter().try_fold(0usize,|n,&b|n.checked_add(align(b)?).ok_or(Error::Overflow))?;
*quota=(keep/sum).min(512);
if *quota==0{self.slots=0;self.sizes.clear();return Ok(false);}
self.sizes=Self::per_layer_sizes(*quota,layer_bytes)?;self.slots=self.sizes.len();
return Ok(true);
}
if self.sizes.is_empty(){self.slots=keep/self.blob;}
else{
let (mut used,mut count)=(0usize,0usize);
@@ -100,7 +123,20 @@ pub(crate) fn open<'ctx>(binding:&ModelBinding,context:&'ctx Context<'ctx>,optio
free.saturating_sub(reserved)/geometry.max_blob
}else{options.slots as usize};
if auto{if let Some(profile)=profile.filter(|p|!p.is_empty()){slots=slots.min(profile.pairs.len());}}
let mut plan=Plan{slots,sizes:Vec::new(),blob:geometry.max_blob};
let mut plan=Plan{slots,sizes:Vec::new(),blob:geometry.max_blob,layers:None};
// Row "5090 gap to vanilla": the per-layer cache took `slots` slots of the LARGEST layer blob (2.54 MiB; 8,702 slots in 21.6 GiB) where the Original
// (and vanilla Strata) give each layer slots of its own blob size (about 1.94 MiB on average; 12,575 slots in 23.9 GiB with the profile). Same VRAM,
// 30 % more resident experts. LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED=0 keeps the uniform slots (the A/B arm).
if options.per_layer&&slots>0&&sized_per_layer(){
let free=context.memory_info().map_err(driver)?.0;
let cap=slots.checked_mul(geometry.max_blob).ok_or(Error::Overflow)?.min(free.saturating_sub(reserve));
let sum=geometry.layer_bytes.iter().try_fold(0usize,|n,&b|n.checked_add(align(b)?).ok_or(Error::Overflow))?;
let quota=(cap/sum).min(512);
if quota>0{
plan.sizes=Plan::per_layer_sizes(quota,&geometry.layer_bytes)?;plan.slots=plan.sizes.len();
plan.layers=Some((quota,geometry.layer_bytes));
}
}
if let Some(profile)=profile.filter(|p|!p.is_empty()&&!options.per_layer&&slots>0){
// Original rereads the card before sizing variable slots.
let free=context.memory_info().map_err(driver)?.0;
@@ -140,3 +176,48 @@ pub(crate) fn open<'ctx>(binding:&ModelBinding,context:&'ctx Context<'ctx>,optio
}
unreachable!()
}
#[cfg(test)]
mod per_layer_plan_tests {
use super::*;
fn layer_bytes() -> [usize; 48] {
let mut b = [2_000_000usize; 48];
b[3] = 2_660_000;
b[47] = 1_500_000;
b
}
#[test]
fn the_per_layer_list_is_a_quota_of_every_layers_own_blob_in_layer_order() {
let lb = layer_bytes();
let sizes = Plan::per_layer_sizes(5, &lb).unwrap();
assert_eq!(sizes.len(), 5 * 48);
for layer in 0..48 {
assert!(sizes[layer * 5..(layer + 1) * 5].iter().all(|&s| s == lb[layer]), "layer {layer} owns slots layer * quota ..");
}
}
#[test]
fn a_shrunk_per_layer_plan_keeps_the_layer_ranges_and_fits_the_bytes() {
let lb = layer_bytes();
let quota = 100;
let sizes = Plan::per_layer_sizes(quota, &lb).unwrap();
let mut plan = Plan { slots: sizes.len(), sizes, blob: 2_660_000, layers: Some((quota, lb)) };
let before = plan.bytes().unwrap();
assert!(plan.shrink_to(before / 4 * 3).unwrap());
let q = plan.slots / 48;
assert_eq!(plan.slots, q * 48);
assert!(q < quota && q > 0);
assert!(plan.bytes().unwrap() <= before / 4 * 3);
for layer in 0..48 {
assert!(plan.sizes[layer * q..(layer + 1) * q].iter().all(|&s| s == lb[layer]));
}
assert!(!plan.shrink_to(0).unwrap());
}
#[test]
fn the_sized_per_layer_cache_holds_more_experts_than_slots_of_the_largest_blob_in_the_same_bytes() {
let lb = layer_bytes();
let bytes = 21 << 30;
let uniform = bytes / 2_660_000;
let sum: usize = lb.iter().map(|&b| align(b).unwrap()).sum();
assert!((bytes / sum) * 48 > uniform);
}
}
@@ -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 = true;
/// 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 = leleka_cuda_driver::qsa_cluster_requested(QSA_CLUSTER_DEFAULT);
let recorded = verifier.record_all(
policy,
|t| windows.get_mut(t - 1).and_then(Option::take).ok_or(leleka_cuda_driver::Error::InvalidQwenShape),
+85 -2
View File
@@ -38,8 +38,8 @@ the run-to-run control); **L** live Codex session.
| 2.1 | sm_120 bitwise decode set (`SIDE_MIXER=2`, `ATTN_DAILY`, `GR_UP75`, `GR_DOWN_TG=1`, `GU_SWIGLU`; interleaved MMVQ 2-4 columns; `ba2c2d5f`, `94104176`, `75afe3f4`, `ffac97f7`, ...) | compare each against our chain kernels / MMVQ; port what is not already ours | I, R | diff list below, nothing implemented |
| 2.2 | #783 decode series and F7 ports (multi-token router, float4 combine, fused per-head RMSNorm+RoPE, batched K/V append, exact-T GDN, MTP catch-up skipping rejected rows, late shared-expert fork, multi-block argmax) | diff the list against `docs/chain-kernels.md`; port the missing | I, R | diff list below, nothing implemented |
| 2.3 | CPU expert rows (`2a669f3c`, `79376a27`, `16c4da94`, `5ece068f`): router accumulators in registers, Q5_1/Q8_0 down-row dots, 512-bit gathers, default worker count | copy job into `crates/native-cpu-expert` | U, R | **3 of 4 sub-items do not apply to this model and these CPUs; worker plan ported opt-in**; see Results |
| 2.4 | Bitwise prefill kernels (`4e69f974`, `c675f5b7`, `5f843a92`): GDN 3 value heads per thread, quantize each token's MoE input once, `DEQUANT_WIDE` | port the prefill kernels | I, R | todo |
| 2.5 | QSA top-k at long context (wide kernel past 135K cells, cluster top-k on sm_90+; `586367cb`, `d05d26e9`, `6ef23b89`) | compare with our `qsa_late`; keep the better | I, R | todo |
| 2.4 | Bitwise prefill kernels (`4e69f974`, `c675f5b7`, `5f843a92`): GDN 3 value heads per thread, quantize each token's MoE input once, `DEQUANT_WIDE` | port the prefill kernels | I, R | **done, see Results 2026-10-27**: `gdn_rec_kh` opt-in (-6 % per launch, not worth enabling), GDN out-norm without the dead store (on, bit-identical, ~1 % of the GDN stage), quantize-once and `DEQUANT_WIDE` not ported (reasons in the analysis table) |
| 2.5 | QSA top-k at long context (wide kernel past 135K cells, cluster top-k on sm_90+; `586367cb`, `d05d26e9`, `6ef23b89`) | compare with our `qsa_late`; keep the better | I, R | **done, see Results 2026-10-27**: wide prompt top-k (QSA stage -4 % at chunk 2048, -6 % at 8192 in the replay) and the cluster decode top-k (window -8..-10 % per round in the replay, bit-identical) are the defaults |
| 2.6 | WSL KV host copy pinned with `cudaHostRegister` (`c41c0ebb`) | laptop only | L (laptop) | todo |
## Phase 3: output-changing, experimental flags (each needs its own quality gate)
@@ -90,6 +90,89 @@ Diff list above; no implementation, nothing measured.
### Not verified / not done
The 30-pass A/Bs (3 repetitions for 3.1, none for 0.6 because the mechanism is absent), the 256k-class A/B, the 2048-slot quality gate, anything on the laptop GPU. `cargo build/test` was not run on this laptop (by instruction); all builds and unit tests ran on the server from a tarball of the worktree.
## Rows 2.4 / 2.5: analysis (2026-10-27, branch `claude/upstream-rest`, from `claude/port-gpu-bringup` c40531f)
Method: read the upstream sources (`engine/strata/src/prefill/kernels.cu`, `src/kernels/cuda/qsa_select.cu`, `moe_mmq.cu`, `prefill.cpp`) against ours (`crates/cuda-driver/src/prefill_stage.cu`,
`qsa_late.cu`, `qsa_resident_index_program.rs`, the sealed `qsa_prompt_select.ptx` that the decode window launches as `qsa_topk_ref`). The upstream repository has no history in our tree, so the
commits are identified by content. Where the 256k workload stands (`night5-long-256k`, job on 2026-10-27, 5090): a 5-turn session to 243k tokens has TTFT 25.2-30.6 s per turn (chunk 2048,
per-layer ring: expert DMA dominates, 0.8-1.1 s of a ~1.2 s chunk) and decode 80-103 tok/s against 130-170 at short context. Two different things can move at depth: the prompt stages whose
cost grows with the position (QSA index: scores, top-k) and the decode window's QSA select (one `qsa_topk_ref` CTA per query, 12 layers).
| Item | Upstream | What we have | Verdict |
|---|---|---|---|
| GDN recurrence, 3 value heads per thread (`4e69f974`) | `gdn_rec_kh_kernel`: 64 blocks, cp.async blocks of 8 tokens, 2 barriers per token | the Original's `gdn_rec_cols_pipe` (192 blocks, 5 barriers) and our opt-in two-barrier `leleka_prefill_gdn_rec` | **ported** (`leleka_prefill_gdn_rec_kh`, opt-in): bit-identical, but only -6 % per launch on the 5090 (see Results); 64 blocks on 170 SMs leaves the card two thirds idle |
| no dead FP32 store in the GDN output norm | `gdn_out_norm` without the `y` store | `leleka_prefill_gdn_out_norm` writes `y` (nothing reads it afterwards: the projection takes `y16`) | **ported** as `leleka_prefill_gdn_out_norm_y16`, bit-identical y16 and status words |
| quantize each token's MoE input once, scatter to the K rows (`c675f5b7`) | `quantize_scatter_mmq_q8_1_cuda` instead of a gather over T*K rows | ggml `quantize_mmq_q8_1` with the id gather over T*K rows (sealed Original MMQ asset) | **not ported**: upstream's own number is 77.5 -> 58.1 ms for a 32K prompt on a 5090, i.e. at most ~5 ms of an 8192-token chunk (0.3 %), and it needs a new kernel in the MMQ q8_1 layout plus the inverse slot map |
| `DEQUANT_WIDE` (`5f843a92`) | wide dequantization of Q4_K/Q5_K/Q6_K/IQ4_XS, default on sm_86/sm_61 only | our `leleka_prefill_dequant_*` already run one thread per element (9 ms per chunk on the 5090, 36 ms per 2048-token chunk on the 3080) | **not applicable** to sm_120; a thread-per-8-values variant could only matter on the 3080 (not measured) |
| QSA top-k, 1,024-thread kernel past ~135K cells (`586367cb`) | `block_topk_wide_kernel` (per-warp histograms, 4 radix passes + count + emit) | `qsa_topk_ref` (Original, 256 threads, 704-byte stride between lanes) and our `leleka_qsa_topk_fast` (256 threads, coalesced, 6 passes) | **ported**, faster than `fast` from ~10k blocks (-45 % at 180k, -49 % at 245k per 256-row tile); upstream's one-read `sample` kernel measured and not used |
| QSA top-k on a thread-block cluster, sm_90+ (`d05d26e9`) | `block_topk_cluster_kernel`: 8 CTAs of 1,024 threads per query, histograms pushed through distributed shared memory | the decode window launches `qsa_topk_ref` with one 256-thread CTA per query (12 layers per window) | **ported** (`qsa_cluster.cu`, `cuLaunchKernelEx` inside the captured window): 183 -> 19.5 us per call at 245k tokens (4 queries) in the model-free probe |
| cluster greedy argmax (`6ef23b89`) | `sampler.cu` | one block per token, 79 us per window (`docs/chain-kernels.md`) | row 2.1/2.2 item, tier 2 |
## Project Maya (github.com/Ajay9o9/project-maya, MIT; analysis 2026-10-27, owner's request)
A Strata fork rewritten for GLM-5.3-Flash (321B MoE, DSA sparse attention, KDA layers, NextN MTP). Read: the README and the sources at commit `10b7b07` (shallow clone kept outside the tree; the
code that matters is `src/core/glm_fast_path.cu`, `glm_prefill.cu`, `src/kernels/cuda/glm_batch.cu`, `src/kernels/cpu/kq_avx512.cpp`, `src/program/generate.cpp`). Every number below is Maya's claim on Maya's
hardware (3090, V100, 4090, GLM), not ours. Their model is not ours: the indexer has 32 heads, the MTP block is a GLM NextN block with RAM-tier experts, the expert formats are Q3_K/Q2_K. Ranked by
expected value for the Qwen3.8-Flash-Next IQ3_S pack on the 5090 (primary) and the laptop:
| Rank | Candidate (Maya switch) | Maya claims | What we have | Verdict |
|---|---|---|---|---|
| 1 | (g) Next-layer expert prestaging while attention runs (`STRATA_GLM_PRESTAGE`, prompt ring; `PREFETCH_N/RANK/AT` for decode), (f) conversation state on SSD (`STRATA_GLM_SLOTS`: 4K tokens resume in 0.2 s instead of a re-read) | prefetch decode 19.64 -> 20.22 tok/s on 3090+3060; no number for prestage | prompt: the per-layer ring plus `stream_all` from 4096 rows (already overlaps the next layers' DMA with the mixers); decode: router lookahead (`LELEKA_CPU_POOL_LOOKAHEAD`, opt-in), adaptive tier. Prefix cache and conversation cache are RAM only | (f) is the one with a 256k payoff: a 245k re-read is 25-40 s of TTFT (night5) against seconds from an SSD slot; it is the tiered-cache epic STRA-236, not a kernel port. (g): small; the stream already does it above 4096 rows; for chunk 2048 the per-layer ring could prefetch layer l+1's routed set only after its router runs (the same limit Maya has). Not started |
| 2 | (d) Multi-token AVX-512 Q3_K/Q2_K CPU kernel (`kq_avx512.cpp`, `STRATA_GLM_KQ`, ~2x ggml from 8 tokens per expert) | prompt-path CPU experts | `crates/native-cpu-expert`: IQ3_S/IQ4_NL (our pack) and Q2_0 kernels with RUNTIME dispatch AVX2 (`iq_avx2`, `q2_avx2`) / AVX-512 (`iq512`, `avx512_ok()`: F/BW/VL/DQ + XCR0) | **does not apply to our pack**: Maya's kernel is for Q3_K/Q2_K weights and for prompt-path CPU experts; our prompt experts run on the GPU (MMQ) and decode has 1-4 tokens per expert, below Maya's break-even of 8. What it exposes is a gap in our CPU tiers (next paragraph) |
| 3 | (a) Sparse-attention indexer as FP32 register-tiled GEMM (`STRATA_GLM_DSA_SCORE`, 78.8 -> 5.6 ms at 4096 tokens, position 10K, 3090) and the mma.sync prompt attention (`STRATA_GLM_PREFILL_ATTN`, 832 -> 966 tok/s at 26.6K) | against Maya's warp-per-pool kernel | our indexer scorer is already the Original's TF32 3-pass tensor-core kernel (`block_scores_tc_kernel`, 0.34 ms per 256-row tile at 147k tokens) and the prompt attention is already `mma` (113 ms per 8192-token chunk, ledger); the select was the top-k, now ported (row 2.5) | **already ahead of the baseline Maya fixes**; folded into row 2.5: after the wide top-k the late-chunk QSA index is scores 131 + top-k ~45 ms of ~1.9 s. The tile size and 3xTF32 split of the scorer (7 TFLOP/s on 2.4 GFLOP) are the only headroom; not bitwise-safe to touch (the Original's score bits decide near-tie selections) |
| 4 | (c) Promotion of a fetched hot RAM-tier expert into VRAM only when its aged route count clears `PROMOTE_MIN` | stops churn on a 4090 with 128 GB RAM; hurts with little RAM (29.6 -> 28.3 tok/s on 30 GB) | adaptive swaps (`ADAPT_EVERY/SWAPS`): replace the least-routed residents of a layer while the gain >= 1.5, counts decay 0.7 (hysteresis already) | equivalent mechanism; revisit only if the e2e traces show swap churn at 256k (job 9r1 / telemetry `swaps`). No port |
| 5 | (b) Draft-expert filter (`STRATA_GLM_MTP_KEEP`: the NextN draft fetches only its best-scored missing experts) | acceptance 76-81 -> 82-83 %, decode +5 % on 3090+3060 | the Qwen MTP block's experts are one `n_expert * BLOB` device allocation (`original_mtp_bank.rs`): the draft has no misses | **not applicable** on the 5090 and (if the MTP bank is device resident there too) on the laptop; to be re-checked on the 3080 profile (docs/laptop-profile.md) before closing |
| 6 | (e) Idle spin sleep for pool threads (`SERVICE_IDLE_MS`) | idle engine 1 % of a core instead of one core per GPU | `rust_general_pool.rs` workers spin `self.spin` and then park on a condvar; `pool_plan` sizes the workers to physical cores | **already have** (not measured idle CPU here) |
CPU tiers (owner's rule: runtime dispatch, the AVX2 path stays the default and keeps being tuned, bit-identical integer dot products, nothing requires AVX-512 at build or run time). State of
`crates/native-cpu-expert` on 2026-10-27, from the sources (no CPU measurement made): (1) **AVX2 baseline**: present for IQ3_S/IQ4_NL/Q2_0 (`iq_avx2.cpp`, `q2_avx2.cpp`, `kq_avx2.cpp`,
`rust_simd::avx2_ok`); (2) **AVX2 + AVX-VNNI (256-bit `vpdpbusd`)**: **missing** as a runtime tier. `rust_ggml_native.rs` probes cpuid 7.1 EAX bit 4 but only as a compile-time `cfg!(target_feature = "avxvnni")` branch of
ggml's types, so the binary neither uses it on an Alder/Raptor Lake/Core Ultra part nor requires it; the IQ dot kernels use `maddubs + madd`; (3) **AVX-512(+VNNI)**: present with runtime dispatch
(`Dispatch.iq512`, `avx512_ok()`; `STRATA_FORCE_AVX2=1` forces tier 1), the Q2_0 S2 path in `expert.cpp` is the VNNI-512 reference. The decode CPU legs are memory-bound (about 39 GB/s of 52, `expert.cpp`
comment), so an AVX-VNNI tier saves ALU work, not bytes: expect a gain only where the pool is compute-bound (laptop, 8 workers on 4-6 cores). A tier 2 would be an additional `#[target_feature(enable = "avx2,avxvnni")]`
variant of the IQ3_S/IQ4_NL dots selected by cpuid 7.1 EAX bit 4 + XCR0, integer-exact against tier 1 (same int32 sums, so bit identity by construction), measured with `rust_bench` on the laptop: **todo, not started**.
Conclusion: nothing from Maya survives as a kernel port for the 5090 beyond what row 2.5 already took; the two items worth a task are the SSD conversation state (f, STRA-236) and the AVX-VNNI CPU tier (laptop).
## Results of the 2026-10-27 session (branch `claude/upstream-rest`, server `rnr5090`, RTX 5090 + Ryzen 9 9950X3D, driver 595.99.02, CUDA 13.2.2, Qwen3.8-Flash-Next IQ3_S + KAR level 2 pack, MTP pack `data/mtp-rt`)
### Rows 2.4 / 2.5 (gates I and R)
* **U**: `leleka-cuda-driver` lib 395 passed (`--features "cuda-driver sm86"`), `leleka-runtime` lib 631 passed (server, release).
* **I, kernels (model-free, `qsa_late::gpu_tests`, `prefill_stage_gdn_gpu`)**: every top-k variant (`fast`, `wide`, `sample` + `wide_failed`, `cluster`) writes the same ids as the Original's `qsa_topk_ref`, whole output buffer, in 24 cases (prompt tiles of 256 rows and decode calls of 1..5 rows, positions 100..261,500, continuous / heavy-tailed / 16 tied levels / all equal scores, the `n_kv <= width` identity branch included). `leleka_prefill_gdn_rec_kh` equals the Original's `gdn_rec_cols_pipe` in state, readout and witness for t = 1, 2, 7, 8, 9, 200, 1500, 2048, 8192 and for an infinite state, a NaN input and an overflow. The no-store out-norm writes the same `y16` and the same four status words (3 cases incl. non-finite inputs).
* **I, end to end (job `rest-id-256k`, replay of `night5-long-256k`, 5 requests 45,766..242,849 tokens, teacher forced, static tier, one CPU worker, fixed window; 8 arms in one process: baseline, kh, two-barrier rec, wide, cluster, all, no-store, baseline again):** `q_tail_gate` over 1,502 forced rows: d_top1 median / p99 / max 0.0000 and 0 argmax flips for all 7 arms against the baseline. The final-residual hashes of the first 100 prefill chunks (requests 0..3, up to 198k tokens) are equal in all arms; request 4 starts from another prefix-cache checkpoint in five of the arms (reused 194,560 instead of 196,608 tokens: the auto prefix budget under host memory pressure), so its chunk hashes are not comparable (its logprob rows are equal anyway).
* **R, kernel level (model-free, warm, mean of 20 launches):** wide against fast top-k per 256-row tile: 91.7 vs 144.6 us at 100k, 138 vs 251 us at 180k, 172 vs 334 us at 245k tokens (equal below ~32k tokens); decode top-k `qsa_topk_ref` vs cluster per call (1..5 queries): 157 vs 17 us at 131k, 183 vs 19.5 us at 245k tokens, 12 QSA layers per window; `qsa_decode_scores` is 14-52 us at the same depths (not the cost). GDN recurrence per 8192 tokens and layer: Original 4.31 ms, two-barrier 3.91, kh 4.04 (the 5090 is latency bound at 4.5 warps per SM; upstream's kh kernel was tuned for 64-80 SM cards).
* **R, replay A/B (job `rest-ab-256k`, `night5-long-256k` replayed in one process, fresh stack per arm, teacher forced, production env, prefix cache 20,000 MiB; B/X/K at chunk 2048 and D/Y at chunk 8192, 3 repetitions per arm; X/Y = wide + cluster + no-store, K = kh only):** host load made the wall times useless (B: 132..273 s for the same work, swap at 40 GB), so the PREFILL-PROFILE stage sums (sd < 1 %) and the decode window time are the measurements. QSA stage: 18,247 -> 17,491 ms (-4.1 %, chunk 2048), 13,846 -> 13,059 ms (-5.7 %, chunk 8192; -7 % past 100k tokens). GDN stage: kh -1 %, no-store -1 % (chunk 8192). Decode `round.run_window` per round: B 19.5 / 20.4, X 18.0 / 18.0 / 18.5 ms (-8..-11 %); decode tok/s 83.2 / 82.7 (B) against 93.5 / 93.0 / 90.1 (X). The kh kernel alone (K) shows no stage gain worth a default.
* Quantize-once and `DEQUANT_WIDE` were not ported (analysis table above): bounded by 0.3 % of a chunk and sm_86-only.
### The 5090 gap to vanilla Strata on the 256k session (owner's priority item, 2026-10-27 evening)
Same text (`long_session.py`, 5 turns to ~245k tokens, 300 output tokens), TTFT s / decode tok/s per turn (`scripts/upstream-rest/turns.py`):
| run | turn 1 | 2 | 3 | 4 | 5 | sum TTFT | mean decode | wall |
|---|---|---|---|---|---|---|---|---|
| night5 (chunk 2048, uniform per-layer slots) | 26.0 / 88.9 | 26.8 / 91.1 | 30.6 / 85.8 | 25.2 / 102.6 | 25.7 / 80.0 | 134.3 | 89.7 | 151 s |
| night6 (chunk 8192) | 12.7 / 88.7 | 11.5 / 96.1 | 13.6 / 83.3 | 12.0 / 91.8 | 11.0 / 92.3 | 60.7 | 90.4 | 77.6 s |
| rest-before1 (night6 config, new binary, branch features off) | 14.2 / 83.3 | 12.2 / 96.8 | 13.8 / 79.2 | 12.4 / 90.7 | 11.2 / 77.5 | 63.8 | 85.5 | 81.6 s |
| rest-before2 | 10.7 / 91.8 | 11.3 / 94.2 | 14.0 / 80.2 | 12.4 / 90.1 | 10.9 / 81.3 | 59.2 | 87.5 | 76.6 s |
| rest-after1 (sized per-layer cache only: the defaults flip of the kernels had not reached the server) | 11.3 / 104.3 | 11.5 / 104.8 | 13.3 / 97.4 | 11.9 / 115.6 | 10.9 / 91.6 | 58.8 | 102.7 | 73.8 s |
| rest-after2 | 15.0 / 95.1 | 13.9 / 109.4 | 13.3 / 99.9 | 12.1 / 113.1 | 10.9 / 90.0 | 65.2 | 101.5 | 80.3 s |
| rest-full1 (all branch defaults: sized cache + cluster decode top-k + wide prompt top-k + no-store out-norm) | 11.3 / 105.3 | 11.2 / 112.4 | 13.0 / 112.8 | 11.5 / 121.7 | 10.5 / 104.4 | 57.6 | 111.3 | 71.3 s |
| rest-full2 | 11.0 / 105.2 | 11.2 / 109.3 | 13.2 / 110.3 | 11.5 / 126.2 | 10.5 / 102.8 | 57.3 | 110.7 | 71.2 s |
| night7 (global slots, `PER_LAYER=no`, night binary, owner's job) | 13.6 / 103.7 | 11.6 / 100.4 | 13.8 / 90.5 | 13.4 / 96.6 | 10.9 / 92.0 | 63.3 | 96.6 | 79.0 s |
| vanilla Strata 0.2.6 / engine 0.1.50 | 6.9 / 121.7 | 8.3 / 144.2 | 9.4 / 147.7 | 8.2 / 164.4 | 8.5 / 194.3 | 41.3 | 154.5 | 51.2 s |
The first `rest-after*` pair measured the sized cache alone: I committed the defaults flip of the three kernels and then synced the server tree from `git ls-files -m`, which no longer listed the committed files, so those binaries still had cluster / wide / no-store off (found when the log line `leleka-serve qsa prompt top-k` was missing from the binary; `sync-rest` now diffs against the base commit). `rest-full*` are the real defaults, with the kernels confirmed by `leleka-serve qsa prompt top-k: wide` and `qsa decode top-k: thread-block cluster` in the engine log.
Findings (runs `rest-before*`, `rest-after*`, `rest-full*` under `~/work/leleka-e2e/runs/`; before = the same binary with `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED=0 LELEKA_QSA_CLUSTER=0 LELEKA_QSA_TOPK=fast LELEKA_PREFILL_GDN_NOSTORE=0`):
1. **Chunk 8192 is the prefill fix** (night5 -> night6: 134 -> 61 s of TTFT); it is not the default of the shipped deploy profile yet.
2. **Slot sizing, root cause.** `run-e2e.sh` (and the `rtx5090-32g` profile `engine_env`) set `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes`. `original_cache_startup::open` took the profile-sized path only for `!per_layer`; with per-layer it opened `slots` slots of the LARGEST layer blob (2.54 MiB; 8,701 slots in 21.57 GiB) with per-layer admission, while the Original's per-layer plan (generate.cpp ~6333, #369) gives every layer `quota` slots of its OWN blob (1.94 MiB average). Fixed: the same VRAM now holds **11,280 slots** (21.50 GiB; the Original/vanilla reach 12,575 in 23.87 GiB because they have 2.2 GiB more free before the cache). `LELEKA_ORIGINAL_SERVE_PER_LAYER_SIZED=0` restores the uniform plan. The output is not bit-identical to the uniform plan (more experts run on the GPU, which rounds differently from the CPU): quality gate `rest-q-256k`.
3. **Decode +28 %** (mean over the turns 85.5 / 87.5 before -> 111.3 / 110.7 tok/s with all defaults): the sized cache alone gives +17 % (102.7 / 101.5; `round.run_window` 19.2 -> 18.4 ms per round, 697 rounds against 787), the cluster top-k adds +9 % (16.9 / 16.0 ms per round, i.e. -12 % against before; QSA decode select was 12 x ~180 us per window). Per-layer sized slots (102 tok/s) are as good as global admission (night7, 96.6 tok/s, old binary): the per-layer admission is not what held decode back, the slot size was. Still 1.4x behind vanilla (154.5 tok/s; its round is ~14 ms). Vanilla's route-tail skip (lossy, on by default) is not copied.
4. **Prefill is still 1.4x behind vanilla** (59-65 s against 41 s of TTFT). Per chunk of 8192 at position 139k (PREFILL-PROFILE): gdn 469, qsa 468, moe 654 (ring 456, prepare 123), total 1,677 ms. The session totals hardly moved between before and after (qsa 13.85 -> 13.76 s, moe.ring 15.6 -> 15.4 s). **`moe.ring` did not change when the resident slots went from 8,701 to 11,280**: our prompt path streams every expert of every layer through the ring whatever is resident (docs/prefill-throughput.md: the tier removes 0.6 % of the entries); vanilla's `stream_all` streams only the non-resident experts, reads the resident ones in place (`STRATA_MMQ_DIRECT`, `mmq_resident_sort.hpp`) and runs the prompt experts on the fused int8 kernels (`STRATA_PF_FUSED=1`, row 3.2, lossy). That is the next item: a pointer-table MMQ for resident experts would take roughly half of the 15.4 s of ring time off the session (11,280 of 24,576 experts are resident). Not started.
5. The wide prompt top-k shows in the e2e as the QSA stage: 13.85 s (before) -> 12.99 / 12.98 s (full), -6.2 %, as in the replay; TTFT sum 63.8 / 59.2 -> 57.6 / 57.3 s (-5..-10 %, inside the turn-to-turn noise of 1-2 s). Prefill is untouched otherwise (moe.ring 15.4 s, gdn 14.7-15.2 s of a 54.4 s prefill total).
6. **Quality gate Q (job `rest-q-256k`, replay of `night5-long-256k`, teacher forced, production env: adaptive tier, 15 CPU workers, chunk 8192, prefix budget 6,000 MiB, top-16 log-probabilities, 1,501 rows; Z0 = all branch defaults (11,280 slots, wide, cluster, no-store), P1 / P2 = before (8,674 uniform per-layer slots, fast top-k, ref decode top-k, store); `q_tail_gate.py --ref 1`):** Z0 against P1: d_top1 median 0.0038, p99 0.186, max 0.417, argmax flips 30 (2.00 %); the run-to-run control P2 against P1: median 0.0036, p99 0.196, max 0.384, flips 34 (2.27 %). Rule (each <= 1.25 x the control): p99 0.186 <= 0.245, max 0.417 <= 0.480, flips 2.00 % <= 2.84 %: **PASS**; both are also inside the Original envelope (p99 0.22, max 0.43, flips 2.8 %). The kernels alone are bit-identical (gate I); the deviation is the placement change of the larger cache, and it is smaller than the noise between two runs of the old build. A first try of this job failed to open the second stack of the process (`driver error: HostAllocation` with a 20,000 MiB prefix cache and a loaded host) and is kept as `rest-q-256k.first-try.log`. Same job, speed (not a paired A/B: logprob tracing slows decode): TTFT sum 56.8 s (Z0) against 57.2 / 57.1 s (P1 / P2).
## Not taken (reasons in the digest)
Qwen3.6-35B-A3B path, Metal/SYCL/HIP-only changes, K8V4 streaming and elastic KV (`--kv-grow`; our serve path excludes K8V4), the installers and host app.
+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
}
]
}
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Re-seal one of OUR OWN already-sealed PTX assets (prefill_stage, qsa_late, ...) after its .cu changed.
seal_pins.py fills the pins of an unsealed placeholder and refuses an asset whose PTX is already pinned ("expected nowhere"), which is
the right default for the Original's assets. The assets that this repository compiles itself (extra-seal-plan.json, encoding
concat_include_str, a `PtxPin { source_sha256, ptx_sha256 }` in the Rust owner) are re-sealed by this tool: it takes the PTX that
`compile_assets.py --group G --out DIR` produced for the CURRENT .cu, writes it over the committed PTX, and patches the two pin fields
the plan names (`rust_fields_to_fill`) with the SHA-256 of the .cu bytes and of the PTX body. Nothing else changes.
reseal_own.py --ptx-dir DIR ASSET_ID [ASSET_ID ...] # dry run: prints what would change
reseal_own.py --ptx-dir DIR --write ASSET_ID [ASSET_ID ...]
The sm_86 companions and the generated table are rebuilt afterwards with `scripts/gpu-bringup/sm86_assets.py build` (docs/sm86-assets.md).
"""
import argparse
import json
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import bringup_lib as L # noqa: E402
import rustpins as R # noqa: E402
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ptx-dir", required=True, type=Path)
ap.add_argument("--write", action="store_true")
ap.add_argument("ids", nargs="+")
args = ap.parse_args()
root = L.REPO
plan = json.loads((root / "scripts/gpu-bringup/extra-seal-plan.json").read_text())
by_id = {Path(a["cu"]).stem: a for a in plan["assets"]}
manifest = json.loads((args.ptx_dir / "build-manifest.json").read_text())
for asset_id in args.ids:
a = by_id[asset_id]
rec = next(r for r in manifest["assets"] if r["id"] == asset_id)
if rec["status"] != "ok" or rec.get("fake"):
sys.exit(f"{asset_id}: manifest status {rec['status']}")
raw = (args.ptx_dir / rec["ptx_file"]).read_bytes()
cu = (root / a["cu"]).read_bytes()
if L.sha256_hex(cu) != rec["cu_sha256"]:
sys.exit(f"{asset_id}: the .cu changed after the compile; compile again")
v = R.PinValues(len(raw), L.sha256_digest(raw), L.sha256_digest(cu))
for consumer, specs in a["rust_fields_to_fill"].items():
path = next(root.glob(f"crates/*/src/{consumer}"))
text = path.read_text(encoding="utf-8", newline="")
new = text
for spec in specs:
new = R.apply_field(new, spec, v)
print(f"{asset_id}: {path.relative_to(root)} {'patched' if new != text else 'unchanged'} (ptx {len(raw)} B sha {v.ptx_sha256.hex()[:16]}, cu sha {v.source_sha256.hex()[:16]})")
if args.write:
path.write_text(new, encoding="utf-8", newline="")
if args.write:
(root / a["ptx"]).write_bytes(raw)
print(f"{asset_id}: wrote {a['ptx']}")
if __name__ == "__main__":
main()
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env python3
"""Per-arm sums of the PREFILL-PROFILE chunk stages of a replay log, and a paired summary of the arms of one kind.
usage: arm_prof.py FULL_LOG [STAGE ...] (default stages: gdn qsa moe inject)
Arms are split by `REPLAY-ARM start label=` lines; every `PREFILL-PROFILE first=F tokens=N total_ms=T <stage>=ms ...` line is one chunk of the arm that
is running. Prints per arm: chunks, tokens, the sum of total_ms and of each stage, and the same for the chunks that start past 100,000 tokens (the
position dependent part). The last table pools the arms by the label's letter (B1/B2/B3 -> B) and prints mean and spread over the pooled arms.
(docs/upstream-port-plan.md rows 2.4 / 2.5.)
"""
import re
import statistics
import sys
log = sys.argv[1]
stages = sys.argv[2:] or ["gdn", "qsa", "moe", "inject"]
arms = []
cur = None
for line in open(log, errors="replace"):
m = re.search(r"REPLAY-ARM start label=(\S+)", line)
if m:
cur = {"label": m[1], "chunks": []}
arms.append(cur)
continue
m = re.match(r"PREFILL-PROFILE first=(\d+) tokens=(\d+) total_ms=([\d.]+)", line)
if m and cur is not None:
row = {"first": int(m[1]), "tokens": int(m[2]), "total": float(m[3])}
for s in stages:
v = re.search(rf" {re.escape(s)}=([\d.]+)", line)
row[s] = float(v[1]) if v else 0.0
cur["chunks"].append(row)
def sums(chunks):
out = {"chunks": len(chunks), "tokens": sum(c["tokens"] for c in chunks), "total": sum(c["total"] for c in chunks)}
for s in stages:
out[s] = sum(c[s] for c in chunks)
return out
cols = ["chunks", "tokens", "total"] + stages
print("per arm (ms): " + " ".join(f"{c:>10}" for c in cols))
for a in arms:
for name, ch in (("all", a["chunks"]), ("pos>=100k", [c for c in a["chunks"] if c["first"] >= 100_000])):
s = sums(ch)
print(f"{a['label']:<8} {name:<14} " + " ".join(f"{s[c]:>10.0f}" for c in cols))
print("\npooled by arm letter (mean +- sd over the arms, ms):")
kinds = {}
for a in arms:
kinds.setdefault(re.sub(r"\d+$", "", a["label"]), []).append(a)
for k, group in kinds.items():
for name, pick in (("all", lambda a: a["chunks"]), ("pos>=100k", lambda a: [c for c in a["chunks"] if c["first"] >= 100_000])):
vals = [sums(pick(a)) for a in group]
cells = []
for c in ["total"] + stages:
xs = [v[c] for v in vals]
cells.append(f"{c} {statistics.mean(xs):.0f}+-{(statistics.stdev(xs) if len(xs) > 1 else 0):.0f}")
print(f"{k:<4} n={len(group)} {name:<10} " + " ".join(cells))
+17
View File
@@ -0,0 +1,17 @@
#!/usr/bin/env python3
"""Per-turn TTFT / decode tok/s / wall of the long-session.json of e2e run directories: turns.py RUN_DIR [RUN_DIR ...]"""
import json
import os
import sys
for r in sys.argv[1:]:
d = json.load(open(os.path.join(r, "long-session.json")))
turns = d if isinstance(d, list) else d.get("turns") or d.get("results") or []
if isinstance(d, dict) and not turns:
print(r, list(d)[:8])
continue
cells = " ".join(f"{t.get('ttft_s')}/{t.get('decode_tok_s')}" for t in turns)
wall = sum(t.get("wall_s", 0) for t in turns)
ttft = sum(t.get("ttft_s", 0) for t in turns)
dec = sum(t.get("decode_tok_s", 0) for t in turns) / max(len(turns), 1)
print(f"{os.path.basename(r):<24} ttft/decode per turn: {cells} | sum ttft {ttft:.1f} s, mean decode {dec:.1f} tok/s, sum wall {wall:.1f} s")