From 3d7db082d9d1a890dabfd6cbe23e8043b25c0108 Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Fri, 6 Nov 2026 22:52:17 +0100 Subject: [PATCH] STRA-338 size2 en3: input stage KAR/PLE rows and PLE CUDA step split into phase helpers --- .../src/qwen_forward/input/gather_rows_fn.rs | 48 ++-- .../src/qwen_forward/input/impl_inputstage.rs | 134 +++++---- .../qwen_forward/input/impl_inputstage_2.rs | 223 +++++++++------ .../src/qwen_forward/input/ple_cuda_fn.rs | 270 +++++++++++++----- 4 files changed, 441 insertions(+), 234 deletions(-) diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs index 6899bdbf..8370f110 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/gather_rows_fn.rs @@ -162,6 +162,27 @@ impl PleMicroBatchReady<'_> { prior: &PlePrior, txn: &QwenStepTxn<'_, '_>, ) -> Result { + self.admit_ready(binding, residual, prior, txn)?; + let identity = self.check_ready_source(binding, residual, txn)?; + let row = self.rows.get_mut(self.next).and_then(Option::take).ok_or(Error::IdentityMismatch)?; + ple_values(&row.streams, PLE_HC)?; + let pending = PlePending::new(prior, identity, row.history)?; + // This is the genuine completed causal history, not a final history + // relabelled for an earlier position. Session admits it separately. + self.prior = pending.next.clone(); + self.next += 1; + Ok(PleReady { binding: self.binding.clone(), identity, streams: row.streams, pending: Some(pending) }) + } + pub(in super::super) fn is_consumed(&self) -> bool { + self.next == self.rows.len() && self.rows.iter().all(Option::is_none) + } + fn admit_ready( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + prior: &PlePrior, + txn: &QwenStepTxn<'_, '_>, + ) -> Result<()> { if !self.binding.matches(&binding.identity()) || !self.prior.same_state(prior) || !std::ptr::eq(self.context, txn.cuda_context()?) @@ -172,7 +193,15 @@ impl PleMicroBatchReady<'_> { txn.validate_ple_prior(prior)?; residual.validate_origin(&self.binding, GrRole::Ffn(0))?; let layer0 = LayerId::new(0, Dimension::new(u64::from(binding.layer_count()))?)?; - residual.identity().validate(txn.token(), txn.position(), layer0)?; + residual.identity().validate(txn.token(), txn.position(), layer0) + } + // The next source row is bound to the actual input values of this current transaction; returns its identity. + fn check_ready_source( + &self, + binding: &ModelBinding, + residual: &InjectedResidual, + txn: &QwenStepTxn<'_, '_>, + ) -> Result { let source = self.sources.get(self.next).ok_or(Error::IdentityMismatch)?; let layer1 = LayerId::new(1, Dimension::new(u64::from(binding.layer_count()))?)?; source.identity.validate(txn.token(), txn.position(), layer1)?; @@ -187,22 +216,7 @@ impl PleMicroBatchReady<'_> { { return Err(Error::IdentityMismatch); } - let row = self.rows.get_mut(self.next).and_then(Option::take).ok_or(Error::IdentityMismatch)?; - ple_values(&row.streams, PLE_HC)?; - let pending = PlePending::new(prior, source.identity, row.history)?; - // This is the genuine completed causal history, not a final history - // relabelled for an earlier position. Session admits it separately. - self.prior = pending.next.clone(); - self.next += 1; - Ok(PleReady { - binding: self.binding.clone(), - identity: source.identity, - streams: row.streams, - pending: Some(pending), - }) - } - pub(in super::super) fn is_consumed(&self) -> bool { - self.next == self.rows.len() && self.rows.iter().all(Option::is_none) + Ok(source.identity) } } impl PleReady { diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs index 5e4e45b8..8dccda6f 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage.rs @@ -24,14 +24,7 @@ impl InputStage { pos: Position, txn: &mut QwenStepTxn, ) -> Result { - let kar = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; - if !kar.matches(&binding.identity()) || !cache.context_matches(txn.cuda_context()?) { - return Err(Error::IdentityMismatch); - } - validate_ids(binding.input_constants(), token, pos)?; - txn.validate_binding(&binding.identity())?; - txn.validate_input(token, pos)?; - let rows = hash::rows(token.get(), txn.input_predecessors()?, binding.input_constants())?; + let (kar, rows) = admit_kar_input(binding, cache, token, pos, txn)?; let embedding_span = super::super::prefill_profile::span(super::super::prefill_profile::Stage::InputEmbedding, None); let embedding = binding.embedding_row(token.get()).map_err(binding_error)?; @@ -60,32 +53,10 @@ impl InputStage { txn: &mut QwenStepTxn, staged: &mut StagedInput, ) -> Result { - let kar = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; - if !kar.matches(&binding.identity()) || !cache.context_matches(txn.cuda_context()?) { - return Err(Error::IdentityMismatch); - } - validate_ids(binding.input_constants(), token, pos)?; - txn.validate_binding(&binding.identity())?; - txn.validate_input(token, pos)?; - let rows = hash::rows(token.get(), txn.input_predecessors()?, binding.input_constants())?; + let (_, rows) = admit_kar_input(binding, cache, token, pos, txn)?; let unique = match staged.unique.get(&token.get()) { Some(&u) => u, - None => { - let embedding = binding.embedding_row(token.get()).map_err(binding_error)?; - if embedding.len() != EMBEDDING_VALUES { - return Err(Error::InvalidDimension); - } - if embedding.iter().any(|v| !v.is_finite()) { - return Err(Error::NonFinite); - } - let u = u32::try_from(staged.unique.len()).map_err(|_| Error::Overflow)?; - staged.embedding_bytes.try_reserve(EMBEDDING_VALUES * 4).map_err(|_| Error::InputAllocation)?; - for v in embedding.iter() { - staged.embedding_bytes.extend_from_slice(&v.to_le_bytes()); - } - staged.unique.insert(token.get(), u); - u - } + None => stage_new_embedding(binding, staged, token)?, }; staged.index.push(unique); staged.rows.push(rows); @@ -135,29 +106,7 @@ impl InputStage { out.try_reserve_exact(tokens.len() * EMBEDDING_VALUES).map_err(|_| Error::InputAllocation)?; let mut before = predecessors; for &token in tokens { - if !(0..VOCABULARY as i32).contains(&token) { - return Err(Error::InvalidToken); - } - let rows = hash::rows(token as u32, before, binding.input_constants())?; - if trace_ple() { - eprintln!("DBG ple token={token} before={before:?} rows={rows:?}"); - } - let gathered = match (binding.kar_ple_binding(), kar.as_deref_mut()) { - (Some(provider), Some(cache)) => { - if !provider.matches(&binding.identity()) || !cache.context_matches(context) { - return Err(Error::IdentityMismatch); - } - cache.gather(provider, &rows)? - } - (None, None) => { - let pending = binding.ple_issue(&rows).map_err(|e| Error::from(InputError::Binding(e)))?; - gather_ple(binding, &rows, pending).map_err(Error::from)? - } - _ => return Err(Error::IdentityMismatch), - }; - if gathered.len() != EMBEDDING_VALUES { - return Err(Error::InvalidDimension); - } + let gathered = window_ple_row(binding, kar.as_deref_mut(), context, (token, before))?; out.extend_from_slice(&gathered); before = [before[1], token]; } @@ -191,6 +140,81 @@ impl InputStage { }) } } +// The KAR binding, the identity/transaction checks and the sixteen PLE rows of one input token. +fn admit_kar_input<'b>( + binding: &'b ModelBinding, + cache: &kar_cache::KarPleCache<'_>, + token: TokenId, + pos: Position, + txn: &QwenStepTxn, +) -> Result<(&'b crate::model_binding::qwen4exp_kar_ple::KarPleBinding, [u64; 16])> { + let kar = binding.kar_ple_binding().ok_or(Error::IdentityMismatch)?; + if !kar.matches(&binding.identity()) || !cache.context_matches(txn.cuda_context()?) { + return Err(Error::IdentityMismatch); + } + validate_ids(binding.input_constants(), token, pos)?; + txn.validate_binding(&binding.identity())?; + txn.validate_input(token, pos)?; + let rows = hash::rows(token.get(), txn.input_predecessors()?, binding.input_constants())?; + Ok((kar, rows)) +} +// First sight of a token in this chunk: its finite embedding row joins the staged bytes. +fn stage_new_embedding(binding: &ModelBinding, staged: &mut StagedInput, token: TokenId) -> Result { + let embedding = binding.embedding_row(token.get()).map_err(binding_error)?; + if embedding.len() != EMBEDDING_VALUES { + return Err(Error::InvalidDimension); + } + if embedding.iter().any(|v| !v.is_finite()) { + return Err(Error::NonFinite); + } + let u = u32::try_from(staged.unique.len()).map_err(|_| Error::Overflow)?; + staged.embedding_bytes.try_reserve(EMBEDDING_VALUES * 4).map_err(|_| Error::InputAllocation)?; + for v in embedding.iter() { + staged.embedding_bytes.extend_from_slice(&v.to_le_bytes()); + } + staged.unique.insert(token.get(), u); + Ok(u) +} +// The PLE row of one window token from the model's own provider. +fn window_ple_row( + binding: &ModelBinding, + kar: Option<&mut kar_cache::KarPleCache<'_>>, + context: &Context<'_>, + (token, before): (i32, [i32; 2]), +) -> Result> { + if !(0..VOCABULARY as i32).contains(&token) { + return Err(Error::InvalidToken); + } + let rows = hash::rows(token as u32, before, binding.input_constants())?; + if trace_ple() { + eprintln!("DBG ple token={token} before={before:?} rows={rows:?}"); + } + let gathered = gather_window_rows(binding, kar, context, &rows)?; + if gathered.len() != EMBEDDING_VALUES { + return Err(Error::InvalidDimension); + } + Ok(gathered) +} +fn gather_window_rows( + binding: &ModelBinding, + kar: Option<&mut kar_cache::KarPleCache<'_>>, + context: &Context<'_>, + rows: &[u64; 16], +) -> Result> { + match (binding.kar_ple_binding(), kar) { + (Some(provider), Some(cache)) => { + if !provider.matches(&binding.identity()) || !cache.context_matches(context) { + return Err(Error::IdentityMismatch); + } + cache.gather(provider, rows) + } + (None, None) => { + let pending = binding.ple_issue(rows).map_err(|e| Error::from(InputError::Binding(e)))?; + gather_ple(binding, rows, pending).map_err(Error::from) + } + _ => Err(Error::IdentityMismatch), + } +} /// `LELEKA_TRACE_PLE`, read once (it sat on the per-token path of every window). pub(super) fn trace_ple() -> bool { crate::settings::process().diagnostics.trace_ple diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs index b9392937..35aca661 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/impl_inputstage_2.rs @@ -53,49 +53,8 @@ impl InputStage { return Err(Error::IdentityMismatch); } ple_values(&prior.0.history, PLE_HISTORY)?; - let mut embedding = Vec::new(); - let mut streams = Vec::new(); - embedding.try_reserve_exact(sources.len() * 2560).map_err(|_| Error::InputAllocation)?; - streams.try_reserve_exact(sources.len() * PLE_HC).map_err(|_| Error::InputAllocation)?; - for (row, source) in sources.iter().enumerate() { - if !source.binding.matches(&binding.identity()) - || source.identity.layer().get() != 1 - || source.identity.position().get() - != prior.next_position().checked_add(row as u64).ok_or(Error::Overflow)? - { - return Err(Error::IdentityMismatch); - } - ple_values(&source.embedding, 2560)?; - ple_values(&source.streams, PLE_HC)?; - embedding.extend_from_slice(&source.embedding); - streams.extend_from_slice(&source.streams); - } - let result = (|| { - let mut queue = cache.ple_batch_queue(binding, context)?.ok_or(Error::IdentityMismatch)?; - let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; - let weights = leleka_cuda_driver::PleClosedWeights { - key: cache.ple_key(entry)?, - value: cache.ple_value(entry)?, - aux: cache.ple_aux(entry)?, - }; - let mut completed = queue - .compose(&mut workspace, weights, &embedding, &streams, &prior.0.history) - .map_err(ple_driver_error)?; - if completed.rows() != sources.len() { - return Err(Error::IdentityMismatch); - } - if completed.numerical_refusal().is_some() { - return Err(Error::NonFinite); - } - let mut rows = Vec::new(); - rows.try_reserve_exact(sources.len()).map_err(|_| Error::InputAllocation)?; - for row in 0..sources.len() { - rows.push(Some(completed.take_row(row).map_err(ple_driver_error)?.ok_or(Error::NonFinite)?)); - } - // Completed owner and both exclusive RefMut loans end here before - // GR borrows the same model-lifetime vendor workspace. - Ok(rows) - })(); + let (embedding, streams) = collect_micro_ple_inputs(binding, &prior, &sources)?; + let result = compose_micro_rows(cache, (binding, context, entry), (&embedding, &streams), (&prior, &sources)); if matches!(result, Err(Error::CudaExecution)) { failed.set(true); } @@ -118,48 +77,69 @@ impl InputStage { txn: &mut QwenStepTxn, cache: Option<&DenseWeightCache<'_>>, ) -> Result { - txn.validate_binding(&binding.identity())?; - residual.validate_origin(&binding.identity(), GrRole::Ffn(0))?; - let layer0 = LayerId::new(0, Dimension::new(u64::from(binding.layer_count()))?)?; - residual.identity().validate(txn.token(), txn.position(), layer0)?; - txn.validate_ple_prior(prior)?; - let input = txn.input()?; - txn.validate_binding(input.binding_identity())?; - txn.validate_input(input.token(), input.position())?; - ple_values(input.ple_embedding(), 2560)?; - ple_values(residual.streams(), PLE_HC)?; - ple_values(&prior.0.history, PLE_HISTORY)?; + check_ple_origin(binding, residual, prior, txn)?; + let input = check_ple_input(residual, prior, txn)?; let context = txn.cuda_context()?; ple_budget(context)?; - let resident = cache.map(|c| c.ple(binding, context)).transpose()?; - let weights = match resident { - Some(entry) => entry.weights.clone(), - None => Rc::new(binding.ple_weights().map_err(binding_error)?), - }; - if !weights.matches(&binding.identity()) { - return Err(Error::IdentityMismatch); - } + let (resident, weights) = resolve_ple_weights(binding, cache, context)?; let layer1 = LayerId::new(1, Dimension::new(u64::from(binding.layer_count()))?)?; let identity = TokenLayer::new(txn.token(), txn.position(), layer1); - let candidate = if let Some((cache, entry)) = cache.zip(resident) { - ple_cuda_cached( - context, - binding, - &weights, - entry, - cache, - input.ple_embedding(), - residual.streams(), - &prior.0.history, - identity, - )? - } else { - ple_cuda(context, binding, &weights, input.ple_embedding(), residual.streams(), &prior.0.history, None)? - }; + let inputs = (input.ple_embedding(), residual.streams(), &prior.0.history[..]); + let candidate = ple_candidate(context, (binding, &weights), cache.zip(resident), inputs, identity)?; let pending = PlePending::new(prior, identity, candidate.history)?; Ok(PleReady { binding: binding.identity(), identity, streams: candidate.streams, pending: Some(pending) }) } } +fn ple_candidate( + context: &Context<'_>, + (binding, weights): (&ModelBinding, &Rc), + cached: Option<(&DenseWeightCache<'_>, &PleResident)>, + (embedding, streams, history): (&[f32], &[f32], &[f32]), + identity: TokenLayer, +) -> Result { + if let Some((cache, entry)) = cached { + ple_cuda_cached(context, binding, weights, entry, cache, embedding, streams, history, identity) + } else { + ple_cuda(context, binding, weights, embedding, streams, history, None) + } +} +fn check_ple_origin( + binding: &ModelBinding, + residual: &InjectedResidual, + prior: &PlePrior, + txn: &QwenStepTxn, +) -> Result<()> { + txn.validate_binding(&binding.identity())?; + residual.validate_origin(&binding.identity(), GrRole::Ffn(0))?; + let layer0 = LayerId::new(0, Dimension::new(u64::from(binding.layer_count()))?)?; + residual.identity().validate(txn.token(), txn.position(), layer0)?; + txn.validate_ple_prior(prior) +} +fn check_ple_input(residual: &InjectedResidual, prior: &PlePrior, txn: &QwenStepTxn) -> Result> { + let input = txn.input()?; + txn.validate_binding(input.binding_identity())?; + txn.validate_input(input.token(), input.position())?; + ple_values(input.ple_embedding(), 2560)?; + ple_values(residual.streams(), PLE_HC)?; + ple_values(&prior.0.history, PLE_HISTORY)?; + Ok(input) +} +// The resident PLE entry when there is a cache, and the weights it (or the binding) provides. +fn resolve_ple_weights<'c>( + binding: &ModelBinding, + cache: Option<&'c DenseWeightCache<'_>>, + context: &Context<'_>, +) -> Result<(Option<&'c PleResident>, Rc)> { + let resident = cache.map(|c| c.ple(binding, context)).transpose()?; + let weights = match resident { + Some(entry) => entry.weights.clone(), + None => Rc::new(binding.ple_weights().map_err(binding_error)?), + }; + if !weights.matches(&binding.identity()) { + return Err(Error::IdentityMismatch); + } + Ok((resident, weights)) +} #[allow(clippy::too_many_arguments)] pub(super) fn ple_cuda_cached( context: &Context<'_>, @@ -172,8 +152,24 @@ pub(super) fn ple_cuda_cached( history: &[f32], identity: TokenLayer, ) -> Result { - // Serving admits only the existing verified resident for this invocation. - // No actual numeric owner crosses this call or enters a checkpoint. + check_cached_ple(cache, context, (binding, weights, entry), identity)?; + let context = cache.retained_context(binding, context)?; + let failed = cache.transport_failure_flag(binding, context)?; + let candidate = compose_cached_ple(cache, (binding, context, entry), (embedding, streams, history), failed)?; + cache.validate(binding)?; + if !weights.matches(&binding.identity()) || !Rc::ptr_eq(weights, &entry.weights) { + return Err(Error::IdentityMismatch); + } + Ok(candidate) +} +// Serving admits only the existing verified resident for this invocation. +// No actual numeric owner crosses this call or enters a checkpoint. +fn check_cached_ple( + cache: &DenseWeightCache<'_>, + context: &Context<'_>, + (binding, weights, entry): (&ModelBinding, &Rc, &PleResident), + identity: TokenLayer, +) -> Result<()> { cache.validate(binding)?; let retained = cache.ple(binding, context)?; if !std::ptr::eq(entry, retained) @@ -183,8 +179,14 @@ pub(super) fn ple_cuda_cached( { return Err(Error::IdentityMismatch); } - let context = cache.retained_context(binding, context)?; - let failed = cache.transport_failure_flag(binding, context)?; + Ok(()) +} +fn compose_cached_ple( + cache: &DenseWeightCache<'_>, + (binding, context, entry): (&ModelBinding, &Context<'_>, &PleResident), + (embedding, streams, history): (&[f32], &[f32], &[f32]), + failed: Rc>, +) -> Result { let key = cache.ple_key(entry)?; let value = cache.ple_value(entry)?; let aux = cache.ple_aux(entry)?; @@ -196,10 +198,61 @@ pub(super) fn ple_cuda_cached( }; #[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))] let result = ple_transport::compose(context, key, value, aux, embedding, streams, history, failed); - let candidate = result?; - cache.validate(binding)?; - if !weights.matches(&binding.identity()) || !Rc::ptr_eq(weights, &entry.weights) { + result +} +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn collect_micro_ple_inputs( + binding: &ModelBinding, + prior: &PlePrior, + sources: &[PleMicroInput], +) -> Result<(Vec, Vec)> { + let mut embedding = Vec::new(); + let mut streams = Vec::new(); + embedding.try_reserve_exact(sources.len() * 2560).map_err(|_| Error::InputAllocation)?; + streams.try_reserve_exact(sources.len() * PLE_HC).map_err(|_| Error::InputAllocation)?; + for (row, source) in sources.iter().enumerate() { + if !source.binding.matches(&binding.identity()) + || source.identity.layer().get() != 1 + || source.identity.position().get() + != prior.next_position().checked_add(row as u64).ok_or(Error::Overflow)? + { + return Err(Error::IdentityMismatch); + } + ple_values(&source.embedding, 2560)?; + ple_values(&source.streams, PLE_HC)?; + embedding.extend_from_slice(&source.embedding); + streams.extend_from_slice(&source.streams); + } + Ok((embedding, streams)) +} +#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] +fn compose_micro_rows( + cache: &DenseWeightCache<'_>, + (binding, context, entry): (&ModelBinding, &Context<'_>, &PleResident), + (embedding, streams): (&[f32], &[f32]), + (prior, sources): (&PlePrior, &[PleMicroInput]), +) -> Result>> { + let mut queue = cache.ple_batch_queue(binding, context)?.ok_or(Error::IdentityMismatch)?; + let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?; + let weights = leleka_cuda_driver::PleClosedWeights { + key: cache.ple_key(entry)?, + value: cache.ple_value(entry)?, + aux: cache.ple_aux(entry)?, + }; + let mut completed = + queue.compose(&mut workspace, weights, embedding, streams, &prior.0.history).map_err(ple_driver_error)?; + if completed.rows() != sources.len() { return Err(Error::IdentityMismatch); } - Ok(candidate) + if completed.numerical_refusal().is_some() { + return Err(Error::NonFinite); + } + let mut rows = Vec::new(); + rows.try_reserve_exact(sources.len()).map_err(|_| Error::InputAllocation)?; + for row in 0..sources.len() { + rows.push(Some(completed.take_row(row).map_err(ple_driver_error)?.ok_or(Error::NonFinite)?)); + } + // Completed owner and both exclusive RefMut loans end here before + // GR borrows the same model-lifetime vendor workspace. + Ok(rows) } diff --git a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs index 4c582196..91e287f0 100644 --- a/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs +++ b/crates/engine-qwen35-cuda/src/qwen_forward/input/ple_cuda_fn.rs @@ -16,51 +16,151 @@ pub(super) fn ple_cuda( let key_values = ple_project(context, binding, weights, PleMatrixRole::Key, &emb, resident)?; let value_values = ple_project(context, binding, weights, PleMatrixRole::Value, &emb, resident)?; emb.release().map_err(ple_driver_error)?; - let raw_key = ple_upload_f32(context, &key_values)?; - let value = ple_upload_f32(context, &value_values)?; - let residual = ple_upload_f32(context, streams)?; - let prior = ple_upload_f32(context, history)?; + let uploads = PleUploads::upload(context, (&key_values, &value_values), streams, history)?; let aux = resident.map(|(c, r)| c.ple_aux(r)).transpose()?; - let norm_key_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_key())?) } else { None }; - let norm_query_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_query())?) } else { None }; - let norm_conv_owned = if aux.is_none() { Some(ple_upload_f32(context, weights.norm_conv())?) } else { None }; - let conv_owned = if aux.is_none() { Some(ple_upload_u16(context, weights.conv())?) } else { None }; - let norm_key = aux.map(|v| v[0]).or(norm_key_owned.as_ref()).ok_or(Error::IdentityMismatch)?; - let norm_query = aux.map(|v| v[1]).or(norm_query_owned.as_ref()).ok_or(Error::IdentityMismatch)?; - let norm_conv = aux.map(|v| v[2]).or(norm_conv_owned.as_ref()).ok_or(Error::IdentityMismatch)?; - let conv_weights = aux.map(|v| v[3]).or(conv_owned.as_ref()).ok_or(Error::IdentityMismatch)?; - let mut key = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut query = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut gate = context.allocate(16).map_err(ple_driver_error)?; - let mut gated = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut normalized = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut conv = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut result = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let mut next = context.allocate(PLE_HISTORY * 4).map_err(ple_driver_error)?; - context.ple_grouped_norm_f32(&raw_key, norm_key, &mut key).map_err(ple_driver_error)?; - let _ = ple_download(&key, PLE_HC)?; - context.ple_grouped_norm_f32(&residual, norm_query, &mut query).map_err(ple_driver_error)?; - let _ = ple_download(&query, PLE_HC)?; - context.ple_signed_gate_f32(&key, &query, &mut gate).map_err(ple_driver_error)?; - let _ = ple_download(&gate, 4)?; - context.ple_broadcast_f32(&value, &gate, &mut gated).map_err(ple_driver_error)?; - let _ = ple_download(&gated, PLE_HC)?; - context.ple_grouped_norm_f32(&gated, norm_conv, &mut normalized).map_err(ple_driver_error)?; - let _ = ple_download(&normalized, PLE_HC)?; - context.ple_conv_history_f32(&prior, &normalized, conv_weights, &mut conv, &mut next).map_err(ple_driver_error)?; - let _ = ple_download(&conv, PLE_HC)?; - let next_values = ple_download(&next, PLE_HISTORY)?; - context.ple_residual_f32(&residual, &gated, &conv, &mut result).map_err(ple_driver_error)?; - let result_values = ple_download(&result, PLE_HC)?; + let owned = OwnedPleAux::upload(context, weights, aux.is_none())?; + let norms = owned.select(aux)?; + let mut work = PleWork::allocate(context)?; + let (result_values, next_values) = work.run(context, &uploads, norms)?; // No candidate can escape until fallible owned resource release succeeds. - for buffer in [next, result, conv, normalized, gated, gate, query, key, prior, residual, value, raw_key] { - buffer.release().map_err(ple_driver_error)?; - } - for buffer in [conv_owned, norm_conv_owned, norm_query_owned, norm_key_owned].into_iter().flatten() { - buffer.release().map_err(ple_driver_error)?; - } + work.release(uploads)?; + owned.release()?; Ok(PleCandidate { streams: result_values, history: next_values }) } + +// The device copies of the projected key/value and the residual streams and history of one PLE step. +struct PleUploads<'c> { + raw_key: DeviceBuffer<'c>, + value: DeviceBuffer<'c>, + residual: DeviceBuffer<'c>, + prior: DeviceBuffer<'c>, +} +impl<'c> PleUploads<'c> { + fn upload( + context: &'c Context<'_>, + (key_values, value_values): (&[f32], &[f32]), + streams: &[f32], + history: &[f32], + ) -> Result { + let raw_key = ple_upload_f32(context, key_values)?; + let value = ple_upload_f32(context, value_values)?; + let residual = ple_upload_f32(context, streams)?; + let prior = ple_upload_f32(context, history)?; + Ok(Self { raw_key, value, residual, prior }) + } +} +// The norm and convolution weights uploaded for this step when no resident copy exists. +struct OwnedPleAux<'c> { + norm_key: Option>, + norm_query: Option>, + norm_conv: Option>, + conv: Option>, +} +impl<'c> OwnedPleAux<'c> { + fn upload(context: &'c Context<'_>, weights: &PleWeights, upload: bool) -> Result { + let norm_key = if upload { Some(ple_upload_f32(context, weights.norm_key())?) } else { None }; + let norm_query = if upload { Some(ple_upload_f32(context, weights.norm_query())?) } else { None }; + let norm_conv = if upload { Some(ple_upload_f32(context, weights.norm_conv())?) } else { None }; + let conv = if upload { Some(ple_upload_u16(context, weights.conv())?) } else { None }; + Ok(Self { norm_key, norm_query, norm_conv, conv }) + } + // The resident matrix when there is one, else the uploaded copy. + fn select<'a>(&'a self, aux: Option<[&'a DeviceBuffer<'a>; 4]>) -> Result<[&'a DeviceBuffer<'a>; 4]> { + let norm_key = aux.map(|v| v[0]).or(self.norm_key.as_ref()).ok_or(Error::IdentityMismatch)?; + let norm_query = aux.map(|v| v[1]).or(self.norm_query.as_ref()).ok_or(Error::IdentityMismatch)?; + let norm_conv = aux.map(|v| v[2]).or(self.norm_conv.as_ref()).ok_or(Error::IdentityMismatch)?; + let conv_weights = aux.map(|v| v[3]).or(self.conv.as_ref()).ok_or(Error::IdentityMismatch)?; + Ok([norm_key, norm_query, norm_conv, conv_weights]) + } + fn release(self) -> Result<()> { + for buffer in [self.conv, self.norm_conv, self.norm_query, self.norm_key].into_iter().flatten() { + buffer.release().map_err(ple_driver_error)?; + } + Ok(()) + } +} +// The eight device outputs of the PLE step. +struct PleWork<'c> { + key: DeviceBuffer<'c>, + query: DeviceBuffer<'c>, + gate: DeviceBuffer<'c>, + gated: DeviceBuffer<'c>, + normalized: DeviceBuffer<'c>, + conv: DeviceBuffer<'c>, + result: DeviceBuffer<'c>, + next: DeviceBuffer<'c>, +} +impl<'c> PleWork<'c> { + fn allocate(context: &'c Context<'_>) -> Result { + let key = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let query = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let gate = context.allocate(16).map_err(ple_driver_error)?; + let gated = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let normalized = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let conv = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let result = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let next = context.allocate(PLE_HISTORY * 4).map_err(ple_driver_error)?; + Ok(Self { key, query, gate, gated, normalized, conv, result, next }) + } + // Returns the finite host copies of the updated streams and history. + fn run( + &mut self, + context: &Context<'_>, + uploads: &PleUploads<'_>, + [norm_key, norm_query, norm_conv, conv_weights]: [&DeviceBuffer<'_>; 4], + ) -> Result<(Box<[f32]>, Box<[f32]>)> { + self.run_gate(context, uploads, (norm_key, norm_query))?; + context.ple_grouped_norm_f32(&self.gated, norm_conv, &mut self.normalized).map_err(ple_driver_error)?; + let _ = ple_download(&self.normalized, PLE_HC)?; + context + .ple_conv_history_f32(&uploads.prior, &self.normalized, conv_weights, &mut self.conv, &mut self.next) + .map_err(ple_driver_error)?; + let _ = ple_download(&self.conv, PLE_HC)?; + let next_values = ple_download(&self.next, PLE_HISTORY)?; + context + .ple_residual_f32(&uploads.residual, &self.gated, &self.conv, &mut self.result) + .map_err(ple_driver_error)?; + let result_values = ple_download(&self.result, PLE_HC)?; + Ok((result_values, next_values)) + } + // The key/query norms, the signed gate and the broadcast, each read back and finite-checked in order. + fn run_gate( + &mut self, + context: &Context<'_>, + uploads: &PleUploads<'_>, + (norm_key, norm_query): (&DeviceBuffer<'_>, &DeviceBuffer<'_>), + ) -> Result<()> { + context.ple_grouped_norm_f32(&uploads.raw_key, norm_key, &mut self.key).map_err(ple_driver_error)?; + let _ = ple_download(&self.key, PLE_HC)?; + context.ple_grouped_norm_f32(&uploads.residual, norm_query, &mut self.query).map_err(ple_driver_error)?; + let _ = ple_download(&self.query, PLE_HC)?; + context.ple_signed_gate_f32(&self.key, &self.query, &mut self.gate).map_err(ple_driver_error)?; + let _ = ple_download(&self.gate, 4)?; + context.ple_broadcast_f32(&uploads.value, &self.gate, &mut self.gated).map_err(ple_driver_error)?; + let _ = ple_download(&self.gated, PLE_HC)?; + Ok(()) + } + fn release(self, uploads: PleUploads<'c>) -> Result<()> { + let buffers = [ + self.next, + self.result, + self.conv, + self.normalized, + self.gated, + self.gate, + self.query, + self.key, + uploads.prior, + uploads.residual, + uploads.value, + uploads.raw_key, + ]; + for buffer in buffers { + buffer.release().map_err(ple_driver_error)?; + } + Ok(()) + } +} pub(super) fn ple_project( context: &Context<'_>, binding: &ModelBinding, @@ -72,22 +172,7 @@ pub(super) fn ple_project( if role == PleMatrixRole::Key && let Some((cache, entry)) = resident { - // Same fixed columns select the original per-row reduction. The full - // readback must be finite before any downstream PLE state is built. - let matrix = cache.ple_key(entry)?; - let mut output = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; - let result = (|| { - context - .bf16_f32(matrix, embedding, &mut output, Bf16ProjectionShape { rows: PLE_HC, columns: 2560 }) - .map_err(ple_driver_error)?; - ple_download(&output, PLE_HC) - })(); - // Attempt release even after projection/readback refusal, preserving - // the primary error and withholding success if cleanup fails. - let close = output.release().map_err(ple_driver_error); - let values = result?; - close?; - return Ok(values); + return project_resident_key(context, cache.ple_key(entry)?, embedding); } let rows = if role == PleMatrixRole::Key { PLE_HC } else { 2560 }; let mut values = Vec::new(); @@ -96,30 +181,61 @@ pub(super) fn ple_project( // per projection instead of allocating and freeing it for every tile. let mut output = context.allocate(64 * 4).map_err(ple_driver_error)?; for first in (0..rows).step_by(64) { - let owned; - let matrix = if let Some((cache, entry)) = resident { - owned = None; - cache.ple_value_tile(entry, first)? - } else { - let block = binding.ple_matrix_block(weights, role, first, 64).map_err(binding_error)?; - if block.rows() != 64 || block.bytes().len() != 64 * 2560 * 2 { - return Err(Error::InvalidDimension); - } - owned = Some(ple_upload(context, block.bytes())?); - owned.as_ref().ok_or(Error::IdentityMismatch)? - }; - context - .bf16_f32(matrix, embedding, &mut output, Bf16ProjectionShape { rows: 64, columns: 2560 }) - .map_err(ple_driver_error)?; - let decoded = ple_download(&output, 64)?; - values.extend_from_slice(&decoded); - if let Some(matrix) = owned { - matrix.release().map_err(ple_driver_error)?; - } + project_tile(context, (binding, weights, role), (embedding, resident), first, (&mut output, &mut values))?; } output.release().map_err(ple_driver_error)?; Ok(values.into_boxed_slice()) } +// Same fixed columns select the original per-row reduction. The full +// readback must be finite before any downstream PLE state is built. +fn project_resident_key( + context: &Context<'_>, + matrix: &DeviceBuffer<'_>, + embedding: &DeviceBuffer<'_>, +) -> Result> { + let mut output = context.allocate(PLE_HC * 4).map_err(ple_driver_error)?; + let result = (|| { + context + .bf16_f32(matrix, embedding, &mut output, Bf16ProjectionShape { rows: PLE_HC, columns: 2560 }) + .map_err(ple_driver_error)?; + ple_download(&output, PLE_HC) + })(); + // Attempt release even after projection/readback refusal, preserving + // the primary error and withholding success if cleanup fails. + let close = output.release().map_err(ple_driver_error); + let values = result?; + close?; + Ok(values) +} +fn project_tile( + context: &Context<'_>, + (binding, weights, role): (&ModelBinding, &PleWeights, PleMatrixRole), + (embedding, resident): (&DeviceBuffer<'_>, Option<(&DenseWeightCache<'_>, &PleResident)>), + first: usize, + (output, values): (&mut DeviceBuffer<'_>, &mut Vec), +) -> Result<()> { + let owned; + let matrix = if let Some((cache, entry)) = resident { + owned = None; + cache.ple_value_tile(entry, first)? + } else { + let block = binding.ple_matrix_block(weights, role, first, 64).map_err(binding_error)?; + if block.rows() != 64 || block.bytes().len() != 64 * 2560 * 2 { + return Err(Error::InvalidDimension); + } + owned = Some(ple_upload(context, block.bytes())?); + owned.as_ref().ok_or(Error::IdentityMismatch)? + }; + context + .bf16_f32(matrix, embedding, output, Bf16ProjectionShape { rows: 64, columns: 2560 }) + .map_err(ple_driver_error)?; + let decoded = ple_download(output, 64)?; + values.extend_from_slice(&decoded); + if let Some(matrix) = owned { + matrix.release().map_err(ple_driver_error)?; + } + Ok(()) +} pub(super) fn ple_budget(context: &Context<'_>) -> Result<()> { if context.allocated_bytes().checked_add(PLE_DEVICE_PEAK).is_none_or(|n| n > context.budget_bytes()) { return Err(Error::InputAllocation);