Merge claude/verify-decode-graph-reuse-handles; decode graph reuse (Q7) wired behind LELEKA_DECODE_GRAPH_REUSE

Merge of the speed session's driver part (DeviceRef handles, OriginalVerifier park/rearm, OriginalVerifyCanonicalGdn reseed; ptx manifest and seal plan entries of both sides kept, ledger rows of both sides kept) with the owner loan: the journal's owners are Option behind accessors, lend() uses the same idle precondition as the speed session's require_idle.

DecodeResources implements HeldAssembly for real (park, rearm from the session priors, lend and take_back through the journal loan; every refusal retires the set). OriginalServeStack holds a GraphReuse; decode assemble asks begin first (re-arm, refill queue; or the owners back to record), teardown keeps the assembly for a clean request (drafter end_request_keep_bank, shared-expert pin, park, lend, adopt) or runs the old teardown; retirement releases the drafter before the bank closes, in begin, close and reset_expert_tier. The MoE cache pins the shared experts while a set is held and counts freed window entries (weights epoch). Switch off: begin is not called and teardown runs the old body unchanged.

Tests: GraphReuse policy with a logging probe (switch off touches nothing, key change, moved owners, refused re-arm, lost owners, order release before drop), keepable outcomes, the lifecycle fake scenarios, the GPU-free loan state machine. Not run on a GPU. No speedup claim.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-11-10 00:50:19 +01:00
co-authored by Claude Sonnet 5.5
144 changed files with 18208 additions and 1013 deletions
+21
View File
@@ -2733,6 +2733,27 @@
"problems": [
"not built for sm_86 by design (claude/prefill-gdn-tensor-core): LELEKA_PREFILL_GDN_TC is opt-in and experimental and gdn_prefill_tc.rs::plan refuses every device below compute capability 12, so an sm_86 build never loads this module (the kernels use only sm_80 features and would retarget; the 3080 plan needs its own parity and quality run first)"
]
},
{
"name": "original_verify_window_qsa_kv_rows.ptx",
"sm120_path": "crates/cuda-driver/src/original_verify_window_qsa_kv_rows.ptx",
"problems": [
"not built for sm_86 by design (claude/verify-qsa-fused-prelude): LELEKA_SM120_FUSED_QSA_PRELUDE is an opt-in compute capability 12 decode switch (original_verify_window_sm120.rs), so an sm_86 build never loads this module"
]
},
{
"name": "original_verify_window_qsa_index_rows.ptx",
"sm120_path": "crates/cuda-driver/src/original_verify_window_qsa_index_rows.ptx",
"problems": [
"not built for sm_86 by design (claude/verify-qsa-fused-prelude): LELEKA_SM120_FUSED_QSA_PRELUDE is an opt-in compute capability 12 decode switch (original_verify_window_sm120.rs), so an sm_86 build never loads this module"
]
},
{
"name": "sm120_gdn_fused.ptx",
"sm120_path": "crates/cuda-driver/src/sm120_gdn_fused.ptx",
"problems": [
"not built for sm_86 by design (claude/verify-gdn-fused-kernels): LELEKA_SM120_FUSED_GDN and LELEKA_SM120_GDN_AB_UNROLL are compute capability 12.0 decode switches; original_verify_window_sm120.rs enables them only on a 12.x card, so an sm_86 build never loads this module"
]
}
],
"portable_no_companion_needed": [
+6
View File
@@ -24,6 +24,12 @@ impl DeviceBuffer<'_> {
Ok(staging)
}
pub fn copy_from(&mut self, input: &[u8]) -> Result<()> {
self.copy_from_shared(input)
}
/// `copy_from` through a shared borrow, for a buffer behind a `DeviceRef` (the PLE history image the held
/// verify graphs read in place): the same staging, copy and synchronisation, so the caller keeps the device idle
/// of other writers to the buffer.
pub fn copy_from_shared(&self, input: &[u8]) -> Result<()> {
let mut staging = self.staging(input.len())?;
staging.copy_from_slice(input);
self.copy_staged(staging, false).map(|_| ())
+102
View File
@@ -0,0 +1,102 @@
//! A shared, cloneable handle to a device allocation (or to a range of one).
//!
//! The verify-window aggregates (`OriginalVerifyWindowResources`, the GDN/QSA journals) used to borrow every weight,
//! scratch and history buffer they read from the cache that owns it (`&'a DeviceBuffer`). A value that borrows
//! fields of its owner cannot be stored next to the owner, so the whole recorded graph set had to be dropped and
//! recorded again for every request. A [`DeviceRef`] replaces the borrow by shared ownership of the allocation:
//!
//! * `Clone` is one reference-count increment. Clones happen when an assembly is built, parked or re-armed, never
//! in the per-step loop; the window code only dereferences (`&*handle`, a pointer read, no count traffic).
//! * It dereferences to the [`DeviceBuffer`] every kernel entry point takes, so `qwen_address()` and the size checks
//! work on the handle unchanged.
//! * The range is the alias' own: a handle made from a [`DeviceSlice`] names `[offset, offset + len)` of a slab (the
//! alias is a non-owning `DeviceBuffer` of exactly that range) and keeps the slab alive; a handle made from a
//! whole `DeviceBuffer` owns it.
//! * The allocation is freed when the last holder drops. An owner that releases its handle while an assembly still
//! holds another keeps the memory alive (`release` reports `Ok` and leaves the free to the last holder).
//!
//! Single-thread affine like the buffers it wraps (`Rc`).
use crate::{DeviceBuffer, DeviceSlice, Result};
use std::{ops::Deref, rc::Rc};
/// What a handle shares: the buffer it names and, for a range of a slab, the slab that keeps the memory alive.
struct Shared<'ctx> {
/// Declared first: a non-owning alias drops (and frees nothing) before the slab it points into.
buffer: DeviceBuffer<'ctx>,
slab: Option<Rc<DeviceBuffer<'ctx>>>,
}
/// A shared handle to a device allocation; see the module comment.
pub struct DeviceRef<'ctx> {
shared: Rc<Shared<'ctx>>,
}
impl<'ctx> DeviceRef<'ctx> {
/// A handle that owns `buffer` (its own allocation).
pub fn from_buffer(buffer: DeviceBuffer<'ctx>) -> Self {
Self { shared: Rc::new(Shared { buffer, slab: None }) }
}
/// A handle to the buffer of a [`DeviceSlice`] (its own allocation, or its range of a shared slab).
pub fn from_slice(slice: DeviceSlice<'ctx>) -> Self {
let (buffer, slab) = slice.into_parts();
Self { shared: Rc::new(Shared { buffer, slab }) }
}
/// Whether both handles name the same allocation range.
pub fn ptr_eq(&self, other: &Self) -> bool {
Rc::ptr_eq(&self.shared, &other.shared)
}
/// How many handles share this range (the cache's own plus every held assembly's).
pub fn holders(&self) -> usize {
Rc::strong_count(&self.shared)
}
/// Give this handle up. The sole holder frees the buffer (the last handle of a slab frees the slab) and returns
/// the error of that free; with other holders left, they keep the memory alive and free it when they drop.
pub fn release(self) -> Result<()> {
let Ok(shared) = Rc::try_unwrap(self.shared) else { return Ok(()) };
let Shared { buffer, slab } = shared;
let freed = buffer.release();
let Some(slab) = slab else { return freed };
match Rc::try_unwrap(slab) {
Ok(slab) => crate::combine(freed, slab.release()),
Err(_) => freed,
}
}
}
impl<'ctx> Clone for DeviceRef<'ctx> {
fn clone(&self) -> Self {
Self { shared: Rc::clone(&self.shared) }
}
}
impl<'ctx> Deref for DeviceRef<'ctx> {
type Target = DeviceBuffer<'ctx>;
fn deref(&self) -> &DeviceBuffer<'ctx> {
&self.shared.buffer
}
}
impl std::fmt::Debug for DeviceRef<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "DeviceRef({} bytes, {} holders)", self.shared.buffer.len(), self.holders())
}
}
impl<'ctx> From<DeviceBuffer<'ctx>> for DeviceRef<'ctx> {
fn from(buffer: DeviceBuffer<'ctx>) -> Self {
Self::from_buffer(buffer)
}
}
impl<'ctx> From<DeviceSlice<'ctx>> for DeviceRef<'ctx> {
fn from(slice: DeviceSlice<'ctx>) -> Self {
Self::from_slice(slice)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,84 @@
//! Device proofs of the shared allocation handle. They need a CUDA device and run only with the enabling variable;
//! on every other host they are compile-checked, never executed (the handle is a thin `Rc` over a `DeviceBuffer`, which
//! cannot exist without a context, so there is nothing to build without a device).
use super::*;
use crate::{Driver, SlabAllocator, SlabPolicy};
const ENABLE: &str = "LELEKA_VERIFY_WINDOW_GPU";
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn a_released_owner_leaves_the_memory_to_the_last_holder() {
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 before = context.allocated_bytes();
let owner = DeviceRef::from_buffer(context.allocate(4096).expect("buffer"));
owner.copy_from_shared(&[7u8; 4096]).expect("upload through the shared handle");
let held = owner.clone();
assert!(owner.ptr_eq(&held));
assert_eq!(owner.holders(), 2);
assert_eq!(owner.len(), 4096);
// the owner gives its handle up while the assembly still holds one: nothing is freed
owner.release().expect("release with a holder left");
assert_eq!(context.allocated_bytes(), before + 4096);
assert_eq!(held.copy_to_owned(4096).expect("read back"), vec![7u8; 4096]);
assert_eq!(held.holders(), 1);
held.release().expect("the last holder frees");
assert_eq!(context.allocated_bytes(), before);
}
#[test]
#[ignore = "Root-only: needs a CUDA device"]
fn a_handle_to_a_slab_range_keeps_the_slab_alive_after_the_allocator_released_it() {
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 before = context.allocated_bytes();
let mut slabs = SlabAllocator::new(&context, SlabPolicy::DENSE).expect("slab allocator");
let first = DeviceRef::from_slice(slabs.allocate(1024).expect("first range"));
let second = DeviceRef::from_slice(slabs.allocate(2048).expect("second range"));
assert!(!first.ptr_eq(&second));
first.copy_from_shared(&[1u8; 1024]).expect("upload");
second.copy_from_shared(&[2u8; 2048]).expect("upload");
let held = second.clone();
// the cache closes: its handles and the allocator go, one handle of an assembly is left
first.release().expect("release first");
second.release().expect("release second with a holder left");
slabs.release().expect("release the allocator");
assert!(context.allocated_bytes() > before, "the slab is still allocated");
assert_eq!(held.copy_to_owned(2048).expect("read back"), vec![2u8; 2048]);
held.release().expect("the last holder frees the slab");
assert_eq!(context.allocated_bytes(), before);
}
/// The per-step path (a `run`: begin, enqueue, drain, commit) and the recorders read the handles through `Deref`
/// only. This guard keeps `.clone()` out of the modules that read the weight handles of a recorded window, so a
/// reference-count increment cannot slip into the loop unnoticed. The clones live in the assembly (the engine's caches
/// hand the handles out) and in `park` / `rearm`.
#[test]
fn the_window_and_journal_modules_never_clone_a_handle() {
let window_ops = [
include_str!("../original_verify_window_ops.rs"),
include_str!("../original_verify_window_ops/gdn_stages.rs"),
include_str!("../original_verify_window_ops/original_verify_window_ops_methods.rs"),
include_str!("../original_verify_window_ops/qsa_prelude_ops.rs"),
include_str!("../original_verify_window_ops/side_qsa_branches.rs"),
include_str!("../original_verify_window_ops/side_shared_expert.rs"),
include_str!("../original_verify_window_ops/window_ops_kernels_and_pcie_plan.rs"),
];
let journals = [
include_str!("../original_verify/original_verify_gdn_journal/verify_gdn_fused_step.rs"),
include_str!("../original_verify/original_verify_gdn_journal/verify_gdn_journal_ladder_logits_scan.rs"),
include_str!("../original_verify/original_verify_gdn_journal/verify_gdn_journal_stage_and_commit.rs"),
include_str!("../original_verify/original_verify_gdn_journal/verify_gdn_journal_window_launches.rs"),
include_str!("../qsa_verification_commit/verify_qsa_journal_capture_commit.rs"),
include_str!("../qsa_verification_commit/verify_qsa_journal_index_image.rs"),
];
for source in window_ops.iter().chain(journals.iter()) {
let code = source.split("#[cfg(test)]").next().unwrap_or(source);
assert!(!code.contains(".clone()"), "a window or journal module clones: handles are dereferenced there");
}
}
+9
View File
@@ -133,6 +133,15 @@ impl<'ctx> DeviceSlice<'ctx> {
matches!(self.backing, SliceBacking::Carved { .. })
}
/// The buffer this slice dereferences to and, for a carved range, the slab that keeps it alive
/// (`DeviceRef::from_slice`).
pub(crate) fn into_parts(self) -> (DeviceBuffer<'ctx>, Option<Rc<DeviceBuffer<'ctx>>>) {
match self.backing {
SliceBacking::Own(buffer) => (buffer, None),
SliceBacking::Carved { slab, view } => (view, Some(slab)),
}
}
/// Release the buffer. The last slice of a slab frees the slab; an error of that free is returned.
pub fn release(self) -> Result<()> {
match self.backing {
+1
View File
@@ -43,6 +43,7 @@ pub use root_exports::*;
pub mod compute_drain;
mod deferred_status;
mod device_ref;
mod device_slab;
#[allow(unsafe_code)]
mod ffi;
@@ -5,6 +5,8 @@ use super::*;
#[path = "original_mtp_drafter/original_mtp_drafter_finish_chain.rs"]
mod original_mtp_drafter_finish_chain;
#[path = "original_mtp_drafter/original_mtp_drafter_keep_bank.rs"]
mod original_mtp_drafter_keep_bank;
#[path = "original_mtp_drafter/original_mtp_drafter_launch_rounds.rs"]
mod original_mtp_drafter_launch_rounds;
#[path = "original_mtp_drafter/original_mtp_drafter_new_draft.rs"]
@@ -0,0 +1,24 @@
//! The drafter's side of a kept verifier bank (`LELEKA_DECODE_GRAPH_REUSE`, docs/experiments/decode-graph-reuse.md).
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalMtpDrafter<'ctx> {
/// End of a request over a verifier bank that STAYS (`LELEKA_DECODE_GRAPH_REUSE`,
/// docs/experiments/decode-graph-reuse.md): the state keyed on the request goes, the programs bound to the bank do
/// not. Drain the draft stream, forget a draft that was launched and never finished (its ring mutation stays open,
/// as in `release_verifier_bindings`) and drop the verifier window the last round staged (the tail owner keeps it
/// until the next stage, and after the bank's re-arm it is a window of an older generation). The cached round
/// programs, the direct mode, the ring owner and the policy key stay: they name the bank's final-R span and the
/// draft ring, both unchanged for the same bank, and `stage_round` refuses a window at another address.
pub fn end_request_keep_bank(&mut self) -> Result<()> {
self.validate_context(self.context)?;
self.stream.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?;
self.in_flight = None;
let source = self.full.as_ref().ok_or(Error::ContextPoisoned)?.release_staged_source();
if source.is_err() {
self.failed = true;
}
source
}
}
@@ -93,10 +93,13 @@ pub struct OriginalNativeHeadRows<'ctx> {
pub(super) mixed: Option<DeviceBuffer<'ctx>>,
pub(super) q8: Option<DeviceBuffer<'ctx>>,
pub(super) logits: Option<DeviceBuffer<'ctx>>,
/// `t` sampled ids, then one word: the finite verdict of the logits when the graph carries it.
pub(super) mapped: Option<MappedAllocation>,
pub(super) commands: RefCell<Vec<Command>>,
pub(super) t: usize,
pub(super) failed: Cell<bool>,
/// `LELEKA_SM120_ACCEPT_ON_DEVICE`: the verify graph of these rows ends with the finite scan (set before capture).
pub(super) verdict_in_graph: Cell<bool>,
}
pub struct NativeHeadFlight<'a, 'ctx> {
pub(super) rows: &'a mut OriginalNativeHeadRows<'ctx>,
@@ -20,6 +20,7 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
commands: RefCell::new(Vec::new()),
t,
failed: Cell::new(false),
verdict_in_graph: Cell::new(false),
};
if let Err(primary) = owner.allocate_buffers() {
return combine(Err(primary), owner.close_inner());
@@ -32,14 +33,36 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
self.q8 = Some(context.allocate(t * self.head.n / 32 * 36)?);
self.logits = Some(context.allocate(t * self.head.vocab * 4)?);
let guard = context.enter()?;
let mapped = MappedAllocation::new(t * 4);
// the ids, then the finite verdict word (read only when the graph carries the scan)
let mapped = MappedAllocation::new(t * 4 + 4);
let pop = guard.finish();
if pop.is_err() {
context.poison();
context.retain_driver();
}
self.mapped = Some(combine(mapped, pop)?);
Ok(())
self.rearm_finite_verdict()
}
/// The verify graph of these rows ends with the finite scan and its store to the verdict word (set before capture).
pub(crate) fn set_finite_verdict_in_graph(&self, on: bool) {
self.verdict_in_graph.set(on);
}
pub(crate) fn finite_verdict_in_graph(&self) -> bool {
self.verdict_in_graph.get()
}
/// Device address of the verdict word, the destination of the graph's store.
pub(crate) fn finite_verdict_address(&self) -> Result<u64> {
self.mapped.as_ref().ok_or(Error::ContextPoisoned)?.address(self.t * 4, 4)
}
/// The word the graph stored, after a genuine drain: `Ok` when every logit was finite.
pub(crate) fn read_finite_verdict(&self) -> Result<()> {
let words = self.mapped.as_ref().ok_or(Error::ContextPoisoned)?.read_i32(self.t + 1)?;
crate::original_verify::finite_verdict::decode_verdict(words[self.t])
}
/// Back to "not written": a window whose graph did not store its verdict reads as an error, not as finite.
fn rearm_finite_verdict(&mut self) -> Result<()> {
let pending = crate::original_verify::finite_verdict::VERDICT_PENDING.to_le_bytes();
self.mapped.as_mut().ok_or(Error::ContextPoisoned)?.write(self.t * 4, &pending)
}
pub fn rows(&self) -> usize {
self.t
@@ -160,6 +183,9 @@ impl<'ctx> OriginalNativeHeadRows<'ctx> {
) -> Result<NativeHeadSelection> {
let NativeHeadSampling { position: pos0, params, history, history_len, enabled: head_sampling, .. } = sampling;
self.check_sampling_request(stream, &params, history_len, pos0)?;
if self.finite_verdict_in_graph() {
self.rearm_finite_verdict()?;
}
self.commands.borrow_mut().clear();
if head_sampling && sampling_needed(&params, history.is_some()) {
self.sample_on_stream(stream, sampling)?;
@@ -35,14 +35,24 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
}
Ok(())
}
/// The finite check of the whole head output. With `LELEKA_SM120_ACCEPT_ON_DEVICE` the graph recorded the scan
/// and stored its verdict in a mapped word: only that word is read here. Otherwise the literal scan runs after
/// the drain. Either way it raises the same error, before the window is completed and before any commit.
fn validate_verifier_logits(&self, stream: &mut OriginalGpuStream<'ctx>) -> Result<()> {
let r = self.resources.as_ref().ok_or(Error::ContextPoisoned)?;
let rows = r.native_head_rows()?.completed_logits()?;
let geometry = r.verifier_journal().geometry();
if rows.len() != r.native_head_rows()?.rows() * geometry.vocabulary * 4 {
return Err(Error::InvalidQwenShape);
}
r.verifier_journal().validate_completed_logits(stream, rows, rows.len() / (geometry.vocabulary * 4))
let head = r.native_head_rows()?;
crate::original_verify::finite_verdict::post_drain_check(
head.finite_verdict_in_graph(),
|| {
let rows = head.completed_logits()?;
let geometry = r.verifier_journal().geometry();
if rows.len() != head.rows() * geometry.vocabulary * 4 {
return Err(Error::InvalidQwenShape);
}
r.verifier_journal().validate_completed_logits(stream, rows, rows.len() / (geometry.vocabulary * 4))
},
|| head.read_finite_verdict(),
)
}
}
@@ -76,6 +86,10 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
r.verifier_journal().validate_bank(bank)?;
r.verifier_qsa().complete_commit(bank)
}
/// No launch of this graph is outstanding (`park` waited them all): the precondition of a re-arm.
pub(crate) fn verifier_is_idle(&self) -> bool {
!self.launched
}
pub(crate) fn verifier_abandon_after_drain(&mut self) -> Result<()> {
let r = self.resources_after_wait()?;
r.verifier_qsa().abandon_after_drain();
@@ -216,6 +216,11 @@ impl<'ctx> OriginalMtpActor<'ctx> {
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.release_verifier_bindings()
}
/// The end of a request over a verifier bank that stays (see `OriginalMtpDrafter::end_request_keep_bank`).
pub fn end_request_keep_bank(&mut self) -> Result<()> {
self.drafter.as_mut().ok_or(Error::ContextPoisoned)?.end_request_keep_bank()
}
/// `kv_restore(upto)`: refill the draft ring's window for a sequence that
/// continues at `upto` from the host pages `prior` authenticates. A no-op
/// when the ring is fully resident, exactly as in Original.
@@ -6,7 +6,7 @@
//! append/copy capability; both refuse while a window is armed (uncommitted).
use crate::{Error, OriginalQsaMappedPrefix, OriginalVerifyQsaJournal, Result};
impl<'ctx> OriginalVerifyQsaJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
/// The mapped K/V prefix of one resident QSA layer (`0..12`) after a committed window.
pub fn committed_mapped_prefix(&self, layer: usize) -> Result<OriginalQsaMappedPrefix> {
if layer >= 12 {
+26 -20
View File
@@ -11,6 +11,9 @@ pub(crate) mod chain;
mod diag;
#[path = "original_verify_window_draft.rs"]
pub(crate) mod draft;
pub(crate) mod finite_verdict;
#[path = "original_verify/original_verify_window_gdn_fused.rs"]
pub(crate) mod gdn_fused;
#[path = "original_verify_window_gr.rs"]
pub(crate) mod gr;
#[path = "original_verify_window_kernels.rs"]
@@ -42,7 +45,7 @@ pub(crate) mod window_plan;
#[path = "original_verify_window_record.rs"]
pub(crate) mod window_record;
use crate::original_gpu_schedule::{OriginalCapture, OriginalGraphResources, resources};
use crate::{Context, DeviceBuffer, Error, Result, combine};
use crate::{Context, DeviceBuffer, DeviceRef, Error, Result, combine};
use abi::{Arg, Command, Module};
pub use diag::{
OriginalVerifyDiag, original_verify_diagnostics, original_verify_live_count, original_verify_release_live,
@@ -138,11 +141,9 @@ struct Physical<'ctx> {
/// resource aggregate; commands retain the stable ABI through final graph drain.
pub struct OriginalVerifyBank<'ctx> {
physical: Rc<Physical<'ctx>>,
last_t: usize,
last_position: usize,
last_tokens: [i32; 8],
/// The window staged last (`stage`, `stage_commit`); empty after `rearm`.
staged: StagedWindow,
generation: u64,
last_keep: usize,
released: bool,
/// Registered expert banks a window's PCIe DMA reads (`publish_gpu_plan`), held until the copy-stream fence.
pcie_sources: Vec<Rc<crate::MappedExpertBank<'ctx>>>,
@@ -179,37 +180,37 @@ pub enum OriginalVerifyGdnStage {
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 OriginalVerifyGdnWeights<'ctx> {
pub conv: DeviceRef<'ctx>,
pub alpha: DeviceRef<'ctx>,
pub beta: DeviceRef<'ctx>,
pub dt: DeviceRef<'ctx>,
pub a: DeviceRef<'ctx>,
pub norm: DeviceRef<'ctx>,
}
pub struct OriginalVerifyGdnJournal<'a, 'ctx> {
pub struct OriginalVerifyGdnJournal<'ctx> {
physical: Rc<Physical<'ctx>>,
canonical: Rc<Canonical<'ctx>>,
weights: [OriginalVerifyGdnWeights<'a, 'ctx>; 36],
ple: Option<&'a DeviceBuffer<'ctx>>,
weights: [OriginalVerifyGdnWeights<'ctx>; 36],
ple: Option<DeviceRef<'ctx>>,
commands: RefCell<Vec<Command>>,
}
/// Only real driver graph aggregates can implement this sealed association.
/// Root's all-layer aggregate returns its retained journal; runtime cannot mint it.
pub trait OriginalVerifyGraphResources<'ctx>: OriginalGraphResources {
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx>;
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx>;
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'ctx>;
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'ctx>;
}
/// The concrete all-owner resource aggregate for one captured verification
/// graph. It retains the GDN state journal, the twelve QSA index images, and
/// the exact native-head output rows as one affine owner. A graph cannot pair
/// a journal from one context with a head or QSA checkpoint from another.
pub struct OriginalVerifyResources<'a, 'ctx> {
pub struct OriginalVerifyResources<'ctx> {
context: &'ctx Context<'ctx>,
journal: OriginalVerifyGdnJournal<'a, 'ctx>,
qsa: Rc<crate::OriginalVerifyQsaJournal<'a, 'ctx>>,
journal: OriginalVerifyGdnJournal<'ctx>,
qsa: Rc<crate::OriginalVerifyQsaJournal<'ctx>>,
head: crate::OriginalNativeHeadRows<'ctx>,
}
#[path = "original_verify_gpu_plan.rs"]
@@ -226,6 +227,9 @@ pub use schedule::{
OriginalVerifier, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyWindowResult,
OriginalVerifyWindowTokens,
};
mod original_verify_rearm;
pub use original_verify_rearm::OriginalVerifyRearm;
use original_verify_rearm::StagedWindow;
#[path = "original_verify_window_ops.rs"]
mod window_ops;
pub use gr::{
@@ -252,6 +256,8 @@ use share_window_modules::admission;
#[allow(unused_imports)]
use share_window_modules::admit;
#[allow(unused_imports)]
use share_window_modules::check_canonical_lengths;
#[allow(unused_imports)]
use share_window_modules::check_commands;
#[allow(unused_imports)]
use share_window_modules::command;
@@ -0,0 +1,163 @@
//! `LELEKA_SM120_ACCEPT_ON_DEVICE`: the finite verdict of the verify window's head logits, decided inside the graph.
//!
//! Literal order (switch off): after the window graph drains, the host launches `verify_clear_status` and
//! `verify_scan_logits` over all `T x vocab` logits, synchronises the stream, copies the 4-byte status back with
//! `cuMemcpyDtoH` and synchronises the context. Three blocking waits sit between the end of the graph and the host
//! reading the picked ids.
//!
//! Vanilla records the same check into the window's own stream after the greedy pick (`logits_nonfinite_rows`,
//! `verify.cpp:2380`) and reads the mapped flags after the window's one synchronisation. This module is that order:
//! the same two kernels of the sealed `original_verify.ptx` end the graph, then one store moves the status word into
//! the host-mapped verdict word of the head rows (a plain store, as the greedy kernel stores its ids: no atomics on
//! mapped memory). The post-drain code reads that word and launches and synchronises nothing. The status is the same
//! integer exponent scan, so the verdict and the error it raises are the literal ones; no number of the model changes.
use super::{Arg, Command, Error, Result};
/// The error label of a non-finite logit, the same one the post-drain scan has always raised.
pub(crate) const NON_FINITE_LABEL: &str = "Original Verifier full logits";
/// What the verdict word holds before the graph stores into it: neither 0 (finite) nor 1 (non-finite).
pub(crate) const VERDICT_PENDING: i32 = 0x5a5a_5a5a;
/// The operands of the finite scan: the head logits, their word count and the device status word the scan ORs into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ScanOperands {
pub logits: u64,
pub words: u64,
pub status: u64,
}
/// The two scan kernels of the literal post-drain check: clear the status, then OR a bit for every non-finite logit.
pub(crate) fn scan_commands(scan: ScanOperands) -> Result<Vec<Command>> {
let ScanOperands { logits, words, status } = scan;
Ok(vec![
Command::new("verify_clear_status", [1, 1, 1], [32, 1, 1], 0, vec![Arg::Address(status)])?,
Command::new(
"verify_scan_logits",
[words.div_ceil(256).min(65535) as u32, 1, 1],
[256, 1, 1],
0,
vec![Arg::Address(logits), Arg::U64(words), Arg::Address(status)],
)?,
])
}
/// The tail of the verify graph with the verdict in it: the scan, then the store of the status into the mapped word
/// (`verify_copy_i32_from_mapped_kernel`: `dst[i] = src[i]` for one word).
pub(crate) fn tail_commands(scan: ScanOperands, verdict: u64) -> Result<Vec<Command>> {
let mut commands = scan_commands(scan)?;
commands.push(Command::new(
"verify_copy_i32_from_mapped_kernel",
[1, 1, 1],
[32, 1, 1],
0,
vec![Arg::Address(verdict), Arg::Address(scan.status), Arg::I32(1)],
)?);
Ok(commands)
}
/// The verdict word after the drain: 0 every logit finite, 1 a non-finite one (the literal error), anything else means
/// the graph did not store it.
pub(crate) fn decode_verdict(word: i32) -> Result<()> {
match word {
0 => Ok(()),
1 => Err(Error::NonFiniteMmqOutput(NON_FINITE_LABEL)),
_ => Err(Error::InvalidDriverValue("Original Verifier finite verdict was not stored by the graph")),
}
}
/// The post-drain finite check. With the verdict in the graph only `graph_verdict` runs (a read of mapped memory);
/// otherwise `scan` runs: the launch, the stream synchronisation, the copy back and the context synchronisation.
pub(crate) fn post_drain_check(
verdict_in_graph: bool,
scan: impl FnOnce() -> Result<()>,
graph_verdict: impl FnOnce() -> Result<()>,
) -> Result<()> {
if verdict_in_graph { graph_verdict() } else { scan() }
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
const OPERANDS: ScanOperands = ScanOperands { logits: 0x1000, words: 8 * 248_320, status: 0x2000 };
fn names(commands: &[Command]) -> Vec<&'static str> {
commands.iter().map(|c| c.name).collect()
}
#[test]
fn the_literal_scan_is_a_clear_then_a_scan_over_every_logit_word() {
let commands = scan_commands(OPERANDS).unwrap();
assert_eq!(names(&commands), ["verify_clear_status", "verify_scan_logits"]);
assert_eq!(commands[0].grid, [1, 1, 1]);
assert_eq!(commands[1].grid, [7760, 1, 1]);
assert_eq!(commands[1].block, [256, 1, 1]);
let huge = scan_commands(ScanOperands { words: 1 << 26, ..OPERANDS }).unwrap();
assert_eq!(huge[1].grid, [65535, 1, 1]);
let small = scan_commands(ScanOperands { words: 300, ..OPERANDS }).unwrap();
assert_eq!(small[1].grid, [2, 1, 1]);
}
#[test]
fn the_graph_tail_is_the_two_scan_kernels_and_then_the_store_to_the_mapped_word() {
let tail = tail_commands(OPERANDS, 0x3000).unwrap();
assert_eq!(names(&tail), ["verify_clear_status", "verify_scan_logits", "verify_copy_i32_from_mapped_kernel"]);
// the scan is the literal one: the same two commands, in the same order, with the same launch shape
let literal = scan_commands(OPERANDS).unwrap();
for (a, b) in literal.iter().zip(&tail) {
assert_eq!((a.name, a.grid, a.block, a.shared), (b.name, b.grid, b.block, b.shared));
}
// one word, one block: the store is not an atomic and not a second scan
assert_eq!((tail[2].grid, tail[2].block), ([1, 1, 1], [32, 1, 1]));
}
#[test]
fn the_verdict_word_reads_finite_non_finite_or_never_stored() {
assert!(decode_verdict(0).is_ok());
assert_eq!(decode_verdict(1), Err(Error::NonFiniteMmqOutput("Original Verifier full logits")));
for stale in [VERDICT_PENDING, 2, -1, i32::MAX] {
assert!(matches!(decode_verdict(stale), Err(Error::InvalidDriverValue(_))), "{stale}");
}
assert!(VERDICT_PENDING != 0 && VERDICT_PENDING != 1);
}
#[test]
fn with_the_verdict_in_the_graph_the_post_drain_code_launches_copies_and_synchronises_nothing() {
let (scan_calls, read_calls) = (Cell::new(0), Cell::new(0));
let scan = || {
scan_calls.set(scan_calls.get() + 1);
Ok(())
};
let read = || {
read_calls.set(read_calls.get() + 1);
Ok(())
};
assert!(post_drain_check(true, scan, read).is_ok());
assert_eq!((scan_calls.get(), read_calls.get()), (0, 1));
}
#[test]
fn with_the_switch_off_the_literal_scan_runs_and_the_verdict_word_is_not_read() {
let (scan_calls, read_calls) = (Cell::new(0), Cell::new(0));
let scan = || {
scan_calls.set(scan_calls.get() + 1);
Ok(())
};
let read = || {
read_calls.set(read_calls.get() + 1);
Ok(())
};
assert!(post_drain_check(false, scan, read).is_ok());
assert_eq!((scan_calls.get(), read_calls.get()), (1, 0));
}
#[test]
fn a_non_finite_verdict_is_the_same_error_on_both_paths() {
let literal = Err(Error::NonFiniteMmqOutput(NON_FINITE_LABEL));
assert_eq!(post_drain_check(false, || literal.clone(), || Ok(())), literal);
assert_eq!(post_drain_check(true, || Ok(()), || decode_verdict(1)), literal);
}
}
@@ -6,6 +6,7 @@
use super::*;
mod original_verify_window;
mod verify_gdn_fused_step;
mod verify_gdn_journal_ladder_logits_scan;
mod verify_gdn_journal_stage_and_commit;
mod verify_gdn_journal_window_launches;
@@ -0,0 +1,86 @@
//! claude/verify-gdn-fused-kernels: the journal side of the fused GDN launch and of the unrolled a/b kernel
//! (`original_verify_window_gdn_fused.rs`, `sm120_gdn_fused.cu`). The operand spans are the ones
//! `capture_layer_stage` binds for the three Original kernels.
use super::super::gdn_fused::{AbUnrolledStep, FusedGdnBuffers, FusedGdnStep, GateSource, GdnGateOperands, RowSpan};
use super::verify_gdn_journal_stage_and_commit::StageOperands;
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalVerifyGdnJournal<'ctx> {
/// One launch for the conv, the gates (computed inside unless `gates` says they are joined) and the recurrence of
/// layer `layer` over `rows`. Writes `h`, `gate`, `beta` and `y` of those rows exactly as the three kernels do.
pub(crate) fn capture_fused_recurrence(
&self,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
rows: std::ops::Range<usize>,
gates: GateSource,
) -> Result<()> {
self.validate_context(self.physical.context)?;
let op = self.stage_operands(layer, rows.start, rows.end)?;
let gate_operands = match gates {
GateSource::InKernel => self.gate_operands(&op)?,
GateSource::Joined => GdnGateOperands::JOINED,
};
let step = FusedGdnStep {
buffers: self.fused_buffers(&op)?,
gates: gate_operands,
rows: RowSpan { begin: op.begin, end: op.end },
eps: EPS,
};
self.submit_launches(capture, vec![step.launch()?])
}
/// The alpha/beta gates of layer `layer` over `rows` by the unrolled kernel of `LELEKA_SM120_GDN_AB_UNROLL`.
pub(crate) fn capture_ab_unrolled(
&self,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
rows: std::ops::Range<usize>,
) -> Result<()> {
self.validate_context(self.physical.context)?;
let op = self.stage_operands(layer, rows.start, rows.end)?;
let first_row = (op.begin * 48 * 4) as u64;
let step = AbUnrolledStep {
gates: self.gate_operands(&op)?,
gate: op.gate + first_row,
beta: op.beta + first_row,
rows: op.end - op.begin,
};
self.submit_launches(capture, vec![step.launch()?])
}
/// The buffers the three Original kernels share, by their arena spans and weights.
fn fused_buffers(&self, op: &StageOperands) -> Result<FusedGdnBuffers> {
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
Ok(FusedGdnBuffers {
state: self.canonical.span(op.layer, false)?,
hist: self.canonical.span(op.layer, true)?,
qkv: op.qkv,
conv_w: admit(c, &w.conv, 10240 * 4 * 4)?,
h: op.h,
gate: op.gate,
beta: op.beta,
z: self.physical.span("z", 0, g.max_t * 6144 * 4)?,
gamma: admit(c, &w.norm, 128 * 4)?,
y: self.physical.span("y", 0, g.max_t * 6144 * 4)?,
})
}
/// The a/b projection operands: the mixed rows of the stage and the layer's alpha/beta weights.
fn gate_operands(&self, op: &StageOperands) -> Result<GdnGateOperands> {
let (g, c, w) = (self.physical.layout.geometry, self.physical.context, &self.weights[op.layer]);
let n = op.end - op.begin;
if g.n != 2560 || g.value_heads != 48 {
return Err(Error::InvalidQwenShape);
}
Ok(GdnGateOperands {
x: self.physical.span("mixed", op.begin * g.n * 4, n * g.n * 4)?,
alpha_w: admit(c, &w.alpha, 48 * 2560 * 2)?,
beta_w: admit(c, &w.beta, 48 * 2560 * 2)?,
dt: admit(c, &w.dt, 48 * 4)?,
a: admit(c, &w.a, 48 * 4)?,
})
}
}
@@ -5,7 +5,7 @@
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyGdnJournal<'ctx> {
/// Retain the actual PLE history after each chronological row, before its
/// subsequent overwrite. Only the actual producer's capture calls this.
/// Bring-up diagnostic (LELEKA_TRACE_LADDER): copy rows `[begin,end)` of the residual R into frame `frame` of the
@@ -45,7 +45,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
if row >= g.max_t {
return Err(Error::InvalidQwenShape);
}
let history = self.ple.ok_or(Error::InvalidQwenShape)?;
let history = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?;
let words = 9 * 10240;
let src = admit(self.physical.context, history, words * 4)?;
self.submit(
@@ -84,6 +84,15 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
logits: &DeviceBuffer<'ctx>,
rows: usize,
) -> Result<(Vec<Command>, crate::ffi::BufferHandle)> {
let (operands, status) = self.logits_scan_operands(logits, rows)?;
Ok((finite_verdict::scan_commands(operands)?, status))
}
/// The admitted logits, their word count and the status word (retired `hit_count` scratch) of the finite scan.
fn logits_scan_operands(
&self,
logits: &DeviceBuffer<'ctx>,
rows: usize,
) -> Result<(finite_verdict::ScanOperands, crate::ffi::BufferHandle)> {
let g = self.physical.layout.geometry;
if !(1..=g.max_t).contains(&rows) {
return Err(Error::InvalidQwenShape);
@@ -92,16 +101,21 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
let src = admit(self.physical.context, logits, words.checked_mul(4).ok_or(Error::InvalidSize)?)?;
self.check_logits_unaliased(logits)?;
let status = self.span("hit_count", 0, 4)?;
let commands = vec![
command("verify_clear_status", [1, 1, 1], [32, 1, 1], vec![Arg::Address(status.qwen_address())])?,
command(
"verify_scan_logits",
[words.div_ceil(256).min(65535) as u32, 1, 1],
[256, 1, 1],
vec![Arg::Address(src), Arg::U64(words as u64), Arg::Address(status.qwen_address())],
)?,
];
Ok((commands, status))
let operands = finite_verdict::ScanOperands { logits: src, words: words as u64, status: status.qwen_address() };
Ok((operands, status))
}
/// `LELEKA_SM120_ACCEPT_ON_DEVICE`: record the same scan as the last nodes of the window graph, followed by the
/// store of its status into the host-mapped verdict word `verdict` (a device address of the head rows' mapped
/// block). The graph then carries the verdict; `validate_completed_logits` is not called for it.
pub(crate) fn capture_finite_verdict(
&self,
capture: &mut OriginalCapture<'_, 'ctx>,
logits: &DeviceBuffer<'ctx>,
(rows, verdict): (usize, u64),
) -> Result<()> {
self.validate_context(self.physical.context)?;
let (operands, _status) = self.logits_scan_operands(logits, rows)?;
self.submit(capture, finite_verdict::tail_commands(operands, verdict)?)
}
/// The head output does not overlap the verifier arena.
fn check_logits_unaliased(&self, logits: &DeviceBuffer<'ctx>) -> Result<()> {
@@ -158,7 +172,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
/// Actual original PLE history image; selected accepted row, never final-image
/// metadata relabel. Borrowed destination must survive the graph aggregate.
pub fn capture_ple_commit(&self, capture: &mut OriginalCapture<'_, 'ctx>) -> Result<()> {
let history = self.ple.ok_or(Error::InvalidQwenShape)?;
let history = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?;
let bytes = 9 * 10240 * 4;
let dst = admit(self.physical.context, history, bytes)?;
let arena = self.physical.arena.as_ref().ok_or(Error::ContextPoisoned)?;
@@ -192,11 +206,11 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
handle(b)?.checked_subspan(b.len(), s.offset + offset, bytes)
}
}
impl<'a, 'ctx> OriginalVerifyResources<'a, 'ctx> {
impl<'ctx> OriginalVerifyResources<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
journal: OriginalVerifyGdnJournal<'a, 'ctx>,
qsa: Rc<crate::OriginalVerifyQsaJournal<'a, 'ctx>>,
journal: OriginalVerifyGdnJournal<'ctx>,
qsa: Rc<crate::OriginalVerifyQsaJournal<'ctx>>,
head: crate::OriginalNativeHeadRows<'ctx>,
) -> Result<Self> {
journal.validate_context(context)?;
@@ -205,8 +219,8 @@ impl<'a, 'ctx> OriginalVerifyResources<'a, 'ctx> {
Ok(Self { context, journal, qsa, head })
}
}
impl resources::Sealed for OriginalVerifyResources<'_, '_> {}
impl OriginalGraphResources for OriginalVerifyResources<'_, '_> {
impl resources::Sealed for OriginalVerifyResources<'_> {}
impl OriginalGraphResources for OriginalVerifyResources<'_> {
fn validate_context(&self, context: &Context<'_>) -> Result<()> {
if !std::ptr::eq(self.context, context) {
return Err(Error::ContextMismatch);
@@ -216,15 +230,15 @@ impl OriginalGraphResources for OriginalVerifyResources<'_, '_> {
self.head.validate_context(context)
}
}
impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx> {
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyResources<'ctx> {
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'ctx> {
self.qsa.as_ref()
}
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> {
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'ctx> {
&self.journal
}
}
impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResources<'_, 'ctx> {
impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResources<'ctx> {
fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> {
Ok(&self.head)
}
@@ -233,12 +247,12 @@ impl<'ctx> crate::OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyResou
}
}
impl OriginalVerifyGdnJournal<'_, '_> {
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()
self.ple.as_ref().map(|b| Ok(handle(b)?.qwen_address())).transpose()
}
pub(crate) fn canonical_identity(&self) -> usize {
Rc::as_ptr(&self.canonical) as usize
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyGdnJournal<'ctx> {
/// Exact batch convolution, BF16 MMVF alpha/beta, and recurrence. Canonical
/// state/history are READ ONLY; retained qkv/h/gate/beta banks span all36 layers.
pub fn capture_layer_stage(
@@ -22,7 +22,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
self.submit(capture, single_command(commands.swap_remove(stage as usize))?)
}
/// The range check and the arena spans one layer stage works on.
fn stage_operands(&self, layer: usize, begin: usize, end: usize) -> Result<StageOperands> {
pub(super) fn stage_operands(&self, layer: usize, begin: usize, end: usize) -> Result<StageOperands> {
let g = self.physical.layout.geometry;
if layer >= 36 || begin >= end || end > g.max_t {
return Err(Error::InvalidQwenShape);
@@ -50,7 +50,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
vec![
Arg::Address(self.canonical.span(op.layer, true)?),
Arg::Address(op.qkv),
Arg::Address(admit(self.physical.context, w.conv, 10240 * 4 * 4)?),
Arg::Address(admit(self.physical.context, &w.conv, 10240 * 4 * 4)?),
Arg::Address(op.h),
Arg::I32(10240),
Arg::I32(32),
@@ -68,10 +68,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
[256, 1, 1],
vec![
Arg::Address(self.physical.span("mixed", op.begin * g.n * 4, n * g.n * 4)?),
Arg::Address(admit(c, w.alpha, 48 * 2560 * 2)?),
Arg::Address(admit(c, w.beta, 48 * 2560 * 2)?),
Arg::Address(admit(c, w.dt, 48 * 4)?),
Arg::Address(admit(c, w.a, 48 * 4)?),
Arg::Address(admit(c, &w.alpha, 48 * 2560 * 2)?),
Arg::Address(admit(c, &w.beta, 48 * 2560 * 2)?),
Arg::Address(admit(c, &w.dt, 48 * 4)?),
Arg::Address(admit(c, &w.a, 48 * 4)?),
Arg::Address(op.gate + (op.begin * 48 * 4) as u64),
Arg::Address(op.beta + (op.begin * 48 * 4) as u64),
Arg::I32(2560),
@@ -93,7 +93,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
Arg::Address(op.gate),
Arg::Address(op.beta),
Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?),
Arg::Address(admit(self.physical.context, w.norm, 128 * 4)?),
Arg::Address(admit(self.physical.context, &w.norm, 128 * 4)?),
Arg::F32(EPS),
Arg::Address(self.physical.span("y", 0, g.max_t * 6144 * 4)?),
Arg::I32(16),
@@ -115,10 +115,10 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
kernels::LaunchExtent::new([96, 1, 1], [32, 1, 1], 0),
vec![
kernels::A::P(x),
kernels::A::P(admit(c, w.alpha, 48 * 2560 * 2)?),
kernels::A::P(admit(c, w.beta, 48 * 2560 * 2)?),
kernels::A::P(admit(c, w.dt, 48 * 4)?),
kernels::A::P(admit(c, w.a, 48 * 4)?),
kernels::A::P(admit(c, &w.alpha, 48 * 2560 * 2)?),
kernels::A::P(admit(c, &w.beta, 48 * 2560 * 2)?),
kernels::A::P(admit(c, &w.dt, 48 * 4)?),
kernels::A::P(admit(c, &w.a, 48 * 4)?),
kernels::A::P(op.gate + (op.begin * 48 * 4) as u64),
kernels::A::P(op.beta + (op.begin * 48 * 4) as u64),
kernels::A::I32(2560),
@@ -187,7 +187,7 @@ impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
Arg::Address(op.gate),
Arg::Address(op.beta),
Arg::Address(self.physical.span("z", 0, g.max_t * 6144 * 4)?),
Arg::Address(admit(self.physical.context, self.weights[op.layer].norm, 128 * 4)?),
Arg::Address(admit(self.physical.context, &self.weights[op.layer].norm, 128 * 4)?),
Arg::F32(EPS),
Arg::Address(self.physical.span("y_dummy", 0, g.max_t * 6144 * 4)?),
Arg::I32(16),
@@ -260,14 +260,14 @@ impl FusedSpans {
}
/// The arena spans and range of one GDN layer stage.
struct StageOperands {
layer: usize,
begin: usize,
end: usize,
qkv: u64,
h: u64,
gate: u64,
beta: u64,
pub(super) struct StageOperands {
pub(super) layer: usize,
pub(super) begin: usize,
pub(super) end: usize,
pub(super) qkv: u64,
pub(super) h: u64,
pub(super) gate: u64,
pub(super) beta: u64,
}
/// The base spans of the fused commit: layer `i` of every operand is `base + i * stride`.
@@ -284,7 +284,7 @@ struct FusedSpans {
small: usize,
}
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyGdnJournal<'ctx> {
/// Whether layer `i`'s per-layer spans are affine in the layer, as the fused commit assumes.
fn layer_is_affine(&self, i: usize, sp: &FusedSpans) -> Result<bool> {
Ok(self.canonical_affine(i, sp)? && self.window_affine(i, sp)?)
@@ -3,11 +3,11 @@
#[allow(unused_imports)]
use super::*;
impl<'ctx> OriginalVerifyGdnJournal<'_, 'ctx> {
impl<'ctx> OriginalVerifyGdnJournal<'ctx> {
/// The device history image the window rows advance (and the commit graph sets from `hist_snap`): the one buffer
/// all aggregates share.
pub(crate) fn ple_buffer(&self) -> Option<&DeviceBuffer<'ctx>> {
self.ple
self.ple.as_deref()
}
pub(crate) fn submit(&self, capture: &mut OriginalCapture<'_, 'ctx>, commands: Vec<Command>) -> Result<()> {
capture.validate_context(self.physical.context)?;
@@ -0,0 +1,155 @@
//! Re-arming a parked Original verifier for the next request (ledger row Q7, `docs/experiments/decode-graph-reuse.md`,
//! `docs/experiments/verify-decode-graph-reuse-handles.md`).
//!
//! A recorded verifier (arena, mapped staging, streams, event, the nine graphs) is bound to buffers whose ADDRESSES
//! the graphs captured, and to nothing else about a request: context length, positions and tokens are data staged
//! before every `run`. Keeping the recording across requests therefore needs the request-bound DATA put back to what
//! a fresh `OriginalVerifier::new` + `record_all` leaves, which is what this module defines:
//!
//! * [`OriginalVerifyRearm`], the seed of the next request: the session's recurrent priors (the canonical GDN image is
//! overwritten in place, same device address) and its PLE history;
//! * [`StagedWindow`], the host's memory of the window staged last, and [`ResetPlan`], the device and mapped memory a
//! fresh bank starts zeroed; both pure, so the tests run without a device;
//! * `OriginalVerifyBank::rearm`, which applies them and advances the bank generation so that every row and window
//! handle of the previous request is refused.
//!
//! The verifier side (`park`, `rearm`, its preconditions and counters) is
//! `original_verify_schedule/verifier_park_rearm.rs`.
use super::*;
/// The PLE history image: nine rows of `10240` f32 (the commit graph's `hist_snap` row).
const PLE_HISTORY_WORDS: usize = 9 * 10240;
/// The seed of the next request: the session's recurrent priors in the canonical image's layout, and its PLE history.
#[derive(Clone, Copy)]
pub struct OriginalVerifyRearm<'s> {
/// The 36 recurrent states, `128 * 48 * 128` f32 each.
pub gdn_states: [&'s [f32]; 36],
/// The 36 convolution histories, `10240 * 3` f32 each.
pub gdn_histories: [&'s [f32]; 36],
/// The PLE history image, `9 * 10240` f32.
pub ple_history: &'s [f32],
}
impl OriginalVerifyRearm<'_> {
/// Every slice has the exact length the images hold; nothing is touched before this passes.
pub(crate) fn check_shapes(&self) -> Result<()> {
if self.ple_history.len() != PLE_HISTORY_WORDS {
return Err(Error::InvalidQwenShape);
}
check_canonical_lengths(&self.gdn_states, &self.gdn_histories)
}
/// The PLE history image as the little-endian bytes the device holds.
pub(crate) fn ple_history_bytes(&self) -> Result<Vec<u8>> {
let mut bytes = Vec::new();
bytes.try_reserve_exact(PLE_HISTORY_WORDS * 4).map_err(|_| Error::HostAllocation)?;
for value in self.ple_history {
bytes.extend_from_slice(&value.to_le_bytes());
}
Ok(bytes)
}
}
/// What the bank remembers about the window staged last: its width, first position, tokens and kept prefix.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct StagedWindow {
pub t: usize,
pub position: usize,
pub tokens: [i32; 8],
pub keep: usize,
}
impl StagedWindow {
/// No window staged: the state of a fresh bank and of a re-armed one.
pub(super) const EMPTY: Self = Self { t: 0, position: 0, tokens: [0; 8], keep: 0 };
}
/// The host-side bookkeeping of a bank that a re-arm resets, as a value: the staged window, the generation that
/// handles of earlier windows are checked against, and whether the GPU waits were released.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Book {
pub staged: StagedWindow,
pub generation: u64,
pub released: bool,
}
impl Book {
/// The book of the next request: nothing staged, not released, and the generation one further, so that every
/// row and window handle minted for the previous request is refused.
pub(super) fn rearmed(self) -> Result<Self> {
let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?;
Ok(Self { staged: StagedWindow::EMPTY, generation, released: false })
}
}
/// The memory a fresh bank starts zeroed, and so a re-armed one: every mapped staging allocation (the token, step and
/// position words, the commit record, the PLE rows, the doorbell and the three flag words, the CPU rows and output,
/// the published GPU plan), the arena (all journals, tail and history snapshots, plan copy, expert staging, the
/// logits) and, with `STRATA_VERIFY_PROFILE`, the stamp words.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct ResetPlan {
pub mapped: usize,
pub arena_bytes: usize,
pub profile_bytes: Option<usize>,
}
impl ResetPlan {
pub(super) fn of(layout: &OriginalVerifyLayout, profile_bytes: Option<usize>) -> Self {
Self { mapped: layout.mapped_bytes.len(), arena_bytes: layout.bytes, profile_bytes }
}
}
impl Physical<'_> {
/// Put the mapped staging, the arena and the profile stamps back to zero, exactly as `initialize` left them. The
/// device is idle (the caller parked both streams); a failed transfer poisons the context as everywhere here.
pub(super) fn reset_to_recorded(&self) -> Result<()> {
self.validate(self.context)?;
let plan = ResetPlan::of(&self.layout, self.prof.as_ref().map(DeviceBuffer::len));
for cell in self.mapped.iter().take(plan.mapped) {
let mut slot = cell.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
slot.as_mut().ok_or(Error::ContextPoisoned)?.initialize_zero()?;
}
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
let guard = self.context.enter()?;
let zeroed = self.zero_device(plan);
let sync = self.context.driver.api.synchronize();
let pop = guard.finish();
if zeroed.as_ref().err().is_some_and(transport) || sync.is_err() || pop.is_err() {
self.failed.set(true);
poison(self.context)
}
combine(combine(zeroed, sync), pop)
}
/// The arena and, when present, the stamp words, zeroed inside an entered context.
fn zero_device(&self, plan: ResetPlan) -> Result<()> {
let arena = self.arena.as_ref().ok_or(Error::ContextPoisoned)?;
debug_assert_eq!(arena.len(), plan.arena_bytes);
self.context.driver.api.zero(handle(arena)?.qwen_address(), plan.arena_bytes)?;
if let (Some(prof), Some(bytes)) = (self.prof.as_ref(), plan.profile_bytes) {
self.context.driver.api.zero(handle(prof)?.qwen_address(), bytes)?;
}
Ok(())
}
}
impl OriginalVerifyBank<'_> {
/// Back to what `new` leaves, for the next request over the same recording. The generation advances FIRST (as
/// `stage` does) so every `OriginalVerifyRow` / `OriginalVerifyWindow` of the previous request is refused before
/// any state changes; then the host memory of the staged window, `released`, the held PCIe sources and the device
/// and mapped memory of [`ResetPlan`] are reset. `pcie_mode` and `pcie_roles` are part of the recording and stay.
/// The device must be idle. Returns the new generation.
pub(crate) fn rearm(&mut self) -> Result<u64> {
self.validate_context(self.physical.context)?;
let next = Book { staged: self.staged, generation: self.generation, released: self.released }.rearmed()?;
self.generation = next.generation;
self.physical.generation.set(next.generation);
self.staged = next.staged;
self.released = next.released;
self.release_pcie_sources();
self.physical.reset_to_recorded()?;
Ok(next.generation)
}
}
#[cfg(test)]
mod tests;
@@ -0,0 +1,90 @@
//! Unit tests of the pure half of the re-arm (no device): the seed shapes, the bookkeeping a bank resets and the
//! memory a re-armed bank zeroes. The device half is exercised by the identity job (see
//! `docs/experiments/verify-decode-graph-reuse-handles.md`).
use super::*;
const STATE_WORDS: usize = 128 * 48 * 128;
const HISTORY_WORDS: usize = 10240 * 3;
fn seed<'s>(state: &'s [f32], history: &'s [f32], ple: &'s [f32]) -> OriginalVerifyRearm<'s> {
OriginalVerifyRearm { gdn_states: [state; 36], gdn_histories: [history; 36], ple_history: ple }
}
#[test]
fn a_seed_of_the_exact_shapes_passes_and_every_other_shape_is_refused() {
let (state, history, ple) =
(vec![0.5f32; STATE_WORDS], vec![0.25f32; HISTORY_WORDS], vec![0.0f32; PLE_HISTORY_WORDS]);
assert_eq!(seed(&state, &history, &ple).check_shapes(), Ok(()));
assert_eq!(seed(&state, &history, &ple[1..]).check_shapes(), Err(Error::InvalidQwenShape));
assert_eq!(seed(&state[1..], &history, &ple).check_shapes(), Err(Error::InvalidQwenShape));
assert_eq!(seed(&state, &history[1..], &ple).check_shapes(), Err(Error::InvalidQwenShape));
let mut one_short = seed(&state, &history, &ple);
one_short.gdn_histories[35] = &history[..HISTORY_WORDS - 1];
assert_eq!(one_short.check_shapes(), Err(Error::InvalidQwenShape));
}
#[test]
fn the_ple_history_goes_to_the_device_as_little_endian_f32() {
let (state, history) = (vec![0.0f32; STATE_WORDS], vec![0.0f32; HISTORY_WORDS]);
let mut ple = vec![0.0f32; PLE_HISTORY_WORDS];
ple[0] = 1.0;
ple[PLE_HISTORY_WORDS - 1] = -2.5;
let bytes = seed(&state, &history, &ple).ple_history_bytes().unwrap();
assert_eq!(bytes.len(), PLE_HISTORY_WORDS * 4);
assert_eq!(bytes[..4], 1.0f32.to_le_bytes());
assert_eq!(bytes[bytes.len() - 4..], (-2.5f32).to_le_bytes());
}
fn staged_once() -> Book {
Book {
staged: StagedWindow { t: 5, position: 1234, tokens: [9, 8, 7, 6, 5, 0, 0, 0], keep: 3 },
generation: 41,
released: true,
}
}
#[test]
fn a_rearmed_book_has_nothing_staged_is_not_released_and_is_one_generation_on() {
let book = staged_once().rearmed().unwrap();
assert_eq!(book.staged, StagedWindow::EMPTY);
assert_eq!(book.staged, StagedWindow { t: 0, position: 0, tokens: [0; 8], keep: 0 });
assert!(!book.released);
// a handle minted at generation 41 (a row or window of the previous request) no longer matches
assert_eq!(book.generation, 42);
}
#[test]
fn every_rearm_advances_the_generation_by_exactly_one_and_the_counter_never_wraps() {
let mut book = staged_once();
for expected in 42..46 {
book = book.rearmed().unwrap();
assert_eq!(book.generation, expected);
}
let last = Book { generation: u64::MAX, ..staged_once() };
assert_eq!(last.rearmed(), Err(Error::InvalidSize));
}
#[test]
fn a_re_armed_bank_zeroes_every_mapped_allocation_the_arena_and_the_profile_stamps() {
let layout = OriginalVerifyLayout::new(kernels::test_geometry()).unwrap();
let plan = ResetPlan::of(&layout, Some(profile_stamp_words(48) * 8));
// all fifteen mapped allocations: the token/step/position words (0..=2), the commit record (3), the PLE rows (4),
// the sampled ids (5), the CPU activation, id and weight rows (6..=8), the doorbell and the three flag words
// (9..=12), the CPU output (13) and the published GPU plan (14)
assert_eq!(plan.mapped, 15);
assert!(layout.mapped_bytes.iter().all(|&bytes| bytes > 0));
assert!(layout.mapped_bytes[9..=12].iter().all(|&bytes| bytes == 64));
assert_eq!(plan.arena_bytes, layout.bytes);
assert_eq!(plan.profile_bytes, Some(profile_stamp_words(48) * 8));
assert_eq!(ResetPlan::of(&layout, None).profile_bytes, None);
}
#[test]
fn the_arena_plan_covers_the_spans_the_graphs_read_back_the_first_window() {
let layout = OriginalVerifyLayout::new(kernels::test_geometry()).unwrap();
// every span, including the snapshots the commit graph restores and the plan copy, lies inside the zeroed bytes
for name in ["tail_snap", "hist_snap", "plan", "staging", "head_logits", "commit", "tok"] {
let span = layout.span(name).unwrap();
assert!(span.offset + span.bytes <= layout.bytes, "{name} is inside the arena");
}
}
@@ -0,0 +1,273 @@
//! claude/verify-gdn-fused-kernels: the GDN layers of the verify window as fewer launches (`sm120_gdn_fused.cu`,
//! design note `docs/experiments/verify-gdn-fused-kernels.md`).
//!
//! Two independent opt-in switches (`original_verify_window_sm120.rs`, both off by default), one sealed sm_120-only
//! asset:
//!
//! * `LELEKA_SM120_FUSED_GDN`: a GDN layer's `verify_gdn_conv_l2_multi_kernel` + `verify_gdn_ab_multi_kernel` (or
//! `chain_gdn_ab_multi_kernel`) + `verify_gdn_step_norm_multi_kernel` are recorded as ONE launch,
//! `leleka_verify_gdn_fused_step`, at the place of the recurrence. With the side-stream GDN branch
//! (`LELEKA_SM120_SIDE_MIXER`) only the conv is fused: the gates stay on side stream 0 and are read.
//! * `LELEKA_SM120_GDN_AB_UNROLL`: upstream `STRATA_SMALL_UNR` bit 1 (`gdn_ab_body`), the a/b projection with constant
//! trip counts, as its own kernel (`leleka_gdn_ab_unrolled_t*`) wherever the a/b projection runs as a kernel of its
//! own (no `FUSED_GDN`, or the side-stream branch).
//!
//! Both compute every output word with the operations of the kernels they replace, in the same order.
use super::kernels::{A, AssetSpec, Launch, LaunchExtent};
use super::sm120::Sm120Switches;
// `ptx` below is read from `../sm120_gdn_fused.ptx` (this file lives one directory below the sealed assets)
use crate::{Error, Result};
pub(crate) const E_FUSED_STEP: &str = "leleka_verify_gdn_fused_step";
/// Unrolled a/b kernels: constant token count for T = 1..=6, the run time count for T = 7 and 8 (upstream's split).
pub(crate) const E_AB_UNROLLED: [&str; 7] = [
"leleka_gdn_ab_unrolled_t1",
"leleka_gdn_ab_unrolled_t2",
"leleka_gdn_ab_unrolled_t3",
"leleka_gdn_ab_unrolled_t4",
"leleka_gdn_ab_unrolled_t5",
"leleka_gdn_ab_unrolled_t6",
"leleka_gdn_ab_unrolled_t8",
];
const ENTRIES: [&str; 8] = [
E_FUSED_STEP,
E_AB_UNROLLED[0],
E_AB_UNROLLED[1],
E_AB_UNROLLED[2],
E_AB_UNROLLED[3],
E_AB_UNROLLED[4],
E_AB_UNROLLED[5],
E_AB_UNROLLED[6],
];
/// `sm120_gdn_fused.cu` (nvcc 13.2.86, `--fmad=true --ftz=false`), sealed by `scripts/gpu-bringup/seal_pins.py`
/// (extra-seal-plan.json, group sm120-decode).
pub(crate) static GDN_FUSED: AssetSpec = AssetSpec {
name: "sm120_gdn_fused.ptx",
ptx: concat!(include_str!("../sm120_gdn_fused.ptx"), "\0").as_bytes(),
sha: [
157, 163, 62, 130, 23, 193, 228, 218, 162, 210, 111, 151, 57, 135, 73, 120, 233, 194, 6, 235, 95, 48, 249, 65,
127, 93, 248, 181, 38, 227, 127, 23,
],
entries: &ENTRIES,
unsealed: "Original verifier asset unsealed: sm120_gdn_fused.ptx (fused GDN layer step, unrolled GDN alpha/beta)",
};
/// The window's rows of the verify graph and the width of the a/b projection input.
pub(crate) const MAX_ROWS: usize = 8;
const N_EMBD: i32 = 2560;
const VALUE_HEADS: u32 = 48;
/// What one `WindowOps` call of a GDN layer records.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GdnStep {
/// Nothing: another call covers it.
Skip,
/// The Original's kernel of this stage (or the chain kernel when `LELEKA_CHAIN_AB` is on).
Original,
/// The unrolled a/b kernel of `LELEKA_SM120_GDN_AB_UNROLL`.
AbUnrolled,
/// The fused launch (conv, gates and step), with the gates computed inside or read.
Fused(GateSource),
}
/// Where the fused launch gets gate and beta.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum GateSource {
/// Computed by two warps of every block and written to `gate` / `beta`.
InKernel,
/// Already in `gate` / `beta` (the side-stream branch computed them and joined before the launch).
Joined,
}
/// The three `WindowOps` calls of a GDN layer, in graph order.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GdnStages {
pub conv: GdnStep,
pub alpha_beta: GdnStep,
pub recurrence: GdnStep,
}
impl GdnStages {
/// Kernel launches the layer records on the capture stream, without the side-stream branch.
#[cfg(test)]
pub(crate) fn launches(&self) -> usize {
[self.conv, self.alpha_beta, self.recurrence].iter().filter(|s| **s != GdnStep::Skip).count()
}
}
/// The resolved switches of one window recording.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) struct GdnFusedPolicy {
pub fused_step: bool,
pub ab_unroll: bool,
}
impl GdnFusedPolicy {
pub(crate) fn from_switches(s: &Sm120Switches) -> Self {
Self { fused_step: s.fused_gdn, ab_unroll: s.gdn_ab_unroll }
}
/// The asset the window preloads before capture (none when both switches are off).
pub(crate) fn assets(self) -> Vec<&'static AssetSpec> {
if self.fused_step || self.ab_unroll { vec![&GDN_FUSED] } else { Vec::new() }
}
/// The a/b stage as a kernel of its own (a graph without `FUSED_GDN`, and the side-stream branch).
pub(crate) fn separate_ab(self) -> GdnStep {
if self.ab_unroll { GdnStep::AbUnrolled } else { GdnStep::Original }
}
/// What the three calls of a GDN layer record; `side_gdn`: the gates run on side stream 0.
pub(crate) fn stages(self, side_gdn: bool) -> GdnStages {
if self.fused_step {
let gates = if side_gdn { GateSource::Joined } else { GateSource::InKernel };
return GdnStages { conv: GdnStep::Skip, alpha_beta: GdnStep::Skip, recurrence: GdnStep::Fused(gates) };
}
let alpha_beta = if side_gdn { GdnStep::Skip } else { self.separate_ab() };
GdnStages { conv: GdnStep::Original, alpha_beta, recurrence: GdnStep::Original }
}
}
/// Resolves the switches for the card and loads the asset before capture (module loading is not capturable). A
/// requested switch whose asset is not sealed refuses the recording, so a paired A/B never runs the default path
/// under the name of the switch.
pub(crate) fn prepare(journal: &super::OriginalVerifyGdnJournal<'_>) -> Result<GdnFusedPolicy> {
let major = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
let minor = journal.window_device_attribute(super::gr::ATTR_COMPUTE_CAPABILITY_MINOR)?;
let policy = GdnFusedPolicy::from_switches(&Sm120Switches::from_env(major, minor));
journal.ensure_window_assets(&policy.assets())?;
if policy != GdnFusedPolicy::default() {
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| eprintln!("leleka-serve gdn kernels: {policy:?} (compute capability {major}.{minor})"));
}
Ok(policy)
}
/// Device addresses of the buffers of one GDN layer the fused launch reads and writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct FusedGdnBuffers {
/// Canonical recurrence state of the layer (read only: the window never writes it).
pub state: u64,
/// Canonical conv history of the layer (read only).
pub hist: u64,
pub qkv: u64,
pub conv_w: u64,
/// Conv + L2 rows: written for the new tokens (q and k by the blocks of value heads 0..16, v by every block).
pub h: u64,
pub gate: u64,
pub beta: u64,
pub z: u64,
pub gamma: u64,
pub y: u64,
}
/// The a/b projection operands: the activation row of the first new token (0: gate and beta are already computed).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct GdnGateOperands {
pub x: u64,
pub alpha_w: u64,
pub beta_w: u64,
pub dt: u64,
pub a: u64,
}
impl GdnGateOperands {
pub(crate) const JOINED: Self = Self { x: 0, alpha_w: 0, beta_w: 0, dt: 0, a: 0 };
}
/// The rows a stage works on: the new tokens `begin..end`; the tokens before `begin` are replayed from the buffers.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct RowSpan {
pub begin: usize,
pub end: usize,
}
/// One launch of `leleka_verify_gdn_fused_step`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct FusedGdnStep {
pub buffers: FusedGdnBuffers,
pub gates: GdnGateOperands,
pub rows: RowSpan,
pub eps: f32,
}
impl FusedGdnStep {
/// The by-value kernel argument `FusedGdnArgs` of `sm120_gdn_fused.cu`, in declaration order.
pub(crate) fn words(&self) -> Vec<u64> {
let (b, g) = (&self.buffers, &self.gates);
vec![
b.state,
b.hist,
b.qkv,
b.conv_w,
b.h,
b.gate,
b.beta,
b.z,
b.gamma,
b.y,
g.x,
g.alpha_w,
g.beta_w,
g.dt,
g.a,
u64::from(self.eps.to_bits()),
self.rows.begin as u64,
self.rows.end as u64,
]
}
/// 48 blocks (one per value head) of 128 x 4 threads, as the Original's step kernel.
pub(crate) fn launch(&self) -> Result<Launch> {
if self.rows.begin >= self.rows.end || self.rows.end > MAX_ROWS {
return Err(Error::InvalidQwenShape);
}
Launch::new(
&GDN_FUSED,
E_FUSED_STEP,
LaunchExtent::new([VALUE_HEADS, 1, 1], [128, 4, 1], 0),
vec![A::Words(self.words())],
)
}
}
/// One launch of the unrolled a/b projection: the Original's arguments, `rows` tokens.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct AbUnrolledStep {
pub gates: GdnGateOperands,
/// `gate` and `beta` of the first token of the stage.
pub gate: u64,
pub beta: u64,
pub rows: usize,
}
impl AbUnrolledStep {
/// The entry for `rows` tokens: constant count up to 6, the run time count above (upstream's `kVerifyNarrowT`).
pub(crate) fn entry(rows: usize) -> Result<&'static str> {
match rows {
1..=6 => Ok(E_AB_UNROLLED[rows - 1]),
7 | 8 => Ok(E_AB_UNROLLED[6]),
_ => Err(Error::InvalidQwenShape),
}
}
/// One warp a row of the 96 (alpha, then beta): 96 blocks of 32 threads, the shape of `chain_gdn_ab_multi_kernel`
/// (what `LELEKA_CHAIN=all` records), so the unrolled loop is the only difference to the shipped kernel. Upstream's
/// own shape, 48 blocks of 64 threads, runs the same kernel.
pub(crate) fn launch(&self) -> Result<Launch> {
let g = &self.gates;
let args = vec![
A::P(g.x),
A::P(g.alpha_w),
A::P(g.beta_w),
A::P(g.dt),
A::P(g.a),
A::P(self.gate),
A::P(self.beta),
A::I32(N_EMBD),
A::I32(VALUE_HEADS as i32),
A::I32(self.rows as i32),
];
Launch::new(
&GDN_FUSED,
Self::entry(self.rows)?,
LaunchExtent::new([2 * VALUE_HEADS, 1, 1], [32, 1, 1], 0),
args,
)
}
}
#[cfg(test)]
#[path = "original_verify_window_gdn_fused/tests.rs"]
mod tests;
@@ -0,0 +1,311 @@
use super::*;
use crate::original_verify::sm120::{DEFAULT_ON_FUSED_GDN, DEFAULT_ON_GDN_AB_UNROLL};
const FUSED_PTX: &str = include_str!("../../sm120_gdn_fused.ptx");
const FUSED_CU: &str = include_str!("../../sm120_gdn_fused.cu");
const ORIGINAL_PTX: &str = include_str!("../../original_verify.ptx");
const CHAIN_PTX: &str = include_str!("../../chain_window.ptx");
fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
move |k| pairs.iter().find(|(n, _)| *n == k).map(|(_, v)| v.to_string())
}
fn policy(major: i32, minor: i32, pairs: &'static [(&'static str, &'static str)]) -> GdnFusedPolicy {
GdnFusedPolicy::from_switches(&Sm120Switches::resolve(major, minor, env(pairs)))
}
#[test]
fn both_switches_are_off_by_default() {
assert!(!DEFAULT_ON_FUSED_GDN && !DEFAULT_ON_GDN_AB_UNROLL);
assert_eq!(policy(12, 0, &[]), GdnFusedPolicy::default());
assert_eq!(policy(12, 0, &[("LELEKA_SM120_PERF", "0")]), GdnFusedPolicy::default());
assert!(policy(12, 0, &[]).assets().is_empty());
}
#[test]
fn each_variable_turns_on_its_own_switch_and_nothing_else() {
let fused = policy(12, 0, &[("LELEKA_SM120_FUSED_GDN", "1")]);
assert_eq!(fused, GdnFusedPolicy { fused_step: true, ab_unroll: false });
let unroll = policy(12, 0, &[("LELEKA_SM120_GDN_AB_UNROLL", "on")]);
assert_eq!(unroll, GdnFusedPolicy { fused_step: false, ab_unroll: true });
let both = policy(12, 1, &[("LELEKA_SM120_FUSED_GDN", "1"), ("LELEKA_SM120_GDN_AB_UNROLL", "1")]);
assert_eq!(both, GdnFusedPolicy { fused_step: true, ab_unroll: true });
assert!(!policy(12, 0, &[("LELEKA_SM120_FUSED_GDN", "0")]).fused_step);
for p in [fused, unroll, both] {
assert_eq!(p.assets().len(), 1);
assert!(std::ptr::eq(p.assets()[0], &GDN_FUSED));
}
}
#[test]
fn a_card_below_compute_capability_12_never_takes_a_switch() {
let on = &[("LELEKA_SM120_FUSED_GDN", "1"), ("LELEKA_SM120_GDN_AB_UNROLL", "1")];
assert_eq!(policy(8, 6, on), GdnFusedPolicy::default());
assert_eq!(policy(9, 0, on), GdnFusedPolicy::default());
}
#[test]
fn the_asset_is_sealed_and_exports_every_entry() {
GDN_FUSED.assert_sealed_and_fail_closed();
assert_eq!(GDN_FUSED.entries.len(), 1 + E_AB_UNROLLED.len());
assert!(GDN_FUSED.has_entry(E_FUSED_STEP));
}
#[test]
fn a_default_layer_records_the_original_three_kernels() {
let off = GdnFusedPolicy::default();
let stages = off.stages(false);
let original = GdnStep::Original;
assert_eq!(stages, GdnStages { conv: original, alpha_beta: original, recurrence: original });
assert_eq!(stages.launches(), 3);
// side-stream branch: the gates are another stream's launch, three kernels in all
let side = off.stages(true);
assert_eq!(side.alpha_beta, GdnStep::Skip);
assert_eq!(side.launches() + 1, 3);
}
#[test]
fn the_fused_switch_records_one_launch_per_layer() {
let on = GdnFusedPolicy { fused_step: true, ab_unroll: false };
let stages = on.stages(false);
assert_eq!(stages.conv, GdnStep::Skip);
assert_eq!(stages.alpha_beta, GdnStep::Skip);
assert_eq!(stages.recurrence, GdnStep::Fused(GateSource::InKernel));
assert_eq!(stages.launches(), 1);
// 36 layers: 108 launches against 36
assert_eq!(36 * GdnFusedPolicy::default().stages(false).launches(), 108);
assert_eq!(36 * stages.launches(), 36);
}
#[test]
fn with_the_side_branch_only_the_conv_is_fused() {
let on = GdnFusedPolicy { fused_step: true, ab_unroll: false };
let side = on.stages(true);
assert_eq!(side.recurrence, GdnStep::Fused(GateSource::Joined));
assert_eq!((side.conv, side.alpha_beta), (GdnStep::Skip, GdnStep::Skip));
// the fused launch and the gates on side stream 0: two launches against the side branch's three
assert_eq!(side.launches() + 1, 2);
assert_eq!(GdnFusedPolicy::default().stages(true).launches() + 1, 3);
}
#[test]
fn the_unrolled_gates_replace_only_the_ab_kernel() {
let on = GdnFusedPolicy { fused_step: false, ab_unroll: true };
let stages = on.stages(false);
assert_eq!(stages.alpha_beta, GdnStep::AbUnrolled);
assert_eq!((stages.conv, stages.recurrence), (GdnStep::Original, GdnStep::Original));
assert_eq!(stages.launches(), 3);
// the side branch still issues the gates, as the unrolled kernel
assert_eq!(on.stages(true).alpha_beta, GdnStep::Skip);
assert_eq!(on.separate_ab(), GdnStep::AbUnrolled);
assert_eq!(GdnFusedPolicy::default().separate_ab(), GdnStep::Original);
// fused + unroll: the gates are inside the fused launch, the unrolled kernel is only for the side branch
let both = GdnFusedPolicy { fused_step: true, ab_unroll: true };
assert_eq!(both.stages(false).launches(), 1);
assert_eq!(both.separate_ab(), GdnStep::AbUnrolled);
}
fn step(begin: usize, end: usize, gates: GdnGateOperands) -> FusedGdnStep {
FusedGdnStep {
buffers: FusedGdnBuffers {
state: 0x100,
hist: 0x200,
qkv: 0x300,
conv_w: 0x400,
h: 0x500,
gate: 0x600,
beta: 0x700,
z: 0x800,
gamma: 0x900,
y: 0xa00,
},
gates,
rows: RowSpan { begin, end },
eps: 1e-6,
}
}
#[rustfmt::skip]
const KERNEL_ARGUMENT_MEMBERS: [&str; 18] = [
"state", "hist", "qkv", "conv_w", "h", "gate", "beta", "z", "gamma", "y",
"ab_x", "ab_alpha_w", "ab_beta_w", "ab_dt", "ab_a", "eps_bits", "t_begin", "t_end",
];
const GATES: GdnGateOperands = GdnGateOperands { x: 0xb00, alpha_w: 0xc00, beta_w: 0xd00, dt: 0xe00, a: 0xf00 };
#[test]
fn the_fused_launch_is_one_block_per_value_head_like_the_originals_step() {
let launch = step(0, 4, GATES).launch().unwrap();
assert_eq!((launch.grid, launch.block, launch.shared), ([48, 1, 1], [128, 4, 1], 0));
assert_eq!(launch.entry, E_FUSED_STEP);
assert!(std::ptr::eq(launch.asset, &GDN_FUSED));
assert_eq!(launch.args.len(), 1);
}
#[test]
fn the_argument_words_follow_the_struct_of_the_kernel_source() {
let words = step(2, 5, GATES).words();
assert_eq!(
words,
vec![0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700, 0x800, 0x900, 0xa00, 0xb00, 0xc00, 0xd00, 0xe00, 0xf00]
.into_iter()
.chain([u64::from(1e-6f32.to_bits()), 2, 5])
.collect::<Vec<u64>>()
);
let (_, body) = FUSED_CU.split_once("struct FusedGdnArgs {").expect("struct in the source");
let body = body.split_once("};").expect("end of the struct").0;
let members: Vec<&str> = body
.lines()
.filter_map(|l| l.trim().strip_prefix("uint64_t "))
.map(|l| l.split(';').next().unwrap().trim())
.collect();
assert_eq!(members, KERNEL_ARGUMENT_MEMBERS);
assert_eq!(members.len(), words.len());
}
#[test]
fn the_fused_launch_writes_what_the_three_kernels_write() {
// conv -> h, ab -> gate and beta, step -> y: the fused launch is given exactly these four (state and history are
// read only: the window never writes them), and a joined launch carries no activation row, so it computes no gate
let words = step(0, 3, GATES).words();
assert_eq!([words[4], words[5], words[6], words[9]], [0x500, 0x600, 0x700, 0xa00]);
assert_ne!(words[10], 0);
let joined = step(0, 3, GdnGateOperands::JOINED).words();
assert_eq!(joined[10..15], [0; 5]);
assert_eq!(joined[..10], words[..10]);
}
#[test]
fn the_fused_launch_refuses_empty_and_oversized_row_ranges() {
assert!(step(0, 8, GATES).launch().is_ok());
assert!(step(7, 8, GATES).launch().is_ok());
assert_eq!(step(3, 3, GATES).launch().unwrap_err(), Error::InvalidQwenShape);
assert_eq!(step(0, 9, GATES).launch().unwrap_err(), Error::InvalidQwenShape);
}
#[test]
fn the_unrolled_entry_follows_the_token_count_like_upstream() {
for rows in 1..=6 {
assert_eq!(AbUnrolledStep::entry(rows).unwrap(), format!("leleka_gdn_ab_unrolled_t{rows}"));
}
assert_eq!(AbUnrolledStep::entry(7).unwrap(), "leleka_gdn_ab_unrolled_t8");
assert_eq!(AbUnrolledStep::entry(8).unwrap(), "leleka_gdn_ab_unrolled_t8");
assert!(AbUnrolledStep::entry(0).is_err() && AbUnrolledStep::entry(9).is_err());
}
#[test]
fn the_unrolled_launch_takes_the_arguments_of_the_original_ab_kernel() {
let unrolled = AbUnrolledStep { gates: GATES, gate: 0x1100, beta: 0x1200, rows: 4 };
let launch = unrolled.launch().unwrap();
// verify_gdn_ab_multi_kernel(x, wa, wb, dt, ssm_a, gate, beta, n = 2560, h_v = 48, T)
assert_eq!(
launch.args,
vec![
A::P(0xb00),
A::P(0xc00),
A::P(0xd00),
A::P(0xe00),
A::P(0xf00),
A::P(0x1100),
A::P(0x1200),
A::I32(2560),
A::I32(48),
A::I32(4)
]
);
assert_eq!((launch.grid, launch.block), ([96, 1, 1], [32, 1, 1]));
assert!(AbUnrolledStep { rows: 0, ..unrolled }.launch().is_err());
}
// ---- the sealed PTX against the Original's: same operations in the same order (CPU-side, no GPU) ----
/// The body of the `.entry` whose name is exactly `name`.
fn entry_body<'t>(ptx: &'t str, name: &str) -> &'t str {
let start = ptx.find(&format!(".entry {name}(")).unwrap_or_else(|| panic!("no entry {name}"));
let end = ptx[start..].find("\n}\n").map_or(ptx.len(), |e| start + e);
&ptx[start..end]
}
/// Float arithmetic, shuffles and barriers of an entry, in program order (loads, stores, moves and address
/// arithmetic differ between a fused and a split producer).
fn numeric_sequence(body: &str) -> Vec<String> {
let numeric = |op: &str| {
let float = ["add", "sub", "mul", "fma", "div", "rcp", "rsqrt", "ex2"].iter().any(|p| op.starts_with(p));
(float && op.contains(".f32")) || op.starts_with("shfl.") || op.starts_with("bar.sync")
};
body.lines()
.map(str::trim)
.map(|l| if l.starts_with('@') { l.split_once(' ').map_or("", |(_, rest)| rest.trim()) } else { l })
.filter_map(|l| l.split_whitespace().next())
.map(|op| op.trim_end_matches(';'))
.filter(|op| numeric(op))
.map(str::to_owned)
.collect()
}
fn ops(names: &[&str]) -> Vec<String> {
names.iter().map(|s| s.to_string()).collect()
}
fn contains_run(hay: &[String], needle: &[String]) -> bool {
!needle.is_empty() && hay.windows(needle.len()).any(|w| w == needle)
}
fn distinct(seq: &[String]) -> std::collections::BTreeSet<&str> {
seq.iter().map(String::as_str).collect()
}
#[test]
fn the_fused_conv_is_the_originals_conv_instruction_for_instruction() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_conv_l2_multi_kernel"));
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
// mul + 3 fma (the four taps), silu by div.rn, y * y, five butterfly adds, the barrier, the L2 sum, rsqrt, scale
assert_eq!(original.len(), 26, "{original:?}");
assert!(contains_run(&fused, &original), "the conv of the Original is not a run of the fused kernel");
}
#[test]
fn the_fused_step_keeps_the_originals_unfused_delta_and_its_output_tail() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_step_norm_multi_kernel"));
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
// kv_col (three adds), then delta = beta * (v - g * kv): mul, sub, mul and no fma (ptxas contracts a plain
// mul + sub into one FFMA at load time, in the Original and in this kernel alike)
let delta = ops(&["add.f32", "add.f32", "add.f32", "mul.f32", "sub.f32", "mul.f32"]);
assert!(contains_run(&original, &delta) && contains_run(&fused, &delta));
// oc = sum * rsqrt(128) (evaluated at run time), the five butterfly adds, ss/128 + eps as one fma, rsqrt, three
// multiplies, the sigmoid by rcp.rn
#[rustfmt::skip]
let tail = ops(&[
"add.f32", "add.f32", "add.f32", "rsqrt.approx.f32", "mul.f32", "mul.f32",
"shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32",
"shfl.sync.bfly.b32", "add.f32", "shfl.sync.bfly.b32", "add.f32", "bar.sync",
"add.f32", "add.f32", "add.f32", "fma.rn.f32", "rsqrt.approx.f32", "mul.f32", "mul.f32", "mul.f32",
"ex2.approx.f32", "add.f32", "rcp.rn.f32", "mul.f32",
]);
assert!(contains_run(&original, &tail), "the Original's tail changed");
assert!(contains_run(&fused, &tail), "the fused output tail differs from the Original's");
}
#[test]
fn the_fused_kernel_has_no_flavour_the_original_kernels_do_not_have() {
let mut union: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
for name in ["verify_gdn_conv_l2_multi_kernel", "verify_gdn_ab_multi_kernel", "verify_gdn_step_norm_multi_kernel"] {
union.extend(distinct(&numeric_sequence(entry_body(ORIGINAL_PTX, name))).into_iter().map(str::to_owned));
}
let fused = numeric_sequence(entry_body(FUSED_PTX, E_FUSED_STEP));
let fused_set: std::collections::BTreeSet<String> = distinct(&fused).into_iter().map(str::to_owned).collect();
assert_eq!(fused_set, union);
// no explicit-rounding intrinsic, no flush to zero, no approximate division: plain contractible forms only
assert!(fused.iter().all(|op| !op.contains(".ftz") && !op.contains("div.approx") && !op.contains("div.full")));
assert!(fused.iter().all(|op| !matches!(op.as_str(), "add.rn.f32" | "mul.rn.f32" | "sub.rn.f32")));
}
#[test]
fn every_unrolled_ab_kernel_has_the_original_ab_kernels_flavours() {
let original = numeric_sequence(entry_body(ORIGINAL_PTX, "verify_gdn_ab_multi_kernel"));
let chain = numeric_sequence(entry_body(CHAIN_PTX, "chain_gdn_ab_multi_kernel"));
assert_eq!(distinct(&original), distinct(&chain));
for entry in E_AB_UNROLLED {
let unrolled = numeric_sequence(entry_body(FUSED_PTX, entry));
assert_eq!(distinct(&unrolled), distinct(&original), "{entry}");
// the multiply-adds of the dot product: eight per weight word and token, ten passes
let fmas = |seq: &[String]| seq.iter().filter(|op| *op == "fma.rn.f32").count();
let tokens: usize = entry.rsplit('t').next().unwrap().parse().unwrap();
assert!(fmas(&unrolled) >= 8 * 10 * tokens, "{entry}: {} fmas", fmas(&unrolled));
}
}
@@ -10,6 +10,8 @@ pub(super) use verify_bank_and_canonical_gdn_open::admission;
#[allow(unused_imports)]
pub(super) use verify_bank_and_canonical_gdn_open::admit;
#[allow(unused_imports)]
pub(super) use verify_bank_and_canonical_gdn_open::check_canonical_lengths;
#[allow(unused_imports)]
pub(super) use verify_bank_and_canonical_gdn_open::check_commands;
#[allow(unused_imports)]
pub(super) use verify_bank_and_canonical_gdn_open::command;
@@ -15,11 +15,8 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
}
Ok(Self {
physical: Rc::new(owner),
last_t: 0,
last_position: 0,
last_tokens: [0; 8],
staged: StagedWindow::EMPTY,
generation: 0,
last_keep: 0,
released: false,
pcie_sources: Vec::new(),
pcie_mode: 0,
@@ -28,21 +25,21 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
}
pub(crate) fn staged_window(&self) -> Result<(u64, usize, usize)> {
self.validate_context(self.physical.context)?;
if self.last_t == 0 || self.released {
if self.staged.t == 0 || self.released {
return Err(Error::InvalidQwenShape);
}
Ok((self.generation, self.last_position, self.last_t))
Ok((self.generation, self.staged.position, self.staged.t))
}
pub(crate) fn staged_keep(&self) -> Result<usize> {
self.staged_window()?;
if !(1..=self.last_t).contains(&self.last_keep) {
if !(1..=self.staged.t).contains(&self.staged.keep) {
return Err(Error::InvalidQwenShape);
}
Ok(self.last_keep)
Ok(self.staged.keep)
}
pub(crate) fn completed_row(&self, row: usize) -> Result<OriginalVerifyRow<'ctx>> {
self.staged_window()?;
if row >= self.last_t {
if row >= self.staged.t {
return Err(Error::InvalidQwenShape);
}
let bytes = self.geometry().hc * self.geometry().n * 4;
@@ -51,7 +48,7 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
physical: self.physical.clone(),
generation: self.generation,
row,
position: self.last_position + row,
position: self.staged.position + row,
})
}
pub fn allocated_bytes(&self) -> usize {
@@ -76,16 +73,16 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
// A failed partial staging cannot retain old generation authority.
self.generation = generation;
self.physical.generation.set(generation);
self.last_t = 0;
self.last_keep = 0;
self.staged.t = 0;
self.staged.keep = 0;
self.write_staged_rows(tokens, position)?;
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
self.last_t = tokens.len();
self.last_position = position;
self.last_tokens[..tokens.len()].copy_from_slice(tokens);
self.staged.t = tokens.len();
self.staged.position = position;
self.staged.tokens[..tokens.len()].copy_from_slice(tokens);
self.generation = generation;
self.physical.generation.set(generation);
self.last_keep = 0;
self.staged.keep = 0;
Ok(generation)
}
fn check_stage(&self, tokens: &[i32], position: usize) -> Result<()> {
@@ -140,7 +137,9 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
}
pub(crate) fn stage_ple(&mut self, values: &[f32]) -> Result<()> {
self.validate_context(self.physical.context)?;
if self.last_t == 0 || values.len() != self.last_t * self.geometry().n || values.iter().any(|x| !x.is_finite())
if self.staged.t == 0
|| values.len() != self.staged.t * self.geometry().n
|| values.iter().any(|x| !x.is_finite())
{
return Err(Error::InvalidQwenShape);
}
@@ -157,7 +156,7 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
}
pub(crate) fn stage_commit(&mut self, keep: usize) -> Result<()> {
self.validate_context(self.physical.context)?;
if !(1..=self.last_t).contains(&keep) {
if !(1..=self.staged.t).contains(&keep) {
return Err(Error::InvalidQwenShape);
}
let m = &self.physical.mapped;
@@ -166,11 +165,11 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
m.write(0, &(keep as i32).to_le_bytes())?;
m.write(4, &(keep as i32 - 1).to_le_bytes())?;
for t in 0..self.geometry().max_t {
let p = if t < keep { (self.last_position + t) as i32 } else { -1 };
let p = if t < keep { (self.staged.position + t) as i32 } else { -1 };
m.write((2 + t) * 4, &p.to_le_bytes())?
}
std::sync::atomic::fence(std::sync::atomic::Ordering::SeqCst);
self.last_keep = keep;
self.staged.keep = keep;
Ok(())
}
pub(crate) fn release_gpu_waits(&mut self) -> Result<()> {
@@ -103,7 +103,7 @@ impl<'ctx> Context<'ctx> {
OriginalVerifyBank::new(self, geometry)
}
}
fn check_canonical_lengths(states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
pub(in super::super) fn check_canonical_lengths(states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
for i in 0..36 {
if states[i].len() != STATE_WORDS || histories[i].len() != HISTORY_WORDS {
return Err(Error::InvalidQwenShape);
@@ -131,16 +131,23 @@ fn encode_layer(bytes: &mut [u8], state: &[f32], history: &[f32]) -> bool {
impl Canonical<'_> {
/// One pass per layer converts to little-endian bytes and checks every word finite; a non-finite word refuses the
/// intake before the layer is uploaded.
fn upload_layers(&mut self, states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
fn upload_layers(&self, states: &[&[f32]; 36], histories: &[&[f32]; 36]) -> Result<()> {
let mut bytes = zero(LAYER_BYTES)?;
for i in 0..36 {
if !encode_layer(&mut bytes, states[i], histories[i]) {
return Err(Error::NonFiniteMmqOutput("Original canonical GDN intake"));
}
self.buffer.as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(i * LAYER_BYTES, &bytes)?;
self.buffer.as_ref().ok_or(Error::ContextPoisoned)?.copy_from_range_shared(i * LAYER_BYTES, &bytes)?;
}
Ok(())
}
/// Overwrite the image in place (same device address, so every graph that captured it stays valid) with the next
/// request's priors: the same checks and the same per-layer transfers as the intake of `new`.
pub(in super::super) fn reseed(&self, states: [&[f32]; 36], histories: [&[f32]; 36]) -> Result<()> {
check_canonical_lengths(&states, &histories)?;
self.validate_context(self.context)?;
self.upload_layers(&states, &histories)
}
pub fn allocated_bytes(&self) -> usize {
self.buffer.as_ref().map_or(0, DeviceBuffer::len)
}
@@ -222,6 +229,12 @@ impl OriginalVerifyCanonicalGdn<'_> {
}
self.inner.with_layer(layer, read)
}
/// Overwrite the image in place (same device address) with `states` and `histories`, 117.7 MB host to device. The
/// graphs that captured the image are idle: the caller parked the verifier first. A non-finite word refuses the
/// layer that holds it, after the layers before it were written (a partial reseed: the caller retires the set).
pub fn reseed(&self, states: [&[f32]; 36], histories: [&[f32]; 36]) -> Result<()> {
self.inner.reseed(states, histories)
}
pub fn close(self) -> Result<()> {
match Rc::try_unwrap(self.inner) {
Ok(mut owner) => owner.close_inner(),
@@ -78,15 +78,15 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
}
/// Fixed real layer operands and borrowed source weights remain alive inside
/// the graph aggregate. No host-made readiness or arbitrary handles enter.
pub fn gdn_journal<'a>(
pub fn gdn_journal(
&self,
canonical: &mut OriginalVerifyCanonicalGdn<'ctx>,
weights: [OriginalVerifyGdnWeights<'a, 'ctx>; 36],
ple: Option<&'a DeviceBuffer<'ctx>>,
) -> Result<OriginalVerifyGdnJournal<'a, 'ctx>> {
weights: [OriginalVerifyGdnWeights<'ctx>; 36],
ple: Option<DeviceRef<'ctx>>,
) -> Result<OriginalVerifyGdnJournal<'ctx>> {
let (owned, arena) = self.journal_buffers(canonical)?;
self.check_journal_weights(&weights, owned, arena)?;
if let Some(history) = ple {
if let Some(history) = &ple {
self.check_journal_ple(history, owned, arena)?;
}
Ok(OriginalVerifyGdnJournal {
@@ -114,18 +114,18 @@ impl<'ctx> OriginalVerifyBank<'ctx> {
/// Every layer operand fits its size and overlaps neither the canonical buffer nor the arena.
fn check_journal_weights(
&self,
weights: &[OriginalVerifyGdnWeights<'_, 'ctx>; 36],
weights: &[OriginalVerifyGdnWeights<'ctx>; 36],
owned: &DeviceBuffer<'ctx>,
arena: &DeviceBuffer<'ctx>,
) -> Result<()> {
for w in weights {
for (b, n) in [
(w.conv, 10240 * 4 * 4),
(w.alpha, 48 * 2560 * 2),
(w.beta, 48 * 2560 * 2),
(w.dt, 48 * 4),
(w.a, 48 * 4),
(w.norm, 128 * 4),
(&w.conv, 10240 * 4 * 4),
(&w.alpha, 48 * 2560 * 2),
(&w.beta, 48 * 2560 * 2),
(&w.dt, 48 * 4),
(&w.a, 48 * 4),
(&w.norm, 128 * 4),
] {
admit(self.physical.context, b, n)?;
if handle(b)?.overlaps(n, handle(owned)?, owned.len())
@@ -220,13 +220,13 @@ impl<'ctx> OriginalVerifyWindow<'ctx> {
}
}
/// The journal resolves arena spans for the pure window plans.
impl kernels::ArenaMap for OriginalVerifyGdnJournal<'_, '_> {
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<'_, '_> {
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)
@@ -129,6 +129,13 @@ impl Registration {
pub(super) fn end_window(&self) {
self.shared.active.store(false, Ordering::SeqCst);
}
/// No window yet: the numbers of a freshly registered verifier (a re-armed one starts the next request there).
pub(super) fn reset_window(&self) {
self.shared.rows.store(0, Ordering::SeqCst);
self.shared.first_position.store(0, Ordering::SeqCst);
self.shared.layer_step.store(0, Ordering::SeqCst);
self.shared.active.store(false, Ordering::SeqCst);
}
/// Raised by the owner (or a watchdog); later windows are refused.
pub(super) fn is_released(&self) -> bool {
self.shared.released.load(Ordering::SeqCst)
@@ -269,6 +276,26 @@ mod tests {
assert!(String::from_utf8(out).unwrap().contains("(last window, not the current stage)"));
}
#[test]
fn a_rearmed_registration_reports_no_window_until_the_next_one_begins() {
let _serial = serial();
let (cells, w) = words();
let r = Registration::new(w);
let used = snapshot_after_a_window(&r, &cells);
assert!(used.current && used.rows == 4);
// the mapped words are zeroed by the bank's re-arm; the registry's own numbers by this
for cell in cells.iter() {
cell.store(0, Ordering::SeqCst);
}
r.reset_window();
let fresh = r.snapshot();
assert_eq!((fresh.rows, fresh.first_position, fresh.host_layer_step), (0, 0, 0));
assert_eq!((fresh.gpu_rang, fresh.served, fresh.plan, fresh.copies), (0, 0, 0, 0));
assert!(!fresh.current && !fresh.released);
r.begin_window(2, 99);
assert_eq!((r.snapshot().rows, r.snapshot().first_position, r.snapshot().host_layer_step), (2, 99, 0));
}
#[test]
fn release_raises_every_flag_past_any_ring_and_waits_for_the_window() {
let _serial = serial();
@@ -219,15 +219,13 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
(kernel, staging, stride): (bool, u64, usize),
) -> Result<()> {
let flag_b = self.flag_b_host_address()?;
if kernel {
if !plan.pcie.is_empty() {
if flag_b_route(kernel, pcie.is_some()) == FlagBRoute::AtOnce {
if kernel && !plan.pcie.is_empty() {
self.bank.retain_pcie_source(Rc::clone(pcie.as_ref().ok_or(Error::InvalidQwenShape)?.bank))?;
}
return self.raise_flag_b();
}
let Some(source) = pcie else {
return self.raise_flag_b();
};
let source = pcie.ok_or(Error::InvalidQwenShape)?;
if !plan.pcie.is_empty() {
// The bank's registered bytes are read by the copy engine after this call returns: the bank
// stays retained by the verifier until the window's copy-stream fence.
@@ -266,6 +264,24 @@ impl<'ctx> schedule::OriginalVerifyCpuSink<'_, 'ctx> {
}
}
/// Where a group's flag B is raised from.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(super) enum FlagBRoute {
/// From the host at once.
AtOnce,
/// Queued on the copy stream behind the group's staging copies, so it lands only after them.
BehindStagingCopies,
}
/// The route of flag B for one group. Only a group staged by DMA waits for its copies; the copy kernel and a group
/// without a PCIe source raise at once. Flag B is one monotone ring word shared by the groups of a window, so a window
/// must not mix a staged group with an at-once group: the at-once raise of a later ring value would announce the
/// earlier group's copies as landed. The product never mixes them: whether a PCIe source exists is `pcie_num > 0` of
/// the round (`decode_parts.rs`), the same for every group of every window of that round.
pub(super) const fn flag_b_route(copy_kernel: bool, has_pcie_source: bool) -> FlagBRoute {
if copy_kernel || !has_pcie_source { FlagBRoute::AtOnce } else { FlagBRoute::BehindStagingCopies }
}
/// Enqueues the host-to-device copies of every PCIe expert's spans into its staging slot: one batched call for all
/// pieces (`many`), or one per piece.
fn stage_pcie<'ctx>(
@@ -71,3 +71,12 @@ fn a_corrupt_plan_is_refused_not_repaired() {
// more entries than the block holds
assert!(encode_plan_block(&layout, PlanEntryShape { cap: 40, k: 10, n_entries: 50 }, &[], &[]).is_err());
}
#[test]
fn flag_b_waits_for_the_staging_copies_only_for_a_dma_group_with_a_pcie_source() {
use plan_phases::{FlagBRoute::*, flag_b_route};
assert_eq!(flag_b_route(false, true), BehindStagingCopies, "DMA with a source: behind the copies");
assert_eq!(flag_b_route(false, false), AtOnce, "no PCIe source: at once");
assert_eq!(flag_b_route(true, true), AtOnce, "copy kernel: the graph stages, flag B at once");
assert_eq!(flag_b_route(true, false), AtOnce);
}
@@ -80,5 +80,7 @@ mod original_verifier;
mod verifier_commit_window_lifecycle;
#[path = "original_verify_schedule/verifier_logits_diagnostics_close.rs"]
mod verifier_logits_diagnostics_close;
#[path = "original_verify_schedule/verifier_park_rearm.rs"]
mod verifier_park_rearm;
#[path = "original_verify_schedule/window_phases.rs"]
mod window_phases;
@@ -40,7 +40,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
self.event = Some(context.original_gpu_event(OriginalEventKind::Completion)?);
Ok(())
}
fn unopened() -> Self {
pub(super) fn unopened() -> Self {
Self {
bank: None,
compute: None,
@@ -0,0 +1,129 @@
//! Unit tests of `park` and `rearm` on a verifier that holds no device state (`unopened`): the preconditions, the
//! order of refusals and the counters a re-arm restores. What touches the device (the bank, the images) is checked by
//! the identity job of `docs/experiments/verify-decode-graph-reuse-handles.md`.
use super::*;
use crate::original_gpu_schedule::resources;
/// Resources that are never used: `unopened` verifiers hold no graph.
struct NoResources;
impl resources::Sealed for NoResources {}
impl OriginalGraphResources for NoResources {
fn validate_context(&self, _: &Context<'_>) -> Result<()> {
Err(Error::ContextPoisoned)
}
}
impl<'ctx> OriginalVerifyGraphResources<'ctx> for NoResources {
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'ctx> {
unreachable!("an unopened verifier holds no graph")
}
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'ctx> {
unreachable!("an unopened verifier holds no graph")
}
}
impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for NoResources {
fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> {
Err(Error::ContextPoisoned)
}
fn native_head_rows_mut(&mut self) -> Result<&mut crate::OriginalNativeHeadRows<'ctx>> {
Err(Error::ContextPoisoned)
}
}
type Bare = OriginalVerifier<'static, NoResources>;
/// A name and the change that makes a verifier unfit to be re-armed.
type Refusal = (&'static str, fn(&mut Bare));
const STATE_WORDS: usize = 128 * 48 * 128;
const HISTORY_WORDS: usize = 10240 * 3;
/// A verifier mid-way through a request: counters up, a completed window remembered.
fn busy() -> Bare {
let mut verifier = Bare::unopened();
verifier.windows = 7;
verifier.commits = 6;
verifier.completed_generation = Some(12);
verifier.completed_ids = [3; 8];
verifier
}
fn counters(v: &Bare) -> (u64, u64, Option<u64>, [i32; 8]) {
(v.windows, v.commits, v.completed_generation, v.completed_ids)
}
fn seeded<R>(use_seed: impl FnOnce(OriginalVerifyRearm<'_>) -> R) -> R {
let (state, history, ple) = (vec![0.0f32; STATE_WORDS], vec![0.0f32; HISTORY_WORDS], vec![0.0f32; 9 * 10240]);
use_seed(OriginalVerifyRearm { gdn_states: [&state; 36], gdn_histories: [&history; 36], ple_history: &ple })
}
#[test]
fn the_counters_of_a_fresh_verifier_come_back() {
let mut verifier = busy();
verifier.profile.add_window(&vec![1u64; profile_stamp_words(48)], 48, |layer| layer % 4 == 3);
assert_eq!(verifier.profile.windows(), 1);
verifier.reset_run_counters();
let fresh = Bare::unopened();
assert_eq!(counters(&verifier), counters(&fresh));
assert_eq!(counters(&verifier), (0, 0, None, [0; 8]));
assert_eq!(verifier.profile.windows(), 0);
assert!(verifier.profile_report().is_empty());
}
#[test]
fn a_verifier_that_is_not_parked_or_is_unusable_refuses_to_rearm_and_keeps_its_counters() {
let flags: [Refusal; 5] = [
("failed", |v| v.failed = true),
("released", |v| v.released = true),
("window outstanding", |v| v.active = true),
("completed window not settled", |v| v.window_ready = true),
("commit pending", |v| v.commit_pending = true),
];
for (what, set) in flags {
let mut verifier = busy();
set(&mut verifier);
let failed_before = verifier.failed;
assert_eq!(seeded(|seed| verifier.rearm(seed)), Err(Error::InvalidQwenShape), "{what}");
assert_eq!(counters(&verifier), counters(&busy()), "{what}: nothing was reset");
assert_eq!(verifier.failed, failed_before, "{what}: a refused precondition does not fail the verifier");
// a failed or active verifier is dropped through its abort path, which needs no device here
verifier.failed = true;
}
}
#[test]
fn a_verifier_without_a_recording_cannot_be_rearmed_and_is_not_marked_failed() {
let mut verifier = busy();
assert_eq!(seeded(|seed| verifier.rearm(seed)), Err(Error::ContextPoisoned));
assert!(!verifier.failed);
assert_eq!(counters(&verifier), counters(&busy()));
}
#[test]
fn a_seed_of_the_wrong_shape_is_refused_before_anything_else() {
let mut verifier = busy();
let (state, history) = (vec![0.0f32; STATE_WORDS], vec![0.0f32; HISTORY_WORDS]);
let short_ple = vec![0.0f32; 9 * 10240 - 1];
let seed = OriginalVerifyRearm { gdn_states: [&state; 36], gdn_histories: [&history; 36], ple_history: &short_ple };
// even a failed verifier answers the shape first: the seed is checked before the state of the verifier
verifier.failed = true;
assert_eq!(verifier.rearm(seed), Err(Error::InvalidQwenShape));
assert_eq!(counters(&verifier), counters(&busy()));
}
#[test]
fn park_refuses_a_verifier_with_a_window_outstanding_or_one_that_failed() {
let flags: [fn(&mut Bare); 4] =
[|v| v.failed = true, |v| v.released = true, |v| v.active = true, |v| v.window_ready = true];
for set in flags {
let mut verifier = Bare::unopened();
set(&mut verifier);
assert_eq!(verifier.park(), Err(Error::InvalidQwenShape));
verifier.failed = true;
}
}
#[test]
fn parking_an_idle_verifier_with_nothing_pending_is_a_no_op() {
let mut verifier = Bare::unopened();
assert_eq!(verifier.park(), Ok(()));
assert!(!verifier.failed);
}
@@ -90,8 +90,8 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
Ok(OriginalVerifyWindow {
physical: b.physical.clone(),
generation: b.generation,
rows: b.last_t,
position: b.last_position,
rows: b.staged.t,
position: b.staged.position,
sampled_ids: self.completed_ids,
})
}
@@ -104,7 +104,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
return Err(Error::InvalidQwenShape);
}
let b = self.bank()?;
Ok(&b.last_tokens[..b.staged_keep()?])
Ok(&b.staged.tokens[..b.staged_keep()?])
}
pub fn with_committed_gdn<T>(
&mut self,
@@ -216,7 +216,7 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
) -> Result<T> {
self.require_completed_window()?;
let bank = self.bank()?;
let t = bank.last_t;
let t = bank.staged.t;
let vocabulary = bank.geometry().vocabulary;
let logits = self
.window
@@ -227,6 +227,6 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
if logits.len() != t.checked_mul(vocabulary).and_then(|n| n.checked_mul(4)).ok_or(Error::InvalidSize)? {
return Err(Error::InvalidQwenShape);
}
read(logits, t, vocabulary, bank.last_position)
read(logits, t, vocabulary, bank.staged.position)
}
}
@@ -95,21 +95,21 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour
pub fn window_residual_rows(&self) -> Result<(usize, usize, Vec<f32>)> {
self.require_completed_window()?;
let bank = self.bank()?;
let t = bank.last_t;
let t = bank.staged.t;
let g = bank.geometry();
let bytes_len =
[t, g.hc, g.n, 4].iter().try_fold(1usize, |n, &x| n.checked_mul(x)).ok_or(Error::InvalidSize)?;
let s = bank.physical.layout.span("R")?;
let span = arena_span(bank, s.offset, bytes_len)?;
let bytes = read_device_bytes(bank.physical.context, span, bytes_len)?;
Ok((t, bank.last_position, decode_f32s(&bytes, bytes_len / 4)?))
Ok((t, bank.staged.position, decode_f32s(&bytes, bytes_len / 4)?))
}
/// Bring-up diagnostic: the `dbg_ladder` frames (96 x rows x hc*n f32, frame = 2*layer + half) of the last
/// completed window, `None` when the region was not laid out (LELEKA_TRACE_LADDER unset at bank creation).
pub fn window_ladder_rows(&self) -> Result<Option<Vec<f32>>> {
self.require_completed_window()?;
let bank = self.bank()?;
let t = bank.last_t;
let t = bank.staged.t;
let g = bank.geometry();
let row = g.hc * g.n;
let Ok(s) = bank.physical.layout.span("dbg_ladder") else { return Ok(None) };
@@ -0,0 +1,112 @@
//! Park and re-arm of a recorded verifier (ledger row Q7, `docs/experiments/verify-decode-graph-reuse-handles.md`).
//!
//! `park` ends a request without closing anything: both streams drained, a pending commit waited, every graph
//! quiescent; the graphs, the bank, the streams and the event stay. `rearm` starts the next request over the same
//! recording: it puts back everything a fresh `OriginalVerifier::new` + `record_all` leaves (the counters here, the
//! bank, its flags and mapped staging in `original_verify_rearm.rs`) and overwrites the canonical GDN image and the PLE
//! history with the next request's priors. Any error leaves the verifier failed, so the caller retires the set and
//! records a new one; a partial re-arm is safe for that reason.
#[allow(unused_imports)]
use super::*;
impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> {
/// End of a request: wait a pending commit, drain both streams and retire every graph's launch. The recorded
/// graphs, the bank, the streams and the event stay; nothing is closed. A verifier that failed, was released or
/// still has a window outstanding (`active`, or completed but neither committed nor discarded) is refused. An error
/// of the waits leaves the verifier failed.
pub fn park(&mut self) -> Result<()> {
if self.failed || self.released || self.active || self.window_ready {
return Err(Error::InvalidQwenShape);
}
let parked = self.wait_commit().and_then(|()| self.drain_streams()).and_then(|()| self.quiesce_graphs());
if parked.is_err() {
self.failed = true;
}
parked
}
/// Start of the next request over the same recording: the preconditions (parked, nothing outstanding, the QSA
/// journal quiet), then the bank, the images and the counters. `Err` leaves the verifier unusable when it came
/// after the first change (the caller retires it); a refused precondition or seed changes nothing.
pub fn rearm(&mut self, seed: OriginalVerifyRearm<'_>) -> Result<()> {
seed.check_shapes()?;
self.require_rearmable()?;
let applied = self.apply_rearm(&seed);
if applied.is_err() {
self.failed = true;
}
applied
}
fn drain_streams(&mut self) -> Result<()> {
for stream in [self.compute.as_ref(), self.copy.as_ref()].into_iter().flatten() {
stream.synchronize()?;
}
if let Some(bank) = self.bank.as_mut() {
bank.release_pcie_sources();
}
Ok(())
}
/// Every window graph and the commit graph have no launch outstanding.
fn quiesce_graphs(&mut self) -> Result<()> {
for graph in self.window.iter_mut().filter_map(Option::as_mut).chain(self.commit.as_mut()) {
graph.resources_after_wait()?;
}
Ok(())
}
/// Parked and quiet: nothing in flight or outstanding, not failed or released, the graphs idle, the QSA journal
/// not armed.
fn require_rearmable(&mut self) -> Result<()> {
if self.is_unusable() || self.active || self.window_ready || self.commit_pending {
return Err(Error::InvalidQwenShape);
}
if self.bank.is_none() || self.commit.is_none() {
return Err(Error::ContextPoisoned);
}
if self.window.iter().flatten().chain(self.commit.iter()).any(|g| !g.verifier_is_idle()) {
return Err(Error::InvalidQwenShape);
}
self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_wait()?.verifier_qsa().require_idle()
}
/// Failed, or released here or by the watchdog (a released verifier ran a window the GPU never finished).
fn is_unusable(&self) -> bool {
self.failed || self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released)
}
fn apply_rearm(&mut self, seed: &OriginalVerifyRearm<'_>) -> Result<()> {
self.bank.as_mut().ok_or(Error::ContextPoisoned)?.rearm()?;
self.reseed_images(seed)?;
self.reset_run_counters();
if let Some(registration) = &self.registration {
registration.reset_window();
}
Ok(())
}
/// The canonical GDN image and the PLE history are overwritten in place: every aggregate shares them, so the
/// commit graph's journal reaches both.
fn reseed_images(&mut self, seed: &OriginalVerifyRearm<'_>) -> Result<()> {
let resources = self.commit.as_mut().ok_or(Error::ContextPoisoned)?.resources_after_wait()?;
let journal = resources.verifier_journal();
journal.canonical.reseed(seed.gdn_states, seed.gdn_histories)?;
let history = journal.ple_buffer().ok_or(Error::InvalidQwenShape)?;
history.copy_from_shared(&seed.ple_history_bytes()?)
}
/// The counters and completed-window memory of a verifier that has run nothing.
pub(super) fn reset_run_counters(&mut self) {
self.windows = 0;
self.commits = 0;
self.completed_generation = None;
self.completed_ids = [0; 8];
self.profile = OriginalVerifyProfile::default();
}
}
#[cfg(test)]
#[path = "park_rearm_tests.rs"]
mod tests;
@@ -31,7 +31,7 @@ use super::proj::{
use super::window_record::{HcHalf, Rows};
use super::{OriginalVerifyGdnJournal, admit, handle};
use crate::native_head::native_head_row_bytes;
use crate::{Context, DeviceBuffer, Error, NativeHeadDispatch, Result};
use crate::{Context, DeviceBuffer, DeviceRef, Error, NativeHeadDispatch, Result};
// ------------------------------------------------------------------------------------------------
// Geometry of the artifact (`fused_gr.cu` is compiled for exactly these)
@@ -275,49 +275,49 @@ pub(crate) struct HcReadPlan {
/// The four buffers of one hc half: `norm` F32 `[hc*N]`, `down` BF16 `[hc_lr][hc*N]`, `up` BF16
/// `[hc*N][hc_lr]`, `inject` BF16 `[hc][hc*N]`.
pub struct HcHalfBuffers<'a, 'ctx> {
pub norm: &'a DeviceBuffer<'ctx>,
pub down: &'a DeviceBuffer<'ctx>,
pub up: &'a DeviceBuffer<'ctx>,
pub inject: &'a DeviceBuffer<'ctx>,
pub struct HcHalfBuffers<'ctx> {
pub norm: DeviceRef<'ctx>,
pub down: DeviceRef<'ctx>,
pub up: DeviceRef<'ctx>,
pub inject: DeviceRef<'ctx>,
}
pub struct HcLayerBuffers<'a, 'ctx> {
pub attention: HcHalfBuffers<'a, 'ctx>,
pub ffn: HcHalfBuffers<'a, 'ctx>,
pub struct HcLayerBuffers<'ctx> {
pub attention: HcHalfBuffers<'ctx>,
pub ffn: HcHalfBuffers<'ctx>,
}
/// `output_hc_norm.weight` / `output_hc_down.weight` / `output_hc_up.weight` (no injection).
pub struct HcOutputBuffers<'a, 'ctx> {
pub norm: &'a DeviceBuffer<'ctx>,
pub down: &'a DeviceBuffer<'ctx>,
pub up: &'a DeviceBuffer<'ctx>,
pub struct HcOutputBuffers<'ctx> {
pub norm: DeviceRef<'ctx>,
pub down: DeviceRef<'ctx>,
pub up: DeviceRef<'ctx>,
}
pub enum PleKeyBuffer<'a, 'ctx> {
pub enum PleKeyBuffer<'ctx> {
/// BF16 `[hc_dim][n_embd]` (`PLE_KEY_BF16_BYTES`).
Bf16(&'a DeviceBuffer<'ctx>),
Bf16(DeviceRef<'ctx>),
/// A native GGUF key of ggml type `ty` (42, 18, 23, 8): `hc_dim` rows of `n_embd`.
Native { ty: u32, data: &'a DeviceBuffer<'ctx> },
Native { ty: u32, data: DeviceRef<'ctx> },
}
/// The PLE weights and state of the layer-1 block. `history` must be the SAME buffer the verify
/// journal snapshots (`ss.ple.hist`).
pub struct PleBuffers<'a, 'ctx> {
pub key: PleKeyBuffer<'a, 'ctx>,
pub value: &'a DeviceBuffer<'ctx>,
pub norm_key: &'a DeviceBuffer<'ctx>,
pub norm_query: &'a DeviceBuffer<'ctx>,
pub norm_conv: &'a DeviceBuffer<'ctx>,
pub conv1d: &'a DeviceBuffer<'ctx>,
pub struct PleBuffers<'ctx> {
pub key: PleKeyBuffer<'ctx>,
pub value: DeviceRef<'ctx>,
pub norm_key: DeviceRef<'ctx>,
pub norm_query: DeviceRef<'ctx>,
pub norm_conv: DeviceRef<'ctx>,
pub conv1d: DeviceRef<'ctx>,
/// At least `PLE_SCRATCH_BYTES` (`ss.ple.scratch`).
pub scratch: &'a DeviceBuffer<'ctx>,
pub history: &'a DeviceBuffer<'ctx>,
pub scratch: DeviceRef<'ctx>,
pub history: DeviceRef<'ctx>,
}
/// The weights of the GR family for the 48 layers, the final mixer and (optionally) the PLE block,
/// validated for context and exact byte sizes.
pub struct OriginalVerifyGrBinding<'a, 'ctx> {
pub struct OriginalVerifyGrBinding<'ctx> {
context: &'ctx Context<'ctx>,
layers: Vec<HcLayerBuffers<'a, 'ctx>>,
output: HcOutputBuffers<'a, 'ctx>,
ple: Option<PleBuffers<'a, 'ctx>>,
layers: Vec<HcLayerBuffers<'ctx>>,
output: HcOutputBuffers<'ctx>,
ple: Option<PleBuffers<'ctx>>,
}
#[cfg(test)]
@@ -54,11 +54,7 @@ impl GrConfig {
}
/// `from_device` with the attributes read from the verifier's device.
pub(crate) fn query(
journal: &OriginalVerifyGdnJournal<'_, '_>,
variant: GrVariant,
native_mmvf: bool,
) -> Result<Self> {
pub(crate) fn query(journal: &OriginalVerifyGdnJournal<'_>, variant: GrVariant, native_mmvf: bool) -> Result<Self> {
Ok(Self::from_device(
variant,
native_mmvf,
@@ -145,12 +145,12 @@ pub(crate) fn plan_ple_layer1(
check_rows(window.geo, rows)?;
(rows.begin..rows.end).map(|t| Ok((t, plan_ple_row(window, ple, a, t)?))).collect()
}
impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
impl<'ctx> OriginalVerifyGrBinding<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
layers: Vec<HcLayerBuffers<'a, 'ctx>>,
output: HcOutputBuffers<'a, 'ctx>,
ple: Option<PleBuffers<'a, 'ctx>>,
layers: Vec<HcLayerBuffers<'ctx>>,
output: HcOutputBuffers<'ctx>,
ple: Option<PleBuffers<'ctx>>,
) -> Result<Self> {
if layers.len() != LAYERS {
return Err(Error::InvalidQwenShape);
@@ -167,7 +167,7 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
}
Ok(binding)
}
pub(super) fn half(&self, layer: usize, half: HcHalf) -> Result<&HcHalfBuffers<'a, 'ctx>> {
pub(super) fn half(&self, layer: usize, half: HcHalf) -> Result<&HcHalfBuffers<'ctx>> {
let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?;
Ok(match half {
HcHalf::Attention => &l.attention,
@@ -179,24 +179,24 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
let h = self.half(layer, half)?;
let c = self.context;
Ok(HcAddrs {
norm: admit(c, h.norm, HC_NORM_BYTES)?,
down: admit(c, h.down, HC_DOWN_BYTES)?,
up: admit(c, h.up, HC_UP_BYTES)?,
inject: admit(c, h.inject, HC_INJECT_BYTES)?,
norm: admit(c, &h.norm, HC_NORM_BYTES)?,
down: admit(c, &h.down, HC_DOWN_BYTES)?,
up: admit(c, &h.up, HC_UP_BYTES)?,
inject: admit(c, &h.inject, HC_INJECT_BYTES)?,
})
}
pub(crate) fn head_addrs(&self) -> Result<HeadAddrs> {
let c = self.context;
Ok(HeadAddrs {
norm: admit(c, self.output.norm, HC_NORM_BYTES)?,
down: admit(c, self.output.down, HC_DOWN_BYTES)?,
up: admit(c, self.output.up, HC_UP_BYTES)?,
norm: admit(c, &self.output.norm, HC_NORM_BYTES)?,
down: admit(c, &self.output.down, HC_DOWN_BYTES)?,
up: admit(c, &self.output.up, HC_UP_BYTES)?,
})
}
pub fn has_ple(&self) -> bool {
self.ple.is_some()
}
fn ple_key_addr(&self, key: &PleKeyBuffer<'a, 'ctx>) -> Result<PleKey> {
fn ple_key_addr(&self, key: &PleKeyBuffer<'ctx>) -> Result<PleKey> {
let c = self.context;
Ok(match key {
PleKeyBuffer::Bf16(b) => PleKey::Bf16(admit(c, b, PLE_KEY_BF16_BYTES)?),
@@ -209,7 +209,7 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
}
})
}
fn ple_scratch_addr(&self, scratch: &'a DeviceBuffer<'ctx>) -> Result<u64> {
fn ple_scratch_addr(&self, scratch: &DeviceBuffer<'ctx>) -> Result<u64> {
if !std::ptr::eq(self.context, scratch.context) {
return Err(Error::ContextMismatch);
}
@@ -224,16 +224,16 @@ impl<'a, 'ctx> OriginalVerifyGrBinding<'a, 'ctx> {
let p = self.ple.as_ref().ok_or(Error::InvalidQwenShape)?;
let c = self.context;
let key = self.ple_key_addr(&p.key)?;
let scratch = self.ple_scratch_addr(p.scratch)?;
let scratch = self.ple_scratch_addr(&p.scratch)?;
Ok(PleAddrs {
key,
value: admit(c, p.value, PLE_VALUE_BYTES)?,
norm_key: admit(c, p.norm_key, PLE_NORM_BYTES)?,
norm_query: admit(c, p.norm_query, PLE_NORM_BYTES)?,
norm_conv: admit(c, p.norm_conv, PLE_NORM_BYTES)?,
conv1d: admit(c, p.conv1d, PLE_CONV_BYTES)?,
value: admit(c, &p.value, PLE_VALUE_BYTES)?,
norm_key: admit(c, &p.norm_key, PLE_NORM_BYTES)?,
norm_query: admit(c, &p.norm_query, PLE_NORM_BYTES)?,
norm_conv: admit(c, &p.norm_conv, PLE_NORM_BYTES)?,
conv1d: admit(c, &p.conv1d, PLE_CONV_BYTES)?,
scratch,
history: admit(c, p.history, PLE_HISTORY_BYTES)?,
history: admit(c, &p.history, PLE_HISTORY_BYTES)?,
})
}
}
@@ -38,7 +38,7 @@ use super::window_plan::{PlanLayout, WINDOW_LAYERS};
use super::window_record::{ExpertTier, Rows};
use super::{OriginalVerifyGeometry, admit, handle};
use crate::native_head::native_head_row_bytes;
use crate::{Context, DeviceBuffer, Error, NativeHeadDispatch, Result};
use crate::{Context, DeviceBuffer, DeviceRef, Error, NativeHeadDispatch, Result};
macro_rules! unavailable {
($producer:literal, $why:literal) => {
@@ -323,21 +323,21 @@ pub(crate) struct MoeLayerAddrs {
}
/// One layer's MoE weights as the runtime hands them over.
pub struct OriginalVerifyMoeLayerWeights<'a, 'ctx> {
pub router: &'a DeviceBuffer<'ctx>,
pub gate_inp_shexp: &'a DeviceBuffer<'ctx>,
pub gate_shexp: &'a DeviceBuffer<'ctx>,
pub struct OriginalVerifyMoeLayerWeights<'ctx> {
pub router: DeviceRef<'ctx>,
pub gate_inp_shexp: DeviceRef<'ctx>,
pub gate_shexp: DeviceRef<'ctx>,
pub gate_shexp_type: u32,
pub up_shexp: &'a DeviceBuffer<'ctx>,
pub up_shexp: DeviceRef<'ctx>,
pub up_shexp_type: u32,
pub down_shexp: &'a DeviceBuffer<'ctx>,
pub down_shexp: DeviceRef<'ctx>,
pub down_shexp_type: u32,
}
/// The router and shared-expert weights of all 48 layers plus the routed experts' formats. Construction
/// validates context equality and the exact byte size of every tensor; the accessors yield addresses.
pub struct OriginalVerifyMoeBinding<'a, 'ctx> {
layers: Vec<OriginalVerifyMoeLayerWeights<'a, 'ctx>>,
pub struct OriginalVerifyMoeBinding<'ctx> {
layers: Vec<OriginalVerifyMoeLayerWeights<'ctx>>,
formats: OriginalVerifyExpertFormats,
n_embd: usize,
n_ff: usize,
@@ -146,11 +146,11 @@ impl OriginalVerifyExpertFormats {
Ok(self.blob(layer)?.bytes)
}
}
impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> {
impl<'ctx> OriginalVerifyMoeBinding<'ctx> {
pub fn new(
context: &Context<'_>,
geometry: &OriginalVerifyGeometry,
layers: Vec<OriginalVerifyMoeLayerWeights<'a, 'ctx>>,
layers: Vec<OriginalVerifyMoeLayerWeights<'ctx>>,
formats: OriginalVerifyExpertFormats,
) -> Result<Self> {
let (n_embd, n_ff, experts) = (geometry.n, geometry.ff, geometry.experts);
@@ -165,7 +165,7 @@ impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> {
}
pub fn validate_context(&self, context: &Context<'_>) -> Result<()> {
for l in &self.layers {
for b in [l.router, l.gate_inp_shexp, l.gate_shexp, l.up_shexp, l.down_shexp] {
for b in [&l.router, &l.gate_inp_shexp, &l.gate_shexp, &l.up_shexp, &l.down_shexp] {
if !std::ptr::eq(context, b.context) {
return Err(Error::ContextMismatch);
}
@@ -181,11 +181,11 @@ impl<'a, 'ctx> OriginalVerifyMoeBinding<'a, 'ctx> {
let l = self.layers.get(layer).ok_or(Error::InvalidQwenShape)?;
let (n, f) = (self.n_embd, self.n_ff);
Ok(MoeLayerAddrs {
router: exact_address(l.router, self.experts * n * 2)?,
gate_inp_shexp: exact_address(l.gate_inp_shexp, n * 2)?,
gate_shexp: shexp_address(l.gate_shexp, l.gate_shexp_type, (f, n))?,
up_shexp: shexp_address(l.up_shexp, l.up_shexp_type, (f, n))?,
down_shexp: shexp_address(l.down_shexp, l.down_shexp_type, (n, f))?,
router: exact_address(&l.router, self.experts * n * 2)?,
gate_inp_shexp: exact_address(&l.gate_inp_shexp, n * 2)?,
gate_shexp: shexp_address(&l.gate_shexp, l.gate_shexp_type, (f, n))?,
up_shexp: shexp_address(&l.up_shexp, l.up_shexp_type, (f, n))?,
down_shexp: shexp_address(&l.down_shexp, l.down_shexp_type, (n, f))?,
})
}
}
@@ -206,15 +206,15 @@ fn shexp_address(b: &DeviceBuffer<'_>, ty: u32, (rows, k): (usize, usize)) -> Re
/// The `new` admission of one layer's router and shared-expert buffers.
fn admit_layer(
context: &Context<'_>,
layer: &OriginalVerifyMoeLayerWeights<'_, '_>,
layer: &OriginalVerifyMoeLayerWeights<'_>,
(n_embd, n_ff): (usize, usize),
router_bytes: usize,
) -> Result<()> {
admit(context, layer.router, router_bytes)?;
admit(context, layer.gate_inp_shexp, n_embd * 2)?;
admit(context, layer.gate_shexp, n_ff * native_head_row_bytes(layer.gate_shexp_type, n_embd)?)?;
admit(context, layer.up_shexp, n_ff * native_head_row_bytes(layer.up_shexp_type, n_embd)?)?;
admit(context, layer.down_shexp, n_embd * native_head_row_bytes(layer.down_shexp_type, n_ff)?)?;
admit(context, &layer.router, router_bytes)?;
admit(context, &layer.gate_inp_shexp, n_embd * 2)?;
admit(context, &layer.gate_shexp, n_ff * native_head_row_bytes(layer.gate_shexp_type, n_embd)?)?;
admit(context, &layer.up_shexp, n_ff * native_head_row_bytes(layer.up_shexp_type, n_embd)?)?;
admit(context, &layer.down_shexp, n_embd * native_head_row_bytes(layer.down_shexp_type, n_ff)?)?;
Ok(())
}
@@ -53,19 +53,19 @@ pub struct OriginalVerifyExpertLayout {
/// twelve QSA images and the head rows (`OriginalVerifyResources`), plus the
/// 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>,
pub struct OriginalVerifyWindowResources<'ctx> {
base: OriginalVerifyResources<'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>>,
proj: Option<OriginalVerifyProjBinding<'ctx>>,
/// hc weights of the 48 layers, the final mixer and the optional PLE block.
gr: Option<OriginalVerifyGrBinding<'a, 'ctx>>,
gr: Option<OriginalVerifyGrBinding<'ctx>>,
/// QSA norms and indexer projections of the 12 QSA layers.
qsa: Option<OriginalVerifyQsaBinding<'a, 'ctx>>,
qsa: Option<OriginalVerifyQsaBinding<'ctx>>,
/// Router, shared experts and routed expert formats of the 48 layers.
moe: Option<OriginalVerifyMoeBinding<'a, 'ctx>>,
moe: Option<OriginalVerifyMoeBinding<'ctx>>,
/// The per-card fused-GR decisions, read once by `prepare`.
gr_cfg: Option<GrConfig>,
}
@@ -82,12 +82,14 @@ macro_rules! unattached {
}
/// The recorder's producer set over one graph's capture stream and resources.
pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'a, 'ctx> {
pub(crate) struct OriginalVerifyWindowOps<'c, 's, 'ctx> {
capture: &'c mut OriginalCapture<'s, 'ctx>,
resources: &'c mut OriginalVerifyWindowResources<'a, 'ctx>,
resources: &'c mut OriginalVerifyWindowResources<'ctx>,
t: usize,
groups: usize,
policy: WindowPolicy,
/// The GDN kernel switches (`original_verify_window_gdn_fused.rs`).
gdn: gdn_fused::GdnFusedPolicy,
}
#[cfg(test)]
@@ -102,10 +104,14 @@ pub(super) use all_window_assets::all_window_assets;
use all_window_assets::unsealed_keys;
#[allow(unused_imports)]
pub use all_window_assets::unsealed_window_assets;
#[path = "original_verify_window_ops/gdn_stages.rs"]
mod gdn_stages;
#[path = "original_verify_window_ops/original_verifier.rs"]
mod original_verifier;
#[path = "original_verify_window_ops/original_verify_window_ops_methods.rs"]
mod original_verify_window_ops_methods;
#[path = "original_verify_window_ops/qsa_prelude_ops.rs"]
mod qsa_prelude_ops;
#[path = "original_verify_window_ops/side_qsa_branches.rs"]
mod side_qsa_branches;
#[path = "original_verify_window_ops/side_shared_expert.rs"]
@@ -75,10 +75,10 @@ impl OriginalVerifyExpertLayout {
.ok_or(Error::InvalidQwenShape)
}
}
impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
impl<'ctx> OriginalVerifyWindowResources<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
base: OriginalVerifyResources<'a, 'ctx>,
base: OriginalVerifyResources<'ctx>,
embed: OriginalNativeEmbedRows<'ctx>,
experts: OriginalVerifyExpertLayout,
rows: usize,
@@ -94,7 +94,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
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> {
pub fn with_projections(mut self, proj: OriginalVerifyProjBinding<'ctx>) -> Result<Self> {
let context = self.base.journal.context();
let geometry = self.base.journal.geometry();
for i in 0..36 {
@@ -109,7 +109,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
/// 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> {
pub fn with_gr(mut self, gr: OriginalVerifyGrBinding<'ctx>) -> Result<Self> {
let journal = &self.base.journal;
if gr.has_ple() != journal.has_ple() {
return Err(Error::InvalidQwenShape);
@@ -121,7 +121,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
Ok(self)
}
/// Attach the QSA layer weights (norms, indexer projections).
pub fn with_qsa(mut self, qsa: OriginalVerifyQsaBinding<'a, 'ctx>) -> Result<Self> {
pub fn with_qsa(mut self, qsa: OriginalVerifyQsaBinding<'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())?;
@@ -131,7 +131,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
}
/// 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> {
pub fn with_moe(mut self, moe: OriginalVerifyMoeBinding<'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)? {
@@ -155,6 +155,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
assets.extend(qsa::assets());
assets.extend(qsa::cluster_assets(&policy.qsa));
assets.extend(qsa::daily_assets(&policy.qsa));
assets.extend(qsa::fused_prelude::assets(policy.qsa.fused_prelude));
}
if self.moe.is_some() {
assets.extend(moe::assets());
@@ -185,7 +186,7 @@ impl<'a, 'ctx> OriginalVerifyWindowResources<'a, 'ctx> {
Ok(())
}
}
impl WindowWeights for OriginalVerifyWindowResources<'_, '_> {
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)
@@ -211,7 +212,7 @@ impl WindowWeights for OriginalVerifyWindowResources<'_, '_> {
Ok(QsaLayerAddrs { weights: b.addrs(q)?, kv })
}
fn rope(&self) -> Result<QsaRope> {
QsaRope::from_rope(&self.base.qsa.rope())
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)
@@ -220,22 +221,22 @@ impl WindowWeights for OriginalVerifyWindowResources<'_, '_> {
Ok(self.moe.as_ref().ok_or(unattached!("expert_groups", "routed expert formats"))?.formats())
}
}
impl resources::Sealed for OriginalVerifyWindowResources<'_, '_> {}
impl OriginalGraphResources for OriginalVerifyWindowResources<'_, '_> {
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> {
impl<'ctx> OriginalVerifyGraphResources<'ctx> for OriginalVerifyWindowResources<'ctx> {
fn verifier_qsa(&self) -> &crate::OriginalVerifyQsaJournal<'ctx> {
self.base.verifier_qsa()
}
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'_, 'ctx> {
fn verifier_journal(&self) -> &OriginalVerifyGdnJournal<'ctx> {
self.base.verifier_journal()
}
}
impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResources<'_, 'ctx> {
impl<'ctx> OriginalNativeHeadGraphResources<'ctx> for OriginalVerifyWindowResources<'ctx> {
fn native_head_rows(&self) -> Result<&crate::OriginalNativeHeadRows<'ctx>> {
self.base.native_head_rows()
}
@@ -0,0 +1,57 @@
//! claude/verify-gdn-fused-kernels: what the three GDN `WindowOps` calls of a layer record
//! (`GdnFusedPolicy::stages`, `original_verify_window_gdn_fused.rs`). With both switches off every call records the
//! Original's kernel as before.
use super::gdn_fused::{GdnStages, GdnStep};
#[allow(unused_imports)]
use super::*;
impl OriginalVerifyWindowOps<'_, '_, '_> {
fn gdn_stages(&self) -> GdnStages {
self.gdn.stages(self.side_gdn())
}
/// The Original's kernel (or the chain kernel) of one GDN stage.
fn gdn_original_stage(&mut self, stage: OriginalVerifyGdnStage, layer: usize, rows: Rows) -> Result<()> {
self.resources.base.journal.capture_layer_stage(stage, self.capture, layer, rows.begin..rows.end)
}
/// The a/b gates as a kernel of their own: the Original's, or the unrolled one of `GDN_AB_UNROLL`. Used by the
/// ordinary call and by the side-stream branch.
pub(super) fn gdn_alpha_beta_kernel(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn.separate_ab() {
GdnStep::AbUnrolled => {
self.resources.base.journal.capture_ab_unrolled(self.capture, layer, rows.begin..rows.end)
}
_ => self.gdn_original_stage(OriginalVerifyGdnStage::AlphaBeta, layer, rows),
}
}
pub(super) fn gdn_conv_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn_stages().conv {
GdnStep::Skip => Ok(()), // the fused launch convolves
_ => self.gdn_original_stage(OriginalVerifyGdnStage::Conv, layer, rows),
}
}
pub(super) fn gdn_alpha_beta_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
match self.gdn_stages().alpha_beta {
GdnStep::Skip => Ok(()), // issued on side stream 0 by `issue_gdn_side`, or computed by the fused launch
_ => self.gdn_alpha_beta_kernel(layer, rows),
}
}
pub(super) fn gdn_recurrence_stage(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
// the recurrence reads the gates and the gate projection: the capture stream joins both branches
self.capture.side_join(0)?;
self.capture.side_join(1)?;
}
match self.gdn_stages().recurrence {
GdnStep::Fused(gates) => {
self.resources.base.journal.capture_fused_recurrence(self.capture, layer, rows.begin..rows.end, gates)
}
_ => self.gdn_original_stage(OriginalVerifyGdnStage::Recurrence, layer, rows),
}
}
}
@@ -3,13 +3,13 @@
#[allow(unused_imports)]
use super::*;
impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
impl<'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'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>,
resources: OriginalVerifyWindowResources<'ctx>,
policy: WindowPolicy,
) -> Result<()> {
policy.validate_selected()?;
@@ -25,11 +25,12 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
// Sealed modules load before capture begins (cuModuleLoadData is not a capturable call).
let mut resources = resources;
resources.prepare(&policy)?;
let gdn = gdn_fused::prepare(resources.verifier_journal())?;
// SIDE_MIXER: this recording's capture creates the two side streams (a split window just leaves them unused)
crate::original_gpu_schedule::set_side_streams_wanted(policy.side.any());
let recorded = 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, policy };
let mut ops = OriginalVerifyWindowOps { capture, resources, t, groups, policy, gdn };
record_window(&mut ops, &policy, t, groups, ple)
});
crate::original_gpu_schedule::set_side_streams_wanted(false);
@@ -42,8 +43,8 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
pub fn record_all(
&mut self,
policy: WindowPolicy,
mut window: impl FnMut(usize) -> Result<OriginalVerifyWindowResources<'a, 'ctx>>,
commit: OriginalVerifyWindowResources<'a, 'ctx>,
mut window: impl FnMut(usize) -> Result<OriginalVerifyWindowResources<'ctx>>,
commit: OriginalVerifyWindowResources<'ctx>,
) -> Result<()> {
policy.validate_selected()?;
let max_t = self.bank()?.geometry().max_t;
@@ -57,7 +58,7 @@ impl<'a, 'ctx> OriginalVerifier<'ctx, OriginalVerifyWindowResources<'a, 'ctx>> {
}
/// The cluster top-k needs sm_90+ and a sealed module; anything else keeps the Original's qsa_topk_ref.
fn resolve_cluster_topk(resources: &OriginalVerifyWindowResources<'_, '_>, policy: &mut WindowPolicy) -> Result<()> {
fn resolve_cluster_topk(resources: &OriginalVerifyWindowResources<'_>, policy: &mut WindowPolicy) -> Result<()> {
if policy.qsa.cluster_topk {
let cc = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
policy.qsa.cluster_topk = cc >= 9 && qsa::CLUSTER.sealed().is_ok();
@@ -74,13 +75,17 @@ fn resolve_cluster_topk(resources: &OriginalVerifyWindowResources<'_, '_>, polic
/// The sm_120 decode switches (original_verify_window_sm120.rs): resolved from the card and the environment, once per
/// recording.
fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_, '_>, policy: &mut WindowPolicy) -> Result<()> {
fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_>, policy: &mut WindowPolicy) -> Result<()> {
let major = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MAJOR)?;
let minor = resources.verifier_journal().window_device_attribute(gr::ATTR_COMPUTE_CAPABILITY_MINOR)?;
let want = sm120::Sm120Switches::from_env(major, minor);
policy.qsa.attn_daily = (policy.qsa.attn_daily || want.attn_daily) && sm120::ATTN_DAILY.sealed().is_ok();
policy.gu_swiglu = (policy.gu_swiglu || want.gu_swiglu) && sm120::GU_SWIGLU.sealed().is_ok();
policy.side = policy.side.union(want.side_branches());
// ACCEPT_ON_DEVICE: marks the head rows of THIS graph (each T has its own); `OriginalVerifyWindowOps::head` records
// the finite scan after the pick and the post-drain check reads its verdict word instead of scanning
resources.base.head.set_finite_verdict_in_graph(want.accept_on_device);
policy.qsa.fused_prelude = qsa::fused_prelude::resolve(policy.qsa.fused_prelude || want.fused_qsa_prelude);
static SAID: std::sync::Once = std::sync::Once::new();
SAID.call_once(|| {
eprintln!(
@@ -94,7 +99,7 @@ fn resolve_sm120_switches(resources: &OriginalVerifyWindowResources<'_, '_>, pol
/// The per-layer gate/up/down role bytes of the experts for the copy-kernel pcie mode 2, else none.
fn pcie_role_bytes(
resources: &OriginalVerifyWindowResources<'_, '_>,
resources: &OriginalVerifyWindowResources<'_>,
pcie_mode: u8,
) -> Result<Option<[[usize; 3]; WINDOW_LAYERS]>> {
if pcie_mode != 2 {
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
impl<'ctx> OriginalVerifyWindowOps<'_, '_, 'ctx> {
/// SIDE_MIXER (upstream `STRATA_SIDE_MIXER=2`, GDN part): the GDN gates and the gate projection run on side
/// streams of the window's graph. Not in a split window (two row groups), as upstream.
pub(super) fn side_gdn(&self) -> bool {
@@ -16,12 +16,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
pub(super) fn issue_gdn_side(&mut self, layer: usize, rows: Rows) -> Result<()> {
let g = gdn_index(layer).ok_or(Error::InvalidQwenShape)?;
self.capture.side_fork(0)?;
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
g,
rows.begin..rows.end,
)?;
self.gdn_alpha_beta_kernel(g, rows)?;
self.capture.side_end(0)?;
self.capture.side_fork(1)?;
self.plan_launch(|p| p.mmvq(layer, Projection::GdnGate, rows))?;
@@ -66,7 +61,7 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
pub(super) fn plan_group_offset(&self, group: usize) -> usize {
group * self.plan().device_stride() * 4
}
pub(super) fn journal(&self) -> &OriginalVerifyGdnJournal<'a, 'ctx> {
pub(super) fn journal(&self) -> &OriginalVerifyGdnJournal<'ctx> {
&self.resources.base.journal
}
pub(super) fn submit(&mut self, commands: Vec<Command>) -> Result<()> {
@@ -0,0 +1,26 @@
//! `LELEKA_SM120_FUSED_QSA_PRELUDE`, indexer half: the tail snapshot and the row appends of a QSA layer index image
//! as the one launch `leleka_verify_qsa_index_rows` (`qsa/fused_prelude.rs`). The K/V half is a planner plan
//! (`QsaWindow::kv_rows`) and needs no journal.
//!
//! The launch sits where `capture_append_rows` of the journal sits (after the K/V append in the in-line order,
//! inside the indexer chain on the side stream with `SIDE_QSA`), and the snapshot that precedes the first row in the
//! literal order is its first step, so the order the side branches rely on is unchanged.
#[allow(unused_imports)]
use super::*;
use qsa::fused_prelude::IndexImage;
impl<'ctx> OriginalVerifyWindowOps<'_, '_, 'ctx> {
/// The index image of QSA layer `q` when this window fuses the indexer rows: the switch is on and the retained
/// RoPE is the analytic variant (the table variant keeps the per-row launches).
pub(super) fn fused_index_image(&self, q: usize) -> Result<Option<IndexImage>> {
if !self.policy.qsa.fused_prelude {
return Ok(None);
}
self.resources.base.qsa.index_image(&self.resources.base.journal, q)
}
/// Record the snapshot (first row group) and the append of `rows` as one launch on the current stream.
pub(super) fn issue_index_rows(&mut self, q: usize, rows: Rows, image: IndexImage) -> Result<()> {
self.plan_launch(|p| p.qsa_index_rows(q, rows, &image))
}
}
@@ -21,7 +21,7 @@ pub(super) struct QsaSideLayer {
pub(super) batched: bool,
}
impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
impl<'ctx> OriginalVerifyWindowOps<'_, '_, 'ctx> {
/// The QSA layers run their indexer and query chains on side streams (not in a split window, as upstream).
pub(super) fn side_qsa(&self) -> bool {
self.policy.side.qsa && self.groups == 1 && self.capture.has_side()
@@ -39,9 +39,13 @@ impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
fn issue_indexer_chain(&mut self, layer: QsaSideLayer) -> Result<()> {
let QsaSideLayer { q, rows, batched } = layer;
self.plan_launch(|p| p.qsa_index_k(q, rows, batched))?;
let base = &self.resources.base;
base.qsa.capture_tail_snapshot(&base.journal, self.capture, q)?;
base.qsa.capture_append_rows(&base.journal, self.capture, q, rows.begin..rows.end)?;
if let Some(image) = self.fused_index_image(q)? {
self.issue_index_rows(q, rows, image)?;
} else {
let base = &self.resources.base;
base.qsa.capture_tail_snapshot(&base.journal, self.capture, q)?;
base.qsa.capture_append_rows(&base.journal, self.capture, q, rows.begin..rows.end)?;
}
self.plan_launch(|p| p.qsa_index_q_path(q, rows, batched))?;
self.plan_launch(|p| p.qsa_block_scores_topk(q, rows))
}
@@ -11,7 +11,7 @@
#[allow(unused_imports)]
use super::*;
impl<'a, 'ctx> OriginalVerifyWindowOps<'_, '_, 'a, 'ctx> {
impl<'ctx> OriginalVerifyWindowOps<'_, '_, 'ctx> {
/// The shared expert runs on side stream 0 (not in a split window, as the other side branches).
pub(super) fn side_shared(&self) -> bool {
self.policy.side.shared_expert && self.groups == 1 && self.capture.has_side()
@@ -5,7 +5,7 @@ use super::side_qsa_branches::QsaSideLayer;
#[allow(unused_imports)]
use super::*;
impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_> {
fn embed(&mut self) -> Result<()> {
self.embed_stage_tokens()?;
self.resources.embed.capture(self.capture)?;
@@ -51,36 +51,13 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
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,
)
self.gdn_conv_stage(layer, rows)
}
fn gdn_alpha_beta(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
return Ok(()); // issued on side stream 0 by `issue_gdn_side`
}
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::AlphaBeta,
self.capture,
layer,
rows.begin..rows.end,
)
self.gdn_alpha_beta_stage(layer, rows)
}
fn gdn_recurrence(&mut self, layer: usize, rows: Rows) -> Result<()> {
if self.side_gdn() {
// the recurrence reads the gates and the gate projection: the capture stream joins both branches
self.capture.side_join(0)?;
self.capture.side_join(1)?;
}
self.resources.base.journal.capture_layer_stage(
OriginalVerifyGdnStage::Recurrence,
self.capture,
layer,
rows.begin..rows.end,
)
self.gdn_recurrence_stage(layer, rows)
}
fn qsa_index_k(&mut self, q: usize, rows: Rows, batched: bool) -> Result<()> {
if self.side_qsa() {
@@ -97,6 +74,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
if self.side_qsa() {
return Ok(()); // issued on side stream 0 by `issue_qsa_side`
}
if self.fused_index_image(layer)?.is_some() {
return Ok(()); // the snapshot is the first step of the fused indexer launch of `qsa_indexer_append`
}
let base = &self.resources.base;
base.qsa.capture_tail_snapshot(&base.journal, self.capture, layer)
}
@@ -107,6 +87,9 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
if self.side_qsa() {
return Ok(()); // issued on side stream 0 by `issue_qsa_side`
}
if let Some(image) = self.fused_index_image(layer)? {
return self.issue_index_rows(layer, rows, image);
}
let base = &self.resources.base;
base.qsa.capture_append_rows(&base.journal, self.capture, layer, rows.begin..rows.end)
}
@@ -241,11 +224,26 @@ impl WindowOps for OriginalVerifyWindowOps<'_, '_, '_, '_> {
// 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)
self.resources.base.head.capture_head_greedy(self.capture)?;
self.capture_finite_verdict()
}
}
impl OriginalVerifyWindowOps<'_, '_, '_, '_> {
impl OriginalVerifyWindowOps<'_, '_, '_> {
/// `LELEKA_SM120_ACCEPT_ON_DEVICE`: after the greedy pick, the finite scan of the logits and the store of its
/// verdict into the head rows' mapped word, as the last nodes of the graph (vanilla's order, `verify.cpp:2380`).
/// Recorded only when `resolve_sm120_switches` marked the head rows of this graph; the literal graph records
/// nothing here and the scan then runs after the drain. Nothing before the pick changes.
fn capture_finite_verdict(&mut self) -> Result<()> {
let head = &self.resources.base.head;
if !head.finite_verdict_in_graph() {
return Ok(());
}
let (rows, verdict) = (head.rows(), head.finite_verdict_address()?);
let logits = head.completed_logits()?;
self.resources.verifier_journal().capture_finite_verdict(self.capture, logits, (rows, verdict))
}
/// Device block and mapped source of this group's GPU plan words.
fn plan_copy_addresses(&self, rows: Rows) -> Result<(u64, u64)> {
let layout = self.plan();
@@ -10,7 +10,7 @@ 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::qsa::{QsaLayerAddrs, QsaRope, QsaWindow, fused_prelude::IndexImage};
use super::window_plan::{gdn_index, qsa_index};
use super::window_record::{ExpertTier, HcHalf, Projection, QuantSource, Rows, WindowPolicy};
use crate::{Error, Result};
@@ -135,6 +135,10 @@ impl<'p> Planner<'p> {
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)
}
/// `LELEKA_SM120_FUSED_QSA_PRELUDE`: the layer's tail snapshot and indexer append rows as one launch.
pub(crate) fn qsa_index_rows(&self, q: usize, rows: Rows, image: &IndexImage) -> Result<Vec<Launch>> {
Ok(vec![self.qsa_window()?.index_rows(q, image, 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)
}
@@ -4,6 +4,7 @@ use super::super::kernels::{LayoutMap, test_geometry};
use super::super::moe::MoeLayerAddrs;
use super::super::proj::NativeWeight;
use super::super::qsa::{OriginalVerifyQsaKvBinding, QsaWeightAddrs, RopeCorrectionRange};
use super::super::qsa::fused_prelude::{IndexImage, IndexRope};
use super::super::window_plan::WINDOW_LAYERS;
use super::super::window_record::{WindowOps, record_window};
use super::*;
@@ -50,6 +51,21 @@ fn fake_qsa_kv(b: u64) -> OriginalVerifyQsaKvBinding {
}
}
/// The retained index image of QSA layer `q` (distinct addresses, analytic RoPE).
fn fake_index_image(q: usize) -> IndexImage {
let b = 0x70_0000_0000u64 + q as u64 * 0x1000_0000;
let rope = IndexRope {
theta_scale: 0.75,
freq_scale: 1.0,
corr_low: 0.0,
corr_high: 0.0,
ext_factor: 0.0,
magnitude: 1.0,
};
let (tail, dead, pooled, block_pos, gamma) = (b, b + 0x1000, b + 0x2000, b + 0x3000, b + 0x4000);
IndexImage { tail, dead, pooled, block_pos, gamma, positions: 0, rope }
}
impl WindowWeights for Fake {
fn gdn_projections(&self, g: usize) -> Result<GdnProjectionAddrs> {
let b = 0x10_0000_0000u64 + g as u64 * 0x1000_0000;
@@ -201,13 +217,20 @@ impl WindowOps for PlanOps<'_> {
self.plan("k_norm_rope", x)
}
fn qsa_tail_snapshot(&mut self, q: usize) -> Result<()> {
if self.planner.policy.qsa.fused_prelude {
return Ok(()); // the first step of the fused indexer launch
}
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<()> {
fn qsa_indexer_append(&mut self, q: usize, r: Rows) -> Result<()> {
if self.planner.policy.qsa.fused_prelude {
let x = self.planner.qsa_index_rows(q, r, &fake_index_image(q));
return self.plan("index_rows", x);
}
self.mark(format!("indexer_append q{q}"))
}
fn qsa_q_path(&mut self, q: usize, r: Rows, b: bool) -> Result<()> {
@@ -318,3 +341,5 @@ fn names(log: &[String]) -> Vec<&str> {
#[path = "tests/every_window_size_and_group.rs"]
mod every_window_size_and_group;
#[path = "tests/fused_qsa_prelude.rs"]
mod fused_qsa_prelude;
@@ -0,0 +1,145 @@
//! `LELEKA_SM120_FUSED_QSA_PRELUDE` through the recorder: the launch sequence with the switch on has fewer
//! launches, and the two fused launches bind exactly the cells the replaced launches write.
use super::super::super::kernels::A;
use super::super::super::window_plan::qsa_layer;
#[allow(unused_imports)]
use super::*;
fn policy_with(fused: bool) -> WindowPolicy {
let mut policy = WindowPolicy::mode17();
policy.qsa.fused_prelude = fused;
policy
}
fn record_with(fused: bool, t: usize, groups: usize) -> Vec<String> {
let (m, fake) = geometry_and_fake(false);
let policy = policy_with(fused);
let planner = Planner::new(&m, test_geometry(), policy, sm120(), &fake);
let mut ops = PlanOps { planner, log: Vec::new(), t };
record_window(&mut ops, &policy, t, groups, false).unwrap();
ops.log
}
fn prelude(log: &[String], q: usize) -> Vec<&str> {
let l = qsa_layer(q);
names(section(log, &format!("stamp {l}.8"), &format!("stamp {l}.9")))
}
fn words(l: &Launch) -> &[u64] {
match l.args.as_slice() {
[A::Words(w)] => w,
other => panic!("one by-value struct expected, got {other:?}"),
}
}
fn address(a: &A) -> u64 {
match a {
A::P(p) => *p,
other => panic!("address expected, got {other:?}"),
}
}
#[test]
fn the_default_window_keeps_one_launch_per_row_and_the_snapshot() {
let log = record_with(false, 4, 1);
assert_eq!(log, record(4, 1, false));
assert_eq!(prelude(&log, 0).iter().filter(|s| **s == "mtp_original_append").count(), 4);
assert!(prelude(&log, 0).contains(&"tail q0") && prelude(&log, 0).contains(&"indexer_append q0"));
assert!(!log.iter().any(|s| s.starts_with("leleka_verify_qsa_")));
}
#[test]
fn the_switch_replaces_the_prelude_of_every_layer_by_two_launches() {
for t in [1usize, 2, 4, 8] {
let on = record_with(true, t, 1);
let off = record_with(false, t, 1);
for q in 0..12 {
let kernels: Vec<&str> =
prelude(&on, q).into_iter().filter(|s| s.starts_with("leleka_verify_qsa_")).collect();
assert_eq!(kernels, ["leleka_verify_qsa_kv_rows", "leleka_verify_qsa_index_rows"], "t={t} q={q}");
let replaced = prelude(&off, q).into_iter().filter(|s| *s == "mtp_original_append").count() + 1 + t;
assert_eq!(replaced, 2 * t + 1, "snapshot + t K/V appends + t indexer appends");
}
assert_eq!(on.iter().filter(|s| s.starts_with("leleka_verify_qsa_")).count(), 24);
let literal = |s: &String| s == "mtp_original_append" || s.starts_with("tail q");
assert!(!on.iter().any(literal) && !on.iter().any(|s| s.starts_with("indexer_append")));
}
}
/// The recorded entries that belong to the prelude, whichever way it is recorded.
fn is_prelude_entry(s: &str) -> bool {
s.starts_with("leleka_verify_qsa_")
|| s == "mtp_original_append"
|| s.starts_with("tail q")
|| s.starts_with("indexer_append")
|| s.contains("index_rows")
|| s.contains("kv_append")
}
#[test]
fn the_switch_changes_nothing_outside_the_prelude() {
for t in [1usize, 2, 4, 8] {
let strip = |l: Vec<String>| l.into_iter().filter(|s| !is_prelude_entry(s)).collect::<Vec<_>>();
assert_eq!(strip(record_with(true, t, 1)), strip(record_with(false, t, 1)), "t={t}");
}
}
#[test]
fn a_split_window_snapshots_once_per_layer_and_appends_every_row_once() {
let on = record_with(true, 5, 2);
assert_eq!(on.iter().filter(|s| *s == "leleka_verify_qsa_index_rows").count(), 24);
assert_eq!(on.iter().filter(|s| *s == "leleka_verify_qsa_kv_rows").count(), 24);
assert!(!on.iter().any(|s| s.starts_with("tail q")));
}
fn planners(fused: bool) -> (LayoutMap, Fake, WindowPolicy) {
let (m, fake) = geometry_and_fake(false);
(m, fake, policy_with(fused))
}
#[test]
fn the_fused_kv_launch_binds_the_cells_of_the_per_row_launches() {
let (m, fake, off) = planners(false);
let (_, _, on) = planners(true);
let per_row = Planner::new(&m, test_geometry(), off, sm120(), &fake);
let fused = Planner::new(&m, test_geometry(), on, sm120(), &fake);
let row_bytes = 2 * 256 * 4;
for rows in
[Rows { begin: 0, end: 4, group: 0 }, Rows { begin: 2, end: 5, group: 1 }, Rows { begin: 7, end: 8, group: 1 }]
{
let literal = per_row.qsa_kv_append(1, rows).unwrap();
let one = fused.qsa_kv_append(1, rows).unwrap();
assert_eq!((literal.len(), one.len()), (rows.len(), 1));
let w = words(&one[0]);
assert_eq!(one[0].grid, [(rows.len() * 2 * 2) as u32, 1, 1]);
for (j, l) in literal.iter().enumerate() {
let a: Vec<u64> = l.args.iter().take(8).map(address).collect();
assert_eq!(a[..5], w[..5], "resident pools and page table");
assert_eq!(a[5], w[9] + 16 * j as u64, "step row {j}");
assert_eq!(a[6], w[10] + (row_bytes * j) as u64, "K row {j}");
assert_eq!(a[7], w[11] + (row_bytes * j) as u64, "V row {j}");
let host: Vec<u64> = l.args[11..].iter().map(address).collect();
assert_eq!(host, w[5..9]);
}
assert_eq!(w[14] >> 32, rows.len() as u64);
}
}
#[test]
fn the_fused_index_launch_binds_the_rows_the_journal_appends_one_by_one() {
let (m, fake, on) = planners(true);
let planner = Planner::new(&m, test_geometry(), on, sm120(), &fake);
for (q, rows) in [(0, Rows { begin: 0, end: 4, group: 0 }), (11, Rows { begin: 3, end: 8, group: 1 })] {
let image = fake_index_image(q);
let one = planner.qsa_index_rows(q, rows, &image).unwrap();
assert_eq!(one.len(), 1);
let w = words(&one[0]);
for (j, row) in (rows.begin..rows.end).enumerate() {
// `append_command`: raw = idx_raw_L + (layer * max_t + row) * 512, step = step + row * 16
let raw = m.span("idx_raw_L", (q * 8 + row) * 512, 512).unwrap();
let step = m.span("step", row * 16, 4).unwrap();
assert_eq!((w[0] + 512 * j as u64, w[1] + 16 * j as u64), (raw, step), "row {row}");
}
assert_eq!(&w[2..8], &[image.tail, image.dead, image.pooled, image.block_pos, image.gamma, 0]);
// the snapshot (verify_copy_from_mapped_kernel into tail_snap + layer * 1536) only before the first group
let snapshot = if rows.group == 0 { m.span("tail_snap", q * 1536, 1536).unwrap() } else { 0 };
assert_eq!((w[8], w[9], w[10]), (snapshot, rows.len() as u64, 4096));
}
}
@@ -15,7 +15,7 @@ use super::kernels::{A, ArenaMap, AssetSpec, Launch, LaunchExtent};
use super::window_plan::{gdn_index, qsa_index};
use super::window_record::{Projection, QuantSource, Rows};
use crate::native_head::native_head_row_bytes;
use crate::{Context, DeviceBuffer};
use crate::{Context, DeviceRef};
use crate::{Error, NativeHeadDispatch, Result};
#[path = "mtp_original_full_head_dispatch.rs"]
@@ -5,19 +5,19 @@ use super::*;
pub(super) fn admit_matrix(
context: &Context<'_>,
m: &OriginalVerifyNativeMatrix<'_, '_>,
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::super::admit(context, m.buffer, bytes)? })
Ok(NativeWeight { ty: m.kind, data: super::super::admit(context, &m.buffer, bytes)? })
}
impl<'a, 'ctx> OriginalVerifyProjBinding<'a, 'ctx> {
impl<'ctx> OriginalVerifyProjBinding<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
geometry: &OriginalVerifyGeometry,
gdn: Vec<OriginalVerifyGdnProjections<'a, 'ctx>>,
qsa: Vec<OriginalVerifyQsaProjections<'a, 'ctx>>,
gdn: Vec<OriginalVerifyGdnProjections<'ctx>>,
qsa: Vec<OriginalVerifyQsaProjections<'ctx>>,
) -> Result<Self> {
if gdn.len() != 36 || qsa.len() != 12 {
return Err(Error::InvalidQwenShape);
@@ -151,22 +151,22 @@ pub(crate) struct NativeWeight {
}
/// One native projection weight with its buffer, as the runtime hands it over.
pub struct OriginalVerifyNativeMatrix<'a, 'ctx> {
pub struct OriginalVerifyNativeMatrix<'ctx> {
pub kind: u32,
pub buffer: &'a DeviceBuffer<'ctx>,
pub buffer: DeviceRef<'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>,
pub struct OriginalVerifyGdnProjections<'ctx> {
pub qkv: OriginalVerifyNativeMatrix<'ctx>,
pub gate: OriginalVerifyNativeMatrix<'ctx>,
pub out: OriginalVerifyNativeMatrix<'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>,
pub struct OriginalVerifyQsaProjections<'ctx> {
pub k: OriginalVerifyNativeMatrix<'ctx>,
pub v: OriginalVerifyNativeMatrix<'ctx>,
pub q: OriginalVerifyNativeMatrix<'ctx>,
pub out: OriginalVerifyNativeMatrix<'ctx>,
}
/// Addresses of a GDN layer's projections.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -186,7 +186,7 @@ pub(crate) struct QsaProjectionAddrs {
/// 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> {
pub(super) gdn: Vec<OriginalVerifyGdnProjections<'a, 'ctx>>,
pub(super) qsa: Vec<OriginalVerifyQsaProjections<'a, 'ctx>>,
pub struct OriginalVerifyProjBinding<'ctx> {
pub(super) gdn: Vec<OriginalVerifyGdnProjections<'ctx>>,
pub(super) qsa: Vec<OriginalVerifyQsaProjections<'ctx>>,
}
@@ -28,7 +28,7 @@ use super::proj::{self, Bf16GemvExtents, StridedRows, plan_bf16_gemv};
use super::window_record::Rows;
use super::{OriginalVerifyGeometry, admit, handle};
use crate::qsa_index_ffi::{RopeAbi, rope_abi};
use crate::{Context, DeviceBuffer, Error, Result};
use crate::{Context, DeviceRef, Error, Result};
/// `EPS` of verify.cpp (RMS epsilon of every QSA norm).
const EPS: f32 = 1e-6;
@@ -181,6 +181,10 @@ pub struct OriginalVerifyQsaPolicy {
/// merge as the Original's chunk and merge kernels. Off in `mode17()`; `record_literal_window` resolves it from the
/// card and `LELEKA_SM120_ATTN_DAILY`.
pub attn_daily: bool,
/// `LELEKA_SM120_FUSED_QSA_PRELUDE` (`fused_prelude.rs`): the K/V rows and the indexer rows
/// (with the tail snapshot) of a layer as one launch each, bitwise the same cells. Off in `mode17()`;
/// `record_literal_window` resolves it from the card, the environment and the seal of its two modules.
pub fused_prelude: bool,
}
/// The resolved `rope_scaling()` constants of the window (`OriginalVerifyRope` without its tables).
@@ -232,17 +236,17 @@ pub struct OriginalVerifyQsaKvBinding {
}
/// The weights of one QSA layer that the window producers read directly.
pub struct OriginalVerifyQsaLayerWeights<'a, 'ctx> {
pub struct OriginalVerifyQsaLayerWeights<'ctx> {
/// `attn_q_norm.weight`, F32 `[head_dim]`.
pub attn_q_norm: &'a DeviceBuffer<'ctx>,
pub attn_q_norm: DeviceRef<'ctx>,
/// `attn_k_norm.weight`, F32 `[head_dim]`.
pub attn_k_norm: &'a DeviceBuffer<'ctx>,
pub attn_k_norm: DeviceRef<'ctx>,
/// `indexer.q_norm.weight`, F32 `[index_dim]`.
pub index_q_norm: &'a DeviceBuffer<'ctx>,
pub index_q_norm: DeviceRef<'ctx>,
/// `indexer.k_proj.weight`, BF16 `[index_dim][n_embd]`.
pub index_k_proj: &'a DeviceBuffer<'ctx>,
pub index_k_proj: DeviceRef<'ctx>,
/// `indexer.q_proj.weight`, BF16 `[index_heads * index_dim][n_embd]`.
pub index_q_proj: &'a DeviceBuffer<'ctx>,
pub index_q_proj: DeviceRef<'ctx>,
}
/// Device addresses of one layer's weights, after byte-exact admission.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -255,10 +259,10 @@ pub struct QsaWeightAddrs {
}
/// The 12 QSA layers' direct weight operands. The index key norm gamma and the index images live in
/// `OriginalVerifyQsaJournal`; the K/V and quantized projections are `proj`/mmvq operands.
pub struct OriginalVerifyQsaBinding<'a, 'ctx> {
pub struct OriginalVerifyQsaBinding<'ctx> {
context: &'ctx Context<'ctx>,
geometry: OriginalVerifyGeometry,
layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12],
layers: [OriginalVerifyQsaLayerWeights<'ctx>; 12],
}
/// Everything one window's QSA plans need: arena, geometry, policy and RoPE constants.
@@ -302,5 +306,7 @@ use assets::max_blocks;
use assets::scratch_floats;
#[allow(unused_imports)]
pub(crate) use assets::shared_attributes;
#[path = "original_verify_window_qsa/fused_prelude.rs"]
pub(crate) mod fused_prelude;
#[path = "original_verify_window_qsa/qsa_window.rs"]
mod qsa_window;
@@ -48,6 +48,7 @@ impl OriginalVerifyQsaPolicy {
scores_multi: true,
cluster_topk: false,
attn_daily: false,
fused_prelude: false,
}
}
/// Refuse every variant that has no genuine sealed owner, with its reason.
@@ -99,7 +100,7 @@ impl QsaRope {
Ok(Self { theta_scale, freq_scale, corr_low, corr_high, ext_factor, mscale })
}
/// From the journal's resolved Original constants. Table variants have no sealed kernel here.
pub fn from_rope(rope: &crate::OriginalVerifyRope<'_, '_>) -> Result<Self> {
pub fn from_rope(rope: &crate::OriginalVerifyRope<'_>) -> Result<Self> {
if rope.positions.is_some() {
return Err(refuse!("an M-RoPE position table needs the mtab variant of native_rope (no sealed kernel)"));
}
@@ -120,7 +121,7 @@ impl QsaRope {
}
impl OriginalVerifyQsaKvBinding {
/// Read the fixed addresses of QSA layer `layer` from the retained journal (nothing is changed).
pub(crate) fn from_journal(qsa: &crate::OriginalVerifyQsaJournal<'_, '_>, layer: usize) -> Result<Self> {
pub(crate) fn from_journal(qsa: &crate::OriginalVerifyQsaJournal<'_>, layer: usize) -> Result<Self> {
let a = qsa.window_addresses(layer)?;
Ok(Self {
resident: a.resident,
@@ -162,11 +163,11 @@ impl OriginalVerifyQsaKvBinding {
Ok(())
}
}
impl<'a, 'ctx> OriginalVerifyQsaBinding<'a, 'ctx> {
impl<'ctx> OriginalVerifyQsaBinding<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
geometry: OriginalVerifyGeometry,
layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12],
layers: [OriginalVerifyQsaLayerWeights<'ctx>; 12],
) -> Result<Self> {
geometry.validate()?;
let this = Self { context, geometry, layers };
@@ -184,7 +185,7 @@ impl<'a, 'ctx> OriginalVerifyQsaBinding<'a, 'ctx> {
let sizes = Self::sizes(&self.geometry);
let mut spans = Vec::with_capacity(60);
for w in &self.layers {
let bufs = [w.attn_q_norm, w.attn_k_norm, w.index_q_norm, w.index_k_proj, w.index_q_proj];
let bufs = [&w.attn_q_norm, &w.attn_k_norm, &w.index_q_norm, &w.index_k_proj, &w.index_q_proj];
for (b, bytes) in bufs.into_iter().zip(sizes) {
admit(context, b, bytes)?;
spans.push((handle(b)?, bytes));
@@ -202,11 +203,11 @@ impl<'a, 'ctx> OriginalVerifyQsaBinding<'a, 'ctx> {
let w = self.layers.get(q).ok_or(Error::InvalidQwenShape)?;
let s = Self::sizes(&self.geometry);
Ok(QsaWeightAddrs {
q_norm: admit(self.context, w.attn_q_norm, s[0])?,
k_norm: admit(self.context, w.attn_k_norm, s[1])?,
index_q_norm: admit(self.context, w.index_q_norm, s[2])?,
index_k_proj: admit(self.context, w.index_k_proj, s[3])?,
index_q_proj: admit(self.context, w.index_q_proj, s[4])?,
q_norm: admit(self.context, &w.attn_q_norm, s[0])?,
k_norm: admit(self.context, &w.attn_k_norm, s[1])?,
index_q_norm: admit(self.context, &w.index_q_norm, s[2])?,
index_k_proj: admit(self.context, &w.index_k_proj, s[3])?,
index_q_proj: admit(self.context, &w.index_q_proj, s[4])?,
})
}
}
@@ -0,0 +1,206 @@
//! verify-qsa-fused-prelude: the K/V and indexer appends of a QSA layer of the verify window as two launches
//! (`LELEKA_SM120_FUSED_QSA_PRELUDE`, off by default; docs/experiments/verify-qsa-fused-prelude.md).
//!
//! The literal window records, per QSA layer and window row, `mtp_original_append` (K/V into the INT8 pools) and
//! `verify_qsa_append_analytic` (the indexer key), plus one tail snapshot copy before the first row: `2 n + 1`
//! launches.
//! With the switch on:
//!
//! * `leleka_verify_qsa_kv_rows` (`original_verify_window_qsa_kv_rows.cu`, precise math) is the n `mtp_original_append`
//! launches with the rows along the grid (rows are independent: every row writes its own cell);
//! * `leleka_verify_qsa_index_rows` (`original_verify_window_qsa_index_rows.cu`, fast math like the Original indexer)
//! is the tail snapshot and the n `verify_qsa_append_analytic` launches as one chain in one CTA (row r + 1 reads what
//! row r wrote).
//!
//! The two stay separate launches because they differ in math mode and because the QSA side streams
//! (`SIDE_QSA`) run the indexer chain beside the K/V chain: each launch sits where the launches it replaces sit.
//! The plans are pure (addresses in, one `Launch` out); the kernel arguments are by-value structs of u64 words.
use super::super::kernels::{A, AssetSpec, Launch, LaunchExtent};
use super::OriginalVerifyQsaKvBinding;
use crate::{Error, Result};
pub(crate) const E_KV_ROWS: &str = "leleka_verify_qsa_kv_rows";
pub(crate) const E_INDEX_ROWS: &str = "leleka_verify_qsa_index_rows";
/// `original_verify_window_qsa_kv_rows.cu`, precise math (the recipe of `mtp_original_kv.ptx`), nvcc 13.2.86, sealed
/// with `scripts/gpu-bringup` (extra-seal-plan.json, group verify-qsa-prelude). `resolve` keeps the switch inert while
/// a pin does not match its bytes.
pub(crate) static KV_ROWS: AssetSpec = AssetSpec {
name: "original_verify_window_qsa_kv_rows.ptx",
ptx: concat!(include_str!("../original_verify_window_qsa_kv_rows.ptx"), "\0").as_bytes(),
sha: [
217, 24, 52, 136, 189, 9, 207, 86, 34, 6, 137, 55, 116, 152, 82, 81, 123, 82, 109, 46, 201, 207, 91, 113, 81,
42, 29, 254, 208, 161, 219, 133,
],
entries: &[E_KV_ROWS],
unsealed: "Original verifier asset unsealed: original_verify_window_qsa_kv_rows.ptx (fused K/V append rows)",
};
/// `original_verify_window_qsa_index_rows.cu`, fast math like `original_verify_qsa.ptx`; nvcc 13.2.86, sealed as
/// `KV_ROWS`.
pub(crate) static INDEX_ROWS: AssetSpec = AssetSpec {
name: "original_verify_window_qsa_index_rows.ptx",
ptx: concat!(include_str!("../original_verify_window_qsa_index_rows.ptx"), "\0").as_bytes(),
sha: [
113, 219, 156, 79, 31, 64, 14, 200, 110, 124, 241, 140, 177, 124, 53, 4, 138, 238, 50, 70, 215, 152, 40, 219,
112, 252, 43, 86, 45, 44, 213, 125,
],
entries: &[E_INDEX_ROWS],
unsealed: "Original verifier asset unsealed: original_verify_window_qsa_index_rows.ptx (fused indexer append rows)",
};
/// `kStepCount` of the step rows: the words between two window rows of the "step" span.
const STEP_WORDS: usize = 4;
/// Threads of both kernels (`THREADS` of the .cu files).
const THREADS: u32 = 256;
/// The key width of the indexer image (`D` of the .cu file) and the INT8 scale group (`KV_GROUP`).
const INDEX_DIM: usize = 128;
const KV_GROUP: usize = 64;
/// The modules a window needs when the switch is on.
pub(crate) fn assets(on: bool) -> Vec<&'static AssetSpec> {
if on { vec![&KV_ROWS, &INDEX_ROWS] } else { Vec::new() }
}
/// Both modules are sealed (their pins match their bytes).
pub(crate) fn sealed() -> bool {
KV_ROWS.sealed().is_ok() && INDEX_ROWS.sealed().is_ok()
}
/// The switch as the window records it: requested, and the sealed modules exist. An unsealed module keeps the literal
/// launches (fail closed), and says so once.
pub(crate) fn resolve(requested: bool) -> bool {
let on = requested && sealed();
static SAID: std::sync::Once = std::sync::Once::new();
if requested && !on {
SAID.call_once(|| eprintln!("leleka-serve fused QSA prelude: refused (PTX not sealed), per-row launches kept"));
}
on
}
fn pack(low: u32, high: u32) -> u64 {
u64::from(low) | (u64::from(high) << 32)
}
fn pack_i32(low: usize, high: usize) -> Result<u64> {
let int = |v: usize| i32::try_from(v).map(|v| v as u32).map_err(|_| Error::InvalidQwenShape);
Ok(pack(int(low)?, int(high)?))
}
fn pack_f32(low: f32, high: f32) -> u64 {
pack(low.to_bits(), high.to_bits())
}
/// Where the K/V rows of one launch live: the first step row, the first K and V rows, and how many rows.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct KvRowsOperands {
pub step: u64,
pub kcur: u64,
pub vcur: u64,
pub rows: usize,
}
/// The cache shape the K/V rows append into.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct KvRowsShape {
pub kv_heads: usize,
pub head_dim: usize,
pub page_size: usize,
}
/// `rows` x `mtp_original_append` as one launch: grid (rows * 2 * kv_heads), 256 threads.
pub(crate) fn plan_kv_rows(kv: &OriginalVerifyQsaKvBinding, ops: KvRowsOperands, shape: KvRowsShape) -> Result<Launch> {
let KvRowsShape { kv_heads, head_dim, page_size } = shape;
if ops.rows == 0 || kv_heads == 0 || head_dim == 0 || head_dim % KV_GROUP != 0 || page_size == 0 {
return Err(Error::InvalidQwenShape);
}
let [k_q, v_q, k_scale, v_scale] = kv.resident;
let [host_k_q, host_v_q, host_k_scale, host_v_scale] = kv.host;
let words = vec![
k_q,
v_q,
k_scale,
v_scale,
kv.table,
host_k_q,
host_v_q,
host_k_scale,
host_v_scale,
ops.step,
ops.kcur,
ops.vcur,
pack_i32(kv_heads, head_dim)?,
pack_i32(page_size, STEP_WORDS)?,
pack_i32(kv_heads * head_dim, ops.rows)?,
];
let blocks = u32::try_from(ops.rows * 2 * kv_heads).map_err(|_| Error::InvalidQwenShape)?;
Launch::new(&KV_ROWS, E_KV_ROWS, LaunchExtent::new([blocks, 1, 1], [THREADS, 1, 1], 0), vec![A::Words(words)])
}
/// The RoPE constants of the indexer keys (`OriginalVerifyRope`, analytic variant).
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct IndexRope {
pub theta_scale: f32,
pub freq_scale: f32,
pub corr_low: f32,
pub corr_high: f32,
pub ext_factor: f32,
pub magnitude: f32,
}
/// The fixed addresses of one layer's retained index image and its key norm (what `append_plan` binds for every row):
/// `positions` is 0 without a retained position table.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct IndexImage {
pub tail: u64,
pub dead: u64,
pub pooled: u64,
pub block_pos: u64,
pub gamma: u64,
pub positions: u64,
pub rope: IndexRope,
}
/// The window rows of one indexer launch: the raw key rows, the step rows, the snapshot destination (0: no snapshot,
/// every row group but the first) and the cell limit.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct IndexRowsOperands {
pub raw: u64,
pub step: u64,
pub snapshot: u64,
pub rows: usize,
pub max_cells: usize,
}
/// The tail snapshot and `rows` x `verify_qsa_append_analytic` as one launch: one CTA of 256 threads.
pub(crate) fn plan_index_rows(image: &IndexImage, ops: IndexRowsOperands) -> Result<Launch> {
if ops.rows == 0 || ops.max_cells == 0 {
return Err(Error::InvalidQwenShape);
}
let r = &image.rope;
let words = vec![
ops.raw,
ops.step,
image.tail,
image.dead,
image.pooled,
image.block_pos,
image.gamma,
image.positions,
ops.snapshot,
ops.rows as u64,
ops.max_cells as u64,
pack_f32(1e-6, r.theta_scale),
pack_f32(r.freq_scale, r.corr_low),
pack_f32(r.corr_high, r.ext_factor),
pack_f32(r.magnitude, 0.0),
];
Launch::new(&INDEX_ROWS, E_INDEX_ROWS, LaunchExtent::new([1, 1, 1], [THREADS, 1, 1], 0), vec![A::Words(words)])
}
/// The indexer key width the kernel is written for.
pub(crate) fn index_dim_supported(index_dim: usize) -> bool {
index_dim == INDEX_DIM
}
#[cfg(test)]
#[path = "fused_prelude/tests.rs"]
mod tests;
@@ -0,0 +1,112 @@
//! Unit tests of the fused QSA prelude plans (the recorded window sequence is tested in the planner tests).
use super::*;
fn binding() -> OriginalVerifyQsaKvBinding {
OriginalVerifyQsaKvBinding {
resident: [0x10, 0x20, 0x30, 0x40],
table: 0x50,
host: [0x60, 0x70, 0x80, 0x90],
resolver: [0; 7],
slots: 8192,
pooled: 0xa0,
pooled_bytes: 1026 * 512,
dead: 0xb0,
dead_bytes: 512,
}
}
fn words(l: &Launch) -> &[u64] {
match l.args.as_slice() {
[A::Words(w)] => w,
other => panic!("one by-value struct expected, got {other:?}"),
}
}
fn image() -> IndexImage {
IndexImage {
tail: 0x1000,
dead: 0x2000,
pooled: 0x3000,
block_pos: 0x4000,
gamma: 0x5000,
positions: 0,
rope: IndexRope {
theta_scale: 0.75,
freq_scale: 1.0,
corr_low: 2.0,
corr_high: 3.0,
ext_factor: 0.5,
magnitude: 1.25,
},
}
}
#[test]
fn the_kv_rows_launch_is_one_cta_per_row_kind_and_head_with_the_literal_pools() {
let ops = KvRowsOperands { step: 0x100, kcur: 0x200, vcur: 0x300, rows: 5 };
let l = plan_kv_rows(&binding(), ops, KvRowsShape { kv_heads: 2, head_dim: 256, page_size: 4 }).unwrap();
assert_eq!((l.entry, l.grid, l.block, l.shared, l.cluster), (E_KV_ROWS, [20, 1, 1], [256, 1, 1], 0, 0));
let w = words(&l);
assert_eq!(w.len(), 15, "KvRowsArgs of the .cu: 12 addresses and 6 i32");
assert_eq!(&w[..9], &[0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80, 0x90]);
assert_eq!(&w[9..12], &[0x100, 0x200, 0x300]);
// kv_heads, head_dim | page_size, step_stride | cur_stride, rows
assert_eq!(&w[12..], &[2 | 256 << 32, 4 | 4 << 32, 512 | 5 << 32]);
}
#[test]
fn the_index_rows_launch_is_one_cta_and_carries_the_literal_append_operands() {
let ops = IndexRowsOperands { raw: 0x10, step: 0x20, snapshot: 0x30, rows: 3, max_cells: 4096 };
let l = plan_index_rows(&image(), ops).unwrap();
assert_eq!((l.entry, l.grid, l.block, l.shared, l.cluster), (E_INDEX_ROWS, [1, 1, 1], [256, 1, 1], 0, 0));
let w = words(&l);
assert_eq!(w.len(), 15, "IndexRowsArgs of the .cu: 11 words and 8 floats");
assert_eq!(&w[..11], &[0x10, 0x20, 0x1000, 0x2000, 0x3000, 0x4000, 0x5000, 0, 0x30, 3, 4096]);
let f = |x: f32| u64::from(x.to_bits());
assert_eq!(w[11], f(1e-6) | f(0.75) << 32);
assert_eq!(&w[12..], &[f(1.0) | f(2.0) << 32, f(3.0) | f(0.5) << 32, f(1.25)]);
}
#[test]
fn degenerate_shapes_are_refused() {
let shape = KvRowsShape { kv_heads: 2, head_dim: 256, page_size: 4 };
let ok = KvRowsOperands { step: 1, kcur: 2, vcur: 3, rows: 1 };
assert!(plan_kv_rows(&binding(), ok, shape).is_ok());
assert!(plan_kv_rows(&binding(), KvRowsOperands { rows: 0, ..ok }, shape).is_err());
assert!(plan_kv_rows(&binding(), ok, KvRowsShape { head_dim: 100, ..shape }).is_err());
assert!(plan_kv_rows(&binding(), ok, KvRowsShape { kv_heads: 0, ..shape }).is_err());
let rows = IndexRowsOperands { raw: 1, step: 2, snapshot: 0, rows: 1, max_cells: 8 };
assert!(plan_index_rows(&image(), rows).is_ok());
assert!(plan_index_rows(&image(), IndexRowsOperands { rows: 0, ..rows }).is_err());
assert!(plan_index_rows(&image(), IndexRowsOperands { max_cells: 0, ..rows }).is_err());
assert!(index_dim_supported(128) && !index_dim_supported(64));
}
#[test]
fn the_cuda_sources_declare_the_entries_and_the_argument_structs_the_plans_fill() {
let kv = include_str!("../../original_verify_window_qsa_kv_rows.cu");
let index = include_str!("../../original_verify_window_qsa_index_rows.cu");
assert!(kv.contains(&format!("__launch_bounds__(THREADS) {E_KV_ROWS}(KvRowsArgs a)")));
assert!(index.contains(&format!("__launch_bounds__(THREADS) {E_INDEX_ROWS}(IndexRowsArgs a)")));
assert!(kv.contains("constexpr int THREADS = 256;") && index.contains("THREADS = 256;"));
assert!(index.contains("D = 128") && kv.contains("KV_GROUP = 64"));
// the precise recipe has no fast math; the indexer recipe is the one of the Original indexer
assert!(kv.contains("--ftz=false") && index.contains("--use_fast_math"));
}
#[test]
fn the_modules_load_only_with_the_switch_and_a_missing_seal_fails_closed() {
assert!(assets(false).is_empty());
let on = assets(true);
assert!(on.iter().any(|a| std::ptr::eq(*a, &KV_ROWS)) && on.iter().any(|a| std::ptr::eq(*a, &INDEX_ROWS)));
assert!(!resolve(false));
for spec in [&KV_ROWS, &INDEX_ROWS] {
if spec.sealed().is_ok() {
spec.assert_sealed_and_fail_closed();
} else {
// no PTX was built yet: refused by the asset's own text, and the switch stays off
assert_eq!(spec.sealed(), Err(Error::InvalidDriverValue(spec.unsealed)));
assert!(!sealed() && !resolve(true));
}
}
assert_eq!(resolve(true), sealed());
}
@@ -3,6 +3,8 @@
#[allow(unused_imports)]
use super::*;
#[path = "qsa_window/qsa_window_prelude_rows.rs"]
mod qsa_window_prelude_rows;
#[path = "qsa_window/qsa_window_query_key_paths.rs"]
mod qsa_window_query_key_paths;
#[path = "qsa_window/qsa_window_select_and_attend.rs"]
@@ -0,0 +1,46 @@
//! `LELEKA_SM120_FUSED_QSA_PRELUDE`: the K/V rows and the indexer rows of a QSA layer as one launch each
//! (`original_verify_window_qsa/fused_prelude.rs`). Same operands as the per-row plans of `qsa_kv_append` and of the
//! journal's indexer append, taken from the same arena spans.
#[allow(unused_imports)]
use super::*;
use crate::original_verify::qsa::fused_prelude::{
self, IndexImage, IndexRowsOperands, KvRowsOperands, KvRowsShape, plan_index_rows, plan_kv_rows,
};
impl<'a> QsaWindow<'a> {
/// `qsa_kv_append` of all `rows` as one launch: the same step rows and K/V rows as the per-row launches.
pub fn kv_rows(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result<Launch> {
let s = self.rows(q, rows, None)?;
let g = &self.g;
let row_bytes = g.kv_heads * g.head_dim * 4;
w.kv.validate(g)?;
let ops = KvRowsOperands {
step: self.span("step", s.tb * 16, s.n * 16)?,
kcur: self.span("kcur", s.tb * row_bytes, s.n * row_bytes)?,
vcur: self.span("vcur", s.tb * row_bytes, s.n * row_bytes)?,
rows: s.n,
};
let shape = KvRowsShape { kv_heads: g.kv_heads, head_dim: g.head_dim, page_size: PAGE_SIZE as usize };
plan_kv_rows(&w.kv, ops, shape)
}
/// The journal's tail snapshot (first row group only) and indexer append of `rows` as one launch.
pub fn index_rows(&self, q: usize, image: &IndexImage, rows: Rows) -> Result<Launch> {
let s = self.rows(q, rows, None)?;
let g = &self.g;
let key_bytes = g.index_dim * 4;
let tail_bytes = (g.index_block - 1) * key_bytes;
if !fused_prelude::index_dim_supported(g.index_dim) {
return Err(Error::InvalidQwenShape);
}
let ops = IndexRowsOperands {
raw: self.span("idx_raw_L", (q * g.max_t + s.tb) * key_bytes, s.n * key_bytes)?,
step: self.span("step", s.tb * 16, s.n * 16)?,
snapshot: if rows.group == 0 { self.span("tail_snap", q * tail_bytes, tail_bytes)? } else { 0 },
rows: s.n,
max_cells: g.max_cells,
};
plan_index_rows(image, ops)
}
}
@@ -133,6 +133,9 @@ impl<'a> QsaWindow<'a> {
/// `qsa_kv_append`: one `kv_append_q8_step` per row into the resident pool (if the page is resident)
/// and the host copy.
pub fn kv_append(&self, q: usize, w: &QsaLayerAddrs, rows: Rows) -> Result<Vec<Launch>> {
if self.policy.fused_prelude {
return Ok(vec![self.kv_rows(q, w, rows)?]);
}
let s = self.rows(q, rows, None)?;
let g = &self.g;
let (nkv, hd) = (g.kv_heads, g.head_dim);
@@ -0,0 +1,152 @@
// verify-qsa-fused-prelude: the indexer half of the QSA prelude of the verify window graph, ONE launch per layer
// (docs/experiments/verify-qsa-fused-prelude.md).
//
// The window graph records, per QSA layer, `verify_copy_from_mapped_kernel` (the tail snapshot, first row group only)
// and then one `verify_qsa_append_analytic` launch per window row (original_verify_qsa.cu, TAB = false): 1 + n
// launches of one CTA each. Row r + 1 reads what row r wrote (the tail slots, `dead`, the pooled keys), so the rows are
// a chain; this kernel is that chain in one CTA of the same 256 threads: the snapshot copy, then the body of
// `verify_qsa_append_analytic` once per row, in row order. Every row is a verbatim copy of that body (same operations,
// same order, same shuffle reduction), so every output word is computed as the replaced launches compute it.
//
// Barriers: the snapshot reads the tail before any row writes it (one barrier). A row that only stores into the tail
// (pos % 4 != 3, pos != 0) touches no shared memory and only its own tail column, so it needs none; a row that closes
// a block ends with a barrier because the next row rewrites `values` and `partials`.
//
// Only the analytic RoPE variant is fused (the table variant, `verify_qsa_append_table`, is not: the Rust side records
// the per-row launches when the retained angle tables are present).
//
// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --use_fast_math. This is the recipe of
// original_verify_qsa.cu and draft_commit_qsa.cu: the Original builds native_qsa_indexer with --use_fast_math, so powf,
// cosf and sinf are __powf / cos.approx / sin.approx and the keys are not those of a precise build.
//
// PTX built with nvcc 13.2.86 (server rnr5090, compile only) and sealed with scripts/gpu-bringup (extra-seal-plan.json,
// group verify-qsa-prelude, SHA-256 pin in original_verify_window_qsa/fused_prelude.rs).
#include <cuda_runtime.h>
#include <cuda_fp16.h>
#include <cstdint>
#include <cstddef>
#include <cmath>
constexpr int D = 128, R = 4, ROT = 64, THREADS = 256;
// by-value kernel parameter: u64 words, then the floats two per word (see original_verify_window_qsa/fused_prelude.rs)
struct IndexRowsArgs {
uint64_t raw; // float [rows][128]: the indexer key rows of this layer, from the first row of the launch
uint64_t step; // int32 [rows][4]: the step rows; word 0 of a row is the position of the new cell
uint64_t tail; // float [3 * 128]
uint64_t dead; // float [128]
uint64_t pooled; // float [blocks * 128]
uint64_t block_pos; // int32 [1]
uint64_t gamma; // float [128]
uint64_t mtab; // int32 [positions][3] (mrope), or 0
uint64_t snapshot; // float [3 * 128] destination of the tail snapshot, or 0: no snapshot
uint64_t rows;
uint64_t max_cells;
float epsilon, theta_scale, freq_scale, corr_low;
float corr_high, ext_factor, mscale, pad;
};
__device__ float warp_sum(float x) {
#pragma unroll
for (int offset = 16; offset; offset >>= 1) x += __shfl_xor_sync(0xffffffffu, x, offset);
return x;
}
__device__ __forceinline__ int mrope_pos(const int32_t* tab, int pos, int pair) {
return tab ? __ldg(tab + (size_t) pos * 3 + pair % 3) : pos;
}
__host__ __device__ inline float rope_yarn_ramp(float low, float high, int pair) {
const float y = ((float) pair - low) / (high - low > 0.001f ? high - low : 0.001f);
const float clamped = y < 0.0f ? 0.0f : (y > 1.0f ? 1.0f : y);
return 1.0f - clamped;
}
__host__ __device__ inline void rope_scaled_angle(float theta_extrap, float freq_scale, float corr_low, float corr_high,
float ext_factor, float mscale_in, int pair, float& cos_out,
float& sin_out) {
float theta = freq_scale * theta_extrap;
float mscale = mscale_in;
if (ext_factor != 0.0f) {
const float ramp_mix = rope_yarn_ramp(corr_low, corr_high, pair) * ext_factor;
theta = theta * (1.0f - ramp_mix) + theta_extrap * ramp_mix;
mscale *= 1.0f + 0.1f * logf(1.0f / freq_scale);
}
cos_out = cosf(theta) * mscale;
sin_out = sinf(theta) * mscale;
}
// The rotated key of a completed block, written to pooled[b] (and the spare to pooled[b + 1]); the tail of
// verify_qsa_append_analytic after the block norm. `values` holds the norm output of all 128 lanes.
__device__ __forceinline__ void store_block(const IndexRowsArgs& a, const float* values, int pos, int d) {
const int32_t* mtab = reinterpret_cast<const int32_t*>(a.mtab);
float* pooled = reinterpret_cast<float*>(a.pooled);
float* dead = reinterpret_cast<float*>(a.dead);
const int b = pos / R;
const int rope_pos = pos == 0 ? 0 : R * b; // pos_base is 0 in the verify window
float y = values[d];
if (d < ROT) {
const int pair = d % (ROT / 2);
float c, s;
const float theta_extrap = (pos == 0 ? 0 : mrope_pos(mtab, rope_pos, pair)) * powf(a.theta_scale, float(pair));
rope_scaled_angle(theta_extrap, a.freq_scale, a.corr_low, a.corr_high, a.ext_factor, a.mscale, pair, c, s);
const float av = values[pair], z = values[pair + ROT / 2];
y = d < ROT / 2 ? av * c - z * s : av * s + z * c;
}
pooled[std::size_t(b) * D + d] = y;
if (pos == 0) dead[d] = y;
else pooled[std::size_t(b + 1) * D + d] = dead[d];
if (d == 0 && pos != 0) *reinterpret_cast<int32_t*>(a.block_pos) = rope_pos;
}
// One row: verify_qsa_append_analytic for the row at `raw` / `pos`. Block uniform control flow; a row that does not
// close a block returns before any barrier.
__device__ __forceinline__ void append_row(const IndexRowsArgs& a, const float* raw, int pos, float* values,
float* partials) {
float* tail = reinterpret_cast<float*>(a.tail);
const float* gamma = reinterpret_cast<const float*>(a.gamma);
const int d = threadIdx.x;
const int slot = pos % R;
float incoming = 0.0f;
if (d < D) {
// SET_ROWS stores F16; GET_ROWS expands those exact values to F32.
incoming = __half2float(__float2half_rn(raw[d]));
if (slot < R - 1) tail[slot * D + d] = incoming;
}
if (pos != 0 && slot != R - 1) return;
float mean = 0.0f;
if (d < D) {
float sum = pos == 0 ? incoming : tail[d];
#pragma unroll
for (int j = 1; j < R; ++j) sum = __fadd_rn(sum, pos == 0 || j == R - 1 ? incoming : tail[j * D + d]);
mean = __fmaf_rn(0.25f, sum, 0.0f); // SCALE includes a zero bias.
}
float square_sum = 0.0f;
if (d < D) square_sum += mean * mean;
square_sum = warp_sum(square_sum);
const int lane = d % 32;
if (lane == 0) partials[d / 32] = square_sum;
__syncthreads();
square_sum = lane < THREADS / 32 ? partials[lane] : 0.0f;
square_sum = warp_sum(square_sum);
const float scale = rsqrtf(square_sum / D + a.epsilon);
if (d < D) values[d] = scale * mean * gamma[d];
__syncthreads();
if (d < D) store_block(a, values, pos, d);
__syncthreads(); // values / partials are rewritten by the next row
}
// grid (1), block (256): the snapshot, then the rows in order
extern "C" __global__ void __launch_bounds__(THREADS) leleka_verify_qsa_index_rows(IndexRowsArgs a) {
__shared__ float values[D];
__shared__ float partials[32];
if (a.snapshot != 0) {
// verify_copy_from_mapped_kernel: 96 float4 (tail_snap <- the tail image)
if (threadIdx.x < 96) {
reinterpret_cast<float4*>(a.snapshot)[threadIdx.x] = reinterpret_cast<const float4*>(a.tail)[threadIdx.x];
}
__syncthreads(); // every read of the tail precedes the first row write
}
for (int row = 0; row < (int) a.rows; ++row) {
const int pos = reinterpret_cast<const int32_t*>(a.step)[row * 4];
if (pos < 0 || pos >= (int) a.max_cells) continue; // block uniform, as the early return of the Original
append_row(a, reinterpret_cast<const float*>(a.raw) + (std::size_t) row * D, pos, values, partials);
}
}
@@ -0,0 +1,294 @@
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: UNKNOWN
// Cuda compilation tools, release 13.2, V13.2.86
// Based on NVVM 22.0.0
//
.version 9.2
.target sm_120
.address_size 64
// .globl leleka_verify_qsa_index_rows
// _ZZ28leleka_verify_qsa_index_rowsE6values has been demoted
// _ZZ28leleka_verify_qsa_index_rowsE8partials has been demoted
.visible .entry leleka_verify_qsa_index_rows(
.param .align 8 .b8 leleka_verify_qsa_index_rows_param_0[120]
)
.maxntid 256
{
.reg .pred %p<40>;
.reg .b16 %rs<7>;
.reg .b32 %r<111>;
.reg .b64 %rd<43>;
// demoted variable
.shared .align 4 .b8 _ZZ28leleka_verify_qsa_index_rowsE6values[512];
// demoted variable
.shared .align 4 .b8 _ZZ28leleka_verify_qsa_index_rowsE8partials[128];
ld.param.v2.b32 {%r1, %r31}, [leleka_verify_qsa_index_rows_param_0+112];
ld.param.v2.b32 {%r29, %r30}, [leleka_verify_qsa_index_rows_param_0+104];
ld.param.v2.b32 {%r27, %r28}, [leleka_verify_qsa_index_rows_param_0+96];
ld.param.v2.b32 {%r25, %r26}, [leleka_verify_qsa_index_rows_param_0+88];
ld.param.b64 %rd10, [leleka_verify_qsa_index_rows_param_0+80];
ld.param.b64 %rd9, [leleka_verify_qsa_index_rows_param_0+72];
ld.param.b64 %rd7, [leleka_verify_qsa_index_rows_param_0+56];
ld.param.b64 %rd6, [leleka_verify_qsa_index_rows_param_0+48];
ld.param.b64 %rd18, [leleka_verify_qsa_index_rows_param_0+40];
ld.param.b64 %rd5, [leleka_verify_qsa_index_rows_param_0+32];
ld.param.b64 %rd4, [leleka_verify_qsa_index_rows_param_0+24];
ld.param.b64 %rd3, [leleka_verify_qsa_index_rows_param_0+16];
ld.param.b64 %rd2, [leleka_verify_qsa_index_rows_param_0+8];
ld.param.b64 %rd1, [leleka_verify_qsa_index_rows_param_0];
ld.param.b64 %rd8, [leleka_verify_qsa_index_rows_param_0+64];
setp.eq.b64 %p1, %rd8, 0;
@%p1 bra $L__BB0_4;
mov.u32 %r2, %tid.x;
setp.gt.u32 %p2, %r2, 95;
@%p2 bra $L__BB0_3;
cvta.to.global.u64 %rd19, %rd8;
mul.wide.u32 %rd20, %r2, 16;
add.s64 %rd21, %rd19, %rd20;
cvta.to.global.u64 %rd22, %rd3;
add.s64 %rd23, %rd22, %rd20;
ld.global.v2.b64 {%rd24, %rd25}, [%rd23];
st.global.v2.b64 [%rd21], {%rd24, %rd25};
$L__BB0_3:
bar.sync 0;
$L__BB0_4:
cvt.u32.u64 %r3, %rd9;
setp.lt.s32 %p3, %r3, 1;
@%p3 bra $L__BB0_42;
cvta.to.global.u64 %rd41, %rd2;
cvt.u32.u64 %r4, %rd10;
cvta.to.global.u64 %rd26, %rd1;
cvta.to.global.u64 %rd27, %rd3;
cvta.to.global.u64 %rd28, %rd6;
mov.u32 %r32, %tid.x;
cvt.u64.u32 %rd11, %r32;
mul.wide.u32 %rd29, %r32, 4;
add.s64 %rd42, %rd26, %rd29;
add.s64 %rd12, %rd27, %rd29;
and.b32 %r5, %r32, 31;
shr.u32 %r33, %r32, 3;
mov.b32 %r34, _ZZ28leleka_verify_qsa_index_rowsE8partials;
add.s32 %r6, %r34, %r33;
shl.b32 %r35, %r32, 2;
and.b32 %r36, %r35, 124;
add.s32 %r7, %r34, %r36;
add.s64 %rd13, %rd28, %rd29;
mov.b32 %r37, _ZZ28leleka_verify_qsa_index_rowsE6values;
add.s32 %r8, %r37, %r35;
cvta.to.global.u64 %rd14, %rd5;
cvta.to.global.u64 %rd30, %rd4;
cvt.u16.u32 %rs1, %r5;
mul.lo.s16 %rs2, %rs1, 86;
shr.u16 %rs3, %rs2, 8;
mul.lo.s16 %rs4, %rs3, 3;
sub.s16 %rs5, %rs1, %rs4;
cvt.u32.u16 %r38, %rs5;
and.b32 %r39, %r38, 255;
mul.wide.u32 %rd31, %r39, 4;
add.s64 %rd15, %rd7, %rd31;
cvt.rn.f32.u32 %r9, %r5;
sub.ftz.f32 %r10, %r9, %r28;
sub.ftz.f32 %r40, %r29, %r28;
max.ftz.f32 %r11, %r40, 0f3A83126F;
rcp.approx.ftz.f32 %r12, %r27;
add.s32 %r13, %r37, %r36;
add.s64 %rd16, %rd30, %rd29;
neg.s32 %r100, %r3;
lg2.approx.ftz.f32 %r77, %r26;
mul.ftz.f32 %r78, %r77, %r9;
ex2.approx.ftz.f32 %r79, %r78;
div.approx.ftz.f32 %r80, %r10, %r11;
lg2.approx.ftz.f32 %r88, %r12;
mul.ftz.f32 %r89, %r88, 0f3F317218;
fma.rn.ftz.f32 %r90, %r89, 0f3DCCCCCD, 0f3F800000;
mul.ftz.f32 %r20, %r1, %r90;
$L__BB0_6:
ld.global.b32 %r14, [%rd41];
setp.lt.s32 %p4, %r14, 0;
setp.ge.s32 %p5, %r14, %r4;
or.pred %p6, %p4, %p5;
@%p6 bra $L__BB0_41;
cvt.u32.u64 %r41, %rd11;
setp.gt.u32 %p7, %r41, 127;
and.b32 %r15, %r14, 3;
mov.b32 %r101, 0f00000000;
@%p7 bra $L__BB0_10;
ld.global.b32 %r42, [%rd42];
// begin inline asm
{ cvt.rn.f16.f32 %rs6, %r42;}
// end inline asm
// begin inline asm
{ cvt.f32.f16 %r101, %rs6;}
// end inline asm
setp.eq.b32 %p8, %r15, 3;
@%p8 bra $L__BB0_10;
mul.wide.u32 %rd32, %r15, 128;
shl.b64 %rd33, %rd32, 2;
add.s64 %rd34, %rd12, %rd33;
st.global.b32 [%rd34], %r101;
$L__BB0_10:
setp.ne.b32 %p9, %r14, 0;
setp.ne.b32 %p10, %r15, 3;
and.pred %p11, %p9, %p10;
@%p11 bra $L__BB0_41;
cvt.u32.u64 %r43, %rd11;
setp.gt.u32 %p12, %r43, 127;
mov.b32 %r104, 0f00000000;
@%p12 bra $L__BB0_18;
setp.eq.b32 %p13, %r14, 0;
mov.b32 %r102, %r101;
@%p13 bra $L__BB0_14;
ld.global.b32 %r102, [%rd12];
$L__BB0_14:
@%p9 bra $L__BB0_16;
add.rn.ftz.f32 %r48, %r102, %r101;
add.rn.ftz.f32 %r49, %r48, %r101;
add.rn.ftz.f32 %r103, %r49, %r101;
bra.uni $L__BB0_17;
$L__BB0_16:
ld.global.b32 %r44, [%rd12+512];
add.rn.ftz.f32 %r45, %r102, %r44;
ld.global.b32 %r46, [%rd12+1024];
add.rn.ftz.f32 %r47, %r45, %r46;
add.rn.ftz.f32 %r103, %r47, %r101;
$L__BB0_17:
fma.rn.ftz.f32 %r104, %r103, 0f3E800000, 0f00000000;
$L__BB0_18:
setp.ne.b32 %p14, %r5, 0;
setp.lt.u32 %p15, %r43, 128;
fma.rn.ftz.f32 %r50, %r104, %r104, 0f00000000;
selp.f32 %r51, %r50, 0f00000000, %p15;
shfl.sync.bfly.b32 %r52|%p16, %r51, 16, 31, -1;
add.ftz.f32 %r53, %r51, %r52;
shfl.sync.bfly.b32 %r54|%p17, %r53, 8, 31, -1;
add.ftz.f32 %r55, %r53, %r54;
shfl.sync.bfly.b32 %r56|%p18, %r55, 4, 31, -1;
add.ftz.f32 %r57, %r55, %r56;
shfl.sync.bfly.b32 %r58|%p19, %r57, 2, 31, -1;
add.ftz.f32 %r59, %r57, %r58;
shfl.sync.bfly.b32 %r60|%p20, %r59, 1, 31, -1;
add.ftz.f32 %r16, %r59, %r60;
@%p14 bra $L__BB0_20;
st.shared.b32 [%r6], %r16;
$L__BB0_20:
setp.gt.u32 %p21, %r5, 7;
bar.sync 0;
mov.b32 %r105, 0f00000000;
@%p21 bra $L__BB0_22;
ld.shared.b32 %r105, [%r7];
$L__BB0_22:
shfl.sync.bfly.b32 %r61|%p22, %r105, 16, 31, -1;
add.ftz.f32 %r62, %r105, %r61;
shfl.sync.bfly.b32 %r63|%p23, %r62, 8, 31, -1;
add.ftz.f32 %r64, %r62, %r63;
shfl.sync.bfly.b32 %r65|%p24, %r64, 4, 31, -1;
add.ftz.f32 %r66, %r64, %r65;
shfl.sync.bfly.b32 %r67|%p25, %r66, 2, 31, -1;
add.ftz.f32 %r68, %r66, %r67;
shfl.sync.bfly.b32 %r69|%p26, %r68, 1, 31, -1;
add.ftz.f32 %r70, %r68, %r69;
mov.b32 %r71, 0f43000000;
div.approx.ftz.f32 %r17, %r70, %r71;
@%p12 bra $L__BB0_24;
add.ftz.f32 %r72, %r25, %r17;
rsqrt.approx.ftz.f32 %r73, %r72;
mul.ftz.f32 %r74, %r104, %r73;
ld.global.b32 %r75, [%rd13];
mul.ftz.f32 %r76, %r74, %r75;
st.shared.b32 [%r8], %r76;
$L__BB0_24:
setp.gt.u32 %p27, %r43, 127;
bar.sync 0;
@%p27 bra $L__BB0_40;
setp.gt.u32 %p28, %r43, 63;
and.b32 %r18, %r14, 2147483644;
ld.shared.b32 %r110, [%r8];
@%p28 bra $L__BB0_35;
setp.eq.b32 %p29, %r14, 0;
mov.b32 %r107, 0f00000000;
@%p29 bra $L__BB0_30;
setp.eq.b64 %p30, %rd7, 0;
mov.b32 %r106, %r18;
@%p30 bra $L__BB0_29;
mul.wide.u32 %rd36, %r18, 12;
add.s64 %rd35, %rd15, %rd36;
// begin inline asm
ld.global.nc.s32 %r106, [%rd35];
// end inline asm
$L__BB0_29:
cvt.rn.f32.s32 %r107, %r106;
$L__BB0_30:
setp.eq.ftz.f32 %p31, %r30, 0f00000000;
mul.ftz.f32 %r19, %r107, %r79;
mul.ftz.f32 %r108, %r27, %r19;
mov.b32 %r109, %r1;
@%p31 bra $L__BB0_32;
setp.lt.ftz.f32 %p32, %r80, 0f00000000;
setp.gt.ftz.f32 %p33, %r80, 0f3F800000;
selp.f32 %r81, 0f3F800000, %r80, %p33;
mov.b32 %r82, 0f3F800000;
sub.ftz.f32 %r83, %r82, %r81;
selp.f32 %r84, 0f3F800000, %r83, %p32;
mul.ftz.f32 %r85, %r30, %r84;
sub.ftz.f32 %r86, %r82, %r85;
mul.ftz.f32 %r87, %r108, %r86;
fma.rn.ftz.f32 %r108, %r19, %r85, %r87;
mov.b32 %r109, %r20;
$L__BB0_32:
cvt.u32.u64 %r91, %rd11;
setp.gt.u32 %p34, %r91, 31;
cos.approx.ftz.f32 %r92, %r108;
mul.ftz.f32 %r21, %r109, %r92;
sin.approx.ftz.f32 %r93, %r108;
mul.ftz.f32 %r22, %r109, %r93;
ld.shared.b32 %r23, [%r13];
ld.shared.b32 %r24, [%r13+128];
@%p34 bra $L__BB0_34;
mul.ftz.f32 %r95, %r21, %r23;
mul.ftz.f32 %r96, %r22, %r24;
sub.ftz.f32 %r110, %r95, %r96;
bra.uni $L__BB0_35;
$L__BB0_34:
mul.ftz.f32 %r94, %r21, %r24;
fma.rn.ftz.f32 %r110, %r23, %r22, %r94;
$L__BB0_35:
shr.u32 %r97, %r14, 2;
mul.wide.u32 %rd37, %r97, 128;
add.s64 %rd38, %rd37, %rd11;
shl.b64 %rd39, %rd38, 2;
add.s64 %rd17, %rd14, %rd39;
st.global.b32 [%rd17], %r110;
setp.ne.b32 %p35, %r14, 0;
@%p35 bra $L__BB0_37;
st.global.b32 [%rd16], %r110;
bra.uni $L__BB0_38;
$L__BB0_37:
ld.global.b32 %r98, [%rd16];
st.global.b32 [%rd17+512], %r98;
$L__BB0_38:
cvt.u32.u64 %r99, %rd11;
setp.eq.b32 %p36, %r14, 0;
setp.ne.b32 %p37, %r99, 0;
or.pred %p38, %p37, %p36;
@%p38 bra $L__BB0_40;
cvta.to.global.u64 %rd40, %rd18;
st.global.b32 [%rd40], %r18;
$L__BB0_40:
bar.sync 0;
$L__BB0_41:
add.s64 %rd42, %rd42, 512;
add.s32 %r100, %r100, 1;
setp.ne.b32 %p39, %r100, 0;
add.s64 %rd41, %rd41, 16;
@%p39 bra $L__BB0_6;
$L__BB0_42:
ret;
}
@@ -0,0 +1,95 @@
// verify-qsa-fused-prelude: the K/V half of the QSA prelude of the verify window graph, ONE launch per layer
// (docs/experiments/verify-qsa-fused-prelude.md).
//
// The window graph records, per QSA layer and window row, one `mtp_original_append` launch (mtp_original_kv.cu, the
// literal Original `kv_append_q8_kernel`): grid (kv_heads, head_dim / 64, 2), 64 threads, one 64-value group of K
// (z = 0) or V (z = 1) of one head. Rows do not depend on each other (every row writes its own cell of the pools: its
// own codes and its own scales), so the n launches are one launch with the rows along the grid. This is the Original
// own multi-token form (`kv_append_q8_kernel<true>`, S26 STRATA_LFUSE: token j reads step + j * step_stride and its
// K/V rows at kcur / vcur + j * cur_stride).
//
// One CTA of 256 threads is one (row, K or V, head): its four 64-thread quarters are four consecutive 64-value groups,
// so the group of 64 values, the two-warp maximum (a shuffle reduction in each warp, then the maximum of the two warp
// values; fmaxf is exact, so any association gives the same bits), the f16 scale, the code and the stores are the
// operations of the Original kernel on the same 64 values. head_dim / 64 may be any count: a CTA loops over the groups
// four at a time.
//
// Compile: PRECISE math, nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false, like mtp_original_kv.cu (the
// Original builds kv_q8.cu with default flags): `amax / 127.0f` and `x / sf` are IEEE divisions.
//
// PTX built with nvcc 13.2.86 (server rnr5090, compile only) and sealed with scripts/gpu-bringup (extra-seal-plan.json,
// group verify-qsa-prelude, SHA-256 pin in original_verify_window_qsa/fused_prelude.rs).
#include "strata/kernels/f16_bits.hpp"
#include "strata/kernels/kv_stream.hpp"
#include <cuda_runtime.h>
using namespace strata::kernels;
constexpr int KV_GROUP = 64;
constexpr int THREADS = 256;
constexpr int QUARTERS = THREADS / KV_GROUP;
// by-value kernel parameter: 12 addresses, then six 32-bit integers (three words)
struct KvRowsArgs {
uint64_t k_q, v_q, k_scale, v_scale; // resident pools (k_q is never null here: the keyless arm is refused)
uint64_t table; // int32 page table
uint64_t host_k_q, host_v_q, host_k_scale, host_v_scale; // host copy (identity layout), each may be 0
uint64_t step; // int32 [rows][step_stride]: word kStepPos is the position
uint64_t kcur, vcur; // float [rows][cur_stride]: the K and V rows of the window
int32_t kv_heads, head_dim, page_size, step_stride;
int32_t cur_stride, rows;
};
// One group of 64 values of one head of K or V of one row: the body of kv_append_q8_kernel.
__device__ __forceinline__ void append_group(const KvRowsArgs& a, long long pos, bool is_v, int h, int g,
float x, float amax) {
const int t = threadIdx.x & (KV_GROUP - 1);
const int groups = a.head_dim / KV_GROUP;
const uint16_t sbits = f16_from_f32(amax / 127.0f);
const float sf = f32_from_f16(sbits); // quantize against the STORED scale
int q = 0;
if (sf > 0.0f) {
q = __float2int_rn(x / sf);
q = q < -127 ? -127 : (q > 127 ? 127 : q);
}
// KV streaming: the host copy (identity layout) always, the VRAM page only if the block is resident
const long long page = (long long) reinterpret_cast<const int32_t*>(a.table)[pos / a.page_size];
if (page >= 0) {
const long long row = (page * a.kv_heads + h) * a.page_size + (pos % a.page_size);
int8_t* codes = reinterpret_cast<int8_t*>(is_v ? a.v_q : a.k_q);
uint16_t* scales = reinterpret_cast<uint16_t*>(is_v ? a.v_scale : a.k_scale);
codes[row * a.head_dim + g * KV_GROUP + t] = (int8_t) q;
if (t == 0) scales[row * groups + g] = sbits;
}
const uint64_t host_codes = is_v ? a.host_v_q : a.host_k_q;
if (host_codes != 0) {
const long long row = ((pos / a.page_size) * a.kv_heads + h) * a.page_size + (pos % a.page_size);
reinterpret_cast<int8_t*>(host_codes)[row * a.head_dim + g * KV_GROUP + t] = (int8_t) q;
if (t == 0) reinterpret_cast<uint16_t*>(is_v ? a.host_v_scale : a.host_k_scale)[row * groups + g] = sbits;
}
}
// grid (rows * 2 * kv_heads), block (256): block b = ((row * 2 + is_v) * kv_heads + head)
extern "C" __global__ void __launch_bounds__(THREADS) leleka_verify_qsa_kv_rows(KvRowsArgs a) {
__shared__ float warp_max[THREADS / 32];
const int h = blockIdx.x % a.kv_heads;
const bool is_v = ((blockIdx.x / a.kv_heads) & 1) != 0;
const int j = blockIdx.x / (2 * a.kv_heads);
const long long pos = (long long) __ldg(reinterpret_cast<const int32_t*>(a.step) + (size_t) j * a.step_stride + kStepPos);
const float* cur = reinterpret_cast<const float*>(is_v ? a.vcur : a.kcur) + (size_t) j * a.cur_stride;
const int quarter = threadIdx.x / KV_GROUP, t = threadIdx.x % KV_GROUP;
const int groups = a.head_dim / KV_GROUP;
for (int g0 = 0; g0 < groups; g0 += QUARTERS) {
const int g = g0 + quarter;
const bool live = g < groups;
const float x = live ? cur[h * a.head_dim + g * KV_GROUP + t] : 0.0f;
// max |x| over the 64 values: two warps, then combine through shared memory in a fixed order
float m = fabsf(x);
for (int o = 16; o > 0; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o));
if ((threadIdx.x & 31) == 0) warp_max[threadIdx.x >> 5] = m;
__syncthreads();
const float amax = fmaxf(warp_max[2 * quarter], warp_max[2 * quarter + 1]);
if (live) append_group(a, pos, is_v, h, g, x, amax);
__syncthreads(); // warp_max is reused by the next group quartet
}
}
@@ -0,0 +1,341 @@
//
// Generated by NVIDIA NVVM Compiler
//
// Compiler Build ID: UNKNOWN
// Cuda compilation tools, release 13.2, V13.2.86
// Based on NVVM 22.0.0
//
.version 9.2
.target sm_120
.address_size 64
// .globl leleka_verify_qsa_kv_rows
// _ZZ25leleka_verify_qsa_kv_rowsE8warp_max has been demoted
.visible .entry leleka_verify_qsa_kv_rows(
.param .align 8 .b8 leleka_verify_qsa_kv_rows_param_0[120]
)
.maxntid 256
{
.reg .pred %p<39>;
.reg .b16 %rs<14>;
.reg .b32 %r<119>;
.reg .b64 %rd<66>;
// demoted variable
.shared .align 4 .b8 _ZZ25leleka_verify_qsa_kv_rowsE8warp_max[32];
ld.param.b64 %rd25, [leleka_verify_qsa_kv_rows_param_0+64];
ld.param.b64 %rd24, [leleka_verify_qsa_kv_rows_param_0+56];
ld.param.b64 %rd23, [leleka_verify_qsa_kv_rows_param_0+48];
ld.param.b64 %rd22, [leleka_verify_qsa_kv_rows_param_0+40];
ld.param.b64 %rd21, [leleka_verify_qsa_kv_rows_param_0+32];
ld.param.b64 %rd20, [leleka_verify_qsa_kv_rows_param_0+24];
ld.param.b64 %rd19, [leleka_verify_qsa_kv_rows_param_0+16];
ld.param.b64 %rd18, [leleka_verify_qsa_kv_rows_param_0+8];
ld.param.b64 %rd17, [leleka_verify_qsa_kv_rows_param_0];
ld.param.v2.b32 {%r29, %r30}, [leleka_verify_qsa_kv_rows_param_0+112];
ld.param.b64 %rd28, [leleka_verify_qsa_kv_rows_param_0+88];
ld.param.b64 %rd27, [leleka_verify_qsa_kv_rows_param_0+80];
ld.param.b64 %rd26, [leleka_verify_qsa_kv_rows_param_0+72];
ld.param.v2.b32 {%r27, %r28}, [leleka_verify_qsa_kv_rows_param_0+104];
ld.param.v2.b32 {%r25, %r26}, [leleka_verify_qsa_kv_rows_param_0+96];
mov.u32 %r32, %ctaid.x;
div.u32 %r33, %r32, %r25;
mul.lo.s32 %r34, %r33, %r25;
sub.s32 %r1, %r32, %r34;
shl.b32 %r35, %r25, 1;
div.u32 %r36, %r32, %r35;
cvt.u64.u32 %rd30, %r36;
cvt.s64.s32 %rd31, %r28;
mul.lo.s64 %rd32, %rd30, %rd31;
shl.b64 %rd33, %rd32, 2;
add.s64 %rd29, %rd26, %rd33;
// begin inline asm
ld.global.nc.s32 %r31, [%rd29];
// end inline asm
cvt.s64.s32 %rd1, %r31;
and.b32 %r2, %r33, 1;
setp.eq.b32 %p1, %r2, 0;
selp.b64 %rd2, %rd27, %rd28, %p1;
cvt.s64.s32 %rd34, %r29;
mul.lo.s64 %rd3, %rd30, %rd34;
mov.u32 %r3, %tid.x;
shr.u32 %r4, %r3, 6;
and.b32 %r5, %r3, 63;
shr.s32 %r37, %r26, 31;
shr.u32 %r38, %r37, 26;
add.s32 %r39, %r26, %r38;
shr.s32 %r6, %r39, 6;
setp.lt.s32 %p2, %r26, 64;
@%p2 bra $L__BB0_48;
mad.lo.s32 %r7, %r1, %r26, %r5;
and.b32 %r8, %r3, 31;
shr.u32 %r40, %r3, 3;
mov.b32 %r41, _ZZ25leleka_verify_qsa_kv_rowsE8warp_max;
add.s32 %r9, %r41, %r40;
shl.b32 %r42, %r4, 3;
add.s32 %r10, %r41, %r42;
cvt.s64.s32 %rd4, %r27;
cvt.s64.s32 %rd5, %r25;
cvt.u64.u32 %rd6, %r1;
selp.b64 %rd7, %rd17, %rd18, %p1;
selp.b64 %rd8, %rd19, %rd20, %p1;
cvt.u64.u32 %rd9, %r26;
cvt.u64.u32 %rd10, %r6;
selp.b64 %rd11, %rd22, %rd23, %p1;
selp.b64 %rd12, %rd24, %rd25, %p1;
mov.b32 %r112, 0;
$L__BB0_2:
add.s32 %r11, %r112, %r4;
setp.ge.s32 %p3, %r11, %r6;
mov.b32 %r113, 0f00000000;
@%p3 bra $L__BB0_4;
shl.b32 %r43, %r11, 6;
add.s32 %r44, %r7, %r43;
cvt.s64.s32 %rd35, %r44;
add.s64 %rd36, %rd3, %rd35;
shl.b64 %rd37, %rd36, 2;
add.s64 %rd38, %rd2, %rd37;
ld.b32 %r113, [%rd38];
$L__BB0_4:
setp.ne.b32 %p4, %r8, 0;
abs.f32 %r45, %r113;
shfl.sync.bfly.b32 %r46|%p5, %r45, 16, 31, -1;
max.f32 %r47, %r45, %r46;
shfl.sync.bfly.b32 %r48|%p6, %r47, 8, 31, -1;
max.f32 %r49, %r47, %r48;
shfl.sync.bfly.b32 %r50|%p7, %r49, 4, 31, -1;
max.f32 %r51, %r49, %r50;
shfl.sync.bfly.b32 %r52|%p8, %r51, 2, 31, -1;
max.f32 %r53, %r51, %r52;
shfl.sync.bfly.b32 %r54|%p9, %r53, 1, 31, -1;
max.f32 %r12, %r53, %r54;
@%p4 bra $L__BB0_6;
st.shared.b32 [%r9], %r12;
$L__BB0_6:
bar.sync 0;
@%p3 bra $L__BB0_47;
ld.shared.b32 %r55, [%r10];
ld.shared.b32 %r56, [%r10+4];
max.f32 %r57, %r55, %r56;
div.rn.f32 %r13, %r57, 0f42FE0000;
shr.u32 %r58, %r13, 16;
and.b32 %r14, %r58, 32768;
shr.u32 %r59, %r13, 23;
and.b32 %r15, %r59, 255;
and.b32 %r16, %r13, 8388607;
setp.ne.b32 %p10, %r15, 255;
@%p10 bra $L__BB0_9;
setp.eq.b32 %p21, %r16, 0;
selp.b32 %r76, 0, 512, %p21;
or.b32 %r77, %r76, %r14;
cvt.u16.u32 %rs6, %r77;
or.b16 %rs12, %rs6, 31744;
bra.uni $L__BB0_18;
$L__BB0_9:
setp.lt.u32 %p11, %r15, 143;
@%p11 bra $L__BB0_11;
cvt.u16.u32 %rs5, %r14;
or.b16 %rs12, %rs5, 31744;
bra.uni $L__BB0_18;
$L__BB0_11:
setp.gt.u32 %p12, %r15, 112;
@%p12 bra $L__BB0_17;
setp.gt.u32 %p16, %r15, 101;
@%p16 bra $L__BB0_14;
cvt.u16.u32 %rs12, %r14;
bra.uni $L__BB0_18;
$L__BB0_14:
or.b32 %r67, %r16, 8388608;
sub.s32 %r68, 126, %r15;
shr.u32 %r17, %r67, %r68;
mov.b32 %r69, -1;
shl.b32 %r70, %r69, %r68;
not.b32 %r71, %r70;
and.b32 %r18, %r67, %r71;
sub.s32 %r72, 125, %r15;
mov.b32 %r114, 1;
shl.b32 %r19, %r114, %r72;
setp.gt.u32 %p17, %r18, %r19;
@%p17 bra $L__BB0_16;
setp.eq.b32 %p18, %r18, %r19;
and.b32 %r73, %r17, 1;
setp.ne.b32 %p19, %r73, 0;
and.pred %p20, %p18, %p19;
selp.b32 %r114, 1, 0, %p20;
$L__BB0_16:
add.s32 %r74, %r114, %r17;
add.s32 %r75, %r74, %r14;
cvt.u16.u32 %rs12, %r75;
bra.uni $L__BB0_18;
$L__BB0_17:
shl.b32 %r60, %r15, 10;
shr.u32 %r61, %r16, 13;
or.b32 %r62, %r60, %r61;
add.s32 %r63, %r62, 16384;
or.b32 %r64, %r63, %r14;
cvt.u16.u32 %rs3, %r64;
and.b32 %r65, %r13, 8191;
setp.gt.u32 %p13, %r65, 4096;
and.b32 %r66, %r13, 16383;
setp.eq.b32 %p14, %r66, 12288;
or.pred %p15, %p13, %p14;
selp.b16 %rs4, 1, 0, %p15;
add.s16 %rs12, %rs3, %rs4;
$L__BB0_18:
cvt.u32.u16 %r78, %rs12;
shl.b32 %r79, %r78, 16;
and.b32 %r118, %r79, -2147483648;
shr.u16 %rs7, %rs12, 10;
and.b16 %rs1, %rs7, 31;
and.b16 %rs2, %rs12, 1023;
cvt.u32.u16 %r20, %rs2;
setp.eq.b16 %p22, %rs1, 31;
@%p22 bra $L__BB0_28;
setp.ne.b16 %p23, %rs1, 0;
@%p23 bra $L__BB0_29;
setp.eq.b16 %p24, %rs2, 0;
@%p24 bra $L__BB0_30;
clz.b32 %r82, %r20;
xor.b32 %r83, %r82, 31;
sub.s32 %r84, 9, %r83;
sub.s32 %r21, 10, %r83;
shl.b32 %r22, %r20, %r84;
and.b32 %r23, %r21, 3;
setp.gt.u32 %p25, %r83, 6;
mov.b32 %r116, 0;
@%p25 bra $L__BB0_25;
cvt.u16.u32 %rs8, %r21;
shr.u16 %rs9, %rs8, 2;
and.b16 %rs10, %rs9, 3;
mul.wide.u16 %r116, %rs10, 4;
neg.s32 %r115, %r116;
$L__BB0_23:
add.s32 %r115, %r115, 4;
setp.ne.b32 %p26, %r115, 0;
@%p26 bra $L__BB0_23;
setp.eq.b32 %p27, %r23, 0;
mov.b32 %r117, %r116;
@%p27 bra $L__BB0_27;
$L__BB0_25:
add.s32 %r117, %r116, 1;
setp.eq.b32 %p28, %r23, 1;
@%p28 bra $L__BB0_27;
setp.eq.b32 %p29, %r23, 2;
selp.b32 %r85, 2, 3, %p29;
add.s32 %r117, %r116, %r85;
$L__BB0_27:
shl.b32 %r86, %r117, 23;
shl.b32 %r87, %r22, 14;
and.b32 %r88, %r87, 8372224;
sub.s32 %r89, %r88, %r86;
add.s32 %r90, %r89, 947912704;
or.b32 %r118, %r90, %r118;
bra.uni $L__BB0_30;
$L__BB0_28:
shl.b32 %r80, %r20, 13;
add.s32 %r81, %r118, %r80;
add.s32 %r118, %r81, 2139095040;
bra.uni $L__BB0_30;
$L__BB0_29:
add.s16 %rs11, %rs1, 112;
cvt.u32.u16 %r91, %rs11;
shl.b32 %r92, %r91, 23;
shl.b32 %r93, %r20, 13;
or.b32 %r94, %r92, %r93;
add.s32 %r118, %r94, %r118;
$L__BB0_30:
setp.leu.f32 %p30, %r118, 0f00000000;
mov.b16 %rs13, 0;
@%p30 bra $L__BB0_32;
div.rn.f32 %r95, %r113, %r118;
cvt.rni.s32.f32 %r96, %r95;
max.s32 %r97, %r96, -127;
min.s32 %r98, %r97, 127;
cvt.u16.u32 %rs13, %r98;
$L__BB0_32:
or.b64 %rd39, %rd1, %rd4;
and.b64 %rd40, %rd39, -4294967296;
setp.ne.b64 %p31, %rd40, 0;
@%p31 bra $L__BB0_34;
cvt.u32.u64 %r99, %rd4;
cvt.u32.u64 %r100, %rd1;
div.u32 %r101, %r100, %r99;
cvt.u64.u32 %rd63, %r101;
bra.uni $L__BB0_35;
$L__BB0_34:
div.s64 %rd63, %rd1, %rd4;
$L__BB0_35:
cvta.to.global.u64 %rd41, %rd21;
shl.b64 %rd42, %rd63, 2;
add.s64 %rd43, %rd41, %rd42;
ld.global.b32 %r24, [%rd43];
setp.lt.s32 %p32, %r24, 0;
@%p32 bra $L__BB0_41;
cvt.u64.u32 %rd44, %r24;
mad.lo.s64 %rd13, %rd44, %rd5, %rd6;
or.b64 %rd45, %rd1, %rd4;
and.b64 %rd46, %rd45, -4294967296;
setp.ne.b64 %p33, %rd46, 0;
@%p33 bra $L__BB0_38;
cvt.u32.u64 %r102, %rd4;
cvt.u32.u64 %r103, %rd1;
rem.u32 %r104, %r103, %r102;
cvt.u64.u32 %rd64, %r104;
bra.uni $L__BB0_39;
$L__BB0_38:
rem.s64 %rd64, %rd1, %rd4;
$L__BB0_39:
setp.ne.b32 %p34, %r5, 0;
mad.lo.s64 %rd14, %rd13, %rd4, %rd64;
shl.b32 %r105, %r11, 6;
or.b32 %r106, %r105, %r5;
cvt.u64.u32 %rd47, %r106;
mad.lo.s64 %rd48, %rd14, %rd9, %rd47;
add.s64 %rd49, %rd7, %rd48;
st.b8 [%rd49], %rs13;
@%p34 bra $L__BB0_41;
cvt.u64.u32 %rd50, %r11;
mad.lo.s64 %rd51, %rd14, %rd10, %rd50;
shl.b64 %rd52, %rd51, 1;
add.s64 %rd53, %rd8, %rd52;
st.b16 [%rd53], %rs12;
$L__BB0_41:
setp.eq.b64 %p35, %rd11, 0;
@%p35 bra $L__BB0_47;
mad.lo.s64 %rd15, %rd63, %rd5, %rd6;
or.b64 %rd54, %rd1, %rd4;
and.b64 %rd55, %rd54, -4294967296;
setp.ne.b64 %p36, %rd55, 0;
@%p36 bra $L__BB0_44;
cvt.u32.u64 %r107, %rd4;
cvt.u32.u64 %r108, %rd1;
rem.u32 %r109, %r108, %r107;
cvt.u64.u32 %rd65, %r109;
bra.uni $L__BB0_45;
$L__BB0_44:
rem.s64 %rd65, %rd1, %rd4;
$L__BB0_45:
setp.ne.b32 %p37, %r5, 0;
mad.lo.s64 %rd16, %rd15, %rd4, %rd65;
shl.b32 %r110, %r11, 6;
or.b32 %r111, %r110, %r5;
cvt.u64.u32 %rd56, %r111;
mad.lo.s64 %rd57, %rd16, %rd9, %rd56;
add.s64 %rd58, %rd11, %rd57;
st.b8 [%rd58], %rs13;
@%p37 bra $L__BB0_47;
cvt.u64.u32 %rd59, %r11;
mad.lo.s64 %rd60, %rd16, %rd10, %rd59;
shl.b64 %rd61, %rd60, 1;
add.s64 %rd62, %rd12, %rd61;
st.b16 [%rd62], %rs12;
$L__BB0_47:
bar.sync 0;
add.s32 %r112, %r112, 4;
setp.lt.s32 %p38, %r112, %r6;
@%p38 bra $L__BB0_2;
$L__BB0_48:
ret;
}
@@ -78,6 +78,14 @@ pub(crate) const DEFAULT_ON_GU_SWIGLU: bool = false;
pub(crate) const DEFAULT_ON_SIDE_MIXER: bool = false;
pub(crate) const DEFAULT_ON_SIDE_QSA: bool = false;
pub(crate) const DEFAULT_ON_SIDE_SHARED: bool = false;
/// ACCEPT_ON_DEVICE: the finite verdict of the head logits is decided in the verify graph and read from a mapped word
/// (vanilla's `logits_nonfinite_rows` flags), not by a scan launched, synchronised and copied back after the drain.
pub(crate) const DEFAULT_ON_ACCEPT_ON_DEVICE: bool = false;
/// The QSA prelude (K/V rows and indexer rows of a layer as one launch each, qsa/fused_prelude.rs).
pub(crate) const DEFAULT_ON_FUSED_QSA_PRELUDE: bool = false;
// claude/verify-gdn-fused-kernels (original_verify_window_gdn_fused.rs): both off until a paired A/B and identity
pub(crate) const DEFAULT_ON_FUSED_GDN: bool = false;
pub(crate) const DEFAULT_ON_GDN_AB_UNROLL: bool = false;
/// Which parts of the verify graph run on the two side streams: the GDN gates and gate projection, the QSA indexer and
/// query chains (upstream `STRATA_SIDE_MIXER=2`), and the shared expert beside the routed experts (upstream's shared
@@ -113,6 +121,15 @@ pub struct Sm120Switches {
pub side_qsa: bool,
/// The shared expert on a side stream, beside the routed experts.
pub side_shared: bool,
/// `LELEKA_SM120_ACCEPT_ON_DEVICE`: the finite verdict of the head logits in the verify graph.
pub accept_on_device: bool,
/// `LELEKA_SM120_FUSED_QSA_PRELUDE`: the K/V rows and the indexer rows of a QSA layer as one launch each.
pub fused_qsa_prelude: bool,
// ---- claude/verify-gdn-fused-kernels
/// `LELEKA_SM120_FUSED_GDN`: a GDN layer's conv, a/b gates and step as one launch (`sm120_gdn_fused.cu`).
pub fused_gdn: bool,
/// `LELEKA_SM120_GDN_AB_UNROLL`: upstream `STRATA_SMALL_UNR` bit 1, the unrolled a/b projection kernel.
pub gdn_ab_unroll: bool,
}
fn one(get: &impl Fn(&str) -> Option<String>, var: &str, default: bool) -> bool {
@@ -155,6 +172,10 @@ impl Sm120Switches {
side_mixer: switch("LELEKA_SM120_SIDE_MIXER", DEFAULT_ON_SIDE_MIXER),
side_qsa: switch("LELEKA_SM120_SIDE_QSA", DEFAULT_ON_SIDE_QSA),
side_shared: switch("LELEKA_SM120_SIDE_SHARED", DEFAULT_ON_SIDE_SHARED),
accept_on_device: switch("LELEKA_SM120_ACCEPT_ON_DEVICE", DEFAULT_ON_ACCEPT_ON_DEVICE),
fused_qsa_prelude: switch("LELEKA_SM120_FUSED_QSA_PRELUDE", DEFAULT_ON_FUSED_QSA_PRELUDE),
fused_gdn: switch("LELEKA_SM120_FUSED_GDN", DEFAULT_ON_FUSED_GDN),
gdn_ab_unroll: switch("LELEKA_SM120_GDN_AB_UNROLL", DEFAULT_ON_GDN_AB_UNROLL),
}
}
/// The side-stream parts these switches ask for.
@@ -169,6 +190,10 @@ impl Sm120Switches {
side_mixer: overridden(&OVERRIDE_SIDE_MIXER, s.side_mixer),
side_qsa: s.side_qsa,
side_shared: s.side_shared,
accept_on_device: s.accept_on_device,
fused_qsa_prelude: s.fused_qsa_prelude,
fused_gdn: s.fused_gdn,
gdn_ab_unroll: s.gdn_ab_unroll,
}
}
}
@@ -249,6 +274,36 @@ mod tests {
assert_eq!(both.union(gdn), SideBranches { gdn: true, qsa: true, shared_expert: true });
}
#[test]
fn accept_on_device_is_off_by_default_and_follows_its_own_variable() {
const VAR: &str = "LELEKA_SM120_ACCEPT_ON_DEVICE";
let accept = |major, minor, e| Sm120Switches::resolve(major, minor, e).accept_on_device;
assert!(!DEFAULT_ON_ACCEPT_ON_DEVICE);
assert!(!accept(12, 0, env(&[])));
assert!(accept(12, 0, env(&[(VAR, "1")])));
assert!(accept(12, 0, env(&[(VAR, "on")])));
assert!(!accept(12, 0, env(&[(VAR, "0")])));
// the master switch only turns the default set off; an explicit variable still wins, as for the others
assert!(accept(12, 0, env(&[("LELEKA_SM120_PERF", "0"), (VAR, "1")])));
// the kernels are in the common PTX, but the switch follows the rule of the others: below 12.x never taken
assert!(!accept(8, 6, env(&[(VAR, "1")])));
// it is not a side-stream part
assert!(!Sm120Switches::resolve(12, 0, env(&[(VAR, "1")])).side_branches().any());
}
#[test]
fn fused_qsa_prelude_is_off_by_default_and_follows_its_own_variable() {
let on = |maj, min, e| Sm120Switches::resolve(maj, min, e).fused_qsa_prelude;
assert_eq!(on(12, 0, env(&[])), DEFAULT_ON_FUSED_QSA_PRELUDE);
assert!(!DEFAULT_ON_FUSED_QSA_PRELUDE && !on(12, 0, env(&[])));
assert!(on(12, 0, env(&[("LELEKA_SM120_FUSED_QSA_PRELUDE", "1")])));
assert!(!on(8, 6, env(&[("LELEKA_SM120_FUSED_QSA_PRELUDE", "1")])));
assert!(!on(12, 0, env(&[("LELEKA_SM120_FUSED_QSA_PRELUDE", "0")])));
// no other switch follows it
let all = Sm120Switches::resolve(12, 0, env(&[("LELEKA_SM120_FUSED_QSA_PRELUDE", "1")]));
assert_eq!(Sm120Switches { fused_qsa_prelude: false, ..all }, Sm120Switches::default());
}
#[test]
fn the_gu_swiglu_asset_is_sealed_and_exports_every_entry() {
GU_SWIGLU.assert_sealed_and_fail_closed();
@@ -9,16 +9,16 @@ use crate::owner_loan::OwnerLoan;
use std::cell::RefCell;
/// Resolved Original analytic constants, and actual optional retained device
/// tables. Process policy is fixed before capture by the genuine model adapter.
#[derive(Clone, Copy)]
pub struct OriginalVerifyRope<'a, 'ctx> {
#[derive(Clone)]
pub struct OriginalVerifyRope<'ctx> {
pub theta_scale: f32,
pub freq_scale: f32,
pub corr_low: f32,
pub corr_high: f32,
pub ext_factor: f32,
pub magnitude: f32,
pub positions: Option<&'a DeviceBuffer<'ctx>>,
pub angles: Option<(&'a DeviceBuffer<'ctx>, &'a DeviceBuffer<'ctx>, usize)>,
pub positions: Option<DeviceRef<'ctx>>,
pub angles: Option<(DeviceRef<'ctx>, DeviceRef<'ctx>, usize)>,
}
/// Addresses of one QSA layer's fixed owners (see `OriginalVerifyQsaJournal::window_addresses`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
@@ -44,14 +44,14 @@ struct Live {
/// The verifier retains both Original QSA state owners. The index image alone
/// is insufficient: upstream `verify.cpp` appends the real K/V projections
/// before the indexer and resolves attention from that same K/V prefix.
pub struct OriginalVerifyQsaJournal<'a, 'ctx> {
pub struct OriginalVerifyQsaJournal<'ctx> {
context: &'ctx Context<'ctx>,
/// The owners; `None` while they are out on loan (`lend` / `take_back`).
indices: [RefCell<Option<OriginalQsaResidentIndex<'ctx>>>; 12],
mapped: [RefCell<Option<OriginalQsaMappedJournal<'ctx>>>; 12],
loan: RefCell<OwnerLoan<[verify_qsa_journal_loan::OwnerPrint; 12]>>,
gamma: [&'a DeviceBuffer<'ctx>; 12],
rope: OriginalVerifyRope<'a, 'ctx>,
gamma: [DeviceRef<'ctx>; 12],
rope: OriginalVerifyRope<'ctx>,
live: RefCell<Live>,
failed: Cell<bool>,
/// `set_window_snapshots`: the index state (12 x `WINDOW_STATE_BYTES`) and the PLE history image at the start of
@@ -74,5 +74,9 @@ mod verify_qsa_journal_loan;
pub use verify_qsa_journal_loan::OriginalQsaOwners;
#[path = "qsa_verification_commit/verify_qsa_journal_capture_commit.rs"]
mod verify_qsa_journal_capture_commit;
#[path = "qsa_verification_commit/verify_qsa_journal_index_image.rs"]
mod verify_qsa_journal_index_image;
#[path = "qsa_verification_commit/verify_qsa_journal_publish_discard.rs"]
mod verify_qsa_journal_publish_discard;
#[path = "qsa_verification_commit/verify_qsa_journal_rearm.rs"]
mod verify_qsa_journal_rearm;
@@ -42,10 +42,10 @@ fn image_clear(buffer: &DeviceBuffer<'_>, index: &OriginalQsaResidentIndex<'_>)
/// Every norm weight is a whole buffer that overlaps no index image.
fn check_gamma<'ctx>(
context: &'ctx Context<'ctx>,
gamma: &[&DeviceBuffer<'ctx>; 12],
gamma: &[DeviceRef<'ctx>; 12],
indices: &Indices<'ctx>,
) -> Result<()> {
for g in gamma.iter().copied() {
for g in gamma.iter() {
whole(context, g, 512)?;
for i in indices {
image_clear(g, i)?;
@@ -54,14 +54,14 @@ fn check_gamma<'ctx>(
Ok(())
}
/// The retained RoPE tables must not overlap any index image.
fn check_rope_clear(rope: &OriginalVerifyRope<'_, '_>, indices: &Indices<'_>) -> Result<()> {
fn check_rope_clear(rope: &OriginalVerifyRope<'_>, indices: &Indices<'_>) -> Result<()> {
for b in indices.iter().flat_map(|i| i.image.iter().flatten()) {
if let Some(p) = rope.positions {
if let Some(p) = &rope.positions {
if overlaps(p, b)? {
return Err(Error::OutputAliasesInput);
}
}
if let Some((cos, sin, _)) = rope.angles {
if let Some((cos, sin, _)) = &rope.angles {
if overlaps(cos, b)? || overlaps(sin, b)? {
return Err(Error::OutputAliasesInput);
}
@@ -85,13 +85,13 @@ pub(super) fn check_aligned<'ctx>(
}
Ok(())
}
impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
pub fn new(
context: &'ctx Context<'ctx>,
indices: [OriginalQsaResidentIndex<'ctx>; 12],
mapped: [OriginalQsaMappedJournal<'ctx>; 12],
gamma: [&'a DeviceBuffer<'ctx>; 12],
rope: OriginalVerifyRope<'a, 'ctx>,
gamma: [DeviceRef<'ctx>; 12],
rope: OriginalVerifyRope<'ctx>,
) -> Result<Rc<Self>> {
let end = indices[0].next_position();
check_aligned(context, &indices, &mapped, end)?;
@@ -151,7 +151,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
i.image[2].as_ref().ok_or(Error::ContextPoisoned)?,
i.image[3].as_ref().ok_or(Error::ContextPoisoned)?,
],
self.gamma[layer],
&self.gamma[layer],
)
}
pub(crate) fn with_committed_index<R>(
@@ -203,8 +203,8 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
consume(&mut m)
}
/// The resolved Original RoPE constants and optional retained tables (read only).
pub(crate) fn rope(&self) -> OriginalVerifyRope<'a, 'ctx> {
self.rope
pub(crate) fn rope(&self) -> &OriginalVerifyRope<'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.
@@ -272,7 +272,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
/// full provisional window and is restored by the accepted-prefix graph.
pub fn capture_tail_snapshot(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
) -> Result<()> {
@@ -3,14 +3,14 @@
#[allow(unused_imports)]
use super::*;
impl OriginalVerifyRope<'_, '_> {
impl OriginalVerifyRope<'_> {
pub(super) fn validate(&self, c: &Context<'_>, capacity: usize) -> Result<()> {
self.validate_scalars()?;
if let Some(p) = self.positions {
if let Some(p) = &self.positions {
whole(c, p, capacity * 3 * 4)?;
}
if let Some((cos, sin, n)) = self.angles {
validate_angles(c, (cos, sin), n)?;
if let Some((cos, sin, n)) = &self.angles {
validate_angles(c, (cos, sin), *n)?;
}
Ok(())
}
@@ -28,7 +28,7 @@ impl OriginalVerifyRope<'_, '_> {
}
}
/// The `n` retained cos and sin rows are whole, exactly sized and disjoint.
fn validate_angles(c: &Context<'_>, (cos, sin): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), n: usize) -> Result<()> {
fn validate_angles(c: &Context<'_>, (cos, sin): (&DeviceRef<'_>, &DeviceRef<'_>), n: usize) -> Result<()> {
if n == 0 || n > i32::MAX as usize {
return Err(Error::InvalidSize);
}
@@ -4,12 +4,12 @@ use super::original_verify_qsa_journal::{check_armed_window, image_addresses};
#[allow(unused_imports)]
use super::*;
impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
/// EXACT Original commit: restore prewindow tail, append all maxT raw rows
/// using accepted positions or -1. No batched-prompt rounding substitution.
pub fn capture_commit_layer(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
) -> Result<()> {
@@ -42,7 +42,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
/// and records nothing.
pub(crate) fn capture_commit_fused(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
) -> Result<bool> {
self.validate_context(journal.context())?;
@@ -77,14 +77,14 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
layers[1][layer] = dead;
layers[2][layer] = pooled;
layers[3][layer] = block_pos;
layers[4][layer] = whole(self.context, self.gamma[layer], 512)?;
layers[4][layer] = whole(self.context, &self.gamma[layer], 512)?;
}
Ok(layers)
}
/// The launch words: the layer tables, the journal addresses, the positions, the sizes and the packed RoPE
/// constants.
fn fused_words(&self, layers: &[[u64; 12]; 5], io: [u64; 3], (t, max_cells): (usize, usize)) -> Result<Vec<u64>> {
let r = self.rope;
let r = &self.rope;
let positions = self.positions_address()?;
let pack = |a: f32, b: f32| (a.to_bits() as u64) | ((b.to_bits() as u64) << 32);
let mut words: Vec<u64> = Vec::with_capacity(5 * 12 + 7 + 4);
@@ -105,6 +105,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
Ok(self
.rope
.positions
.as_ref()
.map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12))
.transpose()?
.unwrap_or(0))
@@ -113,7 +114,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
/// Caller records the tail snapshot before the first group's append.
pub fn capture_append_rows(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
layer: usize,
rows: std::ops::Range<usize>,
@@ -123,7 +124,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
/// Records the row appends of `target` (`commit`: the steps come from the accepted-position words).
pub(super) fn capture_append(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
capture: &mut OriginalCapture<'_, 'ctx>,
target: LayerRows,
commit: bool,
@@ -135,14 +136,14 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
return Err(Error::InvalidQwenShape);
}
let i = self.index(layer)?;
let gamma = whole(self.context, self.gamma[layer], 512)?;
let gamma = whole(self.context, &self.gamma[layer], 512)?;
let commands = self.append_commands(journal, &i, (layer * t, begin..end), (commit, gamma))?;
journal.submit_qsa(capture, commands)
}
/// One append command per row of the layer.
fn append_commands(
&self,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
i: &OriginalQsaResidentIndex<'ctx>,
(layer_rows, rows): (usize, std::ops::Range<usize>),
(commit, gamma): (bool, u64),
@@ -157,12 +158,12 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
}
/// The kernel variant (analytic or table RoPE) and the fixed addresses of every row append of a layer.
fn append_plan(&self, gamma: u64, is_commit: bool) -> Result<AppendPlan> {
let (name, cos, sin, max_pos) = match self.rope.angles {
let (name, cos, sin, max_pos) = match &self.rope.angles {
Some((c, s, n)) => (
"verify_qsa_append_table",
whole(self.context, c, n * 128)?,
whole(self.context, s, n * 128)?,
n as i32,
whole(self.context, c, *n * 128)?,
whole(self.context, s, *n * 128)?,
*n as i32,
),
None => ("verify_qsa_append_analytic", 0, 0, 0),
};
@@ -172,7 +173,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
fn append_command(
&self,
plan: &AppendPlan,
journal: &OriginalVerifyGdnJournal<'_, 'ctx>,
journal: &OriginalVerifyGdnJournal<'ctx>,
i: &OriginalQsaResidentIndex<'ctx>,
(raw_row, row): (usize, usize),
) -> Result<Command> {
@@ -188,7 +189,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
Command::new(plan.name, [1, 1, 1], [256, 1, 1], 0, self.append_args(plan, &addresses, max_cells))
}
fn append_args(&self, plan: &AppendPlan, a: &AppendAddresses, max_cells: i32) -> Vec<Arg> {
let r = self.rope;
let r = &self.rope;
vec![
Arg::Address(a.raw),
Arg::Address(a.step),
@@ -266,7 +267,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
}
/// The journal addresses of the fused commit: the raw index rows, the tail snapshots and the commit table. Their
/// layer and row strides are affine, so the far ends are checked against the first.
fn fused_io(journal: &OriginalVerifyGdnJournal<'_, '_>, t: usize) -> Result<[u64; 3]> {
fn fused_io(journal: &OriginalVerifyGdnJournal<'_>, t: usize) -> Result<[u64; 3]> {
let raw = journal.address("idx_raw_L", 0, 512)?;
let snap = journal.address("tail_snap", 0, 1536)?;
let commit = journal.address("commit", 0, (t + 2) * 4)?;
@@ -0,0 +1,47 @@
//! The retained index image of a layer as the fused indexer launch binds it (`LELEKA_SM120_FUSED_QSA_PRELUDE`).
use super::original_verify_qsa_journal::image_addresses;
#[allow(unused_imports)]
use super::*;
use crate::original_verify::qsa::fused_prelude::{IndexImage, IndexRope};
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
/// The addresses and RoPE constants every row append of `layer` binds (`append_plan` / `append_args`), or `None`
/// with retained angle tables: only the analytic variant (`verify_qsa_append_analytic`) is fused.
pub(crate) fn index_image(
&self,
journal: &OriginalVerifyGdnJournal<'ctx>,
layer: usize,
) -> Result<Option<IndexImage>> {
self.validate_context(journal.context())?;
if layer >= 12 {
return Err(Error::InvalidQwenShape);
}
if self.rope.angles.is_some() {
return Ok(None);
}
let i = self.index(layer)?;
let [tail, dead, pooled, block_pos] = image_addresses(&i)?;
let gamma = whole(self.context, &self.gamma[layer], 512)?;
let positions = self
.rope
.positions
.as_ref()
.map(|b| whole(self.context, b, crate::serving_context::geometry().cells() * 12))
.transpose()?
.unwrap_or(0);
Ok(Some(IndexImage { tail, dead, pooled, block_pos, gamma, positions, rope: index_rope(&self.rope) }))
}
}
/// The analytic RoPE constants every row append binds.
fn index_rope(r: &OriginalVerifyRope<'_>) -> IndexRope {
IndexRope {
theta_scale: r.theta_scale,
freq_scale: r.freq_scale,
corr_low: r.corr_low,
corr_high: r.corr_high,
ext_factor: r.ext_factor,
magnitude: r.magnitude,
}
}
@@ -44,7 +44,7 @@ pub(super) fn print_of(index: &OriginalQsaResidentIndex<'_>, kv: &OriginalQsaMap
}
/// The accessors every use of the owners goes through: an error while the owners are out.
impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
pub(super) fn index(&self, layer: usize) -> Result<Ref<'_, OriginalQsaResidentIndex<'ctx>>> {
let cell = self.indices.get(layer).ok_or(Error::InvalidQwenShape)?;
let held = cell.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
@@ -89,15 +89,7 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
/// Needs the journal idle: no window armed, every index published and standing where its journal does. The
/// fingerprint of the owners' addresses is kept for `take_back`. Any use of the journal fails until then.
pub fn lend(&self) -> Result<OriginalQsaOwners<'ctx>> {
self.validate_context(self.context)?;
let (position, armed) = {
let live = self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?;
(live.position, live.armed)
};
if armed {
return Err(Error::InvalidQwenShape);
}
self.check_idle_at(position)?;
self.require_idle()?;
let prints = self.prints()?;
let mut loan = self.loan.try_borrow_mut().map_err(|_| Error::InvalidQwenShape)?;
loan.lend(prints).map_err(|_| Error::InvalidQwenShape)?;
@@ -4,7 +4,7 @@ use super::original_verify_qsa_journal::check_armed_window;
#[allow(unused_imports)]
use super::*;
impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> {
impl<'ctx> OriginalVerifyQsaJournal<'ctx> {
// Called only by the closed graph bridge after its actual commit receipt.
pub(crate) fn complete_commit(&self, bank: &OriginalVerifyBank<'ctx>) -> Result<()> {
self.validate_context(self.context)?;
@@ -0,0 +1,19 @@
//! The re-arm precondition of the journal (ledger row Q7): between two requests the verifier may keep its recorded
//! graphs only if the QSA journal they hold is quiet.
#[allow(unused_imports)]
use super::*;
impl OriginalVerifyQsaJournal<'_> {
/// The journal is valid, no window is armed, and all twelve indices and mapped journals are idle, published and
/// standing at one position. The owners themselves are not touched; a prompt that ran over them in between has
/// only appended (the stack compares their addresses before it keeps the graphs).
pub(crate) fn require_idle(&self) -> Result<()> {
self.validate_context(self.context)?;
if self.live.try_borrow().map_err(|_| Error::InvalidQwenShape)?.armed {
return Err(Error::InvalidQwenShape);
}
let end = self.index(0)?.next_position();
self.check_idle_at(end)
}
}
+3 -2
View File
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
pub use device_ref::DeviceRef;
pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats};
pub use gdn_state_finite_guard::GdnStateFiniteGuard;
pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace};
@@ -226,8 +227,8 @@ pub use original_verify::{
MAX_PCIE_FETCHES as ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalVerifier, OriginalVerifyBank,
OriginalVerifyCanonicalGdn, OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGdnJournal,
OriginalVerifyGdnStage, OriginalVerifyGdnWeights, OriginalVerifyGeometry, OriginalVerifyGpuPlan,
OriginalVerifyGraphResources, OriginalVerifyLayout, OriginalVerifyPcieSource, OriginalVerifyResources,
OriginalVerifyRow, OriginalVerifySpan, OriginalVerifyWindow, OriginalVerifyWindowResult,
OriginalVerifyGraphResources, OriginalVerifyLayout, OriginalVerifyPcieSource, OriginalVerifyRearm,
OriginalVerifyResources, OriginalVerifyRow, OriginalVerifySpan, OriginalVerifyWindow, OriginalVerifyWindowResult,
OriginalVerifyWindowTokens,
};
// Live verifier release/diagnostic owner, profile report and completed-logit readout.
+310
View File
@@ -0,0 +1,310 @@
// verify window, GDN layers (docs/experiments/verify-gdn-fused-kernels.md). Two switches, one asset, sm_120 only.
//
// LELEKA_SM120_FUSED_GDN: the three kernels of a GDN layer of the Original-literal verify window
// verify_gdn_conv_l2_multi_kernel (grid 80 x T) -> verify_gdn_ab_multi_kernel / chain_gdn_ab_multi_kernel -> verify_gdn_step_norm_multi_kernel (48 blocks of 128 x 4)
// as ONE launch of the Original's step loop (`leleka_verify_gdn_fused_step`, 48 blocks of 128 x 4, one block per value head):
// * the conv prologue: the block convolves its head's q, k and v channels (three chunks of 128) for the NEW tokens [t_begin, t_end) into shared memory. The blocks of heads < 16 write q and k to `h`
// (one writer per q/k chunk), every block writes its v chunk, because the commit graph (draft_commit.cu) and a later split-window group read `h`;
// * the gates: with ab_x != 0 two warps (alpha row `head`, beta row `head`) compute gate and beta of the new tokens and write them to `gate` / `beta`; with ab_x == 0 (SIDE_MIXER: they came from
// side stream 0 and the stream joined before this launch) they are read;
// * the tokens before t_begin (a split window's earlier group) are read from h / gate / beta, as the Original reads them;
// * the step loop: the Original's loop with its loads redirected to shared memory. A replayed token (t < t_begin) needs the state update only: its o dot product and the output path
// never feed the state and are not computed (as draft_commit.cu).
// Every output word is computed by the same operations in the same order as by the kernels above. The arithmetic is written with the SAME plain C++ expressions as original_verify.cu
// and NOT with __fmul_rn / __fadd_rn intrinsics: ptxas contracts a plain `mul.f32` feeding an `add.f32` / `sub.f32` into one FFMA (checked with ptxas 13.2 on a two instruction kernel),
// the `.rn` forms it never contracts, so the loader's JIT of original_verify.ptx fuses `v - g * kv` (the sealed PTX has a plain mul.f32 + sub.f32) and an intrinsic version would not.
// The same expression shape gives the same PTX, hence the same contraction decisions (the PTX of every phase is compared with the sealed one by a unit test).
//
// LELEKA_SM120_GDN_AB_UNROLL: upstream STRATA_SMALL_UNR bit 1 (08b20b104, gdn_ab_body): the same a/b projection with the weight/activation loop at constant trip counts (ten passes of 32 lanes, a
// constant number of tokens for T <= 6), as its own entries `leleka_gdn_ab_unrolled_t*`. One warp a row (96 rows: alpha 0..47, beta 48..95), any block of 1 or 2 warps: the host launches
// 96 blocks of 32 threads (the shape of chain_gdn_ab_multi_kernel, which `LELEKA_CHAIN=all` records) or upstream's 48 blocks of 64.
//
// Compile: nvcc --ptx -O3 -arch=sm_120 -std=c++17 --fmad=true --ftz=false (the recipe of original_verify.cu / draft_commit.cu, which are not on the fast-math list).
#include <cuda_runtime.h>
#include <cstdint>
#include <cstddef>
constexpr int S = 128, RG = 4, RPG = S / RG;
constexpr int H_K = 16, H_V = 48, C_QKV = 10240, QK = S * H_K, VALUE_DIM = S * H_V;
constexpr int MAX_N = 8; // window rows (max_t)
constexpr int N_EMBD = 2560, AB_CHUNKS = N_EMBD / 8 / 32; // ten passes of 32 lanes over a weight row of 320 uint4
// by-value kernel argument: u64 words (the host side is FusedGdnStep::words in original_verify_window_gdn_fused.rs)
struct FusedGdnArgs {
uint64_t state; // canonical state of the layer, f32 [128][48][128] (read only: the window never writes it)
uint64_t hist; // canonical conv history of the layer, f32 [10240][3] (read only)
uint64_t qkv; // qkv rows of the layer, f32 [max_t][10240]
uint64_t conv_w; // conv weights, f32 [10240][4]
uint64_t h; // conv + L2 rows of the layer, f32 [max_t][10240] (written for the new tokens)
uint64_t gate; // f32 [max_t][48]
uint64_t beta; // f32 [max_t][48]
uint64_t z; // gate projection rows, f32 [max_t][6144]
uint64_t gamma; // norm weights, f32 [128]
uint64_t y; // output rows, f32 [max_t][6144]
uint64_t ab_x; // activation row of token t_begin, f32 [m][2560]; 0: gate and beta are already in `gate` / `beta`
uint64_t ab_alpha_w; // bf16 [48][2560]
uint64_t ab_beta_w; // bf16 [48][2560]
uint64_t ab_dt; // f32 [48]
uint64_t ab_a; // f32 [48]
uint64_t eps_bits; // the f32 epsilon, bits in the low word
uint64_t t_begin; // first new token
uint64_t t_end; // window rows so far (<= 8)
};
struct FusedShared {
float q[MAX_N][S], k[MAX_N][S], v[MAX_N][S]; // conv + L2 output (new tokens) or h rows (replayed tokens)
float red_kv[2][RG][S]; // double buffered by token parity: a replayed token has one barrier
float red_o[RG][S];
float l2[2][RG][S / 32]; // per conv group, double buffered by iteration
float wsum[S / 32];
float gate[MAX_N], beta[MAX_N];
};
// ---- the conv of verify_gdn_conv_l2_multi_kernel for channel c of token t (the Original's expression) ----
__device__ __forceinline__ float conv_silu(const FusedGdnArgs& a, int c, int t) {
const float* hist = reinterpret_cast<const float*>(a.hist);
const float* qkv = reinterpret_cast<const float*>(a.qkv);
const float* w = reinterpret_cast<const float*>(a.conv_w);
float win[3];
#pragma unroll
for (int j = 0; j < 3; ++j) {
const int src = t + j; // index into [hist(3) | x...]
win[j] = src < 3 ? hist[c * 3 + src] : qkv[(size_t) (src - 3) * C_QKV + c];
}
const float v0 = win[0], v1 = win[1], v2 = win[2], x = qkv[(size_t) t * C_QKV + c];
float sum = v0 * w[c * 4] + v1 * w[c * 4 + 1] + v2 * w[c * 4 + 2] + x * w[c * 4 + 3];
return sum / (1.0f + __expf(-sum));
}
// ---- one conv task: (kind 0 q, 1 k, 2 v) x (new token). The barrier count is the same for every thread of the block. ----
__device__ __forceinline__ void conv_new_tokens(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int col = threadIdx.x, rg = threadIdx.y, lane = col & 31, warp = col >> 5;
const int tb = (int) a.t_begin, tasks = 3 * ((int) a.t_end - tb), qh = head % H_K;
const float eps = __uint_as_float((uint32_t) a.eps_bits);
float* h = reinterpret_cast<float*>(a.h);
for (int it = 0; it * RG < tasks; ++it) {
const int task = it * RG + rg, kind = task % 3, t = tb + task / 3;
const bool valid = task < tasks, l2 = valid && kind < 2;
const int c = (kind == 0 ? qh : (kind == 1 ? H_K + qh : 2 * H_K + head)) * S + col;
float y = valid ? conv_silu(a, c, t) : 0.0f;
float sq = y * y; // the partials of a v task or an idle task are never read
for (int o = 16; o > 0; o >>= 1) sq += __shfl_xor_sync(0xffffffffu, sq, o);
if (lane == 0) sh.l2[it & 1][rg][warp] = sq;
__syncthreads();
if (l2) {
const float ss = sh.l2[it & 1][rg][0] + sh.l2[it & 1][rg][1] + sh.l2[it & 1][rg][2] + sh.l2[it & 1][rg][3];
y *= rsqrtf(ss + eps);
}
if (!valid) continue;
(kind == 0 ? sh.q : (kind == 1 ? sh.k : sh.v))[t][col] = y;
if (kind == 2 || head < H_K) h[(size_t) t * C_QKV + c] = y;
}
__syncthreads();
}
// ---- the tokens before t_begin come from h / gate / beta, as the Original reads them ----
__device__ __forceinline__ void load_replayed_tokens(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int tid = threadIdx.y * S + threadIdx.x, qh = head % H_K;
const float* h = reinterpret_cast<const float*>(a.h);
for (int t = 0; t < (int) a.t_begin; ++t) {
if (tid < S) {
sh.k[t][tid] = h[(size_t) t * C_QKV + QK + qh * S + tid];
sh.v[t][tid] = h[(size_t) t * C_QKV + 2 * QK + head * S + tid];
}
}
}
__device__ __forceinline__ void load_gate_rows(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int tid = threadIdx.y * S + threadIdx.x;
const int last = a.ab_x != 0 ? (int) a.t_begin : (int) a.t_end; // the rows from t_begin on are written by the ab warps
if (tid < last) {
sh.gate[tid] = reinterpret_cast<const float*>(a.gate)[(size_t) tid * H_V + head];
sh.beta[tid] = reinterpret_cast<const float*>(a.beta)[(size_t) tid * H_V + head];
}
}
// ---- the alpha / beta projection of one row (verify_gdn_ab_multi_kernel / chain_gdn_ab_multi_kernel arithmetic) ----
struct AbRow { uint4 w[AB_CHUNKS]; };
__device__ __forceinline__ AbRow ab_load_row(const uint16_t* wa, const uint16_t* wb, int head, bool is_beta, int lane) {
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) head * N_EMBD);
AbRow row;
#pragma unroll
for (int q = 0; q < AB_CHUNKS; ++q) row.w[q] = __ldg(w4 + lane + 32 * q);
return row;
}
// per-lane partial dot products: chunk ascending, token independent (the Original's order)
__device__ __forceinline__ void ab_partials(const AbRow& row, const float* x, int lane, int m, float (&acc)[MAX_N]) {
#pragma unroll
for (int t = 0; t < MAX_N; ++t) acc[t] = 0.0f;
#pragma unroll
for (int q = 0; q < AB_CHUNKS; ++q) {
const int j = lane + 32 * q;
#pragma unroll
for (int t = 0; t < MAX_N; ++t) {
if (t >= m) break;
const float* xt = x + (size_t) t * N_EMBD;
const float4 xa = *reinterpret_cast<const float4*>(xt + j * 8);
const float4 xb = *reinterpret_cast<const float4*>(xt + j * 8 + 4);
float v = acc[t];
v = fmaf(__uint_as_float(row.w[q].x << 16), xa.x, v); v = fmaf(__uint_as_float(row.w[q].x & 0xffff0000u), xa.y, v);
v = fmaf(__uint_as_float(row.w[q].y << 16), xa.z, v); v = fmaf(__uint_as_float(row.w[q].y & 0xffff0000u), xa.w, v);
v = fmaf(__uint_as_float(row.w[q].z << 16), xb.x, v); v = fmaf(__uint_as_float(row.w[q].z & 0xffff0000u), xb.y, v);
v = fmaf(__uint_as_float(row.w[q].w << 16), xb.z, v); v = fmaf(__uint_as_float(row.w[q].w & 0xffff0000u), xb.w, v);
acc[t] = v;
}
}
}
// the gate (alpha row) or beta (beta row) of a reduced dot product
__device__ __forceinline__ float ab_value(float a, bool is_beta, float dt, float ssm_a) {
if (is_beta) return 1.0f / (1.0f + __expf(-a));
const float v = a + dt;
const float sp = v > 20.0f ? v : log1pf(__expf(v));
return sp * ssm_a;
}
__device__ __forceinline__ void ab_new_tokens(const FusedGdnArgs& a, FusedShared& sh, int head, const AbRow& row) {
const int lane = threadIdx.x & 31, tb = (int) a.t_begin, m = (int) a.t_end - tb;
const bool is_beta = (threadIdx.x >> 5) == 1;
float acc[MAX_N];
ab_partials(row, reinterpret_cast<const float*>(a.ab_x), lane, m, acc);
#pragma unroll
for (int t = 0; t < MAX_N; ++t) {
if (t >= m) break;
float sum = acc[t];
for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
if (lane != 0) continue;
const float v = ab_value(sum, is_beta, reinterpret_cast<const float*>(a.ab_dt)[head], reinterpret_cast<const float*>(a.ab_a)[head]);
(is_beta ? sh.beta : sh.gate)[tb + t] = v;
(is_beta ? reinterpret_cast<float*>(a.beta) : reinterpret_cast<float*>(a.gate))[(size_t) (tb + t) * H_V + head] = v;
}
}
// ---- the Original's step loop (verify_gdn_step_norm_multi_kernel) over shared memory ----
__device__ __forceinline__ void output_token(const FusedGdnArgs& a, FusedShared& sh, int head, int t, float o) {
const int col = threadIdx.x, rg = threadIdx.y, tid = rg * S + col;
const float eps = __uint_as_float((uint32_t) a.eps_bits);
sh.red_o[rg][col] = o;
__syncthreads();
float oc = 0.0f, sq_part = 0.0f;
if (rg == 0) {
oc = (sh.red_o[0][col] + sh.red_o[1][col] + sh.red_o[2][col] + sh.red_o[3][col]) * rsqrtf((float) S);
sq_part = oc * oc;
for (int o2 = 16; o2 > 0; o2 >>= 1) sq_part += __shfl_xor_sync(0xffffffffu, sq_part, o2);
if ((tid & 31) == 0) sh.wsum[tid >> 5] = sq_part;
}
__syncthreads();
if (rg != 0) return;
const float ss = sh.wsum[0] + sh.wsum[1] + sh.wsum[2] + sh.wsum[3];
const float scale = rsqrtf(ss / (float) S + eps);
const float zz = reinterpret_cast<const float*>(a.z)[(size_t) t * VALUE_DIM + head * S + col];
reinterpret_cast<float*>(a.y)[(size_t) t * VALUE_DIM + head * S + col] =
oc * scale * reinterpret_cast<const float*>(a.gamma)[col] * (1.0f / (1.0f + __expf(-zz)));
}
__device__ __forceinline__ void recurrence(const FusedGdnArgs& a, FusedShared& sh, int head) {
const int col = threadIdx.x, rg = threadIdx.y, n = (int) a.t_end, tb = (int) a.t_begin;
const float* state = reinterpret_cast<const float*>(a.state) + ((size_t) (rg * RPG) * H_V + head) * S + col;
float s[RPG];
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = state[(size_t) r * H_V * S];
for (int t = 0; t < n; ++t) {
const float g = __expf(sh.gate[t]);
float kv = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) kv = fmaf(s[r], sh.k[t][rg * RPG + r], kv);
sh.red_kv[t & 1][rg][col] = kv;
__syncthreads();
const float kv_col = sh.red_kv[t & 1][0][col] + sh.red_kv[t & 1][1][col] + sh.red_kv[t & 1][2][col] + sh.red_kv[t & 1][3][col];
const float delta = (sh.v[t][col] - g * kv_col) * sh.beta[t];
if (t < tb) { // a replayed token: its state update is needed, its output is not
#pragma unroll
for (int r = 0; r < RPG; ++r) s[r] = fmaf(g, s[r], sh.k[t][rg * RPG + r] * delta);
continue;
}
float o = 0.0f;
#pragma unroll
for (int r = 0; r < RPG; ++r) {
s[r] = fmaf(g, s[r], sh.k[t][rg * RPG + r] * delta);
o = fmaf(s[r], sh.q[t][rg * RPG + r], o);
}
output_token(a, sh, head, t, o);
}
}
// grid (48), block (128, 4): one block per value head
extern "C" __global__ void __launch_bounds__(S * RG) leleka_verify_gdn_fused_step(FusedGdnArgs a) {
__shared__ FusedShared sh;
const int head = blockIdx.x, warp = (threadIdx.y * S + threadIdx.x) >> 5;
AbRow row;
if (a.ab_x != 0 && warp < 2) { // the weight loads are in flight while the whole block convolves
row = ab_load_row(reinterpret_cast<const uint16_t*>(a.ab_alpha_w), reinterpret_cast<const uint16_t*>(a.ab_beta_w), head, warp == 1,
threadIdx.x & 31);
}
load_replayed_tokens(a, sh, head);
load_gate_rows(a, sh, head);
conv_new_tokens(a, sh, head);
if (a.ab_x != 0 && warp < 2) ab_new_tokens(a, sh, head, row);
__syncthreads();
recurrence(a, sh, head);
}
// ------------------------------------------------------------------------------------------------------------------
// LELEKA_SM120_GDN_AB_UNROLL: upstream gdn_ab_body (STRATA_SMALL_UNR bit 1) on the Original's arguments.
// ------------------------------------------------------------------------------------------------------------------
template <int MAX_T, bool EXACT_T>
__device__ __forceinline__ void ab_unrolled_body(const float* __restrict__ x, const uint16_t* __restrict__ wa, const uint16_t* __restrict__ wb,
const float* __restrict__ dt, const float* __restrict__ ssm_a, float* __restrict__ gate,
float* __restrict__ beta, int h_v, int T) {
const int row = blockIdx.x * (blockDim.x >> 5) + (threadIdx.x >> 5), lane = threadIdx.x & 31;
if (row >= 2 * h_v) return;
const bool is_beta = row >= h_v;
const int r = is_beta ? row - h_v : row;
const uint4* w4 = reinterpret_cast<const uint4*>((is_beta ? wb : wa) + (size_t) r * N_EMBD);
float acc[MAX_T];
#pragma unroll
for (int t = 0; t < MAX_T; ++t) acc[t] = 0.0f;
#pragma unroll
for (int jj = 0; jj < AB_CHUNKS; ++jj) { // the ten passes, j = lane + 32 jj, all < 320
const int j = lane + 32 * jj;
const uint4 wv = __ldg(w4 + j);
#pragma unroll
for (int t = 0; t < MAX_T; ++t) {
if (!EXACT_T && t >= T) break;
const float* xt = x + (size_t) t * N_EMBD;
const float4 xa = __ldg(reinterpret_cast<const float4*>(xt + j * 8));
const float4 xb = __ldg(reinterpret_cast<const float4*>(xt + j * 8 + 4));
float v = acc[t];
v = fmaf(__uint_as_float(wv.x << 16), xa.x, v); v = fmaf(__uint_as_float(wv.x & 0xffff0000u), xa.y, v);
v = fmaf(__uint_as_float(wv.y << 16), xa.z, v); v = fmaf(__uint_as_float(wv.y & 0xffff0000u), xa.w, v);
v = fmaf(__uint_as_float(wv.z << 16), xb.x, v); v = fmaf(__uint_as_float(wv.z & 0xffff0000u), xb.y, v);
v = fmaf(__uint_as_float(wv.w << 16), xb.z, v); v = fmaf(__uint_as_float(wv.w & 0xffff0000u), xb.w, v);
acc[t] = v;
}
}
#pragma unroll
for (int t = 0; t < MAX_T; ++t) {
if (!EXACT_T && t >= T) break;
float sum = acc[t];
#pragma unroll
for (int o = 16; o > 0; o >>= 1) sum += __shfl_xor_sync(0xffffffffu, sum, o);
if (lane != 0) continue;
const float v = ab_value(sum, is_beta, dt[r], ssm_a[r]);
(is_beta ? beta : gate)[(size_t) t * h_v + r] = v;
}
}
// the Original's argument list (x, wa, wb, dt, ssm_a, gate, beta, n, h_v, T); 2 h_v rows, one warp each
#define LELEKA_AB_UNROLLED(NAME, MAX_T, EXACT_T) \
extern "C" __global__ void __launch_bounds__(64) NAME(const float* __restrict__ x, const uint16_t* __restrict__ wa, \
const uint16_t* __restrict__ wb, const float* __restrict__ dt, \
const float* __restrict__ ssm_a, float* __restrict__ gate, \
float* __restrict__ beta, int n, int h_v, int T) { \
(void) n; /* n == 2560: the host refuses any other width */ \
ab_unrolled_body<MAX_T, EXACT_T>(x, wa, wb, dt, ssm_a, gate, beta, h_v, T); \
}
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t1, 1, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t2, 2, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t3, 3, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t4, 4, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t5, 5, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t6, 6, true)
LELEKA_AB_UNROLLED(leleka_gdn_ab_unrolled_t8, 8, false) // T = 7 and 8: upstream's kVerifyNarrowT loop, the token count a run time argument
File diff suppressed because it is too large Load Diff
@@ -16,14 +16,14 @@ mod window;
/// The drafter of the serve stack: the draft ring and its actor.
type Mtp<'ctx> = (MtpOriginalInt8<'ctx>, OriginalMtpActor<'ctx>);
/// A verifier over the window resources of one request.
type Verifier<'w, 'ctx> = OriginalVerifier<'ctx, OriginalVerifyWindowResources<'w, 'ctx>>;
type Verifier<'w, 'ctx> = OriginalVerifier<'ctx, OriginalVerifyWindowResources<'ctx>>;
/// The QSA index checkpoint and the mapped prefix a request ends with.
type Kept<'ctx> = (Option<OriginalQsaIndexCheckpoint<'ctx>>, Option<OriginalQsaMappedPrefix>);
/// The twelve resident QSA indices and the twelve mapped journals.
type Owners<'ctx> = ([OriginalQsaResidentIndex<'ctx>; 12], [OriginalQsaMappedJournal<'ctx>; 12]);
fn rope<'a, 'ctx>() -> OriginalVerifyRope<'a, 'ctx> {
fn rope<'ctx>() -> OriginalVerifyRope<'ctx> {
OriginalVerifyRope {
theta_scale: 1e7f32.powf(-2.0 / 64.0),
freq_scale: 1.0,
@@ -50,8 +50,8 @@ pub(super) struct Drafting<'a, 'ctx> {
pub(super) reset_snapshot: &'a mut Option<MtpInt8Snapshot>,
}
/// What a request leaves for `take_apart`: the QSA journal and the checkpoint and mapped prefix its replay ended with.
struct QsaRequestEnd<'w, 'ctx> {
journal: Rc<OriginalVerifyQsaJournal<'w, 'ctx>>,
struct QsaRequestEnd<'ctx> {
journal: Rc<OriginalVerifyQsaJournal<'ctx>>,
kept: Kept<'ctx>,
}
/// The expert formats, geometry and layout, and the head and embedding rows.
@@ -189,10 +189,10 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
Some((indices.try_into().ok().expect("12"), mapped.try_into().ok().expect("12")))
}
/// The twelve QSA owners as one journal over the mapped prefixes, with the workspace they were prepared on.
fn qsa_journal<'w>(&'w self) -> Option<(Rc<OriginalVerifyQsaJournal<'w, 'ctx>>, NativeBatchWorkspace<'ctx>)> {
fn qsa_journal<'w>(&'w self) -> Option<(Rc<OriginalVerifyQsaJournal<'ctx>>, NativeBatchWorkspace<'ctx>)> {
let mut batch_ws = step!("native_batch_workspace", self.context.native_batch_workspace())?;
let (indices, mapped) = self.qsa_owners(&mut batch_ws)?;
let gamma: [&DeviceBuffer<'ctx>; 12] = std::array::from_fn(|i| &self.w.gamma[i]);
let gamma: [DeviceRef<'ctx>; 12] = std::array::from_fn(|i| self.w.gamma[i].clone());
let journal = step!(
"OriginalVerifyQsaJournal::new",
OriginalVerifyQsaJournal::new(self.context, indices, mapped, gamma, rope())
@@ -217,7 +217,7 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
let before_verifier = context.allocated_bytes();
let verifier = step!(
"OriginalVerifier::new",
OriginalVerifier::<OriginalVerifyWindowResources<'_, 'ctx>>::new(context, self.parts.g)
OriginalVerifier::<OriginalVerifyWindowResources<'ctx>>::new(context, self.parts.g)
)?;
eprintln!(
"PREFLIGHT verifier bank device={}MiB mapped_host={}MiB (context allocated {}MiB -> {}MiB)",
@@ -252,7 +252,7 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
fn record<'w>(
&self,
verifier: &mut Verifier<'w, 'ctx>,
mut windows: Vec<Option<OriginalVerifyWindowResources<'w, 'ctx>>>,
mut windows: Vec<Option<OriginalVerifyWindowResources<'ctx>>>,
) -> bool {
let max_t = self.max_t;
let commit = windows.pop().flatten().expect("commit aggregate");
@@ -275,7 +275,7 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
request: usize,
verifier: Verifier<'w, 'ctx>,
mtp: &mut Option<Mtp<'ctx>>,
qsa: QsaRequestEnd<'w, 'ctx>,
qsa: QsaRequestEnd<'ctx>,
) -> Option<()> {
let QsaRequestEnd { journal: qsa_journal, kept: (last_checkpoint, last_prefix) } = qsa;
if std::env::var_os("PROBE_NO_RELEASE").is_none() {
@@ -111,7 +111,7 @@ impl<'ctx> Replay<'ctx> {
Some((window.selection, completed))
}
/// The reads `OriginalServeHost::publish_committed` / `settle_state` make after a commit.
fn reads<'w>(&mut self, verifier: &mut Verifier<'w, 'ctx>, qsa_journal: &Rc<OriginalVerifyQsaJournal<'w, 'ctx>>) {
fn reads<'w>(&mut self, verifier: &mut Verifier<'w, 'ctx>, qsa_journal: &Rc<OriginalVerifyQsaJournal<'ctx>>) {
let _ = step!("verifier.accepted_tokens", verifier.accepted_tokens().map(|a| a.len()));
let publish_ws = &mut self.publish_ws;
self.last_checkpoint = step!(
@@ -176,7 +176,7 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
request: usize,
verifier: &mut Verifier<'w, 'ctx>,
drafting: Drafting<'_, 'ctx>,
qsa_journal: &Rc<OriginalVerifyQsaJournal<'w, 'ctx>>,
qsa_journal: &Rc<OriginalVerifyQsaJournal<'ctx>>,
) -> Option<Kept<'ctx>> {
let Drafting { mtp, reset_snapshot } = drafting;
let mut replay = Replay::start(self.context)?;
@@ -2,57 +2,57 @@
use super::*;
/// One allocation, reported as the other preflight steps are.
fn alloc<'ctx>(context: &'ctx Context<'ctx>, name: impl std::fmt::Display, bytes: usize) -> Option<DeviceBuffer<'ctx>> {
step!(name, context.allocate(bytes))
fn alloc<'ctx>(context: &'ctx Context<'ctx>, name: impl std::fmt::Display, bytes: usize) -> Option<DeviceRef<'ctx>> {
step!(name, context.allocate(bytes).map(DeviceRef::from_buffer))
}
fn size(kind: u32, n_in: usize, n_out: usize) -> Result<usize> {
native_head_row_bytes(kind, n_in).map(|r| r * n_out)
}
/// The hyper-connection weights of one half layer.
pub(super) struct Hc<'ctx> {
pub(super) norm: DeviceBuffer<'ctx>,
pub(super) down: DeviceBuffer<'ctx>,
pub(super) up: DeviceBuffer<'ctx>,
pub(super) inject: DeviceBuffer<'ctx>,
pub(super) norm: DeviceRef<'ctx>,
pub(super) down: DeviceRef<'ctx>,
pub(super) up: DeviceRef<'ctx>,
pub(super) inject: DeviceRef<'ctx>,
}
pub(super) struct Ple<'ctx> {
pub(super) key: DeviceBuffer<'ctx>,
pub(super) value: DeviceBuffer<'ctx>,
pub(super) norm_key: DeviceBuffer<'ctx>,
pub(super) norm_query: DeviceBuffer<'ctx>,
pub(super) norm_conv: DeviceBuffer<'ctx>,
pub(super) conv1d: DeviceBuffer<'ctx>,
pub(super) scratch: DeviceBuffer<'ctx>,
pub(super) history: DeviceBuffer<'ctx>,
pub(super) key: DeviceRef<'ctx>,
pub(super) value: DeviceRef<'ctx>,
pub(super) norm_key: DeviceRef<'ctx>,
pub(super) norm_query: DeviceRef<'ctx>,
pub(super) norm_conv: DeviceRef<'ctx>,
pub(super) conv1d: DeviceRef<'ctx>,
pub(super) scratch: DeviceRef<'ctx>,
pub(super) history: DeviceRef<'ctx>,
}
/// The router and the shared experts.
pub(super) struct Moe<'ctx> {
pub(super) router: DeviceBuffer<'ctx>,
pub(super) gate_inp: DeviceBuffer<'ctx>,
pub(super) gate: DeviceBuffer<'ctx>,
pub(super) up: DeviceBuffer<'ctx>,
pub(super) down: DeviceBuffer<'ctx>,
pub(super) router: DeviceRef<'ctx>,
pub(super) gate_inp: DeviceRef<'ctx>,
pub(super) gate: DeviceRef<'ctx>,
pub(super) up: DeviceRef<'ctx>,
pub(super) down: DeviceRef<'ctx>,
}
/// The GDN weights that are not matrices.
pub(super) struct Gdn<'ctx> {
pub(super) conv: DeviceBuffer<'ctx>,
pub(super) alpha: DeviceBuffer<'ctx>,
pub(super) beta: DeviceBuffer<'ctx>,
pub(super) dt: DeviceBuffer<'ctx>,
pub(super) a: DeviceBuffer<'ctx>,
pub(super) norm: DeviceBuffer<'ctx>,
pub(super) conv: DeviceRef<'ctx>,
pub(super) alpha: DeviceRef<'ctx>,
pub(super) beta: DeviceRef<'ctx>,
pub(super) dt: DeviceRef<'ctx>,
pub(super) a: DeviceRef<'ctx>,
pub(super) norm: DeviceRef<'ctx>,
}
pub(super) struct Weights<'ctx> {
pub(super) proj: Vec<DeviceBuffer<'ctx>>,
pub(super) proj: Vec<DeviceRef<'ctx>>,
pub(super) hc: Hc<'ctx>,
pub(super) ple: Ple<'ctx>,
/// QSA norms and indexer projections: pairwise disjoint per layer.
pub(super) qsa: Vec<Vec<DeviceBuffer<'ctx>>>,
pub(super) gamma: Vec<DeviceBuffer<'ctx>>,
pub(super) qsa: Vec<Vec<DeviceRef<'ctx>>>,
pub(super) gamma: Vec<DeviceRef<'ctx>>,
pub(super) moe: Moe<'ctx>,
pub(super) gdn: Gdn<'ctx>,
}
fn projections<'ctx>(context: &'ctx Context<'ctx>, proj: &[u32]) -> Option<Vec<DeviceBuffer<'ctx>>> {
fn projections<'ctx>(context: &'ctx Context<'ctx>, proj: &[u32]) -> Option<Vec<DeviceRef<'ctx>>> {
let mats: Vec<(usize, usize)> =
vec![(2560, 10240), (2560, 6144), (6144, 2560), (2560, 512), (2560, 512), (2560, 12288), (6144, 2560)];
let mut proj_bufs = Vec::new();
@@ -82,7 +82,7 @@ fn ple<'ctx>(context: &'ctx Context<'ctx>) -> Option<Ple<'ctx>> {
history: alloc(context, "alloc ple_history", 9 * 10240 * 4)?,
})
}
fn qsa_norms<'ctx>(context: &'ctx Context<'ctx>) -> Option<Vec<Vec<DeviceBuffer<'ctx>>>> {
fn qsa_norms<'ctx>(context: &'ctx Context<'ctx>) -> Option<Vec<Vec<DeviceRef<'ctx>>>> {
let mut qsa_bufs = Vec::new();
for layer in 0..12 {
let mut five = Vec::new();
@@ -93,7 +93,7 @@ fn qsa_norms<'ctx>(context: &'ctx Context<'ctx>) -> Option<Vec<Vec<DeviceBuffer<
}
Some(qsa_bufs)
}
fn gammas<'ctx>(context: &'ctx Context<'ctx>) -> Option<Vec<DeviceBuffer<'ctx>>> {
fn gammas<'ctx>(context: &'ctx Context<'ctx>) -> Option<Vec<DeviceRef<'ctx>>> {
let mut gamma_bufs = Vec::new();
for i in 0..12 {
gamma_bufs.push(alloc(context, format!("alloc gamma[{i}]"), 512)?);
@@ -7,8 +7,8 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
&'w self,
verifier: &Verifier<'w, 'ctx>,
canonical: &mut OriginalVerifyCanonicalGdn<'ctx>,
qsa_journal: &Rc<OriginalVerifyQsaJournal<'w, 'ctx>>,
) -> Option<Vec<Option<OriginalVerifyWindowResources<'w, 'ctx>>>> {
qsa_journal: &Rc<OriginalVerifyQsaJournal<'ctx>>,
) -> Option<Vec<Option<OriginalVerifyWindowResources<'ctx>>>> {
let mut windows = Vec::new();
for t in 1..=self.max_t + 1 {
let window_t = if t <= self.max_t { t } else { self.max_t };
@@ -20,15 +20,15 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
}
Some(windows)
}
fn gdn_weights(&self) -> [OriginalVerifyGdnWeights<'_, 'ctx>; 36] {
fn gdn_weights(&self) -> [OriginalVerifyGdnWeights<'ctx>; 36] {
let gdn = &self.w.gdn;
std::array::from_fn(|_| OriginalVerifyGdnWeights {
conv: &gdn.conv,
alpha: &gdn.alpha,
beta: &gdn.beta,
dt: &gdn.dt,
a: &gdn.a,
norm: &gdn.norm,
conv: gdn.conv.clone(),
alpha: gdn.alpha.clone(),
beta: gdn.beta.clone(),
dt: gdn.dt.clone(),
a: gdn.a.clone(),
norm: gdn.norm.clone(),
})
}
/// The GDN journal, the head and embedding rows and the layout.
@@ -37,14 +37,14 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
window_t: usize,
verifier: &Verifier<'w, 'ctx>,
canonical: &mut OriginalVerifyCanonicalGdn<'ctx>,
qsa_journal: &Rc<OriginalVerifyQsaJournal<'w, 'ctx>>,
) -> Option<OriginalVerifyWindowResources<'w, 'ctx>> {
qsa_journal: &Rc<OriginalVerifyQsaJournal<'ctx>>,
) -> Option<OriginalVerifyWindowResources<'ctx>> {
let context = self.context;
let gdn_weights = self.gdn_weights();
let bank = step!("verifier.bank()", verifier.bank())?;
let journal = step!(
format!("gdn_journal(t={window_t})"),
bank.gdn_journal(canonical, gdn_weights, Some(&self.w.ple.history))
bank.gdn_journal(canonical, gdn_weights, Some(self.w.ple.history.clone()))
)?;
let head_rows = step!(format!("head.rows({window_t})"), self.parts.head.rows(window_t))?;
let resources = step!(
@@ -57,95 +57,86 @@ impl<'a, 'ctx> Rig<'a, 'ctx> {
OriginalVerifyWindowResources::new(context, resources, embed_rows, self.parts.layout.clone(), window_t)
)
}
fn gdn_proj(&self) -> Vec<OriginalVerifyGdnProjections<'_, 'ctx>> {
fn gdn_proj(&self) -> Vec<OriginalVerifyGdnProjections<'ctx>> {
let (proj, bufs) = (self.proj, &self.w.proj);
(0..36)
.map(|_| OriginalVerifyGdnProjections {
qkv: OriginalVerifyNativeMatrix { kind: proj[0], buffer: &bufs[0] },
gate: OriginalVerifyNativeMatrix { kind: proj[1], buffer: &bufs[1] },
out: OriginalVerifyNativeMatrix { kind: proj[2], buffer: &bufs[2] },
qkv: OriginalVerifyNativeMatrix { kind: proj[0], buffer: bufs[0].clone() },
gate: OriginalVerifyNativeMatrix { kind: proj[1], buffer: bufs[1].clone() },
out: OriginalVerifyNativeMatrix { kind: proj[2], buffer: bufs[2].clone() },
})
.collect::<Vec<_>>()
}
fn qsa_proj(&self) -> Vec<OriginalVerifyQsaProjections<'_, 'ctx>> {
fn qsa_proj(&self) -> Vec<OriginalVerifyQsaProjections<'ctx>> {
let (proj, bufs) = (self.proj, &self.w.proj);
(0..12)
.map(|_| OriginalVerifyQsaProjections {
k: OriginalVerifyNativeMatrix { kind: proj[3], buffer: &bufs[3] },
v: OriginalVerifyNativeMatrix { kind: proj[4], buffer: &bufs[4] },
q: OriginalVerifyNativeMatrix { kind: proj[5], buffer: &bufs[5] },
out: OriginalVerifyNativeMatrix { kind: proj[6], buffer: &bufs[6] },
k: OriginalVerifyNativeMatrix { kind: proj[3], buffer: bufs[3].clone() },
v: OriginalVerifyNativeMatrix { kind: proj[4], buffer: bufs[4].clone() },
q: OriginalVerifyNativeMatrix { kind: proj[5], buffer: bufs[5].clone() },
out: OriginalVerifyNativeMatrix { kind: proj[6], buffer: bufs[6].clone() },
})
.collect::<Vec<_>>()
}
fn with_projections<'w>(
&'w self,
w: OriginalVerifyWindowResources<'w, 'ctx>,
) -> Option<OriginalVerifyWindowResources<'w, 'ctx>> {
w: OriginalVerifyWindowResources<'ctx>,
) -> Option<OriginalVerifyWindowResources<'ctx>> {
step!(
"with_projections",
OriginalVerifyProjBinding::new(self.context, &self.parts.g, self.gdn_proj(), self.qsa_proj())
.and_then(|p| w.with_projections(p))
)
}
fn half(&self) -> HcHalfBuffers<'_, 'ctx> {
fn half(&self) -> HcHalfBuffers<'ctx> {
let hc = &self.w.hc;
HcHalfBuffers { norm: &hc.norm, down: &hc.down, up: &hc.up, inject: &hc.inject }
HcHalfBuffers { norm: hc.norm.clone(), down: hc.down.clone(), up: hc.up.clone(), inject: hc.inject.clone() }
}
fn with_gr<'w>(
&'w self,
w: OriginalVerifyWindowResources<'w, 'ctx>,
) -> Option<OriginalVerifyWindowResources<'w, 'ctx>> {
fn with_gr<'w>(&'w self, w: OriginalVerifyWindowResources<'ctx>) -> Option<OriginalVerifyWindowResources<'ctx>> {
let (hc, ple) = (&self.w.hc, &self.w.ple);
let layers: Vec<_> = (0..48).map(|_| HcLayerBuffers { attention: self.half(), ffn: self.half() }).collect();
let output = HcOutputBuffers { norm: &hc.norm, down: &hc.down, up: &hc.up };
let output = HcOutputBuffers { norm: hc.norm.clone(), down: hc.down.clone(), up: hc.up.clone() };
let ple = PleBuffers {
key: PleKeyBuffer::Bf16(&ple.key),
value: &ple.value,
norm_key: &ple.norm_key,
norm_query: &ple.norm_query,
norm_conv: &ple.norm_conv,
conv1d: &ple.conv1d,
scratch: &ple.scratch,
history: &ple.history,
key: PleKeyBuffer::Bf16(ple.key.clone()),
value: ple.value.clone(),
norm_key: ple.norm_key.clone(),
norm_query: ple.norm_query.clone(),
norm_conv: ple.norm_conv.clone(),
conv1d: ple.conv1d.clone(),
scratch: ple.scratch.clone(),
history: ple.history.clone(),
};
step!(
"with_gr",
OriginalVerifyGrBinding::new(self.context, layers, output, Some(ple)).and_then(|b| w.with_gr(b))
)
}
fn with_qsa<'w>(
&'w self,
w: OriginalVerifyWindowResources<'w, 'ctx>,
) -> Option<OriginalVerifyWindowResources<'w, 'ctx>> {
fn with_qsa<'w>(&'w self, w: OriginalVerifyWindowResources<'ctx>) -> Option<OriginalVerifyWindowResources<'ctx>> {
let qsa = &self.w.qsa;
let qsa_layers: [OriginalVerifyQsaLayerWeights<'_, 'ctx>; 12] =
let qsa_layers: [OriginalVerifyQsaLayerWeights<'ctx>; 12] =
std::array::from_fn(|i| OriginalVerifyQsaLayerWeights {
attn_q_norm: &qsa[i][0],
attn_k_norm: &qsa[i][1],
index_q_norm: &qsa[i][2],
index_k_proj: &qsa[i][3],
index_q_proj: &qsa[i][4],
attn_q_norm: qsa[i][0].clone(),
attn_k_norm: qsa[i][1].clone(),
index_q_norm: qsa[i][2].clone(),
index_k_proj: qsa[i][3].clone(),
index_q_proj: qsa[i][4].clone(),
});
step!(
"with_qsa",
OriginalVerifyQsaBinding::new(self.context, self.parts.g, qsa_layers).and_then(|b| w.with_qsa(b))
)
}
fn with_moe<'w>(
&'w self,
w: OriginalVerifyWindowResources<'w, 'ctx>,
) -> Option<OriginalVerifyWindowResources<'w, 'ctx>> {
fn with_moe<'w>(&'w self, w: OriginalVerifyWindowResources<'ctx>) -> Option<OriginalVerifyWindowResources<'ctx>> {
let (moe, shared) = (&self.w.moe, self.shared);
let moe_layers: Vec<_> = (0..48)
.map(|_| OriginalVerifyMoeLayerWeights {
router: &moe.router,
gate_inp_shexp: &moe.gate_inp,
gate_shexp: &moe.gate,
router: moe.router.clone(),
gate_inp_shexp: moe.gate_inp.clone(),
gate_shexp: moe.gate.clone(),
gate_shexp_type: shared[0],
up_shexp: &moe.up,
up_shexp: moe.up.clone(),
up_shexp_type: shared[1],
down_shexp: &moe.down,
down_shexp: moe.down.clone(),
down_shexp_type: shared[2],
})
.collect();
+5 -3
View File
@@ -111,8 +111,8 @@ impl Profile {
for (key, value) in &self.engine_env {
if !engine_env_key_ok(key) {
return Err(format!(
"engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_* or \
LELEKA_PLE_* name (or LELEKA_CHAIN)"
"engine_env key {key} must be an upper-case LELEKA_ORIGINAL_SERVE_*, LELEKA_SM120_*, \
LELEKA_DRAFT_* or LELEKA_PLE_* name (or LELEKA_CHAIN)"
));
}
if value.is_empty() || value.len() > 1024 || value.chars().any(char::is_control) {
@@ -126,11 +126,13 @@ impl Profile {
}
/// LELEKA_CHAIN selects the chain-kernel group (docs/chain-kernels.md), LELEKA_SM120_* the compute-capability-12
/// kernel switches (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the GGUF PLE row reader
/// kernel switches, LELEKA_DRAFT_* the draft-round ones (docs/experiments/draft-round-5090.md), LELEKA_PLE_* the
/// GGUF PLE row reader
/// (`kar_source: none`); every other switch is a serve-stack one.
fn engine_env_key_ok(key: &str) -> bool {
let known = key.starts_with("LELEKA_ORIGINAL_SERVE_")
|| key.starts_with("LELEKA_SM120_")
|| key.starts_with("LELEKA_DRAFT_")
|| key.starts_with("LELEKA_PLE_")
|| key == "LELEKA_CHAIN";
known
@@ -189,8 +189,14 @@ fn only_the_5090_profiles_enable_the_sm120_main_attention_and_swiglu_kernels() {
}
}
/// Engine switches of the compute capability 12 kernels that replace the main attention and the gate/up SwiGLU.
const SM120_MAIN_KERNEL_KEYS: [&str; 2] = ["LELEKA_SM120_ATTN_DAILY", "LELEKA_SM120_GU_SWIGLU"];
/// Engine switches of the compute capability 12 kernels (main attention, gate/up SwiGLU) and of the GDN side streams.
const SM120_MAIN_KERNEL_KEYS: [&str; 5] = [
"LELEKA_SM120_ATTN_DAILY",
"LELEKA_SM120_GU_SWIGLU",
"LELEKA_SM120_SIDE_MIXER",
"LELEKA_SM120_SIDE_QSA",
"LELEKA_SM120_SIDE_SHARED",
];
#[test]
fn validation_rejects_unsafe_values() {
@@ -1,10 +1,11 @@
//! Router and shared-expert operands of the Original verifier window, borrowed from the MoE cache.
//! Router and shared-expert operands of the Original verifier window, shared with the MoE cache.
//!
//! The window reads the router matrix and the shared expert (gate, up, down and the shared scalar) of all
//! 48 layers at once, in place, for the whole decode phase. The prompt path loads exactly the same raw
//! tensors layer by layer (`original_shared_layer`); `ensure_original_verify_shared` runs that loader for
//! every layer and then proves all 192 tensors are resident together (a load of a later layer may not have
//! evicted an earlier one), and `original_verify_moe` lends them. Nothing is copied or re-encoded: the
//! 48 layers at once, in place, for the whole decode phase. It holds them as shared handles (`DeviceRef`), so the
//! assembly does not borrow the cache and an entry the cache evicts stays alive while it is held. The prompt path
//! loads exactly the same raw tensors layer by layer (`original_shared_layer`); `ensure_original_verify_shared` runs
//! that loader for every layer and then proves all 192 tensors are resident together (a load of a later layer may
//! not have evicted an earlier one), and `original_verify_moe` hands them out. Nothing is copied or re-encoded: the
//! routed experts are not here (the verifier's expert tier is the pool callback).
use super::*;
use crate::qwen_forward::original_serve_verifier::VerifyWeights;
@@ -12,7 +13,7 @@ use crate::qwen_forward::{
contract::{Dimension, LayerId},
dense_weight_cache::DenseWeightCache,
};
use leleka_cuda_driver::{OriginalVerifyGeometry, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights};
use leleka_cuda_driver::{DeviceRef, OriginalVerifyGeometry, OriginalVerifyMoeBinding, OriginalVerifyMoeLayerWeights};
/// Descriptors of one layer's shared gate, up, down and the shared scalar, in that order.
pub(in crate::qwen_forward) type SharedKeys = Vec<[MoeWeightDescriptor; 4]>;
@@ -39,28 +40,29 @@ impl<'ctx> MoeWeightCache<'ctx> {
Ok(all)
}
fn raw_shared(&self, key: &MoeWeightDescriptor) -> Result<&DeviceBuffer<'ctx>> {
/// A shared handle to the raw tensor of `key`: one reference-count increment, no copy.
fn raw_shared(&self, key: &MoeWeightDescriptor) -> Result<DeviceRef<'ctx>> {
let entry = self.main.get(key).ok_or(Error::IdentityMismatch)?;
if entry.charged_bytes != key.bytes {
return Err(Error::IdentityMismatch);
}
match &entry.weight {
EncodedWeight::Raw(buffer) => Ok(buffer),
EncodedWeight::Raw(buffer) => Ok(buffer.clone()),
_ => Err(Error::IdentityMismatch),
}
}
fn verify_moe_layer<'a>(
&'a self,
fn verify_moe_layer(
&self,
binding: &ModelBinding,
dense: &'a DenseWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
layer: usize,
keys: &[MoeWeightDescriptor; 4],
) -> Result<OriginalVerifyMoeLayerWeights<'a, 'ctx>> {
) -> Result<OriginalVerifyMoeLayerWeights<'ctx>> {
if keys.iter().any(|key| key.layer as usize != layer) {
return Err(Error::IdentityMismatch);
}
Ok(OriginalVerifyMoeLayerWeights {
router: dense.router(binding, layer as u32)?,
router: dense.router_handle(binding, layer as u32)?,
gate_inp_shexp: self.raw_shared(&keys[3])?,
gate_shexp: self.raw_shared(&keys[0])?,
gate_shexp_type: keys[0].raw_kind,
@@ -78,7 +80,7 @@ impl<'a, 'ctx> VerifyWeights<'a, 'ctx> {
&self,
binding: &ModelBinding,
geometry: &OriginalVerifyGeometry,
) -> Result<OriginalVerifyMoeBinding<'a, 'ctx>> {
) -> Result<OriginalVerifyMoeBinding<'ctx>> {
let (moe, dense, shared) = (self.moe, self.dense, self.shared);
moe.validate(binding, moe.context)?;
if shared.len() != 48 {
@@ -147,7 +147,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
EncodedWeight::Dual(format, owner)
} else {
// Original upload includes the same full encoded bytes.
EncodedWeight::Raw(self.upload(&raw[i])?)
EncodedWeight::Raw(DeviceRef::from_buffer(self.upload(&raw[i])?))
};
owned[i] = Some(weight);
}
@@ -95,7 +95,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
if raw.len() != key.bytes {
return Err(Error::InvalidDimension);
}
owned[index] = Some(EncodedWeight::Raw(self.upload(&raw)?));
owned[index] = Some(EncodedWeight::Raw(DeviceRef::from_buffer(self.upload(&raw)?)));
}
Ok(())
}
@@ -1,9 +1,10 @@
//! Weight bindings of the Original verifier window that the dense cache owns: the hyper-connection weights
//! of the 48 layers, the final mixer and the PLE block (`OriginalVerifyGrBinding`), and the QSA norms and
//! indexer projections of the twelve QSA layers (`OriginalVerifyQsaBinding`). They are the cache's own
//! allocations, borrowed for the lifetime of a decode phase: the very buffers the prompt path reads, so the
//! window and the prefill cannot disagree about a weight. Native MMVQ projections are
//! `original_verify_projections`; router and shared experts live in the MoE cache (`cache_original_verify`).
//! indexer projections of the twelve QSA layers (`OriginalVerifyQsaBinding`). They are shared handles
//! (`DeviceRef`) to the cache's own allocations: the very buffers the prompt path reads, so the window and the
//! prefill cannot disagree about a weight, and a held assembly keeps them alive without borrowing the cache.
//! Native MMVQ projections are `original_verify_projections`; router and shared experts live in the MoE cache
//! (`cache_original_verify`).
use super::*;
use leleka_cuda_driver::{
HcHalfBuffers, HcLayerBuffers, HcOutputBuffers, OriginalVerifyGeometry, OriginalVerifyGrBinding,
@@ -11,9 +12,20 @@ use leleka_cuda_driver::{
};
impl<'ctx> DenseWeightCache<'ctx> {
fn verify_gr_half<'a>(&'a self, binding: &ModelBinding, role: GrRole) -> Result<HcHalfBuffers<'a, 'ctx>> {
/// The handles of a hyper-connection entry's present buffers (norm, down, up, inject), owner checked.
fn gr_handles(&self, entry: &GrResident) -> Result<[Option<DeviceRef<'ctx>>; 4]> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
let mut handles: [Option<DeviceRef<'ctx>>; 4] = Default::default();
for (handle, slot) in handles.iter_mut().zip(entry.buffers) {
*handle = slot.map(|index| self.handle(index)).transpose()?;
}
Ok(handles)
}
fn verify_gr_half(&self, binding: &ModelBinding, role: GrRole) -> Result<HcHalfBuffers<'ctx>> {
let entry = self.gr(binding, role)?;
let [norm, down, up, inject] = self.gr_buffers(entry)?;
let [norm, down, up, inject] = self.gr_handles(entry)?;
Ok(HcHalfBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
@@ -21,42 +33,45 @@ impl<'ctx> DenseWeightCache<'ctx> {
inject: inject.ok_or(Error::IdentityMismatch)?,
})
}
fn verify_gr_output<'a>(&'a self, binding: &ModelBinding) -> Result<HcOutputBuffers<'a, 'ctx>> {
fn verify_gr_output(&self, binding: &ModelBinding) -> Result<HcOutputBuffers<'ctx>> {
let entry = self.gr(binding, GrRole::Final)?;
let [norm, down, up, _] = self.gr_buffers(entry)?;
let [norm, down, up, _] = self.gr_handles(entry)?;
Ok(HcOutputBuffers {
norm: norm.ok_or(Error::IdentityMismatch)?,
down: down.ok_or(Error::IdentityMismatch)?,
up: up.ok_or(Error::IdentityMismatch)?,
})
}
fn verify_ple_buffers<'a>(
&'a self,
fn verify_ple_buffers(
&self,
binding: &ModelBinding,
ple_scratch: &'a DeviceBuffer<'ctx>,
ple_history: &'a DeviceBuffer<'ctx>,
) -> Result<PleBuffers<'a, 'ctx>> {
ple_scratch: &DeviceRef<'ctx>,
ple_history: &DeviceRef<'ctx>,
) -> Result<PleBuffers<'ctx>> {
let ple = self.ple(binding, self.context)?;
let [norm_key, norm_query, norm_conv, conv1d] = self.ple_aux(ple)?;
// the size checks of the accessors stay; the handles come from the same slots
self.ple_key(ple)?;
self.ple_value(ple)?;
let [norm_key, norm_query, norm_conv, conv1d] = self.handles(self.ple_aux_slots(ple)?)?;
Ok(PleBuffers {
key: PleKeyBuffer::Bf16(self.ple_key(ple)?),
value: self.ple_value(ple)?,
key: PleKeyBuffer::Bf16(self.handle(ple.key)?),
value: self.handle(ple.value)?,
norm_key,
norm_query,
norm_conv,
conv1d,
scratch: ple_scratch,
history: ple_history,
scratch: ple_scratch.clone(),
history: ple_history.clone(),
})
}
/// `hc_*` weights of every layer half, the `output_hc_*` mixer and the PLE block. `ple_history` must be
/// the buffer the verify journal snapshots; `ple_scratch` at least `PLE_SCRATCH_BYTES`.
pub(in crate::qwen_forward) fn original_verify_gr<'a>(
&'a self,
pub(in crate::qwen_forward) fn original_verify_gr(
&self,
binding: &ModelBinding,
ple_scratch: &'a DeviceBuffer<'ctx>,
ple_history: &'a DeviceBuffer<'ctx>,
) -> Result<OriginalVerifyGrBinding<'a, 'ctx>> {
ple_scratch: &DeviceRef<'ctx>,
ple_history: &DeviceRef<'ctx>,
) -> Result<OriginalVerifyGrBinding<'ctx>> {
self.check(binding)?;
let mut layers = Vec::new();
layers.try_reserve_exact(48).map_err(|_| Error::InputAllocation)?;
@@ -71,33 +86,29 @@ impl<'ctx> DenseWeightCache<'ctx> {
OriginalVerifyGrBinding::new(self.context, layers, output, Some(ple)).map_err(driver_error)
}
fn verify_qsa_layer<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyQsaLayerWeights<'a, 'ctx>> {
fn verify_qsa_layer(&self, binding: &ModelBinding, layer: u32) -> Result<OriginalVerifyQsaLayerWeights<'ctx>> {
let entry = self.qsa(binding, layer)?;
// norms: [q, k, index q, index k]; the index-k gamma belongs to the journal
let norms = self.qsa_norms(entry)?;
let (index_k, kind_k) = self.qsa_matrix(entry, QsaMatrixRole::IndexK)?;
let (index_q, kind_q) = self.qsa_matrix(entry, QsaMatrixRole::IndexQ)?;
let [attn_q_norm, attn_k_norm, index_q_norm, _] = self.handles(self.qsa_norm_slots(entry)?)?;
let (index_k, kind_k) = self.qsa_matrix_slot(entry, QsaMatrixRole::IndexK)?;
let (index_q, kind_q) = self.qsa_matrix_slot(entry, QsaMatrixRole::IndexQ)?;
if kind_k != QsaMatrixKind::Bf16 || kind_q != QsaMatrixKind::Bf16 {
return Err(Error::Unsupported(crate::qwen_forward::contract::Stage::QsaIndex));
}
Ok(OriginalVerifyQsaLayerWeights {
attn_q_norm: norms[0],
attn_k_norm: norms[1],
index_q_norm: norms[2],
index_k_proj: index_k,
index_q_proj: index_q,
attn_q_norm,
attn_k_norm,
index_q_norm,
index_k_proj: self.handle(index_k)?,
index_q_proj: self.handle(index_q)?,
})
}
/// The twelve QSA layers' Q/K norms, indexer Q norm and the BF16 indexer K/Q projections.
pub(in crate::qwen_forward) fn original_verify_qsa<'a>(
&'a self,
pub(in crate::qwen_forward) fn original_verify_qsa(
&self,
binding: &ModelBinding,
geometry: &OriginalVerifyGeometry,
) -> Result<OriginalVerifyQsaBinding<'a, 'ctx>> {
) -> Result<OriginalVerifyQsaBinding<'ctx>> {
self.check(binding)?;
let mut layers = Vec::new();
layers.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?;
@@ -107,8 +118,14 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
layers.push(self.verify_qsa_layer(binding, layer.index())?);
}
let layers: [OriginalVerifyQsaLayerWeights<'a, 'ctx>; 12] =
let layers: [OriginalVerifyQsaLayerWeights<'ctx>; 12] =
layers.try_into().map_err(|_| Error::InvalidDimension)?;
OriginalVerifyQsaBinding::new(self.context, *geometry, layers).map_err(driver_error)
}
/// The router matrix of `layer` for the verifier window's MoE binding (a shared handle).
pub(in crate::qwen_forward) fn router_handle(&self, binding: &ModelBinding, layer: u32) -> Result<DeviceRef<'ctx>> {
self.check(binding)?;
self.hit()?;
self.handle(*self.router.get(layer as usize).ok_or(Error::InvalidLayer)?)
}
}
@@ -16,7 +16,7 @@ use crate::model_binding::qwen4exp_input::{
use leleka_cuda_driver::GrBatchInjectWorkspace;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use leleka_cuda_driver::OriginalVerifyGdnWeights;
use leleka_cuda_driver::{Context, DeviceBuffer, DeviceSlice, SlabAllocator, SlabPolicy};
use leleka_cuda_driver::{Context, DeviceBuffer, DeviceRef, SlabAllocator, SlabPolicy};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use leleka_cuda_driver::{
OriginalVerifyGdnProjections, OriginalVerifyGeometry, OriginalVerifyNativeMatrix, OriginalVerifyProjBinding,
@@ -78,7 +78,7 @@ pub(crate) struct DenseWeightCache<'ctx> {
context: &'ctx Context<'ctx>,
/// Every resident weight, in `add` order. Small ones are sub-ranges of 64 MiB slabs (`dense_slab_policy`): the
/// driver rounds each separate allocation above 1 MiB up to 2 MiB, which took 688 MiB for about 700 buffers.
buffers: Vec<DeviceSlice<'ctx>>,
buffers: Vec<DeviceRef<'ctx>>,
slabs: Option<SlabAllocator<'ctx>>,
gdn: Vec<Option<GdnResident>>,
gdn_mirrors: Vec<Option<RefCell<GdnStateMirror<'ctx>>>>,
@@ -224,4 +224,18 @@ impl<'ctx> DenseWeightCache<'ctx> {
pub(in super::super) fn buffer(&self, index: usize) -> Result<&DeviceBuffer<'ctx>> {
self.buffers.get(index).map(|slice| &**slice).ok_or(Error::IdentityMismatch)
}
/// A shared handle to buffer `index` for a held verify assembly: one reference-count increment, so the
/// allocation outlives this cache's own release of it.
pub(in super::super) fn handle(&self, index: usize) -> Result<DeviceRef<'ctx>> {
self.buffers.get(index).cloned().ok_or(Error::IdentityMismatch)
}
/// `handle` of several slots at once, in order.
pub(in super::super) fn handles<const N: usize>(&self, slots: [usize; N]) -> Result<[DeviceRef<'ctx>; N]> {
let mut out = Vec::new();
out.try_reserve_exact(N).map_err(|_| Error::InputAllocation)?;
for slot in slots {
out.push(self.handle(slot)?);
}
out.try_into().map_err(|_| Error::InvalidDimension)
}
}
@@ -29,7 +29,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
return Err(primary);
}
let index = self.buffers.len();
self.buffers.push(b);
self.buffers.push(DeviceRef::from_slice(b));
let mut c = self.counters.get();
c.matrices = c.matrices.checked_add(1).ok_or(Error::Overflow)?;
c.read_bytes = c.read_bytes.checked_add(source_bytes as u64).ok_or(Error::Overflow)?;
@@ -53,21 +53,30 @@ impl<'ctx> DenseWeightCache<'ctx> {
Err(Error::Unsupported(super::super::super::contract::Stage::Input))
}
pub(in super::super::super) fn ple_aux(&self, entry: &PleResident) -> Result<[&DeviceBuffer<'ctx>; 4]> {
let slots = self.ple_aux_slots(entry)?;
Ok([self.buffer(slots[0])?, self.buffer(slots[1])?, self.buffer(slots[2])?, self.buffer(slots[3])?])
}
/// The cache slots of the PLE norms and the causal convolution (`ple_aux` order).
pub(in super::super::super) fn ple_aux_slots(&self, entry: &PleResident) -> Result<[usize; 4]> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
Ok([
self.buffer(entry.aux[0])?,
self.buffer(entry.aux[1])?,
self.buffer(entry.aux[2])?,
self.buffer(entry.aux[3])?,
])
Ok(entry.aux)
}
pub(in super::super::super) fn gdn_matrix(
&self,
entry: &GdnResident,
role: GdnMatrixRole,
) -> Result<(&DeviceBuffer<'ctx>, GdnMatrixKind)> {
let (index, kind) = self.gdn_matrix_slot(entry, role)?;
Ok((self.buffer(index)?, kind))
}
/// The cache slot and storage kind of one GDN matrix.
pub(in super::super::super) fn gdn_matrix_slot(
&self,
entry: &GdnResident,
role: GdnMatrixRole,
) -> Result<(usize, GdnMatrixKind)> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
@@ -78,28 +87,27 @@ impl<'ctx> DenseWeightCache<'ctx> {
GdnMatrixRole::Beta => 3,
GdnMatrixRole::Out => 4,
};
let (index, kind) = entry.matrices[i];
Ok((self.buffer(index)?, kind))
Ok(entry.matrices[i])
}
pub(in super::super::super) fn gdn_aux(&self, entry: &GdnResident) -> Result<[&DeviceBuffer<'ctx>; 4]> {
let slots = self.gdn_aux_slots(entry)?;
Ok([self.buffer(slots[0])?, self.buffer(slots[1])?, self.buffer(slots[2])?, self.buffer(slots[3])?])
}
/// The cache slots of a GDN layer's conv, dt, a and norm tensors (`gdn_aux` order).
pub(in super::super::super) fn gdn_aux_slots(&self, entry: &GdnResident) -> Result<[usize; 4]> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
Ok([
self.buffer(entry.aux[0])?,
self.buffer(entry.aux[1])?,
self.buffer(entry.aux[2])?,
self.buffer(entry.aux[3])?,
])
Ok(entry.aux)
}
/// Ordered, retained operands for the native verifier's thirty-six GDN
/// layers. These are the cache's actual allocations: no host-side weight
/// conversion or subrange projection is permitted at this boundary.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn original_verify_gdn_weights<'a>(
&'a self,
pub(in super::super::super) fn original_verify_gdn_weights(
&self,
binding: &ModelBinding,
) -> Result<[OriginalVerifyGdnWeights<'a, 'ctx>; 36]> {
) -> Result<[OriginalVerifyGdnWeights<'ctx>; 36]> {
self.check(binding)?;
let mut retained = Vec::new();
retained.try_reserve_exact(36).map_err(|_| Error::InputAllocation)?;
@@ -112,27 +120,23 @@ impl<'ctx> DenseWeightCache<'ctx> {
retained.try_into().map_err(|_| Error::InvalidDimension)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn original_verify_gdn_layer<'a>(
&'a self,
binding: &ModelBinding,
index: u32,
) -> Result<OriginalVerifyGdnWeights<'a, 'ctx>> {
fn original_verify_gdn_layer(&self, binding: &ModelBinding, index: u32) -> Result<OriginalVerifyGdnWeights<'ctx>> {
let resident = self.gdn(binding, index)?;
let (alpha, alpha_kind) = self.gdn_matrix(resident, GdnMatrixRole::Alpha)?;
let (beta, beta_kind) = self.gdn_matrix(resident, GdnMatrixRole::Beta)?;
let (alpha, alpha_kind) = self.gdn_matrix_slot(resident, GdnMatrixRole::Alpha)?;
let (beta, beta_kind) = self.gdn_matrix_slot(resident, GdnMatrixRole::Beta)?;
if alpha_kind != GdnMatrixKind::Bf16 || beta_kind != GdnMatrixKind::Bf16 {
return Err(Error::Unsupported(super::super::super::contract::Stage::Gdn));
}
let aux = self.gdn_aux(resident)?;
Ok(OriginalVerifyGdnWeights { conv: aux[0], alpha, beta, dt: aux[1], a: aux[2], norm: aux[3] })
let [conv, dt, a, norm] = self.handles(self.gdn_aux_slots(resident)?)?;
Ok(OriginalVerifyGdnWeights { conv, alpha: self.handle(alpha)?, beta: self.handle(beta)?, dt, a, norm })
}
/// The twelve QSA layers' indexer K norm gamma (128 F32 each), in layer order: the verifier's
/// indexer append re-normalizes each raw index key with exactly these cache allocations.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn original_verify_qsa_gamma<'a>(
&'a self,
pub(in super::super::super) fn original_verify_qsa_gamma(
&self,
binding: &ModelBinding,
) -> Result<[&'a DeviceBuffer<'ctx>; 12]> {
) -> Result<[DeviceRef<'ctx>; 12]> {
self.check(binding)?;
let mut gamma = Vec::new();
gamma.try_reserve_exact(12).map_err(|_| Error::InputAllocation)?;
@@ -142,20 +146,16 @@ impl<'ctx> DenseWeightCache<'ctx> {
}
let resident = self.qsa(binding, layer.index())?;
// norms: [q, k, index q, index k]
gamma.push(self.qsa_norms(resident)?[3]);
gamma.push(self.handle(self.qsa_norm_slots(resident)?[3])?);
}
gamma.try_into().map_err(|_| Error::InvalidDimension)
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn verify_gdn_projections<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyGdnProjections<'a, 'ctx>> {
fn verify_gdn_projections(&self, binding: &ModelBinding, layer: u32) -> Result<OriginalVerifyGdnProjections<'ctx>> {
let resident = self.gdn(binding, layer)?;
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'a, 'ctx>> {
let (buffer, kind) = self.gdn_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: gdn_native_type(kind)?, buffer })
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'ctx>> {
let (slot, kind) = self.gdn_matrix_slot(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: gdn_native_type(kind)?, buffer: self.handle(slot)? })
};
Ok(OriginalVerifyGdnProjections {
qkv: matrix(GdnMatrixRole::Qkv)?,
@@ -164,15 +164,11 @@ impl<'ctx> DenseWeightCache<'ctx> {
})
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn verify_qsa_projections<'a>(
&'a self,
binding: &ModelBinding,
layer: u32,
) -> Result<OriginalVerifyQsaProjections<'a, 'ctx>> {
fn verify_qsa_projections(&self, binding: &ModelBinding, layer: u32) -> Result<OriginalVerifyQsaProjections<'ctx>> {
let resident = self.qsa(binding, layer)?;
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'a, 'ctx>> {
let (buffer, kind) = self.qsa_matrix(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: qsa_native_type(kind)?, buffer })
let matrix = |role| -> Result<OriginalVerifyNativeMatrix<'ctx>> {
let (slot, kind) = self.qsa_matrix_slot(resident, role)?;
Ok(OriginalVerifyNativeMatrix { kind: qsa_native_type(kind)?, buffer: self.handle(slot)? })
};
Ok(OriginalVerifyQsaProjections {
k: matrix(QsaMatrixRole::K)?,
@@ -182,14 +178,14 @@ impl<'ctx> DenseWeightCache<'ctx> {
})
}
/// 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.
/// layers for the literal Verifier window: shared handles to the cache's own allocations.
/// A matrix the cache holds as BF16 has no native MMVQ owner and is refused.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in super::super::super) fn original_verify_projections<'a>(
&'a self,
pub(in super::super::super) fn original_verify_projections(
&self,
binding: &ModelBinding,
geometry: &OriginalVerifyGeometry,
) -> Result<OriginalVerifyProjBinding<'a, 'ctx>> {
) -> Result<OriginalVerifyProjBinding<'ctx>> {
self.check(binding)?;
let mut gdn = Vec::new();
let mut qsa = Vec::new();
@@ -208,6 +204,15 @@ impl<'ctx> DenseWeightCache<'ctx> {
entry: &QsaResident,
role: QsaMatrixRole,
) -> Result<(&DeviceBuffer<'ctx>, QsaMatrixKind)> {
let (index, kind) = self.qsa_matrix_slot(entry, role)?;
Ok((self.buffer(index)?, kind))
}
/// The cache slot and storage kind of one QSA matrix.
pub(in super::super::super) fn qsa_matrix_slot(
&self,
entry: &QsaResident,
role: QsaMatrixRole,
) -> Result<(usize, QsaMatrixKind)> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
@@ -219,19 +224,18 @@ impl<'ctx> DenseWeightCache<'ctx> {
QsaMatrixRole::IndexK => 4,
QsaMatrixRole::Out => 5,
};
let (index, kind) = entry.matrices[i];
Ok((self.buffer(index)?, kind))
Ok(entry.matrices[i])
}
pub(in super::super::super) fn qsa_norms(&self, entry: &QsaResident) -> Result<[&DeviceBuffer<'ctx>; 4]> {
let slots = self.qsa_norm_slots(entry)?;
Ok([self.buffer(slots[0])?, self.buffer(slots[1])?, self.buffer(slots[2])?, self.buffer(slots[3])?])
}
/// The cache slots of a QSA layer's q, k, indexer-q and indexer-k norms (`qsa_norms` order).
pub(in super::super::super) fn qsa_norm_slots(&self, entry: &QsaResident) -> Result<[usize; 4]> {
if !Rc::ptr_eq(&self.owner, &entry.owner) {
return Err(Error::IdentityMismatch);
}
Ok([
self.buffer(entry.norms[0])?,
self.buffer(entry.norms[1])?,
self.buffer(entry.norms[2])?,
self.buffer(entry.norms[3])?,
])
Ok(entry.norms)
}
}
@@ -264,6 +264,12 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
pub(in crate::qwen_forward) fn mtp_release_verifier(&mut self, binding: &ModelBinding) -> Result<()> {
self.mtp_actor(binding)?.release_verifier_bindings().map_err(driver_error)
}
/// End of a request whose verifier bank is kept for the next one (`LELEKA_DECODE_GRAPH_REUSE`): the drafter keeps
/// its programs bound to the bank and forgets what belongs to the request. See
/// `OriginalMtpActor::end_request_keep_bank`.
pub(in crate::qwen_forward) fn mtp_end_request_keep_bank(&mut self, binding: &ModelBinding) -> Result<()> {
self.mtp_actor(binding)?.end_request_keep_bank().map_err(driver_error)
}
/// `MtpDrafter::device()`.
pub(in crate::qwen_forward) fn mtp_device(&mut self, binding: &ModelBinding) -> Result<i32> {
Ok(self.mtp_actor(binding)?.device())
@@ -6,7 +6,7 @@ use crate::model_binding::qwen4exp_input::{
MtpRole,
};
use leleka_cuda_driver::{
Context, DeviceBuffer, MmqFormat, MmqWeights, MmqWorkspace, MtpInputWorkspace, RoutedFiniteStage,
Context, DeviceBuffer, DeviceRef, MmqFormat, MmqWeights, MmqWorkspace, MtpInputWorkspace, RoutedFiniteStage,
RoutedGroupWorkspace, RoutedStageFiniteGuard,
};
use std::cell::{Cell, RefCell};
@@ -76,7 +76,9 @@ pub(crate) struct WeightCacheCounters {
// One allocation per actual descriptor. Dual storage is shared by native and
// experimental MMQ consumers; the native logical extent never exposes a view.
enum EncodedWeight<'ctx> {
Raw(DeviceBuffer<'ctx>),
/// A shared handle: the verify window's assembly holds the shared-expert and router tensors in place across
/// requests, so an evicted entry's memory outlives the cache's book while a held assembly still has it.
Raw(DeviceRef<'ctx>),
Dual(MmqFormat, MmqWeights<'ctx>),
}
#[derive(Clone, Copy)]
@@ -170,9 +172,9 @@ pub(crate) struct MoeWeightCache<'ctx> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
adaptive_shared: Option<cache_profile::SharedPermanentPool>,
age: u64,
/// The entries a held decode graph set reads in place (`window_pins`), and how many raw entries were evicted.
window_pins: std::collections::HashSet<MoeWeightDescriptor>,
raw_evictions: u64,
/// The entries a held decode graph set reads in place, and how many of them were freed (`window_pins.rs`).
window_pins: RefCell<window_pins::WindowPins>,
raw_evictions: Cell<u64>,
failed: Cell<bool>,
bank: Option<Rc<DeviceBuffer<'ctx>>>,
dense: Vec<Dense<'ctx>>,
@@ -142,7 +142,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
charged_bytes: usize,
) -> Result<EncodedWeight<'ctx>> {
let Some((format, expected)) = dual else {
return Ok(EncodedWeight::Raw(self.upload(&bytes)?));
return Ok(EncodedWeight::Raw(DeviceRef::from_buffer(self.upload(&bytes)?)));
};
let built = self.context.mmq_weights(format, &bytes);
self.admit_dual_weight(built, (format, expected), (bytes.len(), charged_bytes))
@@ -157,7 +157,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
charged_bytes: usize,
) -> Result<EncodedWeight<'ctx>> {
let Some((format, expected)) = dual else {
return Ok(EncodedWeight::Raw(self.upload(&bytes)?));
return Ok(EncodedWeight::Raw(DeviceRef::from_buffer(self.upload(&bytes)?)));
};
let raw_bytes = bytes.len();
let shape = gate_up_shape(key)?;
@@ -31,7 +31,7 @@ macro_rules! blank_cache {
adaptive_shared: None,
age: 0,
window_pins: Default::default(),
raw_evictions: 0,
raw_evictions: Cell::new(0),
failed: Cell::new(false),
bank: None,
dense: Vec::new(),
@@ -139,7 +139,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
self.routed_workspace.as_ref().map(Rc::clone).ok_or(Error::IdentityMismatch)
}
pub(in super::super) fn is_pinned(&self, key: MoeWeightDescriptor) -> bool {
if self.window_pins.contains(&key) {
if self.window_pinned(&key) {
return true;
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -279,7 +279,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
let key = self.eviction_key(protected)?;
self.remove_lru_entry(key)?;
let entry = self.main.remove(&key).ok_or(Error::IdentityMismatch)?;
self.note_eviction(&entry.weight);
self.note_eviction(&key);
if entry.weight.close().is_err() {
self.failed.set(true);
return Err(Error::CudaExecution);

Some files were not shown because too many files have changed in this diff Show More