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 bad039aa..1700cee3 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 @@ -80,7 +80,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } Ok(Admit::Run(r0)) } - fn fallback_for(policy: &DraftKvPolicy, tokens: &[i32]) -> Option { + pub(in super::super) fn fallback_for(policy: &DraftKvPolicy, tokens: &[i32]) -> Option { if policy.disabled { return Some(DraftKvFallback::Disabled); } @@ -98,7 +98,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } None } - fn reject_bad_rope(policy: &DraftKvPolicy) -> Result<()> { + pub(in super::super) 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 @@ -294,7 +294,11 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { 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)> { + pub(in super::super) 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)?; @@ -351,7 +355,7 @@ impl<'ctx> OriginalMtpPrefill<'ctx> { } Ok(()) } - fn finish( + pub(in super::super) fn finish( ring: &mut MtpOriginalInt8<'ctx>, mut pages: Vec>, changed: Vec, diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs index eccd7ebf..8ae424cc 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill.rs @@ -13,3 +13,11 @@ mod impl_originalmtpscalarprefill_3; mod impl_originalmtpscalarprefill_4; #[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_5.rs"] mod impl_originalmtpscalarprefill_5; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs"] +mod impl_originalmtpscalarprefill_6; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs"] +mod impl_originalmtpscalarprefill_7; +#[path = "impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs"] +mod impl_originalmtpscalarprefill_8; +#[allow(unused_imports)] +use impl_originalmtpscalarprefill_6::{Cap, GroupIo, ScalarCall, ScalarStaged}; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs index a56bb7f7..5b72ca6f 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_4.rs @@ -1,8 +1,25 @@ -//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (4). +//! Moved out of the parent module by STRA-338: impl OriginalMtpScalarPrefill (4). `record_impl` admits the call, +//! stages the weights and claims the policy; the group loop is in `impl_originalmtpscalarprefill_7.rs` and the capture +//! of one group in `impl_originalmtpscalarprefill_8.rs`. #[allow(unused_imports)] use super::*; +/// Byte extents of the eleven weights: the ten of the MTP prefill and the GR inject matrix. +const SCALAR_EXTENTS: [usize; 11] = [ + 10240, + 2560 * 80 * 34, + 40960, + 2560 * 80 * 34, + 40960, + 320 * 10240 * 2, + 10240 * 320 * 2, + 512 * 80 * 34, + 512 * 80 * 34, + 1024, + 4 * 10240 * 2, +]; + impl<'ctx> OriginalMtpScalarPrefill<'ctx> { /// Literal cached device-input or mapped-input per-T graph scheduling. /// Unsupported storage/math branches return explicit fallback, never completion. @@ -20,74 +37,125 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { policy: &OriginalMtpScalarPolicy, mut cancelled: impl FnMut() -> bool, ) -> Result { - let kv = &policy.kv; - if kv.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if kv.mode != 0 || kv.hybrid || kv.rotated || kv.q4 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedStorage)); - } - if kv.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if kv.rope_table_enabled || kv.multimodal_positions { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::UnsupportedRopeTable)); - } - if [kv.theta_scale, kv.freq_scale, kv.corr_low, kv.corr_high, kv.ext_factor, kv.mscale] - .iter() - .any(|x| !x.is_finite()) - || kv.theta_scale <= 0.0 - || kv.freq_scale <= 0.0 - || kv.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); + let call = ScalarCall { prior, tokens, cell0, first_needed, policy }; + self.record_scalar(residual, workspace, ring, &call, retained, &mut cancelled) + } + fn record_scalar( + &mut self, + residual: &mut OriginalDeviceResidual<'_, '_, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &ScalarCall<'_>, + retained: Rc>, + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + if let Some(outcome) = Self::early_outcome(call.policy, call.tokens)? { + return Ok(outcome); } let (weights, embedding) = retained.loans(self.context)?; - self.validate()?; - ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if !residual.context_matches(self.context) - || tokens.len() != residual.rows() - || tokens.len() > self.prompt_cap - || cell0.checked_add(tokens.len()).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) - || ring.max_t < self.max_t - { - return Err(Error::InvalidProjectionShape); - } - if tokens.iter().any(|t| *t < 0 || *t as usize >= embedding.vocab()) { - return Err(Error::InvalidProjectionShape); - } - // Original skips WHOLE groups whose end<=first_needed, not individual rows. - let first_group = (0..tokens.len()) - .step_by(self.max_t) - .find(|c| cell0 + *c + self.max_t.min(tokens.len() - *c) > first_needed); - let Some(first_group) = first_group else { + self.validate_scalar(residual, workspace, ring, call, &embedding)?; + let Some(first_group) = self.first_group(call) else { return Ok(DraftKvOutcome::Skipped); }; - let first = cell0 + first_group; - let end = cell0 + tokens.len(); let rows = residual.lease_mut(); + let staged = self.stage_scalar(rows, workspace, ring, (&weights, &embedding))?; + self.claim_policy(&retained, call.prior, call.policy)?; + let operands = (&staged, &retained, &embedding); + self.record_groups(rows, workspace, ring, (call, first_group), operands, cancelled) + } + fn early_outcome(policy: &OriginalMtpScalarPolicy, tokens: &[i32]) -> Result> { + if let Some(fallback) = OriginalMtpPrefill::fallback_for(&policy.kv, tokens) { + return Ok(Some(DraftKvOutcome::Fallback(fallback))); + } + OriginalMtpPrefill::reject_bad_rope(&policy.kv)?; + Ok(None) + } + fn validate_scalar( + &self, + residual: &OriginalDeviceResidual<'_, '_, 'ctx>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + call: &ScalarCall<'_>, + embedding: &OriginalMtpEmbedding<'_, 'ctx>, + ) -> Result<()> { + self.validate()?; + ring.validate_original_main(self.scratch.as_ref().ok_or(Error::ContextPoisoned)?)?; + ring.validate_snapshot(call.prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if self.shape_rejected(residual, ring, 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>, + ring: &MtpOriginalInt8<'ctx>, + call: &ScalarCall<'_>, + ) -> bool { + let len = call.tokens.len(); + !residual.context_matches(self.context) + || len != residual.rows() + || len > self.prompt_cap + || call.cell0.checked_add(len).is_none_or(|n| n > MTP_ORIGINAL_MAX_CELLS) + || ring.max_t < self.max_t + } + /// Original skips WHOLE groups whose end<=first_needed, not individual rows. + fn first_group(&self, call: &ScalarCall<'_>) -> Option { + let len = call.tokens.len(); + (0..len).step_by(self.max_t).find(|c| call.cell0 + *c + self.max_t.min(len - *c) > call.first_needed) + } + fn stage_scalar( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + operands: (&OriginalMtpScalarWeights<'_, 'ctx>, &OriginalMtpEmbedding<'_, 'ctx>), + ) -> Result { let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; + self.reject_input_alias(rh, rbytes)?; + self.reject_state_aliases(workspace, ring)?; + let (wh, eh) = self.stage_weights(rows, workspace, ring, operands, rh)?; + Ok(ScalarStaged { wh, eh, rh, rbytes }) + } + fn reject_input_alias(&self, rh: BufferHandle, rbytes: usize) -> Result<()> { for own in [&self.scratch, &self.records, &self.status].into_iter().flatten() { if rh.overlaps(rbytes, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { return Err(Error::OutputAliasesInput); } } + Ok(()) + } + fn reject_state_aliases(&self, workspace: &NativeBatchWorkspace<'ctx>, ring: &MtpOriginalInt8<'ctx>) -> Result<()> { for own in [&self.scratch, &self.records, &self.status].into_iter().flatten() { ring.reject_state_alias(own)?; let h = own.handle.ok_or(Error::ContextPoisoned)?; workspace.reject_alias(h, own.bytes)?; - for other in ring.buffers()?.iter().flatten() { - if h.overlaps(own.bytes, other.handle.ok_or(Error::ContextPoisoned)?, other.bytes) { - return Err(Error::OutputAliasesInput); - } + Self::reject_ring_overlap(ring, h, own.bytes)?; + } + Ok(()) + } + fn reject_ring_overlap(ring: &MtpOriginalInt8<'ctx>, h: BufferHandle, bytes: usize) -> Result<()> { + for other in ring.buffers()?.iter().flatten() { + if h.overlaps(bytes, other.handle.ok_or(Error::ContextPoisoned)?, other.bytes) { + return Err(Error::OutputAliasesInput); } } + Ok(()) + } + fn stage_weights( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + workspace: &NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + operands: (&OriginalMtpScalarWeights<'_, 'ctx>, &OriginalMtpEmbedding<'_, 'ctx>), + rh: BufferHandle, + ) -> Result<([BufferHandle; 11], BufferHandle)> { + let (weights, embedding) = operands; let wr = [ weights.input.embedding_norm, weights.input.embedding_fc, @@ -101,25 +169,17 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { weights.input.key_norm, weights.gr_inject, ]; - let extents = [ - 10240, - 2560 * 80 * 34, - 40960, - 2560 * 80 * 34, - 40960, - 320 * 10240 * 2, - 10240 * 320 * 2, - 512 * 80 * 34, - 512 * 80 * 34, - 1024, - 4 * 10240 * 2, - ]; let mut wh = [rh; 11]; for i in 0..11 { - wh[i] = self.external(rows, workspace, ring, wr[i], extents[i])?; + wh[i] = self.external(rows, workspace, ring, wr[i], SCALAR_EXTENTS[i])?; } let eh = self.external(rows, workspace, ring, embedding.table, embedding.table.bytes)?; - for i in 0..wr.len() { + Self::reject_overlapping_weights(&wh)?; + Ok((wh, eh)) + } + fn reject_overlapping_weights(wh: &[BufferHandle; 11]) -> Result<()> { + let extents = SCALAR_EXTENTS; + for i in 0..wh.len() { for j in 0..i { if wh[i].overlaps(extents[i], wh[j], extents[j]) && !(wh[i].qwen_address() == wh[j].qwen_address() && extents[i] == extents[j]) @@ -128,6 +188,16 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { } } } + Ok(()) + } + /// The first call pins the weights, the ring and the rope/GR policy; later calls must use the same. + fn claim_policy( + &mut self, + retained: &Rc>, + prior: &MtpInt8Snapshot, + policy: &OriginalMtpScalarPolicy, + ) -> Result<()> { + let kv = &policy.kv; let key = [ policy.gr as u32, policy.per_group_sync as u32, @@ -139,7 +209,7 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { kv.mscale.to_bits(), 0, ]; - if self.retained.as_ref().is_some_and(|old| !Rc::ptr_eq(old, &retained)) + if self.retained.as_ref().is_some_and(|old| !Rc::ptr_eq(old, retained)) || self.ring_id.as_ref().is_some_and(|id| !id.same_owner(&prior.owner_id())) || self.policy_key.is_some_and(|old| old != key) { @@ -148,340 +218,6 @@ impl<'ctx> OriginalMtpScalarPrefill<'ctx> { self.retained = Some(retained.clone()); self.ring_id = Some(prior.owner_id()); self.policy_key = Some(key); - let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; - let first_page = first / 4; - let count = end.div_ceil(4); - let mut pages = Vec::new(); - pages.try_reserve_exact(count).map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed.try_reserve_exact(count - first_page).map_err(|_| Error::HostAllocation)?; - for p in 0..count { - if p < first_page { - if let Some(old) = prior.0.pages.get(p) { - pages.push(old.clone()); - 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)?; - } - if p < first_page { - pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); - } else { - changed.push(runs); - } - } - // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. - let mut rec = zero_bytes(tokens.len() * 29 * 4)?; - let n = tokens.len(); - for (i, token) in tokens.iter().enumerate() { - let cell = cell0 + i; - rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); - for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() { - let off = (n + i * 4 + j) * 4; - rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - for h in 0..24 { - let off = (n * 5 + i * 24 + h) * 4; - rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); - } - } - let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; - let rec_h = rb.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(rb.bytes, 0, rec.len())?; - let mut staging = vec![(rec_h, rec)]; - let mut cmds = Vec::new(); - cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - ring.execute(workspace, Vec::new())?; - ring.restore(workspace, prior)?; - ring.current = None; - if !policy.per_group_sync { - self.upload_records(&mut staging)?; - } else { - self.upload_records(&mut Vec::new())?; - } - staging.clear(); - for (group, c) in (0..n).step_by(self.max_t).enumerate() { - let t = self.max_t.min(n - c); - if cell0 + c + t <= first_needed { - continue; - } - let rin = self.address(0, t * 40960)?; - let emb = self.address(2, t * 10240)?; - let en = self.address(3, t * 10240)?; - let e2 = self.address(4, t * 10240)?; - let hn = self.address(5, t * 40960)?; - let h2 = self.address(6, t * 40960)?; - let r = self.address(1, t * 40960)?; - let mixed = self.address(11, t * 10240)?; - let tok = self.address(12, t * 4)?; - let step = self.address(13, t * 16)?; - let pos = self.address(14, t * 96)?; - let mut copies = [ - (tok, rec_h.qwen_address() + (c * 4) as u64, t * 4), - (step, rec_h.qwen_address() + ((n + c * 4) * 4) as u64, t * 16), - (pos, rec_h.qwen_address() + ((n * 5 + c * 24) * 4) as u64, t * 96), - (rin, rh.checked_subspan(rbytes, c * 40960, t * 40960)?.qwen_address(), t * 40960), - ] - .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes }); - let needs_capture = self - .graphs - .as_mut() - .ok_or(Error::ContextPoisoned)? - .find_mut(OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !policy.per_group_sync })? - .is_none(); - if needs_capture { - // Captured per-T forward owns fixed whole scratch/status and stable arguments. - Self::kernel( - &mut cmds, - 0, - 11, - [1, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)], - )?; - if policy.per_group_sync { - let mapped = self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; - let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; - for (dst, offset, count) in - [(tok, 0, t), (step, self.max_t * 4, t * 4), (pos, self.max_t * 20, t * 24)] - { - Self::kernel( - &mut cmds, - 3, - 2, - [1, 1, 1], - [128, 1, 1], - 0, - vec![Arg::U64(dst), Arg::U64(m.address(offset, count * 4)?), Arg::I32(count as i32)], - )?; - } - } - match embedding.kind { - EmbeddingKind::Native { kind, row_bytes, .. } => Self::kernel( - &mut cmds, - 1, - 0, - [10, t as u32, 1], - [32, 1, 1], - 0, - vec![ - Arg::I32(kind), - Arg::U64(eh.qwen_address()), - Arg::U64(row_bytes as u64), - Arg::U64(tok), - Arg::I64(2560), - Arg::U64(emb), - ], - )?, - EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => Self::kernel( - &mut cmds, - 0, - 5, - [10, t as u32, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(eh.qwen_address()), - Arg::U64(eh.qwen_address() + codes as u64), - Arg::U64(if offsets { eh.qwen_address() + (codes + scales) as u64 } else { 0 }), - Arg::U64(tok), - Arg::I64(2560), - Arg::I32(bits), - Arg::I32(bias), - Arg::I32(group as i32), - Arg::U64((2560 / (8 / bits)) as u64), - Arg::U64((2560 / group) as u64), - Arg::U64(emb), - ], - )?, - } - self.finite(&mut cmds, emb, t * 2560, group, 0)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![Arg::U64(emb), Arg::U64(wh[0].qwen_address()), Arg::U64(en), Arg::I32(2560), Arg::F32(1e-6)], - )?; - self.finite(&mut cmds, en, t * 2560, group, 1)?; - let q = self.address(15, 8 * 80 * 36)?; - Self::quant(&mut cmds, en, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 2)?; - Self::project(&mut cmds, wh[1].qwen_address(), q, e2, t, 2560)?; - self.finite(&mut cmds, e2, t * 2560, group, 2)?; - Self::kernel( - &mut cmds, - 3, - 0, - [t as u32, 1, 1], - [1024, 1, 1], - 0, - vec![Arg::U64(rin), Arg::U64(wh[2].qwen_address()), Arg::U64(hn), Arg::I32(10240), Arg::F32(1e-6)], - )?; - self.finite(&mut cmds, hn, t * 10240, group, 3)?; - for hc in (0..t * 4).step_by(8) { - let cols = 8.min(t * 4 - hc); - Self::quant(&mut cmds, hn + (hc * 10240) as u64, q, cols)?; - self.q8_guard(&mut cmds, q, cols, group, 4)?; - Self::project(&mut cmds, wh[3].qwen_address(), q, h2 + (hc * 10240) as u64, cols, 2560)?; - } - self.finite(&mut cmds, h2, t * 10240, group, 4)?; - Self::kernel( - &mut cmds, - 0, - 4, - [40, t as u32, 1], - [256, 1, 1], - 0, - vec![Arg::U64(h2), Arg::U64(e2), Arg::U64(r), Arg::I64(2560), Arg::I32(4)], - )?; - self.finite(&mut cmds, r, t * 10240, group, 5)?; - self.gr(&mut cmds, t, &wh, policy)?; - self.finite(&mut cmds, self.address(9, t * 16)?, t * 4, group, 6)?; - self.finite(&mut cmds, self.address(7, t * 40960)?, t * 10240, group, 6)?; - self.finite(&mut cmds, self.address(8, t * 1280)?, t * 320, group, 7)?; - self.finite(&mut cmds, self.address(10, t * 16)?, t * 4, group, 7)?; - self.finite(&mut cmds, mixed, t * 2560, group, 8)?; - Self::quant(&mut cmds, mixed, q, t)?; - self.q8_guard(&mut cmds, q, t, group, 9)?; - let (kc, vc) = self.current_kv(ring)?; - Self::project(&mut cmds, wh[7].qwen_address(), q, kc, t, 512)?; - self.finite(&mut cmds, kc, t * 512, group, 10)?; - Self::project(&mut cmds, wh[8].qwen_address(), q, vc, t, 512)?; - self.finite(&mut cmds, vc, t * 512, group, 11)?; - for row in 0..t { - let k = kc + (row * 2048) as u64; - Self::kernel( - &mut cmds, - 2, - 9, - [2, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(k), Arg::U64(wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)], - )?; - self.finite(&mut cmds, k, 512, group, 12)?; - Self::kernel( - &mut cmds, - 3, - 1, - [4, 2, 1], - [32, 1, 1], - 0, - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::I32(64), - Arg::F32(kv.theta_scale), - Arg::F32(kv.freq_scale), - Arg::F32(kv.corr_low), - Arg::F32(kv.corr_high), - Arg::F32(kv.ext_factor), - Arg::F32(kv.mscale), - Arg::U64(pos + (row * 96) as u64), - Arg::U64(0), - Arg::Words3([0; 3]), - ], - )?; - self.finite(&mut cmds, k, 512, group, 13)?; - let mut host = [0u64; 8]; - host[2..6].copy_from_slice(&ring.host_addresses()?); - // Literal step append kernel and actual private step record, not batched prompt arithmetic. - Self::kernel( - &mut cmds, - 5, - 0, - [2, 4, 2], - [64, 1, 1], - 0, - vec![ - Arg::U64(ring.address(0)?), - Arg::U64(ring.address(1)?), - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step + (row * 16) as u64), - Arg::U64(k), - Arg::U64(vc + (row * 2048) as u64), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[2]), - Arg::U64(host[3]), - Arg::U64(host[4]), - Arg::U64(host[5]), - ], - )?; - } - Self::kernel( - &mut cmds, - 3, - 3, - [64, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(ring.address(2)?), - Arg::U64(ring.address(3)?), - Arg::U64(ring.address(4)?), - Arg::U64(step), - Arg::I32(t as i32), - Arg::U64(self.flag(0, 14)?), - ], - )?; - } - if cancelled() { - self.drain_graphs(rows, workspace)?; - return Ok(DraftKvOutcome::Cancelled); - } - if let Err(primary) = self.enqueue_group( - t, - group, - policy.per_group_sync, - &retained, - ring, - &mut cmds, - if policy.per_group_sync { &mut copies[3..] } else { &mut copies[..] }, - &tokens[c..c + t], - cell0 + c, - ) { - let drained = self.drain_graphs(rows, workspace); - return combine(Err(primary), drained); - } - cmds.clear(); - if policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - } - if !policy.per_group_sync { - self.drain_graphs(rows, workspace)?; - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - for (p, runs) in changed.iter_mut().enumerate() { - ring.read_encoded_page(first_page + p, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { runs: runs.map(Vec::into_boxed_slice) })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: ring.origin.clone(), - pages: Pages::from_vec(pages), - end, - checked: std::cell::Cell::new(false), - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { snapshot, first_materialized: first, end, generation })) + Ok(()) } } diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs new file mode 100644 index 00000000..db48a9c6 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_6.rs @@ -0,0 +1,95 @@ +//! Operands of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the call, the staged weights and the addresses of +//! one group of rows. + +#[allow(unused_imports)] +use super::*; + +/// What the caller of `record_impl` supplies besides the buffers. +pub(in super::super) struct ScalarCall<'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 OriginalMtpScalarPolicy, +} + +/// The weights, embedding table and prompt residual after the alias admission. +pub(in super::super) struct ScalarStaged { + pub(in super::super) wh: [BufferHandle; 11], + pub(in super::super) eh: BufferHandle, + pub(in super::super) rh: BufferHandle, + pub(in super::super) rbytes: usize, +} + +/// The scratch addresses of one group of `t` rows. +#[derive(Clone, Copy)] +pub(in super::super) struct GroupIo { + pub(in super::super) rin: u64, + pub(in super::super) emb: u64, + pub(in super::super) en: u64, + pub(in super::super) e2: u64, + pub(in super::super) hn: u64, + pub(in super::super) h2: u64, + pub(in super::super) r: u64, + pub(in super::super) mixed: u64, + pub(in super::super) tok: u64, + pub(in super::super) step: u64, + pub(in super::super) pos: u64, +} + +/// Everything the capture of one group reads. +pub(in super::super) struct Cap<'a, 'ctx> { + pub(in super::super) io: GroupIo, + pub(in super::super) wh: &'a [BufferHandle; 11], + pub(in super::super) eh: BufferHandle, + pub(in super::super) t: usize, + pub(in super::super) group: usize, + pub(in super::super) policy: &'a OriginalMtpScalarPolicy, + pub(in super::super) ring: &'a MtpOriginalInt8<'ctx>, + pub(in super::super) embedding: &'a OriginalMtpEmbedding<'a, 'ctx>, +} + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + /// The addresses of several scratch slots, resolved in the order given. + pub(in super::super) fn addresses(&self, specs: [(usize, usize); N]) -> Result<[u64; N]> { + let mut out = [0; N]; + for (k, (i, n)) in specs.into_iter().enumerate() { + out[k] = self.address(i, n)?; + } + Ok(out) + } + pub(in super::super) fn group_io(&self, t: usize) -> Result { + let [rin, emb, en, e2, hn, h2, r, mixed, tok, step, pos] = self.addresses([ + (0, t * 40960), + (2, t * 10240), + (3, t * 10240), + (4, t * 10240), + (5, t * 40960), + (6, t * 40960), + (1, t * 40960), + (11, t * 10240), + (12, t * 4), + (13, t * 16), + (14, t * 96), + ])?; + Ok(GroupIo { rin, emb, en, e2, hn, h2, r, mixed, tok, step, pos }) + } + /// The four copies that stage the token, step and position records and the residual into the group's scratch. + pub(in super::super) fn group_copies( + io: &GroupIo, + rec_h: BufferHandle, + residual: (BufferHandle, usize), + at: (usize, usize, usize), + ) -> Result<[ScalarCommand; 4]> { + let (n, c, t) = at; + let rec = rec_h.qwen_address(); + let rin = residual.0.checked_subspan(residual.1, c * 40960, t * 40960)?.qwen_address(); + Ok([ + (io.tok, rec + (c * 4) as u64, t * 4), + (io.step, rec + ((n + c * 4) * 4) as u64, t * 16), + (io.pos, rec + ((n * 5 + c * 24) * 4) as u64, t * 96), + (io.rin, rin, t * 40960), + ] + .map(|(dst, src, bytes)| ScalarCommand::Copy { dst, src, bytes })) + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs new file mode 100644 index 00000000..5cb1d370 --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_7.rs @@ -0,0 +1,192 @@ +//! The group loop of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the page and record staging, the per-group +//! graph capture and enqueue, and the publication of the completed range. + +#[allow(unused_imports)] +use super::*; + +/// Fills the `[tokens n][steps4*n][positions24*n]` records of a prompt. +fn fill_records(rec: &mut [u8], tokens: &[i32], cell0: usize) { + let n = tokens.len(); + for (i, token) in tokens.iter().enumerate() { + let cell = cell0 + i; + rec[i * 4..i * 4 + 4].copy_from_slice(&token.to_le_bytes()); + for (j, v) in [cell, cell + 1, (cell + 1) / 4, cell + 1].into_iter().enumerate() { + let off = (n + i * 4 + j) * 4; + rec[off..off + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + for h in 0..24 { + let off = (n * 5 + i * 24 + h) * 4; + rec[off..off + 4].copy_from_slice(&(cell as i32).to_le_bytes()); + } + } +} + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + /// Stages the pages and records, restores the ring and records every group; publishes the completed range. + #[allow(clippy::too_many_arguments)] + pub(in super::super) fn record_groups( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + at: (&ScalarCall<'_>, usize), + operands: (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + let (call, first_group) = at; + let generation = ring.generation.checked_add(1).ok_or(Error::InvalidQwenShape)?; + let (first, end) = (call.cell0 + first_group, call.cell0 + call.tokens.len()); + let first_page = first / 4; + let (pages, changed) = OriginalMtpPrefill::prepare_pages(call.prior, end, first_page)?; + // Literal prefill records [tokens n][steps4*n][positions24*n], one upload. + let (rec_h, rec) = self.build_records(call)?; + let mut staging = vec![(rec_h, rec)]; + let mut cmds = Vec::new(); + cmds.try_reserve(128).map_err(|_| Error::HostAllocation)?; + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + self.restore_and_upload(workspace, ring, call, &mut staging)?; + if let Some(outcome) = + self.run_groups(rows, workspace, ring, (call, operands), (rec_h, &mut cmds), cancelled)? + { + return Ok(outcome); + } + self.complete(rows, workspace, ring, call, (pages, changed), (first_page, first, end, generation), cancelled) + } + fn build_records(&self, call: &ScalarCall<'_>) -> Result<(BufferHandle, Vec)> { + let mut rec = zero_bytes(call.tokens.len() * 29 * 4)?; + fill_records(&mut rec, call.tokens, call.cell0); + let rb = self.records.as_ref().ok_or(Error::ContextPoisoned)?; + let rec_h = rb.handle.ok_or(Error::ContextPoisoned)?.checked_subspan(rb.bytes, 0, rec.len())?; + Ok((rec_h, rec)) + } + fn restore_and_upload( + &mut self, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &ScalarCall<'_>, + staging: &mut Vec<(BufferHandle, Vec)>, + ) -> Result<()> { + ring.execute(workspace, Vec::new())?; + ring.restore(workspace, call.prior)?; + ring.current = None; + if !call.policy.per_group_sync { + self.upload_records(staging)?; + } else { + self.upload_records(&mut Vec::new())?; + } + staging.clear(); + Ok(()) + } + #[allow(clippy::too_many_arguments)] + fn run_groups( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + ctx: ( + &ScalarCall<'_>, + (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), + ), + buf: (BufferHandle, &mut Vec), + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + let (call, operands) = ctx; + let (rec_h, cmds) = buf; + let n = call.tokens.len(); + for (group, c) in (0..n).step_by(self.max_t).enumerate() { + let t = self.max_t.min(n - c); + if call.cell0 + c + t <= call.first_needed { + continue; + } + let at = (group, c, t); + if let Some(o) = + self.run_group(rows, workspace, ring, (call, operands), (at, rec_h, &mut *cmds), cancelled)? + { + return Ok(Some(o)); + } + } + Ok(None) + } + #[allow(clippy::too_many_arguments)] + fn run_group( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + ctx: ( + &ScalarCall<'_>, + (&ScalarStaged, &Rc>, &OriginalMtpEmbedding<'_, 'ctx>), + ), + buf: ((usize, usize, usize), BufferHandle, &mut Vec), + cancelled: &mut impl FnMut() -> bool, + ) -> Result> { + let (call, (st, retained, embedding)) = ctx; + let (at, rec_h, cmds) = buf; + let (group, c, t) = at; + let io = self.group_io(t)?; + let mut copies = Self::group_copies(&io, rec_h, (st.rh, st.rbytes), (call.tokens.len(), c, t))?; + if self.needs_capture(t, call.policy.per_group_sync)? { + let cap = Cap { io, wh: &st.wh, eh: st.eh, t, group, policy: call.policy, ring, embedding }; + self.capture_group(cmds, &cap)?; + } + if cancelled() { + self.drain_graphs(rows, workspace)?; + return Ok(Some(DraftKvOutcome::Cancelled)); + } + self.submit_group(rows, workspace, ring, (call, retained), (at, cmds, &mut copies))?; + Ok(None) + } + fn needs_capture(&mut self, t: usize, per_group_sync: bool) -> Result { + let key = OriginalGraphKey::MtpPrefill { rows: t as u8, device_inputs: !per_group_sync }; + Ok(self.graphs.as_mut().ok_or(Error::ContextPoisoned)?.find_mut(key)?.is_none()) + } + fn submit_group( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &MtpOriginalInt8<'ctx>, + ctx: (&ScalarCall<'_>, &Rc>), + run: ((usize, usize, usize), &mut Vec, &mut [ScalarCommand; 4]), + ) -> Result<()> { + let (call, retained) = ctx; + let ((group, c, t), cmds, copies) = run; + let sync = call.policy.per_group_sync; + let copies = if sync { &mut copies[3..] } else { &mut copies[..] }; + let tokens = &call.tokens[c..c + t]; + if let Err(primary) = self.enqueue_group(t, group, sync, retained, ring, cmds, copies, tokens, call.cell0 + c) { + let drained = self.drain_graphs(rows, workspace); + return combine(Err(primary), drained); + } + cmds.clear(); + if sync { + self.drain_graphs(rows, workspace)?; + } + Ok(()) + } + /// Drains the last graphs, reads the encoded pages back and publishes the completed range. + #[allow(clippy::too_many_arguments)] + fn complete( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + call: &ScalarCall<'_>, + pages: (Vec>, Vec<[Vec; 4]>), + range: (usize, usize, usize, u64), + cancelled: &mut impl FnMut() -> bool, + ) -> Result { + let ((pages, mut changed), (first_page, first, end, generation)) = (pages, range); + if !call.policy.per_group_sync { + self.drain_graphs(rows, workspace)?; + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + for (p, runs) in changed.iter_mut().enumerate() { + ring.read_encoded_page(first_page + p, runs)?; + } + Ok(OriginalMtpPrefill::finish(ring, pages, changed, (first, end, generation))) + } +} diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs new file mode 100644 index 00000000..8902776e --- /dev/null +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill/impl_originalmtpscalarprefill/impl_originalmtpscalarprefill_8.rs @@ -0,0 +1,199 @@ +//! Capture of one group of `OriginalMtpScalarPrefill::record_impl` (STRA-338): the per-T forward owns fixed whole +//! scratch/status and stable arguments; its commands are recorded in the order of the former single function. + +#[allow(unused_imports)] +use super::*; + +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + /// Captured per-T forward owns fixed whole scratch/status and stable arguments. + pub(in super::super) fn capture_group(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + self.cap_inputs(cmds, cap)?; + self.cap_embedding(cmds, cap)?; + let q = self.cap_embed_chain(cmds, cap)?; + self.cap_hidden(cmds, cap, q)?; + self.cap_gr(cmds, cap)?; + let kv = self.cap_kv(cmds, cap, q)?; + for row in 0..cap.t { + self.cap_row(cmds, cap, row, kv)?; + } + self.cap_commit(cmds, cap) + } + fn cap_inputs(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + Self::kernel(cmds, 0, 11, [1, 1, 1], [256, 1, 1], 0, vec![Arg::U64(self.flag(0, 0)?), Arg::I32(64)])?; + if cap.policy.per_group_sync { + self.cap_map_inputs(cmds, cap)?; + } + Ok(()) + } + fn cap_map_inputs(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + let (io, t, max_t) = (&cap.io, cap.t, self.max_t); + let mapped = self.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + let m = mapped.as_ref().ok_or(Error::ContextPoisoned)?; + for (dst, offset, count) in [(io.tok, 0, t), (io.step, max_t * 4, t * 4), (io.pos, max_t * 20, t * 24)] { + let args = vec![Arg::U64(dst), Arg::U64(m.address(offset, count * 4)?), Arg::I32(count as i32)]; + Self::kernel(cmds, 3, 2, [1, 1, 1], [128, 1, 1], 0, args)?; + } + Ok(()) + } + fn cap_embedding(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + match cap.embedding.kind { + EmbeddingKind::Native { kind, row_bytes, .. } => Self::lookup_native(cmds, cap, kind, row_bytes), + EmbeddingKind::Compressed { bits, bias, group, codes, scales, offsets, .. } => { + let eh = cap.eh.qwen_address(); + let offsets = if offsets { eh + (codes + scales) as u64 } else { 0 }; + let args = vec![ + Arg::U64(eh), + Arg::U64(eh + codes as u64), + Arg::U64(offsets), + Arg::U64(cap.io.tok), + Arg::I64(2560), + Arg::I32(bits), + Arg::I32(bias), + Arg::I32(group as i32), + Arg::U64((2560 / (8 / bits)) as u64), + Arg::U64((2560 / group) as u64), + Arg::U64(cap.io.emb), + ]; + Self::kernel(cmds, 0, 5, [10, cap.t as u32, 1], [256, 1, 1], 0, args) + } + } + } + fn lookup_native(cmds: &mut Vec, cap: &Cap<'_, 'ctx>, kind: i32, row_bytes: usize) -> Result<()> { + let eh = cap.eh.qwen_address(); + let args = vec![ + Arg::I32(kind), + Arg::U64(eh), + Arg::U64(row_bytes as u64), + Arg::U64(cap.io.tok), + Arg::I64(2560), + Arg::U64(cap.io.emb), + ]; + Self::kernel(cmds, 1, 0, [10, cap.t as u32, 1], [32, 1, 1], 0, args) + } + /// The embedding half: finite guard, RMS norm and the Q8 projection into `e2`; returns the Q8 scratch. + fn cap_embed_chain(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result { + let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); + self.finite(cmds, io.emb, t * 2560, g, 0)?; + let norm = + vec![Arg::U64(io.emb), Arg::U64(wh[0].qwen_address()), Arg::U64(io.en), Arg::I32(2560), Arg::F32(1e-6)]; + Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?; + self.finite(cmds, io.en, t * 2560, g, 1)?; + let q = self.address(15, 8 * 80 * 36)?; + Self::quant(cmds, io.en, q, t)?; + self.q8_guard(cmds, q, t, g, 2)?; + Self::project(cmds, wh[1].qwen_address(), q, io.e2, t, 2560)?; + self.finite(cmds, io.e2, t * 2560, g, 2)?; + Ok(q) + } + /// The hidden half: RMS norm of the residual and the Q8 projection into `h2`, eight columns at a time. + fn cap_hidden(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, q: u64) -> Result<()> { + let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); + let norm = + vec![Arg::U64(io.rin), Arg::U64(wh[2].qwen_address()), Arg::U64(io.hn), Arg::I32(10240), Arg::F32(1e-6)]; + Self::kernel(cmds, 3, 0, [t as u32, 1, 1], [1024, 1, 1], 0, norm)?; + self.finite(cmds, io.hn, t * 10240, g, 3)?; + for hc in (0..t * 4).step_by(8) { + let cols = 8.min(t * 4 - hc); + Self::quant(cmds, io.hn + (hc * 10240) as u64, q, cols)?; + self.q8_guard(cmds, q, cols, g, 4)?; + Self::project(cmds, wh[3].qwen_address(), q, io.h2 + (hc * 10240) as u64, cols, 2560)?; + } + self.finite(cmds, io.h2, t * 10240, g, 4) + } + fn cap_gr(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + let (io, t, g) = (&cap.io, cap.t, cap.group); + let args = vec![Arg::U64(io.h2), Arg::U64(io.e2), Arg::U64(io.r), Arg::I64(2560), Arg::I32(4)]; + Self::kernel(cmds, 0, 4, [40, t as u32, 1], [256, 1, 1], 0, args)?; + self.finite(cmds, io.r, t * 10240, g, 5)?; + self.gr(cmds, t, cap.wh, cap.policy)?; + self.cap_gr_guards(cmds, cap) + } + fn cap_gr_guards(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + let (t, g) = (cap.t, cap.group); + self.finite(cmds, self.address(9, t * 16)?, t * 4, g, 6)?; + self.finite(cmds, self.address(7, t * 40960)?, t * 10240, g, 6)?; + self.finite(cmds, self.address(8, t * 1280)?, t * 320, g, 7)?; + self.finite(cmds, self.address(10, t * 16)?, t * 4, g, 7)?; + self.finite(cmds, cap.io.mixed, t * 2560, g, 8) + } + /// The K and V projections of the mixed state into the current KV; returns their addresses. + fn cap_kv(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, q: u64) -> Result<(u64, u64)> { + let (io, wh, t, g) = (&cap.io, cap.wh, cap.t, cap.group); + Self::quant(cmds, io.mixed, q, t)?; + self.q8_guard(cmds, q, t, g, 9)?; + let (kc, vc) = self.current_kv(cap.ring)?; + Self::project(cmds, wh[7].qwen_address(), q, kc, t, 512)?; + self.finite(cmds, kc, t * 512, g, 10)?; + Self::project(cmds, wh[8].qwen_address(), q, vc, t, 512)?; + self.finite(cmds, vc, t * 512, g, 11)?; + Ok((kc, vc)) + } + /// K norm and rope, then the step append kernel for one row. + fn cap_row(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, row: usize, kv: (u64, u64)) -> Result<()> { + let (kc, vc) = kv; + let k = kc + (row * 2048) as u64; + let norm = vec![Arg::U64(k), Arg::U64(cap.wh[9].qwen_address()), Arg::U64(k), Arg::I32(256), Arg::F32(1e-6)]; + Self::kernel(cmds, 2, 9, [2, 1, 1], [256, 1, 1], 0, norm)?; + self.finite(cmds, k, 512, cap.group, 12)?; + Self::cap_rope(cmds, cap, row, k)?; + self.finite(cmds, k, 512, cap.group, 13)?; + self.cap_append(cmds, cap, row, (k, vc)) + } + fn cap_rope(cmds: &mut Vec, cap: &Cap<'_, 'ctx>, row: usize, k: u64) -> Result<()> { + let kv = &cap.policy.kv; + let args = vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::I32(64), + Arg::F32(kv.theta_scale), + Arg::F32(kv.freq_scale), + Arg::F32(kv.corr_low), + Arg::F32(kv.corr_high), + Arg::F32(kv.ext_factor), + Arg::F32(kv.mscale), + Arg::U64(cap.io.pos + (row * 96) as u64), + Arg::U64(0), + Arg::Words3([0; 3]), + ]; + Self::kernel(cmds, 3, 1, [4, 2, 1], [32, 1, 1], 0, args) + } + /// Literal step append kernel and actual private step record, not batched prompt arithmetic. + fn cap_append(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>, row: usize, kv: (u64, u64)) -> Result<()> { + let (k, vc) = kv; + let ring = cap.ring; + let mut host = [0u64; 8]; + host[2..6].copy_from_slice(&ring.host_addresses()?); + let args = vec![ + Arg::U64(ring.address(0)?), + Arg::U64(ring.address(1)?), + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(cap.io.step + (row * 16) as u64), + Arg::U64(k), + Arg::U64(vc + (row * 2048) as u64), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[2]), + Arg::U64(host[3]), + Arg::U64(host[4]), + Arg::U64(host[5]), + ]; + Self::kernel(cmds, 5, 0, [2, 4, 2], [64, 1, 1], 0, args) + } + fn cap_commit(&self, cmds: &mut Vec, cap: &Cap<'_, 'ctx>) -> Result<()> { + let ring = cap.ring; + let args = vec![ + Arg::U64(ring.address(2)?), + Arg::U64(ring.address(3)?), + Arg::U64(ring.address(4)?), + Arg::U64(cap.io.step), + Arg::I32(cap.t as i32), + Arg::U64(self.flag(0, 14)?), + ]; + Self::kernel(cmds, 3, 3, [64, 1, 1], [256, 1, 1], 0, args) + } +}