From 223638475deb0831c8fcbc4d988dd60959fc3219 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 13:50:49 +0100 Subject: [PATCH] STRA-338 size: split OriginalMtpPrefill::record into admission, staging, block and append phases --- .../impl_originalmtpprefill.rs | 6 + .../impl_originalmtpprefill_4.rs | 661 +++++++----------- .../impl_originalmtpprefill_6.rs | 284 ++++++++ .../impl_originalmtpprefill_7.rs | 115 +++ 4 files changed, 644 insertions(+), 422 deletions(-) create mode 100644 crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs create mode 100644 crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs index 71d8ebfa..ada64a27 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill.rs @@ -13,3 +13,9 @@ mod impl_originalmtpprefill_3; mod impl_originalmtpprefill_4; #[path = "impl_originalmtpprefill/impl_originalmtpprefill_5.rs"] mod impl_originalmtpprefill_5; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_6.rs"] +mod impl_originalmtpprefill_6; +#[path = "impl_originalmtpprefill/impl_originalmtpprefill_7.rs"] +mod impl_originalmtpprefill_7; +#[allow(unused_imports)] +use impl_originalmtpprefill_7::{Admit, Block, Call, GrBufs, PageRuns, Stage, Staged, WEIGHT_EXTENTS}; diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs index 2021feab..bad039aa 100644 --- a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_4.rs @@ -1,8 +1,25 @@ -//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (4). +//! Moved out of the parent module by STRA-338: impl OriginalMtpPrefill (4). `record` admits the call, stages the +//! weights and walks the blocks; the commands of one block are recorded in `impl_originalmtpprefill_6.rs`. #[allow(unused_imports)] use super::*; +/// The weights in the order of `WEIGHT_EXTENTS`. +fn weight_refs<'a, 'c>(w: &OriginalMtpPrefillWeights<'a, 'c>) -> [&'a DeviceBuffer<'c>; 10] { + [ + w.embedding_norm, + w.embedding_fc, + w.hidden_norm, + w.hidden_fc, + w.gr_norm, + w.gr_down, + w.gr_up, + w.key, + w.value, + w.key_norm, + ] +} + impl<'ctx> OriginalMtpPrefill<'ctx> { #[allow(clippy::too_many_arguments)] pub fn record<'arena, 'loan>( @@ -19,87 +36,147 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { policy: &DraftKvPolicy, mut cancelled: impl FnMut() -> bool, ) -> Result { + let call = Call { prior, tokens, cell0, first_needed, policy }; + self.record_call(residual, workspace, ring, &call, (&weights, &embedding), &mut cancelled) + } + fn record_call( + &mut self, + residual: &mut OriginalDeviceResidual<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &Call<'_>, + operands: (&OriginalMtpPrefillWeights<'_, '_>, &OriginalMtpEmbedding<'_, '_>), + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + let (weights, embedding) = operands; + let r0 = match self.admit(residual, workspace, ring, call, embedding)? { + Admit::Run(r0) => r0, + Admit::Done(outcome) => return Ok(outcome), + }; + let rows = residual.lease_mut(); + let staged = match self.stage(rows, workspace, ring, (call, r0), (weights, embedding))? { + Stage::Ready(staged) => staged, + Stage::Done(outcome) => return Ok(outcome), + }; + self.record_blocks(rows, workspace, ring, call, (&staged, embedding), cancelled) + } + /// The fallbacks and refusals that precede any device work. + fn admit( + &self, + residual: &OriginalDeviceResidual<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + call: &Call<'_>, + embedding: &OriginalMtpEmbedding<'_, '_>, + ) -> Result { + if let Some(fallback) = Self::fallback_for(call.policy, call.tokens) { + return Ok(Admit::Done(DraftKvOutcome::Fallback(fallback))); + } + Self::reject_bad_rope(call.policy)?; + self.validate_inputs(residual, workspace, ring, call, embedding)?; + let r0 = call.first_needed.saturating_sub(call.cell0); + if r0 >= call.tokens.len() { + return Ok(Admit::Done(DraftKvOutcome::Skipped)); + } + Ok(Admit::Run(r0)) + } + fn fallback_for(policy: &DraftKvPolicy, tokens: &[i32]) -> Option { if policy.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + return Some(DraftKvFallback::Disabled); } if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + return Some(DraftKvFallback::Empty); } if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedStorage)); + return Some(DraftKvFallback::UnsupportedStorage); } if policy.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + return Some(DraftKvFallback::AlternateF16); } if policy.rope_table_enabled || policy.multimodal_positions { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedRopeTable)); + return Some(DraftKvFallback::UnsupportedRopeTable); } - if [policy.theta_scale, policy.freq_scale, policy.corr_low, policy.corr_high, policy.ext_factor, policy.mscale] - .iter() - .any(|x| !x.is_finite()) + None + } + fn reject_bad_rope(policy: &DraftKvPolicy) -> Result<()> { + let scales = [policy.theta_scale, policy.freq_scale, policy.corr_low, policy.corr_high, policy.ext_factor]; + if scales.iter().chain([&policy.mscale]).any(|x| !x.is_finite()) || policy.theta_scale <= 0.0 || policy.freq_scale <= 0.0 || policy.mscale <= 0.0 { return Err(Error::InvalidProjectionShape); } - ring.validate_snapshot(prior)?; + Ok(()) + } + fn validate_inputs( + &self, + residual: &OriginalDeviceResidual<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + call: &Call<'_>, + embedding: &OriginalMtpEmbedding<'_, '_>, + ) -> Result<()> { + ring.validate_snapshot(call.prior)?; workspace.validate_context(self.context)?; ring.validate_context(self.context)?; - if self.is_failed() + if self.shape_rejected(residual, call) { + return Err(Error::InvalidProjectionShape); + } + if call.tokens.iter().any(|t| *t < 0 || *t as usize >= embedding.vocab()) { + return Err(Error::InvalidProjectionShape); + } + Ok(()) + } + fn shape_rejected(&self, residual: &OriginalDeviceResidual<'_, '_, 'ctx>, call: &Call<'_>) -> bool { + let len = call.tokens.len(); + self.is_failed() || !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > 8192 - || cell0.checked_add(tokens.len()).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidProjectionShape); - } - if tokens.iter().any(|t| *t < 0 || *t as usize >= embedding.vocab()) { - return Err(Error::InvalidProjectionShape); - } - let r0 = first_needed.saturating_sub(cell0); - if r0 >= tokens.len() { - return Ok(DraftKvOutcome::Skipped); - } - let rows = residual.lease_mut(); + || len != residual.rows() + || len > 8192 + || call.cell0.checked_add(len).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + } + /// Q8 tile widths that fit the shared-memory limit of the device. + fn has_q8_tile(&self) -> bool { + WIDTHS.into_iter().any(|j| 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize) + } + /// The region, the staged weights and embedding table, and the proof that none of them alias. + fn stage( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + first: (&Call<'_>, usize), + operands: (&OriginalMtpPrefillWeights<'_, '_>, &OriginalMtpEmbedding<'_, '_>), + ) -> Result { + let ((call, r0), (weights, embedding)) = (first, operands); let (region, region_bytes) = rows.draft_kv_region()?; - let Some(r) = Region::new(region, region_bytes, tokens.len(), r0)? else { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall)); + let Some(r) = Region::new(region, region_bytes, call.tokens.len(), r0)? else { + return Ok(Stage::Done(DraftKvOutcome::Fallback(DraftKvFallback::RegionTooSmall))); }; - crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, tokens.len()); - if !WIDTHS - .into_iter() - .any(|j| 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024 <= self.shared_limit as usize) - { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile)); + crate::bringup_trace!("DBG prefill.record: region ok b={} tokens={} r0={r0}", r.b, call.tokens.len()); + if !self.has_q8_tile() { + return Ok(Stage::Done(DraftKvOutcome::Fallback(DraftKvFallback::NoQ8Tile))); } - let weight_refs = [ - weights.embedding_norm, - weights.embedding_fc, - weights.hidden_norm, - weights.hidden_fc, - weights.gr_norm, - weights.gr_down, - weights.gr_up, - weights.key, - weights.value, - weights.key_norm, - ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - ]; + let refs = weight_refs(weights); + let (wh, eh) = self.stage_operands(rows, workspace, &refs, embedding, region)?; + let (rh, rbytes) = Self::input_span(rows, region, region_bytes)?; + let staged = Staged { r, r0, wh, eh, rh, rbytes, table_bytes: embedding.table.bytes }; + staged.check_ring(ring, region, region_bytes)?; + crate::bringup_trace!("DBG prefill.record: overlap checks ok"); + Ok(Stage::Ready(staged)) + } + fn stage_operands( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'ctx>, + refs: &[&DeviceBuffer<'_>; 10], + embedding: &OriginalMtpEmbedding<'_, '_>, + region: BufferHandle, + ) -> Result<([BufferHandle; 10], BufferHandle)> { let mut wh = [region; 10]; for i in 0..10 { - wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { + wh[i] = self.weight(rows, workspace, refs[i], WEIGHT_EXTENTS[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; @@ -110,8 +187,13 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { e })?; crate::bringup_trace!("DBG prefill.record: embedding table staged"); - for (i, a) in weight_refs.iter().enumerate() { - for b in weight_refs.iter().take(i) { + Self::check_weights_disjoint(refs)?; + Self::check_embedding_disjoint(refs, eh, embedding.table.bytes)?; + Ok((wh, eh)) + } + fn check_weights_disjoint(refs: &[&DeviceBuffer<'_>; 10]) -> Result<()> { + for (i, a) in refs.iter().enumerate() { + for b in refs.iter().take(i) { let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned @@ -126,18 +208,28 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } } } - for b in weight_refs { + Ok(()) + } + fn check_embedding_disjoint(refs: &[&DeviceBuffer<'_>; 10], eh: BufferHandle, table_bytes: usize) -> Result<()> { + for b in refs { let h = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight b.handle is None (embedding overlap)"); Error::ContextPoisoned })?; - if eh.overlaps(embedding.table.bytes, h, b.bytes) - && !(eh.qwen_address() == h.qwen_address() && embedding.table.bytes == b.bytes) + if eh.overlaps(table_bytes, h, b.bytes) + && !(eh.qwen_address() == h.qwen_address() && table_bytes == b.bytes) { return Err(Error::OutputAliasesInput); } } - // Actual input residual lies outside the region being overwritten. + Ok(()) + } + /// Actual input residual lies outside the region being overwritten. + fn input_span( + rows: &OriginalPromptRows<'_, '_, '_>, + region: BufferHandle, + region_bytes: usize, + ) -> Result<(BufferHandle, usize)> { let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e @@ -146,25 +238,63 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { if rh.overlaps(rbytes, region, region_bytes) { return Err(Error::OutputAliasesInput); } - // The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not - // separately owned DeviceBuffers; compare by address (ring.address works for both layouts). - for i in 0..5 { - let hv = ring.address(i)?; - let n = ring.sizes[i]; - let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); - if ov(region.qwen_address(), region_bytes) - || ov(rh.qwen_address(), rbytes) - || wh.iter().zip(extents).any(|(w, n2)| ov(w.qwen_address(), n2)) - || ov(eh.qwen_address(), embedding.table.bytes) - { - return Err(Error::OutputAliasesInput); + Ok((rh, rbytes)) + } + /// Walks the blocks and publishes the completed range (or the cancellation). + fn record_blocks( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &Call<'_>, + operands: (&Staged, &OriginalMtpEmbedding<'_, '_>), + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + let (staged, embedding) = operands; + let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; + let (end, first) = (call.cell0 + call.tokens.len(), call.cell0 + staged.r0); + let first_page = first / 4; + let (pages, mut changed) = Self::prepare_pages(call.prior, end, first_page)?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + Self::restore_ring(workspace, ring, call.prior)?; + if let Some(outcome) = self.record_each(rows, workspace, ring, call, (staged, embedding), cancelled)? { + return Ok(outcome); + } + Self::read_back(ring, &mut changed, first_page)?; + Ok(Self::finish(ring, pages, changed, (first, end, generation))) + } + fn record_each( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &Call<'_>, + operands: (&Staged, &OriginalMtpEmbedding<'_, '_>), + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + let (staged, embedding) = operands; + let len = call.tokens.len(); + for b0 in (staged.r0..len).step_by(staged.r.b) { + let blk = Block { st: staged, nb: staged.r.b.min(len - b0), b0, c0: call.cell0 + b0 }; + crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={} c0={}", blk.nb, blk.c0); + if cancelled() { + return Ok(Some(DraftKvOutcome::Cancelled)); + } + let (kc, vc) = self.compute_block(rows, workspace, &blk, (call, embedding))?; + if cancelled() { + return Ok(Some(DraftKvOutcome::Cancelled)); + } + self.append_block(rows, workspace, ring, &blk, (kc, vc))?; + if cancelled() { + return Ok(Some(DraftKvOutcome::Cancelled)); } } - crate::bringup_trace!("DBG prefill.record: overlap checks ok"); - let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; - let end = cell0 + tokens.len(); - let first = cell0 + r0; - let first_page = first / 4; + Ok(None) + } + /// The pages below the first needed cell are shared with `prior`; the others are zeroed and filled by the blocks. + fn prepare_pages(prior: &MtpInt8Snapshot, end: usize, first_page: usize) -> Result<(Vec>, Vec)> { let page_count = end.div_ceil(4); let mut pages = Vec::new(); pages.try_reserve_exact(page_count).map_err(|_| Error::HostAllocation)?; @@ -177,20 +307,28 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { continue; } } - let mut runs: [Vec; 4] = std::array::from_fn(|_| Vec::new()); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - runs[i] = zero_bytes(n)?; - } + let runs = Self::zero_runs()?; if p < first_page { pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } else { changed.push(runs); } } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); + Ok((pages, changed)) + } + fn zero_runs() -> Result { + let mut runs: PageRuns = std::array::from_fn(|_| Vec::new()); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + runs[i] = zero_bytes(n)?; } - // Genuine idle dependency before this stream can mutate the real drafter KV. + Ok(runs) + } + /// Genuine idle dependency before this stream can mutate the real drafter KV. + fn restore_ring( + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + ) -> Result<()> { crate::bringup_trace!("DBG prefill.record: pages ready, ring.execute(idle)"); ring.execute(workspace, Vec::new()).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.execute err {e:?}"); @@ -202,345 +340,24 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { })?; crate::bringup_trace!("DBG prefill.record: ring restored"); ring.current = None; - for b0 in (r0..tokens.len()).step_by(r.b) { - let nb = r.b.min(tokens.len() - b0); - let c0 = cell0 + b0; - crate::bringup_trace!("DBG prefill.record: block b0={b0} nb={nb} c0={c0}"); - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mut commands = Vec::new(); - commands.try_reserve_exact(80).map_err(|_| Error::HostAllocation)?; - let mut tk = zero_bytes(nb * 4)?; - for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[b0..b0 + nb]) { - dst.copy_from_slice(&t.to_le_bytes()); - } - let mut bounds = zero_bytes(16)?; - for (dst, v) in bounds.chunks_exact_mut(4).zip([0, nb as i32, 0, (nb * 4) as i32]) { - dst.copy_from_slice(&v.to_le_bytes()); - } - Self::kernel( - &mut commands, - 0, - 9, - [(nb * 4).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)], - )?; - let emb = r.address(0, nb * 10240)?; - let tok = r.address(16, nb * 4)?; - match embedding.kind { - EmbeddingKind::Native { kind, row_bytes, .. } => Self::kernel( - &mut commands, - 1, - 0, - [10, nb as u32, 1], - [32, 1, 1], - 0, - vec![ - A::I32(kind), - A::U64(eh.qwen_address()), - A::U64(row_bytes as u64), - A::U64(tok), - A::I64(2560), - A::U64(emb), - ], - )?, - EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => Self::kernel( - &mut commands, - 0, - 5, - [10, nb as u32, 1], - [256, 1, 1], - 0, - vec![ - A::U64(eh.qwen_address()), - A::U64(eh.qwen_address() + codes as u64), - A::U64(if offsets { eh.qwen_address() + (codes + scales) as u64 } else { 0 }), - A::U64(tok), - A::I64(2560), - A::I32(bits), - A::I32(bias), - A::I32(group as i32), - A::U64((2560 / (8 / bits)) as u64), - A::U64((2560 / group) as u64), - A::U64(emb), - ], - )?, - } - self.finite(&mut commands, emb, nb * 2560, 0)?; - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(emb), A::U64(wh[0].qwen_address()), A::I64(2560), A::I64(2560), A::F32(1e-6)], - )?; - self.finite(&mut commands, emb, nb * 2560, 1)?; - let e2 = r.address(1, nb * 10240)?; - self.project(&mut commands, &r, emb, wh[1].qwen_address(), e2, nb, 2560, 0, 2)?; - self.finite(&mut commands, e2, nb * 2560, 2)?; - let hn = r.address(3, nb * 40960)?; - let h2 = r.address(4, nb * 40960)?; - commands.push(Cmd::Copy { - dst: hn, - src: rh.checked_subspan(rbytes, b0 * 40960, nb * 40960)?.qwen_address(), - bytes: nb * 40960, - }); - Self::kernel( - &mut commands, - 0, - 0, - [nb as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(hn), A::U64(wh[2].qwen_address()), A::I64(10240), A::I64(10240), A::F32(1e-6)], - )?; - self.finite(&mut commands, hn, nb * 10240, 3)?; - self.project(&mut commands, &r, hn, wh[3].qwen_address(), h2, nb * 4, 2560, 1, 4)?; - self.finite(&mut commands, h2, nb * 10240, 4)?; - let rm = r.address(5, nb * 40960)?; - let gated = r.address(6, nb * 40960)?; - let xn = r.address(8, nb * 20480)?; - let lo = r.address(9, nb * 1280)?; - let lo16 = r.address(10, nb * 640)?; - let grs = r.address(11, nb * 16)?; - let mixed = r.address(12, nb * 10240)?; - let mixedh = r.address(13, nb * 5120)?; - Self::kernel( - &mut commands, - 0, - 4, - [40, nb as u32, 1], - [256, 1, 1], - 0, - vec![A::U64(h2), A::U64(e2), A::U64(rm), A::I64(2560), A::I32(4)], - )?; - self.finite(&mut commands, rm, nb * 10240, 5)?; - Self::kernel( - &mut commands, - 0, - 1, - [(nb * 4) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(rm), A::U64(wh[4].qwen_address()), A::F32(1e-6), A::U64(grs), A::U64(xn), A::U64(0)], - )?; - self.finite(&mut commands, grs, nb * 4, 6)?; - Self::kernel( - &mut commands, - 0, - 12, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(self.status(6)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(xn), A::I32((nb * 10240) as i32), A::U64(self.status(6)?.qwen_address())], - )?; - commands.push(Cmd::Gemm { - x: r.handle(8, nb * 20480)?, - w: wh[5], - y: r.handle(9, nb * 1280)?, - rows: nb as i32, - n: 320, - k: 10240, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, lo, nb * 320, 7)?; - Self::kernel( - &mut commands, - 0, - 2, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(lo), A::U64(lo16), A::U64(0), A::I64((nb * 320) as i64)], - )?; - Self::kernel( - &mut commands, - 0, - 13, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(lo), A::U64(self.status(8)?.qwen_address()), A::I64(nb as i64)], - )?; - Self::kernel( - &mut commands, - 0, - 14, - [(nb * 320).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(lo16), A::I32((nb * 320) as i32), A::U64(self.status(8)?.qwen_address())], - )?; - commands.push(Cmd::Gemm { - x: r.handle(10, nb * 640)?, - w: wh[6], - y: r.handle(6, nb * 40960)?, - rows: nb as i32, - n: 10240, - k: 320, - alpha: 1.0, - beta: 0.0, - }); - self.finite(&mut commands, gated, nb * 10240, 9)?; - Self::kernel( - &mut commands, - 0, - 3, - [(nb * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(mixed), - A::U64(0), - A::I64(nb as i64), - A::U64(mixedh), - A::U64(0), - ], - )?; - Self::kernel( - &mut commands, - 0, - 15, - [(nb * 10240).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(rm), - A::U64(grs), - A::U64(wh[4].qwen_address()), - A::U64(gated), - A::U64(self.status(10)?.qwen_address()), - A::I64(nb as i64), - ], - )?; - self.finite(&mut commands, mixed, nb * 2560, 10)?; - let kc = r.address(14, nb * 2048)?; - let vc = r.address(15, nb * 2048)?; - self.project(&mut commands, &r, mixed, wh[7].qwen_address(), kc, nb, 512, 0, 11)?; - self.finite(&mut commands, kc, nb * 512, 11)?; - self.project(&mut commands, &r, mixed, wh[8].qwen_address(), vc, nb, 512, 0, 12)?; - self.finite(&mut commands, vc, nb * 512, 12)?; - Self::kernel( - &mut commands, - 0, - 0, - [(nb * 2) as u32, 1, 1], - [256, 1, 1], - 0, - vec![A::U64(kc), A::U64(wh[9].qwen_address()), A::I64(256), A::I64(256), A::F32(1e-6)], - )?; - self.finite(&mut commands, kc, nb * 512, 13)?; - Self::kernel( - &mut commands, - 0, - 6, - [(nb * 2) as u32, 1, 1], - [32, 1, 1], - 0, - vec![ - A::U64(kc), - A::I64(2), - A::I64(256), - A::I64(512), - A::I64(c0 as i64), - A::F32(policy.theta_scale), - A::F32(policy.freq_scale), - A::F32(policy.corr_low), - A::F32(policy.corr_high), - A::F32(policy.ext_factor), - A::F32(policy.mscale), - A::U64(0), - A::Words3([0; 3]), - ], - )?; - self.finite(&mut commands, kc, nb * 512, 14)?; - self.run(rows, workspace, commands, vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)])?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - let mapped = ring.mapped()?; - let mut host = [0u64; 8]; - for (i, n) in HOST_RUNS.into_iter().enumerate() { - host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; - } - let mut append = Vec::new(); - append.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; - Self::kernel( - &mut append, - 0, - 7, - [nb as u32, 2, 8], - [64, 1, 1], - 0, - vec![ - A::U64(kc), - A::U64(vc), - A::I64(c0 as i64), - A::U64(ring.address(4)?), - A::I64(4), - A::U64(0), - A::U64(0), - A::U64(ring.address(0)?), - A::U64(ring.address(1)?), - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::Words8(host), - A::Words8([0; 8]), - ], - )?; - Self::kernel( - &mut append, - 0, - 10, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(ring.address(2)?), - A::U64(ring.address(3)?), - A::U64(ring.address(4)?), - A::I64(c0 as i64), - A::I32(nb as i32), - A::U64(self.status(15)?.qwen_address()), - ], - )?; - self.run(rows, workspace, append, Vec::new())?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - } + Ok(()) + } + fn read_back(ring: &MtpOriginalInt8<'ctx>, changed: &mut [PageRuns], first_page: usize) -> Result<()> { let mapped = ring.mapped()?; for (p, runs) in changed.iter_mut().enumerate() { for (i, n) in PAGE_BYTES.into_iter().enumerate() { mapped.read_into(HOST_OFFSETS[i] + (first_page + p) * n, &mut runs[i])?; } } - drop(mapped); + Ok(()) + } + fn finish( + ring: &mut MtpOriginalInt8<'ctx>, + mut pages: Vec>, + changed: Vec, + range: (usize, usize, u64), + ) -> DraftKvOutcome { + let (first, end, generation) = range; for runs in changed { pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); } @@ -552,6 +369,6 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { })); ring.current = Some(snapshot.clone()); ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { snapshot, first_materialized: first, end, generation })) + DraftKvOutcome::Completed(CompletedDraftKv { snapshot, first_materialized: first, end, generation }) } } diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs new file mode 100644 index 00000000..0b1272f7 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_6.rs @@ -0,0 +1,284 @@ +//! Commands of one block of `OriginalMtpPrefill::record` (STRA-338): the embedding, hidden, GR and K/V phases are +//! recorded in the order of the former single function, then run; the append kernels follow in `append_block`. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalMtpPrefill<'ctx> { + /// `Self::kernel` for this program: no dynamic shared memory and `block` threads in x. + fn kernel1( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: u32, + args: Vec, + ) -> Result<()> { + Self::kernel(cmds, asset, index, grid, [block, 1, 1], 0, args) + } + fn gemm(x: BufferHandle, w: BufferHandle, y: BufferHandle, shape: [usize; 3]) -> Cmd { + let [rows, n, k] = shape; + Cmd::Gemm { x, w, y, rows: rows as i32, n: n as i32, k: k as i32, alpha: 1.0, beta: 0.0 } + } + /// Records the block, uploads its token ids and bounds, and runs it; returns the K and V addresses. + pub(in super::super) fn compute_block( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + blk: &Block<'_>, + operands: (&Call<'_>, &OriginalMtpEmbedding<'_, '_>), + ) -> Result<(u64, u64)> { + let (call, embedding) = operands; + let mut commands = Vec::new(); + commands.try_reserve_exact(80).map_err(|_| Error::HostAllocation)?; + let (tk, bounds) = Self::block_inputs(blk, call.tokens)?; + let e2 = self.embed_phase(&mut commands, blk, embedding)?; + let h2 = self.hidden_phase(&mut commands, blk)?; + let mixed = self.gr_phase(&mut commands, blk, (h2, e2))?; + let (kc, vc) = self.kv_phase(&mut commands, blk, mixed, call.policy)?; + let (r, nb) = (&blk.st.r, blk.nb); + let staging = vec![(r.handle(16, nb * 4)?, tk), (r.handle(19, 16)?, bounds)]; + self.run(rows, workspace, commands, staging)?; + Ok((kc, vc)) + } + fn block_inputs(blk: &Block<'_>, tokens: &[i32]) -> Result<(Vec, Vec)> { + let nb = blk.nb; + let mut tk = zero_bytes(nb * 4)?; + for (dst, t) in tk.chunks_exact_mut(4).zip(&tokens[blk.b0..blk.b0 + nb]) { + dst.copy_from_slice(&t.to_le_bytes()); + } + let mut bounds = zero_bytes(16)?; + for (dst, v) in bounds.chunks_exact_mut(4).zip([0, nb as i32, 0, (nb * 4) as i32]) { + dst.copy_from_slice(&v.to_le_bytes()); + } + Ok((tk, bounds)) + } + /// Token ids, embedding rows, their RMS norm and the projection of the embedding half; returns that projection. + fn embed_phase( + &self, + cmds: &mut Vec, + blk: &Block<'_>, + embedding: &OriginalMtpEmbedding<'_, '_>, + ) -> Result { + let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); + let emb = self.embed_rows(cmds, blk, embedding)?; + let e2 = r.address(1, nb * 10240)?; + self.project(cmds, r, emb, wh[1].qwen_address(), e2, nb, 2560, 0, 2)?; + self.finite(cmds, e2, nb * 2560, 2)?; + Ok(e2) + } + fn embed_rows( + &self, + cmds: &mut Vec, + blk: &Block<'_>, + embedding: &OriginalMtpEmbedding<'_, '_>, + ) -> Result { + let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); + let iota = vec![A::U64(r.address(18, nb * 16)?), A::I32((nb * 4) as i32)]; + Self::kernel1(cmds, 0, 9, [(nb * 4).div_ceil(256) as u32, 1, 1], 256, iota)?; + let emb = r.address(0, nb * 10240)?; + let tok = r.address(16, nb * 4)?; + Self::lookup(cmds, blk, &embedding.kind, (tok, emb))?; + self.finite(cmds, emb, nb * 2560, 0)?; + let norm = vec![A::U64(emb), A::U64(wh[0].qwen_address()), A::I64(2560), A::I64(2560), A::F32(1e-6)]; + Self::kernel1(cmds, 0, 0, [nb as u32, 1, 1], 256, norm)?; + self.finite(cmds, emb, nb * 2560, 1)?; + Ok(emb) + } + fn lookup(cmds: &mut Vec, blk: &Block<'_>, kind: &EmbeddingKind, io: (u64, u64)) -> Result<()> { + let (eh, nb) = (blk.st.eh.qwen_address(), blk.nb); + match *kind { + EmbeddingKind::Native { kind, row_bytes, .. } => Self::lookup_native(cmds, nb, (kind, row_bytes), (eh, io)), + EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => { + let (tok, emb) = io; + let offsets = if offsets { eh + (codes + scales) as u64 } else { 0 }; + let args = vec![ + A::U64(eh), + A::U64(eh + codes as u64), + A::U64(offsets), + A::U64(tok), + A::I64(2560), + A::I32(bits), + A::I32(bias), + A::I32(group as i32), + A::U64((2560 / (8 / bits)) as u64), + A::U64((2560 / group) as u64), + A::U64(emb), + ]; + Self::kernel1(cmds, 0, 5, [10, nb as u32, 1], 256, args) + } + } + } + fn lookup_native(cmds: &mut Vec, nb: usize, format: (i32, usize), at: (u64, (u64, u64))) -> Result<()> { + let ((kind, row_bytes), (eh, (tok, emb))) = (format, at); + let args = vec![A::I32(kind), A::U64(eh), A::U64(row_bytes as u64), A::U64(tok), A::I64(2560), A::U64(emb)]; + Self::kernel1(cmds, 1, 0, [10, nb as u32, 1], 32, args) + } + /// The hidden state of the main model: copied from the residual, normed and projected; returns the projection. + fn hidden_phase(&self, cmds: &mut Vec, blk: &Block<'_>) -> Result { + let (st, r, nb) = (blk.st, &blk.st.r, blk.nb); + let hn = r.address(3, nb * 40960)?; + let h2 = r.address(4, nb * 40960)?; + let src = st.rh.checked_subspan(st.rbytes, blk.b0 * 40960, nb * 40960)?.qwen_address(); + cmds.push(Cmd::Copy { dst: hn, src, bytes: nb * 40960 }); + let norm = vec![A::U64(hn), A::U64(st.wh[2].qwen_address()), A::I64(10240), A::I64(10240), A::F32(1e-6)]; + Self::kernel1(cmds, 0, 0, [nb as u32, 1, 1], 256, norm)?; + self.finite(cmds, hn, nb * 10240, 3)?; + self.project(cmds, r, hn, st.wh[3].qwen_address(), h2, nb * 4, 2560, 1, 4)?; + self.finite(cmds, h2, nb * 10240, 4)?; + Ok(h2) + } + /// The GR branch over the mixed state; returns the address of its mixed output. + fn gr_phase(&self, cmds: &mut Vec, blk: &Block<'_>, hidden: (u64, u64)) -> Result { + let g = GrBufs::new(&blk.st.r, blk.nb)?; + self.gr_norm(cmds, blk, &g, hidden)?; + self.gr_down(cmds, blk, &g)?; + self.gr_up(cmds, blk, &g)?; + Ok(g.mixed) + } + fn gr_norm(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs, hidden: (u64, u64)) -> Result<()> { + let (nb, wh4) = (blk.nb, blk.st.wh[4].qwen_address()); + let broadcast = vec![A::U64(hidden.0), A::U64(hidden.1), A::U64(g.rm), A::I64(2560), A::I32(4)]; + Self::kernel1(cmds, 0, 4, [40, nb as u32, 1], 256, broadcast)?; + self.finite(cmds, g.rm, nb * 10240, 5)?; + let norm = vec![A::U64(g.rm), A::U64(wh4), A::F32(1e-6), A::U64(g.grs), A::U64(g.xn), A::U64(0)]; + Self::kernel1(cmds, 0, 1, [(nb * 4) as u32, 1, 1], 256, norm)?; + self.finite(cmds, g.grs, nb * 4, 6)?; + let grid = [(nb * 10240).div_ceil(256) as u32, 1, 1]; + let scan = + vec![A::U64(g.rm), A::U64(g.grs), A::U64(wh4), A::U64(self.status(6)?.qwen_address()), A::I64(nb as i64)]; + Self::kernel1(cmds, 0, 12, grid, 256, scan)?; + let args = vec![A::U64(g.xn), A::I32((nb * 10240) as i32), A::U64(self.status(6)?.qwen_address())]; + Self::kernel1(cmds, 0, 14, grid, 256, args) + } + fn gr_down(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs) -> Result<()> { + let (r, nb) = (&blk.st.r, blk.nb); + cmds.push(Self::gemm(r.handle(8, nb * 20480)?, blk.st.wh[5], r.handle(9, nb * 1280)?, [nb, 320, 10240])); + self.finite(cmds, g.lo, nb * 320, 7)?; + let grid = [(nb * 320).div_ceil(256) as u32, 1, 1]; + let round = vec![A::U64(g.lo), A::U64(g.lo16), A::U64(0), A::I64((nb * 320) as i64)]; + Self::kernel1(cmds, 0, 2, grid, 256, round)?; + let scan = vec![A::U64(g.lo), A::U64(self.status(8)?.qwen_address()), A::I64(nb as i64)]; + Self::kernel1(cmds, 0, 13, grid, 256, scan)?; + let args = vec![A::U64(g.lo16), A::I32((nb * 320) as i32), A::U64(self.status(8)?.qwen_address())]; + Self::kernel1(cmds, 0, 14, grid, 256, args) + } + fn gr_up(&self, cmds: &mut Vec, blk: &Block<'_>, g: &GrBufs) -> Result<()> { + let (r, nb, wh4) = (&blk.st.r, blk.nb, blk.st.wh[4].qwen_address()); + cmds.push(Self::gemm(r.handle(10, nb * 640)?, blk.st.wh[6], r.handle(6, nb * 40960)?, [nb, 10240, 320])); + self.finite(cmds, g.gated, nb * 10240, 9)?; + let mix = vec![ + A::U64(g.rm), + A::U64(g.grs), + A::U64(wh4), + A::U64(g.gated), + A::U64(g.mixed), + A::U64(0), + A::I64(nb as i64), + A::U64(g.mixedh), + A::U64(0), + ]; + Self::kernel1(cmds, 0, 3, [(nb * 2560).div_ceil(256) as u32, 1, 1], 256, mix)?; + let grid = [(nb * 10240).div_ceil(256) as u32, 1, 1]; + let status = A::U64(self.status(10)?.qwen_address()); + let scan = vec![A::U64(g.rm), A::U64(g.grs), A::U64(wh4), A::U64(g.gated), status, A::I64(nb as i64)]; + Self::kernel1(cmds, 0, 15, grid, 256, scan)?; + self.finite(cmds, g.mixed, nb * 2560, 10) + } + /// K and V projections of the mixed state, K norm and rope; returns their addresses. + fn kv_phase(&self, cmds: &mut Vec, blk: &Block<'_>, mixed: u64, policy: &DraftKvPolicy) -> Result<(u64, u64)> { + let (r, nb, wh) = (&blk.st.r, blk.nb, &blk.st.wh); + let kc = r.address(14, nb * 2048)?; + let vc = r.address(15, nb * 2048)?; + self.project(cmds, r, mixed, wh[7].qwen_address(), kc, nb, 512, 0, 11)?; + self.finite(cmds, kc, nb * 512, 11)?; + self.project(cmds, r, mixed, wh[8].qwen_address(), vc, nb, 512, 0, 12)?; + self.finite(cmds, vc, nb * 512, 12)?; + self.k_norm_rope(cmds, blk, kc, policy)?; + Ok((kc, vc)) + } + fn k_norm_rope(&self, cmds: &mut Vec, blk: &Block<'_>, kc: u64, policy: &DraftKvPolicy) -> Result<()> { + let nb = blk.nb; + let norm = vec![A::U64(kc), A::U64(blk.st.wh[9].qwen_address()), A::I64(256), A::I64(256), A::F32(1e-6)]; + Self::kernel1(cmds, 0, 0, [(nb * 2) as u32, 1, 1], 256, norm)?; + self.finite(cmds, kc, nb * 512, 13)?; + let rope = vec![ + A::U64(kc), + A::I64(2), + A::I64(256), + A::I64(512), + A::I64(blk.c0 as i64), + A::F32(policy.theta_scale), + A::F32(policy.freq_scale), + A::F32(policy.corr_low), + A::F32(policy.corr_high), + A::F32(policy.ext_factor), + A::F32(policy.mscale), + A::U64(0), + A::Words3([0; 3]), + ]; + Self::kernel1(cmds, 0, 6, [(nb * 2) as u32, 1, 1], 32, rope)?; + self.finite(cmds, kc, nb * 512, 14) + } + /// Appends the block's K and V to the real drafter KV ring and runs the append kernels. + pub(in super::super) fn append_block( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + blk: &Block<'_>, + kv: (u64, u64), + ) -> Result<()> { + let mapped = ring.mapped()?; + let mut host = [0u64; 8]; + for (i, n) in HOST_RUNS.into_iter().enumerate() { + host[i + 2] = mapped.address(HOST_OFFSETS[i], n)?; + } + let ra = Self::ring_addresses(ring)?; + let mut append = Vec::new(); + append.try_reserve_exact(2).map_err(|_| Error::HostAllocation)?; + self.append_kernels(&mut append, blk, (kv, ra, host))?; + self.run(rows, workspace, append, Vec::new()) + } + fn append_kernels( + &self, + append: &mut Vec, + blk: &Block<'_>, + operands: ((u64, u64), [u64; 5], [u64; 8]), + ) -> Result<()> { + let (kv, ra, host) = operands; + let args = Self::append_args(blk, kv, ra, host); + Self::kernel(append, 0, 7, [blk.nb as u32, 2, 8], [64, 1, 1], 0, args)?; + let status = self.status(15)?.qwen_address(); + let commit = vec![ + A::U64(ra[2]), + A::U64(ra[3]), + A::U64(ra[4]), + A::I64(blk.c0 as i64), + A::I32(blk.nb as i32), + A::U64(status), + ]; + Self::kernel1(append, 0, 10, [64, 1, 1], 256, commit) + } + fn ring_addresses(ring: &MtpOriginalInt8<'ctx>) -> Result<[u64; 5]> { + Ok([ring.address(0)?, ring.address(1)?, ring.address(2)?, ring.address(3)?, ring.address(4)?]) + } + /// Literal step append kernel and actual private step record, not batched prompt arithmetic. + fn append_args(blk: &Block<'_>, kv: (u64, u64), ra: [u64; 5], host: [u64; 8]) -> Vec { + vec![ + A::U64(kv.0), + A::U64(kv.1), + A::I64(blk.c0 as i64), + A::U64(ra[4]), + A::I64(4), + A::U64(0), + A::U64(0), + A::U64(ra[0]), + A::U64(ra[1]), + A::U64(ra[2]), + A::U64(ra[3]), + A::Words8(host), + A::Words8([0; 8]), + ] + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs new file mode 100644 index 00000000..005702c4 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_prefill/impl_originalmtpprefill/impl_originalmtpprefill_7.rs @@ -0,0 +1,115 @@ +//! Operands of `OriginalMtpPrefill::record` (STRA-338): the call, the admission and staging results, and the block. + +#[allow(unused_imports)] +use super::*; + +/// Host copies of the four runs of one 4-cell page. +pub(in super::super) type PageRuns = [Vec; 4]; + +/// Byte extents of the ten weights, in the order of `weight_refs`: embedding norm and fc, hidden norm and fc, GR norm, +/// down and up, key, value and key norm. +pub(in super::super) const WEIGHT_EXTENTS: [usize; 10] = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, +]; + +/// What the caller of `record` supplies besides the buffers. +#[derive(Clone, Copy)] +pub(in super::super) struct Call<'a> { + pub(in super::super) prior: &'a MtpInt8Snapshot, + pub(in super::super) tokens: &'a [i32], + pub(in super::super) cell0: usize, + pub(in super::super) first_needed: usize, + pub(in super::super) policy: &'a DraftKvPolicy, +} + +/// The outcome of the checks that precede any device work: run from row `r0`, or finish with an outcome. +pub(in super::super) enum Admit { + Run(usize), + Done(DraftKvOutcome), +} + +/// The staged operands, or the outcome that ends the call before the first block. +pub(in super::super) enum Stage { + Ready(Staged), + Done(DraftKvOutcome), +} + +/// The prompt region and the device operands every block reads. +pub(in super::super) struct Staged { + pub(in super::super) r: Region, + pub(in super::super) r0: usize, + pub(in super::super) wh: [BufferHandle; 10], + pub(in super::super) eh: BufferHandle, + pub(in super::super) rh: BufferHandle, + pub(in super::super) rbytes: usize, + pub(in super::super) table_bytes: usize, +} + +/// One block of `nb` tokens from token `b0`, whose first cell is `c0`. +pub(in super::super) struct Block<'a> { + pub(in super::super) st: &'a Staged, + pub(in super::super) nb: usize, + pub(in super::super) b0: usize, + pub(in super::super) c0: usize, +} + +/// The GR scratch addresses of a block. +pub(in super::super) struct GrBufs { + pub(in super::super) rm: u64, + pub(in super::super) gated: u64, + pub(in super::super) xn: u64, + pub(in super::super) lo: u64, + pub(in super::super) lo16: u64, + pub(in super::super) grs: u64, + pub(in super::super) mixed: u64, + pub(in super::super) mixedh: u64, +} + +impl GrBufs { + pub(in super::super) fn new(r: &Region, nb: usize) -> Result { + Ok(Self { + rm: r.address(5, nb * 40960)?, + gated: r.address(6, nb * 40960)?, + xn: r.address(8, nb * 20480)?, + lo: r.address(9, nb * 1280)?, + lo16: r.address(10, nb * 640)?, + grs: r.address(11, nb * 16)?, + mixed: r.address(12, nb * 10240)?, + mixedh: r.address(13, nb * 5120)?, + }) + } +} + +impl Staged { + /// The serve ring is built from prepared spans of the drafter's shared region, so buffers 0..5 are not separately + /// owned DeviceBuffers; compare by address (ring.address works for both layouts). + pub(in super::super) fn check_ring( + &self, + ring: &MtpOriginalInt8<'_>, + region: BufferHandle, + region_bytes: usize, + ) -> Result<()> { + for i in 0..5 { + let hv = ring.address(i)?; + let n = ring.sizes[i]; + let ov = |o: u64, on: usize| hv < o.saturating_add(on as u64) && o < hv.saturating_add(n as u64); + if ov(region.qwen_address(), region_bytes) + || ov(self.rh.qwen_address(), self.rbytes) + || self.wh.iter().zip(WEIGHT_EXTENTS).any(|(w, n2)| ov(w.qwen_address(), n2)) + || ov(self.eh.qwen_address(), self.table_bytes) + { + return Err(Error::OutputAliasesInput); + } + } + Ok(()) + } +}