Merge branch 'claude/port-window-producers' into claude/port-main

This commit is contained in:
Pavlo Ratushnyi
2026-10-14 16:21:00 +02:00
23 changed files with 6533 additions and 116 deletions
+1 -1
View File
@@ -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<DeviceBuffer>` 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. |
+13
View File
@@ -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,
+1 -1
View File
@@ -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,
+64 -4
View File
@@ -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<DeviceBuffer<'ctx>>,prof:Option<DeviceBuffer<'ctx>>,mapped:[RefCell<Option<MappedAllocation>>;15],module:Option<Module>,qsa_module:Option<Module>,generation:Cell<u64>,failed:Cell<bool>}
struct Physical<'ctx>{context:&'ctx Context<'ctx>,layout:OriginalVerifyLayout,arena:Option<DeviceBuffer<'ctx>>,prof:Option<DeviceBuffer<'ctx>>,mapped:[RefCell<Option<MappedAllocation>>;15],module:Option<Module>,qsa_module:Option<Module>,window:RefCell<Vec<(&'static str,Module,Vec<&'static str>)>>,generation:Cell<u64>,failed:Cell<bool>}
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<u64>{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<i32>{
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<u64>{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<Physical<'ctx>>,last_t:usize,las
impl<'ctx> OriginalVerifyBank<'ctx>{
fn new(context:&'ctx Context<'ctx>,geometry:OriginalVerifyGeometry)->Result<Self>{
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<Physical<'ctx>>,canonical:Rc<Canonical<'ctx>>,weights:[OriginalVerifyGdnWeights<'a,'ctx>;36],ple:Option<&'a DeviceBuffer<'ctx>>,commands:RefCell<Vec<Command>>}
/// 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<u64>{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<i32>{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<kernels::Launch>)->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<u64>{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<Option<u64>>{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<'_>{
+14 -5
View File
@@ -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<usize>{self.args.len().checked_mul(std::mem::size_of::<Arg>()).and_then(|n|self.pointers.capacity().checked_mul(std::mem::size_of::<*mut c_void>()).and_then(|m|n.checked_add(m))).ok_or(Error::InvalidSize)}
pub(crate) fn new(name:&'static str,grid:[u32;3],block:[u32;3],shared:u32,args:Vec<Arg>)->Result<Self>{let mut pointers=Vec::new();pointers.try_reserve_exact(args.len()).map_err(|_|Error::HostAllocation)?;Ok(Self{name,grid,block,shared,args:args.into_boxed_slice(),pointers})}}
struct Library(Handle);
impl Drop for Library{fn drop(&mut self){if !self.0.is_null(){unsafe{libc::dlclose(self.0);}}}}
pub(crate) struct Module{library:Option<Library>,handle:Option<usize>,functions:Vec<(&'static str,usize)>,launch:Launch,unload:Destroy}
pub(crate) struct Module{library:Option<Library>,handle:Option<usize>,functions:Vec<(&'static str,usize)>,launch:Launch,unload:Destroy,set_attr:SetAttr,device:DeviceOf,device_attr:DeviceAttr}
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<Self>{
pub(crate) fn load(ptx:&'static[u8],entries:&[&'static str])->Result<Self>{
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<Handle>{let p=unsafe{libc::dlsym(l.0,n.as_ptr())};if p.is_null(){Err(Error::MissingSymbol(n.to_str().unwrap_or("OriginalVerify ABI")))}else{Ok(p)}}
macro_rules! symbol{($n:literal,$t:ty)=>{unsafe{std::mem::transmute::<Handle,$t>(sym(&library,$n)?)} };}
let load=symbol!(c"cuModuleLoadData",Load);let function=symbol!(c"cuModuleGetFunction",Function);
let mut owner=Self{launch:symbol!(c"cuLaunchKernel",Launch),unload:symbol!(c"cuModuleUnload",Destroy),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<i32>{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(())}}
}
@@ -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::<std::collections::BTreeSet<_>>();
let loaded = bank.physical.window.borrow().iter().map(|(name, _, _)| *name).collect::<std::collections::BTreeSet<_>>();
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");
}
File diff suppressed because it is too large Load Diff
@@ -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<Launch>` (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<u64>),
}
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`: `<<<grid, block, shared>>>` 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<A>,
}
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<A>,
) -> Result<Self> {
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> {
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 <<<g,b,s>>>`.
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<u64>;
}
/// 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<u64> {
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>>>");
}
}
File diff suppressed because it is too large Load Diff
@@ -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<T> -> native_gu_kernel<T> | native_gu_multi_kernel<T> (kSplit<T> selects the second)
// swiglu_entries_kernel, quantize_q8_1_kernel (sealed in mtp_original_full_head_iq.ptx)
// launch_down<T> -> native_down_kernel<T> | native_down_multi_kernel<T>
//
// `native_gu_kernel<T>` 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> (T in STRATA_GU_FMTS) and window_moe_down_<T> (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<TG> / native_gu_multi_kernel<TG>
template<int TG>
__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<TG>::qk), xb = (int) (L.n_embd / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
if constexpr (!kSplit<TG>) {
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TG>(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<TG, GRP_NC>(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<TD> / native_down_multi_kernel<TD>
template<int TD>
__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<TD>::qk), hb = (int) (L.n_ff / 32);
const int e0 = grp_start[g], e1 = grp_start[g + 1];
if constexpr (!kSplit<TD>) {
for (int e = e0; e < e1; ++e) {
const float s = row_dot<TD>(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<TD, GRP_NC>(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<T>(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<T>(grp_ptr, grp_start, n_groups, ent_dst, hq, L, out); \
}
STRATA_D_FMTS(STRATA_WINDOW_DOWN)
#undef STRATA_WINDOW_DOWN
} // namespace strata::kernels
@@ -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: <producer>: ... not attached`, a producer
//! whose policy variant has no genuine kernel refuses with `... producer unavailable:
//! <producer>: <why>`, and a kernel asset that is not sealed refuses the whole window
//! BEFORE capture with `... asset unsealed: <file> (<what>)` (`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<OriginalVerifyProjBinding<'a, 'ctx>>,
/// hc weights of the 48 layers, the final mixer and the optional PLE block.
gr: Option<OriginalVerifyGrBinding<'a, 'ctx>>,
/// QSA norms and indexer projections of the 12 QSA layers.
qsa: Option<OriginalVerifyQsaBinding<'a, 'ctx>>,
/// Router, shared experts and routed expert formats of the 48 layers.
moe: Option<OriginalVerifyMoeBinding<'a, 'ctx>>,
/// The per-card fused-GR decisions, read once by `prepare`.
gr_cfg: Option<GrConfig>,
}
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<Self> {
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<Self> {
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<Self> {
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<Self> {
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<GdnProjectionAddrs> {
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<QsaProjectionAddrs> {
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<gr::HcAddrs> {
self.gr.as_ref().ok_or(unattached!("hc_read", "hyper-connection weights"))?.half_addrs(layer, half)
}
fn head(&self) -> Result<gr::HeadAddrs> {
self.gr.as_ref().ok_or(unattached!("head", "output hyper-connection weights"))?.head_addrs()
}
fn ple(&self) -> Result<Option<gr::PleAddrs>> {
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<QsaLayerAddrs> {
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> {
QsaRope::from_rope(&self.base.qsa.rope())
}
fn moe(&self, layer: usize) -> Result<MoeLayerAddrs> {
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<Command>) -> 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<Launch>) -> 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<Planner<'_>> {
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<Vec<Launch>>) -> 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<u64> {
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}");
}
}
}
@@ -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<Launch>`) 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<GdnProjectionAddrs>;
/// `attn_k` / `attn_v` / `attn_q` / `attn_output` of QSA layer `q` (0..12).
fn qsa_projections(&self, q: usize) -> Result<QsaProjectionAddrs>;
fn hc(&self, layer: usize, half: HcHalf) -> Result<HcAddrs>;
fn head(&self) -> Result<HeadAddrs>;
/// `None` when the model has no PLE block.
fn ple(&self) -> Result<Option<PleAddrs>>;
/// Norm / indexer weights plus the fixed KV and index addresses of QSA layer `q`.
fn qsa(&self, q: usize) -> Result<QsaLayerAddrs>;
fn rope(&self) -> Result<QsaRope>;
fn moe(&self, layer: usize) -> Result<MoeLayerAddrs>;
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<'p>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<(usize, Vec<Launch>)>> {
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<Vec<Launch>> {
Ok(vec![proj::plan_window_quantize(self.arena, &self.geo, source, rows)?])
}
pub(crate) fn mmvq(&self, layer: usize, projection: Projection, rows: Rows) -> Result<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
self.qsa_window()?.block_scores_topk(q, &self.weights.qsa(q)?, rows)
}
pub(crate) fn qsa_kv_resolve(&self, q: usize, rows: Rows) -> Result<Vec<Launch>> {
self.qsa_window()?.kv_resolve(q, &self.weights.qsa(q)?, rows)
}
pub(crate) fn qsa_decode_attention(&self, q: usize, rows: Rows) -> Result<Vec<Launch>> {
self.qsa_window()?.decode_attention(q, &self.weights.qsa(q)?, rows)
}
pub(crate) fn qsa_gate(&self, q: usize, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
self.qsa_window()?.gate(q, rows, batched)
}
// ---- FFN
pub(crate) fn router(&self, layer: usize, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
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<Vec<Launch>> {
moe::plan_hit_add(self.arena, &self.geo, rows)
}
pub(crate) fn combine(&self, rows: Rows, batched: bool) -> Result<Vec<Launch>> {
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<GdnProjectionAddrs> {
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<QsaProjectionAddrs> {
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<HcAddrs> {
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<HeadAddrs> {
Ok(HeadAddrs { norm: 0x3f_0000_0000, down: 0x3f_0100_0000, up: 0x3f_0200_0000 })
}
fn ple(&self) -> Result<Option<PleAddrs>> {
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<QsaLayerAddrs> {
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> {
QsaRope::new(0.7498942, 1.0, 0.0, 0.0, 0.0, 1.0)
}
fn moe(&self, layer: usize) -> Result<MoeLayerAddrs> {
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<String>,
t: usize,
}
impl PlanOps<'_> {
fn plan(&mut self, name: &str, r: Result<Vec<Launch>>) -> 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!("<ple row{row}"));
self.log.extend(launches.iter().map(kernel));
self.log.push(format!("snapshot row{row}"));
}
Ok(())
}
fn hc_read(&mut self, l: usize, h: HcHalf, a: bool, r: Rows) -> 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<String> {
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("<ple")).count(), if ple { t } else { 0 });
}
}
}
}
#[test]
fn a_gdn_layer_records_verify_cpp_order_with_the_sealed_kernels() {
let log = record(3, 1, false);
// layer 0 up to the ring: hc read (staged variant: split norm, staged down, up), q8_1 + qkv, conv, alpha/beta,
// z projection, recurrence, y quantization + out projection, FFN hc read, router, doorbell, shared expert
let pre = section(&log, "stamp 0.0", "stamp 0.18");
let k = names(pre);
let pos = |needle: &str| k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}"));
assert!(pos("<hc Attention apply=false") < pos("mtp_scalar_gr_split"));
assert!(pos("mtp_scalar_gr_split") < pos("mtp_scalar_gr_staged") && pos("mtp_scalar_gr_staged") < pos("mtp_scalar_gr_up"));
assert!(pos("hc Attention apply=false>") < pos("<quant Mixed"));
assert!(pos("<quant Mixed") < pos("<mmvq GdnQkv") && pos("<mmvq GdnQkv") < pos("gdn_conv g0 0..3"));
assert!(pos("gdn_conv g0 0..3") < pos("gdn_ab g0") && pos("gdn_ab g0") < pos("<mmvq GdnGate"));
assert!(pos("<mmvq GdnGate") < pos("gdn_rec g0") && pos("gdn_rec g0") < pos("<quant GdnY"));
assert!(pos("<quant GdnY") < pos("<mmvq GdnOut") && pos("<mmvq GdnOut") < pos("<hc Ffn apply=true"));
// the three-row router is the batched pair, then the doorbell, then the shared expert and the expert input
assert!(pos("<hc Ffn apply=true") < pos("<router") && pos("<router") < pos("doorbell"));
assert!(pos("doorbell") < pos("<shared") && pos("<shared") < pos("<xq"));
let router = section(&log, "<router", "router>");
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 == "<hc Attention apply=true"));
assert!(!pre.iter().any(|s| s == "<hc Attention apply=true"));
}
#[test]
fn a_qsa_layer_records_the_kv_chain_between_the_projections() {
let log = record(4, 1, false);
let layer = section(&log, "stamp 3.0", "stamp 3.16");
let k = names(layer);
let pos = |needle: &str| k.iter().position(|s| *s == needle).unwrap_or_else(|| panic!("{needle} missing in {k:?}"));
let order = [
"<quant Mixed", "<index_k", "<mmvq QsaK", "<mmvq QsaV", "<k_norm_rope", "tail q0", "<kv_append", "indexer_append q0",
"<mmvq QsaQ", "<q_path", "<index_q_path", "<scores_topk", "<kv_resolve", "<attention", "<gate", "<quant Attention", "<mmvq QsaOut",
];
let at: Vec<usize> = 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", "<experts Vram", "waitB 1", "<experts Pcie", "waitM 1", "cpu_rows", "<hit_add", "<combine"];
let at: Vec<usize> = 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, "<experts Vram", "experts Vram>"));
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<usize> = log.iter().enumerate().filter(|(_, s)| s.starts_with("<hc Attention")).map(|(i, _)| i).collect();
let wa1 = log.iter().position(|s| s == "waitA 1").unwrap();
let wa2 = log.iter().position(|s| s == "waitA 2").unwrap();
assert!(hcs[0] < hcs[1] && hcs[1] < wa1 && wa1 < hcs[2] && hcs[2] < wa2);
assert_eq!(log.iter().filter(|s| *s == "tail q0").count(), 1);
}
#[test]
fn the_head_mixes_every_row_then_the_head_owner_finishes() {
let log = record(3, 1, false);
let tail = section(&log, "stamp 48.0", "stamp 48.1");
let k = names(tail);
assert_eq!(k.iter().filter(|s| **s == "mtp_full_gr_norm").count(), 3);
assert_eq!(k.iter().filter(|s| **s == "mtp_full_pre_final").count(), 3);
assert_eq!(k[k.len() - 2], "head_tail");
}
#[test]
fn ple_runs_once_at_layer_one_row_by_row_with_each_rows_snapshot() {
let log = record(2, 1, true);
let l1 = section(&log, "stamp 1.0", "stamp 1.1");
let k = names(l1);
assert_eq!(k.iter().filter(|s| s.starts_with("<ple row")).count(), 2);
let first = k.iter().position(|s| *s == "snapshot row0").unwrap();
let second = k.iter().position(|s| *s == "<ple row1").unwrap();
assert!(first < second, "row 0's snapshot precedes row 1's block");
assert!(k.contains(&"<hc Attention apply=false"), "the PLE block replaced the pending write");
}
}
@@ -0,0 +1,613 @@
//! Shared projection primitives of the Verifier window (child of `original_verify`): the
//! Original `native_quantize_q8_1`, `native_mmvq` (every GGUF type the target carries) and
//! `bf16_gemv_fp32_mmvf(_multi)` as launch plans over sealed assets. Pure: addresses in,
//! `Launch`es out. Every family producer (GDN/QSA mixers, router, shared expert, head)
//! builds its matrix products from here, so the arithmetic is the Original kernel's.
//!
//! * quantize: `native_quantize_q8_1(x, xq, n_in, rows)` is ONE `head_quant` launch over
//! `rows * n_in` contiguous elements (a 32-element block never straddles a row).
//! * mmvq: the head dispatch (`head_n{type}_*`, 1..=8 columns, IQ kinds through `head_i*`)
//! with the activation rows `n_in/32*36` bytes apart and outputs `n_out` floats apart.
//! * bf16 gemv: `mtp_full_mmvf{B}` for one row, the `_multi_kernel<B, 4|8>` 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<Launch> {
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<Launch> {
if n_in == 0 || n_in % 32 != 0 || n_out == 0 || !(1..=8).contains(&rows) {
return Err(Error::InvalidQwenShape);
}
let (n_in32, n_out32) = (i32::try_from(n_in).map_err(|_| Error::InvalidSize)?, i32::try_from(n_out).map_err(|_| Error::InvalidSize)?);
let (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<Launch> {
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<Launch> {
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<Launch> {
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<NativeWeight> {
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<NativeWeight> {
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<OriginalVerifyGdnProjections<'a, 'ctx>>,
qsa: Vec<OriginalVerifyQsaProjections<'a, 'ctx>>,
}
/// 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<usize> {
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<NativeWeight> {
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<OriginalVerifyGdnProjections<'a, 'ctx>>,
qsa: Vec<OriginalVerifyQsaProjections<'a, 'ctx>>,
) -> Result<Self> {
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<GdnProjectionAddrs> {
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<QsaProjectionAddrs> {
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());
}
}
File diff suppressed because it is too large Load Diff
@@ -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 <cuda_runtime.h>
#include <cmath>
#include <cstddef>
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;
}
@@ -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()
}
}
@@ -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)?;
@@ -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<Vec<Arg>> {
self.validate()?;
let mut v = Vec::new();
@@ -16,6 +16,8 @@ impl OriginalVerifyRope<'_, '_>{fn validate(&self,c:&Context<'_>,capacity:usize)
}}
fn whole(c:&Context<'_>,b:&DeviceBuffer<'_>,bytes:usize)->Result<u64>{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<bool>{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<R>(&self,layer:usize,consume:impl FnOnce(&mut OriginalQsaMappedJournal<'ctx>)->Result<R>)->Result<R>{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<OriginalVerifyQsaWindowAddresses>{
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<u64>{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::<usize>()+self.mapped.iter().map(|m|m.borrow().allocated_bytes()).sum::<usize>()}
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)}
@@ -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<OriginalVerifyProjBinding<'a, 'ctx>> {
self.check(binding)?;
let gdn_type = |kind: GdnMatrixKind| -> Result<u32> {
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<u32> {
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<OriginalVerifyNativeMatrix<'_, 'ctx>> {
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<OriginalVerifyNativeMatrix<'_, 'ctx>> {
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,
+195
View File
@@ -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"
}
]
}
}