diff --git a/crates/cuda-driver/src/native_head/dispatch_fn.rs b/crates/cuda-driver/src/native_head/dispatch_fn.rs index 04a71759..cfef54df 100644 --- a/crates/cuda-driver/src/native_head/dispatch_fn.rs +++ b/crates/cuda-driver/src/native_head/dispatch_fn.rs @@ -14,308 +14,18 @@ pub(super) fn dispatch( return Err(Error::InvalidQwenShape); } if matches!(kind, 7 | 16 | 17 | 18 | 21 | 22 | 29) { - let columns = if t == 1 { - 1 - } else if t == 2 { - 2 - } else if t <= 4 { - 4 - } else { - 8 - }; - let name = match (kind, if p.old_iq || kind == 7 { 0 } else { columns }) { - (7, 0) => "head_i7_old", - (16, 0) => "head_i16_old", - (16, 1) => "head_i16_c1", - (16, 2) => "head_i16_c2", - (16, 4) => "head_i16_c4", - (16, 8) => "head_i16_c8", - (17, 0) => "head_i17_old", - (17, 1) => "head_i17_c1", - (17, 2) => "head_i17_c2", - (17, 4) => "head_i17_c4", - (17, 8) => "head_i17_c8", - (18, 0) => "head_i18_old", - (18, 1) => "head_i18_c1", - (18, 2) => "head_i18_c2", - (18, 4) => "head_i18_c4", - (18, 8) => "head_i18_c8", - (21, 0) => "head_i21_old", - (21, 1) => "head_i21_c1", - (21, 2) => "head_i21_c2", - (21, 4) => "head_i21_c4", - (21, 8) => "head_i21_c8", - (22, 0) => "head_i22_old", - (22, 1) => "head_i22_c1", - (22, 2) => "head_i22_c2", - (22, 4) => "head_i22_c4", - (22, 8) => "head_i22_c8", - (29, 0) => "head_i29_old", - (29, 1) => "head_i29_c1", - (29, 2) => "head_i29_c2", - (29, 4) => "head_i29_c4", - (29, 8) => "head_i29_c8", - _ => return Err(Error::UnsupportedQwenOperation), - }; + let name = iq_kernel_name(kind, iq_columns(kind, t, p))?; return Ok((name, [v.div_ceil(4) as u32, 1, 1], [32, 4, 1], true)); } - let (div, bpi) = match kind { - 2 => (32, 64), - 6 => (32, 64), - 8 => (32, 32), - 20 => (32, 64), - 11 => (256, 8), - 12 => (256, 8), - 13 => (256, 8), - 14 => (256, 4), - 23 => (256, 16), - 42 => (64, 64), - _ => return Err(Error::UnsupportedQwenOperation), - }; + let (div, bpi) = kind_geometry(kind)?; let small = n / div < bpi; let upstream = t > 1 && !p.multi_exact; - let mode = if t == 1 { - if small { 0 } else { 1 } - } else if upstream { - 2 - } else if small { - 3 - } else { - 4 - }; - let name = match (kind, t, mode) { - (2, 1, 0) => "head_n2_s1", - (2, 1, 1) => "head_n2_s0", - (2, 2, 2) => "head_n2_t2_upstream", - (2, 2, 3) => "head_n2_t2_small", - (2, 2, 4) => "head_n2_t2_large", - (2, 3, 2) => "head_n2_t3_upstream", - (2, 3, 3) => "head_n2_t3_small", - (2, 3, 4) => "head_n2_t3_large", - (2, 4, 2) => "head_n2_t4_upstream", - (2, 4, 3) => "head_n2_t4_small", - (2, 4, 4) => "head_n2_t4_large", - (2, 5, 2) => "head_n2_t5_upstream", - (2, 5, 3) => "head_n2_t5_small", - (2, 5, 4) => "head_n2_t5_large", - (2, 6, 2) => "head_n2_t6_upstream", - (2, 6, 3) => "head_n2_t6_small", - (2, 6, 4) => "head_n2_t6_large", - (2, 7, 2) => "head_n2_t7_upstream", - (2, 7, 3) => "head_n2_t7_small", - (2, 7, 4) => "head_n2_t7_large", - (2, 8, 2) => "head_n2_t8_upstream", - (2, 8, 3) => "head_n2_t8_small", - (2, 8, 4) => "head_n2_t8_large", - (6, 1, 0) => "head_n6_s1", - (6, 1, 1) => "head_n6_s0", - (6, 2, 2) => "head_n6_t2_upstream", - (6, 2, 3) => "head_n6_t2_small", - (6, 2, 4) => "head_n6_t2_large", - (6, 3, 2) => "head_n6_t3_upstream", - (6, 3, 3) => "head_n6_t3_small", - (6, 3, 4) => "head_n6_t3_large", - (6, 4, 2) => "head_n6_t4_upstream", - (6, 4, 3) => "head_n6_t4_small", - (6, 4, 4) => "head_n6_t4_large", - (6, 5, 2) => "head_n6_t5_upstream", - (6, 5, 3) => "head_n6_t5_small", - (6, 5, 4) => "head_n6_t5_large", - (6, 6, 2) => "head_n6_t6_upstream", - (6, 6, 3) => "head_n6_t6_small", - (6, 6, 4) => "head_n6_t6_large", - (6, 7, 2) => "head_n6_t7_upstream", - (6, 7, 3) => "head_n6_t7_small", - (6, 7, 4) => "head_n6_t7_large", - (6, 8, 2) => "head_n6_t8_upstream", - (6, 8, 3) => "head_n6_t8_small", - (6, 8, 4) => "head_n6_t8_large", - (8, 1, 0) => "head_n8_s1", - (8, 1, 1) => "head_n8_s0", - (8, 2, 2) => "head_n8_t2_upstream", - (8, 2, 3) => "head_n8_t2_small", - (8, 2, 4) => "head_n8_t2_large", - (8, 3, 2) => "head_n8_t3_upstream", - (8, 3, 3) => "head_n8_t3_small", - (8, 3, 4) => "head_n8_t3_large", - (8, 4, 2) => "head_n8_t4_upstream", - (8, 4, 3) => "head_n8_t4_small", - (8, 4, 4) => "head_n8_t4_large", - (8, 5, 2) => "head_n8_t5_upstream", - (8, 5, 3) => "head_n8_t5_small", - (8, 5, 4) => "head_n8_t5_large", - (8, 6, 2) => "head_n8_t6_upstream", - (8, 6, 3) => "head_n8_t6_small", - (8, 6, 4) => "head_n8_t6_large", - (8, 7, 2) => "head_n8_t7_upstream", - (8, 7, 3) => "head_n8_t7_small", - (8, 7, 4) => "head_n8_t7_large", - (8, 8, 2) => "head_n8_t8_upstream", - (8, 8, 3) => "head_n8_t8_small", - (8, 8, 4) => "head_n8_t8_large", - (20, 1, 0) => "head_n20_s1", - (20, 1, 1) => "head_n20_s0", - (20, 2, 2) => "head_n20_t2_upstream", - (20, 2, 3) => "head_n20_t2_small", - (20, 2, 4) => "head_n20_t2_large", - (20, 3, 2) => "head_n20_t3_upstream", - (20, 3, 3) => "head_n20_t3_small", - (20, 3, 4) => "head_n20_t3_large", - (20, 4, 2) => "head_n20_t4_upstream", - (20, 4, 3) => "head_n20_t4_small", - (20, 4, 4) => "head_n20_t4_large", - (20, 5, 2) => "head_n20_t5_upstream", - (20, 5, 3) => "head_n20_t5_small", - (20, 5, 4) => "head_n20_t5_large", - (20, 6, 2) => "head_n20_t6_upstream", - (20, 6, 3) => "head_n20_t6_small", - (20, 6, 4) => "head_n20_t6_large", - (20, 7, 2) => "head_n20_t7_upstream", - (20, 7, 3) => "head_n20_t7_small", - (20, 7, 4) => "head_n20_t7_large", - (20, 8, 2) => "head_n20_t8_upstream", - (20, 8, 3) => "head_n20_t8_small", - (20, 8, 4) => "head_n20_t8_large", - (11, 1, 0) => "head_n11_s1", - (11, 1, 1) => "head_n11_s0", - (11, 2, 2) => "head_n11_t2_upstream", - (11, 2, 3) => "head_n11_t2_small", - (11, 2, 4) => "head_n11_t2_large", - (11, 3, 2) => "head_n11_t3_upstream", - (11, 3, 3) => "head_n11_t3_small", - (11, 3, 4) => "head_n11_t3_large", - (11, 4, 2) => "head_n11_t4_upstream", - (11, 4, 3) => "head_n11_t4_small", - (11, 4, 4) => "head_n11_t4_large", - (11, 5, 2) => "head_n11_t5_upstream", - (11, 5, 3) => "head_n11_t5_small", - (11, 5, 4) => "head_n11_t5_large", - (11, 6, 2) => "head_n11_t6_upstream", - (11, 6, 3) => "head_n11_t6_small", - (11, 6, 4) => "head_n11_t6_large", - (11, 7, 2) => "head_n11_t7_upstream", - (11, 7, 3) => "head_n11_t7_small", - (11, 7, 4) => "head_n11_t7_large", - (11, 8, 2) => "head_n11_t8_upstream", - (11, 8, 3) => "head_n11_t8_small", - (11, 8, 4) => "head_n11_t8_large", - (12, 1, 0) => "head_n12_s1", - (12, 1, 1) => "head_n12_s0", - (12, 2, 2) => "head_n12_t2_upstream", - (12, 2, 3) => "head_n12_t2_small", - (12, 2, 4) => "head_n12_t2_large", - (12, 3, 2) => "head_n12_t3_upstream", - (12, 3, 3) => "head_n12_t3_small", - (12, 3, 4) => "head_n12_t3_large", - (12, 4, 2) => "head_n12_t4_upstream", - (12, 4, 3) => "head_n12_t4_small", - (12, 4, 4) => "head_n12_t4_large", - (12, 5, 2) => "head_n12_t5_upstream", - (12, 5, 3) => "head_n12_t5_small", - (12, 5, 4) => "head_n12_t5_large", - (12, 6, 2) => "head_n12_t6_upstream", - (12, 6, 3) => "head_n12_t6_small", - (12, 6, 4) => "head_n12_t6_large", - (12, 7, 2) => "head_n12_t7_upstream", - (12, 7, 3) => "head_n12_t7_small", - (12, 7, 4) => "head_n12_t7_large", - (12, 8, 2) => "head_n12_t8_upstream", - (12, 8, 3) => "head_n12_t8_small", - (12, 8, 4) => "head_n12_t8_large", - (13, 1, 0) => "head_n13_s1", - (13, 1, 1) => "head_n13_s0", - (13, 2, 2) => "head_n13_t2_upstream", - (13, 2, 3) => "head_n13_t2_small", - (13, 2, 4) => "head_n13_t2_large", - (13, 3, 2) => "head_n13_t3_upstream", - (13, 3, 3) => "head_n13_t3_small", - (13, 3, 4) => "head_n13_t3_large", - (13, 4, 2) => "head_n13_t4_upstream", - (13, 4, 3) => "head_n13_t4_small", - (13, 4, 4) => "head_n13_t4_large", - (13, 5, 2) => "head_n13_t5_upstream", - (13, 5, 3) => "head_n13_t5_small", - (13, 5, 4) => "head_n13_t5_large", - (13, 6, 2) => "head_n13_t6_upstream", - (13, 6, 3) => "head_n13_t6_small", - (13, 6, 4) => "head_n13_t6_large", - (13, 7, 2) => "head_n13_t7_upstream", - (13, 7, 3) => "head_n13_t7_small", - (13, 7, 4) => "head_n13_t7_large", - (13, 8, 2) => "head_n13_t8_upstream", - (13, 8, 3) => "head_n13_t8_small", - (13, 8, 4) => "head_n13_t8_large", - (14, 1, 0) => "head_n14_s1", - (14, 1, 1) => "head_n14_s0", - (14, 2, 2) => "head_n14_t2_upstream", - (14, 2, 3) => "head_n14_t2_small", - (14, 2, 4) => "head_n14_t2_large", - (14, 3, 2) => "head_n14_t3_upstream", - (14, 3, 3) => "head_n14_t3_small", - (14, 3, 4) => "head_n14_t3_large", - (14, 4, 2) => "head_n14_t4_upstream", - (14, 4, 3) => "head_n14_t4_small", - (14, 4, 4) => "head_n14_t4_large", - (14, 5, 2) => "head_n14_t5_upstream", - (14, 5, 3) => "head_n14_t5_small", - (14, 5, 4) => "head_n14_t5_large", - (14, 6, 2) => "head_n14_t6_upstream", - (14, 6, 3) => "head_n14_t6_small", - (14, 6, 4) => "head_n14_t6_large", - (14, 7, 2) => "head_n14_t7_upstream", - (14, 7, 3) => "head_n14_t7_small", - (14, 7, 4) => "head_n14_t7_large", - (14, 8, 2) => "head_n14_t8_upstream", - (14, 8, 3) => "head_n14_t8_small", - (14, 8, 4) => "head_n14_t8_large", - (23, 1, 0) => "head_n23_s1", - (23, 1, 1) => "head_n23_s0", - (23, 2, 2) => "head_n23_t2_upstream", - (23, 2, 3) => "head_n23_t2_small", - (23, 2, 4) => "head_n23_t2_large", - (23, 3, 2) => "head_n23_t3_upstream", - (23, 3, 3) => "head_n23_t3_small", - (23, 3, 4) => "head_n23_t3_large", - (23, 4, 2) => "head_n23_t4_upstream", - (23, 4, 3) => "head_n23_t4_small", - (23, 4, 4) => "head_n23_t4_large", - (23, 5, 2) => "head_n23_t5_upstream", - (23, 5, 3) => "head_n23_t5_small", - (23, 5, 4) => "head_n23_t5_large", - (23, 6, 2) => "head_n23_t6_upstream", - (23, 6, 3) => "head_n23_t6_small", - (23, 6, 4) => "head_n23_t6_large", - (23, 7, 2) => "head_n23_t7_upstream", - (23, 7, 3) => "head_n23_t7_small", - (23, 7, 4) => "head_n23_t7_large", - (23, 8, 2) => "head_n23_t8_upstream", - (23, 8, 3) => "head_n23_t8_small", - (23, 8, 4) => "head_n23_t8_large", - (42, 1, 0) => "head_n42_s1", - (42, 1, 1) => "head_n42_s0", - (42, 2, 2) => "head_n42_t2_upstream", - (42, 2, 3) => "head_n42_t2_small", - (42, 2, 4) => "head_n42_t2_large", - (42, 3, 2) => "head_n42_t3_upstream", - (42, 3, 3) => "head_n42_t3_small", - (42, 3, 4) => "head_n42_t3_large", - (42, 4, 2) => "head_n42_t4_upstream", - (42, 4, 3) => "head_n42_t4_small", - (42, 4, 4) => "head_n42_t4_large", - (42, 5, 2) => "head_n42_t5_upstream", - (42, 5, 3) => "head_n42_t5_small", - (42, 5, 4) => "head_n42_t5_large", - (42, 6, 2) => "head_n42_t6_upstream", - (42, 6, 3) => "head_n42_t6_small", - (42, 6, 4) => "head_n42_t6_large", - (42, 7, 2) => "head_n42_t7_upstream", - (42, 7, 3) => "head_n42_t7_small", - (42, 7, 4) => "head_n42_t7_large", - (42, 8, 2) => "head_n42_t8_upstream", - (42, 8, 3) => "head_n42_t8_small", - (42, 8, 4) => "head_n42_t8_large", - _ => return Err(Error::UnsupportedQwenOperation), - }; + let name = head_kernel_name(kind, t, head_mode(t, small, upstream))?; + let (grid, block) = head_launch_shape(v, t, small, upstream); + Ok((name, grid, block, false)) +} + +fn head_launch_shape(v: usize, t: usize, small: bool, upstream: bool) -> ([u32; 3], [u32; 3]) { let rows = if upstream { 2 } else if small { @@ -324,5 +34,367 @@ pub(super) fn dispatch( 1 }; let nw = if upstream && t > 4 { 2 } else { 4 }; - Ok((name, [v.div_ceil(rows) as u32, 1, 1], [32, nw, 1], false)) + ([v.div_ceil(rows) as u32, 1, 1], [32, nw, 1]) } + +/// Token-column count of the IQ head kernels (`0` selects the old kernel). +fn iq_columns(kind: u32, t: usize, p: NativeHeadDispatch) -> usize { + let columns = if t == 1 { + 1 + } else if t == 2 { + 2 + } else if t <= 4 { + 4 + } else { + 8 + }; + if p.old_iq || kind == 7 { 0 } else { columns } +} + +/// Rows divisor and blocks-per-item threshold of the plain head kernels by kind. +fn kind_geometry(kind: u32) -> Result<(usize, usize)> { + const GEOMETRY: [(u32, usize, usize); 10] = [ + (2, 32, 64), + (6, 32, 64), + (8, 32, 32), + (20, 32, 64), + (11, 256, 8), + (12, 256, 8), + (13, 256, 8), + (14, 256, 4), + (23, 256, 16), + (42, 64, 64), + ]; + let row = GEOMETRY.iter().find(|(k, _, _)| *k == kind); + row.map(|(_, div, bpi)| (*div, *bpi)).ok_or(Error::UnsupportedQwenOperation) +} + +fn head_mode(t: usize, small: bool, upstream: bool) -> u32 { + if t == 1 { + if small { 0 } else { 1 } + } else if upstream { + 2 + } else if small { + 3 + } else { + 4 + } +} + +/// IQ kernel by kind and column count `0, 1, 2, 4, 8` (kind 7 has only the old kernel). +fn iq_kernel_name(kind: u32, columns: usize) -> Result<&'static str> { + let slot = match columns { + 0 => 0, + 1 => 1, + 2 => 2, + 4 => 3, + 8 => 4, + _ => return Err(Error::UnsupportedQwenOperation), + }; + let names = IQ_NAMES.iter().find(|(k, _)| *k == kind).map(|(_, names)| *names); + names.and_then(|names| names.get(slot)).copied().ok_or(Error::UnsupportedQwenOperation) +} + +/// Head kernel by kind, token count and mode: slot `mode` for one token, else `2 + 3 * (t - 2) + (mode - 2)`. +fn head_kernel_name(kind: u32, t: usize, mode: u32) -> Result<&'static str> { + let slot = match (t, mode) { + (1, 0..=1) => mode as usize, + (2..=8, 2..=4) => 2 + 3 * (t - 2) + (mode as usize - 2), + _ => return Err(Error::UnsupportedQwenOperation), + }; + let names = HEAD_NAMES.iter().find(|(k, _)| *k == kind).map(|(_, names)| names); + names.map(|names| names[slot]).ok_or(Error::UnsupportedQwenOperation) +} + +static IQ_NAMES: [(u32, &[&str]); 7] = [ + (7, &["head_i7_old"]), + (16, &["head_i16_old", "head_i16_c1", "head_i16_c2", "head_i16_c4", "head_i16_c8"]), + (17, &["head_i17_old", "head_i17_c1", "head_i17_c2", "head_i17_c4", "head_i17_c8"]), + (18, &["head_i18_old", "head_i18_c1", "head_i18_c2", "head_i18_c4", "head_i18_c8"]), + (21, &["head_i21_old", "head_i21_c1", "head_i21_c2", "head_i21_c4", "head_i21_c8"]), + (22, &["head_i22_old", "head_i22_c1", "head_i22_c2", "head_i22_c4", "head_i22_c8"]), + (29, &["head_i29_old", "head_i29_c1", "head_i29_c2", "head_i29_c4", "head_i29_c8"]), +]; + +static HEAD_NAMES: [(u32, [&str; 23]); 10] = [ + ( + 2, + [ + "head_n2_s1", + "head_n2_s0", + "head_n2_t2_upstream", + "head_n2_t2_small", + "head_n2_t2_large", + "head_n2_t3_upstream", + "head_n2_t3_small", + "head_n2_t3_large", + "head_n2_t4_upstream", + "head_n2_t4_small", + "head_n2_t4_large", + "head_n2_t5_upstream", + "head_n2_t5_small", + "head_n2_t5_large", + "head_n2_t6_upstream", + "head_n2_t6_small", + "head_n2_t6_large", + "head_n2_t7_upstream", + "head_n2_t7_small", + "head_n2_t7_large", + "head_n2_t8_upstream", + "head_n2_t8_small", + "head_n2_t8_large", + ], + ), + ( + 6, + [ + "head_n6_s1", + "head_n6_s0", + "head_n6_t2_upstream", + "head_n6_t2_small", + "head_n6_t2_large", + "head_n6_t3_upstream", + "head_n6_t3_small", + "head_n6_t3_large", + "head_n6_t4_upstream", + "head_n6_t4_small", + "head_n6_t4_large", + "head_n6_t5_upstream", + "head_n6_t5_small", + "head_n6_t5_large", + "head_n6_t6_upstream", + "head_n6_t6_small", + "head_n6_t6_large", + "head_n6_t7_upstream", + "head_n6_t7_small", + "head_n6_t7_large", + "head_n6_t8_upstream", + "head_n6_t8_small", + "head_n6_t8_large", + ], + ), + ( + 8, + [ + "head_n8_s1", + "head_n8_s0", + "head_n8_t2_upstream", + "head_n8_t2_small", + "head_n8_t2_large", + "head_n8_t3_upstream", + "head_n8_t3_small", + "head_n8_t3_large", + "head_n8_t4_upstream", + "head_n8_t4_small", + "head_n8_t4_large", + "head_n8_t5_upstream", + "head_n8_t5_small", + "head_n8_t5_large", + "head_n8_t6_upstream", + "head_n8_t6_small", + "head_n8_t6_large", + "head_n8_t7_upstream", + "head_n8_t7_small", + "head_n8_t7_large", + "head_n8_t8_upstream", + "head_n8_t8_small", + "head_n8_t8_large", + ], + ), + ( + 20, + [ + "head_n20_s1", + "head_n20_s0", + "head_n20_t2_upstream", + "head_n20_t2_small", + "head_n20_t2_large", + "head_n20_t3_upstream", + "head_n20_t3_small", + "head_n20_t3_large", + "head_n20_t4_upstream", + "head_n20_t4_small", + "head_n20_t4_large", + "head_n20_t5_upstream", + "head_n20_t5_small", + "head_n20_t5_large", + "head_n20_t6_upstream", + "head_n20_t6_small", + "head_n20_t6_large", + "head_n20_t7_upstream", + "head_n20_t7_small", + "head_n20_t7_large", + "head_n20_t8_upstream", + "head_n20_t8_small", + "head_n20_t8_large", + ], + ), + ( + 11, + [ + "head_n11_s1", + "head_n11_s0", + "head_n11_t2_upstream", + "head_n11_t2_small", + "head_n11_t2_large", + "head_n11_t3_upstream", + "head_n11_t3_small", + "head_n11_t3_large", + "head_n11_t4_upstream", + "head_n11_t4_small", + "head_n11_t4_large", + "head_n11_t5_upstream", + "head_n11_t5_small", + "head_n11_t5_large", + "head_n11_t6_upstream", + "head_n11_t6_small", + "head_n11_t6_large", + "head_n11_t7_upstream", + "head_n11_t7_small", + "head_n11_t7_large", + "head_n11_t8_upstream", + "head_n11_t8_small", + "head_n11_t8_large", + ], + ), + ( + 12, + [ + "head_n12_s1", + "head_n12_s0", + "head_n12_t2_upstream", + "head_n12_t2_small", + "head_n12_t2_large", + "head_n12_t3_upstream", + "head_n12_t3_small", + "head_n12_t3_large", + "head_n12_t4_upstream", + "head_n12_t4_small", + "head_n12_t4_large", + "head_n12_t5_upstream", + "head_n12_t5_small", + "head_n12_t5_large", + "head_n12_t6_upstream", + "head_n12_t6_small", + "head_n12_t6_large", + "head_n12_t7_upstream", + "head_n12_t7_small", + "head_n12_t7_large", + "head_n12_t8_upstream", + "head_n12_t8_small", + "head_n12_t8_large", + ], + ), + ( + 13, + [ + "head_n13_s1", + "head_n13_s0", + "head_n13_t2_upstream", + "head_n13_t2_small", + "head_n13_t2_large", + "head_n13_t3_upstream", + "head_n13_t3_small", + "head_n13_t3_large", + "head_n13_t4_upstream", + "head_n13_t4_small", + "head_n13_t4_large", + "head_n13_t5_upstream", + "head_n13_t5_small", + "head_n13_t5_large", + "head_n13_t6_upstream", + "head_n13_t6_small", + "head_n13_t6_large", + "head_n13_t7_upstream", + "head_n13_t7_small", + "head_n13_t7_large", + "head_n13_t8_upstream", + "head_n13_t8_small", + "head_n13_t8_large", + ], + ), + ( + 14, + [ + "head_n14_s1", + "head_n14_s0", + "head_n14_t2_upstream", + "head_n14_t2_small", + "head_n14_t2_large", + "head_n14_t3_upstream", + "head_n14_t3_small", + "head_n14_t3_large", + "head_n14_t4_upstream", + "head_n14_t4_small", + "head_n14_t4_large", + "head_n14_t5_upstream", + "head_n14_t5_small", + "head_n14_t5_large", + "head_n14_t6_upstream", + "head_n14_t6_small", + "head_n14_t6_large", + "head_n14_t7_upstream", + "head_n14_t7_small", + "head_n14_t7_large", + "head_n14_t8_upstream", + "head_n14_t8_small", + "head_n14_t8_large", + ], + ), + ( + 23, + [ + "head_n23_s1", + "head_n23_s0", + "head_n23_t2_upstream", + "head_n23_t2_small", + "head_n23_t2_large", + "head_n23_t3_upstream", + "head_n23_t3_small", + "head_n23_t3_large", + "head_n23_t4_upstream", + "head_n23_t4_small", + "head_n23_t4_large", + "head_n23_t5_upstream", + "head_n23_t5_small", + "head_n23_t5_large", + "head_n23_t6_upstream", + "head_n23_t6_small", + "head_n23_t6_large", + "head_n23_t7_upstream", + "head_n23_t7_small", + "head_n23_t7_large", + "head_n23_t8_upstream", + "head_n23_t8_small", + "head_n23_t8_large", + ], + ), + ( + 42, + [ + "head_n42_s1", + "head_n42_s0", + "head_n42_t2_upstream", + "head_n42_t2_small", + "head_n42_t2_large", + "head_n42_t3_upstream", + "head_n42_t3_small", + "head_n42_t3_large", + "head_n42_t4_upstream", + "head_n42_t4_small", + "head_n42_t4_large", + "head_n42_t5_upstream", + "head_n42_t5_small", + "head_n42_t5_large", + "head_n42_t6_upstream", + "head_n42_t6_small", + "head_n42_t6_large", + "head_n42_t7_upstream", + "head_n42_t7_small", + "head_n42_t7_large", + "head_n42_t8_upstream", + "head_n42_t8_small", + "head_n42_t8_large", + ], + ), +]; diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs index 537f45e7..946f9864 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +mod gr_read_phases; mod impl_originalpromptdevice_2; mod impl_originalpromptdevice_2_2; mod impl_originalpromptdevice_3; diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs new file mode 100644 index 00000000..cb65cdc9 --- /dev/null +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/gr_read_phases.rs @@ -0,0 +1,136 @@ +//! STRA-338 size: the phases of `OriginalPromptDevice::read_gr_impl`, extracted in command order. + +#[allow(unused_imports)] +use super::*; + +/// Spans, weights and scalars every command of one GR read shares. +pub(super) struct GrReadPlan { + h: [BufferHandle; 15], + w: [BufferHandle; 4], + flags: BufferHandle, + t: usize, + low_half: bool, +} + +impl GrReadPlan { + pub(super) fn new( + h: [BufferHandle; 15], + w: [BufferHandle; 4], + flags: BufferHandle, + t: usize, + low_half: bool, + ) -> Self { + Self { h, w, flags, t, low_half } + } + + fn low(&self, i: usize) -> A { + if self.low_half { A::Address(self.h[i]) } else { A::NullAddress } + } + + fn gemm(&self, v: &mut Vec, (input, lo): (usize, usize), weight: BufferHandle, out: usize, (n, k): (i32, i32)) { + let (h, t) = (&self.h, self.t as i32); + v.push(C::Gemm { input: h[input], weight, output: h[out], t, n, k, alpha: 1., beta: 0. }); + if self.low_half { + v.push(C::Gemm { input: h[lo], weight, output: h[out], t, n, k, alpha: 1., beta: 1. }) + } + } + + /// RMS-norm of R into the row scales and the high/low X; the scan rides on it when fused. + pub(super) fn push_norm(&self, v: &mut Vec, epsilon: f32, normed: bool, fused: bool) { + if fused { + self.push_norm_fused(v, epsilon, normed); + } else { + self.push_norm_scanned(v, epsilon, normed); + } + } + + fn push_norm_fused(&self, v: &mut Vec, epsilon: f32, normed: bool) { + let (h, w) = (&self.h, &self.w); + // the norm guard rides on the norm kernel; a normed read follows `inject_gr_fused`, which already guarded + // this very norm (same R, rs and gamma), so nothing is left to scan + if !normed { + let args = vec![ + A::Address(h[0]), + A::Address(w[0]), + A::F32(epsilon), + A::Address(h[1]), + A::Address(h[2]), + self.low(3), + A::Address(self.flags), + ]; + kernel(v, 3, 3, self.t * 4, 256, args); + } + } + + fn push_norm_scanned(&self, v: &mut Vec, epsilon: f32, normed: bool) { + let (h, w, t) = (&self.h, &self.w, self.t); + if !normed { + let args = vec![ + A::Address(h[0]), + A::Address(w[0]), + A::F32(epsilon), + A::Address(h[1]), + A::Address(h[2]), + self.low(3), + ]; + kernel(v, 2, 0, t * 4, 256, args); + } + let scan = vec![A::Address(h[0]), A::Address(h[1]), A::Address(w[0]), A::Address(self.flags), A::I64(t as i64)]; + kernel(v, 2, 5, (t * 10240).div_ceil(256), 256, scan); + } + + /// Down projection, SiLU, up projection and the injection GEMM, each followed by its guard. + pub(super) fn push_projections(&self, v: &mut Vec, fused: bool) { + let (h, w, t, flags) = (&self.h, &self.w, self.t, self.flags); + self.gemm(v, (2, 3), w[1], 4, (320, 10240)); + scan_gr(v, h[4], flags, 320, t, 1); + let silu = vec![A::Address(h[4]), A::Address(h[5]), self.low(6), A::I64((t * 320) as i64)]; + kernel(v, 2, 1, (t * 320).div_ceil(256), 256, silu); + kernel(v, 2, 6, (t * 320).div_ceil(256), 256, vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)]); + self.gemm(v, (5, 6), w[2], 7, (10240, 320)); + if !fused { + scan_gr(v, h[7], flags, 10240, t, 3); + } + // Original injection GEMM precedes mixed production. + self.gemm(v, (2, 3), w[3], 12, (4, 10240)); + scan_gr(v, h[12], flags, 4, t, 6); + } + + /// Mixed production; fused folds the gated, product and mixed-row guards into the mix kernel. + pub(super) fn push_mix(&self, v: &mut Vec, fused: bool) { + let (h, t, flags) = (&self.h, self.t, self.flags); + let mut mix = vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(self.w[0]), + A::Address(h[7]), + A::Address(h[8]), + A::Address(h[9]), + A::I64(t as i64), + A::Address(h[11]), + self.low(10), + ]; + if fused { + // mix + the guards of the gated tensor (3), the products (4) and the mixed row (5) + mix.push(A::Address(flags)); + kernel(v, 3, 4, (t * 2560).div_ceil(256), 256, mix); + } else { + kernel(v, 2, 2, (t * 2560).div_ceil(256), 256, mix); + self.push_mix_guards(v); + } + } + + fn push_mix_guards(&self, v: &mut Vec) { + let (h, w, t, flags) = (&self.h, &self.w, self.t, self.flags); + let guard = vec![ + A::Address(h[0]), + A::Address(h[1]), + A::Address(w[0]), + A::Address(h[7]), + A::Address(flags), + A::I64(t as i64), + ]; + kernel(v, 2, 7, (t * 10240).div_ceil(256), 256, guard); + scan_gr(v, h[8], flags, 2560, t, 5); + } +} diff --git a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs index af1d73df..86198bec 100644 --- a/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs +++ b/crates/cuda-driver/src/native_prompt_device/impl_originalpromptdevice/impl_originalpromptdevice_5.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalPromptDevice (5). #[allow(unused_imports)] +use super::gr_read_phases::GrReadPlan; use super::*; impl<'ctx> OriginalPromptDevice<'ctx> { @@ -19,6 +20,41 @@ impl<'ctx> OriginalPromptDevice<'ctx> { return Err(Error::InvalidQwenShape); } let t = lease.rows(); + let h = self.gr_read_spans(lease)?; + let mut w = [h[0]; 4]; + for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { + w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; + } + let low_half = self.profile == GrNativeProfile::HighAndLow; + let plan = GrReadPlan::new(h, w, self.status()?, t, low_half); + let mut v = Vec::new(); + v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; + let fused = fused_scans(); + plan.push_norm(&mut v, epsilon, normed, fused); + plan.push_projections(&mut v, fused); + plan.push_mix(&mut v, fused); + self.run( + lease, + workspace, + v, + t, + 8, + &[0, 1, 2, 3, 6, 4, 5], + &[ + "GR native norm", + "GR native down", + "GR native silu", + "GR native up", + "GR native products", + "GR native mixed", + "GR native inject", + "GR native candidate", + ], + )?; + Ok(OriginalDeviceGrRead { lease: residual.lease }) + } + /// The device spans a GR read touches; the low-half ones only when the profile keeps a low half. + fn gr_read_spans(&self, lease: &OriginalPromptRows<'_, '_, 'ctx>) -> Result<[BufferHandle; 15]> { let mut h = [self.status()?; 15]; for (i, r, n) in [ (0, S::R, 40960), @@ -40,164 +76,6 @@ impl<'ctx> OriginalPromptDevice<'ctx> { h[i] = Self::span(lease, r, n)?; } } - let mut w = [h[0]; 4]; - for (i, n) in [40960, 6553600, 6553600, 81920].into_iter().enumerate() { - w[i] = self.weight(lease, workspace, weights[i], n, if i == 0 { 4 } else { 2 })?; - } - let low = |i| { - if self.profile == GrNativeProfile::HighAndLow { A::Address(h[i]) } else { A::NullAddress } - }; - let flags = self.status()?; - let mut v = Vec::new(); - v.try_reserve_exact(20).map_err(|_| Error::HostAllocation)?; - let fused = fused_scans(); - if fused { - // the norm guard rides on the norm kernel; a normed read follows `inject_gr_fused`, which already guarded - // this very norm (same R, rs and gamma), so nothing is left to scan - if !normed { - kernel( - &mut v, - 3, - 3, - t * 4, - 256, - vec![ - A::Address(h[0]), - A::Address(w[0]), - A::F32(epsilon), - A::Address(h[1]), - A::Address(h[2]), - low(3), - A::Address(flags), - ], - ); - } - } else { - if !normed { - kernel( - &mut v, - 2, - 0, - t * 4, - 256, - vec![ - A::Address(h[0]), - A::Address(w[0]), - A::F32(epsilon), - A::Address(h[1]), - A::Address(h[2]), - low(3), - ], - ); - } - kernel( - &mut v, - 2, - 5, - (t * 10240).div_ceil(256), - 256, - vec![A::Address(h[0]), A::Address(h[1]), A::Address(w[0]), A::Address(flags), A::I64(t as i64)], - ); - } - let gemm = |v: &mut Vec, input, lo, weight, out, n, k| { - v.push(C::Gemm { input: h[input], weight, output: h[out], t: t as i32, n, k, alpha: 1., beta: 0. }); - if self.profile == GrNativeProfile::HighAndLow { - v.push(C::Gemm { input: h[lo], weight, output: h[out], t: t as i32, n, k, alpha: 1., beta: 1. }) - } - }; - gemm(&mut v, 2, 3, w[1], 4, 320, 10240); - scan_gr(&mut v, h[4], flags, 320, t, 1); - kernel( - &mut v, - 2, - 1, - (t * 320).div_ceil(256), - 256, - vec![A::Address(h[4]), A::Address(h[5]), low(6), A::I64((t * 320) as i64)], - ); - kernel(&mut v, 2, 6, (t * 320).div_ceil(256), 256, vec![A::Address(h[4]), A::Address(flags), A::I64(t as i64)]); - gemm(&mut v, 5, 6, w[2], 7, 10240, 320); - if !fused { - scan_gr(&mut v, h[7], flags, 10240, t, 3); - } - // Original injection GEMM precedes mixed production. - gemm(&mut v, 2, 3, w[3], 12, 4, 10240); - scan_gr(&mut v, h[12], flags, 4, t, 6); - if fused { - // mix + the guards of the gated tensor (3), the products (4) and the mixed row (5) - kernel( - &mut v, - 3, - 4, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(h[8]), - A::Address(h[9]), - A::I64(t as i64), - A::Address(h[11]), - low(10), - A::Address(flags), - ], - ); - } else { - kernel( - &mut v, - 2, - 2, - (t * 2560).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(h[8]), - A::Address(h[9]), - A::I64(t as i64), - A::Address(h[11]), - low(10), - ], - ); - kernel( - &mut v, - 2, - 7, - (t * 10240).div_ceil(256), - 256, - vec![ - A::Address(h[0]), - A::Address(h[1]), - A::Address(w[0]), - A::Address(h[7]), - A::Address(flags), - A::I64(t as i64), - ], - ); - scan_gr(&mut v, h[8], flags, 2560, t, 5); - } - self.run( - lease, - workspace, - v, - t, - 8, - &[0, 1, 2, 3, 6, 4, 5], - &[ - "GR native norm", - "GR native down", - "GR native silu", - "GR native up", - "GR native products", - "GR native mixed", - "GR native inject", - "GR native candidate", - ], - )?; - Ok(OriginalDeviceGrRead { lease: residual.lease }) + Ok(h) } } diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs index 2104a6b0..e692d235 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +mod build_phases; mod impl_originalfileexpertsource_2; mod impl_originalfileexpertsource_2_2; mod impl_originalfileexpertsource_3; diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs new file mode 100644 index 00000000..5801d276 --- /dev/null +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/build_phases.rs @@ -0,0 +1,362 @@ +//! STRA-338 size: the phases of `OriginalFileExpertSource::build_cache_complement`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +type Primary = Vec<(i32, i32, usize)>; + +/// Where every expert of the complement lands in the arena, and the limits it was planned against. +pub(super) struct Layout { + pub(super) offsets: Vec, + pub(super) bytes: usize, + pub(super) lend: Option, + pub(super) budget: u64, + pub(super) keep_from: usize, + pub(super) physical: usize, +} + +/// Marks the source failed and poisons the context (disjoint fields, so a live `api` borrow stays valid). +pub(super) fn poison_parts(failed: &mut bool, context: &Context<'_>) { + *failed = true; + context.poison(); + context.retain_driver(); +} + +/// Closes a half-built arena after its fill failed, returning the fill error combined with the cleanup result. +pub(super) fn discard_arena( + failed: &mut bool, + context: &Context<'_>, + api: &abi::Api, + mut arena: abi::Arena, + primary: Error, +) -> Result<()> { + let g = match context.enter() { + Ok(g) => g, + Err(e) => { + poison_parts(failed, context); + std::mem::forget(arena); + return combine::<()>(Err(primary), Err(e)); + } + }; + let cleanup = combine(api.close(&mut arena), g.finish()); + if cleanup.is_err() { + poison_parts(failed, context); + std::mem::forget(arena); + } + combine(Err(primary), cleanup) +} + +/// The first offset at or below `want` whose expert straddles `want`, else `want`. +fn straddling_cut(layer_bytes: &[usize; LAYERS], offsets: &[usize], want: usize) -> usize { + for (i, &off) in offsets.iter().enumerate() { + if off != NONE && off < want && off.checked_add(layer_bytes[i / EXPERTS]).is_some_and(|end| end > want) { + return off; + } + } + want +} + +/// One worker: claims layers until none are left or an earlier error was recorded. +fn fill_worker(per_layer: &[Vec], next: &AtomicUsize, first: &Mutex>) { + loop { + let l = next.fetch_add(1, Ordering::Relaxed); + if l >= LAYERS { + break; + } + if first.lock().is_ok_and(|e| e.is_some()) { + break; + } + for j in &per_layer[l] { + if let Err(e) = j.run() { + if let Ok(mut f) = first.lock() { + if f.is_none() { + *f = Some(e); + } + } + break; + } + } + } +} + +/// Six Original layer workers; one actor participates. No Context/Rc is sent. +fn run_fill_workers(per_layer: &[Vec], stack: usize) -> Result<()> { + let next = AtomicUsize::new(0); + let first = Mutex::new(None); + let work = || fill_worker(per_layer, &next, &first); + thread::scope(|s| { + let mut workers = Vec::new(); + workers.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; + for _ in 0..5 { + workers.push( + thread::Builder::new().stack_size(stack).spawn_scoped(s, work).map_err(|_| Error::HostAllocation)?, + ); + } + work(); + for w in workers { + if w.join().is_err() { + return Err(Error::HostAllocation); + } + } + Ok(()) + })?; + if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { + return Err(e); + } + Ok(()) +} + +impl<'ctx> OriginalFileExpertSource<'ctx> { + pub(super) fn build_preflight(&mut self, cache: &OriginalExpertCache<'ctx>) -> Result<()> { + self.live()?; + if self.ready { + return Err(Error::InvalidSize); + } + cache.validate_file_source_context(self.context)?; + if cache.fills() != cache.resident() as u64 { + return Err(Error::InvalidSize); + } + self.context.synchronize().inspect_err(|_| { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + }) + } + + /// The (layer, expert, slot) triples resident in the cache and the byte size of every slot. + pub(super) fn collect_primary(&self, cache: &OriginalExpertCache<'ctx>) -> Result<(Primary, Vec)> { + let mut primary = Vec::new(); + let mut slot_bytes = vec_filled(cache.slots(), 0usize)?; + for l in 0..LAYERS { + for e in 0..EXPERTS { + self.note_slot(cache, (l, e), &mut primary, &mut slot_bytes)?; + } + } + Ok((primary, slot_bytes)) + } + + fn note_slot( + &self, + cache: &OriginalExpertCache<'ctx>, + (l, e): (usize, usize), + primary: &mut Primary, + slot_bytes: &mut [usize], + ) -> Result<()> { + let s = cache.slot_of(l, e); + if s < 0 { + return Ok(()); + } + let s = s as usize; + if s >= cache.slots() { + return Err(Error::InvalidSize); + } + primary.try_reserve(1).map_err(|_| Error::HostAllocation)?; + primary.push((l as i32, e as i32, s)); + slot_bytes[s] = self.layer_bytes[l]; + Ok(()) + } + + pub(super) fn plan_layout( + &self, + cache: &OriginalExpertCache<'ctx>, + (primary, slot_bytes): (&Primary, &[usize]), + (additional, rank): (&[(i32, i32)], Option<&[(i32, i32)]>), + options: OriginalResidentOptions, + ) -> Result { + let (offsets, bytes) = self.plan(primary, additional)?; + let lend = options.lend_from_slot.filter(|s| *s < cache.slots() && additional.is_empty()); + let physical = available_memory()?; + let room = physical.saturating_sub(options.headroom_bytes); + let mut layout = + Layout { offsets, bytes, lend, budget: options.budget_bytes, keep_from: cache.slots(), physical }; + if layout.budget > 0 { + self.apply_budget(&mut layout, rank, options, room)?; + } + if layout.bytes > room { + return Err(Error::BudgetExceeded); + } + if let Some(first) = layout.lend { + self.lend_slots(&mut layout, (primary, slot_bytes), additional, (first, room, cache.slots()))?; + } + Ok(layout) + } + + /// Replaces the planned layout by the ranked subset that fits the byte budget. + fn apply_budget( + &self, + layout: &mut Layout, + rank: Option<&[(i32, i32)]>, + options: OriginalResidentOptions, + room: usize, + ) -> Result<()> { + if layout.budget > (room as u64) { + layout.budget = room.saturating_sub(256 << 20) as u64; + } + let mut ranked = vec_filled(N, NONE)?; + let mut at = 0usize; + let mut held = 0; + for &entry in rank.unwrap_or_default() { + if self.rank_one(entry, &layout.offsets, &mut ranked, &mut at, layout.budget)? { + held += 1; + } + } + if options.budget_bytes == u64::MAX && held == 0 { + return Err(Error::BudgetExceeded); + } + layout.offsets = ranked; + layout.bytes = at; + layout.lend = None; + Ok(()) + } + + /// Places one ranked expert at the next offset when it is planned, new and fits; reports whether it was kept. + fn rank_one( + &self, + (l, e): (i32, i32), + offsets: &[usize], + ranked: &mut [usize], + at: &mut usize, + budget: u64, + ) -> Result { + if l < 0 || e < 0 { + return Ok(false); + } + let Ok(i) = key(l as usize, e as usize) else { + return Ok(false); + }; + if offsets[i] == NONE || ranked[i] != NONE { + return Ok(false); + } + let b = self.layer_bytes[l as usize]; + if (b as u64) > budget.saturating_sub(*at as u64) { + return Ok(false); + } + ranked[i] = *at; + *at = at.checked_add(b).ok_or(Error::InvalidSize)?; + Ok(true) + } + + /// Lends the highest cache slots that still fit in `room`, re-planning without the lent slots' experts. + fn lend_slots( + &self, + layout: &mut Layout, + (primary, slot_bytes): (&Primary, &[usize]), + additional: &[(i32, i32)], + (first, room, slots): (usize, usize, usize), + ) -> Result<()> { + let mut b = layout.bytes; + let mut keep_from = slots; + while keep_from > first { + let n = slot_bytes[keep_from - 1]; + if n > room - b { + break; + } + b += n; + keep_from -= 1; + } + layout.keep_from = keep_from; + if keep_from < slots { + let mut core = Vec::new(); + core.try_reserve_exact(primary.len()).map_err(|_| Error::HostAllocation)?; + core.extend(primary.iter().copied().filter(|p| p.2 < keep_from)); + (layout.offsets, layout.bytes) = self.plan(&core, additional)?; + } + Ok(()) + } + + #[allow(clippy::ptr_arg)] + /// Checks the planned arena and its bookkeeping against the metadata, source and physical caps. + pub(super) fn check_host_budget( + &self, + layout: &Layout, + (primary, slot_bytes): (&Primary, &Vec), + headroom: usize, + ) -> Result { + let stack = abi::worker_stack_bytes()?; + let prospective_meta = self + .metadata_bytes()? + .checked_add( + layout.offsets.capacity() * size_of::() + + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() + + slot_bytes.capacity() * size_of::() + + N * (size_of::() + size_of::() + size_of::()) + + LAYERS * size_of::>() + + 5 * size_of::>(), + ) + .ok_or(Error::BudgetExceeded)?; + let bytes = layout.bytes; + if prospective_meta > META_CAP + || bytes.checked_add(prospective_meta).is_none_or(|n| n > SOURCE_CAP) + || bytes + .checked_add(5 * stack) + .and_then(|n| n.checked_add(prospective_meta)) + .and_then(|n| n.checked_add(headroom)) + .is_none_or(|n| n > layout.physical) + { + return Err(Error::BudgetExceeded); + } + Ok(stack) + } + + /// Pins the arena as asked, then copies every planned expert from the mapped source with worker threads. + pub(super) fn fill_arena( + &self, + api: &abi::Api, + arena: &mut abi::Arena, + layout: &Layout, + options: OriginalResidentOptions, + stack: usize, + ) -> Result<()> { + if options.pin && arena.pin_limit() == 0 { + if layout.budget > 0 && options.partial_pin { + self.pin_partial(api, arena, layout, options)?; + } + arena.lock_remainder(); + } + // Closed raw records derived only from retained mapped source and actual arena. + let per_layer = self.write_jobs(arena, &layout.offsets)?; + run_fill_workers(&per_layer, stack)?; + self.lease.validate_current().map_err(|_| Error::InvalidSize)?; + Ok(()) + } + + /// Registers the largest prefix of the arena, in 2 GiB steps down, that does not cut an expert in half. + fn pin_partial( + &self, + api: &abi::Api, + arena: &mut abi::Arena, + layout: &Layout, + options: OriginalResidentOptions, + ) -> Result<()> { + let step = 2 * GIB; + let mut want = layout.bytes.min(options.partial_pin_cap); + while want >= step { + let cut = straddling_cut(&self.layer_bytes, &layout.offsets, want); + if cut == 0 { + break; + } + if api.register_prefix(arena, cut)? { + break; + } + want = if want > step { want - step } else { 0 }; + } + Ok(()) + } + + fn write_jobs(&self, arena: &abi::Arena, offsets: &[usize]) -> Result>> { + let mut per_layer = Vec::new(); + per_layer.try_reserve_exact(LAYERS).map_err(|_| Error::HostAllocation)?; + for l in 0..LAYERS { + let mut jobs = Vec::new(); + jobs.try_reserve_exact(EXPERTS).map_err(|_| Error::HostAllocation)?; + for e in 0..EXPERTS { + let off = offsets[l * EXPERTS + e]; + if off != NONE { + jobs.push(arena.write(off, self.parts(l, e)?)?); + } + } + per_layer.push(jobs); + } + Ok(per_layer) + } +} diff --git a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs index b093b3e3..9e4eb783 100644 --- a/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs +++ b/crates/cuda-driver/src/original_file_expert_source/impl_originalfileexpertsource/impl_originalfileexpertsource_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalFileExpertSource (2). #[allow(unused_imports)] +use super::build_phases::{discard_arena, poison_parts}; use super::*; impl<'ctx> OriginalFileExpertSource<'ctx> { @@ -13,124 +14,17 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { additional: &[(i32, i32)], rank: Option<&[(i32, i32)]>, ) -> Result<()> { - self.live()?; - if self.ready { - return Err(Error::InvalidSize); - } - cache.validate_file_source_context(self.context)?; - if cache.fills() != cache.resident() as u64 { - return Err(Error::InvalidSize); - } - self.context.synchronize().inspect_err(|_| { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - })?; - let mut primary = Vec::new(); - let mut slot_bytes = vec_filled(cache.slots(), 0usize)?; - for l in 0..LAYERS { - for e in 0..EXPERTS { - let s = cache.slot_of(l, e); - if s >= 0 { - let s = s as usize; - if s >= cache.slots() { - return Err(Error::InvalidSize); - } - primary.try_reserve(1).map_err(|_| Error::HostAllocation)?; - primary.push((l as i32, e as i32, s)); - slot_bytes[s] = self.layer_bytes[l]; - } - } - } - let (mut offsets, mut bytes) = self.plan(&primary, additional)?; - let mut lend = options.lend_from_slot.filter(|s| *s < cache.slots() && additional.is_empty()); - let physical = available_memory()?; - let room = physical.saturating_sub(options.headroom_bytes); - let mut budget = options.budget_bytes; - if budget > 0 { - if budget > (room as u64) { - budget = room.saturating_sub(256 << 20) as u64; - } - let mut ranked = vec_filled(N, NONE)?; - let mut at = 0usize; - let mut held = 0; - if let Some(rank) = rank { - for &(l, e) in rank { - if l < 0 || e < 0 { - continue; - } - let Ok(i) = key(l as usize, e as usize) else { - continue; - }; - if offsets[i] == NONE || ranked[i] != NONE { - continue; - } - let b = self.layer_bytes[l as usize]; - if (b as u64) > budget.saturating_sub(at as u64) { - continue; - } - ranked[i] = at; - at = at.checked_add(b).ok_or(Error::InvalidSize)?; - held += 1; - } - } - if options.budget_bytes == u64::MAX && held == 0 { - return Err(Error::BudgetExceeded); - } - offsets = ranked; - bytes = at; - lend = None; - } - if bytes > room { - return Err(Error::BudgetExceeded); - } - let mut keep_from = cache.slots(); - if let Some(first) = lend { - let mut b = bytes; - while keep_from > first { - let n = slot_bytes[keep_from - 1]; - if n > room - b { - break; - } - b += n; - keep_from -= 1; - } - if keep_from < cache.slots() { - let mut core = Vec::new(); - core.try_reserve_exact(primary.len()).map_err(|_| Error::HostAllocation)?; - core.extend(primary.iter().copied().filter(|p| p.2 < keep_from)); - (offsets, bytes) = self.plan(&core, additional)?; - } - } - let stack = abi::worker_stack_bytes()?; - let prospective_meta = self - .metadata_bytes()? - .checked_add( - offsets.capacity() * size_of::() - + 2 * primary.capacity() * size_of::<(i32, i32, usize)>() - + slot_bytes.capacity() * size_of::() - + N * (size_of::() + size_of::() + size_of::()) - + LAYERS * size_of::>() - + 5 * size_of::>(), - ) - .ok_or(Error::BudgetExceeded)?; - if prospective_meta > META_CAP - || bytes.checked_add(prospective_meta).is_none_or(|n| n > SOURCE_CAP) - || bytes - .checked_add(5 * stack) - .and_then(|n| n.checked_add(prospective_meta)) - .and_then(|n| n.checked_add(options.headroom_bytes)) - .is_none_or(|n| n > physical) - { - return Err(Error::BudgetExceeded); - } + self.build_preflight(cache)?; + let (primary, slot_bytes) = self.collect_primary(cache)?; + let layout = self.plan_layout(cache, (&primary, &slot_bytes), (additional, rank), options)?; + let stack = self.check_host_budget(&layout, (&primary, &slot_bytes), options.headroom_bytes)?; let guard = self.context.enter().inspect_err(|_| { self.failed = true; self.context.poison(); self.context.retain_driver(); })?; let api = self.api.as_ref().ok_or(Error::ContextPoisoned)?; - let mut arena = match api.allocate(bytes, options.pin) { + let mut arena = match api.allocate(layout.bytes, options.pin) { Ok(a) => a, Err(primary) => { let pop = guard.finish(); @@ -142,126 +36,20 @@ impl<'ctx> OriginalFileExpertSource<'ctx> { return combine(Err(primary), pop); } }; - let prepare = (|| { - if options.pin && arena.pin_limit() == 0 { - if budget > 0 && options.partial_pin { - let step = 2 * GIB; - let mut want = bytes.min(options.partial_pin_cap); - while want >= step { - let mut cut = want; - for (i, &off) in offsets.iter().enumerate() { - if off != NONE - && off < want - && off.checked_add(self.layer_bytes[i / EXPERTS]).is_some_and(|end| end > want) - { - cut = off; - break; - } - } - if cut == 0 { - break; - } - if api.register_prefix(&mut arena, cut)? { - break; - } - want = if want > step { want - step } else { 0 }; - } - } - arena.lock_remainder(); - } - // Closed raw records derived only from retained mapped source and actual arena. - // Six Original layer workers; one actor participates. No Context/Rc is sent. - let mut per_layer = Vec::new(); - per_layer.try_reserve_exact(LAYERS).map_err(|_| Error::HostAllocation)?; - for l in 0..LAYERS { - let mut jobs = Vec::new(); - jobs.try_reserve_exact(EXPERTS).map_err(|_| Error::HostAllocation)?; - for e in 0..EXPERTS { - let off = offsets[l * EXPERTS + e]; - if off != NONE { - jobs.push(arena.write(off, self.parts(l, e)?)?); - } - } - per_layer.push(jobs); - } - let next = AtomicUsize::new(0); - let first = Mutex::new(None); - let work = || loop { - let l = next.fetch_add(1, Ordering::Relaxed); - if l >= LAYERS { - break; - } - if first.lock().is_ok_and(|e| e.is_some()) { - break; - } - for j in &per_layer[l] { - if let Err(e) = j.run() { - if let Ok(mut f) = first.lock() { - if f.is_none() { - *f = Some(e); - } - } - break; - } - } - }; - thread::scope(|s| { - let mut workers = Vec::new(); - workers.try_reserve_exact(5).map_err(|_| Error::HostAllocation)?; - for _ in 0..5 { - workers.push( - thread::Builder::new() - .stack_size(stack) - .spawn_scoped(s, work) - .map_err(|_| Error::HostAllocation)?, - ); - } - work(); - for w in workers { - if w.join().is_err() { - return Err(Error::HostAllocation); - } - } - Ok(()) - })?; - if let Some(e) = first.into_inner().map_err(|_| Error::HostAllocation)? { - return Err(e); - } - self.lease.validate_current().map_err(|_| Error::InvalidSize)?; - Ok(()) - })(); + let prepare = self.fill_arena(api, &mut arena, &layout, options, stack); let pop = guard.finish(); if pop.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); + poison_parts(&mut self.failed, self.context); std::mem::forget(arena); return combine(prepare, pop); } if let Err(primary) = prepare { - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(arena); - return combine::<()>(Err(primary), Err(e)); - } - }; - let cleanup = combine(api.close(&mut arena), g.finish()); - if cleanup.is_err() { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(arena); - } - return combine(Err(primary), cleanup); + return discard_arena(&mut self.failed, self.context, api, arena, primary); } self.arena = Some(arena); - self.offsets = offsets; + self.offsets = layout.offsets; self.ready = true; - self.lent_slots = if lend.is_some() { cache.slots() - keep_from } else { 0 }; + self.lent_slots = if layout.lend.is_some() { cache.slots() - layout.keep_from } else { 0 }; Ok(()) } } diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs index 8eb71496..869ee62f 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions.rs @@ -11,3 +11,5 @@ pub(super) use impl_originalstreamalloptions_2::issuer_thread; mod impl_originalexpertstager; #[path = "impl_originalstreamalloptions/impl_originalstreamall.rs"] mod impl_originalstreamall; +#[path = "impl_originalstreamalloptions/stream_phases.rs"] +mod stream_phases; diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs index a306cb24..771fcab9 100644 --- a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/impl_originalexpertstager.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl OriginalExpertStager. #[allow(unused_imports)] +use super::stream_phases::{arm_scope, finish_scope, start_issuer}; use super::*; impl<'ctx> OriginalExpertStager<'ctx> { @@ -18,156 +19,13 @@ impl<'ctx> OriginalExpertStager<'ctx> { host_allowance: usize, consumer: impl FnOnce(&mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>) -> Result, ) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> { - if self.is_failed() || self.external || self.flight.is_some() { - return Err(Error::ContextPoisoned); - } - if first >= end || end > 48 { - return Err(Error::InvalidQwenShape); - } - if !std::ptr::eq(rows.context(), self.context) { - return Err(Error::ContextMismatch); - } - copy.validate_context(self.context)?; - compute.validate_context(self.context)?; - let ring = rows.copy_ring_slots()?; - if !options.eligible(rows.rows(), ring) { - return Err(Error::InvalidQwenShape); - } - let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; - source.validate()?; - let metadata_bytes = MAX_JOBS - .checked_mul(size_of::()) - .and_then(|n| { - n.checked_add( - GPU_RING_MAX * size_of::() - + size_of::() - + size_of::>() - + size_of::>(), - ) - }) - .filter(|n| *n <= META_CAP) - .ok_or(Error::BudgetExceeded)?; - if self.metadata_bytes.checked_add(metadata_bytes).is_none_or(|n| n > META_CAP) { - return Err(Error::BudgetExceeded); - } - let extra = - metadata_bytes.checked_add(if options.issuer { WORKER_STACK } else { 0 }).ok_or(Error::BudgetExceeded)?; - if extra > host_allowance - || available_memory()? < extra.checked_add(HEADROOM).ok_or(Error::BudgetExceeded)? - || source - .charge() - .checked_add(self.host_bytes as u64) - .and_then(|n| n.checked_add(extra as u64)) - .is_none_or(|n| n > SOURCE_CAP) - { - return Err(Error::BudgetExceeded); - } - let mut entries = Vec::new(); - let mut targets = Vec::new(); - let mut copied = Vec::new(); - let mut used = Vec::new(); - entries.try_reserve_exact(MAX_JOBS).map_err(|_| Error::HostAllocation)?; - targets.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; - if entries.capacity() > MAX_JOBS || targets.capacity() > GPU_RING_MAX { - return Err(Error::BudgetExceeded); - } - for s in 0..ring { - let (h, n) = rows.copy_ring_span(s)?; - h.validate_extent(n)?; - if n < self.blob_bytes { - return Err(Error::InvalidSize); - } - targets.push(h); - } - let mut layer_start = [0usize; 49]; + let ring = self.stream_preflight(&rows, (©, &compute), (first, end), options)?; + self.check_stream_budget(options, host_allowance)?; + let (mut entries, targets) = self.reserve_stream_targets(&rows, ring)?; let generation = self.generation.checked_add(1).ok_or(Error::InvalidSize)?; - { - let mut work = self.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; - work.jobs.clear(); - for l in first..end { - layer_start[l as usize] = entries.len(); - for e in 0..512u32 { - if rows.cache_expert_span(l as usize, e as usize)?.is_some() { - continue; - } - let raw = source.raw_at(l, e, self.blob_bytes)?; - let job = work.jobs.len(); - entries.push(Entry { layer: l, expert: e, bytes: raw.bytes(), job }); - work.jobs.push(raw); - } - } - for l in end..=48 { - layer_start[l as usize] = entries.len(); - } - } - // Persistent Original RING_MAX copied/used bank. Constructor metadata - // reserves it; same real events/stage_live survive subsequent prompt chunks. - if self.stream_events.is_none() { - copied.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; - used.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; - if copied.capacity() > GPU_RING_MAX || used.capacity() > GPU_RING_MAX { - return Err(Error::BudgetExceeded); - } - let mut live = Vec::new(); - live.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; - if live.capacity() > GPU_RING_MAX { - return Err(Error::BudgetExceeded); - } - live.resize_with(GPU_RING_MAX, || AtomicBool::new(false)); - let guard = self.context.enter().inspect_err(|_| { - self.context.poison(); - self.context.retain_driver(); - })?; - let creation: Result<()> = (|| { - for _ in 0..GPU_RING_MAX { - copied.push(self.api.event_create()?); - used.push(self.api.event_create()?); - } - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - if let Err(primary) = combine(creation, pop) { - if self.context.is_poisoned() { - std::mem::forget(copied); - std::mem::forget(used); - std::mem::forget(self.api.clone()); - return Err(primary); - } - let cleanup = (|| { - let guard = self.context.enter()?; - let mut r = Ok(()); - for e in copied.iter().chain(&used) { - r = combine(r, self.api.event_destroy(*e)); - } - combine(r, guard.finish()) - })(); - if cleanup.is_err() { - self.context.poison(); - self.context.retain_driver(); - std::mem::forget(copied); - std::mem::forget(used); - std::mem::forget(self.api.clone()); - } - return combine(Err(primary), cleanup); - } - self.stream_events = Some(Arc::new(EventBank { copied, used, live })); - } - let events = self.stream_events.as_ref().ok_or(Error::ContextPoisoned)?.clone(); - let issuer = Arc::new(Issuer { - entries, - targets, - events, - issued: AtomicUsize::new(0), - consumed: AtomicUsize::new(0), - stop: AtomicBool::new(false), - failed: AtomicBool::new(false), - error: Mutex::new(None), - ring, - }); + let layer_start = self.queue_stream_jobs(&rows, (first, end), &mut entries)?; + self.ensure_stream_events()?; + let issuer = self.new_issuer(entries, targets, ring)?; let mut scope = OriginalStreamAll { stager: self, rows: Some(rows), @@ -182,66 +40,10 @@ impl<'ctx> OriginalExpertStager<'ctx> { cursor: layer_start[first as usize], finished: false, }; - { - let mut work = scope.stager.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; - for ready in scope.stager.shared.ready.iter().take(work.jobs.len()) { - ready.store(0, Ordering::Relaxed); - } - scope.stager.external = true; - scope.stager.generation = generation; - scope.stager.shared.issued.store(0, Ordering::Release); - scope - .stager - .shared - .head - .store((u64::from(generation) << 32) | ((work.jobs.len() as u64) << 16), Ordering::Release); - work.generation = generation; - } - scope.stager.shared.cv.notify_all(); - let start = if options.issuer { - let api = scope.stager.api.clone(); - let shared = scope.issuer.clone(); - let stager = scope.stager.shared.clone(); - let token = abi::Api::context_token(scope.stager.context.handle.ok_or(Error::ContextPoisoned)?); - let stream = scope.copy.as_mut().ok_or(Error::InvalidSize)?.with_enqueue(Ok)?; - match thread::Builder::new() - .stack_size(WORKER_STACK) - .spawn(move || issuer_thread(api, shared, stager, token, stream)) - { - Ok(t) => { - scope.thread = Some(t); - Ok(()) - } - Err(_) => Err(Error::HostAllocation), - } - } else { - scope.issue_inline(ring) - }; - if let Err(primary) = start { + arm_scope(&mut scope, generation)?; + if let Err(primary) = start_issuer(&mut scope, options, ring)? { return combine(Err(primary), scope.cleanup()); } - let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut scope))); - let result = match invoked { - Ok(result) => result, - Err(panic) => { - let _ = scope.cleanup(); - std::panic::resume_unwind(panic) - } - }; - let complete = if result.is_ok() && (scope.next_layer != end || scope.cursor != scope.issuer.entries.len()) { - Err(Error::InvalidQwenShape) - } else { - Ok(()) - }; - let result = combine(result, complete); - let cleanup = scope.cleanup(); - let value = combine(result, cleanup)?; - let completed = OriginalStreamAllCompleted { - rows: scope.rows.take().ok_or(Error::ContextPoisoned)?, - copy: scope.copy.take().ok_or(Error::ContextPoisoned)?, - compute: scope.compute.take().ok_or(Error::ContextPoisoned)?, - streamed: scope.issuer.issued.load(Ordering::Acquire), - }; - Ok((value, completed)) + finish_scope(&mut scope, end, consumer) } } diff --git a/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs new file mode 100644 index 00000000..bdd5a8d9 --- /dev/null +++ b/crates/cuda-driver/src/original_stream_all/impl_originalstreamalloptions/stream_phases.rs @@ -0,0 +1,314 @@ +//! STRA-338 size: the phases of `OriginalExpertStager::run_stream_all`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +/// Persistent Original RING_MAX copied/used bank. Constructor metadata +/// reserves it; same real events/stage_live survive subsequent prompt chunks. +fn reserve_event_bank() -> Result<(Vec, Vec, Vec)> { + let mut copied = Vec::new(); + let mut used = Vec::new(); + copied.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + used.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if copied.capacity() > GPU_RING_MAX || used.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + let mut live = Vec::new(); + live.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if live.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + live.resize_with(GPU_RING_MAX, || AtomicBool::new(false)); + Ok((copied, used, live)) +} + +/// Bytes of scope bookkeeping: entries, ring handles, issuer, scope and issuer thread handle. +fn stream_metadata_bytes() -> Result { + MAX_JOBS + .checked_mul(size_of::()) + .and_then(|n| { + n.checked_add( + GPU_RING_MAX * size_of::() + + size_of::() + + size_of::>() + + size_of::>(), + ) + }) + .filter(|n| *n <= META_CAP) + .ok_or(Error::BudgetExceeded) +} + +/// Publishes the new generation to the shared job table and wakes the workers. +pub(super) fn arm_scope(scope: &mut OriginalStreamAll<'_, '_, '_, '_>, generation: u32) -> Result<()> { + { + let mut work = scope.stager.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; + for ready in scope.stager.shared.ready.iter().take(work.jobs.len()) { + ready.store(0, Ordering::Relaxed); + } + scope.stager.external = true; + scope.stager.generation = generation; + scope.stager.shared.issued.store(0, Ordering::Release); + scope + .stager + .shared + .head + .store((u64::from(generation) << 32) | ((work.jobs.len() as u64) << 16), Ordering::Release); + work.generation = generation; + } + scope.stager.shared.cv.notify_all(); + Ok(()) +} + +/// Starts the issuer thread or issues inline. The outer error returns straight from the caller; the inner one +/// is the start failure the caller cleans up after. +pub(super) fn start_issuer( + scope: &mut OriginalStreamAll<'_, '_, '_, '_>, + options: OriginalStreamAllOptions, + ring: usize, +) -> Result> { + if !options.issuer { + return Ok(scope.issue_inline(ring)); + } + let api = scope.stager.api.clone(); + let shared = scope.issuer.clone(); + let stager = scope.stager.shared.clone(); + let token = abi::Api::context_token(scope.stager.context.handle.ok_or(Error::ContextPoisoned)?); + let stream = scope.copy.as_mut().ok_or(Error::InvalidSize)?.with_enqueue(Ok)?; + match thread::Builder::new() + .stack_size(WORKER_STACK) + .spawn(move || issuer_thread(api, shared, stager, token, stream)) + { + Ok(t) => { + scope.thread = Some(t); + Ok(Ok(())) + } + Err(_) => Ok(Err(Error::HostAllocation)), + } +} + +/// Runs the consumer (a panic cleans up and resumes), checks every layer was consumed and hands the streams back. +pub(super) fn finish_scope<'arena, 'loan, 'ctx, T>( + scope: &mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>, + end: u8, + consumer: impl FnOnce(&mut OriginalStreamAll<'_, 'arena, 'loan, 'ctx>) -> Result, +) -> Result<(T, OriginalStreamAllCompleted<'arena, 'loan, 'ctx>)> { + let invoked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| consumer(&mut *scope))); + let result = match invoked { + Ok(result) => result, + Err(panic) => { + let _ = scope.cleanup(); + std::panic::resume_unwind(panic) + } + }; + let complete = if result.is_ok() && (scope.next_layer != end || scope.cursor != scope.issuer.entries.len()) { + Err(Error::InvalidQwenShape) + } else { + Ok(()) + }; + let result = combine(result, complete); + let cleanup = scope.cleanup(); + let value = combine(result, cleanup)?; + let completed = OriginalStreamAllCompleted { + rows: scope.rows.take().ok_or(Error::ContextPoisoned)?, + copy: scope.copy.take().ok_or(Error::ContextPoisoned)?, + compute: scope.compute.take().ok_or(Error::ContextPoisoned)?, + streamed: scope.issuer.issued.load(Ordering::Acquire), + }; + Ok((value, completed)) +} + +impl<'ctx> OriginalExpertStager<'ctx> { + /// Rejects a stager, range, rows or streams that are not usable; returns the copy-ring slot count. + pub(super) fn stream_preflight( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + streams: (&OriginalGpuStream<'ctx>, &OriginalGpuStream<'ctx>), + (first, end): (u8, u8), + options: OriginalStreamAllOptions, + ) -> Result { + if self.is_failed() || self.external || self.flight.is_some() { + return Err(Error::ContextPoisoned); + } + if first >= end || end > 48 { + return Err(Error::InvalidQwenShape); + } + self.validate_stream_context(rows, streams)?; + let ring = rows.copy_ring_slots()?; + if !options.eligible(rows.rows(), ring) { + return Err(Error::InvalidQwenShape); + } + Ok(ring) + } + + fn validate_stream_context( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + streams: (&OriginalGpuStream<'ctx>, &OriginalGpuStream<'ctx>), + ) -> Result<()> { + if !std::ptr::eq(rows.context(), self.context) { + return Err(Error::ContextMismatch); + } + streams.0.validate_context(self.context)?; + streams.1.validate_context(self.context) + } + + /// Checks the scope's metadata, issuer stack and source charge against the caps and the host allowance. + pub(super) fn check_stream_budget(&self, options: OriginalStreamAllOptions, host_allowance: usize) -> Result<()> { + let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; + source.validate()?; + let metadata_bytes = stream_metadata_bytes()?; + if self.metadata_bytes.checked_add(metadata_bytes).is_none_or(|n| n > META_CAP) { + return Err(Error::BudgetExceeded); + } + let extra = + metadata_bytes.checked_add(if options.issuer { WORKER_STACK } else { 0 }).ok_or(Error::BudgetExceeded)?; + self.check_stream_extra(source.charge(), extra, host_allowance) + } + + fn check_stream_extra(&self, charge: u64, extra: usize, host_allowance: usize) -> Result<()> { + if extra > host_allowance + || available_memory()? < extra.checked_add(HEADROOM).ok_or(Error::BudgetExceeded)? + || self.source_overcharged(charge, extra) + { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + + fn source_overcharged(&self, charge: u64, extra: usize) -> bool { + charge + .checked_add(self.host_bytes as u64) + .and_then(|n| n.checked_add(extra as u64)) + .is_none_or(|n| n > SOURCE_CAP) + } + + /// Reserves the entry and target tables and collects the copy-ring target spans. + pub(super) fn reserve_stream_targets( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + ring: usize, + ) -> Result<(Vec, Vec)> { + let mut entries = Vec::new(); + let mut targets = Vec::new(); + entries.try_reserve_exact(MAX_JOBS).map_err(|_| Error::HostAllocation)?; + targets.try_reserve_exact(GPU_RING_MAX).map_err(|_| Error::HostAllocation)?; + if entries.capacity() > MAX_JOBS || targets.capacity() > GPU_RING_MAX { + return Err(Error::BudgetExceeded); + } + for s in 0..ring { + let (h, n) = rows.copy_ring_span(s)?; + h.validate_extent(n)?; + if n < self.blob_bytes { + return Err(Error::InvalidSize); + } + targets.push(h); + } + Ok((entries, targets)) + } + + /// Queues the source job of every expert the cache does not hold; returns the first entry of each layer. + pub(super) fn queue_stream_jobs( + &self, + rows: &OriginalPromptRows<'_, '_, 'ctx>, + (first, end): (u8, u8), + entries: &mut Vec, + ) -> Result<[usize; 49]> { + let source = self.source.as_ref().ok_or(Error::ContextPoisoned)?; + let mut layer_start = [0usize; 49]; + let mut work = self.shared.work.lock().map_err(|_| Error::ContextPoisoned)?; + work.jobs.clear(); + for l in first..end { + layer_start[l as usize] = entries.len(); + for e in 0..512u32 { + if rows.cache_expert_span(l as usize, e as usize)?.is_some() { + continue; + } + let raw = source.raw_at(l, e, self.blob_bytes)?; + let job = work.jobs.len(); + entries.push(Entry { layer: l, expert: e, bytes: raw.bytes(), job }); + work.jobs.push(raw); + } + } + for l in end..=48 { + layer_start[l as usize] = entries.len(); + } + Ok(layer_start) + } + + pub(super) fn new_issuer( + &self, + entries: Vec, + targets: Vec, + ring: usize, + ) -> Result> { + let events = self.stream_events.as_ref().ok_or(Error::ContextPoisoned)?.clone(); + Ok(Arc::new(Issuer { + entries, + targets, + events, + issued: AtomicUsize::new(0), + consumed: AtomicUsize::new(0), + stop: AtomicBool::new(false), + failed: AtomicBool::new(false), + error: Mutex::new(None), + ring, + })) + } + + /// Creates the persistent copied/used event bank on first use. + pub(super) fn ensure_stream_events(&mut self) -> Result<()> { + if self.stream_events.is_some() { + return Ok(()); + } + let (mut copied, mut used, live) = reserve_event_bank()?; + let guard = self.context.enter().inspect_err(|_| { + self.context.poison(); + self.context.retain_driver(); + })?; + let creation = self.create_events(&mut copied, &mut used); + let pop = guard.finish(); + if pop.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + if let Err(primary) = combine(creation, pop) { + return self.discard_events(copied, used, primary); + } + self.stream_events = Some(Arc::new(EventBank { copied, used, live })); + Ok(()) + } + + fn create_events(&self, copied: &mut Vec, used: &mut Vec) -> Result<()> { + for _ in 0..GPU_RING_MAX { + copied.push(self.api.event_create()?); + used.push(self.api.event_create()?); + } + Ok(()) + } + + /// Destroys the events of a failed bank creation, or leaks them when the context is no longer usable. + fn discard_events(&self, copied: Vec, used: Vec, primary: Error) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(copied); + std::mem::forget(used); + std::mem::forget(self.api.clone()); + return Err(primary); + } + let cleanup = (|| { + let guard = self.context.enter()?; + let mut r = Ok(()); + for e in copied.iter().chain(&used) { + r = combine(r, self.api.event_destroy(*e)); + } + combine(r, guard.finish()) + })(); + if cleanup.is_err() { + self.context.poison(); + self.context.retain_driver(); + std::mem::forget(copied); + std::mem::forget(used); + std::mem::forget(self.api.clone()); + } + combine(Err(primary), cleanup) + } +} diff --git a/crates/cuda-driver/src/original_verify_schedule.rs b/crates/cuda-driver/src/original_verify_schedule.rs index 517fc476..9c51a81a 100644 --- a/crates/cuda-driver/src/original_verify_schedule.rs +++ b/crates/cuda-driver/src/original_verify_schedule.rs @@ -72,3 +72,5 @@ mod impl_originalverifier_2; mod impl_originalverifier_3; #[path = "original_verify_schedule/impl_originalverifier_4.rs"] mod impl_originalverifier_4; +#[path = "original_verify_schedule/window_phases.rs"] +mod window_phases; diff --git a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs index e911f00e..da204a0b 100644 --- a/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs +++ b/crates/cuda-driver/src/original_verify_schedule/impl_originalverifier_2.rs @@ -19,200 +19,15 @@ impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResour &mut OriginalGpuStream<'ctx>, ) -> Result<()>, ) -> Result { - // #267: a released verifier (a window the GPU never finished) refuses every later window. - if self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) { - return Err(Error::InvalidDriverValue( - "Verifier released: an earlier window never finished on the GPU (#267)", - )); - } - if self.failed || self.active || self.window_ready || self.commit.is_none() { - return Err(Error::InvalidQwenShape); - } - if sampling.position != position as u64 { - return Err(Error::InvalidQwenShape); - } + self.check_run_inputs(tokens, position, ple, sampling.position)?; let t = tokens.len(); - if !(1..=self.bank()?.geometry().max_t).contains(&t) || self.window[t - 1].is_none() { - return Err(Error::InvalidQwenShape); - } - let wants_ple = self.window[t - 1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?; - if wants_ple != ple.is_some() { - return Err(Error::InvalidQwenShape); - } - // The preceding asynchronous commit has the same compute stream. Its actual - // mapped records are overwritten only after that completed receipt/window. - let span_wait = crate::host_profile::span("drv.run_wait_commit"); - self.wait_commit()?; - drop(span_wait); - let span_stage = crate::host_profile::span("drv.stage"); - let generation = self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens, position)?; - if let Some(ple) = ple { - self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)? - } - drop(span_stage); - let span_begin = crate::host_profile::span("drv.begin_window"); - self.window[t - 1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?; - drop(span_begin); - self.active = true; - if let Some(r) = &self.registration { - r.begin_window(t, position as u64) - } - let operation = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| -> Result { - let span_launch = crate::host_profile::span("drv.launch"); - self.window[t - 1] - .as_mut() - .ok_or(Error::ContextPoisoned)? - .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; - let _ = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; - drop(span_launch); - let groups = self.groups[t - 1]; - for k in 0..window_plan::window_rings(groups) { - let layer = k / groups; - let group = k % groups; - let want = window_plan::ring(layer, groups, group); - let start = Instant::now(); - let mut last_flush = start; - let mut spins = 0u32; - if let Some(r) = &self.registration { - r.layer_step(want) - } - let span_bell = crate::host_profile::span("drv.doorbell_wait"); - loop { - if self.bank()?.doorbell_sequence()? >= want { - break; - } - std::hint::spin_loop(); - spins = spins.wrapping_add(1); - if spins & 1023 != 0 { - continue; - } - let now = Instant::now(); - if self.registration.as_ref().is_some_and(diag::Registration::is_released) { - return Err(Error::InvalidDriverValue( - "Verifier window released while waiting for a layer (#267)", - )); - } - if now.duration_since(last_flush) > Duration::from_micros(2000) { - last_flush = now; - let q = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; - if q && self.bank()?.doorbell_sequence()? < want { - return Err(Error::InvalidDriverValue("Verifier layer never rang")); - } - } - if now.duration_since(start) > Duration::from_secs(20) { - return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout")); - } - } - drop(span_bell); - let (begin, end) = window_plan::group_rows(t, groups, group); - let rows = end - begin; - let g = self.bank()?.geometry(); - let physical = self.bank()?.physical.clone(); - let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?; - let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; - let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?; - MappedAllocation::with_cpu_rows( - x.as_ref().ok_or(Error::ContextPoisoned)?, - ids.as_ref().ok_or(Error::ContextPoisoned)?, - w.as_ref().ok_or(Error::ContextPoisoned)?, - begin, - rows, - g.n, - g.k, - |activation, ids, route_weights| { - pool( - OriginalVerifyCpuRows { layer, group, first_row: begin, activation, ids, route_weights }, - &mut OriginalVerifyCpuSink { - bank: self.bank.as_mut().ok_or(Error::ContextPoisoned)?, - first: begin, - rows, - layer, - group, - groups, - ring: want, - }, - self.copy.as_mut().ok_or(Error::ContextPoisoned)?, - ) - }, - )?; - drop((x, ids, w)); - // A pool with no GPU plan publishes the literal empty plan; actual DMA - // producers publish A and raise B only from completed host callbacks. - let span_flag = crate::host_profile::span("drv.group_publish"); - let flag = self.bank()?.physical.mapped[11] - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_u32(0)?; - if flag != want { - self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group, want)? - } - let stalled = self.test_stall > 0 - && self.windows + 1 == self.test_stall - && k + 1 == window_plan::window_rings(groups); - if !stalled { - self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10] - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)? - .as_mut() - .ok_or(Error::ContextPoisoned)? - .publish_u32(0, want)?; - } - drop(span_flag); - } - // Original order: compute fence, then copy-stream fence (no late flag B), - // then request sampling with Philox counter tied to actual position. - let span_sync = crate::host_profile::span("drv.sync_compute"); - let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; - drop(span_sync); - let span_copy = crate::host_profile::span("drv.sync_copy"); - self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; - drop(span_copy); - // Every PCIe copy of the window has landed: the registered sources it read may go. - self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources(); - // The window's GPU stage stamps (single-group windows only, as in Original). - if groups == 1 && self.bank()?.profile_enabled() { - let stamps = self.bank()?.read_profile()?; - self.profile.add_window(&stamps, 48, |l| l % 4 == 3); - } - let _span_head = crate::host_profile::span("drv.head"); - self.window[t - 1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain( - self.compute.as_mut().ok_or(Error::ContextPoisoned)?, - &receipt, - sampling, - ) - })); + let generation = self.stage_window(tokens, position, ple)?; + let operation = + std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.run_window(t, sampling, &mut pool))); if let Some(r) = &self.registration { r.end_window() } - match operation { - Ok(Ok(selection)) => { - if selection.ids().len() != t - || selection.position() != position as u64 - || selection.vocabulary() != self.bank()?.geometry().vocabulary - { - self.failed = true; - return combine(Err(Error::InvalidQwenShape), self.abort_gpu_waits()); - } - self.completed_ids[..t].copy_from_slice(selection.ids()); - self.active = false; - self.window_ready = true; - self.completed_generation = Some(generation); - self.windows = self.windows.checked_add(1).ok_or(Error::InvalidSize)?; - Ok(OriginalVerifyWindowResult { selection, generation, first_position: position, rows: t }) - } - Ok(Err(primary)) => { - self.failed = true; - let cleanup = self.abort_gpu_waits(); - combine(Err(primary), cleanup) - } - Err(panic) => { - self.failed = true; - let _ = self.abort_gpu_waits(); - std::panic::resume_unwind(panic) - } - } + self.settle_window(operation, (t, position, generation)) } /// n_keep is meaningful only after the actual preceding window completes. /// Root prepares all genuine accepted-prefix publication permits AFTER this diff --git a/crates/cuda-driver/src/original_verify_schedule/window_phases.rs b/crates/cuda-driver/src/original_verify_schedule/window_phases.rs new file mode 100644 index 00000000..6b8c15a3 --- /dev/null +++ b/crates/cuda-driver/src/original_verify_schedule/window_phases.rs @@ -0,0 +1,340 @@ +//! STRA-338 size: the phases of `OriginalVerifier::run`, extracted in call order. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx, R: OriginalVerifyGraphResources<'ctx> + OriginalNativeHeadGraphResources<'ctx>> OriginalVerifier<'ctx, R> { + /// Refuses a released or busy verifier, a mismatched position or row count and a PLE mismatch. + pub(super) fn check_run_inputs( + &self, + tokens: &[i32], + position: usize, + ple: Option<&[f32]>, + sampling_position: u64, + ) -> Result<()> { + // #267: a released verifier (a window the GPU never finished) refuses every later window. + if self.released || self.registration.as_ref().is_some_and(diag::Registration::is_released) { + return Err(Error::InvalidDriverValue( + "Verifier released: an earlier window never finished on the GPU (#267)", + )); + } + if self.failed || self.active || self.window_ready || self.commit.is_none() { + return Err(Error::InvalidQwenShape); + } + self.check_window_shape(tokens, position, ple, sampling_position) + } + + fn check_window_shape( + &self, + tokens: &[i32], + position: usize, + ple: Option<&[f32]>, + sampling_position: u64, + ) -> Result<()> { + if sampling_position != position as u64 { + return Err(Error::InvalidQwenShape); + } + let t = tokens.len(); + if !(1..=self.bank()?.geometry().max_t).contains(&t) || self.window[t - 1].is_none() { + return Err(Error::InvalidQwenShape); + } + let wants_ple = self.window[t - 1].as_ref().ok_or(Error::InvalidQwenShape)?.verifier_uses_ple()?; + if wants_ple != ple.is_some() { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + + /// Waits for the previous commit, stages tokens and PLE and begins the window; returns its generation. + pub(super) fn stage_window(&mut self, tokens: &[i32], position: usize, ple: Option<&[f32]>) -> Result { + let t = tokens.len(); + // The preceding asynchronous commit has the same compute stream. Its actual + // mapped records are overwritten only after that completed receipt/window. + let span_wait = crate::host_profile::span("drv.run_wait_commit"); + self.wait_commit()?; + drop(span_wait); + let span_stage = crate::host_profile::span("drv.stage"); + let generation = self.stage_bank(tokens, position, ple)?; + drop(span_stage); + let span_begin = crate::host_profile::span("drv.begin_window"); + self.window[t - 1].as_ref().ok_or(Error::ContextPoisoned)?.verifier_begin_window(self.bank()?)?; + drop(span_begin); + self.active = true; + if let Some(r) = &self.registration { + r.begin_window(t, position as u64) + } + Ok(generation) + } + + fn stage_bank(&mut self, tokens: &[i32], position: usize, ple: Option<&[f32]>) -> Result { + let generation = self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage(tokens, position)?; + if let Some(ple) = ple { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.stage_ple(ple)? + } + Ok(generation) + } + + /// Launches the window graph, serves every ring through `pool`, then drains both streams and samples. + pub(super) fn run_window

( + &mut self, + t: usize, + sampling: NativeHeadSampling<'_, 'ctx>, + pool: &mut P, + ) -> Result + where + P: FnMut( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, + { + let span_launch = crate::host_profile::span("drv.launch"); + self.window[t - 1] + .as_mut() + .ok_or(Error::ContextPoisoned)? + .enqueue(self.compute.as_ref().ok_or(Error::ContextPoisoned)?)?; + let _ = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; + drop(span_launch); + let groups = self.groups[t - 1]; + for k in 0..window_plan::window_rings(groups) { + self.run_ring(t, groups, k, pool)?; + } + self.finish_window(t, groups, sampling) + } + + fn run_ring

(&mut self, t: usize, groups: usize, k: usize, pool: &mut P) -> Result<()> + where + P: FnMut( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, + { + let layer = k / groups; + let group = k % groups; + let want = window_plan::ring(layer, groups, group); + let start = Instant::now(); + if let Some(r) = &self.registration { + r.layer_step(want) + } + let span_bell = crate::host_profile::span("drv.doorbell_wait"); + self.wait_doorbell(want, start)?; + drop(span_bell); + self.pool_group(t, groups, (layer, group), want, pool)?; + self.publish_group(k, groups, group, want) + } + + /// Spins on the mapped doorbell until ring `want` rings; checks release, a finished-but-silent stream and 20 s. + fn wait_doorbell(&self, want: u32, start: Instant) -> Result<()> { + let mut last_flush = start; + let mut spins = 0u32; + loop { + if self.bank()?.doorbell_sequence()? >= want { + break; + } + std::hint::spin_loop(); + spins = spins.wrapping_add(1); + if spins & 1023 != 0 { + continue; + } + last_flush = self.doorbell_poll(want, (start, last_flush))?; + } + Ok(()) + } + + /// One slow-path check of the doorbell wait; returns the time of the last stream query. + fn doorbell_poll(&self, want: u32, (start, mut last_flush): (Instant, Instant)) -> Result { + let now = Instant::now(); + if self.registration.as_ref().is_some_and(diag::Registration::is_released) { + return Err(Error::InvalidDriverValue("Verifier window released while waiting for a layer (#267)")); + } + if now.duration_since(last_flush) > Duration::from_micros(2000) { + last_flush = now; + let q = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.query()?; + if q && self.bank()?.doorbell_sequence()? < want { + return Err(Error::InvalidDriverValue("Verifier layer never rang")); + } + } + if now.duration_since(start) > Duration::from_secs(20) { + return Err(Error::InvalidDriverValue("Verifier layer doorbell timeout")); + } + Ok(last_flush) + } + + /// Hands the group's mapped CPU rows to the caller's pool together with the plan sink. + fn pool_group

( + &mut self, + t: usize, + groups: usize, + (layer, group): (usize, usize), + want: u32, + pool: &mut P, + ) -> Result<()> + where + P: FnMut( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, + { + let (begin, end) = window_plan::group_rows(t, groups, group); + let rows = end - begin; + let g = self.bank()?.geometry(); + let physical = self.bank()?.physical.clone(); + let x = physical.mapped[6].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let ids = physical.mapped[7].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let w = physical.mapped[8].try_borrow().map_err(|_| Error::InvalidQwenShape)?; + MappedAllocation::with_cpu_rows( + x.as_ref().ok_or(Error::ContextPoisoned)?, + ids.as_ref().ok_or(Error::ContextPoisoned)?, + w.as_ref().ok_or(Error::ContextPoisoned)?, + begin, + rows, + g.n, + g.k, + |activation, ids, route_weights| { + let cpu = OriginalVerifyCpuRows { layer, group, first_row: begin, activation, ids, route_weights }; + self.invoke_pool(pool, cpu, (begin, rows, groups, want)) + }, + )?; + drop((x, ids, w)); + Ok(()) + } + + fn invoke_pool

( + &mut self, + pool: &mut P, + cpu: OriginalVerifyCpuRows<'_>, + (first, rows, groups, ring): (usize, usize, usize, u32), + ) -> Result<()> + where + P: FnMut( + OriginalVerifyCpuRows<'_>, + &mut OriginalVerifyCpuSink<'_, 'ctx>, + &mut OriginalGpuStream<'ctx>, + ) -> Result<()>, + { + let (layer, group) = (cpu.layer, cpu.group); + pool( + cpu, + &mut OriginalVerifyCpuSink { + bank: self.bank.as_mut().ok_or(Error::ContextPoisoned)?, + first, + rows, + layer, + group, + groups, + ring, + }, + self.copy.as_mut().ok_or(Error::ContextPoisoned)?, + ) + } + + /// A pool with no GPU plan publishes the literal empty plan; actual DMA + /// producers publish A and raise B only from completed host callbacks. + fn publish_group(&mut self, k: usize, groups: usize, group: usize, want: u32) -> Result<()> { + let span_flag = crate::host_profile::span("drv.group_publish"); + let flag = self.bank()?.physical.mapped[11] + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_u32(0)?; + if flag != want { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.publish_empty_plan(group, want)? + } + self.raise_group_flag(k, groups, want)?; + drop(span_flag); + Ok(()) + } + + /// Raises flag B for the ring unless the test stall hook holds back the last ring of its window. + fn raise_group_flag(&mut self, k: usize, groups: usize, want: u32) -> Result<()> { + let stalled = + self.test_stall > 0 && self.windows + 1 == self.test_stall && k + 1 == window_plan::window_rings(groups); + if !stalled { + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.physical.mapped[10] + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)? + .as_mut() + .ok_or(Error::ContextPoisoned)? + .publish_u32(0, want)?; + } + Ok(()) + } + + /// Original order: compute fence, then copy-stream fence (no late flag B), + /// then request sampling with Philox counter tied to actual position. + fn finish_window( + &mut self, + t: usize, + groups: usize, + sampling: NativeHeadSampling<'_, 'ctx>, + ) -> Result { + let span_sync = crate::host_profile::span("drv.sync_compute"); + let receipt = self.compute.as_ref().ok_or(Error::ContextPoisoned)?.synchronize_with_receipt()?; + drop(span_sync); + let span_copy = crate::host_profile::span("drv.sync_copy"); + self.copy.as_ref().ok_or(Error::ContextPoisoned)?.synchronize()?; + drop(span_copy); + // Every PCIe copy of the window has landed: the registered sources it read may go. + self.bank.as_mut().ok_or(Error::ContextPoisoned)?.release_pcie_sources(); + self.record_window_profile(groups)?; + let _span_head = crate::host_profile::span("drv.head"); + self.window[t - 1].as_mut().ok_or(Error::ContextPoisoned)?.verifier_head_after_drain( + self.compute.as_mut().ok_or(Error::ContextPoisoned)?, + &receipt, + sampling, + ) + } + + /// The window's GPU stage stamps (single-group windows only, as in Original). + fn record_window_profile(&mut self, groups: usize) -> Result<()> { + if groups == 1 && self.bank()?.profile_enabled() { + let stamps = self.bank()?.read_profile()?; + self.profile.add_window(&stamps, 48, |l| l % 4 == 3); + } + Ok(()) + } + + fn complete_window( + &mut self, + selection: NativeHeadSelection, + (t, position, generation): (usize, usize, u64), + ) -> Result { + if selection.ids().len() != t + || selection.position() != position as u64 + || selection.vocabulary() != self.bank()?.geometry().vocabulary + { + self.failed = true; + return combine(Err(Error::InvalidQwenShape), self.abort_gpu_waits()); + } + self.completed_ids[..t].copy_from_slice(selection.ids()); + self.active = false; + self.window_ready = true; + self.completed_generation = Some(generation); + self.windows = self.windows.checked_add(1).ok_or(Error::InvalidSize)?; + Ok(OriginalVerifyWindowResult { selection, generation, first_position: position, rows: t }) + } + + /// Records the outcome of a window: validates and completes it, or fails the verifier and releases the waits. + pub(super) fn settle_window( + &mut self, + operation: std::thread::Result>, + (t, position, generation): (usize, usize, u64), + ) -> Result { + match operation { + Ok(Ok(selection)) => self.complete_window(selection, (t, position, generation)), + Ok(Err(primary)) => { + self.failed = true; + let cleanup = self.abort_gpu_waits(); + combine(Err(primary), cleanup) + } + Err(panic) => { + self.failed = true; + let _ = self.abort_gpu_waits(); + std::panic::resume_unwind(panic) + } + } + } +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs index 1c44f8a6..32193609 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue.rs @@ -3,6 +3,7 @@ #[allow(unused_imports)] use super::*; +mod compose_phases; mod impl_plebatchqueue_2; mod impl_plebatchqueue_2_2; mod impl_plebatchqueue_3; diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs new file mode 100644 index 00000000..cde7da7f --- /dev/null +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/compose_phases.rs @@ -0,0 +1,194 @@ +//! STRA-338 size: the phases of `PleBatchQueue::compose`, extracted in command order. + +#[allow(unused_imports)] +use super::*; + +/// Device spans, weights and the row count one batch compose shares. +pub(super) struct BatchPlan { + h: [BufferHandle; 15], + key: BufferHandle, + value: BufferHandle, + aux: [BufferHandle; 4], + rows: usize, +} + +/// Host buffers one batch compose stages its uploads in and reads its status words back into. +pub(super) struct BatchHost { + pub(super) e: Vec, + pub(super) s: Vec, + pub(super) p: Vec, + pub(super) zero: Vec, + pub(super) statuses: Vec, + pub(super) flags: Vec, +} + +impl BatchHost { + pub(super) fn new(embedding: &[f32], streams: &[f32], history: &[f32], rows: usize) -> Result { + let e = float_staging(embedding)?; + let s = float_staging(streams)?; + let p = float_staging(history)?; + let zero = staging(rows * 40)?; + let statuses = staging(rows * 40)?; + let mut flags = Vec::new(); + flags.try_reserve_exact(rows * 10).map_err(|_| Error::HostAllocation)?; + flags.resize(rows * 10, 0); + Ok(Self { e, s, p, zero, statuses, flags }) + } + + /// Decodes the drained status words; a status above 1 is a failed finite check (`false`). + pub(super) fn decode_flags(&mut self) -> bool { + for (flag, bytes) in self.flags.iter_mut().zip(self.statuses.as_chunks::<4>().0) { + *flag = u32::from_le_bytes(*bytes); + if *flag > 1 { + return false; + } + } + true + } +} + +impl<'ctx> PleBatchQueue<'ctx> { + /// Rejects spans aliasing the workspace and sources of the wrong shape or with non-finite values; returns the rows. + pub(super) fn check_batch_inputs( + &self, + workspace: &NativeBatchWorkspace<'_>, + h: [BufferHandle; 15], + (embedding, streams, history): (&[f32], &[f32], &[f32]), + ) -> Result { + for (handle, bytes) in h.into_iter().zip(self.sizes) { + workspace.reject_alias(handle, bytes)?; + } + if !embedding.len().is_multiple_of(2560) { + return Err(Error::InvalidQwenShape); + } + let rows = embedding.len() / 2560; + if !(1..=self.capacity).contains(&rows) || streams.len() != rows * 10240 || history.len() != 92160 { + return Err(Error::InvalidQwenShape); + } + if embedding.iter().chain(streams).chain(history).any(|v| !v.is_finite()) { + return Err(Error::InvalidDriverValue("PLE batch source finite")); + } + Ok(rows) + } + + /// Validates the key, value and auxiliary weights and rejects any aliasing the workspace. + pub(super) fn batch_plan( + &self, + workspace: &NativeBatchWorkspace<'_>, + weights: &PleClosedWeights<'_, '_>, + h: [BufferHandle; 15], + rows: usize, + ) -> Result { + let key = self.weight(weights.key, 52428800, 2)?; + let value = self.weight(weights.value, 13107200, 2)?; + let mut aux = [h[0]; 4]; + for (i, w) in weights.aux.iter().enumerate() { + aux[i] = self.weight(w, if i == 3 { 81920 } else { 40960 }, if i == 3 { 2 } else { 4 })?; + } + for (weight, bytes) in + [(key, 52428800), (value, 13107200), (aux[0], 40960), (aux[1], 40960), (aux[2], 40960), (aux[3], 81920)] + { + workspace.reject_alias(weight, bytes)?; + } + Ok(BatchPlan { h, key, value, aux, rows }) + } + + /// The batch launches in order: pack and projections, norms and mixing, convolution and history. + pub(super) fn batch_commands(&self, plan: &BatchPlan) -> Result> { + let mut commands = Vec::new(); + commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; + self.push_pack_projections(&mut commands, plan); + push_norms_and_mix(&mut commands, plan); + push_conv_and_history(&mut commands, plan); + Ok(commands) + } + + fn push_pack_projections(&self, commands: &mut Vec, plan: &BatchPlan) { + let (h, rows) = (&plan.h, plan.rows); + let t = rows as i32; + let pack_low = if self.mode == PleBf16Mode::HighAndLow { A::Address(h[13]) } else { A::NullAddress }; + push( + commands, + 0, + (rows * 2560).div_ceil(256) as u32, + 256, + vec![A::Address(h[0]), A::Address(h[12]), pack_low, A::I64(i64::from(t) * 2560)], + ); + for (out, n, w) in [(3, 10240, plan.key), (4, 2560, plan.value)] { + commands.push(Command::Gemm { input: h[12], weight: w, output: h[out], rows: t, n, alpha: 1.0, beta: 0.0 }); + if self.mode == PleBf16Mode::HighAndLow { + commands.push(Command::Gemm { + input: h[13], + weight: w, + output: h[out], + rows: t, + n, + alpha: 1.0, + beta: 1.0, + }); + } + scan(commands, h[out], h[14], n, t, if out == 3 { 0 } else { 1 }); + } + } + + /// Uploads the three sources and the zeroed status words, then proves the uploads landed before any launch. + pub(super) fn upload_batch(&self, h: &[BufferHandle; 15], host: &BatchHost) -> Result<()> { + let api = &self.context.driver.api; + api.copy_from(h[0], &host.e)?; + api.copy_from(h[1], &host.s)?; + api.copy_from(h[2], &host.p)?; + api.copy_from(h[14], &host.zero)?; + // Synchronous pageable H2D may return after staging before device DMA. + // The private NON_BLOCKING vendor stream has no implicit default-stream + // dependency: prove completion of real source uploads before enqueuing. + api.synchronize() + } + + /// Launches every command in order; the first failure stops the rest. + pub(super) fn launch_batch( + &self, + (blas, pack, module): (&Blas, &KernelModule, &KernelModule), + commands: &mut [Command], + ) -> Result<()> { + for command in commands { + command.launch(blas, pack, module)?; + } + Ok(()) + } +} + +fn push_norms_and_mix(commands: &mut Vec, plan: &BatchPlan) { + let (h, rows, aux) = (&plan.h, plan.rows, &plan.aux); + let t = rows as i32; + push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])]); + scan(commands, h[5], h[14], 10240, t, 2); + push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])]); + scan(commands, h[6], h[14], 10240, t, 3); + let gate = vec![A::Address(h[5]), A::Address(h[6]), A::Address(h[7]), A::F32(1.0 / 2560.0f32.sqrt())]; + push(commands, 2, (rows * 4) as u32, 512, gate); + scan(commands, h[7], h[14], 4, t, 4); + push(commands, 3, (rows * 40) as u32, 256, vec![A::Address(h[4]), A::Address(h[7]), A::Address(h[8]), A::I32(t)]); + scan(commands, h[8], h[14], 10240, t, 5); + push(commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])]); + scan(commands, h[9], h[14], 10240, t, 6); +} + +fn push_conv_and_history(commands: &mut Vec, plan: &BatchPlan) { + let (h, rows) = (&plan.h, plan.rows); + let t = rows as i32; + let conv = vec![ + A::Address(h[2]), + A::Address(h[9]), + A::Address(plan.aux[3]), + A::Address(h[1]), + A::Address(h[8]), + A::Address(h[10]), + A::I32(t), + ]; + push(commands, 4, (rows * 40) as u32, 256, conv); + scan(commands, h[10], h[14], 10240, t, 7); + push(commands, 6, (rows * 360) as u32, 256, vec![A::Address(h[2]), A::Address(h[9]), A::Address(h[11]), A::I32(t)]); + scan(commands, h[11], h[14], 92160, t, 8); + push(commands, 5, 40, 256, vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)]); + scan(commands, h[1], h[14], 10240, t, 9); +} diff --git a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs index bfe6c938..14856a89 100644 --- a/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs +++ b/crates/cuda-driver/src/ple_batch_queue/impl_plebatchqueue/impl_plebatchqueue_2_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl PleBatchQueue (2). #[allow(unused_imports)] +use super::compose_phases::BatchHost; use super::*; impl<'ctx> PleBatchQueue<'ctx> { @@ -17,142 +18,22 @@ impl<'ctx> PleBatchQueue<'ctx> { ) -> Result> { workspace.validate_context(self.context)?; let h = self.handles()?; - for (handle, bytes) in h.into_iter().zip(self.sizes) { - workspace.reject_alias(handle, bytes)?; - } - if !embedding.len().is_multiple_of(2560) { - return Err(Error::InvalidQwenShape); - } - let rows = embedding.len() / 2560; - if !(1..=self.capacity).contains(&rows) || streams.len() != rows * 10240 || history.len() != 92160 { - return Err(Error::InvalidQwenShape); - } - if embedding.iter().chain(streams).chain(history).any(|v| !v.is_finite()) { - return Err(Error::InvalidDriverValue("PLE batch source finite")); - } - let key = self.weight(weights.key, 52428800, 2)?; - let value = self.weight(weights.value, 13107200, 2)?; - let mut aux = [h[0]; 4]; - for (i, w) in weights.aux.iter().enumerate() { - aux[i] = self.weight(w, if i == 3 { 81920 } else { 40960 }, if i == 3 { 2 } else { 4 })?; - } - for (weight, bytes) in - [(key, 52428800), (value, 13107200), (aux[0], 40960), (aux[1], 40960), (aux[2], 40960), (aux[3], 81920)] - { - workspace.reject_alias(weight, bytes)?; - } - let t = rows as i32; - let mut commands = Vec::new(); - commands.try_reserve_exact(24).map_err(|_| Error::HostAllocation)?; - let pack_low = if self.mode == PleBf16Mode::HighAndLow { A::Address(h[13]) } else { A::NullAddress }; - push( - &mut commands, - 0, - (rows * 2560).div_ceil(256) as u32, - 256, - vec![A::Address(h[0]), A::Address(h[12]), pack_low, A::I64(i64::from(t) * 2560)], - ); - for (out, n, w) in [(3, 10240, key), (4, 2560, value)] { - commands.push(Command::Gemm { input: h[12], weight: w, output: h[out], rows: t, n, alpha: 1.0, beta: 0.0 }); - if self.mode == PleBf16Mode::HighAndLow { - commands.push(Command::Gemm { - input: h[13], - weight: w, - output: h[out], - rows: t, - n, - alpha: 1.0, - beta: 1.0, - }); - } - scan(&mut commands, h[out], h[14], n, t, if out == 3 { 0 } else { 1 }); - } - push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[3]), A::Address(aux[0]), A::Address(h[5])]); - scan(&mut commands, h[5], h[14], 10240, t, 2); - push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[1]), A::Address(aux[1]), A::Address(h[6])]); - scan(&mut commands, h[6], h[14], 10240, t, 3); - push( - &mut commands, - 2, - (rows * 4) as u32, - 512, - vec![A::Address(h[5]), A::Address(h[6]), A::Address(h[7]), A::F32(1.0 / 2560.0f32.sqrt())], - ); - scan(&mut commands, h[7], h[14], 4, t, 4); - push( - &mut commands, - 3, - (rows * 40) as u32, - 256, - vec![A::Address(h[4]), A::Address(h[7]), A::Address(h[8]), A::I32(t)], - ); - scan(&mut commands, h[8], h[14], 10240, t, 5); - push(&mut commands, 1, (rows * 4) as u32, 1024, vec![A::Address(h[8]), A::Address(aux[2]), A::Address(h[9])]); - scan(&mut commands, h[9], h[14], 10240, t, 6); - push( - &mut commands, - 4, - (rows * 40) as u32, - 256, - vec![ - A::Address(h[2]), - A::Address(h[9]), - A::Address(aux[3]), - A::Address(h[1]), - A::Address(h[8]), - A::Address(h[10]), - A::I32(t), - ], - ); - scan(&mut commands, h[10], h[14], 10240, t, 7); - push( - &mut commands, - 6, - (rows * 360) as u32, - 256, - vec![A::Address(h[2]), A::Address(h[9]), A::Address(h[11]), A::I32(t)], - ); - scan(&mut commands, h[11], h[14], 92160, t, 8); - push(&mut commands, 5, 40, 256, vec![A::Address(h[2]), A::Address(h[9]), A::I32(t)]); - scan(&mut commands, h[1], h[14], 10240, t, 9); - let e = float_staging(embedding)?; - let s = float_staging(streams)?; - let p = float_staging(history)?; - let zero = staging(rows * 40)?; - let mut statuses = staging(rows * 40)?; - let mut flags = Vec::new(); - flags.try_reserve_exact(rows * 10).map_err(|_| Error::HostAllocation)?; - flags.resize(rows * 10, 0); + let rows = self.check_batch_inputs(workspace, h, (embedding, streams, history))?; + let plan = self.batch_plan(workspace, &weights, h, rows)?; + let mut commands = self.batch_commands(&plan)?; + let mut host = BatchHost::new(embedding, streams, history, rows)?; let context = self.context; let guard = context.enter()?; - let mut operation = context.driver.api.copy_from(h[0], &e); - if operation.is_ok() { - operation = context.driver.api.copy_from(h[1], &s); - } - if operation.is_ok() { - operation = context.driver.api.copy_from(h[2], &p); - } - if operation.is_ok() { - operation = context.driver.api.copy_from(h[14], &zero); - } - // Synchronous pageable H2D may return after staging before device DMA. - // The private NON_BLOCKING vendor stream has no implicit default-stream - // dependency: prove completion of real source uploads before enqueuing. - if operation.is_ok() { - operation = context.driver.api.synchronize(); - } + let mut operation = self.upload_batch(&h, &host); let blas = workspace.blas()?; let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; let pack = self.pack_module.as_ref().ok_or(Error::ContextPoisoned)?; - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(blas, pack, module); + if operation.is_ok() { + operation = self.launch_batch((blas, pack, module), &mut commands); } let sync = blas.synchronize(); if operation.is_ok() && sync.is_ok() { - operation = context.driver.api.copy_to(h[14], &mut statuses); + operation = context.driver.api.copy_to(h[14], &mut host.statuses); } let all = context.driver.api.synchronize(); let pop = guard.finish(); @@ -161,20 +42,17 @@ impl<'ctx> PleBatchQueue<'ctx> { workspace.mark_failed(); } if sync.is_err() || all.is_err() || pop.is_err() { - std::mem::forget((commands, e, s, p, zero, statuses, flags, weights)); + std::mem::forget((commands, host, weights)); context.retain_driver(); return combine(combine(combine(operation, sync), all), pop) .map(|()| unreachable!("uncertain PLE batch drain")); } combine(combine(combine(operation, sync), all), pop)?; - for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { - *flag = u32::from_le_bytes(*bytes); - if *flag > 1 { - self.failed = true; - context.poisoned.set(true); - return Err(Error::InvalidDriverValue("PLE batch finite status")); - } + if !host.decode_flags() { + self.failed = true; + context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE batch finite status")); } - Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: flags.into_boxed_slice() }) + Ok(PleBatchCompletion { owner: self, rows, next: 0, flags: host.flags.into_boxed_slice() }) } } diff --git a/crates/cuda-driver/src/ple_closed_queue.rs b/crates/cuda-driver/src/ple_closed_queue.rs index f0e274e3..1c80c797 100644 --- a/crates/cuda-driver/src/ple_closed_queue.rs +++ b/crates/cuda-driver/src/ple_closed_queue.rs @@ -73,6 +73,8 @@ enum Command { #[path = "ple_closed_queue_gpu.rs"] mod gpu; +#[path = "ple_closed_queue/compose_phases.rs"] +mod compose_phases; #[path = "ple_closed_queue/impl_pleclosedcompletion.rs"] mod impl_pleclosedcompletion; #[path = "ple_closed_queue/impl_pleclosedqueue_2.rs"] diff --git a/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs b/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs new file mode 100644 index 00000000..5cce9455 --- /dev/null +++ b/crates/cuda-driver/src/ple_closed_queue/compose_phases.rs @@ -0,0 +1,190 @@ +//! STRA-338 size: the phases of `PleClosedQueue::compose`, extracted in command order. + +#[allow(unused_imports)] +use super::*; + +/// Host buffers one compose stages its uploads in and reads its results back into. +pub(super) struct ComposeHost { + pub(super) embedding_bytes: Vec, + pub(super) streams_bytes: Vec, + pub(super) history_bytes: Vec, + pub(super) statuses: Vec, + pub(super) streams_out: Vec, + pub(super) history_out: Vec, + pub(super) streams_values: Vec, + pub(super) history_values: Vec, +} + +impl ComposeHost { + pub(super) fn new(embedding: &[f32], streams: &[f32], history: &[f32]) -> Result { + Ok(Self { + embedding_bytes: float_staging(embedding)?, + streams_bytes: float_staging(streams)?, + history_bytes: float_staging(history)?, + statuses: staging(40)?, + streams_out: staging(40960)?, + history_out: staging(368640)?, + streams_values: float_owner(10240)?, + history_values: float_owner(92160)?, + }) + } + + /// Decodes the drained status words and result rows; a status above 1 is a failed finite check. + pub(super) fn decode_flags(&mut self) -> Option<[u32; 10]> { + let mut flags = [0; 10]; + for (flag, bytes) in flags.iter_mut().zip(self.statuses.as_chunks::<4>().0) { + *flag = u32::from_le_bytes(*bytes); + if *flag > 1 { + return None; + } + } + for (value, bytes) in self.streams_values.iter_mut().zip(self.streams_out.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + for (value, bytes) in self.history_values.iter_mut().zip(self.history_out.as_chunks::<4>().0) { + *value = f32::from_le_bytes(*bytes); + } + Some(flags) + } +} + +impl<'ctx> PleClosedQueue<'ctx> { + /// Checks the source lengths and finiteness, then every weight's size and alignment. + pub(super) fn check_compose_inputs( + &self, + weights: &PleClosedWeights<'_, '_>, + (embedding, streams, history): (&[f32], &[f32], &[f32]), + ) -> Result<()> { + for (values, words) in [(embedding, 2560), (streams, 10240), (history, 92160)] { + if values.len() != words { + return Err(Error::InvalidQwenShape); + } + if values.iter().any(|v| !v.is_finite()) { + return Err(Error::InvalidDriverValue("PLE finite source")); + } + } + self.weight(weights.key, 52_428_800, 2)?; + self.weight(weights.value, 13_107_200, 2)?; + for weight in weights.aux.iter().take(3) { + self.weight(weight, 40960, 4)?; + } + self.weight(weights.aux[3], 81920, 2) + } + + /// The nineteen launches of one compose: both BF16 projections, the norms, gate, broadcast, conv and residual. + pub(super) fn compose_commands(&self, weights: &PleClosedWeights<'_, '_>) -> Result> { + let mut commands = Vec::new(); + commands.try_reserve_exact(19).map_err(|_| Error::HostAllocation)?; + self.push_projections(&mut commands, weights)?; + self.push_norms(&mut commands, weights)?; + self.push_mix(&mut commands)?; + self.push_late_norm(&mut commands, weights)?; + self.push_conv(&mut commands, weights)?; + self.push_residual(&mut commands)?; + Ok(commands) + } + + fn push_projections(&self, commands: &mut Vec, weights: &PleClosedWeights<'_, '_>) -> Result<()> { + self.qwen( + commands, + Operation::Bf16, + &[weights.key, self.buffer(0)?, self.buffer(3)?], + qwen_ffi::bf16_layout(10240, 2560)?, + )?; + self.scan(commands, 0)?; + self.qwen( + commands, + Operation::Bf16, + &[weights.value, self.buffer(0)?, self.buffer(4)?], + qwen_ffi::bf16_layout(2560, 2560)?, + )?; + self.scan(commands, 1) + } + + fn push_norms(&self, commands: &mut Vec, weights: &PleClosedWeights<'_, '_>) -> Result<()> { + self.qwen( + commands, + Operation::PleNorm, + &[self.buffer(3)?, weights.aux[0], self.buffer(5)?], + Operation::PleNorm.layout(), + )?; + self.scan(commands, 2)?; + self.qwen( + commands, + Operation::PleNorm, + &[self.buffer(1)?, weights.aux[1], self.buffer(6)?], + Operation::PleNorm.layout(), + )?; + self.scan(commands, 3) + } + + fn push_mix(&self, commands: &mut Vec) -> Result<()> { + self.qwen( + commands, + Operation::PleGate, + &[self.buffer(5)?, self.buffer(6)?, self.buffer(7)?], + Operation::PleGate.layout(), + )?; + self.scan(commands, 4)?; + self.qwen( + commands, + Operation::PleBroadcast, + &[self.buffer(4)?, self.buffer(7)?, self.buffer(8)?], + Operation::PleBroadcast.layout(), + )?; + self.scan(commands, 5) + } + + fn push_late_norm(&self, commands: &mut Vec, weights: &PleClosedWeights<'_, '_>) -> Result<()> { + self.qwen( + commands, + Operation::PleNorm, + &[self.buffer(8)?, weights.aux[2], self.buffer(9)?], + Operation::PleNorm.layout(), + )?; + self.scan(commands, 6) + } + + fn push_conv(&self, commands: &mut Vec, weights: &PleClosedWeights<'_, '_>) -> Result<()> { + self.qwen( + commands, + Operation::PleConv, + &[self.buffer(2)?, self.buffer(9)?, weights.aux[3], self.buffer(10)?, self.buffer(11)?], + Operation::PleConv.layout(), + )?; + self.scan(commands, 7)?; + self.scan(commands, 8) + } + + fn push_residual(&self, commands: &mut Vec) -> Result<()> { + self.qwen( + commands, + Operation::PleResidual, + &[self.buffer(1)?, self.buffer(8)?, self.buffer(10)?, self.buffer(12)?], + Operation::PleResidual.layout(), + )?; + self.scan(commands, 9) + } + + /// Uploads the sources, resets the finite flags, launches every command and downloads status, streams and + /// history; the first failure stops the rest. + pub(super) fn drain_ops( + &self, + handles: &[ffi::BufferHandle; 14], + commands: &mut [Command], + reset: &mut ffi::MmqResidentArguments, + host: &mut ComposeHost, + ) -> Result<()> { + let context = self.context; + context.driver.api.copy_from(handles[0], &host.embedding_bytes)?; + context.driver.api.copy_from(handles[1], &host.streams_bytes)?; + context.driver.api.copy_from(handles[2], &host.history_bytes)?; + context.driver.api.launch_mmq_resident(self.finite.ok_or(Error::ContextPoisoned)?[0], 10, reset)?; + for command in commands { + command.launch(context)?; + } + context.driver.api.copy_to(handles[13], &mut host.statuses)?; + context.driver.api.copy_to(handles[12], &mut host.streams_out)?; + context.driver.api.copy_to(handles[11], &mut host.history_out) + } +} diff --git a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs index 0e437505..c6ef160e 100644 --- a/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs +++ b/crates/cuda-driver/src/ple_closed_queue/impl_pleclosedqueue_2.rs @@ -1,6 +1,7 @@ //! Moved out of the parent module by STRA-338: impl PleClosedQueue (2), impl Drop_for_PleClosedQueue, fn staging, fn float_staging. #[allow(unused_imports)] +use super::compose_phases::ComposeHost; use super::*; impl<'ctx> PleClosedQueue<'ctx> { @@ -14,123 +15,13 @@ impl<'ctx> PleClosedQueue<'ctx> { history: &[f32], ) -> Result> { let handles = self.handles()?; - for (values, words) in [(embedding, 2560), (streams, 10240), (history, 92160)] { - if values.len() != words { - return Err(Error::InvalidQwenShape); - } - if values.iter().any(|v| !v.is_finite()) { - return Err(Error::InvalidDriverValue("PLE finite source")); - } - } - self.weight(weights.key, 52_428_800, 2)?; - self.weight(weights.value, 13_107_200, 2)?; - for weight in weights.aux.iter().take(3) { - self.weight(weight, 40960, 4)?; - } - self.weight(weights.aux[3], 81920, 2)?; - let mut commands = Vec::new(); - commands.try_reserve_exact(19).map_err(|_| Error::HostAllocation)?; - self.qwen( - &mut commands, - Operation::Bf16, - &[weights.key, self.buffer(0)?, self.buffer(3)?], - qwen_ffi::bf16_layout(10240, 2560)?, - )?; - self.scan(&mut commands, 0)?; - self.qwen( - &mut commands, - Operation::Bf16, - &[weights.value, self.buffer(0)?, self.buffer(4)?], - qwen_ffi::bf16_layout(2560, 2560)?, - )?; - self.scan(&mut commands, 1)?; - self.qwen( - &mut commands, - Operation::PleNorm, - &[self.buffer(3)?, weights.aux[0], self.buffer(5)?], - Operation::PleNorm.layout(), - )?; - self.scan(&mut commands, 2)?; - self.qwen( - &mut commands, - Operation::PleNorm, - &[self.buffer(1)?, weights.aux[1], self.buffer(6)?], - Operation::PleNorm.layout(), - )?; - self.scan(&mut commands, 3)?; - self.qwen( - &mut commands, - Operation::PleGate, - &[self.buffer(5)?, self.buffer(6)?, self.buffer(7)?], - Operation::PleGate.layout(), - )?; - self.scan(&mut commands, 4)?; - self.qwen( - &mut commands, - Operation::PleBroadcast, - &[self.buffer(4)?, self.buffer(7)?, self.buffer(8)?], - Operation::PleBroadcast.layout(), - )?; - self.scan(&mut commands, 5)?; - self.qwen( - &mut commands, - Operation::PleNorm, - &[self.buffer(8)?, weights.aux[2], self.buffer(9)?], - Operation::PleNorm.layout(), - )?; - self.scan(&mut commands, 6)?; - self.qwen( - &mut commands, - Operation::PleConv, - &[self.buffer(2)?, self.buffer(9)?, weights.aux[3], self.buffer(10)?, self.buffer(11)?], - Operation::PleConv.layout(), - )?; - self.scan(&mut commands, 7)?; - self.scan(&mut commands, 8)?; - self.qwen( - &mut commands, - Operation::PleResidual, - &[self.buffer(1)?, self.buffer(8)?, self.buffer(10)?, self.buffer(12)?], - Operation::PleResidual.layout(), - )?; - self.scan(&mut commands, 9)?; - let mut embedding_bytes = float_staging(embedding)?; - let mut streams_bytes = float_staging(streams)?; - let mut history_bytes = float_staging(history)?; - let mut statuses = staging(40)?; - let mut streams_out = staging(40960)?; - let mut history_out = staging(368640)?; - let mut streams_values = float_owner(10240)?; - let mut history_values = float_owner(92160)?; + self.check_compose_inputs(&weights, (embedding, streams, history))?; + let mut commands = self.compose_commands(&weights)?; + let mut host = ComposeHost::new(embedding, streams, history)?; let mut reset = ffi::MmqResidentArguments::zero(handles[13], 10); let context = self.context; let guard = context.enter()?; - let mut operation = context.driver.api.copy_from(handles[0], &embedding_bytes); - if operation.is_ok() { - operation = context.driver.api.copy_from(handles[1], &streams_bytes); - } - if operation.is_ok() { - operation = context.driver.api.copy_from(handles[2], &history_bytes); - } - if operation.is_ok() { - operation = - context.driver.api.launch_mmq_resident(self.finite.ok_or(Error::ContextPoisoned)?[0], 10, &mut reset); - } - for command in &mut commands { - if operation.is_err() { - break; - } - operation = command.launch(context); - } - if operation.is_ok() { - operation = context.driver.api.copy_to(handles[13], &mut statuses); - } - if operation.is_ok() { - operation = context.driver.api.copy_to(handles[12], &mut streams_out); - } - if operation.is_ok() { - operation = context.driver.api.copy_to(handles[11], &mut history_out); - } + let operation = self.drain_ops(&handles, &mut commands, &mut reset, &mut host); let sync = context.driver.api.synchronize(); let pop = guard.finish(); if operation.is_err() || sync.is_err() || pop.is_err() { @@ -138,47 +29,25 @@ impl<'ctx> PleClosedQueue<'ctx> { context.poisoned.set(true); } if sync.is_err() || pop.is_err() { - std::mem::forget(( - commands, - reset, - embedding_bytes, - streams_bytes, - history_bytes, - statuses, - streams_out, - history_out, - streams_values, - history_values, - weights, - )); + std::mem::forget((commands, reset, host, weights)); context.retain_driver(); return combine(combine(operation, sync), pop).map(|()| unreachable!("uncertain PLE drain")); } combine(combine(operation, sync), pop)?; - let mut flags = [0; 10]; - for (flag, bytes) in flags.iter_mut().zip(statuses.as_chunks::<4>().0) { - *flag = u32::from_le_bytes(*bytes); - if *flag > 1 { - self.failed = true; - context.poisoned.set(true); - return Err(Error::InvalidDriverValue("PLE finite status")); - } - } - for (value, bytes) in streams_values.iter_mut().zip(streams_out.as_chunks::<4>().0) { - *value = f32::from_le_bytes(*bytes); - } - for (value, bytes) in history_values.iter_mut().zip(history_out.as_chunks::<4>().0) { - *value = f32::from_le_bytes(*bytes); - } + let Some(flags) = host.decode_flags() else { + self.failed = true; + context.poisoned.set(true); + return Err(Error::InvalidDriverValue("PLE finite status")); + }; // Staging is no longer exposed or used once the actual completion drains. - embedding_bytes.clear(); - streams_bytes.clear(); - history_bytes.clear(); + host.embedding_bytes.clear(); + host.streams_bytes.clear(); + host.history_bytes.clear(); Ok(PleClosedCompletion { owner: self, flags, - streams: streams_values.into_boxed_slice(), - history: history_values.into_boxed_slice(), + streams: host.streams_values.into_boxed_slice(), + history: host.history_values.into_boxed_slice(), }) } pub fn close(mut self) -> Result<()> { diff --git a/crates/cuda-driver/src/qsa_prompt_device_index.rs b/crates/cuda-driver/src/qsa_prompt_device_index.rs index 09e78c26..8a1a7891 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_index.rs @@ -1,4 +1,5 @@ //! Private real-arena continuation of the exact old prompt program. +use super::run_phases::{HostStaging, run_theta, step_bytes}; use super::*; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { #[allow(clippy::too_many_arguments)] @@ -19,337 +20,25 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ) -> Result<()> { let n = t as usize; let p = p0 as usize; - let end = p + n; - let nb = end / 4; - if !pooled.is_empty() { - self.upload(0, pooled)?; - } - // The current spare is genuine prior state even when this batch completes no block. - let spare = encode(dead)?; - let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare); - if result.is_err() { - self.failed = true; - } - result?; - self.upload(1, tail)?; - self.upload(2, dead)?; - let mut steps = Vec::new(); - steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; - for row in 0..n { - let pos = p + row; - for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { - steps.extend((x as i32).to_le_bytes()); - } - } - let zero = vec![0u8; 64]; - let mut flags = vec![0u8; 64]; + self.upload_run_state(p, pooled, tail, dead)?; + let steps = step_bytes(p, n)?; let status = self.handle(10, 64)?; let mut commands: Vec<(Launch, Arguments)> = Vec::new(); commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; - let mut push = |shape, args| -> Result<()> { - commands.push((shape, Arguments::for_launch(shape, args)?)); - Ok(()) + let theta = run_theta()?; + let (decode_positions, positions) = if decode { + let (words, span) = self.decode_position_words(p0, n)?; + (words, Some(span)) + } else { + (Vec::new(), None) }; - let theta = crate::qsa_index_ffi::theta(); - if !theta.is_finite() || theta <= 0.0 { - return Err(Error::InvalidDriverValue("QSA theta")); - } - let mut decode_positions = Vec::new(); - let positions = if decode { - decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; - for _ in 0..24 { - decode_positions.extend((p0 as i32).to_le_bytes()); - } - let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; - let full = self.handle(4, self.sizes[4])?; - let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; - h.validate_projection_extent(24 * 4, 4)?; - if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { - return Err(Error::OutputAliasesInput); - } - Some(h) - } else { - None - }; - let k_h = out[0]; - let pooled_h = self.handle(0, self.sizes[0])?; - let tail_h = self.handle(1, self.sizes[1])?; - let dead_h = self.handle(2, self.sizes[2])?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(2), - vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(2), - vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)], - )?; - } else { - push( - Launch::Rms(t * 2), - vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 2), - vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 512) as u32), - vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)], - )?; - push(Launch::Split((n * 6144) as u32), vec![A::Address(qfull_h), A::Address(out[2]), A::I64(t as i64)])?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(24), - vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(24), - vec![ - A::Address(out[2]), - A::Address(out[2]), - A::I32(24), - A::I32(256), - A::F32(theta), - A::Address(positions), - ], - )?; - } else { - push( - Launch::Rms(t * 24), - vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 24), - vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 6144) as u32), - vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)], - )?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(4), - vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(4), - vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)], - )?; - } else { - push( - Launch::Rms(t * 4), - vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 4), - vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 512) as u32), - vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)], - )?; - if decode { - push( - Launch::DecodeAppend, - vec![ - A::Address(raw_h), - A::Address(out[4]), - A::I32(0), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(tail_h), - A::Address(dead_h), - A::Address(pooled_h), - A::Address(self.handle(3, 4)?), - A::I32(crate::serving_context::geometry().cells() as i32), - A::F32(theta), - ], - )?; - } else { - if p == 0 { - push( - Launch::First, - vec![ - A::Address(raw_h), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(dead_h), - A::Address(pooled_h), - A::F32(theta), - ], - )?; - } - let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; - let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; - if let Some(hi) = hi.filter(|hi| *hi >= first) { - push( - Launch::Blocks((hi - first + 1) as u32), - vec![ - A::Address(raw_h), - A::I64(t as i64), - A::I64(p0 as i64), - A::I32(0), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(tail_h), - A::Address(dead_h), - A::Address(pooled_h), - A::Address(self.handle(3, 4)?), - A::I64(first as i64), - A::I64(hi as i64), - A::F32(theta), - ], - )?; - } - push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?; - } - for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] { - push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?; - } - // Original prompt selection reuses one 256-row score tile. Every - // offset is checked against the actual whole producer allocation. - let tile_rows = if decode { 1 } else { n.min(256) }; - let scores = self.handle(9, tile_rows * max_blocks() * 4)?; - for first_row in (0..n).step_by(256) { - let count = (n - first_row).min(256); - let ct = count as u32; - let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?; - let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?; - let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?; - let tile_reach = (p + first_row + count) / 4 + 1; - if decode { - push( - Launch::DecodeScores, - vec![ - A::Address(pooled_h), - A::Address(dead_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I32(1), - A::I64(max_blocks() as i64), - A::Address(scores), - ], - )?; - } else { - push( - Launch::Tc { t: ct, reach: tile_reach as u32 }, - vec![ - A::Address(pooled_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I64(count as i64), - A::I64(max_blocks() as i64), - A::I64(tile_reach as i64), - A::Address(scores), - ], - )?; - push( - Launch::ScoreTail(ct), - vec![ - A::Address(dead_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I64(max_blocks() as i64), - A::Address(scores), - ], - )?; - } - push( - Launch::ScoreScan((count * max_blocks()) as u32), - vec![ - A::Address(scores), - A::Address(steps_tile), - A::I32(count as i32), - A::I64(max_blocks() as i64), - A::Address(status), - A::U32(4), - ], - )?; - push( - Launch::Topk(ct), - vec![ - A::Address(scores), - A::Address(steps_tile), - A::I64(max_blocks() as i64), - A::I64(CAP as i64), - A::Address(ids_tile), - ], - )?; - } - push(Launch::Round((n * 128) as u32), vec![A::Address(raw_h), A::I64((n * 128) as i64)])?; - push( - Launch::Scan((n * 128) as u32), - vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)], - )?; - let context = self.context; - let blas = ws.blas()?; - let guard = match context.enter() { - Ok(guard) => guard, - Err(error) => { - self.failed = true; - ws.mark_failed(); - context.poison(); - context.retain_driver(); - return Err(error); - } - }; - let operation = (|| { - context.driver.api.copy_from(status, &zero)?; - context.driver.api.copy_from(out[4], &steps)?; - if let Some(positions) = positions { - context.driver.api.copy_from(positions, &decode_positions)?; - } - // Pageable uploads/status have a real dependency before the nonblocking shared stream. - context.driver.api.synchronize()?; - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - for (shape, args) in &mut commands { - module.launch(*shape, blas.stream(), args)?; - } - Ok(()) - })(); - let sync = blas.synchronize(); - let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; - let pop = guard.finish(); - if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { - self.failed = true; - ws.mark_failed(); - context.poison(); - context.retain_driver(); - std::mem::forget((commands, steps, zero, flags, decode_positions)); - return combine(combine(combine(operation, sync), read), pop); - } - combine(combine(combine(operation, sync), read), pop)?; - for flag in flags.as_chunks::<4>().0 { - if u32::from_le_bytes(*flag) > 1 { - self.failed = true; - return Err(Error::InvalidDriverValue("QSA finite status")); - } - } - if flags[24..].iter().any(|x| *x != 0) { - self.failed = true; - return Err(Error::InvalidDriverValue("QSA unused status")); - } - if flags[..24].iter().any(|x| *x != 0) { - return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); - } - let ids = self.read(out[3], n * CAP * 4)?; - for row in 0..n { - let width = (p + row + 1).min(CAP); - let mut last = None; - for i in 0..width { - let at = (row * CAP + i) * 4; - let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?); - if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) { - return Err(Error::InvalidDriverValue("QSA selected IDs")); - } - last = Some(id); - } - } - Ok(()) + let plan = self.arena_plan((t, p0, decode), (raw_h, iq_h, out[0]), status, (positions, theta))?; + self.push_run_commands(&mut commands, &plan, Some(qfull_h), gamma, out)?; + let mut host = + HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv: None, decode_positions }; + self.execute_run(&plan, out, ws, &mut host)?; + self.check_run_flags(&host.flags)?; + self.check_selected_ids(out[3], p, n) } pub(super) fn final_state_original_arena( &mut self, diff --git a/crates/cuda-driver/src/qsa_prompt_index.rs b/crates/cuda-driver/src/qsa_prompt_index.rs index 26061d2a..f8132f97 100644 --- a/crates/cuda-driver/src/qsa_prompt_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_index.rs @@ -83,3 +83,5 @@ mod impl_qsapromptindexworkspace; mod impl_qsapromptindexworkspace_2; mod impl_qsapromptindexworkspace_3; mod impl_qsapromptindexworkspace_4; +mod run_launches; +mod run_phases; diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs index c12fdc1f..cbf5f0f7 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_3.rs @@ -1,5 +1,6 @@ //! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (3). +use super::run_phases::{HostStaging, RunPlan, run_theta, step_bytes}; #[allow(unused_imports)] use super::*; @@ -24,348 +25,55 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ) -> Result<()> { let n = t as usize; let p = p0 as usize; - let end = p + n; - let nb = end / 4; - if !pooled.is_empty() { - self.upload(0, pooled)?; - } - // The current spare is genuine prior state even when this batch completes no block. - let spare = encode(dead)?; - let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare); - if result.is_err() { - self.failed = true; - } - result?; - self.upload(1, tail)?; - self.upload(2, dead)?; - for (i, x) in [(4, raw), (7, qfull), (8, iq)] { - self.upload(i, x)?; - } - let mut steps = Vec::new(); - steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; - for row in 0..n { - let pos = p + row; - for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { - steps.extend((x as i32).to_le_bytes()); - } - } - let zero = vec![0u8; 64]; - let mut flags = vec![0u8; 64]; + self.upload_run_inputs(p, pooled, tail, dead, raw, qfull, iq)?; + let steps = step_bytes(p, n)?; let status = self.handle(10, 64)?; let mut commands: Vec<(Launch, Arguments)> = Vec::new(); commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; - let mut push = |shape, args| -> Result<()> { - commands.push((shape, Arguments::for_launch(shape, args)?)); - Ok(()) + let theta = run_theta()?; + let (decode_positions, positions) = if decode { + let (words, span) = self.decode_position_words(p0, n)?; + (words, Some(span)) + } else { + (Vec::new(), None) }; - let theta = crate::qsa_index_ffi::theta(); - if !theta.is_finite() || theta <= 0.0 { - return Err(Error::InvalidDriverValue("QSA theta")); - } - let mut decode_positions = Vec::new(); - let positions = if decode { - decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; - for _ in 0..24 { - decode_positions.extend((p0 as i32).to_le_bytes()); - } - let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; - let full = self.handle(4, self.sizes[4])?; - let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; - h.validate_projection_extent(24 * 4, 4)?; - if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { - return Err(Error::OutputAliasesInput); - } - Some(h) - } else { - None - }; - let raw_h = self.handle(4, n * 128 * 4)?; - let k_h = out[0]; - let iq_h = self.handle(8, n * 512 * 4)?; - let pooled_h = self.handle(0, self.sizes[0])?; - let tail_h = self.handle(1, self.sizes[1])?; - let dead_h = self.handle(2, self.sizes[2])?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(2), - vec![A::Address(k_h), A::Address(gamma[1]), A::Address(k_h), A::I32(256), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(2), - vec![A::Address(k_h), A::Address(k_h), A::I32(2), A::I32(256), A::F32(theta), A::Address(positions)], - )?; - } else { - push( - Launch::Rms(t * 2), - vec![A::Address(k_h), A::Address(gamma[1]), A::I64(256), A::I64(256), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 2), - vec![A::Address(k_h), A::I64(2), A::I64(256), A::I64(512), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 512) as u32), - vec![A::Address(k_h), A::I64((n * 512) as i64), A::Address(status), A::U32(0)], - )?; - push( - Launch::Split((n * 6144) as u32), - vec![A::Address(self.handle(7, n * 12288 * 4)?), A::Address(out[2]), A::I64(t as i64)], - )?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(24), - vec![A::Address(out[2]), A::Address(gamma[0]), A::Address(out[2]), A::I32(256), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(24), - vec![ - A::Address(out[2]), - A::Address(out[2]), - A::I32(24), - A::I32(256), - A::F32(theta), - A::Address(positions), - ], - )?; - } else { - push( - Launch::Rms(t * 24), - vec![A::Address(out[2]), A::Address(gamma[0]), A::I64(256), A::I64(256), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 24), - vec![A::Address(out[2]), A::I64(24), A::I64(256), A::I64(6144), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 6144) as u32), - vec![A::Address(out[2]), A::I64((n * 6144) as i64), A::Address(status), A::U32(1)], - )?; - if let Some(positions) = positions { - push( - Launch::DecodeRms(4), - vec![A::Address(iq_h), A::Address(gamma[2]), A::Address(iq_h), A::I32(128), A::F32(1e-6)], - )?; - push( - Launch::DecodeRope(4), - vec![A::Address(iq_h), A::Address(iq_h), A::I32(4), A::I32(128), A::F32(theta), A::Address(positions)], - )?; - } else { - push( - Launch::Rms(t * 4), - vec![A::Address(iq_h), A::Address(gamma[2]), A::I64(128), A::I64(128), A::F32(1e-6)], - )?; - push( - Launch::Rope(t * 4), - vec![A::Address(iq_h), A::I64(4), A::I64(128), A::I64(512), A::I64(p0 as i64), A::F32(theta)], - )?; - } - push( - Launch::Scan((n * 512) as u32), - vec![A::Address(iq_h), A::I64((n * 512) as i64), A::Address(status), A::U32(2)], - )?; - if decode { - push( - Launch::DecodeAppend, - vec![ - A::Address(raw_h), - A::Address(out[4]), - A::I32(0), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(tail_h), - A::Address(dead_h), - A::Address(pooled_h), - A::Address(self.handle(3, 4)?), - A::I32(crate::serving_context::geometry().cells() as i32), - A::F32(theta), - ], - )?; - } else { - if p == 0 { - push( - Launch::First, - vec![ - A::Address(raw_h), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(dead_h), - A::Address(pooled_h), - A::F32(theta), - ], - )?; - } - let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; - let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; - if let Some(hi) = hi.filter(|hi| *hi >= first) { - push( - Launch::Blocks((hi - first + 1) as u32), - vec![ - A::Address(raw_h), - A::I64(t as i64), - A::I64(p0 as i64), - A::I32(0), - A::Address(gamma[3]), - A::F32(1e-6), - A::Address(tail_h), - A::Address(dead_h), - A::Address(pooled_h), - A::Address(self.handle(3, 4)?), - A::I64(first as i64), - A::I64(hi as i64), - A::F32(theta), - ], - )?; - } - push(Launch::Tail, vec![A::Address(raw_h), A::I64(t as i64), A::I64(p0 as i64), A::Address(tail_h)])?; - } - for (h, count) in [(pooled_h, (nb + 1) * 128), (tail_h, 384), (dead_h, 128)] { - push(Launch::Scan(count as u32), vec![A::Address(h), A::I64(count as i64), A::Address(status), A::U32(3)])?; - } - // Original prompt selection reuses one 256-row score tile. Every - // offset is checked against the actual whole producer allocation. - let tile_rows = if decode { 1 } else { n.min(256) }; - let scores = self.handle(9, tile_rows * max_blocks() * 4)?; - for first_row in (0..n).step_by(256) { - let count = (n - first_row).min(256); - let ct = count as u32; - let iq_tile = iq_h.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?; - let steps_tile = out[4].checked_subspan(n * 16, first_row * 16, count * 16)?; - let ids_tile = out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?; - let tile_reach = (p + first_row + count) / 4 + 1; - if decode { - push( - Launch::DecodeScores, - vec![ - A::Address(pooled_h), - A::Address(dead_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I32(1), - A::I64(max_blocks() as i64), - A::Address(scores), - ], - )?; - } else { - push( - Launch::Tc { t: ct, reach: tile_reach as u32 }, - vec![ - A::Address(pooled_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I64(count as i64), - A::I64(max_blocks() as i64), - A::I64(tile_reach as i64), - A::Address(scores), - ], - )?; - push( - Launch::ScoreTail(ct), - vec![ - A::Address(dead_h), - A::Address(iq_tile), - A::Address(steps_tile), - A::I64(max_blocks() as i64), - A::Address(scores), - ], - )?; - } - push( - Launch::ScoreScan((count * max_blocks()) as u32), - vec![ - A::Address(scores), - A::Address(steps_tile), - A::I32(count as i32), - A::I64(max_blocks() as i64), - A::Address(status), - A::U32(4), - ], - )?; - push( - Launch::Topk(ct), - vec![ - A::Address(scores), - A::Address(steps_tile), - A::I64(max_blocks() as i64), - A::I64(CAP as i64), - A::Address(ids_tile), - ], - )?; - } - push(Launch::Round((n * 128) as u32), vec![A::Address(raw_h), A::I64((n * 128) as i64)])?; - push( - Launch::Scan((n * 128) as u32), - vec![A::Address(raw_h), A::I64((n * 128) as i64), A::Address(status), A::U32(5)], - )?; + let plan = self.run_plan((t, p0, decode), out[0], status, (positions, theta))?; + self.push_run_commands(&mut commands, &plan, None, gamma, out)?; let k_bytes = encode(k)?; let v_bytes = encode(v)?; + let kv = Some([k_bytes, v_bytes]); + let mut host = HostStaging { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv, decode_positions }; + self.execute_run(&plan, out, ws, &mut host)?; + self.check_run_flags(&host.flags)?; + self.check_selected_ids(out[3], p, n) + } + + /// Runs the staged copies and launches under the context guard, then reads the status words back. + pub(super) fn execute_run( + &mut self, + plan: &RunPlan, + out: [ffi::BufferHandle; 5], + ws: &mut NativeBatchWorkspace<'ctx>, + host: &mut HostStaging, + ) -> Result<()> { let context = self.context; let blas = ws.blas()?; let guard = match context.enter() { Ok(guard) => guard, Err(error) => { - self.failed = true; - ws.mark_failed(); - context.poison(); - context.retain_driver(); + self.fail_run(ws); return Err(error); } }; - let operation = (|| { - context.driver.api.copy_from(status, &zero)?; - context.driver.api.copy_from(out[4], &steps)?; - context.driver.api.copy_from(out[0], &k_bytes)?; - context.driver.api.copy_from(out[1], &v_bytes)?; - if let Some(positions) = positions { - context.driver.api.copy_from(positions, &decode_positions)?; - } - // Pageable uploads/status have a real dependency before the nonblocking shared stream. - context.driver.api.synchronize()?; - let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; - for (shape, args) in &mut commands { - module.launch(*shape, blas.stream(), args)?; - } - Ok(()) - })(); + let operation = self.submit_run(blas, plan, out, host); let sync = blas.synchronize(); - let read = if sync.is_ok() { context.driver.api.copy_to(status, &mut flags) } else { Ok(()) }; + let read = if sync.is_ok() { context.driver.api.copy_to(plan.status, &mut host.flags) } else { Ok(()) }; let pop = guard.finish(); if operation.is_err() || sync.is_err() || read.is_err() || pop.is_err() { - self.failed = true; - ws.mark_failed(); - context.poison(); - context.retain_driver(); - std::mem::forget((commands, steps, zero, flags, k_bytes, v_bytes, decode_positions)); + self.fail_run(ws); + std::mem::forget(std::mem::take(host)); return combine(combine(combine(operation, sync), read), pop); } - combine(combine(combine(operation, sync), read), pop)?; - for flag in flags.as_chunks::<4>().0 { - if u32::from_le_bytes(*flag) > 1 { - self.failed = true; - return Err(Error::InvalidDriverValue("QSA finite status")); - } - } - if flags[24..].iter().any(|x| *x != 0) { - self.failed = true; - return Err(Error::InvalidDriverValue("QSA unused status")); - } - if flags[..24].iter().any(|x| *x != 0) { - return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); - } - let ids = self.read(out[3], n * CAP * 4)?; - for row in 0..n { - let width = (p + row + 1).min(CAP); - let mut last = None; - for i in 0..width { - let at = (row * CAP + i) * 4; - let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?); - if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) { - return Err(Error::InvalidDriverValue("QSA selected IDs")); - } - last = Some(id); - } - } - Ok(()) + combine(combine(combine(operation, sync), read), pop) } } diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs b/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs new file mode 100644 index 00000000..d2a46249 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/run_launches.rs @@ -0,0 +1,267 @@ +//! STRA-338 size: the launch builders of `QsaPromptIndexWorkspace::run`, one function per phase. + +use super::run_phases::{Commands, RunPlan, push_launch}; +#[allow(unused_imports)] +use super::*; + +struct ScoreTile { + count: usize, + reach: usize, + iq: ffi::BufferHandle, + steps: ffi::BufferHandle, + ids: ffi::BufferHandle, +} + +pub(super) fn push_scan( + commands: &mut Commands, + plan: &RunPlan, + buf: ffi::BufferHandle, + count: usize, + which: u32, +) -> Result<()> { + push_launch( + commands, + Launch::Scan(count as u32), + vec![A::Address(buf), A::I64(count as i64), A::Address(plan.status), A::U32(which)], + ) +} + +pub(super) fn push_norm_rope( + commands: &mut Commands, + plan: &RunPlan, + bufs: (ffi::BufferHandle, ffi::BufferHandle), + shape: (u32, i32, i64), +) -> Result<()> { + match plan.positions { + Some(positions) => push_decode_norm_rope(commands, plan, positions, bufs, shape), + None => push_prompt_norm_rope(commands, plan, bufs, shape), + } +} + +fn push_decode_norm_rope( + commands: &mut Commands, + plan: &RunPlan, + positions: ffi::BufferHandle, + (buf, gamma): (ffi::BufferHandle, ffi::BufferHandle), + (heads, dim, _): (u32, i32, i64), +) -> Result<()> { + let rms = vec![A::Address(buf), A::Address(gamma), A::Address(buf), A::I32(dim), A::F32(1e-6)]; + push_launch(commands, Launch::DecodeRms(heads), rms)?; + let rope = vec![ + A::Address(buf), + A::Address(buf), + A::I32(heads as i32), + A::I32(dim), + A::F32(plan.theta), + A::Address(positions), + ]; + push_launch(commands, Launch::DecodeRope(heads), rope) +} + +fn push_prompt_norm_rope( + commands: &mut Commands, + plan: &RunPlan, + (buf, gamma): (ffi::BufferHandle, ffi::BufferHandle), + (heads, dim, stride): (u32, i32, i64), +) -> Result<()> { + let rms = vec![A::Address(buf), A::Address(gamma), A::I64(dim as i64), A::I64(dim as i64), A::F32(1e-6)]; + push_launch(commands, Launch::Rms(plan.t * heads), rms)?; + let rope = vec![ + A::Address(buf), + A::I64(heads as i64), + A::I64(dim as i64), + A::I64(stride), + A::I64(plan.p0 as i64), + A::F32(plan.theta), + ]; + push_launch(commands, Launch::Rope(plan.t * heads), rope) +} + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + pub(super) fn push_pool( + &self, + commands: &mut Commands, + plan: &RunPlan, + gamma: ffi::BufferHandle, + out4: ffi::BufferHandle, + ) -> Result<()> { + if plan.decode { + self.push_pool_decode(commands, plan, gamma, out4)?; + } else { + self.push_pool_prompt(commands, plan, gamma)?; + } + let nb = (plan.p0 as usize + plan.t as usize) / 4; + for (h, count) in [(plan.pooled, (nb + 1) * 128), (plan.tail, 384), (plan.dead, 128)] { + push_scan(commands, plan, h, count, 3)?; + } + Ok(()) + } + + fn push_pool_decode( + &self, + commands: &mut Commands, + plan: &RunPlan, + gamma: ffi::BufferHandle, + out4: ffi::BufferHandle, + ) -> Result<()> { + let args = vec![ + A::Address(plan.raw), + A::Address(out4), + A::I32(0), + A::Address(gamma), + A::F32(1e-6), + A::Address(plan.tail), + A::Address(plan.dead), + A::Address(plan.pooled), + A::Address(self.handle(3, 4)?), + A::I32(crate::serving_context::geometry().cells() as i32), + A::F32(plan.theta), + ]; + push_launch(commands, Launch::DecodeAppend, args) + } + + fn push_pool_prompt(&self, commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHandle) -> Result<()> { + let (t, p0) = (plan.t, plan.p0); + let p = p0 as usize; + let end = p + t as usize; + if p == 0 { + push_pool_first(commands, plan, gamma)?; + } + let first = if p <= 3 { 0 } else { (p - 3).div_ceil(4) }; + let hi = if end - 1 >= 3 { Some((end - 4) / 4) } else { None }; + if let Some(hi) = hi.filter(|hi| *hi >= first) { + self.push_pool_blocks(commands, plan, gamma, (first, hi))?; + } + let tail = vec![A::Address(plan.raw), A::I64(t as i64), A::I64(p0 as i64), A::Address(plan.tail)]; + push_launch(commands, Launch::Tail, tail) + } + + fn push_pool_blocks( + &self, + commands: &mut Commands, + plan: &RunPlan, + gamma: ffi::BufferHandle, + (first, hi): (usize, usize), + ) -> Result<()> { + let args = vec![ + A::Address(plan.raw), + A::I64(plan.t as i64), + A::I64(plan.p0 as i64), + A::I32(0), + A::Address(gamma), + A::F32(1e-6), + A::Address(plan.tail), + A::Address(plan.dead), + A::Address(plan.pooled), + A::Address(self.handle(3, 4)?), + A::I64(first as i64), + A::I64(hi as i64), + A::F32(plan.theta), + ]; + push_launch(commands, Launch::Blocks((hi - first + 1) as u32), args) + } + + pub(super) fn push_scores( + &self, + commands: &mut Commands, + plan: &RunPlan, + out: [ffi::BufferHandle; 5], + ) -> Result<()> { + let n = plan.t as usize; + // Original prompt selection reuses one 256-row score tile. Every + // offset is checked against the actual whole producer allocation. + let tile_rows = if plan.decode { 1 } else { n.min(256) }; + let scores = self.handle(9, tile_rows * max_blocks() * 4)?; + for first_row in (0..n).step_by(256) { + let count = (n - first_row).min(256); + let tile = ScoreTile { + count, + reach: (plan.p0 as usize + first_row + count) / 4 + 1, + iq: plan.iq.checked_subspan(n * 512 * 4, first_row * 512 * 4, count * 512 * 4)?, + steps: out[4].checked_subspan(n * 16, first_row * 16, count * 16)?, + ids: out[3].checked_subspan(n * CAP * 4, first_row * CAP * 4, count * CAP * 4)?, + }; + push_tile_scores(commands, plan, scores, &tile)?; + push_tile_select(commands, plan, scores, &tile)?; + } + Ok(()) + } +} +fn push_pool_first(commands: &mut Commands, plan: &RunPlan, gamma: ffi::BufferHandle) -> Result<()> { + let args = vec![ + A::Address(plan.raw), + A::Address(gamma), + A::F32(1e-6), + A::Address(plan.dead), + A::Address(plan.pooled), + A::F32(plan.theta), + ]; + push_launch(commands, Launch::First, args) +} + +fn push_tile_scores( + commands: &mut Commands, + plan: &RunPlan, + scores: ffi::BufferHandle, + tile: &ScoreTile, +) -> Result<()> { + if plan.decode { + let args = vec![ + A::Address(plan.pooled), + A::Address(plan.dead), + A::Address(tile.iq), + A::Address(tile.steps), + A::I32(1), + A::I64(max_blocks() as i64), + A::Address(scores), + ]; + return push_launch(commands, Launch::DecodeScores, args); + } + push_tile_tc(commands, plan, scores, tile)?; + let tail = vec![ + A::Address(plan.dead), + A::Address(tile.iq), + A::Address(tile.steps), + A::I64(max_blocks() as i64), + A::Address(scores), + ]; + push_launch(commands, Launch::ScoreTail(tile.count as u32), tail) +} + +fn push_tile_tc(commands: &mut Commands, plan: &RunPlan, scores: ffi::BufferHandle, tile: &ScoreTile) -> Result<()> { + let tc = vec![ + A::Address(plan.pooled), + A::Address(tile.iq), + A::Address(tile.steps), + A::I64(tile.count as i64), + A::I64(max_blocks() as i64), + A::I64(tile.reach as i64), + A::Address(scores), + ]; + push_launch(commands, Launch::Tc { t: tile.count as u32, reach: tile.reach as u32 }, tc) +} + +fn push_tile_select( + commands: &mut Commands, + plan: &RunPlan, + scores: ffi::BufferHandle, + tile: &ScoreTile, +) -> Result<()> { + let scan = vec![ + A::Address(scores), + A::Address(tile.steps), + A::I32(tile.count as i32), + A::I64(max_blocks() as i64), + A::Address(plan.status), + A::U32(4), + ]; + push_launch(commands, Launch::ScoreScan((tile.count * max_blocks()) as u32), scan)?; + let topk = vec![ + A::Address(scores), + A::Address(tile.steps), + A::I64(max_blocks() as i64), + A::I64(CAP as i64), + A::Address(tile.ids), + ]; + push_launch(commands, Launch::Topk(tile.count as u32), topk) +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs new file mode 100644 index 00000000..9f6cd090 --- /dev/null +++ b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs @@ -0,0 +1,262 @@ +//! STRA-338 size: the phases of `QsaPromptIndexWorkspace::run`, extracted without reordering any call. + +use super::run_launches::{push_norm_rope, push_scan}; +#[allow(unused_imports)] +use super::*; +use crate::ple_batch_ffi::Blas; + +pub(super) type Commands = Vec<(Launch, Arguments)>; + +/// Handles and scalars every launch of one `run` shares. +pub(super) struct RunPlan { + pub(super) t: u32, + pub(super) p0: u32, + pub(super) decode: bool, + pub(super) raw: ffi::BufferHandle, + pub(super) k: ffi::BufferHandle, + pub(super) iq: ffi::BufferHandle, + pub(super) pooled: ffi::BufferHandle, + pub(super) tail: ffi::BufferHandle, + pub(super) dead: ffi::BufferHandle, + pub(super) status: ffi::BufferHandle, + pub(super) positions: Option, + pub(super) theta: f32, +} + +#[derive(Default)] +/// Host memory the asynchronous copies and launches read; leaked on failure while they may still be in flight. +pub(super) struct HostStaging { + pub(super) commands: Commands, + pub(super) steps: Vec, + pub(super) zero: Vec, + pub(super) flags: Vec, + /// K and V bytes copied to the output buffers; absent when the caller already wrote them. + pub(super) kv: Option<[Vec; 2]>, + pub(super) decode_positions: Vec, +} + +pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec) -> Result<()> { + commands.push((shape, Arguments::for_launch(shape, args)?)); + Ok(()) +} + +pub(super) fn run_theta() -> Result { + let theta = crate::qsa_index_ffi::theta(); + if !theta.is_finite() || theta <= 0.0 { + return Err(Error::InvalidDriverValue("QSA theta")); + } + Ok(theta) +} + +pub(super) fn step_bytes(p: usize, n: usize) -> Result> { + let mut steps = Vec::new(); + steps.try_reserve_exact(n * 16).map_err(|_| Error::HostAllocation)?; + for row in 0..n { + let pos = p + row; + for x in [pos, pos + 1, (pos + 1) / 4, (pos + 1).min(CAP)] { + steps.extend((x as i32).to_le_bytes()); + } + } + Ok(steps) +} + +impl<'ctx> QsaPromptIndexWorkspace<'ctx> { + #[allow(clippy::too_many_arguments)] + pub(super) fn upload_run_inputs( + &mut self, + p: usize, + pooled: &[f32], + tail: &[f32], + dead: &[f32], + raw: &[f32], + qfull: &[f32], + iq: &[f32], + ) -> Result<()> { + self.upload_run_state(p, pooled, tail, dead)?; + for (i, x) in [(4, raw), (7, qfull), (8, iq)] { + self.upload(i, x)?; + } + Ok(()) + } + + pub(super) fn upload_run_state(&mut self, p: usize, pooled: &[f32], tail: &[f32], dead: &[f32]) -> Result<()> { + if !pooled.is_empty() { + self.upload(0, pooled)?; + } + // The current spare is genuine prior state even when this batch completes no block. + let spare = encode(dead)?; + let result = self.buffers[0].as_mut().ok_or(Error::ContextPoisoned)?.copy_from_range(p / 4 * 128 * 4, &spare); + if result.is_err() { + self.failed = true; + } + result?; + self.upload(1, tail)?; + self.upload(2, dead) + } + + /// The 24 per-head position words of a decode step and their device span. + pub(super) fn decode_position_words(&self, p0: u32, n: usize) -> Result<(Vec, ffi::BufferHandle)> { + let mut decode_positions = Vec::new(); + decode_positions.try_reserve_exact(24 * 4).map_err(|_| Error::HostAllocation)?; + for _ in 0..24 { + decode_positions.extend((p0 as i32).to_le_bytes()); + } + let b = self.buffers[4].as_ref().ok_or(Error::ContextPoisoned)?; + let full = self.handle(4, self.sizes[4])?; + let h = full.checked_subspan(b.len(), self.sizes[4] - 24 * 4, 24 * 4)?; + h.validate_projection_extent(24 * 4, 4)?; + if h.overlaps(24 * 4, self.handle(4, n * 128 * 4)?, n * 128 * 4) { + return Err(Error::OutputAliasesInput); + } + Ok((decode_positions, h)) + } + + pub(super) fn run_plan( + &self, + (t, p0, decode): (u32, u32, bool), + k: ffi::BufferHandle, + status: ffi::BufferHandle, + (positions, theta): (Option, f32), + ) -> Result { + let n = t as usize; + let raw = self.handle(4, n * 128 * 4)?; + let iq = self.handle(8, n * 512 * 4)?; + self.arena_plan((t, p0, decode), (raw, iq, k), status, (positions, theta)) + } + + /// The plan over caller-provided raw and index-query handles. + pub(super) fn arena_plan( + &self, + (t, p0, decode): (u32, u32, bool), + (raw, iq, k): (ffi::BufferHandle, ffi::BufferHandle, ffi::BufferHandle), + status: ffi::BufferHandle, + (positions, theta): (Option, f32), + ) -> Result { + Ok(RunPlan { + t, + p0, + decode, + raw, + k, + iq, + pooled: self.handle(0, self.sizes[0])?, + tail: self.handle(1, self.sizes[1])?, + dead: self.handle(2, self.sizes[2])?, + status, + positions, + theta, + }) + } + + pub(super) fn push_run_commands( + &self, + commands: &mut Commands, + plan: &RunPlan, + qfull: Option, + gamma: [ffi::BufferHandle; 4], + out: [ffi::BufferHandle; 5], + ) -> Result<()> { + let n = plan.t as usize; + push_norm_rope(commands, plan, (plan.k, gamma[1]), (2, 256, 512))?; + push_scan(commands, plan, plan.k, n * 512, 0)?; + let qfull = match qfull { + Some(handle) => handle, + None => self.handle(7, n * 12288 * 4)?, + }; + let split = vec![A::Address(qfull), A::Address(out[2]), A::I64(plan.t as i64)]; + push_launch(commands, Launch::Split((n * 6144) as u32), split)?; + push_norm_rope(commands, plan, (out[2], gamma[0]), (24, 256, 6144))?; + push_scan(commands, plan, out[2], n * 6144, 1)?; + push_norm_rope(commands, plan, (plan.iq, gamma[2]), (4, 128, 512))?; + push_scan(commands, plan, plan.iq, n * 512, 2)?; + self.push_pool_scores_round(commands, plan, gamma[3], out) + } + + fn push_pool_scores_round( + &self, + commands: &mut Commands, + plan: &RunPlan, + gamma: ffi::BufferHandle, + out: [ffi::BufferHandle; 5], + ) -> Result<()> { + let n = plan.t as usize; + self.push_pool(commands, plan, gamma, out[4])?; + self.push_scores(commands, plan, out)?; + push_launch(commands, Launch::Round((n * 128) as u32), vec![A::Address(plan.raw), A::I64((n * 128) as i64)])?; + push_scan(commands, plan, plan.raw, n * 128, 5) + } + + /// Copies the staged host bytes up and launches every command on the shared stream. + pub(super) fn submit_run( + &self, + blas: &Blas, + plan: &RunPlan, + out: [ffi::BufferHandle; 5], + host: &mut HostStaging, + ) -> Result<()> { + self.copy_run_inputs(plan, out, host)?; + // Pageable uploads/status have a real dependency before the nonblocking shared stream. + self.context.driver.api.synchronize()?; + let module = self.module.as_ref().ok_or(Error::ContextPoisoned)?; + for (shape, args) in &mut host.commands { + module.launch(*shape, blas.stream(), args)?; + } + Ok(()) + } + + fn copy_run_inputs(&self, plan: &RunPlan, out: [ffi::BufferHandle; 5], host: &HostStaging) -> Result<()> { + let api = &self.context.driver.api; + api.copy_from(plan.status, &host.zero)?; + api.copy_from(out[4], &host.steps)?; + if let Some([k_bytes, v_bytes]) = &host.kv { + api.copy_from(out[0], k_bytes)?; + api.copy_from(out[1], v_bytes)?; + } + if let Some(positions) = plan.positions { + api.copy_from(positions, &host.decode_positions)?; + } + Ok(()) + } + + /// Marks the workspace, the batch workspace and the context failed after a device error. + pub(super) fn fail_run(&mut self, ws: &mut NativeBatchWorkspace<'ctx>) { + self.failed = true; + ws.mark_failed(); + self.context.poison(); + self.context.retain_driver(); + } + + pub(super) fn check_run_flags(&mut self, flags: &[u8]) -> Result<()> { + for flag in flags.as_chunks::<4>().0 { + if u32::from_le_bytes(*flag) > 1 { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA finite status")); + } + } + if flags[24..].iter().any(|x| *x != 0) { + self.failed = true; + return Err(Error::InvalidDriverValue("QSA unused status")); + } + if flags[..24].iter().any(|x| *x != 0) { + return Err(Error::NonFiniteMmqOutput("QSA prompt normalized/index/scores")); + } + Ok(()) + } + + pub(super) fn check_selected_ids(&mut self, ids_handle: ffi::BufferHandle, p: usize, n: usize) -> Result<()> { + let ids = self.read(ids_handle, n * CAP * 4)?; + for row in 0..n { + let width = (p + row + 1).min(CAP); + let mut last = None; + for i in 0..width { + let at = (row * CAP + i) * 4; + let id = i32::from_le_bytes(ids[at..at + 4].try_into().map_err(|_| Error::InvalidSize)?); + if id < 0 || id as usize > p + row || last.is_some_and(|old| old >= id) { + return Err(Error::InvalidDriverValue("QSA selected IDs")); + } + last = Some(id); + } + } + Ok(()) + } +} diff --git a/limits-baseline.json b/limits-baseline.json index f9563b26..0987e7b0 100644 --- a/limits-baseline.json +++ b/limits-baseline.json @@ -35,8 +35,8 @@ "leleka-cuda-driver": { "fn_lines": 675, "width": 820, - "complexity": 663, - "nesting": 31 + "complexity": 661, + "nesting": 30 }, "leleka-deploy": { "fn_lines": 105,