From d239d27e7a8f5b94cc34b5d7cdfd978d2b71a51e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 7 Nov 2026 10:29:03 +0100 Subject: [PATCH] STRA-338 size4 s01: wrap wide comments and strings, split oversized tests into arrange/act/assert helpers --- crates/cuda-driver/src/arch_ptx.rs | 76 ++++-- .../src/arch_ptx/stream_k_off_fn.rs | 31 ++- .../src/asset_validation_cache_tests.rs | 145 +++++----- .../src/bringup_trace_enabled_fn.rs | 3 +- crates/cuda-driver/src/closed_kernels.rs | 9 +- .../src/closed_kernels/impl_program.rs | 3 +- .../flash_and_poison_signatures_match.rs | 128 ++++++--- .../tests/sealed_assets_match_their_pins.rs | 77 +++--- .../src/closed_kernels_gpu_smoke.rs | 5 +- crates/cuda-driver/src/compute_drain.rs | 8 +- crates/cuda-driver/src/deferred_status.rs | 42 +-- crates/cuda-driver/src/deferred_status_ffi.rs | 9 +- crates/cuda-driver/src/deferred_status_gpu.rs | 7 +- crates/cuda-driver/src/device_arena.rs | 11 +- crates/cuda-driver/src/device_slab.rs | 23 +- crates/cuda-driver/src/device_slab/tests.rs | 101 ++++--- .../src/experimental/impl_kvshape.rs | 3 +- .../cuda-driver/src/experimental/impl_mode.rs | 3 +- crates/cuda-driver/src/experimental/tests.rs | 159 ++++++----- crates/cuda-driver/src/family_tests.rs | 258 +++++++++--------- .../cuda-driver/src/ffi/impl_contexthandle.rs | 3 +- .../src/ffi/impl_functionhandle.rs | 3 +- .../src/ffi/impl_qsaselectedarguments.rs | 3 +- .../gdn_closed_queue/impl_gdnqueuestage.rs | 3 +- crates/cuda-driver/src/gdn_fused_t1.rs | 9 +- .../impl_gdnfusedprefix_2_2.rs | 3 +- .../cuda-driver/src/gdn_fused_t1/pinned_fn.rs | 3 +- .../cuda-driver/src/gdn_fused_t1/words_fn.rs | 3 +- .../src/gdn_native_batch/impl_context.rs | 3 +- .../src/gdn_native_batch/pinned_fn.rs | 3 +- .../src/gdn_native_batch_gpu/bytes_of_fn.rs | 3 +- .../src/gdn_native_batch_gpu/impl_hostgemm.rs | 3 +- 32 files changed, 672 insertions(+), 471 deletions(-) diff --git a/crates/cuda-driver/src/arch_ptx.rs b/crates/cuda-driver/src/arch_ptx.rs index 722924b5..c8fd20f1 100644 --- a/crates/cuda-driver/src/arch_ptx.rs +++ b/crates/cuda-driver/src/arch_ptx.rs @@ -147,36 +147,38 @@ mod tests { } } + fn manifest_names<'a>(manifest: &'a serde_json::Value, list: &str, field: &str) -> Vec<&'a str> { + manifest[list].as_array().unwrap().iter().map(|v| v[field].as_str().unwrap()).collect() + } + + fn manifest_file_names<'a>(manifest: &'a serde_json::Value, list: &str, field: Option<&str>) -> Vec<&'a str> { + let entries = manifest[list].as_array().unwrap().iter(); + entries.map(|v| field.map_or(v, |f| &v[f]).as_str().unwrap().rsplit('/').next().unwrap()).collect() + } + + fn assert_sealed_file_has_a_companion_or_a_reason(name: &str, bytes: &[u8], documented: &[&[&str]]) { + let head = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]).into_owned(); + let is_sm120 = head.lines().any(|l| l == ".target sm_120"); + if !is_sm120 || head.contains("UNSEALED") { + return; + } + let key = crate::qwen_ffi::sha256(body(bytes)); + let has = COMPANIONS.binary_search_by(|c| c.key.cmp(&key)).is_ok(); + assert!( + has || documented.iter().any(|names| names.contains(&name)), + "{name}: sealed sm_120 PTX with no companion and no not_built record" + ); + } + #[test] fn every_sealed_sm120_file_has_a_companion_or_a_documented_reason() { let manifest: serde_json::Value = serde_json::from_slice(&std::fs::read(src().join("ptx-sm86/MANIFEST.json")).unwrap()).unwrap(); - let not_built: Vec<&str> = - manifest["not_built"].as_array().unwrap().iter().map(|v| v["name"].as_str().unwrap()).collect(); - let portable: Vec<&str> = manifest["portable_no_companion_needed"] - .as_array() - .unwrap() - .iter() - .map(|v| v["path"].as_str().unwrap().rsplit('/').next().unwrap()) - .collect(); - let placeholders: Vec<&str> = manifest["unsealed_sm120_placeholders"] - .as_array() - .unwrap() - .iter() - .map(|v| v.as_str().unwrap().rsplit('/').next().unwrap()) - .collect(); + let not_built = manifest_names(&manifest, "not_built", "name"); + let portable = manifest_file_names(&manifest, "portable_no_companion_needed", Some("path")); + let placeholders = manifest_file_names(&manifest, "unsealed_sm120_placeholders", None); for (name, bytes) in sealed_files() { - let head = String::from_utf8_lossy(&bytes[..bytes.len().min(4096)]).into_owned(); - let is_sm120 = head.lines().any(|l| l == ".target sm_120"); - if !is_sm120 || head.contains("UNSEALED") { - continue; - } - let key = crate::qwen_ffi::sha256(body(&bytes)); - let has = COMPANIONS.binary_search_by(|c| c.key.cmp(&key)).is_ok(); - assert!( - has || not_built.contains(&name.as_str()) || portable.contains(&name.as_str()), - "{name}: sealed sm_120 PTX with no companion and no not_built record" - ); + assert_sealed_file_has_a_companion_or_a_reason(&name, &bytes, &[¬_built, &portable]); } // the placeholders have no companion by design: they cannot be loaded on any device until sealed assert!(placeholders.iter().all(|p| !COMPANIONS.iter().any(|c| c.name == *p))); @@ -196,7 +198,8 @@ mod tests { let mut changed = stored.clone(); changed[8] ^= 1; assert!(companion_for(&changed).is_none()); - // an asset stored with a NUL and given a second one by concat!(.., "\0") (qsa_native_batch) maps to the same companion + // an asset stored with a NUL and given a second one by concat!(.., "\0") (qsa_native_batch) maps to the same + // companion let mut doubled = stored.clone(); doubled.push(0); assert_eq!(companion_for(&doubled), Some(swapped)); @@ -205,9 +208,24 @@ mod tests { #[test] fn capability_gates() { - assert!(cc_major_ok(12) && cc_major_ok(8) && cc_major_ok(9) && !cc_major_ok(7) && !cc_major_ok(13)); - assert!(mmq_cc_ok(12, 0) && mmq_cc_ok(8, 6) && mmq_cc_ok(8, 9) && !mmq_cc_ok(8, 0) && !mmq_cc_ok(12, 1)); - assert!(companion_cc(8, 6) && companion_cc(9, 0) && !companion_cc(8, 0) && !companion_cc(12, 0)); + assert_major_gate(); + assert_mmq_gate(); + assert_companion_gate(); + } + + fn assert_major_gate() { + assert!(cc_major_ok(12) && cc_major_ok(8) && cc_major_ok(9)); + assert!(!cc_major_ok(7) && !cc_major_ok(13)); + } + + fn assert_mmq_gate() { + assert!(mmq_cc_ok(12, 0) && mmq_cc_ok(8, 6) && mmq_cc_ok(8, 9)); + assert!(!mmq_cc_ok(8, 0) && !mmq_cc_ok(12, 1)); + } + + fn assert_companion_gate() { + assert!(companion_cc(8, 6) && companion_cc(9, 0)); + assert!(!companion_cc(8, 0) && !companion_cc(12, 0)); } } diff --git a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs index a8a553d3..bbeea83b 100644 --- a/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs +++ b/crates/cuda-driver/src/arch_ptx/stream_k_off_fn.rs @@ -1,14 +1,16 @@ -//! Moved out of the parent module by STRA-338: fn stream_k_off, fn forced_sms, fn chunk_drain, fn latch_stream_k_policy, fn cc_major_ok, fn mmq_cc_ok .... +//! Moved out of the parent module by STRA-338: fn stream_k_off, fn forced_sms, fn chunk_drain, fn +//! latch_stream_k_policy, fn cc_major_ok, fn mmq_cc_ok .... #[allow(unused_imports)] use super::*; -/// STRA-235: the grouped / MTP / resident MMQ launch one block per tile instead of the stream-K grid of `sms` blocks (no split of -/// the K loop, no fixup kernel). On by default for an sm_86-class device (latched by `latch_stream_k_policy`, called where the -/// owners of those kernels are built with the device's context current); `LELEKA_MMQ_STREAMK=1` restores the stream-K grid there; -/// `LELEKA_MMQ_NO_STREAMK=1` forces it everywhere, and so does the existence of the file named by `LELEKA_MMQ_NO_STREAMK_FILE` -/// (looked at most every 250 ms, so an A/B can switch arms inside one engine). On a native sm_120 device with none of these set it -/// is false and every grid is exactly the one of the sealed code. +/// STRA-235: the grouped / MTP / resident MMQ launch one block per tile instead of the stream-K grid of `sms` blocks +/// (no split of the K loop, no fixup kernel). On by default for an sm_86-class device (latched by +/// `latch_stream_k_policy`, called where the owners of those kernels are built with the device's context current); +/// `LELEKA_MMQ_STREAMK=1` restores the stream-K grid there; `LELEKA_MMQ_NO_STREAMK=1` forces it everywhere, and so +/// does the existence of the file named by `LELEKA_MMQ_NO_STREAMK_FILE` (looked at most every 250 ms, so an A/B can +/// switch arms inside one engine). On a native sm_120 device with none of these set it is false and every grid is +/// exactly the one of the sealed code. pub(crate) fn stream_k_off() -> bool { use std::sync::atomic::Ordering::Relaxed; static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -31,7 +33,8 @@ pub(crate) fn stream_k_off() -> bool { fixed || STREAM_K_AVOIDED.load(Relaxed) } -/// Presence of the two marker files (`LELEKA_MMQ_NO_STREAMK_FILE`, `LELEKA_MMQ_STREAMK_FILE`), looked at most every 250 ms. +/// Presence of the two marker files (`LELEKA_MMQ_NO_STREAMK_FILE`, `LELEKA_MMQ_STREAMK_FILE`), looked at most every +/// 250 ms. fn marker_files_present(paths: &[Option; 2]) -> [bool; 2] { use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; static CHECKED: std::sync::OnceLock = std::sync::OnceLock::new(); @@ -48,8 +51,9 @@ fn marker_files_present(paths: &[Option; 2]) -> [bool; 2] { [PRESENT[0].load(Relaxed), PRESENT[1].load(Relaxed)] } -/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K grids (and size -/// their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the laptop's decomposition there. +/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_FORCE_SMS=N` makes the MMQ and MTP-prefill owners plan their stream-K +/// grids (and size their fixup workspaces) for N SMs instead of the device's count, e.g. 48 on a 5090 to run the +/// laptop's decomposition there. pub(crate) fn forced_sms(real: u32) -> u32 { std::env::var("LELEKA_FORCE_SMS") .ok() @@ -58,9 +62,10 @@ pub(crate) fn forced_sms(real: u32) -> u32 { .unwrap_or(real) } -/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_CHUNK_DRAIN=1`, or the existence of the file named by `LELEKA_CHUNK_DRAIN_FILE` -/// (looked at most every 250 ms), drains the whole context before the expert cache lends its tail to a prompt chunk and again -/// when the chunk's arena is released: nothing of one chunk (or of the refill / decode before it) can overlap the next. +/// EXPERIMENTAL diagnostic (STRA-235): `LELEKA_CHUNK_DRAIN=1`, or the existence of the file named by +/// `LELEKA_CHUNK_DRAIN_FILE` (looked at most every 250 ms), drains the whole context before the expert cache lends +/// its tail to a prompt chunk and again when the chunk's arena is released: nothing of one chunk (or of the refill / +/// decode before it) can overlap the next. pub(crate) fn chunk_drain() -> bool { use std::sync::atomic::{AtomicBool, AtomicU64, Ordering::Relaxed}; static FIXED: std::sync::OnceLock = std::sync::OnceLock::new(); diff --git a/crates/cuda-driver/src/asset_validation_cache_tests.rs b/crates/cuda-driver/src/asset_validation_cache_tests.rs index 287b4e0f..82f39e53 100644 --- a/crates/cuda-driver/src/asset_validation_cache_tests.rs +++ b/crates/cuda-driver/src/asset_validation_cache_tests.rs @@ -9,20 +9,28 @@ fn checked(asset: &Asset, operation: Operation, memo: &OnceLock, calls }) } -#[test] -fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { - let operation = Operation::RouteTop10; - let memo = OnceLock::new(); - let calls = Cell::new(0); - let base = mock_asset(operation); - assert_eq!(checked(&base, operation, &memo, &calls), Ok(())); +fn assert_a_warm_memo_is_inspected_once( + base: &Asset, + operation: Operation, + memo: &OnceLock, + calls: &Cell, +) { + assert_eq!(checked(base, operation, memo, calls), Ok(())); for _ in 0..3 { - assert_eq!(checked(&base, operation, &memo, &calls), Ok(())); + assert_eq!(checked(base, operation, memo, calls), Ok(())); } assert_eq!(calls.get(), 1); let proof = memo.get().unwrap(); assert!(std::ptr::eq(proof.ptx, base.ptx)); assert_eq!(proof.digest, inspect_ptx(base.ptx).unwrap()); +} + +fn assert_a_distinct_allocation_is_fully_checked( + base: &Asset, + operation: Operation, + memo: &OnceLock, + calls: &Cell, +) { // Distinct allocation with identical bytes cannot inherit the first proof. // Tiny intentional static test allocation: Asset's real contract is static // immutable bytes. It is not a GPU resource or a production asset. @@ -30,68 +38,65 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { assert!(!std::ptr::eq(other, base.ptx)); assert_eq!(other, base.ptx); let distinct = Asset { operation, ptx: other, receipt: base.receipt, pin: base.pin }; - assert_eq!(checked(&distinct, operation, &memo, &calls), Ok(())); + assert_eq!(checked(&distinct, operation, memo, calls), Ok(())); assert_eq!(calls.get(), 2); // A one-slot memo still holds the original allocation. The distinct one // must remain fully checked on a later call rather than trusting equalSHA. - assert_eq!(checked(&distinct, operation, &memo, &calls), Ok(())); + assert_eq!(checked(&distinct, operation, memo, calls), Ok(())); assert_eq!(calls.get(), 3); - assert_eq!(checked(&base, operation, &memo, &calls), Ok(())); + assert_eq!(checked(base, operation, memo, calls), Ok(())); assert_eq!(calls.get(), 3); - for case in 0..13 { - let mut asset = mock_asset(operation); - let mut request = operation; - match case { - 0 => { - asset.receipt.ptx_sha256 = [0xa5; 32]; - asset.pin = asset.receipt; - } - 1 => asset.receipt.source_sha256 = [3; 32], // receipt/pin mismatch - 2 => asset.operation = Operation::MtpS2DownFull, - 3 => request = Operation::MtpS2DownFull, - 4 => { - asset.receipt.abi_version = 2; - asset.pin = asset.receipt; - } - 5 => { - asset.receipt.topology = [512, 11, 1]; - asset.pin = asset.receipt; - } - 6 => { - asset.receipt.version = 2; - asset.pin = asset.receipt; - } - 7 => { - asset.receipt.source_sha256 = [0; 32]; - asset.pin = asset.receipt; - } - 8 => { - asset.receipt.oracle_sha256 = [0; 32]; - asset.pin = asset.receipt; - } - 9 => { - asset.receipt.compiler = ""; - asset.pin = asset.receipt; - } - 10 => { - asset.receipt.compiler_flags = ""; - asset.pin = asset.receipt; - } - 11 => { - asset.receipt.qualification_receipt = ""; - asset.pin = asset.receipt; - } - 12 => { - asset.receipt.comparison = ""; - asset.pin = asset.receipt; - } - _ => unreachable!(), +} + +fn corrupt_receipt_field(case: u32, receipt: &mut Receipt) { + match case { + 7 => receipt.source_sha256 = [0; 32], + 8 => receipt.oracle_sha256 = [0; 32], + 9 => receipt.compiler = "", + 10 => receipt.compiler_flags = "", + 11 => receipt.qualification_receipt = "", + 12 => receipt.comparison = "", + _ => unreachable!(), + } +} + +fn corrupt_receipt(case: u32, receipt: &mut Receipt) { + match case { + 0 => receipt.ptx_sha256 = [0xa5; 32], + 4 => receipt.abi_version = 2, + 5 => receipt.topology = [512, 11, 1], + 6 => receipt.version = 2, + _ => corrupt_receipt_field(case, receipt), + } +} + +/// The asset and the requested operation of one refused case. +fn corrupted(case: u32, operation: Operation) -> (Asset, Operation) { + let mut asset = mock_asset(operation); + let mut request = operation; + match case { + 1 => asset.receipt.source_sha256 = [3; 32], // receipt/pin mismatch + 2 => asset.operation = Operation::MtpS2DownFull, + 3 => request = Operation::MtpS2DownFull, + _ => { + corrupt_receipt(case, &mut asset.receipt); + asset.pin = asset.receipt; } - assert_eq!(checked(&asset, request, &memo, &calls), Err(Error::UnsupportedQwenOperation), "warm case {case}"); + } + (asset, request) +} + +fn assert_warm_refusals_never_rescan(base: &Asset, memo: &OnceLock, calls: &Cell) { + for case in 0..13 { + let (asset, request) = corrupted(case, base.operation); + assert_eq!(checked(&asset, request, memo, calls), Err(Error::UnsupportedQwenOperation), "warm case {case}"); assert_eq!(calls.get(), 3, "metadata and memo hash refusal must not rescan"); assert!(std::ptr::eq(memo.get().unwrap().ptx, base.ptx)); assert_eq!(memo.get().unwrap().digest, base.receipt.ptx_sha256); } +} + +fn assert_malformed_ptx_is_refused_and_not_memoised(operation: Operation) { let malformed: [&'static [u8]; 5] = [b"", b"\0", b"XY", b"X\0Y\0", b"\xff\0"]; for bytes in malformed { let mut asset = mock_asset(operation); @@ -104,6 +109,9 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { assert_eq!(count.get(), 1); assert!(fresh.get().is_none()); } +} + +fn assert_a_failed_check_does_not_poison_the_memo(base: &Asset, operation: Operation) { let mut wrong_hash = mock_asset(operation); wrong_hash.receipt.ptx_sha256 = [0x5a; 32]; wrong_hash.pin = wrong_hash.receipt; @@ -114,7 +122,20 @@ fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { assert!(fresh.get().is_none()); // Failure did not reserve/poison the content proof: the first valid asset // must inspect once and then warm without another inspector invocation. - assert_eq!(checked(&base, operation, &fresh, &count), Ok(())); - assert_eq!(checked(&base, operation, &fresh, &count), Ok(())); + assert_eq!(checked(base, operation, &fresh, &count), Ok(())); + assert_eq!(checked(base, operation, &fresh, &count), Ok(())); assert_eq!(count.get(), 2); } + +#[test] +fn immutable_ptx_memo_rechecks_metadata_and_refuses_failed_content() { + let operation = Operation::RouteTop10; + let memo = OnceLock::new(); + let calls = Cell::new(0); + let base = mock_asset(operation); + assert_a_warm_memo_is_inspected_once(&base, operation, &memo, &calls); + assert_a_distinct_allocation_is_fully_checked(&base, operation, &memo, &calls); + assert_warm_refusals_never_rescan(&base, &memo, &calls); + assert_malformed_ptx_is_refused_and_not_memoised(operation); + assert_a_failed_check_does_not_poison_the_memo(&base, operation); +} diff --git a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs index 0c8cbcf0..c2d28261 100644 --- a/crates/cuda-driver/src/bringup_trace_enabled_fn.rs +++ b/crates/cuda-driver/src/bringup_trace_enabled_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn bringup_trace_enabled, impl PromptSyncTrace, impl Drop_for_PromptSyncTrace, impl Error, impl fmt_Display_for, impl std_error_Error .... +//! Moved out of the parent module by STRA-338: fn bringup_trace_enabled, impl PromptSyncTrace, impl +//! Drop_for_PromptSyncTrace, impl Error, impl fmt_Display_for, impl std_error_Error .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/closed_kernels.rs b/crates/cuda-driver/src/closed_kernels.rs index a6663bbd..1abc661a 100644 --- a/crates/cuda-driver/src/closed_kernels.rs +++ b/crates/cuda-driver/src/closed_kernels.rs @@ -3,10 +3,11 @@ //! block), the legacy S-form GEMVs (`s_gemv.cu`, `s2_gemv*.cu`, dynamic shared memory) and the arena poison fill //! (`device.cu`). The Linux-gated driver half is `closed_kernels_gpu`. //! -//! Like the experimental programs, a program refuses to open while its PTX pin is zero or does not match the bytes ([`ExperimentalError::Unpinned`]); -//! nothing in the engine selects any of these by default. Entry names, argument layouts and launch geometry are fixed -//! tables here, cross-checked against the checked-in `.cu` text by the unit tests; the planners and admission rules -//! they call are the already tested pure modules (`native_flash_attn`, `s_gemv_legacy`, `device_arena`). +//! Like the experimental programs, a program refuses to open while its PTX pin is zero or does not match the bytes +//! ([`ExperimentalError::Unpinned`]); nothing in the engine selects any of these by default. Entry names, argument +//! layouts and launch geometry are fixed tables here, cross-checked against the checked-in `.cu` text by the unit +//! tests; the planners and admission rules they call are the already tested pure modules (`native_flash_attn`, +//! `s_gemv_legacy`, `device_arena`). //! //! STATUS: the three PTX assets were compiled with nvcc 13.2.86 and sealed on 2026-10-15 (the pins match the //! checked-in bytes). Loading on a GPU is verified separately by the host smokes (`closed_kernels_gpu_smoke.rs`, diff --git a/crates/cuda-driver/src/closed_kernels/impl_program.rs b/crates/cuda-driver/src/closed_kernels/impl_program.rs index 7e52ece0..5ae70169 100644 --- a/crates/cuda-driver/src/closed_kernels/impl_program.rs +++ b/crates/cuda-driver/src/closed_kernels/impl_program.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Program, fn admit_ptx, fn admit, fn s_gemv_entry_index, impl Slot, fn conforms .... +//! Moved out of the parent module by STRA-338: impl Program, fn admit_ptx, fn admit, fn s_gemv_entry_index, impl +//! Slot, fn conforms .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs b/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs index ab5d1bb1..83301584 100644 --- a/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs +++ b/crates/cuda-driver/src/closed_kernels/tests/flash_and_poison_signatures_match.rs @@ -1,4 +1,6 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): flash_and_poison_signatures_match_their_cuda_source, s_gemv_signatures_match_their_cuda_source, index_constants_and_planners_point_at_the_named_entries, every_planned_launch_conforms_to_its_entry .... +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! flash_and_poison_signatures_match_their_cuda_source, s_gemv_signatures_match_their_cuda_source, +//! index_constants_and_planners_point_at_the_named_entries, every_planned_launch_conforms_to_its_entry .... #[allow(unused_imports)] use super::*; @@ -57,6 +59,59 @@ fn index_constants_and_planners_point_at_the_named_entries() { } } +fn planned_s_gemv_kernels(form: &SForm, offset: bool) -> Vec { + let (n_in, n_out) = (1024, 6); + let mut plans: Vec = Vec::new(); + plans.extend(sg::plan_s_gemv(n_in, n_out, form, offset).ok().flatten()); + plans.extend(sg::plan_s_gemv_split(n_in, n_out, form, 64, offset).ok().flatten()); + plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, form).ok().flatten()); + plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, form).ok().flatten()); + plans.extend(sg::plan_s_gemv_q8_0_split(n_in, n_out, form).ok().flatten()); + plans +} + +fn assert_plan_conforms_with_operand_sizes(plan: &Plan, form: &SForm, offset: bool) { + let (n_in, n_out) = (1024, 6); + let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; + let slots = s_gemv_slots(plan, form, n_in, n_out, offset); + assert!(conforms(entry, &slots), "{:?}", plan.kernel); + let bytes = s_operand_bytes(plan.kernel, form, n_in, n_out).unwrap(); + assert_eq!(bytes.offset.is_some(), form.has_offset); + assert_eq!(bytes.y, 24); +} + +fn count_conforming_s_gemv_plans(form: &SForm) -> usize { + let mut planned = 0; + for offset in [false, true] { + if form.has_offset && !offset { + continue; + } + for plan in planned_s_gemv_kernels(form, offset) { + assert_plan_conforms_with_operand_sizes(&plan, form, offset); + planned += 1; + } + } + planned +} + +fn count_conforming_s2_gemv_plans() -> usize { + let plans = [ + sg::plan_s2_gemv(1024, 6).unwrap().unwrap(), + sg::plan_s2_gemv_quads(1024, 6, 64).unwrap().unwrap(), + sg::plan_s2_gemv_q8(1024, 6, 64).unwrap().unwrap(), + sg::plan_s2_gemv_fast(1024, 6, 64, true).unwrap().unwrap(), + sg::plan_s2_gemv_fast(1024, 6, 64, false).unwrap().unwrap(), + ]; + let mut planned = 0; + for plan in plans { + let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; + let slots = s_gemv_slots(&plan, &SForm::default(), 1024, 6, false); + assert!(conforms(entry, &slots), "{:?}", plan.kernel); + planned += 1; + } + planned +} + #[test] fn every_planned_launch_conforms_to_its_entry() { let forms = [ @@ -66,56 +121,26 @@ fn every_planned_launch_conforms_to_its_entry() { ]; let mut planned = 0; for form in forms { - for offset in [false, true] { - if form.has_offset && !offset { - continue; - } - let (n_in, n_out) = (1024, 6); - let mut plans: Vec = Vec::new(); - plans.extend(sg::plan_s_gemv(n_in, n_out, &form, offset).ok().flatten()); - plans.extend(sg::plan_s_gemv_split(n_in, n_out, &form, 64, offset).ok().flatten()); - plans.extend(sg::plan_s_gemv_q8k(n_in, n_out, &form).ok().flatten()); - plans.extend(sg::plan_s_gemv_q8k_split(n_in, n_out, &form).ok().flatten()); - plans.extend(sg::plan_s_gemv_q8_0_split(n_in, n_out, &form).ok().flatten()); - for plan in plans { - let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; - let slots = s_gemv_slots(&plan, &form, n_in, n_out, offset); - assert!(conforms(entry, &slots), "{:?}", plan.kernel); - let bytes = s_operand_bytes(plan.kernel, &form, n_in, n_out).unwrap(); - assert_eq!(bytes.offset.is_some(), form.has_offset); - assert_eq!(bytes.y, 24); - planned += 1; - } - } - } - for plan in [ - sg::plan_s2_gemv(1024, 6).unwrap().unwrap(), - sg::plan_s2_gemv_quads(1024, 6, 64).unwrap().unwrap(), - sg::plan_s2_gemv_q8(1024, 6, 64).unwrap().unwrap(), - sg::plan_s2_gemv_fast(1024, 6, 64, true).unwrap().unwrap(), - sg::plan_s2_gemv_fast(1024, 6, 64, false).unwrap().unwrap(), - ] { - let entry = &S_GEMV_ENTRIES[s_gemv_entry_index(plan.kernel)]; - let slots = s_gemv_slots(&plan, &SForm::default(), 1024, 6, false); - assert!(conforms(entry, &slots), "{:?}", plan.kernel); - planned += 1; + planned += count_conforming_s_gemv_plans(&form); } + planned += count_conforming_s2_gemv_plans(); assert!(planned >= 20, "{planned}"); } -#[test] -fn slot_values_follow_the_oracle_driver() { - // oracle/drivers/s_gemv_legacy.cpp: split passes (bias, codebook, group, shift_of(group), has_offset, tpr) - let form = SForm { +fn oracle_split_form() -> SForm { + SForm { code_bits: 4, code_bias: -8, group_elems: 32, codebook: sg::Codebook::Iq4Nl, has_offset: true, ..SForm::default() - }; - let plan = sg::plan_s_gemv_split(512, 8, &form, 64, true).unwrap().unwrap(); - let slots = s_gemv_slots(&plan, &form, 512, 8, true); + } +} + +fn assert_split_slots_follow_the_oracle(form: &SForm) { + let plan = sg::plan_s_gemv_split(512, 8, form, 64, true).unwrap().unwrap(); + let slots = s_gemv_slots(&plan, form, 512, 8, true); assert_eq!( slots, vec![ @@ -135,16 +160,31 @@ fn slot_values_follow_the_oracle_driver() { ] ); assert_eq!((plan.launch.grid, plan.launch.block, plan.launch.dynamic_shared), ([8, 1, 1], [64, 1, 1], 256)); +} + +fn assert_q8_split_slots_take_the_shift(form: &SForm) { // the Q8 split kernels take the shift in place of the group - let plan = sg::plan_s_gemv_q8k_split(512, 8, &form).unwrap().unwrap(); - let slots = s_gemv_slots(&plan, &form, 512, 8, true); + let plan = sg::plan_s_gemv_q8k_split(512, 8, form).unwrap().unwrap(); + let slots = s_gemv_slots(&plan, form, 512, 8, true); assert_eq!(&slots[7..], &[Slot::I32(-8), Slot::I32(1), Slot::I32(5), Slot::I32(1)]); +} + +fn assert_a_form_without_offset_passes_null(form: &SForm) { // a form without an offset passes a null offset pointer - let none = SForm { has_offset: false, ..form }; + let none = SForm { has_offset: false, ..*form }; let plan = sg::plan_s_gemv(512, 8, &none, false).unwrap().unwrap(); assert_eq!(s_gemv_slots(&plan, &none, 512, 8, false)[3], Slot::Null); } +#[test] +fn slot_values_follow_the_oracle_driver() { + // oracle/drivers/s_gemv_legacy.cpp: split passes (bias, codebook, group, shift_of(group), has_offset, tpr) + let form = oracle_split_form(); + assert_split_slots_follow_the_oracle(&form); + assert_q8_split_slots_take_the_shift(&form); + assert_a_form_without_offset_passes_null(&form); +} + #[test] fn operand_sizes_follow_the_pack_format() { let form = SForm { code_bits: 4, code_bias: -8, group_elems: 32, has_offset: true, ..SForm::default() }; diff --git a/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs b/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs index 214f6a57..0d787251 100644 --- a/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs +++ b/crates/cuda-driver/src/closed_kernels/tests/sealed_assets_match_their_pins.rs @@ -1,42 +1,46 @@ -//! Tests of tests by topic (moved out of the test file by STRA-338): sealed_assets_match_their_pins_and_export_every_entry. +//! Tests of tests by topic (moved out of the test file by STRA-338): +//! sealed_assets_match_their_pins_and_export_every_entry. #[allow(unused_imports)] use super::*; -#[test] -fn sealed_assets_match_their_pins_and_export_every_entry() { +fn assert_pin_is_the_sealed_ptx(program: Program) { + use crate::sealed_ptx::test_support::{assert_nvcc_13_2_86, assert_real_sm120_ptx}; + // Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim, + // GPU load is verified separately by the host smokes). + let ptx = program.ptx(); + let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); + assert_real_sm120_ptx(program.name(), ptx, names); + assert_nvcc_13_2_86(program.name(), ptx); + let pin = program.pin(); + assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); + assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); + assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); + assert_eq!(pin.source_sha256, qwen_ffi::sha256(program.source().as_bytes()), "{}", program.name()); + assert_eq!(admit(program), Ok(()), "{}", program.name()); +} + +fn assert_guard_refuses_every_deviation(program: Program) { use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, - with_embedded_nul, without_terminator, + one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, without_terminator, }; - for program in Program::ALL { - // Sealed with nvcc 13.2.86 on 2026-10-15; this checks structure and the pin only (no numerical claim, - // GPU load is verified separately by the host smokes). - let ptx = program.ptx(); - let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); - assert_real_sm120_ptx(program.name(), ptx, names); - assert_nvcc_13_2_86(program.name(), ptx); - let pin = program.pin(); - assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); - assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); - assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); - assert_eq!(pin.source_sha256, qwen_ffi::sha256(program.source().as_bytes()), "{}", program.name()); - assert_eq!(admit(program), Ok(()), "{}", program.name()); - // the guard still refuses every deviation, on synthetic copies of the real PTX - let refuse = Err(ExperimentalError::Unpinned(program.name())); - assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); - assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); - assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); - let mut wrong_digest = *pin; - wrong_digest.ptx_sha256[0] ^= 1; - assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { - assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); - } + // the guard still refuses every deviation, on synthetic copies of the real PTX + let (ptx, pin) = (program.ptx(), program.pin()); + let refuse = Err(ExperimentalError::Unpinned(program.name())); + assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); + assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); + assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); + let mut wrong_digest = *pin; + wrong_digest.ptx_sha256[0] ^= 1; + assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); + for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { + assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); } - // a matching pin admits; any difference refuses +} + +fn assert_a_matching_pin_admits_and_any_difference_refuses() { static GOOD: &[u8] = b".version 8.7\n.target sm_120\n\0"; let pin = PtxPin { source_sha256: [1; 32], ptx_sha256: qwen_ffi::sha256(&GOOD[..GOOD.len() - 1]) }; assert_eq!(admit_ptx(Program::DevicePoison, GOOD, &pin), Ok(())); @@ -44,3 +48,12 @@ fn sealed_assets_match_their_pins_and_export_every_entry() { assert!(admit_ptx(Program::DevicePoison, GOOD, &wrong).is_err()); assert!(admit_ptx(Program::DevicePoison, GOOD, &PtxPin { source_sha256: [0; 32], ..pin }).is_err()); } + +#[test] +fn sealed_assets_match_their_pins_and_export_every_entry() { + for program in Program::ALL { + assert_pin_is_the_sealed_ptx(program); + assert_guard_refuses_every_deviation(program); + } + assert_a_matching_pin_admits_and_any_difference_refuses(); +} diff --git a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs index 7d350a1f..41d7bbdf 100644 --- a/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs +++ b/crates/cuda-driver/src/closed_kernels_gpu_smoke.rs @@ -1,7 +1,8 @@ //! Root-only GPU smokes for the closed native_flash_attn / s_gemv_legacy / device_poison programs. Compiled only on //! Linux x86_64 with `cuda-driver`; ignored by default because they need the compiled PTX, frozen pins and an -//! RTX-class device. Each compares the device with the CPU model of the pure module (`native_flash_attn::reference_head`, -//! `s_gemv_legacy`'s summation-order models and the shim-executed golden fixture, `device_arena::poison_model`). +//! RTX-class device. Each compares the device with the CPU model of the pure module +//! (`native_flash_attn::reference_head`, `s_gemv_legacy`'s summation-order models and the shim-executed golden +//! fixture, `device_arena::poison_model`). //! //! Run (after TODO-ROOT: build the three PTX files and freeze `closed_kernels::PINS`): //! cargo test -p leleka-cuda-driver --features cuda-driver -- --ignored closed_gpu diff --git a/crates/cuda-driver/src/compute_drain.rs b/crates/cuda-driver/src/compute_drain.rs index d780dea8..cf87e014 100644 --- a/crates/cuda-driver/src/compute_drain.rs +++ b/crates/cuda-driver/src/compute_drain.rs @@ -34,8 +34,8 @@ pub(crate) fn set_background(stream: usize) { pub(crate) fn background() -> usize { BACKGROUND.load(Ordering::SeqCst) } -/// Every registered stream except `except` and the chunk's background copy stream, plus the legacy default stream (0): the -/// streams whose later work must be ordered after a stream's deferred-guard run (deferred_status.rs). +/// Every registered stream except `except` and the chunk's background copy stream, plus the legacy default stream +/// (0): the streams whose later work must be ordered after a stream's deferred-guard run (deferred_status.rs). pub(crate) fn streams_except(except: usize) -> Vec { let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner()); let background = background(); @@ -87,8 +87,8 @@ static SHOWN: AtomicUsize = AtomicUsize::new(0); static SITES: Mutex> = Mutex::new(std::collections::BTreeMap::new()); static BLOCK_NS: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS]; static BLOCK_N: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS]; -/// Run a host-blocking driver call (0 alloc, 1 free, 2 H2D, 3 D2H, 4 memset, 5 scoped drain, 6 D2D, 7 other stream/event sync), timing it while a chunk -/// stream is in flight. +/// Run a host-blocking driver call (0 alloc, 1 free, 2 H2D, 3 D2H, 4 memset, 5 scoped drain, 6 D2D, 7 other +/// stream/event sync), timing it while a chunk stream is in flight. pub(crate) fn timed(kind: usize, f: impl FnOnce() -> T) -> T { if background() == 0 { return f(); diff --git a/crates/cuda-driver/src/deferred_status.rs b/crates/cuda-driver/src/deferred_status.rs index 8705b6bf..c7a318b8 100644 --- a/crates/cuda-driver/src/deferred_status.rs +++ b/crates/cuda-driver/src/deferred_status.rs @@ -1,23 +1,31 @@ -//! `LELEKA_PREFILL_DEFER_GUARDS` (default on, `=0` restores the immediate guards; claude/schedule): deferred guard status for the prompt producer's `run`. +//! `LELEKA_PREFILL_DEFER_GUARDS` (default on, `=0` restores the immediate guards; claude/schedule): deferred guard +//! status for the prompt producer's `run`. //! -//! Today every `OriginalPromptDevice::run` (the hyper-connection reads and injections: about 560 per 8192-token chunk) zeroes its status -//! words with a synchronous upload, runs its kernels, drains the whole context, reads the words back and refuses on the first set one: -//! three host synchronizations and two transfers per call, each one a hole in the GPU queue and a latecomer in the H2D copy FIFO. -//! Deferred mode keeps the same words, the same kernels and the same refusal, but moves the *host's look* at them: +//! Today every `OriginalPromptDevice::run` (the hyper-connection reads and injections: about 560 per 8192-token +//! chunk) zeroes its status words with a synchronous upload, runs its kernels, drains the whole context, reads the +//! words back and refuses on the first set one: three host synchronizations and two transfers per call, each one a +//! hole in the GPU queue and a latecomer in the H2D copy FIFO. Deferred mode keeps the same words, the same kernels +//! and the same refusal, but moves the *host's look* at them: //! 1. the words are zeroed by a stream-ordered memset (no upload, no wait); -//! 2. after the kernels the words are copied by a stream-ordered DtoH into a pinned slot and an event is recorded behind the copy; -//! 3. every other stream (and the legacy default stream) is ordered after that event on the device, which replaces the context +//! 2. after the kernels the words are copied by a stream-ordered DtoH into a pinned slot and an event is recorded +//! behind the copy; +//! 3. every other stream (and the legacy default stream) is ordered after that event on the device, which replaces +//! the context //! drain that used to order the next producer after this one (the host does not wait); -//! 4. the slot is evaluated by `resolve`, in order, with the unchanged evaluation (`evaluate`): when the ring of 64 slots is full, and -//! at the points where results leave the device (final-row reads, preview/finish of the phase, row-lease teardown). -//! A failing slot poisons the context exactly like the immediate check does (every later driver call refuses with `ContextPoisoned`) and -//! returns the same error class and label as the immediate path would have, only later: work enqueued after the failing run has executed -//! on its output, but nothing of it is observable (no row is read back, no phase is sealed, no session state is published) before `resolve`. +//! 4. the slot is evaluated by `resolve`, in order, with the unchanged evaluation (`evaluate`): when the ring of 64 +//! slots is full, and +//! at the points where results leave the device (final-row reads, preview/finish of the phase, row-lease +//! teardown). +//! A failing slot poisons the context exactly like the immediate check does (every later driver call refuses with +//! `ContextPoisoned`) and returns the same error class and label as the immediate path would have, only later: work +//! enqueued after the failing run has executed on its output, but nothing of it is observable (no row is read back, +//! no phase is sealed, no session state is published) before `resolve`. use crate::Error; use crate::Result; -/// The evaluation of one status readback, shared by the immediate and the deferred path: any word above 1 is an unknown status; then -/// the first set word in the producer's order (`stride == 10`: PLE, row first then stage order; otherwise GR, stage first over all rows). +/// The evaluation of one status readback, shared by the immediate and the deferred path: any word above 1 is an +/// unknown status; then the first set word in the producer's order (`stride == 10`: PLE, row first then stage order; +/// otherwise GR, stage first over all rows). pub(crate) fn evaluate(readback: &[u8], stride: usize, order: &[usize], labels: &[&'static str]) -> Result<()> { for word in readback.as_chunks::<4>().0 { if u32::from_le_bytes(*word) > 1 { @@ -100,7 +108,8 @@ mod device { Ok(State { api, context: std::ptr::from_ref(context) as usize, slots, live: VecDeque::new(), head: 0 }) } - /// Wait for the oldest live check and evaluate it. The first failure poisons the context; every other live copy is still waited for. + /// Wait for the oldest live check and evaluate it. The first failure poisons the context; every other live copy + /// is still waited for. fn resolve_oldest(context: &Context<'_>, st: &mut State) -> Result<()> { let Some(check) = st.live.pop_front() else { return Ok(()) }; let slot = &st.slots[check.slot]; @@ -153,7 +162,8 @@ mod device { }) } - /// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, remember the check. + /// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, + /// remember the check. pub(crate) fn finish( context: &Context<'_>, status: BufferHandle, diff --git a/crates/cuda-driver/src/deferred_status_ffi.rs b/crates/cuda-driver/src/deferred_status_ffi.rs index efa13d3f..cc93452d 100644 --- a/crates/cuda-driver/src/deferred_status_ffi.rs +++ b/crates/cuda-driver/src/deferred_status_ffi.rs @@ -1,8 +1,9 @@ //! Audited child of ffi (claude/schedule): the few asynchronous driver calls the deferred guard status block needs -//! (`LELEKA_PREFILL_DEFER_GUARDS`, see deferred_status.rs): a device memset and a device-to-host copy on a stream, pinned host -//! buffers, and events with cross-stream waits. Nothing here owns a device allocation or a stream; the host buffers are owned -//! by `HostBuffer` and freed by `Api::free_host`. Callers keep the context current (their `enter()` guard) and keep every -//! device allocation alive until the event of the copy that reads it has been waited for. +//! (`LELEKA_PREFILL_DEFER_GUARDS`, see deferred_status.rs): a device memset and a device-to-host copy on a stream, +//! pinned host buffers, and events with cross-stream waits. Nothing here owns a device allocation or a stream; the +//! host buffers are owned by `HostBuffer` and freed by `Api::free_host`. Callers keep the context current (their +//! `enter()` guard) and keep every device allocation alive until the event of the copy that reads it has been waited +//! for. use super::BufferHandle; use crate::{Error, Result}; use std::ffi::{CStr, c_void}; diff --git a/crates/cuda-driver/src/deferred_status_gpu.rs b/crates/cuda-driver/src/deferred_status_gpu.rs index a4244af2..8087324f 100644 --- a/crates/cuda-driver/src/deferred_status_gpu.rs +++ b/crates/cuda-driver/src/deferred_status_gpu.rs @@ -1,6 +1,7 @@ -//! Model-free GPU proof of the deferred guard status machinery (deferred_status.rs): the stream-ordered zero, the DtoH into the pinned -//! ring, the ordering events, the ring wrap and the poisoning, against the immediate evaluation. Enable with -//! `LELEKA_PREFILL_STAGE_GPU=yes` (`cargo test -p leleka-cuda-driver --features cuda-driver deferred -- --ignored`). +//! Model-free GPU proof of the deferred guard status machinery (deferred_status.rs): the stream-ordered zero, the +//! DtoH into the pinned ring, the ordering events, the ring wrap and the poisoning, against the immediate evaluation. +//! Enable with `LELEKA_PREFILL_STAGE_GPU=yes` (`cargo test -p leleka-cuda-driver --features cuda-driver deferred -- +//! --ignored`). use super::*; use crate::{Context, DeviceBuffer, Driver}; diff --git a/crates/cuda-driver/src/device_arena.rs b/crates/cuda-driver/src/device_arena.rs index d2c3d717..43ba7414 100644 --- a/crates/cuda-driver/src/device_arena.rs +++ b/crates/cuda-driver/src/device_arena.rs @@ -59,8 +59,9 @@ impl DeviceArenaPlan { pub fn used(&self) -> u64 { self.used } - /// `alloc(bytes, align)`: `Ok(None)` is the Original's `nullptr` for zero bytes; `Ok(Some(offset))` the aligned start. - /// Hardening over the Original: `start + bytes` is overflow-checked (the Original's wraps and would accept it). + /// `alloc(bytes, align)`: `Ok(None)` is the Original's `nullptr` for zero bytes; `Ok(Some(offset))` the aligned + /// start. Hardening over the Original: `start + bytes` is overflow-checked (the Original's wraps and would accept + /// it). pub fn alloc(&mut self, bytes: u64, align: u64) -> Result, String> { if bytes == 0 { return Ok(None); @@ -175,7 +176,8 @@ mod tests { let err = a.alloc(700, 8).unwrap_err(); assert_eq!( err, - "DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - the plan from P1.S9 did not close" + "DeviceArena out of memory: asked for 700 B at offset 376 (align 8) in a 1000 B region - \ + the plan from P1.S9 did not close" ); assert_eq!(a.used(), 369, "a refused allocation leaves the arena untouched"); assert!(a.alloc(u64::MAX, 8).is_err()); @@ -188,7 +190,8 @@ mod tests { assert!(check_compute_capability("RTX 2080", 7, 5, false).is_ok()); assert_eq!( check_compute_capability("V100", 7, 0, false).unwrap_err(), - "device V100 reports compute capability 7.0; Strata needs compute capability 7.5 or newer (RTX 20 / 30 / 40 / 50 series)" + "device V100 reports compute capability 7.0; Strata needs compute capability 7.5 or newer \ + (RTX 20 / 30 / 40 / 50 series)" ); assert!(check_compute_capability("V100", 7, 0, true).is_ok()); assert!(check_compute_capability("GTX 1080", 6, 1, true).is_ok()); diff --git a/crates/cuda-driver/src/device_slab.rs b/crates/cuda-driver/src/device_slab.rs index 12091459..bd55163c 100644 --- a/crates/cuda-driver/src/device_slab.rs +++ b/crates/cuda-driver/src/device_slab.rs @@ -1,15 +1,16 @@ //! Slab suballocation of model-lifetime device buffers. //! -//! The driver rounds every `cuMemAlloc` above 1 MiB up to a multiple of 2 MiB (probe: `scripts/dev/alloc-granularity-probe.py`; -//! the 5090 load ledger agrees: a 322.1 MiB table takes 324 MiB). The dense weights are about 700 separate buffers of -//! 0.5-10 MiB, so the dense-weights stage of the load ledger shows 4,578 MiB taken for 3,890 MiB requested: 688 MiB that no -//! kernel reads. A [`SlabAllocator`] packs such buffers, in arrival order and first fit, into 64 MiB slabs (a multiple of the -//! granule: no rounding of its own) and hands out [`DeviceSlice`]s: ordinary `&DeviceBuffer`s (they `Deref` to one) that -//! alias a sub-range, never free it and keep their slab alive. The bytes, their order inside a buffer and every kernel's -//! arithmetic are unchanged; only the address of the buffer moves, 512-byte aligned (cuMemAlloc guarantees 256). +//! The driver rounds every `cuMemAlloc` above 1 MiB up to a multiple of 2 MiB (probe: +//! `scripts/dev/alloc-granularity-probe.py`; the 5090 load ledger agrees: a 322.1 MiB table takes 324 MiB). The dense +//! weights are about 700 separate buffers of 0.5-10 MiB, so the dense-weights stage of the load ledger shows 4,578 +//! MiB taken for 3,890 MiB requested: 688 MiB that no kernel reads. A [`SlabAllocator`] packs such buffers, in +//! arrival order and first fit, into 64 MiB slabs (a multiple of the granule: no rounding of its own) and hands out +//! [`DeviceSlice`]s: ordinary `&DeviceBuffer`s (they `Deref` to one) that alias a sub-range, never free it and keep +//! their slab alive. The bytes, their order inside a buffer and every kernel's arithmetic are unchanged; only the +//! address of the buffer moves, 512-byte aligned (cuMemAlloc guarantees 256). //! -//! Buffers above `direct_above` keep their own allocation (rounding waste of at most 2 MiB on 16 MiB or more is below 12 % -//! and a slab cannot hold them without stranding its tail). +//! Buffers above `direct_above` keep their own allocation (rounding waste of at most 2 MiB on 16 MiB or more is below +//! 12 % and a slab cannot hold them without stranding its tail). use crate::{Context, DeviceBuffer, Error, Result}; use std::ops::{Deref, DerefMut}; use std::rc::Rc; @@ -236,8 +237,8 @@ impl<'ctx> SlabAllocator<'ctx> { } impl<'ctx> DeviceBuffer<'ctx> { - /// A non-owning buffer aliasing `[offset, offset + len)` of this one (dropping it frees nothing). The caller keeps `self` - /// alive for as long as the alias is used: [`DeviceSlice`] holds the slab for it. + /// A non-owning buffer aliasing `[offset, offset + len)` of this one (dropping it frees nothing). The caller + /// keeps `self` alive for as long as the alias is used: [`DeviceSlice`] holds the slab for it. pub(crate) fn view(&self, offset: usize, len: usize) -> Result> { let handle = self.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(self.bytes, offset, len)?; Ok(DeviceBuffer { diff --git a/crates/cuda-driver/src/device_slab/tests.rs b/crates/cuda-driver/src/device_slab/tests.rs index 129e2abe..5b042696 100644 --- a/crates/cuda-driver/src/device_slab/tests.rs +++ b/crates/cuda-driver/src/device_slab/tests.rs @@ -64,9 +64,8 @@ fn requests_above_the_direct_limit_keep_their_own_allocation() { assert_eq!(p.totals(), (16 * MIB, 1)); } -#[test] -fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { - // a deterministic mix of dense-weight sizes: tiny norms, 0.3-9 MiB matrices, the odd 2.5 MiB router +/// A deterministic mix of dense-weight sizes: tiny norms, 0.3-9 MiB matrices, the odd 2.5 MiB router. +fn mixed_dense_weight_sizes() -> Vec { let mut sizes = Vec::new(); let mut state = 0x9e37_79b9u32; for i in 0..2000 { @@ -80,19 +79,27 @@ fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { }; sizes.push(size.max(1)); } - let mut p = packer(); - let mut ranges: Vec<(usize, usize, usize)> = Vec::new(); // slab, start, end - for &size in &sizes { + sizes +} + +/// The (slab, start, end) of every carved request, in arrival order. +fn place_all(p: &mut Packer, sizes: &[usize]) -> Vec<(usize, usize, usize)> { + let mut ranges = Vec::new(); + for &size in sizes { match p.place(size).unwrap() { Placement::Slab { slab, offset } => ranges.push((slab, offset, offset + size)), Placement::NewSlab { slab } => ranges.push((slab, 0, size)), Placement::Direct => {} } } - for &(_, start, end) in &ranges { + ranges +} + +fn assert_ranges_aligned_and_disjoint(ranges: &[(usize, usize, usize)]) { + for &(_, start, end) in ranges { assert!(start % 512 == 0 && end <= SlabPolicy::DENSE.slab_bytes); } - let mut sorted = ranges.clone(); + let mut sorted = ranges.to_vec(); sorted.sort(); for pair in sorted.windows(2) { if pair[0].0 == pair[1].0 { @@ -102,9 +109,16 @@ fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { } #[test] -fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_each() { - // 36 GDN layers x (qkv 6.3 MiB, z 3.1, out 3.1, alpha/beta 0.01), 12 QSA x 6 matrices of 1.3-4.7 MiB, 48 routers of 2.5 MiB, - // and 97 gated-residual triples of 0.3 MiB: all sizes the driver rounds one by one +fn no_two_ranges_overlap_every_range_stays_inside_its_slab() { + let sizes = mixed_dense_weight_sizes(); + let mut p = packer(); + let ranges = place_all(&mut p, &sizes); + assert_ranges_aligned_and_disjoint(&ranges); +} + +/// 36 GDN layers x (qkv 6.3 MiB, z 3.1, out 3.1, alpha/beta 0.01), 12 QSA x 6 matrices of 1.3-4.7 MiB, 48 routers +/// of 2.5 MiB, and 97 gated-residual triples of 0.3 MiB: all sizes the driver rounds one by one. +fn model_dense_weight_sizes() -> Vec { let mut sizes: Vec = Vec::new(); for _ in 0..36 { sizes.extend([6_600_000, 3_300_000, 3_300_000, 10_240, 10_240, 4096, 4096, 4096, 4096]); @@ -127,23 +141,59 @@ fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_e sizes.extend(std::iter::repeat_n(330_000, 97 * 3)); sizes.push(50 * MIB); sizes.push(2560 * 2560 * 2); - let requested: usize = sizes.iter().sum(); - let separate: usize = sizes.iter().map(|&b| driver_bytes(b)).sum(); + sizes +} + +/// The device bytes the packer would take for `sizes`: its slabs plus the rounded direct allocations. +fn packed_device_bytes(sizes: &[usize]) -> usize { let mut p = packer(); let mut direct = 0usize; - for &size in &sizes { + for &size in sizes { if p.place(size).unwrap() == Placement::Direct { direct += driver_bytes(size); } } let (_, slabs) = p.totals(); - let packed = slabs * SlabPolicy::DENSE.slab_bytes + direct; + slabs * SlabPolicy::DENSE.slab_bytes + direct +} + +#[test] +fn packing_the_dense_weights_takes_much_less_device_memory_than_one_allocation_each() { + let sizes = model_dense_weight_sizes(); + let requested: usize = sizes.iter().sum(); + let separate: usize = sizes.iter().map(|&b| driver_bytes(b)).sum(); + let packed = packed_device_bytes(&sizes); assert!(separate > requested + 60 * MIB, "rounding must be visible in the model: {separate} vs {requested}"); assert!(packed < separate - 60 * MIB, "packing saves the rounding: {packed} vs {separate}"); // the holes behind the last items of each slab and the last slab's tail are the only cost assert!(packed <= requested + requested / 16 + SlabPolicy::DENSE.slab_bytes, "{packed} vs {requested}"); } +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +type Views<'ctx> = Vec<(DeviceSlice<'ctx>, Vec)>; + +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn allocate_and_fill<'ctx>(slabs: &mut SlabAllocator<'ctx>, sizes: &[usize]) -> Views<'ctx> { + let mut buffers = Vec::new(); + for (i, &size) in sizes.iter().enumerate() { + let mut buffer = slabs.allocate(size).unwrap(); + assert_eq!(buffer.len(), size); + let bytes: Vec = (0..size).map(|k| (k as u8).wrapping_mul(31).wrapping_add(i as u8 * 17 + 1)).collect(); + buffer.copy_from(&bytes).unwrap(); + buffers.push((buffer, bytes)); + } + buffers +} + +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn assert_views_read_back(buffers: &[(DeviceSlice<'_>, Vec)], skip: usize, what: &str) { + for (buffer, bytes) in buffers.iter().skip(skip) { + let mut back = vec![0u8; bytes.len()]; + buffer.copy_to(&mut back).unwrap(); + assert!(&back == bytes, "{what}"); + } +} + /// Needs a CUDA device (`cargo test -p leleka-cuda-driver --features cuda-driver --lib -- --ignored device_slab`). #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] #[test] @@ -153,32 +203,17 @@ fn device_slab_views_keep_their_bytes_apart_and_charge_only_the_slab() { let context = driver.device(0).unwrap().create_context(256 << 20).unwrap(); let mut slabs = SlabAllocator::new(&context, SlabPolicy::DENSE).unwrap(); let sizes = [4096usize, 3 * MIB, 700_001, 5 * MIB / 2, 17 * MIB, 1]; - let mut buffers = Vec::new(); - for (i, &size) in sizes.iter().enumerate() { - let mut buffer = slabs.allocate(size).unwrap(); - assert_eq!(buffer.len(), size); - let bytes: Vec = (0..size).map(|k| (k as u8).wrapping_mul(31).wrapping_add(i as u8 * 17 + 1)).collect(); - buffer.copy_from(&bytes).unwrap(); - buffers.push((buffer, bytes)); - } + let mut buffers = allocate_and_fill(&mut slabs, &sizes); // only the first five are carved: the 17 MiB request keeps its own allocation assert_eq!(buffers.iter().filter(|(b, _)| b.is_carved()).count(), 5); let stats = slabs.stats(); assert_eq!((stats.slabs, stats.carved, stats.direct), (1, 5, 1)); assert_eq!(context.allocated_bytes(), SlabPolicy::DENSE.slab_bytes + 17 * MIB); - for (buffer, bytes) in &buffers { - let mut back = vec![0u8; bytes.len()]; - buffer.copy_to(&mut back).unwrap(); - assert!(&back == bytes, "a view read back different bytes"); - } + assert_views_read_back(&buffers, 0, "a view read back different bytes"); // overwriting one view leaves its neighbours alone let (first, _) = &mut buffers[0]; first.copy_from(&vec![0xAB; 4096]).unwrap(); - for (buffer, bytes) in buffers.iter().skip(1) { - let mut back = vec![0u8; bytes.len()]; - buffer.copy_to(&mut back).unwrap(); - assert!(&back == bytes, "a neighbour changed"); - } + assert_views_read_back(&buffers, 1, "a neighbour changed"); for (buffer, _) in buffers { buffer.release().unwrap(); } diff --git a/crates/cuda-driver/src/experimental/impl_kvshape.rs b/crates/cuda-driver/src/experimental/impl_kvshape.rs index 760f0dd3..bc140719 100644 --- a/crates/cuda-driver/src/experimental/impl_kvshape.rs +++ b/crates/cuda-driver/src/experimental/impl_kvshape.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl KvShape, fn fwht_grid, fn fwht_bytes, fn q4_step_grid, fn q4_batch_grid, fn q4_gather_grid .... +//! Moved out of the parent module by STRA-338: impl KvShape, fn fwht_grid, fn fwht_bytes, fn q4_step_grid, fn +//! q4_batch_grid, fn q4_gather_grid .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/experimental/impl_mode.rs b/crates/cuda-driver/src/experimental/impl_mode.rs index ec20b093..5128e6a3 100644 --- a/crates/cuda-driver/src/experimental/impl_mode.rs +++ b/crates/cuda-driver/src/experimental/impl_mode.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Mode, impl OptIn, impl Program, impl fmt_Display_for, impl std_error_Error, impl From_for_ExperimentalError .... +//! Moved out of the parent module by STRA-338: impl Mode, impl OptIn, impl Program, impl fmt_Display_for, impl +//! std_error_Error, impl From_for_ExperimentalError .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/experimental/tests.rs b/crates/cuda-driver/src/experimental/tests.rs index b03e0a4f..d5ca6d08 100644 --- a/crates/cuda-driver/src/experimental/tests.rs +++ b/crates/cuda-driver/src/experimental/tests.rs @@ -102,48 +102,65 @@ fn every_mode_is_off_by_default_and_programs_need_an_explicit_one() { assert_eq!(names.len(), Mode::ALL.len()); } -#[test] -fn sealed_assets_match_their_pins_and_export_every_entry() { - use crate::sealed_ptx::test_support::{ - assert_nvcc_13_2_86, assert_real_sm120_ptx, one_byte_corrupted, one_byte_longer, one_byte_shorter, - with_embedded_nul, without_terminator, - }; - let all = OptIn::NONE +fn every_mode() -> OptIn { + OptIn::NONE .with(Mode::KvQ40) .with(Mode::KvK8V4) .with(Mode::KeylessVOnly) .with(Mode::KvStreamed) - .with(Mode::ControlVectors); + .with(Mode::ControlVectors) +} + +fn assert_pin_is_the_sealed_ptx(program: Program) { + use crate::sealed_ptx::test_support::{assert_nvcc_13_2_86, assert_real_sm120_ptx}; + // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is + // verified separately by the host smokes). + let ptx = program.ptx(); + let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); + assert_real_sm120_ptx(program.name(), ptx, names); + assert_nvcc_13_2_86(program.name(), ptx); + let pin = program.pin(); + assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); + assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); + assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); +} + +fn assert_admission_order(program: Program, all: &OptIn) { + // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open + let expected = + if PENDING_RESEAL.contains(&program) { Err(ExperimentalError::Unpinned(program.name())) } else { Ok(()) }; + assert_eq!(admit(program, all), expected, "{}", program.name()); + // the opt-in gate still comes first + assert_eq!(admit(program, &OptIn::NONE), Err(ExperimentalError::NotEnabled(program.name()))); +} + +fn assert_pin_guard_refuses_every_deviation(program: Program) { + use crate::sealed_ptx::test_support::{ + one_byte_corrupted, one_byte_longer, one_byte_shorter, with_embedded_nul, without_terminator, + }; + // the pin guard still refuses every deviation, on synthetic copies of the real PTX + let (ptx, pin) = (program.ptx(), program.pin()); + let refuse = Err(ExperimentalError::Unpinned(program.name())); + assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); + assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); + assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); + assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); + let mut wrong_digest = *pin; + wrong_digest.ptx_sha256[0] ^= 1; + assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); + for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { + assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); + } +} + +#[test] +fn sealed_assets_match_their_pins_and_export_every_entry() { + let all = every_mode(); for program in Program::ALL { - // Sealed with nvcc 13.2.86 on 2026-10-15; structure and pin only (no numerical claim, GPU load is - // verified separately by the host smokes). - let ptx = program.ptx(); - let names = program.entries().iter().map(|e| e.name.to_str().unwrap()); - assert_real_sm120_ptx(program.name(), ptx, names); - assert_nvcc_13_2_86(program.name(), ptx); - let pin = program.pin(); - assert_ne!(pin.source_sha256, [0; 32], "{}", program.name()); - assert_ne!(pin.ptx_sha256, [0; 32], "{}", program.name()); - assert_eq!(pin.ptx_sha256, qwen_ffi::sha256(&ptx[..ptx.len() - 1]), "{}", program.name()); - // a program re-synced after the seal (PENDING_RESEAL) keeps its old PTX and refuses to open - let expected = - if PENDING_RESEAL.contains(&program) { Err(ExperimentalError::Unpinned(program.name())) } else { Ok(()) }; - assert_eq!(admit(program, &all), expected, "{}", program.name()); - // the opt-in gate still comes first - assert_eq!(admit(program, &OptIn::NONE), Err(ExperimentalError::NotEnabled(program.name()))); - // the pin guard still refuses every deviation, on synthetic copies of the real PTX - let refuse = Err(ExperimentalError::Unpinned(program.name())); - assert_eq!(admit_ptx(program, one_byte_corrupted(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_shorter(ptx), pin), refuse); - assert_eq!(admit_ptx(program, one_byte_longer(ptx), pin), refuse); - assert_eq!(admit_ptx(program, with_embedded_nul(ptx), pin), refuse); - assert_eq!(admit_ptx(program, without_terminator(ptx), pin), refuse); - let mut wrong_digest = *pin; - wrong_digest.ptx_sha256[0] ^= 1; - assert_eq!(admit_ptx(program, ptx, &wrong_digest), refuse); - for zeroed in [PtxPin { source_sha256: [0; 32], ..*pin }, PtxPin { ptx_sha256: [0; 32], ..*pin }] { - assert_eq!(admit_ptx(program, ptx, &zeroed), refuse); - } + assert_pin_is_the_sealed_ptx(program); + assert_admission_order(program, &all); + assert_pin_guard_refuses_every_deviation(program); } } @@ -153,7 +170,8 @@ fn pending_reseal_lists_exactly_the_unsealed_sources() { assert_eq!( source_is_sealed(program), !PENDING_RESEAL.contains(&program), - "{}: PENDING_RESEAL and the source digest of the pin disagree (after a server reseal the list must shrink, after a .cu edit without reseal it must grow)", + "{}: PENDING_RESEAL and the source digest of the pin disagree (after a server reseal the list must \ + shrink, after a .cu edit without reseal it must grow)", program.name() ); } @@ -164,12 +182,7 @@ fn pending_reseal_lists_exactly_the_unsealed_sources() { #[test] fn a_program_whose_source_is_newer_than_its_ptx_refuses_even_with_a_matching_ptx_digest() { - let all = OptIn::NONE - .with(Mode::KvQ40) - .with(Mode::KvK8V4) - .with(Mode::KeylessVOnly) - .with(Mode::KvStreamed) - .with(Mode::ControlVectors); + let all = every_mode(); for &program in PENDING_RESEAL { // the PTX bytes are the sealed ones and match their digest ... assert_eq!(admit_ptx(program, program.ptx(), program.pin()), Ok(())); @@ -196,35 +209,39 @@ fn a_matching_pin_admits_and_any_difference_refuses() { assert!(admit_ptx(Program::Cvec, EMBEDDED, &p3).is_err()); } -#[test] -fn kv_geometry_matches_the_originals_host_wrappers() { - let s = KvShape::real(); +fn assert_kv_quantizer_grids(s: &KvShape) { assert_eq!(fwht_grid(1), Ok([1, 1, 1])); assert_eq!(fwht_grid(4), Ok([1, 1, 1])); assert_eq!(fwht_grid(5), Ok([2, 1, 1])); assert!(fwht_grid(0).is_err()); - assert_eq!(q4_step_grid(&s), Ok([2, 8, 2])); - assert_eq!(q4_batch_grid(7, &s), Ok([7, 2, 8])); - assert!(q4_batch_grid(0, &s).is_err()); + assert_eq!(q4_step_grid(s), Ok([2, 8, 2])); + assert_eq!(q4_batch_grid(7, s), Ok([7, 2, 8])); + assert!(q4_batch_grid(0, s).is_err()); // 3 ids * 2 heads * 8 blocks = 48 blocks, 4 per grid block - assert_eq!(q4_gather_grid(3, &s), Ok([12, 1, 1])); - assert_eq!(q4_gather_grid(1, &s), Ok([4, 1, 1])); - assert_eq!(q8_step_grid(&s, true), Ok([2, 4, 2])); - assert_eq!(q8_step_grid(&s, false), Ok([2, 4, 1])); + assert_eq!(q4_gather_grid(3, s), Ok([12, 1, 1])); + assert_eq!(q4_gather_grid(1, s), Ok([4, 1, 1])); + assert_eq!(q8_step_grid(s, true), Ok([2, 4, 2])); + assert_eq!(q8_step_grid(s, false), Ok([2, 4, 1])); // 5 ids * 2 heads * 64 float4 = 640 threads - assert_eq!(q8_gather_grid(5, &s), Ok([3, 1, 1])); + assert_eq!(q8_gather_grid(5, s), Ok([3, 1, 1])); +} + +fn assert_kv_shape_checks(s: KvShape) { let odd = KvShape { head_dim: 192, ..s }; assert!(odd.check_q8().is_ok() && odd.check_q4().is_err() && odd.check_attn().is_err()); assert!(KvShape { head_dim: 100, ..s }.check_q8().is_err()); assert!(KvShape { kv_heads: 0, ..s }.check_q4().is_err()); assert!(KvShape { page_size: 0, ..s }.check_q8().is_err()); +} + +fn assert_attention_and_cvec_grids(s: &KvShape) { assert_eq!(copy_u4_grid(1), Ok([1, 1, 1])); assert_eq!(copy_u4_grid(129), Ok([2, 1, 1])); assert_eq!(copy_u4_grid(1 << 40), Ok([4096, 1, 1])); - assert_eq!(attn_chunk_grid(64, &s, 3), Ok([1, 2, 3])); - assert_eq!(attn_chunk_grid(65, &s, 1), Ok([2, 2, 1])); - assert_eq!(attn_merge_grid(&s, 4), Ok([24, 4, 1])); - assert!(attn_chunk_grid(0, &s, 1).is_err() && attn_chunk_grid(64, &s, 65_536).is_err()); + assert_eq!(attn_chunk_grid(64, s, 3), Ok([1, 2, 3])); + assert_eq!(attn_chunk_grid(65, s, 1), Ok([2, 2, 1])); + assert_eq!(attn_merge_grid(s, 4), Ok([24, 4, 1])); + assert!(attn_chunk_grid(0, s, 1).is_err() && attn_chunk_grid(64, s, 65_536).is_err()); assert_eq!(keyless_grid(3, 24), Ok([72, 1, 1])); assert!(keyless_grid(0, 24).is_err()); assert_eq!(keyless_matrices_bytes(24), 24 * 65_536 * 4); @@ -232,6 +249,14 @@ fn kv_geometry_matches_the_originals_host_wrappers() { assert!(cvec_grid(4, 3, 4097).is_err() && cvec_grid(4, 3, 0).is_err() && cvec_grid(0, 3, 2560).is_err()); } +#[test] +fn kv_geometry_matches_the_originals_host_wrappers() { + let s = KvShape::real(); + assert_kv_quantizer_grids(&s); + assert_kv_shape_checks(s); + assert_attention_and_cvec_grids(&s); +} + #[test] fn byte_sizes_agree_with_the_reference_layouts() { use leleka_experimental_ref::layout::{KvFormat, kv_pool_bytes, pool_arrays}; @@ -258,19 +283,17 @@ fn byte_sizes_agree_with_the_reference_layouts() { assert_eq!(s.as_qsa(), q); } +fn refuses_with(result: Result<()>, needle: &str) -> bool { + matches!(result, Err(ExperimentalError::Invalid(m)) if m.contains(needle)) +} + #[test] fn stream_resolve_guards_are_the_originals() { let s = KvShape::real(); assert_eq!(check_stream_resolve(&s, 5120, 1, 2048), Ok(())); - assert!( - matches!(check_stream_resolve(&s, 1023, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("fewer slots")) - ); - assert!( - matches!(check_stream_resolve(&s, 1024, 8, 4096), Err(ExperimentalError::Invalid(m)) if m.contains("distinct blocks")) - ); + assert!(refuses_with(check_stream_resolve(&s, 1023, 1, 8), "fewer slots")); + assert!(refuses_with(check_stream_resolve(&s, 1024, 8, 4096), "distinct blocks")); assert!(check_stream_resolve(&s, 5120, 0, 8).is_err()); let misaligned = KvShape { kv_heads: 1, page_size: 1, ..s }; - assert!( - matches!(check_stream_resolve(&misaligned, 5120, 1, 8), Err(ExperimentalError::Invalid(m)) if m.contains("16 bytes")) - ); + assert!(refuses_with(check_stream_resolve(&misaligned, 5120, 1, 8), "16 bytes")); } diff --git a/crates/cuda-driver/src/family_tests.rs b/crates/cuda-driver/src/family_tests.rs index d4c6abc7..ed869202 100644 --- a/crates/cuda-driver/src/family_tests.rs +++ b/crates/cuda-driver/src/family_tests.rs @@ -57,106 +57,168 @@ fn common_invalid_shapes_have_fixed_errors() { ); } -#[test] -fn q4_k_admission_bounds_every_padded_cta_byte_offset() { +const BLOCK_BYTES: usize = 144; +const ROWS_PER_CTA: usize = 4; +const MAX_BLOCK_INDEX: usize = i32::MAX as usize / BLOCK_BYTES; + +fn q4_k_spec(rows: usize, columns: usize) -> ProjectionSpec { + ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows, columns } +} + +fn assert_small_n_stays_on_a_four_row_boundary() { // At N=256 the kernel launches four output rows per CTA and computes // all four row-arm offsets before guarding the final partial CTA. // The largest admitted padded row count therefore stays on a four // row boundary and its post-loop signed offset fits i32. - const BLOCK_BYTES: usize = 144; - const ROWS_PER_CTA: usize = 4; - let max_block_index = i32::MAX as usize / BLOCK_BYTES; // Include the common final +8-block PTX increment after the last // iteration, then round the small-N four-row CTA down to its boundary. - let max_padded_rows = ((max_block_index.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); + let max_padded_rows = ((MAX_BLOCK_INDEX.saturating_sub(7) / ROWS_PER_CTA) * ROWS_PER_CTA).max(ROWS_PER_CTA); let at_limit_offset = (max_padded_rows + 7) * BLOCK_BYTES; assert!(at_limit_offset <= i32::MAX as usize); assert!(q4_k_native_indices_fit(max_padded_rows - ROWS_PER_CTA, 256)); assert!(q4_k_native_indices_fit(max_padded_rows, 256)); assert!(!q4_k_native_indices_fit(max_padded_rows + 1, 256)); - assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_padded_rows, - columns: 256, - }) - .is_ok() - ); + assert!(projection_shape(q4_k_spec(max_padded_rows, 256)).is_ok()); +} +fn assert_large_n_materializes_the_next_rows() { // The large-N launch uses one CTA per row but still materializes // row+1 through row+3 and the final offsets of all eight lane groups. let blocks_per_row = 2048 / 256; - let max_large_n_rows = ((max_block_index - (blocks_per_row + 7)) / blocks_per_row) - 2; + let max_large_n_rows = ((MAX_BLOCK_INDEX - (blocks_per_row + 7)) / blocks_per_row) - 2; assert!(q4_k_native_indices_fit(max_large_n_rows - 1, 2048)); assert!(q4_k_native_indices_fit(max_large_n_rows, 2048)); assert!(!q4_k_native_indices_fit(max_large_n_rows + 1, 2048)); - assert!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_large_n_rows, - columns: 2048, - }) - .is_ok() - ); - assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: max_large_n_rows + 1, - columns: 2048, - }), - Err(Error::InvalidProjectionShape) - ); + assert!(projection_shape(q4_k_spec(max_large_n_rows, 2048)).is_ok()); + assert_eq!(projection_shape(q4_k_spec(max_large_n_rows + 1, 2048)), Err(Error::InvalidProjectionShape)); +} - // N=2304 has nine blocks: lane group 0 visits 0 and 8 then reaches - // 16, the maximum final index across groups 0..7. - let blocks_per_row: usize = 2304 / 256; +fn assert_final_loop_index_bounds_the_rows(columns: usize, expected_final_index: usize) { + let blocks_per_row: usize = columns / 256; let final_loop_index = blocks_per_row + 7; - assert_eq!(final_loop_index, 16); - let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; - assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 2304)); - assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 2304)); - - // For sixteen blocks, lane group 7 visits block 15 and increments to - // 23; checking only the block-zero loop would miss this signed offset. - let blocks_per_row: usize = 4096 / 256; - let final_loop_index = blocks_per_row + 7; - assert_eq!(final_loop_index, 23); - let max_nonwrapping_rows = ((max_block_index - final_loop_index) / blocks_per_row) - 2; - assert!(q4_k_native_indices_fit(max_nonwrapping_rows, 4096)); - assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, 4096)); + assert_eq!(final_loop_index, expected_final_index); + let max_nonwrapping_rows = ((MAX_BLOCK_INDEX - final_loop_index) / blocks_per_row) - 2; + assert!(q4_k_native_indices_fit(max_nonwrapping_rows, columns)); + assert!(!q4_k_native_indices_fit(max_nonwrapping_rows + 1, columns)); +} +fn assert_the_qa_counterexample_is_refused() { // The independent QA counterexample and its adjacent valid-row // boundary are rejected before any context, cache, or allocation work. for rows in [14_913_081, 14_913_082] { assert!(!q4_k_native_indices_fit(rows, 256)); - assert_eq!( - projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows, columns: 256 }), - Err(Error::InvalidProjectionShape) - ); + assert_eq!(projection_shape(q4_k_spec(rows, 256)), Err(Error::InvalidProjectionShape)); } +} +fn assert_one_row_and_huge_n_is_structural() { // With one row, a large N may have a large total extent while every // native signed packed-byte base remains representable. This case is // structural only and deliberately allocates no host or device data. let large_n = 256 * 3_000_000; assert!(q4_k_native_indices_fit(1, large_n)); - assert!( - projection_shape(ProjectionSpec { kind: ProjectionKind::Dense(DenseFormat::Q4_K), rows: 1, columns: large_n }) - .is_ok() - ); - + assert!(projection_shape(q4_k_spec(1, large_n)).is_ok()); // Positive individually-valid M and N still refuse when their Q4_K // row/block product would overflow the native signed byte offset. let max_i32_n = (i32::MAX as usize / 256) * 256; assert!(!q4_k_native_indices_fit(2, max_i32_n)); - assert_eq!( - projection_shape(ProjectionSpec { - kind: ProjectionKind::Dense(DenseFormat::Q4_K), - rows: 2, - columns: max_i32_n, - }), - Err(Error::InvalidProjectionShape) - ); + assert_eq!(projection_shape(q4_k_spec(2, max_i32_n)), Err(Error::InvalidProjectionShape)); +} + +#[test] +fn q4_k_admission_bounds_every_padded_cta_byte_offset() { + assert_small_n_stays_on_a_four_row_boundary(); + assert_large_n_materializes_the_next_rows(); + // N=2304 has nine blocks: lane group 0 visits 0 and 8 then reaches + // 16, the maximum final index across groups 0..7. + assert_final_loop_index_bounds_the_rows(2304, 16); + // For sixteen blocks, lane group 7 visits block 15 and increments to + // 23; checking only the block-zero loop would miss this signed offset. + assert_final_loop_index_bounds_the_rows(4096, 23); + assert_the_qa_counterexample_is_refused(); + assert_one_row_and_huge_n_is_structural(); +} + +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +fn assert_misaligned_ranges_are_refused_without_driver_work(context: &Context<'_>, trace_path: &str, before: &[u8]) { + for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) { + let shape = projection_shape(ProjectionSpec { kind, rows: 1, columns: 256 }).unwrap(); + let addresses = + [ffi::BufferHandle::synthetic(2), ffi::BufferHandle::synthetic(4096), ffi::BufferHandle::synthetic(8192)]; + assert_eq!( + projection_ranges(kind, &shape, addresses), + if alignment == 4 { Err(Error::InvalidProjectionShape) } else { Ok(()) } + ); + assert_eq!(std::fs::read(trace_path).unwrap(), before); + assert_eq!(context.allocated_bytes(), 0); + assert!(context.common_quantizer.get().is_none()); + assert!(context.projection_kernels.iter().all(|slot| slot.get().is_none())); + } +} + +/// The three device buffers of one common-quantize launch. +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +struct QuantizeBuffers<'a, 'c> { + input: &'a DeviceBuffer<'c>, + scratch: &'a DeviceBuffer<'c>, + status: &'a mut DeviceBuffer<'c>, +} + +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +fn quantize_through_the_mock(context: &Context<'_>, buffers: QuantizeBuffers<'_, '_>, n: usize) -> Result<()> { + let QuantizeBuffers { input, scratch, status } = buffers; + status.copy_from(&[0; 4])?; + let guard = context.enter()?; + let kernel = match context.fixed_kernel(FixedOperation::CommonQuantize) { + Ok(k) => k, + Err(e) => return combine(Err(e), guard.finish()), + }; + combine(Ok(()), guard.finish())?; + let mut args = + ffi::Q8QuantizeArguments::new(input.handle.unwrap(), scratch.handle.unwrap(), status.handle.unwrap(), n as u32); + let guard = context.enter()?; + let launch = context.driver.api.launch_q8_quantize(kernel.function, n.div_ceil(256) as u32, &mut args); + context.complete_launch(launch, args, guard)?; + let mut bytes = [0; 4]; + status.copy_to(&mut bytes)?; + let expected = std::env::var("MOCK_FAMILY_STATUS").unwrap_or_else(|_| "0".into()).parse::().unwrap(); + assert_eq!(u32::from_le_bytes(bytes), expected); + Ok(()) +} + +/// The bytes the context still charges after the injected failure `base` / `family`. +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +fn expected_charge_after(base: &str, family: &str, n: usize) -> usize { + if family.contains("quant_sync") || family.contains("quant_restore") || base == "lookup:1,unload:1" { + 4 * n + n / 32 * 36 + 4 + } else if base == "free:1" { + 4 * n + 4 + } else if base == "free:2" { + 4 * n + n / 32 * 36 + } else { + 4 * n + } +} + +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +fn assert_launch_sync_restore_errors_keep_their_order(result: &Result<()>) { + let error = format!("{result:?}"); + let launch = error.find("cuLaunchKernel").unwrap(); + let sync = error.find("cuCtxSynchronize").unwrap(); + let restore = error.find("cuCtxPopCurrent_v2").unwrap(); + assert!(launch < sync && sync < restore); +} + +/// Close the context; the injected close failure must surface, any other close must succeed unless the run failed. +#[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] +fn close_and_check(context: Context<'_>, failure: bool) { + let close = context.close(); + let close_failure = std::env::var("LELEKA_FAMILY_CLOSE_FAILURE").as_deref() == Ok("1"); + if close_failure { + assert!(close.is_err()); + } else if !failure { + close.unwrap(); + } } #[cfg(all(feature = "cuda-driver", any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))] @@ -169,75 +231,25 @@ fn family_quantizer_transport_child() { let context = driver.device(0).unwrap().create_context(8192).unwrap(); let trace_path = std::env::var("MOCK_CUDA_TRACE").unwrap(); let before = std::fs::read(&trace_path).unwrap(); - for (kind, alignment) in KINDS.into_iter().zip([2, 4, 2, 2, 2, 2, 2, 4, 4, 2]) { - let shape = projection_shape(ProjectionSpec { kind, rows: 1, columns: 256 }).unwrap(); - let addresses = - [ffi::BufferHandle::synthetic(2), ffi::BufferHandle::synthetic(4096), ffi::BufferHandle::synthetic(8192)]; - assert_eq!( - projection_ranges(kind, &shape, addresses), - if alignment == 4 { Err(Error::InvalidProjectionShape) } else { Ok(()) } - ); - assert_eq!(std::fs::read(&trace_path).unwrap(), before); - assert_eq!(context.allocated_bytes(), 0); - assert!(context.common_quantizer.get().is_none()); - assert!(context.projection_kernels.iter().all(|slot| slot.get().is_none())); - } + assert_misaligned_ranges_are_refused_without_driver_work(&context, &trace_path, &before); let mut input = context.allocate(4 * n).unwrap(); input.copy_from(&vec![0; 4 * n]).unwrap(); let scratch = context.allocate(n / 32 * 36).unwrap(); let mut status = context.allocate(4).unwrap(); - let operation = (|| { - status.copy_from(&[0; 4])?; - let guard = context.enter()?; - let kernel = match context.fixed_kernel(FixedOperation::CommonQuantize) { - Ok(k) => k, - Err(e) => return combine(Err(e), guard.finish()), - }; - combine(Ok(()), guard.finish())?; - let mut args = ffi::Q8QuantizeArguments::new( - input.handle.unwrap(), - scratch.handle.unwrap(), - status.handle.unwrap(), - n as u32, - ); - let guard = context.enter()?; - let launch = context.driver.api.launch_q8_quantize(kernel.function, n.div_ceil(256) as u32, &mut args); - context.complete_launch(launch, args, guard)?; - let mut bytes = [0; 4]; - status.copy_to(&mut bytes)?; - let expected = std::env::var("MOCK_FAMILY_STATUS").unwrap_or_else(|_| "0".into()).parse::().unwrap(); - assert_eq!(u32::from_le_bytes(bytes), expected); - Ok(()) - })(); + let operation = quantize_through_the_mock( + &context, + QuantizeBuffers { input: &input, scratch: &scratch, status: &mut status }, + n, + ); let result = context.release_quantized_temporaries(operation, scratch, status); let failure = std::env::var("LELEKA_FAMILY_EXPECT_FAILURE").as_deref() == Ok("1"); assert_eq!(result.is_err(), failure, "result={result:?}"); let base = std::env::var("MOCK_CUDA_FAIL").unwrap_or_default(); let family = std::env::var("MOCK_CUDA_FAMILY_FAIL").unwrap_or_default(); - let expected_charge = - if family.contains("quant_sync") || family.contains("quant_restore") || base == "lookup:1,unload:1" { - 4 * n + n / 32 * 36 + 4 - } else if base == "free:1" { - 4 * n + 4 - } else if base == "free:2" { - 4 * n + n / 32 * 36 - } else { - 4 * n - }; - assert_eq!(context.allocated_bytes(), expected_charge); + assert_eq!(context.allocated_bytes(), expected_charge_after(&base, &family, n)); if family == "quant_launch,quant_sync,quant_restore" { - let error = format!("{result:?}"); - let launch = error.find("cuLaunchKernel").unwrap(); - let sync = error.find("cuCtxSynchronize").unwrap(); - let restore = error.find("cuCtxPopCurrent_v2").unwrap(); - assert!(launch < sync && sync < restore); + assert_launch_sync_restore_errors_keep_their_order(&result); } drop(input); - let close = context.close(); - let close_failure = std::env::var("LELEKA_FAMILY_CLOSE_FAILURE").as_deref() == Ok("1"); - if close_failure { - assert!(close.is_err()); - } else if !failure { - close.unwrap(); - } + close_and_check(context, failure); } diff --git a/crates/cuda-driver/src/ffi/impl_contexthandle.rs b/crates/cuda-driver/src/ffi/impl_contexthandle.rs index 3a1e6832..1cf1c0aa 100644 --- a/crates/cuda-driver/src/ffi/impl_contexthandle.rs +++ b/crates/cuda-driver/src/ffi/impl_contexthandle.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl ContextHandle, impl BufferHandle, fn projection_ptx, fn validate_projection_ptx, fn projection_available, fn projection_entry .... +//! Moved out of the parent module by STRA-338: impl ContextHandle, impl BufferHandle, fn projection_ptx, fn +//! validate_projection_ptx, fn projection_available, fn projection_entry .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/ffi/impl_functionhandle.rs b/crates/cuda-driver/src/ffi/impl_functionhandle.rs index b393a0ab..d2504d10 100644 --- a/crates/cuda-driver/src/ffi/impl_functionhandle.rs +++ b/crates/cuda-driver/src/ffi/impl_functionhandle.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl FunctionHandle, impl FunctionHandle, impl LaunchArguments, impl Drop_for_LaunchArguments, impl GrReadGuardArguments, impl Drop_for_GrReadGuardArguments .... +//! Moved out of the parent module by STRA-338: impl FunctionHandle, impl FunctionHandle, impl LaunchArguments, impl +//! Drop_for_LaunchArguments, impl GrReadGuardArguments, impl Drop_for_GrReadGuardArguments .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/ffi/impl_qsaselectedarguments.rs b/crates/cuda-driver/src/ffi/impl_qsaselectedarguments.rs index 8579cc0c..e894d0f2 100644 --- a/crates/cuda-driver/src/ffi/impl_qsaselectedarguments.rs +++ b/crates/cuda-driver/src/ffi/impl_qsaselectedarguments.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl QsaSelectedArguments, impl Drop_for_QsaSelectedArguments, impl HeadGreedyArguments, impl Drop_for_HeadGreedyArguments. +//! Moved out of the parent module by STRA-338: impl QsaSelectedArguments, impl Drop_for_QsaSelectedArguments, impl +//! HeadGreedyArguments, impl Drop_for_HeadGreedyArguments. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs index 42c14ce0..bfe8b6dc 100644 --- a/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs +++ b/crates/cuda-driver/src/gdn_closed_queue/impl_gdnqueuestage.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl GdnQueueStage, impl Step, fn decode_statuses, fn column_row_offset, impl GdnRowCompletion, impl Context .... +//! Moved out of the parent module by STRA-338: impl GdnQueueStage, impl Step, fn decode_statuses, fn +//! column_row_offset, impl GdnRowCompletion, impl Context .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_fused_t1.rs b/crates/cuda-driver/src/gdn_fused_t1.rs index 41197b74..e13dcdc1 100644 --- a/crates/cuda-driver/src/gdn_fused_t1.rs +++ b/crates/cuda-driver/src/gdn_fused_t1.rs @@ -4,7 +4,8 @@ //! decomposed conv / L2 / alpha-beta / gate / step / out-norm launches by //! `fused_gdn_conv_l2` (4-tap causal conv + SiLU + both L2 norms, history updated in place), //! `fused_gdn_ab` (BF16 alpha/beta GEMV + softplus/sigmoid epilogues), -//! `fused_gdn_step_norm` (state update, readout, per-head RMS norm, ssm_norm weight, sigmoid(z) gate; state in place). +//! `fused_gdn_step_norm` (state update, readout, per-head RMS norm, ssm_norm weight, sigmoid(z) gate; state in +//! place). //! The kernels are the verbatim text of `engine/strata/src/kernels/cuda/fused_gdn.cu` (see //! `offline_gdn_fused_t1_kernel.cu`). The pinned decode/T1 asset of `offline_gdn_kernel.cu` (decomposed //! `native_gdn = true / fused_gdn = false`) is NOT touched and keeps serving the decomposed path and MTP @@ -42,9 +43,9 @@ pub const GDN_FUSED_T1_PERSISTENT_BYTES: usize = STATUS_BYTES; // ------------------------------------------------------------------ asset // A privately pinned, candidate-only PTX image produced offline by the toolchain owner from -// `offline_gdn_fused_t1_kernel.cu`: nvcc -ptx -O3 -arch=sm_120 offline_gdn_fused_t1_kernel.cu -o offline_gdn_fused_t1.ptx -// It does not join the production `Operation` table. Until the pins below are filled in, `fused_asset()` refuses -// (fail closed); no digest is invented here. +// `offline_gdn_fused_t1_kernel.cu`: nvcc -ptx -O3 -arch=sm_120 offline_gdn_fused_t1_kernel.cu -o +// offline_gdn_fused_t1.ptx It does not join the production `Operation` table. Until the pins below are filled in, +// `fused_asset()` refuses (fail closed); no digest is invented here. // TODO-ROOT: exact byte length (without the trailing NUL) of offline_gdn_fused_t1.ptx. const FUSED_PTX_LEN: usize = 51663; diff --git a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs index 36ffa34a..5904b09a 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/impl_gdnfusedprefix/impl_gdnfusedprefix_2_2.rs @@ -24,7 +24,8 @@ impl<'lease, 'ctx> GdnFusedPrefix<'lease, 'ctx> { })(); self.latch(result) } - /// The retained state, H, gate, beta and Z handles, then the bound gamma and Y: `[state, h, gate, beta, z, gamma, y]`. + /// The retained state, H, gate, beta and Z handles, then the bound gamma and Y: `[state, h, gate, beta, z, gamma, + /// y]`. fn step_norm_handles( &mut self, gamma: &'lease DeviceBuffer<'lease>, diff --git a/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs index cd25993a..04fe922e 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/pinned_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn pinned, fn fused_asset, impl FusedKernel, fn linear, impl GdnFusedStage, fn decode_statuses .... +//! Moved out of the parent module by STRA-338: fn pinned, fn fused_asset, impl FusedKernel, fn linear, impl +//! GdnFusedStage, fn decode_statuses .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs index 21e2db0a..95b66405 100644 --- a/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs +++ b/crates/cuda-driver/src/gdn_fused_t1/words_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn words, fn staging, impl GdnFusedT1, impl Drop_for_GdnFusedT1, impl GdnFusedT1, impl GdnFusedPrefix. +//! Moved out of the parent module by STRA-338: fn words, fn staging, impl GdnFusedT1, impl Drop_for_GdnFusedT1, impl +//! GdnFusedT1, impl GdnFusedPrefix. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs index 3458de9e..4de60a62 100644 --- a/crates/cuda-driver/src/gdn_native_batch/impl_context.rs +++ b/crates/cuda-driver/src/gdn_native_batch/impl_context.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl Context, impl GdnPrefillBatch, impl Command, impl GdnBatchCompletion. +//! Moved out of the parent module by STRA-338: impl Context, impl GdnPrefillBatch, impl Command, impl +//! GdnBatchCompletion. #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs b/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs index 3b94acad..fb1ea091 100644 --- a/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch/pinned_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn pinned, fn prefill_asset, fn dequant_asset, impl Kernel, fn linear, impl GdnNativeFormat .... +//! Moved out of the parent module by STRA-338: fn pinned, fn prefill_asset, fn dequant_asset, impl Kernel, fn linear, +//! impl GdnNativeFormat .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs index 238ec515..cf13fe41 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/bytes_of_fn.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: fn bytes_of, fn words_of, fn halves_of, fn f16_bits, fn f16_value, fn bf_bits .... +//! Moved out of the parent module by STRA-338: fn bytes_of, fn words_of, fn halves_of, fn f16_bits, fn f16_value, fn +//! bf_bits .... #[allow(unused_imports)] use super::*; diff --git a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs index 15636bd3..337024e2 100644 --- a/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs +++ b/crates/cuda-driver/src/gdn_native_batch_gpu/impl_hostgemm.rs @@ -1,4 +1,5 @@ -//! Moved out of the parent module by STRA-338: impl HostGemm, impl GdnGemm_for_HostGemm, fn upload, fn read, impl Fixture, fn mismatch. +//! Moved out of the parent module by STRA-338: impl HostGemm, impl GdnGemm_for_HostGemm, fn upload, fn read, impl +//! Fixture, fn mismatch. #[allow(unused_imports)] use super::*;