From d3b9f39732e17f77c40f67e3155eab0eda34de4e Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:20:30 +0100 Subject: [PATCH] STRA-338 size2 cd7: new qsa helpers stay within the complexity limit --- .../impl_originalqsapromptdevice.rs | 36 +++++++++----- .../impl_originalqsapromptdevice_2.rs | 14 ++++-- .../impl_qsapromptindexworkspace_2.rs | 25 ++++++---- .../src/qsa_resident_transfer/enabled.rs | 34 ++++++++----- .../impl_drop_for_qsaselectedkvworkspace.rs | 17 ++++--- .../impl_qsaselectedkvworkspace.rs | 24 +++++++--- .../impl_originalverifyqsajournal_2.rs | 48 +++++++++++++------ .../impl_originalverifyqsajournal_3.rs | 44 ++++++++++++----- 8 files changed, 168 insertions(+), 74 deletions(-) diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs index 1dfe79b5..f43e0506 100644 --- a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice.rs @@ -69,14 +69,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { resident: &OriginalQsaResidentIndex<'ctx>, prior: &OriginalQsaIndexCheckpoint<'ctx>, ) -> Result<(usize, u32, usize)> { - resident.validate_checkpoint(prior)?; - if resident.in_flight - || resident.unpublished - || resident.next_position() != prior.next_position() - || !std::ptr::eq(resident.context, self.context) - { - return Err(Error::InvalidQwenShape); - } + self.check_resident_idle(resident, prior)?; let p = prior.next_position(); let p0 = u32::try_from(p).map_err(|_| Error::InvalidQwenShape)?; let t = read.rows(); @@ -89,6 +82,22 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { self.admit_budget(t)?; Ok((p, p0, t)) } + /// The index is valid, idle and stands at the checkpoint, on this device's context. + fn check_resident_idle( + &self, + resident: &OriginalQsaResidentIndex<'ctx>, + prior: &OriginalQsaIndexCheckpoint<'ctx>, + ) -> Result<()> { + resident.validate_checkpoint(prior)?; + if resident.in_flight + || resident.unpublished + || resident.next_position() != prior.next_position() + || !std::ptr::eq(resident.context, self.context) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } fn admit_budget(&self, t: usize) -> Result<()> { let needed = (t * 512).checked_add(2564 + RESERVE).ok_or(Error::BudgetExceeded)?; if self.context.allocated_bytes().checked_add(needed).is_none_or(|x| x > self.context.budget_bytes()) @@ -118,9 +127,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { Ok(mark) } fn run_spans(&self, read: &OriginalDeviceGrRead<'_, '_, 'ctx>, t: usize) -> Result { - let steps = self - .own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)? - .checked_subspan(self.capacity * 16, 0, t * 16)?; + let steps = self.resident_steps(t)?; let out = [ arena_span(read, "Kc", 2048)?, arena_span(read, "Vc", 2048)?, @@ -133,6 +140,13 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { let iq = arena_span(read, "q_idx", 2048)?; Ok(ResidentSpans { out, raw, qfull, iq }) } + fn resident_steps(&self, t: usize) -> Result { + self.own(self.steps.as_ref().ok_or(Error::ContextPoisoned)?, self.capacity * 16, 4)?.checked_subspan( + self.capacity * 16, + 0, + t * 16, + ) + } /// Run the index program, then copy the raw rows into the retained buffer. A failure of either puts the private image /// back to `start`. fn run_resident( diff --git a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs index 82e29762..e94daeaa 100644 --- a/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs +++ b/crates/cuda-driver/src/qsa_resident_device/impl_originalqsapromptdevice_2.rs @@ -81,11 +81,7 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { /// Allocate the buffers and load the kernel modules of a fresh resident device; the caller closes it on error. fn init_resident(&mut self, sizes: [usize; 11]) -> Result<()> { let context = self.context; - for (i, n) in sizes.into_iter().enumerate() { - self.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(context.allocate(n)?) - } - self.scratch = Some(context.allocate(SCRATCH)?); - self.steps = Some(context.allocate(self.capacity * 16)?); + self.allocate_resident(sizes)?; let guard = context.enter().map_err(|e| { context.poison(); context.retain_driver(); @@ -103,6 +99,14 @@ impl<'ctx> OriginalQsaPromptDevice<'ctx> { } Ok(()) } + fn allocate_resident(&mut self, sizes: [usize; 11]) -> Result<()> { + for (i, n) in sizes.into_iter().enumerate() { + self.index.as_mut().ok_or(Error::ContextPoisoned)?.buffers[i] = Some(self.context.allocate(n)?) + } + self.scratch = Some(self.context.allocate(SCRATCH)?); + self.steps = Some(self.context.allocate(self.capacity * 16)?); + Ok(()) + } fn load_resident_modules(&mut self) -> Result<()> { self.index.as_mut().ok_or(Error::ContextPoisoned)?.module = Some(Module::load(INDEX, SELECT, POSTOPS, DECODE_POSTOPS)?); diff --git a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs index 90c5668f..cdff4dc6 100644 --- a/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs +++ b/crates/cuda-driver/src/qsa_resident_index_program/impl_qsapromptindexworkspace_2.rs @@ -78,14 +78,8 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { ws: &mut NativeBatchWorkspace<'ctx>, ) -> Result<()> { self.check_replay(p0, t, (raw, gamma), ws)?; - let status = self.handle(10, 64)?; - let pooled = self.handle(0, self.sizes[0])?; - let tail = self.handle(1, 1536)?; - let dead = self.handle(2, 512)?; - let bp = self.handle(3, 4)?; - let steps = replay_steps(p0, t)?; - let mut step = self.context.allocate(t * 16)?; - step.copy_from(&steps)?; + let [status, pooled, tail, dead, bp] = self.replay_handles()?; + let step = self.upload_steps(p0, t)?; let sh = step.handle.ok_or(Error::ContextPoisoned)?; let io = ReplayIo { raw, gamma, step: sh, status, pooled, tail, dead, bp }; let commands = replay_commands(p0, t, &io)?; @@ -93,6 +87,21 @@ impl<'ctx> QsaPromptIndexWorkspace<'ctx> { self.run_replay(ws, status, (commands, step), &mut flags)?; self.check_replay_flags(&flags) } + /// The status, pooled keys, tail, `dead` and block position spans of the image. + fn replay_handles(&self) -> Result<[ffi::BufferHandle; 5]> { + let status = self.handle(10, 64)?; + let pooled = self.handle(0, self.sizes[0])?; + let tail = self.handle(1, 1536)?; + let dead = self.handle(2, 512)?; + let bp = self.handle(3, 4)?; + Ok([status, pooled, tail, dead, bp]) + } + fn upload_steps(&self, p0: usize, t: usize) -> Result> { + let steps = replay_steps(p0, t)?; + let mut step = self.context.allocate(t * 16)?; + step.copy_from(&steps)?; + Ok(step) + } fn check_replay( &self, p0: usize, diff --git a/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs index b8b3c741..ca16f1bc 100644 --- a/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs +++ b/crates/cuda-driver/src/qsa_resident_transfer/enabled.rs @@ -117,15 +117,7 @@ impl Transfer { w: &mut NativeBatchWorkspace<'ctx>, ranges: &[(u64, u64, usize)], ) -> Result<()> { - let side = self.side.as_ref().ok_or(Error::MissingSymbol("cuStreamCreate"))?; - w.validate_context(c)?; - if c.is_poisoned() { - return Err(Error::ContextPoisoned); - } - if self.pending.get() { - self.cancel(c)?; - } - check_ranges(ranges)?; + let side = self.begin_preflight(c, w, ranges)?; let g = c.enter().map_err(|e| { poison_failed(c, w); e @@ -138,13 +130,32 @@ impl Transfer { } combine(op, pop) } + /// The side symbols, once the workspace, the context and the ranges admit a side copy; a still pending one is waited for. + fn begin_preflight<'ctx>( + &self, + c: &'ctx Context<'ctx>, + w: &NativeBatchWorkspace<'ctx>, + ranges: &[(u64, u64, usize)], + ) -> Result<&Side> { + let side = self.side.as_ref().ok_or(Error::MissingSymbol("cuStreamCreate"))?; + w.validate_context(c)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + if self.pending.get() { + self.cancel(c)?; + } + check_ranges(ranges)?; + Ok(side) + } /// The side stream and its two events, created on first use (owned by this Transfer, destroyed in Drop). fn side_handles(&self, side: &Side) -> Result<(usize, usize, usize)> { if let Some(h) = self.handles.get() { return Ok(h); } let (mut s, mut x, mut y) = (std::ptr::null_mut(), std::ptr::null_mut(), std::ptr::null_mut()); - // SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by this Transfer and destroyed in Drop. + // SAFETY: fresh out-pointers; CU_STREAM_NON_BLOCKING = 1, CU_EVENT_DISABLE_TIMING = 2; the handles are owned by + // this Transfer and destroyed in Drop. driver_code("cuStreamCreate", unsafe { (side.stream_create)(&mut s, 1) })?; driver_code("cuEventCreate", unsafe { (side.event_create)(&mut x, 2) })?; driver_code("cuEventCreate", unsafe { (side.event_create)(&mut y, 2) })?; @@ -158,7 +169,8 @@ impl Transfer { // SAFETY: live handles of this context; the compute stream is the workspace's retained stream. driver_code("cuEventRecord", unsafe { (side.event_record)(e1 as *mut c_void, compute) })?; driver_code("cuStreamWaitEvent", unsafe { (side.stream_wait)(stream as *mut c_void, e1 as *mut c_void, 0) })?; - // SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / the chunk's final drain. + // SAFETY: as `copy`: checked extents of live owners; the owners stay leased until `wait_pending` / `cancel` / + // the chunk's final drain. self.enqueue_copies(ranges, stream as *mut c_void)?; driver_code("cuEventRecord", unsafe { (side.event_record)(e2 as *mut c_void, stream as *mut c_void) })?; self.pending.set(true); diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs index f0a08f7d..22c5e2c9 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_drop_for_qsaselectedkvworkspace.rs @@ -43,12 +43,7 @@ impl QsaSelectedKvWorkspace<'_> { query: &DeviceBuffer<'_>, output: &DeviceBuffer<'_>, ) -> Result<(ffi::BufferHandle, ffi::BufferHandle)> { - if !std::ptr::eq(self.context, query.context) || !std::ptr::eq(self.context, output.context) { - return Err(Error::ContextMismatch); - } - if query.bytes != 24576 || output.bytes != 24576 { - return Err(Error::InvalidQwenShape); - } + self.check_attend_buffers(query, output)?; let q = query.handle.ok_or(Error::ContextPoisoned)?; let o = output.handle.ok_or(Error::ContextPoisoned)?; q.validate_projection_extent(24576, 4)?; @@ -63,6 +58,16 @@ impl QsaSelectedKvWorkspace<'_> { } Ok((q, o)) } + /// Both buffers belong to this context and have the exact query size. + fn check_attend_buffers(&self, query: &DeviceBuffer<'_>, output: &DeviceBuffer<'_>) -> Result<()> { + if !std::ptr::eq(self.context, query.context) || !std::ptr::eq(self.context, output.context) { + return Err(Error::ContextMismatch); + } + if query.bytes != 24576 || output.bytes != 24576 { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } fn launch_attend(&self, function: ffi::FunctionHandle, mut args: qwen_ffi::Arguments) -> Result<()> { let guard = match self.context.enter() { Ok(guard) => guard, diff --git a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs index ce1640be..16394ece 100644 --- a/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs +++ b/crates/cuda-driver/src/qsa_selected_kv/impl_qsaselectedkvworkspace.rs @@ -174,13 +174,7 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { ) -> Result> { let h = self.handles()?; let functions = self.functions.ok_or(Error::ContextPoisoned)?; - check_shapes(layer, (miss_slots, miss_k, miss_v), selected_slots)?; - let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; - self.check_slots(layer, miss_slots, selected_slots)?; - check_finite(miss_k, miss_v)?; - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } + let generation = self.check_request(layer, (miss_slots, miss_k, miss_v), selected_slots)?; let launch = Self::selected_launch(&h, layer, (miss_slots, miss_k, miss_v), selected_slots)?; self.run_selected(functions, launch)?; for &slot in miss_slots { @@ -189,6 +183,22 @@ impl<'ctx> QsaSelectedKvWorkspace<'ctx> { self.generation = generation; Ok(QsaSelectedKvProducts { workspace: self, width: selected_slots.len() as u32, generation }) } + /// The generation the request would publish, once its shape, slots, rows and the device budget are admitted. + fn check_request( + &self, + layer: u32, + (miss_slots, miss_k, miss_v): (&[u32], &[u8], &[u8]), + selected_slots: &[u32], + ) -> Result { + check_shapes(layer, (miss_slots, miss_k, miss_v), selected_slots)?; + let generation = self.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; + self.check_slots(layer, miss_slots, selected_slots)?; + check_finite(miss_k, miss_v)?; + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(generation) + } /// Miss slots are unique and in range, selected slots are unique, in range and either missed now or already resident. fn check_slots(&self, layer: u32, miss_slots: &[u32], selected_slots: &[u32]) -> Result<()> { let mut missing = [false; CELLS]; diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs index e757c7c7..4a11a03e 100644 --- a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_2.rs @@ -136,14 +136,25 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { } let i = self.indices[layer].try_borrow().map_err(|_| Error::InvalidQwenShape)?; let gamma = whole(self.context, self.gamma[layer], 512)?; - let mut commands = Vec::new(); - commands.try_reserve_exact(end - begin).map_err(|_| Error::HostAllocation)?; - let plan = self.append_plan(gamma)?; - for row in begin..end { - commands.push(self.append_command(&plan, journal, &i, (layer * t + row, row), commit)?); - } + let commands = self.append_commands(journal, &i, (layer * t, begin..end), (commit, gamma))?; journal.submit_qsa(capture, commands) } + /// One append command per row of the layer. + fn append_commands( + &self, + journal: &OriginalVerifyGdnJournal<'_, 'ctx>, + i: &OriginalQsaResidentIndex<'ctx>, + (layer_rows, rows): (usize, std::ops::Range), + (commit, gamma): (bool, u64), + ) -> Result> { + let mut commands = Vec::new(); + commands.try_reserve_exact(rows.len()).map_err(|_| Error::HostAllocation)?; + let plan = self.append_plan(gamma)?; + for row in rows { + commands.push(self.append_command(&plan, journal, i, (layer_rows + row, row), commit)?); + } + Ok(commands) + } /// The kernel variant (analytic or table RoPE) and the fixed addresses of every row append of a layer. fn append_plan(&self, gamma: u64) -> Result { let (name, cos, sin, max_pos) = match self.rope.angles { @@ -231,19 +242,26 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { let staged = bank.staged_window()?; let keep = bank.staged_keep()?; check_armed_window(&live, staged, keep)?; - let (_, position, rows) = staged; for (m, a) in self.mapped.iter().zip(appended.iter()) { - let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; - if a.first_position() != position - || a.rows() != rows - || a.final_prefix().next_position() != position.checked_add(rows).ok_or(Error::InvalidSize)? - { - return Err(Error::InvalidQwenShape); - } - m.validate_prefix(a.final_prefix())?; + Self::check_receipt(m, a, (staged.1, staged.2))?; } Ok(keep) } + /// A receipt covers exactly the staged window, and its journal accepts the final prefix. + fn check_receipt( + m: &RefCell>, + a: &OriginalQsaMappedAppend, + (position, rows): (usize, usize), + ) -> Result<()> { + let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if a.first_position() != position + || a.rows() != rows + || a.final_prefix().next_position() != position.checked_add(rows).ok_or(Error::InvalidSize)? + { + return Err(Error::InvalidQwenShape); + } + m.validate_prefix(a.final_prefix()) + } } /// The journal addresses of the fused commit: the raw index rows, the tail snapshots and the commit table. Their /// layer and row strides are affine, so the far ends are checked against the first. diff --git a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs index 93b8846c..ce97e13a 100644 --- a/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs +++ b/crates/cuda-driver/src/qsa_verification_commit/impl_originalverifyqsajournal_3.rs @@ -14,13 +14,24 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { check_armed_window(&live, staged, keep)?; let position = staged.1; let end = position.checked_add(keep).ok_or(Error::InvalidSize)?; + self.check_all_in_flight()?; + self.publish_window_kv(position, keep)?; + self.publish_window_indices(position, end); + live.armed = false; + Ok(()) + } + /// Every index is still in flight and unpublished. + fn check_all_in_flight(&self) -> Result<()> { for i in &self.indices { let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; if !i.in_flight || !i.unpublished { return Err(Error::InvalidQwenShape); } } - self.publish_window_kv(position, keep)?; + Ok(()) + } + /// Advance every index to `end` and publish it. + fn publish_window_indices(&self, position: usize, end: usize) { for i in &self.indices { let mut i = i.borrow_mut(); i.coverage.end.set(i.coverage.end.get().min(position)); @@ -29,8 +40,6 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { i.in_flight = false; i.unpublished = false; } - live.armed = false; - Ok(()) } /// The window graph appended the actual K/V (resident pool and host copy) before the index images are made /// visible; publish that K/V half on the host here, after the commit drain, and only then the index half. Do not @@ -80,25 +89,35 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { self.validate_context(self.context)?; bank.validate_context(self.context)?; let staged = bank.staged_window()?; - let n = OriginalQsaResidentIndex::WINDOW_STATE_BYTES; - let snapshot = self.snapshot.try_borrow().map_err(|_| Error::InvalidQwenShape)?; - if !self.snapshots.get() || snapshot.len() != 12 * n { - return Err(Error::InvalidQwenShape); - } + let snapshot = self.window_snapshot()?; self.check_discardable(staged)?; // the PLE history: the window advanced it row by row, and only the commit graph sets it (from the kept // row's snapshot) let ple_snapshot = self.ple_snapshot.try_borrow().map_err(|_| Error::InvalidQwenShape)?; Self::check_ple_snapshot(&ple_snapshot, ple)?; + self.restore_window_state(&snapshot, ple.map(|ple| (ple, &ple_snapshot[..])))?; + self.release_window() + } + /// The index snapshots taken when the window began. + fn window_snapshot(&self) -> Result>> { + let snapshot = self.snapshot.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + if !self.snapshots.get() || snapshot.len() != 12 * OriginalQsaResidentIndex::WINDOW_STATE_BYTES { + return Err(Error::InvalidQwenShape); + } + Ok(snapshot) + } + /// Write the snapshots back: each index image, then the PLE history. + fn restore_window_state(&self, snapshot: &[u8], ple: Option<(&DeviceBuffer<'ctx>, &[u8])>) -> Result<()> { + let n = OriginalQsaResidentIndex::WINDOW_STATE_BYTES; for (layer, i) in self.indices.iter().enumerate() { i.try_borrow_mut() .map_err(|_| Error::InvalidQwenShape)? .write_window_state(&snapshot[layer * n..(layer + 1) * n])?; } - if let Some(ple) = ple { - ple.copy_from_range_shared(0, &ple_snapshot)?; + if let Some((ple, bytes)) = ple { + ple.copy_from_range_shared(0, bytes)?; } - self.release_window() + Ok(()) } /// The PLE history snapshot has the size of the image it restores. fn check_ple_snapshot(snapshot: &[u8], ple: Option<&DeviceBuffer<'ctx>>) -> Result<()> { @@ -113,6 +132,9 @@ impl<'a, 'ctx> OriginalVerifyQsaJournal<'a, 'ctx> { if !live.armed || live.generation != generation || live.position != position || live.rows != rows { return Err(Error::InvalidQwenShape); } + self.check_in_flight_at(position) + } + fn check_in_flight_at(&self, position: usize) -> Result<()> { for (i, m) in self.indices.iter().zip(self.mapped.iter()) { let i = i.try_borrow().map_err(|_| Error::InvalidQwenShape)?; let m = m.try_borrow().map_err(|_| Error::InvalidQwenShape)?;