From 5487bb6db25a719ee7b54787e9217af34c83e155 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 10:37:20 +0100 Subject: [PATCH 1/2] STRA-338 size4 s06: wrap wide lines, split offending tests and the selected-KV GPU proof, launch_label --- .../src/qsa_prompt_attention_ffi.rs | 3 +- .../impl_poolpresence.rs | 6 +- .../q_prescale_fn.rs | 3 +- .../src/qsa_prompt_attention_select/tests.rs | 14 + .../src/qsa_prompt_device/impl_context.rs | 3 +- .../impl_originalqsapromptdevice_3.rs | 3 +- .../impl_qsapromptindexworkspace_4.rs | 3 +- .../impl_drop_for_qsapromptkv.rs | 3 +- .../src/qsa_prompt_kv/offsets_fn.rs | 3 +- .../impl_originalqsapromptdevice.rs | 16 +- .../impl_originalqsaresidentselection.rs | 3 +- .../src/qsa_resident_index/image_bytes_fn.rs | 3 +- .../impl_originalqsaresidentindex_2.rs | 15 +- .../impl_qsapromptindexworkspace_2.rs | 13 +- .../src/qsa_resident_transfer/enabled.rs | 14 +- .../cuda-driver/src/qsa_resident_transport.rs | 12 +- crates/cuda-driver/src/qsa_selected_kv.rs | 296 +------------ .../impl_drop_for_qsaselectedkvworkspace.rs | 3 +- .../impl_qsaselectedkvworkspace.rs | 3 +- .../qsa_selected_kv/selected_kv_installed.rs | 395 ++++++++++++++++++ .../src/qsa_verification_commit.rs | 3 +- .../impl_originalverifyqsajournal_2.rs | 13 +- .../impl_originalverifyqsajournal_3.rs | 28 +- .../src/qwen_dispatch/impl_cache.rs | 3 +- .../qwen_dispatch/prepare_gr_read_set_fn.rs | 3 +- .../tests/full_s2_bank_extent.rs | 167 +++++--- .../tests/moe_new_preflight_requires_exact.rs | 80 ++-- .../tests/qsa_new_slots_keep_atomic.rs | 274 ++++++------ .../tests/qwen_actual_owner_poison_missing.rs | 229 +++++----- .../qwen_attempted_launch_always_syncs.rs | 135 +++--- .../src/qwen_ffi/bf16_receipt_types.rs | 47 ++- .../src/qwen_ffi/impl_operation_2.rs | 3 +- .../src/qwen_ffi/mtp_extended_assets_types.rs | 13 +- .../src/qwen_ffi/mtp_s2_full_layout_fn.rs | 3 +- crates/cuda-driver/src/qwen_ffi/n_types.rs | 3 +- .../qwen_ffi/qsa_attention_receipt_types.rs | 30 +- 36 files changed, 1066 insertions(+), 782 deletions(-) create mode 100644 crates/cuda-driver/src/qsa_selected_kv/selected_kv_installed.rs diff --git a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs index 81518f9a..29c68327 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_ffi.rs @@ -195,7 +195,8 @@ mod enabled { } } } - /// The current Context's compute capability `[major, minor, opt-in shared]`; it must be sm_80+ with 45584 B of shared. + /// The current Context's compute capability `[major, minor, opt-in shared]`; it must be sm_80+ with 45584 B of + /// shared. fn device_caps(dev: Device, attr: Attr) -> Result<[u32; 3]> { let mut device = 0; check("cuCtxGetDevice", unsafe { dev(&mut device) })?; diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs index 72e835be..e9c1c81c 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/impl_poolpresence.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl PoolPresence, impl Shapes, impl SelectSwitches, impl PromptAttnKernel, fn align_up, fn smem_bytes .... +//! Moved out of the parent module by STRA-338: impl PoolPresence, impl Shapes, impl SelectSwitches, impl +//! PromptAttnKernel, fn align_up, fn smem_bytes .... #[allow(unused_imports)] use super::*; @@ -160,7 +161,8 @@ fn pools_admitted(pools: &PoolPresence, shapes: &Shapes, cap: i64, have_ids_and_ || !pools.page_table) } -/// The kernel family of the pools present (`None`: a pool or scale it needs is missing); Turing and the debug arm take v1. +/// The kernel family of the pools present (`None`: a pool or scale it needs is missing); Turing and the debug arm take +/// v1. fn kernel_for_pools(pools: &PoolPresence, switches: &SelectSwitches, turing: bool) -> Option { if pools.k_q && pools.v_q4 { return pools.k_scale.then_some(PromptAttnKernel::HybridK8V4); diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs index daff9322..b2cb306c 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/q_prescale_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn q_prescale, fn pow2f, fn f16_hi_lo, fn f16_round, fn f32_to_f16, fn f16_to_f32. +//! Moved out of the parent module by STRA-338: fn q_prescale, fn pow2f, fn f16_hi_lo, fn f16_round, fn f32_to_f16, fn +//! f16_to_f32. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs index 3d082e1b..56fccacc 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention_select/tests.rs @@ -28,6 +28,12 @@ fn smem_sizes_match_the_compiled_structs() { #[test] fn selection_follows_the_original_decision_tree() { + assert_architecture_arms(); + assert_pool_arms(); + assert_geometry_and_shared_arms(); +} + +fn assert_architecture_arms() { use PromptAttnKernel::*; assert_eq!(pick(PoolPresence::int8(), BLACKWELL, NONE), Some(Int8V2)); assert_eq!(pick(PoolPresence::int8(), AMPERE, NONE), Some(Int8V2)); @@ -41,6 +47,10 @@ fn selection_follows_the_original_decision_tree() { assert_eq!(pick(PoolPresence::int8(), BLACKWELL, warp), Some(Int8V1)); // sm_70 has no m16n8k8: refused assert_eq!(pick(PoolPresence::int8(), VOLTA, NONE), None); +} + +fn assert_pool_arms() { + use PromptAttnKernel::*; assert_eq!(pick(PoolPresence::fp16(), BLACKWELL, NONE), Some(Fp16)); assert_eq!(pick(PoolPresence::hybrid_k8v4(), BLACKWELL, NONE), Some(HybridK8V4)); assert_eq!(pick(PoolPresence::hybrid_k8v4(), TURING, NONE), Some(HybridK8V4)); @@ -57,6 +67,10 @@ fn selection_follows_the_original_decision_tree() { ] { assert_eq!(pick(broken, BLACKWELL, NONE), None, "{broken:?}"); } +} + +fn assert_geometry_and_shared_arms() { + use PromptAttnKernel::*; // geometry and selection arrays let bad = Shapes { n_head: 24, n_head_kv: 4, head_dim: 256 }; assert_eq!(select(PoolPresence::int8(), bad, 2051, true, BLACKWELL, NONE), None); diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs index d41a63af..db11e051 100644 --- a/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_context.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Context, fn native_block, fn native_entry, fn arena_span, fn common. +//! Moved out of the parent module by STRA-338: impl Context, fn native_block, fn native_entry, fn arena_span, fn +//! common. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs index 835c267d..933be999 100644 --- a/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs +++ b/crates/cuda-driver/src/qsa_prompt_device/impl_originalqsapromptdevice_3.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice (3), impl Drop_for_OriginalQsaPromptDevice, impl OriginalQsaDeviceSelection. +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice (3), impl Drop_for_OriginalQsaPromptDevice, +//! impl OriginalQsaDeviceSelection. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs index 18af326e..9ad2f2fa 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (4), impl Drop_for_QsaPromptIndexWorkspace, impl QsaPromptIndexPrefix, impl QsaPromptIndexState, impl QsaPromptSelection, impl QsaPromptSelection .... +//! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (4), impl Drop_for_QsaPromptIndexWorkspace, +//! impl QsaPromptIndexPrefix, impl QsaPromptIndexState, impl QsaPromptSelection, impl QsaPromptSelection .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs index 15db40a7..b423c0e0 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/impl_drop_for_qsapromptkv.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Drop_for_QsaPromptKv, impl QsaPromptStage, impl Drop_for_QsaPromptStage, fn read_range. +//! Moved out of the parent module by STRA-338: impl Drop_for_QsaPromptKv, impl QsaPromptStage, impl +//! Drop_for_QsaPromptStage, fn read_range. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs b/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs index 2d616cff..6fb06730 100644 --- a/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs +++ b/crates/cuda-driver/src/qsa_prompt_kv/offsets_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn offsets, fn stage_runs, fn resident_runs, impl QsaKvInputs, impl QsaKvOwnerId, impl QsaKvSnapshot .... +//! Moved out of the parent module by STRA-338: fn offsets, fn stage_runs, fn resident_runs, impl QsaKvInputs, impl +//! QsaKvOwnerId, impl QsaKvSnapshot .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs index f43e0506..ce4de0e4 100644 --- a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice, impl OriginalQsaResidentSelection, fn kv_stage_spans_of. +//! Moved out of the parent module by STRA-338: impl OriginalQsaPromptDevice, impl OriginalQsaResidentSelection, fn +//! kv_stage_spans_of. #[allow(unused_imports)] use super::*; @@ -61,8 +62,8 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { let batch = OriginalQsaIndexBatch { owner: resident, start, raw: Some(raw_rows), gamma, rows: t }; Ok(OriginalQsaResidentSelection { owner: self, read, p0, batch }) } - /// The first position `p`, its `u32` form and the row count `t` of a resident chunk, once the index, the chunk and the - /// device budget admit it. + /// The first position `p`, its `u32` form and the row count `t` of a resident chunk, once the index, the chunk and + /// the device budget admit it. fn resident_bounds( &self, read: &OriginalDeviceGrRead<'_, '_, 'ctx>, @@ -147,8 +148,8 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { t * 16, ) } - /// Run the index program, then copy the raw rows into the retained buffer. A failure of either puts the private image - /// back to `start`. + /// Run the index program, then copy the raw rows into the retained buffer. A failure of either puts the private + /// image back to `start`. fn run_resident( &mut self, resident: &mut OriginalQsaResidentIndex<'ctx>, @@ -235,8 +236,9 @@ impl<'lease, 'index, 'weights, 'arena, 'loan, 'ctx> kv_stage_spans_of(&self.read, self.rows()) } } -/// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`, `kv_v_scale`), each checked against the layer's -/// working spans. The stage is the same four arena spans for every QSA layer of a chunk, so they are known before the layer's indexer runs. +/// The four KV stage spans of a read lease for `rows` rows (the arena's `kv_k_q`, `kv_v_q`, `kv_k_scale`, +/// `kv_v_scale`), each checked against the layer's working spans. The stage is the same four arena spans for every QSA +/// layer of a chunk, so they are known before the layer's indexer runs. pub(crate) fn kv_stage_spans_of( read: &OriginalDeviceGrRead<'_, '_, '_>, rows: usize, diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs index 03dffc7e..cbac41b1 100644 --- a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsaresidentselection.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentSelection, impl Context, impl OriginalQsaResidentPromptDevice. +//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentSelection, impl Context, impl +//! OriginalQsaResidentPromptDevice. use super::impl_originalqsapromptdevice::lap; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs b/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs index daa6ce88..85b58f1e 100644 --- a/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs +++ b/crates/cuda-driver/src/qsa_resident_index/image_bytes_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn image_bytes, impl Drop_for_Saved, impl OriginalQsaIndexCheckpoint, impl Context. +//! Moved out of the parent module by STRA-338: fn image_bytes, impl Drop_for_Saved, impl OriginalQsaIndexCheckpoint, +//! impl Context. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs index fa4420ba..70f1f956 100644 --- a/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs +++ b/crates/cuda-driver/src/qsa_resident_index/impl_originalqsaresidentindex_2.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentIndex (2), impl OriginalQsaResidentIndex, impl Drop_for_OriginalQsaResidentIndex, impl OriginalQsaResidentIndex. +//! Moved out of the parent module by STRA-338: impl OriginalQsaResidentIndex (2), impl OriginalQsaResidentIndex, impl +//! Drop_for_OriginalQsaResidentIndex, impl OriginalQsaResidentIndex. use super::impl_originalqsaresidentindex::poison_unless_host_allocation; #[allow(unused_imports)] @@ -138,9 +139,10 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { result } } -/// The part of the image a verifier window can disturb and the accepted-prefix graph does not put back (a checkpoint's four pieces): -/// the tail, `dead`, the pooled row of the block in progress (`end / 4`, the spare) and the block position. Read before a window -/// and written back to undo it (`OriginalVerifyQsaJournal::discard_window`); the device must be idle. +/// The part of the image a verifier window can disturb and the accepted-prefix graph does not put back (a checkpoint's +/// four pieces): the tail, `dead`, the pooled row of the block in progress (`end / 4`, the spare) and the block +/// position. Read before a window and written back to undo it (`OriginalVerifyQsaJournal::discard_window`); the device +/// must be idle. impl<'ctx> OriginalQsaResidentIndex<'ctx> { pub(crate) const WINDOW_STATE_BYTES: usize = CHECKPOINT_BYTES; pub(crate) fn read_window_state(&self, out: &mut [u8]) -> Result<()> { @@ -211,8 +213,9 @@ impl<'ctx> OriginalQsaResidentIndex<'ctx> { s.0.bytes.copy_to_range(0, &mut out)?; Ok(out) } - /// Write the parked spans `(first_row, bytes)` and the tail `tail` (exported at position `end`), set the image's end - /// and return a fresh checkpoint of it. The rows below `end / 4` that no span names must already hold the prefix. + /// Write the parked spans `(first_row, bytes)` and the tail `tail` (exported at position `end`), set the image's + /// end and return a fresh checkpoint of it. The rows below `end / 4` that no span names must already hold the + /// prefix. pub fn import( &mut self, ws: &mut NativeBatchWorkspace<'ctx>, diff --git a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs index cdff4dc6..0d5859b3 100644 --- a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs +++ b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs @@ -146,7 +146,8 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let pop = g.finish(); self.settle_replay(ws, (op, sync, read, pop), work) } - /// Poison the context when any step of the replay failed; the launches are leaked when the device may still read them. + /// Poison the context when any step of the replay failed; the launches are leaked when the device may still read + /// them. fn settle_replay( &mut self, ws: &mut NativeBatchWorkspace<'ctx>, @@ -192,6 +193,13 @@ pub(super) fn launch_label(launch: &Launch) -> (usize, &'static str) { Launch::Split(_) => (6, "split"), Launch::Scan(_) => (7, "finite scan"), Launch::ScoreScan(_) => (8, "score scan"), + later => launch_label_later(later), + } +} + +/// The labels of the launches after the eighth; every earlier variant is answered by `launch_label`. +fn launch_label_later(launch: &Launch) -> (usize, &'static str) { + match launch { Launch::Round(_) => (9, "round"), Launch::Tc { .. } => (10, "tc scores"), Launch::ScoreTail(_) => (11, "score tail"), @@ -199,6 +207,7 @@ pub(super) fn launch_label(launch: &Launch) -> (usize, &'static str) { Launch::DecodeAppend => (13, "decode append"), Launch::DecodeScores => (14, "decode scores"), Launch::DecodeRms(_) => (15, "decode rms"), - Launch::DecodeRope(_) => (16, "decode rope"), + // the last variant; the first eight never reach this function + _ => (16, "decode rope"), } } diff --git a/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs index 54ef4853..e4be2f1b 100644 --- a/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs +++ b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs @@ -108,9 +108,10 @@ impl Transfer { pub(crate) fn is_pending(&self) -> bool { self.pending.get() } - /// Start `ranges` on a side stream that first waits for everything queued on the compute stream so far, without a host wait: the - /// copy then runs under the compute stream's next kernels. `wait_pending` makes the compute stream wait for its end. Row "256k prefill - /// gap" (docs/upstream-port-plan.md): the QSA layer's prior-KV prefix copy overlapped with the layer's own projections and indexer. + /// Start `ranges` on a side stream that first waits for everything queued on the compute stream so far, without a + /// host wait: the copy then runs under the compute stream's next kernels. `wait_pending` makes the compute stream + /// wait for its end. Row "256k prefill gap" (docs/upstream-port-plan.md): the QSA layer's prior-KV prefix copy + /// overlapped with the layer's own projections and indexer. pub(crate) fn begin<'ctx>( &self, c: &'ctx Context<'ctx>, @@ -130,7 +131,8 @@ impl Transfer { } combine(op, pop) } - /// The side symbols, once the workspace, the context and the ranges admit a side copy; a still pending one is waited for. + /// The side symbols, once the workspace, the context and the ranges admit a side copy; a still pending one is + /// waited for. fn begin_preflight<'ctx>( &self, c: &'ctx Context<'ctx>, @@ -293,8 +295,8 @@ impl Transfer { combine(combine(op, sync), pop) } } -// SAFETY (Drop): `copy` is never called after drop; libcuda itself stays loaded (the driver holds its own reference), and -// every `Transfer::copy*` drains its stream before returning, so no enqueued copy outlives the dlclose. +// SAFETY (Drop): `copy` is never called after drop; libcuda itself stays loaded (the driver holds its own reference), +// and every `Transfer::copy*` drains its stream before returning, so no enqueued copy outlives the dlclose. impl Drop for Transfer { fn drop(&mut self) { // the side copy is waited for by `cancel` before a context goes away; here only the handles are diff --git a/crates/cuda-driver/src/qsa_resident_transport.rs b/crates/cuda-driver/src/qsa_resident_transport.rs index 0c9a29fd..7e6c80c8 100644 --- a/crates/cuda-driver/src/qsa_resident_transport.rs +++ b/crates/cuda-driver/src/qsa_resident_transport.rs @@ -161,9 +161,9 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { } Ok(ranges) } - /// `LELEKA_PREFILL_QSA_PREFETCH` (docs/upstream-port-plan.md, 256k prefill gap): the prior-KV prefix copy of a QSA layer starts on a side - /// stream at the beginning of the layer, under its projections and indexer, instead of between the indexer and the attention. - /// `1` on, `0` off; unset: `QSA_PREFETCH_DEFAULT`. A per-arm override wins. + /// `LELEKA_PREFILL_QSA_PREFETCH` (docs/upstream-port-plan.md, 256k prefill gap): the prior-KV prefix copy of a QSA + /// layer starts on a side stream at the beginning of the layer, under its projections and indexer, instead of + /// between the indexer and the attention. `1` on, `0` off; unset: `QSA_PREFETCH_DEFAULT`. A per-arm override wins. pub fn prefetch_enabled() -> bool { match PREFETCH_OVERRIDE.load(std::sync::atomic::Ordering::Relaxed) { 0 => return false, @@ -173,9 +173,9 @@ impl<'ctx> OriginalQsaResidentTransport<'ctx> { static ON: std::sync::OnceLock = std::sync::OnceLock::new(); *ON.get_or_init(|| std::env::var("LELEKA_PREFILL_QSA_PREFETCH").map_or(QSA_PREFETCH_DEFAULT, |v| v != "0")) } - /// Start the prefix copy of the layer that is about to run (its stage spans and host mirror are known before the indexer runs). The - /// layer's `copy_prefix` then only orders the compute stream after it. Falls back to nothing (the blocking copy runs later) when the - /// driver cannot overlap or the switch is off. + /// Start the prefix copy of the layer that is about to run (its stage spans and host mirror are known before the + /// indexer runs). The layer's `copy_prefix` then only orders the compute stream after it. Falls back to nothing + /// (the blocking copy runs later) when the driver cannot overlap or the switch is off. pub(crate) fn begin_prefix( &mut self, w: &mut NativeBatchWorkspace<'ctx>, diff --git a/crates/cuda-driver/src/qsa_selected_kv.rs b/crates/cuda-driver/src/qsa_selected_kv.rs index aa51503a..87ecc972 100644 --- a/crates/cuda-driver/src/qsa_selected_kv.rs +++ b/crates/cuda-driver/src/qsa_selected_kv.rs @@ -37,301 +37,7 @@ pub struct QsaSelectedKvProducts<'lease, 'ctx> { } #[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] -mod selected_kv_installed { - use super::*; - struct RestoreHandle<'a, 'ctx> { - buffer: &'a mut DeviceBuffer<'ctx>, - previous: Option, - } - impl Drop for RestoreHandle<'_, '_> { - fn drop(&mut self) { - self.buffer.handle = self.previous; - } - } - fn packed(order: &[usize], seed: usize) -> Vec { - order - .iter() - .flat_map(|&cell| { - (0..512).flat_map(move |i| { - let bits = match (i + cell + seed) % 5 { - 0 => 0x8000u16, - 1 => 0x0000, - 2 => 0x3000, - 3 => 0xb000, - _ => 0x3400, - }; - bits.to_le_bytes() - }) - }) - .collect() - } - fn upload<'ctx>(context: &'ctx Context<'ctx>, bytes: &[u8]) -> Result> { - let mut buffer = context.allocate(bytes.len())?; - if let Err(error) = buffer.copy_from(bytes) { - return combine(Err(error), buffer.release()); - } - Ok(buffer) - } - fn read(buffer: &DeviceBuffer<'_>, bytes: usize) -> Result> { - let mut output = vec![0; bytes]; - buffer.copy_to(&mut output)?; - Ok(output) - } - #[test] - #[ignore = "Root only; exact new asset, one lossless changed transport proof"] - fn original_first_selected_kv_bytes_attention_reorder_refusals_cleanup() { - if std::env::var("LELEKA_STRA172_RUN_QSA_SELECTED_KV").as_deref() != Ok("yes") { - return; - } - let driver = Driver::load().expect("actual CUDA library"); - let device = driver.device(0).expect("actual device"); - let context = device.create_context(256 * 1024 * 1024).expect("bounded actual context"); - let mut buffers = Vec::new(); - let mut workspace = None; - let mut differences = 0usize; - let mut compared = 0usize; - let mut guards = 0usize; - let operation: Result<()> = (|| { - let query: Vec = (0..6144) - .flat_map(|i| if i % 3 == 0 { 0.125f32.to_le_bytes() } else { (-0.125f32).to_le_bytes() }) - .collect(); - buffers.push(upload(&context, &query)?); - buffers.push(context.allocate(24576)?); - buffers.push(context.allocate(24576)?); - let small = device.create_context(TOTAL + RESERVE - 1)?; - let refused = small.qsa_selected_kv_workspace(); - if !matches!(refused, Err(Error::BudgetExceeded)) { - return Err(Error::InvalidDriverValue("QSA budget guard")); - } - drop(refused); - let small_allocated = small.allocated_bytes(); - small.close()?; - if small_allocated != 0 { - return Err(Error::InvalidDriverValue("QSA refused budget allocation")); - } - guards += 1; - // Original attention FIRST, exact independently packed full-cell order. - for (layer, misses, selected, seed) in [ - (0u32, vec![0u32, 17, 2050], vec![2050u32, 0, 17], 0usize), - (0, vec![], vec![17, 2050, 0], 0), - (0, vec![17], vec![17, 0, 2050], 1), - (11, vec![0, 17, 2050], vec![0, 17, 2050], 2), - ] { - let ids: Vec = selected.iter().map(|n| *n as usize).collect(); - let mut keys = packed(&ids, 0); - let mut values = packed(&ids, 0); - for (j, &slot) in selected.iter().enumerate() { - let old_seed = if layer == 11 { - 2 - } else if slot == 17 && seed == 1 { - 1 - } else { - 0 - }; - keys[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed)); - values[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed + 7)); - } - let key = upload(&context, &keys)?; - let value = upload(&context, &values)?; - let (query_owner, output_owner) = buffers.split_at_mut(1); - let reference = - context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], selected.len() as u32); - let cleanup = combine(key.release(), value.release()); - combine(reference, cleanup)?; - let expected = read(&buffers[1], 24576)?; - if workspace.is_none() { - workspace = Some(context.qsa_selected_kv_workspace()?); - } - let owner = workspace.as_mut().ok_or(Error::ContextPoisoned)?; - let miss_ids: Vec = misses.iter().map(|n| *n as usize).collect(); - let (miss_k, miss_v) = (packed(&miss_ids, seed), packed(&miss_ids, seed + 7)); - let products = owner.prepare(layer, &misses, &miss_k, &miss_v, &selected)?; - let h = products.workspace.handles()?; - for (index, expected) in [(2, &keys), (3, &values)] { - let mut actual = vec![0; expected.len()]; - let prefix = h[index].checked_subspan(PACKED, 0, actual.len())?; - let guard = context.enter()?; - let copy = context.driver.api.copy_to(prefix, &mut actual); - let sync = context.driver.api.synchronize(); - let pop = guard.finish(); - if sync.is_err() || pop.is_err() { - context.poisoned.set(true); - std::mem::forget(actual); - return combine(combine(copy, sync), pop); - } - combine(combine(copy, sync), pop)?; - differences += actual.iter().zip(expected).filter(|(a, b)| a != b).count(); - compared += expected.len(); - } - // Actual independent query/output owners, no forged product factory. - let (left, right) = buffers.split_at_mut(2); - products.attend(&left[0], &mut right[0])?; - let prior_output = read(&right[0], 24576)?; - let mut wrong = context.allocate(4)?; - let refused = products.attend(&left[0], &mut wrong); - let release = wrong.release(); - if !matches!(refused, Err(Error::InvalidQwenShape)) { - return Err(Error::InvalidDriverValue("QSA shape guard")); - } - release?; - guards += 1; - { - let previous = right[0].handle; - let alias = RestoreHandle { buffer: &mut right[0], previous }; - alias.buffer.handle = left[0].handle; - if !matches!(products.attend(&left[0], &mut *alias.buffer), Err(Error::OutputAliasesInput)) { - return Err(Error::InvalidDriverValue("QSA alias guard")); - } - guards += 1; - } - let foreign = device.create_context(1024 * 1024)?; - let foreign_query = upload(&foreign, &query)?; - let refusal = products.attend(&foreign_query, &mut right[0]); - let released = foreign_query.release(); - let allocated = foreign.allocated_bytes(); - let closed = foreign.close(); - if !matches!(refusal, Err(Error::ContextMismatch)) || allocated != 0 { - return Err(Error::InvalidDriverValue("QSA foreign guard")); - } - released?; - closed?; - guards += 1; - let actual = read(&right[0], 24576)?; - if actual != prior_output { - return Err(Error::InvalidDriverValue("QSA refused output mutation")); - } - if expected - .as_chunks::<4>() - .0 - .iter() - .chain(actual.as_chunks::<4>().0.iter()) - .any(|b| !f32::from_le_bytes(*b).is_finite()) - { - return Err(Error::InvalidDriverValue("QSA full output finite")); - } - differences += - actual.as_chunks::<4>().0.iter().zip(expected.as_chunks::<4>().0).filter(|(a, b)| a != b).count(); - compared += 6144; - drop(products); - let generation = owner.generation; - let charged = context.allocated_bytes(); - for refused in [ - owner.prepare(12, &[], &[], &[], &[0]).is_err(), - owner.prepare(layer, &[], &[], &[], &[0, 0]).is_err(), - owner.prepare(layer, &[0, 0], &vec![0; 2048], &vec![0; 2048], &[0]).is_err(), - owner.prepare(layer, &[], &[], &[], &[2051]).is_err(), - owner.prepare(layer, &[], &[], &[], &[18]).is_err(), - owner.prepare(layer, &[0], &vec![0; 1023], &vec![0; 1023], &[0]).is_err(), - ] { - if !refused { - return Err(Error::InvalidDriverValue("QSA guard accepted")); - } - guards += 1; - } - let mut nonfinite = vec![0; 1024]; - nonfinite[510..512].copy_from_slice(&0x7e00u16.to_le_bytes()); - if owner.prepare(layer, &[0], &nonfinite, &vec![0; 1024], &[0]).is_ok() { - return Err(Error::InvalidDriverValue("QSA nonfinite accepted")); - } - guards += 1; - if owner.generation != generation || context.allocated_bytes() != charged || owner.is_failed() { - return Err(Error::InvalidDriverValue("QSA prewrite mutation")); - } - } - // Max-width phase runs AFTER all uninitialized-slot refusals above. - // Original full-width attention FIRST with independent reverse order. - let misses: Vec = (0..2051u32).collect(); - let selected: Vec = misses.iter().copied().rev().collect(); - let selected_ids: Vec = selected.iter().map(|n| *n as usize).collect(); - let missing_ids: Vec = misses.iter().map(|n| *n as usize).collect(); - // Each max-width cell has a unique finite first-halfword witness. - let max_packed = |order: &[usize], seed: u16| -> Vec { - order - .iter() - .flat_map(|&cell| { - (0..512).flat_map(move |lane| { - let bits = (0x2000u16 + cell as u16 + seed) | if lane % 2 == 0 { 0 } else { 0x8000 }; - bits.to_le_bytes() - }) - }) - .collect() - }; - let keys = max_packed(&selected_ids, 3); - let values = max_packed(&selected_ids, 10); - let key = upload(&context, &keys)?; - let value = upload(&context, &values)?; - let (query_owner, output_owner) = buffers.split_at_mut(1); - let reference = context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], 2051); - let released = combine(key.release(), value.release()); - combine(reference, released)?; - let expected_output = read(&buffers[1], 24576)?; - let owner = workspace.as_mut().ok_or(Error::ContextPoisoned)?; - let generation = owner.generation; - let products = - owner.prepare(11, &misses, &max_packed(&missing_ids, 3), &max_packed(&missing_ids, 10), &selected)?; - if products.width() != 2051 || products.generation() != generation + 1 { - return Err(Error::InvalidDriverValue("QSA max-width witness")); - } - let handles = products.workspace.handles()?; - for (index, expected) in [(2, &keys), (3, &values)] { - let mut actual = vec![0; expected.len()]; - let prefix = handles[index].checked_subspan(PACKED, 0, actual.len())?; - let guard = context.enter()?; - let copy = context.driver.api.copy_to(prefix, &mut actual); - let sync = context.driver.api.synchronize(); - let pop = guard.finish(); - if sync.is_err() || pop.is_err() { - context.poisoned.set(true); - std::mem::forget(actual); - return combine(combine(copy, sync), pop); - } - combine(combine(copy, sync), pop)?; - differences += actual.iter().zip(expected).filter(|(a, b)| a != b).count(); - compared += expected.len(); - } - let (query_owner, output_owner) = buffers.split_at_mut(2); - products.attend(&query_owner[0], &mut output_owner[0])?; - let actual_output = read(&output_owner[0], 24576)?; - if expected_output - .as_chunks::<4>() - .0 - .iter() - .chain(actual_output.as_chunks::<4>().0.iter()) - .any(|b| !f32::from_le_bytes(*b).is_finite()) - { - return Err(Error::InvalidDriverValue("QSA max-width finite output")); - } - differences += actual_output - .as_chunks::<4>() - .0 - .iter() - .zip(expected_output.as_chunks::<4>().0) - .filter(|(a, b)| a != b) - .count(); - compared += 6144; - drop(products); - Ok(()) - })(); - let mut cleanup = workspace.take().map_or(Ok(()), QsaSelectedKvWorkspace::close); - drop(workspace); - for buffer in buffers.drain(..) { - cleanup = combine(cleanup, buffer.release()); - } - drop(buffers); - let sync = context.synchronize(); - let allocated = context.allocated_bytes(); - let closed = context.close(); - operation.expect("new transport operation"); - cleanup.expect("all owner cleanup"); - sync.expect("final sync"); - closed.expect("context close"); - assert_eq!(allocated, 0); - assert_eq!(differences, 0); - println!( - "QSA_SELECTED_KV_COMPLETE compared_bytes_and_f32_words={compared} different=0 guards={guards} allocated=0" - ); - } -} +mod selected_kv_installed; mod asset_fn; #[allow(unused_imports)] diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs index 22c5e2c9..0af56f93 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Drop_for_QsaSelectedKvWorkspace, impl QsaSelectedKvProducts, fn owned_bytes, fn slot_bytes. +//! Moved out of the parent module by STRA-338: impl Drop_for_QsaSelectedKvWorkspace, impl QsaSelectedKvProducts, fn +//! owned_bytes, fn slot_bytes. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs index ee8b8eb8..869e9429 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs @@ -210,7 +210,8 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { } Ok(generation) } - /// Miss slots are unique and in range, selected slots are unique, in range and either missed now or already resident. + /// Miss slots are unique and in range, selected slots are unique, in range and either missed now or already + /// resident. fn check_slots(&self, layer: u32, miss_slots: &[u32], selected_slots: &[u32]) -> Result<()> { let mut missing = [false; CELLS]; for &slot in miss_slots { diff --git a/crates/cuda-driver/src/qsa_selected_kv/selected_kv_installed.rs b/crates/cuda-driver/src/qsa_selected_kv/selected_kv_installed.rs new file mode 100644 index 00000000..cd4d9a01 --- /dev/null +++ b/crates/cuda-driver/src/qsa_selected_kv/selected_kv_installed.rs @@ -0,0 +1,395 @@ +//! The Root-only actual-GPU proof of the lossless selected-KV transport (moved out of `qsa_selected_kv.rs` by +//! STRA-338; the test id `selected_kv_installed::original_first_selected_kv_bytes_attention_reorder_refusals_cleanup` +//! is unchanged). + +use super::*; + +struct RestoreHandle<'a, 'ctx> { + buffer: &'a mut DeviceBuffer<'ctx>, + previous: Option, +} +impl Drop for RestoreHandle<'_, '_> { + fn drop(&mut self) { + self.buffer.handle = self.previous; + } +} +fn packed(order: &[usize], seed: usize) -> Vec { + order + .iter() + .flat_map(|&cell| { + (0..512).flat_map(move |i| { + let bits = match (i + cell + seed) % 5 { + 0 => 0x8000u16, + 1 => 0x0000, + 2 => 0x3000, + 3 => 0xb000, + _ => 0x3400, + }; + bits.to_le_bytes() + }) + }) + .collect() +} +/// Each max-width cell has a unique finite first-halfword witness. +fn max_packed(order: &[usize], seed: u16) -> Vec { + order + .iter() + .flat_map(|&cell| { + (0..512).flat_map(move |lane| { + let bits = (0x2000u16 + cell as u16 + seed) | if lane % 2 == 0 { 0 } else { 0x8000 }; + bits.to_le_bytes() + }) + }) + .collect() +} +fn upload<'ctx>(context: &'ctx Context<'ctx>, bytes: &[u8]) -> Result> { + let mut buffer = context.allocate(bytes.len())?; + if let Err(error) = buffer.copy_from(bytes) { + return combine(Err(error), buffer.release()); + } + Ok(buffer) +} +fn read(buffer: &DeviceBuffer<'_>, bytes: usize) -> Result> { + let mut output = vec![0; bytes]; + buffer.copy_to(&mut output)?; + Ok(output) +} + +/// What the proof counts: compared bytes and f32 words, differences among them, and refusals that held. +#[derive(Default)] +struct Tally { + differences: usize, + compared: usize, + guards: usize, +} + +/// The actual device and context, and the query every phase attends. +struct Env<'a> { + device: &'a Device<'a>, + context: &'a Context<'a>, + query: Vec, +} + +/// The owners the proof keeps across its phases; `finish` releases them. +struct Proof<'a> { + env: Env<'a>, + buffers: Vec>, + workspace: Option>, + tally: Tally, +} + +impl<'a> Proof<'a> { + fn new(device: &'a Device<'a>, context: &'a Context<'a>) -> Self { + let query: Vec = (0..6144) + .flat_map(|i| if i % 3 == 0 { 0.125f32.to_le_bytes() } else { (-0.125f32).to_le_bytes() }) + .collect(); + Self { env: Env { device, context, query }, buffers: Vec::new(), workspace: None, tally: Tally::default() } + } + + fn run(&mut self) -> Result<()> { + self.setup_buffers()?; + self.refuse_small_budget()?; + // Original attention FIRST, exact independently packed full-cell order. + for (layer, misses, selected, seed) in [ + (0u32, vec![0u32, 17, 2050], vec![2050u32, 0, 17], 0usize), + (0, vec![], vec![17, 2050, 0], 0), + (0, vec![17], vec![17, 0, 2050], 1), + (11, vec![0, 17, 2050], vec![0, 17, 2050], 2), + ] { + self.run_case(layer, (&misses, &selected), seed)?; + } + // Max-width phase runs AFTER all uninitialized-slot refusals above. + self.run_max_width() + } + + fn setup_buffers(&mut self) -> Result<()> { + self.buffers.push(upload(self.env.context, &self.env.query)?); + self.buffers.push(self.env.context.allocate(24576)?); + self.buffers.push(self.env.context.allocate(24576)?); + Ok(()) + } + + fn refuse_small_budget(&mut self) -> Result<()> { + let small = self.env.device.create_context(TOTAL + RESERVE - 1)?; + let refused = small.qsa_selected_kv_workspace(); + if !matches!(refused, Err(Error::BudgetExceeded)) { + return Err(Error::InvalidDriverValue("QSA budget guard")); + } + drop(refused); + let small_allocated = small.allocated_bytes(); + small.close()?; + if small_allocated != 0 { + return Err(Error::InvalidDriverValue("QSA refused budget allocation")); + } + self.tally.guards += 1; + Ok(()) + } + + /// The original attention over `keys` and `values` (`width` cells) into the reference output, which is read back. + fn reference_output(&mut self, images: (&[u8], &[u8]), width: u32) -> Result> { + let key = upload(self.env.context, images.0)?; + let value = upload(self.env.context, images.1)?; + let (query_owner, output_owner) = self.buffers.split_at_mut(1); + let reference = self.env.context.qsa_attend(&query_owner[0], &key, &value, &mut output_owner[0], width); + let cleanup = combine(key.release(), value.release()); + combine(reference, cleanup)?; + read(&self.buffers[1], 24576) + } + + fn run_case(&mut self, layer: u32, slots: (&[u32], &[u32]), seed: usize) -> Result<()> { + let (misses, selected) = slots; + let (keys, values) = case_images(layer, selected, seed); + let expected = self.reference_output((&keys, &values), selected.len() as u32)?; + if self.workspace.is_none() { + self.workspace = Some(self.env.context.qsa_selected_kv_workspace()?); + } + let owner = self.workspace.as_mut().ok_or(Error::ContextPoisoned)?; + let miss_ids: Vec = misses.iter().map(|n| *n as usize).collect(); + let (miss_k, miss_v) = (packed(&miss_ids, seed), packed(&miss_ids, seed + 7)); + let products = owner.prepare(layer, misses, &miss_k, &miss_v, selected)?; + compare_prefixes(self.env.context, &products, (&keys, &values), &mut self.tally)?; + let prior_output = attend_and_refuse(&self.env, &products, &mut self.buffers, &mut self.tally)?; + check_output_unchanged(&self.buffers[2], (&prior_output, &expected), &mut self.tally)?; + drop(products); + refuse_bad_prepares(self.env.context, owner, layer, &mut self.tally) + } + + fn run_max_width(&mut self) -> Result<()> { + // Original full-width attention FIRST with independent reverse order. + let misses: Vec = (0..2051u32).collect(); + let selected: Vec = misses.iter().copied().rev().collect(); + let selected_ids: Vec = selected.iter().map(|n| *n as usize).collect(); + let missing_ids: Vec = misses.iter().map(|n| *n as usize).collect(); + let keys = max_packed(&selected_ids, 3); + let values = max_packed(&selected_ids, 10); + let expected_output = self.reference_output((&keys, &values), 2051)?; + let owner = self.workspace.as_mut().ok_or(Error::ContextPoisoned)?; + let generation = owner.generation; + let products = + owner.prepare(11, &misses, &max_packed(&missing_ids, 3), &max_packed(&missing_ids, 10), &selected)?; + if products.width() != 2051 || products.generation() != generation + 1 { + return Err(Error::InvalidDriverValue("QSA max-width witness")); + } + compare_prefixes(self.env.context, &products, (&keys, &values), &mut self.tally)?; + let (query_owner, output_owner) = self.buffers.split_at_mut(2); + products.attend(&query_owner[0], &mut output_owner[0])?; + let actual_output = read(&output_owner[0], 24576)?; + tally_output(&expected_output, &actual_output, "QSA max-width finite output", &mut self.tally)?; + drop(products); + Ok(()) + } + + /// Close the workspace, release every buffer, and hand back the cleanup result with the counts. + fn finish(mut self) -> (Result<()>, Tally) { + let mut cleanup = self.workspace.take().map_or(Ok(()), QsaSelectedKvWorkspace::close); + for buffer in self.buffers.drain(..) { + cleanup = combine(cleanup, buffer.release()); + } + (cleanup, self.tally) + } +} + +/// The key and value images of the selected slots in selection order, each cell packed by the seed it was uploaded +/// with. +fn case_images(layer: u32, selected: &[u32], seed: usize) -> (Vec, Vec) { + let ids: Vec = selected.iter().map(|n| *n as usize).collect(); + let mut keys = packed(&ids, 0); + let mut values = packed(&ids, 0); + for (j, &slot) in selected.iter().enumerate() { + let old_seed = if layer == 11 { + 2 + } else if slot == 17 && seed == 1 { + 1 + } else { + 0 + }; + keys[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed)); + values[j * CELL..(j + 1) * CELL].copy_from_slice(&packed(&[slot as usize], old_seed + 7)); + } + (keys, values) +} + +/// The prefix of the key (2) and value (3) stages equals the uploaded images byte for byte. +fn compare_prefixes( + context: &Context<'_>, + products: &QsaSelectedKvProducts<'_, '_>, + images: (&[u8], &[u8]), + tally: &mut Tally, +) -> Result<()> { + let h = products.workspace.handles()?; + for (index, expected) in [(2, images.0), (3, images.1)] { + let mut actual = vec![0; expected.len()]; + let prefix = h[index].checked_subspan(PACKED, 0, actual.len())?; + let guard = context.enter()?; + let copy = context.driver.api.copy_to(prefix, &mut actual); + let sync = context.driver.api.synchronize(); + let pop = guard.finish(); + if sync.is_err() || pop.is_err() { + context.poisoned.set(true); + std::mem::forget(actual); + return combine(combine(copy, sync), pop); + } + combine(combine(copy, sync), pop)?; + tally.differences += actual.iter().zip(expected).filter(|(a, b)| a != b).count(); + tally.compared += expected.len(); + } + Ok(()) +} + +/// Attend with the actual independent query/output owners (no forged product factory), then show that a wrong shape, +/// an aliased output and a foreign-context query are refused. Returns the output as it stood before the refusals. +fn attend_and_refuse( + env: &Env<'_>, + products: &QsaSelectedKvProducts<'_, '_>, + buffers: &mut [DeviceBuffer<'_>], + tally: &mut Tally, +) -> Result> { + let (left, right) = buffers.split_at_mut(2); + products.attend(&left[0], &mut right[0])?; + let prior_output = read(&right[0], 24576)?; + refuse_wrong_shape(env.context, products, &left[0], tally)?; + refuse_alias(products, (&left[0], &mut right[0]), tally)?; + refuse_foreign(env, products, &mut right[0], tally)?; + Ok(prior_output) +} + +fn refuse_wrong_shape( + context: &Context<'_>, + products: &QsaSelectedKvProducts<'_, '_>, + query: &DeviceBuffer<'_>, + tally: &mut Tally, +) -> Result<()> { + let mut wrong = context.allocate(4)?; + let refused = products.attend(query, &mut wrong); + let release = wrong.release(); + if !matches!(refused, Err(Error::InvalidQwenShape)) { + return Err(Error::InvalidDriverValue("QSA shape guard")); + } + release?; + tally.guards += 1; + Ok(()) +} + +fn refuse_alias( + products: &QsaSelectedKvProducts<'_, '_>, + io: (&DeviceBuffer<'_>, &mut DeviceBuffer<'_>), + tally: &mut Tally, +) -> Result<()> { + let (query, output) = io; + let previous = output.handle; + let alias = RestoreHandle { buffer: output, previous }; + alias.buffer.handle = query.handle; + if !matches!(products.attend(query, &mut *alias.buffer), Err(Error::OutputAliasesInput)) { + return Err(Error::InvalidDriverValue("QSA alias guard")); + } + tally.guards += 1; + Ok(()) +} + +fn refuse_foreign( + env: &Env<'_>, + products: &QsaSelectedKvProducts<'_, '_>, + output: &mut DeviceBuffer<'_>, + tally: &mut Tally, +) -> Result<()> { + let foreign = env.device.create_context(1024 * 1024)?; + let foreign_query = upload(&foreign, &env.query)?; + let refusal = products.attend(&foreign_query, output); + let released = foreign_query.release(); + let allocated = foreign.allocated_bytes(); + let closed = foreign.close(); + if !matches!(refusal, Err(Error::ContextMismatch)) || allocated != 0 { + return Err(Error::InvalidDriverValue("QSA foreign guard")); + } + released?; + closed?; + tally.guards += 1; + Ok(()) +} + +/// The output after the refusals is the output before them, and every word of it is finite and counted. +fn check_output_unchanged(output: &DeviceBuffer<'_>, outputs: (&[u8], &[u8]), tally: &mut Tally) -> Result<()> { + let (prior_output, expected) = outputs; + let actual = read(output, 24576)?; + if actual != prior_output { + return Err(Error::InvalidDriverValue("QSA refused output mutation")); + } + tally_output(expected, &actual, "QSA full output finite", tally) +} + +/// Every output word is finite; count the words that differ from the reference and the words compared. +fn tally_output(expected: &[u8], actual: &[u8], finite_error: &'static str, tally: &mut Tally) -> Result<()> { + let (expected_words, actual_words) = (expected.as_chunks::<4>().0, actual.as_chunks::<4>().0); + if expected_words.iter().chain(actual_words.iter()).any(|b| !f32::from_le_bytes(*b).is_finite()) { + return Err(Error::InvalidDriverValue(finite_error)); + } + tally.differences += actual_words.iter().zip(expected_words).filter(|(a, b)| a != b).count(); + tally.compared += 6144; + Ok(()) +} + +/// Bad requests are refused before any write: the generation, the charge and the failed flag stay as they were. +fn refuse_bad_prepares( + context: &Context<'_>, + owner: &mut QsaSelectedKvWorkspace<'_>, + layer: u32, + tally: &mut Tally, +) -> Result<()> { + let generation = owner.generation; + let charged = context.allocated_bytes(); + for refused in [ + owner.prepare(12, &[], &[], &[], &[0]).is_err(), + owner.prepare(layer, &[], &[], &[], &[0, 0]).is_err(), + owner.prepare(layer, &[0, 0], &vec![0; 2048], &vec![0; 2048], &[0]).is_err(), + owner.prepare(layer, &[], &[], &[], &[2051]).is_err(), + owner.prepare(layer, &[], &[], &[], &[18]).is_err(), + owner.prepare(layer, &[0], &vec![0; 1023], &vec![0; 1023], &[0]).is_err(), + ] { + if !refused { + return Err(Error::InvalidDriverValue("QSA guard accepted")); + } + tally.guards += 1; + } + refuse_nonfinite_prepare(owner, layer, tally)?; + if owner.generation != generation || context.allocated_bytes() != charged || owner.is_failed() { + return Err(Error::InvalidDriverValue("QSA prewrite mutation")); + } + Ok(()) +} + +fn refuse_nonfinite_prepare(owner: &mut QsaSelectedKvWorkspace<'_>, layer: u32, tally: &mut Tally) -> Result<()> { + let mut nonfinite = vec![0; 1024]; + nonfinite[510..512].copy_from_slice(&0x7e00u16.to_le_bytes()); + if owner.prepare(layer, &[0], &nonfinite, &vec![0; 1024], &[0]).is_ok() { + return Err(Error::InvalidDriverValue("QSA nonfinite accepted")); + } + tally.guards += 1; + Ok(()) +} + +#[test] +#[ignore = "Root only; exact new asset, one lossless changed transport proof"] +fn original_first_selected_kv_bytes_attention_reorder_refusals_cleanup() { + if std::env::var("LELEKA_STRA172_RUN_QSA_SELECTED_KV").as_deref() != Ok("yes") { + return; + } + let driver = Driver::load().expect("actual CUDA library"); + let device = driver.device(0).expect("actual device"); + let context = device.create_context(256 * 1024 * 1024).expect("bounded actual context"); + let mut proof = Proof::new(&device, &context); + let operation = proof.run(); + let (cleanup, tally) = proof.finish(); + let sync = context.synchronize(); + let allocated = context.allocated_bytes(); + let closed = context.close(); + operation.expect("new transport operation"); + cleanup.expect("all owner cleanup"); + sync.expect("final sync"); + closed.expect("context close"); + assert_eq!(allocated, 0); + assert_eq!(tally.differences, 0); + let (compared, guards) = (tally.compared, tally.guards); + println!( + "QSA_SELECTED_KV_COMPLETE compared_bytes_and_f32_words={compared} different=0 guards={guards} allocated=0" + ); +} diff --git a/crates/cuda-driver/src/qsa_verification_commit.rs b/crates/cuda-driver/src/qsa_verification_commit.rs index 49a3c44f..46738806 100644 --- a/crates/cuda-driver/src/qsa_verification_commit.rs +++ b/crates/cuda-driver/src/qsa_verification_commit.rs @@ -50,7 +50,8 @@ pub struct OriginalVerifyQsaJournal<'a, 'ctx> { rope: OriginalVerifyRope<'a, 'ctx>, live: RefCell, failed: Cell, - /// `set_window_snapshots`: the index state (12 x `WINDOW_STATE_BYTES`) and the PLE history image at the start of every window, for `discard_window`. + /// `set_window_snapshots`: the index state (12 x `WINDOW_STATE_BYTES`) and the PLE history image at the start of + /// every window, for `discard_window`. snapshots: Cell, snapshot: RefCell>, ple_snapshot: RefCell>, diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs index 4a11a03e..00c9e7f4 100644 --- a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs @@ -36,8 +36,10 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { drop(i); self.capture_append(journal, capture, layer, 0, t, true) } - /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the twelve layers' `capture_commit_layer` (tail restore + all `max_t` row appends) in ONE launch (`draft_commit_qsa_layers`, - /// one block per layer, rows in order). Only the analytic RoPE variant (`verify_qsa_append_analytic`) is fused: with retained angle tables it returns `Ok(false)` and records nothing. + /// draft-round (`LELEKA_DRAFT_FUSED_COMMIT=on`): the twelve layers' `capture_commit_layer` (tail restore + all + /// `max_t` row appends) in ONE launch (`draft_commit_qsa_layers`, one block per layer, rows in order). Only the + /// analytic RoPE variant (`verify_qsa_append_analytic`) is fused: with retained angle tables it returns `Ok(false)` + /// and records nothing. pub(crate) fn capture_commit_fused( &self, journal: &OriginalVerifyGdnJournal<'_, 'ctx>, @@ -81,7 +83,8 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { } Ok(layers) } - /// The launch words: the layer tables, the journal addresses, the positions, the sizes and the packed RoPE constants. + /// 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> { let r = self.rope; let positions = self.positions_address()?; @@ -231,8 +234,8 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { } Ok(()) } - /// The append receipts must be those of the armed window, and each journal must accept its final prefix. Returns the - /// number of rows to keep. + /// The append receipts must be those of the armed window, and each journal must accept its final prefix. Returns + /// the number of rows to keep. fn check_appended( &self, bank: &OriginalVerifyBank<'ctx>, diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs index ce97e13a..25040bbd 100644 --- a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs @@ -55,12 +55,14 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { } Ok(()) } - /// Switch on the per-window snapshots `discard_window` needs (the NaN guard, `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on`). They cost twelve small - /// device-to-host reads and one of the 360 KB PLE history at the start of every window, so they are off unless asked for. + /// Switch on the per-window snapshots `discard_window` needs (the NaN guard, `LELEKA_ORIGINAL_SERVE_NAN_GUARD=on`). + /// They cost twelve small device-to-host reads and one of the 360 KB PLE history at the start of every window, so + /// they are off unless asked for. pub fn set_window_snapshots(&self, on: bool) { self.snapshots.set(on); } - /// The PLE history image as it stands when a window begins (called right after `begin_window`, device idle); nothing unless the snapshots are on. + /// The PLE history image as it stands when a window begins (called right after `begin_window`, device idle); + /// nothing unless the snapshots are on. pub(crate) fn snapshot_ple(&self, ple: &DeviceBuffer<'ctx>) -> Result<()> { if !self.snapshots.get() { return Ok(()); @@ -71,15 +73,17 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { bytes.resize(ple.len(), 0); ple.copy_to_range(0, &mut bytes) } - /// Undo the armed window that completed on the GPU and that nothing was committed for (the serve loop's NaN guard refused it and wants - /// the same rows run again). What a window disturbs in the index images and the accepted-prefix graph would not put back is the tail, - /// `dead`, the pooled row of the block in progress and the block position (a checkpoint's four pieces; the rows read the spare and the - /// tail from them, so the same rows staged again at the same position read different values if the window left its own), and the PLE - /// history, which every window row advances and only the commit graph sets from the kept row's snapshot (the first live attempt that - /// restored the index state alone got a rerun that differed from the refused window, deterministically, a different one each time): they - /// are written back from the snapshots taken when the window began. Each index then stands at `position` again, published, and the journal can arm - /// the next window. The K/V cells and pooled rows above the block in progress that the window wrote lie beyond every coverage, as after - /// a rejected suffix, and the rerun writes them again before it reads them. The device is idle (the window drained). An error leaves the + /// Undo the armed window that completed on the GPU and that nothing was committed for (the serve loop's NaN guard + /// refused it and wants the same rows run again). What a window disturbs in the index images and the + /// accepted-prefix graph would not put back is the tail, `dead`, the pooled row of the block in progress and the + /// block position (a checkpoint's four pieces; the rows read the spare and the tail from them, so the same rows + /// staged again at the same position read different values if the window left its own), and the PLE history, which + /// every window row advances and only the commit graph sets from the kept row's snapshot (the first live attempt + /// that restored the index state alone got a rerun that differed from the refused window, deterministically, a + /// different one each time): they are written back from the snapshots taken when the window began. Each index then + /// stands at `position` again, published, and the journal can arm the next window. The K/V cells and pooled rows + /// above the block in progress that the window wrote lie beyond every coverage, as after a rejected suffix, and the + /// rerun writes them again before it reads them. The device is idle (the window drained). An error leaves the /// journal armed. pub(crate) fn discard_window( &self, diff --git a/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs b/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs index afd1fefc..c9c5ae28 100644 --- a/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs +++ b/crates/cuda-driver/src/qwen_dispatch/impl_cache.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Cache, impl Backend_for_Context, fn restore, fn registered, fn execute, fn prepare_pair. +//! Moved out of the parent module by STRA-338: impl Cache, impl Backend_for_Context, fn restore, fn registered, fn +//! execute, fn prepare_pair. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs b/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs index 8b71883f..e4a3c49c 100644 --- a/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs +++ b/crates/cuda-driver/src/qwen_dispatch/prepare_gr_read_set_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn prepare_gr_read_set, fn unload, fn ranges, fn ranges_layout, fn native_span. +//! Moved out of the parent module by STRA-338: fn prepare_gr_read_set, fn unload, fn ranges, fn ranges_layout, fn +//! native_span. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs b/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs index 59b9f1a7..b7d137da 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/full_s2_bank_extent.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): full_s2_bank_extent_and_output_refusals, mtp_new_ninth_output_and_scale_extent_refuse, kar_ple_qualified_receipt_corruption_refuses_before_mutation, kar_ple_whole_spans_require_all_disjoint_allocations .... +//! Tests of tests by topic (moved out of the test file by STRA-338): full_s2_bank_extent_and_output_refusals, +//! mtp_new_ninth_output_and_scale_extent_refuse, kar_ple_qualified_receipt_corruption_refuses_before_mutation, +//! kar_ple_whole_spans_require_all_disjoint_allocations .... #[allow(unused_imports)] use super::*; @@ -82,32 +84,19 @@ fn kar_ple_qualified_receipt_corruption_refuses_before_mutation() { } } +/// Nine synthetic, distinct, 256 MiB-spaced buffer addresses; no real allocation. +fn disjoint_handles() -> [ffi::BufferHandle; 9] { + std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))) +} + #[test] fn kar_ple_whole_spans_require_all_disjoint_allocations() { for (operation, value) in [(Operation::KarPleScatter, 16), (Operation::KarPleDecode, 65_535)] { let layout = qwen_ffi::kar_ple_layout(operation, value).unwrap(); - let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + let handles = disjoint_handles(); assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); for i in 0..layout.count { - let mut short = layout.bytes; - short[i] -= 1; - assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); - if layout.align[i] > 1 { - let mut misaligned = handles; - misaligned[i] = ffi::BufferHandle::synthetic(handles[i].qwen_address() + 1); - assert_eq!( - ranges_layout(operation, layout, misaligned, layout.bytes, false), - Err(Error::InvalidQwenShape) - ); - } - for j in i + 1..layout.count { - let mut alias = handles; - alias[j] = handles[i]; - assert_eq!( - ranges_layout(operation, layout, alias, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); - } + assert_kar_ple_span_refused(operation, layout, handles, i); } let mut overflow = handles; overflow[0] = ffi::BufferHandle::synthetic(u64::MAX - 63); @@ -116,6 +105,69 @@ fn kar_ple_whole_spans_require_all_disjoint_allocations() { } } +/// Span `i` too short, misaligned (when it needs alignment) and aliased by each later span is refused. +fn assert_kar_ple_span_refused( + operation: Operation, + layout: qwen_ffi::Layout, + handles: [ffi::BufferHandle; 9], + i: usize, +) { + let mut short = layout.bytes; + short[i] -= 1; + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); + if layout.align[i] > 1 { + let mut misaligned = handles; + misaligned[i] = ffi::BufferHandle::synthetic(handles[i].qwen_address() + 1); + assert_eq!(ranges_layout(operation, layout, misaligned, layout.bytes, false), Err(Error::InvalidQwenShape)); + } + for j in i + 1..layout.count { + let mut alias = handles; + alias[j] = handles[i]; + assert_eq!(ranges_layout(operation, layout, alias, layout.bytes, false), Err(Error::OutputAliasesInput)); + } +} + +/// A context over the unsupported-platform backend with `budget` bytes of which `allocated` are charged. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub(super) fn platform_context(driver: &crate::Driver, budget: usize, allocated: usize) -> Context<'_> { + use crate::{FixedPairKernels, ProjectionKernels}; + Context { + driver, + handle: Some(ffi::ContextHandle::synthetic(1)), + ordinal: 0, + budget, + allocated: Cell::new(allocated), + poisoned: Cell::new(false), + vector_add_kernel: Cell::new(None), + matvec_kernel: Cell::new(None), + q5_k_kernel: Cell::>::new(None), + q6_k_kernel: Cell::new(None), + common_quantizer: Cell::new(None), + projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), + qwen_kernels: Cache::new(), + } +} + +/// A synthetic device buffer of `bytes` at `address` in `context`; it owns no CUDA allocation. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +pub(super) fn synthetic_buffer<'a>(context: &'a Context<'a>, address: u64, bytes: usize) -> DeviceBuffer<'a> { + DeviceBuffer { + context, + handle: Some(ffi::BufferHandle::synthetic(address)), + bytes, + _thread: std::marker::PhantomData, + borrowed: false, + } +} + #[cfg(not(all( feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), @@ -123,36 +175,14 @@ fn kar_ple_whole_spans_require_all_disjoint_allocations() { )))] #[test] fn kar_ple_qualified_public_calls_refuse_unsupported_platform_preserve_owner_and_cache() { - use crate::{Driver, FixedPairKernels, ProjectionKernels}; - use std::marker::PhantomData; + use crate::Driver; let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let context = Context { - driver: &driver, - handle: Some(ffi::ContextHandle::synthetic(1)), - ordinal: 0, - budget: 100_000_000, - allocated: Cell::new(67_119_176), - poisoned: Cell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::>::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), - qwen_kernels: Cache::new(), - }; - let buffer = |address, bytes| DeviceBuffer { - context: &context, - handle: Some(ffi::BufferHandle::synthetic(address)), - bytes, - _thread: PhantomData, - borrowed: false, - }; - let mut cache = buffer(0x10000000, 67_108_864); - let mut updates = buffer(0x20000000, 56); - let mut slots = buffer(0x30000000, 64); - let mut books = buffer(0x40000000, 8); - let mut out = buffer(0x50000000, 10_240); + let context = platform_context(&driver, 100_000_000, 67_119_176); + let mut cache = synthetic_buffer(&context, 0x10000000, 67_108_864); + let mut updates = synthetic_buffer(&context, 0x20000000, 56); + let mut slots = synthetic_buffer(&context, 0x30000000, 64); + let mut books = synthetic_buffer(&context, 0x40000000, 8); + let mut out = synthetic_buffer(&context, 0x50000000, 10_240); assert_eq!(context.kar_ple_scatter(&mut cache, &updates, 1), Err(Error::UnsupportedPlatform)); assert_eq!(context.kar_ple_decode(&cache, &slots, &books, &mut out), Err(Error::UnsupportedPlatform)); assert_eq!(context.allocated.get(), 67_119_176); @@ -172,23 +202,10 @@ fn qsa_new_preflight_checks_whole_spans_aliases_and_fixed_shared_memory() { for operation in qwen_ffi::QSA_OPERATIONS { let value = if operation == Operation::QsaAttend { 2051 } else { crate::MAX_CONTEXT_CELLS as u32 - 1 }; let layout = qwen_ffi::qsa_layout(operation, value).unwrap(); - let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); + let handles = disjoint_handles(); assert_eq!(ranges_layout(operation, layout, handles, layout.bytes, false), Ok(())); for output in (0..layout.count).filter(|i| layout.outputs & (1 << i) != 0) { - let mut short = layout.bytes; - short[output] -= 1; - assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); - for input in 0..layout.count { - if input == output { - continue; - } - let mut alias = handles; - alias[output] = handles[input]; - assert_eq!( - ranges_layout(operation, layout, alias, layout.bytes, false), - Err(Error::OutputAliasesInput) - ); - } + assert_qsa_output_refused(operation, layout, handles, output); } let mut wrapped = handles; wrapped[0] = ffi::BufferHandle::synthetic(u64::MAX - 3); @@ -200,3 +217,23 @@ fn qsa_new_preflight_checks_whole_spans_aliases_and_fixed_shared_memory() { qwen_ffi::asset(operation).expect("qualified QSA component").validate(operation).unwrap(); } } + +/// A short output span and an output aliased onto each other span are refused. +fn assert_qsa_output_refused( + operation: Operation, + layout: qwen_ffi::Layout, + handles: [ffi::BufferHandle; 9], + output: usize, +) { + let mut short = layout.bytes; + short[output] -= 1; + assert_eq!(ranges_layout(operation, layout, handles, short, false), Err(Error::InvalidQwenShape)); + for input in 0..layout.count { + if input == output { + continue; + } + let mut alias = handles; + alias[output] = handles[input]; + assert_eq!(ranges_layout(operation, layout, alias, layout.bytes, false), Err(Error::OutputAliasesInput)); + } +} diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs b/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs index 001c59a8..ef5fabb3 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/moe_new_preflight_requires_exact.rs @@ -1,4 +1,8 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): moe_new_preflight_requires_exact_disjoint_owner_spans, moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order, gdn_fixed_abi_keeps_recurrent_order_and_refuses_prior_output_alias, qwen_fixed_slots_atomic_cache_and_no_quantizer .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! moe_new_preflight_requires_exact_disjoint_owner_spans, +//! moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order, +//! gdn_fixed_abi_keeps_recurrent_order_and_refuses_prior_output_alias, qwen_fixed_slots_atomic_cache_and_no_quantizer +//! .... #[allow(unused_imports)] use super::*; @@ -32,42 +36,52 @@ fn moe_new_preflight_requires_exact_disjoint_owner_spans() { #[test] fn moe_new_slots_cache_atomically_and_keep_launch_sync_restore_order() { for operation in MOE_OPERATIONS { - let backend = Mock::default(); - let cache = Cache::new(); let asset = qwen_ffi::mock_asset(operation); - execute(&backend, &cache, &asset, arguments(operation)).unwrap(); - execute(&backend, &cache, &asset, arguments(operation)).unwrap(); - assert_eq!( - *backend.trace.borrow(), - ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] - ); - assert_eq!(ready(&cache), 1); - - let backend = Mock::fault(&["lookup", "unload", "restore"]); - let cache = Cache::new(); - assert_eq!( - execute(&backend, &cache, &asset, arguments(operation)), - Err(nested(nested(error("lookup"), error("unload")), error("restore"))) - ); - assert_eq!(ready(&cache), 0); - assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); - assert!(backend.poisoned()); - - let backend = Mock::fault(&["launch", "sync", "restore"]); - let cache = Cache::new(); - assert_eq!( - execute(&backend, &cache, &asset, arguments(operation)), - Err(nested(nested(error("launch"), error("sync")), error("restore"))) - ); - assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "launch", "sync", "restore"]); - assert!(backend.poisoned()); - assert!(backend.retained.get() > 0); - let trace = backend.trace.borrow().clone(); - assert_eq!(execute(&backend, &cache, &asset, arguments(operation)), Err(Error::ContextPoisoned)); - assert_eq!(*backend.trace.borrow(), trace); + assert_second_execute_reuses_the_cached_slot(operation, &asset); + assert_lookup_unload_restore_faults_poison_without_publishing(operation, &asset); + assert_launch_sync_restore_faults_retain_and_poison(operation, &asset); } } +fn assert_second_execute_reuses_the_cached_slot(operation: Operation, asset: &Asset) { + let backend = Mock::default(); + let cache = Cache::new(); + execute(&backend, &cache, asset, arguments(operation)).unwrap(); + execute(&backend, &cache, asset, arguments(operation)).unwrap(); + assert_eq!( + *backend.trace.borrow(), + ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] + ); + assert_eq!(ready(&cache), 1); +} + +fn assert_lookup_unload_restore_faults_poison_without_publishing(operation: Operation, asset: &Asset) { + let backend = Mock::fault(&["lookup", "unload", "restore"]); + let cache = Cache::new(); + assert_eq!( + execute(&backend, &cache, asset, arguments(operation)), + Err(nested(nested(error("lookup"), error("unload")), error("restore"))) + ); + assert_eq!(ready(&cache), 0); + assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); + assert!(backend.poisoned()); +} + +fn assert_launch_sync_restore_faults_retain_and_poison(operation: Operation, asset: &Asset) { + let backend = Mock::fault(&["launch", "sync", "restore"]); + let cache = Cache::new(); + assert_eq!( + execute(&backend, &cache, asset, arguments(operation)), + Err(nested(nested(error("launch"), error("sync")), error("restore"))) + ); + assert_eq!(*backend.trace.borrow(), ["push", "load", "lookup", "launch", "sync", "restore"]); + assert!(backend.poisoned()); + assert!(backend.retained.get() > 0); + let trace = backend.trace.borrow().clone(); + assert_eq!(execute(&backend, &cache, asset, arguments(operation)), Err(Error::ContextPoisoned)); + assert_eq!(*backend.trace.borrow(), trace); +} + #[test] fn gdn_fixed_abi_keeps_recurrent_order_and_refuses_prior_output_alias() { let operation = Operation::GdnStep; diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs index 8ef8bf67..9cb9b2f2 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qsa_new_slots_keep_atomic.rs @@ -1,5 +1,15 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners, qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation, moe_qualified_methods_refuse_unsupported_platform_without_mutation, qsa_qualified_public_slots_refuse_platform_without_owner_mutation. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners, +//! qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation, +//! moe_qualified_methods_refuse_unsupported_platform_without_mutation, +//! qsa_qualified_public_slots_refuse_platform_without_owner_mutation. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +use super::full_s2_bank_extent::{platform_context, synthetic_buffer}; #[allow(unused_imports)] use super::*; @@ -7,42 +17,51 @@ use super::*; fn qsa_new_slots_keep_atomic_lookup_and_uncertain_completion_owners() { for operation in qwen_ffi::QSA_OPERATIONS { let asset = qwen_ffi::mock_asset(operation); - let backend = Mock::default(); - let cache = Cache::new(); - execute(&backend, &cache, &asset, arguments(operation)).unwrap(); - execute(&backend, &cache, &asset, arguments(operation)).unwrap(); - assert_eq!( - *backend.trace.borrow(), - ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] - ); - assert_eq!(ready(&cache), 1); - let failed = Mock::fault(&["lookup", "unload"]); - let cache = Cache::new(); - assert_eq!( - execute(&failed, &cache, &asset, arguments(operation)), - Err(nested(error("lookup"), error("unload"))) - ); - assert_eq!(ready(&cache), 0); - assert!(failed.poison.get()); - assert_eq!(*failed.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); - let failed = Mock::fault(&["launch", "sync", "restore"]); - let cache = Cache::new(); - let drops = Rc::new(Cell::new(0)); - assert_eq!( - execute(&failed, &cache, &asset, arguments(operation).observe_drop(Rc::clone(&drops))), - Err(nested(nested(error("launch"), error("sync")), error("restore"))) - ); - assert_eq!(drops.get(), 0); - assert!(failed.poison.get()); - let before = failed.trace.borrow().clone(); - assert_eq!(execute(&failed, &cache, &asset, arguments(operation)), Err(Error::ContextPoisoned)); - assert_eq!(*failed.trace.borrow(), before); - unload(&failed, &cache).unwrap(); - assert_eq!(*failed.trace.borrow(), before); - assert_eq!(ready(&cache), 0); + assert_second_execute_reuses_the_cached_slot(operation, &asset); + assert_lookup_and_unload_faults_publish_nothing(operation, &asset); + assert_uncertain_completion_keeps_owners_and_poison(operation, &asset); } } +fn assert_second_execute_reuses_the_cached_slot(operation: Operation, asset: &Asset) { + let backend = Mock::default(); + let cache = Cache::new(); + execute(&backend, &cache, asset, arguments(operation)).unwrap(); + execute(&backend, &cache, asset, arguments(operation)).unwrap(); + assert_eq!( + *backend.trace.borrow(), + ["push", "load", "lookup", "launch", "sync", "restore", "push", "launch", "sync", "restore"] + ); + assert_eq!(ready(&cache), 1); +} + +fn assert_lookup_and_unload_faults_publish_nothing(operation: Operation, asset: &Asset) { + let failed = Mock::fault(&["lookup", "unload"]); + let cache = Cache::new(); + assert_eq!(execute(&failed, &cache, asset, arguments(operation)), Err(nested(error("lookup"), error("unload")))); + assert_eq!(ready(&cache), 0); + assert!(failed.poison.get()); + assert_eq!(*failed.trace.borrow(), ["push", "load", "lookup", "unload", "restore"]); +} + +fn assert_uncertain_completion_keeps_owners_and_poison(operation: Operation, asset: &Asset) { + let failed = Mock::fault(&["launch", "sync", "restore"]); + let cache = Cache::new(); + let drops = Rc::new(Cell::new(0)); + assert_eq!( + execute(&failed, &cache, asset, arguments(operation).observe_drop(Rc::clone(&drops))), + Err(nested(nested(error("launch"), error("sync")), error("restore"))) + ); + assert_eq!(drops.get(), 0); + assert!(failed.poison.get()); + let before = failed.trace.borrow().clone(); + assert_eq!(execute(&failed, &cache, asset, arguments(operation)), Err(Error::ContextPoisoned)); + assert_eq!(*failed.trace.borrow(), before); + unload(&failed, &cache).unwrap(); + assert_eq!(*failed.trace.borrow(), before); + assert_eq!(ready(&cache), 0); +} + #[test] fn qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation() { for operation in qwen_ffi::QSA_OPERATIONS { @@ -80,35 +99,12 @@ fn qsa_qualified_asset_receipts_refuse_corruption_before_cache_mutation() { )))] #[test] fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { - use crate::{Driver, FixedPairKernels, ProjectionKernels}; - use std::marker::PhantomData; + use crate::Driver; let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let context = Context { - driver: &driver, - handle: Some(ffi::ContextHandle::synthetic(1)), - ordinal: 0, - budget: 1_000_000, - allocated: Cell::new(99), - poisoned: Cell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::>::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), - qwen_kernels: Cache::new(), - }; + let context = platform_context(&driver, 1_000_000, 99); for operation in MOE_OPERATIONS { let layout = operation.layout(); - let mut buffers: Vec<_> = (0..layout.count) - .map(|i| DeviceBuffer { - context: &context, - handle: Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))), - bytes: layout.bytes[i], - _thread: PhantomData, - borrowed: false, - }) - .collect(); + let mut buffers = synthetic_layout_buffers(&context, layout); let (inputs, outputs) = buffers.split_at_mut(layout.count - 1); let result = match operation { Operation::MoeSwiglu => context.moe_swiglu_f32(&inputs[0], &inputs[1], &mut outputs[0]), @@ -121,12 +117,32 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { assert_eq!(context.allocated.get(), 99); assert_eq!(ready(&context.qwen_kernels), 0); assert!(!context.poisoned.get()); - for (i, buffer) in buffers.iter_mut().enumerate() { - assert!(buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))); - assert_eq!(buffer.bytes, layout.bytes[i]); - // Synthetic owners have no CUDA allocation to free. - buffer.handle = None; - } + release_synthetic_layout_buffers(&mut buffers, layout); + } +} + +/// One synthetic buffer per layout entry, at `0x1000000 * (i + 1)`. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +fn synthetic_layout_buffers<'a>(context: &'a Context<'a>, layout: qwen_ffi::Layout) -> Vec> { + (0..layout.count).map(|i| synthetic_buffer(context, 0x1000000 * (i as u64 + 1), layout.bytes[i])).collect() +} + +/// Check that the buffers still hold their synthetic handles and sizes, then drop the handles (no allocation behind). +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +fn release_synthetic_layout_buffers(buffers: &mut [DeviceBuffer<'_>], layout: qwen_ffi::Layout) { + for (i, buffer) in buffers.iter_mut().enumerate() { + assert!(buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))); + assert_eq!(buffer.bytes, layout.bytes[i]); + // Synthetic owners have no CUDA allocation to free. + buffer.handle = None; } } @@ -137,72 +153,16 @@ fn moe_qualified_methods_refuse_unsupported_platform_without_mutation() { )))] #[test] fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { - use crate::{Driver, FixedPairKernels, ProjectionKernels}; - use std::marker::PhantomData; + use crate::Driver; let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let make_context = || Context { - driver: &driver, - handle: Some(ffi::ContextHandle::synthetic(1)), - ordinal: 0, - budget: 1_000_000, - allocated: Cell::new(99), - poisoned: Cell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::>::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), - qwen_kernels: Cache::new(), - }; - let context = make_context(); - let other = make_context(); + let context = platform_context(&driver, 1_000_000, 99); + let other = platform_context(&driver, 1_000_000, 99); for operation in qwen_ffi::QSA_OPERATIONS { let layout = operation.layout(); - let mut buffers: Vec<_> = (0..layout.count) - .map(|i| DeviceBuffer { - context: &context, - handle: Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))), - bytes: layout.bytes[i], - _thread: PhantomData, - borrowed: false, - }) - .collect(); + let mut buffers = synthetic_layout_buffers(&context, layout); let (inputs, outputs) = buffers.split_at_mut(layout.outputs.trailing_zeros() as usize); - let result = match operation { - Operation::QsaSplit => { - let (q, gate) = outputs.split_at_mut(1); - context.qsa_split_q_gate(&inputs[0], &mut q[0], &mut gate[0]) - } - Operation::QsaNormQ => context.qsa_norm_q(&inputs[0], &inputs[1], &mut outputs[0]), - Operation::QsaNormK => context.qsa_norm_k(&inputs[0], &inputs[1], &mut outputs[0]), - Operation::QsaNormIndexQ => context.qsa_norm_index_q(&inputs[0], &inputs[1], &mut outputs[0]), - Operation::QsaRopeQ => context.qsa_rope_q(&inputs[0], 0, &mut outputs[0]), - Operation::QsaRopeK => context.qsa_rope_k(&inputs[0], 0, &mut outputs[0]), - Operation::QsaRopeIndexQ => context.qsa_rope_index_q(&inputs[0], 0, &mut outputs[0]), - Operation::QsaIndexAppend => { - context.qsa_index_append(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0) - } - Operation::QsaPackKv => { - let (k, v) = outputs.split_at_mut(1); - context.qsa_pack_kv(&inputs[0], &inputs[1], &mut k[0], &mut v[0]) - } - Operation::QsaBlockScores => { - context.qsa_block_scores(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0) - } - Operation::QsaBlockTopk => context.qsa_block_topk(&inputs[0], &mut outputs[0], 0), - Operation::QsaAttend => context.qsa_attend(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 1), - Operation::QsaGate => context.qsa_gate_f32(&inputs[0], &inputs[1], &mut outputs[0]), - _ => unreachable!("exact thirteen QSA methods"), - }; - assert_eq!(result, Err(Error::UnsupportedPlatform)); - let mut foreign = DeviceBuffer { - context: &other, - handle: Some(ffi::BufferHandle::synthetic(0x90000000)), - bytes: layout.bytes[0], - _thread: PhantomData, - borrowed: false, - }; + assert_eq!(call_qsa_method(&context, operation, inputs, outputs), Err(Error::UnsupportedPlatform)); + let mut foreign = synthetic_buffer(&other, 0x90000000, layout.bytes[0]); assert_eq!(context.qsa_call(operation, &[&foreign], 0), Err(Error::ContextMismatch)); foreign.handle = None; context.poisoned.set(true); @@ -212,11 +172,59 @@ fn qsa_qualified_public_slots_refuse_platform_without_owner_mutation() { assert_eq!(context.allocated.get(), 99); assert_eq!(ready(&context.qwen_kernels), 0); assert!(!context.poisoned.get()); - for (i, buffer) in buffers.iter_mut().enumerate() { - assert!(buffer.handle == Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1)))); - assert_eq!(buffer.bytes, layout.bytes[i]); - // Synthetic owners have no CUDA allocation to free. - buffer.handle = None; + release_synthetic_layout_buffers(&mut buffers, layout); + } +} + +/// The public method of `operation` called with the split input and output buffers. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +fn call_qsa_method( + context: &Context<'_>, + operation: Operation, + inputs: &[DeviceBuffer<'_>], + outputs: &mut [DeviceBuffer<'_>], +) -> Result<()> { + match operation { + Operation::QsaSplit => { + let (q, gate) = outputs.split_at_mut(1); + context.qsa_split_q_gate(&inputs[0], &mut q[0], &mut gate[0]) } + Operation::QsaNormQ => context.qsa_norm_q(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::QsaNormK => context.qsa_norm_k(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::QsaNormIndexQ => context.qsa_norm_index_q(&inputs[0], &inputs[1], &mut outputs[0]), + Operation::QsaRopeQ => context.qsa_rope_q(&inputs[0], 0, &mut outputs[0]), + Operation::QsaRopeK => context.qsa_rope_k(&inputs[0], 0, &mut outputs[0]), + Operation::QsaRopeIndexQ => context.qsa_rope_index_q(&inputs[0], 0, &mut outputs[0]), + _ => call_qsa_index_method(context, operation, inputs, outputs), + } +} + +/// The public method of the index, pack, score, top-k, attend and gate operations. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +fn call_qsa_index_method( + context: &Context<'_>, + operation: Operation, + inputs: &[DeviceBuffer<'_>], + outputs: &mut [DeviceBuffer<'_>], +) -> Result<()> { + match operation { + Operation::QsaIndexAppend => context.qsa_index_append(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0), + Operation::QsaPackKv => { + let (k, v) = outputs.split_at_mut(1); + context.qsa_pack_kv(&inputs[0], &inputs[1], &mut k[0], &mut v[0]) + } + Operation::QsaBlockScores => context.qsa_block_scores(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 0), + Operation::QsaBlockTopk => context.qsa_block_topk(&inputs[0], &mut outputs[0], 0), + Operation::QsaAttend => context.qsa_attend(&inputs[0], &inputs[1], &inputs[2], &mut outputs[0], 1), + Operation::QsaGate => context.qsa_gate_f32(&inputs[0], &inputs[1], &mut outputs[0]), + _ => unreachable!("exact thirteen QSA methods"), } } diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs index 2066dd15..789afacb 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_actual_owner_poison_missing.rs @@ -1,5 +1,14 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge, mtp_new_exact_dense_and_input_ranges_fail_closed, mtp_new_public_dense_preflight_preserves_owners_on_refusal, mtp_new_pair_second_lookup_and_restore_failures_publish_nothing. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge, +//! mtp_new_exact_dense_and_input_ranges_fail_closed, mtp_new_public_dense_preflight_preserves_owners_on_refusal, +//! mtp_new_pair_second_lookup_and_restore_failures_publish_nothing. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +use super::full_s2_bank_extent::{platform_context, synthetic_buffer}; #[allow(unused_imports)] use super::*; @@ -10,83 +19,24 @@ use super::*; )))] #[test] fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { - use crate::{Driver, FixedPairKernels, ProjectionKernels}; - use std::marker::PhantomData; + use crate::Driver; let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let make_context = || Context { - driver: &driver, - handle: Some(ffi::ContextHandle::synthetic(1)), - ordinal: 0, - budget: 100_000_000, - allocated: Cell::new(99), - poisoned: Cell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::>::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), - qwen_kernels: Cache::new(), - }; - let context = make_context(); - let other = make_context(); + let context = platform_context(&driver, 100_000_000, 99); + let other = platform_context(&driver, 100_000_000, 99); for op in OPERATIONS { let layout = op.layout(); let asset = qwen_ffi::mock_asset(op); - let make_buffer = |i: usize| DeviceBuffer { - context: &context, - handle: Some(ffi::BufferHandle::synthetic(0x10000000 * (i + 1) as u64)), - bytes: layout.bytes[i], - _thread: PhantomData, - borrowed: false, - }; - let mut storage: Vec<_> = (0..layout.count).map(make_buffer).collect(); - let call = |buffers: &[&DeviceBuffer<'_>], qualified: bool, epsilon: f32| { - admission( - &context, - buffers, - Admission { - operation: op, - layout: Ok(layout), - asset: if qualified { Some(&asset) } else { None }, - epsilon, - in_place: false, - }, - ) - }; - let refs: Vec<_> = storage.iter().collect(); - assert!(call(&refs, true, 1e-6).is_ok()); - assert!(matches!(call(&refs, false, 1e-6), Err(Error::UnsupportedQwenOperation))); - context.poisoned.set(true); - assert!(matches!(call(&refs, true, 1e-6), Err(Error::ContextPoisoned))); - context.poisoned.set(false); - let foreign = DeviceBuffer { - context: &other, - handle: Some(ffi::BufferHandle::synthetic(0x6000000)), - bytes: layout.bytes[0], - _thread: PhantomData, - borrowed: false, - }; - let mut foreign_refs = refs.clone(); - foreign_refs[0] = &foreign; - assert!(matches!(call(&foreign_refs, true, 1e-6), Err(Error::ContextMismatch))); - context.allocated.set(context.budget + 1); - assert!(matches!(call(&refs, true, 1e-6), Err(Error::BudgetExceeded))); - context.allocated.set(99); - if op == Operation::Norm { - for eps in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] { - assert!(matches!(call(&refs, true, eps), Err(Error::InvalidQwenShape))); - } - for eps in [0.0, -0.0, 1e-6] { - assert!(call(&refs, true, eps).is_ok()); - } - } + let mut storage: Vec<_> = (0..layout.count) + .map(|i| synthetic_buffer(&context, 0x10000000 * (i as u64 + 1), layout.bytes[i])) + .collect(); + let probe = AdmissionProbe { context: &context, op, layout, asset: &asset }; + let foreign = synthetic_buffer(&other, 0x6000000, layout.bytes[0]); + probe.assert_gates_refuse(&storage, &foreign); + probe.assert_epsilon_gate(&storage); assert_eq!(ready(&context.qwen_kernels), 0); assert_eq!(context.allocated.get(), 99); - drop(foreign_refs); - drop(refs); storage[0].handle = None; - assert!(matches!(call(&storage.iter().collect::>(), true, 1e-6), Err(Error::ContextPoisoned))); + assert!(matches!(probe.call(&storage.iter().collect::>(), true, 1e-6), Err(Error::ContextPoisoned))); context.poisoned.set(true); other.poisoned.set(true); let last = storage.pop().unwrap(); @@ -98,6 +48,72 @@ fn qwen_actual_owner_poison_missing_budget_refusal_and_retained_charge() { other.poisoned.set(false); } } + +/// One operation of the fixed Qwen set admitted against a context: the context, its layout and its qualified asset. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +struct AdmissionProbe<'a> { + context: &'a Context<'a>, + op: Operation, + layout: qwen_ffi::Layout, + asset: &'a Asset, +} + +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +impl AdmissionProbe<'_> { + fn call(&self, buffers: &[&DeviceBuffer<'_>], qualified: bool, epsilon: f32) -> Result<()> { + admission( + self.context, + buffers, + Admission { + operation: self.op, + layout: Ok(self.layout), + asset: if qualified { Some(self.asset) } else { None }, + epsilon, + in_place: false, + }, + ) + .map(|_| ()) + } + + /// Qualified, unqualified, poisoned, foreign-owner and over-budget calls over the storage buffers. + fn assert_gates_refuse(&self, storage: &[DeviceBuffer<'_>], foreign: &DeviceBuffer<'_>) { + let refs: Vec<_> = storage.iter().collect(); + assert!(self.call(&refs, true, 1e-6).is_ok()); + assert!(matches!(self.call(&refs, false, 1e-6), Err(Error::UnsupportedQwenOperation))); + self.context.poisoned.set(true); + assert!(matches!(self.call(&refs, true, 1e-6), Err(Error::ContextPoisoned))); + self.context.poisoned.set(false); + let mut foreign_refs = refs.clone(); + foreign_refs[0] = foreign; + assert!(matches!(self.call(&foreign_refs, true, 1e-6), Err(Error::ContextMismatch))); + self.context.allocated.set(self.context.budget + 1); + assert!(matches!(self.call(&refs, true, 1e-6), Err(Error::BudgetExceeded))); + self.context.allocated.set(99); + } + + /// The norm epsilon must be finite and non-negative; the other operations have no epsilon gate. + fn assert_epsilon_gate(&self, storage: &[DeviceBuffer<'_>]) { + if self.op != Operation::Norm { + return; + } + let refs: Vec<_> = storage.iter().collect(); + for eps in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] { + assert!(matches!(self.call(&refs, true, eps), Err(Error::InvalidQwenShape))); + } + for eps in [0.0, -0.0, 1e-6] { + assert!(self.call(&refs, true, eps).is_ok()); + } + } +} + #[test] fn mtp_new_exact_dense_and_input_ranges_fail_closed() { for operation in [ @@ -136,58 +152,17 @@ fn mtp_new_exact_dense_and_input_ranges_fail_closed() { )))] #[test] fn mtp_new_public_dense_preflight_preserves_owners_on_refusal() { - use crate::{Driver, FixedPairKernels, ProjectionKernels}; - use std::marker::PhantomData; + use crate::Driver; let driver = Driver { api: Rc::new(ffi::Api), version: 0 }; - let context = Context { - driver: &driver, - handle: Some(ffi::ContextHandle::synthetic(1)), - ordinal: 0, - budget: 100000, - allocated: Cell::new(99), - poisoned: Cell::new(false), - vector_add_kernel: Cell::new(None), - matvec_kernel: Cell::new(None), - q5_k_kernel: Cell::>::new(None), - q6_k_kernel: Cell::new(None), - common_quantizer: Cell::new(None), - projection_kernels: std::array::from_fn(|_| Cell::>::new(None)), - qwen_kernels: Cache::new(), - }; + let context = platform_context(&driver, 100000, 99); let layout = qwen_ffi::mtp_dense_layout(Operation::MtpDenseChunk, 0).unwrap(); let mut buffers: Vec<_> = [layout.bytes[0], layout.bytes[1], layout.bytes[2], 24576] .iter() .enumerate() - .map(|(i, bytes)| DeviceBuffer { - context: &context, - handle: Some(ffi::BufferHandle::synthetic(0x1000000 * (i as u64 + 1))), - bytes: *bytes, - _thread: PhantomData, - borrowed: false, - }) + .map(|(i, bytes)| synthetic_buffer(&context, 0x1000000 * (i as u64 + 1), *bytes)) .collect(); let (inputs, out) = buffers.split_at_mut(3); - assert_eq!( - context.mtp_dense_attend_f16(&inputs[0], &inputs[1], &inputs[2], &mut out[0], crate::MAX_CONTEXT_CELLS as u32), - Err(Error::InvalidQwenShape) - ); - let prior = out[0].bytes; - out[0].bytes -= 4; - assert_eq!( - context.mtp_dense_attend_f16(&inputs[0], &inputs[1], &inputs[2], &mut out[0], 0), - Err(Error::InvalidQwenShape) - ); - out[0].bytes = prior; - context.allocated.set(99999); - assert_eq!( - context.mtp_dense_attend_f16(&inputs[0], &inputs[1], &inputs[2], &mut out[0], 0), - Err(Error::BudgetExceeded) - ); - context.allocated.set(99); - assert_eq!( - context.mtp_dense_attend_f16(&inputs[0], &inputs[1], &inputs[2], &mut out[0], 0), - Err(Error::UnsupportedPlatform) - ); + assert_dense_attend_refusals(&context, inputs, &mut out[0]); assert_eq!(context.allocated.get(), 99); assert!(!context.poisoned.get()); assert_eq!(ready(&context.qwen_kernels), 0); @@ -195,6 +170,28 @@ fn mtp_new_public_dense_preflight_preserves_owners_on_refusal() { buffer.handle = None; } } + +/// The public dense attend on `inputs` and `out` refuses an oversize context, a short output, an exceeded budget and +/// the unsupported platform, in that order, without touching the owner. +#[cfg(not(all( + feature = "cuda-driver", + any(target_os = "linux", target_os = "windows"), + target_pointer_width = "64" +)))] +fn assert_dense_attend_refusals(context: &Context<'_>, inputs: &[DeviceBuffer<'_>], out: &mut DeviceBuffer<'_>) { + let attend = |out: &mut DeviceBuffer<'_>, cells: u32| { + context.mtp_dense_attend_f16(&inputs[0], &inputs[1], &inputs[2], out, cells) + }; + assert_eq!(attend(out, crate::MAX_CONTEXT_CELLS as u32), Err(Error::InvalidQwenShape)); + let prior = out.bytes; + out.bytes -= 4; + assert_eq!(attend(out, 0), Err(Error::InvalidQwenShape)); + out.bytes = prior; + context.allocated.set(99999); + assert_eq!(attend(out, 0), Err(Error::BudgetExceeded)); + context.allocated.set(99); + assert_eq!(attend(out, 0), Err(Error::UnsupportedPlatform)); +} #[test] fn mtp_new_pair_second_lookup_and_restore_failures_publish_nothing() { let chunk = qwen_ffi::asset(Operation::MtpDenseChunk).unwrap(); diff --git a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs index fd5513de..0d8ad43f 100644 --- a/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs +++ b/crates/cuda-driver/src/qwen_dispatch/tests/qwen_attempted_launch_always_syncs.rs @@ -1,4 +1,7 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): qwen_attempted_launch_always_syncs_and_uncertainty_never_retries, qwen_failed_teardown_consumes_once_and_retains_other_slots, qwen_receipt_refusal_precedes_any_backend_mutation, qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! qwen_attempted_launch_always_syncs_and_uncertainty_never_retries, +//! qwen_failed_teardown_consumes_once_and_retains_other_slots, qwen_receipt_refusal_precedes_any_backend_mutation, +//! qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary .... #[allow(unused_imports)] use super::*; @@ -56,17 +59,7 @@ fn qwen_receipt_refusal_precedes_any_backend_mutation() { qwen_ffi::asset(op).expect("admitted component").validate(op).unwrap(); for change in 0..9 { let mut asset = qwen_ffi::mock_asset(op); - match change { - 0 => asset.receipt.version = 2, - 1 => asset.receipt.abi_version = 2, - 2 => asset.receipt.topology[0] += 1, - 3 => asset.receipt.source_sha256[0] ^= 1, - 4 => asset.receipt.ptx_sha256[0] ^= 1, - 5 => asset.receipt.oracle_sha256[0] ^= 1, - 6 => asset.receipt.compiler = "sentinel credential/path/prompt", - 7 => asset.ptx = b"wrong frozen bytes\0", - _ => asset.operation = OPERATIONS[(op as usize + 1) % OPERATIONS.len()], - } + corrupt_receipt(&mut asset, op, change); let backend = Mock::default(); let cache = Cache::new(); let result = @@ -78,6 +71,22 @@ fn qwen_receipt_refusal_precedes_any_backend_mutation() { } } } + +/// Corrupt one piece of the frozen asset: the receipt fields 0 to 6, the PTX bytes (7) or the operation (any other). +fn corrupt_receipt(asset: &mut Asset, op: Operation, change: usize) { + match change { + 0 => asset.receipt.version = 2, + 1 => asset.receipt.abi_version = 2, + 2 => asset.receipt.topology[0] += 1, + 3 => asset.receipt.source_sha256[0] ^= 1, + 4 => asset.receipt.ptx_sha256[0] ^= 1, + 5 => asset.receipt.oracle_sha256[0] ^= 1, + 6 => asset.receipt.compiler = "sentinel credential/path/prompt", + 7 => asset.ptx = b"wrong frozen bytes\0", + _ => asset.operation = OPERATIONS[(op as usize + 1) % OPERATIONS.len()], + } +} + #[test] fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { assert!(native_span(i32::MAX as usize + 1).is_ok()); @@ -89,49 +98,71 @@ fn qwen_exact_shapes_alignment_endpoints_aliases_and_signed_byte_boundary() { let handles = std::array::from_fn(|i| ffi::BufferHandle::synthetic(0x10000000 * (i as u64 + 1))); let bytes = op.layout().bytes; assert!(ranges(op, handles, bytes, false).is_ok()); - for i in 0..op.layout().count { - let mut wrong = bytes; - wrong[i] = wrong[i].saturating_sub(1); - assert_eq!(ranges(op, handles, wrong, false), Err(Error::InvalidQwenShape)); - for address in [0, u64::MAX - 3, handles[i].qwen_address() + 1] { - // A byte-aligned buffer (KAR PLE) has no misalignment case. - if address == handles[i].qwen_address() + 1 && op.layout().align[i] == 1 { - continue; - } - let mut wrong = handles; - wrong[i] = ffi::BufferHandle::synthetic(address); - assert_eq!(ranges(op, wrong, bytes, false), Err(Error::InvalidQwenShape)); + assert_wrong_spans_and_addresses_refused(op, handles, bytes); + assert_output_overlaps_refused(op, handles, bytes); + assert_in_place_admission(op, handles, bytes); + } +} + +/// Each buffer too short, at address 0, at the end of the address space or (when aligned) misaligned is refused. +fn assert_wrong_spans_and_addresses_refused(op: Operation, handles: [ffi::BufferHandle; 9], bytes: [usize; 9]) { + for i in 0..op.layout().count { + let mut wrong = bytes; + wrong[i] = wrong[i].saturating_sub(1); + assert_eq!(ranges(op, handles, wrong, false), Err(Error::InvalidQwenShape)); + for address in [0, u64::MAX - 3, handles[i].qwen_address() + 1] { + // A byte-aligned buffer (KAR PLE) has no misalignment case. + if address == handles[i].qwen_address() + 1 && op.layout().align[i] == 1 { + continue; } - } - for i in 0..op.layout().count { - for j in i + 1..op.layout().count { - if op.layout().outputs & ((1 << i) | (1 << j)) == 0 { - continue; - } - let mut wrong = handles; - wrong[j] = wrong[i]; - assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); - // Offset by a step that keeps buffer j aligned. - let step = 8.max(op.layout().align[j]); - if (bytes[i].min(bytes[j]) as u64) > step { - wrong[j] = ffi::BufferHandle::synthetic(wrong[i].qwen_address() + step); - assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); - } - } - } - let mut inplace = handles; - inplace[3] = inplace[0]; - if op == Operation::InjectResidual { - assert!(ranges(op, inplace, bytes, true).is_ok()); - inplace[3] = ffi::BufferHandle::synthetic(inplace[0].qwen_address() + 4); - assert_eq!(ranges(op, inplace, bytes, true), Err(Error::OutputAliasesInput)); - } else { - assert_eq!(ranges(op, handles, bytes, true), Err(Error::OutputAliasesInput)); + let mut wrong = handles; + wrong[i] = ffi::BufferHandle::synthetic(address); + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::InvalidQwenShape)); } } } + +/// An output aliased onto another buffer, exactly or by an aligned offset inside it, is refused. +fn assert_output_overlaps_refused(op: Operation, handles: [ffi::BufferHandle; 9], bytes: [usize; 9]) { + for i in 0..op.layout().count { + for j in i + 1..op.layout().count { + if op.layout().outputs & ((1 << i) | (1 << j)) == 0 { + continue; + } + let mut wrong = handles; + wrong[j] = wrong[i]; + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); + // Offset by a step that keeps buffer j aligned. + let step = 8.max(op.layout().align[j]); + if (bytes[i].min(bytes[j]) as u64) > step { + wrong[j] = ffi::BufferHandle::synthetic(wrong[i].qwen_address() + step); + assert_eq!(ranges(op, wrong, bytes, false), Err(Error::OutputAliasesInput)); + } + } + } +} + +/// Only the residual injection may run in place, and only exactly onto its input. +fn assert_in_place_admission(op: Operation, handles: [ffi::BufferHandle; 9], bytes: [usize; 9]) { + let mut inplace = handles; + inplace[3] = inplace[0]; + if op == Operation::InjectResidual { + assert!(ranges(op, inplace, bytes, true).is_ok()); + inplace[3] = ffi::BufferHandle::synthetic(inplace[0].qwen_address() + 4); + assert_eq!(ranges(op, inplace, bytes, true), Err(Error::OutputAliasesInput)); + } else { + assert_eq!(ranges(op, handles, bytes, true), Err(Error::OutputAliasesInput)); + } +} + #[test] fn qwen_bf16_structural_geometry_and_wide_address_admission() { + assert_bf16_block_selection(); + assert_bf16_shape_refusals(); + assert_bf16_address_admission(); +} + +fn assert_bf16_block_selection() { // These are new checks of the new host selector, not numerical tests // of previously qualified CUDA. Strict improvements preserve ties. for (n, block) in [ @@ -154,6 +185,9 @@ fn qwen_bf16_structural_geometry_and_wide_address_admission() { for (n, block) in [(64, 32), (128, 64), (192, 96), (256, 128), (320, 160), (384, 192), (448, 224), (512, 256)] { assert_eq!(qwen_ffi::bf16_layout(1, n).unwrap().block, block); } +} + +fn assert_bf16_shape_refusals() { for (m, n) in [ (0, 2), (1, 0), @@ -166,6 +200,9 @@ fn qwen_bf16_structural_geometry_and_wide_address_admission() { ] { assert!(matches!(qwen_ffi::bf16_layout(m, n), Err(Error::InvalidBf16ProjectionShape))); } +} + +fn assert_bf16_address_admission() { let handles = [0x1000000, 0x2000000, 0x3000000, 0x4000000, 0x5000000, 0x6000000, 0x7000000, 0x8000000, 0] .map(ffi::BufferHandle::synthetic); let layout = qwen_ffi::bf16_layout(3, 66).unwrap(); diff --git a/crates/cuda-driver/src/qwen_ffi/bf16_receipt_types.rs b/crates/cuda-driver/src/qwen_ffi/bf16_receipt_types.rs index 6fd20a6f..4b4896ce 100644 --- a/crates/cuda-driver/src/qwen_ffi/bf16_receipt_types.rs +++ b/crates/cuda-driver/src/qwen_ffi/bf16_receipt_types.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: BF16_RECEIPT, BF16_ASSETS, PLE_RECEIPT, PLE_ASSETS, PLE_VALUE_FULL_RECEIPT, PLE_VALUE_FULL_ASSET .... +//! Moved out of the parent module by STRA-338: BF16_RECEIPT, BF16_ASSETS, PLE_RECEIPT, PLE_ASSETS, +//! PLE_VALUE_FULL_RECEIPT, PLE_VALUE_FULL_ASSET .... #[allow(unused_imports)] use super::*; @@ -19,9 +20,11 @@ pub(super) const BF16_RECEIPT: Receipt = Receipt { 0x9a, 0x48, 0xcc, 0x38, 0xf3, 0x09, 0xd3, 0x27, 0xa2, 0x97, 0x6c, 0x3e, 0xd3, 0xda, ], compiler: "candidate manual PTX9.0, installed Driver595.91.07 JIT; unchanged original NVCC12.8.93/GCC13.3", - compiler_flags: "candidate two ordered fma.rn.ftz, native adaptive/XOR order; original -O3 -arch=sm_120 --use_fast_math --ftz=true --fmad=true", + compiler_flags: "candidate two ordered fma.rn.ftz, native adaptive/XOR order; original -O3 -arch=sm_120 \ + --use_fast_math --ftz=true --fmad=true", qualification_receipt: "STRA-145 ba39263f-610a-41b2-895a-3f8fb2d404cf", - comparison: "independent123-case frozen corpus30313768,246pairs174024words: exact nonNaN bits/signzero/Inf, equalNaNclass and canaries; CUDA13offlineassembly/actualalpha/fullmodel open", + comparison: "independent123-case frozen corpus30313768,246pairs174024words: exact nonNaN bits/signzero/Inf, \ + equalNaNclass and canaries; CUDA13offlineassembly/actualalpha/fullmodel open", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -69,7 +72,8 @@ pub(super) const PLE_RECEIPT: Receipt = Receipt { compiler: "NVCC 12.8.93; CUDA 12.8.1; installed Driver595.91.07; SM120", compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", qualification_receipt: "STRA-161 ada1a470-76ad-47af-a326-e388ae592d51", - comparison: "Frozen default-PLE corpus:26 exact-bit comparisons709196 values;5 failure-only intermediate refusals; narrowed finite-intermediate domain; fullmodel and actual weight-payload quality open", + comparison: "Frozen default-PLE corpus:26 exact-bit comparisons709196 values;5 failure-only intermediate refusals; \ + narrowed finite-intermediate domain; fullmodel and actual weight-payload quality open", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -91,10 +95,14 @@ pub(super) const PLE_VALUE_FULL_RECEIPT: Receipt = Receipt { 0x61, 0x80, 0xf3, 0xde, 0xbc, 0x74, 0x34, 0x9d, 0x62, 0xe2, 0x9c, 0x17, 0xe0, 0x75, 0x17, 0xac, 0x6c, 0x15, 0x1e, 0x71, 0xea, 0xe6, 0x72, 0x97, 0x85, 0x66, 0x49, 0x58, 0x84, 0x23, 0x25, 0xd0, ], - compiler: "NVCC 12.8.93; CUDA 12.8.1; GPU-hidden runc; pinned image520292dbb4f755fd360766059e62956e9379485d9e073bbd2f6e3c20c270ed66; SM120", + compiler: "NVCC 12.8.93; CUDA 12.8.1; GPU-hidden runc; pinned \ + image520292dbb4f755fd360766059e62956e9379485d9e073bbd2f6e3c20c270ed66; SM120", compiler_flags: "-std=c++17 -O3 -ptx -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", - qualification_receipt: "STRA-172 workResult7ae0dd7c-ab21-4bcc-ba13-9dd69837714a; RTX5090 installedDriver595.91.07; logSHA9a96689d44d7b228a9ebbda46cf96561ac92ee12d8adff75d25560dc9c9e491c", - comparison: "Original40 admitted tile kernels FIRST versus whole2560 Value: 5120 finite exactF32bits ordinary/signedzero; last-row NaN with2559 unchanged prefix;6 guards; allocated0. Component only, no model/quality/performance/release claim", + qualification_receipt: "STRA-172 workResult7ae0dd7c-ab21-4bcc-ba13-9dd69837714a; RTX5090 installedDriver595.91.07; \ + logSHA9a96689d44d7b228a9ebbda46cf96561ac92ee12d8adff75d25560dc9c9e491c", + comparison: "Original40 admitted tile kernels FIRST versus whole2560 Value: 5120 finite exactF32bits \ + ordinary/signedzero; last-row NaN with2559 unchanged prefix;6 guards; allocated0. Component only, no \ + model/quality/performance/release claim", ..PLE_RECEIPT }; pub(super) const PLE_VALUE_FULL_ASSET: Asset = Asset { @@ -121,8 +129,10 @@ pub(super) const GR_RECEIPT: Receipt = Receipt { ], compiler: "authored PTX9.0 norm RCP/FMA derivative; unchanged four NVCC12.8.93 postops", compiler_flags: "norm runtime cvt/rcp.approx.ftz/fma.rn.ftz matches actual d080 SASS DAG; postops byte unchanged", - qualification_receipt: "STRA-169 actual GPU norm49d3b9ca-eed1-45b1-9845-d6fbf2199612; original10240 exact bits; batch4/16/64 scalar-first860160 exact bits; unchanged postops prior evidence", - comparison: "Norm actual original10240 words zero differences and batch860160 words zero differences; allocated0; finite guards8; unchanged postops saturation23ae9aa8 prior; fullmodel quality/performance open", + qualification_receipt: "STRA-169 actual GPU norm49d3b9ca-eed1-45b1-9845-d6fbf2199612; original10240 exact bits; \ + batch4/16/64 scalar-first860160 exact bits; unchanged postops prior evidence", + comparison: "Norm actual original10240 words zero differences and batch860160 words zero differences; allocated0; \ + finite guards8; unchanged postops saturation23ae9aa8 prior; fullmodel quality/performance open", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -150,8 +160,11 @@ pub(super) const GDN_RECEIPT: Receipt = Receipt { ], compiler: "NVCC12.8.93 CUDA12.8.1; installed Driver595.91.07 JIT; SM120", compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --use_fast_math --fmad=true; nativeGDN=true fusedGDN=false", - qualification_receipt: "STRA-163 92e3e33a-0803-4a5e-8ae0-edd4ae21949e + lowering8ceaf3e8 + pairedf71ac7b2; independent70d151b7", - comparison: "63 same-input comparisons11808960 words exact; 14 paired primitive boundaries; identical33-op log DAG64964a52; finite-intermediate fixed-realization conditional component parity, not absolute-real/allfinite/unequal-upstream/fullmodel quality", + qualification_receipt: "STRA-163 92e3e33a-0803-4a5e-8ae0-edd4ae21949e + lowering8ceaf3e8 + pairedf71ac7b2; \ + independent70d151b7", + comparison: "63 same-input comparisons11808960 words exact; 14 paired primitive boundaries; identical33-op log \ + DAG64964a52; finite-intermediate fixed-realization conditional component parity, not \ + absolute-real/allfinite/unequal-upstream/fullmodel quality", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -179,9 +192,11 @@ pub(super) const MOE_RECEIPT: Receipt = Receipt { 0xf3, 0x97, 0x02, 0x17, 0xb1, 0x72, 0x9c, 0xa9, 0x7b, 0x2d, 0x84, 0xb2, 0x99, 0x48, ], compiler: "NVCC12.8.93 CUDA12.8.1; installed Driver595.91.07; SM120", - compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --fmad=true --ftz=false; explicit native SwiGLU intrinsics; legacy shared/combine ordinary flags", + compiler_flags: "-ptx -O3 -std=c++17 -arch=sm_120 --fmad=true --ftz=false; explicit native SwiGLU intrinsics; \ + legacy shared/combine ordinary flags", qualification_receipt: "STRA-167 1999cfbd-15c8-4edd-86fe-e51378eeb1ff; rawmanifest63742810", - comparison: "Frozen10case corpus11524 F32words exact/signzero;3 malformed refusals; defined exponential saturation preserved; component profile only, no allfinite/fullmodel proof", + comparison: "Frozen10case corpus11524 F32words exact/signzero;3 malformed refusals; defined exponential saturation \ + preserved; component profile only, no allfinite/fullmodel proof", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -209,7 +224,8 @@ pub(super) const QSA_NATIVE_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math", qualification_receipt: "STRA16400fa6c92/00487c4a-67e2-41d2-9b92-a91c22d680e2; STRA165e8c27aa7", - comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", + comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention \ + DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -230,7 +246,8 @@ pub(super) const QSA_SELECT_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false", qualification_receipt: "STRA16400fa6c92/00487c4a-67e2-41d2-9b92-a91c22d680e2; STRA165e8c27aa7", - comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", + comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention \ + DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; diff --git a/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs b/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs index bf2669b5..964521c2 100644 --- a/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs +++ b/crates/cuda-driver/src/qwen_ffi/impl_operation_2.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Operation, fn kar_ple_layout, fn bf16_layout, fn inspect_ptx, impl Asset, fn ple_asset .... +//! Moved out of the parent module by STRA-338: impl Operation, fn kar_ple_layout, fn bf16_layout, fn inspect_ptx, impl +//! Asset, fn ple_asset .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_ffi/mtp_extended_assets_types.rs b/crates/cuda-driver/src/qwen_ffi/mtp_extended_assets_types.rs index 354e8889..f6e1678d 100644 --- a/crates/cuda-driver/src/qwen_ffi/mtp_extended_assets_types.rs +++ b/crates/cuda-driver/src/qwen_ffi/mtp_extended_assets_types.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: MTP_EXTENDED_ASSETS, MTP_S2_FULL_RECEIPT, MTP_S2_FULL_ASSETS, Storage, Arguments. +//! Moved out of the parent module by STRA-338: MTP_EXTENDED_ASSETS, MTP_S2_FULL_RECEIPT, MTP_S2_FULL_ASSETS, Storage, +//! Arguments. #[allow(unused_imports)] use super::*; @@ -69,8 +70,14 @@ pub(super) const MTP_S2_FULL_RECEIPT: Receipt = Receipt { 0x43, 0x81, 0x4a, 0x9c, 0x17, 0x9a, 0xba, 0xba, 0x8f, 0xe0, 0xa8, 0x0b, 0x88, 0xa3, 0x15, 0xbc, 0x94, 0xc4, 0x38, 0xf3, 0x9b, 0x38, 0x42, 0xf4, 0xe4, 0x30, 0x1e, 0x96, 0xa0, 0x32, 0xf7, 0x8d, ], - qualification_receipt: "STRA-172 f05040fb-af66-4112-84bd-34d4cdcf9eae; independent frozen47d85033; actual log355b310041afd479dd82f96b73fc782e4fd0757e77106c68b544d6d86e98536a", - comparison: "NEW full-vs40legacy-vsoriginal:115200 exact paired words,18finite/6late/4badIDs; oracle cubin38c0ca6fd0cdd9d9af39f657f407cfbd9df3919747c4e7cf260ed88079061621; helperdfa0f329d9fd40657fd14651866fa92b72d43feb1d4e71e0c877f29eebd10a17; ELFa50c4361380a1ae7f0fda14cf590068ecd565fb15ca0bd6c7b9239c61b0e51eb; corpus723d44b9a561198b59db508926d7897cfb807c308d7de33e3f9469eab7613dea; component-only,no fullmodel/performance claim", + qualification_receipt: "STRA-172 f05040fb-af66-4112-84bd-34d4cdcf9eae; independent frozen47d85033; actual \ + log355b310041afd479dd82f96b73fc782e4fd0757e77106c68b544d6d86e98536a", + comparison: "NEW full-vs40legacy-vsoriginal:115200 exact paired words,18finite/6late/4badIDs; oracle \ + cubin38c0ca6fd0cdd9d9af39f657f407cfbd9df3919747c4e7cf260ed88079061621; \ + helperdfa0f329d9fd40657fd14651866fa92b72d43feb1d4e71e0c877f29eebd10a17; \ + ELFa50c4361380a1ae7f0fda14cf590068ecd565fb15ca0bd6c7b9239c61b0e51eb; \ + corpus723d44b9a561198b59db508926d7897cfb807c308d7de33e3f9469eab7613dea; component-only,no \ + fullmodel/performance claim", ..MTP_S2_RECEIPT }; pub(super) const MTP_S2_FULL_ASSETS: [Asset; 2] = [ diff --git a/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs b/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs index 69c1fb27..d3a6e3d7 100644 --- a/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs +++ b/crates/cuda-driver/src/qwen_ffi/mtp_s2_full_layout_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn mtp_s2_full_layout, fn mtp_extended_layout, fn mtp_input_layout, fn mtp_dense_layout. +//! Moved out of the parent module by STRA-338: fn mtp_s2_full_layout, fn mtp_extended_layout, fn mtp_input_layout, fn +//! mtp_dense_layout. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/qwen_ffi/n_types.rs b/crates/cuda-driver/src/qwen_ffi/n_types.rs index 65a16439..9ae8fc69 100644 --- a/crates/cuda-driver/src/qwen_ffi/n_types.rs +++ b/crates/cuda-driver/src/qwen_ffi/n_types.rs @@ -211,7 +211,8 @@ pub(super) const ROUTE_RECEIPT: Receipt = Receipt { compiler: "NVCC 12.8.93; CUDA 12.8.1; GCC 13.3", compiler_flags: "-ptx -O3 -std=c++17 -arch=compute_120; no --use_fast_math", qualification_receipt: "STRA-166 b31a40ef-50b1-4ece-8d9d-1467c1feb388", - comparison: "RTX5090 driver595.91.07: five synthetic cases, 50 IDs and 50 F32 weight bits exact against unchanged native oracle; model quality unqualified", + comparison: "RTX5090 driver595.91.07: five synthetic cases, 50 IDs and 50 F32 weight bits exact against unchanged \ + native oracle; model quality unqualified", abi_version: 1, topology: [512, 10, 1], }; diff --git a/crates/cuda-driver/src/qwen_ffi/qsa_attention_receipt_types.rs b/crates/cuda-driver/src/qwen_ffi/qsa_attention_receipt_types.rs index 3f2f9b8a..020db166 100644 --- a/crates/cuda-driver/src/qwen_ffi/qsa_attention_receipt_types.rs +++ b/crates/cuda-driver/src/qwen_ffi/qsa_attention_receipt_types.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: QSA_ATTENTION_RECEIPT, QSA_GATE_RECEIPT, QSA_ASSETS, KAR_PLE_RECEIPT, KAR_PLE_ASSETS, MTP_INPUT_RECEIPT .... +//! Moved out of the parent module by STRA-338: QSA_ATTENTION_RECEIPT, QSA_GATE_RECEIPT, QSA_ASSETS, KAR_PLE_RECEIPT, +//! KAR_PLE_ASSETS, MTP_INPUT_RECEIPT .... #[allow(unused_imports)] use super::*; @@ -20,7 +21,8 @@ pub(super) const QSA_ATTENTION_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true --ftz=false", qualification_receipt: "STRA16400fa6c92/00487c4a-67e2-41d2-9b92-a91c22d680e2; STRA165e8c27aa7", - comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", + comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention \ + DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -41,7 +43,8 @@ pub(super) const QSA_GATE_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93; SM120; installed Driver595.91.07/13020", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --use_fast_math", qualification_receipt: "STRA16400fa6c92/00487c4a-67e2-41d2-9b92-a91c22d680e2; STRA165e8c27aa7", - comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", + comparison: "59 original comparisons161245 exact words plus15 repair cases30336 exact words; attention \ + DOUBLErelativeL1<=1e-5; fixed corpus/profile only, no fullmodel proof", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -78,8 +81,10 @@ pub(super) const KAR_PLE_RECEIPT: Receipt = Receipt { ], compiler: "NVCC12.8.93 NVVM20.0.0 CL-35583870; cached CUDA12.8.1", compiler_flags: "-ptx -O3 -arch=sm_120 --ftz=false --prec-div=true --prec-sqrt=true --fmad=true", - qualification_receipt: "STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; DEV2df2eb3d-7d75-43a4-8019-7583921daf0d", - comparison: "RTX5090 driver595.91.07: 16unique updates including slot1048575, 67108864 byte sentinels/padding exact; 16reordered/repeated rows x160 F32 words/signzero/subnormal exact; selected literal domain only", + qualification_receipt: "STRA161 SDET7ca247af-161d-4215-9128-f4ba19018b7b; GPUbb8d133b-2286-4b59-8ab0-876c2ca03321; \ + DEV2df2eb3d-7d75-43a4-8019-7583921daf0d", + comparison: "RTX5090 driver595.91.07: 16unique updates including slot1048575, 67108864 byte sentinels/padding \ + exact; 16reordered/repeated rows x160 F32 words/signzero/subnormal exact; selected literal domain only", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -113,8 +118,10 @@ pub(super) const MTP_INPUT_RECEIPT: Receipt = Receipt { ], compiler: "NVCC12.8.93; installed Driver595.91.07 JIT on RTX5090", compiler_flags: "-std=c++17 -O3 -arch=sm_120 --use_fast_math --ftz=true --fmad=true", - qualification_receipt: "norm9bbd8977-7c77-44af-92f8-d2f366927e93; unchanged broadcast passing subset8dbd0ed3-7535-45e7-8c6d-c995775ab71a", - comparison: "Six paired norms38400 words0 mismatch; affected guards/unchanged inputs; unchanged broadcast exact; no model qualification", + qualification_receipt: "norm9bbd8977-7c77-44af-92f8-d2f366927e93; unchanged broadcast passing \ + subset8dbd0ed3-7535-45e7-8c6d-c995775ab71a", + comparison: "Six paired norms38400 words0 mismatch; affected guards/unchanged inputs; unchanged broadcast exact; \ + no model qualification", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -135,7 +142,8 @@ pub(super) const MTP_DENSE_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93; installed Driver595.91.07 JIT on RTX5090", compiler_flags: "-std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse; no --use_fast_math", qualification_receipt: "e656da6e-c02b-400e-af4f-02cd66cd090e", - comparison: "24 unique cases; 12 paired73728 exactwords0 mismatch; 12 component refusals; unchanged inputs/cleanup; no model qualification", + comparison: "24 unique cases; 12 paired73728 exactwords0 mismatch; 12 component refusals; unchanged \ + inputs/cleanup; no model qualification", abi_version: 1, topology: [N as u32, HC as u32, H as u32], }; @@ -190,7 +198,8 @@ pub(super) const MTP_GR_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93/GCC13.3 CUDA12.8.1", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse nofastmath", qualification_receipt: "STRA-169 c1367a37-a1f4-4acd-884f-447b77373bc1", - comparison: "Independent original source paired exact bits; fresh finite+invalid corpus; component-only, no modelquality claim", + comparison: "Independent original source paired exact bits; fresh finite+invalid corpus; component-only, no \ + modelquality claim", abi_version: 1, topology: [2560, 4, 320], }; @@ -211,7 +220,8 @@ pub(super) const MTP_S2_RECEIPT: Receipt = Receipt { compiler: "NVCC12.8.93/GCC13.3 CUDA12.8.1", compiler_flags: "-ptx -std=c++17 -O3 -arch=sm_120 --fmad=true; FTZfalse nofastmath", qualification_receipt: "STRA-169 e3771ec3-b182-4a28-8df2-9bf745c50686", - comparison: "Independent original source paired exact bits; fresh finite+invalid corpus; component-only, no modelquality claim", + comparison: "Independent original source paired exact bits; fresh finite+invalid corpus; component-only, no \ + modelquality claim", abi_version: 1, topology: [2560, 4, 320], }; From 49968a62ef998c95496af21a085a9192fe5dee31 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 16:34:54 +0100 Subject: [PATCH 2/2] STRA-338 size4 s06: WIP of the slice (unverified, committed by the integrator after the workers died) --- .s06check.sh | 5 +++++ .s06test.sh | 5 +++++ 2 files changed, 10 insertions(+) create mode 100644 .s06check.sh create mode 100644 .s06test.sh diff --git a/.s06check.sh b/.s06check.sh new file mode 100644 index 00000000..bd7569f4 --- /dev/null +++ b/.s06check.sh @@ -0,0 +1,5 @@ +export PATH=$HOME/.cargo/bin:$PATH +cd /mnt/c/Users/pavel/work/leleka/.git/wt/size3-cd6 +export CARGO_TARGET_DIR=$PWD/target/wsl +nice -n 10 cargo fmt -p leleka-cuda-driver 2>&1 | tail -5 +nice -n 10 cargo check --locked -j2 -p leleka-cuda-driver --features cuda-driver --all-targets --message-format short 2>&1 | grep -v "warning" | tail -40; echo CHECK_END diff --git a/.s06test.sh b/.s06test.sh new file mode 100644 index 00000000..0ec62da1 --- /dev/null +++ b/.s06test.sh @@ -0,0 +1,5 @@ +export PATH=$HOME/.cargo/bin:$PATH +cd /mnt/c/Users/pavel/work/leleka/.git/wt/size3-cd6 +export CARGO_TARGET_DIR=$PWD/target/wsl +flock /tmp/leleka-test.lock nice -n 10 cargo test --locked -j4 -p leleka-cuda-driver --features cuda-driver --lib 2>&1 | grep -E "^test result|FAILED|failed|panicked|error" | head -20 +echo TEST_END