feat(verify): literal record_window recorder, window resource aggregate and record_all
Pure Verifier schedule (pre/post order, split-window groups, ring numbers, plan-block carve) and the exact record_window call sequence over a WindowOps producer set, unit-tested with a trace producer (single/split windows, PLE layer 1, pcie mode 2, last-layer write, head). OriginalVerifyWindowResources joins the GDN/QSA/head aggregate with the embedding rows and expert blob layout; OriginalVerifier::record_all records every T graph and the real commit graph before run. Bound producers: verify-module copies/waits/plan/PCIe staging/doorbell, GDN and QSA-index journals, embedding. Every producer without a capturable owner fails closed by name (UNBOUND_PRODUCERS) instead of approximating. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
9f7d7c79f3
commit
b5196e10e5
@@ -3087,6 +3087,10 @@ pub use original_verify::{
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
pub use original_verify::{
|
||||
ExpertTier, HcHalf, OriginalVerifyExpertLayout, OriginalVerifyWindowResources, PlanLayout,
|
||||
Projection, QuantSource, Rows as OriginalVerifyRows, UNBOUND_PRODUCERS, WINDOW_LAYERS,
|
||||
WindowOps as OriginalVerifyWindowOps, WindowPolicy as OriginalVerifyWindowPolicy,
|
||||
record_window as record_original_verify_window,
|
||||
OriginalVerifyDiag, OriginalVerifyProfile, PROFILE_STAMPS_PER_LAYER, RowLogprob, analyse_row,
|
||||
logpos_topk_from_environment, original_verify_diagnostics, original_verify_live_count,
|
||||
original_verify_release_live, profile_stamp_slot, profile_stamp_words, top_k, write_row_line,
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
#[path="original_verify_diag.rs"] #[allow(unsafe_code)] mod diag;
|
||||
#[path="original_verify_profile.rs"] mod profile;
|
||||
#[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;
|
||||
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};
|
||||
@@ -316,6 +318,10 @@ 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_record::{ExpertTier,HcHalf,Projection,QuantSource,Rows,WindowOps,WindowPolicy,record_window};
|
||||
pub use window_plan::{PlanLayout,WINDOW_LAYERS};
|
||||
|
||||
impl OriginalVerifyWindow<'_>{
|
||||
/// Structural geometry admission, not a numerical/session authority.
|
||||
|
||||
@@ -36,7 +36,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
pub fn record_window(&mut self,t:usize,resources:R,record:impl FnOnce(&mut OriginalCapture<'_, 'ctx>,&mut R,usize)->Result<()>)->Result<()>{
|
||||
if self.failed||self.active||!(1..=self.bank()?.geometry().max_t).contains(&t)||self.window[t-1].is_some(){return Err(Error::InvalidQwenShape)}self.record_keys(&resources)?;
|
||||
if resources.native_head_rows()?.rows()!=t||resources.native_head_rows()?.completed_logits()?.len()!=t*self.bank()?.geometry().vocabulary*4{return Err(Error::InvalidQwenShape)}
|
||||
let groups=if self.split&&t>=2{2}else{1};let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let groups=window_plan::window_groups(t,self.split);let stream=self.compute.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let graph=stream.capture_owned(OriginalCapturePolicy::VerifierWindow,resources,|capture,r|{r.verifier_journal().capture_inputs(capture,t)?;record(capture,r,groups)})?;
|
||||
self.window[t-1]=Some(graph);self.groups[t-1]=groups;Ok(())
|
||||
}
|
||||
@@ -68,11 +68,11 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
let operation=std::panic::catch_unwind(std::panic::AssertUnwindSafe(||->Result<NativeHeadSelection>{
|
||||
self.window[t-1].as_mut().ok_or(Error::ContextPoisoned)?.enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
|
||||
let _=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;
|
||||
let groups=self.groups[t-1];for k in 0..48*groups{
|
||||
let layer=k/groups;let group=k%groups;let want=(k+1)as u32;let start=Instant::now();let mut last_flush=start;let mut spins=0u32;
|
||||
let groups=self.groups[t-1];for k in 0..window_plan::window_rings(groups){
|
||||
let layer=k/groups;let group=k%groups;let want=window_plan::ring(layer,groups,group);let start=Instant::now();let mut last_flush=start;let mut spins=0u32;
|
||||
if let Some(r)=&self.registration{r.layer_step(want)}
|
||||
loop{if self.bank()?.doorbell_sequence()?>=want{break}std::hint::spin_loop();spins=spins.wrapping_add(1);if spins&1023!=0{continue}let now=Instant::now();if self.registration.as_ref().is_some_and(diag::Registration::is_released){return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)"))}if now.duration_since(last_flush)>Duration::from_micros(2000){last_flush=now;let q=self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?;if q&&self.bank()?.doorbell_sequence()?<want{return Err(Error::InvalidDriverValue("Verifier layer never rang"))}}if now.duration_since(start)>Duration::from_secs(20){return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout"))}}
|
||||
let begin=if group==0{0}else{t.div_ceil(2)};let end=if groups==2&&group==0{t.div_ceil(2)}else{t};let rows=end-begin;let g=self.bank()?.geometry();let physical=self.bank()?.physical.clone();
|
||||
let (begin,end)=window_plan::group_rows(t,groups,group);let rows=end-begin;let g=self.bank()?.geometry();let physical=self.bank()?.physical.clone();
|
||||
let x=physical.mapped[6].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
|
||||
let ids=physical.mapped[7].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
|
||||
let w=physical.mapped[8].try_borrow().map_err(|_|Error::InvalidQwenShape)?;
|
||||
@@ -82,7 +82,7 @@ impl<'ctx,R:OriginalVerifyGraphResources<'ctx>+OriginalNativeHeadGraphResources<
|
||||
// producers publish A and raise B only from completed host callbacks.
|
||||
let flag=self.bank()?.physical.mapped[11].try_borrow().map_err(|_|Error::InvalidQwenShape)?.as_ref().ok_or(Error::ContextPoisoned)?.read_u32(0)?;
|
||||
if flag!=want{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group,want)?}
|
||||
let stalled=self.test_stall>0&&self.windows+1==self.test_stall&&k+1==48*groups;
|
||||
let stalled=self.test_stall>0&&self.windows+1==self.test_stall&&k+1==window_plan::window_rings(groups);
|
||||
if !stalled{self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10].try_borrow_mut().map_err(|_|Error::InvalidQwenShape)?.as_mut().ok_or(Error::ContextPoisoned)?.publish_u32(0,want)?;}
|
||||
}
|
||||
// Original order: compute fence, then copy-stream fence (no late flag B),
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
//! 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:
|
||||
//!
|
||||
//! * 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.
|
||||
//!
|
||||
//! 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.
|
||||
use super::*;
|
||||
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",
|
||||
];
|
||||
|
||||
/// 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
|
||||
/// graphs' lifetime with the expert source that defines them.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct OriginalVerifyExpertLayout {
|
||||
blob_bytes: [usize; WINDOW_LAYERS],
|
||||
}
|
||||
impl OriginalVerifyExpertLayout {
|
||||
pub fn new(blob_bytes: [usize; WINDOW_LAYERS], max_blob: usize) -> Result<Self> {
|
||||
if blob_bytes.iter().any(|&b| b == 0 || b % 16 != 0 || b > max_blob) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(Self { blob_bytes })
|
||||
}
|
||||
pub fn blob_bytes(&self, layer: usize) -> Result<usize> {
|
||||
self.blob_bytes.get(layer).copied().ok_or(Error::InvalidQwenShape)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.
|
||||
pub struct OriginalVerifyWindowResources<'a, 'ctx> {
|
||||
base: OriginalVerifyResources<'a, 'ctx>,
|
||||
embed: OriginalNativeEmbedRows<'ctx>,
|
||||
experts: OriginalVerifyExpertLayout,
|
||||
rows: usize,
|
||||
}
|
||||
impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
|
||||
pub fn new(
|
||||
context: &'ctx Context<'ctx>,
|
||||
base: OriginalVerifyResources<'a, 'ctx>,
|
||||
embed: OriginalNativeEmbedRows<'ctx>,
|
||||
experts: OriginalVerifyExpertLayout,
|
||||
rows: usize,
|
||||
) -> Result<Self> {
|
||||
base.validate_context(context)?;
|
||||
embed.validate_context(context)?;
|
||||
if !(1..=8).contains(&rows) || base.head.rows() != rows {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
Ok(Self { base, embed, experts, rows })
|
||||
}
|
||||
pub fn rows(&self) -> usize {
|
||||
self.rows
|
||||
}
|
||||
}
|
||||
impl resources::Sealed for OriginalVerifyWindowResources<'_, '_> {}
|
||||
impl OriginalGraphResources for OriginalVerifyWindowResources<'_, '_> {
|
||||
fn validate_context(&self, context: &Context<'_>) -> Result<()> {
|
||||
self.base.validate_context(context)?;
|
||||
self.embed.validate_context(context)
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> {
|
||||
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx> {
|
||||
self.base.verifier_qsa()
|
||||
}
|
||||
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> {
|
||||
self.base.verifier_journal()
|
||||
}
|
||||
}
|
||||
impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> {
|
||||
fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> {
|
||||
self.base.native_head_rows()
|
||||
}
|
||||
fn native_head_rows_mut(&mut self) -> Result<&mut crate::OriginalNativeHeadRows<'ctx>> {
|
||||
self.base.native_head_rows_mut()
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
}
|
||||
impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
|
||||
fn geometry(&self) -> OriginalVerifyGeometry {
|
||||
self.resources.base.journal.geometry()
|
||||
}
|
||||
fn plan(&self) -> PlanLayout {
|
||||
let g = self.geometry();
|
||||
PlanLayout::new(g.max_t * g.k)
|
||||
}
|
||||
/// Byte offset of one group's device plan copy inside the "plan" span.
|
||||
fn plan_group_offset(&self, group: usize) -> usize {
|
||||
group * self.plan().device_stride() * 4
|
||||
}
|
||||
fn journal(&self) -> &OriginalVerifyGdnJournal<'a, 'ctx> {
|
||||
&self.resources.base.journal
|
||||
}
|
||||
fn submit(&mut self, commands: Vec<Command>) -> Result<()> {
|
||||
self.resources.base.journal.submit(self.capture, commands)
|
||||
}
|
||||
/// 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();
|
||||
if group >= self.groups || word >= layout.words {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.journal().address("plan", self.plan_group_offset(group) + word * 4, 4)
|
||||
}
|
||||
fn mapped_flag(&self, index: usize) -> Result<u64> {
|
||||
self.journal().physical.mapped_address(index, 0, 4)
|
||||
}
|
||||
fn wait_flag(&mut self, flag: usize, ring: u32) -> Result<()> {
|
||||
let address = self.mapped_flag(flag)?;
|
||||
self.submit(vec![command(
|
||||
"verify_wait_flag_ge_kernel",
|
||||
[1, 1, 1],
|
||||
[1, 1, 1],
|
||||
vec![Arg::Address(address), Arg::I32(ring as i32)],
|
||||
)?])
|
||||
}
|
||||
}
|
||||
|
||||
impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
|
||||
fn embed(&mut self) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let t = self.t;
|
||||
let tokens = handle(self.resources.embed.tokens_mut()?)?.qwen_address();
|
||||
let source = self.journal().address("tok", 0, t * 4)?;
|
||||
// The embedding rows read their own staged token bank; the verifier's staged tokens are
|
||||
// copied (device to device, in capture order) into it before the gather.
|
||||
self.submit(vec![command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![Arg::Address(tokens), Arg::Address(source), Arg::I32(t as i32)],
|
||||
)?])?;
|
||||
self.resources.embed.capture(self.capture)?;
|
||||
let embedded = handle(self.resources.embed.output_device()?)?.qwen_address();
|
||||
let residual = self.journal().address("R", 0, t * g.hc * g.n * 4)?;
|
||||
self.submit(vec![command(
|
||||
"verify_broadcast_streams_kernel",
|
||||
[(g.n * g.hc).div_ceil(256) as u32, t as u32, 1],
|
||||
[256, 1, 1],
|
||||
vec![Arg::Address(embedded), Arg::Address(residual), Arg::I64(g.n as i64), Arg::I32(g.hc as i32)],
|
||||
)?])
|
||||
}
|
||||
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 hc_read(&mut self, _: usize, _: HcHalf, _: bool, _: Rows) -> Result<()> {
|
||||
unbound!("hc_read")
|
||||
}
|
||||
fn quantize_q8_1(&mut self, _: usize, _: QuantSource, _: Rows) -> Result<()> {
|
||||
unbound!("quantize_q8_1")
|
||||
}
|
||||
fn mmvq(&mut self, _: usize, _: Projection, _: Rows) -> Result<()> {
|
||||
unbound!("mmvq")
|
||||
}
|
||||
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)
|
||||
}
|
||||
fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> {
|
||||
self.resources.base.journal.capture_layer_stage(OriginalVerifyGdnStage::AlphaBeta, self.capture, layer, rows.begin, rows.end)
|
||||
}
|
||||
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_k_norm_rope(&mut self, _: usize, _: Rows, _: bool) -> Result<()> {
|
||||
unbound!("qsa_k_norm_rope")
|
||||
}
|
||||
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_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_index_q_path(&mut self, _: usize, _: Rows, _: bool) -> Result<()> {
|
||||
unbound!("qsa_index_q_path")
|
||||
}
|
||||
fn qsa_block_scores_topk(&mut self, _: usize, _: Rows) -> Result<()> {
|
||||
unbound!("qsa_block_scores_topk")
|
||||
}
|
||||
fn qsa_kv_resolve(&mut self, _: usize, _: Rows) -> Result<()> {
|
||||
unbound!("qsa_kv_resolve")
|
||||
}
|
||||
fn qsa_decode_attention(&mut self, _: usize, _: Rows) -> Result<()> {
|
||||
unbound!("qsa_decode_attention")
|
||||
}
|
||||
fn qsa_gate(&mut self, _: usize, _: Rows, _: bool) -> Result<()> {
|
||||
unbound!("qsa_gate")
|
||||
}
|
||||
fn router(&mut self, _: usize, _: Rows, _: bool) -> Result<()> {
|
||||
unbound!("router")
|
||||
}
|
||||
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 quantize_expert_input(&mut self, _: usize, _: Rows) -> Result<()> {
|
||||
unbound!("quantize_expert_input")
|
||||
}
|
||||
fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()> {
|
||||
self.wait_flag(11, ring)?;
|
||||
// The pool's GPU plan, copied from mapped host memory into this group's device block.
|
||||
let layout = self.plan();
|
||||
let device = self.journal().address("plan", self.plan_group_offset(rows.group), layout.words * 4)?;
|
||||
let mapped = self.journal().physical.mapped_address(14, rows.group * layout.mapped_stride() * 4, layout.words * 4)?;
|
||||
self.submit(vec![command(
|
||||
"verify_copy_i32_from_mapped_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
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 wait_copies(&mut self, ring: u32) -> Result<()> {
|
||||
self.wait_flag(12, ring)
|
||||
}
|
||||
fn pcie_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let layout = self.plan();
|
||||
let blob = self.resources.experts.blob_bytes(layer)?;
|
||||
let per = staging_blobs_per_group(self.groups);
|
||||
let stage_offset = rows.group * per * g.max_expert_blob;
|
||||
let stage = self.journal().address("staging", stage_offset, per * g.max_expert_blob)?;
|
||||
let source = self.plan_word(rows.group, layout.ptr2)?;
|
||||
let count = self.plan_word(rows.group, layout.counts + 2)?;
|
||||
self.submit(vec![
|
||||
command(
|
||||
"verify_fetch_blobs_kernel",
|
||||
[48 * 8, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![Arg::Address(source), Arg::Address(count), Arg::Address(stage), Arg::I64((blob / 16) as i64)],
|
||||
)?,
|
||||
command(
|
||||
"verify_rebase_ptrs_kernel",
|
||||
[1, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![Arg::Address(source), Arg::Address(count), Arg::U64(stage), Arg::I64(blob as i64)],
|
||||
)?,
|
||||
])
|
||||
}
|
||||
fn wait_cpu(&mut self, ring: u32) -> Result<()> {
|
||||
self.wait_flag(10, ring)
|
||||
}
|
||||
fn copy_cpu_rows(&mut self, rows: Rows, only_cpu_hits: bool) -> Result<()> {
|
||||
let g = self.geometry();
|
||||
let n = rows.len();
|
||||
let first = rows.begin * g.k * g.n * 4;
|
||||
let bytes = n * g.k * g.n * 4;
|
||||
let parts = self.journal().address("parts", first, bytes)?;
|
||||
let mapped = self.journal().physical.mapped_address(13, first, bytes)?;
|
||||
let command = if only_cpu_hits {
|
||||
let layout = self.plan();
|
||||
command(
|
||||
"verify_copy_rows_from_mapped_kernel",
|
||||
[(n * g.k) as u32, 1, 1],
|
||||
[128, 1, 1],
|
||||
vec![
|
||||
Arg::Address(parts),
|
||||
Arg::Address(mapped),
|
||||
Arg::I64((g.n / 4) as i64),
|
||||
Arg::Address(self.plan_word(rows.group, layout.dst)?),
|
||||
Arg::Address(self.plan_word(rows.group, layout.counts + 1)?),
|
||||
],
|
||||
)?
|
||||
} else {
|
||||
let n4 = bytes / 16;
|
||||
command(
|
||||
"verify_copy_from_mapped_kernel",
|
||||
[n4.div_ceil(256).min(64) as u32, 1, 1],
|
||||
[256, 1, 1],
|
||||
vec![Arg::Address(parts), Arg::Address(mapped), Arg::I64(n4 as i64)],
|
||||
)?
|
||||
};
|
||||
self.submit(vec![command])
|
||||
}
|
||||
fn hit_add(&mut self, _: Rows) -> Result<()> {
|
||||
unbound!("hit_add")
|
||||
}
|
||||
fn combine(&mut self, _: usize, _: Rows, _: bool) -> Result<()> {
|
||||
unbound!("combine")
|
||||
}
|
||||
fn final_write(&mut self, _: Rows) -> Result<()> {
|
||||
unbound!("final_write")
|
||||
}
|
||||
fn head(&mut self, _: usize) -> Result<()> {
|
||||
unbound!("head")
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
|
||||
/// Record the T-token window graph for `t` (split windows use two groups).
|
||||
/// `resources` is this graph's own aggregate (its head rows hold `t` rows).
|
||||
pub fn record_literal_window(
|
||||
&mut self,
|
||||
t: usize,
|
||||
resources: OriginalVerifyWindowResources<'a, 'ctx>,
|
||||
policy: WindowPolicy,
|
||||
) -> Result<()> {
|
||||
policy.validate_selected()?;
|
||||
if resources.rows() != t {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
let ple = resources.verifier_journal().has_ple();
|
||||
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 };
|
||||
record_window(&mut ops, &policy, t, groups, ple)
|
||||
})
|
||||
}
|
||||
/// Record every T = 1..=max_t window graph and the real accepted-prefix commit
|
||||
/// graph, in Original's order, BEFORE the first `run`. `window(t)` supplies each
|
||||
/// graph's aggregate. All-or-nothing: the first unbound producer or admission
|
||||
/// failure returns its error and `run` stays refused (`commit` is absent).
|
||||
pub fn record_all(
|
||||
&mut self,
|
||||
policy: WindowPolicy,
|
||||
mut window: impl FnMut(usize) -> Result<OriginalVerifyWindowResources<'a, 'ctx>>,
|
||||
commit: OriginalVerifyWindowResources<'a, 'ctx>,
|
||||
) -> Result<()> {
|
||||
policy.validate_selected()?;
|
||||
let max_t = self.bank()?.geometry().max_t;
|
||||
for t in 1..=max_t {
|
||||
self.record_literal_window(t, window(t)?, policy)?;
|
||||
}
|
||||
// The K/V half of a verifier commit is host publication of the mapped journal; the commit
|
||||
// graph itself is GDN layer replay + QSA tail restore + re-append (+ PLE history).
|
||||
self.record_commit(commit, |_, _, _| Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn expert_layout_requires_whole_16_byte_blobs_within_the_staging_bound() {
|
||||
assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 4 << 20).is_ok());
|
||||
assert!(OriginalVerifyExpertLayout::new([1 << 20; WINDOW_LAYERS], 1 << 19).is_err());
|
||||
let mut odd = [1 << 20; WINDOW_LAYERS];
|
||||
odd[7] = (1 << 20) + 8;
|
||||
assert!(OriginalVerifyExpertLayout::new(odd, 4 << 20).is_err());
|
||||
let mut zero = [1 << 20; WINDOW_LAYERS];
|
||||
zero[0] = 0;
|
||||
assert!(OriginalVerifyExpertLayout::new(zero, 4 << 20).is_err());
|
||||
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,261 @@
|
||||
//! Pure Verifier window schedule (verify.cpp `record_window` ordering, `run`
|
||||
//! ring numbers and group bounds). No driver object: this is the order the
|
||||
//! recorded graph, the doorbell loop in `OriginalVerifier::run` and the CPU
|
||||
//! pool callbacks must all agree on.
|
||||
//!
|
||||
//! Plan v0.3 P6 (split window): with two groups A=[0,ceil(T/2)) and B=rest the
|
||||
//! stream is
|
||||
//!
|
||||
//! ```text
|
||||
//! pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B) | post(1,A) pre(2,A) | ...
|
||||
//! ```
|
||||
//!
|
||||
//! so the CPU computes A's experts of layer l while the GPU runs B's mixer and
|
||||
//! router of layer l. Every token's arithmetic is unchanged.
|
||||
|
||||
/// Layers of the whole-model window (no layer split: single-GPU target).
|
||||
pub const WINDOW_LAYERS: usize = 48;
|
||||
/// QSA layers are every fourth layer starting at 3; the rest are GDN.
|
||||
pub const fn is_qsa_layer(layer: usize) -> bool {
|
||||
layer % 4 == 3
|
||||
}
|
||||
/// Index of a GDN layer among the 36 GDN layers (`None` for a QSA layer).
|
||||
pub const fn gdn_index(layer: usize) -> Option<usize> {
|
||||
if is_qsa_layer(layer) { None } else { Some(layer - layer / 4) }
|
||||
}
|
||||
/// Index of a QSA layer among the 12 QSA layers (`None` for a GDN layer).
|
||||
pub const fn qsa_index(layer: usize) -> Option<usize> {
|
||||
if is_qsa_layer(layer) { Some(layer / 4) } else { None }
|
||||
}
|
||||
|
||||
/// Groups of a T-token window: split windows of at least two rows use two.
|
||||
pub const fn window_groups(t: usize, split: bool) -> usize {
|
||||
if split && t >= 2 { 2 } else { 1 }
|
||||
}
|
||||
/// Row range `[tb, te)` of group `grp` (`tb_`/`te_` of `record_window`).
|
||||
pub const fn group_rows(t: usize, groups: usize, grp: usize) -> (usize, usize) {
|
||||
let tb = if grp == 0 { 0 } else { t.div_ceil(2) };
|
||||
let te = if grp == 1 || groups == 1 { t } else { t.div_ceil(2) };
|
||||
(tb, te)
|
||||
}
|
||||
/// Doorbell / flag ring of `(layer, group)`; `run` waits for the same value
|
||||
/// (`want = k + 1`, `k = layer * groups + group`). Layer 0 is the first layer.
|
||||
pub const fn ring(layer: usize, groups: usize, grp: usize) -> u32 {
|
||||
(layer * groups + grp + 1) as u32
|
||||
}
|
||||
/// Total doorbell rings of a window.
|
||||
pub const fn window_rings(groups: usize) -> usize {
|
||||
WINDOW_LAYERS * groups
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Phase {
|
||||
/// Everything up to the ring: hc read, mixer, out-projection, FFN read,
|
||||
/// router, doorbell, shared expert, activation quantization.
|
||||
Pre,
|
||||
/// Plan wait, VRAM/PCIe expert groups, CPU wait, hit add, combine.
|
||||
Post,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Step {
|
||||
pub phase: Phase,
|
||||
pub layer: usize,
|
||||
pub group: usize,
|
||||
}
|
||||
/// The recorded order of `pre`/`post` over all layers and groups.
|
||||
pub fn schedule(groups: usize, layers: usize) -> Vec<Step> {
|
||||
let mut steps = Vec::with_capacity(2 * groups * layers);
|
||||
for group in 0..groups {
|
||||
steps.push(Step { phase: Phase::Pre, layer: 0, group });
|
||||
}
|
||||
for layer in 0..layers {
|
||||
for group in 0..groups {
|
||||
steps.push(Step { phase: Phase::Post, layer, group });
|
||||
if layer + 1 < layers {
|
||||
steps.push(Step { phase: Phase::Pre, layer: layer + 1, group });
|
||||
}
|
||||
}
|
||||
}
|
||||
steps
|
||||
}
|
||||
|
||||
/// Staging blobs per window group: a split window halves the 16 staged blobs.
|
||||
pub const STAGING_BLOBS: usize = 16;
|
||||
pub const fn staging_blobs_per_group(groups: usize) -> usize {
|
||||
if groups == 2 { STAGING_BLOBS / 2 } else { STAGING_BLOBS }
|
||||
}
|
||||
|
||||
/// Word offsets (int32 units) inside ONE group's GPU plan block, exactly the
|
||||
/// `counts | start | dst | tok | pad | ptr | ptr2 | start2` carve of
|
||||
/// `Verifier::init` for `capx = max_t * k` entries. `ptr`/`ptr2` are u64 arrays
|
||||
/// (two words per entry); counts[0] is the VRAM group count, [1] the number of
|
||||
/// GPU hit entries (the `p_counts + 1` of `copy_rows_from_mapped`), [2] the PCIe
|
||||
/// group count (`p_counts + 2`).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PlanLayout {
|
||||
pub counts: usize,
|
||||
pub start: usize,
|
||||
pub dst: usize,
|
||||
pub tok: usize,
|
||||
pub ptr: usize,
|
||||
pub ptr2: usize,
|
||||
pub start2: usize,
|
||||
/// int32 words of the block as staged from mapped host memory.
|
||||
pub words: usize,
|
||||
}
|
||||
impl PlanLayout {
|
||||
pub const fn new(capx: usize) -> Self {
|
||||
let start = 4;
|
||||
let dst = start + capx + 1;
|
||||
let tok = dst + capx;
|
||||
let ptr = (4 + (capx + 1) + 2 * capx + 1) & !1;
|
||||
let ptr2 = ptr + 2 * capx;
|
||||
let start2 = ptr + 4 * capx;
|
||||
Self { counts: 0, start, dst, tok, ptr, ptr2, start2, words: start2 + capx + 2 }
|
||||
}
|
||||
/// Distance in words between two groups' device copies (`plan_i32 + 16`).
|
||||
pub const fn device_stride(&self) -> usize {
|
||||
self.words + 16
|
||||
}
|
||||
/// Distance in words between two groups' mapped blocks (`plan_i32`).
|
||||
pub const fn mapped_stride(&self) -> usize {
|
||||
self.words
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn layer_kinds_follow_the_qwen_pattern() {
|
||||
let qsa: Vec<usize> = (0..WINDOW_LAYERS).filter(|&l| is_qsa_layer(l)).collect();
|
||||
assert_eq!(qsa, [3, 7, 11, 15, 19, 23, 27, 31, 35, 39, 43, 47]);
|
||||
let gdn: Vec<usize> = (0..WINDOW_LAYERS).filter_map(gdn_index).collect();
|
||||
assert_eq!(gdn, (0..36).collect::<Vec<_>>(), "GDN indices are dense and ordered");
|
||||
let q: Vec<usize> = (0..WINDOW_LAYERS).filter_map(qsa_index).collect();
|
||||
assert_eq!(q, (0..12).collect::<Vec<_>>());
|
||||
assert_eq!((gdn_index(4), gdn_index(3), qsa_index(3), qsa_index(4)), (Some(3), None, Some(0), None));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_and_row_bounds_match_record_window() {
|
||||
assert_eq!(window_groups(1, true), 1);
|
||||
assert_eq!(window_groups(2, true), 2);
|
||||
assert_eq!(window_groups(8, false), 1);
|
||||
for t in 1..=8usize {
|
||||
// one group covers everything
|
||||
assert_eq!(group_rows(t, 1, 0), (0, t));
|
||||
if t >= 2 {
|
||||
let (a0, a1) = group_rows(t, 2, 0);
|
||||
let (b0, b1) = group_rows(t, 2, 1);
|
||||
assert_eq!((a0, b1), (0, t));
|
||||
assert_eq!(a1, b0, "the groups tile the window without a gap");
|
||||
assert_eq!(a1, t.div_ceil(2), "group A takes the larger half");
|
||||
}
|
||||
}
|
||||
assert_eq!(group_rows(5, 2, 0), (0, 3));
|
||||
assert_eq!(group_rows(5, 2, 1), (3, 5));
|
||||
assert_eq!(group_rows(2, 2, 1), (1, 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rings_are_one_based_layer_major_and_match_the_run_loop() {
|
||||
assert_eq!(ring(0, 1, 0), 1);
|
||||
assert_eq!(ring(47, 1, 0), 48);
|
||||
assert_eq!(ring(0, 2, 0), 1);
|
||||
assert_eq!(ring(0, 2, 1), 2);
|
||||
assert_eq!(ring(47, 2, 1), 96);
|
||||
assert_eq!(window_rings(2), 96);
|
||||
// run's k -> (layer, group) mapping produces exactly these rings
|
||||
for groups in [1usize, 2] {
|
||||
for k in 0..window_rings(groups) {
|
||||
assert_eq!(ring(k / groups, groups, k % groups) as usize, k + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_group_schedule_alternates_pre_post_per_layer() {
|
||||
let s = schedule(1, 3);
|
||||
let kinds: Vec<(Phase, usize)> = s.iter().map(|x| (x.phase, x.layer)).collect();
|
||||
assert_eq!(
|
||||
kinds,
|
||||
[(Phase::Pre, 0), (Phase::Post, 0), (Phase::Pre, 1), (Phase::Post, 1), (Phase::Pre, 2), (Phase::Post, 2)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_schedule_pipelines_cpu_experts_of_one_group_with_gpu_work_of_the_other() {
|
||||
let s = schedule(2, 3);
|
||||
let text: Vec<String> = s
|
||||
.iter()
|
||||
.map(|x| format!("{}{}{}", if x.phase == Phase::Pre { "pre" } else { "post" }, x.layer, ['A', 'B'][x.group]))
|
||||
.collect();
|
||||
assert_eq!(
|
||||
text,
|
||||
["pre0A", "pre0B", "post0A", "pre1A", "post0B", "pre1B", "post1A", "pre2A", "post1B", "pre2B", "post2A", "post2B"]
|
||||
);
|
||||
// B's mixer of layer l never precedes A's mixer of the same layer, and no group's post
|
||||
// precedes its own pre
|
||||
for l in 0..3 {
|
||||
for g in 0..2 {
|
||||
let pre = s.iter().position(|x| *x == Step { phase: Phase::Pre, layer: l, group: g }).unwrap();
|
||||
let post = s.iter().position(|x| *x == Step { phase: Phase::Post, layer: l, group: g }).unwrap();
|
||||
assert!(pre < post);
|
||||
}
|
||||
let a = s.iter().position(|x| *x == Step { phase: Phase::Pre, layer: l, group: 0 }).unwrap();
|
||||
let b = s.iter().position(|x| *x == Step { phase: Phase::Pre, layer: l, group: 1 }).unwrap();
|
||||
assert!(a < b);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_window_schedule_covers_every_layer_and_group_once() {
|
||||
for groups in [1usize, 2] {
|
||||
let s = schedule(groups, WINDOW_LAYERS);
|
||||
assert_eq!(s.len(), 2 * groups * WINDOW_LAYERS);
|
||||
for l in 0..WINDOW_LAYERS {
|
||||
for g in 0..groups {
|
||||
for p in [Phase::Pre, Phase::Post] {
|
||||
assert_eq!(s.iter().filter(|x| **x == Step { phase: p, layer: l, group: g }).count(), 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// the doorbell rings come out in order as the stream reaches each post
|
||||
let posts: Vec<u32> =
|
||||
s.iter().filter(|x| x.phase == Phase::Post).map(|x| ring(x.layer, groups, x.group)).collect();
|
||||
assert_eq!(posts, (1..=window_rings(groups) as u32).collect::<Vec<_>>());
|
||||
// and the GPU rings the host in the same order from the pre side (one doorbell per pre)
|
||||
let pres: Vec<u32> =
|
||||
s.iter().filter(|x| x.phase == Phase::Pre).map(|x| ring(x.layer, groups, x.group)).collect();
|
||||
assert_eq!(pres, posts);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_block_matches_the_init_carve_for_every_window_size() {
|
||||
// the same arithmetic as the driver layout (`OriginalVerifyLayout::new`)
|
||||
for t in 2..=8usize {
|
||||
let cap = t * 10;
|
||||
let l = PlanLayout::new(cap);
|
||||
let ptr_off = (4 + (cap + 1) + cap + cap + 1) & !1;
|
||||
assert_eq!(l.ptr, ptr_off);
|
||||
assert_eq!(l.words, ptr_off + 4 * cap + (cap + 2));
|
||||
assert_eq!(l.ptr % 2, 0, "the u64 arrays are 8-byte aligned");
|
||||
assert_eq!((l.counts, l.start, l.dst), (0, 4, 4 + cap + 1));
|
||||
assert_eq!(l.tok, l.dst + cap);
|
||||
assert!(l.tok + cap <= l.ptr, "the int tables end before the pointer arrays");
|
||||
assert_eq!(l.ptr2, l.ptr + 2 * cap);
|
||||
assert_eq!(l.start2, l.ptr + 4 * cap);
|
||||
assert_eq!(l.device_stride(), l.words + 16);
|
||||
assert_eq!(l.mapped_stride(), l.words);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staging_is_split_between_the_two_groups() {
|
||||
assert_eq!(staging_blobs_per_group(1), 16);
|
||||
assert_eq!(staging_blobs_per_group(2), 8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,611 @@
|
||||
//! The literal `Verifier::record_window` call sequence, expressed over a
|
||||
//! `WindowOps` producer set. The recorder owns ORDER only (which producer runs
|
||||
//! when, on which rows, with which ring and stamp); every arithmetic kernel
|
||||
//! belongs to a producer, so a window can never be assembled from prompt-GEMM
|
||||
//! or per-token forward substitutes. Pure: it is unit-tested with a trace
|
||||
//! producer, and the real producer (`OriginalVerifyWindowOps`) fails closed on
|
||||
//! any kernel family that has no genuine capturable owner yet.
|
||||
use super::window_plan::{
|
||||
Phase, WINDOW_LAYERS, gdn_index, group_rows, is_qsa_layer, qsa_index, ring, schedule,
|
||||
};
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Rows `[begin, end)` of one split-window group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Rows {
|
||||
pub begin: usize,
|
||||
pub end: usize,
|
||||
pub group: usize,
|
||||
}
|
||||
impl Rows {
|
||||
pub fn len(&self) -> usize {
|
||||
self.end - self.begin
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.end == self.begin
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum HcHalf {
|
||||
/// `hc_attn_*`: reads the residual before the mixer.
|
||||
Attention,
|
||||
/// `hc_ffn_*`: reads after the mixer's write was folded in.
|
||||
Ffn,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum QuantSource {
|
||||
/// `mixed_` (the hc read output).
|
||||
Mixed,
|
||||
/// GDN `y_` (the gated delta-net output norm).
|
||||
GdnY,
|
||||
/// QSA gated attention `attn32_`.
|
||||
Attention,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Projection {
|
||||
GdnQkv,
|
||||
GdnGate,
|
||||
GdnOut,
|
||||
QsaK,
|
||||
QsaV,
|
||||
QsaQ,
|
||||
QsaOut,
|
||||
}
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum ExpertTier {
|
||||
/// Experts resident in the VRAM tier (`p_ptr`, `p_start`, `p_counts`).
|
||||
Vram,
|
||||
/// The PCIe share, staged by DMA, a copy kernel or read mapped (`p_ptr2`...).
|
||||
Pcie,
|
||||
}
|
||||
|
||||
/// Process-wide Original configuration fixed before any capture. The selected
|
||||
/// mode17 values are `WindowPolicy::mode17()`; anything the recorder cannot
|
||||
/// reproduce literally is refused by `validate_selected`, never approximated.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct WindowPolicy {
|
||||
/// STRATA_DEC_BATCH (default on): one multi-row launch where the single-row
|
||||
/// arithmetic is identical.
|
||||
pub dec_batch: bool,
|
||||
pub native_router: bool,
|
||||
pub native_combine: bool,
|
||||
/// `expert_layout().native`: GGUF-format experts (else S2 Q8_0 scaled).
|
||||
pub native_experts: bool,
|
||||
/// `Verifier::set_pcie_mode`: 0 DMA to staging, 1 mapped arena, 2 copy kernel.
|
||||
pub pcie_mode: u8,
|
||||
/// STRATA_VERIFY_DEVICE_PLAN (E-6): resident-only layers planned on the device.
|
||||
pub device_plan: bool,
|
||||
/// A control vector covering any layer.
|
||||
pub cvec: bool,
|
||||
/// KV formats other than the canonical INT8 pools (q4 / hybrid / rotated).
|
||||
pub non_int8_kv: bool,
|
||||
/// Keyless / traced / layer-split variants.
|
||||
pub variant: bool,
|
||||
}
|
||||
impl WindowPolicy {
|
||||
pub const fn mode17() -> Self {
|
||||
Self {
|
||||
dec_batch: true,
|
||||
native_router: true,
|
||||
native_combine: true,
|
||||
native_experts: true,
|
||||
pcie_mode: 0,
|
||||
device_plan: false,
|
||||
cvec: false,
|
||||
non_int8_kv: false,
|
||||
variant: false,
|
||||
}
|
||||
}
|
||||
pub fn validate_selected(&self) -> Result<()> {
|
||||
if self.pcie_mode > 2 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
if self.device_plan || self.cvec || self.non_int8_kv || self.variant {
|
||||
return Err(Error::UnsupportedQwenOperation);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// One producer per Strata call of `record_window`. Implementations enqueue onto
|
||||
/// the actual capture stream of the T-window graph; they may refuse (fail
|
||||
/// closed) but must never substitute different arithmetic.
|
||||
pub trait WindowOps {
|
||||
/// Embedding gather of the staged tokens broadcast to the hc streams.
|
||||
fn embed(&mut self) -> Result<()>;
|
||||
/// `gpu_stamp` (STRATA_VERIFY_PROFILE); the recorder calls it for group 0 only.
|
||||
fn stamp(&mut self, layer: usize, stage: usize) -> Result<()>;
|
||||
/// Layer 1 PLE block per token: pending write, `ple_block`, history advance, snapshot.
|
||||
fn ple_layer1(&mut self, rows: Rows) -> Result<()>;
|
||||
/// Fused hyper-connection read. `apply` folds the previous layer's pending write.
|
||||
fn hc_read(&mut self, layer: usize, half: HcHalf, apply: bool, rows: Rows) -> Result<()>;
|
||||
fn quantize_q8_1(&mut self, layer: usize, source: QuantSource, rows: Rows) -> Result<()>;
|
||||
fn mmvq(&mut self, layer: usize, projection: Projection, rows: Rows) -> Result<()>;
|
||||
// ---- GDN (journal-owned conv / alpha-beta / recurrence)
|
||||
fn gdn_conv(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
// ---- QSA (`batched` = STRATA_DEC_BATCH && n > 1 && native QSA/RoPE && !kv_q4)
|
||||
fn qsa_index_k(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
fn qsa_k_norm_rope(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
fn qsa_tail_snapshot(&mut self, layer: usize) -> Result<()>;
|
||||
fn qsa_kv_append(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn qsa_indexer_append(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
/// q/gate split + q norm + RoPE.
|
||||
fn qsa_q_path(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
/// indexer query projection + norm + RoPE.
|
||||
fn qsa_index_q_path(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
fn qsa_block_scores_topk(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn qsa_kv_resolve(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn qsa_decode_attention(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn qsa_gate(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
// ---- FFN
|
||||
/// Router logits + top-10 (multi-row only when `batched`).
|
||||
fn router(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
/// Group doorbell: publishes the layer's mixed/ids/weights to the mapped rows.
|
||||
fn doorbell(&mut self, rows: Rows) -> Result<()>;
|
||||
fn shared_expert(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
/// Activation quantization consumed by the routed experts (nat q8_1 / S2 q8_0 scaled).
|
||||
fn quantize_expert_input(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
// ---- post
|
||||
/// `wait_flag_ge(flag A, ring)` then the mapped plan block copy.
|
||||
fn wait_plan(&mut self, ring: u32, rows: Rows) -> Result<()>;
|
||||
fn expert_groups(&mut self, layer: usize, rows: Rows, tier: ExpertTier) -> Result<()>;
|
||||
fn wait_copies(&mut self, ring: u32) -> Result<()>;
|
||||
/// `pcie_mode == 2`: stage the PCIe blobs with a copy kernel and rebase pointers.
|
||||
fn pcie_stage(&mut self, layer: usize, rows: Rows) -> Result<()>;
|
||||
fn wait_cpu(&mut self, ring: u32) -> Result<()>;
|
||||
/// Only the CPU rows cross PCIe when `dec_batch`.
|
||||
fn copy_cpu_rows(&mut self, rows: Rows, only_cpu_hits: bool) -> Result<()>;
|
||||
fn hit_add(&mut self, rows: Rows) -> Result<()>;
|
||||
fn combine(&mut self, layer: usize, rows: Rows, batched: bool) -> Result<()>;
|
||||
/// The final layer's residual write per token (no control vector).
|
||||
fn final_write(&mut self, rows: Rows) -> Result<()>;
|
||||
/// `output_hc_*` mixing per token, then quantize ALL T, MMVQ ALL T, greedy argmax.
|
||||
fn head(&mut self, rows: usize) -> Result<()>;
|
||||
}
|
||||
|
||||
/// Record one T-token window onto `ops`, exactly in the order of
|
||||
/// `Verifier::record_window` (inputs are captured by the caller).
|
||||
pub fn record_window<O: WindowOps>(
|
||||
ops: &mut O,
|
||||
policy: &WindowPolicy,
|
||||
t: usize,
|
||||
groups: usize,
|
||||
ple: bool,
|
||||
) -> Result<()> {
|
||||
policy.validate_selected()?;
|
||||
if !(1..=8).contains(&t) || !(1..=2).contains(&groups) || (groups == 2 && t < 2) {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
ops.embed()?;
|
||||
for step in schedule(groups, WINDOW_LAYERS) {
|
||||
let (begin, end) = group_rows(t, groups, step.group);
|
||||
let rows = Rows { begin, end, group: step.group };
|
||||
match step.phase {
|
||||
Phase::Pre => pre(ops, policy, ple, step.layer, rows)?,
|
||||
Phase::Post => post(ops, policy, groups, step.layer, rows)?,
|
||||
}
|
||||
}
|
||||
ops.stamp(WINDOW_LAYERS, 0)?;
|
||||
ops.head(t)?;
|
||||
ops.stamp(WINDOW_LAYERS, 1)
|
||||
}
|
||||
|
||||
fn stamp<O: WindowOps>(ops: &mut O, layer: usize, stage: usize, rows: Rows) -> Result<()> {
|
||||
if rows.group == 0 { ops.stamp(layer, stage) } else { Ok(()) }
|
||||
}
|
||||
|
||||
fn pre<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, ple: bool, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
stamp(ops, l, 0, rows)?;
|
||||
// The previous layer's FFN write, folded into this layer's first read.
|
||||
let mut pending = l > 0;
|
||||
if l == 1 && ple {
|
||||
ops.ple_layer1(rows)?;
|
||||
pending = false;
|
||||
}
|
||||
ops.hc_read(l, HcHalf::Attention, pending, rows)?;
|
||||
stamp(ops, l, 1, rows)?;
|
||||
if !is_qsa_layer(l) {
|
||||
let g = gdn_index(l).ok_or(Error::InvalidQwenShape)?;
|
||||
ops.quantize_q8_1(l, QuantSource::Mixed, rows)?;
|
||||
ops.mmvq(l, Projection::GdnQkv, rows)?;
|
||||
stamp(ops, l, 2, rows)?;
|
||||
ops.gdn_conv(g, rows)?;
|
||||
stamp(ops, l, 3, rows)?;
|
||||
ops.gdn_alpha_beta(g, rows)?;
|
||||
stamp(ops, l, 4, rows)?;
|
||||
ops.mmvq(l, Projection::GdnGate, rows)?;
|
||||
stamp(ops, l, 5, rows)?;
|
||||
ops.gdn_recurrence(g, rows)?;
|
||||
stamp(ops, l, 6, rows)?;
|
||||
ops.quantize_q8_1(l, QuantSource::GdnY, rows)?;
|
||||
ops.mmvq(l, Projection::GdnOut, rows)?;
|
||||
} else {
|
||||
let q = qsa_index(l).ok_or(Error::InvalidQwenShape)?;
|
||||
let batched = policy.dec_batch && n > 1;
|
||||
ops.quantize_q8_1(l, QuantSource::Mixed, rows)?;
|
||||
ops.qsa_index_k(q, rows, batched)?;
|
||||
stamp(ops, l, 7, rows)?;
|
||||
ops.mmvq(l, Projection::QsaK, rows)?;
|
||||
ops.mmvq(l, Projection::QsaV, rows)?;
|
||||
ops.qsa_k_norm_rope(q, rows, batched)?;
|
||||
stamp(ops, l, 8, rows)?;
|
||||
if rows.group == 0 {
|
||||
ops.qsa_tail_snapshot(q)?;
|
||||
}
|
||||
ops.qsa_kv_append(q, rows)?;
|
||||
ops.qsa_indexer_append(q, rows)?;
|
||||
stamp(ops, l, 9, rows)?;
|
||||
ops.mmvq(l, Projection::QsaQ, rows)?;
|
||||
ops.qsa_q_path(q, rows, batched)?;
|
||||
ops.qsa_index_q_path(q, rows, batched)?;
|
||||
stamp(ops, l, 10, rows)?;
|
||||
ops.qsa_block_scores_topk(q, rows)?;
|
||||
stamp(ops, l, 11, rows)?;
|
||||
ops.qsa_kv_resolve(q, rows)?;
|
||||
stamp(ops, l, 12, rows)?;
|
||||
ops.qsa_decode_attention(q, rows)?;
|
||||
stamp(ops, l, 13, rows)?;
|
||||
ops.qsa_gate(q, rows, batched)?;
|
||||
stamp(ops, l, 14, rows)?;
|
||||
ops.quantize_q8_1(l, QuantSource::Attention, rows)?;
|
||||
ops.mmvq(l, Projection::QsaOut, rows)?;
|
||||
}
|
||||
stamp(ops, l, 16, rows)?;
|
||||
ops.hc_read(l, HcHalf::Ffn, true, rows)?;
|
||||
// One router launch pair for the window's rows (NE == 512, K == 10) instead of 2 per token.
|
||||
ops.router(l, rows, policy.dec_batch && n > 1 && policy.native_router)?;
|
||||
ops.doorbell(rows)?;
|
||||
stamp(ops, l, 17, rows)?;
|
||||
ops.shared_expert(l, rows, policy.dec_batch)?;
|
||||
ops.quantize_expert_input(l, rows)?;
|
||||
stamp(ops, l, 18, rows)
|
||||
}
|
||||
|
||||
fn post<O: WindowOps>(ops: &mut O, policy: &WindowPolicy, groups: usize, l: usize, rows: Rows) -> Result<()> {
|
||||
let n = rows.len();
|
||||
let ring = ring(l, groups, rows.group);
|
||||
ops.wait_plan(ring, rows)?;
|
||||
stamp(ops, l, 19, rows)?;
|
||||
ops.expert_groups(l, rows, ExpertTier::Vram)?;
|
||||
stamp(ops, l, 20, rows)?;
|
||||
ops.wait_copies(ring)?;
|
||||
if policy.pcie_mode == 2 {
|
||||
ops.pcie_stage(l, rows)?;
|
||||
}
|
||||
stamp(ops, l, 21, rows)?;
|
||||
ops.expert_groups(l, rows, ExpertTier::Pcie)?;
|
||||
stamp(ops, l, 22, rows)?;
|
||||
ops.wait_cpu(ring)?;
|
||||
stamp(ops, l, 23, rows)?;
|
||||
ops.copy_cpu_rows(rows, policy.dec_batch)?;
|
||||
ops.hit_add(rows)?;
|
||||
ops.combine(l, rows, policy.dec_batch && n > 1 && policy.native_combine)?;
|
||||
stamp(ops, l, 24, rows)?;
|
||||
if l == WINDOW_LAYERS - 1 {
|
||||
ops.final_write(rows)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct Trace {
|
||||
log: Vec<String>,
|
||||
fail_at: Option<String>,
|
||||
}
|
||||
impl Trace {
|
||||
fn note(&mut self, s: String) -> Result<()> {
|
||||
let fail = self.fail_at.as_deref().is_some_and(|f| s.split_whitespace().next() == Some(f));
|
||||
self.log.push(s);
|
||||
if fail { Err(Error::InvalidDriverValue("trace")) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
fn r(rows: Rows) -> String {
|
||||
format!("{}..{}g{}", rows.begin, rows.end, rows.group)
|
||||
}
|
||||
impl WindowOps for Trace {
|
||||
fn embed(&mut self) -> Result<()> { self.note("embed".into()) }
|
||||
fn stamp(&mut self, l: usize, s: usize) -> Result<()> { self.note(format!("stamp {l}.{s}")) }
|
||||
fn ple_layer1(&mut self, x: Rows) -> Result<()> { self.note(format!("ple {}", r(x))) }
|
||||
fn hc_read(&mut self, l: usize, h: HcHalf, a: bool, x: Rows) -> Result<()> {
|
||||
self.note(format!("hc {l} {:?} apply={a} {}", h, r(x)))
|
||||
}
|
||||
fn quantize_q8_1(&mut self, l: usize, s: QuantSource, x: Rows) -> Result<()> { self.note(format!("quant {l} {s:?} {}", r(x))) }
|
||||
fn mmvq(&mut self, l: usize, p: Projection, x: Rows) -> Result<()> { self.note(format!("mmvq {l} {p:?} {}", r(x))) }
|
||||
fn gdn_conv(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("conv g{g} {}", r(x))) }
|
||||
fn gdn_alpha_beta(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("ab g{g} {}", r(x))) }
|
||||
fn gdn_recurrence(&mut self, g: usize, x: Rows) -> Result<()> { self.note(format!("rec g{g} {}", r(x))) }
|
||||
fn qsa_index_k(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("idxk q{q} {} b={b}", r(x))) }
|
||||
fn qsa_k_norm_rope(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("knr q{q} {} b={b}", r(x))) }
|
||||
fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> { self.note(format!("tail q{q}")) }
|
||||
fn qsa_kv_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("kv q{q} {}", r(x))) }
|
||||
fn qsa_indexer_append(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("iapp q{q} {}", r(x))) }
|
||||
fn qsa_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("qpath q{q} {} b={b}", r(x))) }
|
||||
fn qsa_index_q_path(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("iqpath q{q} {} b={b}", r(x))) }
|
||||
fn qsa_block_scores_topk(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("scores q{q} {}", r(x))) }
|
||||
fn qsa_kv_resolve(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("resolve q{q} {}", r(x))) }
|
||||
fn qsa_decode_attention(&mut self, q: usize, x: Rows) -> Result<()> { self.note(format!("attn q{q} {}", r(x))) }
|
||||
fn qsa_gate(&mut self, q: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("gate q{q} {} b={b}", r(x))) }
|
||||
fn router(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("router {l} {} b={b}", r(x))) }
|
||||
fn doorbell(&mut self, x: Rows) -> Result<()> { self.note(format!("doorbell {}", r(x))) }
|
||||
fn shared_expert(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("shared {l} {} b={b}", r(x))) }
|
||||
fn quantize_expert_input(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("xq {l} {}", r(x))) }
|
||||
fn wait_plan(&mut self, ring: u32, x: Rows) -> Result<()> { self.note(format!("waitA {ring} {}", r(x))) }
|
||||
fn expert_groups(&mut self, l: usize, x: Rows, t: ExpertTier) -> Result<()> { self.note(format!("experts {l} {t:?} {}", r(x))) }
|
||||
fn wait_copies(&mut self, ring: u32) -> Result<()> { self.note(format!("waitB {ring}")) }
|
||||
fn pcie_stage(&mut self, l: usize, x: Rows) -> Result<()> { self.note(format!("stage {l} {}", r(x))) }
|
||||
fn wait_cpu(&mut self, ring: u32) -> Result<()> { self.note(format!("waitM {ring}")) }
|
||||
fn copy_cpu_rows(&mut self, x: Rows, only: bool) -> Result<()> { self.note(format!("cpurows {} only={only}", r(x))) }
|
||||
fn hit_add(&mut self, x: Rows) -> Result<()> { self.note(format!("hitadd {}", r(x))) }
|
||||
fn combine(&mut self, l: usize, x: Rows, b: bool) -> Result<()> { self.note(format!("combine {l} {} b={b}", r(x))) }
|
||||
fn final_write(&mut self, x: Rows) -> Result<()> { self.note(format!("final {}", r(x))) }
|
||||
fn head(&mut self, t: usize) -> Result<()> { self.note(format!("head {t}")) }
|
||||
}
|
||||
|
||||
fn record(t: usize, groups: usize, ple: bool) -> Vec<String> {
|
||||
let mut o = Trace::default();
|
||||
record_window(&mut o, &WindowPolicy::mode17(), t, groups, ple).unwrap();
|
||||
o.log
|
||||
}
|
||||
fn index_of(log: &[String], prefix: &str) -> usize {
|
||||
log.iter().position(|s| s.starts_with(prefix)).unwrap_or_else(|| panic!("{prefix} missing"))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn policy_refuses_what_it_cannot_reproduce_literally() {
|
||||
let mut p = WindowPolicy::mode17();
|
||||
assert!(p.validate_selected().is_ok());
|
||||
for f in [
|
||||
|p: &mut WindowPolicy| p.device_plan = true,
|
||||
|p: &mut WindowPolicy| p.cvec = true,
|
||||
|p: &mut WindowPolicy| p.non_int8_kv = true,
|
||||
|p: &mut WindowPolicy| p.variant = true,
|
||||
] {
|
||||
let mut q = p;
|
||||
f(&mut q);
|
||||
assert_eq!(q.validate_selected(), Err(Error::UnsupportedQwenOperation));
|
||||
}
|
||||
p.pcie_mode = 3;
|
||||
assert_eq!(p.validate_selected(), Err(Error::InvalidQwenShape));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_invalid_window_shapes() {
|
||||
let mut o = Trace::default();
|
||||
let p = WindowPolicy::mode17();
|
||||
assert!(record_window(&mut o, &p, 0, 1, false).is_err());
|
||||
assert!(record_window(&mut o, &p, 9, 1, false).is_err());
|
||||
assert!(record_window(&mut o, &p, 1, 2, false).is_err());
|
||||
assert!(record_window(&mut o, &p, 4, 3, false).is_err());
|
||||
assert!(o.log.is_empty(), "nothing is recorded before the shape is admitted");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gdn_layer_runs_the_literal_pre_sequence() {
|
||||
let log = record(3, 1, false);
|
||||
// layer 0 (GDN): stamps 0..6 interleaved with the producers, no pending write, then out-projection
|
||||
let first: Vec<&str> = log.iter().map(String::as_str).skip(1).take(17).collect();
|
||||
assert_eq!(
|
||||
first,
|
||||
[
|
||||
"stamp 0.0",
|
||||
"hc 0 Attention apply=false 0..3g0",
|
||||
"stamp 0.1",
|
||||
"quant 0 Mixed 0..3g0",
|
||||
"mmvq 0 GdnQkv 0..3g0",
|
||||
"stamp 0.2",
|
||||
"conv g0 0..3g0",
|
||||
"stamp 0.3",
|
||||
"ab g0 0..3g0",
|
||||
"stamp 0.4",
|
||||
"mmvq 0 GdnGate 0..3g0",
|
||||
"stamp 0.5",
|
||||
"rec g0 0..3g0",
|
||||
"stamp 0.6",
|
||||
"quant 0 GdnY 0..3g0",
|
||||
"mmvq 0 GdnOut 0..3g0",
|
||||
"stamp 0.16"
|
||||
]
|
||||
);
|
||||
assert_eq!(log[0], "embed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qsa_layer_runs_the_literal_pre_sequence_with_batched_rows() {
|
||||
let log = record(4, 1, false);
|
||||
let start = index_of(&log, "stamp 3.0");
|
||||
let end = index_of(&log, "stamp 3.16") + 1;
|
||||
let seq: Vec<&str> = log[start..end].iter().map(String::as_str).collect();
|
||||
assert_eq!(
|
||||
seq,
|
||||
[
|
||||
"stamp 3.0",
|
||||
"hc 3 Attention apply=true 0..4g0",
|
||||
"stamp 3.1",
|
||||
"quant 3 Mixed 0..4g0",
|
||||
"idxk q0 0..4g0 b=true",
|
||||
"stamp 3.7",
|
||||
"mmvq 3 QsaK 0..4g0",
|
||||
"mmvq 3 QsaV 0..4g0",
|
||||
"knr q0 0..4g0 b=true",
|
||||
"stamp 3.8",
|
||||
"tail q0",
|
||||
"kv q0 0..4g0",
|
||||
"iapp q0 0..4g0",
|
||||
"stamp 3.9",
|
||||
"mmvq 3 QsaQ 0..4g0",
|
||||
"qpath q0 0..4g0 b=true",
|
||||
"iqpath q0 0..4g0 b=true",
|
||||
"stamp 3.10",
|
||||
"scores q0 0..4g0",
|
||||
"stamp 3.11",
|
||||
"resolve q0 0..4g0",
|
||||
"stamp 3.12",
|
||||
"attn q0 0..4g0",
|
||||
"stamp 3.13",
|
||||
"gate q0 0..4g0 b=true",
|
||||
"stamp 3.14",
|
||||
"quant 3 Attention 0..4g0",
|
||||
"mmvq 3 QsaOut 0..4g0",
|
||||
"stamp 3.16"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_row_windows_are_never_batched() {
|
||||
let log = record(1, 1, false);
|
||||
assert!(log.iter().any(|s| s == "idxk q0 0..1g0 b=false"));
|
||||
assert!(log.iter().any(|s| s == "router 0 0..1g0 b=false"));
|
||||
assert!(log.iter().any(|s| s == "combine 0 0..1g0 b=false"));
|
||||
assert!(!log.iter().any(|s| s.contains("b=true") && !s.starts_with("shared")));
|
||||
// shared expert follows dec_batch, not the row count
|
||||
assert!(log.iter().any(|s| s == "shared 0 0..1g0 b=true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffn_half_router_doorbell_shared_and_expert_input_precede_the_ring_wait() {
|
||||
let log = record(2, 1, false);
|
||||
let seq: Vec<&str> =
|
||||
log[index_of(&log, "stamp 0.16")..index_of(&log, "stamp 0.18") + 1].iter().map(String::as_str).collect();
|
||||
assert_eq!(
|
||||
seq,
|
||||
[
|
||||
"stamp 0.16",
|
||||
"hc 0 Ffn apply=true 0..2g0",
|
||||
"router 0 0..2g0 b=true",
|
||||
"doorbell 0..2g0",
|
||||
"stamp 0.17",
|
||||
"shared 0 0..2g0 b=true",
|
||||
"xq 0 0..2g0",
|
||||
"stamp 0.18"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn post_sequence_waits_the_three_flags_in_order_with_the_layers_ring() {
|
||||
let log = record(2, 1, false);
|
||||
let from = index_of(&log, "waitA 1");
|
||||
let to = index_of(&log, "stamp 0.24") + 1;
|
||||
let seq: Vec<&str> = log[from..to].iter().map(String::as_str).collect();
|
||||
assert_eq!(
|
||||
seq,
|
||||
[
|
||||
"waitA 1 0..2g0",
|
||||
"stamp 0.19",
|
||||
"experts 0 Vram 0..2g0",
|
||||
"stamp 0.20",
|
||||
"waitB 1",
|
||||
"stamp 0.21",
|
||||
"experts 0 Pcie 0..2g0",
|
||||
"stamp 0.22",
|
||||
"waitM 1",
|
||||
"stamp 0.23",
|
||||
"cpurows 0..2g0 only=true",
|
||||
"hitadd 0..2g0",
|
||||
"combine 0 0..2g0 b=true",
|
||||
"stamp 0.24"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pcie_mode_two_stages_blobs_with_a_copy_kernel_between_wait_b_and_the_pcie_group() {
|
||||
let mut o = Trace::default();
|
||||
let mut p = WindowPolicy::mode17();
|
||||
p.pcie_mode = 2;
|
||||
record_window(&mut o, &p, 3, 1, false).unwrap();
|
||||
let b = index_of(&o.log, "waitB 1");
|
||||
assert!(o.log[b + 1].starts_with("stage 0"));
|
||||
let none = record(3, 1, false);
|
||||
assert!(!none.iter().any(|s| s.starts_with("stage")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer_one_pending_write_is_replaced_by_the_ple_block_only_when_ple_is_on() {
|
||||
let with = record(2, 1, true);
|
||||
let l1 = index_of(&with, "stamp 1.0");
|
||||
assert_eq!(with[l1 + 1], "ple 0..2g0");
|
||||
assert_eq!(with[l1 + 2], "hc 1 Attention apply=false 0..2g0");
|
||||
let without = record(2, 1, false);
|
||||
let l1 = index_of(&without, "stamp 1.0");
|
||||
assert_eq!(without[l1 + 1], "hc 1 Attention apply=true 0..2g0");
|
||||
assert_eq!(without.iter().filter(|s| s.starts_with("ple")).count(), 0);
|
||||
assert_eq!(with.iter().filter(|s| s.starts_with("ple")).count(), 1, "PLE runs once, at layer 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn last_layer_writes_the_residual_and_the_window_ends_with_the_head() {
|
||||
let log = record(3, 1, false);
|
||||
let n = log.len();
|
||||
assert_eq!(&log[n - 5..], ["stamp 47.24", "final 0..3g0", "stamp 48.0", "head 3", "stamp 48.1"]);
|
||||
assert_eq!(log.iter().filter(|s| s.starts_with("final")).count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_window_stamps_group_zero_only_and_interleaves_cpu_with_gpu_work() {
|
||||
let log = record(5, 2, false);
|
||||
// pre(0,A) pre(0,B) | post(0,A) pre(1,A) | post(0,B) pre(1,B)
|
||||
let order = [
|
||||
"hc 0 Attention apply=false 0..3g0",
|
||||
"hc 0 Attention apply=false 3..5g1",
|
||||
"waitA 1 0..3g0",
|
||||
"hc 1 Attention apply=true 0..3g0",
|
||||
"waitA 2 3..5g1",
|
||||
"hc 1 Attention apply=true 3..5g1",
|
||||
];
|
||||
let mut at = 0;
|
||||
for want in order {
|
||||
let found = log[at..].iter().position(|s| s == want).unwrap_or_else(|| panic!("{want} not after {at}"));
|
||||
at += found + 1;
|
||||
}
|
||||
// profile stamps come from group 0 only
|
||||
let stamps0 = log.iter().filter(|s| s.starts_with("stamp 5.")).count();
|
||||
let g1_lines: Vec<&String> = log.iter().filter(|s| s.ends_with("g1")).collect();
|
||||
assert!(stamps0 > 0 && !g1_lines.iter().any(|s| s.starts_with("stamp")));
|
||||
// the doorbell of each group is its own rows
|
||||
assert!(log.contains(&"doorbell 0..3g0".to_string()) && log.contains(&"doorbell 3..5g1".to_string()));
|
||||
// only group 0 snapshots the index tail (before the first group's append)
|
||||
let tails = log.iter().filter(|s| s.starts_with("tail q0")).count();
|
||||
assert_eq!(tails, 1);
|
||||
let tail = index_of(&log, "tail q0");
|
||||
assert!(tail < index_of(&log, "kv q0 3..5g1"), "the snapshot precedes B's append");
|
||||
// rings of group B are even
|
||||
assert!(log.contains(&"waitA 2 3..5g1".to_string()) && log.contains(&"waitM 96".to_string()));
|
||||
// group B of a 2-row window is one row and is not batched
|
||||
let two = record(2, 2, false);
|
||||
assert!(two.iter().any(|s| s == "router 0 1..2g1 b=false"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_ring_is_waited_exactly_three_times_and_in_run_order() {
|
||||
for groups in [1usize, 2] {
|
||||
let log = record(4, groups, true);
|
||||
let a: Vec<u32> = log.iter().filter_map(|s| s.strip_prefix("waitA ")?.split(' ').next()?.parse().ok()).collect();
|
||||
assert_eq!(a, (1..=(48 * groups) as u32).collect::<Vec<_>>());
|
||||
for flag in ["waitB ", "waitM "] {
|
||||
let v: Vec<u32> = log.iter().filter_map(|s| s.strip_prefix(flag)?.parse().ok()).collect();
|
||||
assert_eq!(v, a);
|
||||
}
|
||||
// exactly one doorbell per (layer, group): the host loop expects the same count
|
||||
assert_eq!(log.iter().filter(|s| s.starts_with("doorbell")).count(), 48 * groups);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_producer_failure_stops_the_recording_at_that_call() {
|
||||
let mut o = Trace { fail_at: Some("router".into()), ..Default::default() };
|
||||
let err = record_window(&mut o, &WindowPolicy::mode17(), 2, 1, false).unwrap_err();
|
||||
assert_eq!(err, Error::InvalidDriverValue("trace"));
|
||||
assert!(o.log.last().unwrap().starts_with("router 0"));
|
||||
assert!(!o.log.iter().any(|s| s.starts_with("doorbell")));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user