diff --git a/crates/cuda-driver/src/qsa_prompt_device_index.rs b/crates/cuda-driver/src/qsa_prompt_device_index.rs index 8a1a7891..03ce63ae 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_index.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_index.rs @@ -1,5 +1,5 @@ //! Private real-arena continuation of the exact old prompt program. -use super::run_phases::{HostStaging, run_theta, step_bytes}; +use super::run_phases::HostStaging; use super::*; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { #[allow(clippy::too_many_arguments)] @@ -18,24 +18,11 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result<()> { - let n = t as usize; - let p = p0 as usize; + let (n, p) = (t as usize, p0 as usize); 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 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 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 }; + let mut prepared = self.prepare_run((t, p0, decode), Some((raw_h, iq_h)), out[0])?; + self.push_run_commands(&mut prepared.commands, &prepared.plan, Some(qfull_h), gamma, out)?; + let (mut host, plan) = HostStaging::new(prepared, None); self.execute_run(&plan, out, ws, &mut host)?; self.check_run_flags(&host.flags)?; self.check_selected_ids(out[3], p, n) @@ -47,38 +34,6 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { initial_tail: &[f32], raw_h: ffi::BufferHandle, ) -> Result { - let end = p0 + t; - let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; - let mut values: Vec> = Vec::new(); - values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; - for (i, size) in sizes.into_iter().enumerate() { - let bytes = self.read(self.handle(i, size)?, size)?; - let mut v = Vec::new(); - v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; - v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if v.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA final index")); - } - values.push(v.into_boxed_slice()); - } - let bytes = self.read(raw_h, t * 128 * 4)?; - let mut rounded = Vec::new(); - rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if rounded.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); - } - let mut old_tail = [0.0; 384]; - old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState { - end: end as u32, - p0: p0 as u32, - t: t as u32, - initial_tail: old_tail, - rounded: rounded.into_boxed_slice(), - pooled: values.remove(0), - tail: values.remove(0), - dead: values.remove(0), - }) + self.final_state_with(p0, t, initial_tail, Some(raw_h)) } } diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs index 281bc150..0dfc0c4f 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace.rs @@ -11,70 +11,46 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); } - let mut sizes = sizes(); - for i in [4, 7, 8] { - sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; - } - sizes[9] = capacity.min(256) * max_blocks() * 4; + let sizes = capacity_sizes(capacity)?; let output_bytes = capacity * (512 * 2 + 6144 + CAP + 4) * 4; - if INDEX.starts_with(b"// UNSEALED") - || SELECT.starts_with(b"// UNSEALED") - || POSTOPS.starts_with(b"// UNSEALED") - || DECODE_POSTOPS.starts_with(b"// UNSEALED") - { - return Err(Error::InvalidDriverValue("QSA index assets unsealed")); - } + check_assets_sealed()?; if context.is_poisoned() { return Err(Error::ContextPoisoned); } - let peak = sizes - .iter() - .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? - .checked_add(output_bytes + RESERVE) - .ok_or(Error::BudgetExceeded)?; - if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < peak - { - return Err(Error::BudgetExceeded); - } - let mut owner = Self { - capacity, - sizes, - context, - buffers: std::array::from_fn(|_| None), - module: None, - late: None, - failed: false, - }; - let operation = (|| { - for (i, n) in sizes.into_iter().enumerate() { - owner.buffers[i] = Some(context.allocate(n)?); - } - let g = context.enter().map_err(|error| { - owner.failed = true; - context.poison(); - context.retain_driver(); - error - })?; - let loaded = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS); - let pop = g.finish(); - if pop.is_err() { - context.poison(); - context.retain_driver(); - } - owner.module = Some(loaded?); - pop?; - if context.memory_info()?.0 < output_bytes + RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(primary) = operation { + check_peak_budget(context, &sizes, output_bytes)?; + let buffers = std::array::from_fn(|_| None); + let mut owner = Self { capacity, sizes, context, buffers, module: None, late: None, failed: false }; + if let Err(primary) = owner.init_resources(output_bytes) { let _ = owner.close(); return Err(primary); } Ok(owner) } + /// Allocates every buffer, loads the kernel module under the context guard and re-checks the free memory. + fn init_resources(&mut self, output_bytes: usize) -> Result<()> { + let context = self.context; + for (i, n) in self.sizes.into_iter().enumerate() { + self.buffers[i] = Some(context.allocate(n)?); + } + let g = context.enter().map_err(|error| { + self.failed = true; + context.poison(); + context.retain_driver(); + error + })?; + let loaded = Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS); + let pop = g.finish(); + if pop.is_err() { + context.poison(); + context.retain_driver(); + } + self.module = Some(loaded?); + pop?; + if context.memory_info()?.0 < output_bytes + RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + } pub fn prompt_device_bytes(capacity: usize) -> Result { if !(1..=8192).contains(&capacity) { return Err(Error::InvalidQwenShape); @@ -131,30 +107,40 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let mut out = [self.handle(10, 4)?; 4]; for (i, w) in weights.into_iter().enumerate() { let n = if i < 2 { 256 } else { 128 } * 4; - if !std::ptr::eq(w.context, self.context) { - return Err(Error::ContextMismatch); - } - if w.len() != n { - return Err(Error::InvalidQwenShape); - } - out[i] = w.handle.ok_or(Error::ContextPoisoned)?; - out[i].validate_projection_extent(n, 4)?; + out[i] = self.weight_handle(w, n)?; ws.reject_alias(out[i], n)?; - for (j, b) in self.buffers.iter().enumerate() { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - let h = self.handle(j, b.len())?; - ws.reject_alias(h, b.len())?; - if h.overlaps(b.len(), out[i], n) { + self.clear_of_buffers(ws, out[i], n)?; + } + Ok(out) + } + /// The weight must belong to this context, have exactly `n` bytes and a valid extent. + fn weight_handle(&self, w: &DeviceBuffer<'_>, n: usize) -> Result { + if !std::ptr::eq(w.context, self.context) { + return Err(Error::ContextMismatch); + } + if w.len() != n { + return Err(Error::InvalidQwenShape); + } + let h = w.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(n, 4)?; + Ok(h) + } + /// A weight span must not overlap any workspace buffer, nor may two workspace buffers overlap each other. + fn clear_of_buffers(&self, ws: &NativeBatchWorkspace<'_>, weight: ffi::BufferHandle, n: usize) -> Result<()> { + for (j, b) in self.buffers.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + let h = self.handle(j, b.len())?; + ws.reject_alias(h, b.len())?; + if h.overlaps(b.len(), weight, n) { + return Err(Error::OutputAliasesInput); + } + for earlier in self.buffers[..j].iter().flatten() { + if h.overlaps(b.len(), earlier.handle.ok_or(Error::ContextPoisoned)?, earlier.len()) { return Err(Error::OutputAliasesInput); } - for earlier in self.buffers[..j].iter().flatten() { - if h.overlaps(b.len(), earlier.handle.ok_or(Error::ContextPoisoned)?, earlier.len()) { - return Err(Error::OutputAliasesInput); - } - } } } - Ok(out) + Ok(()) } #[allow(clippy::too_many_arguments)] // Closed original fixed QSA geometry and genuine prior image. pub fn append_select<'lease>( @@ -172,21 +158,8 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - self.append_select_inner( - p0, - t, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - weights, - ws, - false, - ) + let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q]; + self.append_select_inner((p0, t), inputs, weights, ws, false) } /// T1 Original decode index: scalar native append and FP32 warp scores. #[allow(clippy::too_many_arguments)] @@ -204,20 +177,43 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result> { - self.append_select_inner( - p0, - 1, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - weights, - ws, - true, - ) + let inputs = [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q]; + self.append_select_inner((p0, 1), inputs, weights, ws, true) } } + +/// Buffer sizes for a workspace of `capacity` rows. +fn capacity_sizes(capacity: usize) -> Result<[usize; 11]> { + let mut sizes = sizes(); + for i in [4, 7, 8] { + sizes[i] = (sizes[i] / 64).checked_mul(capacity).ok_or(Error::BudgetExceeded)?; + } + sizes[9] = capacity.min(256) * max_blocks() * 4; + Ok(sizes) +} + +fn check_assets_sealed() -> Result<()> { + if INDEX.starts_with(b"// UNSEALED") + || SELECT.starts_with(b"// UNSEALED") + || POSTOPS.starts_with(b"// UNSEALED") + || DECODE_POSTOPS.starts_with(b"// UNSEALED") + { + return Err(Error::InvalidDriverValue("QSA index assets unsealed")); + } + Ok(()) +} + +/// The workspace plus its outputs and reserve must fit the context budget and the free device memory. +fn check_peak_budget(context: &Context<'_>, sizes: &[usize; 11], output_bytes: usize) -> Result<()> { + let peak = sizes + .iter() + .try_fold(0usize, |sum, n| sum.checked_add(*n).ok_or(Error::BudgetExceeded))? + .checked_add(output_bytes + RESERVE) + .ok_or(Error::BudgetExceeded)?; + if context.allocated_bytes().checked_add(peak).is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < peak + { + return Err(Error::BudgetExceeded); + } + Ok(()) +} diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs index 7eace98f..f03774c7 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_2.rs @@ -4,49 +4,46 @@ use super::*; impl<'ctx> QsaPromptIndexWorkspace<'ctx> { - #[allow(clippy::too_many_arguments)] pub(super) fn append_select_inner<'lease>( &'lease mut self, - p0: u32, - t: u32, - prior_pooled: &[f32], - prior_tail: &[f32], - prior_dead: &[f32], - raw: &[f32], - k: &[f32], - v: &[f32], - qfull: &[f32], - index_q: &[f32], + (p0, t): (u32, u32), + inputs: [&[f32]; 8], weights: [&DeviceBuffer<'_>; 4], ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result> { + self.check_select_inputs((p0, t, decode), inputs)?; + let gamma = self.weights(weights, ws)?; + let (outputs, handles) = self.admit_outputs(t as usize, gamma, ws)?; + let operation = self.run_selected((p0, t, decode), inputs, (gamma, handles), ws); + self.finish_select(operation, outputs, (p0, t), inputs[1]) + } + /// Checks the geometry, the lengths of the prior image and rows and that every input value is finite. + fn check_select_inputs(&self, (p0, t, decode): (u32, u32, bool), inputs: [&[f32]; 8]) -> Result<()> { if decode && t != 1 { return Err(Error::InvalidQwenShape); } - let n = t as usize; - let p = p0 as usize; - if n == 0 - || n > self.capacity - || p.checked_add(n).is_none_or(|e| e > crate::serving_context::geometry().cells()) - || prior_pooled.len() != p / 4 * 128 - || prior_tail.len() != 384 - || prior_dead.len() != 128 - || raw.len() != n * 128 - || k.len() != n * 512 - || v.len() != n * 512 - || qfull.len() != n * 12288 - || index_q.len() != n * 512 - { + let (n, p) = (t as usize, p0 as usize); + if !self.select_bounds_ok(p, n) || !select_lengths_ok(p, n, inputs) { return Err(Error::InvalidQwenShape); } - if [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q] - .into_iter() - .any(|x| x.iter().any(|v| !v.is_finite())) - { + if inputs.into_iter().any(|x| x.iter().any(|v| !v.is_finite())) { return Err(Error::NonFiniteMmqOutput("QSA prompt input/prior")); } - let gamma = self.weights(weights, ws)?; + Ok(()) + } + fn select_bounds_ok(&self, p: usize, n: usize) -> bool { + n != 0 + && n <= self.capacity + && p.checked_add(n).is_some_and(|e| e <= crate::serving_context::geometry().cells()) + } + /// Budget check, exact-size allocation and alias admission of the five outputs; releases them on failure. + fn admit_outputs( + &self, + n: usize, + gamma: [ffi::BufferHandle; 4], + ws: &NativeBatchWorkspace<'ctx>, + ) -> Result<(Outputs<'ctx>, [ffi::BufferHandle; 5])> { let output_bytes = n * (512 * 2 + 6144 + CAP + 4) * 4; if self .context @@ -57,93 +54,129 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { { return Err(Error::BudgetExceeded); } - let mut outputs: [Option>; 5] = std::array::from_fn(|_| None); let sizes = [n * 512 * 4, n * 512 * 4, n * 6144 * 4, n * CAP * 4, n * 4 * 4]; - let operation = (|| { - for (i, size) in sizes.iter().enumerate() { - outputs[i] = Some(self.context.allocate(*size)?); - } - Ok(()) - })(); - if let Err(primary) = operation { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - return Err(primary); - } + let outputs = self.allocate_outputs(&sizes)?; let handles: [ffi::BufferHandle; 5] = std::array::from_fn(|i| outputs[i].as_ref().and_then(|b| b.handle).expect("allocated exact owner")); - let admission = (|| { - for (i, b) in outputs.iter().enumerate() { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - if !std::ptr::eq(b.context, self.context) || b.len() != sizes[i] { - return Err(Error::InvalidQwenShape); - } - handles[i].validate_projection_extent(sizes[i], 4)?; - ws.reject_alias(handles[i], sizes[i])?; - for other in self.buffers.iter().flatten() { - if handles[i].overlaps(sizes[i], other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { - return Err(Error::OutputAliasesInput); - } - } - for j in 0..i { - if handles[i].overlaps(sizes[i], handles[j], sizes[j]) { - return Err(Error::OutputAliasesInput); - } - } - for (j, g) in gamma.iter().enumerate() { - if handles[i].overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) { - return Err(Error::OutputAliasesInput); - } - } - } - Ok(()) - })(); - if let Err(primary) = admission { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } + if let Err(primary) = self.admit_alias_free(&outputs, &handles, &sizes, (gamma, ws)) { + release_outputs(outputs); return Err(primary); } - let operation = self.run( - p0, - t, - prior_pooled, - prior_tail, - prior_dead, - raw, - k, - v, - qfull, - index_q, - gamma, - handles, - ws, - decode, - ); + Ok((outputs, handles)) + } + fn allocate_outputs(&self, sizes: &[usize; 5]) -> Result> { + let mut outputs: Outputs<'ctx> = std::array::from_fn(|_| None); + for (i, size) in sizes.iter().enumerate() { + match self.context.allocate(*size) { + Ok(b) => outputs[i] = Some(b), + Err(primary) => { + release_outputs(outputs); + return Err(primary); + } + } + } + Ok(outputs) + } + fn admit_alias_free( + &self, + outputs: &Outputs<'ctx>, + handles: &[ffi::BufferHandle; 5], + sizes: &[usize; 5], + (gamma, ws): ([ffi::BufferHandle; 4], &NativeBatchWorkspace<'ctx>), + ) -> Result<()> { + for (i, b) in outputs.iter().enumerate() { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + if !std::ptr::eq(b.context, self.context) || b.len() != sizes[i] { + return Err(Error::InvalidQwenShape); + } + handles[i].validate_projection_extent(sizes[i], 4)?; + ws.reject_alias(handles[i], sizes[i])?; + self.output_clear_of(i, handles, sizes, gamma)?; + } + Ok(()) + } + /// Output `i` must not overlap a workspace buffer, an earlier output or a weight. + fn output_clear_of( + &self, + i: usize, + handles: &[ffi::BufferHandle; 5], + sizes: &[usize; 5], + gamma: [ffi::BufferHandle; 4], + ) -> Result<()> { + for other in self.buffers.iter().flatten() { + if handles[i].overlaps(sizes[i], other.handle.ok_or(Error::ContextPoisoned)?, other.len()) { + return Err(Error::OutputAliasesInput); + } + } + for j in 0..i { + if handles[i].overlaps(sizes[i], handles[j], sizes[j]) { + return Err(Error::OutputAliasesInput); + } + } + for (j, g) in gamma.iter().enumerate() { + if handles[i].overlaps(sizes[i], *g, if j < 2 { 1024 } else { 512 }) { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn run_selected( + &mut self, + (p0, t, decode): (u32, u32, bool), + inputs: [&[f32]; 8], + (gamma, handles): ([ffi::BufferHandle; 4], [ffi::BufferHandle; 5]), + ws: &mut NativeBatchWorkspace<'ctx>, + ) -> Result<()> { + let [pooled, tail, dead, raw, k, v, qfull, index_q] = inputs; + self.run(p0, t, pooled, tail, dead, raw, k, v, qfull, index_q, gamma, handles, ws, decode) + } + /// Reads the final state back; any failure releases (or, on a poisoned context, leaks) the outputs. + fn finish_select<'lease>( + &'lease mut self, + operation: Result<()>, + outputs: Outputs<'ctx>, + (p0, t): (u32, u32), + prior_tail: &[f32], + ) -> Result> { if let Err(primary) = operation { - if self.context.is_poisoned() { - std::mem::forget(outputs); - } else { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - } + self.discard_outputs(outputs); return Err(primary); } - let state = self.final_state(p, n, prior_tail); - match state { + match self.final_state(p0 as usize, t as usize, prior_tail) { Ok(state) => Ok(QsaPromptSelection { owner: self, outputs, t, p0, state }), Err(primary) => { - if self.context.is_poisoned() { - std::mem::forget(outputs); - } else { - for b in outputs.into_iter().flatten() { - let _ = b.release(); - } - } + self.discard_outputs(outputs); Err(primary) } } } + fn discard_outputs(&self, outputs: Outputs<'ctx>) { + if self.context.is_poisoned() { + std::mem::forget(outputs); + } else { + release_outputs(outputs); + } + } +} + +type Outputs<'ctx> = [Option>; 5]; + +fn release_outputs(outputs: Outputs<'_>) { + for b in outputs.into_iter().flatten() { + let _ = b.release(); + } +} + +/// The prior image and the row inputs must have exactly the lengths of an `n`-row append at position `p`. +fn select_lengths_ok(p: usize, n: usize, inputs: [&[f32]; 8]) -> bool { + let [prior_pooled, prior_tail, prior_dead, raw, k, v, qfull, index_q] = inputs; + prior_pooled.len() == p / 4 * 128 + && prior_tail.len() == 384 + && prior_dead.len() == 128 + && raw.len() == n * 128 + && k.len() == n * 512 + && v.len() == n * 512 + && qfull.len() == n * 12288 + && index_q.len() == n * 512 } 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 cbf5f0f7..abba20ac 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,6 +1,6 @@ //! Moved out of the parent module by STRA-338: impl QsaPromptIndexWorkspace (3). -use super::run_phases::{HostStaging, RunPlan, run_theta, step_bytes}; +use super::run_phases::{HostStaging, RunPlan}; #[allow(unused_imports)] use super::*; @@ -23,26 +23,12 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ws: &mut NativeBatchWorkspace<'ctx>, decode: bool, ) -> Result<()> { - let n = t as usize; - let p = p0 as usize; + let (n, p) = (t as usize, p0 as usize); 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 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 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 }; + let mut prepared = self.prepare_run((t, p0, decode), None, out[0])?; + self.push_run_commands(&mut prepared.commands, &prepared.plan, None, gamma, out)?; + let kv = Some([encode(k)?, encode(v)?]); + let (mut host, plan) = HostStaging::new(prepared, kv); self.execute_run(&plan, out, ws, &mut host)?; self.check_run_flags(&host.flags)?; self.check_selected_ids(out[3], p, n) diff --git a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs index 5b737012..18af326e 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/impl_qsapromptindexworkspace_4.rs @@ -28,39 +28,45 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { Ok(bytes) } pub(super) fn final_state(&mut self, p0: usize, t: usize, initial_tail: &[f32]) -> Result { + self.final_state_with(p0, t, initial_tail, None) + } + /// Reads back pooled, tail, dead and the rounded rows; `raw` overrides the workspace's own raw span. + pub(super) fn final_state_with( + &mut self, + p0: usize, + t: usize, + initial_tail: &[f32], + raw: Option, + ) -> Result { let end = p0 + t; let sizes = [(end / 4 + 1) * 128 * 4, 384 * 4, 128 * 4]; let mut values: Vec> = Vec::new(); values.try_reserve_exact(3).map_err(|_| Error::HostAllocation)?; for (i, size) in sizes.into_iter().enumerate() { - let bytes = self.read(self.handle(i, size)?, size)?; - let mut v = Vec::new(); - v.try_reserve_exact(size / 4).map_err(|_| Error::HostAllocation)?; - v.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if v.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA final index")); - } - values.push(v.into_boxed_slice()); - } - let bytes = self.read(self.handle(4, t * 128 * 4)?, t * 128 * 4)?; - let mut rounded = Vec::new(); - rounded.try_reserve_exact(t * 128).map_err(|_| Error::HostAllocation)?; - rounded.extend(bytes.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); - if rounded.iter().any(|x| !x.is_finite()) { - return Err(Error::NonFiniteMmqOutput("QSA rounded index rows")); + let h = self.handle(i, size)?; + values.push(self.read_finite(h, size, "QSA final index")?); } + let h = match raw { + Some(h) => h, + None => self.handle(4, t * 128 * 4)?, + }; + let rounded = self.read_finite(h, t * 128 * 4, "QSA rounded index rows")?; let mut old_tail = [0.0; 384]; old_tail.copy_from_slice(initial_tail); - Ok(QsaPromptIndexState { - end: end as u32, - p0: p0 as u32, - t: t as u32, - initial_tail: old_tail, - rounded: rounded.into_boxed_slice(), - pooled: values.remove(0), - tail: values.remove(0), - dead: values.remove(0), - }) + let (end, p0, t) = (end as u32, p0 as u32, t as u32); + let [pooled, tail, dead] = [values.remove(0), values.remove(0), values.remove(0)]; + Ok(QsaPromptIndexState { end, p0, t, initial_tail: old_tail, rounded, pooled, tail, dead }) + } + /// Reads `bytes` of f32 values from the device and rejects any non-finite one. + fn read_finite(&mut self, h: ffi::BufferHandle, bytes: usize, what: &'static str) -> Result> { + let raw = self.read(h, bytes)?; + let mut v = Vec::new(); + v.try_reserve_exact(bytes / 4).map_err(|_| Error::HostAllocation)?; + v.extend(raw.as_chunks::<4>().0.iter().map(|x| f32::from_le_bytes(*x))); + if v.iter().any(|x| !x.is_finite()) { + return Err(Error::NonFiniteMmqOutput(what)); + } + Ok(v.into_boxed_slice()) } pub fn close(mut self) -> Result<()> { self.close_inner() @@ -69,44 +75,14 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { let mut result = Ok(()); self.failed = true; if let Some(m) = self.late.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, close); + result = combine(result, self.close_owned(m, |m| m.close())); } if let Some(m) = self.module.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - std::mem::forget(m); - Err(e) - } - } - }; - result = combine(result, close); + result = combine(result, self.close_owned(m, |m| m.close())); } for b in &mut self.buffers { if let Some(b) = b.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - result = combine(result, close); + result = combine(result, close_buffer(self.context, b)); } } if result.is_err() { @@ -115,6 +91,27 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { } result } + /// Closes a kernel module under the context guard, or leaks it when the context is unusable. + fn close_owned(&self, m: M, close: impl FnOnce(M) -> Result<()>) -> Result<()> { + if self.context.is_poisoned() { + std::mem::forget(m); + return Err(Error::ContextPoisoned); + } + match self.context.enter() { + Ok(g) => combine(close(m), g.finish()), + Err(e) => { + std::mem::forget(m); + Err(e) + } + } + } +} +fn close_buffer<'ctx>(context: &Context<'ctx>, b: DeviceBuffer<'ctx>) -> Result<()> { + if context.is_poisoned() { + std::mem::forget(b); + return Err(Error::ContextPoisoned); + } + b.release() } impl Drop for QsaPromptIndexWorkspace<'_> { fn drop(&mut self) { diff --git a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs index 9f6cd090..4a796f94 100644 --- a/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs +++ b/crates/cuda-driver/src/qsa_prompt_index/run_phases.rs @@ -35,6 +35,21 @@ pub(super) struct HostStaging { pub(super) decode_positions: Vec, } +/// Everything `run` stages before it builds the launches. +pub(super) struct Prepared { + pub(super) plan: RunPlan, + pub(super) commands: Commands, + pub(super) steps: Vec, + pub(super) decode_positions: Vec, +} + +impl HostStaging { + pub(super) fn new(prepared: Prepared, kv: Option<[Vec; 2]>) -> (Self, RunPlan) { + let Prepared { plan, commands, steps, decode_positions } = prepared; + (Self { commands, steps, zero: vec![0u8; 64], flags: vec![0u8; 64], kv, decode_positions }, plan) + } +} + pub(super) fn push_launch(commands: &mut Commands, shape: Launch, args: Vec) -> Result<()> { commands.push((shape, Arguments::for_launch(shape, args)?)); Ok(()) @@ -94,6 +109,34 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { self.upload(2, dead) } + /// Builds the step bytes, launch list and plan of one run; `given` carries caller-provided raw and + /// index-query handles (the arena path), else the workspace's own spans are used. + pub(super) fn prepare_run( + &self, + (p0, t, decode): (u32, u32, bool), + given: Option<(ffi::BufferHandle, ffi::BufferHandle)>, + out0: ffi::BufferHandle, + ) -> Result { + let n = t as usize; + let steps = step_bytes(p0 as usize, n)?; + let status = self.handle(10, 64)?; + let mut commands: Commands = Vec::new(); + commands.try_reserve_exact(32 + 4 * n.div_ceil(256)).map_err(|_| Error::HostAllocation)?; + 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 shape = (t, p0, decode); + let plan = match given { + None => self.run_plan(shape, out0, status, (positions, theta))?, + Some((raw, iq)) => self.arena_plan(shape, (raw, iq, out0), status, (positions, theta))?, + }; + Ok(Prepared { plan, commands, steps, decode_positions }) + } + /// 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();