diff --git a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs index 9741d4d5..86c71169 100644 --- a/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs +++ b/crates/cuda-driver/src/ple_batch_ffi/enabled/impl_blas.rs @@ -26,10 +26,8 @@ impl Blas { _driver: Some(driver), _vendor: Some(vendor), }; - let result = owner.init_handle( - HandleSymbols { stream_create, create, set_stream, set_workspace, set_math }, - (workspace, bytes), - ); + let symbols = HandleSymbols { stream_create, create, set_stream, set_workspace, set_math }; + let result = owner.init_handle(symbols, (workspace, bytes)); if let Err(e) = result { return combine(Err(e), owner.close()); } diff --git a/crates/cuda-driver/src/ple_closed_queue_gpu.rs b/crates/cuda-driver/src/ple_closed_queue_gpu.rs index aace4d54..68565083 100644 --- a/crates/cuda-driver/src/ple_closed_queue_gpu.rs +++ b/crates/cuda-driver/src/ple_closed_queue_gpu.rs @@ -223,6 +223,17 @@ fn tiny_budget_refused(device: &Device<'_>) { assert_eq!(allocated, 0); assert!(closed.is_ok()); } +/// The six weights: key, value, three aux norms and the convolution. +fn upload_weights<'c>(context: &'c Context<'c>, weights: &mut Vec>) -> Result<()> { + weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; + weights.push(upload(context, &bf16(10240 * 2560, 2))?); + weights.push(upload(context, &bf16(2560 * 2560, 3))?); + for _ in 0..3 { + weights.push(upload(context, &float_staging(&vec![1.0; 10240])?)?); + } + weights.push(upload(context, &bf16(4 * 10240, 4))?); + Ok(()) +} /// The weights, the queue and the foreign weight stay owned by the caller so it can release them on any error. fn queue_cases<'c>( context: &'c Context<'c>, @@ -233,13 +244,7 @@ fn queue_cases<'c>( &mut Option>, ), ) -> Result { - weights.try_reserve_exact(6).map_err(|_| Error::HostAllocation)?; - weights.push(upload(context, &bf16(10240 * 2560, 2))?); - weights.push(upload(context, &bf16(2560 * 2560, 3))?); - for _ in 0..3 { - weights.push(upload(context, &float_staging(&vec![1.0; 10240])?)?); - } - weights.push(upload(context, &bf16(4 * 10240, 4))?); + upload_weights(context, weights)?; *queue = Some(context.ple_closed_queue()?); let q = queue.as_mut().ok_or(Error::ContextPoisoned)?; let mut tally = Tally::default(); @@ -252,6 +257,12 @@ fn queue_cases<'c>( invalid_input_cases(q, weights, inputs, &mut tally); *foreign_weight = Some(foreign.allocate(1024)?); foreign_weight_case(q, weights, foreign_weight.as_ref().ok_or(Error::ContextPoisoned)?, inputs, &mut tally); + alias_refused_and_status_unchanged(q, &before, &mut tally)?; + Ok(tally) +} +/// A weight view of the queue's own buffer is refused, and the status buffer still holds what it held before the +/// refusals. +fn alias_refused_and_status_unchanged(q: &mut PleClosedQueue<'_>, before: &[u32], tally: &mut Tally) -> Result<()> { if !matches!(q.weight(q.buffer(0)?, 10240, 4), Err(Error::OutputAliasesInput)) { tally.differences += 1; } @@ -259,7 +270,7 @@ fn queue_cases<'c>( if read(q.buffer(12)?)? != before { tally.differences += 1; } - Ok(tally) + Ok(()) } /// Four causal rows: each candidate history must equal the original complete history first. Returns the last one. fn causal_history_cases<'c>( @@ -290,8 +301,19 @@ fn causal_history_cases<'c>( } Ok(history) } -/// A non-finite or oversized element in each weight is refused alike by the original and the queue, and the restored -/// weight gives identical products again. +/// A non-finite or oversized element (weight index, byte offset, bytes) in each weight. +fn corruptions() -> [(usize, usize, Vec); 6] { + [ + (0, 52_428_798, vec![0x80, 0x7f]), + (1, 13_107_198, vec![0x80, 0x7f]), + (2, 40956, f32::NAN.to_le_bytes().to_vec()), + (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), + (4, 40956, f32::NAN.to_le_bytes().to_vec()), + (5, 81918, vec![0xc0, 0x7f]), + ] +} +/// A corrupted weight is refused alike by the original and the queue, and the restored weight gives identical +/// products again. fn corrupted_weight_cases<'c>( context: &Context<'_>, q: &mut PleClosedQueue<'c>, @@ -299,14 +321,7 @@ fn corrupted_weight_cases<'c>( (embedding, streams, history): (&[f32], &[f32], &[f32]), tally: &mut Tally, ) -> Result<()> { - for (weight, offset, bytes) in [ - (0, 52_428_798, vec![0x80, 0x7f]), - (1, 13_107_198, vec![0x80, 0x7f]), - (2, 40956, f32::NAN.to_le_bytes().to_vec()), - (3, 40956, f32::INFINITY.to_le_bytes().to_vec()), - (4, 40956, f32::NAN.to_le_bytes().to_vec()), - (5, 81918, vec![0xc0, 0x7f]), - ] { + for (weight, offset, bytes) in corruptions() { let mut saved = staging(weights[weight].bytes)?; weights[weight].copy_to(&mut saved)?; weights[weight].copy_from_range(offset, &bytes)?; @@ -317,19 +332,30 @@ fn corrupted_weight_cases<'c>( } tally.guards += 1; weights[weight].copy_from(&saved)?; - let old = original(context, refs(weights), embedding, streams, history)?; - let (refusal, products) = queued(q, refs(weights), embedding, streams, history)?; - if refusal.is_some() || old.refusal.is_some() { - tally.differences += 1; - } - for (a, b) in old.products.iter().zip(products) { - tally.words += a.len(); - tally.differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); - } - tally.guards += 1; + restored_weight_case(context, q, weights, (embedding, streams, history), tally)?; } Ok(()) } +/// With the weight restored the original and the queue give identical, finite products again. +fn restored_weight_case<'c>( + context: &Context<'_>, + q: &mut PleClosedQueue<'c>, + weights: &[DeviceBuffer<'_>], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + tally: &mut Tally, +) -> Result<()> { + let old = original(context, refs(weights), embedding, streams, history)?; + let (refusal, products) = queued(q, refs(weights), embedding, streams, history)?; + if refusal.is_some() || old.refusal.is_some() { + tally.differences += 1; + } + for (a, b) in old.products.iter().zip(products) { + tally.words += a.len(); + tally.differences += a.iter().zip(b).filter(|(a, b)| **a != *b).count(); + } + tally.guards += 1; + Ok(()) +} /// Whether the queue composes these weights with `key` as the key weight. fn composes( q: &mut PleClosedQueue<'_>, diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs index a9dd6183..7cbfae34 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_recurrence_equals_the_original.rs @@ -46,11 +46,10 @@ struct RecBuffers<'c> { } impl<'c> RecBuffers<'c> { - /// `variant`: 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow. + /// `variant`: 0 clean, 1 an infinite state value, 2 a NaN in the input, 3 products that overflow. The q/k rows are + /// L2-normalised in the real chain; they are kept O(1/sqrt(S)) here so the state stays bounded over the chunk. fn new(context: &'c Context<'c>, rng: &mut Rng, t: usize, variant: u8) -> Self { let mut state: Vec = (0..STATE_LEN).map(|_| rng.f(0.05)).collect(); - // q/k rows are L2-normalised in the real chain; keep them O(1/sqrt(S)) so the state stays bounded over the - // chunk let mut h: Vec = (0..t * 10240).map(|_| rng.f(0.2)).collect(); let gate: Vec = (0..t * 48).map(|_| -rng.f(0.6).abs()).collect(); let beta: Vec = (0..t * 48).map(|_| (rng.f(0.5) + 0.5).abs()).collect(); diff --git a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs index 8e558a08..34f11c76 100644 --- a/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gdn_gpu/gdn_stage_kernels_equal.rs @@ -156,6 +156,37 @@ fn conv_inputs(rng: &mut Rng, case: usize) -> (Vec, Vec, Vec) { (hist, qkv, w) } +/// The Original's tiled convolution of `qkv` through the history `hist` with weights `w` into `out`. +fn conv_old_launch( + (hist_d, qkv_d, w_d, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), +) -> OldLaunch { + let args = vec![ + ffi::KernelArg::Pointer(hd(hist_d)), + ffi::KernelArg::Pointer(hd(qkv_d)), + ffi::KernelArg::Pointer(hd(w_d)), + ffi::KernelArg::Pointer(hd(out)), + ffi::KernelArg::I64(T as i64), + ]; + (Kernel::ConvTiled, [80, T.div_ceil(64) as u32, 1], [128, 1, 1], args) +} + +/// The staged convolution with its QKV and conv guards writing two status words. +fn conv_new_launch( + (hist_d, qkv_d, w_d, out): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>, &DeviceBuffer<'_>), + status: &DeviceBuffer<'_>, +) -> (usize, u32, Vec) { + let args = vec![ + A::Address(hd(hist_d)), + A::Address(hd(qkv_d)), + A::Address(hd(w_d)), + A::Address(hd(out)), + A::I64(T as i64), + A::Address(status_word(status, 0)), + A::Address(status_word(status, 1)), + ]; + (crate::prefill_stage::GDN_CONV_TILED, 40 * T.div_ceil(64) as u32, args) +} + /// The convolution (with its QKV and conv guards) of the staged kernel equals the Original's. fn conv_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> ConvOut<'c> { let (context, t) = (rig.context, T); @@ -165,28 +196,12 @@ fn conv_stage<'c>(rig: &Rig<'c>, rng: &mut Rng, case: usize) -> ConvOut<'c> { let (h_old, h_new) = (upload(context, &zero), upload(context, &zero)); let status_old = upload(context, &[0u8; 64]); let status_new = upload(context, &[0u8; 64]); - let args = vec![ - ffi::KernelArg::Pointer(hd(&hist_d)), - ffi::KernelArg::Pointer(hd(&qkv_d)), - ffi::KernelArg::Pointer(hd(&w_d)), - ffi::KernelArg::Pointer(hd(&h_old)), - ffi::KernelArg::I64(t as i64), - ]; rig.old.run(vec![ - (Kernel::ConvTiled, [80, t.div_ceil(64) as u32, 1], [128, 1, 1], args), + conv_old_launch((&hist_d, &qkv_d, &w_d, &h_old)), scan_launch(&qkv_d, &status_old, t * 10240, 0), scan_launch(&h_old, &status_old, t * 10240, 1), ]); - let args = vec![ - A::Address(hd(&hist_d)), - A::Address(hd(&qkv_d)), - A::Address(hd(&w_d)), - A::Address(hd(&h_new)), - A::I64(t as i64), - A::Address(status_word(&status_new, 0)), - A::Address(status_word(&status_new, 1)), - ]; - let launch = (crate::prefill_stage::GDN_CONV_TILED, 40 * t.div_ceil(64) as u32, args); + let launch = conv_new_launch((&hist_d, &qkv_d, &w_d, &h_new), &status_new); run_stage(context, rig.stream, &rig.stage, vec![launch]); assert_eq!(download(&h_old, t * 10240 * 4), download(&h_new, t * 10240 * 4), "case {case}: conv output"); assert_eq!(words(&status_old, 2), words(&status_new, 2), "case {case}: conv status words (qkv, conv)"); diff --git a/crates/cuda-driver/src/prefill_stage_gpu.rs b/crates/cuda-driver/src/prefill_stage_gpu.rs index 160f9630..698b5cc3 100644 --- a/crates/cuda-driver/src/prefill_stage_gpu.rs +++ b/crates/cuda-driver/src/prefill_stage_gpu.rs @@ -86,13 +86,8 @@ fn packet_records(rng: &mut Rng) -> Vec { records } -/// The reference: the fixed per-token kernels, 16 rows per call. Returns the decoded values and the scatter cache, -/// which stays allocated for the rest of the test. -fn per_token_reference<'c>( - context: &'c Context<'c>, - books: &DeviceBuffer<'c>, - (records, slots): (&[u8], &[u32]), -) -> (Vec, DeviceBuffer<'c>) { +/// The fixed per-token scatter of all records, 16 per call, into a fresh 64 MiB cache. +fn scatter_records<'c>(context: &'c Context<'c>, records: &[u8]) -> DeviceBuffer<'c> { let mut old_cache = context.allocate(64 << 20).expect("old cache"); for group in records.chunks(16 * 56) { let mut updates = context.allocate(16 * 56).expect("updates"); @@ -106,6 +101,17 @@ fn per_token_reference<'c>( context.kar_ple_scatter(&mut old_cache, &updates, 16).expect("old scatter"); updates.release().expect("release"); } + old_cache +} + +/// The reference: the fixed per-token kernels, 16 rows per call. Returns the decoded values and the scatter cache, +/// which stays allocated for the rest of the test. +fn per_token_reference<'c>( + context: &'c Context<'c>, + books: &DeviceBuffer<'c>, + (records, slots): (&[u8], &[u32]), +) -> (Vec, DeviceBuffer<'c>) { + let old_cache = scatter_records(context, records); let mut reference = Vec::::new(); for position in 0..T { let mut slot_bytes = Vec::new(); @@ -194,6 +200,19 @@ fn stage_owners<'c>(context: &'c Context<'c>) -> StageOwners<'c> { } } +/// R rows: four copies of the selected embedding row. +fn assert_r_rows(residual: &mut OriginalDeviceResidual<'_, '_, '_>, staged: &Staged) { + for row in [0usize, 1, 57, T - 1] { + let streams = residual.read_prompt_row(row).expect("R row"); + let source = &staged.embedding[staged.index[row] as usize * 2560..][..2560]; + for stream in 0..4 { + for (i, v) in streams[stream * 2560..][..2560].iter().enumerate() { + assert_eq!(v.to_bits(), source[i].to_bits(), "row {row} stream {stream} value {i}"); + } + } + } +} + /// `initialize_staged` fills R with four copies of the selected embedding row and the PLE span bit-identical to the /// per-token decode. fn check_staged_equals_reference<'c>( @@ -209,16 +228,7 @@ fn check_staged_equals_reference<'c>( (&staged.records, &staged.slots), ); let mut residual = owners.prompt.initialize_staged(lease, &mut owners.workspace, input).expect("initialize_staged"); - // R rows: four copies of the selected embedding row - for row in [0usize, 1, 57, T - 1] { - let streams = residual.read_prompt_row(row).expect("R row"); - let source = &staged.embedding[staged.index[row] as usize * 2560..][..2560]; - for stream in 0..4 { - for (i, v) in streams[stream * 2560..][..2560].iter().enumerate() { - assert_eq!(v.to_bits(), source[i].to_bits(), "row {row} stream {stream} value {i}"); - } - } - } + assert_r_rows(&mut residual, staged); // PLE embedding span: bit-identical to the per-token decode let (handle, span_bytes) = residual.lease().common_span(S::PleEmbedding).expect("ple span"); let raw = read(context, handle, T * 10240); diff --git a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs index 83493593..596acce8 100644 --- a/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs +++ b/crates/cuda-driver/src/prefill_stage_gr_gpu/gr_fused_guards_equal.rs @@ -131,6 +131,13 @@ fn norm_phase<'c>(rig: &GrRig<'c>, host: &Host, case: usize) -> NormOut<'c> { NormOut { r_old, r_new, w, rs_o, rs_n, fl_n } } +/// `mix_r` arguments over R, the row scales, gamma, g and the three mixed outputs; the fused flags word when `flags`. +fn mix_args([r, rs, w, g, mx, m16, mh]: [&DeviceBuffer<'_>; 7], flags: Option<&DeviceBuffer<'_>>) -> Vec { + let mut args = vec![a(r), a(rs), a(w), a(g), a(mx), a(m16), A::I64(T as i64), a(mh), A::NullAddress]; + args.extend(flags.map(a)); + args +} + /// Mix (uses the row scales of the norm phase); returns the staged flags. fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) -> DeviceBuffer<'c> { let (c, t, gr, stage) = (rig.context, T, &rig.gr, &rig.stage); @@ -140,20 +147,8 @@ fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) let (fl2_o, fl2_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); let NormOut { r_old, r_new, w, rs_o, rs_n, .. } = norm; let rows = (t * 10240).div_ceil(256); - let mix_old = - vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&mx_o), a(&m16_o), A::I64(t as i64), a(&mh_o), A::NullAddress]; - let mix_new = vec![ - a(r_new), - a(rs_n), - a(w), - a(&g_dev), - a(&mx_n), - a(&m16_n), - A::I64(t as i64), - a(&mh_n), - A::NullAddress, - a(&fl2_n), - ]; + let mix_old = mix_args([r_old, rs_o, w, &g_dev, &mx_o, &m16_o, &mh_o], None); + let mix_new = mix_args([r_new, rs_n, w, &g_dev, &mx_n, &m16_n, &mh_n], Some(&fl2_n)); rig.run(vec![ (gr, 2, (t * 2560).div_ceil(256), 256, mix_old), (gr, 7, rows, 256, vec![a(r_old), a(rs_o), a(w), a(&g_dev), a(&fl2_o), A::I64(t as i64)]), @@ -168,6 +163,14 @@ fn mix_phase<'c>(rig: &GrRig<'c>, host: &Host, norm: &NormOut<'c>, case: usize) fl2_n } +/// Fused write + next norm arguments over R, bo, the injection, gamma, the row scales and xn16; the fused flags word +/// when `flags`. +fn write_args([r, bo, inj, w, rs, xn]: [&DeviceBuffer<'_>; 6], flags: Option<&DeviceBuffer<'_>>) -> Vec { + let mut args = vec![a(r), a(bo), a(inj), A::I64(4), a(w), A::F32(EPS), a(rs), a(xn), A::NullAddress]; + args.extend(flags.map(a)); + args +} + /// Fused write + next norm; returns the staged flags and the uploaded bo and injection the plain write reuses. fn write_phase<'c>( rig: &GrRig<'c>, @@ -181,20 +184,8 @@ fn write_phase<'c>( let (rs2_o, rs2_n, xn2_o, xn2_n) = (zeros(c, t * 16), zeros(c, t * 16), zeros(c, t * 20480), zeros(c, t * 20480)); let (fl3_o, fl3_n) = (zeros(c, FLAGS_LEN), zeros(c, FLAGS_LEN)); let rows = (t * 10240).div_ceil(256); - let write_old = - vec![a(&rw_o), a(&bo_d), a(&inj_d), A::I64(4), a(w), A::F32(EPS), a(&rs2_o), a(&xn2_o), A::NullAddress]; - let write_new = vec![ - a(&rw_n), - a(&bo_d), - a(&inj_d), - A::I64(4), - a(w), - A::F32(EPS), - a(&rs2_n), - a(&xn2_n), - A::NullAddress, - a(&fl3_n), - ]; + let write_old = write_args([&rw_o, &bo_d, &inj_d, w, &rs2_o, &xn2_o], None); + let write_new = write_args([&rw_n, &bo_d, &inj_d, w, &rs2_n, &xn2_n], Some(&fl3_n)); rig.run(vec![ (gr, 8, t * 4, 256, write_old), (gr, 4, rows, 256, vec![a(&rw_o), a(&fl3_o), A::I64(10240), A::I64(t as i64), A::U32(7)]), diff --git a/crates/cuda-driver/src/qsa_late_gpu.rs b/crates/cuda-driver/src/qsa_late_gpu.rs index 66803b55..03cbb294 100644 --- a/crates/cuda-driver/src/qsa_late_gpu.rs +++ b/crates/cuda-driver/src/qsa_late_gpu.rs @@ -189,46 +189,9 @@ fn scan_flags_match_original( (scores, steps_d): (&[f32], &DeviceBuffer<'_>), (case, p0, rows): (usize, usize, usize), ) { - let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks); - let reach = (p0 + rows) / 4 + 1; for variant in 0..3 { - let mut bad = scores.to_vec(); - match variant { - 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, - 2 => { - let row = rows - 1; - let n_bid = (p0 + row + 1) / 4; - if n_bid + 1 < max_blocks { - bad[row * max_blocks + n_bid + 1] = f32::INFINITY; - } - } - _ => {} - } - let bad_d = upload(context, &f32_raw(&bad)); - let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16])); - let guard = context.enter().expect("enter"); - let mut so = KernelArguments::new(vec![ - A::Address(handle(&bad_d)), - A::Address(handle(steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::Address(handle(&st_o)), - A::U32(1), - ]); - rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); - let mut sn = KernelArguments::new(vec![ - A::Address(handle(&bad_d)), - A::Address(handle(steps_d)), - A::I32(rows as i32), - A::I64(max_blocks as i64), - A::I64(reach as i64), - A::Address(handle(&st_n)), - A::U32(1), - ]); - let grid = (rows * reach).div_ceil(256) as u32; - rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan"); - context.driver.api.synchronize().expect("sync"); - guard.finish().expect("finish"); + let bad = scores_with_variant(scores, rig.max_blocks, (p0, rows), variant); + let (st_o, st_n) = scan_both(rig, (&bad, steps_d), (p0, rows)); assert_eq!(download(&st_o, 8), download(&st_n, 8), "case {case} variant {variant}: scan flags"); if variant == 1 { assert_ne!(download(&st_n, 8)[4..8], [0, 0, 0, 0], "a NaN inside the blocks must raise the flag"); @@ -236,6 +199,48 @@ fn scan_flags_match_original( } } +/// `scores` with a NaN inside a row's blocks (variant 1) or an infinity beyond a row's last block (variant 2). +fn scores_with_variant(scores: &[f32], max_blocks: usize, (p0, rows): (usize, usize), variant: usize) -> Vec { + let mut bad = scores.to_vec(); + match variant { + 1 => bad[(rows / 2) * max_blocks + ((p0 + rows / 2 + 1) / 4) / 2] = f32::NAN, + 2 => { + let row = rows - 1; + let n_bid = (p0 + row + 1) / 4; + if n_bid + 1 < max_blocks { + bad[row * max_blocks + n_bid + 1] = f32::INFINITY; + } + } + _ => {} + } + bad +} + +/// The Original's score scan and the late fast scan over the same scores; returns both status buffers. +fn scan_both<'c>( + rig: &SelectionRig<'c>, + (bad, steps_d): (&[f32], &DeviceBuffer<'_>), + (p0, rows): (usize, usize), +) -> (DeviceBuffer<'c>, DeviceBuffer<'c>) { + let (context, stream, max_blocks) = (rig.context, rig.stream, rig.max_blocks); + let reach = (p0 + rows) / 4 + 1; + let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b)); + let bad_d = upload(context, &f32_raw(bad)); + let (st_o, st_n) = (upload(context, &[0u8; 16]), upload(context, &[0u8; 16])); + let guard = context.enter().expect("enter"); + let old = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64), ad(&st_o), A::U32(1)]; + let mut so = KernelArguments::new(old); + rig.index.launch(0, (rows * max_blocks).div_ceil(256) as u32, 256, stream, &mut so).expect("old scan"); + let mut new = vec![ad(&bad_d), ad(steps_d), A::I32(rows as i32), A::I64(max_blocks as i64)]; + new.extend([A::I64(reach as i64), ad(&st_n), A::U32(1)]); + let mut sn = KernelArguments::new(new); + let grid = (rows * reach).div_ceil(256) as u32; + rig.late.launch(SCORE_SCAN_FAST, grid, 256, stream, &mut sn).expect("new scan"); + context.driver.api.synchronize().expect("sync"); + guard.finish().expect("finish"); + (st_o, st_n) +} + // ---------------------------------------------------------------------------------------------- top-k variants /// The Original's top-k, the late variants and the decode cluster kernel. @@ -266,40 +271,44 @@ fn topk_variants_equal_the_original_and_are_timed() { guard.finish().expect("finish"); let mut rng = Rng(0x9e3779b97f4a7c15); let rig = BenchRig { context, stream, max_blocks, select, late, cluster }; - // (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail - // (relu-sum like) - let cases: [(usize, usize, u8, &str); 24] = [ - (100, 4, 3, "decode"), - (2_040, 4, 3, "decode"), - (2_049, 5, 1, "decode"), - (3_000, 4, 3, "decode"), - (9_999, 3, 2, "decode"), - (2_040, 256, 3, "prompt"), - (8_000, 256, 3, "prompt"), - (24_000, 256, 3, "prompt"), - (48_000, 256, 3, "prompt"), - (70_000, 256, 3, "prompt"), - (100_003, 256, 0, "prompt"), - (100_003, 256, 3, "prompt"), - (180_000, 256, 0, "prompt"), - (180_000, 256, 3, "prompt"), - (180_000, 256, 1, "prompt"), - (245_000, 256, 3, "prompt"), - (245_000, 256, 2, "prompt"), - (131_072, 1, 3, "decode"), - (131_072, 4, 3, "decode"), - (245_000, 1, 3, "decode"), - (245_000, 4, 3, "decode"), - (245_000, 5, 0, "decode"), - (245_000, 4, 1, "decode"), - (261_500, 4, 2, "decode"), - ]; + let cases = bench_cases(); for (case, c) in cases.into_iter().enumerate() { bench_case(&rig, &mut rng, case, c); } }); } +/// (first position, rows, style, label): style 0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy tail (relu-sum +/// like). +fn bench_cases() -> [(usize, usize, u8, &'static str); 24] { + [ + (100, 4, 3, "decode"), + (2_040, 4, 3, "decode"), + (2_049, 5, 1, "decode"), + (3_000, 4, 3, "decode"), + (9_999, 3, 2, "decode"), + (2_040, 256, 3, "prompt"), + (8_000, 256, 3, "prompt"), + (24_000, 256, 3, "prompt"), + (48_000, 256, 3, "prompt"), + (70_000, 256, 3, "prompt"), + (100_003, 256, 0, "prompt"), + (100_003, 256, 3, "prompt"), + (180_000, 256, 0, "prompt"), + (180_000, 256, 3, "prompt"), + (180_000, 256, 1, "prompt"), + (245_000, 256, 3, "prompt"), + (245_000, 256, 2, "prompt"), + (131_072, 1, 3, "decode"), + (131_072, 4, 3, "decode"), + (245_000, 1, 3, "decode"), + (245_000, 4, 3, "decode"), + (245_000, 5, 0, "decode"), + (245_000, 4, 1, "decode"), + (261_500, 4, 2, "decode"), + ] +} + /// Block scores of `rows` rows from position `p0` in `style` (0 uniform, 1 sixteen tied levels, 2 all equal, 3 heavy /// tail). fn bench_scores(rng: &mut Rng, max_blocks: usize, (p0, rows, style): (usize, usize, u8)) -> Vec { @@ -355,7 +364,6 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, let scores_d = upload(context, &f32_raw(&scores)); let steps_d = upload(context, &steps); let out_len = rows * CAP * 4; - let reps = 20; let variants = topk_variants(rig, rows as u32); let mut reference: Option> = None; let mut line = format!("QSA-TOPK-BENCH case {case} {label} p0={p0} rows={rows} style={style}:"); @@ -363,20 +371,7 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, if *name == "cluster" && rows > 16 { continue; // the decode kernel (the upstream dispatch uses it for at most 16 queries) } - let ids = upload(context, &vec![0xffu8; out_len]); - let mut a = topk_args(rig.max_blocks, (&scores_d, &steps_d), &ids); - let guard = context.enter().expect("enter"); - // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run - run(&mut a); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..reps { - run(&mut a); - } - context.driver.api.synchronize().expect("sync"); - let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; - guard.finish().expect("finish"); - let got = download(&ids, out_len); + let (got, us) = time_variant(rig, run, (&scores_d, &steps_d), out_len); match &reference { None => reference = Some(got), Some(r) => assert!( @@ -389,6 +384,30 @@ fn bench_case(rig: &BenchRig<'_>, rng: &mut Rng, case: usize, (p0, rows, style, eprintln!("{line} ids equal"); } +/// Runs one variant warm, then 20 launches drained once; returns the ids it wrote and the per-launch microseconds. +fn time_variant( + rig: &BenchRig<'_>, + run: &Run<'_>, + inputs: (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + out_len: usize, +) -> (Vec, f64) { + let (context, reps) = (rig.context, 20); + let ids = upload(context, &vec![0xffu8; out_len]); + let mut a = topk_args(rig.max_blocks, inputs, &ids); + let guard = context.enter().expect("enter"); + // the sample kernel flags its failures in a module global that persists: clear by running sample first inside run + run(&mut a); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..reps { + run(&mut a); + } + context.driver.api.synchronize().expect("sync"); + let us = t0.elapsed().as_secs_f64() * 1e6 / reps as f64; + guard.finish().expect("finish"); + (download(&ids, out_len), us) +} + // ---------------------------------------------------------------------------------------------- decode scores /// Timing only (row 2.5 follow-up): the decode window's block scores (`qsa_decode_scores`, the Original's multi-query kernel, 256 CTAs) next to its @@ -409,7 +428,28 @@ fn decode_scores_are_timed_next_to_the_topk() { }); } -/// Random pooled/dead/query vectors, the steps, and the scores/ids outputs of one `(pos, nq)` shape. +/// Random pooled, dead and query vectors and the steps of one `(pos, nq)` shape, uploaded in that order. +fn decode_inputs<'c>( + context: &'c Context<'c>, + rng: &mut Rng, + max_blocks: usize, + (pos, nq): (usize, usize), +) -> [DeviceBuffer<'c>; 4] { + let mut random = + |n: usize| -> Vec { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() }; + let pooled = random((max_blocks + 1) * 128); + let dead = random(128); + let qidx = random(nq * 4 * 128); + let steps = step_bytes(pos, nq); + [ + upload(context, &f32_raw(&pooled)), + upload(context, &f32_raw(&dead)), + upload(context, &f32_raw(&qidx)), + upload(context, &steps), + ] +} + +/// Times the decode scores kernel and the top-k at one `(pos, nq)` shape, 20 warm launches each. fn time_scores_and_topk( context: &Context<'_>, (select, stream, max_blocks): (&KernelModule, usize, usize), @@ -417,45 +457,32 @@ fn time_scores_and_topk( (pos, nq): (usize, usize), ) { let n_bid_max = (pos + nq) / 4; - let mut random = - |n: usize| -> Vec { (0..n).map(|_| ((rng.next() % 2001) as f32 - 1000.0) / 1000.0).collect() }; - let pooled = random((max_blocks + 1) * 128); - let dead = random(128); - let qidx = random(nq * 4 * 128); - let steps = step_bytes(pos, nq); - let (pooled_d, dead_d, qidx_d, steps_d) = ( - upload(context, &f32_raw(&pooled)), - upload(context, &f32_raw(&dead)), - upload(context, &f32_raw(&qidx)), - upload(context, &steps), - ); + let [pooled_d, dead_d, qidx_d, steps_d] = decode_inputs(context, rng, max_blocks, (pos, nq)); let scores_d = upload(context, &vec![0u8; nq * max_blocks * 4]); let ids_d = upload(context, &vec![0xffu8; nq * CAP * 4]); let guard = context.enter().expect("enter"); - let time = |run: &mut dyn FnMut()| -> f64 { - run(); - context.driver.api.synchronize().expect("sync"); - let t0 = std::time::Instant::now(); - for _ in 0..20 { - run(); - } - context.driver.api.synchronize().expect("sync"); - t0.elapsed().as_secs_f64() * 1e6 / 20.0 - }; - let mut sa = KernelArguments::new(vec![ - A::Address(handle(&pooled_d)), - A::Address(handle(&dead_d)), - A::Address(handle(&qidx_d)), - A::Address(handle(&steps_d)), - A::I32(nq as i32), - A::I64(max_blocks as i64), - A::Address(handle(&scores_d)), - ]); - let scores_us = time(&mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); + let ad = |b: &DeviceBuffer<'_>| A::Address(handle(b)); + let (nq_arg, blocks_arg) = (A::I32(nq as i32), A::I64(max_blocks as i64)); + let mut sa: Vec = [&pooled_d, &dead_d, &qidx_d, &steps_d].into_iter().map(|b| ad(b)).collect(); + sa.extend([nq_arg, blocks_arg, ad(&scores_d)]); + let mut sa = KernelArguments::new(sa); + let scores_us = time_warm(context, &mut || select.launch(0, 256, 256, stream, &mut sa).expect("scores")); let mut ta = topk_args(max_blocks, (&scores_d, &steps_d), &ids_d); - let topk_us = time(&mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); + let topk_us = time_warm(context, &mut || select.launch(1, nq as u32, 256, stream, &mut ta).expect("topk")); guard.finish().expect("finish"); eprintln!( "QSA-DECODE-SCORES pos={pos} nq={nq} n_bid={n_bid_max}: qsa_decode_scores {scores_us:.1} us, qsa_topk_ref {topk_us:.1} us (per layer, warm)" ); } + +/// One warm-up run, then 20 timed runs drained once; microseconds per run. +fn time_warm(context: &Context<'_>, run: &mut dyn FnMut()) -> f64 { + run(); + context.driver.api.synchronize().expect("sync"); + let t0 = std::time::Instant::now(); + for _ in 0..20 { + run(); + } + context.driver.api.synchronize().expect("sync"); + t0.elapsed().as_secs_f64() * 1e6 / 20.0 +} diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs index 7c54e849..4ea2012e 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedjournal.rs @@ -99,8 +99,8 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { } Ok(()) } - /// The guard scan, the quantize/append kernel and the scale kernel, each followed by its status check. - pub(super) fn run_append( + /// The guard scan and fence: the new K and V cells must be finite and in range before they are written. + fn guard_append( &mut self, workspace: &mut NativeBatchWorkspace<'ctx>, stage: &mut OriginalQsaResidentTransport<'ctx>, @@ -112,19 +112,26 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { if stage.flags()? != 0 { return Err(Error::InvalidQ8Activation); } + Ok(()) + } + /// The guard scan, the quantize/append kernel and the scale kernel, each followed by its status check. + pub(super) fn run_append( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + stage: &mut OriginalQsaResidentTransport<'ctx>, + p: &AppendPlan, + ) -> Result<()> { + self.guard_append(workspace, stage, p)?; + let [k, v] = p.kv; let mut args = vec![Arg::U64(k), Arg::U64(v), Arg::I64(p.prior_end as i64)]; args.extend([Arg::U64(self.owner.pools.table()?), Arg::I64(4)]); args.extend(p.rp.map(Arg::U64)); args.extend(p.sp.map(Arg::U64)); args.extend(p.hp.map(Arg::U64)); let args = Arguments::new(args)?; - let scales = Arguments::new(vec![ - Arg::U64(p.sp[2]), - Arg::U64(p.sp[3]), - Arg::I32(p.prior_end as i32), - Arg::I32(p.end as i32), - Arg::U64(p.sa), - ])?; + let mut scales = vec![Arg::U64(p.sp[2]), Arg::U64(p.sp[3])]; + scales.extend([Arg::I32(p.prior_end as i32), Arg::I32(p.end as i32), Arg::U64(p.sa)]); + let scales = Arguments::new(scales)?; self.owner.current = None; self.owner.mapped_current = None; diff --git a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs index c069395a..9505b102 100644 --- a/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs +++ b/crates/cuda-driver/src/qsa_mapped_journal/impl_originalqsamappedprefix/impl_originalqsamappedjournal_2.rs @@ -5,6 +5,8 @@ use super::super::impl_originalqsamappedjournal::AppendPlan; use super::*; impl<'ctx> OriginalQsaMappedJournal<'ctx> { + /// Whole original mapped storage/staging has fixed addresses. Only new cells are written; preceding prefix bytes + /// remain actual owners. pub(crate) fn append_resident_arena( &mut self, workspace: &mut NativeBatchWorkspace<'ctx>, @@ -17,8 +19,6 @@ impl<'ctx> OriginalQsaMappedJournal<'ctx> { let (kh, vh) = inputs.kv_spans(self.owner.context)?; self.reject_kv_spans(workspace, stage, (kh, vh), t)?; let table = self.check_prior_and_table(stage, prior)?; - // Whole original mapped storage/staging has fixed addresses. Only new - // cells are written; preceding prefix bytes remain actual owners. let sa = Self::zero_stage_status(stage, self.owner.context)?; let rp = self.owner.pools.addresses()?; let sp = inputs.kv_stage_spans(self.owner.context)?.map(|h| h.qwen_address()); 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 ef4f9305..1240f6b3 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 @@ -93,6 +93,14 @@ impl<'ctx> QsaPromptStage<'ctx> { let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?.copy_to_owned(4)?; Ok(u32::from_le_bytes(b.try_into().map_err(|_| Error::InvalidSize)?)) } + fn launch_pass( + &self, + w: &NativeBatchWorkspace<'ctx>, + (index, grid, block): (usize, [u32; 3], u32), + a: &mut Arguments, + ) -> Result<()> { + self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch(index, grid, block, 0, w.blas()?.stream(), a) + } pub(super) fn run( &mut self, w: &mut NativeBatchWorkspace<'ctx>, @@ -105,16 +113,7 @@ impl<'ctx> QsaPromptStage<'ctx> { w.validate_context(self.context)?; let g = self.context.enter()?; let dependency = self.context.driver.api.synchronize(); - let op = dependency.and_then(|()| { - self.module.as_ref().ok_or(Error::ContextPoisoned)?.launch( - index, - grid, - block, - 0, - w.blas()?.stream(), - &mut a, - ) - }); + let op = dependency.and_then(|()| self.launch_pass(w, (index, grid, block), &mut a)); let sync = w.blas()?.synchronize(); let pop = g.finish(); if sync.is_err() || pop.is_err() {