diff --git a/PORT-GAPS-MODE17.md b/PORT-GAPS-MODE17.md index d1f15aa1..709cd50a 100644 --- a/PORT-GAPS-MODE17.md +++ b/PORT-GAPS-MODE17.md @@ -10,7 +10,7 @@ This is a bounded core-path ledger, not a whole-project completion certificate. | Original source / function | Current Rust boundary | Required completion | | --- | --- | --- | | `src/core/mtp.cpp:143` `MtpDrafter::load`; `:380` `bind`; `:677` `kv_restore`; `include/strata/core/mtp.hpp` `idle/device/tensor_*` | SOURCE-COMPLETE, NOT GPU-RUN (2026-10-14, branch `claude/port-mtp-loader`). `original_mtp_rt.rs` reads dense.txt/dense.bin/experts.bin/draft_vocab.bin; `original_mtp_bank.rs` places them (Original order, nine-name check last); `original_mtp_loader.rs` plans geometry/session/KV/coupled and admits the retained ring; `original_mtp_draft_head.rs` gathers the subset head; `original_mtp_actor_loaded.rs` adopts the genuine drafter and links `idle/device/kv_restore/set_*/draft*/coupled`. Runtime: `RetainedOriginalMtpWeights::from_rt_bank`, `OriginalMtpFullOwner::assemble_rt`, `OriginalPromptExecutor::select_rt_mtp` and the actor-driven `draft_committed_mtp`/`draft_first_committed_mtp`. | Remaining is GPU-only evidence: run the ignored `original_mtp_bank_gpu` tests (`LELEKA_MTP_RT_BANK_GPU=yes`), a real-pack load, and compare drafts with the Original. Nothing above `select_rt_mtp` (serving backend, `OriginalSpecController`) calls it yet: rows 2-3. Not repeated: Original `cudaMemset(cring_, 0xff)`; the Original single-allocation `dense_` (each indexed tensor is its own allocation, same total bytes); `tensor_f32/bf16/q8` host accessors (roles are the retained `Rc` bank). | -| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. No concrete implementation of that combined verifier resource trait was found in `crates/`. | Implement retained whole 48-layer native window resources, actual projection/GR/GDN/QSA/MoE/head command recording, cache-slot/source lifetime and CPU pool/PCIe plan callbacks. Record all T graphs and real commit graph before `run`; existing scheduler alone is not the window producer. | +| `src/core/verify.cpp:405` `record_window`, `:925` `capture`, `:988` `capture_commit`, `:1054` `run` | `original_verify.rs:235` defines `OriginalVerifyGraphResources`; `original_verify_schedule.rs` owns real streams/graphs/doorbells and accepts a caller recording closure. No concrete implementation of that combined verifier resource trait was found in `crates/`. | `OriginalVerifyWindowOps` now has capture-time producers for every former `UNBOUND_PRODUCERS` entry (pure planners over SHA-pinned sealed PTX: projections/head, GR, GDN, QSA, MoE; unit-tested against verify.cpp order). Still open: seal `original_verify_window_moe_experts.ptx` and `original_verify_window_qsa_gate.ptx` (`docs/cuda-seal-plan-additions-window.json`; the window fails closed with those names until then), GPU smokes/golden comparisons per kernel and for a whole window, the fast-math re-seal question listed in that JSON, and the runtime-side wiring (weights, QSA/PLE journals, CPU pool callbacks, graph registration before `run`). | | `mtp.cpp` `draft/draft_first` and `verify.cpp` `run/commit/wait_commit`, used together by mode17 generation | `qwen_forward/original_spec_draft.rs` defines `OriginalDraftEngine` / `OriginalFirstDraftEngine`; `original_spec_controller.rs:20` defines `OriginalSpecEngine`. No concrete impl or production `OriginalSpecController::new` call was found. The real driver `OriginalMtpDrafter` and verifier receipt bridge already exist. | Bind the genuine verifier receipts, all-T residual catch-up, actual MTP ring/full seed, accepted-prefix replay/publication, adaptive work and BOTH checkpoint restoration to these traits; then select that controller in the actual serving owner. Preserve sampled history/counter and async commit event dependencies. | | `include/strata/core/verify.hpp` `set_stage/set_next`; `src/core/verify.cpp:191,1054,1382,1412`; `core/on_device.hpp` | `OriginalVerifier` loops all 48 layers, has no next-stage owner or stage handoff fields. Context identity exists, but the unselected MTP actor cannot infer an actual current CUDA device ordinal. | Port stage bounds, mapped portable R+pending-bo+inject handoff, next-user CPU dispatch and last-stage head/sampling/final_R/commit forwarding. This is an absent multi-GPU mode17 leaf, not a single-device quality defect. | | `verify.cpp:137,158,899,1323,1422` public release/diag/profile/logprob/logit APIs | Internal Rust bounded wait release, commit event and completed-row bridge are present. No equivalent public diagnostic/watchdog registry, profile report, window_logprobs or copy_logits API was found in the inspected Original Rust modules. | Expose the actual live verifier release/diagnostic owner; port literal GPU-stage stamps and completed logit/logprob readout (including LOGPOS_TOPK). Keep capture-only graphs inadmissible for readout. Do not call the existing internal release absent. | diff --git a/crates/cuda-driver/src/lib.rs b/crates/cuda-driver/src/lib.rs index fbc79166..87181465 100644 --- a/crates/cuda-driver/src/lib.rs +++ b/crates/cuda-driver/src/lib.rs @@ -3226,6 +3226,19 @@ pub use original_verify::{ target_os = "linux", target_pointer_width = "64" ))] +pub use original_verify::{ + HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyExpertFormats, + OriginalVerifyGdnProjections, OriginalVerifyGrBinding, OriginalVerifyMoeBinding, + OriginalVerifyMoeLayerWeights, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding, + OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, OriginalVerifyQsaLayerWeights, + OriginalVerifyQsaPolicy, OriginalVerifyQsaProjections, PleBuffers, PleKeyBuffer, QsaRope, + unsealed_window_assets, +}; +#[cfg(all( + feature = "cuda-driver", + target_os = "linux", + target_pointer_width = "64" +))] pub use original_verify::{ ExpertTier, HcHalf, OriginalVerifyExpertLayout, OriginalVerifyWindowResources, PlanLayout, Projection, QuantSource, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS, diff --git a/crates/cuda-driver/src/native_head.rs b/crates/cuda-driver/src/native_head.rs index b8029866..6f198e01 100644 --- a/crates/cuda-driver/src/native_head.rs +++ b/crates/cuda-driver/src/native_head.rs @@ -31,7 +31,7 @@ pub struct NativeHeadSampling<'a, 'ctx> { pub path: SamplerPath, pub enabled: bool, } -#[derive(Clone, Copy, Debug)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NativeHeadDispatch { pub multi_exact: bool, pub old_iq: bool, diff --git a/crates/cuda-driver/src/original_verify.rs b/crates/cuda-driver/src/original_verify.rs index 066de932..f8cece58 100644 --- a/crates/cuda-driver/src/original_verify.rs +++ b/crates/cuda-driver/src/original_verify.rs @@ -9,6 +9,13 @@ #[path="original_verify_logits.rs"] mod logits; #[path="original_verify_window_plan.rs"] pub(crate) mod window_plan; #[path="original_verify_window_record.rs"] pub(crate) mod window_record; +#[path="original_verify_window_kernels.rs"] pub(crate) mod kernels; +#[path="original_verify_window_proj.rs"] pub(crate) mod proj; +#[path="original_verify_window_gr.rs"] pub(crate) mod gr; +#[path="original_verify_window_qsa.rs"] pub(crate) mod qsa; +#[path="original_verify_window_moe.rs"] pub(crate) mod moe; +#[path="original_verify_window_planner.rs"] pub(crate) mod planner; +#[cfg(test)] #[path="original_verify_window_gpu.rs"] mod window_gpu; pub use layout::{OriginalVerifyGeometry,OriginalVerifyLayout,OriginalVerifySpan}; pub use diag::{OriginalVerifyDiag,original_verify_diagnostics,original_verify_live_count,original_verify_release_live,write_original_verify_diagnostics}; pub use profile::{OriginalVerifyProfile,PROFILE_STAMPS_PER_LAYER,profile_stamp_slot,profile_stamp_words}; @@ -80,12 +87,45 @@ impl OriginalVerifyCanonicalGdn<'_>{ pub fn close(self)->Result<()>{match Rc::try_unwrap(self.inner){Ok(mut owner)=>owner.close_inner(),Err(_)=>Err(Error::InvalidQwenShape)}} } -struct Physical<'ctx>{context:&'ctx Context<'ctx>,layout:OriginalVerifyLayout,arena:Option>,prof:Option>,mapped:[RefCell>;15],module:Option,qsa_module:Option,generation:Cell,failed:Cell} +struct Physical<'ctx>{context:&'ctx Context<'ctx>,layout:OriginalVerifyLayout,arena:Option>,prof:Option>,mapped:[RefCell>;15],module:Option,qsa_module:Option,window:RefCell)>>,generation:Cell,failed:Cell} impl Physical<'_>{ fn validate(&self,c:&Context<'_>)->Result<()>{if !std::ptr::eq(c,self.context){return Err(Error::ContextMismatch)}if self.failed.get()||c.is_poisoned()||self.module.is_none()||self.qsa_module.is_none(){return Err(Error::ContextPoisoned)}admit(c,self.arena.as_ref().ok_or(Error::ContextPoisoned)?,self.layout.bytes).map(|_|())} fn span(&self,name:&str,offset:usize,bytes:usize)->Result{self.validate(self.context)?;let s=self.layout.span(name)?;let b=self.arena.as_ref().ok_or(Error::ContextPoisoned)?;if bytes==0||offset.checked_add(bytes).is_none_or(|n|n>s.bytes){return Err(Error::InvalidSize)}Ok(handle(b)?.checked_subspan(b.len(),s.offset+offset,bytes)?.qwen_address())} + /// Load (once) the sealed PTX modules a window producer launches from. Runs before any capture + /// (module loading is not capturable). Specs naming the same PTX file share one module (entries + /// unioned). Every sealed module is loaded; the first unsealed one fails closed AFTER that, by name. + fn ensure_window_assets(&self,specs:&[&'static kernels::AssetSpec])->Result<()>{ + self.validate(self.context)?; + let mut groups:Vec<(&'static str,&'static kernels::AssetSpec,Vec<&'static str>)>=Vec::new(); + for s in specs{match groups.iter_mut().find(|g|g.0==s.key()){Some(g)=>{for e in s.entries{if !g.2.contains(e){g.2.push(e)}}},None=>groups.push((s.key(),s,s.entries.to_vec()))}} + let mut ready=Vec::new();let mut unsealed:Result<()>=Ok(()); + {let loaded=self.window.try_borrow().map_err(|_|Error::InvalidQwenShape)?; + for(key,spec,entries)in groups{ + if let Some((_,_,have))=loaded.iter().find(|(n,_,_)|*n==key){if entries.iter().all(|e|have.contains(e)){continue}return Err(Error::InvalidDriverValue("Original verifier window module is already loaded without an entry a later graph needs"))} + match spec.sealed(){Ok(ptx)=>ready.push((key,ptx,entries)),Err(error)=>{if unsealed.is_ok(){unsealed=Err(error)}}} + }} + if ready.is_empty(){return unsealed} + let guard=self.context.enter()?;let mut result=Ok(()); + for(key,ptx,entries)in ready{match Module::load(ptx,&entries){Ok(m)=>{match self.window.try_borrow_mut(){Ok(mut w)=>w.push((key,m,entries)),Err(_)=>{result=combine(result,Err(Error::InvalidQwenShape));break}}},Err(error)=>{result=combine(result,Err(error));break}}} + let pop=guard.finish();if result.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)}combine(combine(result,pop),unsealed) + } + /// `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` of loaded window entries, once, before any capture + /// (what Original does for the fused GR down kernels). + fn configure_window_shared(&self,attrs:&[(&'static kernels::AssetSpec,&'static str,usize)])->Result<()>{ + self.validate(self.context)?;if attrs.is_empty(){return Ok(())} + let guard=self.context.enter()?;let mut result=Ok(()); + {let loaded=self.window.try_borrow().map_err(|_|Error::InvalidQwenShape)?;for(spec,entry,bytes)in attrs{match loaded.iter().find(|(n,_,_)|*n==spec.key()){Some((_,m,_))=>{result=combine(result,m.set_max_dynamic_shared(entry,*bytes))},None=>{result=combine(result,Err(Error::InvalidDriverValue(spec.unsealed)))}}}} + let pop=guard.finish();if result.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)}combine(result,pop) + } + /// `cuDeviceGetAttribute` of the verifier context's device (compute capability and shared-memory limits that Original + /// reads when it picks kernel variants). + fn window_device_attribute(&self,attribute:i32)->Result{ + self.validate(self.context)?;let guard=self.context.enter()?; + let value=match self.module.as_ref(){Some(m)=>m.device_attribute(attribute),None=>Err(Error::ContextPoisoned)}; + let pop=guard.finish();if value.as_ref().err().is_some_and(transport)||pop.is_err(){self.failed.set(true);poison(self.context)}pop?;value + } fn mapped_address(&self,i:usize,offset:usize,bytes:usize)->Result{self.mapped.get(i).ok_or(Error::InvalidQwenShape)?.try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.address(offset,bytes)} - fn close(&mut self)->Result<()>{if self.arena.is_none()&&self.prof.is_none()&&self.module.is_none()&&self.qsa_module.is_none(){return Ok(())}self.failed.set(true);if self.context.is_poisoned(){if let Some(b)=self.arena.take(){std::mem::forget(b)}if let Some(b)=self.prof.take(){std::mem::forget(b)}if let Some(m)=self.module.take(){std::mem::forget(m)}if let Some(m)=self.qsa_module.take(){std::mem::forget(m)}for m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){std::mem::forget(m)}return Err(Error::ContextPoisoned)}let sync=self.context.synchronize();if sync.is_err(){poison(self.context);return combine(sync,self.close())}let mut result=combine(self.arena.take().map_or(Ok(()),DeviceBuffer::release),self.prof.take().map_or(Ok(()),DeviceBuffer::release));if self.context.is_poisoned(){return combine(result,self.close())}let guard=match self.context.enter(){Ok(g)=>g,Err(e)=>return combine(combine(result,Err(e)),self.close())};for mut m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){result=combine(result,m.close());if result.is_err(){std::mem::forget(m)}}let unload=combine(self.module.take().map_or(Ok(()),Module::close),self.qsa_module.take().map_or(Ok(()),Module::close));let pop=guard.finish();if unload.is_err()||pop.is_err(){poison(self.context)}combine(combine(result,unload),pop)} + fn close(&mut self)->Result<()>{if self.arena.is_none()&&self.prof.is_none()&&self.module.is_none()&&self.qsa_module.is_none()&&self.window.get_mut().is_empty(){return Ok(())}self.failed.set(true);if self.context.is_poisoned(){if let Some(b)=self.arena.take(){std::mem::forget(b)}if let Some(b)=self.prof.take(){std::mem::forget(b)}if let Some(m)=self.module.take(){std::mem::forget(m)}if let Some(m)=self.qsa_module.take(){std::mem::forget(m)}for(_,m,_)in self.window.get_mut().drain(..){std::mem::forget(m)}for m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){std::mem::forget(m)}return Err(Error::ContextPoisoned)}let sync=self.context.synchronize();if sync.is_err(){poison(self.context);return combine(sync,self.close())}let mut result=combine(self.arena.take().map_or(Ok(()),DeviceBuffer::release),self.prof.take().map_or(Ok(()),DeviceBuffer::release));if self.context.is_poisoned(){return combine(result,self.close())}let guard=match self.context.enter(){Ok(g)=>g,Err(e)=>return combine(combine(result,Err(e)),self.close())};for mut m in self.mapped.iter_mut().filter_map(|m|m.get_mut().take()){result=combine(result,m.close());if result.is_err(){std::mem::forget(m)}}let mut unload=combine(self.module.take().map_or(Ok(()),Module::close),self.qsa_module.take().map_or(Ok(()),Module::close));for(_,m,_)in self.window.get_mut().drain(..){unload=combine(unload,m.close());}let pop=guard.finish();if unload.is_err()||pop.is_err(){poison(self.context)}combine(combine(result,unload),pop)} } impl Drop for Physical<'_>{fn drop(&mut self){let _=self.close();}} /// One genuine fixed max-T bank. Root keeps this in every captured graph's @@ -94,7 +134,7 @@ pub struct OriginalVerifyBank<'ctx>{physical:Rc>,last_t:usize,las impl<'ctx> OriginalVerifyBank<'ctx>{ fn new(context:&'ctx Context<'ctx>,geometry:OriginalVerifyGeometry)->Result{ let layout=OriginalVerifyLayout::new(geometry)?;let asset=sealed_asset(ASSET,ASSET_SHA)?;let qsa_asset=sealed_asset(QSA_ASSET,QSA_ASSET_SHA)?;admission(context,layout.bytes)?; - let mut owner=Physical{context,layout,arena:None,prof:None,mapped:std::array::from_fn(|_|RefCell::new(None)),module:None,qsa_module:None,generation:Cell::new(0),failed:Cell::new(false)}; + let mut owner=Physical{context,layout,arena:None,prof:None,mapped:std::array::from_fn(|_|RefCell::new(None)),module:None,qsa_module:None,window:RefCell::new(Vec::new()),generation:Cell::new(0),failed:Cell::new(false)}; let operation=(||{ let guard=context.enter()?; let loaded=(||{ @@ -187,6 +227,8 @@ impl<'ctx> OriginalVerifyWindow<'ctx>{ pub enum OriginalVerifyGdnStage{Conv=0,AlphaBeta=1,Recurrence=2} pub struct OriginalVerifyGdnWeights<'a,'ctx>{pub conv:&'a DeviceBuffer<'ctx>,pub alpha:&'a DeviceBuffer<'ctx>,pub beta:&'a DeviceBuffer<'ctx>,pub dt:&'a DeviceBuffer<'ctx>,pub a:&'a DeviceBuffer<'ctx>,pub norm:&'a DeviceBuffer<'ctx>} pub struct OriginalVerifyGdnJournal<'a,'ctx>{physical:Rc>,canonical:Rc>,weights:[OriginalVerifyGdnWeights<'a,'ctx>;36],ple:Option<&'a DeviceBuffer<'ctx>>,commands:RefCell>} +/// The journal resolves arena spans for the pure window plans. +impl kernels::ArenaMap for OriginalVerifyGdnJournal<'_, '_>{fn span(&self,name:&str,offset:usize,bytes:usize)->Result{self.physical.span(name,offset,bytes)}} impl resources::Sealed for OriginalVerifyGdnJournal<'_, '_>{} impl OriginalGraphResources for OriginalVerifyGdnJournal<'_, '_>{fn validate_context(&self,c:&Context<'_>)->Result<()>{self.physical.validate(c)?;self.canonical.validate_context(c)}} impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{ @@ -196,6 +238,19 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx>{ for c in &commands{module.admit(c)?;}let mut retained=self.commands.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;retained.try_reserve_exact(commands.len()).map_err(|_|Error::HostAllocation)?;let first=retained.len();retained.extend(commands);check_commands(&retained)?; for c in &mut retained[first..]{if let Err(error)=module.launch(stream,c){if transport(&error){self.physical.failed.set(true);poison(self.physical.context)}return Err(error)}}Ok(()) } + /// Pre-capture: load the sealed PTX assets the window producers will launch from. + pub(crate) fn ensure_window_assets(&self,specs:&[&'static kernels::AssetSpec])->Result<()>{self.physical.ensure_window_assets(specs)} + pub(crate) fn configure_window_shared(&self,attrs:&[(&'static kernels::AssetSpec,&'static str,usize)])->Result<()>{self.physical.configure_window_shared(attrs)} + pub(crate) fn window_device_attribute(&self,attribute:i32)->Result{self.physical.window_device_attribute(attribute)} + /// Launch window kernels (any loaded sealed asset) on the capture stream, in order. + pub(crate) fn submit_launches(&self,capture:&mut OriginalCapture<'_, 'ctx>,launches:Vec)->Result<()>{ + capture.validate_context(self.physical.context)?;let stream=capture.stream_handle(self.physical.context)?; + let mut commands=Vec::new();commands.try_reserve_exact(launches.len()).map_err(|_|Error::HostAllocation)?;for l in &launches{commands.push(l.command()?)} + let modules=self.physical.window.try_borrow().map_err(|_|Error::InvalidQwenShape)?; + for(l,c)in launches.iter().zip(&commands){let m=modules.iter().find(|(n,_,_)|*n==l.asset.key()).ok_or(Error::InvalidDriverValue(l.asset.unsealed))?;m.1.admit(c)?} + let mut retained=self.commands.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;retained.try_reserve_exact(commands.len()).map_err(|_|Error::HostAllocation)?;let first=retained.len();retained.extend(commands);check_commands(&retained)?; + for(i,c)in retained[first..].iter_mut().enumerate(){let m=modules.iter().find(|(n,_,_)|*n==launches[i].asset.key()).ok_or(Error::InvalidDriverValue(launches[i].asset.unsealed))?;if let Err(e)=m.1.launch(stream,c){if transport(&e){self.physical.failed.set(true);poison(self.physical.context)}return Err(e)}}Ok(()) + } pub(crate) fn context(&self)->&'ctx Context<'ctx>{self.physical.context} pub(crate) fn address(&self,name:&str,offset:usize,bytes:usize)->Result{self.physical.span(name,offset,bytes)} /// Literal mapped token/step/position copies at the start of each T graph. @@ -316,6 +371,7 @@ impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResou impl OriginalVerifyGdnJournal<'_, '_>{ pub(crate) fn has_ple(&self)->bool{self.ple.is_some()} + pub(crate) fn ple_history_address(&self)->Result>{self.ple.map(|b|Ok(handle(b)?.qwen_address())).transpose()} pub(crate) fn canonical_identity(&self)->usize{Rc::as_ptr(&self.canonical)as usize} pub(crate) fn geometry(&self)->OriginalVerifyGeometry{self.physical.layout.geometry} pub fn validate_bank(&self,bank:&OriginalVerifyBank<'_>)->Result<()>{if !Rc::ptr_eq(&self.physical,&bank.physical){return Err(Error::InvalidQwenShape)}self.validate_context(self.physical.context)} @@ -323,8 +379,12 @@ impl OriginalVerifyGdnJournal<'_, '_>{ #[path="original_verify_schedule.rs"] mod schedule; pub use schedule::{OriginalVerifier,OriginalVerifyWindowResult,OriginalVerifyCpuRows,OriginalVerifyCpuSink}; #[path="original_verify_window_ops.rs"] mod window_ops; -pub use window_ops::{OriginalVerifyExpertLayout,OriginalVerifyWindowResources,UNBOUND_PRODUCERS}; +pub use window_ops::{OriginalVerifyExpertLayout,OriginalVerifyWindowResources,UNBOUND_PRODUCERS,unsealed_window_assets}; +pub use gr::{HcHalfBuffers,HcLayerBuffers,HcOutputBuffers,OriginalVerifyGrBinding,PleBuffers,PleKeyBuffer}; +pub use moe::{OriginalVerifyExpertFormats,OriginalVerifyMoeBinding,OriginalVerifyMoeLayerWeights}; +pub use qsa::{OriginalVerifyQsaBinding,OriginalVerifyQsaKvBinding,OriginalVerifyQsaLayerWeights,OriginalVerifyQsaPolicy,QsaRope}; pub use window_record::{ExpertTier,HcHalf,Projection,QuantSource,Rows,WindowOps,WindowPolicy,record_window}; +pub use proj::{OriginalVerifyGdnProjections,OriginalVerifyNativeMatrix,OriginalVerifyProjBinding,OriginalVerifyQsaProjections}; pub use window_plan::{PlanLayout,WINDOW_LAYERS}; impl OriginalVerifyWindow<'_>{ diff --git a/crates/cuda-driver/src/original_verify_ffi.rs b/crates/cuda-driver/src/original_verify_ffi.rs index 5b1df254..3234e2ae 100644 --- a/crates/cuda-driver/src/original_verify_ffi.rs +++ b/crates/cuda-driver/src/original_verify_ffi.rs @@ -6,29 +6,38 @@ type Load=unsafe extern "C" fn(*mut Handle,*const c_void)->i32; type Destroy=unsafe extern "C" fn(Handle)->i32; type Function=unsafe extern "C" fn(*mut Handle,Handle,*const i8)->i32; type Launch=unsafe extern "C" fn(Handle,u32,u32,u32,u32,u32,u32,u32,Handle,*mut *mut c_void,*mut *mut c_void)->i32; -pub(crate) enum Arg{Address(u64),I32(i32),I64(i64),U64(u64),F32(f32)} -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()}}} +type SetAttr=unsafe extern "C" fn(Handle,i32,i32)->i32; +type DeviceOf=unsafe extern "C" fn(*mut i32)->i32; +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>} impl Command{pub(crate) fn abi_bytes(&self)->Result{self.args.len().checked_mul(std::mem::size_of::()).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)->Result{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})}} 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,handle:Option,functions:Vec<(&'static str,usize)>,launch:Launch,unload:Destroy} +pub(crate) struct Module{library:Option,handle:Option,functions:Vec<(&'static str,usize)>,launch:Launch,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[&'static str])->Result{ + pub(crate) fn load(ptx:&'static[u8],entries:&[&'static str])->Result{ if ptx.last()!=Some(&0)||entries.is_empty(){return Err(Error::InvalidDriverValue("OriginalVerify sealed PTX"));} let library=Library(unsafe{libc::dlopen(c"libcuda.so.1".as_ptr(),libc::RTLD_NOW|libc::RTLD_LOCAL)});if library.0.is_null(){return Err(Error::LibraryUnavailable);} fn sym(l:&Library,n:&'static CStr)->Result{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::(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),library:Some(library),handle:None,functions:Vec::new()}; + 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()}; 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,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())})} + /// `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)?)})} + /// `cuDeviceGetAttribute` of the context's current device (97 = max shared per block opt-in, 8 = per block, 75/76 = cc). + pub(crate) fn device_attribute(&self,attribute:i32)->Result{let mut device=0;check("cuCtxGetDevice",unsafe{(self.device)(&mut device)})?;let mut value=0;check("cuDeviceGetAttribute",unsafe{(self.device_attr)(&mut value,attribute,device)})?;Ok(value)} pub(crate) fn close(mut self)->Result<()>{self.close_inner()} fn close_inner(&mut self)->Result<()>{if let Some(h)=self.handle.take(){let result=check("cuModuleUnload",unsafe{(self.unload)(h as Handle)});if result.is_err(){if let Some(l)=self.library.take(){std::mem::forget(l);}}result}else{Ok(())}} } diff --git a/crates/cuda-driver/src/original_verify_window_gpu.rs b/crates/cuda-driver/src/original_verify_window_gpu.rs new file mode 100644 index 00000000..80841cfb --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gpu.rs @@ -0,0 +1,37 @@ +//! Root-only device proofs for the window producers' sealed kernel assets. They need a CUDA device +//! and run only with the enabling variable; on every other host they are compile-checked, never +//! executed. They certify that the pinned PTX loads on the card and exports every entry the +//! planners name, NOT numerics (the per-kernel golden comparisons against the Original are listed in +//! the work report). +use super::*; +use crate::Driver; + +const ENABLE: &str = "LELEKA_VERIFY_WINDOW_GPU"; + +#[test] +#[ignore = "Root-only: needs a CUDA device"] +fn sealed_window_assets_load_on_the_device_and_export_every_named_entry() { + 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(1 << 30).expect("context"); + let bank = context.original_verify_bank(kernels::test_geometry()).expect("bank"); + let all = window_ops::all_window_assets(); + // Every sealed module is loaded (cuModuleLoadData + cuModuleGetFunction per named entry); the first + // placeholder is then reported by name. + let result = bank.physical.ensure_window_assets(&all); + let sealed = all.iter().filter(|a| a.sealed().is_ok()).map(|a| a.key()).collect::>(); + let loaded = bank.physical.window.borrow().iter().map(|(name, _, _)| *name).collect::>(); + assert_eq!(loaded, sealed); + match window_ops::unsealed_window_assets().first() { + Some(_) => assert!(matches!(result, Err(Error::InvalidDriverValue(m)) if m.contains("unsealed"))), + None => result.expect("all assets sealed"), + } + // the card's fused-GR decisions are readable (compute capability 12.x for the sm_120 PTX, a shared opt-in) + assert!(bank.physical.window_device_attribute(75).expect("cc major") >= 7); + assert!(bank.physical.window_device_attribute(97).expect("opt-in shared") >= 48 * 1024); + // loading again is a no-op and a second call with a subset is satisfied by the loaded modules + let _ = bank.physical.ensure_window_assets(&all); + assert_eq!(bank.physical.window.borrow().len(), loaded.len()); + bank.close().expect("close"); +} diff --git a/crates/cuda-driver/src/original_verify_window_gr.rs b/crates/cuda-driver/src/original_verify_window_gr.rs new file mode 100644 index 00000000..053685f9 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_gr.rs @@ -0,0 +1,1369 @@ +//! Hyper-connection family of the Verifier window (child of `original_verify`): the fused +//! GR read (`fused_gr_read_multi`), the final residual write, the head mix +//! (`lm_head_mix`) and the layer-1 PLE block of `Verifier::record_window`. +//! +//! Everything here is a pure planner (addresses in, `Launch`es out) over sealed assets: +//! +//! * `mtp_original_full_fused_gr.ptx` holds the literal Original `fused_gr.cu` kernels as the +//! six `mtp_scalar_gr_*` wrappers, each taking the Original `GrMulti` by value +//! (114 u64 words: eight 14-word `FusedGrArgs`, then `xn` at word 112 and `T` at word 113): +//! `norm` (plain norm, one block per token), `split` (norm per token and stream), +//! `staged` (cp.async down projection), `up`, `down1280` / `down2560` +//! (`gr_down_multi_kernel`). +//! * `mtp_original_full_gr_norm.ptx` / `mtp_original_full_gr_post.ptx` hold the native +//! (`gr_set_native_mmvf(true)`, the mode17 setting) `gr_read` / `gr_write` pieces: +//! `native_gr_rms_norm_weighted`, `native_gr_down_silu`, `native_gr_pre_gated`, +//! `native_gr_post`. +//! * `ple_native_batch.ptx` holds the Original `native_ple_postops_batch` kernels; with `T = 1` +//! their launch geometry and per-element arithmetic are the single-token `native_ple_postops` +//! kernels `ple_block` runs in the decode path (see `plan_ple_row`). +//! * the projections are the shared `proj` primitives (`bf16_gemv_fp32_mmvf`, q8_1 + MMVQ). +//! +//! The Original selects the hc read variant per card (`fused_gr_check`, `STRATA_HC_SPLIT`) and +//! the down kernel's tile and token chunking from the device attributes (`down_chunk`); +//! `GrConfig` carries exactly those decisions and `GrConfig::from_device` replicates `down_chunk`. +use super::kernels::{A, ArenaMap, AssetSpec, Launch}; +use super::layout::OriginalVerifyGeometry; +use super::proj::{self, NativeWeight, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1, q8_1_row_bytes}; +use super::window_record::{HcHalf, Rows}; +use super::{OriginalVerifyGdnJournal, admit, handle}; +use crate::native_head::native_head_row_bytes; +use crate::{Context, DeviceBuffer, Error, NativeHeadDispatch, Result}; + +// ------------------------------------------------------------------------------------------------ +// Geometry of the artifact (`fused_gr.cu` is compiled for exactly these) +// ------------------------------------------------------------------------------------------------ +const N: usize = 2560; +const HC: usize = 4; +const LR: usize = 320; +const D: usize = N * HC; +const MAX_T: usize = 8; +const LAYERS: usize = 48; +const DOWN_BLOCKS: u32 = (LR / 8) as u32 + 1; +const UP_BLOCKS: u32 = (N / 16) as u32; +const THREADS: u32 = 256; +const EPS: f32 = 1e-6; +/// `1.0f / float(hc)`: the scale of `native_gr_down_silu`, `native_gr_pre_gated`, `native_gr_post`. +const QUARTER: f32 = 0.25; +const STAGED_TILE: u32 = 1280; + +/// Words of `FusedGrArgs` (112 bytes) and of `GrMulti` (912 bytes). +const ARGS_WORDS: usize = 14; +const MULTI_WORDS: usize = ARGS_WORDS * MAX_T + 2; +const XN_WORD: usize = ARGS_WORDS * MAX_T; +const T_WORD: usize = XN_WORD + 1; + +/// Bytes of the hc weights of one half (`hc_attn_*` / `hc_ffn_*`) and of the final mixer. +pub const HC_NORM_BYTES: usize = D * 4; +pub const HC_DOWN_BYTES: usize = LR * D * 2; +pub const HC_UP_BYTES: usize = D * LR * 2; +pub const HC_INJECT_BYTES: usize = HC * D * 2; + +// ------------------------------------------------------------------------------------------------ +// Sealed assets +// ------------------------------------------------------------------------------------------------ +const E_NORM: &str = "mtp_scalar_gr_norm"; +const E_SPLIT: &str = "mtp_scalar_gr_split"; +const E_STAGED: &str = "mtp_scalar_gr_staged"; +const E_UP: &str = "mtp_scalar_gr_up"; +const E_DOWN1280: &str = "mtp_scalar_gr_down1280"; +const E_DOWN2560: &str = "mtp_scalar_gr_down2560"; + +pub(crate) static GR_FUSED: AssetSpec = AssetSpec { + name: "mtp_original_full_fused_gr.ptx", + ptx: include_bytes!("mtp_original_full_fused_gr.ptx"), + sha: [ + 172, 84, 0, 167, 151, 43, 63, 36, 38, 72, 194, 222, 113, 239, 79, 23, 132, 102, 211, 139, 19, 146, 168, 58, 149, + 145, 179, 178, 78, 146, 197, 155, + ], + entries: &[E_NORM, E_SPLIT, E_STAGED, E_UP, E_DOWN1280, E_DOWN2560], + unsealed: "Original verifier asset unsealed: mtp_original_full_fused_gr.ptx (fused hc read)", +}; +pub(crate) static GR_NORM: AssetSpec = AssetSpec { + name: "mtp_original_full_gr_norm.ptx", + ptx: include_bytes!("mtp_original_full_gr_norm.ptx"), + sha: [ + 186, 149, 215, 197, 178, 124, 201, 212, 193, 207, 188, 107, 59, 205, 0, 14, 91, 162, 155, 18, 76, 102, 28, 9, 5, + 21, 200, 109, 130, 55, 224, 92, + ], + entries: &["mtp_full_gr_norm"], + unsealed: "Original verifier asset unsealed: mtp_original_full_gr_norm.ptx (native weighted RMS norm)", +}; +pub(crate) static GR_POST: AssetSpec = AssetSpec { + name: "mtp_original_full_gr_post.ptx", + ptx: include_bytes!("mtp_original_full_gr_post.ptx"), + sha: [ + 232, 132, 196, 163, 162, 6, 149, 199, 152, 212, 139, 21, 102, 87, 255, 36, 185, 50, 44, 21, 104, 67, 15, 81, 68, + 207, 218, 238, 209, 78, 242, 90, + ], + entries: &["mtp_full_down_silu", "mtp_full_pre_final", "mtp_full_native_write"], + unsealed: "Original verifier asset unsealed: mtp_original_full_gr_post.ptx (native hc silu / gate / write)", +}; +pub(crate) static PLE_BATCH: AssetSpec = AssetSpec { + name: "ple_native_batch.ptx", + ptx: concat!(include_str!("ple_native_batch.ptx"), "\0").as_bytes(), + sha: [ + 26, 56, 44, 190, 134, 123, 193, 147, 198, 175, 82, 146, 194, 203, 207, 189, 142, 47, 87, 205, 25, 80, 201, 13, 228, + 243, 0, 0, 54, 116, 16, 179, + ], + entries: &["ple_gate", "ple_rms", "ple_broadcast", "ple_conv", "ple_history"], + unsealed: "Original verifier asset unsealed: ple_native_batch.ptx (native PLE post-ops)", +}; + +/// Every module this family may launch from (the lead preloads them BEFORE capture). +pub(crate) fn assets() -> Vec<&'static AssetSpec> { + vec![ + &GR_FUSED, + &GR_NORM, + &GR_POST, + &PLE_BATCH, + &proj::BF16, + &proj::HEAD_NATIVE, + &proj::HEAD_IQ, + ] +} + +// ------------------------------------------------------------------------------------------------ +// Process-wide / per-card decisions of the Original +// ------------------------------------------------------------------------------------------------ + +/// `fused_gr_variant()`: which bitwise-equal arrangement of the multi read runs on the card. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum GrVariant { + /// `kHcPlain`: norm one block per token, plain down projection. + Plain, + /// `kHcSplit`: norm one block per token and stream, plain down projection. + Split, + /// `kHcStaged`: split norm, cp.async staged down projection. + Staged, +} +impl GrVariant { + /// `env_variant()`: `STRATA_HC_SPLIT` unset / empty / other = staged, `0` plain, `1` split. + /// `fused_gr_check` may still lower the choice for a card where the check disagrees; the + /// runtime passes the variant that check settled on. + pub(crate) fn from_env_value(value: Option<&str>) -> Self { + match value.and_then(|v| v.bytes().next()) { + None => GrVariant::Staged, + Some(b'0') => GrVariant::Plain, + Some(b'1') => GrVariant::Split, + Some(_) => GrVariant::Staged, + } + } +} + +/// `cuDeviceGetAttribute` ids `down_chunk` reads. +pub(crate) const ATTR_MAX_SHARED_PER_BLOCK: i32 = 8; +pub(crate) const ATTR_COMPUTE_CAPABILITY_MAJOR: i32 = 75; +pub(crate) const ATTR_COMPUTE_CAPABILITY_MINOR: i32 = 76; +pub(crate) const ATTR_MAX_SHARED_PER_BLOCK_OPTIN: i32 = 97; + +/// The hc-read decisions: `fused_gr_variant()` plus the result of `down_chunk` on this card. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct GrConfig { + pub variant: GrVariant, + /// `gr_set_native_mmvf` (`--native`, the mode17 setting). The final write and the head mix + /// follow it; a non-native Original is refused (fail closed). + pub native_mmvf: bool, + /// The plain down kernel's TILEV: 1280 on sm_75, 2560 elsewhere. + pub tile: u32, + /// Tokens one plain down launch may carry (`down_chunk(false)`). + pub chunk_plain: usize, + /// Tokens one staged down launch may carry (`down_chunk(true)`). + pub chunk_staged: usize, + /// The shared memory a launch can actually have (`usable` of `down_chunk`). + pub usable_shared: u32, + /// `cudaFuncSetAttribute(gr_down_multi_kernel, MaxDynamicSharedMemorySize, bytes)`. + pub attr_down: Option, + /// The same for `gr_down_staged_kernel`. + pub attr_staged: Option, +} +impl GrConfig { + /// Replicates the one-time per-device block of `down_chunk` from the four device attributes + /// (`ATTR_*`). An attribute call is only emitted when the card reports an opt-in (Original + /// issues it unconditionally but ignores its failure and drops the error). + pub(crate) fn from_device( + variant: GrVariant, + native_mmvf: bool, + cc_major: i32, + cc_minor: i32, + optin: i32, + per_block: i32, + ) -> Self { + let optin = optin.max(0) as u32; + let per_block = per_block.max(0) as u32; + let small_tile = cc_major * 10 + cc_minor == 75; + let tile: u32 = if small_tile { 1280 } else { 2560 }; + let mut want = MAX_T as u32 * tile * 4; + if optin > 0 && want > optin { + want = optin; + } + let mut want_staged = 2 * MAX_T as u32 * STAGED_TILE * 4; + if optin > 0 && want_staged > optin { + want_staged = optin; + } + // Below sm_70 the opt-in is a promise the card does not keep: the per-block limit counts. + let usable = if cc_major >= 7 && optin > 0 { optin } else { per_block }; + let clamp = |capacity: u32| (capacity.max(1) as usize).min(MAX_T); + Self { + variant, + native_mmvf, + tile, + chunk_plain: clamp(usable / (tile * 4)), + chunk_staged: clamp(usable / (2 * STAGED_TILE * 4)), + usable_shared: usable, + // below sm_70 the attribute cannot raise the limit (and a card that rejects it is ignored + // by the Original), so no attribute is emitted there + attr_down: (cc_major >= 7 && optin > 0).then_some(want), + attr_staged: (cc_major >= 7 && optin > 0).then_some(want_staged), + } + } + + /// `from_device` with the attributes read from the verifier's device. + pub(crate) fn query( + journal: &OriginalVerifyGdnJournal<'_, '_>, + variant: GrVariant, + native_mmvf: bool, + ) -> Result { + Ok(Self::from_device( + variant, + native_mmvf, + journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MAJOR)?, + journal.window_device_attribute(ATTR_COMPUTE_CAPABILITY_MINOR)?, + journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK_OPTIN)?, + journal.window_device_attribute(ATTR_MAX_SHARED_PER_BLOCK)?, + )) + } + + fn down_entry(&self) -> &'static str { + if self.variant == GrVariant::Staged { + E_STAGED + } else if self.tile == 1280 { + E_DOWN1280 + } else { + E_DOWN2560 + } + } +} + +/// The `cuFuncSetAttribute(MAX_DYNAMIC_SHARED_SIZE)` calls `down_chunk` makes once per device +/// (`gr_down_multi_kernel` and `gr_down_staged_kernel`), to apply before capture. +pub(crate) fn shared_attributes(cfg: &GrConfig) -> Vec<(&'static AssetSpec, &'static str, usize)> { + let mut out = Vec::new(); + if let Some(bytes) = cfg.attr_down { + let entry = if cfg.tile == 1280 { E_DOWN1280 } else { E_DOWN2560 }; + out.push((&GR_FUSED, entry, bytes as usize)); + } + if let Some(bytes) = cfg.attr_staged { + out.push((&GR_FUSED, E_STAGED, bytes as usize)); + } + out +} + +/// PLE settings of the Original (`--native`: `ple_set_native_bf16` + `ple_set_native_postops`). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PleConfig { + /// `ple_set_native_bf16`: the value projection is the pinned BF16 MMVF. + pub native_value_bf16: bool, + /// `ple_set_native_postops`: pinned norms, gate, conv and residual. + pub native_postops: bool, + /// The dispatch of the native key MMVQ (`PleKey::Native`). + pub dispatch: NativeHeadDispatch, +} +impl PleConfig { + pub(crate) fn mode17() -> Self { + Self { native_value_bf16: true, native_postops: true, dispatch: NativeHeadDispatch::default() } + } +} + +// ------------------------------------------------------------------------------------------------ +// Weight addresses +// ------------------------------------------------------------------------------------------------ + +/// The four weights of one hc half (`hc_attn_*` / `hc_ffn_*` of one layer). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct HcAddrs { + pub norm: u64, + pub down: u64, + pub up: u64, + pub inject: u64, +} +/// `output_hc_{norm,down,up}` (the final mixer has no injection). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct HeadAddrs { + pub norm: u64, + pub down: u64, + pub up: u64, +} +/// The PLE key projection of the Original's `PleWeights`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PleKey { + /// `key_bf16`: `[n_embd, hc_dim]` BF16 (IQ model files). + Bf16(u64), + /// `key_native_data` of ggml type `ty` (42, 18, 23 or 8) with the q8_1 scratch in the arena. + Native { ty: u32, data: u64 }, +} +/// The `PleWeights` / `ss.ple` state of the layer-1 PLE block. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct PleAddrs { + pub key: PleKey, + pub value: u64, + pub norm_key: u64, + pub norm_query: u64, + pub norm_conv: u64, + pub conv1d: u64, + /// `ss.ple.scratch`: the `ple_block` workspace (first `PLE_SCRATCH_BYTES` are used). + pub scratch: u64, + /// `ss.ple.hist`: 9 rows x 10240 floats, row-fastest. + pub history: u64, +} + +/// `5 * hc_dim + n_embd + hc` floats of `ple_block`'s workspace; the Q8 / bf16 images behind it +/// are not used by the native path. +pub const PLE_SCRATCH_BYTES: usize = (5 * D + N + HC) * 4; +pub const PLE_HISTORY_BYTES: usize = 9 * D * 4; +pub const PLE_VALUE_BYTES: usize = N * N * 2; +pub const PLE_KEY_BF16_BYTES: usize = D * N * 2; +pub const PLE_NORM_BYTES: usize = D * 4; +pub const PLE_CONV_BYTES: usize = 4 * D * 2; +const SCRATCH_KEY: u64 = 0; +const SCRATCH_QUERY: u64 = (D * 4) as u64; +const SCRATCH_NORM: u64 = 2 * (D * 4) as u64; +const SCRATCH_GATED: u64 = 3 * (D * 4) as u64; +const SCRATCH_CONV: u64 = 4 * (D * 4) as u64; +const SCRATCH_VALUE: u64 = 5 * (D * 4) as u64; +const SCRATCH_GATE: u64 = SCRATCH_VALUE + (N * 4) as u64; + +// ------------------------------------------------------------------------------------------------ +// Shared helpers +// ------------------------------------------------------------------------------------------------ +fn check_geometry(geo: &OriginalVerifyGeometry) -> Result<()> { + if geo.n != N || geo.hc != HC || geo.lr != LR || !(1..=MAX_T).contains(&geo.max_t) { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn check_rows(geo: &OriginalVerifyGeometry, rows: Rows) -> Result<()> { + check_geometry(geo)?; + if rows.begin >= rows.end || rows.end > geo.max_t || rows.len() > MAX_T { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn row_span(arena: &dyn ArenaMap, name: &str, row: usize, row_bytes: usize) -> Result { + arena.span(name, row * row_bytes, row_bytes) +} +fn refuse(producer: &'static str) -> Error { + // The precise reasons are in the module docs; the error text is a `&'static str`. + match producer { + "head" => Error::InvalidDriverValue( + "Original verifier producer unavailable: head: only the native (gr_set_native_mmvf) head mix is sealed", + ), + "final_write" => Error::InvalidDriverValue( + "Original verifier producer unavailable: final_write: only the native gr_write (native_gr_post) is sealed", + ), + "ple_layer1" => Error::InvalidDriverValue( + "Original verifier producer unavailable: ple_layer1: only native PLE (native bf16 value + native post-ops) is sealed", + ), + _ => Error::UnsupportedQwenOperation, + } +} + +// ------------------------------------------------------------------------------------------------ +// hc_read: fused_gr_read_multi +// ------------------------------------------------------------------------------------------------ + +/// One window row's `FusedGrArgs` addresses. +#[derive(Clone, Copy)] +struct RowArgs { + r: u64, + bo_prev: u64, + inj_prev: u64, + lo: u64, + rs: u64, + inject_out: u64, + mixed: u64, +} + +/// `GrMulti` as the 114 words the wrapper kernels take by value. +fn multi_words(rows: &[RowArgs], w: &HcAddrs, apply: bool, xn: u64) -> Vec { + let mut words = vec![0u64; MULTI_WORDS]; + for (k, row) in rows.iter().enumerate() { + let a = &mut words[k * ARGS_WORDS..(k + 1) * ARGS_WORDS]; + a[0] = row.r; // R + a[1] = row.r; // R_out (in place) + a[2] = u64::from(apply); // bool apply (+ padding) + a[3] = row.bo_prev; + a[4] = row.inj_prev; + a[5] = w.norm; + a[6] = w.down; + a[7] = w.up; + a[8] = w.inject; + a[9] = u64::from(EPS.to_bits()); // float eps (+ padding) + a[10] = row.lo; + a[11] = row.rs; + a[12] = row.inject_out; + a[13] = row.mixed; + } + words[XN_WORD] = xn; + words[T_WORD] = rows.len() as u64; + words +} + +/// The down projection's launch for tokens `[c0, c0 + ct)` of the call: the whole `GrMulti` when it +/// is one chunk, else `GrMulti c{}` with `xn + c0 * D`, `T = ct` and `a[k] = m.a[c0 + k]`. +fn chunk_words(full: &[u64], n: usize, c0: usize, ct: usize) -> Vec { + if ct == n { + return full.to_vec(); + } + let mut words = vec![0u64; MULTI_WORDS]; + words[..ct * ARGS_WORDS].copy_from_slice(&full[c0 * ARGS_WORDS..(c0 + ct) * ARGS_WORDS]); + words[XN_WORD] = full[XN_WORD] + (c0 * D * 4) as u64; + words[T_WORD] = ct as u64; + words +} + +/// The kernels of one `fused_gr_read_multi` call in their order (`launch_multi`). The profile stamps +/// the Original puts after the norm and after the down launches (group 0 only, profile mode) are +/// the caller's: `norm`, then `down`, then `up`. +#[derive(Clone, Debug, PartialEq)] +pub(crate) struct HcReadPlan { + pub norm: Launch, + pub down: Vec, + pub up: Launch, +} +impl HcReadPlan { + pub(crate) fn launches(self) -> Vec { + let mut out = Vec::with_capacity(self.down.len() + 2); + out.push(self.norm); + out.extend(self.down); + out.push(self.up); + out + } +} + +/// `gr_read_group(half, apply, inj_prev, inj_out)` of `pre(l, group)` for the window rows +/// `[tb, te)`: `fused_gr_read_multi(fa, n, xn_ + tb * HC * N, ...)`. +/// +/// Per row `t`: `R = R_out = R_ + t*HC*N` (in place), `bo_prev = bo_ + t*N`, `lo = lo_ + t*hc_lr`, +/// `rs = rs_ + t*HC`, `mixed = mixed_ + t*N`; the attention half reads `inj2_` and writes `inj_`, the +/// FFN half the reverse. +pub(crate) fn plan_hc_read( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + w: &HcAddrs, + cfg: &GrConfig, + half: HcHalf, + apply: bool, + rows: Rows, +) -> Result { + check_rows(geo, rows)?; + let (inj_prev_name, inj_out_name) = match half { + HcHalf::Attention => ("inj2", "inj"), + HcHalf::Ffn => ("inj", "inj2"), + }; + let n = rows.len(); + let mut per_row = Vec::with_capacity(n); + for t in rows.begin..rows.end { + per_row.push(RowArgs { + r: row_span(arena, "R", t, D * 4)?, + bo_prev: row_span(arena, "bo", t, N * 4)?, + inj_prev: row_span(arena, inj_prev_name, t, HC * 4)?, + lo: row_span(arena, "lo", t, LR * 4)?, + rs: row_span(arena, "rs", t, HC * 4)?, + inject_out: row_span(arena, inj_out_name, t, HC * 4)?, + mixed: row_span(arena, "mixed", t, N * 4)?, + }); + } + let xn = arena.span("xn", rows.begin * D * 4, n * D * 4)?; + let full = multi_words(&per_row, w, apply, xn); + + // norm: variant >= split is [n, 4] blocks, the plain read [n] blocks + let norm = if cfg.variant == GrVariant::Plain { + Launch::new(&GR_FUSED, E_NORM, [n as u32, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + } else { + Launch::new(&GR_FUSED, E_SPLIT, [n as u32, HC as u32, 1], [THREADS, 1, 1], 0, vec![A::Words(full.clone())])? + }; + + // down: launches of as many tokens as the shared memory allows + let staged = cfg.variant == GrVariant::Staged; + let per_token = if staged { 2 * STAGED_TILE * 4 } else { cfg.tile * 4 }; + let chunk_tok = if staged { cfg.chunk_staged } else { cfg.chunk_plain }; + if chunk_tok == 0 { + return Err(Error::InvalidQwenShape); + } + let mut down = Vec::new(); + let mut c0 = 0; + while c0 < n { + let ct = (n - c0).min(chunk_tok); + let shared = ct as u32 * per_token; + if shared > cfg.usable_shared { + // the card cannot launch it (Original would fail the launch) + return Err(Error::InvalidProjectionShape); + } + down.push(Launch::new( + &GR_FUSED, + cfg.down_entry(), + [DOWN_BLOCKS, 1, 1], + [THREADS, 1, 1], + shared, + vec![A::Words(chunk_words(&full, n, c0, ct))], + )?); + c0 += ct; + } + + let up = Launch::new(&GR_FUSED, E_UP, [UP_BLOCKS, 1, 1], [THREADS, 1, 1], 0, vec![A::Words(full)])?; + Ok(HcReadPlan { norm, down, up }) +} + +// ------------------------------------------------------------------------------------------------ +// gr_write: the last layer's final residual write, and the PLE pending write +// ------------------------------------------------------------------------------------------------ + +/// `gr_write(Rt(t), bo_ + t*N, inj2_ + t*HC, gs, Rt(t), cs)` for one window row: `native_gr_post`. +fn write_row(arena: &dyn ArenaMap, cfg: &GrConfig, row: usize, producer: &'static str) -> Result { + if !cfg.native_mmvf { + return Err(refuse(producer)); + } + let r = row_span(arena, "R", row, D * 4)?; + let bo = row_span(arena, "bo", row, N * 4)?; + let inject = row_span(arena, "inj2", row, HC * 4)?; + Launch::new( + &GR_POST, + "mtp_full_native_write", + [(D as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(r), A::P(bo), A::P(inject), A::P(r), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)], + ) +} + +/// `for t in [tb, te): gr_write(Rt(t), bo_+t*N, inj2_+t*HC, gs, Rt(t), cs)` of the last layer. +pub(crate) fn plan_final_write( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + rows: Rows, +) -> Result> { + check_rows(geo, rows)?; + (rows.begin..rows.end).map(|t| write_row(arena, cfg, t, "final_write")).collect() +} + +// ------------------------------------------------------------------------------------------------ +// head: lm_head_mix per token +// ------------------------------------------------------------------------------------------------ + +/// The per-token `lm_head_mix(wt, g, bb, cs, err)` of the head section: the native +/// `gr_read(R, output_hc_norm, output_hc_down, output_hc_up, nullptr, ...)` writing the mixed row +/// `t` at `mixed_out_base + t*N*4` (the head rows' `mixed`, which the `head_->loaded()` path +/// quantizes and projects next). +/// +/// Per row, in order: `native_gr_rms_norm_weighted(R_t -> xn)`, `bf16_gemv_fp32_mmvf(xn, down -> lo)`, +/// `native_gr_down_silu(lo)`, `bf16_gemv_fp32_mmvf(lo, up -> gated)`, `native_gr_pre_gated(xn, +/// gated -> mixed)` (no injection: the final mixer). The Original's per-session `bb.gr` workspace +/// (xn, gated, lo) is carved from arena spans that are dead after the layers: `xn` slot `t`, `lo` +/// slot `t` and the first `HC*N` floats of `parts` slot `t`. +pub(crate) fn plan_head_mix( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + w: &HeadAddrs, + cfg: &GrConfig, + mixed_out_base: u64, + rows: usize, +) -> Result> { + check_geometry(geo)?; + if !(1..=geo.max_t).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + if !cfg.native_mmvf { + return Err(refuse("head")); + } + let mut out = Vec::with_capacity(rows * 5); + for t in 0..rows { + let r = row_span(arena, "R", t, D * 4)?; + let xn = row_span(arena, "xn", t, D * 4)?; + let lo = row_span(arena, "lo", t, LR * 4)?; + let gated = arena.span("parts", t * geo.k * N * 4, D * 4)?; + let mixed = mixed_out_base + (t * N * 4) as u64; + // native_gr_rms_norm_weighted(R, w_norm, xn, n_embd, hc, eps): n_cols >= 1024 -> <1024>, hc blocks + out.push(Launch::new( + &GR_NORM, + "mtp_full_gr_norm", + [HC as u32, 1, 1], + [1024, 1, 1], + 0, + vec![A::P(r), A::P(w.norm), A::P(xn), A::I32(N as i32), A::F32(EPS)], + )?); + out.push(plan_bf16_gemv(xn, D, w.down, lo, LR, D, LR, 1)?); + out.push(Launch::new( + &GR_POST, + "mtp_full_down_silu", + [(LR as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(lo), A::I32(LR as i32), A::F32(QUARTER)], + )?); + out.push(plan_bf16_gemv(lo, LR, w.up, gated, D, LR, D, 1)?); + out.push(Launch::new( + &GR_POST, + "mtp_full_pre_final", + [(N as u32).div_ceil(THREADS), 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(N as i32), A::I32(HC as i32), A::F32(QUARTER)], + )?); + } + Ok(out) +} + +// ------------------------------------------------------------------------------------------------ +// ple_layer1 +// ------------------------------------------------------------------------------------------------ + +/// One window row of the layer-1 PLE block (`for t in [tb, te)` of `pre(1, group)`), WITHOUT the +/// trailing `copy_from_mapped(hist_snap_ + t*HS, ss.ple.hist, HS)`: the caller records that with +/// `OriginalVerifyGdnJournal::capture_ple_snapshot(t)` after submitting this row, so each row's +/// snapshot sees that row's history. +/// +/// Order: `gr_write(Rt, bo, inj2 -> Rt)` (the pending layer-0 write), then `ple_block(ple_+t*N, Rt, +/// hist, w, po{normalized, result=Rt})`: key projection (BF16 MMVF, or q8_1 + MMVQ for a native +/// Q2_0 / IQ3_XXS / IQ4_XS / Q8_0 key), value projection (BF16 MMVF), `native_ple_postops` +/// (rms of the key, rms of the hidden, gate, broadcast, rms of the gated, conv + residual into +/// `Rt`), then `ple_history_advance(hist, normalized)`. +/// +/// The Original copies `normalized` out of the workspace (a device-to-device memcpy node) and then +/// shifts the history with `history_advance_kernel`; here `ple_history(T = 1)` reads `normalized` +/// from the workspace and performs the identical shift-and-append (pure data movement, same +/// 40x256 launch), so the memcpy node is not recorded. `native_ple_postops_batch`'s kernels at +/// `T = 1` have the single-token kernels' launch geometry and per-element arithmetic. +pub(crate) fn plan_ple_row( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + ple: &PleConfig, + a: &PleAddrs, + row: usize, +) -> Result> { + check_geometry(geo)?; + if row >= geo.max_t { + return Err(Error::InvalidQwenShape); + } + if !(ple.native_value_bf16 && ple.native_postops) { + return Err(refuse("ple_layer1")); + } + let mut out = Vec::with_capacity(14); + out.push(write_row(arena, cfg, row, "ple_layer1")?); + + let r = row_span(arena, "R", row, D * 4)?; + let emb = row_span(arena, "ple", row, N * 4)?; + let key = a.scratch + SCRATCH_KEY; + let query = a.scratch + SCRATCH_QUERY; + let norm = a.scratch + SCRATCH_NORM; + let gated = a.scratch + SCRATCH_GATED; + let conv = a.scratch + SCRATCH_CONV; + let value = a.scratch + SCRATCH_VALUE; + let gate = a.scratch + SCRATCH_GATE; + + // key = ple_key @ emb + match a.key { + PleKey::Bf16(w) => out.push(plan_bf16_gemv(emb, N, w, key, D, N, D, 1)?), + PleKey::Native { ty, data } => { + if !matches!(ty, 42 | 18 | 23 | 8) { + return Err(Error::UnsupportedQwenOperation); + } + let q8 = arena.span("xq", 0, q8_1_row_bytes(N))?; + out.push(plan_quantize_q8_1(emb, q8, N, 1)?); + out.push(plan_mmvq(&NativeWeight { ty, data }, q8, key, N, D, 1, ple.dispatch)?); + } + } + // value = ple_value @ emb + out.push(plan_bf16_gemv(emb, N, a.value, value, N, N, N, 1)?); + + // native_ple_postops(d_key, hidden, d_value, hist, w, {key=d_query, query=d_norm, gate=d_gate, + // gated=d_gated, normalized=d_norm, conv=d_conv, result=hidden}) + let rms = |input: u64, gamma: u64, output: u64| { + Launch::new(&PLE_BATCH, "ple_rms", [HC as u32, 1, 1], [1024, 1, 1], 0, vec![A::P(input), A::P(gamma), A::P(output)]) + }; + out.push(rms(key, a.norm_key, query)?); + out.push(rms(r, a.norm_query, norm)?); + out.push(Launch::new( + &PLE_BATCH, + "ple_gate", + [HC as u32, 1, 1], + [512, 1, 1], + 0, + vec![A::P(query), A::P(norm), A::P(gate), A::F32(1.0f32 / (N as f32).sqrt())], + )?); + let blocks = (D as u32) / THREADS; + out.push(Launch::new( + &PLE_BATCH, + "ple_broadcast", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(value), A::P(gate), A::P(gated), A::I32(1)], + )?); + out.push(rms(gated, a.norm_conv, norm)?); + out.push(Launch::new( + &PLE_BATCH, + "ple_conv", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(a.history), A::P(norm), A::P(a.conv1d), A::P(r), A::P(gated), A::P(conv), A::I32(1)], + )?); + // ple_history_advance(hist, normalized) + out.push(Launch::new( + &PLE_BATCH, + "ple_history", + [blocks, 1, 1], + [THREADS, 1, 1], + 0, + vec![A::P(a.history), A::P(norm), A::I32(1)], + )?); + Ok(out) +} + +/// `pre(1, group)`'s PLE loop for the rows `[tb, te)`: one `(row, launches)` entry per row, to be +/// submitted in order, each followed by `capture_ple_snapshot(row)`. +pub(crate) fn plan_ple_layer1( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + cfg: &GrConfig, + ple: &PleConfig, + a: &PleAddrs, + rows: Rows, +) -> Result)>> { + check_rows(geo, rows)?; + (rows.begin..rows.end).map(|t| Ok((t, plan_ple_row(arena, geo, cfg, ple, a, t)?))).collect() +} + +// ------------------------------------------------------------------------------------------------ +// Binding: the weights the runtime hands over +// ------------------------------------------------------------------------------------------------ + +/// The four buffers of one hc half: `norm` F32 `[hc*N]`, `down` BF16 `[hc_lr][hc*N]`, `up` BF16 +/// `[hc*N][hc_lr]`, `inject` BF16 `[hc][hc*N]`. +pub struct HcHalfBuffers<'a, 'ctx> { + pub norm: &'a DeviceBuffer<'ctx>, + pub down: &'a DeviceBuffer<'ctx>, + pub up: &'a DeviceBuffer<'ctx>, + pub inject: &'a DeviceBuffer<'ctx>, +} +pub struct HcLayerBuffers<'a, 'ctx> { + pub attention: HcHalfBuffers<'a, 'ctx>, + pub ffn: HcHalfBuffers<'a, 'ctx>, +} +/// `output_hc_norm.weight` / `output_hc_down.weight` / `output_hc_up.weight` (no injection). +pub struct HcOutputBuffers<'a, 'ctx> { + pub norm: &'a DeviceBuffer<'ctx>, + pub down: &'a DeviceBuffer<'ctx>, + pub up: &'a DeviceBuffer<'ctx>, +} +pub enum PleKeyBuffer<'a, 'ctx> { + /// BF16 `[hc_dim][n_embd]` (`PLE_KEY_BF16_BYTES`). + Bf16(&'a DeviceBuffer<'ctx>), + /// A native GGUF key of ggml type `ty` (42, 18, 23, 8): `hc_dim` rows of `n_embd`. + Native { ty: u32, data: &'a DeviceBuffer<'ctx> }, +} +/// The PLE weights and state of the layer-1 block. `history` must be the SAME buffer the verify +/// journal snapshots (`ss.ple.hist`). +pub struct PleBuffers<'a, 'ctx> { + pub key: PleKeyBuffer<'a, 'ctx>, + pub value: &'a DeviceBuffer<'ctx>, + pub norm_key: &'a DeviceBuffer<'ctx>, + pub norm_query: &'a DeviceBuffer<'ctx>, + pub norm_conv: &'a DeviceBuffer<'ctx>, + pub conv1d: &'a DeviceBuffer<'ctx>, + /// At least `PLE_SCRATCH_BYTES` (`ss.ple.scratch`). + pub scratch: &'a DeviceBuffer<'ctx>, + pub history: &'a DeviceBuffer<'ctx>, +} + +/// The weights of the GR family for the 48 layers, the final mixer and (optionally) the PLE block, +/// validated for context and exact byte sizes. +pub struct OriginalVerifyGrBinding<'a, 'ctx> { + context: &'ctx Context<'ctx>, + layers: Vec>, + output: HcOutputBuffers<'a, 'ctx>, + ple: Option>, +} +impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + layers: Vec>, + output: HcOutputBuffers<'a, 'ctx>, + ple: Option>, + ) -> Result { + if layers.len() != LAYERS { + return Err(Error::InvalidQwenShape); + } + let binding = Self { context, layers, output, ple }; + // fail early: every address is validated once here and again when it is used + for layer in 0..LAYERS { + binding.half_addrs(layer, HcHalf::Attention)?; + binding.half_addrs(layer, HcHalf::Ffn)?; + } + binding.head_addrs()?; + if binding.ple.is_some() { + binding.ple_addrs()?; + } + Ok(binding) + } + fn half(&self, layer: usize, half: HcHalf) -> Result<&HcHalfBuffers<'a, 'ctx>> { + let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?; + Ok(match half { + HcHalf::Attention => &l.attention, + HcHalf::Ffn => &l.ffn, + }) + } + /// `hc_attn_*` / `hc_ffn_*` of `layer`. + pub(crate) fn half_addrs(&self, layer: usize, half: HcHalf) -> Result { + let h = self.half(layer, half)?; + let c = self.context; + Ok(HcAddrs { + norm: admit(c, h.norm, HC_NORM_BYTES)?, + down: admit(c, h.down, HC_DOWN_BYTES)?, + up: admit(c, h.up, HC_UP_BYTES)?, + inject: admit(c, h.inject, HC_INJECT_BYTES)?, + }) + } + pub(crate) fn head_addrs(&self) -> Result { + let c = self.context; + Ok(HeadAddrs { + norm: admit(c, self.output.norm, HC_NORM_BYTES)?, + down: admit(c, self.output.down, HC_DOWN_BYTES)?, + up: admit(c, self.output.up, HC_UP_BYTES)?, + }) + } + pub fn has_ple(&self) -> bool { + self.ple.is_some() + } + pub(crate) fn ple_addrs(&self) -> Result { + let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?; + let c = self.context; + let key = match &p.key { + PleKeyBuffer::Bf16(b) => PleKey::Bf16(admit(c, b, PLE_KEY_BF16_BYTES)?), + PleKeyBuffer::Native { ty, data } => { + if !matches!(ty, 42 | 18 | 23 | 8) { + return Err(Error::UnsupportedQwenOperation); + } + let bytes = native_head_row_bytes(*ty, N)?.checked_mul(D).ok_or(Error::InvalidSize)?; + PleKey::Native { ty: *ty, data: admit(c, data, bytes)? } + } + }; + let scratch = p.scratch; + if !std::ptr::eq(c, scratch.context) { + return Err(Error::ContextMismatch); + } + if scratch.len() < PLE_SCRATCH_BYTES { + return Err(Error::ShapeMismatch { expected: PLE_SCRATCH_BYTES, actual: scratch.len() }); + } + let scratch_handle = handle(scratch)?; + scratch_handle.validate_projection_extent(PLE_SCRATCH_BYTES, 4)?; + Ok(PleAddrs { + key, + value: admit(c, p.value, PLE_VALUE_BYTES)?, + norm_key: admit(c, p.norm_key, PLE_NORM_BYTES)?, + norm_query: admit(c, p.norm_query, PLE_NORM_BYTES)?, + norm_conv: admit(c, p.norm_conv, PLE_NORM_BYTES)?, + conv1d: admit(c, p.conv1d, PLE_CONV_BYTES)?, + scratch: scratch_handle.qwen_address(), + history: admit(c, p.history, PLE_HISTORY_BYTES)?, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use super::super::kernels::{LayoutMap, test_geometry}; + + const BASE: u64 = 0x7000_0000_0000; + + fn arena() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) + } + fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + (m.layout.span(name).unwrap().offset + offset) as u64 + } + fn weights() -> HcAddrs { + HcAddrs { norm: 0x1000_0000, down: 0x2000_0000, up: 0x3000_0000, inject: 0x4000_0000 } + } + fn words(l: &Launch) -> &[u64] { + match &l.args[..] { + [A::Words(w)] => w, + other => panic!("expected one by-value struct, got {other:?}"), + } + } + fn rows(begin: usize, end: usize, group: usize) -> Rows { + Rows { begin, end, group } + } + /// RTX-class sm_120: 99 KiB opt-in, 48 KiB default per block. + fn sm120(variant: GrVariant) -> GrConfig { + GrConfig::from_device(variant, true, 12, 0, 101_376, 49_152) + } + fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) || ptx.contains(&format!(".visible .entry {e}(")) + } + + // ---------------------------------------------------------------------------------- assets + #[test] + fn assets_are_pinned_and_export_every_named_entry() { + for spec in assets() { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + // the six fused-gr wrappers take ONE 912-byte by-value struct (the Original GrMulti) + let text = String::from_utf8_lossy(GR_FUSED.ptx); + for e in GR_FUSED.entries { + assert!(text.contains(&format!("{e}_param_0[912]")), "{e} is not a GrMulti-by-value entry"); + } + } + + #[test] + fn struct_layout_constants_match_fused_gr_args() { + // FusedGrArgs: R,R_out,bool(+pad),bo,inj,wn,wd,wu,wi,float(+pad),lo,rs,inject,mixed = 112 bytes + assert_eq!(ARGS_WORDS * 8, 112); + // GrMulti: 8 * 112 + xn pointer + int T (+pad) = 912 bytes + assert_eq!(MULTI_WORDS * 8, 912); + assert_eq!((XN_WORD, T_WORD), (112, 113)); + assert_eq!(1e-6f32.to_bits(), 0x358637BD); + } + + // ----------------------------------------------------------------- down_chunk replication + #[test] + fn down_chunk_on_big_cards_runs_the_2560_tile_with_all_eight_tokens() { + let c = sm120(GrVariant::Staged); + assert_eq!(c.tile, 2560); + // 8 * 2560 * 4 = 81920 <= 101376 -> attribute is the full want + assert_eq!(c.attr_down, Some(81_920)); + // staged: 2 * 8 * 1280 * 4 = 81920 + assert_eq!(c.attr_staged, Some(81_920)); + // capacity 101376 / 10240 = 9 -> clamped to 8, both kinds + assert_eq!((c.chunk_plain, c.chunk_staged), (8, 8)); + assert_eq!(c.usable_shared, 101_376); + } + + #[test] + fn down_chunk_on_turing_slices_staged_tokens_and_uses_the_1280_tile() { + // sm_75: 64 KiB opt-in + let c = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + assert_eq!(c.tile, 1280); + assert_eq!(c.attr_down, Some(8 * 1280 * 4)); // 40960 fits + assert_eq!(c.attr_staged, Some(65_536)); // 81920 > opt-in -> opt-in + assert_eq!(c.chunk_plain, 8); // 65536 / 5120 = 12 -> 8 + assert_eq!(c.chunk_staged, 6); // 65536 / 10240 = 6 ("sm_75 carries 6 tokens") + } + + #[test] + fn down_chunk_below_volta_uses_the_per_block_limit_and_never_less_than_one_token() { + // sm_61 reports no usable opt-in: per-block limit 48 KiB + let c = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 49_152); + assert_eq!(c.tile, 2560); + assert_eq!((c.chunk_plain, c.chunk_staged), (4, 4)); // 49152 / 10240 + assert_eq!((c.attr_down, c.attr_staged), (None, None)); + // sm_60 answers a 64 KiB opt-in it does not keep: the limit is still per block + let c60 = GrConfig::from_device(GrVariant::Plain, true, 6, 0, 65_536, 49_152); + assert_eq!(c60.usable_shared, 49_152); + assert_eq!(c60.chunk_plain, 4); + assert_eq!((c60.attr_down, c60.attr_staged), (None, None)); + // a card that cannot hold one token still reports a chunk of 1 (the launch is then refused) + let tiny = GrConfig::from_device(GrVariant::Plain, true, 6, 1, 0, 4096); + assert_eq!((tiny.chunk_plain, tiny.chunk_staged), (1, 1)); + let m = arena(); + assert_eq!( + plan_hc_read(&m, &test_geometry(), &weights(), &tiny, HcHalf::Attention, false, rows(0, 2, 0)).unwrap_err(), + Error::InvalidProjectionShape + ); + } + + #[test] + fn shared_attributes_name_the_tile_kernel_of_the_card_and_the_staged_kernel() { + let big = shared_attributes(&sm120(GrVariant::Staged)); + assert_eq!(big.len(), 2); + assert_eq!((big[0].1, big[0].2), (E_DOWN2560, 81_920)); + assert_eq!((big[1].1, big[1].2), (E_STAGED, 81_920)); + assert!(big.iter().all(|a| std::ptr::eq(a.0, &GR_FUSED))); + let turing = shared_attributes(&GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152)); + assert_eq!((turing[0].1, turing[0].2), (E_DOWN1280, 40_960)); + assert_eq!((turing[1].1, turing[1].2), (E_STAGED, 65_536)); + } + + #[test] + fn variant_follows_strata_hc_split() { + assert_eq!(GrVariant::from_env_value(None), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("")), GrVariant::Staged); + assert_eq!(GrVariant::from_env_value(Some("0")), GrVariant::Plain); + assert_eq!(GrVariant::from_env_value(Some("1")), GrVariant::Split); + assert_eq!(GrVariant::from_env_value(Some("2")), GrVariant::Staged); + } + + // ------------------------------------------------------------------------------- hc_read + #[test] + fn staged_read_of_eight_rows_is_three_launch_kinds_with_the_multi_struct() { + let m = arena(); + let g = test_geometry(); + let w = weights(); + let plan = plan_hc_read(&m, &g, &w, &sm120(GrVariant::Staged), HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // norm: split, one block per token and stream + assert_eq!((plan.norm.entry, plan.norm.grid, plan.norm.block, plan.norm.shared), (E_SPLIT, [8, 4, 1], [256, 1, 1], 0)); + // down: ONE launch, 41 blocks, dynamic shared = 8 tokens * 2 * 1280 * 4 + assert_eq!(plan.down.len(), 1); + let d = &plan.down[0]; + assert_eq!((d.entry, d.grid, d.block, d.shared), (E_STAGED, [41, 1, 1], [256, 1, 1], 81_920)); + // up: 160 blocks of 16 columns + assert_eq!((plan.up.entry, plan.up.grid, plan.up.block, plan.up.shared), (E_UP, [160, 1, 1], [256, 1, 1], 0)); + let full = words(&plan.norm).to_vec(); + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(words(d), &full[..]); + assert_eq!(full.len(), 114); + // trailer: xn = xn_ + tb*HC*N*4, T = 8 + assert_eq!(full[112], at(&m, "xn", 0)); + assert_eq!(full[113], 8); + // token 3, attention half, apply + let a = &full[3 * 14..4 * 14]; + assert_eq!(a[0], at(&m, "R", 3 * 40_960)); + assert_eq!(a[1], a[0]); + assert_eq!(a[2], 1); + assert_eq!(a[3], at(&m, "bo", 3 * 10_240)); + assert_eq!(a[4], at(&m, "inj2", 3 * 16)); + assert_eq!(&a[5..9], &[w.norm, w.down, w.up, w.inject]); + assert_eq!(a[9], 0x358637BD); + assert_eq!(a[10], at(&m, "lo", 3 * 1280)); + assert_eq!(a[11], at(&m, "rs", 3 * 16)); + assert_eq!(a[12], at(&m, "inj", 3 * 16)); + assert_eq!(a[13], at(&m, "mixed", 3 * 10_240)); + // every distinct row has its own addresses + assert_ne!(full[0], full[14]); + } + + #[test] + fn ffn_half_swaps_the_injection_buffers_and_apply_is_carried() { + let m = arena(); + let g = test_geometry(); + let plan = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, false, rows(0, 1, 0)).unwrap(); + let a = &words(&plan.norm)[..14]; + assert_eq!(a[2], 0); + assert_eq!(a[4], at(&m, "inj", 0)); + assert_eq!(a[12], at(&m, "inj2", 0)); + // a single row: norm grid [1, 4] + assert_eq!(plan.norm.grid, [1, 4, 1]); + assert_eq!(words(&plan.norm)[113], 1); + assert_eq!(plan.down[0].shared, 10_240); + } + + #[test] + fn split_windows_read_their_own_rows_and_offset_the_scratch() { + let m = arena(); + let g = test_geometry(); + // T = 7 -> groups [0,4) and [4,7): (T+1)/2 = 4 + let g1 = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Staged), HcHalf::Ffn, true, rows(4, 7, 1)).unwrap(); + let w1 = words(&g1.norm); + assert_eq!(w1[112], at(&m, "xn", 4 * 40_960)); + assert_eq!(w1[113], 3); + assert_eq!(w1[0], at(&m, "R", 4 * 40_960)); + assert_eq!(w1[14 + 10], at(&m, "lo", 5 * 1280)); + assert_eq!(g1.norm.grid, [3, 4, 1]); + assert_eq!(g1.down[0].shared, 3 * 10_240); + // unused slots stay zero + assert!(w1[3 * 14..112].iter().all(|&x| x == 0)); + } + + #[test] + fn plain_and_split_variants_pick_the_norm_and_the_tile_kernel() { + let m = arena(); + let g = test_geometry(); + let plain = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Plain), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((plain.norm.entry, plain.norm.grid), (E_NORM, [5, 1, 1])); + assert_eq!((plain.down[0].entry, plain.down[0].shared), (E_DOWN2560, 5 * 2560 * 4)); + let split = plan_hc_read(&m, &g, &weights(), &sm120(GrVariant::Split), HcHalf::Attention, false, rows(0, 5, 0)).unwrap(); + assert_eq!((split.norm.entry, split.norm.grid), (E_SPLIT, [5, 4, 1])); + assert_eq!(split.down[0].entry, E_DOWN2560); + let turing = GrConfig::from_device(GrVariant::Plain, true, 7, 5, 65_536, 49_152); + let t = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, false, rows(0, 8, 0)).unwrap(); + assert_eq!((t.down[0].entry, t.down[0].shared), (E_DOWN1280, 8 * 1280 * 4)); + } + + #[test] + fn down_projection_is_chunked_by_the_card_capacity() { + let m = arena(); + let g = test_geometry(); + let turing = GrConfig::from_device(GrVariant::Staged, true, 7, 5, 65_536, 49_152); + let plan = plan_hc_read(&m, &g, &weights(), &turing, HcHalf::Attention, true, rows(0, 8, 0)).unwrap(); + // 8 tokens, 6 per launch -> 6 + 2 + assert_eq!(plan.down.len(), 2); + assert_eq!((plan.down[0].shared, plan.down[1].shared), (61_440, 20_480)); + let full = words(&plan.norm).to_vec(); + let first = words(&plan.down[0]); + let second = words(&plan.down[1]); + // the first chunk is a FRESH struct: tokens 0..6, T = 6, same xn + assert_eq!(first[113], 6); + assert_eq!(first[112], full[112]); + assert_eq!(&first[..6 * 14], &full[..6 * 14]); + assert!(first[6 * 14..112].iter().all(|&x| x == 0)); + // the second: tokens 6..8 moved to slots 0..2, xn advanced by 6 * D floats, T = 2 + assert_eq!(second[113], 2); + assert_eq!(second[112], full[112] + 6 * 40_960); + assert_eq!(&second[..2 * 14], &full[6 * 14..8 * 14]); + assert!(second[2 * 14..112].iter().all(|&x| x == 0)); + // norm and up still see all eight tokens + assert_eq!(words(&plan.up), &full[..]); + assert_eq!(plan.norm.grid, [8, 4, 1]); + assert_eq!(plan.clone().launches().len(), 4); + // launches() keeps the Original order: norm, down..., up + let order: Vec<&str> = plan.launches().iter().map(|l| l.entry).collect(); + assert_eq!(order, [E_SPLIT, E_STAGED, E_STAGED, E_UP]); + } + + #[test] + fn hc_read_validates_rows_and_geometry() { + let m = arena(); + let g = test_geometry(); + let c = sm120(GrVariant::Staged); + let w = weights(); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(3, 3, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(0, 9, 0)).is_err()); + assert!(plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, false, rows(7, 9, 1)).is_err()); + let mut odd = g; + odd.hc = 8; + assert_eq!( + plan_hc_read(&m, &odd, &w, &c, HcHalf::Attention, false, rows(0, 1, 0)).unwrap_err(), + Error::InvalidQwenShape + ); + // every T = 1..=8 and both groups of the split window plan + for t in 1..=8usize { + let first = (t + 1) / 2; + let groups = if t >= 2 { vec![(0, first), (first, t)] } else { vec![(0, t)] }; + for (gi, (b, e)) in groups.into_iter().enumerate() { + let plan = plan_hc_read(&m, &g, &w, &c, HcHalf::Attention, true, rows(b, e, gi)).unwrap(); + assert_eq!(words(&plan.up)[113], (e - b) as u64); + assert_eq!(plan.norm.grid[0], (e - b) as u32); + } + } + } + + // ----------------------------------------------------------------------------- final write + #[test] + fn final_write_is_native_post_in_place_per_row() { + let m = arena(); + let g = test_geometry(); + let l = plan_final_write(&m, &g, &sm120(GrVariant::Staged), rows(2, 5, 0)).unwrap(); + assert_eq!(l.len(), 3); + for (i, launch) in l.iter().enumerate() { + let t = 2 + i; + assert!(std::ptr::eq(launch.asset, &GR_POST)); + assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_full_native_write", [40, 1, 1], [256, 1, 1], 0)); + assert_eq!( + launch.args, + vec![ + A::P(at(&m, "R", t * 40_960)), + A::P(at(&m, "bo", t * 10_240)), + A::P(at(&m, "inj2", t * 16)), + A::P(at(&m, "R", t * 40_960)), + A::I32(2560), + A::I32(4), + A::F32(0.25), + ] + ); + } + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_final_write(&m, &g, &non_native, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("final_write") + )); + } + + // ------------------------------------------------------------------------------------ head + #[test] + fn head_mix_is_the_native_unfused_gr_read_per_token() { + let m = arena(); + let g = test_geometry(); + let w = HeadAddrs { norm: 0xA000, down: 0xB000, up: 0xC000 }; + let mixed_base = 0x9999_0000u64; + let l = plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 3).unwrap(); + assert_eq!(l.len(), 15); + for t in 0..3usize { + let k = &l[t * 5..t * 5 + 5]; + let r = at(&m, "R", t * 40_960); + let xn = at(&m, "xn", t * 40_960); + let lo = at(&m, "lo", t * 1280); + let gated = at(&m, "parts", t * 10 * 2560 * 4); + let mixed = mixed_base + (t * 10_240) as u64; + // 1. native_gr_rms_norm_weighted: hc blocks of 1024 threads + assert_eq!((k[0].entry, k[0].grid, k[0].block), ("mtp_full_gr_norm", [4, 1, 1], [1024, 1, 1])); + assert_eq!(k[0].args, vec![A::P(r), A::P(0xA000), A::P(xn), A::I32(2560), A::F32(1e-6)]); + // 2. bf16_gemv_fp32_mmvf(xn, down -> lo, 10240 -> 320): mmvf block 256 + assert_eq!((k[1].entry, k[1].grid, k[1].block), ("mtp_full_mmvf256", [320, 1, 1], [256, 1, 1])); + assert_eq!(k[1].args, vec![A::P(xn), A::P(0xB000), A::P(lo), A::I32(10_240)]); + // 3. native_gr_down_silu(lo, 320, 1/4): ceil(320/256) = 2 blocks + assert_eq!((k[2].entry, k[2].grid, k[2].block), ("mtp_full_down_silu", [2, 1, 1], [256, 1, 1])); + assert_eq!(k[2].args, vec![A::P(lo), A::I32(320), A::F32(0.25)]); + // 4. bf16_gemv_fp32_mmvf(lo, up -> gated, 320 -> 10240): mmvf block 160 (ceil(320/320) = 1 iteration) + assert_eq!((k[3].entry, k[3].grid, k[3].block), ("mtp_full_mmvf160", [10_240, 1, 1], [160, 1, 1])); + assert_eq!(k[3].args, vec![A::P(lo), A::P(0xC000), A::P(gated), A::I32(320)]); + // 5. native_gr_pre_gated(xn, gated, mixed, n, hc, 1/4): 10 blocks + assert_eq!((k[4].entry, k[4].grid, k[4].block), ("mtp_full_pre_final", [10, 1, 1], [256, 1, 1])); + assert_eq!(k[4].args, vec![A::P(xn), A::P(gated), A::P(mixed), A::I32(2560), A::I32(4), A::F32(0.25)]); + } + // the whole window: 1..=8 rows; none beyond max_t + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 8).is_ok()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 9).is_err()); + assert!(plan_head_mix(&m, &g, &w, &sm120(GrVariant::Staged), mixed_base, 0).is_err()); + let mut non_native = sm120(GrVariant::Staged); + non_native.native_mmvf = false; + assert!(matches!( + plan_head_mix(&m, &g, &w, &non_native, mixed_base, 1), + Err(Error::InvalidDriverValue(s)) if s.contains("head") + )); + } + + // ------------------------------------------------------------------------------------ PLE + fn ple_addrs(key: PleKey) -> PleAddrs { + PleAddrs { + key, + value: 0x5000_0000, + norm_key: 0x5100_0000, + norm_query: 0x5200_0000, + norm_conv: 0x5300_0000, + conv1d: 0x5400_0000, + scratch: 0x6000_0000, + history: 0x6100_0000, + } + } + + #[test] + fn ple_scratch_matches_ple_block_workspace_carving() { + // 5 * hc_dim + n_embd + hc floats: key, query, norm, gated, conv, value, gate + assert_eq!(PLE_SCRATCH_BYTES, 215_056); + assert_eq!(SCRATCH_QUERY, 40_960); + assert_eq!(SCRATCH_NORM, 81_920); + assert_eq!(SCRATCH_GATED, 122_880); + assert_eq!(SCRATCH_CONV, 163_840); + assert_eq!(SCRATCH_VALUE, 204_800); + assert_eq!(SCRATCH_GATE, 215_040); + assert_eq!(SCRATCH_GATE + 16, PLE_SCRATCH_BYTES as u64); + } + + #[test] + fn ple_row_with_a_bf16_key_follows_ple_block_native_order() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 2).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!( + names, + [ + "mtp_full_native_write", // the pending layer-0 gr_write + "mtp_full_mmvf256", // key = ple_key @ emb (10240 x 2560) + "mtp_full_mmvf256", // value = ple_value @ emb (2560 x 2560) + "ple_rms", // key norm -> d_query + "ple_rms", // hidden norm -> d_norm + "ple_gate", + "ple_broadcast", + "ple_rms", // gated norm -> d_norm + "ple_conv", + "ple_history", + ] + ); + let r = at(&m, "R", 2 * 40_960); + let emb = at(&m, "ple", 2 * 10_240); + let s = 0x6000_0000u64; + assert_eq!(l[0].args[0], A::P(r)); + assert_eq!(l[0].args[3], A::P(r)); + // key: x = emb, y = scratch key (ldy = 10240), 2560 -> 10240 + assert_eq!(l[1].grid, [10_240, 1, 1]); + assert_eq!(l[1].args, vec![A::P(emb), A::P(0x7000_0000), A::P(s), A::I32(2560)]); + // value: y = scratch value, 2560 -> 2560 + assert_eq!(l[2].grid, [2560, 1, 1]); + assert_eq!(l[2].args, vec![A::P(emb), A::P(0x5000_0000), A::P(s + 204_800), A::I32(2560)]); + // postops: rms(key -> query), rms(hidden -> norm), gate(query, norm -> gate), ... + assert_eq!(l[3].args, vec![A::P(s), A::P(0x5100_0000), A::P(s + 40_960)]); + assert_eq!(l[4].args, vec![A::P(r), A::P(0x5200_0000), A::P(s + 81_920)]); + assert_eq!((l[3].grid, l[3].block), ([4, 1, 1], [1024, 1, 1])); + assert_eq!((l[5].grid, l[5].block), ([4, 1, 1], [512, 1, 1])); + assert_eq!(l[5].args, vec![A::P(s + 40_960), A::P(s + 81_920), A::P(s + 215_040), A::F32(1.0 / 2560f32.sqrt())]); + assert_eq!((l[6].grid, l[6].block), ([40, 1, 1], [256, 1, 1])); + assert_eq!(l[6].args, vec![A::P(s + 204_800), A::P(s + 215_040), A::P(s + 122_880), A::I32(1)]); + assert_eq!(l[7].args, vec![A::P(s + 122_880), A::P(0x5300_0000), A::P(s + 81_920)]); + // conv + residual: hidden = Rt in place + assert_eq!( + l[8].args, + vec![A::P(0x6100_0000), A::P(s + 81_920), A::P(0x5400_0000), A::P(r), A::P(s + 122_880), A::P(s + 163_840), A::I32(1)] + ); + assert_eq!((l[8].grid, l[8].block), ([40, 1, 1], [256, 1, 1])); + // history advance reads the normalized row from the workspace + assert_eq!(l[9].args, vec![A::P(0x6100_0000), A::P(s + 81_920), A::I32(1)]); + assert_eq!((l[9].grid, l[9].block), ([40, 1, 1], [256, 1, 1])); + for launch in &l[3..] { + assert!(std::ptr::eq(launch.asset, &PLE_BATCH)); + } + } + + #[test] + fn ple_row_with_a_native_key_quantizes_into_the_arena_and_runs_mmvq() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Native { ty: 42, data: 0x7100_0000 }); + let l = plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &a, 0).unwrap(); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!(&names[..4], &["mtp_full_native_write", "head_quant", "head_n42_s1", "mtp_full_mmvf256"]); + assert_eq!(l.len(), 11); + let q8 = at(&m, "xq", 0); + let emb = at(&m, "ple", 0); + assert_eq!(l[1].args, vec![A::P(emb), A::P(q8), A::I32(2560)]); + // 2560 / 64 = 40 blocks < 64 per iteration: the "small" layout, 4 rows per block + assert_eq!((l[2].grid, l[2].block), ([2560, 1, 1], [32, 4, 1])); + assert_eq!( + l[2].args, + vec![A::P(0x7100_0000), A::P(q8), A::P(0x6000_0000), A::I32(2560), A::I32(10_240)] + ); + // an unsupported native key type fails closed + let bad = ple_addrs(PleKey::Native { ty: 14, data: 1 }); + assert_eq!( + plan_ple_row(&m, &g, &sm120(GrVariant::Staged), &PleConfig::mode17(), &bad, 0).unwrap_err(), + Error::UnsupportedQwenOperation + ); + } + + #[test] + fn ple_layer1_walks_the_group_rows_in_order_and_fails_closed_on_policy() { + let m = arena(); + let g = test_geometry(); + let a = ple_addrs(PleKey::Bf16(0x7000_0000)); + let c = sm120(GrVariant::Staged); + let out = plan_ple_layer1(&m, &g, &c, &PleConfig::mode17(), &a, rows(4, 7, 1)).unwrap(); + assert_eq!(out.iter().map(|(t, _)| *t).collect::>(), [4, 5, 6]); + assert!(out.iter().all(|(_, l)| l.len() == 10)); + let mut legacy = PleConfig::mode17(); + legacy.native_postops = false; + assert!(matches!( + plan_ple_layer1(&m, &g, &c, &legacy, &a, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("ple_layer1") + )); + legacy = PleConfig::mode17(); + legacy.native_value_bf16 = false; + assert!(plan_ple_row(&m, &g, &c, &legacy, &a, 0).is_err()); + assert!(plan_ple_row(&m, &g, &c, &PleConfig::mode17(), &a, 8).is_err()); + } + + // ---------------------------------------------------------------------------- byte sizes + #[test] + fn weight_byte_sizes_follow_the_hc_geometry() { + // hc=4, N=2560, hc_lr=320 + assert_eq!(HC_NORM_BYTES, 4 * 2560 * 4); + assert_eq!(HC_DOWN_BYTES, 320 * 4 * 2560 * 2); + assert_eq!(HC_UP_BYTES, 4 * 2560 * 320 * 2); + assert_eq!(HC_INJECT_BYTES, 4 * 4 * 2560 * 2); + assert_eq!(PLE_HISTORY_BYTES, 9 * 4 * 2560 * 4); + assert_eq!(PLE_VALUE_BYTES, 2560 * 2560 * 2); + assert_eq!(PLE_KEY_BF16_BYTES, 10_240 * 2560 * 2); + assert_eq!(PLE_CONV_BYTES, 4 * 10_240 * 2); + // a Q2_0 key: 64-element blocks of 18 bytes -> 40 blocks per row + assert_eq!(native_head_row_bytes(42, 2560).unwrap(), 40 * 18); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_kernels.rs b/crates/cuda-driver/src/original_verify_window_kernels.rs new file mode 100644 index 00000000..702f394d --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_kernels.rs @@ -0,0 +1,226 @@ +//! Kernel launch plans of the literal Verifier window (child of `original_verify`). +//! +//! A producer of the window never touches the driver directly: it computes a +//! `Vec` (pure arithmetic over arena/weight addresses, unit tested) and +//! the window ops submit it on the capture stream. Every kernel belongs to a +//! sealed PTX asset (`AssetSpec`: the bytes, their SHA-256 pin and the exact set of +//! entries a producer may name). An asset that is not sealed/present fails closed +//! with its name; no producer substitutes other arithmetic. +use super::abi::{Arg, Command}; +use crate::{Error, Result}; + +/// One sealed PTX module a window producer launches from. +/// +/// `ptx` is the whole file INCLUDING the single terminal NUL the loader requires +/// (the SHA is over the bytes before it, exactly like `sealed_asset`). `entries` +/// are the symbol names loaded with `cuModuleGetFunction`; a `Launch` may only +/// name one of them. +pub(crate) struct AssetSpec { + pub name: &'static str, + pub ptx: &'static [u8], + pub sha: [u8; 32], + pub entries: &'static [&'static str], + /// Static, human-readable refusal returned when the asset is not sealed. + pub unsealed: &'static str, +} +impl std::fmt::Debug for AssetSpec { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "AssetSpec({})", self.name) + } +} +impl AssetSpec { + /// The PTX is acceptable for loading: one terminal NUL, no interior NUL, not marked + /// UNSEALED and equal to its pinned digest. + pub(crate) fn sealed(&self) -> Result<&'static [u8]> { + let p = self.ptx; + if p.len() < 2 || p.last() != Some(&0) || p[..p.len() - 1].contains(&0) { + return Err(Error::InvalidDriverValue(self.unsealed)); + } + if p.windows(8).any(|w| w == b"UNSEALED") || crate::qwen_ffi::sha256(&p[..p.len() - 1]) != self.sha { + return Err(Error::InvalidDriverValue(self.unsealed)); + } + Ok(p) + } + /// Module identity: specs of the same PTX file share one loaded module (their entry lists are + /// unioned). A `#suffix` on the name only distinguishes specs that list different entries. + pub(crate) fn key(&self) -> &'static str { + self.name.split('#').next().unwrap_or(self.name) + } + pub(crate) fn has_entry(&self, entry: &str) -> bool { + self.entries.contains(&entry) + } +} + +/// One kernel argument (the ABI `Arg` without a driver object, so plans compare in tests). +#[derive(Clone, Debug, PartialEq)] +pub(crate) enum A { + /// Device (or mapped-device) address. + P(u64), + I32(i32), + I64(i64), + U64(u64), + F32(f32), + /// A by-value struct parameter, as little-endian u64 words. + Words(Vec), +} +impl A { + fn abi(&self) -> Arg { + match self { + A::P(v) => Arg::Address(*v), + A::I32(v) => Arg::I32(*v), + A::I64(v) => Arg::I64(*v), + A::U64(v) => Arg::U64(*v), + A::F32(v) => Arg::F32(*v), + A::Words(v) => Arg::Words(v.clone().into_boxed_slice()), + } + } +} + +/// One `cuLaunchKernel`: `<<>>` of `entry` in `asset`. +#[derive(Clone, Debug)] +pub(crate) struct Launch { + pub asset: &'static AssetSpec, + pub entry: &'static str, + pub grid: [u32; 3], + pub block: [u32; 3], + pub shared: u32, + pub args: Vec, +} +impl PartialEq for Launch { + fn eq(&self, o: &Self) -> bool { + std::ptr::eq(self.asset, o.asset) + && self.entry == o.entry + && self.grid == o.grid + && self.block == o.block + && self.shared == o.shared + && self.args == o.args + } +} +impl Launch { + /// Refuses an entry the asset does not export and degenerate geometry. + pub(crate) fn new( + asset: &'static AssetSpec, + entry: &'static str, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result { + if !asset.has_entry(entry) || grid.contains(&0) || block.contains(&0) { + return Err(Error::InvalidQwenShape); + } + Ok(Self { asset, entry, grid, block, shared, args }) + } + pub(crate) fn command(&self) -> Result { + Command::new(self.entry, self.grid, self.block, self.shared, self.args.iter().map(A::abi).collect()) + } + /// Short text used by unit tests and by diagnostics: `asset:entry <<>>`. + pub(crate) fn label(&self) -> String { + format!("{}:{} <<<{:?},{:?},{}>>>", self.asset.name, self.entry, self.grid, self.block, self.shared) + } +} + +/// The address of a named arena span (`OriginalVerifyLayout` spans carved from one +/// allocation). The real implementation is the verifier journal; tests use a base +/// address plus the pure layout so every offset is the real one. +pub(crate) trait ArenaMap { + fn span(&self, name: &str, offset: usize, bytes: usize) -> Result; +} + +/// Pure test double of `ArenaMap`: `base + layout.span(name).offset + offset`, with the same +/// bounds refusal as the real arena. +#[cfg(test)] +pub(crate) struct LayoutMap { + pub base: u64, + pub layout: super::layout::OriginalVerifyLayout, +} +#[cfg(test)] +impl LayoutMap { + pub(crate) fn new(base: u64, geometry: super::OriginalVerifyGeometry) -> Self { + Self { base, layout: super::layout::OriginalVerifyLayout::new(geometry).expect("layout") } + } +} +#[cfg(test)] +impl ArenaMap for LayoutMap { + fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + let s = self.layout.span(name)?; + if bytes == 0 || offset.checked_add(bytes).is_none_or(|n| n > s.bytes) { + return Err(Error::InvalidSize); + } + Ok(self.base + (s.offset + offset) as u64) + } +} + +/// The geometry of a mode17 target at the window's maximum T = 8 (the shapes +/// `OriginalVerifyGeometry::validate` admits), shared by the plan unit tests. +#[cfg(test)] +pub(crate) fn test_geometry() -> super::OriginalVerifyGeometry { + super::OriginalVerifyGeometry { + max_t: 8, + n: 2560, + hc: 4, + lr: 320, + ff: 640, + experts: 512, + k: 10, + channels: 10240, + value_heads: 48, + key_heads: 16, + heads: 24, + kv_heads: 2, + head_dim: 256, + index_heads: 4, + index_dim: 128, + index_block: 4, + selection: 2051, + max_cells: 4096, + vocabulary: 248320, + max_expert_blob: 1 << 20, + } +} + +#[cfg(test)] +mod tests { + use super::*; + static SPEC: AssetSpec = AssetSpec { + name: "demo", + ptx: b"// demo\n\0", + sha: [0; 32], + entries: &["a", "b"], + unsealed: "demo unsealed", + }; + + #[test] + fn launch_refuses_foreign_entries_and_empty_geometry() { + assert!(Launch::new(&SPEC, "a", [1, 1, 1], [32, 1, 1], 0, vec![]).is_ok()); + assert_eq!(Launch::new(&SPEC, "c", [1, 1, 1], [32, 1, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(Launch::new(&SPEC, "a", [0, 1, 1], [32, 1, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(Launch::new(&SPEC, "a", [1, 1, 1], [32, 0, 1], 0, vec![]).unwrap_err(), Error::InvalidQwenShape); + } + + #[test] + fn a_pin_mismatch_fails_closed_with_the_asset_name() { + // all-zero digest cannot match any PTX + assert_eq!(SPEC.sealed().unwrap_err(), Error::InvalidDriverValue("demo unsealed")); + static MARK: AssetSpec = AssetSpec { name: "m", ptx: b"UNSEALED placeholder\n\0", sha: [0; 32], entries: &[], unsealed: "m unsealed" }; + assert_eq!(MARK.sealed().unwrap_err(), Error::InvalidDriverValue("m unsealed")); + static NONUL: AssetSpec = AssetSpec { name: "n", ptx: b"abc", sha: [0; 32], entries: &[], unsealed: "n unsealed" }; + assert_eq!(NONUL.sealed().unwrap_err(), Error::InvalidDriverValue("n unsealed")); + } + + #[test] + fn layout_map_resolves_the_real_carve_offsets_and_bounds() { + let m = LayoutMap::new(0x1000_0000, test_geometry()); + let r = m.layout.span("R").unwrap(); + assert_eq!(m.span("R", 0, 16).unwrap(), 0x1000_0000 + r.offset as u64); + assert_eq!(m.span("R", 64, 16).unwrap(), 0x1000_0000 + r.offset as u64 + 64); + assert!(m.span("R", r.bytes, 4).is_err()); + assert!(m.span("nope", 0, 4).is_err()); + } + + #[test] + fn launch_label_names_asset_entry_and_geometry() { + let l = Launch::new(&SPEC, "b", [2, 3, 1], [32, 4, 1], 16, vec![A::I32(1)]).unwrap(); + assert_eq!(l.label(), "demo:b <<<[2, 3, 1],[32, 4, 1],16>>>"); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_moe.rs b/crates/cuda-driver/src/original_verify_window_moe.rs new file mode 100644 index 00000000..2a9ba97e --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_moe.rs @@ -0,0 +1,1512 @@ +//! MoE / FFN producers of the Verifier window (child of `original_verify`): the FFN half of +//! `pre` and `post` of `Verifier::record_window` (engine/strata/src/core/verify.cpp) as pure launch plans +//! over sealed assets. +//! +//! ```text +//! pre : gr_read_group(1) | router | doorbell (bound elsewhere) | shared expert | expert-input quantization +//! post : wait plan (bound) | grouped experts VRAM | wait (bound) | grouped experts PCIe | wait (bound) +//! | copy cpu rows (bound) | hit add | combine +//! ``` +//! +//! Every producer returns the launches of its Strata call in the Original's order, with the Original's +//! grids, blocks and argument lists; nothing is substituted: +//! +//! * `router`: batched (`dec_batch && n > 1 && native_router`): `bf16_gemv_fp32_mmvf_multi` + +//! `native_router_top10_multi` (`route<<>>`); otherwise per token `moe_route` +//! (`project_bf16` = `bf16_gemv_fp32_mmvf` under `--native-bf16`, then `native_router_top10` or the generic +//! `router_top10_kernel<<<1, 512, 6656>>>`). +//! * `shared_expert`: `f32_to_bf16_bulk`, then `shared_expert_multi` = q8_1 quantize, native MMVQ gate and up, +//! `native_swiglu_kernel`, quantize, native MMVQ down, the scalar gate (`bf16_gemv_fp32_mmvf(_multi)` + +//! `native_scalar_sigmoid(_multi)_kernel` under `--native-bf16-extra`, else `scalar_gate_kernel`) and +//! `scale_rows_kernel`. +//! * `quantize_expert_input`: `quantize_q8_1_rows` (native experts). The S2 Q8_0 scaled experts +//! (`quantize_q8_0_scaled` + `moe_grouped_s2`) have no window owner and fail closed. +//! * `expert_groups`: `native_expert_grouped` = gate/up kernel, `swiglu_entries_kernel`, +//! `quantize_q8_1_kernel`, down kernel, per (gate/up, down) format of the layer. +//! * `hit_add`: `moe_hit_add` (`add_hits_kernel`). +//! * `combine`: `native_moe_combine_multi` (batched) / `native_moe_combine` / `moe_combine` per token. +//! +//! The gate/up and down grouped kernels are TEMPLATES no sealed PTX instantiates for the target's formats; +//! they live in the new source `original_verify_window_moe_experts.cu` (placeholder PTX until Root seals it), +//! so the expert producers fail closed with the asset's refusal text until then. Everything else launches +//! from PTX that is already sealed in this tree. +use super::kernels::{A, ArenaMap, AssetSpec, Launch}; +use super::proj::{self, NativeWeight, plan_bf16_gemv, plan_mmvq, plan_quantize_q8_1}; +use super::window_plan::{PlanLayout, WINDOW_LAYERS}; +use super::window_record::{ExpertTier, Rows}; +use super::{OriginalVerifyGeometry, admit, handle}; +use crate::native_head::native_head_row_bytes; +use crate::{Context, DeviceBuffer, Error, NativeHeadDispatch, Result}; + +macro_rules! unavailable { + ($producer:literal, $why:literal) => { + Err(Error::InvalidDriverValue(concat!("Original verifier producer unavailable: ", $producer, ": ", $why))) + }; +} + +// --------------------------------------------------------------------------------------------- +// Sealed assets +// --------------------------------------------------------------------------------------------- + +const E_TO_BF16: &str = + "_ZN6strata7kernels61_GLOBAL__N__c914d947_28_mtp_original_full_element_cu_4a5c8c9814to_bf16_kernelEPKfPtl"; +/// `elementwise.cu` (`f32_to_bf16_bulk`). +pub(crate) static ELEMENT: AssetSpec = AssetSpec { + name: "mtp_original_full_element.ptx", + ptx: include_bytes!("mtp_original_full_element.ptx"), + sha: [143,223,223,142,246,22,105,140,18,48,31,125,244,113,111,192,34,191,52,180,25,9,158,76,151,39,41,146,11,213,244,167], + entries: &[E_TO_BF16], + unsealed: "Original verifier asset unsealed: mtp_original_full_element.ptx (f32_to_bf16_bulk)", +}; + +const E_ROUTE: &str = "mtp_full_route"; +/// `native_router.cu` (`native_router_top10(_multi)`). +pub(crate) static ROUTER: AssetSpec = AssetSpec { + name: "mtp_original_full_router.ptx", + ptx: include_bytes!("mtp_original_full_router.ptx"), + sha: [197,185,51,181,1,6,131,169,42,218,65,77,49,33,86,187,222,135,198,197,155,177,248,131,113,58,6,130,161,89,32,228], + entries: &[E_ROUTE], + unsealed: "Original verifier asset unsealed: mtp_original_full_router.ptx (native router top-10)", +}; + +const E_ROUTER_TOP10: &str = + "_ZN6strata7kernels67_GLOBAL__N__bb863e17_34_mtp_original_full_router_legacy_cu_731ba72319router_top10_kernelEPKfiiiPiPf"; +/// `router_top10.cu` (`router_top10`, the generic router when the native one is off). +pub(crate) static ROUTER_LEGACY: AssetSpec = AssetSpec { + name: "mtp_original_full_router_legacy.ptx", + ptx: include_bytes!("mtp_original_full_router_legacy.ptx"), + sha: [165,132,18,36,151,87,204,53,30,184,51,46,128,126,121,241,179,218,88,101,87,77,15,183,23,158,245,88,223,112,175,36], + entries: &[E_ROUTER_TOP10], + unsealed: "Original verifier asset unsealed: mtp_original_full_router_legacy.ptx (router_top10)", +}; + +const E_NATIVE_SWIGLU: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f20native_swiglu_kernelEPKfS3_Pfi"; +const E_SCALAR_GATE: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18scalar_gate_kernelEPKtS3_Pfi"; +const E_SIGMOID: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f28native_scalar_sigmoid_kernelEPf"; +const E_SIGMOID_MULTI: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f34native_scalar_sigmoid_multi_kernelEPf"; +const E_SCALE_ROWS: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f17scale_rows_kernelEPfPKfi"; +const E_MOE_COMBINE: &str = + "_ZN6strata7kernels60_GLOBAL__N__f559df67_27_mtp_original_full_shared_cu_0708558f18moe_combine_kernelEPKfS3_S3_Pfiii"; +/// `shared_expert.cu` (the Original TU: `shared_expert_multi`'s kernels and `moe_combine`). +pub(crate) static SHARED: AssetSpec = AssetSpec { + name: "mtp_original_full_shared.ptx", + ptx: include_bytes!("mtp_original_full_shared.ptx"), + sha: [179,111,67,38,146,228,63,121,72,162,83,140,34,202,181,94,246,124,98,91,141,68,97,198,124,162,162,117,25,185,224,240], + entries: &[E_NATIVE_SWIGLU, E_SCALAR_GATE, E_SIGMOID, E_SIGMOID_MULTI, E_SCALE_ROWS, E_MOE_COMBINE], + unsealed: "Original verifier asset unsealed: mtp_original_full_shared.ptx (shared expert)", +}; + +const E_SWIGLU_ENTRIES: &str = + "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28421swiglu_entries_kernelEPKfS3_Pfx"; +const E_QUANTIZE_Q8_1: &str = + "_ZN6strata7kernels65_GLOBAL__N__a184a76c_28_mtp_original_full_head_iq_cu_934c6f21_28420quantize_q8_1_kernelEPKfP10block_q8_1x"; +/// `iq_kernels.cu`: the entry-wise SwiGLU and the q8_1 quantizer of `native_expert_grouped` / +/// `quantize_q8_1_rows`. The same PTX file as `proj::HEAD_IQ` (same pin); `proj` names only the MMVQ heads, +/// so the window's MoE owns this entry list under a distinct asset name (the lead's loader must key modules by +/// this name or union the entry lists of both specs). +pub(crate) static HEAD_IQ_EXPERT: AssetSpec = AssetSpec { + name: "mtp_original_full_head_iq.ptx#window-moe", + ptx: include_bytes!("mtp_original_full_head_iq.ptx"), + sha: [60,95,19,213,116,127,120,160,75,228,21,95,8,36,185,31,126,75,16,202,55,150,173,210,73,18,34,143,171,90,69,32], + entries: &[E_SWIGLU_ENTRIES, E_QUANTIZE_Q8_1], + unsealed: "Original verifier asset unsealed: mtp_original_full_head_iq.ptx (expert swiglu / q8_1 quantize)", +}; + +const E_ADD_HITS: &str = + "_ZN6strata7kernels56_GLOBAL__N__2b3d023b_23_mtp_original_full_s2_cu_9e2602a815add_hits_kernelEPfPKfPKiS6_i"; +/// `s2_expert_grouped.cu` (`moe_hit_add`). +pub(crate) static S2_HITS: AssetSpec = AssetSpec { + name: "mtp_original_full_s2.ptx", + ptx: include_bytes!("mtp_original_full_s2.ptx"), + sha: [251,185,23,213,144,234,128,51,138,123,223,7,178,202,109,69,143,167,39,99,186,39,158,87,107,204,30,236,136,54,253,85], + entries: &[E_ADD_HITS], + unsealed: "Original verifier asset unsealed: mtp_original_full_s2.ptx (moe_hit_add)", +}; + +const E_COMBINE: &str = "mtp_full_combine"; +/// `native_moe.cu` (`native_moe_combine(_multi)`). +pub(crate) static COMBINE: AssetSpec = AssetSpec { + name: "mtp_original_full_combine.ptx", + ptx: include_bytes!("mtp_original_full_combine.ptx"), + sha: [34,83,254,45,100,19,80,244,68,90,10,105,196,160,252,34,184,92,47,255,202,124,189,83,111,254,93,41,18,248,31,183], + entries: &[E_COMBINE], + unsealed: "Original verifier asset unsealed: mtp_original_full_combine.ptx (native MoE combine)", +}; + +/// ggml types of `STRATA_GU_FMTS` (gate/up) and `STRATA_D_FMTS` (down) in iq_kernels.cu, with the kernel +/// each launches from the new source (`window_moe_gu_` / `window_moe_down_`). +const GU_ENTRIES: &[(u32, &str)] = &[ + (16, "window_moe_gu_16"), + (17, "window_moe_gu_17"), + (18, "window_moe_gu_18"), + (21, "window_moe_gu_21"), + (22, "window_moe_gu_22"), + (23, "window_moe_gu_23"), + (29, "window_moe_gu_29"), + (42, "window_moe_gu_42"), + (12, "window_moe_gu_12"), + (13, "window_moe_gu_13"), + (8, "window_moe_gu_8"), +]; +const DOWN_ENTRIES: &[(u32, &str)] = &[ + (20, "window_moe_down_20"), + (23, "window_moe_down_23"), + (42, "window_moe_down_42"), + (7, "window_moe_down_7"), + (8, "window_moe_down_8"), +]; +const EXPERT_ENTRIES: &[&str] = &[ + "window_moe_gu_16", "window_moe_gu_17", "window_moe_gu_18", "window_moe_gu_21", "window_moe_gu_22", + "window_moe_gu_23", "window_moe_gu_29", "window_moe_gu_42", "window_moe_gu_12", "window_moe_gu_13", + "window_moe_gu_8", "window_moe_down_20", "window_moe_down_23", "window_moe_down_42", "window_moe_down_7", + "window_moe_down_8", +]; +/// The grouped native-expert gate/up and down kernels (UNSEALED placeholder: no sealed PTX instantiates +/// `native_gu(_multi)_kernel` / `native_down(_multi)_kernel` for the target's formats). +pub(crate) static EXPERTS: AssetSpec = AssetSpec { + name: "original_verify_window_moe_experts.ptx", + ptx: include_bytes!("original_verify_window_moe_experts.ptx"), + sha: [0; 32], + entries: EXPERT_ENTRIES, + unsealed: "Original verifier asset unsealed: original_verify_window_moe_experts.ptx (grouped native expert gate/up and down)", +}; + +/// Every module the MoE producers may launch from (the lead loads them all before capture). +pub(crate) fn assets() -> Vec<&'static AssetSpec> { + vec![ + &proj::HEAD_NATIVE, + &proj::HEAD_IQ, + &proj::BF16, + &ELEMENT, + &ROUTER, + &ROUTER_LEGACY, + &SHARED, + &HEAD_IQ_EXPERT, + &S2_HITS, + &COMBINE, + &EXPERTS, + ] +} + +/// Kernels of the MoE family that need `MAX_DYNAMIC_SHARED_SIZE` raised before capture: none (the generic +/// router uses 6656 bytes, every other kernel static shared memory only). +pub(crate) fn shared_attributes(_knobs: &MoeKnobs) -> Vec<(&'static AssetSpec, &'static str, usize)> { + Vec::new() +} + +// --------------------------------------------------------------------------------------------- +// Configuration, formats, addresses +// --------------------------------------------------------------------------------------------- + +/// Process-wide Original knobs the MoE kernels depend on (fixed before any capture). `mode17()` is the +/// selected `--native` preset of generate.cpp: native router / combine / experts, `native_bf16` and +/// `native_bf16_extra` both on, default native-head dispatch. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct MoeKnobs { + /// `native_router_enabled()`: the fused 512x10 router (else the generic `router_top10`). + pub native_router: bool, + /// `native_moe_combine_enabled()` (else `moe_combine`). + pub native_combine: bool, + /// `expert_layout().native` (GGUF-format experts; else S2 Q8_0 scaled, refused). + pub native_experts: bool, + /// `layer_set_native_bf16` (`--native-bf16`): router logits through `bf16_gemv_fp32_mmvf` for single rows. + pub native_bf16: bool, + /// `shared_expert_set_native_bf16` (`--native-bf16-extra`): the shared expert's scalar gate through MMVF. + pub native_bf16_extra: bool, + /// `native_mmvq` dispatch of the shared expert's projections. + pub dispatch: NativeHeadDispatch, +} +impl MoeKnobs { + pub(crate) fn mode17() -> Self { + Self { + native_router: true, + native_combine: true, + native_experts: true, + native_bf16: true, + native_bf16_extra: true, + dispatch: NativeHeadDispatch::default(), + } + } +} + +/// Values per block of the gate/up types `native_expert_grouped` takes (`gu_qk`), 0 for any other. +const fn gu_qk(ty: u32) -> usize { + match ty { + 16 | 17 | 18 | 21 | 22 | 23 | 29 | 12 | 13 => 256, + 42 => 64, + 8 => 32, + _ => 0, + } +} +/// Values per block of the down types (`d_qk`), 0 for any other. +const fn d_qk(ty: u32) -> usize { + match ty { + 23 => 256, + 42 => 64, + 20 | 7 | 8 => 32, + _ => 0, + } +} + +/// `NativeExpertLayout` of one layer (`native_expert_layout`): `[gate rows | up rows | down rows]`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct ExpertBlob { + pub gu_type: u32, + pub d_type: u32, + pub n_embd: usize, + pub n_ff: usize, + pub gu_row: usize, + pub d_row: usize, + pub up_off: usize, + pub down_off: usize, + pub bytes: usize, +} +impl ExpertBlob { + /// The by-value 64-byte struct kernel parameter, as its eight little-endian words + /// (`int gu_type, d_type; int64 n_embd, n_ff; size_t gu_row, d_row, up_off, down_off, bytes`). + fn words(&self) -> Vec { + vec![ + u64::from(self.gu_type) | (u64::from(self.d_type) << 32), + self.n_embd as u64, + self.n_ff as u64, + self.gu_row as u64, + self.d_row as u64, + self.up_off as u64, + self.down_off as u64, + self.bytes as u64, + ] + } +} + +/// `native_expert_supported` + `native_expert_layout`. +fn expert_blob(gu_type: u32, d_type: u32, n_embd: usize, n_ff: usize) -> Result { + let (qg, qd) = (gu_qk(gu_type), d_qk(d_type)); + if qg == 0 || qd == 0 || n_embd % qg != 0 || n_ff % qd != 0 || n_embd % 256 != 0 || (n_ff * n_embd) % 256 != 0 { + return Err(Error::UnsupportedQwenOperation); + } + let gu_row = native_head_row_bytes(gu_type, n_embd)?; + let d_row = native_head_row_bytes(d_type, n_ff)?; + let up_off = n_ff.checked_mul(gu_row).ok_or(Error::InvalidSize)?; + let down_off = up_off.checked_mul(2).ok_or(Error::InvalidSize)?; + let bytes = n_embd.checked_mul(d_row).and_then(|d| d.checked_add(down_off)).ok_or(Error::InvalidSize)?; + Ok(ExpertBlob { gu_type, d_type, n_embd, n_ff, gu_row, d_row, up_off, down_off, bytes }) +} + +/// `expert_layout().fmt[l]`: the (gate/up, down) ggml types of each of the 48 layers' routed experts. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OriginalVerifyExpertFormats { + formats: [(u32, u32); WINDOW_LAYERS], + n_embd: usize, + n_ff: usize, +} +impl OriginalVerifyExpertFormats { + /// Every pair must be one `native_expert_grouped` has kernels for at these dimensions; anything else + /// is refused here, before a window is recorded. + pub fn new(formats: [(u32, u32); WINDOW_LAYERS], n_embd: usize, n_ff: usize) -> Result { + for &(gu, d) in &formats { + expert_blob(gu, d, n_embd, n_ff)?; + } + Ok(Self { formats, n_embd, n_ff }) + } + pub(crate) fn blob(&self, layer: usize) -> Result { + let &(gu, d) = self.formats.get(layer).ok_or(Error::InvalidQwenShape)?; + expert_blob(gu, d, self.n_embd, self.n_ff) + } + /// `expert_layout().blob_bytes(l)`; the lead compares it with `OriginalVerifyExpertLayout`. + pub fn blob_bytes(&self, layer: usize) -> Result { + Ok(self.blob(layer)?.bytes) + } +} + +/// Device addresses of one layer's MoE weights (what the pure planners consume). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct MoeLayerAddrs { + /// `ffn_gate_inp.weight`: bf16 `[experts][n_embd]`. + pub router: u64, + /// `ffn_gate_inp_shexp.weight`: bf16 `[n_embd]`. + pub gate_inp_shexp: u64, + pub gate_shexp: NativeWeight, + pub up_shexp: NativeWeight, + pub down_shexp: NativeWeight, +} + +/// One layer's MoE weights as the runtime hands them over. +pub struct OriginalVerifyMoeLayerWeights<'a, 'ctx> { + pub router: &'a DeviceBuffer<'ctx>, + pub gate_inp_shexp: &'a DeviceBuffer<'ctx>, + pub gate_shexp: &'a DeviceBuffer<'ctx>, + pub gate_shexp_type: u32, + pub up_shexp: &'a DeviceBuffer<'ctx>, + pub up_shexp_type: u32, + pub down_shexp: &'a DeviceBuffer<'ctx>, + pub down_shexp_type: u32, +} + +/// The router and shared-expert weights of all 48 layers plus the routed experts' formats. Construction +/// validates context equality and the exact byte size of every tensor; the accessors yield addresses. +pub struct OriginalVerifyMoeBinding<'a, 'ctx> { + layers: Vec>, + formats: OriginalVerifyExpertFormats, + n_embd: usize, + n_ff: usize, + experts: usize, +} +impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> { + pub fn new( + context: &Context<'_>, + geometry: &OriginalVerifyGeometry, + layers: Vec>, + formats: OriginalVerifyExpertFormats, + ) -> Result { + let (n_embd, n_ff, experts) = (geometry.n, geometry.ff, geometry.experts); + if layers.len() != WINDOW_LAYERS || formats.n_embd != n_embd || formats.n_ff != n_ff { + return Err(Error::InvalidQwenShape); + } + let router_bytes = experts.checked_mul(n_embd).and_then(|x| x.checked_mul(2)).ok_or(Error::InvalidSize)?; + for layer in &layers { + admit(context, layer.router, router_bytes)?; + admit(context, layer.gate_inp_shexp, n_embd * 2)?; + admit(context, layer.gate_shexp, n_ff * native_head_row_bytes(layer.gate_shexp_type, n_embd)?)?; + admit(context, layer.up_shexp, n_ff * native_head_row_bytes(layer.up_shexp_type, n_embd)?)?; + admit(context, layer.down_shexp, n_embd * native_head_row_bytes(layer.down_shexp_type, n_ff)?)?; + } + Ok(Self { layers, formats, n_embd, n_ff, experts }) + } + pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { + for l in &self.layers { + for b in [l.router, l.gate_inp_shexp, l.gate_shexp, l.up_shexp, l.down_shexp] { + if !std::ptr::eq(context, b.context) { + return Err(Error::ContextMismatch); + } + } + } + Ok(()) + } + pub fn formats(&self) -> &OriginalVerifyExpertFormats { + &self.formats + } + /// Re-validates the sizes (a closed or resized buffer fails) and returns the layer's addresses. + pub(crate) fn addrs(&self, layer: usize) -> Result { + let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?; + let (n, f) = (self.n_embd, self.n_ff); + let address = |b: &DeviceBuffer<'_>, bytes: usize| -> Result { + if b.len() != bytes { + return Err(Error::ShapeMismatch { expected: bytes, actual: b.len() }); + } + Ok(handle(b)?.qwen_address()) + }; + Ok(MoeLayerAddrs { + router: address(l.router, self.experts * n * 2)?, + gate_inp_shexp: address(l.gate_inp_shexp, n * 2)?, + gate_shexp: NativeWeight { + ty: l.gate_shexp_type, + data: address(l.gate_shexp, f * native_head_row_bytes(l.gate_shexp_type, n)?)?, + }, + up_shexp: NativeWeight { + ty: l.up_shexp_type, + data: address(l.up_shexp, f * native_head_row_bytes(l.up_shexp_type, n)?)?, + }, + down_shexp: NativeWeight { + ty: l.down_shexp_type, + data: address(l.down_shexp, n * native_head_row_bytes(l.down_shexp_type, f)?)?, + }, + }) + } +} + +// --------------------------------------------------------------------------------------------- +// Planner helpers +// --------------------------------------------------------------------------------------------- + +/// Rows `[begin, end)` of a group must lie in the window (`n <= max_t`) and the group must be A or B. +fn check_rows(g: &OriginalVerifyGeometry, rows: Rows) -> Result { + if rows.begin >= rows.end || rows.end > g.max_t || rows.group > 1 { + return Err(Error::InvalidQwenShape); + } + Ok(rows.len()) +} +/// `n_elems` consecutive `elem`-byte items of a span starting at item `first`. +fn items(arena: &dyn ArenaMap, name: &str, first: usize, count: usize, elem: usize) -> Result { + arena.span(name, first * elem, count * elem) +} +fn f32s(arena: &dyn ArenaMap, name: &str, first: usize, count: usize) -> Result { + items(arena, name, first, count, 4) +} +/// Word `word` of group `group`'s device plan copy (`plan_ + group * (plan_i32_ + 16)`). +fn plan_word(arena: &dyn ArenaMap, g: &OriginalVerifyGeometry, group: usize, word: usize) -> Result { + let layout = PlanLayout::new(g.max_t * g.k); + if group > 1 || word >= layout.words { + return Err(Error::InvalidQwenShape); + } + arena.span("plan", (group * layout.device_stride() + word) * 4, 4) +} +fn align256(n: usize) -> usize { + (n + 255) & !255 +} + +/// `f32_to_bf16_bulk(x, y, count)`: `to_bf16_kernel<<>>(x, y, count)`. +fn plan_f32_to_bf16(x: u64, y: u64, count: usize) -> Result { + Launch::new( + &ELEMENT, + E_TO_BF16, + [count.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::P(x), A::P(y), A::I64(count as i64)], + ) +} + +// --------------------------------------------------------------------------------------------- +// router +// --------------------------------------------------------------------------------------------- + +/// `route<<>>(logits, ids, weights)` (`native_router_top10(_multi)`). +fn plan_route(logits: u64, ids: u64, weights: u64, tokens: usize) -> Result { + Launch::new( + &ROUTER, + E_ROUTE, + [tokens as u32, 1, 1], + [32, 8, 1], + 0, + vec![A::P(logits), A::P(ids), A::P(weights)], + ) +} + +/// The router of a group: Router logits and top-10 for rows `[tb, te)`. +/// +/// `batched` is the recorder's `dec_batch && n > 1 && native_router` (NE == 512, K == 10): ONE logits GEMV +/// reading the weight once (`bf16_gemv_fp32_mmvf_multi`) and one top-10 launch. Otherwise each row runs +/// `moe_route`: `bf16_gemv_fp32_mmvf` (under `--native-bf16`; without it the Original converts the activation +/// with `f32_to_bf16_bulk` and runs `bf16_gemv_split`, which has no sealed owner) and `native_router_top10`, +/// or the generic `router_top10_kernel<<<1, 512, 6656>>>` when the native router is off. +pub(crate) fn plan_router( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + router: u64, + rows: Rows, + batched: bool, +) -> Result> { + let n = check_rows(g, rows)?; + let (n_embd, ne, k, tb) = (g.n, g.experts, g.k, rows.begin); + if ne != 512 || k != 10 { + return unavailable!("router", "the router kernels are the canonical 512 experts x top-10 only"); + } + let mixed = |t: usize, c: usize| f32s(arena, "mixed", t * n_embd, c * n_embd); + let logits = |t: usize, c: usize| f32s(arena, "logits", t * ne, c * ne); + let ids = |t: usize, c: usize| items(arena, "ids", t * k, c * k, 4); + let weights = |t: usize, c: usize| f32s(arena, "w", t * k, c * k); + if batched { + if n < 2 || !knobs.native_router { + return Err(Error::InvalidQwenShape); + } + let (x, y) = (mixed(tb, n)?, logits(tb, n)?); + return Ok(vec![ + plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, n)?, + plan_route(y, ids(tb, n)?, weights(tb, n)?, n)?, + ]); + } + if !knobs.native_bf16 { + return unavailable!( + "router", + "per-row routing without --native-bf16 needs f32_to_bf16_bulk + bf16_gemv_split, which has no sealed owner" + ); + } + let mut out = Vec::with_capacity(2 * n); + for t in rows.begin..rows.end { + let (x, y) = (mixed(t, 1)?, logits(t, 1)?); + out.push(plan_bf16_gemv(x, n_embd, router, y, ne, n_embd, ne, 1)?); + if knobs.native_router { + out.push(plan_route(y, ids(t, 1)?, weights(t, 1)?, 1)?); + } else { + // router_top10(logits, 1, NE, K, ids, weights): threads = min(NE, 512) rounded to a warp, + // smem = taken (NE rounded to 16) + NE doubles + NE floats. + let smem = ((ne + 15) & !15) + ne * 8 + ne * 4; + out.push(Launch::new( + &ROUTER_LEGACY, + E_ROUTER_TOP10, + [1, 1, 1], + [((ne.min(512) + 31) & !31) as u32, 1, 1], + smem as u32, + vec![A::P(y), A::I32(1), A::I32(ne as i32), A::I32(k as i32), A::P(ids(t, 1)?), A::P(weights(t, 1)?)], + )?); + } + } + Ok(out) +} + +// --------------------------------------------------------------------------------------------- +// shared expert +// --------------------------------------------------------------------------------------------- + +/// The shared expert of a group: `f32_to_bf16_bulk` of the rows, then `shared_expert_multi(n, xm, sh_bf16, +/// nsw, ffn_gate_inp_shexp, sh_gate, sh_up, sh_g, shared, N, n_ff)`. `dec_batch` is `STRATA_DEC_BATCH`: one +/// contiguous conversion and (under `--native-bf16-extra`, n > 1) one gate GEMV + one sigmoid launch. +pub(crate) fn plan_shared_expert( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + w: &MoeLayerAddrs, + rows: Rows, + dec_batch: bool, +) -> Result> { + let n = check_rows(g, rows)?; + let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin); + let xm = f32s(arena, "mixed", tb * n_embd, n * n_embd)?; + let bf16 = |t: usize, c: usize| items(arena, "sh_bf16", t * n_embd, c * n_embd, 2); + let mut out = Vec::new(); + if dec_batch { + out.push(plan_f32_to_bf16(xm, bf16(tb, n)?, n * n_embd)?); + } else { + for t in rows.begin..rows.end { + out.push(plan_f32_to_bf16(f32s(arena, "mixed", t * n_embd, n_embd)?, bf16(t, 1)?, n_embd)?); + } + } + // shared_expert_multi + // `nw.q8_1 = xq_`: first the n activation rows (N values), then the n activated gate rows (n_ff values) + let xq = arena.span("xq", 0, n * proj::q8_1_row_bytes(n_embd.max(n_ff)))?; + let gate = f32s(arena, "sh_gate", tb * n_ff, n * n_ff)?; + let up = f32s(arena, "sh_up", tb * n_ff, n * n_ff)?; + let gscalar = f32s(arena, "sh_g", tb, n)?; + let shared = f32s(arena, "shared", tb * n_embd, n * n_embd)?; + out.push(plan_quantize_q8_1(xm, xq, n_embd, n)?); + out.push(plan_mmvq(&w.gate_shexp, xq, gate, n_embd, n_ff, n, knobs.dispatch)?); + out.push(plan_mmvq(&w.up_shexp, xq, up, n_embd, n_ff, n, knobs.dispatch)?); + let count = n_ff * n; + out.push(Launch::new( + &SHARED, + E_NATIVE_SWIGLU, + [count.div_ceil(128) as u32, 1, 1], + [128, 1, 1], + 0, + vec![A::P(gate), A::P(up), A::P(gate), A::I32(count as i32)], + )?); + out.push(plan_quantize_q8_1(gate, xq, n_ff, n)?); + out.push(plan_mmvq(&w.down_shexp, xq, shared, n_ff, n_embd, n, knobs.dispatch)?); + if knobs.native_bf16_extra && dec_batch && n > 1 { + // one GEMV for all rows (outputs identical), one sigmoid launch with thread t = token t + out.push(plan_bf16_gemv(xm, n_embd, w.gate_inp_shexp, gscalar, 1, n_embd, 1, n)?); + out.push(Launch::new(&SHARED, E_SIGMOID_MULTI, [1, 1, 1], [n as u32, 1, 1], 0, vec![A::P(gscalar)])?); + } else { + for t in 0..n { + let g_t = f32s(arena, "sh_g", tb + t, 1)?; + if knobs.native_bf16_extra { + let x_t = f32s(arena, "mixed", (tb + t) * n_embd, n_embd)?; + out.push(plan_bf16_gemv(x_t, n_embd, w.gate_inp_shexp, g_t, 1, n_embd, 1, 1)?); + out.push(Launch::new(&SHARED, E_SIGMOID, [1, 1, 1], [1, 1, 1], 0, vec![A::P(g_t)])?); + } else { + out.push(Launch::new( + &SHARED, + E_SCALAR_GATE, + [1, 1, 1], + [256, 1, 1], + 0, + vec![A::P(bf16(tb + t, 1)?), A::P(w.gate_inp_shexp), A::P(g_t), A::I32(n_embd as i32)], + )?); + } + } + } + out.push(Launch::new( + &SHARED, + E_SCALE_ROWS, + [n_embd.div_ceil(128) as u32, n as u32, 1], + [128, 1, 1], + 0, + vec![A::P(shared), A::P(gscalar), A::I32(n_embd as i32)], + )?); + Ok(out) +} + +// --------------------------------------------------------------------------------------------- +// expert input quantization, grouped experts, hit add, combine +// --------------------------------------------------------------------------------------------- + +/// `quantize_q8_1_rows(xm, n, N, nat_xq_ + tb * (N/32) * 36)`: `quantize_q8_1_kernel<<>>`. +/// Only the native (GGUF-format) experts; the S2 path (`quantize_q8_0_scaled` into hit_xq / hit_xs) is refused. +pub(crate) fn plan_quantize_expert_input( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + rows: Rows, +) -> Result> { + let n = check_rows(g, rows)?; + if !knobs.native_experts { + return unavailable!( + "quantize_expert_input", + "S2 Q8_0 scaled experts (quantize_q8_0_scaled + moe_grouped_s2) have no window owner" + ); + } + let (n_embd, tb) = (g.n, rows.begin); + let row_bytes = proj::q8_1_row_bytes(n_embd); + let x = f32s(arena, "mixed", tb * n_embd, n * n_embd)?; + let y = arena.span("nat_xq", tb * row_bytes, n * row_bytes)?; + let total = n * n_embd; + Ok(vec![Launch::new( + &HEAD_IQ_EXPERT, + E_QUANTIZE_Q8_1, + [total.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::P(x), A::P(y), A::I64(total as i64)], + )?]) +} + +/// Byte offsets inside `hit_scratch_` (`native_expert_grouped`): gate, up, h (each `fa` bytes) then hq. +pub(crate) fn expert_scratch(cap: usize, n_ff: usize) -> (usize, usize) { + let fa = align256(cap * n_ff * 4); + let total = 3 * fa + align256(cap * (n_ff / 32) * 36); + (fa, total) +} + +/// `grouped(gp, gs, gn)` of `post`: `native_expert_grouped(L, ...)` for one tier, `L` the layer's native +/// layout and `cap = n * K` groups / entries. +pub(crate) fn plan_expert_groups( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + formats: &OriginalVerifyExpertFormats, + layer: usize, + rows: Rows, + tier: ExpertTier, +) -> Result> { + let n = check_rows(g, rows)?; + if !knobs.native_experts { + return unavailable!( + "expert_groups", + "S2 Q8_0 scaled experts (moe_grouped_s2) have no window owner; only native experts are bound" + ); + } + let blob = formats.blob(layer)?; + if blob.n_embd != g.n || blob.n_ff != g.ff { + return Err(Error::InvalidQwenShape); + } + let gu_entry = GU_ENTRIES.iter().find(|e| e.0 == blob.gu_type).ok_or(Error::UnsupportedQwenOperation)?.1; + let down_entry = DOWN_ENTRIES.iter().find(|e| e.0 == blob.d_type).ok_or(Error::UnsupportedQwenOperation)?.1; + let layout = PlanLayout::new(g.max_t * g.k); + let (ptr_word, start_word, count_word) = match tier { + ExpertTier::Vram => (layout.ptr, layout.start, layout.counts), + ExpertTier::Pcie => (layout.ptr2, layout.start2, layout.counts + 2), + }; + let group = rows.group; + let grp_ptr = plan_word(arena, g, group, ptr_word)?; + let grp_start = plan_word(arena, g, group, start_word)?; + let n_groups = plan_word(arena, g, group, count_word)?; + let ent_dst = plan_word(arena, g, group, layout.dst)?; + let ent_tok = plan_word(arena, g, group, layout.tok)?; + let (n_embd, n_ff, tb) = (g.n, g.ff, rows.begin); + let cap = n * g.k; + let row_bytes = proj::q8_1_row_bytes(n_embd); + let x_q8_1 = arena.span("nat_xq", tb * row_bytes, n * row_bytes)?; + let (fa, scratch_bytes) = expert_scratch(cap, n_ff); + let scratch = arena.span("hit_scratch", 0, scratch_bytes)?; + let (gate, up, h, hq) = (scratch, scratch + fa as u64, scratch + 2 * fa as u64, scratch + 3 * fa as u64); + let out = f32s(arena, "hit_out", tb * g.k * n_embd, cap * n_embd)?; + let nh = cap * n_ff; + let words = blob.words(); + Ok(vec![ + Launch::new( + &EXPERTS, + gu_entry, + [(2 * n_ff).div_ceil(8) as u32, cap as u32, 1], + [256, 1, 1], + 0, + vec![ + A::P(grp_ptr), + A::P(grp_start), + A::P(n_groups), + A::P(ent_tok), + A::P(x_q8_1), + A::Words(words.clone()), + A::P(gate), + A::P(up), + ], + )?, + Launch::new( + &HEAD_IQ_EXPERT, + E_SWIGLU_ENTRIES, + [nh.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::P(gate), A::P(up), A::P(h), A::I64(nh as i64)], + )?, + Launch::new( + &HEAD_IQ_EXPERT, + E_QUANTIZE_Q8_1, + [nh.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![A::P(h), A::P(hq), A::I64(nh as i64)], + )?, + Launch::new( + &EXPERTS, + down_entry, + [n_embd.div_ceil(8) as u32, cap as u32, 1], + [256, 1, 1], + 0, + vec![A::P(grp_ptr), A::P(grp_start), A::P(n_groups), A::P(ent_dst), A::P(hq), A::Words(words), A::P(out)], + )?, + ]) +} + +/// `moe_hit_add(parts_ + tb*K*N, hit_out, p_dst, p_counts + 1, cap, N)`: +/// `add_hits_kernel<<<(min(ceil(N/256), 8), cap), 256>>>`. +pub(crate) fn plan_hit_add(arena: &dyn ArenaMap, g: &OriginalVerifyGeometry, rows: Rows) -> Result> { + let n = check_rows(g, rows)?; + let layout = PlanLayout::new(g.max_t * g.k); + let (n_embd, k, tb) = (g.n, g.k, rows.begin); + let cap = n * k; + let parts = f32s(arena, "parts", tb * k * n_embd, cap * n_embd)?; + let hit_out = f32s(arena, "hit_out", tb * k * n_embd, cap * n_embd)?; + let dst = plan_word(arena, g, rows.group, layout.dst)?; + let count = plan_word(arena, g, rows.group, layout.counts + 1)?; + Ok(vec![Launch::new( + &S2_HITS, + E_ADD_HITS, + [n_embd.div_ceil(256).min(8) as u32, cap as u32, 1], + [256, 1, 1], + 0, + vec![A::P(parts), A::P(hit_out), A::P(dst), A::P(count), A::I32(n_embd as i32)], + )?]) +} + +/// The MoE combine of a group. `batched` is the recorder's `dec_batch && n > 1 && native_combine`: ONE +/// `native_moe_combine_multi` launch (`grid.y` = token). Otherwise `moe_combine_parts` per row: +/// `native_moe_combine` (same kernel, one token) or the legacy double-precision `moe_combine`. +pub(crate) fn plan_combine( + arena: &dyn ArenaMap, + g: &OriginalVerifyGeometry, + knobs: &MoeKnobs, + rows: Rows, + batched: bool, +) -> Result> { + let n = check_rows(g, rows)?; + let (n_embd, k, tb) = (g.n, g.k, rows.begin); + let native = |parts: u64, w: u64, shared: u64, bo: u64, tokens: usize| { + Launch::new( + &COMBINE, + E_COMBINE, + [n_embd.div_ceil(256) as u32, tokens as u32, 1], + [256, 1, 1], + 0, + vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I64(n_embd as i64), A::I32(k as i32)], + ) + }; + if batched { + if n < 2 || !knobs.native_combine { + return Err(Error::InvalidQwenShape); + } + return Ok(vec![native( + f32s(arena, "parts", tb * k * n_embd, n * k * n_embd)?, + f32s(arena, "w", tb * k, n * k)?, + f32s(arena, "shared", tb * n_embd, n * n_embd)?, + f32s(arena, "bo", tb * n_embd, n * n_embd)?, + n, + )?]); + } + let mut out = Vec::with_capacity(n); + for t in rows.begin..rows.end { + let parts = f32s(arena, "parts", t * k * n_embd, k * n_embd)?; + let w = f32s(arena, "w", t * k, k)?; + let shared = f32s(arena, "shared", t * n_embd, n_embd)?; + let bo = f32s(arena, "bo", t * n_embd, n_embd)?; + if knobs.native_combine { + out.push(native(parts, w, shared, bo, 1)?); + } else { + out.push(Launch::new( + &SHARED, + E_MOE_COMBINE, + [n_embd.div_ceil(128) as u32, 1, 1], + [128, 1, 1], + 0, + vec![A::P(parts), A::P(w), A::P(shared), A::P(bo), A::I32(n_embd as i32), A::I32(k as i32), A::I32(1)], + )?); + } + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::super::kernels::{LayoutMap, test_geometry}; + use super::*; + + const BASE: u64 = 0x2000_0000; + + fn map() -> LayoutMap { + LayoutMap::new(BASE, test_geometry()) + } + fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + m.span(name, offset, 4).unwrap() + } + fn rows(begin: usize, end: usize, group: usize) -> Rows { + Rows { begin, end, group } + } + fn weights() -> MoeLayerAddrs { + MoeLayerAddrs { + router: 0x9000_0000, + gate_inp_shexp: 0x9100_0000, + gate_shexp: NativeWeight { ty: 8, data: 0x9200_0000 }, + up_shexp: NativeWeight { ty: 8, data: 0x9300_0000 }, + down_shexp: NativeWeight { ty: 8, data: 0x9400_0000 }, + } + } + fn formats() -> OriginalVerifyExpertFormats { + OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap() + } + fn entries(l: &[Launch]) -> Vec<&'static str> { + l.iter().map(|x| x.entry).collect() + } + + // ---- assets ------------------------------------------------------------------------------ + + fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) + } + + /// `.param` type tokens of an entry's parameter list (the first token after `.param`). + fn param_types(ptx: &str, entry: &str) -> Vec { + let head = format!(".entry {entry}("); + let start = ptx.find(&head).unwrap_or_else(|| panic!("{entry} missing")) + head.len(); + let rest = &ptx[start..]; + let end = rest.find("\n)").expect("parameter list end"); + rest[..end] + .lines() + .filter(|l| l.contains(".param")) + .map(|l| l.split_whitespace().nth(1).unwrap().to_string()) + .collect() + } + fn expected_type(a: &A) -> &'static str { + match a { + A::P(_) | A::I64(_) | A::U64(_) => ".u64", + A::I32(_) => ".u32", + A::F32(_) => ".f32", + A::Words(_) => ".align", + } + } + + #[test] + fn sealed_assets_are_pinned_and_export_every_named_entry() { + for spec in [&ELEMENT, &ROUTER, &ROUTER_LEGACY, &SHARED, &HEAD_IQ_EXPERT, &S2_HITS, &COMBINE] { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + // the window's HEAD_IQ_EXPERT is the same file and pin as proj::HEAD_IQ + assert_eq!(HEAD_IQ_EXPERT.sha, proj::HEAD_IQ.sha); + assert!(HEAD_IQ_EXPERT.ptx == proj::HEAD_IQ.ptx); + } + + #[test] + fn expert_asset_is_an_unsealed_placeholder_until_root_seals_it() { + assert_eq!( + EXPERTS.sealed().unwrap_err(), + Error::InvalidDriverValue(EXPERTS.unsealed), + "the placeholder must refuse to load" + ); + assert!(EXPERTS.ptx.windows(8).any(|w| w == b"UNSEALED")); + assert_eq!(EXPERTS.ptx.last(), Some(&0)); + assert!(!EXPERTS.ptx[..EXPERTS.ptx.len() - 1].contains(&0)); + assert_eq!(EXPERTS.sha, [0; 32]); + } + + #[test] + fn expert_entries_match_the_cu_source_and_the_original_format_lists() { + let cu = include_str!("original_verify_window_moe_experts.cu"); + assert!(cu.contains("window_moe_gu_##T") && cu.contains("window_moe_down_##T")); + assert!(cu.contains("STRATA_GU_FMTS(STRATA_WINDOW_GU)") && cu.contains("STRATA_D_FMTS(STRATA_WINDOW_DOWN)")); + let iq = include_str!("mtp_original_full_head_iq.cu"); + let parse = |macro_name: &str| -> Vec { + let line = iq.lines().find(|l| l.starts_with(&format!("#define {macro_name}(X)"))).expect(macro_name); + line.split("X(").skip(1).map(|s| s.split(')').next().unwrap().parse().unwrap()).collect() + }; + let gu: Vec = GU_ENTRIES.iter().map(|e| e.0).collect(); + let d: Vec = DOWN_ENTRIES.iter().map(|e| e.0).collect(); + assert_eq!(gu, parse("STRATA_GU_FMTS")); + assert_eq!(d, parse("STRATA_D_FMTS")); + for (t, name) in GU_ENTRIES { + assert_eq!(*name, format!("window_moe_gu_{t}")); + assert!(EXPERTS.has_entry(name) && gu_qk(*t) > 0); + } + for (t, name) in DOWN_ENTRIES { + assert_eq!(*name, format!("window_moe_down_{t}")); + assert!(EXPERTS.has_entry(name) && d_qk(*t) > 0); + } + assert_eq!(EXPERTS.entries.len(), GU_ENTRIES.len() + DOWN_ENTRIES.len()); + // the Original's per-type values-per-block (Fmt::qk) used by native_expert_supported + for (t, _) in GU_ENTRIES { + let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", gu_qk(*t)); + assert!(iq.contains(&want), "{want}"); + } + for (t, _) in DOWN_ENTRIES { + let want = format!("template<> struct Fmt<{t}> {{ static constexpr int qk = {},", d_qk(*t)); + assert!(iq.contains(&want), "{want}"); + } + assert_eq!((gu_qk(20), gu_qk(7), d_qk(16), d_qk(12), d_qk(0)), (0, 0, 0, 0, 0)); + } + + #[test] + fn asset_list_names_every_module_once() { + let a = assets(); + let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); + names.sort_unstable(); + let len = names.len(); + names.dedup(); + assert_eq!(names.len(), len, "duplicate asset names"); + assert!(a.iter().any(|s| std::ptr::eq(*s, &EXPERTS))); + assert!(shared_attributes(&MoeKnobs::mode17()).is_empty()); + } + + /// The ABI check: every launch of a SEALED asset names an entry whose `.param` list has exactly the + /// recorded argument count and widths. + fn assert_abi(launches: &[Launch]) { + for l in launches { + if l.asset.sha == [0; 32] { + continue; // placeholder + } + let text = String::from_utf8_lossy(l.asset.ptx); + let types = param_types(&text, l.entry); + let want: Vec<&str> = l.args.iter().map(expected_type).collect(); + assert_eq!(types, want, "{}", l.label()); + } + } + + // ---- router ------------------------------------------------------------------------------ + + #[test] + fn batched_router_is_one_gemv_and_one_top10_over_the_groups_rows() { + let m = map(); + let g = test_geometry(); + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(3, 8, 1), true).unwrap(); + assert_eq!(l.len(), 2); + // bf16_gemv_fp32_mmvf_multi(mixed + 3*N, N, w, logits + 3*NE, NE, N, NE, 5): block 256, 5 rows -> 8-col kernel + assert!(l[0].entry.contains("ILi256ELi8EE")); + assert_eq!((l[0].grid, l[0].block), ([512, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 3 * 2560 * 4)), + A::I64(2560), + A::P(0x9000_0000), + A::P(at(&m, "logits", 3 * 512 * 4)), + A::I64(512), + A::I32(2560), + A::I32(5) + ] + ); + // native_router_top10_multi: route<<<5, (32, 8)>>>(logits + 3*NE, ids + 3*K, w + 3*K) + assert_eq!((l[1].entry, l[1].grid, l[1].block, l[1].shared), ("mtp_full_route", [5, 1, 1], [32, 8, 1], 0)); + assert_eq!( + l[1].args, + vec![A::P(at(&m, "logits", 3 * 512 * 4)), A::P(at(&m, "ids", 3 * 10 * 4)), A::P(at(&m, "w", 3 * 10 * 4))] + ); + assert_abi(&l); + } + + #[test] + fn batched_router_uses_the_four_column_kernel_up_to_four_rows() { + let m = map(); + let g = test_geometry(); + for n in 2..=4usize { + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(0, n, 0), true).unwrap(); + assert!(l[0].entry.contains("ILi256ELi4EE"), "{n}"); + assert_eq!(l[1].grid, [n as u32, 1, 1]); + } + } + + #[test] + fn per_row_router_follows_moe_route_for_every_row() { + let m = map(); + let g = test_geometry(); + let l = plan_router(&m, &g, &MoeKnobs::mode17(), 0x9000_0000, rows(1, 3, 0), false).unwrap(); + // row 1: bf16_gemv_fp32_mmvf(mixed + N, w, logits + NE, N, NE) + native_router_top10; then row 2 + assert_eq!(entries(&l), ["mtp_full_mmvf256", "mtp_full_route", "mtp_full_mmvf256", "mtp_full_route"]); + assert_eq!(l[0].grid, [512, 1, 1]); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9000_0000), A::P(at(&m, "logits", 512 * 4)), A::I32(2560)] + ); + assert_eq!((l[1].grid, l[1].block), ([1, 1, 1], [32, 8, 1])); + assert_eq!( + l[3].args, + vec![A::P(at(&m, "logits", 2 * 512 * 4)), A::P(at(&m, "ids", 2 * 10 * 4)), A::P(at(&m, "w", 2 * 10 * 4))] + ); + assert_abi(&l); + } + + #[test] + fn generic_router_is_the_original_router_top10_launch() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_router = false; + let l = plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 1, 0), false).unwrap(); + assert_eq!(l.len(), 2); + // threads = 512, smem = 512 (taken) + 512*8 (doubles) + 512*4 (floats) = 6656 + assert_eq!((l[1].grid, l[1].block, l[1].shared), ([1, 1, 1], [512, 1, 1], 6656)); + assert_eq!( + l[1].args, + vec![ + A::P(at(&m, "logits", 0)), + A::I32(1), + A::I32(512), + A::I32(10), + A::P(at(&m, "ids", 0)), + A::P(at(&m, "w", 0)) + ] + ); + assert_abi(&l); + // the batched launch needs the native router + assert_eq!( + plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).unwrap_err(), + Error::InvalidQwenShape + ); + } + + #[test] + fn router_fails_closed_precisely_without_native_bf16_and_on_bad_shapes() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_bf16 = false; + let e = plan_router(&m, &g, &knobs, 1, rows(0, 1, 0), false).unwrap_err(); + match e { + Error::InvalidDriverValue(s) => { + assert!(s.starts_with("Original verifier producer unavailable: router: "), "{s}") + } + other => panic!("{other:?}"), + } + // the batched path never needs the bf16 conversion + assert!(plan_router(&m, &g, &knobs, 0x9000_0000, rows(0, 2, 0), true).is_ok()); + // batched with one row, empty rows, rows past the window, group C + let mode = MoeKnobs::mode17(); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 0), true).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(2, 2, 0), false).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 9, 0), false).is_err()); + assert!(plan_router(&m, &g, &mode, 1, rows(0, 1, 2), false).is_err()); + } + + // ---- shared expert ----------------------------------------------------------------------- + + #[test] + fn batched_shared_expert_runs_the_shared_expert_multi_sequence_in_order() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(2, 6, 1), true).unwrap(); + // f32_to_bf16_bulk(4 rows), quantize x, MMVQ gate, MMVQ up, swiglu, quantize h, MMVQ down, + // gate GEMV (multi), sigmoid (multi), scale rows + assert_eq!(l.len(), 10); + assert!(l[0].entry.ends_with("to_bf16_kernelEPKfPtl")); + assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); // 4*2560 = 10240 elements + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 2 * 2560 * 4)), A::P(at(&m, "sh_bf16", 2 * 2560 * 2)), A::I64(10240)] + ); + let xq = at(&m, "xq", 0); + let xm = at(&m, "mixed", 2 * 2560 * 4); + let gate = at(&m, "sh_gate", 2 * 640 * 4); + let up = at(&m, "sh_up", 2 * 640 * 4); + let shared = at(&m, "shared", 2 * 2560 * 4); + let gs = at(&m, "sh_g", 2 * 4); + assert_eq!(l[1].entry, "head_quant"); + assert_eq!(l[1].args, vec![A::P(xm), A::P(xq), A::I32(4 * 2560)]); + // gate/up: Q8_0, 4 columns: head_n8_t4_large, y rows n_ff floats apart + assert_eq!(l[2].entry, "head_n8_t4_large"); + assert_eq!(l[2].args, vec![A::P(0x9200_0000), A::P(xq), A::P(gate), A::I32(2560), A::I32(640)]); + assert_eq!(l[3].entry, "head_n8_t4_large"); + assert_eq!(l[3].args, vec![A::P(0x9300_0000), A::P(xq), A::P(up), A::I32(2560), A::I32(640)]); + // native_swiglu_kernel<<>>(gate, up, gate, 2560) + assert!(l[4].entry.ends_with("native_swiglu_kernelEPKfS3_Pfi")); + assert_eq!((l[4].grid, l[4].block), ([20, 1, 1], [128, 1, 1])); + assert_eq!(l[4].args, vec![A::P(gate), A::P(up), A::P(gate), A::I32(2560)]); + // quantize the activated gate (640 elements per row) in place into xq, then the down projection + assert_eq!(l[5].args, vec![A::P(gate), A::P(xq), A::I32(4 * 640)]); + // down: n_in = 640 values is "small" for Q8_0 (640/32 < 32 blocks per iteration) + assert_eq!(l[6].entry, "head_n8_t4_small"); + assert_eq!(l[6].args, vec![A::P(0x9400_0000), A::P(xq), A::P(shared), A::I32(640), A::I32(2560)]); + // the scalar gate: one GEMV (4 rows, ldy 1, n_out 1) and one sigmoid with thread t = token t + assert!(l[7].entry.contains("ILi256ELi4EE")); + assert_eq!(l[7].grid, [1, 1, 1]); + assert_eq!( + l[7].args, + vec![A::P(xm), A::I64(2560), A::P(0x9100_0000), A::P(gs), A::I64(1), A::I32(2560), A::I32(4)] + ); + assert!(l[8].entry.ends_with("native_scalar_sigmoid_multi_kernelEPf")); + assert_eq!((l[8].grid, l[8].block, l[8].args.clone()), ([1, 1, 1], [4, 1, 1], vec![A::P(gs)])); + // scale_rows_kernel<<<(20, 4), 128>>>(shared, g, 2560) + assert!(l[9].entry.ends_with("scale_rows_kernelEPfPKfi")); + assert_eq!((l[9].grid, l[9].block), ([20, 4, 1], [128, 1, 1])); + assert_eq!(l[9].args, vec![A::P(shared), A::P(gs), A::I32(2560)]); + assert_abi(&l); + } + + #[test] + fn single_row_shared_expert_uses_the_per_token_gate_and_single_row_projections() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, 1, 0), true).unwrap(); + // bulk, quantize, gate, up, swiglu, quantize, down, [mmvf + sigmoid], scale + assert_eq!(l.len(), 10); + assert_eq!((l[2].entry, l[6].entry), ("head_n8_s0", "head_n8_s1")); + assert_eq!(l[7].entry, "mtp_full_mmvf256"); + assert_eq!(l[7].args, vec![A::P(at(&m, "mixed", 0)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 0)), A::I32(2560)]); + assert!(l[8].entry.ends_with("native_scalar_sigmoid_kernelEPf")); + assert_eq!(l[8].block, [1, 1, 1]); + assert_eq!(l[9].grid, [20, 1, 1]); + assert_abi(&l); + } + + #[test] + fn shared_expert_without_dec_batch_converts_and_gates_one_row_at_a_time() { + let m = map(); + let g = test_geometry(); + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(1, 3, 0), false).unwrap(); + // 2 conversions, the six projection / activation launches, 2 x (mmvf + sigmoid), scale + assert_eq!(l.len(), 2 + 6 + 4 + 1); + assert_eq!((l[0].grid, l[0].args.clone()), ([10, 1, 1], vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(at(&m, "sh_bf16", 2560 * 2)), A::I64(2560)])); + assert_eq!(l[1].args[1], A::P(at(&m, "sh_bf16", 2 * 2560 * 2))); + // the projections are still two-row launches, but the gate is per token + assert_eq!(l[3].entry, "head_n8_t2_large"); + assert_eq!( + l[8].args, + vec![A::P(at(&m, "mixed", 2560 * 4)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] + ); + assert_eq!(l[10].args[2], A::P(at(&m, "sh_g", 2 * 4))); + assert_eq!(l[12].grid, [20, 2, 1]); + assert_abi(&l); + } + + #[test] + fn shared_gate_without_native_bf16_extra_reads_the_bf16_activation() { + let m = map(); + let g = test_geometry(); + let mut knobs = MoeKnobs::mode17(); + knobs.native_bf16_extra = false; + let l = plan_shared_expert(&m, &g, &knobs, &weights(), rows(0, 2, 0), true).unwrap(); + // one scalar_gate_kernel<<<1, 256>>>(x_bf16 + t*N, w, g + t, N) per token, no GEMV / sigmoid + let gates: Vec<&Launch> = l.iter().filter(|x| x.entry.ends_with("scalar_gate_kernelEPKtS3_Pfi")).collect(); + assert_eq!(gates.len(), 2); + assert_eq!((gates[0].grid, gates[0].block), ([1, 1, 1], [256, 1, 1])); + assert_eq!( + gates[1].args, + vec![A::P(at(&m, "sh_bf16", 2560 * 2)), A::P(0x9100_0000), A::P(at(&m, "sh_g", 4)), A::I32(2560)] + ); + assert!(!l.iter().any(|x| x.entry.contains("sigmoid"))); + assert_abi(&l); + } + + #[test] + fn shared_expert_covers_every_window_size() { + let m = map(); + let g = test_geometry(); + for n in 1..=8usize { + let l = plan_shared_expert(&m, &g, &MoeKnobs::mode17(), &weights(), rows(0, n, 0), true).unwrap(); + assert_eq!(l.last().unwrap().grid, [20, n as u32, 1]); + assert_eq!(l[4].grid, [(640 * n).div_ceil(128) as u32, 1, 1]); + assert_abi(&l); + } + } + + // ---- expert input, groups ---------------------------------------------------------------- + + #[test] + fn expert_input_is_the_q8_1_row_quantizer_into_nat_xq() { + let m = map(); + let g = test_geometry(); + let l = plan_quantize_expert_input(&m, &g, &MoeKnobs::mode17(), rows(4, 8, 1)).unwrap(); + assert_eq!(l.len(), 1); + assert!(l[0].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); + assert_eq!((l[0].grid, l[0].block), ([40, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "mixed", 4 * 2560 * 4)), A::P(at(&m, "nat_xq", 4 * 2880)), A::I64(4 * 2560)] + ); + assert_abi(&l); + let mut s2 = MoeKnobs::mode17(); + s2.native_experts = false; + assert!(matches!( + plan_quantize_expert_input(&m, &g, &s2, rows(0, 1, 0)), + Err(Error::InvalidDriverValue(s)) if s.contains("quantize_expert_input") + )); + } + + #[test] + fn expert_blob_layout_matches_native_expert_layout() { + // IQ2_XXS gate/up (66 B per 256), IQ4_NL down (18 B per 32): n_embd 2560, n_ff 640 + let b = expert_blob(16, 20, 2560, 640).unwrap(); + assert_eq!((b.gu_row, b.d_row), (10 * 66, 20 * 18)); + assert_eq!((b.up_off, b.down_off), (640 * 660, 2 * 640 * 660)); + assert_eq!(b.bytes, 844_800 + 2560 * 360); + assert_eq!(b.bytes % 16, 0); + assert_eq!( + b.words(), + vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400] + ); + // Q4_K gate/up (144 B per 256) and Q8_0 down (34 B per 32) + let q = expert_blob(12, 8, 2560, 640).unwrap(); + assert_eq!((q.gu_row, q.d_row, q.bytes), (1440, 680, 2 * 640 * 1440 + 2560 * 680)); + // Q2_0 (64 values, 18 B) on both sides + let z = expert_blob(42, 42, 2560, 640).unwrap(); + assert_eq!((z.gu_row, z.d_row), (40 * 18, 10 * 18)); + // IQ4_XS down needs n_ff % 256 == 0: 640 is not; IQ4_NL gate/up and unknown types are refused + assert_eq!(expert_blob(16, 23, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(20, 20, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(16, 99, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(expert_blob(16, 20, 2560, 650).unwrap_err(), Error::UnsupportedQwenOperation); + } + + #[test] + fn expert_formats_validate_all_layers_and_report_blob_bytes() { + let f = formats(); + assert_eq!(f.blob_bytes(0), Ok(1_766_400)); + assert_eq!(f.blob_bytes(47), Ok(1_766_400)); + assert!(f.blob_bytes(48).is_err()); + let mut mixed = [(16, 20); WINDOW_LAYERS]; + mixed[10] = (12, 8); + let f = OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap(); + assert_eq!(f.blob_bytes(10), Ok(2 * 640 * 1440 + 2560 * 680)); + assert_eq!(f.blob_bytes(11), Ok(1_766_400)); + mixed[30] = (20, 20); + assert_eq!(OriginalVerifyExpertFormats::new(mixed, 2560, 640).unwrap_err(), Error::UnsupportedQwenOperation); + } + + #[test] + fn expert_scratch_follows_native_expert_scratch_bytes() { + // gate | up | h each cap*n_ff floats rounded to 256, then cap*(n_ff/32) q8_1 blocks rounded to 256 + assert_eq!(expert_scratch(10, 640), (25_600, 3 * 25_600 + 7_424)); // 10*20*36 = 7200 -> 7424 + assert_eq!(expert_scratch(80, 640), (204_800, 3 * 204_800 + 80 * 20 * 36)); + // rounding path (never reached by n_ff = 640 where cap * n_ff * 4 is a multiple of 256) + assert_eq!(expert_scratch(1, 100), (512, 3 * 512 + 256)); + } + + #[test] + fn vram_tier_reads_the_first_plan_arrays() { + let m = map(); + let g = test_geometry(); + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 5, rows(0, 3, 0), ExpertTier::Vram); + // the kernels live in the unsealed asset, but the plan itself is pure data + let l = l.unwrap(); + assert_eq!(entries(&l).len(), 4); + // PlanLayout(capx = 80): start 4, dst 85, tok 165, ptr 246, ptr2 406, start2 566; device stride 664 words + let plan = |word: usize| at(&m, "plan", word * 4); + let scratch = at(&m, "hit_scratch", 0); + let xq = at(&m, "nat_xq", 0); + let fa = 3 * 10 * 640 * 4; + // gate/up: grid ((2*640+7)/8 = 160, cap = 30), 256 threads + assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("window_moe_gu_16", [160, 30, 1], [256, 1, 1], 0)); + assert_eq!( + l[0].args, + vec![ + A::P(plan(246)), + A::P(plan(4)), + A::P(plan(0)), + A::P(plan(165)), + A::P(xq), + A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), + A::P(scratch), + A::P(scratch + fa as u64) + ] + ); + // swiglu_entries and quantize over cap * n_ff = 19200 values + assert!(l[1].entry.ends_with("swiglu_entries_kernelEPKfS3_Pfx")); + assert_eq!((l[1].grid, l[1].block), ([75, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![A::P(scratch), A::P(scratch + fa as u64), A::P(scratch + 2 * fa as u64), A::I64(19_200)] + ); + assert!(l[2].entry.ends_with("quantize_q8_1_kernelEPKfP10block_q8_1x")); + assert_eq!(l[2].args, vec![A::P(scratch + 2 * fa as u64), A::P(scratch + 3 * fa as u64), A::I64(19_200)]); + // down: grid ((2560+7)/8 = 320, 30) + assert_eq!((l[3].entry, l[3].grid), ("window_moe_down_20", [320, 30, 1])); + assert_eq!( + l[3].args, + vec![ + A::P(plan(246)), + A::P(plan(4)), + A::P(plan(0)), + A::P(plan(85)), + A::P(scratch + 3 * fa as u64), + A::Words(vec![16 | (20 << 32), 2560, 640, 660, 360, 422_400, 844_800, 1_766_400]), + A::P(at(&m, "hit_out", 0)) + ] + ); + assert_abi(&l[1..3]); + } + + #[test] + fn pcie_tier_uses_the_second_pointer_start_and_count_of_the_group() { + let m = map(); + let g = test_geometry(); + // group B of a 5-row window: rows 3..5, plan block of group 1 (664 words further) + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(3, 5, 1), ExpertTier::Pcie).unwrap(); + let plan = |word: usize| at(&m, "plan", (664 + word) * 4); + assert_eq!( + l[0].args[..5], + [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(165)), A::P(at(&m, "nat_xq", 3 * 2880))] + ); + assert_eq!(l[0].grid, [160, 20, 1]); + assert_eq!( + l[3].args[..4], + [A::P(plan(406)), A::P(plan(566)), A::P(plan(2)), A::P(plan(85))] + ); + // output rows of the group start at tb*K*N + assert_eq!(l[3].args[6], A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4))); + assert_eq!(l[3].grid, [320, 20, 1]); + } + + #[test] + fn expert_groups_pick_the_kernels_of_the_layers_formats() { + let m = map(); + let g = test_geometry(); + let mut fmts = [(16, 20); WINDOW_LAYERS]; + fmts[7] = (12, 8); + fmts[8] = (42, 42); + fmts[9] = (13, 7); + let f = OriginalVerifyExpertFormats::new(fmts, 2560, 640).unwrap(); + let pick = |layer: usize| { + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, layer, rows(0, 1, 0), ExpertTier::Vram).unwrap(); + (l[0].entry, l[3].entry) + }; + assert_eq!(pick(0), ("window_moe_gu_16", "window_moe_down_20")); + assert_eq!(pick(7), ("window_moe_gu_12", "window_moe_down_8")); + assert_eq!(pick(8), ("window_moe_gu_42", "window_moe_down_42")); + assert_eq!(pick(9), ("window_moe_gu_13", "window_moe_down_7")); + // every launch names an entry of its asset + for t in 0..8usize { + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &f, 7, rows(0, t + 1, 0), ExpertTier::Pcie).unwrap(); + assert_eq!(l[0].grid[1], ((t + 1) * 10) as u32); + assert_eq!(l[3].grid[1], ((t + 1) * 10) as u32); + } + } + + #[test] + fn expert_groups_refuse_s2_and_a_mismatched_geometry() { + let m = map(); + let g = test_geometry(); + let mut s2 = MoeKnobs::mode17(); + s2.native_experts = false; + assert!(matches!( + plan_expert_groups(&m, &g, &s2, &formats(), 0, rows(0, 1, 0), ExpertTier::Vram), + Err(Error::InvalidDriverValue(s)) if s.contains("expert_groups") + )); + let other = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 1280).unwrap(); + assert_eq!( + plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &other, 0, rows(0, 1, 0), ExpertTier::Vram).unwrap_err(), + Error::InvalidQwenShape + ); + assert!(plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 48, rows(0, 1, 0), ExpertTier::Vram).is_err()); + } + + #[test] + fn expert_launches_are_refused_while_the_asset_is_unsealed() { + let m = map(); + let g = test_geometry(); + let l = plan_expert_groups(&m, &g, &MoeKnobs::mode17(), &formats(), 0, rows(0, 1, 0), ExpertTier::Vram).unwrap(); + assert_eq!(l[0].asset.sealed().unwrap_err(), Error::InvalidDriverValue(EXPERTS.unsealed)); + assert!(l[1].asset.sealed().is_ok()); + } + + // ---- hit add, combine ---------------------------------------------------------------------- + + #[test] + fn hit_add_scans_the_cpu_and_gpu_hits_of_the_group() { + let m = map(); + let g = test_geometry(); + let l = plan_hit_add(&m, &g, rows(3, 5, 1)).unwrap(); + assert_eq!(l.len(), 1); + assert!(l[0].entry.ends_with("add_hits_kernelEPfPKfPKiS6_i")); + // grid (min(ceil(2560/256), 8) = 8, cap = 20), 256 threads + assert_eq!((l[0].grid, l[0].block), ([8, 20, 1], [256, 1, 1])); + let plan = |word: usize| at(&m, "plan", (664 + word) * 4); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "parts", 3 * 10 * 2560 * 4)), + A::P(at(&m, "hit_out", 3 * 10 * 2560 * 4)), + A::P(plan(85)), + A::P(plan(1)), + A::I32(2560) + ] + ); + assert_abi(&l); + assert_eq!(plan_hit_add(&m, &g, rows(0, 1, 0)).unwrap()[0].grid, [8, 10, 1]); + } + + #[test] + fn batched_combine_is_one_launch_with_the_token_on_grid_y() { + let m = map(); + let g = test_geometry(); + let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 8, 0), true).unwrap(); + assert_eq!(l.len(), 1); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("mtp_full_combine", [10, 8, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "parts", 0)), + A::P(at(&m, "w", 0)), + A::P(at(&m, "shared", 0)), + A::P(at(&m, "bo", 0)), + A::I64(2560), + A::I32(10) + ] + ); + assert_abi(&l); + let b = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(4, 7, 1), true).unwrap(); + assert_eq!(b[0].grid, [10, 3, 1]); + assert_eq!(b[0].args[0], A::P(at(&m, "parts", 4 * 10 * 2560 * 4))); + assert_eq!(b[0].args[1], A::P(at(&m, "w", 4 * 10 * 4))); + assert_eq!(b[0].args[2], A::P(at(&m, "shared", 4 * 2560 * 4))); + assert_eq!(b[0].args[3], A::P(at(&m, "bo", 4 * 2560 * 4))); + } + + #[test] + fn per_row_combine_is_native_combine_per_token_or_the_legacy_kernel() { + let m = map(); + let g = test_geometry(); + let l = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(1, 3, 0), false).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[1].grid, l[1].block), ([10, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![ + A::P(at(&m, "parts", 2 * 10 * 2560 * 4)), + A::P(at(&m, "w", 2 * 10 * 4)), + A::P(at(&m, "shared", 2 * 2560 * 4)), + A::P(at(&m, "bo", 2 * 2560 * 4)), + A::I64(2560), + A::I32(10) + ] + ); + assert_abi(&l); + // a single-row window is never batched, even with native combine on + let one = plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), false).unwrap(); + assert_eq!((one[0].entry, one[0].grid), ("mtp_full_combine", [10, 1, 1])); + // moe_combine<<>>(parts, w, shared, y, N, K, has_shared = 1) + let mut legacy = MoeKnobs::mode17(); + legacy.native_combine = false; + let l = plan_combine(&m, &g, &legacy, rows(0, 2, 0), false).unwrap(); + assert_eq!(l.len(), 2); + assert!(l[0].entry.ends_with("moe_combine_kernelEPKfS3_S3_Pfiii")); + assert_eq!((l[0].grid, l[0].block), ([20, 1, 1], [128, 1, 1])); + assert_eq!(l[1].args[4..], [A::I32(2560), A::I32(10), A::I32(1)]); + assert_abi(&l); + assert_eq!(plan_combine(&m, &g, &legacy, rows(0, 2, 0), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_combine(&m, &g, &MoeKnobs::mode17(), rows(0, 1, 0), true).unwrap_err(), Error::InvalidQwenShape); + } + + #[test] + fn plan_word_stays_inside_the_plan_span_and_the_two_groups() { + let m = map(); + let g = test_geometry(); + assert_eq!(plan_word(&m, &g, 0, 0).unwrap(), at(&m, "plan", 0)); + assert_eq!(plan_word(&m, &g, 1, 647).unwrap(), at(&m, "plan", (664 + 647) * 4)); + assert!(plan_word(&m, &g, 0, 648).is_err()); + assert!(plan_word(&m, &g, 2, 0).is_err()); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_moe_experts.cu b/crates/cuda-driver/src/original_verify_window_moe_experts.cu new file mode 100644 index 00000000..2a3f5f16 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_moe_experts.cu @@ -0,0 +1,130 @@ +// src/original_verify_window_moe_experts.cu - the grouped native-expert gate/up and down kernels of the +// Verifier window (child of `original_verify`, producer family MoE / FFN). +// +// Original: engine/strata/src/kernels/cuda/iq_kernels.cu, `native_expert_grouped`: +// +// launch_gu -> native_gu_kernel | native_gu_multi_kernel (kSplit selects the second) +// swiglu_entries_kernel, quantize_q8_1_kernel (sealed in mtp_original_full_head_iq.ptx) +// launch_down -> native_down_kernel | native_down_multi_kernel +// +// `native_gu_kernel` and friends are TEMPLATES instantiated by the in-TU host wrapper, and no sealed PTX +// instantiates them for the target's expert formats (mtp_original_full_head_iq.ptx carries the swiglu and q8_1 +// quantize kernels, the MMVQ heads and the dequantizers, but neither the gu nor the down grouped kernels). This +// translation unit textually includes the sealed copy of iq_kernels.cu (so every trait, `row_dot`, `row_dot_multi`, +// `Fmt`, `Split`, `kSplit`, `GU_ROWS`, `GRP_NC` and the STRATA_GU_FMTS / STRATA_D_FMTS lists are the Original's, +// unchanged) and adds one `extern "C"` kernel per format whose body is the Original kernel body, line for line +// (a `__global__` template cannot be called from another kernel, so the bodies are `__device__` templates here). +// The exports are named by ggml type: window_moe_gu_ (T in STRATA_GU_FMTS) and window_moe_down_ (T in +// STRATA_D_FMTS). The split/non-split choice of `launch_gu` / `launch_down` is made at compile time per type, +// exactly as in the Original with STRATA_OLD_IQ_MMVQ unset (the default). +// +// Build: scripts/build-original-verify-ptx.sh flags (nvcc --ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false); +// engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source options (it is not in the --use_fast_math list). +#include "mtp_original_full_head_iq.cu" + +namespace strata::kernels { +namespace { + +// native_gu_kernel / native_gu_multi_kernel +template +__device__ __forceinline__ void window_gu_body(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_tok, + const block_q8_1* __restrict__ xq, const NativeExpertLayout& L, + float* __restrict__ gate, float* __restrict__ up) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int row = blockIdx.x * GU_ROWS + warp; // 0 .. 2*n_ff + if (row >= 2 * L.n_ff) return; + const bool is_up = row >= L.n_ff; + const int r = is_up ? row - (int) L.n_ff : row; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + (is_up ? L.up_off : 0) + (size_t) r * L.gu_row; + const int nb = (int) (L.n_embd / Fmt::qk), xb = (int) (L.n_embd / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + if constexpr (!kSplit) { + for (int e = e0; e < e1; ++e) { + const float s = row_dot(wr, xq + (size_t) ent_tok[e] * xb, nb, lane); + if (lane == 0) (is_up ? up : gate)[(size_t) e * L.n_ff + r] = s; + } + } else { + float* dst = is_up ? up : gate; + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + int off[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = ent_tok[e + min(c, n - 1)] * xb; + float s[GRP_NC]; + row_dot_multi(wr, xq, off, n, nb, lane, s); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) dst[(size_t) (e + c) * L.n_ff + r] = s[c]; + } + } +} + +// native_down_kernel / native_down_multi_kernel +template +__device__ __forceinline__ void window_down_body(const unsigned long long* __restrict__ grp_ptr, + const int32_t* __restrict__ grp_start, + const int32_t* __restrict__ n_groups, + const int32_t* __restrict__ ent_dst, + const block_q8_1* __restrict__ hq, const NativeExpertLayout& L, + float* __restrict__ out) { + const int g = blockIdx.y; + if (g >= *n_groups) return; + const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; + const int r = blockIdx.x * 8 + warp; + if (r >= L.n_embd) return; + const uint8_t* blob = (const uint8_t*) grp_ptr[g]; + const uint8_t* wr = blob + L.down_off + (size_t) r * L.d_row; + const int nb = (int) (L.n_ff / Fmt::qk), hb = (int) (L.n_ff / 32); + const int e0 = grp_start[g], e1 = grp_start[g + 1]; + if constexpr (!kSplit) { + for (int e = e0; e < e1; ++e) { + const float s = row_dot(wr, hq + (size_t) e * hb, nb, lane); + if (lane == 0) out[(size_t) ent_dst[e] * L.n_embd + r] = s; + } + } else { + for (int e = e0; e < e1; e += GRP_NC) { + const int n = min(GRP_NC, e1 - e); + int off[GRP_NC]; +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) off[c] = (e + min(c, n - 1)) * hb; + float s[GRP_NC]; + row_dot_multi(wr, hq, off, n, nb, lane, s); +#pragma unroll + for (int c = 0; c < GRP_NC; ++c) + if (c < n && lane == c) out[(size_t) ent_dst[e + c] * L.n_embd + r] = s[c]; + } + } +} + +} // namespace + +// Kernel parameters, in the Original's order: (grp_ptr, grp_start, n_groups, ent_tok, xq, L, gate, up). +// `L` is the 64-byte NativeExpertLayout by value (gu_type, d_type, n_embd, n_ff, gu_row, d_row, up_off, down_off, bytes). +#define STRATA_WINDOW_GU(T) \ + extern "C" __global__ void __launch_bounds__(256) window_moe_gu_##T( \ + const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, \ + const int32_t* __restrict__ n_groups, const int32_t* __restrict__ ent_tok, \ + const block_q8_1* __restrict__ xq, NativeExpertLayout L, float* __restrict__ gate, float* __restrict__ up) { \ + window_gu_body(grp_ptr, grp_start, n_groups, ent_tok, xq, L, gate, up); \ + } +STRATA_GU_FMTS(STRATA_WINDOW_GU) +#undef STRATA_WINDOW_GU + +// Kernel parameters, in the Original's order: (grp_ptr, grp_start, n_groups, ent_dst, hq, L, out). +#define STRATA_WINDOW_DOWN(T) \ + extern "C" __global__ void __launch_bounds__(256) window_moe_down_##T( \ + const unsigned long long* __restrict__ grp_ptr, const int32_t* __restrict__ grp_start, \ + const int32_t* __restrict__ n_groups, const int32_t* __restrict__ ent_dst, \ + const block_q8_1* __restrict__ hq, NativeExpertLayout L, float* __restrict__ out) { \ + window_down_body(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \ + } +STRATA_D_FMTS(STRATA_WINDOW_DOWN) +#undef STRATA_WINDOW_DOWN + +} // namespace strata::kernels diff --git a/crates/cuda-driver/src/original_verify_window_moe_experts.ptx b/crates/cuda-driver/src/original_verify_window_moe_experts.ptx new file mode 100644 index 00000000..caa84823 Binary files /dev/null and b/crates/cuda-driver/src/original_verify_window_moe_experts.ptx differ diff --git a/crates/cuda-driver/src/original_verify_window_ops.rs b/crates/cuda-driver/src/original_verify_window_ops.rs index afece7d3..e8ba27f8 100644 --- a/crates/cuda-driver/src/original_verify_window_ops.rs +++ b/crates/cuda-driver/src/original_verify_window_ops.rs @@ -1,53 +1,67 @@ //! Concrete producer set of the literal Verifier window (child of //! `original_verify`). It binds the recorder (`window_record`) to the genuine -//! owners that already exist and are capturable: +//! owners and sealed kernels, producer by producer: //! //! * the verify module (token/step copies, embedding broadcast, ring waits, plan //! copy, PCIe blob staging, CPU-row copy, doorbell, GPU stamps), -//! * the retained GDN journal (conv / alpha-beta / recurrence), -//! * the retained QSA journal (tail snapshot and indexer append over the twelve -//! resident images), -//! * the native embedding rows. +//! * the retained GDN journal (conv / alpha-beta / recurrence) and QSA journal +//! (tail snapshot and indexer append over the twelve resident images), +//! * the native embedding rows and the native head rows (`capture_head_greedy`), +//! * `Planner` (`original_verify_window_planner.rs`), which plans every other +//! Strata call of `record_window` as launches of SEALED PTX assets: hc read, +//! q8_1 quantization and native MMVQ projections (`proj`), QSA K/V append, norm/RoPE, +//! scores/top-k, KV resolve, decode attention and gate (`qsa`), router, shared expert, +//! routed expert groups, hit add and combine (`moe`), final residual write, head +//! mixing and PLE layer 1 (`gr`). //! -//! Every other Strata call of `record_window` (hc read, q8_1 quantization, -//! native MMVQ projections, QSA norm/RoPE/KV append/scores/resolve/decode -//! attention/gate, router, shared expert, grouped experts, hit add, combine, -//! final residual write, head mixing, PLE) has NO capturable Rust owner yet. -//! Those producers fail closed with a named error instead of substituting -//! prompt-GEMM or per-token arithmetic, so a partially bound window can never be -//! recorded, replayed or relabelled complete. `UNBOUND_PRODUCERS` is the -//! authoritative list of what is still missing. +//! Nothing here substitutes prompt-GEMM or per-token arithmetic. What cannot run is +//! refused by name: a family whose weights are not attached refuses with +//! `Original verifier producer unbound: : ... not attached`, a producer +//! whose policy variant has no genuine kernel refuses with `... producer unavailable: +//! : `, and a kernel asset that is not sealed refuses the whole window +//! BEFORE capture with `... asset unsealed: ()` (`unsealed_window_assets` +//! lists them). A partially bound window can therefore never be recorded or replayed. use super::*; +use super::gr::{self, GrConfig, OriginalVerifyGrBinding}; +use super::kernels::{AssetSpec, Launch}; +use super::moe::{self, MoeLayerAddrs, OriginalVerifyExpertFormats, OriginalVerifyMoeBinding}; +use super::planner::{Planner, WindowWeights}; +use super::proj::{self, GdnProjectionAddrs, OriginalVerifyProjBinding, QsaProjectionAddrs}; +use super::qsa::{self, OriginalVerifyQsaBinding, OriginalVerifyQsaKvBinding, QsaLayerAddrs, QsaRope}; use super::window_plan::{PlanLayout, WINDOW_LAYERS, staging_blobs_per_group}; use super::window_record::{ ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowOps, WindowPolicy, record_window, }; use crate::{OriginalNativeEmbedRows, OriginalNativeHeadGraphResources}; -/// Producers with no genuine capturable owner in this tree, by recorder method. -pub const UNBOUND_PRODUCERS: &[&str] = &[ - "ple_layer1", - "hc_read", - "quantize_q8_1", - "mmvq", - "qsa_index_k", - "qsa_k_norm_rope", - "qsa_kv_append", - "qsa_q_path", - "qsa_index_q_path", - "qsa_block_scores_topk", - "qsa_kv_resolve", - "qsa_decode_attention", - "qsa_gate", - "router", - "shared_expert", - "quantize_expert_input", - "expert_groups", - "hit_add", - "combine", - "final_write", - "head", -]; +/// Producers with no genuine capturable owner in this tree: none. Every `WindowOps` call is bound; what is +/// unavailable at run time is reported by `unsealed_window_assets` and by the per-producer refusals above. +pub const UNBOUND_PRODUCERS: &[&str] = &[]; + +/// Every kernel asset a window can launch from (all families), regardless of what is attached. +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 spec in family { + if !all.iter().any(|a: &&AssetSpec| std::ptr::eq(*a, spec)) { + all.push(spec); + } + } + } + all +} +/// The kernel assets that are placeholders or fail their SHA-256 pin: a window cannot be recorded until Root +/// seals them (`scripts/build-original-verify-ptx.sh`, `docs/cuda-seal-plan-additions-window.json`). +pub fn unsealed_window_assets() -> Vec<&'static str> { + let mut out: Vec<&'static str> = Vec::new(); + for spec in all_window_assets() { + if spec.sealed().is_err() && !out.contains(&spec.key()) { + out.push(spec.key()); + } + } + out +} /// Per-layer routed-expert blob sizes (`expert_layout().blob_bytes(l)`): the /// PCIe share staged by a copy kernel moves whole blobs. Retained for the @@ -70,13 +84,23 @@ impl OriginalVerifyExpertLayout { /// The all-owner aggregate of one captured window graph: the GDN journal, the /// twelve QSA images and the head rows (`OriginalVerifyResources`), plus the -/// graph-referenced embedding rows and the expert blob layout. A graph cannot -/// pair owners of different contexts. +/// graph-referenced embedding rows and the expert blob layout, and the weight +/// bindings of every producer family. A graph cannot pair owners of different contexts. pub struct OriginalVerifyWindowResources<'a, 'ctx> { base: OriginalVerifyResources<'a, 'ctx>, embed: OriginalNativeEmbedRows<'ctx>, experts: OriginalVerifyExpertLayout, rows: usize, + /// Native MMVQ projection matrices of the 36 GDN and 12 QSA layers (attached by the model adapter). + proj: Option>, + /// hc weights of the 48 layers, the final mixer and the optional PLE block. + gr: Option>, + /// QSA norms and indexer projections of the 12 QSA layers. + qsa: Option>, + /// Router, shared experts and routed expert formats of the 48 layers. + moe: Option>, + /// The per-card fused-GR decisions, read once by `prepare`. + gr_cfg: Option, } impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> { pub fn new( @@ -91,11 +115,136 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> { if !(1..=8).contains(&rows) || base.head.rows() != rows { return Err(Error::InvalidQwenShape); } - Ok(Self { base, embed, experts, rows }) + Ok(Self { base, embed, experts, rows, proj: None, gr: None, qsa: None, moe: None, gr_cfg: None }) } pub fn rows(&self) -> usize { self.rows } + /// Attach the GDN/QSA native projection matrices (`quantize_q8_1` + `mmvq` producers). + pub fn with_projections(mut self, proj: OriginalVerifyProjBinding<'a, 'ctx>) -> Result { + let context = self.base.journal.context(); + let geometry = self.base.journal.geometry(); + for i in 0..36 { + proj.gdn_addrs(context, &geometry, i)?; + } + for i in 0..12 { + proj.qsa_addrs(context, &geometry, i)?; + } + self.proj = Some(proj); + Ok(self) + } + /// Attach the hyper-connection weights (`hc_read`, `final_write`, `head`, and `ple_layer1` with PLE). + /// The PLE binding must match the journal: present exactly when the window carries a PLE history, and + /// the SAME history buffer the journal snapshots. + pub fn with_gr(mut self, gr: OriginalVerifyGrBinding<'a, 'ctx>) -> Result { + let journal = &self.base.journal; + if gr.has_ple() != journal.has_ple() { + return Err(Error::InvalidQwenShape); + } + if gr.has_ple() && Some(gr.ple_addrs()?.history) != journal.ple_history_address()? { + return Err(Error::OutputAliasesInput); + } + self.gr = Some(gr); + Ok(self) + } + /// Attach the QSA layer weights (norms, indexer projections). + pub fn with_qsa(mut self, qsa: OriginalVerifyQsaBinding<'a, 'ctx>) -> Result { + qsa.validate_context(self.base.journal.context())?; + for q in 0..12 { + OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?.validate(&self.base.journal.geometry())?; + } + self.qsa = Some(qsa); + Ok(self) + } + /// Attach the router / shared-expert weights and the routed experts' formats. The formats' blob sizes must + /// equal the expert layout this graph stages PCIe blobs with. + pub fn with_moe(mut self, moe: OriginalVerifyMoeBinding<'a, 'ctx>) -> Result { + moe.validate_context(self.base.journal.context())?; + for layer in 0..WINDOW_LAYERS { + if moe.formats().blob_bytes(layer)? != self.experts.blob_bytes(layer)? { + return Err(Error::InvalidQwenShape); + } + } + self.moe = Some(moe); + Ok(self) + } + /// 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> { + let mut assets: Vec<&'static AssetSpec> = Vec::new(); + if let Some(proj) = &self.proj { + assets.extend(proj.assets()); + } + if self.gr.is_some() { + assets.extend(gr::assets()); + } + if self.qsa.is_some() { + assets.extend(qsa::assets()); + } + if self.moe.is_some() { + assets.extend(moe::assets()); + } + assets + } + /// 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())?; + 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)); + } + if self.moe.is_some() { + attributes.extend(moe::shared_attributes(&Planner::moe_knobs_of(policy))); + } + self.base.journal.configure_window_shared(&attributes)?; + self.gr_cfg = Some(cfg); + Ok(()) + } +} +macro_rules! unattached { + ($producer:literal, $what:literal) => { + Error::InvalidDriverValue(concat!("Original verifier producer unbound: ", $producer, ": ", $what, " not attached")) + }; +} +impl WindowWeights for OriginalVerifyWindowResources<'_, '_> { + fn gdn_projections(&self, gdn: usize) -> Result { + let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; + p.gdn_addrs(self.base.journal.context(), &self.base.journal.geometry(), gdn) + } + fn qsa_projections(&self, q: usize) -> Result { + let p = self.proj.as_ref().ok_or(unattached!("mmvq", "projection weights"))?; + p.qsa_addrs(self.base.journal.context(), &self.base.journal.geometry(), q) + } + fn hc(&self, layer: usize, half: HcHalf) -> Result { + self.gr.as_ref().ok_or(unattached!("hc_read", "hyper-connection weights"))?.half_addrs(layer, half) + } + fn head(&self) -> Result { + self.gr.as_ref().ok_or(unattached!("head", "output hyper-connection weights"))?.head_addrs() + } + fn ple(&self) -> Result> { + let gr = self.gr.as_ref().ok_or(unattached!("ple_layer1", "hyper-connection / PLE weights"))?; + if gr.has_ple() { gr.ple_addrs().map(Some) } else { Ok(None) } + } + fn qsa(&self, q: usize) -> Result { + let b = self.qsa.as_ref().ok_or(unattached!("qsa", "QSA layer weights"))?; + let kv = OriginalVerifyQsaKvBinding::from_journal(&self.base.qsa, q)?; + kv.validate(&self.base.journal.geometry())?; + Ok(QsaLayerAddrs { weights: b.addrs(q)?, kv }) + } + fn rope(&self) -> Result { + QsaRope::from_rope(&self.base.qsa.rope()) + } + fn moe(&self, layer: usize) -> Result { + self.moe.as_ref().ok_or(unattached!("router", "router / shared-expert weights"))?.addrs(layer) + } + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { + Ok(self.moe.as_ref().ok_or(unattached!("expert_groups", "routed expert formats"))?.formats()) + } } impl resources::Sealed for OriginalVerifyWindowResources<'_, '_> {} impl OriginalGraphResources for OriginalVerifyWindowResources<'_, '_> { @@ -121,18 +270,13 @@ impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResour } } -macro_rules! unbound { - ($name:literal) => { - Err(Error::InvalidDriverValue(concat!("Original verifier producer unbound: ", $name))) - }; -} - /// The recorder's producer set over one graph's capture stream and resources. pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'a, 'ctx> { capture: &'c mut OriginalCapture<'s, 'ctx>, resources: &'c mut OriginalVerifyWindowResources<'a, 'ctx>, t: usize, groups: usize, + policy: WindowPolicy, } impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { fn geometry(&self) -> OriginalVerifyGeometry { @@ -152,6 +296,26 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> { fn submit(&mut self, commands: Vec) -> Result<()> { self.resources.base.journal.submit(self.capture, commands) } + /// Record planned launches of any sealed asset on the capture stream, in order. + fn launch(&mut self, launches: Vec) -> Result<()> { + self.resources.base.journal.submit_launches(self.capture, launches) + } + /// The pure planner over this graph's arena, policy and weight bindings. + fn planner(&self) -> Result> { + let cfg = self + .resources + .gr_cfg + .ok_or(Error::InvalidDriverValue("Original verifier window: resources were not prepared before capture"))?; + Ok(Planner::new(&self.resources.base.journal, self.geometry(), self.policy, cfg, &*self.resources)) + } + /// Plan with the planner, then record the launches. + fn plan_launch(&mut self, plan: impl FnOnce(&Planner<'_>) -> Result>) -> Result<()> { + let launches = { + let planner = self.planner()?; + plan(&planner)? + }; + self.launch(launches) + } /// Address of a word inside the group's device plan block (`words` int32 units). fn plan_word(&self, group: usize, word: usize) -> Result { let layout = self.plan(); @@ -201,17 +365,26 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { fn stamp(&mut self, layer: usize, stage: usize) -> Result<()> { self.resources.base.journal.capture_stamp(self.capture, layer, stage) } - fn ple_layer1(&mut self, _: Rows) -> Result<()> { - unbound!("ple_layer1") + fn ple_layer1(&mut self, rows: Rows) -> Result<()> { + let per_row = { + let planner = self.planner()?; + planner.ple_layer1(rows)? + }; + // Each row's history snapshot (`copy_from_mapped(hist_snap_ + t*HS, ss.ple.hist, HS)`) follows that row. + for (row, launches) in per_row { + self.launch(launches)?; + self.resources.base.journal.capture_ple_snapshot(self.capture, row)?; + } + Ok(()) } - fn hc_read(&mut self, _: usize, _: HcHalf, _: bool, _: Rows) -> Result<()> { - unbound!("hc_read") + fn hc_read(&mut self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.hc_read(layer, half, apply, rows)) } - fn quantize_q8_1(&mut self, _: usize, _: QuantSource, _: Rows) -> Result<()> { - unbound!("quantize_q8_1") + fn quantize_q8_1(&mut self, _layer: usize, source: QuantSource, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.quantize_q8_1(source, rows)) } - fn mmvq(&mut self, _: usize, _: Projection, _: Rows) -> Result<()> { - unbound!("mmvq") + fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.mmvq(layer, projection, rows)) } fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()> { self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Conv, self.capture, layer, rows.begin, rows.end) @@ -222,52 +395,52 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> { self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::Recurrence, self.capture, layer, rows.begin, rows.end) } - fn qsa_index_k(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("qsa_index_k") + fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_index_k(q, rows, batched)) } - fn qsa_k_norm_rope(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("qsa_k_norm_rope") + fn qsa_k_norm_rope(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_k_norm_rope(q, rows, batched)) } fn qsa_tail_snapshot(&mut self, layer: usize) -> Result<()> { let base = &self.resources.base; base.qsa.capture_tail_snapshot(&base.journal, self.capture, layer) } - fn qsa_kv_append(&mut self, _: usize, _: Rows) -> Result<()> { - unbound!("qsa_kv_append") + fn qsa_kv_append(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_kv_append(q, rows)) } fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()> { let base = &self.resources.base; base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin, rows.end) } - fn qsa_q_path(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("qsa_q_path") + fn qsa_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_q_path(q, rows, batched)) } - fn qsa_index_q_path(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("qsa_index_q_path") + fn qsa_index_q_path(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched)) } - fn qsa_block_scores_topk(&mut self, _: usize, _: Rows) -> Result<()> { - unbound!("qsa_block_scores_topk") + fn qsa_block_scores_topk(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_block_scores_topk(q, rows)) } - fn qsa_kv_resolve(&mut self, _: usize, _: Rows) -> Result<()> { - unbound!("qsa_kv_resolve") + fn qsa_kv_resolve(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_kv_resolve(q, rows)) } - fn qsa_decode_attention(&mut self, _: usize, _: Rows) -> Result<()> { - unbound!("qsa_decode_attention") + fn qsa_decode_attention(&mut self, q: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.qsa_decode_attention(q, rows)) } - fn qsa_gate(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("qsa_gate") + fn qsa_gate(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.qsa_gate(q, rows, batched)) } - fn router(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("router") + fn router(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.router(layer, rows, batched)) } fn doorbell(&mut self, rows: Rows) -> Result<()> { self.resources.base.journal.capture_doorbell(self.capture, rows.begin, rows.end) } - fn shared_expert(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("shared_expert") + fn shared_expert(&mut self, layer: usize, rows: Rows, dec_batch: bool) -> Result<()> { + self.plan_launch(|p| p.shared_expert(layer, rows, dec_batch)) } - fn quantize_expert_input(&mut self, _: usize, _: Rows) -> Result<()> { - unbound!("quantize_expert_input") + fn quantize_expert_input(&mut self, _layer: usize, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.quantize_expert_input(rows)) } fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> { self.wait_flag(11, ring)?; @@ -282,8 +455,8 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { vec![Arg::Address(device), Arg::Address(mapped), Arg::I32(layout.words as i32)], )?]) } - fn expert_groups(&mut self, _: usize, _: Rows, _: ExpertTier) -> Result<()> { - unbound!("expert_groups") + fn expert_groups(&mut self, layer: usize, rows: Rows, tier: ExpertTier) -> Result<()> { + self.plan_launch(|p| p.expert_groups(layer, rows, tier)) } fn wait_copies(&mut self, ring: u32) -> Result<()> { self.wait_flag(12, ring) @@ -347,17 +520,21 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> { }; self.submit(vec![command]) } - fn hit_add(&mut self, _: Rows) -> Result<()> { - unbound!("hit_add") + fn hit_add(&mut self, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.hit_add(rows)) } - fn combine(&mut self, _: usize, _: Rows, _: bool) -> Result<()> { - unbound!("combine") + fn combine(&mut self, _layer: usize, rows: Rows, batched: bool) -> Result<()> { + self.plan_launch(|p| p.combine(rows, batched)) } - fn final_write(&mut self, _: Rows) -> Result<()> { - unbound!("final_write") + fn final_write(&mut self, rows: Rows) -> Result<()> { + self.plan_launch(|p| p.final_write(rows)) } - fn head(&mut self, _: usize) -> Result<()> { - unbound!("head") + fn head(&mut self, rows: usize) -> Result<()> { + // Per token `lm_head_mix` into the head rows' `mixed` buffer, then the head owner's captured tail: + // quantize ALL T, native MMVQ ALL T, greedy argmax (`capture_head_greedy`). + let mixed = handle(self.resources.base.head.mixed_mut()?)?.qwen_address(); + self.plan_launch(|p| p.head_mix(mixed, rows))?; + self.resources.base.head.capture_head_greedy(self.capture) } } @@ -375,9 +552,12 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { return Err(Error::InvalidQwenShape); } let ple = resources.verifier_journal().has_ple(); + // Sealed modules load before capture begins (cuModuleLoadData is not a capturable call). + let mut resources = resources; + resources.prepare(&policy)?; self.record_window(t, resources, |capture, resources, groups| { // The recorder re-validates the shape; the groups come from `set_split`. - let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups }; + let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy }; record_window(&mut ops, &policy, t, groups, ple) }) } @@ -406,6 +586,32 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> { mod tests { use super::*; + #[test] + fn exactly_the_new_sources_are_unsealed_until_root_seals_them() { + // The two NEW sources (grouped native experts, fast-math QSA gate) are placeholders; every other asset is a + // pinned, sealed PTX. A window cannot be recorded while any asset it uses is unsealed. + let mut unsealed = unsealed_window_assets(); + unsealed.sort_unstable(); + assert_eq!(unsealed, ["original_verify_window_moe_experts.ptx", "original_verify_window_qsa_gate.ptx"]); + } + + #[test] + fn every_window_asset_is_listed_once_and_names_a_distinct_module() { + let all = all_window_assets(); + let mut keys: Vec<&str> = all.iter().map(|a| a.key()).collect(); + let count = keys.len(); + keys.sort_unstable(); + keys.dedup(); + // specs of one PTX file share a key (entries are unioned by the loader); no key hides two different files + assert!(keys.len() <= count); + for key in &keys { + let mut pins = all.iter().filter(|a| a.key() == *key).map(|a| (a.sha, a.ptx.len())); + let first = pins.next().unwrap(); + assert!(pins.all(|p| p == first), "{key}: specs of one module disagree on the file"); + } + assert!(UNBOUND_PRODUCERS.is_empty()); + } + #[test] fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() { assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok()); @@ -419,19 +625,4 @@ mod tests { assert_eq!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(47), Ok(32)); assert!(OriginalVerifyExpertLayout::new([32; WINDOW_LAYERS], 64).unwrap().blob_bytes(48).is_err()); } - - #[test] - fn unbound_producers_are_listed_once_and_fail_closed_with_their_name() { - let mut seen = std::collections::BTreeSet::new(); - for name in UNBOUND_PRODUCERS { - assert!(seen.insert(*name), "{name} listed twice"); - } - let error: Result<()> = unbound!("router"); - assert_eq!(error, Err(Error::InvalidDriverValue("Original verifier producer unbound: router"))); - // the bound producers (journals, verify module, embedding) are not on the list - for bound in ["embed", "stamp", "gdn_conv", "gdn_alpha_beta", "gdn_recurrence", "qsa_tail_snapshot", - "qsa_indexer_append", "doorbell", "wait_plan", "wait_copies", "pcie_stage", "wait_cpu", "copy_cpu_rows"] { - assert!(!UNBOUND_PRODUCERS.contains(&bound), "{bound}"); - } - } } diff --git a/crates/cuda-driver/src/original_verify_window_planner.rs b/crates/cuda-driver/src/original_verify_window_planner.rs new file mode 100644 index 00000000..c3aa8218 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_planner.rs @@ -0,0 +1,535 @@ +//! The pure planning half of the window producers (child of `original_verify`). +//! +//! `Planner` turns one `WindowOps` call into the kernel launches of `Verifier::record_window` +//! (`Vec`) from the arena map, the window geometry, the process-wide policy and a +//! `WindowWeights` source. The real `OriginalVerifyWindowOps` submits those launches on the +//! capture stream; the tests run the whole recorder through `PlanOps` (no driver) to pin +//! the complete launch order of a window against verify.cpp. +use super::gr::{self, GrConfig, HcAddrs, HeadAddrs, PleAddrs, PleConfig}; +use super::kernels::{ArenaMap, Launch}; +use super::moe::{self, MoeKnobs, MoeLayerAddrs, OriginalVerifyExpertFormats}; +use super::proj::{self, GdnProjectionAddrs, QsaProjectionAddrs}; +use super::qsa::{QsaLayerAddrs, QsaRope, QsaWindow}; +use super::window_plan::{gdn_index, qsa_index}; +use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowPolicy}; +use super::OriginalVerifyGeometry; +use crate::{Error, Result}; + +/// Where the planners read model weights and fixed state addresses from. The real source is the +/// window resource aggregate (validated bindings); tests supply synthetic addresses. +pub(crate) trait WindowWeights { + /// `attn_qkv` / `attn_gate` / `ssm_out` of GDN layer `gdn` (0..36). + fn gdn_projections(&self, gdn: usize) -> Result; + /// `attn_k` / `attn_v` / `attn_q` / `attn_output` of QSA layer `q` (0..12). + fn qsa_projections(&self, q: usize) -> Result; + fn hc(&self, layer: usize, half: HcHalf) -> Result; + fn head(&self) -> Result; + /// `None` when the model has no PLE block. + fn ple(&self) -> Result>; + /// Norm / indexer weights plus the fixed KV and index addresses of QSA layer `q`. + fn qsa(&self, q: usize) -> Result; + fn rope(&self) -> Result; + fn moe(&self, layer: usize) -> Result; + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats>; +} + +pub(crate) struct Planner<'p> { + pub arena: &'p dyn ArenaMap, + pub geo: OriginalVerifyGeometry, + pub policy: WindowPolicy, + pub gr: GrConfig, + pub weights: &'p dyn WindowWeights, +} + +impl<'p> Planner<'p> { + pub(crate) fn new( + arena: &'p dyn ArenaMap, + geo: OriginalVerifyGeometry, + policy: WindowPolicy, + gr: GrConfig, + weights: &'p dyn WindowWeights, + ) -> Self { + Self { arena, geo, policy, gr, weights } + } + pub(crate) fn moe_knobs_of(policy: &WindowPolicy) -> MoeKnobs { + MoeKnobs { + native_router: policy.native_router, + native_combine: policy.native_combine, + native_experts: policy.native_experts, + native_bf16: policy.native_bf16, + native_bf16_extra: policy.native_bf16_extra, + dispatch: policy.dispatch, + } + } + fn moe_knobs(&self) -> MoeKnobs { + Self::moe_knobs_of(&self.policy) + } + fn ple_config(&self) -> PleConfig { + PleConfig { native_value_bf16: self.policy.native_ple, native_postops: self.policy.native_ple, dispatch: self.policy.dispatch } + } + fn qsa_window(&self) -> Result> { + QsaWindow::new(self.arena, self.geo, self.policy.qsa, self.weights.rope()?) + } + + // ---- GR + pub(crate) fn hc_read(&self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result> { + let w = self.weights.hc(layer, half)?; + Ok(gr::plan_hc_read(self.arena, &self.geo, &w, &self.gr, half, apply, rows)?.launches()) + } + pub(crate) fn final_write(&self, rows: Rows) -> Result> { + gr::plan_final_write(self.arena, &self.geo, &self.gr, rows) + } + /// The per-token `lm_head_mix` launches writing the head rows' `mixed` buffer at `mixed_out_base`. + pub(crate) fn head_mix(&self, mixed_out_base: u64, rows: usize) -> Result> { + let w = self.weights.head()?; + gr::plan_head_mix(self.arena, &self.geo, &w, &self.gr, mixed_out_base, rows) + } + /// One entry per window row: that row's launches, to be followed by the PLE history snapshot copy of the row. + pub(crate) fn ple_layer1(&self, rows: Rows) -> Result)>> { + let ple = self.weights.ple()?.ok_or(Error::InvalidDriverValue( + "Original verifier producer unbound: ple_layer1: the model has a PLE block but no PLE weights are attached", + ))?; + gr::plan_ple_layer1(self.arena, &self.geo, &self.gr, &self.ple_config(), &ple, rows) + } + + // ---- projections + pub(crate) fn quantize_q8_1(&self, source: QuantSource, rows: Rows) -> Result> { + Ok(vec![proj::plan_window_quantize(self.arena, &self.geo, source, rows)?]) + } + pub(crate) fn mmvq(&self, layer: usize, projection: Projection, rows: Rows) -> Result> { + let weight = match projection { + Projection::GdnQkv | Projection::GdnGate | Projection::GdnOut => { + let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?; + self.weights.gdn_projections(g)?.get(projection)? + } + Projection::QsaK | Projection::QsaV | Projection::QsaQ | Projection::QsaOut => { + let q = qsa_index(layer).ok_or(Error::InvalidQwenShape)?; + self.weights.qsa_projections(q)?.get(projection)? + } + }; + Ok(vec![proj::plan_window_mmvq(self.arena, &self.geo, layer, projection, &weight, rows, self.policy.dispatch)?]) + } + + // ---- QSA (all take the QSA layer index) + pub(crate) fn qsa_index_k(&self, q: usize, rows: Rows, batched: bool) -> Result> { + self.qsa_window()?.index_k(q, &self.weights.qsa(q)?, rows, batched) + } + pub(crate) fn qsa_k_norm_rope(&self, q: usize, rows: Rows, batched: bool) -> Result> { + self.qsa_window()?.k_norm_rope(q, &self.weights.qsa(q)?, rows, batched) + } + pub(crate) fn qsa_kv_append(&self, q: usize, rows: Rows) -> Result> { + self.qsa_window()?.kv_append(q, &self.weights.qsa(q)?, rows) + } + pub(crate) fn qsa_q_path(&self, q: usize, rows: Rows, batched: bool) -> Result> { + self.qsa_window()?.q_path(q, &self.weights.qsa(q)?, rows, batched) + } + pub(crate) fn qsa_index_q_path(&self, q: usize, rows: Rows, batched: bool) -> Result> { + self.qsa_window()?.index_q_path(q, &self.weights.qsa(q)?, rows, batched) + } + pub(crate) fn qsa_block_scores_topk(&self, q: usize, rows: Rows) -> Result> { + self.qsa_window()?.block_scores_topk(q, &self.weights.qsa(q)?, rows) + } + pub(crate) fn qsa_kv_resolve(&self, q: usize, rows: Rows) -> Result> { + self.qsa_window()?.kv_resolve(q, &self.weights.qsa(q)?, rows) + } + pub(crate) fn qsa_decode_attention(&self, q: usize, rows: Rows) -> Result> { + self.qsa_window()?.decode_attention(q, &self.weights.qsa(q)?, rows) + } + pub(crate) fn qsa_gate(&self, q: usize, rows: Rows, batched: bool) -> Result> { + self.qsa_window()?.gate(q, rows, batched) + } + + // ---- FFN + pub(crate) fn router(&self, layer: usize, rows: Rows, batched: bool) -> Result> { + let w = self.weights.moe(layer)?; + moe::plan_router(self.arena, &self.geo, &self.moe_knobs(), w.router, rows, batched) + } + pub(crate) fn shared_expert(&self, layer: usize, rows: Rows, dec_batch: bool) -> Result> { + let w = self.weights.moe(layer)?; + moe::plan_shared_expert(self.arena, &self.geo, &self.moe_knobs(), &w, rows, dec_batch) + } + pub(crate) fn quantize_expert_input(&self, rows: Rows) -> Result> { + moe::plan_quantize_expert_input(self.arena, &self.geo, &self.moe_knobs(), rows) + } + pub(crate) fn expert_groups(&self, layer: usize, rows: Rows, tier: ExpertTier) -> Result> { + moe::plan_expert_groups(self.arena, &self.geo, &self.moe_knobs(), self.weights.expert_formats()?, layer, rows, tier) + } + pub(crate) fn hit_add(&self, rows: Rows) -> Result> { + moe::plan_hit_add(self.arena, &self.geo, rows) + } + pub(crate) fn combine(&self, rows: Rows, batched: bool) -> Result> { + moe::plan_combine(self.arena, &self.geo, &self.moe_knobs(), rows, batched) + } +} + +#[cfg(test)] +mod tests { + use super::super::kernels::{LayoutMap, test_geometry}; + use super::super::moe::MoeLayerAddrs; + use super::super::proj::NativeWeight; + use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs}; + use super::super::window_plan::WINDOW_LAYERS; + use super::super::window_record::{WindowOps, record_window}; + use super::*; + + const BASE: u64 = 0x7000_0000_0000; + + /// Synthetic weights: every layer's operands get distinct, 256-aligned addresses. + struct Fake { + formats: OriginalVerifyExpertFormats, + ple: bool, + } + fn w(a: u64) -> NativeWeight { + NativeWeight { ty: 14, data: a } + } + impl WindowWeights for Fake { + fn gdn_projections(&self, g: usize) -> Result { + let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000; + Ok(GdnProjectionAddrs { qkv: w(b), gate: NativeWeight { ty: 8, data: b + 0x100_0000 }, out: NativeWeight { ty: 12, data: b + 0x200_0000 } }) + } + fn qsa_projections(&self, q: usize) -> Result { + let b = 0x20_0000_0000u64 + q as u64 * 0x1000_0000; + Ok(QsaProjectionAddrs { + k: NativeWeight { ty: 12, data: b }, + v: NativeWeight { ty: 12, data: b + 0x100_0000 }, + q: w(b + 0x200_0000), + out: w(b + 0x300_0000), + }) + } + fn hc(&self, layer: usize, half: HcHalf) -> Result { + let b = 0x30_0000_0000u64 + layer as u64 * 0x1_0000_0000 + if half == HcHalf::Ffn { 0x8000_0000 } else { 0 }; + Ok(HcAddrs { norm: b, down: b + 0x100_0000, up: b + 0x200_0000, inject: b + 0x300_0000 }) + } + fn head(&self) -> Result { + Ok(HeadAddrs { norm: 0x3f_0000_0000, down: 0x3f_0100_0000, up: 0x3f_0200_0000 }) + } + fn ple(&self) -> Result> { + Ok(self.ple.then_some(PleAddrs { + key: gr::PleKey::Bf16(0x40_0000_0000), + value: 0x40_1000_0000, + norm_key: 0x40_2000_0000, + norm_query: 0x40_2100_0000, + norm_conv: 0x40_2200_0000, + conv1d: 0x40_2300_0000, + scratch: 0x40_3000_0000, + history: 0x40_4000_0000, + })) + } + fn qsa(&self, q: usize) -> Result { + let b = 0x50_0000_0000u64 + q as u64 * 0x1_0000_0000; + Ok(QsaLayerAddrs { + weights: QsaWeightAddrs { q_norm: b, k_norm: b + 0x1_0000, index_q_norm: b + 0x2_0000, index_k_proj: b + 0x100_0000, index_q_proj: b + 0x200_0000 }, + kv: OriginalVerifyQsaKvBinding { + resident: [b + 0x1000_0000, b + 0x1100_0000, b + 0x1200_0000, b + 0x1210_0000], + table: b + 0x1300_0000, + host: [b + 0x2000_0000, b + 0x2100_0000, b + 0x2200_0000, b + 0x2210_0000], + resolver: [b + 0x1300_0000, b + 0x1310_0000, b + 0x1320_0000, b + 0x1330_0000, b + 0x1340_0000, b + 0x1350_0000, b + 0x1360_0000], + pooled: b + 0x1400_0000, + pooled_bytes: 1026 * 512, + dead: b + 0x1410_0000, + dead_bytes: 512, + }, + }) + } + fn rope(&self) -> Result { + QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0) + } + fn moe(&self, layer: usize) -> Result { + let b = 0x60_0000_0000u64 + layer as u64 * 0x1_0000_0000; + Ok(MoeLayerAddrs { + router: b, + gate_inp_shexp: b + 0x100_0000, + gate_shexp: NativeWeight { ty: 8, data: b + 0x200_0000 }, + up_shexp: NativeWeight { ty: 8, data: b + 0x300_0000 }, + down_shexp: NativeWeight { ty: 8, data: b + 0x400_0000 }, + }) + } + fn expert_formats(&self) -> Result<&OriginalVerifyExpertFormats> { + Ok(&self.formats) + } + } + + /// Readable name of a launched kernel: the entry, or for a mangled Original kernel its base name. + fn kernel(l: &Launch) -> String { + const BASES: [&str; 14] = [ + "mmvf_multi_kernel", "mmvf_kernel", "to_bf16_kernel", "native_swiglu_kernel", "scalar_gate_kernel", + "native_scalar_sigmoid_multi_kernel", "native_scalar_sigmoid_kernel", "scale_rows_kernel", "moe_combine_kernel", + "swiglu_entries_kernel", "quantize_q8_1_kernel", "add_hits_kernel", "router_top10_kernel", "block_scores_kernel", + ]; + if !l.entry.starts_with("_ZN") { + return l.entry.to_string(); + } + BASES.iter().find(|b| l.entry.contains(*b)).map(|b| b.to_string()).unwrap_or_else(|| l.entry.to_string()) + } + + /// The recorder driven through the planners with no driver: every producer logs the kernels it would + /// launch (journal-owned producers log a marker). `fail` makes the named producer error. + struct PlanOps<'p> { + planner: Planner<'p>, + log: Vec, + t: usize, + } + impl PlanOps<'_> { + fn plan(&mut self, name: &str, r: Result>) -> Result<()> { + let launches = r?; + self.log.push(format!("<{name}")); + for l in &launches { + self.log.push(kernel(l)); + } + self.log.push(format!("{name}>")); + Ok(()) + } + fn mark(&mut self, s: String) -> Result<()> { + self.log.push(s); + Ok(()) + } + } + impl WindowOps for PlanOps<'_> { + fn embed(&mut self) -> Result<()> { self.mark("embed".into()) } + fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.mark(format!("stamp {l}.{s}")) } + fn ple_layer1(&mut self, rows: Rows) -> Result<()> { + let per = self.planner.ple_layer1(rows)?; + for (row, launches) in per { + self.log.push(format!(" Result<()> { + let x = self.planner.hc_read(l, h, a, r); + self.plan(&format!("hc {h:?} apply={a}"), x) + } + fn quantize_q8_1(&mut self, _: usize, s: QuantSource, r: Rows) -> Result<()> { + let x = self.planner.quantize_q8_1(s, r); + self.plan(&format!("quant {s:?}"), x) + } + fn mmvq(&mut self, l: usize, p: Projection, r: Rows) -> Result<()> { + let x = self.planner.mmvq(l, p, r); + self.plan(&format!("mmvq {p:?}"), x) + } + fn gdn_conv(&mut self, g: usize, r: Rows) -> Result<()> { self.mark(format!("gdn_conv g{g} {}..{}", r.begin, r.end)) } + fn gdn_alpha_beta(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_ab g{g}")) } + fn gdn_recurrence(&mut self, g: usize, _: Rows) -> Result<()> { self.mark(format!("gdn_rec g{g}")) } + fn qsa_index_k(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_k(q, r, b); + self.plan("index_k", x) + } + fn qsa_k_norm_rope(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_k_norm_rope(q, r, b); + self.plan("k_norm_rope", x) + } + fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.mark(format!("tail q{q}")) } + fn qsa_kv_append(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_append(q, r); + self.plan("kv_append", x) + } + fn qsa_indexer_append(&mut self, q: usize, _: Rows) -> Result<()> { self.mark(format!("indexer_append q{q}")) } + fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_q_path(q, r, b); + self.plan("q_path", x) + } + fn qsa_index_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_index_q_path(q, r, b); + self.plan("index_q_path", x) + } + fn qsa_block_scores_topk(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_block_scores_topk(q, r); + self.plan("scores_topk", x) + } + fn qsa_kv_resolve(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_kv_resolve(q, r); + self.plan("kv_resolve", x) + } + fn qsa_decode_attention(&mut self, q: usize, r: Rows) -> Result<()> { + let x = self.planner.qsa_decode_attention(q, r); + self.plan("attention", x) + } + fn qsa_gate(&mut self, q: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.qsa_gate(q, r, b); + self.plan("gate", x) + } + fn router(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.router(l, r, b); + self.plan("router", x) + } + fn doorbell(&mut self, _: Rows) -> Result<()> { self.mark("doorbell".into()) } + fn shared_expert(&mut self, l: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.shared_expert(l, r, b); + self.plan("shared", x) + } + fn quantize_expert_input(&mut self, _: usize, r: Rows) -> Result<()> { + let x = self.planner.quantize_expert_input(r); + self.plan("xq", x) + } + fn wait_plan(&mut self, ring: u32, _: Rows) -> Result<()> { self.mark(format!("waitA {ring}")) } + fn expert_groups(&mut self, l: usize, r: Rows, t: ExpertTier) -> Result<()> { + let x = self.planner.expert_groups(l, r, t); + self.plan(&format!("experts {t:?}"), x) + } + fn wait_copies(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitB {ring}")) } + fn pcie_stage(&mut self, _: usize, _: Rows) -> Result<()> { self.mark("pcie_stage".into()) } + fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.mark(format!("waitM {ring}")) } + fn copy_cpu_rows(&mut self, _: Rows, _: bool) -> Result<()> { self.mark("cpu_rows".into()) } + fn hit_add(&mut self, r: Rows) -> Result<()> { + let x = self.planner.hit_add(r); + self.plan("hit_add", x) + } + fn combine(&mut self, _: usize, r: Rows, b: bool) -> Result<()> { + let x = self.planner.combine(r, b); + self.plan("combine", x) + } + fn final_write(&mut self, r: Rows) -> Result<()> { + let x = self.planner.final_write(r); + self.plan("final_write", x) + } + fn head(&mut self, rows: usize) -> Result<()> { + assert_eq!(rows, self.t); + let x = self.planner.head_mix(0x7f_0000_0000, rows); + self.plan("head_mix", x)?; + self.mark("head_tail".into()) + } + } + + fn geometry_and_fake(ple: bool) -> (LayoutMap, Fake) { + let m = LayoutMap::new(BASE, test_geometry()); + let formats = OriginalVerifyExpertFormats::new([(16, 20); WINDOW_LAYERS], 2560, 640).unwrap(); + (m, Fake { formats, ple }) + } + fn sm120() -> GrConfig { + GrConfig::from_device(gr::GrVariant::Staged, true, 12, 0, 99 * 1024, 48 * 1024) + } + fn record(t: usize, groups: usize, ple: bool) -> Vec { + let (m, fake) = geometry_and_fake(ple); + let planner = Planner::new(&m, test_geometry(), WindowPolicy::mode17(), sm120(), &fake); + let mut ops = PlanOps { planner, log: Vec::new(), t }; + record_window(&mut ops, &WindowPolicy::mode17(), t, groups, ple).unwrap(); + ops.log + } + fn section<'a>(log: &'a [String], from: &str, to: &str) -> &'a [String] { + let a = log.iter().position(|s| s == from).unwrap_or_else(|| panic!("{from} missing")); + let b = a + log[a..].iter().position(|s| s == to).unwrap_or_else(|| panic!("{to} missing")); + &log[a..=b] + } + fn names(log: &[String]) -> Vec<&str> { + log.iter().map(String::as_str).collect() + } + + #[test] + fn every_window_size_and_group_split_plans_without_error() { + for groups in [1usize, 2] { + for t in 1..=8usize { + if groups == 2 && t < 2 { + continue; + } + for ple in [false, true] { + // the 8-row xq/qfull/kcur ... spans and every arena bound hold for the whole 48-layer window + let log = record(t, groups, ple); + assert_eq!(log.iter().filter(|s| *s == "doorbell").count(), 48 * groups); + assert_eq!(log.iter().filter(|s| s.as_str() == "head_tail").count(), 1); + assert_eq!(log.iter().filter(|s| s.starts_with("") < pos(""); + assert_eq!(names(router).iter().filter(|s| s.contains("mmvf_multi_kernel") || **s == "mtp_full_route").count(), 2); + // the projections are the native MMVQ of the bound weight types at three rows + assert!(k.contains(&"head_n14_t3_large") && k.contains(&"head_n8_t3_large") && k.contains(&"head_n12_t3_large")); + // layer 1's attention read folds the pending write (apply=true), layer 0's did not + assert!(log.iter().any(|s| s == " = order.iter().map(|n| pos(n)).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{order:?} -> {at:?}"); + // four rows are batched: one index-k multi gemv, one mmvq per projection at four columns + assert!(k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + assert!(k.contains(&"head_n12_t4_large") && k.contains(&"head_n14_t4_large")); + assert!(k.contains(&"verify_window_qsa_gate")); + assert!(k.contains(&"leleka_qsa_decode_chunk") && k.contains(&"leleka_qsa_decode_merge")); + // the single-row window keeps the per-token (unbatched) kernels + let one = record(1, 1, false); + let one_k = names(section(&one, "stamp 3.0", "stamp 3.16")); + assert!(one_k.iter().any(|s| s.contains("mtp_full_mmvf"))); + assert!(!one_k.iter().any(|s| s.contains("mmvf_multi_kernel"))); + } + + #[test] + fn post_records_vram_then_pcie_experts_hit_add_and_combine() { + let log = record(2, 1, false); + let post = section(&log, "waitA 1", "stamp 0.24"); + let k = names(post); + let order = ["waitA 1", " = order.iter().map(|n| k.iter().position(|s| s == n).unwrap_or_else(|| panic!("{n} missing"))).collect(); + assert!(at.windows(2).all(|w| w[0] < w[1]), "{at:?}"); + // each tier is gate/up, swiglu, quantize, down + let vram = names(section(&log, "")); + assert_eq!(&vram[1..vram.len() - 1], ["window_moe_gu_16", "swiglu_entries_kernel", "quantize_q8_1_kernel", "window_moe_down_20"]); + // the last layer writes the residual once per row + let last = section(&log, "stamp 47.24", "stamp 48.0"); + assert_eq!(names(last).iter().filter(|s| **s == "mtp_full_native_write").count(), 2); + } + + #[test] + fn split_windows_interleave_groups_but_keep_each_group_in_order() { + let log = record(5, 2, false); + // pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) ...: group B's first read follows A's FFN prep, then A's experts + let hcs: Vec = log.iter().enumerate().filter(|(_, s)| s.starts_with("` instantiation +//! for 2..=8 rows (the weight row read once, every row its single-row order). +use super::kernels::{A, ArenaMap, AssetSpec, Launch}; +use super::window_plan::{gdn_index, qsa_index}; +use super::window_record::{Projection, QuantSource, Rows}; +use super::OriginalVerifyGeometry; +use crate::{Context, DeviceBuffer}; +use crate::native_head::native_head_row_bytes; +use crate::{Error, NativeHeadDispatch, Result}; + +#[path = "mtp_original_full_head_dispatch.rs"] +mod head_dispatch; + +const HEAD_NATIVE_ENTRIES:&[&str]=&[ + "head_quant", "head_n2_s0", "head_n2_s1", "head_n2_t2_large", "head_n2_t2_small", "head_n2_t2_upstream", + "head_n2_t3_large", "head_n2_t3_small", "head_n2_t3_upstream", "head_n2_t4_large", "head_n2_t4_small", + "head_n2_t4_upstream", "head_n2_t5_large", "head_n2_t5_small", "head_n2_t5_upstream", "head_n2_t6_large", + "head_n2_t6_small", "head_n2_t6_upstream", "head_n2_t7_large", "head_n2_t7_small", "head_n2_t7_upstream", + "head_n2_t8_large", "head_n2_t8_small", "head_n2_t8_upstream", "head_n6_s0", "head_n6_s1", "head_n6_t2_large", + "head_n6_t2_small", "head_n6_t2_upstream", "head_n6_t3_large", "head_n6_t3_small", "head_n6_t3_upstream", + "head_n6_t4_large", "head_n6_t4_small", "head_n6_t4_upstream", "head_n6_t5_large", "head_n6_t5_small", + "head_n6_t5_upstream", "head_n6_t6_large", "head_n6_t6_small", "head_n6_t6_upstream", "head_n6_t7_large", + "head_n6_t7_small", "head_n6_t7_upstream", "head_n6_t8_large", "head_n6_t8_small", "head_n6_t8_upstream", + "head_n8_s0", "head_n8_s1", "head_n8_t2_large", "head_n8_t2_small", "head_n8_t2_upstream", "head_n8_t3_large", + "head_n8_t3_small", "head_n8_t3_upstream", "head_n8_t4_large", "head_n8_t4_small", "head_n8_t4_upstream", + "head_n8_t5_large", "head_n8_t5_small", "head_n8_t5_upstream", "head_n8_t6_large", "head_n8_t6_small", + "head_n8_t6_upstream", "head_n8_t7_large", "head_n8_t7_small", "head_n8_t7_upstream", "head_n8_t8_large", + "head_n8_t8_small", "head_n8_t8_upstream", "head_n20_s0", "head_n20_s1", "head_n20_t2_large", "head_n20_t2_small", + "head_n20_t2_upstream", "head_n20_t3_large", "head_n20_t3_small", "head_n20_t3_upstream", "head_n20_t4_large", + "head_n20_t4_small", "head_n20_t4_upstream", "head_n20_t5_large", "head_n20_t5_small", "head_n20_t5_upstream", + "head_n20_t6_large", "head_n20_t6_small", "head_n20_t6_upstream", "head_n20_t7_large", "head_n20_t7_small", + "head_n20_t7_upstream", "head_n20_t8_large", "head_n20_t8_small", "head_n20_t8_upstream", "head_n11_s0", + "head_n11_s1", "head_n11_t2_large", "head_n11_t2_small", "head_n11_t2_upstream", "head_n11_t3_large", + "head_n11_t3_small", "head_n11_t3_upstream", "head_n11_t4_large", "head_n11_t4_small", "head_n11_t4_upstream", + "head_n11_t5_large", "head_n11_t5_small", "head_n11_t5_upstream", "head_n11_t6_large", "head_n11_t6_small", + "head_n11_t6_upstream", "head_n11_t7_large", "head_n11_t7_small", "head_n11_t7_upstream", "head_n11_t8_large", + "head_n11_t8_small", "head_n11_t8_upstream", "head_n12_s0", "head_n12_s1", "head_n12_t2_large", + "head_n12_t2_small", "head_n12_t2_upstream", "head_n12_t3_large", "head_n12_t3_small", "head_n12_t3_upstream", + "head_n12_t4_large", "head_n12_t4_small", "head_n12_t4_upstream", "head_n12_t5_large", "head_n12_t5_small", + "head_n12_t5_upstream", "head_n12_t6_large", "head_n12_t6_small", "head_n12_t6_upstream", "head_n12_t7_large", + "head_n12_t7_small", "head_n12_t7_upstream", "head_n12_t8_large", "head_n12_t8_small", "head_n12_t8_upstream", + "head_n13_s0", "head_n13_s1", "head_n13_t2_large", "head_n13_t2_small", "head_n13_t2_upstream", + "head_n13_t3_large", "head_n13_t3_small", "head_n13_t3_upstream", "head_n13_t4_large", "head_n13_t4_small", + "head_n13_t4_upstream", "head_n13_t5_large", "head_n13_t5_small", "head_n13_t5_upstream", "head_n13_t6_large", + "head_n13_t6_small", "head_n13_t6_upstream", "head_n13_t7_large", "head_n13_t7_small", "head_n13_t7_upstream", + "head_n13_t8_large", "head_n13_t8_small", "head_n13_t8_upstream", "head_n14_s0", "head_n14_s1", + "head_n14_t2_large", "head_n14_t2_small", "head_n14_t2_upstream", "head_n14_t3_large", "head_n14_t3_small", + "head_n14_t3_upstream", "head_n14_t4_large", "head_n14_t4_small", "head_n14_t4_upstream", "head_n14_t5_large", + "head_n14_t5_small", "head_n14_t5_upstream", "head_n14_t6_large", "head_n14_t6_small", "head_n14_t6_upstream", + "head_n14_t7_large", "head_n14_t7_small", "head_n14_t7_upstream", "head_n14_t8_large", "head_n14_t8_small", + "head_n14_t8_upstream", "head_n23_s0", "head_n23_s1", "head_n23_t2_large", "head_n23_t2_small", + "head_n23_t2_upstream", "head_n23_t3_large", "head_n23_t3_small", "head_n23_t3_upstream", "head_n23_t4_large", + "head_n23_t4_small", "head_n23_t4_upstream", "head_n23_t5_large", "head_n23_t5_small", "head_n23_t5_upstream", + "head_n23_t6_large", "head_n23_t6_small", "head_n23_t6_upstream", "head_n23_t7_large", "head_n23_t7_small", + "head_n23_t7_upstream", "head_n23_t8_large", "head_n23_t8_small", "head_n23_t8_upstream", "head_n42_s0", + "head_n42_s1", "head_n42_t2_large", "head_n42_t2_small", "head_n42_t2_upstream", "head_n42_t3_large", + "head_n42_t3_small", "head_n42_t3_upstream", "head_n42_t4_large", "head_n42_t4_small", "head_n42_t4_upstream", + "head_n42_t5_large", "head_n42_t5_small", "head_n42_t5_upstream", "head_n42_t6_large", "head_n42_t6_small", + "head_n42_t6_upstream", "head_n42_t7_large", "head_n42_t7_small", "head_n42_t7_upstream", "head_n42_t8_large", + "head_n42_t8_small", "head_n42_t8_upstream", +]; +const HEAD_IQ_ENTRIES:&[&str]=&[ + "head_i7_old", "head_i16_old", "head_i16_c1", "head_i16_c2", "head_i16_c4", "head_i16_c8", "head_i17_old", + "head_i17_c1", "head_i17_c2", "head_i17_c4", "head_i17_c8", "head_i18_old", "head_i18_c1", "head_i18_c2", + "head_i18_c4", "head_i18_c8", "head_i21_old", "head_i21_c1", "head_i21_c2", "head_i21_c4", "head_i21_c8", + "head_i22_old", "head_i22_c1", "head_i22_c2", "head_i22_c4", "head_i22_c8", "head_i29_old", "head_i29_c1", + "head_i29_c2", "head_i29_c4", "head_i29_c8", +]; +const BF16_ENTRIES:&[&str]=&[ + "mtp_full_mmvf32", "mtp_full_mmvf64", "mtp_full_mmvf96", "mtp_full_mmvf128", "mtp_full_mmvf160", + "mtp_full_mmvf192", "mtp_full_mmvf224", "mtp_full_mmvf256", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi32ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi32ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi64ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi64ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi96ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi96ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi128ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi128ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi160ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi160ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi192ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi192ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi224ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi224ELi8EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi256ELi4EEEvPKflPKtPflii", + "_ZN6strata7kernels58_GLOBAL__N__d5e6e908_25_mtp_original_full_bf16_cu_55b113d026bf16_f32_mmvf_multi_kernelILi256ELi8EEEvPKflPKtPflii", +]; + +pub(crate) static HEAD_NATIVE: AssetSpec = AssetSpec { + name: "mtp_original_full_head_native.ptx", + ptx: include_bytes!("mtp_original_full_head_native.ptx"), + sha: [218,92,166,59,230,97,73,85,77,24,176,58,230,163,234,41,95,123,44,151,175,189,100,145,68,94,225,174,10,41,226,66], + entries: HEAD_NATIVE_ENTRIES, + unsealed: "Original verifier asset unsealed: mtp_original_full_head_native.ptx (native MMVQ / q8_1 quantize)", +}; +pub(crate) static HEAD_IQ: AssetSpec = AssetSpec { + name: "mtp_original_full_head_iq.ptx", + ptx: include_bytes!("mtp_original_full_head_iq.ptx"), + sha: [60,95,19,213,116,127,120,160,75,228,21,95,8,36,185,31,126,75,16,202,55,150,173,210,73,18,34,143,171,90,69,32], + entries: HEAD_IQ_ENTRIES, + unsealed: "Original verifier asset unsealed: mtp_original_full_head_iq.ptx (IQ-type MMVQ)", +}; +pub(crate) static BF16: AssetSpec = AssetSpec { + name: "mtp_original_full_bf16.ptx", + ptx: include_bytes!("mtp_original_full_bf16.ptx"), + sha: [161,109,252,252,154,73,204,171,37,216,3,2,147,213,130,111,143,117,226,134,143,174,27,108,76,239,112,107,109,252,61,8], + entries: BF16_ENTRIES, + unsealed: "Original verifier asset unsealed: mtp_original_full_bf16.ptx (bf16 MMVF)", +}; + +/// A native (GGUF-format) projection weight: the ggml type id and the device address of its rows. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct NativeWeight { + pub ty: u32, + pub data: u64, +} + +/// Bytes of one q8_1-quantized activation row of `n_in` elements (`n_in/32` blocks of 36). +pub(crate) const fn q8_1_row_bytes(n_in: usize) -> usize { + n_in / 32 * 36 +} +/// Kinds served by the IQ head kernels (`head_i*`); every other native kind is `head_n*`. +pub(crate) const fn is_iq_kind(kind: u32) -> bool { + matches!(kind, 7 | 16 | 17 | 18 | 21 | 22 | 29) +} +/// Both native MMVQ head assets (the IQ one only serves IQ-typed weights). +pub(crate) fn mmvq_assets() -> Vec<&'static AssetSpec> { + vec![&HEAD_NATIVE, &HEAD_IQ] +} +/// The sealed asset that serves `native_mmvq` for this ggml type. +pub(crate) fn mmvq_asset(kind: u32) -> &'static AssetSpec { + if is_iq_kind(kind) { &HEAD_IQ } else { &HEAD_NATIVE } +} + +/// `native_quantize_q8_1(x, xq, n_in, rows)`: one launch over all `rows * n_in` elements. +pub(crate) fn plan_quantize_q8_1(x: u64, xq: u64, n_in: usize, rows: usize) -> Result { + if n_in == 0 || n_in % 32 != 0 || !(1..=8).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + let total = n_in * rows; + let count = i32::try_from(total).map_err(|_| Error::InvalidSize)?; + Launch::new(&HEAD_NATIVE, "head_quant", [total.div_ceil(256) as u32, 1, 1], [256, 1, 1], 0, vec![A::P(x), A::P(xq), A::I32(count)]) +} + +/// `native_mmvq(type, w, xq, y, n_in, n_out, rows)`. `y` rows are `n_out` floats apart, `xq` rows +/// `q8_1_row_bytes(n_in)` apart (the layout `plan_quantize_q8_1` writes). +pub(crate) fn plan_mmvq( + w: &NativeWeight, + xq: u64, + y: u64, + n_in: usize, + n_out: usize, + rows: usize, + dispatch: NativeHeadDispatch, +) -> Result { + if n_in == 0 || n_in % 32 != 0 || n_out == 0 || !(1..=8).contains(&rows) { + return Err(Error::InvalidQwenShape); + } + let (n_in32, n_out32) = (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?); + let (entry, grid, block, iq) = head_dispatch::head_dispatch(w.ty, n_in, n_out, rows, dispatch)?; + let mut args = vec![A::P(w.data)]; + if iq { + args.push(A::U64(native_head_row_bytes(w.ty, n_in)? as u64)); + } + args.extend([A::P(xq), A::P(y), A::I32(n_in32), A::I32(n_out32)]); + if iq { + args.push(A::I32(rows as i32)); + } + Launch::new(mmvq_asset(w.ty), entry, grid, block, 0, args) +} + +/// `mmvf_block_size`: the block (32..=256 in steps of 32) with the fewest weight-row iterations. +pub(crate) const fn mmvf_block_size(n_in: usize) -> u32 { + let mut best = 32usize; + let mut best_iterations = n_in.div_ceil(64); + let mut candidate = 64usize; + while candidate <= 256 { + let iterations = n_in.div_ceil(2 * candidate); + if iterations < best_iterations { + best_iterations = iterations; + best = candidate; + } + candidate += 32; + } + best as u32 +} +fn multi_entry(block: u32, nt: u32) -> Result<&'static str> { + let needle = format!("mmvf_multi_kernelILi{block}ELi{nt}EE"); + BF16_ENTRIES.iter().copied().find(|e| e.contains(&needle)).ok_or(Error::UnsupportedQwenOperation) +} +fn single_entry(block: u32) -> Result<&'static str> { + let name = format!("mtp_full_mmvf{block}"); + BF16_ENTRIES.iter().copied().find(|e| **e == *name).ok_or(Error::UnsupportedQwenOperation) +} + +/// `bf16_gemv_fp32_mmvf_multi(x, ldx, w, y, ldy, n_in, n_out, n_tok)` (1..=8 rows; one row with +/// `ldy >= n_out` is `bf16_gemv_fp32_mmvf`). Strides are in elements. +#[allow(clippy::too_many_arguments)] +pub(crate) fn plan_bf16_gemv( + x: u64, + ldx: usize, + w: u64, + y: u64, + ldy: usize, + n_in: usize, + n_out: usize, + n_tok: usize, +) -> Result { + if !(1..=8).contains(&n_tok) || n_in == 0 || n_in % 2 != 0 || n_out == 0 || ldx % 2 != 0 || x % 8 != 0 { + return Err(Error::InvalidQwenShape); + } + let (n_in32, grid) = (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, u32::try_from(n_out).map_err(|_| Error::InvalidSize)?); + let block = mmvf_block_size(n_in); + if n_tok == 1 && ldy >= n_out { + return Launch::new(&BF16, single_entry(block)?, [grid, 1, 1], [block, 1, 1], 0, vec![A::P(x), A::P(w), A::P(y), A::I32(n_in32)]); + } + let nt = if n_tok <= 4 { 4 } else { 8 }; + Launch::new( + &BF16, + multi_entry(block, nt)?, + [grid, 1, 1], + [block, 1, 1], + 0, + vec![A::P(x), A::I64(ldx as i64), A::P(w), A::P(y), A::I64(ldy as i64), A::I32(n_in32), A::I32(n_tok as i32)], + ) +} + + +// ------------------------------------------------------------------------------------------------ +// The window's projection producers: `quantize_q8_1` and `mmvq` of `record_window`. +// ------------------------------------------------------------------------------------------------ + +/// Elements of one activation row for each `QuantSource` and the arena span holding it. +const fn quant_source_span(source: QuantSource) -> &'static str { + match source { + QuantSource::Mixed => "mixed", + QuantSource::GdnY => "y", + QuantSource::Attention => "attn32", + } +} +/// Floats per activation row of a quantization source: `mixed_` N, GDN `y_` ssm_value_dim, +/// QSA `attn32_` n_head * head_dim. +pub(crate) fn quant_source_width(geo: &OriginalVerifyGeometry, source: QuantSource) -> usize { + match source { + QuantSource::Mixed => geo.n, + QuantSource::GdnY => geo.value_heads * 128, + QuantSource::Attention => geo.heads * geo.head_dim, + } +} + +/// `native_quantize_q8_1(src + tb*width, xq_, width, n)`: the group's rows are quantized into the +/// START of `xq_` (every group overwrites it; the MMVQs that follow read it from row 0). +pub(crate) fn plan_window_quantize( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + source: QuantSource, + rows: Rows, +) -> Result { + let width = quant_source_width(geo, source); + let n = rows.len(); + if rows.is_empty() || rows.end > geo.max_t { + return Err(Error::InvalidQwenShape); + } + let x = arena.span(quant_source_span(source), rows.begin * width * 4, n * width * 4)?; + let xq = arena.span("xq", 0, n * q8_1_row_bytes(width))?; + plan_quantize_q8_1(x, xq, width, n) +} + +/// `(input width, output width, y span, y row stride in floats)` of one window projection on `layer`. +fn projection_shape( + geo: &OriginalVerifyGeometry, + projection: Projection, + layer: usize, +) -> Result<(usize, usize, &'static str, usize)> { + let (n, zv, ch) = (geo.n, geo.value_heads * 128, geo.channels); + let gdn = gdn_index(layer); + let qsa = qsa_index(layer); + match projection { + Projection::GdnQkv if gdn.is_some() => Ok((n, ch, "qkv_L", ch)), + Projection::GdnGate if gdn.is_some() => Ok((n, zv, "z", zv)), + Projection::GdnOut if gdn.is_some() => Ok((zv, n, "bo", n)), + Projection::QsaK if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "kcur", geo.kv_heads * geo.head_dim)), + Projection::QsaV if qsa.is_some() => Ok((n, geo.kv_heads * geo.head_dim, "vcur", geo.kv_heads * geo.head_dim)), + Projection::QsaQ if qsa.is_some() => Ok((n, geo.heads * 2 * geo.head_dim, "qfull", geo.heads * 2 * geo.head_dim)), + Projection::QsaOut if qsa.is_some() => Ok((geo.heads * geo.head_dim, n, "bo", n)), + _ => Err(Error::InvalidQwenShape), + } +} +/// Rows of the layer-major retained banks (`qkv_L`) a GDN layer owns: `gdn_index * max_t`. +fn projection_first_row(geo: &OriginalVerifyGeometry, projection: Projection, layer: usize, begin: usize) -> usize { + match (projection, gdn_index(layer)) { + (Projection::GdnQkv, Some(g)) => g * geo.max_t + begin, + _ => begin, + } +} + +/// `native_mmvq(type, w, xq_, y + tb*rows_stride, n_in, n_out, n)`: the weight reads the q8_1 rows the +/// preceding `plan_window_quantize` left at the start of `xq_`. +pub(crate) fn plan_window_mmvq( + arena: &dyn ArenaMap, + geo: &OriginalVerifyGeometry, + layer: usize, + projection: Projection, + weight: &NativeWeight, + rows: Rows, + dispatch: NativeHeadDispatch, +) -> Result { + let (n_in, n_out, y_span, stride) = projection_shape(geo, projection, layer)?; + let n = rows.len(); + if rows.is_empty() || rows.end > geo.max_t { + return Err(Error::InvalidQwenShape); + } + let first = projection_first_row(geo, projection, layer, rows.begin); + let y = arena.span(y_span, first * stride * 4, n * n_out * 4)?; + let xq = arena.span("xq", 0, n * q8_1_row_bytes(n_in))?; + plan_mmvq(weight, xq, y, n_in, n_out, n, dispatch) +} + +/// One native projection weight with its buffer, as the runtime hands it over. +pub struct OriginalVerifyNativeMatrix<'a, 'ctx> { + pub kind: u32, + pub buffer: &'a DeviceBuffer<'ctx>, +} +/// `attn_qkv.weight`, `attn_gate.weight`, `ssm_out.weight` of one GDN layer. +pub struct OriginalVerifyGdnProjections<'a, 'ctx> { + pub qkv: OriginalVerifyNativeMatrix<'a, 'ctx>, + pub gate: OriginalVerifyNativeMatrix<'a, 'ctx>, + pub out: OriginalVerifyNativeMatrix<'a, 'ctx>, +} +/// `attn_k.weight`, `attn_v.weight`, `attn_q.weight`, `attn_output.weight` of one QSA layer. +pub struct OriginalVerifyQsaProjections<'a, 'ctx> { + pub k: OriginalVerifyNativeMatrix<'a, 'ctx>, + pub v: OriginalVerifyNativeMatrix<'a, 'ctx>, + pub q: OriginalVerifyNativeMatrix<'a, 'ctx>, + pub out: OriginalVerifyNativeMatrix<'a, 'ctx>, +} +/// Addresses of a GDN layer's projections. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct GdnProjectionAddrs { + pub qkv: NativeWeight, + pub gate: NativeWeight, + pub out: NativeWeight, +} +/// Addresses of a QSA layer's projections. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct QsaProjectionAddrs { + pub k: NativeWeight, + pub v: NativeWeight, + pub q: NativeWeight, + pub out: NativeWeight, +} +impl GdnProjectionAddrs { + pub(crate) fn get(&self, projection: Projection) -> Result { + match projection { + Projection::GdnQkv => Ok(self.qkv), + Projection::GdnGate => Ok(self.gate), + Projection::GdnOut => Ok(self.out), + _ => Err(Error::InvalidQwenShape), + } + } +} +impl QsaProjectionAddrs { + pub(crate) fn get(&self, projection: Projection) -> Result { + match projection { + Projection::QsaK => Ok(self.k), + Projection::QsaV => Ok(self.v), + Projection::QsaQ => Ok(self.q), + Projection::QsaOut => Ok(self.out), + _ => Err(Error::InvalidQwenShape), + } + } +} + +/// The 36 GDN and 12 QSA layers' native projection matrices (the Original `native_of(...)` weights). +/// Sizes are exact: `n_out` rows of `native_head_row_bytes(kind, n_in)`. +pub struct OriginalVerifyProjBinding<'a, 'ctx> { + gdn: Vec>, + qsa: Vec>, +} +/// Bytes of a native matrix of `n_out` rows by `n_in` columns of ggml `kind`. +pub(crate) fn native_matrix_bytes(kind: u32, n_in: usize, n_out: usize) -> Result { + native_head_row_bytes(kind, n_in)?.checked_mul(n_out).ok_or(Error::InvalidSize) +} +fn admit_matrix( + context: &Context<'_>, + m: &OriginalVerifyNativeMatrix<'_, '_>, + n_in: usize, + n_out: usize, +) -> Result { + let bytes = native_matrix_bytes(m.kind, n_in, n_out)?; + Ok(NativeWeight { ty: m.kind, data: super::admit(context, m.buffer, bytes)? }) +} +impl<'a, 'ctx> OriginalVerifyProjBinding<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + geometry: &OriginalVerifyGeometry, + gdn: Vec>, + qsa: Vec>, + ) -> Result { + if gdn.len() != 36 || qsa.len() != 12 { + return Err(Error::InvalidQwenShape); + } + let this = Self { gdn, qsa }; + for i in 0..36 { + this.gdn_addrs(context, geometry, i)?; + } + for i in 0..12 { + this.qsa_addrs(context, geometry, i)?; + } + Ok(this) + } + pub(crate) fn gdn_addrs(&self, context: &Context<'_>, geo: &OriginalVerifyGeometry, gdn_index: usize) -> Result { + let m = self.gdn.get(gdn_index).ok_or(Error::InvalidQwenShape)?; + let zv = geo.value_heads * 128; + Ok(GdnProjectionAddrs { + qkv: admit_matrix(context, &m.qkv, geo.n, geo.channels)?, + gate: admit_matrix(context, &m.gate, geo.n, zv)?, + out: admit_matrix(context, &m.out, zv, geo.n)?, + }) + } + pub(crate) fn qsa_addrs(&self, context: &Context<'_>, geo: &OriginalVerifyGeometry, qsa_index: usize) -> Result { + let m = self.qsa.get(qsa_index).ok_or(Error::InvalidQwenShape)?; + let kv = geo.kv_heads * geo.head_dim; + Ok(QsaProjectionAddrs { + k: admit_matrix(context, &m.k, geo.n, kv)?, + v: admit_matrix(context, &m.v, geo.n, kv)?, + q: admit_matrix(context, &m.q, geo.n, geo.heads * 2 * geo.head_dim)?, + out: admit_matrix(context, &m.out, geo.heads * geo.head_dim, geo.n)?, + }) + } + /// Every sealed asset the bound projection types need (the IQ kernels only when an IQ type is bound). + pub(crate) fn assets(&self) -> Vec<&'static AssetSpec> { + let mut out = vec![&HEAD_NATIVE]; + let iq = self.gdn.iter().any(|m| [&m.qkv, &m.gate, &m.out].iter().any(|x| is_iq_kind(x.kind))) + || self.qsa.iter().any(|m| [&m.k, &m.v, &m.q, &m.out].iter().any(|x| is_iq_kind(x.kind))); + if iq { + out.push(&HEAD_IQ); + } + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn entry_declared(ptx: &str, e: &str) -> bool { + ptx.contains(&format!(".entry {e}(")) + } + + #[test] + fn assets_are_pinned_and_export_every_named_entry() { + for spec in [&HEAD_NATIVE, &HEAD_IQ, &BF16] { + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(entry_declared(&text, e), "{} lacks {e}", spec.name); + } + } + } + + #[test] + fn quantize_is_one_launch_over_all_rows() { + let l = plan_quantize_q8_1(0x100, 0x200, 2560, 8).unwrap(); + assert_eq!(l.entry, "head_quant"); + assert_eq!(l.grid, [80, 1, 1]); + assert_eq!(l.args, vec![A::P(0x100), A::P(0x200), A::I32(20480)]); + assert_eq!(plan_quantize_q8_1(0, 0, 2560, 9).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_quantize_q8_1(0, 0, 2570, 1).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(q8_1_row_bytes(2560), 2880); + } + + #[test] + fn mmvq_follows_the_native_head_dispatch() { + let d = NativeHeadDispatch::default(); + let q8 = NativeWeight { ty: 8, data: 0x1000 }; + let one = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 1, d).unwrap(); + assert_eq!((one.entry, one.grid, one.block), ("head_n8_s0", [12288, 1, 1], [32, 4, 1])); + assert_eq!(one.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560), A::I32(12288)]); + let four = plan_mmvq(&q8, 0x2000, 0x3000, 2560, 12288, 4, d).unwrap(); + assert_eq!((four.entry, four.grid), ("head_n8_t4_large", [12288, 1, 1])); + // 256-wide K quants, 3 rows + let q6 = NativeWeight { ty: 14, data: 0x1000 }; + assert_eq!(plan_mmvq(&q6, 1, 2, 6144, 2560, 3, d).unwrap().entry, "head_n14_t3_large"); + // not exact: the upstream layout + let up = NativeHeadDispatch { multi_exact: false, old_iq: false }; + assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 640, 3, up).unwrap().entry, "head_n8_t3_upstream"); + assert_eq!(plan_mmvq(&NativeWeight { ty: 99, data: 0 }, 1, 2, 2560, 64, 1, d).unwrap_err(), Error::UnsupportedQwenOperation); + assert_eq!(plan_mmvq(&q8, 1, 2, 2560, 0, 1, d).unwrap_err(), Error::InvalidQwenShape); + } + + #[test] + fn iq_kinds_use_the_iq_asset_with_row_bytes_and_columns() { + assert!(is_iq_kind(16) && !is_iq_kind(8) && !is_iq_kind(23)); + let w = NativeWeight { ty: 16, data: 0x10 }; + let l = plan_mmvq(&w, 0x20, 0x30, 2560, 1280, 3, NativeHeadDispatch::default()).unwrap(); + assert!(std::ptr::eq(l.asset, &HEAD_IQ)); + assert_eq!(l.entry, "head_i16_c4"); + assert_eq!(l.args[1], A::U64(2560 / 256 * 66)); + assert_eq!(l.args.last(), Some(&A::I32(3))); + assert_eq!(l.grid, [320, 1, 1]); + } + + #[test] + fn mmvf_block_matches_the_original_search() { + assert_eq!(mmvf_block_size(2560), 256); + // 64: 3 iterations, 96: 2, 128: 2 (no gain), 160: 1 -> 160 (later candidates cannot beat one iteration) + assert_eq!(mmvf_block_size(320), 160); + assert_eq!(mmvf_block_size(192), 96); + assert_eq!(mmvf_block_size(10240), 256); + assert_eq!(mmvf_block_size(64), 32); + assert_eq!(mmvf_block_size(128), 64); + } + + #[test] + fn bf16_gemv_is_single_for_one_row_and_multi_otherwise() { + let s = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 128, 2560, 128, 1).unwrap(); + assert_eq!((s.entry, s.grid, s.block), ("mtp_full_mmvf256", [128, 1, 1], [256, 1, 1])); + assert_eq!(s.args, vec![A::P(0x1000), A::P(0x2000), A::P(0x3000), A::I32(2560)]); + let m = plan_bf16_gemv(0x1000, 2560, 0x2000, 0x3000, 512, 2560, 512, 4).unwrap(); + assert!(m.entry.contains("ILi256ELi4EE")); + assert_eq!(m.args[1], A::I64(2560)); + assert_eq!(m.args[4], A::I64(512)); + assert_eq!(m.args[6], A::I32(4)); + assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 5).unwrap().entry.contains("ILi256ELi8EE")); + // one row whose output stride is narrower than the row goes through the multi kernel + assert!(plan_bf16_gemv(0x1000, 2560, 2, 3, 64, 2560, 512, 1).unwrap().entry.contains("ILi256ELi4EE")); + assert_eq!(plan_bf16_gemv(0x1004, 2560, 2, 3, 512, 2560, 512, 2).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2561, 512, 2).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(plan_bf16_gemv(0x1000, 2560, 2, 3, 512, 2560, 512, 9).unwrap_err(), Error::InvalidQwenShape); + } + + use super::super::kernels::{LayoutMap, test_geometry}; + + fn rows(begin: usize, end: usize) -> Rows { + Rows { begin, end, group: 0 } + } + + #[test] + fn window_quantize_reads_the_groups_rows_and_writes_the_start_of_xq() { + let geo = test_geometry(); + let m = LayoutMap::new(0x4000_0000, geo); + let off = |name: &str| m.layout.span(name).unwrap().offset as u64; + let l = plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(2, 5)).unwrap(); + assert_eq!(l.entry, "head_quant"); + assert_eq!(l.grid, [(3 * 2560usize).div_ceil(256) as u32, 1, 1]); + assert_eq!(l.args, vec![A::P(0x4000_0000 + off("mixed") + 2 * 2560 * 4), A::P(0x4000_0000 + off("xq")), A::I32(7680)]); + // GDN y rows are 48 heads x 128, QSA attn32 rows 24 x 256: both 6144 wide + let y = plan_window_quantize(&m, &geo, QuantSource::GdnY, rows(0, 8)).unwrap(); + assert_eq!(y.args, vec![A::P(0x4000_0000 + off("y")), A::P(0x4000_0000 + off("xq")), A::I32(8 * 6144)]); + assert_eq!(y.grid, [192, 1, 1]); + let a = plan_window_quantize(&m, &geo, QuantSource::Attention, rows(4, 8)).unwrap(); + assert_eq!(a.args[0], A::P(0x4000_0000 + off("attn32") + 4 * 6144 * 4)); + // the 8-row 6144-wide image fills xq exactly (the arena carves xq for max_in = 6144) + assert_eq!(m.layout.span("xq").unwrap().bytes, 8 * q8_1_row_bytes(6144)); + assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(3, 3)).is_err()); + assert!(plan_window_quantize(&m, &geo, QuantSource::Mixed, rows(6, 9)).is_err()); + } + + #[test] + fn window_mmvq_addresses_follow_the_original_output_banks() { + let geo = test_geometry(); + let m = LayoutMap::new(0x4000_0000, geo); + let off = |name: &str| m.layout.span(name).unwrap().offset as u64; + let w = NativeWeight { ty: 8, data: 0xAA00 }; + let d = NativeHeadDispatch::default(); + // GDN layer 4 is the fourth GDN layer (index 3); the retained qkv bank has max_t rows per GDN layer + let qkv = plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(3, 5), d).unwrap(); + assert_eq!((qkv.entry, qkv.grid, qkv.block), ("head_n8_t2_large", [10240, 1, 1], [32, 4, 1])); + assert_eq!( + qkv.args, + vec![A::P(0xAA00), A::P(0x4000_0000 + off("xq")), A::P(0x4000_0000 + off("qkv_L") + (3 * 8 + 3) as u64 * 10240 * 4), A::I32(2560), A::I32(10240)] + ); + let gate = plan_window_mmvq(&m, &geo, 0, Projection::GdnGate, &w, rows(0, 1), d).unwrap(); + assert_eq!((gate.entry, gate.grid), ("head_n8_s0", [6144, 1, 1])); + assert_eq!(gate.args[2], A::P(0x4000_0000 + off("z"))); + let out = plan_window_mmvq(&m, &geo, 0, Projection::GdnOut, &w, rows(0, 8), d).unwrap(); + assert_eq!(out.args[3..], [A::I32(6144), A::I32(2560)]); + assert_eq!(out.args[2], A::P(0x4000_0000 + off("bo"))); + // QSA layer 3 (index 0) + let q = plan_window_mmvq(&m, &geo, 3, Projection::QsaQ, &w, rows(1, 3), d).unwrap(); + assert_eq!(q.args[2], A::P(0x4000_0000 + off("qfull") + 12288 * 4)); + assert_eq!(q.args[4], A::I32(12288)); + let k = plan_window_mmvq(&m, &geo, 3, Projection::QsaK, &w, rows(0, 8), d).unwrap(); + assert_eq!(k.args[4], A::I32(512)); + assert_eq!(k.args[2], A::P(0x4000_0000 + off("kcur"))); + let o = plan_window_mmvq(&m, &geo, 7, Projection::QsaOut, &w, rows(0, 2), d).unwrap(); + assert_eq!(o.args[3..], [A::I32(6144), A::I32(2560)]); + // a projection of the other layer kind is refused + assert!(plan_window_mmvq(&m, &geo, 3, Projection::GdnQkv, &w, rows(0, 1), d).is_err()); + assert!(plan_window_mmvq(&m, &geo, 4, Projection::QsaK, &w, rows(0, 1), d).is_err()); + assert!(plan_window_mmvq(&m, &geo, 4, Projection::GdnQkv, &w, rows(0, 9), d).is_err()); + } + + #[test] + fn native_matrix_sizes_are_row_bytes_times_rows() { + assert_eq!(native_matrix_bytes(8, 2560, 10240).unwrap(), 2560 / 32 * 34 * 10240); + assert_eq!(native_matrix_bytes(14, 6144, 2560).unwrap(), 6144 / 256 * 210 * 2560); + assert!(native_matrix_bytes(8, 2570, 4).is_err()); + assert!(native_matrix_bytes(99, 2560, 4).is_err()); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa.rs b/crates/cuda-driver/src/original_verify_window_qsa.rs new file mode 100644 index 00000000..1ad81888 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_qsa.rs @@ -0,0 +1,1375 @@ +//! QSA attention-layer producers of the Verifier window (child of `original_verify`). +//! +//! These are the launch plans of the QSA branch of `Verifier::record_window` (verify.cpp, the +//! `pre` lambda), except the projections the lead records with `proj` (`native_quantize_q8_1` +//! and `native_mmvq`): indexer k projection, K norm + RoPE, K/V append into the streamed INT8 +//! pools, q/gate split, q norm + RoPE, indexer q projection + norm + RoPE, block scores and +//! top-k, device-side KV streaming resolve, batched decode attention and the output gate. The +//! tail snapshot and the indexer append stay with the retained QSA journal. +//! +//! Every plan is pure (addresses in, `Launch`es out) and drives the genuine sealed kernel with +//! the Original grid, block, shared memory, argument order and strides: +//! +//! * norm / RoPE: `qsa_decode_rms` / `qsa_decode_rope` (Original `native_qsa::norm<256>` and +//! `native_rope::apply`, compiled with `--use_fast_math` like Original); the RoPE entry +//! follows whatever argument list the committed PTX declares (ROPE-ARGS ABI 1). +//! * q/gate split: Original uses a `cudaMemcpy2DAsync` node; the plan launches the sealed +//! `qsa_split_q` copy kernel instead. Both move the identical 32-bit words +//! (`q[t][h][d] = qfull[t][h][0][d]`), so the bytes are bit-identical. +//! * gate: Original `native_qsa.cu` `gate` under `--use_fast_math`; no sealed PTX holds it with the +//! Original ABI, so `original_verify_window_qsa_gate.cu` carries it (placeholder PTX, unsealed). +//! * K/V append: `mtp_original_append` (Original `kv_append_q8_kernel`, step driven). +//! * scores / top-k / resolve / attention: `qsa_decode_scores` (Original +//! `block_scores_multi_kernel`, the Original dispatch for 1..=8 queries), `qsa_topk_ref`, +//! `leleka_qsa_resolve` + `leleka_qsa_miss_copy`, `leleka_qsa_decode_chunk` / `_merge`. +use super::kernels::{A, ArenaMap, AssetSpec, Launch}; +use super::proj::{self, plan_bf16_gemv}; +use super::window_record::Rows; +use super::{OriginalVerifyGeometry, admit, handle}; +use crate::qsa_index_ffi::{RopeAbi, rope_abi}; +use crate::{Context, DeviceBuffer, Error, Result}; + +/// `EPS` of verify.cpp (RMS epsilon of every QSA norm). +const EPS: f32 = 1e-6; +/// `QsaShapes::page_size` of the real artifact: one page = one indexer block. +const PAGE_SIZE: i32 = 4; +/// The streamed pool of the Rust target holds this many pages (baked in the sealed resolver). +const RESIDENT_PAGES: usize = 8192; +/// Original `MQ`: queries at most for the multi-query block score kernel. +const SCORE_MAX_QUERIES: usize = 8; +const ATTN_CHUNK: usize = 64; + +const DECODE_POSTOPS_ENTRIES: &[&str] = &["qsa_decode_rms", "qsa_decode_rope"]; +const SPLIT_ENTRIES: &[&str] = &["qsa_split_q"]; +const KV_APPEND_ENTRIES: &[&str] = &["mtp_original_append"]; +const SCORE_SINGLE: &str = + "_ZN6strata7kernels56_GLOBAL__N__2c1021f8_20_qsa_prompt_select_cu_6d57069d_8319block_scores_kernelEPKfS3_S3_PKilPf"; +const SELECT_ENTRIES: &[&str] = &["qsa_decode_scores", "qsa_topk_ref", SCORE_SINGLE]; +const RESOLVER_ENTRIES: &[&str] = &["leleka_qsa_resolve", "leleka_qsa_miss_copy"]; +const ATTENTION_ENTRIES: &[&str] = &["leleka_qsa_decode_chunk", "leleka_qsa_decode_merge"]; +const GATE_ENTRIES: &[&str] = &["verify_window_qsa_gate"]; + +/// Literal Original `native_qsa::norm<256>` and `native_rope::apply`, `--use_fast_math`. +pub(crate) static DECODE_POSTOPS: AssetSpec = AssetSpec { + name: "qsa_decode_postops.ptx", + ptx: include_bytes!("qsa_decode_postops.ptx"), + sha: [ + 0, 10, 130, 78, 8, 124, 86, 155, 250, 76, 186, 216, 220, 145, 159, 132, 92, 186, 42, 134, 52, 139, 191, 241, + 231, 252, 210, 6, 220, 40, 179, 169, + ], + entries: DECODE_POSTOPS_ENTRIES, + unsealed: "Original verifier asset unsealed: qsa_decode_postops.ptx (QSA RMS norm / RoPE)", +}; +/// `qsa_split_q`: the q half of `qfull` (the q/gate split copy). +pub(crate) static SPLIT: AssetSpec = AssetSpec { + name: "qsa_prompt_postops.ptx", + ptx: include_bytes!("qsa_prompt_postops.ptx"), + sha: [ + 38, 18, 51, 241, 151, 89, 65, 168, 109, 15, 250, 123, 154, 46, 38, 37, 1, 99, 221, 234, 104, 40, 116, 188, + 133, 170, 173, 141, 155, 32, 193, 160, + ], + entries: SPLIT_ENTRIES, + unsealed: "Original verifier asset unsealed: qsa_prompt_postops.ptx (QSA q/gate split)", +}; +/// Original `kv_append_q8_kernel` (precise flags). +pub(crate) static KV_APPEND: AssetSpec = AssetSpec { + name: "mtp_original_kv.ptx", + ptx: include_bytes!("mtp_original_kv.ptx"), + sha: [ + 224, 193, 255, 16, 211, 212, 188, 248, 253, 51, 105, 113, 48, 121, 178, 50, 230, 44, 219, 44, 58, 52, 95, 174, + 196, 157, 30, 102, 118, 63, 145, 31, + ], + entries: KV_APPEND_ENTRIES, + unsealed: "Original verifier asset unsealed: mtp_original_kv.ptx (INT8 KV append)", +}; +/// Original `block_scores_multi_kernel` / `block_scores_kernel` / `block_topk_kernel`. +pub(crate) static SELECT: AssetSpec = AssetSpec { + name: "qsa_prompt_select.ptx", + ptx: include_bytes!("qsa_prompt_select.ptx"), + sha: [ + 30, 53, 81, 71, 68, 33, 98, 41, 176, 207, 251, 79, 69, 210, 241, 63, 37, 203, 149, 243, 119, 163, 12, 28, 1, + 37, 67, 219, 245, 58, 28, 45, + ], + entries: SELECT_ENTRIES, + unsealed: "Original verifier asset unsealed: qsa_prompt_select.ptx (QSA block scores / top-k)", +}; +/// Original `kv_stream.cu` `resolve_kernel` + `copy_kernel`. +pub(crate) static RESOLVER: AssetSpec = AssetSpec { + name: "qsa_prompt_resolver.ptx", + ptx: include_bytes!("qsa_prompt_resolver.ptx"), + sha: [ + 171, 103, 42, 84, 167, 185, 19, 29, 133, 178, 72, 207, 86, 180, 9, 52, 38, 52, 249, 40, 11, 155, 24, 72, 40, + 80, 251, 163, 182, 107, 17, 0, + ], + entries: RESOLVER_ENTRIES, + unsealed: "Original verifier asset unsealed: qsa_prompt_resolver.ptx (KV streaming resolve)", +}; +/// Original `attn_chunk_kernel<1>` + `attn_merge_kernel` (batched form). +pub(crate) static ATTENTION: AssetSpec = AssetSpec { + name: "mtp_original_full_attention.ptx", + ptx: include_bytes!("mtp_original_full_attention.ptx"), + sha: [ + 63, 178, 53, 202, 64, 93, 36, 195, 184, 208, 236, 70, 97, 29, 157, 100, 1, 3, 183, 26, 101, 133, 153, 35, 25, + 79, 2, 240, 107, 72, 47, 108, + ], + entries: ATTENTION_ENTRIES, + unsealed: "Original verifier asset unsealed: mtp_original_full_attention.ptx (QSA decode attention)", +}; +/// Original `native_qsa.cu` `gate` under `--use_fast_math`. NEW source; the digest is all zero until Root seals it. +pub(crate) static GATE: AssetSpec = AssetSpec { + name: "original_verify_window_qsa_gate.ptx", + ptx: include_bytes!("original_verify_window_qsa_gate.ptx"), + sha: [0; 32], + entries: GATE_ENTRIES, + 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. +pub(crate) fn assets() -> Vec<&'static AssetSpec> { + vec![&proj::BF16, &DECODE_POSTOPS, &SPLIT, &KV_APPEND, &SELECT, &RESOLVER, &ATTENTION, &GATE] +} + +/// 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() +} + +macro_rules! refuse { + ($why:literal) => { + Error::InvalidDriverValue(concat!("Original verifier producer unavailable: qsa: ", $why)) + }; +} + +/// Process-wide Original configuration of the QSA branch, fixed before capture. `mode17()` is the selected +/// policy (native QSA and native RoPE on, canonical INT8 streamed KV); every other variant is refused. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OriginalVerifyQsaPolicy { + /// `native_qsa_enabled()`. + pub native_qsa: bool, + /// `native_rope_enabled()`. + pub native_rope: bool, + /// `st.kv_int8`. + pub kv_int8: bool, + /// `st.kv_q4`. + pub kv_q4: bool, + /// `st.kv_hybrid` (K8V4). + pub kv_hybrid: bool, + /// `st.kv_rot` (rotated K/V). + pub kv_rot: bool, + /// `st.without_key` (keyless). + pub without_key: bool, + /// `trace_h_` / `trace_q_h_` (keyless trace copies). + pub trace: bool, + /// `st.kv_mode == 1`: the pool is streamed (resident pages + host copy + device resolver). + pub kv_streamed: bool, + /// `STRATA_SCORES_MULTI` (default on): the multi-query block score kernel for at most 8 queries. + pub scores_multi: bool, +} +impl OriginalVerifyQsaPolicy { + pub const fn mode17() -> Self { + Self { + native_qsa: true, + native_rope: true, + kv_int8: true, + kv_q4: false, + kv_hybrid: false, + kv_rot: false, + without_key: false, + trace: false, + kv_streamed: true, + scores_multi: true, + } + } + /// Refuse every variant that has no genuine sealed owner, with its reason. + pub fn validate(&self) -> Result<()> { + if !self.native_qsa { + return Err(refuse!("native QSA is off (rms_norm_weighted / qsa_gate_apply_f32 have no sealed owner)")); + } + if !self.native_rope { + return Err(refuse!("native RoPE is off (rope_neox_apply with the session cos/sin tables has no sealed owner)")); + } + if self.kv_q4 || self.kv_hybrid || self.kv_rot { + return Err(refuse!("q4 / K8V4 / rotated KV has no sealed append, fwht or attention owner")); + } + if !self.kv_int8 { + return Err(refuse!("the FP16 KV pool has no sealed append or attention owner")); + } + if self.without_key { + return Err(refuse!("keyless QSA (keyless_route_query, V-only attention) has no sealed owner")); + } + if self.trace { + return Err(refuse!("the keyless trace copies are not part of the selected window")); + } + if !self.kv_streamed { + return Err(refuse!("only the streamed KV state (resident pool + host copy + resolver) is owned")); + } + Ok(()) + } +} + +/// The resolved `rope_scaling()` constants of the window (`OriginalVerifyRope` without its tables). +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct QsaRope { + pub theta_scale: f32, + pub freq_scale: f32, + pub corr_low: f32, + pub corr_high: f32, + pub ext_factor: f32, + pub mscale: f32, +} +impl QsaRope { + /// The Original default: identity scaling at `freq_base` 1e7 (`powf(1e7f, -2/64)`). + pub fn new(theta_scale: f32, freq_scale: f32, corr_low: f32, corr_high: f32, ext_factor: f32, mscale: f32) -> Result { + for v in [theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale] { + if !v.is_finite() { + return Err(Error::InvalidQwenShape); + } + } + if theta_scale <= 0.0 || freq_scale <= 0.0 || ext_factor < 0.0 || mscale <= 0.0 { + return Err(Error::InvalidQwenShape); + } + Ok(Self { theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale }) + } + /// From the journal's resolved Original constants. Table variants have no sealed kernel here. + pub fn from_rope(rope: &crate::OriginalVerifyRope<'_, '_>) -> Result { + if rope.positions.is_some() { + return Err(refuse!("an M-RoPE position table needs the mtab variant of native_rope (no sealed kernel)")); + } + if rope.angles.is_some() { + return Err(refuse!("STRATA_ROPE_TABLE angles need native_rope apply (no sealed kernel)")); + } + Self::new(rope.theta_scale, rope.freq_scale, rope.corr_low, rope.corr_high, rope.ext_factor, rope.magnitude) + } + /// The identity constants `(1, 0, 0, 0, 1)` the frozen RoPE PTX bakes. + pub fn is_identity(&self) -> bool { + self.freq_scale == 1.0 && self.corr_low == 0.0 && self.corr_high == 0.0 && self.ext_factor == 0.0 && self.mscale == 1.0 + } +} + +/// Fixed device addresses of one layer's streamed INT8 KV and index keys (what Original reads from `QsaState`): +/// `st.k_q/v_q/k_scale/v_scale`, `st.page_table`, `st.host`, `st.map` and `st.idx_pooled/idx_dead`. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct OriginalVerifyQsaKvBinding { + /// Resident pools `[k_q, v_q, k_scale, v_scale]`. + pub resident: [u64; 4], + /// `st.page_table`. + pub table: u64, + /// Host (pinned, device mapped) copy `[k_q, v_q, k_scale, v_scale]` = `st.host`. + pub host: [u64; 4], + /// `st.map`: `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`. + pub resolver: [u64; 7], + /// `st.idx_pooled` and its byte length. + pub pooled: u64, + pub pooled_bytes: usize, + /// `st.idx_dead` and its byte length. + pub dead: u64, + pub dead_bytes: usize, +} +impl OriginalVerifyQsaKvBinding { + /// Read the fixed addresses of QSA layer `layer` from the retained journal (nothing is changed). + pub(crate) fn from_journal(qsa: &crate::OriginalVerifyQsaJournal<'_, '_>, layer: usize) -> Result { + let a = qsa.window_addresses(layer)?; + Ok(Self { + resident: a.resident, + table: a.table, + host: a.host, + resolver: a.resolver, + pooled: a.pooled, + pooled_bytes: a.pooled_bytes, + dead: a.dead, + dead_bytes: a.dead_bytes, + }) + } + /// Byte-exact structural admission against the window geometry. + pub fn validate(&self, g: &OriginalVerifyGeometry) -> Result<()> { + let all = self.resident.iter().chain(&self.host).chain(&self.resolver).chain([&self.pooled, &self.dead]); + if all.clone().any(|&a| a == 0 || a % 16 != 0) { + return Err(Error::InvalidQwenShape); + } + if self.table != self.resolver[0] { + return Err(Error::InvalidQwenShape); + } + // pairwise distinct owners (the page table is the resolver's first word) + let mut seen: Vec = all.copied().collect(); + seen.sort_unstable(); + if seen.windows(2).any(|w| w[0] == w[1]) { + return Err(Error::OutputAliasesInput); + } + // The serving index image holds one pooled key row per completed block plus the partial one + // (`pooled_rows() = max_cells / index_block + 1`); the scratch arrays use two more rows + // (`max_blocks`) but they live in the arena, not in the index image. + let pooled_need = (g.max_cells / g.index_block + 1) * g.index_dim * 4; + if self.pooled_bytes < pooled_need || self.dead_bytes != g.index_dim * 4 { + return Err(Error::ShapeMismatch { expected: pooled_need, actual: self.pooled_bytes }); + } + Ok(()) + } +} + +/// The weights of one QSA layer that the window producers read directly. +pub struct OriginalVerifyQsaLayerWeights<'a, 'ctx> { + /// `attn_q_norm.weight`, F32 `[head_dim]`. + pub attn_q_norm: &'a DeviceBuffer<'ctx>, + /// `attn_k_norm.weight`, F32 `[head_dim]`. + pub attn_k_norm: &'a DeviceBuffer<'ctx>, + /// `indexer.q_norm.weight`, F32 `[index_dim]`. + pub index_q_norm: &'a DeviceBuffer<'ctx>, + /// `indexer.k_proj.weight`, BF16 `[index_dim][n_embd]`. + pub index_k_proj: &'a DeviceBuffer<'ctx>, + /// `indexer.q_proj.weight`, BF16 `[index_heads * index_dim][n_embd]`. + pub index_q_proj: &'a DeviceBuffer<'ctx>, +} +/// Device addresses of one layer's weights, after byte-exact admission. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct QsaWeightAddrs { + pub q_norm: u64, + pub k_norm: u64, + pub index_q_norm: u64, + pub index_k_proj: u64, + pub index_q_proj: u64, +} +/// The 12 QSA layers' direct weight operands. The index key norm gamma and the index images live in +/// `OriginalVerifyQsaJournal`; the K/V and quantized projections are `proj`/mmvq operands. +pub struct OriginalVerifyQsaBinding<'a, 'ctx> { + context: &'ctx Context<'ctx>, + geometry: OriginalVerifyGeometry, + layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12], +} +impl<'a, 'ctx> OriginalVerifyQsaBinding<'a, 'ctx> { + pub fn new( + context: &'ctx Context<'ctx>, + geometry: OriginalVerifyGeometry, + layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12], + ) -> Result { + geometry.validate()?; + let this = Self { context, geometry, layers }; + this.validate_context(context)?; + Ok(this) + } + fn sizes(g: &OriginalVerifyGeometry) -> [usize; 5] { + [g.head_dim * 4, g.head_dim * 4, g.index_dim * 4, g.index_dim * g.n * 2, g.index_heads * g.index_dim * g.n * 2] + } + /// Context equality, exact byte sizes and pairwise disjoint weights for all 12 layers. + pub fn validate_context(&self, context: &Context<'_>) -> Result<()> { + if !std::ptr::eq(context, self.context) { + return Err(Error::ContextMismatch); + } + let sizes = Self::sizes(&self.geometry); + let mut spans = Vec::with_capacity(60); + for w in &self.layers { + let bufs = [w.attn_q_norm, w.attn_k_norm, w.index_q_norm, w.index_k_proj, w.index_q_proj]; + for (b, bytes) in bufs.into_iter().zip(sizes) { + admit(context, b, bytes)?; + spans.push((handle(b)?, bytes)); + } + } + for (i, (a, an)) in spans.iter().enumerate() { + if spans[i + 1..].iter().any(|(b, bn)| a.overlaps(*an, *b, *bn)) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + /// The admitted addresses of QSA layer `q` (0..12). + pub fn addrs(&self, q: usize) -> Result { + let w = self.layers.get(q).ok_or(Error::InvalidQwenShape)?; + let s = Self::sizes(&self.geometry); + Ok(QsaWeightAddrs { + q_norm: admit(self.context, w.attn_q_norm, s[0])?, + k_norm: admit(self.context, w.attn_k_norm, s[1])?, + index_q_norm: admit(self.context, w.index_q_norm, s[2])?, + index_k_proj: admit(self.context, w.index_k_proj, s[3])?, + index_q_proj: admit(self.context, w.index_q_proj, s[4])?, + }) + } +} + +fn max_blocks(g: &OriginalVerifyGeometry) -> usize { + g.max_cells / g.index_block + 2 +} +fn scratch_floats(g: &OriginalVerifyGeometry) -> usize { + g.selection.div_ceil(ATTN_CHUNK) * g.heads * (g.head_dim + 2) + 64 +} +fn declared_i32(v: usize) -> Result { + i32::try_from(v).map_err(|_| Error::InvalidSize) +} +fn grid_u32(v: usize) -> Result { + u32::try_from(v).map_err(|_| Error::InvalidSize) +} + +/// Everything one window's QSA plans need: arena, geometry, policy and RoPE constants. +pub struct QsaWindow<'a> { + arena: &'a dyn ArenaMap, + g: OriginalVerifyGeometry, + policy: OriginalVerifyQsaPolicy, + rope: QsaRope, +} +/// One layer's operands (weights and fixed KV/index addresses). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct QsaLayerAddrs { + pub weights: QsaWeightAddrs, + pub kv: OriginalVerifyQsaKvBinding, +} + +struct Span { + tb: usize, + n: usize, +} + +impl<'a> QsaWindow<'a> { + pub fn new( + arena: &'a dyn ArenaMap, + geometry: OriginalVerifyGeometry, + policy: OriginalVerifyQsaPolicy, + rope: QsaRope, + ) -> Result { + policy.validate()?; + geometry.validate()?; + if geometry.index_block != PAGE_SIZE as usize || geometry.selection != 2051 { + return Err(Error::InvalidQwenShape); + } + Ok(Self { arena, g: geometry, policy, rope }) + } + fn span(&self, name: &str, offset: usize, bytes: usize) -> Result { + self.arena.span(name, offset, bytes) + } + fn rows(&self, q: usize, rows: Rows, batched: Option) -> Result { + if q >= 12 || rows.begin >= rows.end || rows.end > self.g.max_t { + return Err(Error::InvalidQwenShape); + } + // the recorder passes `dec_batch && n > 1`; a batched launch of one row cannot exist + if batched == Some(true) && rows.len() < 2 { + return Err(Error::InvalidQwenShape); + } + Ok(Span { tb: rows.begin, n: rows.len() }) + } + fn rms(&self, data: u64, gamma: u64, rows: usize, cols: usize) -> Result { + Launch::new( + &DECODE_POSTOPS, + "qsa_decode_rms", + [grid_u32(rows)?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(data), A::P(gamma), A::P(data), A::I32(declared_i32(cols)?), A::F32(EPS)], + ) + } + fn rope_with(&self, abi: RopeAbi, data: u64, rows: usize, width: usize, positions: u64) -> Result { + if positions % 4 != 0 || rows == 0 || rows > 65535 || (width != 128 && width != 256) { + return Err(Error::InvalidQwenShape); + } + let r = &self.rope; + let mut args = vec![ + A::P(data), + A::P(data), + A::I32(declared_i32(rows)?), + A::I32(declared_i32(width)?), + A::F32(r.theta_scale), + A::P(positions), + ]; + match abi { + RopeAbi::Frozen if !r.is_identity() => { + return Err(refuse!("scaled RoPE needs the regenerated qsa_decode_postops.ptx (ROPE-ARGS ABI 1)")); + } + RopeAbi::Frozen => {} + RopeAbi::Extended => { + args.extend([A::F32(r.freq_scale), A::F32(r.corr_low), A::F32(r.corr_high), A::F32(r.ext_factor), A::F32(r.mscale)]) + } + } + // native_rope_apply: dim3 grid((head_dim / 2 + 127) / 128, rows), 128 threads + Launch::new(&DECODE_POSTOPS, "qsa_decode_rope", [grid_u32((width / 2).div_ceil(128))?, grid_u32(rows)?, 1], [128, 1, 1], 0, args) + } + fn rope(&self, data: u64, rows: usize, width: usize, positions: u64) -> Result { + self.rope_with(rope_abi()?, data, rows, width, positions) + } + /// `norm_rope` of verify.cpp: native RMS norm (in place) then native RoPE (in place). + fn norm_rope(&self, data: u64, gamma: u64, rows: usize, cols: usize, positions: u64) -> Result<[Launch; 2]> { + Ok([self.rms(data, gamma, rows, cols)?, self.rope(data, rows, cols, positions)?]) + } + + /// `qsa_index_k`: indexer k projection, `idx_raw[q][row] = mixed[row] * indexer.k_proj`. + pub fn index_k(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (n_in, id) = (g.n, g.index_dim); + let gemv = |from: usize, count: usize| -> Result { + let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; + let y = self.span("idx_raw_L", (q * g.max_t + from) * id * 4, count * id * 4)?; + plan_bf16_gemv(x, n_in, w.weights.index_k_proj, y, id, n_in, id, count) + }; + if batched { + return Ok(vec![gemv(s.tb, s.n)?]); + } + (s.tb..s.tb + s.n).map(|t| gemv(t, 1)).collect() + } + + /// `qsa_k_norm_rope`: K per-head RMS norm with `attn_k_norm.weight`, then RoPE with the K row positions. + pub fn k_norm_rope(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nkv, hd) = (g.kv_heads, g.head_dim); + let mut out = Vec::new(); + if batched { + let data = self.span("kcur", s.tb * nkv * hd * 4, s.n * nkv * hd * 4)?; + // pos_k = pos_ + MT * NH; rows [t][NKV] + let pos = self.span("pos", (g.max_t * g.heads + s.tb * nkv) * 4, s.n * nkv * 4)?; + out.extend(self.norm_rope(data, w.weights.k_norm, s.n * nkv, hd, pos)?); + } else { + for t in s.tb..s.tb + s.n { + let data = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; + let pos = self.span("pos", t * g.heads * 4, nkv * 4)?; + out.extend(self.norm_rope(data, w.weights.k_norm, nkv, hd, pos)?); + } + } + Ok(out) + } + + /// `qsa_kv_append`: one `kv_append_q8_step` per row into the resident pool (if the page is resident) + /// and the host copy. + pub fn kv_append(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + let (nkv, hd) = (g.kv_heads, g.head_dim); + let kv = &w.kv; + kv.validate(g)?; + let mut out = Vec::with_capacity(s.n); + for t in s.tb..s.tb + s.n { + let step = self.span("step", t * 16, 16)?; + let k = self.span("kcur", t * nkv * hd * 4, nkv * hd * 4)?; + let v = self.span("vcur", t * nkv * hd * 4, nkv * hd * 4)?; + out.push(Launch::new( + &KV_APPEND, + "mtp_original_append", + [grid_u32(nkv)?, grid_u32(hd / 64)?, 2], + [64, 1, 1], + 0, + vec![ + A::P(kv.resident[0]), + A::P(kv.resident[1]), + A::P(kv.resident[2]), + A::P(kv.resident[3]), + A::P(kv.table), + A::P(step), + A::P(k), + A::P(v), + A::I32(declared_i32(nkv)?), + A::I32(declared_i32(hd)?), + A::I32(PAGE_SIZE), + A::P(kv.host[0]), + A::P(kv.host[1]), + A::P(kv.host[2]), + A::P(kv.host[3]), + ], + )?); + } + Ok(out) + } + + /// `qsa_q_path`: q/gate split, q RMS norm with `attn_q_norm.weight`, RoPE with the query positions. + pub fn q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nh, hd) = (g.heads, g.head_dim); + let split = |from: usize, count: usize| -> Result { + let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; + let qcur = self.span("qcur", from * nh * hd * 4, count * nh * hd * 4)?; + // `cudaMemcpy2DAsync(qcur, HD*4, qfull, HD*2*4, HD*4, count*NH)` as the sealed word copy + Launch::new(&SPLIT, "qsa_split_q", [grid_u32(count * nh)?, 1, 1], [256, 1, 1], 0, vec![A::P(qfull), A::P(qcur), A::I64(count as i64)]) + }; + let mut out = Vec::new(); + if batched { + out.push(split(s.tb, s.n)?); + let data = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + let pos = self.span("pos", s.tb * nh * 4, s.n * nh * 4)?; + out.extend(self.norm_rope(data, w.weights.q_norm, s.n * nh, hd, pos)?); + } else { + for t in s.tb..s.tb + s.n { + out.push(split(t, 1)?); + let data = self.span("qcur", t * nh * hd * 4, nh * hd * 4)?; + let pos = self.span("pos", t * nh * 4, nh * 4)?; + out.extend(self.norm_rope(data, w.weights.q_norm, nh, hd, pos)?); + } + } + Ok(out) + } + + /// `qsa_index_q_path`: indexer query projection, RMS norm with `indexer.q_norm.weight`, RoPE. + pub fn index_q_path(&self, q: usize, w: &QsaLayerAddrs, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (n_in, iq, id, nh) = (g.n, g.index_heads, g.index_dim, g.heads); + let gemv = |from: usize, count: usize| -> Result { + let x = self.span("mixed", from * n_in * 4, count * n_in * 4)?; + let y = self.span("qidx", from * iq * id * 4, count * iq * id * 4)?; + plan_bf16_gemv(x, n_in, w.weights.index_q_proj, y, iq * id, n_in, iq * id, count) + }; + let mut out = Vec::new(); + if batched { + out.push(gemv(s.tb, s.n)?); + let data = self.span("qidx", s.tb * iq * id * 4, s.n * iq * id * 4)?; + // pos_i = pos_ + MT * (NH + NKV); rows [t][IQ] + let pos = self.span("pos", (g.max_t * (nh + g.kv_heads) + s.tb * iq) * 4, s.n * iq * 4)?; + out.extend(self.norm_rope(data, w.weights.index_q_norm, s.n * iq, id, pos)?); + } else { + for t in s.tb..s.tb + s.n { + out.push(gemv(t, 1)?); + let data = self.span("qidx", t * iq * id * 4, iq * id * 4)?; + let pos = self.span("pos", t * nh * 4, iq * 4)?; + out.extend(self.norm_rope(data, w.weights.index_q_norm, iq, id, pos)?); + } + } + Ok(out) + } + + /// `qsa_block_scores_topk`: `qsa_block_scores` then `qsa_block_topk` over the window group's queries. + pub fn block_scores_topk(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + let (mb, cap) = (max_blocks(g), g.selection); + let qidx = self.span("qidx", s.tb * g.index_heads * g.index_dim * 4, s.n * g.index_heads * g.index_dim * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let scores = self.span("scores", s.tb * mb * 4, s.n * mb * 4)?; + let sel = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; + let scored = if self.policy.scores_multi && s.n <= SCORE_MAX_QUERIES { + // block_scores_multi_kernel<<<256, SCORE_WARPS * 32>>> + Launch::new( + &SELECT, + "qsa_decode_scores", + [256, 1, 1], + [256, 1, 1], + 0, + vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I32(s.n as i32), A::I64(mb as i64), A::P(scores)], + )? + } else { + // block_scores_kernel<<<(ceil(max_blocks / 8), nq), 256>>> + Launch::new( + &SELECT, + SCORE_SINGLE, + [grid_u32(mb.div_ceil(8))?, grid_u32(s.n)?, 1], + [256, 1, 1], + 0, + vec![A::P(w.kv.pooled), A::P(w.kv.dead), A::P(qidx), A::P(steps), A::I64(mb as i64), A::P(scores)], + )? + }; + // 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)], + )?; + Ok(vec![scored, topk]) + } + + /// `qsa_kv_resolve`: the selections' blocks resident, device side (`kv_stream_resolve`). + pub fn kv_resolve(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + // each query selects whole 4-cell blocks plus a partial one; all of them must fit the miss arrays + if s.n * (g.selection.div_ceil(PAGE_SIZE as usize) + 1) > RESIDENT_PAGES { + return Err(refuse!("the window's selections can miss more blocks than the resolver has slots")); + } + let ids = self.span("sel", s.tb * g.selection * 4, s.n * g.selection * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let r = &w.kv.resolver; + let mut resolve: Vec = r.iter().map(|&a| A::P(a)).collect(); + resolve.extend([A::P(ids), A::P(steps), A::I32(s.n as i32)]); + let mut copy = vec![A::P(r[4]), A::P(r[5]), A::P(r[6])]; + copy.extend(w.kv.host.iter().chain(&w.kv.resident).map(|&a| A::P(a))); + Ok(vec![ + Launch::new(&RESOLVER, "leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1], 0, resolve)?, + Launch::new(&RESOLVER, "leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1], 0, copy)?, + ]) + } + + /// `qsa_decode_attention`: `qsa_decode_attn_batch` (chunk grid `[chunks, n_head_kv, n]`, merge grid `[n_head, n]`). + pub fn decode_attention(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result> { + let s = self.rows(q, rows, None)?; + let g = &self.g; + w.kv.validate(g)?; + let (nh, nkv, hd, cap) = (g.heads, g.kv_heads, g.head_dim, g.selection); + let chunks = cap.div_ceil(ATTN_CHUNK); + let stride = scratch_floats(g); + let qcur = self.span("qcur", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + let ids = self.span("sel", s.tb * cap * 4, s.n * cap * 4)?; + let steps = self.span("step", s.tb * 16, s.n * 16)?; + let acc = self.span("attn_scratch", s.tb * stride * 4, s.n * stride * 4)?; + let part_m = acc + (chunks * nh * hd * 4) as u64; + let part_l = part_m + (chunks * nh * 4) as u64; + let attn = self.span("attn", s.tb * nh * hd * 4, s.n * nh * hd * 4)?; + // 1.0f / sqrtf(256.0f) + let scale = 1.0f32 / (hd as f32).sqrt(); + let r = &w.kv.resident; + let chunk = Launch::new( + &ATTENTION, + "leleka_qsa_decode_chunk", + [grid_u32(chunks)?, grid_u32(nkv)?, grid_u32(s.n)?], + [256, 1, 1], + 0, + vec![ + A::P(qcur), + A::P(r[0]), + A::P(r[1]), + A::P(r[2]), + A::P(r[3]), + A::P(w.kv.table), + A::P(ids), + A::P(steps), + A::I32(declared_i32(nkv)?), + A::I32(PAGE_SIZE), + A::F32(scale), + A::P(acc), + A::P(part_m), + A::P(part_l), + A::I32(declared_i32(chunks)?), + A::I32(declared_i32(cap)?), + A::I64(stride as i64), + ], + )?; + let merge = Launch::new( + &ATTENTION, + "leleka_qsa_decode_merge", + [grid_u32(nh)?, grid_u32(s.n)?, 1], + [256, 1, 1], + 0, + vec![A::P(acc), A::P(part_m), A::P(part_l), A::I32(declared_i32(chunks)?), A::P(attn), A::I64(stride as i64)], + )?; + Ok(vec![chunk, merge]) + } + + /// `qsa_gate`: `native_qsa_gate_apply(attn, qfull, attn32, heads, HD)`; batched = one launch over `n * NH` heads. + pub fn gate(&self, q: usize, rows: Rows, batched: bool) -> Result> { + let s = self.rows(q, rows, Some(batched))?; + let g = &self.g; + let (nh, hd) = (g.heads, g.head_dim); + let one = |from: usize, count: usize| -> Result { + let heads = count * nh; + let attn = self.span("attn", from * nh * hd * 4, count * nh * hd * 4)?; + let qfull = self.span("qfull", from * nh * 2 * hd * 4, count * nh * 2 * hd * 4)?; + let out = self.span("attn32", from * nh * hd * 4, count * nh * hd * 4)?; + Launch::new( + &GATE, + "verify_window_qsa_gate", + [grid_u32((heads * hd).div_ceil(256))?, 1, 1], + [256, 1, 1], + 0, + vec![A::P(attn), A::P(qfull), A::P(out), A::I32(declared_i32(heads)?), A::I32(declared_i32(hd)?)], + ) + }; + if batched { + return Ok(vec![one(s.tb, s.n)?]); + } + (s.tb..s.tb + s.n).map(|t| one(t, 1)).collect() + } +} + +#[cfg(test)] +mod tests { + use super::super::kernels::{LayoutMap, test_geometry}; + use super::*; + + const BASE: u64 = 0x7000_0000_0000; + const KV: OriginalVerifyQsaKvBinding = OriginalVerifyQsaKvBinding { + resident: [0x1_0000_0000, 0x1_1000_0000, 0x1_2000_0000, 0x1_2100_0000], + table: 0x1_3000_0000, + host: [0x2_0000_0000, 0x2_1000_0000, 0x2_2000_0000, 0x2_2100_0000], + resolver: [0x1_3000_0000, 0x1_3100_0000, 0x1_3200_0000, 0x1_3300_0000, 0x1_3400_0000, 0x1_3500_0000, 0x1_3600_0000], + pooled: 0x1_4000_0000, + pooled_bytes: 1026 * 512, + dead: 0x1_4100_0000, + dead_bytes: 512, + }; + const W: QsaWeightAddrs = QsaWeightAddrs { + q_norm: 0x3_0000_0000, + k_norm: 0x3_0001_0000, + index_q_norm: 0x3_0002_0000, + index_k_proj: 0x3_1000_0000, + index_q_proj: 0x3_2000_0000, + }; + fn layer() -> QsaLayerAddrs { + QsaLayerAddrs { weights: W, kv: KV } + } + fn identity() -> QsaRope { + QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0).unwrap() + } + fn rows(begin: usize, end: usize) -> Rows { + Rows { begin, end, group: if begin == 0 { 0 } else { 1 } } + } + fn setup() -> (LayoutMap, OriginalVerifyGeometry) { + let g = test_geometry(); + (LayoutMap::new(BASE, g), g) + } + fn at(m: &LayoutMap, name: &str, offset: usize) -> u64 { + BASE + m.layout.span(name).unwrap().offset as u64 + offset as u64 + } + fn window(m: &LayoutMap, g: OriginalVerifyGeometry) -> QsaWindow<'_> { + QsaWindow::new(m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap() + } + + /// `.param` count the PTX declares for `entry`. + fn declared_params(ptx: &[u8], entry: &str) -> usize { + let text = String::from_utf8_lossy(ptx); + let head = format!(".entry {entry}("); + let at = text.find(&head).unwrap_or_else(|| panic!("{entry} not declared")); + let rest = &text[at..]; + let end = rest.find("\n)\n").expect("entry parameter list end"); + rest[..end].matches(".param").count() + } + fn assert_abi(l: &Launch) { + if l.asset.sha == [0; 32] { + return; + } + assert_eq!(declared_params(l.asset.ptx, l.entry), l.args.len(), "{}", l.label()); + } + + #[test] + fn sealed_assets_are_pinned_and_export_every_named_entry() { + for spec in assets() { + if std::ptr::eq(spec, &GATE) { + continue; + } + spec.sealed().unwrap_or_else(|e| panic!("{}: {e:?}", spec.name)); + let text = String::from_utf8_lossy(spec.ptx); + for e in spec.entries { + assert!(text.contains(&format!(".entry {e}(")), "{} lacks {e}", spec.name); + } + } + } + + #[test] + fn the_new_gate_asset_is_an_unsealed_placeholder_with_a_matching_source() { + assert_eq!(GATE.sealed().unwrap_err(), Error::InvalidDriverValue(GATE.unsealed)); + assert!(GATE.ptx.windows(8).any(|w| w == b"UNSEALED")); + assert_eq!(GATE.ptx.iter().filter(|&&b| b == 0).count(), 1); + assert_eq!(GATE.sha, [0; 32]); + let source = include_str!("original_verify_window_qsa_gate.cu"); + for e in GATE.entries { + assert!(source.contains(&format!("extern \"C\" __global__ void {e}(")), "{e}"); + } + // the body is the Original `gate`: second half of each [head][2][head_dim] row + assert!(source.contains("q_full[head * 2 * head_dim + head_dim + channel]")); + assert!(source.contains("1.0f / (1.0f + expf(-raw))")); + assert!(include_str!("../../../docs/cuda-seal-plan-additions-window.json").contains("--use_fast_math")); + } + + #[test] + fn asset_set_has_distinct_names_and_the_bf16_projection_module() { + let a = assets(); + let mut names: Vec<&str> = a.iter().map(|s| s.name).collect(); + names.sort_unstable(); + 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()); + } + + #[test] + fn policy_refuses_every_variant_without_a_sealed_owner() { + assert!(OriginalVerifyQsaPolicy::mode17().validate().is_ok()); + let base = OriginalVerifyQsaPolicy::mode17(); + let variants: [fn(&mut OriginalVerifyQsaPolicy); 8] = [ + |p| p.native_qsa = false, + |p| p.native_rope = false, + |p| p.kv_q4 = true, + |p| p.kv_hybrid = true, + |p| p.kv_rot = true, + |p| p.without_key = true, + |p| p.trace = true, + |p| p.kv_streamed = false, + ]; + let mut seen = std::collections::BTreeSet::new(); + for f in variants { + let mut p = base; + f(&mut p); + match p.validate().unwrap_err() { + Error::InvalidDriverValue(m) => { + assert!(m.starts_with("Original verifier producer unavailable: qsa: "), "{m}"); + seen.insert(m); + } + e => panic!("{e:?}"), + } + } + assert!(seen.len() >= 6, "reasons are specific: {seen:?}"); + let mut fp16 = base; + fp16.kv_int8 = false; + assert!(fp16.validate().is_err()); + } + + #[test] + fn rope_constants_refuse_tables_and_non_finite_values() { + assert!(QsaRope::new(f32::NAN, 1.0, 0.0, 0.0, 0.0, 1.0).is_err()); + assert!(QsaRope::new(0.7, 0.0, 0.0, 0.0, 0.0, 1.0).is_err()); + assert!(QsaRope::new(0.7, 1.0, 0.0, 0.0, -1.0, 1.0).is_err()); + assert!(identity().is_identity()); + assert!(!QsaRope::new(0.7, 0.5, 0.0, 0.0, 1.0, 1.1).unwrap().is_identity()); + } + + #[test] + fn index_k_is_one_multi_gemv_when_batched_and_a_single_gemv_per_token_otherwise() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.index_k(2, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 1); + let nt = if n <= 4 { "ELi4EE" } else { "ELi8EE" }; + assert!(l[0].entry.contains("ILi256") && l[0].entry.contains(nt), "{}", l[0].entry); + assert_eq!((l[0].grid, l[0].block), ([128, 1, 1], [256, 1, 1])); + // x = mixed, ldx = 2560, w, y = idx_raw layer 2 row 0, ldy = 128, n_in = 2560, n_tok + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 0)), + A::I64(2560), + A::P(W.index_k_proj), + A::P(at(&m, "idx_raw_L", 2 * 8 * 128 * 4)), + A::I64(128), + A::I32(2560), + A::I32(n as i32) + ] + ); + assert_abi(&l[0]); + } + // second group rows 3..5 of an 8 row bank: x at row 3, y at (layer 11 * 8 + 3) * 128 floats + let l = w.index_k(11, &layer(), rows(3, 5), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "mixed", 3 * 2560 * 4))); + assert_eq!(l[0].args[3], A::P(at(&m, "idx_raw_L", (11 * 8 + 3) * 128 * 4))); + // per token + let l = w.index_k(0, &layer(), rows(0, 3), false).unwrap(); + assert_eq!(l.len(), 3); + for (t, launch) in l.iter().enumerate() { + assert_eq!(launch.entry, "mtp_full_mmvf256"); + assert_eq!( + launch.args, + vec![A::P(at(&m, "mixed", t * 2560 * 4)), A::P(W.index_k_proj), A::P(at(&m, "idx_raw_L", t * 128 * 4)), A::I32(2560)] + ); + assert_abi(launch); + } + // a lone row is never batched; layer and row bounds + assert_eq!(w.index_k(0, &layer(), rows(0, 1), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(w.index_k(12, &layer(), rows(0, 2), true).unwrap_err(), Error::InvalidQwenShape); + assert_eq!(w.index_k(0, &layer(), rows(0, 9), false).unwrap_err(), Error::InvalidQwenShape); + } + + fn rope_param_count() -> usize { + match rope_abi().unwrap() { + RopeAbi::Frozen => 6, + RopeAbi::Extended => 11, + } + } + + #[test] + fn k_norm_rope_batched_is_one_norm_and_one_rope_over_n_times_two_head_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.k_norm_rope(1, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 2); + let data = at(&m, "kcur", 0); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_rms", [2 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!(l[0].args, vec![A::P(data), A::P(W.k_norm), A::P(data), A::I32(256), A::F32(1e-6)]); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_decode_rope", [1, 2 * n as u32, 1], [128, 1, 1])); + // pos_k = pos + MT * NH = 8 * 24 ints + assert_eq!(l[1].args[5], A::P(at(&m, "pos", 8 * 24 * 4))); + assert_eq!(l[1].args[..5], [A::P(data), A::P(data), A::I32(2 * n as i32), A::I32(256), A::F32(0.7498942)]); + assert_eq!(l[1].args.len(), rope_param_count()); + l.iter().for_each(assert_abi); + } + // second group: rows 5..8 start at token 5, 2 K rows per token + let l = w.k_norm_rope(0, &layer(), rows(5, 8), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 5 * 2 * 256 * 4))); + assert_eq!(l[1].args[5], A::P(at(&m, "pos", (8 * 24 + 5 * 2) * 4))); + assert_eq!(l[0].grid, [6, 1, 1]); + } + + #[test] + fn k_norm_rope_per_token_uses_the_pos_rows_of_the_query_layout() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.k_norm_rope(0, &layer(), rows(2, 4), false).unwrap(); + assert_eq!(l.len(), 4); + // token 2 then 3: NKV rows each, positions pos_ + t * NH + assert_eq!(l[0].args[0], A::P(at(&m, "kcur", 2 * 512 * 4))); + assert_eq!(l[0].grid, [2, 1, 1]); + assert_eq!(l[1].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); + assert_eq!(l[3].args[5], A::P(at(&m, "pos", 3 * 24 * 4))); + assert_eq!(l[3].grid, [1, 2, 1]); + } + + #[test] + fn the_rope_entry_follows_the_declared_abi_and_refuses_scaling_on_frozen_ptx() { + let (m, g) = setup(); + let scaled = QsaRope::new(0.7498942, 0.5, 1.0, 20.0, 1.0, 1.1).unwrap(); + let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), scaled).unwrap(); + let frozen = w.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2000).unwrap_err(); + assert!(matches!(frozen, Error::InvalidDriverValue(msg) if msg.contains("ROPE-ARGS ABI 1"))); + let ext = w.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap(); + assert_eq!(ext.args.len(), 11); + assert_eq!(ext.args[6..], [A::F32(0.5), A::F32(1.0), A::F32(20.0), A::F32(1.0), A::F32(1.1)]); + let id = window(&m, g); + let fro = id.rope_with(RopeAbi::Frozen, 0x1000, 128, 128, 0x2000).unwrap(); + assert_eq!(fro.args.len(), 6); + assert_eq!(fro.grid, [1, 128, 1]); + assert_eq!(id.rope_with(RopeAbi::Extended, 0x1000, 4, 256, 0x2000).unwrap().args.len(), 11); + // positions are 4-byte aligned, widths 128/256 only + assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 256, 0x2002).is_err()); + assert!(id.rope_with(RopeAbi::Frozen, 0x1000, 4, 64, 0x2000).is_err()); + } + + #[test] + fn kv_append_is_one_step_driven_launch_per_row_with_the_host_mirror() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.kv_append(4, &layer(), rows(1, 4)).unwrap(); + assert_eq!(l.len(), 3); + for (i, launch) in l.iter().enumerate() { + let t = 1 + i; + assert_eq!((launch.entry, launch.grid, launch.block, launch.shared), ("mtp_original_append", [2, 4, 2], [64, 1, 1], 0)); + assert_eq!( + launch.args, + vec![ + A::P(KV.resident[0]), + A::P(KV.resident[1]), + A::P(KV.resident[2]), + A::P(KV.resident[3]), + A::P(KV.table), + A::P(at(&m, "step", t * 16)), + A::P(at(&m, "kcur", t * 512 * 4)), + A::P(at(&m, "vcur", t * 512 * 4)), + A::I32(2), + A::I32(256), + A::I32(4), + A::P(KV.host[0]), + A::P(KV.host[1]), + A::P(KV.host[2]), + A::P(KV.host[3]), + ] + ); + assert_abi(launch); + } + // the binding is validated at capture: aliased owners and short index keys refuse + let mut bad = layer(); + bad.kv.host[1] = bad.kv.resident[0]; + assert_eq!(w.kv_append(0, &bad, rows(0, 1)).unwrap_err(), Error::OutputAliasesInput); + let mut short = layer(); + short.kv.pooled_bytes = 512; + assert!(w.kv_append(0, &short, rows(0, 1)).is_err()); + // the serving image is exactly (max_cells / index_block + 1) rows: it must be admitted + let mut serving = layer(); + serving.kv.pooled_bytes = (4096 / 4 + 1) * 512; + assert!(w.kv_append(0, &serving, rows(0, 1)).is_ok()); + serving.kv.pooled_bytes -= 1; + assert!(w.kv_append(0, &serving, rows(0, 1)).is_err()); + let mut unaligned = layer(); + unaligned.kv.table += 4; + assert!(w.kv_append(0, &unaligned, rows(0, 1)).is_err()); + } + + #[test] + fn q_path_batched_is_split_norm_rope_over_n_times_24_head_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.q_path(0, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 3); + // cudaMemcpy2DAsync width HD*4 x n*NH rows, src pitch HD*2*4: T=n tokens of 24 heads + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_split_q", [24 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!(l[0].args, vec![A::P(at(&m, "qfull", 0)), A::P(at(&m, "qcur", 0)), A::I64(n as i64)]); + assert_eq!(l[1].grid, [24 * n as u32, 1, 1]); + assert_eq!(l[1].args[1], A::P(W.q_norm)); + assert_eq!(l[2].grid, [1, 24 * n as u32, 1]); + // positions pos_ + tb * NH + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 0))); + l.iter().for_each(assert_abi); + } + let l = w.q_path(0, &layer(), rows(4, 8), true).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "qfull", 4 * 24 * 512 * 4))); + assert_eq!(l[0].args[1], A::P(at(&m, "qcur", 4 * 24 * 256 * 4))); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 4 * 24 * 4))); + } + + #[test] + fn q_path_per_token_splits_and_rotates_each_token_in_order() { + let (m, g) = setup(); + let w = window(&m, g); + let l = w.q_path(7, &layer(), rows(0, 2), false).unwrap(); + assert_eq!(l.len(), 6); + let names: Vec<&str> = l.iter().map(|x| x.entry).collect(); + assert_eq!(names, ["qsa_split_q", "qsa_decode_rms", "qsa_decode_rope", "qsa_split_q", "qsa_decode_rms", "qsa_decode_rope"]); + assert_eq!(l[0].grid, [24, 1, 1]); + assert_eq!(l[3].args, vec![A::P(at(&m, "qfull", 24 * 512 * 4)), A::P(at(&m, "qcur", 24 * 256 * 4)), A::I64(1)]); + assert_eq!(l[5].args[5], A::P(at(&m, "pos", 24 * 4))); + assert_eq!(l[4].grid, [24, 1, 1]); + } + + #[test] + fn index_q_path_projects_512_outputs_then_norms_and_rotates_index_rows() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.index_q_path(3, &layer(), rows(0, n), true).unwrap(); + assert_eq!(l.len(), 3); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "mixed", 0)), + A::I64(2560), + A::P(W.index_q_proj), + A::P(at(&m, "qidx", 0)), + A::I64(512), + A::I32(2560), + A::I32(n as i32) + ] + ); + assert_eq!(l[0].grid, [512, 1, 1]); + assert_eq!((l[1].grid, l[1].args[1].clone(), l[1].args[3].clone()), ([4 * n as u32, 1, 1], A::P(W.index_q_norm), A::I32(128))); + assert_eq!(l[2].grid, [1, 4 * n as u32, 1]); + assert_eq!(l[2].args[3], A::I32(128)); + // pos_i = pos + MT * (NH + NKV) + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 8 * 26 * 4))); + l.iter().for_each(assert_abi); + } + let l = w.index_q_path(0, &layer(), rows(6, 8), true).unwrap(); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", (8 * 26 + 6 * 4) * 4))); + // per token: single gemv (ldy == n_out), rows IQ, positions pos_ + t * NH + let l = w.index_q_path(0, &layer(), rows(1, 3), false).unwrap(); + assert_eq!(l.len(), 6); + assert_eq!(l[0].entry, "mtp_full_mmvf256"); + assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 512 * 4))); + assert_eq!(l[2].args[5], A::P(at(&m, "pos", 24 * 4))); + assert_eq!(l[2].grid, [1, 4, 1]); + assert_eq!(l[5].args[5], A::P(at(&m, "pos", 2 * 24 * 4))); + } + + #[test] + fn scores_use_the_multi_query_kernel_then_the_radix_topk() { + let (m, g) = setup(); + let w = window(&m, g); + // max_blocks = 4096 / 4 + 2 = 1026, cap = 2051 + for n in 1..=8usize { + let l = w.block_scores_topk(5, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("qsa_decode_scores", [256, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![ + A::P(KV.pooled), + A::P(KV.dead), + A::P(at(&m, "qidx", 0)), + A::P(at(&m, "step", 0)), + A::I32(n as i32), + A::I64(1026), + A::P(at(&m, "scores", 0)) + ] + ); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("qsa_topk_ref", [n as u32, 1, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![A::P(at(&m, "scores", 0)), A::P(at(&m, "step", 0)), A::I64(1026), A::I64(2051), A::P(at(&m, "sel", 0))] + ); + l.iter().for_each(assert_abi); + } + // group B rows 4..7: q rows, steps (16 B), scores rows (1026 floats) and ids rows (2051 ints) offset by tb + let l = w.block_scores_topk(5, &layer(), rows(4, 7)).unwrap(); + assert_eq!(l[0].args[2], A::P(at(&m, "qidx", 4 * 512 * 4))); + assert_eq!(l[0].args[3], A::P(at(&m, "step", 4 * 16))); + assert_eq!(l[0].args[6], A::P(at(&m, "scores", 4 * 1026 * 4))); + assert_eq!(l[1].args[4], A::P(at(&m, "sel", 4 * 2051 * 4))); + assert_eq!(l[1].grid, [3, 1, 1]); + } + + #[test] + fn the_single_query_score_kernel_is_used_without_the_multi_policy() { + let (m, g) = setup(); + let mut p = OriginalVerifyQsaPolicy::mode17(); + p.scores_multi = false; + let w = QsaWindow::new(&m, g, p, identity()).unwrap(); + let l = w.block_scores_topk(0, &layer(), rows(0, 3)).unwrap(); + assert_eq!(l[0].entry, SCORE_SINGLE); + // grid (ceil(1026 / 8), nq) + assert_eq!((l[0].grid, l[0].block), ([129, 3, 1], [256, 1, 1])); + assert_eq!(l[0].args.len(), 6); + assert_eq!(l[0].args[4], A::I64(1026)); + assert_abi(&l[0]); + } + + #[test] + fn production_context_geometry_scales_the_block_arrays() { + let mut g = test_geometry(); + g.max_cells = 262144; + let m = LayoutMap::new(BASE, g); + let w = QsaWindow::new(&m, g, OriginalVerifyQsaPolicy::mode17(), identity()).unwrap(); + let mut kv = KV; + kv.pooled_bytes = 65538 * 512; + let l = QsaLayerAddrs { weights: W, kv }; + let launches = w.block_scores_topk(0, &l, rows(2, 4)).unwrap(); + assert_eq!(launches[0].args[5], A::I64(65538)); + assert_eq!(launches[0].args[6], A::P(at(&m, "scores", 2 * 65538 * 4))); + assert_eq!(launches[1].args[2], A::I64(65538)); + } + + #[test] + fn resolve_is_the_clock_kernel_then_the_96_block_miss_copy() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 1..=8usize { + let l = w.kv_resolve(9, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("leleka_qsa_resolve", [1, 1, 1], [1024, 1, 1])); + let mut want: Vec = KV.resolver.iter().map(|&a| A::P(a)).collect(); + want.extend([A::P(at(&m, "sel", 0)), A::P(at(&m, "step", 0)), A::I32(n as i32)]); + assert_eq!(l[0].args, want); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_miss_copy", [96, 1, 1], [128, 1, 1])); + let mut copy = vec![A::P(KV.resolver[4]), A::P(KV.resolver[5]), A::P(KV.resolver[6])]; + copy.extend(KV.host.iter().chain(&KV.resident).map(|&a| A::P(a))); + assert_eq!(l[1].args, copy); + l.iter().for_each(assert_abi); + } + let l = w.kv_resolve(0, &layer(), rows(3, 6)).unwrap(); + assert_eq!(l[0].args[7], A::P(at(&m, "sel", 3 * 2051 * 4))); + assert_eq!(l[0].args[8], A::P(at(&m, "step", 3 * 16))); + assert_eq!(l[0].args[9], A::I32(3)); + } + + #[test] + fn attention_chunk_and_merge_grids_cover_33_chunks_per_query() { + let (m, g) = setup(); + let w = window(&m, g); + // ceil(2051 / 64) = 33 chunks; scratch floats = 33 * 24 * 258 + 64 = 204400 + let stride = 33 * 24 * 258 + 64; + assert_eq!(stride, 204_400); + for n in 1..=8usize { + let l = w.decode_attention(2, &layer(), rows(0, n)).unwrap(); + assert_eq!(l.len(), 2); + assert_eq!((l[0].entry, l[0].grid, l[0].block, l[0].shared), ("leleka_qsa_decode_chunk", [33, 2, n as u32], [256, 1, 1], 0)); + let acc = at(&m, "attn_scratch", 0); + assert_eq!( + l[0].args, + vec![ + A::P(at(&m, "qcur", 0)), + A::P(KV.resident[0]), + A::P(KV.resident[1]), + A::P(KV.resident[2]), + A::P(KV.resident[3]), + A::P(KV.table), + A::P(at(&m, "sel", 0)), + A::P(at(&m, "step", 0)), + A::I32(2), + A::I32(4), + A::F32(0.0625), + A::P(acc), + // part_m after n_chunks * n_head * HD floats, part_l after n_chunks * n_head more + A::P(acc + 33 * 24 * 256 * 4), + A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), + A::I32(33), + A::I32(2051), + A::I64(stride as i64) + ] + ); + assert_eq!((l[1].entry, l[1].grid, l[1].block), ("leleka_qsa_decode_merge", [24, n as u32, 1], [256, 1, 1])); + assert_eq!( + l[1].args, + vec![ + A::P(acc), + A::P(acc + 33 * 24 * 256 * 4), + A::P(acc + (33 * 24 * 256 + 33 * 24) * 4), + A::I32(33), + A::P(at(&m, "attn", 0)), + A::I64(stride as i64) + ] + ); + l.iter().for_each(assert_abi); + } + let l = w.decode_attention(2, &layer(), rows(5, 8)).unwrap(); + assert_eq!(l[0].args[0], A::P(at(&m, "qcur", 5 * 24 * 256 * 4))); + assert_eq!(l[0].args[11], A::P(at(&m, "attn_scratch", 5 * stride * 4))); + assert_eq!(l[0].args[6], A::P(at(&m, "sel", 5 * 2051 * 4))); + assert_eq!(l[1].args[4], A::P(at(&m, "attn", 5 * 24 * 256 * 4))); + // the per-query scratch region holds acc + m + l + assert!(((33 * 24 * 258) as usize) < stride); + } + + #[test] + fn gate_is_one_launch_over_n_times_24_heads_when_batched() { + let (m, g) = setup(); + let w = window(&m, g); + for n in 2..=8usize { + let l = w.gate(1, rows(0, n), true).unwrap(); + assert_eq!(l.len(), 1); + // ceil(n * 24 * 256 / 256) blocks of 256 threads + assert_eq!((l[0].entry, l[0].grid, l[0].block), ("verify_window_qsa_gate", [24 * n as u32, 1, 1], [256, 1, 1])); + assert_eq!( + l[0].args, + vec![A::P(at(&m, "attn", 0)), A::P(at(&m, "qfull", 0)), A::P(at(&m, "attn32", 0)), A::I32(24 * n as i32), A::I32(256)] + ); + } + let l = w.gate(1, rows(2, 5), false).unwrap(); + assert_eq!(l.len(), 3); + assert_eq!(l[1].args[0], A::P(at(&m, "attn", 3 * 6144 * 4))); + assert_eq!(l[1].args[1], A::P(at(&m, "qfull", 3 * 12288 * 4))); + assert_eq!(l[1].args[2], A::P(at(&m, "attn32", 3 * 6144 * 4))); + assert_eq!(l[1].args[3], A::I32(24)); + assert_eq!(l[1].grid, [24, 1, 1]); + } + + #[test] + fn the_unsealed_gate_fails_closed_when_its_module_is_loaded_but_other_plans_are_unaffected() { + // loading goes through `AssetSpec::sealed`, which names the missing asset + let err = GATE.sealed().unwrap_err(); + assert!(matches!(err, Error::InvalidDriverValue(m) if m.contains("original_verify_window_qsa_gate.ptx"))); + let (m, g) = setup(); + let w = window(&m, g); + assert!(w.kv_resolve(0, &layer(), rows(0, 2)).is_ok()); + } + + #[test] + fn the_whole_layer_sequence_follows_verify_cpp_for_one_group() { + // order of the producers' first launch across a batched QSA layer (projections excluded) + let (m, g) = setup(); + let w = window(&m, g); + let r = rows(0, 4); + let a = layer(); + let mut seq: Vec<&str> = Vec::new(); + for l in [ + w.index_k(0, &a, r, true).unwrap(), + w.k_norm_rope(0, &a, r, true).unwrap(), + w.kv_append(0, &a, r).unwrap(), + w.q_path(0, &a, r, true).unwrap(), + w.index_q_path(0, &a, r, true).unwrap(), + w.block_scores_topk(0, &a, r).unwrap(), + w.kv_resolve(0, &a, r).unwrap(), + w.decode_attention(0, &a, r).unwrap(), + w.gate(0, r, true).unwrap(), + ] { + seq.extend(l.iter().map(|x| x.entry)); + } + assert_eq!(seq.len(), 1 + 2 + 4 + 3 + 3 + 2 + 2 + 2 + 1); + assert_eq!(seq[1], "qsa_decode_rms"); + assert_eq!(seq[seq.len() - 1], "verify_window_qsa_gate"); + } + + #[test] + fn weight_sizes_are_the_original_tensor_shapes() { + let g = test_geometry(); + assert_eq!(OriginalVerifyQsaBinding::sizes(&g), [1024, 1024, 512, 128 * 2560 * 2, 512 * 2560 * 2]); + assert_eq!(max_blocks(&g), 1026); + assert_eq!(scratch_floats(&g), 204_400); + assert!(KV.validate(&g).is_ok()); + } + + #[test] + fn construction_refuses_unsupported_geometry_and_policy() { + let (m, g) = setup(); + let mut bad = g; + bad.selection = 2048; + assert!(QsaWindow::new(&m, bad, OriginalVerifyQsaPolicy::mode17(), identity()).is_err()); + let mut p = OriginalVerifyQsaPolicy::mode17(); + p.kv_q4 = true; + assert!(QsaWindow::new(&m, g, p, identity()).is_err()); + } +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa_gate.cu b/crates/cuda-driver/src/original_verify_window_qsa_gate.cu new file mode 100644 index 00000000..c5f6b534 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_window_qsa_gate.cu @@ -0,0 +1,23 @@ +// Original native_qsa.cu `gate` (strata::kernels, anonymous namespace), exported under an extern "C" name for the +// literal Verifier window (verify.cpp `native_qsa_gate_apply`, QSA layer branch of `record_window`). Body unchanged. +// +// Original launch (native_qsa.cu): gate<<<(n_head*head_dim + 255) / 256, 256, 0, stream>>>(attn, q_full, output, +// n_head, head_dim) with q_full rows of [head][2][head_dim] (the gate is the second half of each head). +// +// COMPILE WITH --use_fast_math: CMakeLists.txt lists native_qsa.cu under COMPILE_OPTIONS "--use_fast_math", so the +// Original `expf` here is ex2.approx.ftz and the division is rcp.approx.ftz. The sealed `mtp_full_gate` (precise +// flags) and the single-token `leleka_qsa_native_gate` (fast math, flattened 24x256 gate, no head stride) are NOT +// this kernel. +#include +#include +#include + +extern "C" __global__ void verify_window_qsa_gate(const float* attn, const float* __restrict__ q_full, float* output, + int n_head, int head_dim) { + const std::size_t i = std::size_t(blockIdx.x) * blockDim.x + threadIdx.x; + if (i >= std::size_t(n_head) * head_dim) return; + const std::size_t head = i / head_dim, channel = i % head_dim; + const float raw = q_full[head * 2 * head_dim + head_dim + channel]; + const float sigmoid = 1.0f / (1.0f + expf(-raw)); + output[i] = attn[i] * sigmoid; +} diff --git a/crates/cuda-driver/src/original_verify_window_qsa_gate.ptx b/crates/cuda-driver/src/original_verify_window_qsa_gate.ptx new file mode 100644 index 00000000..adf07a71 Binary files /dev/null and b/crates/cuda-driver/src/original_verify_window_qsa_gate.ptx differ diff --git a/crates/cuda-driver/src/original_verify_window_record.rs b/crates/cuda-driver/src/original_verify_window_record.rs index 62f8a01e..0c3b0161 100644 --- a/crates/cuda-driver/src/original_verify_window_record.rs +++ b/crates/cuda-driver/src/original_verify_window_record.rs @@ -82,6 +82,20 @@ pub struct WindowPolicy { pub non_int8_kv: bool, /// Keyless / traced / layer-split variants. pub variant: bool, + /// Process-wide MMVQ column layout (`native_mmvq_set_multi_exact`, `STRATA_OLD_IQ_MMVQ`), fixed before capture. + pub dispatch: crate::NativeHeadDispatch, + /// `layer_set_native_bf16` (`--native-bf16`): router logits through the pinned BF16 MMVF. + pub native_bf16: bool, + /// `shared_expert_set_native_bf16` (`--native-bf16-extra`): the shared expert's scalar gate through MMVF. + pub native_bf16_extra: bool, + /// `gr_set_native_mmvf` (`--native`): the final residual write and the head mix. + pub native_mmvf: bool, + /// `ple_set_native_bf16` + `ple_set_native_postops` (`--native`). + pub native_ple: bool, + /// `fused_gr_variant()` the card's `fused_gr_check` settled on (`STRATA_HC_SPLIT`: unset = staged). + pub gr_variant: super::gr::GrVariant, + /// Process-wide QSA branch configuration (native QSA / RoPE, INT8 streamed KV, multi-query scores). + pub qsa: super::qsa::OriginalVerifyQsaPolicy, } impl WindowPolicy { pub const fn mode17() -> Self { @@ -95,6 +109,13 @@ impl WindowPolicy { cvec: false, non_int8_kv: false, variant: false, + dispatch: crate::NativeHeadDispatch { multi_exact: true, old_iq: false }, + native_bf16: true, + native_bf16_extra: true, + native_mmvf: true, + native_ple: true, + gr_variant: super::gr::GrVariant::Staged, + qsa: super::qsa::OriginalVerifyQsaPolicy::mode17(), } } pub fn validate_selected(&self) -> Result<()> { @@ -104,7 +125,8 @@ impl WindowPolicy { if self.device_plan || self.cvec || self.non_int8_kv || self.variant { return Err(Error::UnsupportedQwenOperation); } - Ok(()) + self.qsa.validate() + } } diff --git a/crates/cuda-driver/src/qsa_mapped_journal.rs b/crates/cuda-driver/src/qsa_mapped_journal.rs index c5841a88..4fb1fd2f 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal.rs @@ -141,6 +141,19 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx>{ } impl<'ctx> OriginalQsaMappedJournal<'ctx>{ + /// Fixed device addresses the captured verifier window binds for this layer's streamed INT8 KV: + /// (resident pools `[k_q, v_q, k_scale, v_scale]`, page table, host copy `[k_q, v_q, k_scale, v_scale]`, + /// resolver `[table, slot_block, slot_stamp, slot_ref, ctl, miss_block, miss_slot]`). + /// Read only: no coverage, epoch or resolver state changes. + pub(crate) fn window_kv_addresses(&self)->Result<([u64;4],u64,[u64;4],[u64;7])>{ + self.validate_context(self.owner.context)?; + // The captured window launches the resolver against these slots: it must have been reset (zeroed + // page table / slot stamps) by an owner call first, exactly like the prompt paths do lazily. + if !self.resolver_ready{return Err(Error::InvalidDriverValue("Original verifier producer unavailable: qsa_resolve: the streamed KV resolver was not initialised (reset) before the window capture"))} + let table=self.owner.pools.table()?; + let resolver=self.owner.resolver.as_ref().ok_or(Error::ContextPoisoned)?.window_addresses(table)?; + Ok((self.owner.pools.addresses()?,table,self.owner.host_addresses()?,resolver)) + } pub(crate) fn resolved_addresses(&mut self,w:&mut NativeBatchWorkspace<'ctx>,prefix:&OriginalQsaMappedPrefix,ids:&DeviceBuffer<'_>,steps:&DeviceBuffer<'_>,t:usize)->Result<([u64;4],u64,usize)>{ self.validate_prefix(prefix)?;w.validate_context(self.owner.context)?;if !(1..=3).contains(&t){return Err(Error::InvalidQwenShape)} let ids=checked(self.owner.context,ids,t*2051*4)?;let steps=checked(self.owner.context,steps,t*16)?; diff --git a/crates/cuda-driver/src/qsa_prompt_resolver.rs b/crates/cuda-driver/src/qsa_prompt_resolver.rs index 6ee8ffca..ba8c5227 100644 --- a/crates/cuda-driver/src/qsa_prompt_resolver.rs +++ b/crates/cuda-driver/src/qsa_prompt_resolver.rs @@ -105,6 +105,15 @@ impl<'ctx> Resolver<'ctx> { )?; Ok(()) } + /// The seven resolver device addresses in the order `leleka_qsa_resolve` takes them + /// (page table, slot block, slot stamp, slot ref, ctl, miss block, miss slot), for the + /// captured verifier window; the miss copy kernel takes entries 4..7. + pub(crate) fn window_addresses(&self, table: u64) -> Result<[u64; 7]> { + self.validate()?; + let slot = |i: usize| checked(self.context, self.slots[i].as_ref().ok_or(Error::ContextPoisoned)?, 32768); + let ctl = checked(self.context, self.ctl.as_ref().ok_or(Error::ContextPoisoned)?, 64)?; + Ok([table, slot(0)?, slot(1)?, slot(2)?, ctl, slot(3)?, slot(4)?]) + } fn addresses(&self, table: u64) -> Result> { self.validate()?; let mut v = Vec::new(); diff --git a/crates/cuda-driver/src/qsa_verification_commit.rs b/crates/cuda-driver/src/qsa_verification_commit.rs index eb878970..b3b3a810 100644 --- a/crates/cuda-driver/src/qsa_verification_commit.rs +++ b/crates/cuda-driver/src/qsa_verification_commit.rs @@ -16,6 +16,8 @@ impl OriginalVerifyRope<'_, '_>{fn validate(&self,c:&Context<'_>,capacity:usize) }} fn whole(c:&Context<'_>,b:&DeviceBuffer<'_>,bytes:usize)->Result{if !std::ptr::eq(c,b.context){return Err(Error::ContextMismatch)}if b.len()!=bytes{return Err(Error::ShapeMismatch{expected:bytes,actual:b.len()})}let h=b.handle.ok_or(Error::ContextPoisoned)?;h.validate_projection_extent(bytes,4)?;Ok(h.qwen_address())} fn overlaps(a:&DeviceBuffer<'_>,b:&DeviceBuffer<'_>)->Result{Ok(a.handle.ok_or(Error::ContextPoisoned)?.overlaps(a.len(),b.handle.ok_or(Error::ContextPoisoned)?,b.len()))} +/// Addresses of one QSA layer's fixed owners (see `OriginalVerifyQsaJournal::window_addresses`). +pub(crate) struct OriginalVerifyQsaWindowAddresses{pub resident:[u64;4],pub table:u64,pub host:[u64;4],pub resolver:[u64;7],pub pooled:u64,pub pooled_bytes:usize,pub dead:u64,pub dead_bytes:usize} struct Live{generation:u64,position:usize,rows:usize,armed:bool} /// Actual source gamma references, table owners and index images stay alive /// through ALL graph captures/replays and accepted-prefix commits. @@ -40,6 +42,19 @@ impl<'a,'ctx> OriginalVerifyQsaJournal<'a,'ctx>{ /// Access to the genuine mapped K/V owner is restricted to the driver graph /// bridge. A caller cannot mint a prefix from an index snapshot. pub(crate) fn with_committed_mapped(&self,layer:usize,consume:impl FnOnce(&mut OriginalQsaMappedJournal<'ctx>)->Result)->Result{self.validate_context(self.context)?;if layer>=12||self.live.try_borrow().map_err(|_|Error::InvalidQwenShape)?.armed{return Err(Error::InvalidQwenShape)}let mut m=self.mapped[layer].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;consume(&mut m)} + /// The resolved Original RoPE constants and optional retained tables (read only). + pub(crate) fn rope(&self)->OriginalVerifyRope<'a,'ctx>{self.rope} + /// Fixed device addresses the captured window kernels of one QSA layer bind: the streamed INT8 KV + /// (resident pools, page table, host copy, resolver) and the index image's pooled keys and spare key. + /// Read only; the window recorder may call it while a window is armed because no state changes. + pub(crate) fn window_addresses(&self,layer:usize)->Result{ + self.validate_context(self.context)?;if layer>=12{return Err(Error::InvalidQwenShape)} + let (resident,table,host,resolver)=self.mapped[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?.window_kv_addresses()?; + let i=self.indices[layer].try_borrow().map_err(|_|Error::InvalidQwenShape)?; + let pooled=i.image[0].as_ref().ok_or(Error::ContextPoisoned)?;let dead=i.image[2].as_ref().ok_or(Error::ContextPoisoned)?; + let address=|b:&DeviceBuffer<'ctx>|->Result{Ok(b.handle.ok_or(Error::ContextPoisoned)?.qwen_address())}; + Ok(OriginalVerifyQsaWindowAddresses{resident,table,host,resolver,pooled:address(pooled)?,pooled_bytes:pooled.len(),dead:address(dead)?,dead_bytes:dead.len()}) + } pub fn allocated_bytes(&self)->usize{self.indices.iter().map(|i|i.borrow().allocated_bytes()).sum::()+self.mapped.iter().map(|m|m.borrow().allocated_bytes()).sum::()} pub(crate) fn begin_window(&self,bank:&OriginalVerifyBank<'ctx>)->Result<()>{ self.validate_context(self.context)?;bank.validate_context(self.context)?;let mut live=self.live.try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?;if live.armed{return Err(Error::InvalidQwenShape)} diff --git a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs index 3fcf368a..4ef07e8d 100644 --- a/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs +++ b/crates/leleka-runtime/src/qwen_forward/dense_weight_cache.rs @@ -16,6 +16,11 @@ use crate::model_binding::qwen4exp_input::{ use leleka_cuda_driver::GrBatchInjectWorkspace; #[cfg(all(target_os = "linux", target_arch = "x86_64"))] use leleka_cuda_driver::OriginalVerifyGdnWeights; +#[cfg(all(target_os = "linux", target_arch = "x86_64"))] +use leleka_cuda_driver::{ + OriginalVerifyGdnProjections, OriginalVerifyGeometry, OriginalVerifyNativeMatrix, + OriginalVerifyProjBinding, OriginalVerifyQsaProjections, +}; use leleka_cuda_driver::{Context, DeviceBuffer}; use std::{ cell::{Cell, RefCell, RefMut}, @@ -1234,6 +1239,71 @@ impl<'ctx> DenseWeightCache<'ctx> { } retained.try_into().map_err(|_| Error::InvalidDimension) } + /// The native-format (GGUF block) MMVQ projection matrices of the 36 GDN and 12 QSA + /// layers for the literal Verifier window: the cache's own allocations, borrowed. + /// A matrix the cache holds as BF16 has no native MMVQ owner and is refused. + #[cfg(all(target_os = "linux", target_arch = "x86_64"))] + pub(super) fn original_verify_projections<'a>( + &'a self, + binding: &ModelBinding, + geometry: &OriginalVerifyGeometry, + ) -> Result> { + self.check(binding)?; + let gdn_type = |kind: GdnMatrixKind| -> Result { + match kind { + GdnMatrixKind::Q8_0 => Ok(8), + GdnMatrixKind::Q4K => Ok(12), + GdnMatrixKind::Q5K => Ok(13), + GdnMatrixKind::Q6K => Ok(14), + GdnMatrixKind::Iq4Nl => Ok(20), + GdnMatrixKind::Iq4Xs => Ok(23), + GdnMatrixKind::Bf16 => Err(Error::Unsupported(super::contract::Stage::Gdn)), + } + }; + let qsa_type = |kind: QsaMatrixKind| -> Result { + match kind { + QsaMatrixKind::Q4K => Ok(12), + QsaMatrixKind::Q5K => Ok(13), + QsaMatrixKind::Q6K => Ok(14), + QsaMatrixKind::Iq4Xs => Ok(23), + QsaMatrixKind::Bf16 => Err(Error::Unsupported(super::contract::Stage::QsaAttention)), + } + }; + let mut gdn = Vec::new(); + let mut qsa = Vec::new(); + gdn.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?; + qsa.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?; + for layer in binding.ordered_layers() { + match layer.kind() { + BoundLayerKind::Gdn => { + let resident = self.gdn(binding, layer.index())?; + let mut matrix = |role| -> Result> { + let (buffer, kind) = self.gdn_matrix(resident, role)?; + Ok(OriginalVerifyNativeMatrix { kind: gdn_type(kind)?, buffer }) + }; + gdn.push(OriginalVerifyGdnProjections { + qkv: matrix(GdnMatrixRole::Qkv)?, + gate: matrix(GdnMatrixRole::Z)?, + out: matrix(GdnMatrixRole::Out)?, + }); + } + BoundLayerKind::Qsa => { + let resident = self.qsa(binding, layer.index())?; + let mut matrix = |role| -> Result> { + let (buffer, kind) = self.qsa_matrix(resident, role)?; + Ok(OriginalVerifyNativeMatrix { kind: qsa_type(kind)?, buffer }) + }; + qsa.push(OriginalVerifyQsaProjections { + k: matrix(QsaMatrixRole::K)?, + v: matrix(QsaMatrixRole::V)?, + q: matrix(QsaMatrixRole::Q)?, + out: matrix(QsaMatrixRole::Out)?, + }); + } + } + } + OriginalVerifyProjBinding::new(self.context, geometry, gdn, qsa).map_err(driver_error) + } pub(super) fn qsa_matrix( &self, entry: &QsaResident, diff --git a/docs/cuda-seal-plan-additions-window.json b/docs/cuda-seal-plan-additions-window.json new file mode 100644 index 00000000..9fe8c747 --- /dev/null +++ b/docs/cuda-seal-plan-additions-window.json @@ -0,0 +1,195 @@ +{ + "schema": 1, + "purpose": "Assets Root must seal for the literal Verifier window recorder (OriginalVerifyWindowOps). Everything not listed under new_sources is an already sealed asset that the window producers merely bind (SHA-256 pinned in the AssetSpec constants of crates/cuda-driver/src/original_verify_window_*.rs).", + "toolkit": "deploy/cuda-toolkit.lock.json (CUDA 13.0.88), built through scripts/build-original-verify-ptx.sh", + "new_sources": [ + { + "source": "crates/cuda-driver/src/original_verify_window_moe_experts.cu", + "ptx": "crates/cuda-driver/src/original_verify_window_moe_experts.ptx", + "nvcc": [ + "--ptx", + "-std=c++17", + "-O3", + "-arch=sm_120", + "--fmad=true", + "--ftz=false", + "-Iengine/strata/include", + "-Iengine/strata/third_party/ggml", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src" + ], + "exports": [ + "window_moe_gu_16", + "window_moe_gu_17", + "window_moe_gu_18", + "window_moe_gu_21", + "window_moe_gu_22", + "window_moe_gu_23", + "window_moe_gu_29", + "window_moe_gu_42", + "window_moe_gu_12", + "window_moe_gu_13", + "window_moe_gu_8", + "window_moe_down_20", + "window_moe_down_23", + "window_moe_down_42", + "window_moe_down_7", + "window_moe_down_8" + ], + "derived_from": "engine/strata/src/kernels/cuda/iq_kernels.cu (native_gu_kernel, native_gu_multi_kernel, native_down_kernel, native_down_multi_kernel via native_expert_grouped / launch_gu / launch_down; textually includes crates/cuda-driver/src/mtp_original_full_head_iq.cu, the sealed copy of iq_kernels.cu; engine/strata/CMakeLists.txt gives iq_kernels.cu no per-source COMPILE_OPTIONS)", + "notes": "NEW source: no sealed PTX instantiates the grouped gate/up and down templates for the target's formats. The rest of native_expert_grouped (swiglu_entries_kernel, quantize_q8_1_kernel) is sealed in mtp_original_full_head_iq.ptx under mangled names. The PTX will also carry the unused head_* / dequant entries of the included file. Update EXPERTS.sha in original_verify_window_moe.rs after sealing; the build script's required-exports check should list the exports above.", + "install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL." + }, + { + "source": "crates/cuda-driver/src/original_verify_window_qsa_gate.cu", + "ptx": "crates/cuda-driver/src/original_verify_window_qsa_gate.ptx", + "nvcc": [ + "--ptx", + "-std=c++17", + "-O3", + "-arch=sm_120", + "--fmad=true", + "--use_fast_math", + "-Iengine/strata/include", + "-Iengine/strata/third_party/ggml", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-cuda", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-include", + "-Icrates/cuda-driver/src/third_party/llamacpp/ggml-src" + ], + "exports": [ + "verify_window_qsa_gate" + ], + "derived_from": "engine/strata/src/kernels/cuda/native_qsa.cu (kernel `gate`; CMakeLists.txt compiles native_qsa.cu with --use_fast_math)", + "nvcc_note": "--use_fast_math (as engine/strata/CMakeLists.txt compiles native_qsa.cu) implies --ftz=true --prec-div=false --prec-sqrt=false --fmad=true; --ftz=false is deliberately NOT passed.", + "install": "Compile, append exactly ONE terminal NUL byte (like the other sealed MTP assets), write over the placeholder .ptx, then replace the all-zero `sha` of the matching AssetSpec by sha256 of the bytes BEFORE the NUL." + } + ], + "sealed_assets_bound": [ + { + "ptx": "crates/cuda-driver/src/mtp_original_full_attention.ptx", + "sha256": "3fb235ca405d24c3b8d0ec46611d9d640103b71a65859923194f02f06b482f6c" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_bf16.ptx", + "sha256": "a16dfcfc9a49ccab25d8030293d5826f8f75e2868fae1b6c4cef706b6dfc3d08" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_combine.ptx", + "sha256": "2253fe2d641350f4445a0a69c4a0fc22b85c2fffca7cbd536ffe5d2912f81fb7" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_element.ptx", + "sha256": "8fdfdf8ef616698c12301f7df4716fc022bf34b419099e4c972729920bd5f4a7" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_fused_gr.ptx", + "sha256": "ac5400a7972b3f242648c2de71ef4f178466d38b1392a83a9591b3b24e92c59b" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_gr_norm.ptx", + "sha256": "ba95d7c5b27cc9d4c1cfbc6b3bcd000e5ba29b124c661c090515c86d8237e05c" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_gr_post.ptx", + "sha256": "e884c4a3a20695c798d48b156657ff24b9322c1568430f5144cfdaeed14ef25a" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_head_iq.ptx", + "sha256": "3c5f13d5747f78a04be4155f0824b91f7e4b10ca3796add24912228fab5a4520" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_head_native.ptx", + "sha256": "da5ca63be66149554d18b03ae6a3ea295f7b2c97afbd6491445ee1ae0a29e242" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_router.ptx", + "sha256": "c5b933b5010683a92ada414d312156bbde87c6c59bb1f883713a0682a15920e4" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_router_legacy.ptx", + "sha256": "a58412249757cc351eb8332e807e79f1b3da5865574d0fb7179ef558df70af24" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_s2.ptx", + "sha256": "fbb917d590ea80338a7bdf07b2ca6d458fa72763ba279e576bcc1eec8836fd55" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_full_shared.ptx", + "sha256": "b36f432692e43f7948a2538c22cab55ef67c625b8d4461c67ca2a27519b9e0f0" + }, + { + "ptx": "crates/cuda-driver/src/mtp_original_kv.ptx", + "sha256": "e0c1ff10d3d4bcf8fd3369713079b232e62cdb2c3a345faec49d1e66763f911f" + }, + { + "ptx": "crates/cuda-driver/src/ple_native_batch.ptx", + "sha256": "1a382cbe867bc193c6af5292c2cbcfbd8e2f57cd1950c90de4f30000367410b3" + }, + { + "ptx": "crates/cuda-driver/src/qsa_decode_postops.ptx", + "sha256": "000a824e087c569bfa4cbad8dc919f845cba2a86348bbff1e7fcd206dc28b3a9" + }, + { + "ptx": "crates/cuda-driver/src/qsa_prompt_postops.ptx", + "sha256": "261233f1975941a86d0ffa7b9a2e26250163ddea682874bc85aaad8d9b20c1a0" + }, + { + "ptx": "crates/cuda-driver/src/qsa_prompt_resolver.ptx", + "sha256": "ab672a54a7b9131d85b248cf56b409342634f9280b9b18482850fba3b66b1100" + }, + { + "ptx": "crates/cuda-driver/src/qsa_prompt_select.ptx", + "sha256": "1e35514744216229b0cffb4f45d2f13f25cb95f377a30c1c012543dbf53a1c2d" + } + ], + "numerics_risk_fast_math": { + "engine_fast_math_sources_cmake": [ + "native_mmvq", + "native_bf16", + "native_gr_norm", + "native_moe", + "native_gdn", + "native_gr_postops", + "native_router", + "native_gdn_preprocess", + "native_qsa", + "native_rope", + "native_ple_postops", + "native_flash_attn", + "native_qsa_indexer", + "native_qsa_score" + ], + "note": "engine/strata/CMakeLists.txt compiles these Original sources with --use_fast_math. The sealed Rust copies below were built with the precise flags of scripts/build-original-verify-ptx.sh (--fmad=true --ftz=false). Some copies reproduce the fast-math operations with explicit intrinsics in the .cu (e.g. mtp_original_full_shared.cu: __fdividef/__expf); the others are a numerics risk for bit-exact parity with the Original window until a per-kernel golden comparison on the GPU (or a re-seal with --use_fast_math) proves otherwise.", + "candidate_resealed_assets": [ + { + "ptx": "mtp_original_full_head_native.ptx", + "derived_from": "native_mmvq / head_dispatch (quantize_q8_1 + MMVQ)" + }, + { + "ptx": "mtp_original_full_bf16.ptx", + "derived_from": "native_bf16" + }, + { + "ptx": "mtp_original_full_router.ptx / mtp_original_full_router_legacy.ptx", + "derived_from": "native_router" + }, + { + "ptx": "mtp_original_full_gr_norm.ptx / mtp_original_full_gr_post.ptx / mtp_original_full_fused_gr.ptx", + "derived_from": "native_gr_norm / native_gr_postops" + }, + { + "ptx": "mtp_original_full_combine.ptx", + "derived_from": "native_moe" + }, + { + "ptx": "mtp_original_full_attention.ptx / qsa_decode_postops.ptx / qsa_prompt_postops.ptx / qsa_prompt_select.ptx", + "derived_from": "native_flash_attn / native_qsa / native_qsa_indexer / native_qsa_score" + }, + { + "ptx": "ple_native_batch.ptx", + "derived_from": "native_ple_postops" + } + ] + } +}