diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs index 30803b27..700019d6 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/impl_mtpframe.rs @@ -105,23 +105,23 @@ impl MtpInput { if cache.has_mtp_input_workspace() { return Self::compute_queued(binding, session, frame, streams, &embedding, cache); } - let en = norm(context, binding, MtpRole::EmbeddingNorm, &embedding, false, cache)?; + Self::compute_host(binding, session, frame, (streams, &embedding), (context, cache)) + } + fn compute_host( + binding: &ModelBinding, + session: &QwenSession<'_>, + frame: MtpFrame, + (streams, embedding): (&[f32], &[f32]), + (context, cache): (&Context<'_>, &MoeWeightCache<'_>), + ) -> Result { + let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, false, cache)?; let e2 = project(context, binding, MtpRole::FcEmbedding, &en, cache)?; let hn = norm(context, binding, MtpRole::HiddenNorm, streams, true, cache)?; - let mut h2 = reserve(10240)?; - for chunk in hn.as_chunks::<2560>().0 { - h2.extend_from_slice(&project(context, binding, MtpRole::FcHidden, chunk, cache)?); - } - let hidden = upload(context, &h2)?; - let emb = upload(context, &e2)?; - let mut out = allocate(context, 10240)?; - context.mtp_broadcast_f32(&hidden, &emb, &mut out).map_err(driver_error)?; - let result = download(&out, 10240)?; - release([hidden, emb, out])?; + let h2 = project_hidden_chunks(context, binding, &hn, cache)?; + let result = broadcast_streams(context, &h2, &e2)?; frame.validate(binding, session)?; Ok(Self { frame, streams: result }) - } - // Each role is acquired at the original stage. Scratch is exclusively + } // Each role is acquired at the original stage. Scratch is exclusively // borrowed from a separate owner while actual dense weights stay immutable. pub(super) fn compute_queued( binding: &ModelBinding, @@ -139,51 +139,117 @@ impl MtpInput { let owner = cache.mtp_input_workspace_owner(binding, context)?; owner.with_workspace(|workspace| { let mut prefix = workspace.begin(embedding, streams).map_err(driver_error)?; - let admitted: Result<()> = (|| { - prefix.embedding_norm(en_weights).map_err(driver_error)?; - let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?; - queued_fc_shape(kind, rows, columns)?; - preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; - prefix.embedding_projection(weights).map_err(driver_error)?; - let hn_gamma = f32_weights(binding, MtpRole::HiddenNorm, cache)?; - validate_values(streams, 10240)?; - validate_values(&hn_gamma, 10240)?; - let (_, _, _, hn_weights) = cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?; - prefix.hidden_norm(hn_weights).map_err(driver_error)?; - // The original host H assembly allocation remains at its role - // point; this queue changes only numerical transport storage. - let _h2 = reserve::(10240)?; - for _ in 0..4 { - let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcHidden)?; - queued_fc_shape(kind, rows, columns)?; - preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; - prefix.hidden_projection(weights).map_err(driver_error)?; - } - Ok(()) - })(); - if let Err(primary) = admitted { - // A fully completed earlier numerical refusal retains its old - // priority over a later cache/source/shape admission refusal. - // CUDA uncertainty keeps conservative transport precedence. - return match prefix.drain_prefix().map_err(driver_error)? { - Some(refusal) => Err(input_refusal(refusal)), - None => Err(primary), - }; + if let Err(primary) = admit_queued_prefix(&mut prefix, binding, context, cache, (streams, en_weights)) { + return refuse_queued(prefix, primary); } - let completion = prefix.finish().map_err(driver_error)?; - #[cfg(test)] - if let Some(stage) = completion.refusal_stage() { - eprintln!("PUBLIC MTP input queued numeric stage={stage}"); - } - let result = completion.into_streams().map_err(input_refusal)?; - validate_values(&result, 10240)?; - frame.validate(binding, session)?; - cache.validate(binding, context)?; - #[cfg(test)] - cache.note_mtp_input_completed(); - Ok(Self { frame, streams: result }) + Self::complete_queued(prefix, (binding, session, context), cache, frame) }) } + fn complete_queued( + prefix: leleka_cuda_driver::MtpInputPrefix<'_, '_>, + (binding, session, context): (&ModelBinding, &QwenSession<'_>, &Context<'_>), + cache: &MoeWeightCache<'_>, + frame: MtpFrame, + ) -> Result { + let completion = prefix.finish().map_err(driver_error)?; + #[cfg(test)] + if let Some(stage) = completion.refusal_stage() { + eprintln!("PUBLIC MTP input queued numeric stage={stage}"); + } + let result = completion.into_streams().map_err(input_refusal)?; + validate_values(&result, 10240)?; + frame.validate(binding, session)?; + cache.validate(binding, context)?; + #[cfg(test)] + cache.note_mtp_input_completed(); + Ok(Self { frame, streams: result }) + } +} +/// The original host H assembly: the hidden stream projected in four 2560-wide chunks. +fn project_hidden_chunks( + context: &Context<'_>, + binding: &ModelBinding, + hn: &[f32], + cache: &MoeWeightCache<'_>, +) -> Result> { + let mut h2 = reserve(10240)?; + for chunk in hn.as_chunks::<2560>().0 { + h2.extend_from_slice(&project(context, binding, MtpRole::FcHidden, chunk, cache)?); + } + Ok(h2) +} +fn broadcast_streams(context: &Context<'_>, h2: &[f32], e2: &[f32]) -> Result> { + let hidden = upload(context, h2)?; + let emb = upload(context, e2)?; + let mut out = allocate(context, 10240)?; + context.mtp_broadcast_f32(&hidden, &emb, &mut out).map_err(driver_error)?; + let result = download(&out, 10240)?; + release([hidden, emb, out])?; + Ok(result) +} +fn queued_embedding<'lease, 'ctx: 'lease>( + prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>, + binding: &ModelBinding, + context: &Context<'_>, + cache: &'lease MoeWeightCache<'ctx>, + en_weights: &'lease DeviceBuffer<'ctx>, +) -> Result<()> { + prefix.embedding_norm(en_weights).map_err(driver_error)?; + let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcEmbedding)?; + queued_fc_shape(kind, rows, columns)?; + preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; + prefix.embedding_projection(weights).map_err(driver_error) +} +fn queued_hidden_norm<'lease, 'ctx: 'lease>( + prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>, + binding: &ModelBinding, + context: &Context<'_>, + cache: &'lease MoeWeightCache<'ctx>, + streams: &[f32], +) -> Result<()> { + let hn_gamma = f32_weights(binding, MtpRole::HiddenNorm, cache)?; + validate_values(streams, 10240)?; + validate_values(&hn_gamma, 10240)?; + let (_, _, _, hn_weights) = cache.mtp_matrix(binding, context, MtpRole::HiddenNorm)?; + prefix.hidden_norm(hn_weights).map_err(driver_error) +} +fn queued_hidden_projections<'lease, 'ctx: 'lease>( + prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>, + binding: &ModelBinding, + context: &Context<'_>, + cache: &'lease MoeWeightCache<'ctx>, +) -> Result<()> { + // The original host H assembly allocation remains at its role + // point; this queue changes only numerical transport storage. + let _h2 = reserve::(10240)?; + for _ in 0..4 { + let (kind, rows, columns, weights) = cache.mtp_matrix(binding, context, MtpRole::FcHidden)?; + queued_fc_shape(kind, rows, columns)?; + preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; + prefix.hidden_projection(weights).map_err(driver_error)?; + } + Ok(()) +} +/// Every queued stage of the prefix is admitted in the original order before the prefix may finish. +fn admit_queued_prefix<'lease, 'ctx: 'lease>( + prefix: &mut leleka_cuda_driver::MtpInputPrefix<'lease, 'ctx>, + binding: &ModelBinding, + context: &Context<'_>, + cache: &'lease MoeWeightCache<'ctx>, + (streams, en_weights): (&[f32], &'lease DeviceBuffer<'ctx>), +) -> Result<()> { + queued_embedding(prefix, binding, context, cache, en_weights)?; + queued_hidden_norm(prefix, binding, context, cache, streams)?; + queued_hidden_projections(prefix, binding, context, cache) +} +/// A fully completed earlier numerical refusal retains its old +/// priority over a later cache/source/shape admission refusal. +/// CUDA uncertainty keeps conservative transport precedence. +fn refuse_queued(prefix: leleka_cuda_driver::MtpInputPrefix<'_, '_>, primary: Error) -> Result { + match prefix.drain_prefix().map_err(driver_error)? { + Some(refusal) => Err(input_refusal(refusal)), + None => Err(primary), + } } // Only the actual loaded Q8_0 pack opts in; old BF16/unsupported paths stay None. pub(super) fn queued_fc_shape(kind: MtpKind, rows: usize, columns: usize) -> Result<()> { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs index 9362f345..06f1ef8c 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/project_attention_out_numeric_fn.rs @@ -3,29 +3,37 @@ #[allow(unused_imports)] use super::*; +const ROWS: usize = 2560; +const COLUMNS: usize = 6144; + +fn project_gated( + context: &Context<'_>, + weights: &DeviceBuffer<'_>, + activation: &DeviceBuffer<'_>, + y: &mut DeviceBuffer<'_>, +) -> Result> { + context + .project_q8_1( + weights, + activation, + y, + ProjectionSpec { rows: ROWS, columns: COLUMNS, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, + ) + .map_err(driver_error)?; + download(y, ROWS) +} + pub(in super::super) fn project_attention_out_numeric( context: &Context<'_>, weights: &DeviceBuffer<'_>, input: &super::super::mtp_attention::RetainedGated<'_>, ) -> Result> { - const ROWS: usize = 2560; - const COLUMNS: usize = 6144; let activation = input.buffer(context)?; // Activation is already charged by Context. Reserve the same remaining // output/quantizer/status increment as the original upload-based path. preflight(context, ROWS * 4 + COLUMNS / 32 * 36 + 4)?; let mut y = allocate(context, ROWS)?; - let result = (|| { - context - .project_q8_1( - weights, - activation, - &mut y, - ProjectionSpec { rows: ROWS, columns: COLUMNS, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, - ) - .map_err(driver_error)?; - download(&y, ROWS) - })(); + let result = project_gated(context, weights, activation, &mut y); if result.as_ref().is_err_and(|e| *e == Error::CudaExecution) { input.failure_flag().set(true); } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs index c2f98430..0fc2c12a 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp/step_fn.rs @@ -52,6 +52,66 @@ pub(in super::super) fn warm_chunk_row( stage.validate_anchor(binding, target) }) } +/// The five numerical stage products of one draft step. They stay alive until the step is committed and synchronized, +/// and drop in the reverse order the stages produced them. +struct MtpBlocks { + final_mixed: super::super::mtp_gr::MtpDraftFinal, + block: super::super::mtp_experts::MtpBlock, + mlp: super::super::mtp_gr::MtpMlpReady, + attention: super::super::mtp_attention::MtpAttentionReady, + read: super::super::mtp_gr::MtpAttentionRead, +} +fn run_blocks( + binding: &ModelBinding, + input: &MtpInput, + (session, draft): (&QwenSession<'_>, &MtpSession), + cache: &MoeWeightCache<'_>, + transport_failed: &Rc>, +) -> Result { + let read = super::super::mtp_gr::attention_read(binding, input, session, cache)?; + let attention = super::super::mtp_attention::MtpAttentionStage::run( + binding, + &read, + draft, + session, + cache, + Rc::clone(transport_failed), + )?; + let mlp = super::super::mtp_gr::mlp_read(binding, &attention, session, cache)?; + let block = + super::super::mtp_experts::MtpExpertStage::run(binding, &mlp, session, cache, Rc::clone(transport_failed))?; + let final_mixed = super::super::mtp_gr::finalize(binding, &block, &mlp, session, cache)?; + if !input.frame.same(final_mixed.frame()) || !input.frame.same(attention.frame()) { + return Err(Error::IdentityMismatch); + } + Ok(MtpBlocks { final_mixed, block, mlp, attention, read }) +} +fn copy_streams(values: &[f32]) -> Result<(Vec, Vec)> { + let mut streams = reserve(10240)?; + streams.extend_from_slice(values); + let mut retained = reserve(10240)?; + retained.extend_from_slice(&streams); + Ok((streams, retained)) +} +fn step_run( + binding: &ModelBinding, + session: &mut QwenSession<'_>, + draft: &mut MtpSession, + input: MtpInput, + output: Option<&super::super::output::OutputStage<'_, '_>>, + (cache, transport_failed): (&MoeWeightCache<'_>, &Rc>), +) -> Result> { + input.frame.validate(binding, session)?; + draft.prior(&input.frame)?; + let blocks = run_blocks(binding, &input, (session, draft), cache, transport_failed)?; + let predicted = output.map(|head| head.mtp_greedy(binding, blocks.final_mixed.mixed(), session)).transpose()?; + let (streams, retained) = copy_streams(blocks.final_mixed.streams())?; + // Teardown/synchronization ambiguity is sticky, never erased by rewind. + session.finish_mtp_device()?; + input.frame.validate(binding, session)?; + draft.commit(&input.frame, blocks.attention.into_pending_kv(), retained.into_boxed_slice())?; + Ok(predicted.map(|predicted| MtpStepProduct { frame: input.frame, predicted, streams: streams.into_boxed_slice() })) +} pub(super) fn step_core( binding: &ModelBinding, session: &mut QwenSession<'_>, @@ -61,45 +121,7 @@ pub(super) fn step_core( cache: &MoeWeightCache<'_>, ) -> Result> { let transport_failed = Rc::new(Cell::new(false)); - let result = (|| { - input.frame.validate(binding, session)?; - draft.prior(&input.frame)?; - let read = super::super::mtp_gr::attention_read(binding, &input, session, cache)?; - let attention = super::super::mtp_attention::MtpAttentionStage::run( - binding, - &read, - draft, - session, - cache, - Rc::clone(&transport_failed), - )?; - let mlp = super::super::mtp_gr::mlp_read(binding, &attention, session, cache)?; - let block = super::super::mtp_experts::MtpExpertStage::run( - binding, - &mlp, - session, - cache, - Rc::clone(&transport_failed), - )?; - let final_mixed = super::super::mtp_gr::finalize(binding, &block, &mlp, session, cache)?; - if !input.frame.same(final_mixed.frame()) || !input.frame.same(attention.frame()) { - return Err(Error::IdentityMismatch); - } - let predicted = output.map(|head| head.mtp_greedy(binding, final_mixed.mixed(), session)).transpose()?; - let mut streams = reserve(10240)?; - streams.extend_from_slice(final_mixed.streams()); - let mut retained = reserve(10240)?; - retained.extend_from_slice(&streams); - // Teardown/synchronization ambiguity is sticky, never erased by rewind. - session.finish_mtp_device()?; - input.frame.validate(binding, session)?; - draft.commit(&input.frame, attention.into_pending_kv(), retained.into_boxed_slice())?; - Ok(predicted.map(|predicted| MtpStepProduct { - frame: input.frame, - predicted, - streams: streams.into_boxed_slice(), - })) - })(); + let result = step_run(binding, session, draft, input, output, (cache, &transport_failed)); if transport_failed.get() { session.note_mtp_failure(&Error::CudaExecution); } @@ -163,6 +185,25 @@ pub(super) fn norm( release([x, y])?; Ok(result) } +fn project_kernel( + context: &Context<'_>, + kind: MtpKind, + weights: &DeviceBuffer<'_>, + (x, y): (&DeviceBuffer<'_>, &mut DeviceBuffer<'_>), + (rows, columns): (usize, usize), +) -> Result<()> { + match kind { + MtpKind::Bf16 => context.bf16_f32(weights, x, y, Bf16ProjectionShape { rows, columns }), + MtpKind::Q8_0 => context.project_q8_1( + weights, + x, + y, + ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, + ), + _ => unreachable!(), + } + .map_err(driver_error) +} /// Bounded exact row tiles of the separately pinned MTP pack. Every numerical /// projection uses the already qualified native CUDA format dispatcher. /// Whole immutable dense role; each original row's projection schedule is unchanged. @@ -181,20 +222,8 @@ pub(in super::super) fn project( preflight(context, columns * 4 + rows * 4 + columns / 32 * 36 + 4)?; let x = upload(context, input)?; let mut y = allocate(context, rows)?; - let result = (|| { - match kind { - MtpKind::Bf16 => context.bf16_f32(weights, &x, &mut y, Bf16ProjectionShape { rows, columns }), - MtpKind::Q8_0 => context.project_q8_1( - weights, - &x, - &mut y, - ProjectionSpec { rows, columns, kind: ProjectionKind::Dense(DenseFormat::Q8_0) }, - ), - _ => unreachable!(), - } - .map_err(driver_error)?; - download(&y, rows) - })(); + let result = + project_kernel(context, kind, weights, (&x, &mut y), (rows, columns)).and_then(|()| download(&y, rows)); let cleanup = release([x, y]); let output = result?; cleanup?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs index 701024eb..c0b7af39 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/geometry_fn.rs @@ -39,6 +39,20 @@ pub(super) fn validate_window(keys: &[u8], values: &[u8], geometry: &DenseGeomet } Ok(()) } +fn norm_rope_launch( + context: &Context<'_>, + (x, gamma_device): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + (norm, rope): (&mut DeviceBuffer<'_>, &mut DeviceBuffer<'_>), + (position, query): (u32, bool), +) -> Result> { + let count = if query { Q } else { KV }; + if query { context.qsa_norm_q(x, gamma_device, norm) } else { context.qsa_norm_k(x, gamma_device, norm) } + .map_err(attention_driver_error)?; + download(norm, count)?; + if query { context.qsa_rope_q(norm, position, rope) } else { context.qsa_rope_k(norm, position, rope) } + .map_err(attention_driver_error)?; + download(rope, count) +} pub(super) fn norm_rope( context: &Context<'_>, values: &[f32], @@ -53,22 +67,7 @@ pub(super) fn norm_rope( let x = upload(context, values)?; let mut norm = allocate(context, count)?; let mut rope = allocate(context, count)?; - let result: Result> = (|| { - if query { - context.qsa_norm_q(&x, gamma_device, &mut norm) - } else { - context.qsa_norm_k(&x, gamma_device, &mut norm) - } - .map_err(attention_driver_error)?; - download(&norm, count)?; - if query { - context.qsa_rope_q(&norm, position, &mut rope) - } else { - context.qsa_rope_k(&norm, position, &mut rope) - } - .map_err(attention_driver_error)?; - download(&rope, count) - })(); + let result = norm_rope_launch(context, (&x, gamma_device), (&mut norm, &mut rope), (position, query)); let cleanup = release([x, norm, rope]); let result = result?; cleanup?; diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs index 180212c2..bbb9caee 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/impl_mtpattentionready.rs @@ -23,6 +23,112 @@ impl MtpAttentionReady { self.pending } } +fn validate_read_values(input: &MtpAttentionRead) -> Result<()> { + validate_values(input.mixed(), N)?; + validate_values(input.streams(), 4 * N)?; + validate_values(input.inject(), 4) +} +/// Every exact descriptor of the pinned pack admitted before row access/CUDA. +fn check_roles(binding: &ModelBinding, expected: &[(MtpRole, (MtpKind, usize, usize))]) -> Result<()> { + let pack = binding.mtp_weights().map_err(binding_error)?; + for (role, expected) in expected { + if pack.dense_shape(binding, *role).map_err(binding_error)? != *expected { + return Err(Error::InvalidDimension); + } + } + Ok(()) +} +/// The K/V projections, K norm/rope and the packed half-precision cell of one row; the source K/V-before-query +/// sequence. No indexer, sparse selection, rotation/INT8/Q4 cache, or target QSA state is substituted. +fn packed_kv( + context: &Context<'_>, + binding: &ModelBinding, + input: &MtpAttentionRead, + (position, cache): (u32, &MoeWeightCache<'_>), +) -> Result { + let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?; + let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?; + let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?; + let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?; + let k = norm_rope(context, &k, &kgamma, kw, position, false)?; + pack_kv(context, &k, &v) +} +/// Q and its gate: the query projection split, then the Q norm/rope. +fn query_gate( + context: &Context<'_>, + binding: &ModelBinding, + input: &MtpAttentionRead, + (position, cache): (u32, &MoeWeightCache<'_>), +) -> Result { + let full = project(context, binding, MtpRole::QueryProjection, input.mixed(), cache)?; + let (q, gate) = split(context, &full)?; + let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?; + let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?; + Ok((norm_rope(context, &q, &qgamma, qw, position, true)?, gate)) +} +/// Frame, prior and descriptor admission, then the context and the budget of the temporary buffers. +fn admit_run<'a, 'd>( + binding: &ModelBinding, + input: &MtpAttentionRead, + (draft, session): (&'a MtpSession, &'a QwenSession<'d>), + cache: &MoeWeightCache<'_>, +) -> Result<(&'a DenseKv, DenseGeometry, &'a Context<'d>, bool)> { + input.frame().validate(binding, session)?; + let prior = draft.prior(input.frame())?; + validate_read_values(input)?; + let geometry = geometry(input.frame().position().get())?; + check_roles( + binding, + &[ + (MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)), + (MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)), + (MtpRole::QueryProjection, (MtpKind::Q8_0, 2 * Q, N)), + (MtpRole::AttentionOutput, (MtpKind::Q8_0, N, Q)), + (MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), + (MtpRole::QueryNorm, (MtpKind::F32, 1, 256)), + ], + )?; + let context = session.mtp_context()?; + let ring_enabled = cache.has_mtp_kv_ring()?; + preflight(context, temporary_bytes(&geometry, ring_enabled)?)?; + Ok((prior, geometry, context, ring_enabled)) +} +fn temporary_bytes(geometry: &DenseGeometry, ring_enabled: bool) -> Result { + if ring_enabled { + geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow) + } else { + Ok(geometry.device_bytes) + } +} +/// The host half windows of the candidate, or none when the actor's bounded ring mirrors them. +fn host_window( + (binding, context, cache): (&ModelBinding, &Context<'_>, &MoeWeightCache<'_>), + (pending, frame, geometry): (&DenseKv, &MtpFrame, &DenseGeometry), + ring_enabled: bool, +) -> Result> { + if ring_enabled { + cache.prepare_mtp_kv(binding, context, pending, frame)?; + return Ok(None); + } + let window = pending.window(frame)?; + validate_window(&window.0, &window.1, geometry)?; + Ok(Some(window)) +} +/// Attention output through the closed AttentionOutput consumer; the gated owner is closed after use. +fn gated_output<'ctx>( + context: &'ctx Context<'ctx>, + (binding, session, cache): (&ModelBinding, &QwenSession<'_>, &MoeWeightCache<'_>), + frame: &MtpFrame, + (attention, gate): (RetainedAttended<'ctx>, &[f32]), +) -> Result> { + let gated = MtpGated { frame: frame.clone(), numeric: gate_retained(context, attention, gate)? }; + let result = project_attention_output(context, binding, session, &gated, cache); + let cleanup = gated.close(); + let output = result?; + cleanup?; + validate_values(&output, N)?; + Ok(output) +} impl MtpAttentionStage { pub(in super::super) fn run( binding: &ModelBinding, @@ -32,67 +138,16 @@ impl MtpAttentionStage { cache: &MoeWeightCache<'_>, failed: Rc>, ) -> Result { - input.frame().validate(binding, session)?; - let prior = draft.prior(input.frame())?; - validate_values(input.mixed(), N)?; - validate_values(input.streams(), 4 * N)?; - validate_values(input.inject(), 4)?; - let geometry = geometry(input.frame().position().get())?; - let pack = binding.mtp_weights().map_err(binding_error)?; - // All exact descriptors and opaque prior admitted before row access/CUDA. - for (role, expected) in [ - (MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)), - (MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)), - (MtpRole::QueryProjection, (MtpKind::Q8_0, 2 * Q, N)), - (MtpRole::AttentionOutput, (MtpKind::Q8_0, N, Q)), - (MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), - (MtpRole::QueryNorm, (MtpKind::F32, 1, 256)), - ] { - if pack.dense_shape(binding, role).map_err(binding_error)? != expected { - return Err(Error::InvalidDimension); - } - } - let context = session.mtp_context()?; - let ring_enabled = cache.has_mtp_kv_ring()?; - let temporary_bytes = if ring_enabled { - geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)? - } else { - geometry.device_bytes - }; - preflight(context, temporary_bytes)?; - // Preserve the source K/V-before-query sequence. No indexer, sparse - // selection, rotation/INT8/Q4 cache, or target QSA state is substituted. - let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?; - let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?; - let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?; - let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?; - let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?; - let (key, value) = pack_kv(context, &k, &v)?; + let (prior, geometry, context, ring_enabled) = admit_run(binding, input, (draft, session), cache)?; + let (key, value) = packed_kv(context, binding, input, (geometry.position, cache))?; let pending = prior.append(input.frame(), key, value)?; - let host_window = if ring_enabled { - cache.prepare_mtp_kv(binding, context, &pending, input.frame())?; - None - } else { - let window = pending.window(input.frame())?; - validate_window(&window.0, &window.1, &geometry)?; - Some(window) + let window = host_window((binding, context, cache), (&pending, input.frame(), &geometry), ring_enabled)?; + let (q, gate) = query_gate(context, binding, input, (geometry.position, cache))?; + let attention = match window { + Some((keys, values)) => attend_retained(context, &q, &keys, &values, &geometry, failed)?, + None => attend_ring_retained(context, &q, &geometry, failed, binding, cache, &pending, input.frame())?, }; - let full = project(context, binding, MtpRole::QueryProjection, input.mixed(), cache)?; - let (q, gate) = split(context, &full)?; - let qgamma = f32_weights(binding, MtpRole::QueryNorm, cache)?; - let (_, _, _, qw) = cache.mtp_matrix(binding, context, MtpRole::QueryNorm)?; - let q = norm_rope(context, &q, &qgamma, qw, geometry.position, true)?; - let attention = if let Some((keys, values)) = host_window { - attend_retained(context, &q, &keys, &values, &geometry, failed)? - } else { - attend_ring_retained(context, &q, &geometry, failed, binding, cache, &pending, input.frame())? - }; - let gated = MtpGated { frame: input.frame().clone(), numeric: gate_retained(context, attention, &gate)? }; - let result = project_attention_output(context, binding, session, &gated, cache); - let cleanup = gated.close(); - let output = result?; - cleanup?; - validate_values(&output, N)?; + let output = gated_output(context, (binding, session, cache), input.frame(), (attention, &gate))?; input.frame().validate(binding, session)?; draft.prior(input.frame())?; let mut streams = reserve(4 * N)?; @@ -116,28 +171,19 @@ pub(in super::super) fn produce_kv_cell( cache: &MoeWeightCache<'_>, ) -> Result { input.frame().validate(binding, session)?; - validate_values(input.mixed(), N)?; - validate_values(input.streams(), 4 * N)?; - validate_values(input.inject(), 4)?; + validate_read_values(input)?; let geometry = geometry(input.frame().position().get())?; - let pack = binding.mtp_weights().map_err(binding_error)?; - for (role, expected) in [ - (MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)), - (MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)), - (MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), - ] { - if pack.dense_shape(binding, role).map_err(binding_error)? != expected { - return Err(Error::InvalidDimension); - } - } + check_roles( + binding, + &[ + (MtpRole::KeyProjection, (MtpKind::Q8_0, KV, N)), + (MtpRole::ValueProjection, (MtpKind::Q8_0, KV, N)), + (MtpRole::KeyNorm, (MtpKind::F32, 1, 256)), + ], + )?; let context = session.mtp_context()?; preflight(context, 2 * 1024 * 1024)?; - let k = project(context, binding, MtpRole::KeyProjection, input.mixed(), cache)?; - let v = project(context, binding, MtpRole::ValueProjection, input.mixed(), cache)?; - let kgamma = f32_weights(binding, MtpRole::KeyNorm, cache)?; - let (_, _, _, kw) = cache.mtp_matrix(binding, context, MtpRole::KeyNorm)?; - let k = norm_rope(context, &k, &kgamma, kw, geometry.position, false)?; - let result = pack_kv(context, &k, &v)?; + let result = packed_kv(context, binding, input, (geometry.position, cache))?; input.frame().validate(binding, session)?; Ok(result) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs index 1f493edd..e3ee58f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/mtp_attention/release_transport_fn.rs @@ -54,6 +54,75 @@ pub(super) fn upload_transport_f32<'ctx>( } upload_transport(context, &bytes, failed) } +/// The step-local device buffers of one attention launch; each is released explicitly, whatever failed. +#[derive(Default)] +struct AttendBuffers<'ctx> { + q: Option>, + k: Option>, + v: Option>, + y: Option>, +} +impl<'ctx> AttendBuffers<'ctx> { + fn upload_window( + &mut self, + context: &'ctx Context<'ctx>, + (query, keys, values): (&[f32], &[u8], &[u8]), + failed: &Cell, + ) -> Result<()> { + self.q = Some(upload_transport_f32(context, query, failed)?); + self.k = Some(upload_transport(context, keys, failed)?); + self.v = Some(upload_transport(context, values, failed)?); + self.y = Some(allocate(context, Q)?); + Ok(()) + } + fn attend(&mut self, context: &Context<'_>, position: u32) -> Result> { + context + .mtp_dense_attend_f16( + self.q.as_ref().ok_or(Error::CudaExecution)?, + self.k.as_ref().ok_or(Error::CudaExecution)?, + self.v.as_ref().ok_or(Error::CudaExecution)?, + self.y.as_mut().ok_or(Error::CudaExecution)?, + position, + ) + .map_err(attention_driver_error)?; + download(self.y.as_ref().ok_or(Error::CudaExecution)?, Q) + } + fn attend_ring( + &mut self, + context: &'ctx Context<'ctx>, + query: &[f32], + failed: &Cell, + (binding, cache, pending, frame): (&ModelBinding, &MoeWeightCache<'_>, &DenseKv, &MtpFrame), + ) -> Result> { + self.q = Some(upload_transport_f32(context, query, failed)?); + self.y = Some(allocate(context, Q)?); + cache.attend_mtp_kv( + binding, + context, + pending, + frame, + self.q.as_ref().ok_or(Error::CudaExecution)?, + self.y.as_mut().ok_or(Error::CudaExecution)?, + )?; + download(self.y.as_ref().ok_or(Error::CudaExecution)?, Q) + } +} +/// A failed launch or release withholds the readback; the output buffer is still released first-class. +fn finish_retained<'ctx>( + context: &'ctx Context<'ctx>, + (result, cleanup): (Result>, Result<()>), + y: Option>, + failed: Rc>, +) -> Result> { + if result.is_err() || cleanup.is_err() { + let y_cleanup = release_transport([y], &failed); + let _ = result?; + cleanup?; + y_cleanup?; + return Err(Error::CudaExecution); + } + Ok(RetainedAttended { context, buffer: y, values: result?, failed }) +} pub(super) fn attend_retained<'ctx>( context: &'ctx Context<'ctx>, query: &[f32], @@ -68,33 +137,13 @@ pub(super) fn attend_retained<'ctx>( validate_values(query, Q)?; validate_window(keys, values, geometry)?; preflight(context, geometry.device_bytes)?; - let (mut q, mut k, mut v, mut y) = (None, None, None, None); - let result = (|| { - q = Some(upload_transport_f32(context, query, &failed)?); - k = Some(upload_transport(context, keys, &failed)?); - v = Some(upload_transport(context, values, &failed)?); - y = Some(allocate(context, Q)?); - context - .mtp_dense_attend_f16( - q.as_ref().ok_or(Error::CudaExecution)?, - k.as_ref().ok_or(Error::CudaExecution)?, - v.as_ref().ok_or(Error::CudaExecution)?, - y.as_mut().ok_or(Error::CudaExecution)?, - geometry.position, - ) - .map_err(attention_driver_error)?; - download(y.as_ref().ok_or(Error::CudaExecution)?, Q) - })(); + let mut buffers = AttendBuffers::default(); + let result = buffers + .upload_window(context, (query, keys, values), &failed) + .and_then(|()| buffers.attend(context, geometry.position)); note_transport(&result, &failed); - let cleanup = release_transport([q, k, v], &failed); - if result.is_err() || cleanup.is_err() { - let y_cleanup = release_transport([y], &failed); - let _ = result?; - cleanup?; - y_cleanup?; - return Err(Error::CudaExecution); - } - Ok(RetainedAttended { context, buffer: y, values: result?, failed }) + let cleanup = release_transport([buffers.q, buffers.k, buffers.v], &failed); + finish_retained(context, (result, cleanup), buffers.y, failed) } // Numeric query/attend/gate/output remains the existing sequence. Only the // canonical K/V ownership moves to the actor's bounded transport mirror. @@ -114,30 +163,57 @@ pub(super) fn attend_ring_retained<'ctx>( } validate_values(query, Q)?; preflight(context, geometry.device_bytes.checked_sub(2 * geometry.half_bytes).ok_or(Error::Overflow)?)?; - let (mut q, mut y) = (None, None); - let result = (|| { - q = Some(upload_transport_f32(context, query, &failed)?); - y = Some(allocate(context, Q)?); - cache.attend_mtp_kv( - binding, - context, - pending, - frame, - q.as_ref().ok_or(Error::CudaExecution)?, - y.as_mut().ok_or(Error::CudaExecution)?, - )?; - download(y.as_ref().ok_or(Error::CudaExecution)?, Q) - })(); + let mut buffers = AttendBuffers::default(); + let result = buffers.attend_ring(context, query, &failed, (binding, cache, pending, frame)); note_transport(&result, &failed); - let cleanup = release_transport([q], &failed); - if result.is_err() || cleanup.is_err() { - let y_cleanup = release_transport([y], &failed); - let _ = result?; - cleanup?; - y_cleanup?; + let cleanup = release_transport([buffers.q], &failed); + finish_retained(context, (result, cleanup), buffers.y, failed) +} +/// The step-local device buffers of one gate launch. +#[derive(Default)] +struct GateBuffers<'ctx> { + gate: Option>, + gated: Option>, +} +/// The attended buffer, admitted to be this context's, healthy and exactly Q floats. +fn gate_source<'a, 'ctx>( + context: &Context<'_>, + attended: &'a RetainedAttended<'ctx>, + gate: &[f32], +) -> Result<&'a DeviceBuffer<'ctx>> { + if !std::ptr::eq(attended.context, context) { + return Err(Error::IdentityMismatch); + } + if attended.failed.get() { return Err(Error::CudaExecution); } - Ok(RetainedAttended { context, buffer: y, values: result?, failed }) + validate_values(attended.values(), Q)?; + validate_values(gate, Q)?; + let source = attended.buffer.as_ref().ok_or(Error::CudaExecution)?; + if source.len() != Q * 4 { + return Err(Error::InvalidDimension); + } + Ok(source) +} +impl<'ctx> GateBuffers<'ctx> { + fn apply( + &mut self, + context: &'ctx Context<'ctx>, + attended: &RetainedAttended<'ctx>, + gate: &[f32], + ) -> Result> { + let source = gate_source(context, attended, gate)?; + self.gate = Some(upload_transport_f32(context, gate, &attended.failed)?); + self.gated = Some(allocate(context, Q)?); + context + .qsa_gate_f32( + source, + self.gate.as_ref().ok_or(Error::CudaExecution)?, + self.gated.as_mut().ok_or(Error::CudaExecution)?, + ) + .map_err(attention_driver_error)?; + download(self.gated.as_ref().ok_or(Error::CudaExecution)?, Q) + } } pub(super) fn gate_retained<'ctx>( context: &'ctx Context<'ctx>, @@ -145,43 +221,19 @@ pub(super) fn gate_retained<'ctx>( gate: &[f32], ) -> Result> { let failed = Rc::clone(&attended.failed); - let (mut gate_buffer, mut gated) = (None, None); - let result = (|| { - if !std::ptr::eq(attended.context, context) { - return Err(Error::IdentityMismatch); - } - if failed.get() { - return Err(Error::CudaExecution); - } - validate_values(attended.values(), Q)?; - validate_values(gate, Q)?; - let source = attended.buffer.as_ref().ok_or(Error::CudaExecution)?; - if source.len() != Q * 4 { - return Err(Error::InvalidDimension); - } - gate_buffer = Some(upload_transport_f32(context, gate, &failed)?); - gated = Some(allocate(context, Q)?); - context - .qsa_gate_f32( - source, - gate_buffer.as_ref().ok_or(Error::CudaExecution)?, - gated.as_mut().ok_or(Error::CudaExecution)?, - ) - .map_err(attention_driver_error)?; - download(gated.as_ref().ok_or(Error::CudaExecution)?, Q) - })(); + let mut buffers = GateBuffers::default(); + let result = buffers.apply(context, &attended, gate); note_transport(&result, &failed); - let cleanup = release_transport([attended.buffer.take(), gate_buffer], &failed); + let cleanup = release_transport([attended.buffer.take(), buffers.gate], &failed); if result.is_err() || cleanup.is_err() { - let gated_cleanup = release_transport([gated], &failed); + let gated_cleanup = release_transport([buffers.gated], &failed); let _ = result?; cleanup?; gated_cleanup?; return Err(Error::CudaExecution); } - Ok(RetainedGated { context, buffer: gated, values: result?, failed }) + Ok(RetainedGated { context, buffer: buffers.gated, values: result?, failed }) } - pub(super) fn attention_driver_error(error: leleka_cuda_driver::Error) -> Error { match driver_error(error) { Error::Unsupported(_) => Error::Unsupported(Stage::QsaAttention),