diff --git a/crates/cuda-driver/src/mtp_original_int8.rs b/crates/cuda-driver/src/mtp_original_int8.rs index caeb144e..5cc0832a 100644 --- a/crates/cuda-driver/src/mtp_original_int8.rs +++ b/crates/cuda-driver/src/mtp_original_int8.rs @@ -1,1568 +1,1579 @@ -//! Literal Original MTP INT8 ring and record_forward(full=false) attention tail. -//! Input/GR and runtime causal authority are separate genuine producer obligations. -//! No F16 ring, whole warm_step, prompt-attention, or host-float readiness substitute. -#[path = "mtp_original_int8_ffi.rs"] -#[allow(unsafe_code)] -mod abi; -#[path = "mtp_original_ring_state.rs"] -mod ring_state; -use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; -use abi::{Arg, Arguments, MappedOwner, Module}; -use std::{ - cell::{Cell, Ref, RefCell, RefMut}, - rc::Rc, -}; - -pub const MTP_ORIGINAL_WINDOW: usize = 32768; -/// The MTP drafter bank is FROZEN at the trained 262144-cell geometry (its mapped host image, page table and -/// ring layouts are literal). It is deliberately NOT derived from the serving context: -/// `validate_existing_int8_bank` refuses any other session geometry, and the runtime refuses the MTP modes for a -/// context past the trained one. Re-deriving and qualifying it is a separate piece of work. -pub const MTP_ORIGINAL_MAX_CELLS: usize = 262144; -pub const MTP_ORIGINAL_PINNED_HOST_BYTES: usize = 276825088; -pub const MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES: usize = 276824064; -const RESERVE: usize = 128 * 1024 * 1024; -const PAGE_BYTES: [usize; 4] = [2048, 2048, 64, 64]; -const HOST_RUNS: [usize; 4] = [134217728, 134217728, 4194304, 4194304]; -const HOST_OFFSETS: [usize; 4] = [0, 134217728, 268435456, 272629760]; -const CHUNKS: usize = 512; -const SCRATCH_FLOATS: usize = CHUNKS * 24 * (256 + 2); -const STATUS_WORDS: usize = 21; // four leading stages, two per real row, final scale scan -const TAIL_ENTRIES: &[&std::ffi::CStr] = &[ - c"mtp_original_quantize", - c"mtp_original_q80_1", - c"mtp_original_q80_2", - c"mtp_original_q80_3", - c"mtp_original_q80_4", - c"mtp_original_q80_5", - c"mtp_original_q80_6", - c"mtp_original_q80_7", - c"mtp_original_q80_8", - c"mtp_original_knorm", - c"mtp_original_krope", - c"mtp_original_finite", - c"mtp_original_q8_guard", -]; -const KV_ENTRIES: &[&std::ffi::CStr] = &[ - c"mtp_original_append", - c"mtp_original_ring_table", - c"mtp_original_window_ids", - c"mtp_original_encoded_guard", -]; -const ATTN_ENTRIES: &[&std::ffi::CStr] = &[ - c"leleka_qsa_prompt_guard", - c"leleka_qsa_decode_chunk", - c"leleka_qsa_decode_merge", - c"leleka_qsa_prompt_output_guard", -]; -struct Origin; -#[derive(Clone)] -pub struct MtpInt8OwnerId(Rc); -impl MtpInt8OwnerId { - pub fn same_owner(&self, other: &Self) -> bool { - Rc::ptr_eq(&self.0, &other.0) - } -} - -#[path = "mtp_original_logical_prefix.rs"] -mod logical_prefix; -pub use logical_prefix::OriginalMtpSkippedPrefix; -// The literal prefill producer is an MTP child because it borrows this -// owner's private ring/state types. Its public contracts are re-exported by -// the crate integration point below. -#[path = "mtp_original_prefill.rs"] -mod prefill; -pub(crate) use prefill::session_assets_sealed; -pub use prefill::{ - CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, - OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, - OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, - OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, - OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, - OriginalMtpStepOutput, -}; -struct Page { - runs: [Box<[u8]>; 4], -} -struct Snapshot { - origin: Rc, - pages: Rc]>>, - end: usize, -} -/// Immutable actual encoded bytes; runtime binds these to its genuine MTP epoch. -#[derive(Clone)] -pub struct MtpInt8Snapshot(Rc); -impl MtpInt8Snapshot { - pub fn owner_id(&self) -> MtpInt8OwnerId { - MtpInt8OwnerId(self.0.origin.clone()) - } - pub fn next_position(&self) -> usize { - self.0.end - } - pub fn encoded_bytes(&self) -> usize { - self.0.pages.len() * 4224 - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::() - + std::mem::size_of::() - + 8 * std::mem::size_of::() - + self.0.pages.len() - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) - } -} -/// Created only inside the actual driver input+fused-GR producer integration. -/// Public constructors accepting arbitrary floats or a caller readiness bit do not exist. -pub struct MtpOriginalMixed<'loan, 'buffers> { - mixed: &'loan DeviceBuffer<'buffers>, - first: usize, - rows: usize, -} -impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { - pub(crate) fn from_completed_gr( - c: &Context<'_>, - mixed: &'loan DeviceBuffer<'buffers>, - first: usize, - rows: usize, - ) -> Result { - rows_range(first, rows, 8)?; - checked(c, mixed, rows * 2560 * 4)?; - Ok(Self { mixed, first, rows }) - } - pub fn rows(&self) -> usize { - self.rows - } - pub fn first_position(&self) -> usize { - self.first - } -} -/// Real native normalized/RoPE query, minted by the actual scalar full-draft producer. -pub struct MtpOriginalQuery<'loan, 'buffers> { - query: &'loan DeviceBuffer<'buffers>, -} -impl<'loan, 'buffers> MtpOriginalQuery<'loan, 'buffers> { - pub(crate) fn from_completed_native( - c: &Context<'_>, - query: &'loan DeviceBuffer<'buffers>, - ) -> Result { - checked(c, query, 6144 * 4)?; - Ok(Self { query }) - } -} -/// Replay completion retains actual ring and immutable whole-weight/input loans. -pub struct CompletedMtpKvReplay<'loan, 'ctx, 'buffers, 'weights> { - owner: &'loan mut MtpOriginalInt8<'ctx>, - snapshot: MtpInt8Snapshot, - _mixed: &'loan MtpOriginalMixed<'loan, 'buffers>, - _weights: [&'loan DeviceBuffer<'weights>; 3], - first: usize, - rows: usize, -} -impl CompletedMtpKvReplay<'_, '_, '_, '_> { - pub fn rows(&self) -> usize { - self.rows - } - pub fn final_snapshot(&self) -> &MtpInt8Snapshot { - &self.snapshot - } - /// End can only be derived from a real row of this completed append. - pub fn snapshot_after(&self, row: usize) -> Result { - self.owner.validate()?; - if row >= self.rows { - return Err(Error::InvalidQwenShape); - } - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.snapshot.0.origin.clone(), - pages: self.snapshot.0.pages.clone(), - end: self.first + row + 1, - }))) - } - pub fn into_final_snapshot(self) -> MtpInt8Snapshot { - self.snapshot - } -} -pub struct CompletedMtpAttention<'loan, 'ctx, 'buffers> { - owner: &'loan mut MtpOriginalInt8<'ctx>, - _snapshot: &'loan MtpInt8Snapshot, - _query: &'loan MtpOriginalQuery<'loan, 'buffers>, -} -impl CompletedMtpAttention<'_, '_, '_> { - pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>) -> Result) -> Result { - self.owner.validate()?; - f(self.owner.buffer(11)?) - } - pub fn into_values(self) -> Result> { - self.owner.validate()?; - let bytes = self.owner.buffer(11)?.copy_to_owned(6144 * 4)?; - let mut out = Vec::new(); - out.try_reserve_exact(6144) - .map_err(|_| Error::HostAllocation)?; - for x in bytes.chunks_exact(4) { - out.push(f32::from_le_bytes( - x.try_into().map_err(|_| Error::InvalidSize)?, - )); - } - Ok(out.into_boxed_slice()) - } -} -enum Command { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, -} -/// Actual model-lifetime physical allocations. Causal current/generation lives -/// only on MtpOriginalInt8. Graph resources retain this Rc without a RefCell loan. -/// Only bounded CPU mapped-page accesses take short exclusive mapped borrows. -struct PhysicalRing<'ctx> { - context: &'ctx Context<'ctx>, - origin: Rc, - sizes: [usize; 15], - buffers: [Option>; 15], - modules: [Option; 3], - mapped: RefCell>, - selected: Option>, - failed: Cell, - active: Cell, -} -/// Opaque genuine physical retention minted only by this ring. No caller pointer, -/// bytes or ready marker can construct a token. It is not a causal state proof. -pub struct MtpOriginalRingResources<'ctx> { - physical: Rc>, -} -impl Clone for MtpOriginalRingResources<'_> { - fn clone(&self) -> Self { - Self { - physical: Rc::clone(&self.physical), - } - } -} -impl MtpOriginalRingResources<'_> { - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - self.physical.validate_context(c) - } - pub fn owner_id(&self) -> MtpInt8OwnerId { - MtpInt8OwnerId(self.physical.origin.clone()) - } - pub fn allocated_bytes(&self) -> usize { - self.physical - .buffers - .iter() - .flatten() - .map(|b| b.bytes) - .sum::() - + self - .physical - .selected - .as_ref() - .map_or(0, |s| s.unique_bytes()) - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::>() - + 2 * std::mem::size_of::() - + std::mem::size_of::() - } -} -impl PhysicalRing<'_> { - fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - if !self.active.get() - || self.failed.get() - || c.is_poisoned() - || c.handle.is_none() - || self.modules.iter().any(Option::is_none) - || (self.selected.is_none() - && self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none()) - { - return Err(Error::ContextPoisoned); - } - for (i, b) in self.buffers.iter().enumerate() { - if let Some(b) = b { - checked(c, b, self.sizes[i])?; - } else if !self.selected.as_ref().is_some_and(|s| s.provides(i)) { - return Err(Error::ContextPoisoned); - } - } - if let Some(s) = &self.selected { - s.validate(c)?; - } - Ok(()) - } - fn close_inner(&mut self) -> Result<()> { - self.active.set(false); - self.failed.set(true); - let mut result = Ok(()); - // Same original module -> mapped -> device order and primary arbitration. - // A poisoned Context retains every actual physical owner and its charge. - for m in &mut self.modules { - if let Some(module) = m.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(module); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(module.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(module); - Err(e) - } - } - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - } - if let Some(mut mapped) = self.mapped.get_mut().take() { - let close = if self.context.is_poisoned() { - std::mem::forget(mapped); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => { - let op = mapped.close(); - let pop = g.finish(); - combine(op, pop) - } - Err(e) => { - self.context.poison(); - std::mem::forget(mapped); - Err(e) - } - } - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - if let Some(mut s) = self.selected.take() { - result = combine(result, s.close()); - } - for b in &mut self.buffers { - if let Some(buffer) = b.take() { - let close = if self.context.is_poisoned() { - std::mem::forget(buffer); - Err(Error::ContextPoisoned) - } else { - buffer.release() - }; - if close.is_err() { - self.context.poison(); - } - result = combine(result, close); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - result - } -} -impl Drop for PhysicalRing<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} -/// One Context-affine model owner. The literal selected plain INT8, unrotated -/// 32K-window profile is explicit. Other Original formats/options remain separate. -pub struct MtpOriginalInt8<'ctx> { - context: &'ctx Context<'ctx>, - origin: Rc, - max_t: usize, - slots: usize, - sizes: [usize; 15], - physical: Option>>, - current: Option, - failed: bool, - generation: u64, -} -fn zero_bytes(n: usize) -> Result> { - let mut v = Vec::new(); - v.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; - v.resize(n, 0); - Ok(v) -} -fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result { - if !std::ptr::eq(c, b.context) { - return Err(Error::ContextMismatch); - } - if b.bytes != n { - return Err(Error::InvalidQwenShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(n, 4)?; - Ok(h.qwen_address()) -} -fn rows_range(first: usize, rows: usize, max_t: usize) -> Result<()> { - if !(1..=max_t).contains(&rows) - || first - .checked_add(rows) - .is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) -} -fn layout(t: usize) -> Result<(usize, [usize; 15])> { - if !(1..=8).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let slots = (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4); - Ok(( - slots, - [ - slots * 2048, - slots * 2048, - slots * 64, - slots * 64, - 65536 * 4, - t * 2880, - t * 2048, - t * 2048, - t * 24 * 4, - t * 4 * 4, - STATUS_WORDS * 4, - 6144 * 4, - SCRATCH_FLOATS * 4, - MTP_ORIGINAL_WINDOW * 4, - 16, - ], - )) -} -impl Context<'_> { - pub fn mtp_original_int8(&self, max_t: usize) -> Result> { - MtpOriginalInt8::new(self, max_t) - } -} -impl<'ctx> MtpOriginalInt8<'ctx> { - pub fn planned_device_bytes(max_t: usize) -> Result { - Ok(layout(max_t)?.1.into_iter().sum()) - } - pub fn pinned_host_bytes() -> usize { - MTP_ORIGINAL_PINNED_HOST_BYTES - } - pub fn max_snapshot_payload_bytes() -> usize { - MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES - } - pub fn max_snapshot_metadata_bytes() -> usize { - std::mem::size_of::() - + std::mem::size_of::() - + 8 * std::mem::size_of::() - + 65536 - * (std::mem::size_of::>() - + std::mem::size_of::() - + 2 * std::mem::size_of::()) - } - fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { - let (slots, sizes) = layout(max_t)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - // Refuse placeholders before any host or device owner allocation. - for ptx in [ - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ] { - if ptx.windows(8).any(|w| w == b"UNSEALED") { - return Err(Error::UnsupportedQwenOperation); - } - } - let needed = sizes - .into_iter() - .sum::() - .checked_add(RESERVE) - .ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(needed) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < needed - { - return Err(Error::BudgetExceeded); - } - let origin = Rc::new(Origin); - let physical = Rc::new(PhysicalRing { - context: c, - origin: origin.clone(), - sizes, - buffers: std::array::from_fn(|_| None), - modules: std::array::from_fn(|_| None), - mapped: RefCell::new(None), - selected: None, - failed: Cell::new(false), - active: Cell::new(true), - }); - let mut o = Self { - context: c, - origin, - max_t, - slots, - sizes, - physical: Some(physical), - current: None, - failed: false, - generation: 0, - }; - let operation = (|| { - let guard = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.physical_mut()?.modules[0] = Some(Module::load( - include_bytes!("mtp_original_tail.ptx"), - TAIL_ENTRIES, - )?); - o.physical_mut()?.modules[1] = Some(Module::load( - include_bytes!("mtp_original_kv.ptx"), - KV_ENTRIES, - )?); - o.physical_mut()?.modules[2] = Some(Module::load( - include_bytes!("qsa_native_decode.ptx"), - ATTN_ENTRIES, - )?); - *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); - if o.physical()? - .mapped - .borrow() - .as_ref() - .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) - { - return Err(Error::InvalidSize); - } - Ok(()) - })(); - let pop = guard.finish(); - if pop.is_err() { - o.poison(); - } - combine(load, pop)?; - for (i, n) in sizes.into_iter().enumerate() { - o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); - } - // Real initialized pools; no reader ever names an unwritten logical cell. - for i in 0..4 { - o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; - } - let mut table = zero_bytes(65536 * 4)?; - for (p, b) in table.chunks_exact_mut(4).enumerate() { - b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); - } - o.copy_from_physical(4, &table)?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - fn physical(&self) -> Result<&PhysicalRing<'ctx>> { - self.physical.as_deref().ok_or(Error::ContextPoisoned) - } - fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { - Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) - .ok_or(Error::InvalidQwenShape) - } - fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { - self.physical()? - .buffers - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn buffers(&self) -> Result<&[Option>; 15]> { - Ok(&self.physical()?.buffers) - } - fn mapped(&self) -> Result> { - Ref::filter_map( - self.physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_ref, - ) - .map_err(|_| Error::ContextPoisoned) - } - fn mapped_mut(&self) -> Result> { - RefMut::filter_map( - self.physical()? - .mapped - .try_borrow_mut() - .map_err(|_| Error::InvalidQwenShape)?, - Option::as_mut, - ) - .map_err(|_| Error::ContextPoisoned) - } - fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return s.copy_from(i, 0, input); - } - } - let b = self.buffer(i)?; - let mut staging = b.staging(input.len())?; - staging.copy_from_slice(input); - b.copy_staged(staging, false).map(|_| ()) - } - pub(crate) fn retain_physical_resources(&self) -> Result> { - self.validate()?; - Ok(MtpOriginalRingResources { - physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), - }) - } - pub fn physical_metadata_bytes() -> usize { - std::mem::size_of::>() + 2 * std::mem::size_of::() - } - - fn address(&self, i: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); - } - } - checked(self.context, self.buffer(i)?, self.sizes[i]) - } - fn sub(&self, i: usize, o: usize, n: usize) -> Result { - if let Some(s) = &self.physical()?.selected { - if s.provides(i) { - return Ok(s.span(i, o, n)?.qwen_address()); - } - } - Ok(self - .buffer(i)? - .handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(self.sizes[i], o, n)? - .qwen_address()) - } - pub fn allocated_bytes(&self) -> usize { - self.physical.as_ref().map_or(0, |p| { - p.buffers.iter().flatten().map(|b| b.bytes).sum::() - + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) - }) - } - pub fn is_failed(&self) -> bool { - self.failed - || self.context.is_poisoned() - || self.context.handle.is_none() - || self - .physical - .as_ref() - .is_none_or(|p| p.failed.get() || !p.active.get()) - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - fn validate(&self) -> Result<()> { - if self.is_failed() { - return Err(Error::ContextPoisoned); - } - self.physical()?.validate_context(self.context)?; - for i in 0..15 { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(i)) - { - continue; - } - let b = self.buffer(i)?; - checked(self.context, b, self.sizes[i])?; - if let Some(s) = &self.physical()?.selected { - s.reject_state_alias(b)?; - s.reject_main_alias(b)?; - } - for j in 0..i { - if self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.provides(j)) - { - continue; - } - let other = self.buffer(j)?; - if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( - b.bytes, - other.handle.ok_or(Error::ContextPoisoned)?, - other.bytes, - ) { - return Err(Error::OutputAliasesInput); - } - } - } - if self.context.allocated_bytes() > self.context.budget { - return Err(Error::BudgetExceeded); - } - Ok(()) - } - fn external( - &self, - w: &NativeBatchWorkspace<'ctx>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - let addr = checked(self.context, b, n)?; - self.reject_state_alias(b)?; - if self - .physical()? - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_some() - { - let mapped = self.mapped()?; - let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { - return Err(Error::OutputAliasesInput); - } - } - if let Some(s) = &self.physical()?.selected { - s.reject_main_alias(b)?; - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - for own in self.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - Ok(addr) - } - pub fn empty_snapshot(&self) -> Result { - self.validate()?; - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(Vec::new().into_boxed_slice()), - end: 0, - }))) - } - pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { - self.validate()?; - if !Rc::ptr_eq(&self.origin, &s.0.origin) - || s.0.end > MTP_ORIGINAL_MAX_CELLS - || s.0.pages.len() < s.0.end.div_ceil(4) - { - return Err(Error::InvalidQwenShape); - } - for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - if p.runs[i].len() != n { - return Err(Error::InvalidSize); - } - } - } - Ok(()) - } - fn poison(&mut self) { - self.failed = true; - self.current = None; - if let Some(p) = &self.physical { - p.failed.set(true); - } - self.context.poison(); - self.context.retain_driver(); - } - fn execute( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - mut commands: Vec, - ) -> Result<()> { - self.validate()?; - w.validate_context(self.context)?; - let blas = w.blas()?; - let stream = blas.stream(); - let modules = &self.physical()?.modules; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - w.mark_failed(); - return Err(e); - } - }; - // Inputs may be produced on Original default stream. This confirmed dependency - // precedes the model-owned nonblocking stream, never a guessed ready flag. - let mut op = self.context.driver.api.synchronize(); - if op.is_ok() { - for command in &mut commands { - let result = match command { - Command::Kernel { - asset, - index, - grid, - block, - args, - } => modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, 0, stream, args) - }), - Command::Copy { dst, src, bytes } => modules[1] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, stream) - }), - }; - if let Err(e) = result { - op = Err(e); - break; - } - } - } - let sync = blas.synchronize(); - let pop = g.finish(); - let uncertain = sync.is_err() || pop.is_err(); - if uncertain { - std::mem::forget(commands); - } - if op.is_err() || uncertain { - self.poison(); - w.mark_failed(); - } - combine(combine(op, sync), pop) - } - fn push( - commands: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - values: Vec, - ) -> Result<()> { - commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; - commands.push(Command::Kernel { - asset, - index, - grid, - block, - args: Arguments::new(values)?, - }); - Ok(()) - } - fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { - Self::push( - commands, - 0, - 11, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(a), - Arg::I32(n as i32), - Arg::U64(self.sub(10, status * 4, 4)?), - ], - ) - } - fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { - let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; - let mut s = [0; STATUS_WORDS]; - for (i, v) in b.chunks_exact(4).enumerate() { - s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); - if s[i] > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("MTP finite flags")); - } - } - Ok(s) - } - /// Restore real immutable host pages, then exact Original modulo ring blocks. - /// The current witness is invalidated BEFORE any write; valid-end guards prevent - /// O(1) future-backing pages from incorrectly skipping rematerialization. - pub fn restore( - &mut self, - w: &mut NativeBatchWorkspace<'ctx>, - s: &MtpInt8Snapshot, - ) -> Result<()> { - self.validate_snapshot(s)?; - w.validate_context(self.context)?; - self.generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - if self - .current - .as_ref() - .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) - { - return Ok(()); - } - let previous = self.current.take(); - if self.fully_resident()? { - // Canonical snapshots remain genuine; restore overwritten accepted pages - // to the same identity cells before publishing the restored witness. - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) - && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - let state = self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)?; - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - state.copy_from(i, p * n, &page.runs[i])?; - } - } - self.current = Some(s.clone()); - return Ok(()); - } - let mut mapped = self.mapped_mut()?; - for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { - if previous.as_ref().is_some_and(|old| { - p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) - }) { - continue; - } - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; - } - } - drop(mapped); - let b1 = s.0.end.div_ceil(4); - let b0 = b1.saturating_sub(self.slots); - let mut commands = Vec::new(); - commands - .try_reserve_exact(8) - .map_err(|_| Error::HostAllocation)?; - let mut b = b0; - while b < b1 { - let slot = b % self.slots; - let run = (b1 - b).min(self.slots - slot); - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - commands.push(Command::Copy { - dst: self.sub(i, slot * n, run * n)?, - src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, - bytes: run * n, - }); - } - b += run; - } - if !commands.is_empty() { - self.execute(w, commands)?; - } - self.current = Some(s.clone()); - Ok(()) - } - /// Exact attention tail of record_forward(false). Real input+GR has already - /// produced this opaque mixed owner; no full MLP/head work is performed here. - pub fn record_kv_only<'loan, 'buffers, 'weights>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - prior: &MtpInt8Snapshot, - input: &'loan MtpOriginalMixed<'loan, 'buffers>, - weights: [&'loan DeviceBuffer<'weights>; 3], - ) -> Result> { - self.validate_snapshot(prior)?; - w.validate_context(self.context)?; - rows_range(input.first, input.rows, self.max_t)?; - if input.first > prior.0.end { - return Err(Error::InvalidQwenShape); - } - let mixed = self.external(w, input.mixed, input.rows * 10240)?; - let wk = self.external(w, weights[0], 512 * 80 * 34)?; - let wv = self.external(w, weights[1], 512 * 80 * 34)?; - let gamma = self.external(w, weights[2], 256 * 4)?; - let spans = [ - ( - input.mixed.handle.ok_or(Error::ContextPoisoned)?, - input.mixed.bytes, - ), - ( - weights[0].handle.ok_or(Error::ContextPoisoned)?, - weights[0].bytes, - ), - ( - weights[1].handle.ok_or(Error::ContextPoisoned)?, - weights[1].bytes, - ), - ( - weights[2].handle.ok_or(Error::ContextPoisoned)?, - weights[2].bytes, - ), - ]; - for (i, (a, an)) in spans.iter().enumerate() { - for (b, bn) in spans.iter().take(i) { - let exact = a.qwen_address() == b.qwen_address() && an == bn; - if !exact && a.overlaps(*an, *b, *bn) { - return Err(Error::OutputAliasesInput); - } - } - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let end = input.first + input.rows; - let n_pages = end.div_ceil(4); - let first_page = input.first / 4; - // All new host ownership is fallibly allocated before the first command. - let mut pages = Vec::new(); - pages - .try_reserve_exact(n_pages) - .map_err(|_| Error::HostAllocation)?; - for page in prior.0.pages.iter().take(first_page) { - pages.push(page.clone()); - } - let mut changed = Vec::new(); - changed - .try_reserve_exact(n_pages - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in first_page..n_pages { - 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 let Some(old) = prior.0.pages.get(p) { - runs[i].copy_from_slice(&old.runs[i]); - } - } - changed.push(runs); - } - let mut pos = zero_bytes(self.sizes[8])?; - let mut steps = zero_bytes(self.sizes[9])?; - for t in 0..input.rows { - let p = input.first + t; - for h in 0..24 { - pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] - .copy_from_slice(&(p as i32).to_le_bytes()); - } - for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { - steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] - .copy_from_slice(&(v as i32).to_le_bytes()); - } - } - // The real mixed producer supplies the rewind position. Restoring the - // longer prior's ring would keep future blocks after a shorter replay. - // This private prefix is bounded by that genuine prior, never caller-minted. - let replay_prior = if input.first == prior.0.end { - prior.clone() - } else { - MtpInt8Snapshot(Rc::new(Snapshot { - origin: prior.0.origin.clone(), - pages: prior.0.pages.clone(), - end: input.first, - })) - }; - self.restore(w, &replay_prior)?; - self.copy_from_physical(8, &pos)?; - self.copy_from_physical(9, &steps)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut commands = Vec::new(); - commands - .try_reserve_exact(32 + input.rows * 5) - .map_err(|_| Error::HostAllocation)?; - self.finite(&mut commands, mixed, input.rows * 2560, 0)?; - Self::push( - &mut commands, - 0, - 0, - [(input.rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(mixed), - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 2560) as i32), - ], - )?; - Self::push( - &mut commands, - 0, - 12, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(5)?), - Arg::I32((input.rows * 80) as i32), - Arg::U64(self.sub(10, 4, 4)?), - ], - )?; - for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { - Self::push( - &mut commands, - 0, - input.rows, - [512, 1, 1], - [32, 4, 1], - vec![ - Arg::U64(weight), - Arg::U64(self.address(5)?), - Arg::U64(self.address(out)?), - Arg::I32(2560), - Arg::I32(512), - ], - )?; - self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; - } - for t in 0..input.rows { - let k = self.sub(6, t * 2048, 2048)?; - Self::push( - &mut commands, - 0, - 9, - [2, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(gamma), - Arg::U64(k), - Arg::I32(256), - Arg::F32(1.0e-6), - ], - )?; - self.finite(&mut commands, k, 512, 4 + 2 * t)?; - Self::push( - &mut commands, - 0, - 10, - [1, 2, 1], - [128, 1, 1], - vec![ - Arg::U64(k), - Arg::U64(k), - Arg::I32(2), - Arg::I32(256), - Arg::F32(crate::qsa_index_ffi::theta()), - Arg::U64(self.sub(8, t * 96, 8)?), - ], - )?; - self.finite(&mut commands, k, 512, 5 + 2 * t)?; - } - // First failed upstream full scan/quant wins. No host/ring write before - // successful numeric admission of all real K/V rows. - self.execute(w, commands)?; - let flags = self.flags()?; - for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { - if *v != 0 { - return Err(if i == 1 { - Error::InvalidQ8Activation - } else { - Error::NonFiniteMmqOutput("mtp-kv-only") - }); - } - } - let mut append = Vec::new(); - append - .try_reserve_exact(input.rows * 2) - .map_err(|_| Error::HostAllocation)?; - let host = self.host_addresses()?; - for t in 0..input.rows { - Self::push( - &mut append, - 1, - 0, - [2, 4, 2], - [64, 1, 1], - vec![ - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.sub(9, t * 16, 16)?), - Arg::U64(self.sub(6, t * 2048, 2048)?), - Arg::U64(self.sub(7, t * 2048, 2048)?), - Arg::I32(2), - Arg::I32(256), - Arg::I32(4), - Arg::U64(host[0]), - Arg::U64(host[1]), - Arg::U64(host[2]), - Arg::U64(host[3]), - ], - )?; - } - Self::push( - &mut append, - 1, - 3, - [64, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::I32((self.slots * 32) as i32), - Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), - ], - )?; - self.current = None; // source pages and resident ring mutate only after invalidation - self.execute(w, append)?; - if self.flags()?[4 + 2 * self.max_t] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); - } - for (p, runs) in changed.iter_mut().enumerate() { - self.read_encoded_page(p + first_page, runs)?; - } - for runs in changed { - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(pages.into_boxed_slice()), - end, - })); - self.current = Some(snapshot.clone()); - self.generation = generation; - Ok(CompletedMtpKvReplay { - owner: self, - snapshot, - _mixed: input, - _weights: weights, - first: input.first, - rows: input.rows, - }) - } - /// Literal Original dense-window INT8 split-K attention. No selected index, - /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. - pub fn attend<'loan, 'buffers>( - &'loan mut self, - w: &mut NativeBatchWorkspace<'ctx>, - snapshot: &'loan MtpInt8Snapshot, - position: usize, - query: &'loan MtpOriginalQuery<'loan, 'buffers>, - ) -> Result> { - self.validate_snapshot(snapshot)?; - w.validate_context(self.context)?; - if position >= snapshot.0.end { - return Err(Error::InvalidQwenShape); - } - // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 - // cells cover every legal earlier query in that same completed replay. - let b1 = snapshot.0.end.div_ceil(4); - let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); - if oldest / 4 < b1.saturating_sub(self.slots) { - return Err(Error::InvalidQwenShape); - } - let q = self.external(w, query.query, 24576)?; - self.restore(w, snapshot)?; - self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; - let mut steps = [0u8; 16]; - for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] - .into_iter() - .enumerate() - { - steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); - } - self.copy_from_physical(14, &steps)?; - let mut admission = Vec::new(); - self.finite(&mut admission, q, 6144, 0)?; - self.execute(w, admission)?; - if self.flags()?[0] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-query")); - } - let mut commands = Vec::new(); - commands - .try_reserve_exact(4) - .map_err(|_| Error::HostAllocation)?; - Self::push( - &mut commands, - 1, - 2, - [8, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(self.address(14)?), - Arg::I32(32768), - Arg::U64(self.address(13)?), - Arg::I64(32768), - ], - )?; - let pa = self.address(12)?; - let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; - let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; - Self::push( - &mut commands, - 2, - 1, - [CHUNKS as u32, 2, 1], - [256, 1, 1], - vec![ - Arg::U64(q), - Arg::U64(self.address(0)?), - Arg::U64(self.address(1)?), - Arg::U64(self.address(2)?), - Arg::U64(self.address(3)?), - Arg::U64(self.address(4)?), - Arg::U64(self.address(13)?), - Arg::U64(self.address(14)?), - Arg::I32(2), - Arg::I32(4), - Arg::F32(1.0 / 16.0), - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::I32(32768), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - Self::push( - &mut commands, - 2, - 2, - [24, 1, 1], - [256, 1, 1], - vec![ - Arg::U64(pa), - Arg::U64(pm), - Arg::U64(pl), - Arg::I32(CHUNKS as i32), - Arg::U64(self.address(11)?), - Arg::I64(SCRATCH_FLOATS as i64), - ], - )?; - self.finite(&mut commands, self.address(11)?, 6144, 1)?; - self.execute(w, commands)?; - if self.flags()?[1] != 0 { - return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); - } - Ok(CompletedMtpAttention { - owner: self, - _snapshot: snapshot, - _query: query, - }) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - self.current = None; - let Some(mut physical) = self.physical.take() else { - return Ok(()); - }; - physical.active.set(false); - // Explicit close requires graph retirement first. Dropping this logical - // ring never frees allocations retained by a real graph resource token. - if Rc::strong_count(&physical) != 1 { - return Err(Error::InvalidQwenShape); - } - Rc::get_mut(&mut physical) - .ok_or(Error::InvalidQwenShape)? - .close_inner() - } -} -impl Drop for MtpOriginalInt8<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -impl<'ctx> MtpOriginalInt8<'ctx> { - fn new_original_state( - c: &'ctx Context<'ctx>, - max_t: usize, - main: Rc>, - spans: [(usize, usize); 7], - prepared: ring_state::PreparedState<'ctx>, - ) -> Result { - let (slots, sizes) = layout(max_t)?; - if c.is_poisoned() { - return Err(Error::ContextPoisoned); - } - for ptx in [ - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - include_bytes!("qsa_native_decode.ptx").as_slice(), - ] { - if ptx.windows(8).any(|w| w == b"UNSEALED") { - return Err(Error::UnsupportedQwenOperation); - } - } - let origin = Rc::new(Origin); - let physical = Rc::new(PhysicalRing { - context: c, - origin: origin.clone(), - sizes, - buffers: std::array::from_fn(|_| None), - modules: std::array::from_fn(|_| None), - mapped: RefCell::new(None), - selected: None, - failed: Cell::new(false), - active: Cell::new(true), - }); - let mut o = Self { - context: c, - origin, - max_t, - slots, - sizes, - physical: Some(physical), - current: None, - failed: false, - generation: 0, - }; - let op = (|| { - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - for (i, (ptx, entries)) in [ - ( - include_bytes!("mtp_original_tail.ptx").as_slice(), - TAIL_ENTRIES, - ), - (include_bytes!("mtp_original_kv.ptx").as_slice(), KV_ENTRIES), - ( - include_bytes!("qsa_native_decode.ptx").as_slice(), - ATTN_ENTRIES, - ), - ] - .into_iter() - .enumerate() - { - o.physical_mut()?.modules[i] = Some(Module::load(ptx, entries)?); - } - Ok(()) - })(); - let pop = g.finish(); - if pop.is_err() { - o.poison(); - } - combine(load, pop)?; - let (selected, mapped) = ring_state::Selected::from_prepared(prepared, main, spans)?; - if selected.layout.resident { - o.slots = 65536; - for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144] - .into_iter() - .enumerate() - { - o.sizes[i] = n; - o.physical_mut()?.sizes[i] = n; - } - } - o.physical_mut()?.selected = Some(selected); - *o.physical_mut()?.mapped.get_mut() = mapped; - let extras = o - .sizes - .into_iter() - .enumerate() - .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold(0usize, |a, (_, n)| { - a.checked_add(n).ok_or(Error::BudgetExceeded) - })?; - let need = extras.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; - if c.allocated_bytes() - .checked_add(need) - .is_none_or(|n| n > c.budget) - || c.memory_info()?.0 < need - { - return Err(Error::BudgetExceeded); - } - for (i, n) in o.sizes.into_iter().enumerate() { - if !matches!(i,0..=9|12..=14) { - o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); - } - } - o.validate()?; - if c.memory_info()?.0 < RESERVE { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = op { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn fully_resident(&self) -> Result { - self.validate()?; - Ok(self - .physical()? - .selected - .as_ref() - .is_some_and(|s| s.layout.resident)) - } - pub fn actual_pinned_host_bytes(&self) -> Result { - let p = self.physical()?; - let m = p.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; - Ok((if p.selected.is_some() { 116 } else { 0 }) + m.as_ref().map_or(0, MappedOwner::bytes)) - } - fn host_addresses(&self) -> Result<[u64; 4]> { - if self.fully_resident()? { - return Ok([0; 4]); - } - let mapped = self.mapped()?; - let mut a = [0; 4]; - for (i, n) in HOST_RUNS.into_iter().enumerate() { - a[i] = mapped.address(HOST_OFFSETS[i], n)?; - } - Ok(a) - } - fn read_encoded_page(&self, page: usize, runs: &mut [Vec; 4]) -> Result<()> { - if self.fully_resident()? { - return self - .physical()? - .selected - .as_ref() - .ok_or(Error::ContextPoisoned)? - .read_page(page, runs); - } - let mapped = self.mapped()?; - for (i, n) in PAGE_BYTES.into_iter().enumerate() { - if runs[i].len() != n { - return Err(Error::InvalidSize); - } - mapped.read_into(HOST_OFFSETS[i] + page * n, &mut runs[i])?; - } - Ok(()) - } - fn validate_original_main(&self, main: &Rc>) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - if !s.same_main(main) { - return Err(Error::InvalidQwenShape); - } - } - Ok(()) - } - fn reject_state_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { - if let Some(s) = &self.physical()?.selected { - s.reject_state_alias(b)?; - } - Ok(()) - } - /// State+retained diagnostic owners only; main bank is counted by paired layout. - pub fn planned_original_state_device_bytes( - max_t: usize, - fully_resident: bool, - ) -> Result { - let (_, sizes) = layout(max_t)?; - sizes - .into_iter() - .enumerate() - .filter(|(i, _)| !matches!(i,0..=9|12..=14)) - .try_fold( - ring_state::StateLayout::new(max_t, fully_resident)?.bytes, - |a, (_, n)| a.checked_add(n).ok_or(Error::InvalidSize), - ) - } -} +//! Literal Original MTP INT8 ring and record_forward(full=false) attention tail. +//! Input/GR and runtime causal authority are separate genuine producer obligations. +//! No F16 ring, whole warm_step, prompt-attention, or host-float readiness substitute. +#[path = "mtp_original_int8_ffi.rs"] +#[allow(unsafe_code)] +mod abi; +#[path = "mtp_original_ring_state.rs"] +mod ring_state; +use crate::{Context, DeviceBuffer, Error, NativeBatchWorkspace, Result, combine}; +use abi::{Arg, Arguments, MappedOwner, Module}; +use std::{ + cell::{Cell, Ref, RefCell, RefMut}, + rc::Rc, +}; + +pub const MTP_ORIGINAL_WINDOW: usize = 32768; +/// The MTP drafter bank is FROZEN at the trained 262144-cell geometry (its mapped host image, page table and +/// ring layouts are literal). It is deliberately NOT derived from the serving context: +/// `validate_existing_int8_bank` refuses any other session geometry, and the runtime refuses the MTP modes for a +/// context past the trained one. Re-deriving and qualifying it is a separate piece of work. +pub const MTP_ORIGINAL_MAX_CELLS: usize = 262144; +pub const MTP_ORIGINAL_PINNED_HOST_BYTES: usize = 276825088; +pub const MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES: usize = 276824064; +const RESERVE: usize = 128 * 1024 * 1024; +const PAGE_BYTES: [usize; 4] = [2048, 2048, 64, 64]; +const HOST_RUNS: [usize; 4] = [134217728, 134217728, 4194304, 4194304]; +const HOST_OFFSETS: [usize; 4] = [0, 134217728, 268435456, 272629760]; +const CHUNKS: usize = 512; +const SCRATCH_FLOATS: usize = CHUNKS * 24 * (256 + 2); +const STATUS_WORDS: usize = 21; // four leading stages, two per real row, final scale scan +const TAIL_ENTRIES: &[&std::ffi::CStr] = &[ + c"mtp_original_quantize", + c"mtp_original_q80_1", + c"mtp_original_q80_2", + c"mtp_original_q80_3", + c"mtp_original_q80_4", + c"mtp_original_q80_5", + c"mtp_original_q80_6", + c"mtp_original_q80_7", + c"mtp_original_q80_8", + c"mtp_original_knorm", + c"mtp_original_krope", + c"mtp_original_finite", + c"mtp_original_q8_guard", +]; +const KV_ENTRIES: &[&std::ffi::CStr] = &[ + c"mtp_original_append", + c"mtp_original_ring_table", + c"mtp_original_window_ids", + c"mtp_original_encoded_guard", +]; +const ATTN_ENTRIES: &[&std::ffi::CStr] = &[ + c"leleka_qsa_prompt_guard", + c"leleka_qsa_decode_chunk", + c"leleka_qsa_decode_merge", + c"leleka_qsa_prompt_output_guard", +]; +struct Origin; +#[derive(Clone)] +pub struct MtpInt8OwnerId(Rc); +impl MtpInt8OwnerId { + pub fn same_owner(&self, other: &Self) -> bool { + Rc::ptr_eq(&self.0, &other.0) + } +} + +#[path = "mtp_original_logical_prefix.rs"] +mod logical_prefix; +pub use logical_prefix::OriginalMtpSkippedPrefix; +// The literal prefill producer is an MTP child because it borrows this +// owner's private ring/state types. Its public contracts are re-exported by +// the crate integration point below. +#[path = "mtp_original_prefill.rs"] +mod prefill; +pub(crate) use prefill::session_assets_sealed; +pub use prefill::{ + CompletedDraftKv, CompletedOriginalMtpDraft, DraftKvFallback, DraftKvOutcome, DraftKvPolicy, + OriginalMtpDraftProgram, OriginalMtpDrafter, OriginalMtpEmbedding, OriginalMtpForwardProgram, + OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, OriginalMtpPrefill, + OriginalMtpPrefillWeights, OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, + OriginalMtpRetainedScalarWeights, OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, + OriginalMtpStepOutput, +}; +struct Page { + runs: [Box<[u8]>; 4], +} +struct Snapshot { + origin: Rc, + pages: Rc]>>, + end: usize, + /// The pages up to `end` were checked to have the exact run sizes (`validate_snapshot`). The snapshot is immutable, so the + /// answer cannot change; the scan is O(context / 4) and ran several times per speculation round. + checked: Cell, +} +/// Immutable actual encoded bytes; runtime binds these to its genuine MTP epoch. +#[derive(Clone)] +pub struct MtpInt8Snapshot(Rc); +impl MtpInt8Snapshot { + pub fn owner_id(&self) -> MtpInt8OwnerId { + MtpInt8OwnerId(self.0.origin.clone()) + } + pub fn next_position(&self) -> usize { + self.0.end + } + pub fn encoded_bytes(&self) -> usize { + self.0.pages.len() * 4224 + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + 8 * std::mem::size_of::() + + self.0.pages.len() + * (std::mem::size_of::>() + + std::mem::size_of::() + + 2 * std::mem::size_of::()) + } +} +/// Created only inside the actual driver input+fused-GR producer integration. +/// Public constructors accepting arbitrary floats or a caller readiness bit do not exist. +pub struct MtpOriginalMixed<'loan, 'buffers> { + mixed: &'loan DeviceBuffer<'buffers>, + first: usize, + rows: usize, +} +impl<'loan, 'buffers> MtpOriginalMixed<'loan, 'buffers> { + pub(crate) fn from_completed_gr( + c: &Context<'_>, + mixed: &'loan DeviceBuffer<'buffers>, + first: usize, + rows: usize, + ) -> Result { + rows_range(first, rows, 8)?; + checked(c, mixed, rows * 2560 * 4)?; + Ok(Self { mixed, first, rows }) + } + pub fn rows(&self) -> usize { + self.rows + } + pub fn first_position(&self) -> usize { + self.first + } +} +/// Real native normalized/RoPE query, minted by the actual scalar full-draft producer. +pub struct MtpOriginalQuery<'loan, 'buffers> { + query: &'loan DeviceBuffer<'buffers>, +} +impl<'loan, 'buffers> MtpOriginalQuery<'loan, 'buffers> { + pub(crate) fn from_completed_native( + c: &Context<'_>, + query: &'loan DeviceBuffer<'buffers>, + ) -> Result { + checked(c, query, 6144 * 4)?; + Ok(Self { query }) + } +} +/// Replay completion retains actual ring and immutable whole-weight/input loans. +pub struct CompletedMtpKvReplay<'loan, 'ctx, 'buffers, 'weights> { + owner: &'loan mut MtpOriginalInt8<'ctx>, + snapshot: MtpInt8Snapshot, + _mixed: &'loan MtpOriginalMixed<'loan, 'buffers>, + _weights: [&'loan DeviceBuffer<'weights>; 3], + first: usize, + rows: usize, +} +impl CompletedMtpKvReplay<'_, '_, '_, '_> { + pub fn rows(&self) -> usize { + self.rows + } + pub fn final_snapshot(&self) -> &MtpInt8Snapshot { + &self.snapshot + } + /// End can only be derived from a real row of this completed append. + pub fn snapshot_after(&self, row: usize) -> Result { + self.owner.validate()?; + if row >= self.rows { + return Err(Error::InvalidQwenShape); + } + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.snapshot.0.origin.clone(), + pages: self.snapshot.0.pages.clone(), + end: self.first + row + 1, + checked: std::cell::Cell::new(self.snapshot.0.checked.get()), + }))) + } + pub fn into_final_snapshot(self) -> MtpInt8Snapshot { + self.snapshot + } +} +pub struct CompletedMtpAttention<'loan, 'ctx, 'buffers> { + owner: &'loan mut MtpOriginalInt8<'ctx>, + _snapshot: &'loan MtpInt8Snapshot, + _query: &'loan MtpOriginalQuery<'loan, 'buffers>, +} +impl CompletedMtpAttention<'_, '_, '_> { + pub fn with_output(&self, f: impl FnOnce(&DeviceBuffer<'_>) -> Result) -> Result { + self.owner.validate()?; + f(self.owner.buffer(11)?) + } + pub fn into_values(self) -> Result> { + self.owner.validate()?; + let bytes = self.owner.buffer(11)?.copy_to_owned(6144 * 4)?; + let mut out = Vec::new(); + out.try_reserve_exact(6144) + .map_err(|_| Error::HostAllocation)?; + for x in bytes.chunks_exact(4) { + out.push(f32::from_le_bytes( + x.try_into().map_err(|_| Error::InvalidSize)?, + )); + } + Ok(out.into_boxed_slice()) + } +} +enum Command { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + args: Arguments, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, +} +/// Actual model-lifetime physical allocations. Causal current/generation lives +/// only on MtpOriginalInt8. Graph resources retain this Rc without a RefCell loan. +/// Only bounded CPU mapped-page accesses take short exclusive mapped borrows. +struct PhysicalRing<'ctx> { + context: &'ctx Context<'ctx>, + origin: Rc, + sizes: [usize; 15], + buffers: [Option>; 15], + modules: [Option; 3], + mapped: RefCell>, + selected: Option>, + failed: Cell, + active: Cell, +} +/// Opaque genuine physical retention minted only by this ring. No caller pointer, +/// bytes or ready marker can construct a token. It is not a causal state proof. +pub struct MtpOriginalRingResources<'ctx> { + physical: Rc>, +} +impl Clone for MtpOriginalRingResources<'_> { + fn clone(&self) -> Self { + Self { + physical: Rc::clone(&self.physical), + } + } +} +impl MtpOriginalRingResources<'_> { + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + self.physical.validate_context(c) + } + pub fn owner_id(&self) -> MtpInt8OwnerId { + MtpInt8OwnerId(self.physical.origin.clone()) + } + pub fn allocated_bytes(&self) -> usize { + self.physical + .buffers + .iter() + .flatten() + .map(|b| b.bytes) + .sum::() + + self + .physical + .selected + .as_ref() + .map_or(0, |s| s.unique_bytes()) + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::>() + + 2 * std::mem::size_of::() + + std::mem::size_of::() + } +} +impl PhysicalRing<'_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + if !self.active.get() + || self.failed.get() + || c.is_poisoned() + || c.handle.is_none() + || self.modules.iter().any(Option::is_none) + || (self.selected.is_none() + && self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_none()) + { + return Err(Error::ContextPoisoned); + } + for (i, b) in self.buffers.iter().enumerate() { + if let Some(b) = b { + checked(c, b, self.sizes[i])?; + } else if !self.selected.as_ref().is_some_and(|s| s.provides(i)) { + return Err(Error::ContextPoisoned); + } + } + if let Some(s) = &self.selected { + s.validate(c)?; + } + Ok(()) + } + fn close_inner(&mut self) -> Result<()> { + self.active.set(false); + self.failed.set(true); + let mut result = Ok(()); + // Same original module -> mapped -> device order and primary arbitration. + // A poisoned Context retains every actual physical owner and its charge. + for m in &mut self.modules { + if let Some(module) = m.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(module); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(module.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(module); + Err(e) + } + } + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + } + if let Some(mut mapped) = self.mapped.get_mut().take() { + let close = if self.context.is_poisoned() { + std::mem::forget(mapped); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => { + let op = mapped.close(); + let pop = g.finish(); + combine(op, pop) + } + Err(e) => { + self.context.poison(); + std::mem::forget(mapped); + Err(e) + } + } + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + if let Some(mut s) = self.selected.take() { + result = combine(result, s.close()); + } + for b in &mut self.buffers { + if let Some(buffer) = b.take() { + let close = if self.context.is_poisoned() { + std::mem::forget(buffer); + Err(Error::ContextPoisoned) + } else { + buffer.release() + }; + if close.is_err() { + self.context.poison(); + } + result = combine(result, close); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + result + } +} +impl Drop for PhysicalRing<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} +/// One Context-affine model owner. The literal selected plain INT8, unrotated +/// 32K-window profile is explicit. Other Original formats/options remain separate. +pub struct MtpOriginalInt8<'ctx> { + context: &'ctx Context<'ctx>, + origin: Rc, + max_t: usize, + slots: usize, + sizes: [usize; 15], + physical: Option>>, + current: Option, + failed: bool, + generation: u64, +} +fn zero_bytes(n: usize) -> Result> { + let mut v = Vec::new(); + v.try_reserve_exact(n).map_err(|_| Error::HostAllocation)?; + v.resize(n, 0); + Ok(v) +} +fn checked(c: &Context<'_>, b: &DeviceBuffer<'_>, n: usize) -> Result { + if !std::ptr::eq(c, b.context) { + return Err(Error::ContextMismatch); + } + if b.bytes != n { + return Err(Error::InvalidQwenShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(n, 4)?; + Ok(h.qwen_address()) +} +fn rows_range(first: usize, rows: usize, max_t: usize) -> Result<()> { + if !(1..=max_t).contains(&rows) + || first + .checked_add(rows) + .is_none_or(|e| e > MTP_ORIGINAL_MAX_CELLS) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) +} +fn layout(t: usize) -> Result<(usize, [usize; 15])> { + if !(1..=8).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let slots = (MTP_ORIGINAL_WINDOW + 4 * t + 64).div_ceil(4); + Ok(( + slots, + [ + slots * 2048, + slots * 2048, + slots * 64, + slots * 64, + 65536 * 4, + t * 2880, + t * 2048, + t * 2048, + t * 24 * 4, + t * 4 * 4, + STATUS_WORDS * 4, + 6144 * 4, + SCRATCH_FLOATS * 4, + MTP_ORIGINAL_WINDOW * 4, + 16, + ], + )) +} +impl Context<'_> { + pub fn mtp_original_int8(&self, max_t: usize) -> Result> { + MtpOriginalInt8::new(self, max_t) + } +} +impl<'ctx> MtpOriginalInt8<'ctx> { + pub fn planned_device_bytes(max_t: usize) -> Result { + Ok(layout(max_t)?.1.into_iter().sum()) + } + pub fn pinned_host_bytes() -> usize { + MTP_ORIGINAL_PINNED_HOST_BYTES + } + pub fn max_snapshot_payload_bytes() -> usize { + MTP_ORIGINAL_SNAPSHOT_PAYLOAD_BYTES + } + pub fn max_snapshot_metadata_bytes() -> usize { + std::mem::size_of::() + + std::mem::size_of::() + + 8 * std::mem::size_of::() + + 65536 + * (std::mem::size_of::>() + + std::mem::size_of::() + + 2 * std::mem::size_of::()) + } + fn new(c: &'ctx Context<'ctx>, max_t: usize) -> Result { + let (slots, sizes) = layout(max_t)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + // Refuse placeholders before any host or device owner allocation. + for ptx in [ + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ] { + if ptx.windows(8).any(|w| w == b"UNSEALED") { + return Err(Error::UnsupportedQwenOperation); + } + } + let needed = sizes + .into_iter() + .sum::() + .checked_add(RESERVE) + .ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes() + .checked_add(needed) + .is_none_or(|n| n > c.budget) + || c.memory_info()?.0 < needed + { + return Err(Error::BudgetExceeded); + } + let origin = Rc::new(Origin); + let physical = Rc::new(PhysicalRing { + context: c, + origin: origin.clone(), + sizes, + buffers: std::array::from_fn(|_| None), + modules: std::array::from_fn(|_| None), + mapped: RefCell::new(None), + selected: None, + failed: Cell::new(false), + active: Cell::new(true), + }); + let mut o = Self { + context: c, + origin, + max_t, + slots, + sizes, + physical: Some(physical), + current: None, + failed: false, + generation: 0, + }; + let operation = (|| { + let guard = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.physical_mut()?.modules[0] = Some(Module::load( + include_bytes!("mtp_original_tail.ptx"), + TAIL_ENTRIES, + )?); + o.physical_mut()?.modules[1] = Some(Module::load( + include_bytes!("mtp_original_kv.ptx"), + KV_ENTRIES, + )?); + o.physical_mut()?.modules[2] = Some(Module::load( + include_bytes!("qsa_native_decode.ptx"), + ATTN_ENTRIES, + )?); + *o.physical_mut()?.mapped.get_mut() = Some(MappedOwner::new()?); + if o.physical()? + .mapped + .borrow() + .as_ref() + .is_none_or(|m| m.bytes() != MTP_ORIGINAL_PINNED_HOST_BYTES) + { + return Err(Error::InvalidSize); + } + Ok(()) + })(); + let pop = guard.finish(); + if pop.is_err() { + o.poison(); + } + combine(load, pop)?; + for (i, n) in sizes.into_iter().enumerate() { + o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); + } + // Real initialized pools; no reader ever names an unwritten logical cell. + for i in 0..4 { + o.copy_from_physical(i, &zero_bytes(sizes[i])?)?; + } + let mut table = zero_bytes(65536 * 4)?; + for (p, b) in table.chunks_exact_mut(4).enumerate() { + b.copy_from_slice(&((p % slots) as i32).to_le_bytes()); + } + o.copy_from_physical(4, &table)?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + fn physical(&self) -> Result<&PhysicalRing<'ctx>> { + self.physical.as_deref().ok_or(Error::ContextPoisoned) + } + fn physical_mut(&mut self) -> Result<&mut PhysicalRing<'ctx>> { + Rc::get_mut(self.physical.as_mut().ok_or(Error::ContextPoisoned)?) + .ok_or(Error::InvalidQwenShape) + } + fn buffer(&self, i: usize) -> Result<&DeviceBuffer<'ctx>> { + self.physical()? + .buffers + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn buffers(&self) -> Result<&[Option>; 15]> { + Ok(&self.physical()?.buffers) + } + fn mapped(&self) -> Result> { + Ref::filter_map( + self.physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_ref, + ) + .map_err(|_| Error::ContextPoisoned) + } + fn mapped_mut(&self) -> Result> { + RefMut::filter_map( + self.physical()? + .mapped + .try_borrow_mut() + .map_err(|_| Error::InvalidQwenShape)?, + Option::as_mut, + ) + .map_err(|_| Error::ContextPoisoned) + } + fn copy_from_physical(&self, i: usize, input: &[u8]) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return s.copy_from(i, 0, input); + } + } + let b = self.buffer(i)?; + let mut staging = b.staging(input.len())?; + staging.copy_from_slice(input); + b.copy_staged(staging, false).map(|_| ()) + } + pub(crate) fn retain_physical_resources(&self) -> Result> { + self.validate()?; + Ok(MtpOriginalRingResources { + physical: Rc::clone(self.physical.as_ref().ok_or(Error::ContextPoisoned)?), + }) + } + pub fn physical_metadata_bytes() -> usize { + std::mem::size_of::>() + 2 * std::mem::size_of::() + } + + fn address(&self, i: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, 0, self.sizes[i])?.qwen_address()); + } + } + checked(self.context, self.buffer(i)?, self.sizes[i]) + } + fn sub(&self, i: usize, o: usize, n: usize) -> Result { + if let Some(s) = &self.physical()?.selected { + if s.provides(i) { + return Ok(s.span(i, o, n)?.qwen_address()); + } + } + Ok(self + .buffer(i)? + .handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(self.sizes[i], o, n)? + .qwen_address()) + } + pub fn allocated_bytes(&self) -> usize { + self.physical.as_ref().map_or(0, |p| { + p.buffers.iter().flatten().map(|b| b.bytes).sum::() + + p.selected.as_ref().map_or(0, |s| s.unique_bytes()) + }) + } + pub fn is_failed(&self) -> bool { + self.failed + || self.context.is_poisoned() + || self.context.handle.is_none() + || self + .physical + .as_ref() + .is_none_or(|p| p.failed.get() || !p.active.get()) + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + fn validate(&self) -> Result<()> { + if self.is_failed() { + return Err(Error::ContextPoisoned); + } + self.physical()?.validate_context(self.context)?; + for i in 0..15 { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(i)) + { + continue; + } + let b = self.buffer(i)?; + checked(self.context, b, self.sizes[i])?; + if let Some(s) = &self.physical()?.selected { + s.reject_state_alias(b)?; + s.reject_main_alias(b)?; + } + for j in 0..i { + if self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.provides(j)) + { + continue; + } + let other = self.buffer(j)?; + if b.handle.ok_or(Error::ContextPoisoned)?.overlaps( + b.bytes, + other.handle.ok_or(Error::ContextPoisoned)?, + other.bytes, + ) { + return Err(Error::OutputAliasesInput); + } + } + } + if self.context.allocated_bytes() > self.context.budget { + return Err(Error::BudgetExceeded); + } + Ok(()) + } + fn external( + &self, + w: &NativeBatchWorkspace<'ctx>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + let addr = checked(self.context, b, n)?; + self.reject_state_alias(b)?; + if self + .physical()? + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_some() + { + let mapped = self.mapped()?; + let ma = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if addr < ma + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 && ma < addr + n as u64 { + return Err(Error::OutputAliasesInput); + } + } + if let Some(s) = &self.physical()?.selected { + s.reject_main_alias(b)?; + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + for own in self.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + Ok(addr) + } + pub fn empty_snapshot(&self) -> Result { + self.validate()?; + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(Vec::new().into_boxed_slice()), + end: 0, + checked: std::cell::Cell::new(true), + }))) + } + pub fn validate_snapshot(&self, s: &MtpInt8Snapshot) -> Result<()> { + self.validate()?; + if !Rc::ptr_eq(&self.origin, &s.0.origin) + || s.0.end > MTP_ORIGINAL_MAX_CELLS + || s.0.pages.len() < s.0.end.div_ceil(4) + { + return Err(Error::InvalidQwenShape); + } + if s.0.checked.get() { + return Ok(()); + } + for p in s.0.pages.iter().take(s.0.end.div_ceil(4)) { + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + if p.runs[i].len() != n { + return Err(Error::InvalidSize); + } + } + } + s.0.checked.set(true); + Ok(()) + } + fn poison(&mut self) { + self.failed = true; + self.current = None; + if let Some(p) = &self.physical { + p.failed.set(true); + } + self.context.poison(); + self.context.retain_driver(); + } + fn execute( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + mut commands: Vec, + ) -> Result<()> { + self.validate()?; + w.validate_context(self.context)?; + let blas = w.blas()?; + let stream = blas.stream(); + let modules = &self.physical()?.modules; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + w.mark_failed(); + return Err(e); + } + }; + // Inputs may be produced on Original default stream. This confirmed dependency + // precedes the model-owned nonblocking stream, never a guessed ready flag. + let mut op = self.context.driver.api.synchronize(); + if op.is_ok() { + for command in &mut commands { + let result = match command { + Command::Kernel { + asset, + index, + grid, + block, + args, + } => modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, 0, stream, args) + }), + Command::Copy { dst, src, bytes } => modules[1] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, stream) + }), + }; + if let Err(e) = result { + op = Err(e); + break; + } + } + } + let sync = blas.synchronize(); + let pop = g.finish(); + let uncertain = sync.is_err() || pop.is_err(); + if uncertain { + std::mem::forget(commands); + } + if op.is_err() || uncertain { + self.poison(); + w.mark_failed(); + } + combine(combine(op, sync), pop) + } + fn push( + commands: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + values: Vec, + ) -> Result<()> { + commands.try_reserve(1).map_err(|_| Error::HostAllocation)?; + commands.push(Command::Kernel { + asset, + index, + grid, + block, + args: Arguments::new(values)?, + }); + Ok(()) + } + fn finite(&self, commands: &mut Vec, a: u64, n: usize, status: usize) -> Result<()> { + Self::push( + commands, + 0, + 11, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(a), + Arg::I32(n as i32), + Arg::U64(self.sub(10, status * 4, 4)?), + ], + ) + } + fn flags(&mut self) -> Result<[u32; STATUS_WORDS]> { + let b = self.buffer(10)?.copy_to_owned(STATUS_WORDS * 4)?; + let mut s = [0; STATUS_WORDS]; + for (i, v) in b.chunks_exact(4).enumerate() { + s[i] = u32::from_le_bytes(v.try_into().map_err(|_| Error::InvalidSize)?); + if s[i] > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("MTP finite flags")); + } + } + Ok(s) + } + /// Restore real immutable host pages, then exact Original modulo ring blocks. + /// The current witness is invalidated BEFORE any write; valid-end guards prevent + /// O(1) future-backing pages from incorrectly skipping rematerialization. + pub fn restore( + &mut self, + w: &mut NativeBatchWorkspace<'ctx>, + s: &MtpInt8Snapshot, + ) -> Result<()> { + self.validate_snapshot(s)?; + w.validate_context(self.context)?; + self.generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + if self + .current + .as_ref() + .is_some_and(|old| Rc::ptr_eq(&old.0, &s.0)) + { + return Ok(()); + } + let previous = self.current.take(); + if self.fully_resident()? { + // Canonical snapshots remain genuine; restore overwritten accepted pages + // to the same identity cells before publishing the restored witness. + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) + && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + let state = self + .physical()? + .selected + .as_ref() + .ok_or(Error::ContextPoisoned)?; + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + state.copy_from(i, p * n, &page.runs[i])?; + } + } + self.current = Some(s.clone()); + return Ok(()); + } + let mut mapped = self.mapped_mut()?; + for (p, page) in s.0.pages.iter().take(s.0.end.div_ceil(4)).enumerate() { + if previous.as_ref().is_some_and(|old| { + p < old.0.end.div_ceil(4) && old.0.pages.get(p).is_some_and(|x| Rc::ptr_eq(x, page)) + }) { + continue; + } + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + mapped.write(HOST_OFFSETS[i] + p * n, &page.runs[i])?; + } + } + drop(mapped); + let b1 = s.0.end.div_ceil(4); + let b0 = b1.saturating_sub(self.slots); + let mut commands = Vec::new(); + commands + .try_reserve_exact(8) + .map_err(|_| Error::HostAllocation)?; + let mut b = b0; + while b < b1 { + let slot = b % self.slots; + let run = (b1 - b).min(self.slots - slot); + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + commands.push(Command::Copy { + dst: self.sub(i, slot * n, run * n)?, + src: self.mapped()?.address(HOST_OFFSETS[i] + b * n, run * n)?, + bytes: run * n, + }); + } + b += run; + } + if !commands.is_empty() { + self.execute(w, commands)?; + } + self.current = Some(s.clone()); + Ok(()) + } + /// Exact attention tail of record_forward(false). Real input+GR has already + /// produced this opaque mixed owner; no full MLP/head work is performed here. + pub fn record_kv_only<'loan, 'buffers, 'weights>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + prior: &MtpInt8Snapshot, + input: &'loan MtpOriginalMixed<'loan, 'buffers>, + weights: [&'loan DeviceBuffer<'weights>; 3], + ) -> Result> { + self.validate_snapshot(prior)?; + w.validate_context(self.context)?; + rows_range(input.first, input.rows, self.max_t)?; + if input.first > prior.0.end { + return Err(Error::InvalidQwenShape); + } + let mixed = self.external(w, input.mixed, input.rows * 10240)?; + let wk = self.external(w, weights[0], 512 * 80 * 34)?; + let wv = self.external(w, weights[1], 512 * 80 * 34)?; + let gamma = self.external(w, weights[2], 256 * 4)?; + let spans = [ + ( + input.mixed.handle.ok_or(Error::ContextPoisoned)?, + input.mixed.bytes, + ), + ( + weights[0].handle.ok_or(Error::ContextPoisoned)?, + weights[0].bytes, + ), + ( + weights[1].handle.ok_or(Error::ContextPoisoned)?, + weights[1].bytes, + ), + ( + weights[2].handle.ok_or(Error::ContextPoisoned)?, + weights[2].bytes, + ), + ]; + for (i, (a, an)) in spans.iter().enumerate() { + for (b, bn) in spans.iter().take(i) { + let exact = a.qwen_address() == b.qwen_address() && an == bn; + if !exact && a.overlaps(*an, *b, *bn) { + return Err(Error::OutputAliasesInput); + } + } + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let end = input.first + input.rows; + let n_pages = end.div_ceil(4); + let first_page = input.first / 4; + // All new host ownership is fallibly allocated before the first command. + let mut pages = Vec::new(); + pages + .try_reserve_exact(n_pages) + .map_err(|_| Error::HostAllocation)?; + for page in prior.0.pages.iter().take(first_page) { + pages.push(page.clone()); + } + let mut changed = Vec::new(); + changed + .try_reserve_exact(n_pages - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in first_page..n_pages { + 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 let Some(old) = prior.0.pages.get(p) { + runs[i].copy_from_slice(&old.runs[i]); + } + } + changed.push(runs); + } + let mut pos = zero_bytes(self.sizes[8])?; + let mut steps = zero_bytes(self.sizes[9])?; + for t in 0..input.rows { + let p = input.first + t; + for h in 0..24 { + pos[(t * 24 + h) * 4..(t * 24 + h + 1) * 4] + .copy_from_slice(&(p as i32).to_le_bytes()); + } + for (i, v) in [p, p + 1, (p + 1) / 4, p + 1].into_iter().enumerate() { + steps[(t * 4 + i) * 4..(t * 4 + i + 1) * 4] + .copy_from_slice(&(v as i32).to_le_bytes()); + } + } + // The real mixed producer supplies the rewind position. Restoring the + // longer prior's ring would keep future blocks after a shorter replay. + // This private prefix is bounded by that genuine prior, never caller-minted. + let replay_prior = if input.first == prior.0.end { + prior.clone() + } else { + MtpInt8Snapshot(Rc::new(Snapshot { + origin: prior.0.origin.clone(), + pages: prior.0.pages.clone(), + end: input.first, + checked: std::cell::Cell::new(prior.0.checked.get()), + })) + }; + self.restore(w, &replay_prior)?; + self.copy_from_physical(8, &pos)?; + self.copy_from_physical(9, &steps)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut commands = Vec::new(); + commands + .try_reserve_exact(32 + input.rows * 5) + .map_err(|_| Error::HostAllocation)?; + self.finite(&mut commands, mixed, input.rows * 2560, 0)?; + Self::push( + &mut commands, + 0, + 0, + [(input.rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(mixed), + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 2560) as i32), + ], + )?; + Self::push( + &mut commands, + 0, + 12, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(5)?), + Arg::I32((input.rows * 80) as i32), + Arg::U64(self.sub(10, 4, 4)?), + ], + )?; + for (weight, out, status) in [(wk, 6, 2), (wv, 7, 3)] { + Self::push( + &mut commands, + 0, + input.rows, + [512, 1, 1], + [32, 4, 1], + vec![ + Arg::U64(weight), + Arg::U64(self.address(5)?), + Arg::U64(self.address(out)?), + Arg::I32(2560), + Arg::I32(512), + ], + )?; + self.finite(&mut commands, self.address(out)?, input.rows * 512, status)?; + } + for t in 0..input.rows { + let k = self.sub(6, t * 2048, 2048)?; + Self::push( + &mut commands, + 0, + 9, + [2, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(gamma), + Arg::U64(k), + Arg::I32(256), + Arg::F32(1.0e-6), + ], + )?; + self.finite(&mut commands, k, 512, 4 + 2 * t)?; + Self::push( + &mut commands, + 0, + 10, + [1, 2, 1], + [128, 1, 1], + vec![ + Arg::U64(k), + Arg::U64(k), + Arg::I32(2), + Arg::I32(256), + Arg::F32(crate::qsa_index_ffi::theta()), + Arg::U64(self.sub(8, t * 96, 8)?), + ], + )?; + self.finite(&mut commands, k, 512, 5 + 2 * t)?; + } + // First failed upstream full scan/quant wins. No host/ring write before + // successful numeric admission of all real K/V rows. + self.execute(w, commands)?; + let flags = self.flags()?; + for (i, v) in flags.iter().enumerate().take(4 + 2 * input.rows) { + if *v != 0 { + return Err(if i == 1 { + Error::InvalidQ8Activation + } else { + Error::NonFiniteMmqOutput("mtp-kv-only") + }); + } + } + let mut append = Vec::new(); + append + .try_reserve_exact(input.rows * 2) + .map_err(|_| Error::HostAllocation)?; + let host = self.host_addresses()?; + for t in 0..input.rows { + Self::push( + &mut append, + 1, + 0, + [2, 4, 2], + [64, 1, 1], + vec![ + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.sub(9, t * 16, 16)?), + Arg::U64(self.sub(6, t * 2048, 2048)?), + Arg::U64(self.sub(7, t * 2048, 2048)?), + Arg::I32(2), + Arg::I32(256), + Arg::I32(4), + Arg::U64(host[0]), + Arg::U64(host[1]), + Arg::U64(host[2]), + Arg::U64(host[3]), + ], + )?; + } + Self::push( + &mut append, + 1, + 3, + [64, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::I32((self.slots * 32) as i32), + Arg::U64(self.sub(10, (4 + 2 * self.max_t) * 4, 4)?), + ], + )?; + self.current = None; // source pages and resident ring mutate only after invalidation + self.execute(w, append)?; + if self.flags()?[4 + 2 * self.max_t] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-scale")); + } + for (p, runs) in changed.iter_mut().enumerate() { + self.read_encoded_page(p + first_page, runs)?; + } + for runs in changed { + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(pages.into_boxed_slice()), + end, + checked: std::cell::Cell::new(false), + })); + self.current = Some(snapshot.clone()); + self.generation = generation; + Ok(CompletedMtpKvReplay { + owner: self, + snapshot, + _mixed: input, + _weights: weights, + first: input.first, + rows: input.rows, + }) + } + /// Literal Original dense-window INT8 split-K attention. No selected index, + /// clock resolver, prompt MMA or F16 intermediate pool stands in for the ring. + pub fn attend<'loan, 'buffers>( + &'loan mut self, + w: &mut NativeBatchWorkspace<'ctx>, + snapshot: &'loan MtpInt8Snapshot, + position: usize, + query: &'loan MtpOriginalQuery<'loan, 'buffers>, + ) -> Result> { + self.validate_snapshot(snapshot)?; + w.validate_context(self.context)?; + if position >= snapshot.0.end { + return Err(Error::InvalidQwenShape); + } + // Snapshot may contain the whole verified suffix. Its ring's extra4*S+64 + // cells cover every legal earlier query in that same completed replay. + let b1 = snapshot.0.end.div_ceil(4); + let oldest = (position + 1).saturating_sub(MTP_ORIGINAL_WINDOW); + if oldest / 4 < b1.saturating_sub(self.slots) { + return Err(Error::InvalidQwenShape); + } + let q = self.external(w, query.query, 24576)?; + self.restore(w, snapshot)?; + self.copy_from_physical(10, &[0; STATUS_WORDS * 4])?; + let mut steps = [0u8; 16]; + for (i, v) in [position, position + 1, (position + 1) / 4, position + 1] + .into_iter() + .enumerate() + { + steps[i * 4..i * 4 + 4].copy_from_slice(&(v as i32).to_le_bytes()); + } + self.copy_from_physical(14, &steps)?; + let mut admission = Vec::new(); + self.finite(&mut admission, q, 6144, 0)?; + self.execute(w, admission)?; + if self.flags()?[0] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-query")); + } + let mut commands = Vec::new(); + commands + .try_reserve_exact(4) + .map_err(|_| Error::HostAllocation)?; + Self::push( + &mut commands, + 1, + 2, + [8, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(self.address(14)?), + Arg::I32(32768), + Arg::U64(self.address(13)?), + Arg::I64(32768), + ], + )?; + let pa = self.address(12)?; + let pm = self.sub(12, CHUNKS * 24 * 256 * 4, CHUNKS * 24 * 4)?; + let pl = self.sub(12, CHUNKS * 24 * 257 * 4, CHUNKS * 24 * 4)?; + Self::push( + &mut commands, + 2, + 1, + [CHUNKS as u32, 2, 1], + [256, 1, 1], + vec![ + Arg::U64(q), + Arg::U64(self.address(0)?), + Arg::U64(self.address(1)?), + Arg::U64(self.address(2)?), + Arg::U64(self.address(3)?), + Arg::U64(self.address(4)?), + Arg::U64(self.address(13)?), + Arg::U64(self.address(14)?), + Arg::I32(2), + Arg::I32(4), + Arg::F32(1.0 / 16.0), + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::I32(32768), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + Self::push( + &mut commands, + 2, + 2, + [24, 1, 1], + [256, 1, 1], + vec![ + Arg::U64(pa), + Arg::U64(pm), + Arg::U64(pl), + Arg::I32(CHUNKS as i32), + Arg::U64(self.address(11)?), + Arg::I64(SCRATCH_FLOATS as i64), + ], + )?; + self.finite(&mut commands, self.address(11)?, 6144, 1)?; + self.execute(w, commands)?; + if self.flags()?[1] != 0 { + return Err(Error::NonFiniteMmqOutput("mtp-int8-attention")); + } + Ok(CompletedMtpAttention { + owner: self, + _snapshot: snapshot, + _query: query, + }) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + self.current = None; + let Some(mut physical) = self.physical.take() else { + return Ok(()); + }; + physical.active.set(false); + // Explicit close requires graph retirement first. Dropping this logical + // ring never frees allocations retained by a real graph resource token. + if Rc::strong_count(&physical) != 1 { + return Err(Error::InvalidQwenShape); + } + Rc::get_mut(&mut physical) + .ok_or(Error::InvalidQwenShape)? + .close_inner() + } +} +impl Drop for MtpOriginalInt8<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +impl<'ctx> MtpOriginalInt8<'ctx> { + fn new_original_state( + c: &'ctx Context<'ctx>, + max_t: usize, + main: Rc>, + spans: [(usize, usize); 7], + prepared: ring_state::PreparedState<'ctx>, + ) -> Result { + let (slots, sizes) = layout(max_t)?; + if c.is_poisoned() { + return Err(Error::ContextPoisoned); + } + for ptx in [ + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + include_bytes!("qsa_native_decode.ptx").as_slice(), + ] { + if ptx.windows(8).any(|w| w == b"UNSEALED") { + return Err(Error::UnsupportedQwenOperation); + } + } + let origin = Rc::new(Origin); + let physical = Rc::new(PhysicalRing { + context: c, + origin: origin.clone(), + sizes, + buffers: std::array::from_fn(|_| None), + modules: std::array::from_fn(|_| None), + mapped: RefCell::new(None), + selected: None, + failed: Cell::new(false), + active: Cell::new(true), + }); + let mut o = Self { + context: c, + origin, + max_t, + slots, + sizes, + physical: Some(physical), + current: None, + failed: false, + generation: 0, + }; + let op = (|| { + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + for (i, (ptx, entries)) in [ + ( + include_bytes!("mtp_original_tail.ptx").as_slice(), + TAIL_ENTRIES, + ), + (include_bytes!("mtp_original_kv.ptx").as_slice(), KV_ENTRIES), + ( + include_bytes!("qsa_native_decode.ptx").as_slice(), + ATTN_ENTRIES, + ), + ] + .into_iter() + .enumerate() + { + o.physical_mut()?.modules[i] = Some(Module::load(ptx, entries)?); + } + Ok(()) + })(); + let pop = g.finish(); + if pop.is_err() { + o.poison(); + } + combine(load, pop)?; + let (selected, mapped) = ring_state::Selected::from_prepared(prepared, main, spans)?; + if selected.layout.resident { + o.slots = 65536; + for (i, n) in [134217728, 134217728, 4194304, 4194304, 262144] + .into_iter() + .enumerate() + { + o.sizes[i] = n; + o.physical_mut()?.sizes[i] = n; + } + } + o.physical_mut()?.selected = Some(selected); + *o.physical_mut()?.mapped.get_mut() = mapped; + let extras = o + .sizes + .into_iter() + .enumerate() + .filter(|(i, _)| !matches!(i,0..=9|12..=14)) + .try_fold(0usize, |a, (_, n)| { + a.checked_add(n).ok_or(Error::BudgetExceeded) + })?; + let need = extras.checked_add(RESERVE).ok_or(Error::BudgetExceeded)?; + if c.allocated_bytes() + .checked_add(need) + .is_none_or(|n| n > c.budget) + || c.memory_info()?.0 < need + { + return Err(Error::BudgetExceeded); + } + for (i, n) in o.sizes.into_iter().enumerate() { + if !matches!(i,0..=9|12..=14) { + o.physical_mut()?.buffers[i] = Some(c.allocate(n)?); + } + } + o.validate()?; + if c.memory_info()?.0 < RESERVE { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = op { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn fully_resident(&self) -> Result { + self.validate()?; + Ok(self + .physical()? + .selected + .as_ref() + .is_some_and(|s| s.layout.resident)) + } + pub fn actual_pinned_host_bytes(&self) -> Result { + let p = self.physical()?; + let m = p.mapped.try_borrow().map_err(|_| Error::InvalidQwenShape)?; + Ok((if p.selected.is_some() { 116 } else { 0 }) + m.as_ref().map_or(0, MappedOwner::bytes)) + } + fn host_addresses(&self) -> Result<[u64; 4]> { + if self.fully_resident()? { + return Ok([0; 4]); + } + let mapped = self.mapped()?; + let mut a = [0; 4]; + for (i, n) in HOST_RUNS.into_iter().enumerate() { + a[i] = mapped.address(HOST_OFFSETS[i], n)?; + } + Ok(a) + } + fn read_encoded_page(&self, page: usize, runs: &mut [Vec; 4]) -> Result<()> { + if self.fully_resident()? { + return self + .physical()? + .selected + .as_ref() + .ok_or(Error::ContextPoisoned)? + .read_page(page, runs); + } + let mapped = self.mapped()?; + for (i, n) in PAGE_BYTES.into_iter().enumerate() { + if runs[i].len() != n { + return Err(Error::InvalidSize); + } + mapped.read_into(HOST_OFFSETS[i] + page * n, &mut runs[i])?; + } + Ok(()) + } + fn validate_original_main(&self, main: &Rc>) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + if !s.same_main(main) { + return Err(Error::InvalidQwenShape); + } + } + Ok(()) + } + fn reject_state_alias(&self, b: &DeviceBuffer<'_>) -> Result<()> { + if let Some(s) = &self.physical()?.selected { + s.reject_state_alias(b)?; + } + Ok(()) + } + /// State+retained diagnostic owners only; main bank is counted by paired layout. + pub fn planned_original_state_device_bytes( + max_t: usize, + fully_resident: bool, + ) -> Result { + let (_, sizes) = layout(max_t)?; + sizes + .into_iter() + .enumerate() + .filter(|(i, _)| !matches!(i,0..=9|12..=14)) + .try_fold( + ring_state::StateLayout::new(max_t, fully_resident)?.bytes, + |a, (_, n)| a.checked_add(n).ok_or(Error::InvalidSize), + ) + } +} diff --git a/crates/cuda-driver/src/mtp_original_logical_prefix.rs b/crates/cuda-driver/src/mtp_original_logical_prefix.rs index 16c8d2d9..081a97db 100644 --- a/crates/cuda-driver/src/mtp_original_logical_prefix.rs +++ b/crates/cuda-driver/src/mtp_original_logical_prefix.rs @@ -1,201 +1,203 @@ -//! Child of mtp_original_int8. A skipped Original prompt group advances only -//! the logical conditioning cursor; it NEVER manufactures materialized KV pages. -use super::*; -use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity}; -/// Genuine ring- and prompt-lease-bound no-work result. The retained physical -/// snapshot remains unchanged and may be empty even when `logical_end` is large. -pub struct OriginalMtpSkippedPrefix { - physical: MtpInt8Snapshot, - generation: u64, - start: usize, - logical_end: usize, - full_prompt_length: usize, - first_needed: usize, - lease: OriginalPromptLeaseIdentity, -} -impl OriginalMtpSkippedPrefix { - pub fn logical_end(&self) -> usize { - self.logical_end - } - pub fn first_needed(&self) -> usize { - self.first_needed - } - pub fn physical_snapshot(&self) -> &MtpInt8Snapshot { - &self.physical - } - pub fn materialized_end(&self) -> usize { - self.physical.0.end - } - pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { - ring.validate_snapshot(&self.physical)?; - if ring.generation != self.generation - || !ring - .current - .as_ref() - .is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn validate_source( - &self, - residual: &OriginalDeviceResidual<'_, '_, '_>, - cell0: usize, - full_prompt_length: usize, - ) -> Result<()> { - if self.start != cell0 - || self.logical_end.checked_sub(cell0) != Some(residual.rows()) - || full_prompt_length != self.full_prompt_length - || !self.lease.same_lease(&residual.lease_identity()) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn metadata_bytes(&self) -> usize { - std::mem::size_of::() - } -} -impl MtpOriginalInt8<'_> { - /// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root - /// supplies full_prompt_length from retained OriginalPromptTxn source, not - /// from this chunk's end. No stream, kernel, page allocation or numerical - /// completion occurs in this outcome. - pub fn skip_original_prompt_prefix( - &mut self, - residual: &OriginalDeviceResidual<'_, '_, '_>, - physical_prior: &MtpInt8Snapshot, - logical_prior: Option<&OriginalMtpSkippedPrefix>, - cell0: usize, - full_prompt_length: usize, - ) -> Result> { - self.validate_snapshot(physical_prior)?; - if !residual.context_matches(self.context) - || residual.rows() == 0 - || full_prompt_length > MTP_ORIGINAL_MAX_CELLS - { - return Err(Error::InvalidProjectionShape); - } - let end = cell0 - .checked_add(residual.rows()) - .ok_or(Error::InvalidSize)?; - if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS { - return Err(Error::InvalidProjectionShape); - } - let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64); - let logical_start = if let Some(old) = logical_prior { - old.validate_current(self)?; - if old.full_prompt_length != full_prompt_length - || old.first_needed != first_needed - || !Rc::ptr_eq(&old.physical.0, &physical_prior.0) - { - return Err(Error::InvalidQwenShape); - } - old.logical_end - } else { - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) - { - return Err(Error::InvalidQwenShape); - } - if self.current.is_none() && physical_prior.0.end != 0 { - return Err(Error::InvalidQwenShape); - } - physical_prior.0.end - }; - if logical_start != cell0 { - return Err(Error::InvalidQwenShape); - } - // All complete groups are skipped iff the last group's end<=cutoff. This - // includes Original short remainder group; no individual-cell rounding. - if end > first_needed { - return Ok(None); - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - let result = OriginalMtpSkippedPrefix { - physical: physical_prior.clone(), - generation, - start: cell0, - logical_end: end, - full_prompt_length, - first_needed, - lease: residual.lease_identity(), - }; - self.current = Some(physical_prior.clone()); - self.generation = generation; - Ok(Some(result)) - } -} - -impl MtpOriginalInt8<'_> { - /// Private affine transition used only by the literal captured drafter. Actual - /// graph/window guards and successful drain, not these integers, authorize it. - pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result { - self.validate_snapshot(prior)?; - if self - .current - .as_ref() - .is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) - || self.current.is_none() && prior.0.end != 0 - { - return Err(Error::InvalidQwenShape); - } - let generation = self - .generation - .checked_add(1) - .ok_or(Error::InvalidQwenShape)?; - self.current = None; - self.generation = generation; - Ok(generation) - } - pub(crate) fn finish_original_graph_mutation( - &mut self, - prior: &MtpInt8Snapshot, - first: usize, - end: usize, - generation: u64, - ) -> Result { - self.validate_snapshot(prior)?; - if self.current.is_some() - || self.generation != generation - || first > prior.0.end - || end <= first - || end > MTP_ORIGINAL_MAX_CELLS - { - return Err(Error::InvalidQwenShape); - } - let page0 = first / 4; - let page1 = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(page1) - .map_err(|_| Error::HostAllocation)?; - for p in 0..page1 { - if p < page0 { - pages.push(prior.0.pages.get(p).ok_or(Error::InvalidQwenShape)?.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)?; - } - self.read_encoded_page(p, &mut runs)?; - pages.push(Rc::new(Page { - runs: runs.map(Vec::into_boxed_slice), - })); - } - let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.origin.clone(), - pages: Rc::new(pages.into_boxed_slice()), - end, - })); - self.current = Some(snapshot.clone()); - Ok(snapshot) - } -} +//! Child of mtp_original_int8. A skipped Original prompt group advances only +//! the logical conditioning cursor; it NEVER manufactures materialized KV pages. +use super::*; +use crate::{OriginalDeviceResidual, OriginalPromptLeaseIdentity}; +/// Genuine ring- and prompt-lease-bound no-work result. The retained physical +/// snapshot remains unchanged and may be empty even when `logical_end` is large. +pub struct OriginalMtpSkippedPrefix { + physical: MtpInt8Snapshot, + generation: u64, + start: usize, + logical_end: usize, + full_prompt_length: usize, + first_needed: usize, + lease: OriginalPromptLeaseIdentity, +} +impl OriginalMtpSkippedPrefix { + pub fn logical_end(&self) -> usize { + self.logical_end + } + pub fn first_needed(&self) -> usize { + self.first_needed + } + pub fn physical_snapshot(&self) -> &MtpInt8Snapshot { + &self.physical + } + pub fn materialized_end(&self) -> usize { + self.physical.0.end + } + pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { + ring.validate_snapshot(&self.physical)?; + if ring.generation != self.generation + || !ring + .current + .as_ref() + .is_some_and(|s| Rc::ptr_eq(&s.0, &self.physical.0)) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn validate_source( + &self, + residual: &OriginalDeviceResidual<'_, '_, '_>, + cell0: usize, + full_prompt_length: usize, + ) -> Result<()> { + if self.start != cell0 + || self.logical_end.checked_sub(cell0) != Some(residual.rows()) + || full_prompt_length != self.full_prompt_length + || !self.lease.same_lease(&residual.lease_identity()) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn metadata_bytes(&self) -> usize { + std::mem::size_of::() + } +} +impl MtpOriginalInt8<'_> { + /// Literal mtp.cpp690 cutoff, checked against actual whole prompt rows. Root + /// supplies full_prompt_length from retained OriginalPromptTxn source, not + /// from this chunk's end. No stream, kernel, page allocation or numerical + /// completion occurs in this outcome. + pub fn skip_original_prompt_prefix( + &mut self, + residual: &OriginalDeviceResidual<'_, '_, '_>, + physical_prior: &MtpInt8Snapshot, + logical_prior: Option<&OriginalMtpSkippedPrefix>, + cell0: usize, + full_prompt_length: usize, + ) -> Result> { + self.validate_snapshot(physical_prior)?; + if !residual.context_matches(self.context) + || residual.rows() == 0 + || full_prompt_length > MTP_ORIGINAL_MAX_CELLS + { + return Err(Error::InvalidProjectionShape); + } + let end = cell0 + .checked_add(residual.rows()) + .ok_or(Error::InvalidSize)?; + if end > full_prompt_length || end > MTP_ORIGINAL_MAX_CELLS { + return Err(Error::InvalidProjectionShape); + } + let first_needed = full_prompt_length.saturating_sub(MTP_ORIGINAL_WINDOW + 64); + let logical_start = if let Some(old) = logical_prior { + old.validate_current(self)?; + if old.full_prompt_length != full_prompt_length + || old.first_needed != first_needed + || !Rc::ptr_eq(&old.physical.0, &physical_prior.0) + { + return Err(Error::InvalidQwenShape); + } + old.logical_end + } else { + if self + .current + .as_ref() + .is_some_and(|s| !Rc::ptr_eq(&s.0, &physical_prior.0)) + { + return Err(Error::InvalidQwenShape); + } + if self.current.is_none() && physical_prior.0.end != 0 { + return Err(Error::InvalidQwenShape); + } + physical_prior.0.end + }; + if logical_start != cell0 { + return Err(Error::InvalidQwenShape); + } + // All complete groups are skipped iff the last group's end<=cutoff. This + // includes Original short remainder group; no individual-cell rounding. + if end > first_needed { + return Ok(None); + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + let result = OriginalMtpSkippedPrefix { + physical: physical_prior.clone(), + generation, + start: cell0, + logical_end: end, + full_prompt_length, + first_needed, + lease: residual.lease_identity(), + }; + self.current = Some(physical_prior.clone()); + self.generation = generation; + Ok(Some(result)) + } +} + +impl MtpOriginalInt8<'_> { + /// Private affine transition used only by the literal captured drafter. Actual + /// graph/window guards and successful drain, not these integers, authorize it. + pub(crate) fn begin_original_graph_mutation(&mut self, prior: &MtpInt8Snapshot) -> Result { + self.validate_snapshot(prior)?; + if self + .current + .as_ref() + .is_some_and(|s| !Rc::ptr_eq(&s.0, &prior.0)) + || self.current.is_none() && prior.0.end != 0 + { + return Err(Error::InvalidQwenShape); + } + let generation = self + .generation + .checked_add(1) + .ok_or(Error::InvalidQwenShape)?; + self.current = None; + self.generation = generation; + Ok(generation) + } + pub(crate) fn finish_original_graph_mutation( + &mut self, + prior: &MtpInt8Snapshot, + first: usize, + end: usize, + generation: u64, + ) -> Result { + self.validate_snapshot(prior)?; + if self.current.is_some() + || self.generation != generation + || first > prior.0.end + || end <= first + || end > MTP_ORIGINAL_MAX_CELLS + { + return Err(Error::InvalidQwenShape); + } + let page0 = first / 4; + let page1 = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(page1) + .map_err(|_| Error::HostAllocation)?; + for p in 0..page1 { + if p < page0 { + pages.push(prior.0.pages.get(p).ok_or(Error::InvalidQwenShape)?.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)?; + } + self.read_encoded_page(p, &mut runs)?; + pages.push(Rc::new(Page { + runs: runs.map(Vec::into_boxed_slice), + })); + } + let snapshot = MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.origin.clone(), + pages: Rc::new(pages.into_boxed_slice()), + end, + // the leading pages are the checked prior's (`validate_snapshot` above), the others were just sized by `zero_bytes` + checked: std::cell::Cell::new(true), + })); + self.current = Some(snapshot.clone()); + Ok(snapshot) + } +} diff --git a/crates/cuda-driver/src/mtp_original_prefill.rs b/crates/cuda-driver/src/mtp_original_prefill.rs index 011d64f3..d3963e31 100644 --- a/crates/cuda-driver/src/mtp_original_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_prefill.rs @@ -1,1600 +1,1602 @@ -//! Literal prefill.cpp741..886, Q8_0 branch, on the actual borrowed prompt -//! region. Register as a PRIVATE child of mtp_original_int8: ring/host backing -//! never becomes a public address or a fabricated owning DeviceBuffer. -use super::*; -use crate::ffi::BufferHandle; -use crate::original_prefill_arena::OriginalPromptSpan; -use crate::{OriginalDeviceResidual, OriginalPromptRows}; -#[allow(unsafe_code)] -#[path = "mtp_original_prefill_ffi.rs"] -mod prefill_abi; -use prefill_abi::{Arg as A, Arguments as Args, Module as Mod}; -use std::ffi::CStr; -const RESERVE_BYTES: usize = 128 << 20; -const FLAG_WORDS: usize = 24; -const WIDTHS: [usize; 11] = [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128]; -const ENTRIES: &[&CStr] = &[ - c"mtp_prefill_rms", - c"mtp_prefill_gr_norm", - c"mtp_prefill_gr_silu", - c"mtp_prefill_gr_mix", - c"mtp_prefill_broadcast", - c"mtp_prefill_embedding", - c"mtp_prefill_rope", - c"mtp_prefill_append", - c"mtp_prefill_finite", - c"mtp_prefill_iota", - c"mtp_prefill_encoded", - c"mtp_prefill_zero", - c"mtp_prefill_gr_norm_scan", - c"mtp_prefill_gr_silu_scan", - c"mtp_prefill_bf16_scan", - c"mtp_prefill_gr_product_scan", - c"mtp_prefill_q8_scan", -]; -#[path = "mtp_original_prefill_symbols.rs"] -mod symbols; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum DraftKvFallback { - Disabled, - Empty, - UnsupportedStorage, - MissingWeights, - UnsupportedEmbedding, - AlternateF16, - RegionTooSmall, - NoQ8Tile, - UnsupportedRopeTable, -} -pub enum DraftKvOutcome { - Fallback(DraftKvFallback), - Skipped, - Cancelled, - Completed(CompletedDraftKv), -} -/// Actual completed range, not a readiness bit or a scalar committed product. -/// Root retains the lower materialized bound with its real draft window state. -pub struct CompletedDraftKv { - snapshot: MtpInt8Snapshot, - first_materialized: usize, - end: usize, - generation: u64, -} -impl CompletedDraftKv { - pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { - ring.validate_snapshot(&self.snapshot)?; - if ring.is_failed() - || ring.generation != self.generation - || self.snapshot.0.end != self.end - || self.first_materialized >= self.end - || ring - .current - .as_ref() - .is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) - { - return Err(Error::InvalidQwenShape); - } - Ok(()) - } - pub fn first_materialized(&self) -> usize { - self.first_materialized - } - pub fn next_position(&self) -> usize { - self.end - } - pub fn owner_id(&self) -> MtpInt8OwnerId { - self.snapshot.owner_id() - } - pub fn generation(&self) -> u64 { - self.generation - } - pub fn snapshot_after(&self, position: usize) -> Result { - if position < self.first_materialized || position >= self.end { - return Err(Error::InvalidQwenShape); - } - if position + 1 == self.end { - return Ok(self.snapshot.clone()); - } - Ok(MtpInt8Snapshot(Rc::new(Snapshot { - origin: self.snapshot.0.origin.clone(), - pages: self.snapshot.0.pages.clone(), - end: position + 1, - }))) - } - /// Use only after checking the true requested window excludes pruned cells. - pub fn snapshot_for_window(&self, position: usize, window: usize) -> Result { - if window == 0 - || position >= self.end - || position - .checked_add(1) - .ok_or(Error::InvalidSize)? - .saturating_sub(window) - < self.first_materialized - { - return Err(Error::InvalidQwenShape); - } - self.snapshot_after(position) - } -} -/// These are actual whole matrix loans acquired by Root's binding owner. The -/// private runtime adapter independently checks descriptor/role identity. -pub struct OriginalMtpPrefillWeights<'a, 'ctx> { - pub embedding_norm: &'a DeviceBuffer<'ctx>, - pub embedding_fc: &'a DeviceBuffer<'ctx>, - pub hidden_norm: &'a DeviceBuffer<'ctx>, - pub hidden_fc: &'a DeviceBuffer<'ctx>, - pub gr_norm: &'a DeviceBuffer<'ctx>, - pub gr_down: &'a DeviceBuffer<'ctx>, - pub gr_up: &'a DeviceBuffer<'ctx>, - pub key: &'a DeviceBuffer<'ctx>, - pub value: &'a DeviceBuffer<'ctx>, - pub key_norm: &'a DeviceBuffer<'ctx>, -} -/// Entire real embedding source, never a borrowed raw pointer supplied by the -/// public protocol. Construction is private to authenticated source adapters. -pub struct OriginalMtpEmbedding<'a, 'ctx> { - table: &'a DeviceBuffer<'ctx>, - kind: EmbeddingKind, -} -enum EmbeddingKind { - Native { - kind: i32, - row_bytes: usize, - vocab: usize, - }, - Compressed { - bits: i32, - bias: i32, - group: usize, - vocab: usize, - codes: usize, - scales: usize, - offsets: bool, - }, -} -impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { - pub fn native( - table: &'a DeviceBuffer<'ctx>, - kind: i32, - row_bytes: usize, - vocab: usize, - ) -> Result { - let per = match kind { - 16 => 66, - 17 => 74, - 18 => 98, - 20 => 144, - 21 => 110, - 22 => 82, - 23 => 136, - 29 => 56, - 11 => 110, - 12 => 144, - 13 => 176, - 7 => 192, - 8 => 272, - 42 => 72, - 30 => 512, - _ => return Err(Error::UnsupportedProjection), - }; - if row_bytes != 10 * per - || vocab == 0 - || vocab > 262144 - || table.bytes != row_bytes.checked_mul(vocab).ok_or(Error::InvalidSize)? - { - return Err(Error::InvalidProjectionShape); - } - Ok(Self { - table, - kind: EmbeddingKind::Native { - kind, - row_bytes, - vocab, - }, - }) - } - pub fn compressed( - table: &'a DeviceBuffer<'ctx>, - bits: i32, - bias: i32, - group: usize, - vocab: usize, - offsets: bool, - ) -> Result { - if !matches!(bits, 2 | 4 | 8) - || group == 0 - || !2560usize.is_multiple_of(group) - || vocab == 0 - || vocab > 262144 - { - return Err(Error::InvalidProjectionShape); - } - let codes = vocab - .checked_mul(2560 / (8 / bits as usize)) - .ok_or(Error::InvalidSize)?; - let scales = vocab - .checked_mul(2560 / group) - .and_then(|n| n.checked_mul(4)) - .ok_or(Error::InvalidSize)?; - let total = codes - .checked_add( - scales - .checked_mul(if offsets { 2 } else { 1 }) - .ok_or(Error::InvalidSize)?, - ) - .ok_or(Error::InvalidSize)?; - if table.bytes != total { - return Err(Error::InvalidProjectionShape); - } - Ok(Self { - table, - kind: EmbeddingKind::Compressed { - bits, - bias, - group, - vocab, - codes, - scales, - offsets, - }, - }) - } - fn vocab(&self) -> usize { - match self.kind { - EmbeddingKind::Native { vocab, .. } | EmbeddingKind::Compressed { vocab, .. } => vocab, - } - } -} -/// Explicit Original optional policy. It cannot assert finite tensors, source -/// provenance, or readiness. Unsupported options produce fallback, never success. -pub struct DraftKvPolicy { - pub disabled: bool, - pub alternate_f16: bool, - pub rotated: bool, - pub q4: bool, - pub hybrid: bool, - pub mode: i32, - pub theta_scale: f32, - pub freq_scale: f32, - pub corr_low: f32, - pub corr_high: f32, - pub ext_factor: f32, - pub mscale: f32, - pub rope_table_enabled: bool, - pub multimodal_positions: bool, -} -impl DraftKvPolicy { - pub fn original_int8(theta_scale: f32) -> Self { - Self { - disabled: false, - alternate_f16: false, - rotated: false, - q4: false, - hybrid: false, - mode: 0, - theta_scale, - freq_scale: 1.0, - corr_low: 0.0, - corr_high: 0.0, - ext_factor: 0.0, - mscale: 1.0, - rope_table_enabled: false, - multimodal_positions: false, - } - } -} -enum Cmd { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Args, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, - Gemm { - x: BufferHandle, - w: BufferHandle, - y: BufferHandle, - rows: i32, - n: i32, - k: i32, - alpha: f32, - beta: f32, - }, -} -struct Region { - base: BufferHandle, - bytes: usize, - b: usize, - roles: [(usize, usize); 20], -} -fn fastdiv(d: u32) -> [u32; 3] { - let l = 32 - (d - 1).leading_zeros(); - [ - (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, - l, - d, - ] -} -fn aligned(n: usize) -> Result { - n.checked_add(255) - .map(|n| n & !255) - .ok_or(Error::InvalidSize) -} -fn q8_bytes(rows: usize) -> Result { - rows.checked_mul(20 * 144) - .and_then(|n| n.checked_add(128 * 144)) - .ok_or(Error::InvalidSize) -} -impl Region { - fn new(base: BufferHandle, bytes: usize, n: usize, r0: usize) -> Result> { - // Literal Original per_row (including fixed128-block tail in q8_bytes(4,N)). - let per = 4 * (2 * 2560 + 4 * 10240 + 320 + 4 + 2560 + 2 * 512 + 1) - + 2 * (2560 + 2 * 10240 + 320 + 2560) - + 64 - + q8_bytes(4)? - + 4 * 4; - let b = (n - r0).min((bytes / per) & !63); - if b < 64 { - return Ok(None); - } - let widths = [ - b * 10240, - b * 10240, - b * 5120, - b * 40960, - b * 40960, - b * 40960, - b * 40960, - b * 20480, - b * 20480, - b * 1280, - b * 640, - b * 16, - b * 10240, - b * 5120, - b * 2048, - b * 2048, - b * 4, - q8_bytes(b * 4)?, - b * 16, - 16, - ]; - let mut end: usize = 0; - let mut roles = [(0, 0); 20]; - for (i, len) in widths.into_iter().enumerate() { - roles[i] = (end, len); - end = end.checked_add(aligned(len)?).ok_or(Error::InvalidSize)?; - } - if end > bytes { - return Ok(None); - } - base.validate_projection_extent(bytes, 256)?; - Ok(Some(Self { - base, - bytes, - b, - roles, - })) - } - fn handle(&self, i: usize, len: usize) -> Result { - let (offset, extent) = self.roles.get(i).copied().ok_or(Error::InvalidSize)?; - if len == 0 || len > extent { - return Err(Error::InvalidSize); - } - self.base.checked_subspan(self.bytes, offset, len) - } - fn address(&self, i: usize, len: usize) -> Result { - Ok(self.handle(i, len)?.qwen_address()) - } -} -pub struct OriginalMtpPrefill<'ctx> { - context: &'ctx Context<'ctx>, - modules: [Option; 5], - status: Option>, - tmp: Option>, - sms: usize, - shared_limit: u32, - failed: bool, -} -impl<'ctx> Context<'ctx> { - pub fn original_mtp_prefill(&'ctx self) -> Result> { - OriginalMtpPrefill::new(self) - } -} -impl<'ctx> OriginalMtpPrefill<'ctx> { - fn new(context: &'ctx Context<'ctx>) -> Result { - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_prefill_quant.ptx").as_slice(), - include_bytes!("mtp_original_prefill_mmq.ptx").as_slice(), - include_bytes!("mtp_original_prefill_fixup.ptx").as_slice(), - ]; - if assets - .iter() - .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let mut owner = Self { - context, - modules: std::array::from_fn(|_| None), - status: None, - tmp: None, - sms: 0, - shared_limit: 0, - failed: false, - }; - let result = (|| { - let g = context.enter()?; - let load = (|| { - owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); - owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); - owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); - owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); - owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); - let (sms, limit) = owner.module(0)?.info()?; - crate::arch_ptx::latch_stream_k_policy(); - owner.sms = sms; - owner.shared_limit = limit; - Ok(()) - })(); - let pop = g.finish(); - if pop.is_err() - || load.as_ref().is_err_and(|e| { - matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) - }) - { - owner.poison(); - } - combine(load, pop)?; - let charge = owner - .sms - .checked_mul(128 * 128 * 4) - .and_then(|n| n.checked_add(FLAG_WORDS * 4)) - .ok_or(Error::BudgetExceeded)?; - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if context - .allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > context.budget_bytes()) - || context.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - owner.status = Some(context.allocate(FLAG_WORDS * 4)?); - owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); - Ok(()) - })(); - if let Err(e) = result { - return combine(Err(e), owner.close()); - } - Ok(owner) - } - pub fn allocated_bytes(&self) -> usize { - self.status.as_ref().map_or(0, DeviceBuffer::len) - + self.tmp.as_ref().map_or(0, DeviceBuffer::len) - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - fn module(&self, i: usize) -> Result<&Mod> { - self.modules - .get(i) - .and_then(Option::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn status(&self, i: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, i * 4, 4) - } - fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args: Args::new(args)?, - }); - Ok(()) - } - fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { - Self::kernel( - cmds, - 0, - 8, - [(words.div_ceil(256)) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(data), - A::I32(words as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - ) - } - fn weight( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - b: &DeviceBuffer<'_>, - bytes: usize, - ) -> Result { - if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { - return Err(Error::InvalidProjectionShape); - } - let h = b.handle.ok_or(Error::ContextPoisoned)?; - h.validate_projection_extent(bytes, 2)?; - w.reject_alias(h, bytes)?; - let (region, n) = rows.draft_kv_region()?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - for (a, len) in [ - (region, n), - (r, rn), - ( - self.status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - FLAG_WORDS * 4, - ), - ( - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?, - self.sms * 128 * 128 * 4, - ), - ] { - if h.overlaps(bytes, a, len) { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - #[allow(clippy::too_many_arguments)] - fn project( - &self, - cmds: &mut Vec, - r: &Region, - x: u64, - w: u64, - y: u64, - rows: usize, - out: usize, - bound_slot: usize, - stage: usize, - ) -> Result<()> { - if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - let mut best = None; - let mut ntx = usize::MAX; - for (i, j) in WIDTHS.into_iter().enumerate() { - if ntx <= 1 { - break; - } - let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; - if shared > self.shared_limit as usize { - continue; - } - if rows.div_ceil(j) < ntx { - best = Some((i, j, shared)); - ntx = rows.div_ceil(j); - } - } - let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; - let tiles = (out / 128) * ntx; - let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); - let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; - let fix = !tiles.is_multiple_of(grid); - if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { - return Err(Error::InvalidProjectionShape); - } - let xq = r.address(17, q8_bytes(rows)?)?; - let ids = r.address(18, rows * 4)?; - let bound = r - .handle(19, 16)? - .checked_subspan(16, bound_slot * 8, 8)? - .qwen_address(); - Self::kernel( - cmds, - 2, - 0, - [rows as u32, 5, 1], - [128, 1, 1], - 0, - vec![ - A::U64(x), - A::U64(0), - A::U64(xq), - A::I64(2560), - A::I64(2560), - A::I64((rows * 2560) as i64), - A::I64((rows * 2560) as i64), - A::I64(2560), - A::I32(rows as i32), - A::I32(1), - A::I32(1), - ], - )?; - // Original D4 data includes a fixed128-block tail. Initialize that exact - // tail before a literal vendor kernel can speculatively load it. - Self::kernel( - cmds, - 0, - 11, - [72, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq + (rows * 20 * 144) as u64), - A::I32((128 * 144) as i32), - ], - )?; - Self::kernel( - cmds, - 0, - 16, - [(rows * 20).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - A::U64(xq), - A::I32((rows * 20) as i32), - A::U64(self.status(stage)?.qwen_address()), - ], - )?; - let tmp = if fix { - self.tmp - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)? - .qwen_address() - } else { - 0 - }; - let fd = fastdiv; - Self::kernel( - cmds, - 3, - index, - [grid as u32, 1, 1], - [32, 8, 1], - shared as u32, - vec![ - A::U64(w), - A::U64(xq), - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U64(0), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(80), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32((out * 80) as i32), - A::I32(0), - A::I32(0), - A::U3(fd(1)), - A::U3(fd(1)), - A::I32(0), - A::I32(0), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - if fix { - Self::kernel( - cmds, - 4, - index, - [grid as u32, 4, 1], - [32, 4, 1], - 0, - vec![ - A::U64(ids), - A::U64(bound), - A::U64(y), - A::U64(tmp), - A::U3(fd(80)), - A::I32(out as i32), - A::I32(rows as i32), - A::I32(out as i32), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(1)), - A::I32(0), - A::U3(fd(ntx as u32)), - ], - )?; - } - Ok(()) - } - fn run( - &mut self, - rows: &mut OriginalPromptRows<'_, '_, '_>, - w: &mut NativeBatchWorkspace<'ctx>, - mut cmds: Vec, - staging: Vec<(BufferHandle, Vec)>, - ) -> Result<()> { - let mut readback = zero_bytes(FLAG_WORDS * 4)?; - let zero = zero_bytes(FLAG_WORDS * 4)?; - let status = self - .status - .as_ref() - .ok_or(Error::ContextPoisoned)? - .handle - .ok_or(Error::ContextPoisoned)?; - status.validate_projection_extent(FLAG_WORDS * 4, 4)?; - for i in 0..5 { - self.module(i)?; - } - let blas = w.blas()?; - let g = match self.context.enter() { - Ok(g) => g, - Err(e) => { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - return Err(e); - } - }; - let mut operation = self.context.driver.api.copy_from(status, &zero); - if operation.is_ok() { - for (dst, bytes) in &staging { - if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { - operation = Err(e); - break; - } - } - } - if operation.is_ok() { - operation = self.context.driver.api.synchronize(); - } - if operation.is_ok() { - for c in &mut cmds { - let r = match c { - Cmd::Kernel { - asset, - index, - grid, - block, - shared, - args, - } => self.modules[*asset] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.launch(*index, *grid, *block, *shared, blas.stream(), args) - }), - Cmd::Copy { dst, src, bytes } => self.modules[0] - .as_ref() - .map_or(Err(Error::ContextPoisoned), |m| { - m.copy(*dst, *src, *bytes, blas.stream()) - }), - Cmd::Gemm { - x, - w, - y, - rows, - n, - k, - alpha, - beta, - } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), - }; - if let Err(e) = r { - operation = Err(e); - break; - } - } - } - let stream = blas.synchronize(); - if operation.is_ok() && stream.is_ok() { - operation = self.context.driver.api.copy_to(status, &mut readback); - } - let device = self.context.driver.api.synchronize(); - let pop = g.finish(); - if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { - self.poison(); - rows.mark_failed(); - w.mark_failed(); - } - if stream.is_err() || device.is_err() || pop.is_err() { - std::mem::forget((cmds, staging, zero, readback)); - self.context.retain_driver(); - return combine(combine(combine(operation, stream), device), pop); - } - combine(combine(combine(operation, stream), device), pop)?; - for word in readback.chunks_exact(4) { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { - self.poison(); - return Err(Error::InvalidDriverValue("draft prefill status")); - } - } - for (stage, word) in readback.chunks_exact(4).enumerate() { - if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { - return Err(Error::NonFiniteMmqOutput(match stage { - 0 => "MTP embedding", - 1 => "MTP embedding norm", - 2 => "MTP FC embedding", - 3 => "MTP hidden norm", - 4 => "MTP FC hidden", - 5 => "MTP broadcast", - 6 => "MTP GR normalized", - 7 => "MTP GR down", - 8 => "MTP GR SiLU", - 9 => "MTP GR up", - 10 => "MTP GR mixed", - 11 => "MTP K", - 12 => "MTP V", - 13 => "MTP K norm", - 14 => "MTP K Rope", - _ => "MTP INT8 encoded", - })); - } - } - Ok(()) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - weights: OriginalMtpPrefillWeights<'_, '_>, - embedding: OriginalMtpEmbedding<'_, '_>, - policy: &DraftKvPolicy, - mut cancelled: impl FnMut() -> bool, - ) -> Result { - if policy.disabled { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); - } - if tokens.is_empty() { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); - } - if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { - return Ok(DraftKvOutcome::Fallback( - DraftKvFallback::UnsupportedStorage, - )); - } - if policy.alternate_f16 { - return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); - } - if policy.rope_table_enabled || policy.multimodal_positions { - return Ok(DraftKvOutcome::Fallback( - 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()) - || policy.theta_scale <= 0.0 - || policy.freq_scale <= 0.0 - || policy.mscale <= 0.0 - { - return Err(Error::InvalidProjectionShape); - } - ring.validate_snapshot(prior)?; - workspace.validate_context(self.context)?; - ring.validate_context(self.context)?; - if 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(); - 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)); - }; - 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)); - } - 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 mut wh = [region; 10]; - for i in 0..10 { - wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; - } - crate::bringup_trace!("DBG prefill.record: 10 weights staged"); - let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); 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) { - let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; - let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; - if ah.overlaps(a.bytes, bh, b.bytes) - && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) - { - return Err(Error::OutputAliasesInput); - } - } - } - for b in weight_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) - { - return Err(Error::OutputAliasesInput); - } - } - // Actual input residual lies outside the region being overwritten. - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; - crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); - 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); - } - } - 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; - let page_count = end.div_ceil(4); - let mut pages = Vec::new(); - pages - .try_reserve_exact(page_count) - .map_err(|_| Error::HostAllocation)?; - let mut changed = Vec::new(); - changed - .try_reserve_exact(page_count - first_page) - .map_err(|_| Error::HostAllocation)?; - for p in 0..page_count { - if p < first_page { - if let Some(page) = prior.0.pages.get(p) { - pages.push(page.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); - } - } - if cancelled() { - return Ok(DraftKvOutcome::Cancelled); - } - // Genuine idle dependency before this stream can mutate the real drafter KV. - 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:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot - ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; - 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); - } - } - 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); - 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: Rc::new(pages.into_boxed_slice()), - end, - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut first = Ok(()); - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - first = combine(first, r); - } - } - for b in [&mut self.status, &mut self.tmp] { - if let Some(b) = b.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - b.release() - }; - first = combine(first, r); - } - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - first - } -} -impl Drop for OriginalMtpPrefill<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -#[path = "mtp_original_scalar_prefill.rs"] -mod scalar; -pub use scalar::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, - OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, -}; -pub(crate) use scalar::session_assets_sealed; +//! Literal prefill.cpp741..886, Q8_0 branch, on the actual borrowed prompt +//! region. Register as a PRIVATE child of mtp_original_int8: ring/host backing +//! never becomes a public address or a fabricated owning DeviceBuffer. +use super::*; +use crate::ffi::BufferHandle; +use crate::original_prefill_arena::OriginalPromptSpan; +use crate::{OriginalDeviceResidual, OriginalPromptRows}; +#[allow(unsafe_code)] +#[path = "mtp_original_prefill_ffi.rs"] +mod prefill_abi; +use prefill_abi::{Arg as A, Arguments as Args, Module as Mod}; +use std::ffi::CStr; +const RESERVE_BYTES: usize = 128 << 20; +const FLAG_WORDS: usize = 24; +const WIDTHS: [usize; 11] = [8, 16, 24, 32, 40, 48, 64, 80, 96, 112, 128]; +const ENTRIES: &[&CStr] = &[ + c"mtp_prefill_rms", + c"mtp_prefill_gr_norm", + c"mtp_prefill_gr_silu", + c"mtp_prefill_gr_mix", + c"mtp_prefill_broadcast", + c"mtp_prefill_embedding", + c"mtp_prefill_rope", + c"mtp_prefill_append", + c"mtp_prefill_finite", + c"mtp_prefill_iota", + c"mtp_prefill_encoded", + c"mtp_prefill_zero", + c"mtp_prefill_gr_norm_scan", + c"mtp_prefill_gr_silu_scan", + c"mtp_prefill_bf16_scan", + c"mtp_prefill_gr_product_scan", + c"mtp_prefill_q8_scan", +]; +#[path = "mtp_original_prefill_symbols.rs"] +mod symbols; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum DraftKvFallback { + Disabled, + Empty, + UnsupportedStorage, + MissingWeights, + UnsupportedEmbedding, + AlternateF16, + RegionTooSmall, + NoQ8Tile, + UnsupportedRopeTable, +} +pub enum DraftKvOutcome { + Fallback(DraftKvFallback), + Skipped, + Cancelled, + Completed(CompletedDraftKv), +} +/// Actual completed range, not a readiness bit or a scalar committed product. +/// Root retains the lower materialized bound with its real draft window state. +pub struct CompletedDraftKv { + snapshot: MtpInt8Snapshot, + first_materialized: usize, + end: usize, + generation: u64, +} +impl CompletedDraftKv { + pub fn validate_current(&self, ring: &MtpOriginalInt8<'_>) -> Result<()> { + ring.validate_snapshot(&self.snapshot)?; + if ring.is_failed() + || ring.generation != self.generation + || self.snapshot.0.end != self.end + || self.first_materialized >= self.end + || ring + .current + .as_ref() + .is_none_or(|current| !Rc::ptr_eq(¤t.0, &self.snapshot.0)) + { + return Err(Error::InvalidQwenShape); + } + Ok(()) + } + pub fn first_materialized(&self) -> usize { + self.first_materialized + } + pub fn next_position(&self) -> usize { + self.end + } + pub fn owner_id(&self) -> MtpInt8OwnerId { + self.snapshot.owner_id() + } + pub fn generation(&self) -> u64 { + self.generation + } + pub fn snapshot_after(&self, position: usize) -> Result { + if position < self.first_materialized || position >= self.end { + return Err(Error::InvalidQwenShape); + } + if position + 1 == self.end { + return Ok(self.snapshot.clone()); + } + Ok(MtpInt8Snapshot(Rc::new(Snapshot { + origin: self.snapshot.0.origin.clone(), + pages: self.snapshot.0.pages.clone(), + end: position + 1, + checked: std::cell::Cell::new(self.snapshot.0.checked.get()), + }))) + } + /// Use only after checking the true requested window excludes pruned cells. + pub fn snapshot_for_window(&self, position: usize, window: usize) -> Result { + if window == 0 + || position >= self.end + || position + .checked_add(1) + .ok_or(Error::InvalidSize)? + .saturating_sub(window) + < self.first_materialized + { + return Err(Error::InvalidQwenShape); + } + self.snapshot_after(position) + } +} +/// These are actual whole matrix loans acquired by Root's binding owner. The +/// private runtime adapter independently checks descriptor/role identity. +pub struct OriginalMtpPrefillWeights<'a, 'ctx> { + pub embedding_norm: &'a DeviceBuffer<'ctx>, + pub embedding_fc: &'a DeviceBuffer<'ctx>, + pub hidden_norm: &'a DeviceBuffer<'ctx>, + pub hidden_fc: &'a DeviceBuffer<'ctx>, + pub gr_norm: &'a DeviceBuffer<'ctx>, + pub gr_down: &'a DeviceBuffer<'ctx>, + pub gr_up: &'a DeviceBuffer<'ctx>, + pub key: &'a DeviceBuffer<'ctx>, + pub value: &'a DeviceBuffer<'ctx>, + pub key_norm: &'a DeviceBuffer<'ctx>, +} +/// Entire real embedding source, never a borrowed raw pointer supplied by the +/// public protocol. Construction is private to authenticated source adapters. +pub struct OriginalMtpEmbedding<'a, 'ctx> { + table: &'a DeviceBuffer<'ctx>, + kind: EmbeddingKind, +} +enum EmbeddingKind { + Native { + kind: i32, + row_bytes: usize, + vocab: usize, + }, + Compressed { + bits: i32, + bias: i32, + group: usize, + vocab: usize, + codes: usize, + scales: usize, + offsets: bool, + }, +} +impl<'a, 'ctx> OriginalMtpEmbedding<'a, 'ctx> { + pub fn native( + table: &'a DeviceBuffer<'ctx>, + kind: i32, + row_bytes: usize, + vocab: usize, + ) -> Result { + let per = match kind { + 16 => 66, + 17 => 74, + 18 => 98, + 20 => 144, + 21 => 110, + 22 => 82, + 23 => 136, + 29 => 56, + 11 => 110, + 12 => 144, + 13 => 176, + 7 => 192, + 8 => 272, + 42 => 72, + 30 => 512, + _ => return Err(Error::UnsupportedProjection), + }; + if row_bytes != 10 * per + || vocab == 0 + || vocab > 262144 + || table.bytes != row_bytes.checked_mul(vocab).ok_or(Error::InvalidSize)? + { + return Err(Error::InvalidProjectionShape); + } + Ok(Self { + table, + kind: EmbeddingKind::Native { + kind, + row_bytes, + vocab, + }, + }) + } + pub fn compressed( + table: &'a DeviceBuffer<'ctx>, + bits: i32, + bias: i32, + group: usize, + vocab: usize, + offsets: bool, + ) -> Result { + if !matches!(bits, 2 | 4 | 8) + || group == 0 + || !2560usize.is_multiple_of(group) + || vocab == 0 + || vocab > 262144 + { + return Err(Error::InvalidProjectionShape); + } + let codes = vocab + .checked_mul(2560 / (8 / bits as usize)) + .ok_or(Error::InvalidSize)?; + let scales = vocab + .checked_mul(2560 / group) + .and_then(|n| n.checked_mul(4)) + .ok_or(Error::InvalidSize)?; + let total = codes + .checked_add( + scales + .checked_mul(if offsets { 2 } else { 1 }) + .ok_or(Error::InvalidSize)?, + ) + .ok_or(Error::InvalidSize)?; + if table.bytes != total { + return Err(Error::InvalidProjectionShape); + } + Ok(Self { + table, + kind: EmbeddingKind::Compressed { + bits, + bias, + group, + vocab, + codes, + scales, + offsets, + }, + }) + } + fn vocab(&self) -> usize { + match self.kind { + EmbeddingKind::Native { vocab, .. } | EmbeddingKind::Compressed { vocab, .. } => vocab, + } + } +} +/// Explicit Original optional policy. It cannot assert finite tensors, source +/// provenance, or readiness. Unsupported options produce fallback, never success. +pub struct DraftKvPolicy { + pub disabled: bool, + pub alternate_f16: bool, + pub rotated: bool, + pub q4: bool, + pub hybrid: bool, + pub mode: i32, + pub theta_scale: f32, + pub freq_scale: f32, + pub corr_low: f32, + pub corr_high: f32, + pub ext_factor: f32, + pub mscale: f32, + pub rope_table_enabled: bool, + pub multimodal_positions: bool, +} +impl DraftKvPolicy { + pub fn original_int8(theta_scale: f32) -> Self { + Self { + disabled: false, + alternate_f16: false, + rotated: false, + q4: false, + hybrid: false, + mode: 0, + theta_scale, + freq_scale: 1.0, + corr_low: 0.0, + corr_high: 0.0, + ext_factor: 0.0, + mscale: 1.0, + rope_table_enabled: false, + multimodal_positions: false, + } + } +} +enum Cmd { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Args, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, + Gemm { + x: BufferHandle, + w: BufferHandle, + y: BufferHandle, + rows: i32, + n: i32, + k: i32, + alpha: f32, + beta: f32, + }, +} +struct Region { + base: BufferHandle, + bytes: usize, + b: usize, + roles: [(usize, usize); 20], +} +fn fastdiv(d: u32) -> [u32; 3] { + let l = 32 - (d - 1).leading_zeros(); + [ + (((1u64 << 32) * ((1u64 << l) - u64::from(d)) / u64::from(d)) + 1) as u32, + l, + d, + ] +} +fn aligned(n: usize) -> Result { + n.checked_add(255) + .map(|n| n & !255) + .ok_or(Error::InvalidSize) +} +fn q8_bytes(rows: usize) -> Result { + rows.checked_mul(20 * 144) + .and_then(|n| n.checked_add(128 * 144)) + .ok_or(Error::InvalidSize) +} +impl Region { + fn new(base: BufferHandle, bytes: usize, n: usize, r0: usize) -> Result> { + // Literal Original per_row (including fixed128-block tail in q8_bytes(4,N)). + let per = 4 * (2 * 2560 + 4 * 10240 + 320 + 4 + 2560 + 2 * 512 + 1) + + 2 * (2560 + 2 * 10240 + 320 + 2560) + + 64 + + q8_bytes(4)? + + 4 * 4; + let b = (n - r0).min((bytes / per) & !63); + if b < 64 { + return Ok(None); + } + let widths = [ + b * 10240, + b * 10240, + b * 5120, + b * 40960, + b * 40960, + b * 40960, + b * 40960, + b * 20480, + b * 20480, + b * 1280, + b * 640, + b * 16, + b * 10240, + b * 5120, + b * 2048, + b * 2048, + b * 4, + q8_bytes(b * 4)?, + b * 16, + 16, + ]; + let mut end: usize = 0; + let mut roles = [(0, 0); 20]; + for (i, len) in widths.into_iter().enumerate() { + roles[i] = (end, len); + end = end.checked_add(aligned(len)?).ok_or(Error::InvalidSize)?; + } + if end > bytes { + return Ok(None); + } + base.validate_projection_extent(bytes, 256)?; + Ok(Some(Self { + base, + bytes, + b, + roles, + })) + } + fn handle(&self, i: usize, len: usize) -> Result { + let (offset, extent) = self.roles.get(i).copied().ok_or(Error::InvalidSize)?; + if len == 0 || len > extent { + return Err(Error::InvalidSize); + } + self.base.checked_subspan(self.bytes, offset, len) + } + fn address(&self, i: usize, len: usize) -> Result { + Ok(self.handle(i, len)?.qwen_address()) + } +} +pub struct OriginalMtpPrefill<'ctx> { + context: &'ctx Context<'ctx>, + modules: [Option; 5], + status: Option>, + tmp: Option>, + sms: usize, + shared_limit: u32, + failed: bool, +} +impl<'ctx> Context<'ctx> { + pub fn original_mtp_prefill(&'ctx self) -> Result> { + OriginalMtpPrefill::new(self) + } +} +impl<'ctx> OriginalMtpPrefill<'ctx> { + fn new(context: &'ctx Context<'ctx>) -> Result { + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_prefill_quant.ptx").as_slice(), + include_bytes!("mtp_original_prefill_mmq.ptx").as_slice(), + include_bytes!("mtp_original_prefill_fixup.ptx").as_slice(), + ]; + if assets + .iter() + .any(|a| a.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let mut owner = Self { + context, + modules: std::array::from_fn(|_| None), + status: None, + tmp: None, + sms: 0, + shared_limit: 0, + failed: false, + }; + let result = (|| { + let g = context.enter()?; + let load = (|| { + owner.modules[0] = Some(Mod::load(assets[0], ENTRIES)?); + owner.modules[1] = Some(Mod::load(assets[1], &[c"mtp_prefill_native_embedding"])?); + owner.modules[2] = Some(Mod::load(assets[2], &[c"mtp_prefill_q8"])?); + owner.modules[3] = Some(Mod::load(assets[3], symbols::PROJECT)?); + owner.modules[4] = Some(Mod::load(assets[4], symbols::FIXUP)?); + let (sms, limit) = owner.module(0)?.info()?; + crate::arch_ptx::latch_stream_k_policy(); + owner.sms = sms; + owner.shared_limit = limit; + Ok(()) + })(); + let pop = g.finish(); + if pop.is_err() + || load.as_ref().is_err_and(|e| { + matches!(e, Error::Driver { .. } | Error::InvalidDriverValue(_)) + }) + { + owner.poison(); + } + combine(load, pop)?; + let charge = owner + .sms + .checked_mul(128 * 128 * 4) + .and_then(|n| n.checked_add(FLAG_WORDS * 4)) + .ok_or(Error::BudgetExceeded)?; + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if context + .allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > context.budget_bytes()) + || context.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + owner.status = Some(context.allocate(FLAG_WORDS * 4)?); + owner.tmp = Some(context.allocate(charge - FLAG_WORDS * 4)?); + Ok(()) + })(); + if let Err(e) = result { + return combine(Err(e), owner.close()); + } + Ok(owner) + } + pub fn allocated_bytes(&self) -> usize { + self.status.as_ref().map_or(0, DeviceBuffer::len) + + self.tmp.as_ref().map_or(0, DeviceBuffer::len) + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + fn module(&self, i: usize) -> Result<&Mod> { + self.modules + .get(i) + .and_then(Option::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn status(&self, i: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, i * 4, 4) + } + fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args: Args::new(args)?, + }); + Ok(()) + } + fn finite(&self, cmds: &mut Vec, data: u64, words: usize, stage: usize) -> Result<()> { + Self::kernel( + cmds, + 0, + 8, + [(words.div_ceil(256)) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(data), + A::I32(words as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + ) + } + fn weight( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + b: &DeviceBuffer<'_>, + bytes: usize, + ) -> Result { + if b.bytes != bytes || !std::ptr::eq(b.context, self.context) { + return Err(Error::InvalidProjectionShape); + } + let h = b.handle.ok_or(Error::ContextPoisoned)?; + h.validate_projection_extent(bytes, 2)?; + w.reject_alias(h, bytes)?; + let (region, n) = rows.draft_kv_region()?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + for (a, len) in [ + (region, n), + (r, rn), + ( + self.status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + FLAG_WORDS * 4, + ), + ( + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?, + self.sms * 128 * 128 * 4, + ), + ] { + if h.overlaps(bytes, a, len) { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + #[allow(clippy::too_many_arguments)] + fn project( + &self, + cmds: &mut Vec, + r: &Region, + x: u64, + w: u64, + y: u64, + rows: usize, + out: usize, + bound_slot: usize, + stage: usize, + ) -> Result<()> { + if rows == 0 || rows > r.b * 4 || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + let mut best = None; + let mut ntx = usize::MAX; + for (i, j) in WIDTHS.into_iter().enumerate() { + if ntx <= 1 { + break; + } + let shared = 128 * 76 * 4 + j * 4 + (j * 144).div_ceil(1024) * 1024; + if shared > self.shared_limit as usize { + continue; + } + if rows.div_ceil(j) < ntx { + best = Some((i, j, shared)); + ntx = rows.div_ceil(j); + } + } + let (index, j, shared) = best.ok_or(Error::UnsupportedProjection)?; + let tiles = (out / 128) * ntx; + let efficiency = 100 * tiles / (self.sms * tiles.div_ceil(self.sms)); + let grid = if efficiency >= 90 || crate::arch_ptx::stream_k_off() { tiles } else { self.sms }; + let fix = !tiles.is_multiple_of(grid); + if tiles.checked_mul(80).is_none_or(|n| n >= 1 << 30) { + return Err(Error::InvalidProjectionShape); + } + let xq = r.address(17, q8_bytes(rows)?)?; + let ids = r.address(18, rows * 4)?; + let bound = r + .handle(19, 16)? + .checked_subspan(16, bound_slot * 8, 8)? + .qwen_address(); + Self::kernel( + cmds, + 2, + 0, + [rows as u32, 5, 1], + [128, 1, 1], + 0, + vec![ + A::U64(x), + A::U64(0), + A::U64(xq), + A::I64(2560), + A::I64(2560), + A::I64((rows * 2560) as i64), + A::I64((rows * 2560) as i64), + A::I64(2560), + A::I32(rows as i32), + A::I32(1), + A::I32(1), + ], + )?; + // Original D4 data includes a fixed128-block tail. Initialize that exact + // tail before a literal vendor kernel can speculatively load it. + Self::kernel( + cmds, + 0, + 11, + [72, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq + (rows * 20 * 144) as u64), + A::I32((128 * 144) as i32), + ], + )?; + Self::kernel( + cmds, + 0, + 16, + [(rows * 20).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + A::U64(xq), + A::I32((rows * 20) as i32), + A::U64(self.status(stage)?.qwen_address()), + ], + )?; + let tmp = if fix { + self.tmp + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)? + .qwen_address() + } else { + 0 + }; + let fd = fastdiv; + Self::kernel( + cmds, + 3, + index, + [grid as u32, 1, 1], + [32, 8, 1], + shared as u32, + vec![ + A::U64(w), + A::U64(xq), + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U64(0), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(80), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32((out * 80) as i32), + A::I32(0), + A::I32(0), + A::U3(fd(1)), + A::U3(fd(1)), + A::I32(0), + A::I32(0), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + if fix { + Self::kernel( + cmds, + 4, + index, + [grid as u32, 4, 1], + [32, 4, 1], + 0, + vec![ + A::U64(ids), + A::U64(bound), + A::U64(y), + A::U64(tmp), + A::U3(fd(80)), + A::I32(out as i32), + A::I32(rows as i32), + A::I32(out as i32), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(1)), + A::I32(0), + A::U3(fd(ntx as u32)), + ], + )?; + } + Ok(()) + } + fn run( + &mut self, + rows: &mut OriginalPromptRows<'_, '_, '_>, + w: &mut NativeBatchWorkspace<'ctx>, + mut cmds: Vec, + staging: Vec<(BufferHandle, Vec)>, + ) -> Result<()> { + let mut readback = zero_bytes(FLAG_WORDS * 4)?; + let zero = zero_bytes(FLAG_WORDS * 4)?; + let status = self + .status + .as_ref() + .ok_or(Error::ContextPoisoned)? + .handle + .ok_or(Error::ContextPoisoned)?; + status.validate_projection_extent(FLAG_WORDS * 4, 4)?; + for i in 0..5 { + self.module(i)?; + } + let blas = w.blas()?; + let g = match self.context.enter() { + Ok(g) => g, + Err(e) => { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + return Err(e); + } + }; + let mut operation = self.context.driver.api.copy_from(status, &zero); + if operation.is_ok() { + for (dst, bytes) in &staging { + if let Err(e) = self.context.driver.api.copy_from(*dst, bytes) { + operation = Err(e); + break; + } + } + } + if operation.is_ok() { + operation = self.context.driver.api.synchronize(); + } + if operation.is_ok() { + for c in &mut cmds { + let r = match c { + Cmd::Kernel { + asset, + index, + grid, + block, + shared, + args, + } => self.modules[*asset] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.launch(*index, *grid, *block, *shared, blas.stream(), args) + }), + Cmd::Copy { dst, src, bytes } => self.modules[0] + .as_ref() + .map_or(Err(Error::ContextPoisoned), |m| { + m.copy(*dst, *src, *bytes, blas.stream()) + }), + Cmd::Gemm { + x, + w, + y, + rows, + n, + k, + alpha, + beta, + } => blas.gemm_bf16(*x, *w, *y, *rows, *n, *k, alpha, beta), + }; + if let Err(e) = r { + operation = Err(e); + break; + } + } + } + let stream = blas.synchronize(); + if operation.is_ok() && stream.is_ok() { + operation = self.context.driver.api.copy_to(status, &mut readback); + } + let device = self.context.driver.api.synchronize(); + let pop = g.finish(); + if operation.is_err() || stream.is_err() || device.is_err() || pop.is_err() { + self.poison(); + rows.mark_failed(); + w.mark_failed(); + } + if stream.is_err() || device.is_err() || pop.is_err() { + std::mem::forget((cmds, staging, zero, readback)); + self.context.retain_driver(); + return combine(combine(combine(operation, stream), device), pop); + } + combine(combine(combine(operation, stream), device), pop)?; + for word in readback.chunks_exact(4) { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) > 1 { + self.poison(); + return Err(Error::InvalidDriverValue("draft prefill status")); + } + } + for (stage, word) in readback.chunks_exact(4).enumerate() { + if u32::from_le_bytes(word.try_into().map_err(|_| Error::InvalidSize)?) != 0 { + return Err(Error::NonFiniteMmqOutput(match stage { + 0 => "MTP embedding", + 1 => "MTP embedding norm", + 2 => "MTP FC embedding", + 3 => "MTP hidden norm", + 4 => "MTP FC hidden", + 5 => "MTP broadcast", + 6 => "MTP GR normalized", + 7 => "MTP GR down", + 8 => "MTP GR SiLU", + 9 => "MTP GR up", + 10 => "MTP GR mixed", + 11 => "MTP K", + 12 => "MTP V", + 13 => "MTP K norm", + 14 => "MTP K Rope", + _ => "MTP INT8 encoded", + })); + } + } + Ok(()) + } + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + weights: OriginalMtpPrefillWeights<'_, '_>, + embedding: OriginalMtpEmbedding<'_, '_>, + policy: &DraftKvPolicy, + mut cancelled: impl FnMut() -> bool, + ) -> Result { + if policy.disabled { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Disabled)); + } + if tokens.is_empty() { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::Empty)); + } + if policy.mode != 0 || policy.hybrid || policy.rotated || policy.q4 { + return Ok(DraftKvOutcome::Fallback( + DraftKvFallback::UnsupportedStorage, + )); + } + if policy.alternate_f16 { + return Ok(DraftKvOutcome::Fallback(DraftKvFallback::AlternateF16)); + } + if policy.rope_table_enabled || policy.multimodal_positions { + return Ok(DraftKvOutcome::Fallback( + 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()) + || policy.theta_scale <= 0.0 + || policy.freq_scale <= 0.0 + || policy.mscale <= 0.0 + { + return Err(Error::InvalidProjectionShape); + } + ring.validate_snapshot(prior)?; + workspace.validate_context(self.context)?; + ring.validate_context(self.context)?; + if 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(); + 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)); + }; + 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)); + } + 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 mut wh = [region; 10]; + for i in 0..10 { + wh[i] = self.weight(rows, workspace, weight_refs[i], extents[i]).map_err(|e| { crate::bringup_trace!("DBG prefill.record: weight {i} err {e:?}"); e })?; + } + crate::bringup_trace!("DBG prefill.record: 10 weights staged"); + let eh = self.weight(rows, workspace, embedding.table, embedding.table.bytes).map_err(|e| { crate::bringup_trace!("DBG prefill.record: embedding table err {e:?}"); 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) { + let ah = a.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref a.handle is None (i={i})"); Error::ContextPoisoned })?; + let bh = b.handle.ok_or_else(|| { crate::bringup_trace!("DBG prefill.record: weight_ref b.handle is None (i={i})"); Error::ContextPoisoned })?; + if ah.overlaps(a.bytes, bh, b.bytes) + && !(ah.qwen_address() == bh.qwen_address() && a.bytes == b.bytes) + { + return Err(Error::OutputAliasesInput); + } + } + } + for b in weight_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) + { + return Err(Error::OutputAliasesInput); + } + } + // Actual input residual lies outside the region being overwritten. + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R).map_err(|e| { crate::bringup_trace!("DBG prefill.record: common_span(R) err {e:?}"); e })?; + crate::bringup_trace!("DBG prefill.record: weights vs embedding overlap ok, R span ok"); + 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); + } + } + 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; + let page_count = end.div_ceil(4); + let mut pages = Vec::new(); + pages + .try_reserve_exact(page_count) + .map_err(|_| Error::HostAllocation)?; + let mut changed = Vec::new(); + changed + .try_reserve_exact(page_count - first_page) + .map_err(|_| Error::HostAllocation)?; + for p in 0..page_count { + if p < first_page { + if let Some(page) = prior.0.pages.get(p) { + pages.push(page.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); + } + } + if cancelled() { + return Ok(DraftKvOutcome::Cancelled); + } + // Genuine idle dependency before this stream can mutate the real drafter KV. + 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:?}"); e })?; // genuine global + shared drafter stream idle, even identical snapshot + ring.restore(workspace, prior).map_err(|e| { crate::bringup_trace!("DBG prefill.record: ring.restore err {e:?}"); e })?; + 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); + } + } + 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); + 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: Rc::new(pages.into_boxed_slice()), + 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, + })) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut first = Ok(()); + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + first = combine(first, r); + } + } + for b in [&mut self.status, &mut self.tmp] { + if let Some(b) = b.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + b.release() + }; + first = combine(first, r); + } + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + first + } +} +impl Drop for OriginalMtpPrefill<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +#[path = "mtp_original_scalar_prefill.rs"] +mod scalar; +pub use scalar::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, OriginalMtpGrVariant, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpRetainedScalarWeights, + OriginalMtpScalarPolicy, OriginalMtpScalarPrefill, OriginalMtpStepOutput, +}; +pub(crate) use scalar::session_assets_sealed; diff --git a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs index d2431b61..8d2856b7 100644 --- a/crates/cuda-driver/src/mtp_original_scalar_prefill.rs +++ b/crates/cuda-driver/src/mtp_original_scalar_prefill.rs @@ -1,1480 +1,1481 @@ -//! Literal MtpDrafter::record_forward(full=false), groups <= actual max_t. -//! Private child of Original prefill. K/V, Q8 scratch and mapped host are the -//! actual MtpOriginalInt8 owner; no half-cache or batch-GEMM substitution. -use super::*; -#[allow(unsafe_code)] -#[path = "mtp_original_scalar_ffi.rs"] -mod scalar_abi; -use crate::{ - OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, - OriginalStreamKind, -}; -use scalar_abi::{Arg, Arguments, Module}; -#[path = "mtp_original_scalar_weights.rs"] -mod retained_weights; -pub use retained_weights::OriginalMtpRetainedScalarWeights; -#[allow(unsafe_code)] -#[path = "mtp_original_scalar_mapped.rs"] -mod mapped_records; -use std::cell::RefCell; -#[allow(unsafe_code)] -#[path = "mtp_original_physical_layout.rs"] -mod physical_layout; -struct OriginalLayoutSetup<'ctx> { - layout: physical_layout::Layout, - bank: Rc>, - mapped: Rc>, -} -struct GraphResources<'ctx> { - context: &'ctx Context<'ctx>, - modules: [Rc; 6], - scratch: Rc>, - records: Rc>, - status: Rc>, - mapped: Rc>>, - ring: MtpOriginalRingResources<'ctx>, - weights: Rc>, - commands: Vec, -} -impl crate::original_gpu_schedule::resources::Sealed for GraphResources<'_> {} -impl OriginalGraphResources for GraphResources<'_> { - fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.ring.validate_context(c)?; - self.weights.validate_context(c)?; - for b in [&self.scratch, &self.records, &self.status] { - checked(c, b, b.bytes)?; - } - if self - .mapped - .try_borrow() - .map_err(|_| Error::InvalidQwenShape)? - .is_none() - { - return Err(Error::ContextPoisoned); - } - Ok(()) - } -} - -const MAX_PROMPT: usize = 8192; -const SCALAR_FLAGS: usize = 16; -const GR_ENTRIES: &[&CStr] = &[ - c"mtp_scalar_gr_norm", - c"mtp_scalar_gr_split", - c"mtp_scalar_gr_staged", - c"mtp_scalar_gr_up", - c"mtp_scalar_gr_down1280", - c"mtp_scalar_gr_down2560", -]; -#[derive(Clone, Copy, PartialEq, Eq)] -pub enum OriginalMtpGrVariant { - Plain, - Split, - Staged, -} -/// Actual Original policy result, not an attestation about inputs/weights. -/// GR_V3 is deliberately a separate producer, not substituted here. -pub struct OriginalMtpScalarPolicy { - pub gr: OriginalMtpGrVariant, - pub per_group_sync: bool, - pub kv: DraftKvPolicy, -} -pub struct OriginalMtpScalarWeights<'a, 'ctx> { - pub input: OriginalMtpPrefillWeights<'a, 'ctx>, - pub gr_inject: &'a DeviceBuffer<'ctx>, -} -// Actual first twelve Original input/read roles plus token,step,position. One -// whole physical owner, each closed range derives from this exact carve. -struct Scratch { - sizes: [usize; 16], - offsets: [usize; 16], - bytes: usize, -} -impl Scratch { - fn new(t: usize) -> Result { - if !(1..=8).contains(&t) { - return Err(Error::InvalidQwenShape); - } - let sizes = [ - t * 40960, - t * 40960, - t * 10240, - t * 10240, - t * 10240, - t * 40960, - t * 40960, - t * 40960, - t * 1280, - t * 16, - t * 16, - t * 10240, - t * 4, - t * 16, - t * 96, - 8 * 80 * 36, - ]; - let mut offsets = [0; 16]; - let mut bytes = 0usize; - for (i, n) in sizes.into_iter().enumerate() { - offsets[i] = bytes; - bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; - } - Ok(Self { - sizes, - offsets, - bytes, - }) - } -} - -#[path = "mtp_original_full_forward.rs"] -mod full_forward; -pub use full_forward::{ - CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, - OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, - OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, -}; -pub(crate) use full_forward::session_assets_sealed; -enum ScalarCommand { - Kernel { - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Arguments, - }, - Copy { - dst: u64, - src: u64, - bytes: usize, - }, -} -/// Real affine scalar producer. Cached Original capture must retain this owner -/// AND genuine model-lifetime whole weights (see the explicit graph handoff). -pub struct OriginalMtpScalarPrefill<'ctx> { - context: &'ctx Context<'ctx>, - max_t: usize, - prompt_cap: usize, - modules: [Option>; 6], - scratch: Option>>, - records: Option>>, - status: Option>>, - layout: Scratch, - original_layout: Option, - shared_limit: usize, - plain_tile: usize, - stream: Option>, - failed: bool, - graphs: Option>>, - mapped: Rc>>, - retained: Option>>, - ring_id: Option, - policy_key: Option<[u32; 9]>, - pending_host: Vec>, - graph_metadata_bytes: usize, - has_pending: bool, -} -impl<'ctx> Context<'ctx> { - pub fn original_mtp_scalar_prefill( - &'ctx self, - max_t: usize, - prompt_cap: usize, - ) -> Result> { - OriginalMtpScalarPrefill::new(self, max_t, prompt_cap) - } -} -impl<'ctx> OriginalMtpScalarPrefill<'ctx> { - fn assets_ready() -> Result<()> { - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - Err(Error::UnsupportedQwenOperation) - } else { - Ok(()) - } - } - pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { - if !(1..=MAX_PROMPT).contains(&prompt_cap) { - return Err(Error::InvalidQwenShape); - } - Scratch::new(max_t)? - .bytes - .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) - .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) - .ok_or(Error::InvalidSize) - } - pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { - Self::planned_device_bytes(max_t, prompt_cap)?; - let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; - // New per-call immutable host snapshot may include absent pruned-prefix pages; - // charge its real worst-case payload+catalog separately from the existing - // physical mapped ring. Cached graph metadata is bounded per actual T/key. - let snapshot = MTP_ORIGINAL_MAX_CELLS - .div_ceil(4) - .checked_mul(4224 + 128) - .ok_or(Error::BudgetExceeded)?; - (2 * max_t) - .checked_mul(512 * 1024) - .and_then(|n| { - n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) - }) - .and_then(|n| n.checked_add(snapshot)) - .ok_or(Error::BudgetExceeded) - } - pub fn host_metadata_bytes(&self) -> usize { - self.graphs - .as_ref() - .map_or(0, OriginalGraphRegistry::metadata_bytes) - + self.graph_metadata_bytes - + std::mem::size_of::() - + self.pending_host.capacity() * std::mem::size_of::>() - } - pub fn pinned_host_bytes(&self) -> usize { - if self.original_layout.is_some() { - self.max_t * 236 + 384 - } else { - self.max_t * 29 * 4 - } - } - fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { - Self::new_internal(c, max_t, prompt_cap, None) - } - fn new_internal( - c: &'ctx Context<'ctx>, - max_t: usize, - prompt_cap: usize, - exact: Option>, - ) -> Result { - let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; - let charge = if exact.is_some() { - legacy_charge - .checked_sub(Scratch::new(max_t)?.bytes) - .ok_or(Error::InvalidSize)? - } else { - legacy_charge - }; - if let Some(e) = &exact { - if e.layout.t != max_t { - return Err(Error::InvalidQwenShape); - } - checked(c, &e.bank, e.layout.bytes)?; - } - let assets = [ - include_bytes!("mtp_original_prefill.ptx").as_slice(), - include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), - include_bytes!("mtp_original_tail.ptx").as_slice(), - include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), - include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), - include_bytes!("mtp_original_kv.ptx").as_slice(), - ]; - if assets - .iter() - .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) - { - return Err(Error::UnsupportedQwenOperation); - } - let required = charge - .checked_add(RESERVE_BYTES) - .ok_or(Error::BudgetExceeded)?; - if c.is_poisoned() || c.handle.is_none() { - return Err(Error::ContextPoisoned); - } - if c.allocated_bytes() - .checked_add(required) - .is_none_or(|n| n > c.budget_bytes()) - || c.memory_info()?.0 < required - { - return Err(Error::BudgetExceeded); - } - let mut o = Self { - context: c, - max_t, - prompt_cap, - modules: std::array::from_fn(|_| None), - scratch: None, - records: None, - status: None, - layout: match &exact { - Some(e) => e.layout.scalar(), - None => Scratch::new(max_t)?, - }, - original_layout: exact.as_ref().map(|e| e.layout.clone()), - shared_limit: 0, - plain_tile: 0, - stream: None, - failed: false, - graphs: None, - mapped: Rc::new(RefCell::new(None)), - retained: None, - ring_id: None, - policy_key: None, - pending_host: Vec::new(), - graph_metadata_bytes: 0, - has_pending: false, - }; - let operation = (|| { - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let load = (|| { - o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); - o.modules[1] = Some(Rc::new(Module::load( - assets[1], - &[c"mtp_prefill_native_embedding"], - )?)); - o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); - o.modules[3] = Some(Rc::new(Module::load( - assets[3], - &[ - c"mtp_scalar_norm1024", - c"mtp_scalar_rope", - c"mtp_scalar_copy_i32", - c"mtp_scalar_encoded", - ], - )?)); - o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); - o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); - let (shared, tile) = o.module(4)?.configure_gr()?; - o.shared_limit = shared; - o.plain_tile = tile; - Ok(()) - })(); - let pop = g.finish(); - if load.is_err() || pop.is_err() { - o.poison(); - } - combine(load, pop)?; - o.scratch = Some(match &exact { - Some(e) => Rc::clone(&e.bank), - None => Rc::new(c.allocate(o.layout.bytes)?), - }); - o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); - o.status = Some(Rc::new( - c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, - )); - o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); - let g = c.enter().inspect_err(|_| { - c.poison(); - c.retain_driver(); - })?; - let allocation = match &exact { - Some(e) => Ok(mapped_records::MappedOwner::original( - max_t, - Rc::clone(&e.mapped), - )), - None => mapped_records::MappedOwner::new(max_t), - }; - let pop = g.finish(); - if pop.is_err() { - o.poison(); - let original = match allocation { - Ok(owner) => { - std::mem::forget(owner); - Ok(()) - } - Err(e) => Err(e), - }; - return combine(original, pop); - } - if allocation.is_err() { - o.poison(); - } - *o.mapped.borrow_mut() = Some(allocation?); - o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); - o.pending_host - .try_reserve_exact(2) - .map_err(|_| Error::HostAllocation)?; - if c.memory_info()?.0 < RESERVE_BYTES { - return Err(Error::BudgetExceeded); - } - Ok(()) - })(); - if let Err(e) = operation { - return combine(Err(e), o.close()); - } - Ok(o) - } - pub fn allocated_bytes(&self) -> usize { - [&self.scratch, &self.records, &self.status] - .into_iter() - .map(|s| s.as_ref().map_or(0, |b| b.len())) - .sum() - } - pub fn is_failed(&self) -> bool { - self.failed || self.context.is_poisoned() - } - pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { - if !std::ptr::eq(c, self.context) { - return Err(Error::ContextMismatch); - } - self.validate() - } - fn validate(&self) -> Result<()> { - if self.is_failed() - || self.modules.iter().any(Option::is_none) - || self - .stream - .as_ref() - .is_none_or(OriginalGpuStream::is_failed) - { - return Err(Error::ContextPoisoned); - } - for (b, n) in [ - (&self.scratch, self.layout.bytes), - (&self.records, self.prompt_cap * 29 * 4), - ( - &self.status, - (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, - ), - ] { - let b = b.as_ref().ok_or(Error::ContextPoisoned)?; - checked(self.context, b, n)?; - } - Ok(()) - } - fn poison(&mut self) { - self.failed = true; - self.context.poison(); - self.context.retain_driver(); - } - fn module(&self, i: usize) -> Result<&Module> { - self.modules - .get(i) - .and_then(Option::as_ref) - .map(Rc::as_ref) - .ok_or(Error::ContextPoisoned) - } - fn scratch(&self, i: usize, n: usize) -> Result { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - if n == 0 || n > self.layout.sizes[i] { - return Err(Error::InvalidSize); - } - b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, self.layout.offsets[i], n) - } - fn address(&self, i: usize, n: usize) -> Result { - Ok(self.scratch(i, n)?.qwen_address()) - } - fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { - match &self.original_layout { - Some(l) => { - let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; - Ok(( - l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), - l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), - )) - } - None => Ok((ring.address(6)?, ring.address(7)?)), - } - } - fn flag(&self, group: usize, stage: usize) -> Result { - let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; - if stage >= SCALAR_FLAGS { - return Err(Error::InvalidSize); - } - Ok(b.handle - .ok_or(Error::ContextPoisoned)? - .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? - .qwen_address()) - } - #[allow(clippy::too_many_arguments)] - fn kernel( - cmds: &mut Vec, - asset: usize, - index: usize, - grid: [u32; 3], - block: [u32; 3], - shared: u32, - args: Vec, - ) -> Result<()> { - cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; - cmds.push(ScalarCommand::Kernel { - asset, - index, - grid, - block, - shared, - args: Arguments::new(args)?, - }); - Ok(()) - } - fn finite( - &self, - cmds: &mut Vec, - data: u64, - n: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 11, - [n.div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(data), - Arg::I32(n as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - fn q8_guard( - &self, - cmds: &mut Vec, - q: u64, - rows: usize, - _g: usize, - s: usize, - ) -> Result<()> { - Self::kernel( - cmds, - 2, - 12, - [(rows * 80).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![ - Arg::U64(q), - Arg::I32((rows * 80) as i32), - Arg::U64(self.flag(0, s)?), - ], - ) - } - fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { - Self::kernel( - cmds, - 2, - 0, - [(rows * 2560).div_ceil(256) as u32, 1, 1], - [256, 1, 1], - 0, - vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], - ) - } - fn project( - cmds: &mut Vec, - w: u64, - q: u64, - y: u64, - rows: usize, - out: usize, - ) -> Result<()> { - if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { - return Err(Error::InvalidProjectionShape); - } - Self::kernel( - cmds, - 2, - rows, - [out as u32, 1, 1], - [32, 4, 1], - 0, - vec![ - Arg::U64(w), - Arg::U64(q), - Arg::U64(y), - Arg::I32(2560), - Arg::I32(out as i32), - ], - ) - } - fn external( - &self, - rows: &OriginalPromptRows<'_, '_, '_>, - w: &NativeBatchWorkspace<'_>, - ring: &MtpOriginalInt8<'_>, - b: &DeviceBuffer<'_>, - n: usize, - ) -> Result { - checked(self.context, b, n)?; - let h = b.handle.ok_or(Error::ContextPoisoned)?; - w.reject_alias(h, n)?; - let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; - if h.overlaps(n, r, rn) { - return Err(Error::OutputAliasesInput); - } - for own in [&self.scratch, &self.records, &self.status] - .into_iter() - .flatten() - { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - for own in ring.buffers()?.iter().flatten() { - if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { - return Err(Error::OutputAliasesInput); - } - } - ring.reject_state_alias(b)?; - if !ring.fully_resident()? { - let mapped = ring.mapped()?; - let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; - if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 - && host < h.qwen_address() + n as u64 - { - return Err(Error::OutputAliasesInput); - } - } - Ok(h) - } - // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). - #[allow(clippy::too_many_arguments)] - fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { - let mut words = Box::new([0u64; 114]); - for i in 0..t { - let row = start + i; - let a = &mut words[i * 14..i * 14 + 14]; - a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; - a[1] = a[0]; - a[2] = 0; // apply=false, exact null previous writers - a[5] = wh[4].qwen_address(); - a[6] = wh[5].qwen_address(); - a[7] = wh[6].qwen_address(); - a[8] = wh[10].qwen_address(); - a[9] = u64::from(1e-6f32.to_bits()); - a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; - a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; - a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; - a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; - } - words[112] = xn; - words[113] = t as u64; - Ok(Arg::GrMulti(words)) - } - fn gr( - &self, - cmds: &mut Vec, - t: usize, - wh: &[BufferHandle; 11], - policy: &OriginalMtpScalarPolicy, - ) -> Result<()> { - let xn = self.address(7, t * 40960)?; - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Plain { - 0 - } else { - 1 - }, - [ - t as u32, - if policy.gr == OriginalMtpGrVariant::Plain { - 1 - } else { - 4 - }, - 1, - ], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - )?; - let per_token = if policy.gr == OriginalMtpGrVariant::Staged { - 2 * 1280 * 4 - } else { - self.plain_tile * 4 - }; - let capacity = (self.shared_limit / per_token).clamp(1, 8); - for c in (0..t).step_by(capacity) { - let ct = capacity.min(t - c); - Self::kernel( - cmds, - 4, - if policy.gr == OriginalMtpGrVariant::Staged { - 2 - } else if self.plain_tile == 1280 { - 4 - } else { - 5 - }, - [41, 1, 1], - [256, 1, 1], - (ct * per_token) as u32, - vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], - )?; - } - Self::kernel( - cmds, - 4, - 3, - [160, 1, 1], - [256, 1, 1], - 0, - vec![self.gr_args(0, t, wh, xn)?], - ) - } - #[allow(clippy::too_many_arguments)] - pub fn record<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - policy: &OriginalMtpScalarPolicy, - cancelled: impl FnMut() -> bool, - ) -> Result { - let result = self.record_impl( - residual, - workspace, - ring, - prior, - tokens, - cell0, - first_needed, - retained, - policy, - cancelled, - ); - if self.has_pending { - let drained = self.drain_graphs(residual.lease_mut(), workspace); - return combine(result, drained); - } - result - } - /// Literal cached device-input or mapped-input per-T graph scheduling. - /// Unsupported storage/math branches return explicit fallback, never completion. - #[allow(clippy::too_many_arguments)] - fn record_impl<'arena, 'loan>( - &mut self, - residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, - workspace: &mut NativeBatchWorkspace<'ctx>, - ring: &mut MtpOriginalInt8<'ctx>, - prior: &MtpInt8Snapshot, - tokens: &[i32], - cell0: usize, - first_needed: usize, - retained: Rc>, - 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 (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 { - return Ok(DraftKvOutcome::Skipped); - }; - let first = cell0 + first_group; - let end = cell0 + tokens.len(); - let rows = residual.lease_mut(); - let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; - 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); - } - } - 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); - } - } - } - let wr = [ - weights.input.embedding_norm, - weights.input.embedding_fc, - weights.input.hidden_norm, - weights.input.hidden_fc, - weights.input.gr_norm, - weights.input.gr_down, - weights.input.gr_up, - weights.input.key, - weights.input.value, - 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])?; - } - let eh = self.external( - rows, - workspace, - ring, - embedding.table, - embedding.table.bytes, - )?; - for i in 0..wr.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]) - { - return Err(Error::OutputAliasesInput); - } - } - } - let key = [ - policy.gr as u32, - policy.per_group_sync as u32, - kv.theta_scale.to_bits(), - kv.freq_scale.to_bits(), - kv.corr_low.to_bits(), - kv.corr_high.to_bits(), - kv.ext_factor.to_bits(), - kv.mscale.to_bits(), - 0, - ]; - 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) - { - return Err(Error::InvalidProjectionShape); - } - 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: Rc::new(pages.into_boxed_slice()), - end, - })); - ring.current = Some(snapshot.clone()); - ring.generation = generation; - Ok(DraftKvOutcome::Completed(CompletedDraftKv { - snapshot, - first_materialized: first, - end, - generation, - })) - } - pub fn close(mut self) -> Result<()> { - self.close_inner() - } - fn close_inner(&mut self) -> Result<()> { - self.failed = true; - let mut primary = Ok(()); - if let Some(graphs) = self.graphs.take() { - primary = combine(primary, graphs.close()); - } - if let Some(stream) = self.stream.take() { - let r = stream.close(); - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - for module in &mut self.modules { - if let Some(m) = module.take() { - let r = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine( - Rc::try_unwrap(m) - .map_err(|_| Error::InvalidQwenShape) - .and_then(Module::close), - g.finish(), - ), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if r.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, r); - } - } - for b in [&mut self.scratch, &mut self.records, &mut self.status] { - if let Some(b) = b.take() { - primary = combine( - primary, - if self.context.is_poisoned() { - std::mem::forget(b); - Err(Error::ContextPoisoned) - } else { - match Rc::try_unwrap(b) { - Ok(b) => b.release(), - Err(b) => { - if self.original_layout.is_some() { - drop(b); - Ok(()) - } else { - Err(Error::InvalidQwenShape) - } - } - } - }, - ); - } - } - if let Some(mut m) = self.mapped.borrow_mut().take() { - let result = if self.context.is_poisoned() { - std::mem::forget(m); - Err(Error::ContextPoisoned) - } else { - match self.context.enter() { - Ok(g) => combine(m.close(), g.finish()), - Err(e) => { - self.context.poison(); - std::mem::forget(m); - Err(e) - } - } - }; - if result.is_err() { - self.context.poison(); - self.context.retain_driver(); - } - primary = combine(primary, result); - } - self.retained = None; - if self.context.is_poisoned() { - std::mem::forget(std::mem::take(&mut self.pending_host)); - } else { - self.pending_host.clear(); - } - if self.context.is_poisoned() { - self.context.retain_driver(); - } - primary - } -} -impl Drop for OriginalMtpScalarPrefill<'_> { - fn drop(&mut self) { - let _ = self.close_inner(); - } -} - -#[path = "mtp_original_scalar_graph.rs"] -mod graph; - -#[cfg(test)] -#[path = "mtp_original_scalar_short_gpu.rs"] -mod short_prompt_gpu; +//! Literal MtpDrafter::record_forward(full=false), groups <= actual max_t. +//! Private child of Original prefill. K/V, Q8 scratch and mapped host are the +//! actual MtpOriginalInt8 owner; no half-cache or batch-GEMM substitution. +use super::*; +#[allow(unsafe_code)] +#[path = "mtp_original_scalar_ffi.rs"] +mod scalar_abi; +use crate::{ + OriginalGpuStream, OriginalGraphKey, OriginalGraphRegistry, OriginalGraphResources, + OriginalStreamKind, +}; +use scalar_abi::{Arg, Arguments, Module}; +#[path = "mtp_original_scalar_weights.rs"] +mod retained_weights; +pub use retained_weights::OriginalMtpRetainedScalarWeights; +#[allow(unsafe_code)] +#[path = "mtp_original_scalar_mapped.rs"] +mod mapped_records; +use std::cell::RefCell; +#[allow(unsafe_code)] +#[path = "mtp_original_physical_layout.rs"] +mod physical_layout; +struct OriginalLayoutSetup<'ctx> { + layout: physical_layout::Layout, + bank: Rc>, + mapped: Rc>, +} +struct GraphResources<'ctx> { + context: &'ctx Context<'ctx>, + modules: [Rc; 6], + scratch: Rc>, + records: Rc>, + status: Rc>, + mapped: Rc>>, + ring: MtpOriginalRingResources<'ctx>, + weights: Rc>, + commands: Vec, +} +impl crate::original_gpu_schedule::resources::Sealed for GraphResources<'_> {} +impl OriginalGraphResources for GraphResources<'_> { + fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.ring.validate_context(c)?; + self.weights.validate_context(c)?; + for b in [&self.scratch, &self.records, &self.status] { + checked(c, b, b.bytes)?; + } + if self + .mapped + .try_borrow() + .map_err(|_| Error::InvalidQwenShape)? + .is_none() + { + return Err(Error::ContextPoisoned); + } + Ok(()) + } +} + +const MAX_PROMPT: usize = 8192; +const SCALAR_FLAGS: usize = 16; +const GR_ENTRIES: &[&CStr] = &[ + c"mtp_scalar_gr_norm", + c"mtp_scalar_gr_split", + c"mtp_scalar_gr_staged", + c"mtp_scalar_gr_up", + c"mtp_scalar_gr_down1280", + c"mtp_scalar_gr_down2560", +]; +#[derive(Clone, Copy, PartialEq, Eq)] +pub enum OriginalMtpGrVariant { + Plain, + Split, + Staged, +} +/// Actual Original policy result, not an attestation about inputs/weights. +/// GR_V3 is deliberately a separate producer, not substituted here. +pub struct OriginalMtpScalarPolicy { + pub gr: OriginalMtpGrVariant, + pub per_group_sync: bool, + pub kv: DraftKvPolicy, +} +pub struct OriginalMtpScalarWeights<'a, 'ctx> { + pub input: OriginalMtpPrefillWeights<'a, 'ctx>, + pub gr_inject: &'a DeviceBuffer<'ctx>, +} +// Actual first twelve Original input/read roles plus token,step,position. One +// whole physical owner, each closed range derives from this exact carve. +struct Scratch { + sizes: [usize; 16], + offsets: [usize; 16], + bytes: usize, +} +impl Scratch { + fn new(t: usize) -> Result { + if !(1..=8).contains(&t) { + return Err(Error::InvalidQwenShape); + } + let sizes = [ + t * 40960, + t * 40960, + t * 10240, + t * 10240, + t * 10240, + t * 40960, + t * 40960, + t * 40960, + t * 1280, + t * 16, + t * 16, + t * 10240, + t * 4, + t * 16, + t * 96, + 8 * 80 * 36, + ]; + let mut offsets = [0; 16]; + let mut bytes = 0usize; + for (i, n) in sizes.into_iter().enumerate() { + offsets[i] = bytes; + bytes = bytes.checked_add(aligned(n)?).ok_or(Error::InvalidSize)?; + } + Ok(Self { + sizes, + offsets, + bytes, + }) + } +} + +#[path = "mtp_original_full_forward.rs"] +mod full_forward; +pub use full_forward::{ + CompletedOriginalMtpDraft, OriginalMtpDraftProgram, OriginalMtpDrafter, + OriginalMtpForwardProgram, OriginalMtpFullForward, OriginalMtpFullPolicy, + OriginalMtpRetainedFullWeights, OriginalMtpRetainedPrefix, OriginalMtpStepOutput, +}; +pub(crate) use full_forward::session_assets_sealed; +enum ScalarCommand { + Kernel { + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Arguments, + }, + Copy { + dst: u64, + src: u64, + bytes: usize, + }, +} +/// Real affine scalar producer. Cached Original capture must retain this owner +/// AND genuine model-lifetime whole weights (see the explicit graph handoff). +pub struct OriginalMtpScalarPrefill<'ctx> { + context: &'ctx Context<'ctx>, + max_t: usize, + prompt_cap: usize, + modules: [Option>; 6], + scratch: Option>>, + records: Option>>, + status: Option>>, + layout: Scratch, + original_layout: Option, + shared_limit: usize, + plain_tile: usize, + stream: Option>, + failed: bool, + graphs: Option>>, + mapped: Rc>>, + retained: Option>>, + ring_id: Option, + policy_key: Option<[u32; 9]>, + pending_host: Vec>, + graph_metadata_bytes: usize, + has_pending: bool, +} +impl<'ctx> Context<'ctx> { + pub fn original_mtp_scalar_prefill( + &'ctx self, + max_t: usize, + prompt_cap: usize, + ) -> Result> { + OriginalMtpScalarPrefill::new(self, max_t, prompt_cap) + } +} +impl<'ctx> OriginalMtpScalarPrefill<'ctx> { + fn assets_ready() -> Result<()> { + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + Err(Error::UnsupportedQwenOperation) + } else { + Ok(()) + } + } + pub fn planned_device_bytes(max_t: usize, prompt_cap: usize) -> Result { + if !(1..=MAX_PROMPT).contains(&prompt_cap) { + return Err(Error::InvalidQwenShape); + } + Scratch::new(max_t)? + .bytes + .checked_add(prompt_cap.checked_mul(29 * 4).ok_or(Error::InvalidSize)?) + .and_then(|n| n.checked_add((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)) + .ok_or(Error::InvalidSize) + } + pub fn planned_host_bytes(max_t: usize, prompt_cap: usize) -> Result { + Self::planned_device_bytes(max_t, prompt_cap)?; + let timeline = (prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4; + // New per-call immutable host snapshot may include absent pruned-prefix pages; + // charge its real worst-case payload+catalog separately from the existing + // physical mapped ring. Cached graph metadata is bounded per actual T/key. + let snapshot = MTP_ORIGINAL_MAX_CELLS + .div_ceil(4) + .checked_mul(4224 + 128) + .ok_or(Error::BudgetExceeded)?; + (2 * max_t) + .checked_mul(512 * 1024) + .and_then(|n| { + n.checked_add(prompt_cap * 29 * 4 + max_t * 29 * 4 + 2 * timeline + 64 * 1024) + }) + .and_then(|n| n.checked_add(snapshot)) + .ok_or(Error::BudgetExceeded) + } + pub fn host_metadata_bytes(&self) -> usize { + self.graphs + .as_ref() + .map_or(0, OriginalGraphRegistry::metadata_bytes) + + self.graph_metadata_bytes + + std::mem::size_of::() + + self.pending_host.capacity() * std::mem::size_of::>() + } + pub fn pinned_host_bytes(&self) -> usize { + if self.original_layout.is_some() { + self.max_t * 236 + 384 + } else { + self.max_t * 29 * 4 + } + } + fn new(c: &'ctx Context<'ctx>, max_t: usize, prompt_cap: usize) -> Result { + Self::new_internal(c, max_t, prompt_cap, None) + } + fn new_internal( + c: &'ctx Context<'ctx>, + max_t: usize, + prompt_cap: usize, + exact: Option>, + ) -> Result { + let legacy_charge = Self::planned_device_bytes(max_t, prompt_cap)?; + let charge = if exact.is_some() { + legacy_charge + .checked_sub(Scratch::new(max_t)?.bytes) + .ok_or(Error::InvalidSize)? + } else { + legacy_charge + }; + if let Some(e) = &exact { + if e.layout.t != max_t { + return Err(Error::InvalidQwenShape); + } + checked(c, &e.bank, e.layout.bytes)?; + } + let assets = [ + include_bytes!("mtp_original_prefill.ptx").as_slice(), + include_bytes!("mtp_original_prefill_embedding.ptx").as_slice(), + include_bytes!("mtp_original_tail.ptx").as_slice(), + include_bytes!("mtp_original_scalar_norm.ptx").as_slice(), + include_bytes!("mtp_original_scalar_gr.ptx").as_slice(), + include_bytes!("mtp_original_kv.ptx").as_slice(), + ]; + if assets + .iter() + .any(|p| p.windows(8).any(|w| w == b"UNSEALED")) + { + return Err(Error::UnsupportedQwenOperation); + } + let required = charge + .checked_add(RESERVE_BYTES) + .ok_or(Error::BudgetExceeded)?; + if c.is_poisoned() || c.handle.is_none() { + return Err(Error::ContextPoisoned); + } + if c.allocated_bytes() + .checked_add(required) + .is_none_or(|n| n > c.budget_bytes()) + || c.memory_info()?.0 < required + { + return Err(Error::BudgetExceeded); + } + let mut o = Self { + context: c, + max_t, + prompt_cap, + modules: std::array::from_fn(|_| None), + scratch: None, + records: None, + status: None, + layout: match &exact { + Some(e) => e.layout.scalar(), + None => Scratch::new(max_t)?, + }, + original_layout: exact.as_ref().map(|e| e.layout.clone()), + shared_limit: 0, + plain_tile: 0, + stream: None, + failed: false, + graphs: None, + mapped: Rc::new(RefCell::new(None)), + retained: None, + ring_id: None, + policy_key: None, + pending_host: Vec::new(), + graph_metadata_bytes: 0, + has_pending: false, + }; + let operation = (|| { + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let load = (|| { + o.modules[0] = Some(Rc::new(Module::load(assets[0], ENTRIES)?)); + o.modules[1] = Some(Rc::new(Module::load( + assets[1], + &[c"mtp_prefill_native_embedding"], + )?)); + o.modules[2] = Some(Rc::new(Module::load(assets[2], TAIL_ENTRIES)?)); + o.modules[3] = Some(Rc::new(Module::load( + assets[3], + &[ + c"mtp_scalar_norm1024", + c"mtp_scalar_rope", + c"mtp_scalar_copy_i32", + c"mtp_scalar_encoded", + ], + )?)); + o.modules[4] = Some(Rc::new(Module::load(assets[4], GR_ENTRIES)?)); + o.modules[5] = Some(Rc::new(Module::load(assets[5], KV_ENTRIES)?)); + let (shared, tile) = o.module(4)?.configure_gr()?; + o.shared_limit = shared; + o.plain_tile = tile; + Ok(()) + })(); + let pop = g.finish(); + if load.is_err() || pop.is_err() { + o.poison(); + } + combine(load, pop)?; + o.scratch = Some(match &exact { + Some(e) => Rc::clone(&e.bank), + None => Rc::new(c.allocate(o.layout.bytes)?), + }); + o.records = Some(Rc::new(c.allocate(prompt_cap * 29 * 4)?)); + o.status = Some(Rc::new( + c.allocate((prompt_cap.div_ceil(max_t) + 1) * SCALAR_FLAGS * 4)?, + )); + o.stream = Some(c.original_gpu_stream(OriginalStreamKind::NonBlocking)?); + let g = c.enter().inspect_err(|_| { + c.poison(); + c.retain_driver(); + })?; + let allocation = match &exact { + Some(e) => Ok(mapped_records::MappedOwner::original( + max_t, + Rc::clone(&e.mapped), + )), + None => mapped_records::MappedOwner::new(max_t), + }; + let pop = g.finish(); + if pop.is_err() { + o.poison(); + let original = match allocation { + Ok(owner) => { + std::mem::forget(owner); + Ok(()) + } + Err(e) => Err(e), + }; + return combine(original, pop); + } + if allocation.is_err() { + o.poison(); + } + *o.mapped.borrow_mut() = Some(allocation?); + o.graphs = Some(OriginalGraphRegistry::new(c, 2 * max_t)?); + o.pending_host + .try_reserve_exact(2) + .map_err(|_| Error::HostAllocation)?; + if c.memory_info()?.0 < RESERVE_BYTES { + return Err(Error::BudgetExceeded); + } + Ok(()) + })(); + if let Err(e) = operation { + return combine(Err(e), o.close()); + } + Ok(o) + } + pub fn allocated_bytes(&self) -> usize { + [&self.scratch, &self.records, &self.status] + .into_iter() + .map(|s| s.as_ref().map_or(0, |b| b.len())) + .sum() + } + pub fn is_failed(&self) -> bool { + self.failed || self.context.is_poisoned() + } + pub fn validate_context(&self, c: &Context<'_>) -> Result<()> { + if !std::ptr::eq(c, self.context) { + return Err(Error::ContextMismatch); + } + self.validate() + } + fn validate(&self) -> Result<()> { + if self.is_failed() + || self.modules.iter().any(Option::is_none) + || self + .stream + .as_ref() + .is_none_or(OriginalGpuStream::is_failed) + { + return Err(Error::ContextPoisoned); + } + for (b, n) in [ + (&self.scratch, self.layout.bytes), + (&self.records, self.prompt_cap * 29 * 4), + ( + &self.status, + (self.prompt_cap.div_ceil(self.max_t) + 1) * SCALAR_FLAGS * 4, + ), + ] { + let b = b.as_ref().ok_or(Error::ContextPoisoned)?; + checked(self.context, b, n)?; + } + Ok(()) + } + fn poison(&mut self) { + self.failed = true; + self.context.poison(); + self.context.retain_driver(); + } + fn module(&self, i: usize) -> Result<&Module> { + self.modules + .get(i) + .and_then(Option::as_ref) + .map(Rc::as_ref) + .ok_or(Error::ContextPoisoned) + } + fn scratch(&self, i: usize, n: usize) -> Result { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + if n == 0 || n > self.layout.sizes[i] { + return Err(Error::InvalidSize); + } + b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, self.layout.offsets[i], n) + } + fn address(&self, i: usize, n: usize) -> Result { + Ok(self.scratch(i, n)?.qwen_address()) + } + fn current_kv(&self, ring: &MtpOriginalInt8<'ctx>) -> Result<(u64, u64)> { + match &self.original_layout { + Some(l) => { + let b = self.scratch.as_ref().ok_or(Error::ContextPoisoned)?; + Ok(( + l.span(b, 22, 0, self.max_t * 2048)?.qwen_address(), + l.span(b, 23, 0, self.max_t * 2048)?.qwen_address(), + )) + } + None => Ok((ring.address(6)?, ring.address(7)?)), + } + } + fn flag(&self, group: usize, stage: usize) -> Result { + let b = self.status.as_ref().ok_or(Error::ContextPoisoned)?; + if stage >= SCALAR_FLAGS { + return Err(Error::InvalidSize); + } + Ok(b.handle + .ok_or(Error::ContextPoisoned)? + .checked_subspan(b.bytes, (group * SCALAR_FLAGS + stage) * 4, 4)? + .qwen_address()) + } + #[allow(clippy::too_many_arguments)] + fn kernel( + cmds: &mut Vec, + asset: usize, + index: usize, + grid: [u32; 3], + block: [u32; 3], + shared: u32, + args: Vec, + ) -> Result<()> { + cmds.try_reserve(1).map_err(|_| Error::HostAllocation)?; + cmds.push(ScalarCommand::Kernel { + asset, + index, + grid, + block, + shared, + args: Arguments::new(args)?, + }); + Ok(()) + } + fn finite( + &self, + cmds: &mut Vec, + data: u64, + n: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 11, + [n.div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(data), + Arg::I32(n as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + fn q8_guard( + &self, + cmds: &mut Vec, + q: u64, + rows: usize, + _g: usize, + s: usize, + ) -> Result<()> { + Self::kernel( + cmds, + 2, + 12, + [(rows * 80).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![ + Arg::U64(q), + Arg::I32((rows * 80) as i32), + Arg::U64(self.flag(0, s)?), + ], + ) + } + fn quant(cmds: &mut Vec, x: u64, q: u64, rows: usize) -> Result<()> { + Self::kernel( + cmds, + 2, + 0, + [(rows * 2560).div_ceil(256) as u32, 1, 1], + [256, 1, 1], + 0, + vec![Arg::U64(x), Arg::U64(q), Arg::I32((rows * 2560) as i32)], + ) + } + fn project( + cmds: &mut Vec, + w: u64, + q: u64, + y: u64, + rows: usize, + out: usize, + ) -> Result<()> { + if !(1..=8).contains(&rows) || !matches!(out, 512 | 2560) { + return Err(Error::InvalidProjectionShape); + } + Self::kernel( + cmds, + 2, + rows, + [out as u32, 1, 1], + [32, 4, 1], + 0, + vec![ + Arg::U64(w), + Arg::U64(q), + Arg::U64(y), + Arg::I32(2560), + Arg::I32(out as i32), + ], + ) + } + fn external( + &self, + rows: &OriginalPromptRows<'_, '_, '_>, + w: &NativeBatchWorkspace<'_>, + ring: &MtpOriginalInt8<'_>, + b: &DeviceBuffer<'_>, + n: usize, + ) -> Result { + checked(self.context, b, n)?; + let h = b.handle.ok_or(Error::ContextPoisoned)?; + w.reject_alias(h, n)?; + let (r, rn) = rows.common_span(OriginalPromptSpan::R)?; + if h.overlaps(n, r, rn) { + return Err(Error::OutputAliasesInput); + } + for own in [&self.scratch, &self.records, &self.status] + .into_iter() + .flatten() + { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + for own in ring.buffers()?.iter().flatten() { + if h.overlaps(n, own.handle.ok_or(Error::ContextPoisoned)?, own.bytes) { + return Err(Error::OutputAliasesInput); + } + } + ring.reject_state_alias(b)?; + if !ring.fully_resident()? { + let mapped = ring.mapped()?; + let host = mapped.address(0, MTP_ORIGINAL_PINNED_HOST_BYTES)?; + if h.qwen_address() < host + MTP_ORIGINAL_PINNED_HOST_BYTES as u64 + && host < h.qwen_address() + n as u64 + { + return Err(Error::OutputAliasesInput); + } + } + Ok(h) + } + // Exact FusedGrArgs/GrMulti by-value ABI (static assertions in source asset). + #[allow(clippy::too_many_arguments)] + fn gr_args(&self, start: usize, t: usize, wh: &[BufferHandle; 11], xn: u64) -> Result { + let mut words = Box::new([0u64; 114]); + for i in 0..t { + let row = start + i; + let a = &mut words[i * 14..i * 14 + 14]; + a[0] = self.address(1, self.max_t * 40960)? + (row * 40960) as u64; + a[1] = a[0]; + a[2] = 0; // apply=false, exact null previous writers + a[5] = wh[4].qwen_address(); + a[6] = wh[5].qwen_address(); + a[7] = wh[6].qwen_address(); + a[8] = wh[10].qwen_address(); + a[9] = u64::from(1e-6f32.to_bits()); + a[10] = self.address(8, self.max_t * 1280)? + (row * 1280) as u64; + a[11] = self.address(9, self.max_t * 16)? + (row * 16) as u64; + a[12] = self.address(10, self.max_t * 16)? + (row * 16) as u64; + a[13] = self.address(11, self.max_t * 10240)? + (row * 10240) as u64; + } + words[112] = xn; + words[113] = t as u64; + Ok(Arg::GrMulti(words)) + } + fn gr( + &self, + cmds: &mut Vec, + t: usize, + wh: &[BufferHandle; 11], + policy: &OriginalMtpScalarPolicy, + ) -> Result<()> { + let xn = self.address(7, t * 40960)?; + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Plain { + 0 + } else { + 1 + }, + [ + t as u32, + if policy.gr == OriginalMtpGrVariant::Plain { + 1 + } else { + 4 + }, + 1, + ], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + )?; + let per_token = if policy.gr == OriginalMtpGrVariant::Staged { + 2 * 1280 * 4 + } else { + self.plain_tile * 4 + }; + let capacity = (self.shared_limit / per_token).clamp(1, 8); + for c in (0..t).step_by(capacity) { + let ct = capacity.min(t - c); + Self::kernel( + cmds, + 4, + if policy.gr == OriginalMtpGrVariant::Staged { + 2 + } else if self.plain_tile == 1280 { + 4 + } else { + 5 + }, + [41, 1, 1], + [256, 1, 1], + (ct * per_token) as u32, + vec![self.gr_args(c, ct, wh, xn + (c * 40960) as u64)?], + )?; + } + Self::kernel( + cmds, + 4, + 3, + [160, 1, 1], + [256, 1, 1], + 0, + vec![self.gr_args(0, t, wh, xn)?], + ) + } + #[allow(clippy::too_many_arguments)] + pub fn record<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + policy: &OriginalMtpScalarPolicy, + cancelled: impl FnMut() -> bool, + ) -> Result { + let result = self.record_impl( + residual, + workspace, + ring, + prior, + tokens, + cell0, + first_needed, + retained, + policy, + cancelled, + ); + if self.has_pending { + let drained = self.drain_graphs(residual.lease_mut(), workspace); + return combine(result, drained); + } + result + } + /// Literal cached device-input or mapped-input per-T graph scheduling. + /// Unsupported storage/math branches return explicit fallback, never completion. + #[allow(clippy::too_many_arguments)] + fn record_impl<'arena, 'loan>( + &mut self, + residual: &mut OriginalDeviceResidual<'arena, 'loan, 'ctx>, + workspace: &mut NativeBatchWorkspace<'ctx>, + ring: &mut MtpOriginalInt8<'ctx>, + prior: &MtpInt8Snapshot, + tokens: &[i32], + cell0: usize, + first_needed: usize, + retained: Rc>, + 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 (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 { + return Ok(DraftKvOutcome::Skipped); + }; + let first = cell0 + first_group; + let end = cell0 + tokens.len(); + let rows = residual.lease_mut(); + let (rh, rbytes) = rows.common_span(OriginalPromptSpan::R)?; + 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); + } + } + 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); + } + } + } + let wr = [ + weights.input.embedding_norm, + weights.input.embedding_fc, + weights.input.hidden_norm, + weights.input.hidden_fc, + weights.input.gr_norm, + weights.input.gr_down, + weights.input.gr_up, + weights.input.key, + weights.input.value, + 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])?; + } + let eh = self.external( + rows, + workspace, + ring, + embedding.table, + embedding.table.bytes, + )?; + for i in 0..wr.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]) + { + return Err(Error::OutputAliasesInput); + } + } + } + let key = [ + policy.gr as u32, + policy.per_group_sync as u32, + kv.theta_scale.to_bits(), + kv.freq_scale.to_bits(), + kv.corr_low.to_bits(), + kv.corr_high.to_bits(), + kv.ext_factor.to_bits(), + kv.mscale.to_bits(), + 0, + ]; + 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) + { + return Err(Error::InvalidProjectionShape); + } + 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: Rc::new(pages.into_boxed_slice()), + 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, + })) + } + pub fn close(mut self) -> Result<()> { + self.close_inner() + } + fn close_inner(&mut self) -> Result<()> { + self.failed = true; + let mut primary = Ok(()); + if let Some(graphs) = self.graphs.take() { + primary = combine(primary, graphs.close()); + } + if let Some(stream) = self.stream.take() { + let r = stream.close(); + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + for module in &mut self.modules { + if let Some(m) = module.take() { + let r = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine( + Rc::try_unwrap(m) + .map_err(|_| Error::InvalidQwenShape) + .and_then(Module::close), + g.finish(), + ), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if r.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, r); + } + } + for b in [&mut self.scratch, &mut self.records, &mut self.status] { + if let Some(b) = b.take() { + primary = combine( + primary, + if self.context.is_poisoned() { + std::mem::forget(b); + Err(Error::ContextPoisoned) + } else { + match Rc::try_unwrap(b) { + Ok(b) => b.release(), + Err(b) => { + if self.original_layout.is_some() { + drop(b); + Ok(()) + } else { + Err(Error::InvalidQwenShape) + } + } + } + }, + ); + } + } + if let Some(mut m) = self.mapped.borrow_mut().take() { + let result = if self.context.is_poisoned() { + std::mem::forget(m); + Err(Error::ContextPoisoned) + } else { + match self.context.enter() { + Ok(g) => combine(m.close(), g.finish()), + Err(e) => { + self.context.poison(); + std::mem::forget(m); + Err(e) + } + } + }; + if result.is_err() { + self.context.poison(); + self.context.retain_driver(); + } + primary = combine(primary, result); + } + self.retained = None; + if self.context.is_poisoned() { + std::mem::forget(std::mem::take(&mut self.pending_host)); + } else { + self.pending_host.clear(); + } + if self.context.is_poisoned() { + self.context.retain_driver(); + } + primary + } +} +impl Drop for OriginalMtpScalarPrefill<'_> { + fn drop(&mut self) { + let _ = self.close_inner(); + } +} + +#[path = "mtp_original_scalar_graph.rs"] +mod graph; + +#[cfg(test)] +#[path = "mtp_original_scalar_short_gpu.rs"] +mod short_prompt_gpu;