Merge branch 'claude/hexagonal-finish-14ee3a' into claude/par-r04

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:38:36 +01:00
63 changed files with 917 additions and 811 deletions
@@ -1,6 +1,7 @@
//! The four PUBLIC candidate proofs: they differ in the caches they load, in what they generate and in what
//! they conclude; the owner, the teardown and the artifacts are shared (`native_down_pair_run.rs`).
use super::*;
use crate::qwen_forward::moe_expert::LoadedArms;
use crate::qwen_forward::moe_weight_cache::LearnedMainWitness;
use fivecase_runtime::FiveCaseReport;
@@ -107,15 +108,16 @@ impl Proof for DirectDown {
// Only the changed direct Down proof shares this model load.
// The unchanged, previously qualified GDN helper is not repeated.
let mut session = QwenSession::for_binding_on_shared_device(run.binding, Rc::clone(run.context));
let down = QwenForward::test_direct_down_on_loaded(
run.binding,
run.context,
&mut session,
&mut owner.kar,
&mut owner.moe,
&owner.dense,
)
.expect("actual original-first direct Down packet proof failed");
let arms = LoadedArms {
binding: run.binding,
context: run.context,
session: &mut session,
kar: &mut owner.kar,
cache: &mut owner.moe,
dense: &owner.dense,
};
let down = QwenForward::test_direct_down_on_loaded(arms)
.expect("actual original-first direct Down packet proof failed");
drop(session);
let execution = EvaluationExecution::ExperimentalNativeIntegerIq3Windowed256RetainedGr;
let arm = owner.armed_inputs(run).arm(&run.case.req, &run.case.ids, execution, DIRECT_PHASE);
@@ -1,6 +1,7 @@
//! Private sole new changed-path model gate; actual source identity/load preserved.
use super::combined_changed_boundary_proof::rig::{DEVICE_BUDGET, Owners, bind_pinned, require_opt_in};
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use std::{env, panic::resume_unwind};
fn required_path(name: &str) -> PathBuf {
@@ -67,7 +68,9 @@ fn pinned_single_load_native_resident_mmq_model_numeric() {
let device = driver.device(0).expect("prefix CUDA device0 unavailable");
let context = Rc::new(device.create_context(DEVICE_BUDGET).expect("bounded prefix Context unavailable"));
let mut owners = Owners::load(&binding, context.as_ref(), (native_resident_mmq, NATIVE_MOE_REFUSAL));
let numerical = owners.run(&binding, &context, QwenForward::test_native_mmq_on_loaded);
let numerical = owners.run(&binding, &context, |binding, session, output, kar, moe, dense| {
QwenForward::test_native_mmq_on_loaded(LoadedTargetOwners { binding, session, output, kar, moe, dense })
});
let mut teardown = owners.close(true);
teardown.close_context(context);
drop((binding, inherited));
@@ -10,6 +10,8 @@ use std::{
panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};
use crate::qwen_forward::oracle_capture::Caches;
fn required_path(name: &str) -> PathBuf {
env::var_os(name).map(PathBuf::from).expect("missing operator-owned prefix test path")
}
@@ -17,13 +19,12 @@ fn required_path(name: &str) -> PathBuf {
/// Capture of two tokens on a fresh owner, then the observation cleanup.
fn capture_two<'d>(binding: &ModelBinding, context: &Rc<leleka_cuda_driver::Context<'d>>, owners: &mut Owners<'d>) {
let mut captured = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let caches = Caches { cache: &mut owners.kar, moe: &mut owners.moe, dense: &owners.dense };
let capture = crate::qwen_forward::oracle_capture::check_on_loaded(
binding,
&mut captured,
&owners.output,
&mut owners.kar,
&mut owners.moe,
&owners.dense,
caches,
required_path("LELEKA_STRA169_CAPTURE_DIR"),
);
let disabled = crate::qwen_forward::oracle_capture::disable(&owners.output);
@@ -20,6 +20,13 @@ enum WeightSource {
Pinned,
RtDirectory,
}
/// The native MTP head and the optional gathered draft-vocabulary head that the full forward chooses between.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct MtpHeadSources<'a, 'ctx> {
pub(in crate::qwen_forward) native: &'a OriginalMtpNativeHead<'ctx>,
pub(in crate::qwen_forward) draft: Option<&'a leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
}
/// Clones share the same device allocations (`Rc`); no buffer is duplicated.
#[derive(Clone)]
pub(in crate::qwen_forward) struct RetainedOriginalMtpWeights<'ctx> {
@@ -186,20 +186,20 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
/// Exact full MTP forward role order. The caller lends the model-affine
/// native-head allocation from `OriginalNativeOutput::mtp_head`; this
/// cache never fabricates a replacement head buffer or dispatch profile.
#[allow(clippy::too_many_arguments)]
/// The id vocabulary is the native head's own vocabulary.
pub(in crate::qwen_forward) fn full_forward_weights(
&self,
binding: &ModelBinding,
context: &'ctx Context<'ctx>,
prefix: Rc<leleka_cuda_driver::OriginalMtpRetainedPrefix<'ctx>>,
head: &OriginalMtpNativeHead<'ctx>,
id_vocab: usize,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
heads: MtpHeadSources<'_, 'ctx>,
) -> Result<Rc<leleka_cuda_driver::OriginalMtpRetainedFullWeights<'ctx>>> {
let head = heads.native;
let id_vocab = head.vocabulary();
self.admit_full_forward(binding, context, head, id_vocab)?;
let roles = self.acquire_roles(binding, context, FULL_FORWARD_ROLES)?;
let experts = self.expert_bank(binding, context)?;
let (head_weights, head_rows, subset) = Self::select_head(head, draft_head);
let (head_weights, head_rows, subset) = Self::select_head(heads);
let weights = FullWeights::retain(
context,
prefix,
@@ -231,13 +231,10 @@ impl<'ctx> RetainedOriginalMtpWeights<'ctx> {
}
Ok(())
}
fn select_head(
head: &OriginalMtpNativeHead<'ctx>,
draft_head: Option<&leleka_cuda_driver::OriginalMtpDraftHead<'ctx>>,
) -> HeadBinding<'ctx> {
match draft_head {
fn select_head(heads: MtpHeadSources<'_, 'ctx>) -> HeadBinding<'ctx> {
match heads.draft {
Some(draft) => (draft.rows(), draft.count(), Some(draft.subset_pair())),
None => (head.weights(), head.vocabulary(), None),
None => (heads.native.weights(), heads.native.vocabulary(), None),
}
}
pub(in crate::qwen_forward) fn metadata_bytes(&self) -> Result<usize> {
@@ -40,6 +40,7 @@ pub(crate) struct DenseCacheCounters {
}
/// What a resident-key selection scores: the candidate prior whose keys are searched, the index query vector and the
/// token position being selected for.
#[derive(Clone, Copy)]
pub(super) struct QsaSelectionRequest<'a> {
pub(super) candidate: &'a QsaPrior,
pub(super) index_query: &'a [f32],
@@ -144,7 +144,7 @@ impl<'ctx> DenseWeightCache<'ctx> {
.ok_or(Error::IdentityMismatch)?
.try_borrow_mut()
.map_err(|_| Error::IdentityMismatch)?
.select(&self.binding, context, request.candidate, request.index_query, request.position)
.select(&self.binding, context, request)
}
pub(in super::super::super) fn gdn_input<'slot, 'source>(
&'slot self,
@@ -25,6 +25,7 @@ type StepCoreResult = (Option<TokenId>, Option<Box<[f32]>>);
pub(in crate::qwen_forward) mod original_prompt;
#[path = "executor_prefill_chunk.rs"]
mod prefill_chunk;
pub(in crate::qwen_forward) use prefill_chunk::mtp_window::{VerificationChunk, VerificationSource, WindowCaches};
/// MTP input from one fully committed target step. No public constructor.
pub(crate) struct TargetStepProduct {
@@ -18,6 +18,17 @@ struct ReadyVerifiedDraft<'draft, 'binding> {
count: usize,
warmed: usize,
}
/// The weight caches a joint publication warms the draft against: the MoE cache always, the dense cache
/// only when the target window leased a device GDN state that must be sealed.
pub(in crate::qwen_forward) struct WindowCaches<'a, 'moe, 'dense> {
pub(in crate::qwen_forward) moe: &'a MoeWeightCache<'moe>,
pub(in crate::qwen_forward) dense: Option<&'a DenseWeightCache<'dense>>,
}
/// The draft chunk stage being warmed together with the MoE cache its rows run against.
struct DraftWarmup<'a, 'stage, 'cache> {
stage: &'a mut MtpChunkStage<'stage>,
cache: &'a MoeWeightCache<'cache>,
}
impl VerifiedDraftPublication for ReadyVerifiedDraft<'_, '_> {
fn validate(&self, txn: &QwenChunkTxn<'_, '_>, prefix: &VerifiedTargetPrefix) -> Result<()> {
txn.validate_verified_prefix(prefix)?;
@@ -49,28 +60,28 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
cache: &MoeWeightCache<'_>,
cancelled: impl FnMut() -> bool,
) -> Result<TargetStepProduct> {
self.publish_joint_with_gdn_replay(binding, draft, cache, None, cancelled)
self.publish_joint_with_gdn_replay(binding, draft, WindowCaches { moe: cache, dense: None }, cancelled)
}
pub(in crate::qwen_forward) fn publish_joint_with_gdn_replay(
mut self,
binding: &ModelBinding,
draft: &mut MtpSession,
cache: &MoeWeightCache<'_>,
dense: Option<&DenseWeightCache<'_>>,
caches: WindowCaches<'_, '_, '_>,
mut cancelled: impl FnMut() -> bool,
) -> Result<TargetStepProduct> {
self.txn.validate_verified_prefix(&self.prefix)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.seal_leased_gdn(binding, dense, &mut cancelled)?;
self.seal_leased_gdn(binding, caches.dense, &mut cancelled)?;
let start = self.txn.start_position();
let count = self.prefix.count();
let rows = self.copy_accepted_rows(count)?;
// The existing stage validates actual draft KV/window/epoch/owner and
// requires genuine draft.next_position == actual target chunk start.
let mut stage = draft.stage_chunk(binding, &self.txn)?;
self.warm_accepted_rows(binding, cache, &mut stage, &rows, &mut cancelled)?;
let warmup = DraftWarmup { stage: &mut stage, cache: caches.moe };
self.warm_accepted_rows(binding, warmup, &rows, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
@@ -101,8 +112,7 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
fn warm_accepted_rows(
&mut self,
binding: &ModelBinding,
cache: &MoeWeightCache<'_>,
stage: &mut MtpChunkStage<'_>,
warmup: DraftWarmup<'_, '_, '_>,
rows: &[ChunkRowResidual],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
@@ -115,18 +125,25 @@ impl<'session, 'driver> PreparedMtpTargetWindow<'session, 'driver> {
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? || next.is_none() {
return Err(Error::IdentityMismatch);
}
mtp::warm_chunk_row(binding, &mut self.txn, row, stage, cache)?;
mtp::warm_chunk_row(binding, &mut self.txn, row, warmup.stage, warmup.cache)?;
}
Ok(())
}
}
/// The target step a verification window continues from, and the end-of-sequence token that closes it.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct VerificationSource<'a> {
pub(in crate::qwen_forward) product: &'a TargetStepProduct,
pub(in crate::qwen_forward) eos: Option<TokenId>,
}
/// The borrowed inputs of the verification chunk that the session, caches and cancel hook do not carry.
struct VerificationChunk<'a, 'o, 'p, 'd> {
binding: &'a ModelBinding,
proposals: &'a [TokenId],
output: &'a OutputStage<'o, 'p>,
dense_cache: &'a DenseWeightCache<'d>,
host_remaining: usize,
pub(in crate::qwen_forward) struct VerificationChunk<'a, 'o, 'p, 'd> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) source: VerificationSource<'a>,
pub(in crate::qwen_forward) proposals: &'a [TokenId],
pub(in crate::qwen_forward) output: &'a OutputStage<'o, 'p>,
pub(in crate::qwen_forward) dense_cache: &'a DenseWeightCache<'d>,
pub(in crate::qwen_forward) host_remaining: usize,
}
// Descending bounded admission, never a numeric/identity/poison retry.
fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()>) -> Result<usize> {
@@ -147,13 +164,12 @@ fn legal_target_rows(limit: usize, mut preflight: impl FnMut(usize) -> Result<()
impl QwenForward {
pub(in crate::qwen_forward) fn mtp_target_window_capacity(
binding: &ModelBinding,
source: &TargetStepProduct,
eos: Option<TokenId>,
source: VerificationSource<'_>,
target: &QwenSession<'_>,
limit: usize,
host_remaining: usize,
) -> Result<usize> {
QwenChunkTxn::validate_verification_source(binding, source, eos, target)?;
QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, target)?;
legal_target_rows(limit, |rows| QwenChunkTxn::preflight_mtp_verification(target, binding, rows, host_remaining))
}
@@ -201,30 +217,23 @@ impl QwenForward {
/// Explicit source-only candidate. Preserves Native/scalar MTP/defaults.
/// Existing Q6/MoE/GR batching survives; GDN uses unchanged scalar pending
/// producers here so every possible accepted prefix has actual state.
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn prepare_mtp_target_window<'session, 'driver>(
binding: &ModelBinding,
source: &TargetStepProduct,
proposals: &[TokenId],
eos: Option<TokenId>,
inputs: VerificationChunk<'_, '_, '_, '_>,
session: &'session mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar_cache: Option<&mut KarPleCache<'_>>,
moe_cache: &mut MoeWeightCache<'driver>,
dense_cache: &DenseWeightCache<'_>,
host_remaining: usize,
mut cancelled: impl FnMut() -> bool,
) -> Result<PreparedMtpTargetWindow<'session, 'driver>> {
let seed = QwenChunkTxn::validate_verification_source(binding, source, eos, session)?;
let (binding, source, proposals) = (inputs.binding, inputs.source, inputs.proposals);
let seed = QwenChunkTxn::validate_verification_source(binding, source.product, source.eos, session)?;
Self::admit_mtp_window(seed, proposals, moe_cache, &mut cancelled)?;
// Refuse the complete journal charge before cache/provider growth.
QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), host_remaining)?;
let inputs = VerificationChunk { binding, proposals, output, dense_cache, host_remaining };
QwenChunkTxn::preflight_mtp_verification(session, binding, proposals.len(), inputs.host_remaining)?;
let txn = Self::prepare_verification_chunk(inputs, session, kar_cache, moe_cache, &mut cancelled)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let prefix = txn.select_verified_prefix(binding, source, eos)?;
let prefix = txn.select_verified_prefix(binding, source.product, source.eos)?;
Ok(PreparedMtpTargetWindow { txn, prefix })
}
}
@@ -1,6 +1,7 @@
//! Separate native-certified activation model observer. Original failed observer unchanged.
use super::mmq_evaluation::{ChunkExact, ChunkRun, MmqRun, Observation, pos};
use super::*;
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
use crate::qwen_forward::mtp_decode::MtpDecoder;
#[derive(Debug)]
@@ -45,25 +46,14 @@ pub(crate) struct NativeMmqReport {
pub(crate) native_fallback_layers: u64,
}
impl QwenForward {
pub(crate) fn test_native_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
) -> NativeMmqReport {
check_native_mmq_on_loaded(binding, session, output, kar, moe, dense)
pub(crate) fn test_native_mmq_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) -> NativeMmqReport {
check_native_mmq_on_loaded(owners)
}
}
pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>(
binding: &ModelBinding,
session: &mut QwenSession<'driver>,
output: &OutputStage<'_, '_>,
kar: &mut KarPleCache<'_>,
moe: &mut MoeWeightCache<'driver>,
dense: &DenseWeightCache<'_>,
pub(in crate::qwen_forward) fn check_native_mmq_on_loaded(
owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>,
) -> NativeMmqReport {
let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners;
let mut run = MmqRun::new(binding, session, output, kar, moe, dense);
let fresh = run.session.test_reset_replay_snapshot(binding).expect("fresh snapshot refused");
assert!(fresh.has_prefix(0, [-1, -1]), "fresh target required");
@@ -77,27 +67,26 @@ pub(in crate::qwen_forward) fn check_native_mmq_on_loaded<'driver>(
run.late_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
run.mtp_row_cancel(&mut candidate_draft, &fresh, &fresh_draft);
let chunk = run.candidate_chunk(&mut candidate_draft);
let (exact, actual_greedy) = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft);
let verdict = run.native_exactness(&baseline, &baseline_streams, &chunk, &candidate_draft);
let after = run.native_continuation(&mut candidate_draft, &chunk, &continued);
run.output.test_reset_replay_record(false).expect("head observer did not drain");
native_report(&baseline, &continued, &chunk, &exact, actual_greedy, &after)
native_report(&baseline, &continued, &chunk, &verdict, &after)
}
fn native_report(
baseline: &Observation,
continued: &Observation,
chunk: &ChunkRun,
exact: &ChunkExact,
actual_greedy: TokenId,
verdict: &NativeChunkVerdict,
after: &NativeContinued,
) -> NativeMmqReport {
NativeMmqReport {
final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, actual_greedy),
final_head: HeadObservation::new(&baseline.logits, &chunk.logits, baseline.greedy, verdict.greedy),
continuation_head: HeadObservation::new(&continued.logits, &after.logits, continued.greedy, after.greedy),
head_exact: exact.head,
residual_exact: exact.residual,
target_exact: exact.target,
draft_exact: exact.draft,
head_exact: verdict.exact.head,
residual_exact: verdict.exact.residual,
target_exact: verdict.exact.target,
draft_exact: verdict.exact.draft,
continued_head_exact: after.head,
continued_target_exact: after.target,
continued_draft_exact: after.draft,
@@ -107,6 +96,12 @@ fn native_report(
}
}
/// How the candidate chunk compares with the scalar baseline: tensor exactness and the candidate's greedy token.
struct NativeChunkVerdict {
exact: ChunkExact,
greedy: TokenId,
}
/// What the continuation step after the candidate chunk observed.
struct NativeContinued {
logits: Box<[u32]>,
@@ -124,7 +119,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
baseline_streams: &[u32],
chunk: &ChunkRun,
candidate_draft: &MtpDecoder,
) -> (ChunkExact, TokenId) {
) -> NativeChunkVerdict {
let actual_greedy = chunk.product.predicted(self.session).expect("MMQ current origin invalid");
let head = baseline.logits.as_ref() == chunk.logits.as_ref();
let actual_streams =
@@ -134,7 +129,7 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
.state
.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding).expect("chunk state invalid"));
let draft = candidate_draft.test_chunk_eq(&baseline.draft);
(ChunkExact { head, residual, target, draft }, actual_greedy)
NativeChunkVerdict { exact: ChunkExact { head, residual, target, draft }, greedy: actual_greedy }
}
fn native_continuation(
&mut self,
@@ -3,7 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::gr::GrBatchRow;
use crate::qwen_forward::moe_expert::ExpertReady;
use crate::qwen_forward::moe_expert::{ChunkFfnLayer, ExpertReady};
use crate::qwen_forward::session::chunk::{ChunkFfnRow, PreparedLayerRow};
/// Releases the native MoE products of the window, if it had any.
@@ -77,7 +77,8 @@ impl QwenForward {
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
ChunkMoePolicy::Layer0Diagnostic => Err(Error::IdentityMismatch),
ChunkMoePolicy::Native | ChunkMoePolicy::ExperimentalRetainedGr => {
MoeExpertStage::execute_chunk(binding, layer, ffn_rows, chunk, moe_cache, cancelled)
let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows };
MoeExpertStage::execute_chunk(ffn, chunk, moe_cache, cancelled)
}
ChunkMoePolicy::ExperimentalResidentMmq
| ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr
@@ -218,14 +218,16 @@ fn compose_cached_ple(
let key = cache.ple_key(entry)?;
let value = cache.ple_value(entry)?;
let aux = cache.ple_aux(entry)?;
let weights = leleka_cuda_driver::PleClosedWeights { key, value, aux };
let rows = ple_transport::PleRows { embedding, streams, history };
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let result = if let Some(mut queue) = cache.ple_queue(binding, context)? {
ple_transport::compose_queued(&mut queue, context, key, value, aux, embedding, streams, history, failed)
ple_transport::compose_queued(&mut queue, context, weights, rows, failed)
} else {
ple_transport::compose(context, key, value, aux, embedding, streams, history, failed)
ple_transport::compose(context, weights, rows, failed)
};
#[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 result = ple_transport::compose(context, weights, rows, failed);
result
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -217,7 +217,15 @@ pub(crate) fn complete(witness: [u64; 3]) -> Result<()> {
Ok(())
})
}
fn comparison(role: &str, row: usize, slot: Option<usize>, expert: Option<u32>, a: &[u32], b: &[u32]) -> String {
/// Which tensor of the layer-0 capture a comparison line describes: its role, input row, route slot and expert.
struct ComparedTensor {
role: &'static str,
row: usize,
slot: Option<usize>,
expert: Option<u32>,
}
fn comparison(tensor: ComparedTensor, a: &[u32], b: &[u32]) -> String {
let ComparedTensor { role, row, slot, expert } = tensor;
assert_eq!(a.len(), b.len());
let first = a.iter().zip(b).position(|(a, b)| a != b);
let count = a.iter().zip(b).filter(|(a, b)| a != b).count();
@@ -287,29 +295,26 @@ impl Report {
fn push_row_comparisons(&self, row: usize, comparisons: &mut String) {
for slot in 0..SLOTS {
let lo = (row * SLOTS + slot) * N;
comparisons.push_str(&comparison(
"packed_down",
let tensor = ComparedTensor {
role: "packed_down",
row,
Some(slot),
Some(self.ids[row * SLOTS + slot]),
slot: Some(slot),
expert: Some(self.ids[row * SLOTS + slot]),
};
comparisons.push_str(&comparison(
tensor,
&self.arms[0].packed[lo..lo + N],
&self.arms[1].packed[lo..lo + N],
));
}
let lo = row * N;
comparisons.push_str(&comparison(
"shared_scaled",
row,
None,
None,
ComparedTensor { role: "shared_scaled", row, slot: None, expert: None },
&self.arms[0].shared[lo..lo + N],
&self.arms[1].shared[lo..lo + N],
));
comparisons.push_str(&comparison(
"final",
row,
None,
None,
ComparedTensor { role: "final", row, slot: None, expert: None },
&self.arms[0].final_values[lo..lo + N],
&self.arms[1].final_values[lo..lo + N],
));
@@ -0,0 +1,17 @@
//! The freshly loaded target model and its device caches, as one value a `test_*_on_loaded` GPU phase receives.
use super::{
dense_weight_cache::DenseWeightCache, kar_ple_cache::KarPleCache, moe_weight_cache::MoeWeightCache,
output::OutputStage, session::QwenSession,
};
use crate::model_binding::qwen4exp_input::ModelBinding;
/// The loaded target model and every cache one on-loaded observation borrows; it exists so a phase takes one
/// argument instead of six owners that always travel together.
pub(crate) struct LoadedTargetOwners<'a, 'driver, 'o, 'p, 'k, 'd> {
pub(crate) binding: &'a ModelBinding,
pub(crate) session: &'a mut QwenSession<'driver>,
pub(crate) output: &'a OutputStage<'o, 'p>,
pub(crate) kar: &'a mut KarPleCache<'k>,
pub(crate) moe: &'a mut MoeWeightCache<'driver>,
pub(crate) dense: &'a DenseWeightCache<'d>,
}
@@ -11,6 +11,8 @@ pub(crate) mod kar_ple_cache;
pub(crate) mod moe_expert;
pub(crate) mod moe_route;
// Original Strata prefill MoE router + shared expert over a whole micro-window of genuine FFN reads.
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) mod loaded_target_owners;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod moe_prefill_batch;
pub(crate) mod moe_weight_cache;
@@ -20,7 +20,9 @@ mod moe_down;
use moe_down::{DownScope, DownSelection, PackedDown, RetainedDown, TransportBuffer};
#[path = "moe_group_chunk.rs"]
mod grouped;
pub(in crate::qwen_forward) use grouped::PreparedMoeRow;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) use grouped::LoadedArms;
pub(in crate::qwen_forward) use grouped::{ChunkFfnLayer, PreparedMoeRow};
const N: usize = 2560;
const FF: usize = 640;
const K: usize = 10;
@@ -110,7 +110,8 @@ fn project_residents<'ctx>(
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
project_group(context, binding, rows, pairs, cache, prepared, scope, origins, down, cancelled)?;
let group = ExpertGroup { context, binding, rows, pairs, scope, origins };
project_group(group, cache, prepared, down, cancelled)?;
}
Ok(())
}
@@ -47,7 +47,8 @@ impl<'g> PacketPlan<'g> {
continue;
}
let pairs = groups[expert].as_slice();
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
let members = PacketGroupMembers { rows, pairs, origins };
validate_packet_pairs(actual, binding, members, packets)?;
self.classify_pairs(binding, rows, pairs, cache)?;
}
}
@@ -62,6 +62,8 @@ mod layer0_pair;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "moe_group_down_direct_gpu.rs"]
mod direct_gpu;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(crate) use direct_gpu::LoadedArms;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[path = "moe_group_adaptive.rs"]
@@ -69,6 +71,7 @@ mod adaptive;
#[path = "moe_group_chunk/impl_preparedmoerow.rs"]
mod impl_preparedmoerow;
pub(in crate::qwen_forward) use impl_preparedmoerow::ChunkFfnLayer;
#[allow(unused_imports)]
use impl_preparedmoerow::grouped_pairs;
#[path = "moe_group_chunk/bound_rows_fn.rs"]
@@ -80,18 +83,15 @@ use execute_bound_fn::execute_bound;
#[path = "moe_group_chunk/project_group_fn.rs"]
mod project_group_fn;
#[allow(unused_imports)]
use project_group_fn::project_group;
use project_group_fn::{ExpertGroup, project_group};
#[path = "moe_group_chunk/project_group_direct_fn.rs"]
mod project_group_direct_fn;
#[path = "moe_group_chunk/project_group_shared_fns.rs"]
mod project_group_shared_fns;
#[path = "moe_group_chunk/project_group_source_fenced_fn.rs"]
mod project_group_source_fenced_fn;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(unused_imports)]
use project_group_source_fenced_fn::project_group_source_fenced;
#[path = "moe_group_chunk/project_group_source_consumers_fn.rs"]
mod project_group_source_consumers_fn;
#[path = "moe_group_chunk/project_group_source_fenced_fn.rs"]
mod project_group_source_fenced_fn;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(unused_imports)]
use project_group_source_consumers_fn::project_group_source_consumers;
@@ -100,7 +100,7 @@ mod direct_packets_fns;
#[path = "moe_group_chunk/ordered_down_refusal_fn.rs"]
mod ordered_down_refusal_fn;
#[allow(unused_imports)]
use ordered_down_refusal_fn::execute_direct_packets;
use ordered_down_refusal_fn::PacketGroupMembers;
#[allow(unused_imports)]
use ordered_down_refusal_fn::finish_shared;
#[allow(unused_imports)]
@@ -116,6 +116,8 @@ use ordered_down_refusal_fn::validate_packet_pairs;
#[path = "moe_group_chunk/finish_shared_with_fn.rs"]
mod finish_shared_with_fn;
#[allow(unused_imports)]
use finish_shared_with_fn::RowTail;
#[allow(unused_imports)]
use finish_shared_with_fn::finish_shared_with;
#[allow(unused_imports)]
use finish_shared_with_fn::uses_adaptive;
@@ -1,6 +1,7 @@
//! The uploaded rows of one chunk and their ungrouped/grouped execution (STRA-338 size: extract-method only).
use super::direct_packets_fns::PacketRun;
use super::finish_shared_with_fn::RowTail;
#[allow(unused_imports)]
use super::*;
@@ -12,46 +13,55 @@ pub(super) struct BoundRows<'a, 'ctx> {
pub(super) scope: &'a DownScope<'ctx>,
pub(super) activations: &'a [TransportBuffer<'ctx>],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
/// Whether the rows run as sorted expert groups instead of row by row.
pub(super) grouped: bool,
}
/// The inputs only the direct-packet path consumes: the sealed chunk transaction its packets are validated
/// against (absent on the ordinary path) and the optional native prompt finish.
pub(super) struct DirectPacketInputs<'a, 'session, 'ctx, 'dense> {
pub(super) actual: Option<&'a QwenChunkTxn<'session, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) native: Option<prompt_finish::NativePromptFinish<'a, 'ctx, 'dense>>,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
pub(super) marker: std::marker::PhantomData<&'dense ()>,
}
/// The expert groups of the chunk rows, in ascending expert order, and the Down origin of every row.
#[derive(Clone, Copy)]
pub(super) struct ExpertGroupPlan<'a> {
pub(super) groups: &'a [Vec<Pair>],
pub(super) origins: &'a [Rc<DownOrigin>],
}
/// What the scalar-Down path projects the expert groups into: the per-row Down cells, following the plan.
struct GroupProjection<'a, 'session, 'ctx> {
plan: ExpertGroupPlan<'a>,
actual: Option<&'a QwenChunkTxn<'session, 'ctx>>,
down: &'a mut [[Option<ActualDown<'ctx>>; K]],
}
impl<'a, 'ctx> BoundRows<'a, 'ctx> {
pub(super) fn execute(
&self,
grouped: bool,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
direct: DirectPacketInputs<'_, '_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
if !grouped {
return self.execute_ungrouped(
cache,
cancelled,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
if !self.grouped {
return self.execute_ungrouped(cache, cancelled, direct);
}
self.execute_grouped(
cache,
cancelled,
actual,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
)
self.execute_grouped(cache, cancelled, direct)
}
fn execute_ungrouped(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
direct: DirectPacketInputs<'_, '_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if native.is_some() {
if direct.native.is_some() {
return Err(Error::IdentityMismatch);
}
let rows = self.rows;
@@ -84,51 +94,30 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
direct: DirectPacketInputs<'_, '_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
let groups = route_groups(self.rows)?;
let origins = down_origins(self.binding, self.rows)?;
if use_direct_packets(cache) {
let run = self.packet_run(
&groups,
&origins,
let run = PacketRun {
context: self.context,
binding: self.binding,
rows: self.rows,
scope: self.scope,
origins: &origins,
activations: self.activations,
groups: &groups,
prepared: self.prepared,
actual: direct.actual.ok_or(Error::IdentityMismatch)?,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
return execute_direct_packets(run, cache, cancelled, actual.ok_or(Error::IdentityMismatch)?);
}
self.execute_scalar_down(cache, cancelled, actual, &groups, &origins)
}
/// The rows of this chunk as one direct-packet batch over their expert `groups` and row `origins`.
fn packet_run<'g, 'l, 'd>(
&self,
groups: &'g [Vec<Pair>],
origins: &'g [Rc<DownOrigin>],
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'l, 'ctx, 'd>,
>,
) -> PacketRun<'g, 'ctx, 'l, 'd>
where
'a: 'g,
{
PacketRun {
context: self.context,
binding: self.binding,
rows: self.rows,
groups,
scope: self.scope,
origins,
activations: self.activations,
prepared: self.prepared,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
marker: std::marker::PhantomData,
native: direct.native,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
marker: std::marker::PhantomData,
};
return run.execute(cache, cancelled);
}
let plan = ExpertGroupPlan { groups: &groups, origins: &origins };
self.execute_scalar_down(cache, cancelled, direct.actual, plan)
}
fn execute_scalar_down(
@@ -136,13 +125,13 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
plan: ExpertGroupPlan<'_>,
) -> Result<Vec<ExpertReady>> {
let mut down = Vec::new();
down.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
down.resize_with(self.rows.len(), || std::array::from_fn::<_, K, _>(|_| None));
let operation = self.project_and_combine(cache, cancelled, actual, groups, origins, &mut down);
let mut projection = GroupProjection { plan, actual, down: &mut down };
let operation = self.project_and_combine(cache, cancelled, &mut projection);
let mut close = Ok(());
for actual in down.into_iter().flatten().flatten() {
let next = actual.output.close();
@@ -158,12 +147,9 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut Vec<[Option<ActualDown<'ctx>>; K]>,
projection: &mut GroupProjection<'_, '_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
self.project_groups(cache, cancelled, actual, groups, origins, down)?;
self.project_groups(cache, cancelled, projection)?;
let rows = self.rows;
let mut outputs = Vec::new();
outputs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
@@ -173,7 +159,7 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
outputs.push(self.combine_row(cache, i, &mut down[i], &origins[i])?);
outputs.push(self.combine_row(cache, i, &mut projection.down[i], &projection.plan.origins[i])?);
}
Ok(outputs)
}
@@ -182,19 +168,18 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
projection: &mut GroupProjection<'_, '_, 'ctx>,
) -> Result<()> {
self.project_adaptive(cache, cancelled, actual, groups, origins, down)?;
self.project_adaptive(cache, cancelled, projection)?;
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let ExpertGroupPlan { groups, origins } = projection.plan;
let adaptive_done = uses_adaptive(cache);
for pairs in groups.iter().filter(|group| !group.is_empty() && !adaptive_done) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
project_group(context, binding, rows, pairs, cache, self.prepared, scope, origins, down, cancelled)?;
let group = ExpertGroup { context, binding, rows, pairs, scope, origins };
project_group(group, cache, self.prepared, &mut *projection.down, cancelled)?;
}
Ok(())
}
@@ -208,15 +193,14 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
groups: &[Vec<Pair>],
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
projection: &mut GroupProjection<'_, '_, 'ctx>,
) -> Result<()> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if cache.uses_strata_adaptive_experts() {
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let prepared = self.prepared;
let ExpertGroupPlan { groups, origins } = projection.plan;
let (actual, down) = (projection.actual, &mut *projection.down);
adaptive::project_adaptive_groups(
context, binding, rows, groups, cache, prepared, scope, origins, down, cancelled, actual,
)?;
@@ -244,7 +228,8 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
packed.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?;
finish_shared(context, binding, row, self.activations[i].buffer()?, cache, scope, origin, &packed)
let activation = self.activations[i].buffer()?;
finish_shared(RowTail { context, binding, row, activation, scope, origin }, cache, &packed)
})();
let close = packed.close();
let values = output?;
@@ -1,39 +1,41 @@
//! Phases of `execute_direct_packets` (STRA-338 size: extract-method only).
//! Phases of the direct-packet layer batch (STRA-338 size: extract-method only).
#[allow(unused_imports)]
use super::finish_shared_with_fn::RowTail;
use super::ordered_down_refusal_fn::close_packets;
use super::project_group_direct_fn::DirectRun;
use super::*;
/// The sealed rows, their expert groups, origins and shared activations of one direct-packet layer batch, with the
/// Gate/Up Q8 products prepared for those rows.
pub(super) struct PacketRun<'a, 'ctx, 'l, 'd> {
/// The sealed rows, their origins, expert groups and shared activations of one direct-packet layer batch.
pub(super) struct PacketRun<'a, 'session, 'ctx, 'l, 'd, 'q> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) groups: &'a [Vec<Pair>],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origins: &'a [Rc<DownOrigin>],
pub(super) activations: &'a [TransportBuffer<'ctx>],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
/// The expert groups of the rows, in ascending expert order.
pub(super) groups: &'a [Vec<Pair>],
/// The Q8 owner of every uploaded activation.
pub(super) prepared: &'a [RoutedGateUpQ8<'q>],
/// The sealed chunk transaction every packet is validated against.
pub(super) actual: &'a QwenChunkTxn<'session, 'ctx>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(super) native: Option<prompt_finish::NativePromptFinish<'l, 'ctx, 'd>>,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
pub(super) marker: std::marker::PhantomData<(&'l (), &'d ())>,
}
impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> {
/// Reserve the packets, run the batch and close every packet whatever the outcome.
pub(super) fn execute(
self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
let mut packets = Vec::new();
packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
let scope = self.scope;
let operation = self.operate(&mut packets, cache, cancelled, actual);
let operation = self.operate(&mut packets, cache, cancelled);
scope.record(&operation);
let cleanup = close_packets(packets);
operation.and_then(|values| cleanup.map(|()| values))
@@ -45,15 +47,14 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
packets: &mut Vec<ActualSlotPacket<'ctx>>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
self.init_packets(packets)?;
self.project_groups(packets, cache, cancelled, actual)?;
self.project_groups(packets, cache, cancelled)?;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(mut finish) = self.native.take() {
return self.finish_native(packets, cache, &mut finish, cancelled, actual);
return self.finish_native(packets, cache, &mut finish, cancelled);
}
self.finish_rows(packets, cache, cancelled, actual)
self.finish_rows(packets, cache, cancelled)
}
/// One empty packet per authenticated row.
@@ -75,37 +76,34 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
packets: &mut [ActualSlotPacket<'ctx>],
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<()> {
let adaptive = uses_adaptive(cache);
self.project_adaptive(adaptive, packets, self.groups, cache, self.prepared, cancelled, actual)?;
if adaptive {
self.project_adaptive(packets, cache, cancelled)?;
}
for pairs in self.groups.iter().filter(|group| !group.is_empty() && !adaptive) {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.project_one(pairs, cache, DirectRun { actual, packets, cancelled })?;
self.project_one(pairs, packets, cache, cancelled)?;
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
#[cfg_attr(
not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")),
allow(unused_variables)
)]
fn project_adaptive(
&self,
adaptive: bool,
packets: &mut [ActualSlotPacket<'ctx>],
groups: &[Vec<Pair>],
cache: &mut MoeWeightCache<'ctx>,
prepared: &[RoutedGateUpQ8<'_>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<()> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if adaptive {
{
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let (groups, prepared, actual) = (self.groups, self.prepared, self.actual);
adaptive_packets::project_adaptive_packets(
context,
binding,
@@ -126,28 +124,13 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
fn project_one(
&self,
pairs: &[Pair],
packets: &mut [ActualSlotPacket<'ctx>],
cache: &mut MoeWeightCache<'ctx>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let run = DirectRun { actual: self.actual, packets, cancelled };
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let DirectRun { actual, packets, cancelled } = run;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let (context, binding, rows, scope, origins) =
(self.context, self.binding, self.rows, self.scope, self.origins);
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
return project_group_source_fenced(
context,
binding,
rows,
pairs,
cache,
self.prepared,
scope,
origins,
packets,
cancelled,
actual,
);
return self.project_group_fenced(pairs, cache, run);
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
return self.project_group_direct(pairs, cache, run);
}
@@ -160,9 +143,8 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
cache: &mut MoeWeightCache<'ctx>,
finish: &mut prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
let (rows, binding) = (self.rows, self.binding);
let (rows, binding, actual) = (self.rows, self.binding, self.actual);
let layer = rows[0].row().route.identity().layer();
let mut refs = Vec::new();
refs.try_reserve_exact(rows.len()).map_err(|_| Error::InputAllocation)?;
@@ -180,8 +162,8 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
packets: &[ActualSlotPacket<'ctx>],
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
let actual = self.actual;
let mut outputs = Vec::new();
outputs.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
for (index, row) in self.rows.iter().enumerate() {
@@ -211,13 +193,10 @@ impl<'ctx> PacketRun<'_, 'ctx, '_, '_> {
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
packet.packet.with_completed(scope, |packet| direct_gpu::observe_packet(packet))?;
let activation = self.activations[index].buffer()?;
let tail = RowTail { context, binding, row, activation, scope, origin };
if use_shared_tail(cache) {
return packet.packet.with_completed(scope, |completed| {
finish_shared_queued(context, binding, row, activation, cache, scope, origin, completed)
});
return packet.packet.with_completed(scope, |completed| finish_shared_queued(tail, cache, completed));
}
finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| {
packet.packet.combine(scope, weights, scaled)
})
finish_shared_with(tail, cache, |weights, scaled| packet.packet.combine(scope, weights, scaled))
}
}
@@ -1,35 +1,26 @@
//! Moved out of the parent module by STRA-338: fn execute_bound.
use super::bound_rows_fn::BoundRows;
use super::bound_rows_fn::{BoundRows, DirectPacketInputs};
#[allow(unused_imports)]
use super::*;
pub(super) fn execute_bound<'ctx>(
context: &Context<'_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
layer: ChunkFfnLayer<'_>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
direct: DirectPacketInputs<'_, '_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
let (binding, rows) = (layer.binding, layer.rows);
let context = cache.mmq_context(binding, context)?;
let (grouped, scope, failed) = open_bound(binding, rows, cache, context)?;
let (mut activations, mut prepared) = (reserved(rows.len())?, reserved(rows.len())?);
let admission = upload_activations(rows, &scope, cancelled, &mut activations)
.and_then(|()| prepare_owners(context, cancelled, &activations, &mut prepared));
let result = admission.and_then(|()| {
let bound = BoundRows { context, binding, rows, scope: &scope, activations: &activations, prepared: &prepared };
bound.execute(
grouped,
cache,
cancelled,
actual,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
)
let (scope, activations, prepared) = (&scope, &activations, &prepared);
let bound = BoundRows { context, binding, rows, scope, activations, prepared, grouped };
bound.execute(cache, cancelled, direct)
});
scope.record(&result);
finish_bound(&failed, cache, result, close_prepared(prepared), activations)
@@ -3,6 +3,18 @@
#[allow(unused_imports)]
use super::*;
/// What the shared-expert tail of one row reads besides the weight cache: the row, its activation, the Down scope and
/// the row's origin.
#[derive(Clone, Copy)]
pub(super) struct RowTail<'a, 'ctx, 'buf> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) row: &'a PreparedMoeRow,
pub(super) activation: &'a DeviceBuffer<'buf>,
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origin: &'a Rc<DownOrigin>,
}
/// Partial owners of the shared expert of one row; every one is closed explicitly, whatever failed.
#[derive(Default)]
struct SharedOwners<'ctx> {
@@ -12,15 +24,8 @@ struct SharedOwners<'ctx> {
route_weights: Option<super::super::moe_down::TransportBuffer<'ctx>>,
}
impl<'ctx> SharedOwners<'ctx> {
fn scale_shared(
&mut self,
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
row: &PreparedMoeRow,
activation: &DeviceBuffer<'_>,
cache: &mut MoeWeightCache<'_>,
(scope, origin): (&DownScope<'ctx>, &Rc<DownOrigin>),
) -> Result<()> {
fn scale_shared(&mut self, tail: RowTail<'_, 'ctx, '_>, cache: &mut MoeWeightCache<'_>) -> Result<()> {
let RowTail { context, binding, row, activation, scope, origin } = tail;
let selection = MoeExpertSelection::Shared;
self.shared =
Some(
@@ -67,25 +72,18 @@ impl<'ctx> SharedOwners<'ctx> {
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn finish_shared_with<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
row: &PreparedMoeRow,
activation: &DeviceBuffer<'_>,
tail: RowTail<'_, 'ctx, '_>,
cache: &mut MoeWeightCache<'_>,
scope: &DownScope<'ctx>,
origin: &Rc<DownOrigin>,
combine: impl FnOnce(&DeviceBuffer<'_>, &super::super::moe_down::ScaledDown<'_>) -> Result<Box<[f32]>>,
) -> Result<Box<[f32]>> {
let (row, scope) = (tail.row, tail.scope);
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if crate::qwen_forward::layer0_mmq_observation::enabled() {
crate::qwen_forward::layer0_mmq_observation::row(row.route.identity().position().get())?;
}
let mut owners = SharedOwners::default();
let operation = owners
.scale_shared(context, binding, row, activation, cache, (scope, origin))
.and_then(|()| owners.combine_with(row, scope, combine));
let operation = owners.scale_shared(tail, cache).and_then(|()| owners.combine_with(row, scope, combine));
scope.record(&operation);
let cleanup = owners.close_all();
operation.and_then(|values| cleanup.map(|()| values))
@@ -1,8 +1,17 @@
//! Moved out of the parent module by STRA-338: impl PreparedMoeRow, impl MoeExpertStage, fn grouped_pairs.
use super::bound_rows_fn::DirectPacketInputs;
#[allow(unused_imports)]
use super::*;
/// The FFN rows of one chunk layer together with the binding they were sealed against.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct ChunkFfnLayer<'a> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) layer: LayerId,
pub(in crate::qwen_forward) rows: &'a [ChunkFfnRow],
}
impl PreparedMoeRow {
pub(in crate::qwen_forward) fn validate(
&self,
@@ -57,13 +66,12 @@ impl MoeExpertStage {
Ok(row)
}
pub(in crate::qwen_forward) fn execute_chunk<'ctx>(
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
ffn: ChunkFfnLayer<'_>,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<Vec<ExpertReady>> {
let ChunkFfnLayer { layer, rows, .. } = ffn;
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let _owner_wall_scope =
crate::qwen_forward::owner_wall_profile::Scope::begin(crate::qwen_forward::owner_wall_profile::Stage::Moe);
@@ -75,22 +83,20 @@ impl MoeExpertStage {
}
if use_direct_packets(cache) {
return chunk.batch_outputs_ffn(layer, rows, |actual, context| {
execute_bound_unprompted(context, binding, rows, cache, cancelled, Some(actual))
execute_bound_unprompted(context, ffn, cache, cancelled, Some(actual))
});
}
chunk.batch_outputs(|context| execute_bound_unprompted(context, binding, rows, cache, cancelled, None))
chunk.batch_outputs(|context| execute_bound_unprompted(context, ffn, cache, cancelled, None))
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) fn execute_chunk_native_prompt<'ctx>(
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
ffn: ChunkFfnLayer<'_>,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
products: &mut super::super::super::moe_prefill_batch::MoeMicroProducts<'ctx>,
dense: &super::super::super::dense_weight_cache::DenseWeightCache<'_>,
finish: prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
let ChunkFfnLayer { layer, rows, .. } = ffn;
if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) || !use_direct_packets(cache) {
return Err(Error::IdentityMismatch);
}
@@ -98,37 +104,27 @@ impl MoeExpertStage {
chunk.validate_ffn_row(chunk.micro_row_index(index)?, layer, row)?;
}
chunk.batch_outputs_ffn(layer, rows, |actual, context| {
execute_bound(
context,
binding,
rows,
cache,
cancelled,
Some(actual),
Some(prompt_finish::NativePromptFinish { products, dense }),
)
let direct = DirectPacketInputs { actual: Some(actual), native: Some(finish) };
execute_bound(context, ffn, cache, cancelled, direct)
})
}
}
/// `execute_bound` of the ordinary chunk path: no native prompt finish.
fn execute_bound_unprompted<'ctx>(
context: &Context<'_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
ffn: ChunkFfnLayer<'_>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: Option<&QwenChunkTxn<'_, 'ctx>>,
) -> Result<Vec<ExpertReady>> {
execute_bound(
context,
binding,
rows,
cache,
cancelled,
let direct = DirectPacketInputs {
actual,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
None,
)
native: None,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
marker: std::marker::PhantomData,
};
execute_bound(context, ffn, cache, cancelled, direct)
} // Actual Strata counts/offsets algorithm, with per-row uniqueness and a checked
// inverse mapping. Private route producers are the only production input.
pub(super) fn grouped_pairs(ids: &[[u32; K]]) -> Result<Vec<Vec<Pair>>> {
@@ -1,19 +1,18 @@
//! Moved out of the parent module by STRA-338: fn ordered_down_refusal, fn use_direct_packets, fn
//! validate_packet_pairs, fn execute_direct_packets, fn finish_shared, fn use_shared_tail ....
#[allow(unused_imports)]
use super::direct_packets_fns::PacketRun;
use super::finish_shared_with_fn::RowTail;
use super::project_group_direct_fn::{DownProjection, RefusalReplay};
use super::*;
pub(super) fn ordered_down_refusal(
context: &Context<'_>,
kind: MoeMatrixKind,
matrix: CachedMoeMatrix<'_, '_>,
hidden: &[f32],
selections: &[DownSelection],
projection: DownProjection<'_>,
replay: RefusalReplay<'_>,
scope: &DownScope<'_>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let RefusalReplay { hidden_values: hidden, selections } = replay;
if hidden.len() != selections.len() * FF {
return Err(Error::IdentityMismatch);
}
@@ -21,7 +20,7 @@ pub(super) fn ordered_down_refusal(
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
replay_selection(context, kind, matrix, values, *selection, scope)?;
replay_selection(context, projection, values, *selection, scope)?;
}
// A native failing status with every scalar column valid is an internal
// inconsistency, never permission to publish candidate output.
@@ -30,12 +29,12 @@ pub(super) fn ordered_down_refusal(
/// One column of the ordered replay: upload its hidden values, project, and close both owners.
fn replay_selection(
context: &Context<'_>,
kind: MoeMatrixKind,
matrix: CachedMoeMatrix<'_, '_>,
projection: DownProjection<'_>,
values: &[f32; FF],
selection: DownSelection,
scope: &DownScope<'_>,
) -> Result<()> {
let DownProjection { kind, matrix, .. } = projection;
let activation = scope.upload(values)?;
let result = scope
.project(selection, |out| launch_cached_projection(context, kind, matrix, activation.buffer()?, out, N, FF));
@@ -64,14 +63,21 @@ pub(super) fn use_direct_packets(cache: &MoeWeightCache<'_>) -> bool {
#[cfg(not(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
cache.uses_direct_native_down_packets()
}
/// The chunk rows, the row/slot pairs of one expert group and each row's Down origin: what the validation of a
/// group's packets reads besides the binding and the packets themselves.
#[derive(Clone, Copy)]
pub(super) struct PacketGroupMembers<'a> {
pub(super) rows: &'a [ChunkFfnRow],
pub(super) pairs: &'a [Pair],
pub(super) origins: &'a [Rc<DownOrigin>],
}
pub(super) fn validate_packet_pairs(
actual: &QwenChunkTxn<'_, '_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
pairs: &[Pair],
origins: &[Rc<DownOrigin>],
members: PacketGroupMembers<'_>,
packets: &[ActualSlotPacket<'_>],
) -> Result<()> {
let PacketGroupMembers { rows, pairs, origins } = members;
if !(1..=64).contains(&pairs.len()) || packets.len() != rows.len() || origins.len() != rows.len() {
return Err(Error::IdentityMismatch);
}
@@ -79,7 +85,7 @@ pub(super) fn validate_packet_pairs(
return Err(Error::IdentityMismatch);
}
for pair in pairs {
validate_pair(actual, binding, rows, pair, origins, packets)?;
validate_pair(actual, binding, members, pair, packets)?;
}
Ok(())
}
@@ -87,11 +93,11 @@ pub(super) fn validate_packet_pairs(
fn validate_pair(
actual: &QwenChunkTxn<'_, '_>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
members: PacketGroupMembers<'_>,
pair: &Pair,
origins: &[Rc<DownOrigin>],
packets: &[ActualSlotPacket<'_>],
) -> Result<()> {
let PacketGroupMembers { rows, origins, .. } = members;
if pair.row >= rows.len() || pair.slot >= K {
return Err(Error::IdentityMismatch);
}
@@ -101,15 +107,6 @@ fn validate_pair(
row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?;
packets[pair.row].validate(&origins[pair.row], binding, identity)
}
pub(super) fn execute_direct_packets<'ctx>(
run: PacketRun<'_, 'ctx, '_, '_>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, 'ctx>,
) -> Result<Vec<ExpertReady>> {
run.execute(cache, cancelled, actual)
}
/// Close every packet; the first failure is kept and every packet is closed.
pub(super) fn close_packets(packets: Vec<ActualSlotPacket<'_>>) -> Result<()> {
let mut cleanup = Ok(());
@@ -121,25 +118,16 @@ pub(super) fn close_packets(packets: Vec<ActualSlotPacket<'_>>) -> Result<()> {
}
cleanup
}
#[allow(clippy::too_many_arguments)]
pub(super) fn finish_shared<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
row: &PreparedMoeRow,
activation: &DeviceBuffer<'_>,
tail: RowTail<'_, 'ctx, '_>,
cache: &mut MoeWeightCache<'_>,
scope: &DownScope<'ctx>,
origin: &Rc<DownOrigin>,
packed: &PackedDown<'ctx>,
) -> Result<Box<[f32]>> {
let scope = tail.scope;
if use_shared_tail(cache) {
return packed.with_completed(scope, |packet| {
finish_shared_queued(context, binding, row, activation, cache, scope, origin, packet)
});
return packed.with_completed(scope, |packet| finish_shared_queued(tail, cache, packet));
}
finish_shared_with(context, binding, row, activation, cache, scope, origin, |weights, scaled| {
packed.combine(scope, weights, scaled)
})
finish_shared_with(tail, cache, |weights, scaled| packed.combine(scope, weights, scaled))
}
// Existing capture providers require their original intermediate readbacks.
// Their reference path is retained rather than emitting incomplete observations.
@@ -150,17 +138,12 @@ pub(super) fn use_shared_tail(cache: &MoeWeightCache<'_>) -> bool {
}
cache.has_target_shared_tail()
}
#[allow(clippy::too_many_arguments)]
pub(super) fn finish_shared_queued(
context: &Context<'_>,
binding: &ModelBinding,
row: &PreparedMoeRow,
activation: &DeviceBuffer<'_>,
tail: RowTail<'_, '_, '_>,
cache: &mut MoeWeightCache<'_>,
scope: &DownScope<'_>,
origin: &Rc<DownOrigin>,
packet: &DeviceBuffer<'_>,
) -> Result<Box<[f32]>> {
let RowTail { context, binding, row, activation, scope, origin } = tail;
let identity = row.route.identity();
row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?;
if !origin.binding.matches(&binding.identity()) || origin.identity != identity {
@@ -5,7 +5,7 @@ use super::direct_packets_fns::PacketRun;
use super::project_group_shared_fns::*;
use super::*;
impl<'a, 'ctx> PacketRun<'a, 'ctx, '_, '_> {
impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> {
/// Project one expert group of the batch through the plain device path (no source fence), filling the slot
/// packets of its rows; the group buffers are closed whatever the outcome.
pub(super) fn project_group_direct(
@@ -14,7 +14,8 @@ impl<'a, 'ctx> PacketRun<'a, 'ctx, '_, '_> {
cache: &mut MoeWeightCache<'_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
validate_packet_pairs(run.actual, self.binding, self.rows, pairs, self.origins, run.packets)?;
let members = PacketGroupMembers { rows: self.rows, pairs, origins: self.origins };
validate_packet_pairs(run.actual, self.binding, members, run.packets)?;
let first = pairs[0];
let weights = &self.rows[first.row].row().weights;
let selection = MoeExpertSelection::Routed { slot: first.slot };
@@ -39,10 +40,10 @@ impl<'a, 'ctx> PacketRun<'a, 'ctx, '_, '_> {
/// The Down matrix of a group: its kind, the routed format it is stored in and the cached matrix itself.
#[derive(Clone, Copy)]
struct DownProjection<'a> {
kind: MoeMatrixKind,
format: RoutedFormat,
matrix: CachedMoeMatrix<'a, 'a>,
pub(super) struct DownProjection<'a> {
pub(super) kind: MoeMatrixKind,
pub(super) format: RoutedFormat,
pub(super) matrix: CachedMoeMatrix<'a, 'a>,
}
/// The chunk transaction, the slot packets a group fills and the cancellation poll of one direct run.
pub(super) struct DirectRun<'a, 'session, 'driver, 'ctx, C> {
@@ -52,10 +53,10 @@ pub(super) struct DirectRun<'a, 'session, 'driver, 'ctx, C> {
}
/// The transport buffers a direct group allocates in turn: Gate, Up and the activated hidden rows.
#[derive(Default)]
struct GroupBuffers<'ctx> {
gate: Option<TransportBuffer<'ctx>>,
up: Option<TransportBuffer<'ctx>>,
hidden: Option<TransportBuffer<'ctx>>,
pub(super) struct GroupBuffers<'ctx> {
pub(super) gate: Option<TransportBuffer<'ctx>>,
pub(super) up: Option<TransportBuffer<'ctx>>,
pub(super) hidden: Option<TransportBuffer<'ctx>>,
}
/// The activated hidden rows of a group: the device transport buffer and its finite host copy.
struct SwigluHidden<'a, 'ctx> {
@@ -63,15 +64,15 @@ struct SwigluHidden<'a, 'ctx> {
values: &'a [f32],
}
/// The device buffers of one grouped Down launch: the hidden activations read and the output written.
struct DownBuffers<'a, 'ctx> {
input: &'a DeviceBuffer<'ctx>,
out: &'a mut DeviceBuffer<'ctx>,
pub(super) struct DownBuffers<'a, 'ctx> {
pub(super) input: &'a DeviceBuffer<'ctx>,
pub(super) out: &'a mut DeviceBuffer<'ctx>,
}
/// What the ordered replay of a numerical Q8 refusal reads: the finite hidden values and the Down selections.
#[derive(Clone, Copy)]
struct RefusalReplay<'a> {
hidden_values: &'a [f32],
selections: &'a [DownSelection],
pub(super) struct RefusalReplay<'a> {
pub(super) hidden_values: &'a [f32],
pub(super) selections: &'a [DownSelection],
}
/// The identity of one direct group: one expert, its row/slot pairs and the actual row origins.
@@ -198,14 +199,11 @@ impl<'a, 'ctx> DirectGroup<'a, 'ctx> {
replay: RefusalReplay<'_>,
cancel: &mut impl FnMut() -> bool,
) -> Result<()> {
let DownProjection { kind, format, matrix } = projection;
let DownProjection { format, matrix, .. } = projection;
let DownBuffers { input, out } = buffers;
let RefusalReplay { hidden_values, selections } = replay;
let columns = DownColumns { total: self.pairs.len(), format };
let result = launch_down_plain(self.context, matrix, input, out, columns)?;
down_outcome(result, || {
ordered_down_refusal(self.context, kind, matrix, hidden_values, selections, self.scope, cancel)
})
down_outcome(result, || ordered_down_refusal(self.context, projection, replay, self.scope, cancel))
}
/// Private grouping has one pair per actual row, in ascending row order. Validate all row origins before
@@ -218,7 +216,8 @@ impl<'a, 'ctx> DirectGroup<'a, 'ctx> {
cancel: &mut impl FnMut() -> bool,
) -> Result<()> {
let (context, binding, pairs) = (self.context, self.binding, self.pairs);
validate_packet_pairs(actual, binding, self.rows, pairs, self.origins, packets)?;
let members = PacketGroupMembers { rows: self.rows, pairs, origins: self.origins };
validate_packet_pairs(actual, binding, members, packets)?;
let mut targets = packet_targets(pairs, packets)?;
super::super::moe_down::ResidentPackedDown::copy_group_with(self.scope, &mut targets, |copies| {
context.copy_routed_down_columns_to_slots(source, pairs.len(), copies).map_err(driver_error)?;
@@ -1,5 +1,6 @@
//! Moved out of the parent module by STRA-338: fn project_group.
use super::project_group_direct_fn::{DownProjection, GroupBuffers, RefusalReplay};
#[allow(unused_imports)]
use super::project_group_shared_fns::{
check_group_descriptors, close_group_buffers, down_kind_format, down_outcome, gate_up_format, gate_up_plain,
@@ -7,29 +8,34 @@ use super::project_group_shared_fns::{
};
use super::*;
#[allow(clippy::too_many_arguments)]
/// One expert's row/slot pairs against the chunk rows, the Down scope and the Down origin of every row.
#[derive(Clone, Copy)]
pub(super) struct ExpertGroup<'a, 'ctx> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) pairs: &'a [Pair],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origins: &'a [Rc<DownOrigin>],
}
pub(super) fn project_group<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
pairs: &[Pair],
group: ExpertGroup<'_, 'ctx>,
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let ExpertGroup { context, binding, rows, pairs, scope, origins } = group;
let first = pairs[0];
let weights = &rows[first.row].row().weights;
let selection = MoeExpertSelection::Routed { slot: first.slot };
check_group_descriptors(binding, rows, pairs, weights, selection)?;
let group = ResidentGroup { context, binding, pairs, scope, origins, weights, selection };
let mut gate = None;
let mut up = None;
let mut hidden = None;
let operation = group.run(cache, prepared, down, cancelled, &mut gate, &mut up, &mut hidden);
let resident = ResidentGroup { context, binding, pairs, scope, origins, weights, selection };
let mut buffers = GroupBuffers::default();
let operation = resident.run(cache, prepared, ResidentRun { down, cancelled }, &mut buffers);
scope.record(&operation);
let GroupBuffers { gate, up, hidden } = buffers;
operation.and(close_group_buffers(hidden, up, gate))
}
@@ -45,24 +51,35 @@ struct ResidentGroup<'a, 'ctx> {
selection: MoeExpertSelection,
}
/// The Down output cells a resident group fills and the cancellation poll of its run.
struct ResidentRun<'a, 'ctx, C> {
down: &'a mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &'a mut C,
}
/// The activated hidden rows of a resident group: the device buffer and, unless the adaptive path only checks
/// finiteness on the device, the finite host copy.
struct ResidentHidden<'a, 'ctx> {
buffer: &'a Option<TransportBuffer<'ctx>>,
values: &'a Option<Box<[f32]>>,
}
impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
#[allow(clippy::too_many_arguments)]
fn run(
&self,
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
gate: &mut Option<TransportBuffer<'ctx>>,
up: &mut Option<TransportBuffer<'ctx>>,
hidden: &mut Option<TransportBuffer<'ctx>>,
run: ResidentRun<'_, 'ctx, impl FnMut() -> bool>,
buffers: &mut GroupBuffers<'ctx>,
) -> Result<()> {
self.project_gate_up(cache, prepared, cancelled, gate, up)?;
let ResidentRun { down, cancelled } = run;
self.project_gate_up(cache, prepared, cancelled, buffers)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let hidden_values = self.swiglu_hidden(cache, gate, up, hidden)?;
self.project_down(cache, down, cancelled, hidden, &hidden_values)
let hidden_values = self.swiglu_hidden(cache, &buffers.gate, &buffers.up, &mut buffers.hidden)?;
let hidden = ResidentHidden { buffer: &buffers.hidden, values: &hidden_values };
self.project_down(cache, down, cancelled, hidden)
}
fn project_gate_up(
@@ -70,9 +87,9 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
cancelled: &mut impl FnMut() -> bool,
gate: &mut Option<TransportBuffer<'ctx>>,
up: &mut Option<TransportBuffer<'ctx>>,
buffers: &mut GroupBuffers<'ctx>,
) -> Result<()> {
let (gate, up) = (&mut buffers.gate, &mut buffers.up);
let refs = prepared_refs(self.pairs, prepared)?;
for (role, output) in [(MoeMatrixRole::Gate, gate), (MoeMatrixRole::Up, up)] {
if cancelled() {
@@ -174,9 +191,9 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
cache: &mut MoeWeightCache<'_>,
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
hidden: &Option<TransportBuffer<'ctx>>,
hidden_values: &Option<Box<[f32]>>,
hidden: ResidentHidden<'_, 'ctx>,
) -> Result<()> {
let ResidentHidden { buffer: hidden, values: hidden_values } = hidden;
let (binding, pairs, scope, selection) = (self.binding, self.pairs, self.scope, self.selection);
let (kind, format) = down_kind_format(self.weights, selection)?;
let selections = self.free_selections(down)?;
@@ -244,8 +261,10 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
scope.with_workspace(|workspace| {
let result = launch_down_in_workspace(workspace, matrix, args.input, out, pairs.len(), args.format)?;
down_outcome(result, || {
let actual_values = args.refusal_values(pairs.len())?;
ordered_down_refusal(context, args.kind, matrix, &actual_values, args.selections, scope, cancel)
let hidden_values = args.refusal_values(pairs.len())?;
let projection = DownProjection { kind: args.kind, format: args.format, matrix };
let replay = RefusalReplay { hidden_values: &hidden_values, selections: args.selections };
ordered_down_refusal(context, projection, replay, scope, cancel)
})
})
}
@@ -264,8 +283,10 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
let columns = DownColumns { total: pairs.len(), format: args.format };
let result = launch_down_plain(context, matrix, args.input, out, columns)?;
down_outcome(result, || {
let actual_values = args.refusal_values(pairs.len())?;
ordered_down_refusal(context, args.kind, matrix, &actual_values, args.selections, scope, cancel)
let hidden_values = args.refusal_values(pairs.len())?;
let projection = DownProjection { kind: args.kind, format: args.format, matrix };
let replay = RefusalReplay { hidden_values: &hidden_values, selections: args.selections };
ordered_down_refusal(context, projection, replay, scope, cancel)
})
}
}
@@ -1,7 +1,9 @@
//! Moved out of the parent module by STRA-338: fn project_group_source_consumers.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::project_group_direct_fn::DirectGroup;
use super::project_group_direct_fn::{
DirectGroup, DirectRun, DownBuffers, DownProjection, GroupBuffers, RefusalReplay,
};
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::project_group_shared_fns::{
close_group_buffers, down_kind_format, down_outcome, gate_up_format, hidden_buffer, launch_down_in_workspace,
@@ -14,35 +16,54 @@ use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use crate::qwen_forward::moe_weight_cache::RoutedSourceHealth;
/// The weight cache and the opened routed-source scope the matrices of one source-backed group are read through.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct SourceMatrices<'a, 'cache, 'src, 'file> {
cache: &'a mut MoeWeightCache<'cache>,
source: &'a mut MoeRoutedSourceScope<'src, 'file>,
}
/// The grouped output of one Gate or Up role, its stored format and the finite stage that completes it.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct GateUpTarget<'a, 'ctx> {
grouped: &'a mut TransportBuffer<'ctx>,
format: RoutedFormat,
stage: leleka_cuda_driver::RoutedFiniteStage,
}
/// One source-backed Down launch: the actor workspace it runs in, the Down matrix and the per-pair selections.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct SourceDownLaunch<'a, 'ctx> {
workspace: &'a mut leleka_cuda_driver::RoutedGroupWorkspace<'ctx>,
projection: DownProjection<'a>,
selections: &'a [DownSelection],
}
/// What ends the source scope after the last private consumer: the cache health and the opened source itself.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct SourceTail<'a, 'ctx, 'src, 'file> {
health: &'a RoutedSourceHealth<'a, 'ctx>,
source: &'a mut MoeRoutedSourceScope<'src, 'file>,
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(clippy::too_many_arguments)]
pub(super) fn project_group_source_consumers<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
pairs: &[Pair],
group: DirectGroup<'_, 'ctx>,
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
source: &mut MoeRoutedSourceScope<'_, '_>,
) -> Result<()> {
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
let first = pairs[0];
let weights = &rows[first.row].row().weights;
let selection = MoeExpertSelection::Routed { slot: first.slot };
let DirectGroup { binding, rows, pairs, scope, origins, .. } = group;
let DirectRun { actual, packets, cancelled } = run;
validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?;
source.validate_binding(binding).map_err(binding_error)?;
check_source_members(source, pairs.len())?;
let group = DirectGroup { context, binding, rows, pairs, scope, origins, weights, selection };
let mut gate = None;
let mut up = None;
let mut hidden = None;
let operation =
group.run_source(cache, prepared, actual, packets, cancelled, source, &mut gate, &mut up, &mut hidden);
let mut buffers = GroupBuffers::default();
let matrices = SourceMatrices { cache, source };
let operation = group.run_source(matrices, prepared, DirectRun { actual, packets, cancelled }, &mut buffers);
scope.record(&operation);
let GroupBuffers { gate, up, hidden } = buffers;
operation.and(close_group_buffers(hidden, up, gate))
}
@@ -63,37 +84,31 @@ pub(super) fn check_source_members(source: &mut MoeRoutedSourceScope<'_, '_>, me
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
impl<'ctx> DirectGroup<'_, 'ctx> {
#[allow(clippy::too_many_arguments)]
fn run_source(
&self,
cache: &mut MoeWeightCache<'_>,
mut matrices: SourceMatrices<'_, '_, '_, '_>,
prepared: &[RoutedGateUpQ8<'_>],
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
source: &mut MoeRoutedSourceScope<'_, '_>,
gate: &mut Option<TransportBuffer<'ctx>>,
up: &mut Option<TransportBuffer<'ctx>>,
hidden: &mut Option<TransportBuffer<'ctx>>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
buffers: &mut GroupBuffers<'ctx>,
) -> Result<()> {
self.source_gate_up(cache, prepared, cancelled, source, gate, up)?;
let DirectRun { actual, packets, cancelled } = run;
self.source_gate_up(&mut matrices, prepared, cancelled, buffers)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.source_swiglu(gate, up, hidden)?;
self.source_down(cache, actual, packets, cancelled, source, hidden)
self.source_swiglu(buffers)?;
self.source_down(&mut matrices, DirectRun { actual, packets, cancelled }, &buffers.hidden)
}
fn source_gate_up(
&self,
cache: &mut MoeWeightCache<'_>,
matrices: &mut SourceMatrices<'_, '_, '_, '_>,
prepared: &[RoutedGateUpQ8<'_>],
cancelled: &mut impl FnMut() -> bool,
source: &mut MoeRoutedSourceScope<'_, '_>,
gate: &mut Option<TransportBuffer<'ctx>>,
up: &mut Option<TransportBuffer<'ctx>>,
buffers: &mut GroupBuffers<'ctx>,
) -> Result<()> {
let (pairs, scope) = (self.pairs, self.scope);
let (gate, up) = (&mut buffers.gate, &mut buffers.up);
let refs = prepared_refs(pairs, prepared)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
@@ -107,18 +122,18 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
let mut columns = workspace.begin_columns(&refs);
// Same full Gate completion precedes every Up operation.
let stage = leleka_cuda_driver::RoutedFiniteStage::Gate;
self.source_gate_up_role(cache, source, &mut columns, MoeMatrixRole::Gate, grouped, format, stage)?;
let target = GateUpTarget { grouped, format, stage };
self.source_gate_up_role(matrices, &mut columns, MoeMatrixRole::Gate, target)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
self.source_up(cache, source, &mut columns, up)
self.source_up(matrices, &mut columns, up)
})
}
fn source_up(
&self,
cache: &mut MoeWeightCache<'_>,
source: &mut MoeRoutedSourceScope<'_, '_>,
matrices: &mut SourceMatrices<'_, '_, '_, '_>,
columns: &mut leleka_cuda_driver::RoutedColumnsLoan<'_, '_, '_, 'ctx>,
up: &mut Option<TransportBuffer<'ctx>>,
) -> Result<()> {
@@ -127,21 +142,18 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
let grouped = up.as_mut().ok_or(Error::IdentityMismatch)?;
// Same full Up completion precedes SwiGLU and Down reuse.
let stage = leleka_cuda_driver::RoutedFiniteStage::Up;
self.source_gate_up_role(cache, source, columns, MoeMatrixRole::Up, grouped, format, stage)
self.source_gate_up_role(matrices, columns, MoeMatrixRole::Up, GateUpTarget { grouped, format, stage })
}
#[allow(clippy::too_many_arguments)]
fn source_gate_up_role(
&self,
cache: &mut MoeWeightCache<'_>,
source: &mut MoeRoutedSourceScope<'_, '_>,
matrices: &mut SourceMatrices<'_, '_, '_, '_>,
columns: &mut leleka_cuda_driver::RoutedColumnsLoan<'_, '_, '_, 'ctx>,
role: MoeMatrixRole,
grouped: &mut TransportBuffer<'ctx>,
format: RoutedFormat,
stage: leleka_cuda_driver::RoutedFiniteStage,
target: GateUpTarget<'_, 'ctx>,
) -> Result<()> {
cache.with_matrix_routed_source(self.binding, source, 0, role, |matrix, _, _| {
let GateUpTarget { grouped, format, stage } = target;
matrices.cache.with_matrix_routed_source(self.binding, matrices.source, 0, role, |matrix, _, _| {
match matrix {
CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format),
CachedMoeMatrix::Dual(actual, owner) => {
@@ -157,12 +169,8 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
})
}
fn source_swiglu(
&self,
gate: &Option<TransportBuffer<'ctx>>,
up: &Option<TransportBuffer<'ctx>>,
hidden: &mut Option<TransportBuffer<'ctx>>,
) -> Result<()> {
fn source_swiglu(&self, buffers: &mut GroupBuffers<'ctx>) -> Result<()> {
let (gate, up, hidden) = (&buffers.gate, &buffers.up, &mut buffers.hidden);
swiglu_into_hidden(self.context, self.scope, gate, up, hidden, self.pairs.len())?;
let stage = leleka_cuda_driver::RoutedFiniteStage::Hidden;
self.scope.finite_stage(hidden_buffer(hidden)?, stage, self.pairs.len())
@@ -170,54 +178,76 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
fn source_down(
&self,
cache: &mut MoeWeightCache<'_>,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
source: &mut MoeRoutedSourceScope<'_, '_>,
matrices: &mut SourceMatrices<'_, '_, '_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
hidden: &Option<TransportBuffer<'ctx>>,
) -> Result<()> {
let (binding, pairs, scope) = (self.binding, self.pairs, self.scope);
let DirectRun { actual, packets, cancelled } = run;
let (binding, scope) = (self.binding, self.scope);
let (kind, format) = down_kind_format(self.weights, self.selection)?;
let selections = self.packet_selections(packets)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
scope.with_workspace(|workspace| {
cache.with_matrix_routed_source(binding, source, 0, MoeMatrixRole::Down, |matrix, health, source| {
scope.project_columns_direct(
&selections,
|out, cancel| {
let input = hidden_buffer(hidden)?;
self.source_down_columns(workspace, matrix, kind, format, input, out, &selections, cancel)
},
|down_source, cancel| self.source_copy_down(actual, packets, health, source, down_source, cancel),
cancelled,
)
})
matrices.cache.with_matrix_routed_source(
binding,
matrices.source,
0,
MoeMatrixRole::Down,
|matrix, health, source| {
let projection = DownProjection { kind, format, matrix };
let launch = SourceDownLaunch { workspace, projection, selections: &selections };
let run = DirectRun { actual, packets: &mut *packets, cancelled: &mut *cancelled };
self.project_source_down(launch, SourceTail { health, source }, hidden, run)
},
)
})?;
Ok(())
}
/// The grouped Down projection of a source-backed group, then the copy of its columns into the row packets.
fn project_source_down(
&self,
launch: SourceDownLaunch<'_, 'ctx>,
tail: SourceTail<'_, '_, '_, '_>,
hidden: &Option<TransportBuffer<'ctx>>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let SourceDownLaunch { workspace, projection, selections } = launch;
let DirectRun { actual, packets, cancelled } = run;
self.scope.project_columns_direct(
selections,
|out, cancel| {
let input = hidden_buffer(hidden)?;
let launch = SourceDownLaunch { workspace: &mut *workspace, projection, selections };
self.source_down_columns(launch, DownBuffers { input, out }, cancel)
},
|down_source, cancel| {
let copy_run = DirectRun { actual, packets: &mut *packets, cancelled: cancel };
self.source_copy_down(copy_run, tail, down_source)
},
cancelled,
)
}
/// Only the numerical refusal needs host values. The unchanged full Hidden download observes the same alive
/// allocation, then original ascending-row arbitration runs.
#[allow(clippy::too_many_arguments)]
fn source_down_columns(
&self,
workspace: &mut leleka_cuda_driver::RoutedGroupWorkspace<'ctx>,
matrix: CachedMoeMatrix<'_, '_>,
kind: MoeMatrixKind,
format: RoutedFormat,
input: &DeviceBuffer<'ctx>,
out: &mut DeviceBuffer<'ctx>,
selections: &[DownSelection],
launch: SourceDownLaunch<'_, 'ctx>,
buffers: DownBuffers<'_, 'ctx>,
cancel: &mut impl FnMut() -> bool,
) -> Result<()> {
let SourceDownLaunch { workspace, projection, selections } = launch;
let DownProjection { format, matrix, .. } = projection;
let DownBuffers { input, out } = buffers;
let pairs = self.pairs;
let result = launch_down_in_workspace(workspace, matrix, input, out, pairs.len(), format)?;
down_outcome(result, || {
let hidden_values = download_f32(input, pairs.len() * FF)?;
ordered_down_refusal(self.context, kind, matrix, &hidden_values, selections, self.scope, cancel)
let replay = RefusalReplay { hidden_values: &hidden_values, selections };
ordered_down_refusal(self.context, projection, replay, self.scope, cancel)
})
}
@@ -226,15 +256,15 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
/// coverage or group acceptance; failure discards all copied private packets.
fn source_copy_down(
&self,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
health: &RoutedSourceHealth<'_, '_>,
source: &mut MoeRoutedSourceScope<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
tail: SourceTail<'_, '_, '_, '_>,
down_source: &DeviceBuffer<'ctx>,
cancel: &mut impl FnMut() -> bool,
) -> Result<()> {
let DirectRun { actual, packets, cancelled: cancel } = run;
let SourceTail { health, source } = tail;
let (context, binding, pairs) = (self.context, self.binding, self.pairs);
validate_packet_pairs(actual, binding, self.rows, pairs, self.origins, packets)?;
let members = PacketGroupMembers { rows: self.rows, pairs, origins: self.origins };
validate_packet_pairs(actual, binding, members, packets)?;
let mut targets = packet_targets(pairs, packets)?;
super::super::moe_down::ResidentPackedDown::copy_group_with(self.scope, &mut targets, |copies| {
context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?;
@@ -1,5 +1,9 @@
//! Moved out of the parent module by STRA-338: fn project_group_source_fenced.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::direct_packets_fns::PacketRun;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::project_group_direct_fn::{DirectGroup, DirectRun};
#[allow(unused_imports)]
use super::*;
@@ -13,37 +17,49 @@ fn source_members<'a>(rows: &'a [ChunkFfnRow], pairs: &[Pair]) -> Result<Vec<(&'
Ok(members)
}
/// The source callback keeps the actual artifact RefMut for all descriptor
/// and cold-read consumers. Its mapped-error bridge preserves runtime
/// primary failures while still attempting the mandatory source finish.
/// The real cache is rechecked after the matrix loan and source loan have ended;
/// private packets still belong to execute_direct_packets on any failure.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
#[allow(clippy::too_many_arguments)]
pub(super) fn project_group_source_fenced<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
pairs: &[Pair],
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
cache.validate(binding, context)?;
if !cache.uses_direct_native_down_packets() {
return Err(Error::IdentityMismatch);
impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> {
/// One expert group of the layer batch, identified by its pairs, with the weights its first pair selects.
fn direct_group<'g>(&'g self, pairs: &'g [Pair]) -> DirectGroup<'g, 'ctx> {
let first = pairs[0];
let weights = &self.rows[first.row].row().weights;
let selection = MoeExpertSelection::Routed { slot: first.slot };
DirectGroup {
context: self.context,
binding: self.binding,
rows: self.rows,
pairs,
scope: self.scope,
origins: self.origins,
weights,
selection,
}
}
/// The source callback keeps the actual artifact RefMut for all descriptor
/// and cold-read consumers. Its mapped-error bridge preserves runtime
/// primary failures while still attempting the mandatory source finish.
/// The real cache is rechecked after the matrix loan and source loan have ended;
/// private packets still belong to `PacketRun::execute` on any failure.
pub(super) fn project_group_fenced(
&self,
pairs: &[Pair],
cache: &mut MoeWeightCache<'_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins);
let DirectRun { actual, packets, cancelled } = run;
validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?;
cache.validate(binding, context)?;
if !cache.uses_direct_native_down_packets() {
return Err(Error::IdentityMismatch);
}
let members = source_members(rows, pairs)?;
let operation = binding.with_moe_routed_source(&members, binding_error, |source| {
let consumers = DirectRun { actual, packets: &mut *packets, cancelled: &mut *cancelled };
project_group_source_consumers(self.direct_group(pairs), cache, self.prepared, consumers, source)
});
let health_check = cache.validate(binding, context);
operation.and(health_check)
}
let members = source_members(rows, pairs)?;
let operation = binding.with_moe_routed_source(&members, binding_error, |source| {
project_group_source_consumers(
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, source,
)
});
let health_check = cache.validate(binding, context);
operation.and(health_check)
}
@@ -50,13 +50,13 @@ struct DirectRun {
words: usize,
}
/// The loaded direct-Down inputs of one fresh session; every arm is run against the same snapshot.
struct LoadedArms<'a, 'k, 'ctx> {
binding: &'a ModelBinding,
context: &'a Rc<Context<'ctx>>,
session: &'a mut QwenSession<'ctx>,
kar: &'a mut KarPleCache<'k>,
cache: &'a mut MoeWeightCache<'ctx>,
dense: &'a DenseWeightCache<'ctx>,
pub(crate) struct LoadedArms<'a, 'k, 'ctx> {
pub(crate) binding: &'a ModelBinding,
pub(crate) context: &'a Rc<Context<'ctx>>,
pub(crate) session: &'a mut QwenSession<'ctx>,
pub(crate) kar: &'a mut KarPleCache<'k>,
pub(crate) cache: &'a mut MoeWeightCache<'ctx>,
pub(crate) dense: &'a DenseWeightCache<'ctx>,
}
#[path = "moe_group_down_direct_gpu/policy_fn.rs"]
@@ -3,26 +3,21 @@
#[allow(unused_imports)]
use super::*;
#[allow(clippy::too_many_arguments)]
pub(super) fn arm<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
arms: &mut LoadedArms<'_, '_, 'ctx>,
old: bool,
cancel_after_copy: bool,
) -> Result<ObservedArm> {
let (binding, context, dense) = (arms.binding, arms.context, arms.dense);
let (session, kar, cache) = (&mut *arms.session, &mut *arms.kar, &mut *arms.cache);
let observation = Observation::begin(old)?;
let (layer, tokens) = arm_tokens()?;
let transient = 3 * (K * N * 4 + 10240 + 2884 + 3 * FF * 4 + N * 4 + 720) + DEVICE_PEAK;
cache.reserve_mmq_transient(binding, context, transient)?;
let mut chunk = QwenChunkTxn::begin(session, binding, &tokens, None, 512 * 1024 * 1024)?;
let rows = arm_chunk_rows(binding, kar, dense, layer, &mut chunk)?;
let values = MoeExpertStage::execute_chunk(binding, layer, &rows, &mut chunk, cache, &mut || {
cancel_probe(cancel_after_copy)
})?;
let ffn = ChunkFfnLayer { binding, layer, rows: &rows };
let values = MoeExpertStage::execute_chunk(ffn, &mut chunk, cache, &mut || cancel_probe(cancel_after_copy))?;
let packets = observation.take()?;
// Completed layer0 FFN products remain private: no injection/head/all48 or
// joint target publication. A canceled real chunk is dropped, not repaired.
@@ -5,7 +5,7 @@ use super::*;
impl LoadedArms<'_, '_, '_> {
pub(super) fn arm(&mut self, old: bool, cancel_after_copy: bool) -> Result<ObservedArm> {
arm(self.binding, self.context, self.session, self.kar, self.cache, self.dense, old, cancel_after_copy)
arm(self, old, cancel_after_copy)
}
pub(super) fn matches_snapshot(&self, initial: &ResetReplaySnapshot) -> Result<bool> {
Ok(initial.numeric_eq(&self.session.test_reset_replay_snapshot(self.binding)?))
@@ -64,15 +64,8 @@ impl LoadedArms<'_, '_, '_> {
impl QwenForward {
/// ONE genuine loaded binding/fresh session. Every arm independently mints
/// real three-row chunk/FFN proofs; canceled chunks are dropped unchanged.
pub(crate) fn test_direct_down_on_loaded<'ctx>(
binding: &ModelBinding,
context: &Rc<Context<'ctx>>,
session: &mut QwenSession<'ctx>,
kar: &mut KarPleCache<'_>,
cache: &mut MoeWeightCache<'ctx>,
dense: &DenseWeightCache<'ctx>,
) -> Result<DirectDownReport> {
let mut arms = LoadedArms { binding, context, session, kar, cache, dense };
pub(crate) fn test_direct_down_on_loaded<'ctx>(mut arms: LoadedArms<'_, '_, 'ctx>) -> Result<DirectDownReport> {
let context = arms.context;
let initial = arms.precheck()?;
let mut run = arms.reference_and_candidate(&initial)?;
let (cancelled_after_copy, reset_exact) = arms.cancel_and_recover(&initial, &mut run)?;
@@ -1,5 +1,5 @@
//! Closed original-kernel resident expert pipeline and genuine packet handoff.
use super::project_group_direct_fn::DirectGroup;
use super::project_group_direct_fn::{DirectGroup, DownProjection, RefusalReplay};
use super::project_group_shared_fns::{down_format, gate_up_format, packet_targets};
use super::project_group_source_consumers_fn::check_source_members;
use super::*;
@@ -20,7 +20,7 @@ pub(super) fn project_group_packets<'ctx>(
actual: &QwenChunkTxn<'_, '_>,
ephemeral_slot: Option<usize>,
) -> Result<()> {
validate_packet_pairs(actual, binding, rows, pairs, origins, packets)?;
validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?;
cache.validate(binding, context)?;
if !uses_adaptive(cache) || !use_direct_packets(cache) {
return Err(Error::IdentityMismatch);
@@ -185,7 +185,9 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
let values = download_f32(hidden.ok_or(Error::IdentityMismatch)?, self.group.pairs.len() * FF)?;
let matrix = CachedMoeMatrix::Raw(down);
let (context, scope) = (self.group.context, self.group.scope);
ordered_down_refusal(context, self.down_kind, matrix, &values, &self.selections, scope, observed_cancel)
let projection = DownProjection { kind: self.down_kind, format: self.down_format, matrix };
let replay = RefusalReplay { hidden_values: &values, selections: &self.selections };
ordered_down_refusal(context, projection, replay, scope, observed_cancel)
}
fn copy_down(
@@ -199,7 +201,8 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
) -> Result<()> {
let group = &self.group;
let (context, binding, pairs) = (group.context, group.binding, group.pairs);
validate_packet_pairs(actual, binding, group.rows, pairs, group.origins, packets)?;
let members = PacketGroupMembers { rows: group.rows, pairs, origins: group.origins };
validate_packet_pairs(actual, binding, members, packets)?;
let mut targets = packet_targets(pairs, packets)?;
super::super::moe_down::ResidentPackedDown::copy_group_with(group.scope, &mut targets, |copies| {
context.copy_routed_down_columns_to_slots(down_source, pairs.len(), copies).map_err(driver_error)?;
@@ -72,7 +72,7 @@ impl MoeExpertStage {
) -> Result<()> {
let _arm = observation::arm(arm)?;
let products = if arm == 0 {
Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)?
Self::execute_chunk(ChunkFfnLayer { binding, layer, rows }, chunk, cache, &mut || false)?
} else {
Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)?
};
@@ -1,6 +1,6 @@
//! Explicit experimental adaptive MMQ chunk producer. Native T1 stays native.
//! Real sealed rows, one source/Q8 layer batch, real group leases, one slotpack.
use super::resident_slotpack::SlotPacks;
use super::resident_slotpack::{SealedLayer, SlotPacks};
use super::*;
use leleka_cuda_driver::MmqWorkspace;
#[path = "moe_mmq_chunk/admission_fns.rs"]
@@ -144,12 +144,10 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> {
let (binding, layer, rows) = (self.binding, self.layer, self.rows);
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(finish) = self.native {
let (products, dense) = (finish.products, finish.dense);
return MoeExpertStage::execute_chunk_native_prompt(
binding, layer, rows, chunk, cache, cancelled, products, dense,
);
let ffn = ChunkFfnLayer { binding, layer, rows };
return MoeExpertStage::execute_chunk_native_prompt(ffn, chunk, cache, cancelled, finish);
}
let result = MoeExpertStage::execute_chunk(binding, layer, rows, chunk, cache, cancelled);
let result = MoeExpertStage::execute_chunk(ChunkFfnLayer { binding, layer, rows }, chunk, cache, cancelled);
#[cfg(test)]
if result.is_ok() {
cache.note_test_mmq_dispatch(false, rows.len());
@@ -158,7 +158,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
) -> Result<Vec<ExpertReady>> {
let (inputs, ids) = self.gather_rows()?;
let groups = grouped_pairs(&ids)?;
let mut packets = SlotPacks::new(self.txn, self.binding, self.layer, self.rows, self.context, scope)?;
let mut packets = SlotPacks::new(self.sealed_layer(), self.rows, self.context, scope)?;
let mut activations = reserved(self.rows.len())?;
let operation = self.operate(
scope,
@@ -177,6 +177,11 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
operation.and_then(|values| cleanup.map(|()| values))
}
/// The sealed transaction, binding and layer the window rows are validated against.
fn sealed_layer(&self) -> SealedLayer<'_, '_, 'ctx> {
SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer }
}
fn gather_rows(&self) -> Result<(Vec<f32>, Vec<[u32; K]>)> {
let mut inputs = reserved(self.rows.len().checked_mul(N).ok_or(Error::Overflow)?)?;
let mut ids = reserved(self.rows.len())?;
@@ -20,22 +20,25 @@ pub(super) struct SlotPacks<'source, 'session, 'ctx> {
origins: Vec<Rc<DownOrigin>>,
packets: Vec<ResidentPackedDown<'ctx>>,
}
fn validate_row(
txn: &QwenChunkTxn<'_, '_>,
binding: &ModelBinding,
layer: LayerId,
index: usize,
row: &ChunkFfnRow,
origin: &Rc<DownOrigin>,
) -> Result<()> {
let global = txn.micro_row_index(index)?;
txn.validate_ffn_row(global, layer, row)?;
let (token, position) = txn.row_ids(global)?;
if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() {
return Err(Error::IdentityMismatch);
/// The sealed chunk transaction, the binding and the layer a window row is validated against.
#[derive(Clone, Copy)]
pub(super) struct SealedLayer<'a, 'session, 'ctx> {
pub(super) txn: &'a QwenChunkTxn<'session, 'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) layer: LayerId,
}
impl SealedLayer<'_, '_, '_> {
fn validate_row(&self, index: usize, row: &ChunkFfnRow, origin: &Rc<DownOrigin>) -> Result<()> {
let Self { txn, binding, layer } = *self;
let global = txn.micro_row_index(index)?;
txn.validate_ffn_row(global, layer, row)?;
let (token, position) = txn.row_ids(global)?;
if !origin.binding.matches(&binding.identity()) || origin.identity != row.row().route.identity() {
return Err(Error::IdentityMismatch);
}
origin.identity.validate(token, position, layer)?;
row.row().validate(&binding.identity(), token, position, layer)
}
origin.identity.validate(token, position, layer)?;
row.row().validate(&binding.identity(), token, position, layer)
}
/// The sealed rows a group copy is validated against, borrowed apart from the mutable packet storage.
struct RowsView<'a, 'session, 'ctx> {
@@ -45,7 +48,7 @@ struct RowsView<'a, 'session, 'ctx> {
rows: &'a [ChunkFfnRow],
origins: &'a [Rc<DownOrigin>],
}
impl RowsView<'_, '_, '_> {
impl<'a, 'session, 'ctx> RowsView<'a, 'session, 'ctx> {
fn validate_group_columns(&self, group: &GroupOrigin) -> Result<()> {
for (column, pair) in group.pairs.iter().enumerate() {
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
@@ -54,10 +57,13 @@ impl RowsView<'_, '_, '_> {
{
return Err(Error::IdentityMismatch);
}
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
self.sealed().validate_row(pair.row, row, origin)?;
}
Ok(())
}
fn sealed(&self) -> SealedLayer<'a, 'session, 'ctx> {
SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer }
}
}
/// The packets of the group rows, in ascending row order, each with the slot its column lands in.
fn select_packets<'p, 'ctx>(
@@ -112,13 +118,12 @@ fn reserve_packets<'ctx>(
}
impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
pub(super) fn new(
txn: &'source QwenChunkTxn<'session, 'ctx>,
binding: &'source ModelBinding,
layer: LayerId,
sealed: SealedLayer<'source, 'session, 'ctx>,
rows: &'source [ChunkFfnRow],
context: &'ctx Context<'ctx>,
scope: &'source DownScope<'ctx>,
) -> Result<Self> {
let SealedLayer { txn, binding, layer } = sealed;
if rows.len() != txn.micro_len()? || !(1..=64).contains(&rows.len()) || !std::ptr::eq(context, txn.context()?) {
return Err(Error::IdentityMismatch);
}
@@ -126,6 +131,9 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
let (origins, packets) = reserve_packets(binding, rows, scope)?;
Ok(Self { owner: Rc::new(()), txn, binding, layer, rows, context, scope, origins, packets })
}
fn sealed(&self) -> SealedLayer<'source, 'session, 'ctx> {
SealedLayer { txn: self.txn, binding: self.binding, layer: self.layer }
}
pub(super) fn group(&self, expert: u32, pairs: &[Pair]) -> Result<GroupOrigin> {
if expert >= 512 || !(1..=self.rows.len()).contains(&pairs.len()) {
return Err(Error::InvalidExpert);
@@ -146,7 +154,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
fn admit_pair(&self, expert: u32, previous: Option<usize>, pair: &Pair) -> Result<Rc<DownOrigin>> {
let row = self.rows.get(pair.row).ok_or(Error::IdentityMismatch)?;
let origin = self.origins.get(pair.row).ok_or(Error::IdentityMismatch)?;
validate_row(self.txn, self.binding, self.layer, pair.row, row, origin)?;
self.sealed().validate_row(pair.row, row, origin)?;
if pair.slot >= K
|| previous.is_some_and(|old| old >= pair.row)
|| row.row().route.experts()[pair.slot].get() != expert
@@ -165,7 +173,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
let mut previous = None;
for (column, pair) in group.pairs.iter().enumerate() {
let origin = self.admit_group_column(group, column, previous, pair)?;
validate_row(self.txn, self.binding, self.layer, pair.row, origin.0, origin.1)?;
self.sealed().validate_row(pair.row, origin.0, origin.1)?;
previous = Some(pair.row);
}
Ok(())
@@ -230,7 +238,7 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
let mut packets = Vec::new();
packets.try_reserve_exact(self.rows.len()).map_err(|_| Error::InputAllocation)?;
for (index, packet) in self.packets.iter().enumerate() {
validate_row(self.txn, self.binding, self.layer, index, &self.rows[index], &self.origins[index])?;
self.sealed().validate_row(index, &self.rows[index], &self.origins[index])?;
packet.complete(self.scope)?;
packets.push(packet);
}
@@ -249,21 +257,15 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
}
fn finish_values(
&self,
row: &ChunkFfnRow,
origin: &Rc<DownOrigin>,
tail: RowTail<'_, 'ctx, '_>,
packed: &ResidentPackedDown<'ctx>,
activation: &DeviceBuffer<'_>,
cache: &mut MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let (context, binding, scope) = (self.context, self.binding, self.scope);
let scope = self.scope;
if use_shared_tail(cache) {
packed.with_completed(scope, |packet| {
finish_shared_queued(context, binding, row.row(), activation, cache, scope, origin, packet)
})
packed.with_completed(scope, |packet| finish_shared_queued(tail, cache, packet))
} else {
finish_shared_with(context, binding, row.row(), activation, cache, scope, origin, |weights, scaled| {
packed.combine(scope, weights, scaled)
})
finish_shared_with(tail, cache, |weights, scaled| packed.combine(scope, weights, scaled))
}
}
pub(super) fn finish_row(
@@ -275,14 +277,22 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
) -> Result<ExpertReady> {
let row = self.rows.get(index).ok_or(Error::IdentityMismatch)?;
let origin = self.origins.get(index).ok_or(Error::IdentityMismatch)?;
validate_row(self.txn, self.binding, self.layer, index, row, origin)?;
self.sealed().validate_row(index, row, origin)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let packed = self.packets.get(index).ok_or(Error::IdentityMismatch)?;
packed.complete(self.scope)?;
let values = self.finish_values(row, origin, packed, activation, cache)?;
validate_row(self.txn, self.binding, self.layer, index, row, origin)?;
let tail = RowTail {
context: self.context,
binding: self.binding,
row: row.row(),
activation,
scope: self.scope,
origin,
};
let values = self.finish_values(tail, packed, cache)?;
self.sealed().validate_row(index, row, origin)?;
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
@@ -339,7 +339,7 @@ pub(super) struct RoutedSourceHealth<'cache, 'ctx> {
#[path = "cache_original_mtp_weights.rs"]
mod original_mtp_weights;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
pub(in crate::qwen_forward) use original_mtp_weights::RetainedOriginalMtpWeights;
pub(in crate::qwen_forward) use original_mtp_weights::{MtpHeadSources, RetainedOriginalMtpWeights};
mod validate_ranked_profile_fn;
#[allow(unused_imports)]
@@ -3,6 +3,7 @@
use super::impl_moeweightcache_3::shared_keys_fn::{raw_shared_buffers, shared_descriptors};
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::mtp_experts::fixed_workspace::{ExpertInputs, FrameAnchor, WorkspaceClaim};
impl<'ctx> MoeWeightCache<'ctx> {
/// Source-descriptor admission precedes all fills. Requested entries cannot
@@ -118,19 +119,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
failed: &Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
slot.as_mut().ok_or(Error::IdentityMismatch)?.compose(
binding,
&self.mmq_owner,
context,
frame,
session,
bank,
shared,
mixed,
ids,
weights,
Rc::clone(failed),
)
let anchor = FrameAnchor { binding, frame, session };
let claim = WorkspaceClaim { owner: &self.mmq_owner, context };
let inputs = ExpertInputs { bank, shared, mixed, ids, weights };
slot.as_mut().ok_or(Error::IdentityMismatch)?.compose(anchor, claim, inputs, Rc::clone(failed))
}
pub(in super::super::super) fn has_mtp_kv_ring(&self) -> Result<bool> {
let slot = self.mtp_kv.try_borrow().map_err(|_| Error::IdentityMismatch)?;
@@ -38,6 +38,16 @@ pub(super) struct MtpInput {
frame: MtpFrame,
streams: Box<[f32]>,
}
/// The target step product a draft input extends together with the known next token it is conditioned on.
pub(super) struct KnownNext<'a, P> {
pub(super) source: &'a P,
pub(super) next_token: TokenId,
}
/// The target session and the draft session that one MTP draft step advances together.
pub(super) struct StepSessions<'a, 'driver, 'draft> {
pub(super) target: &'a mut QwenSession<'driver>,
pub(super) draft: &'draft mut MtpSession,
}
/// A completed draft with its exact post-MLP residual. Only this composer can
/// publish draft state after the reused main output head finishes successfully.
pub(super) struct MtpStepProduct {
@@ -37,6 +37,11 @@ impl MtpFrame {
&& self.origin.same_prefix(&other.origin)
}
}
/// The hidden residual streams of the source row and the embedding row of the next token.
struct InputRows<'a> {
streams: &'a [f32],
embedding: &'a [f32],
}
impl MtpInput {
pub(in super::super) fn from_previous(
binding: &ModelBinding,
@@ -67,10 +72,10 @@ impl MtpInput {
binding: &ModelBinding,
session: &QwenSession<'_>,
draft: &MtpSession,
source: &TargetStepProduct,
next_token: TokenId,
next: KnownNext<'_, TargetStepProduct>,
cache: &MoeWeightCache<'_>,
) -> Result<Self> {
let KnownNext { source, next_token } = next;
let (_, position, streams, origin) = source.mtp_source(binding, session)?;
let frame = draft.frame(binding, position, next_token, origin)?;
frame.validate(binding, session)?;
@@ -80,10 +85,10 @@ impl MtpInput {
binding: &ModelBinding,
session: &QwenSession<'_>,
draft: &MtpSession,
source: &PrefillStepProduct,
next_token: TokenId,
next: KnownNext<'_, PrefillStepProduct>,
cache: &MoeWeightCache<'_>,
) -> Result<Self> {
let KnownNext { source, next_token } = next;
let (_, position, streams, origin) = source.mtp_source(binding, session)?;
let frame = draft.frame(binding, position, next_token, origin)?;
frame.validate(binding, session)?;
@@ -106,7 +111,7 @@ impl MtpInput {
preflight(context, 2 * 40960 + 5 * 10240 + 2 * 1310720 + 10000)?;
let embedding = binding.embedding_row(frame.token.get()).map_err(binding_error)?;
if cache.has_mtp_input_workspace() {
return Self::compute_queued(binding, session, frame, streams, &embedding, cache);
return Self::compute_queued(binding, session, frame, InputRows { streams, embedding: &embedding }, cache);
}
Self::compute_host(binding, session, frame, (streams, &embedding), (context, cache))
}
@@ -117,9 +122,9 @@ impl MtpInput {
(streams, embedding): (&[f32], &[f32]),
(context, cache): (&Context<'_>, &MoeWeightCache<'_>),
) -> Result<Self> {
let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, false, cache)?;
let en = norm(context, binding, MtpRole::EmbeddingNorm, embedding, cache)?;
let e2 = project(context, binding, MtpRole::FcEmbedding, &en, cache)?;
let hn = norm(context, binding, MtpRole::HiddenNorm, streams, true, cache)?;
let hn = norm(context, binding, MtpRole::HiddenNorm, streams, cache)?;
let h2 = project_hidden_chunks(context, binding, &hn, cache)?;
let result = broadcast_streams(context, &h2, &e2)?;
frame.validate(binding, session)?;
@@ -130,10 +135,10 @@ impl MtpInput {
binding: &ModelBinding,
session: &QwenSession<'_>,
frame: MtpFrame,
streams: &[f32],
embedding: &[f32],
rows: InputRows<'_>,
cache: &MoeWeightCache<'_>,
) -> Result<Self> {
let InputRows { streams, embedding } = rows;
let context = session.mtp_context()?;
let en_gamma = f32_weights(binding, MtpRole::EmbeddingNorm, cache)?;
validate_values(embedding, 2560)?;
@@ -6,13 +6,12 @@ use super::*;
pub(in super::super) fn step(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
draft: &mut MtpSession,
sessions: StepSessions<'_, '_, '_>,
input: MtpInput,
output: &super::super::output::OutputStage<'_, '_>,
cache: &MoeWeightCache<'_>,
) -> Result<MtpStepProduct> {
step_core(binding, session, draft, input, Some(output), cache)?.ok_or(Error::IdentityMismatch)
step_core(binding, sessions, input, Some(output), cache)?.ok_or(Error::IdentityMismatch)
}
/// Known-next warm path publishes the real draft state, without an unused head.
pub(in super::super) fn warm_step(
@@ -22,7 +21,7 @@ pub(in super::super) fn warm_step(
input: MtpInput,
cache: &MoeWeightCache<'_>,
) -> Result<()> {
if step_core(binding, session, draft, input, None, cache)?.is_some() {
if step_core(binding, StepSessions { target: session, draft }, input, None, cache)?.is_some() {
return Err(Error::IdentityMismatch);
}
Ok(())
@@ -96,12 +95,12 @@ fn copy_streams(values: &[f32]) -> Result<(Vec<f32>, Vec<f32>)> {
}
fn step_run(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
draft: &mut MtpSession,
sessions: &mut StepSessions<'_, '_, '_>,
input: MtpInput,
output: Option<&super::super::output::OutputStage<'_, '_>>,
(cache, transport_failed): (&MoeWeightCache<'_>, &Rc<Cell<bool>>),
) -> Result<Option<MtpStepProduct>> {
let (session, draft) = (&mut *sessions.target, &mut *sessions.draft);
input.frame.validate(binding, session)?;
draft.prior(&input.frame)?;
let blocks = run_blocks(binding, &input, (session, draft), cache, transport_failed)?;
@@ -115,14 +114,14 @@ fn step_run(
}
pub(super) fn step_core(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
draft: &mut MtpSession,
mut sessions: StepSessions<'_, '_, '_>,
input: MtpInput,
output: Option<&super::super::output::OutputStage<'_, '_>>,
cache: &MoeWeightCache<'_>,
) -> Result<Option<MtpStepProduct>> {
let transport_failed = Rc::new(Cell::new(false));
let result = step_run(binding, session, draft, input, output, (cache, &transport_failed));
let result = step_run(binding, &mut sessions, input, output, (cache, &transport_failed));
let session = &mut *sessions.target;
if transport_failed.get() {
session.note_mtp_failure(&Error::CudaExecution);
}
@@ -181,9 +180,9 @@ pub(super) fn norm(
binding: &ModelBinding,
role: MtpRole,
values: &[f32],
hidden: bool,
cache: &MoeWeightCache<'_>,
) -> Result<Box<[f32]>> {
let hidden = role == MtpRole::HiddenNorm;
let gamma = f32_weights(binding, role, cache)?;
let n = norm_width(hidden);
validate_values(values, n)?;
@@ -3,9 +3,11 @@
use super::{
contract::{Dimension, Error, Position, Result, TokenId},
executor::{PrefillStepProduct, QwenForward, TargetStepProduct},
executor::{
PrefillStepProduct, QwenForward, TargetStepProduct, VerificationChunk, VerificationSource, WindowCaches,
},
kar_ple_cache::KarPleCache,
mtp::{self, MtpInput, MtpSession, reserve},
mtp::{self, KnownNext, MtpInput, MtpSession, StepSessions, reserve},
output::OutputStage,
session::QwenSession,
};
@@ -105,8 +105,14 @@ impl MtpDecoder {
) -> Result<()> {
let prior = self.draft.checkpoint()?;
let result = (|| {
let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?;
mtp::step(binding, target, &mut self.draft, input, output, cache)?;
let input = MtpInput::from_target(
binding,
target,
&self.draft,
KnownNext { source, next_token: known_next },
cache,
)?;
mtp::step(binding, StepSessions { target, draft: &mut self.draft }, input, output, cache)?;
Ok(())
})();
if let Err(error) = result {
@@ -129,7 +135,13 @@ impl MtpDecoder {
) -> Result<()> {
let prior = self.draft.checkpoint()?;
let result = (|| {
let input = MtpInput::from_target(binding, target, &self.draft, source, known_next, cache)?;
let input = MtpInput::from_target(
binding,
target,
&self.draft,
KnownNext { source, next_token: known_next },
cache,
)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)
})();
if let Err(error) = result {
@@ -150,7 +162,13 @@ impl MtpDecoder {
) -> Result<()> {
let prior = self.draft.checkpoint()?;
let result = (|| {
let input = MtpInput::from_prefill(binding, target, &self.draft, source, known_next, cache)?;
let input = MtpInput::from_prefill(
binding,
target,
&self.draft,
KnownNext { source, next_token: known_next },
cache,
)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)
})();
if let Err(error) = result {
@@ -87,7 +87,8 @@ impl MtpDecoder {
};
// Pure complete-state admission before any draft/canonical mutation.
let budget = capacity_budget(cache, host_remaining)?;
let capacity = QwenForward::mtp_target_window_capacity(binding, source, eos, target, limit, budget)?;
let source = VerificationSource { product: source, eos };
let capacity = QwenForward::mtp_target_window_capacity(binding, source, target, limit, budget)?;
Ok(BatchedPlan { first, limit, reuse_first_seed, seed_host_charge, host_remaining, capacity })
}
@@ -138,7 +139,7 @@ impl MtpDecoder {
};
let input = self.batched_chain_input(cx, target, cache, previous.as_ref(), candidate)?;
let seed_frame = plan.seed_frame(previous.is_none(), &input);
let product = mtp::step(binding, target, &mut self.draft, input, cx.output, cache)?;
let product = mtp::step(binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?;
first_seed = self.capture_seed(plan, seed_frame)?.or(first_seed);
st.candidates.push(product.predicted(binding, target)?);
previous = Some(product);
@@ -161,7 +162,10 @@ impl MtpDecoder {
) -> Result<MtpInput> {
match previous {
Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache),
None => MtpInput::from_target(cx.binding, target, &self.draft, cx.source, candidate, cache),
None => {
let next = KnownNext { source: cx.source, next_token: candidate };
MtpInput::from_target(cx.binding, target, &self.draft, next, cache)
}
}
}
@@ -206,7 +210,8 @@ impl MtpDecoder {
if cancelled() {
return Err(MtpWindowError::Cancelled);
}
let input = MtpInput::from_target(binding, target, &self.draft, source, cx.plan.first, cache)?;
let next = KnownNext { source, next_token: cx.plan.first };
let input = MtpInput::from_target(binding, target, &self.draft, next, cache)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
Ok(())
}
@@ -231,15 +236,16 @@ impl MtpDecoder {
let (source, eos, output, dense) = (cx.source, cx.eos, cx.output, cx.dense_cache);
let (kar, proposals, host) = (kar_cache.as_deref_mut(), &st.candidates[..rows], plan.host_remaining);
let observer = observe_cancel(cancelled, &mut fired);
let prepared = QwenForward::prepare_mtp_target_window(
binding, source, proposals, eos, target, output, kar, cache, dense, host, observer,
);
let source = VerificationSource { product: source, eos };
let chunk = VerificationChunk { binding, source, proposals, output, dense_cache: dense, host_remaining: host };
let prepared = QwenForward::prepare_mtp_target_window(chunk, target, kar, cache, observer);
let pending = prepared.map_err(|error| window_stage_error(error, fired))?;
cx.check_accepted(pending.accepted_rows(), rows)?;
st.tokens.extend_from_slice(&st.candidates[..pending.accepted_rows()]);
let mut fired = false;
let observer = observe_cancel(cancelled, &mut fired);
let published = pending.publish_joint_with_gdn_replay(binding, &mut self.draft, cache, Some(dense), observer);
let caches = WindowCaches { moe: cache, dense: Some(dense) };
let published = pending.publish_joint_with_gdn_replay(binding, &mut self.draft, caches, observer);
published.map_err(|error| window_stage_error(error, fired))
}
@@ -164,7 +164,8 @@ impl MtpDecoder {
break;
}
let input = self.scalar_chain_input(cx, target, cache, previous.as_ref(), st, candidate)?;
let product = mtp::step(cx.binding, target, &mut self.draft, input, cx.output, cache)?;
let product =
mtp::step(cx.binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?;
st.candidates.push(product.predicted(cx.binding, target)?);
previous = Some(product);
}
@@ -184,7 +185,13 @@ impl MtpDecoder {
Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache),
None => {
let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?;
MtpInput::from_target(cx.binding, target, &self.draft, latest, candidate, cache)
MtpInput::from_target(
cx.binding,
target,
&self.draft,
KnownNext { source: latest, next_token: candidate },
cache,
)
}
}
}
@@ -266,7 +273,13 @@ impl MtpDecoder {
expected: TokenId,
) -> WindowResult<()> {
let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?;
let input = MtpInput::from_target(binding, target, &self.draft, latest, expected, cache)?;
let input = MtpInput::from_target(
binding,
target,
&self.draft,
KnownNext { source: latest, next_token: expected },
cache,
)?;
mtp::warm_step(binding, target, &mut self.draft, input, cache)?;
if cancelled() {
return Err(MtpWindowError::Cancelled);
@@ -9,16 +9,17 @@ use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
macro_rules! prepare_window {
($flow:expr, $candidate:expr, ($source:expr, $proposals:expr, $eos:expr)) => {
QwenForward::prepare_mtp_target_window(
$flow.shared.binding,
$source,
$proposals,
$eos,
$crate::qwen_forward::executor::VerificationChunk {
binding: $flow.shared.binding,
source: $crate::qwen_forward::executor::VerificationSource { product: $source, eos: $eos },
proposals: $proposals,
output: $flow.shared.output,
dense_cache: $flow.shared.dense,
host_remaining: TRANSACTION_CAP,
},
&mut $flow.target,
$flow.shared.output,
Some(&mut *$flow.shared.kar),
$candidate,
$flow.shared.dense,
TRANSACTION_CAP,
|| false,
)
};
@@ -91,6 +91,39 @@ pub(in crate::qwen_forward) struct MtpExpertWorkspace<'ctx> {
owner: Rc<()>,
storage: FixedBuffers<'ctx>,
}
/// The draft frame, checked against the model binding and the target session before and after a composition.
pub(in crate::qwen_forward) struct FrameAnchor<'a, 'session> {
pub(in crate::qwen_forward) binding: &'a ModelBinding,
pub(in crate::qwen_forward) frame: &'a MtpFrame,
pub(in crate::qwen_forward) session: &'a QwenSession<'session>,
}
/// The cache owner token and the device context that must be the ones this workspace was created for.
pub(in crate::qwen_forward) struct WorkspaceClaim<'a, 'ctx> {
pub(in crate::qwen_forward) owner: &'a Rc<()>,
pub(in crate::qwen_forward) context: &'a Context<'ctx>,
}
/// What one draft composition reads: the expert bank, the shared-expert matrices, the mixed hidden row and the
/// ids and weights of the ten routed experts.
#[derive(Clone, Copy)]
pub(in crate::qwen_forward) struct ExpertInputs<'a, 'bank, 'shared> {
pub(in crate::qwen_forward) bank: &'a DeviceBuffer<'bank>,
pub(in crate::qwen_forward) shared: [&'a DeviceBuffer<'shared>; 4],
pub(in crate::qwen_forward) mixed: &'a [f32],
pub(in crate::qwen_forward) ids: [u32; K],
pub(in crate::qwen_forward) weights: [f32; K],
}
/// The slot a routed expert occupies in the ten-expert route and the expert it selects.
#[derive(Clone, Copy)]
struct RouteSlot {
slot: usize,
expert: u32,
}
/// The transport indices of the quantized input values and their scales.
#[derive(Clone, Copy)]
struct QuantizedIndices {
values: usize,
scales: usize,
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
mod fixed_workspace_gpu {
@@ -198,7 +231,7 @@ mod fixed_workspace_gpu {
) -> Result<ObservedOutput> {
let mut t = Transport::new(storage, Rc::new(Cell::new(false)))?;
t.observations = Some(Vec::new());
let result = compose_inner(&mut t, bank, w, mixed, IDS, ROUTE);
let result = compose_inner(&mut t, ExpertInputs { bank, shared: w, mixed, ids: IDS, weights: ROUTE });
let observed = t.observations.take().ok_or(Error::IdentityMismatch)?;
t.finish(result.map(|output| (output, observed)))
}
@@ -308,7 +341,8 @@ mod fixed_workspace_gpu {
actual.len()
}
fn compose_with(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32], failed: bool) -> Result<Box<[f32]>> {
compose(storage, &self.bank, self.w(), mixed, IDS, ROUTE, Rc::new(Cell::new(failed)))
let inputs = ExpertInputs { bank: &self.bank, shared: self.w(), mixed, ids: IDS, weights: ROUTE };
compose(storage, inputs, Rc::new(Cell::new(failed)))
}
fn refuse_bad_input_and_failed_flag(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32]) {
let mut bad = mixed.to_vec();
@@ -55,15 +55,14 @@ fn routed_down(
pub(super) fn routed(
transport: &mut Transport<'_, '_>,
bank: &DeviceBuffer<'_>,
slot: usize,
expert: u32,
q: usize,
scales: usize,
pick: RouteSlot,
quantized: QuantizedIndices,
) -> Result<Finite> {
let RouteSlot { slot, expert } = pick;
if slot >= K || expert >= 512 {
return Err(Error::InvalidExpert);
}
let hidden_index = routed_hidden(transport, bank, (slot, expert), (q, scales))?;
let hidden_index = routed_hidden(transport, bank, (slot, expert), (quantized.values, quantized.scales))?;
routed_down(transport, bank, (slot, expert), hidden_index)
}
pub(super) fn shared_project(
@@ -205,20 +204,15 @@ impl Packed {
})
}
}
#[allow(clippy::too_many_arguments)]
pub(super) fn compose(
storage: &mut FixedBuffers<'_>,
bank: &DeviceBuffer<'_>,
shared_weights: [&DeviceBuffer<'_>; 4],
mixed: &[f32],
ids: [u32; K],
weights: [f32; K],
inputs: ExpertInputs<'_, '_, '_>,
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
validate_values(mixed, N)?;
validate_route(ids.map(|id| i32::try_from(id).unwrap_or(-1)), &weights)?;
validate_values(inputs.mixed, N)?;
validate_route(inputs.ids.map(|id| i32::try_from(id).unwrap_or(-1)), &inputs.weights)?;
let mut transport = Transport::new(storage, failed)?;
let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights);
let result = compose_inner(&mut transport, inputs);
transport.finish(result)
}
/// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs.
@@ -230,19 +224,13 @@ fn pack_routed(
(q, scales): (usize, usize),
) -> Result<()> {
for (slot, expert) in ids.into_iter().enumerate() {
let down = routed(transport, bank, slot, expert, q, scales)?;
let down = routed(transport, bank, RouteSlot { slot, expert }, QuantizedIndices { values: q, scales })?;
packed.pack(transport, down)?;
}
Ok(())
}
pub(super) fn compose_inner(
transport: &mut Transport<'_, '_>,
bank: &DeviceBuffer<'_>,
shared_weights: [&DeviceBuffer<'_>; 4],
mixed: &[f32],
ids: [u32; K],
weights: [f32; K],
) -> Result<Box<[f32]>> {
pub(super) fn compose_inner(transport: &mut Transport<'_, '_>, inputs: ExpertInputs<'_, '_, '_>) -> Result<Box<[f32]>> {
let ExpertInputs { bank, shared: shared_weights, mixed, ids, weights } = inputs;
let input = transport.upload(mixed, Slot::Input)?;
let mut packed = Packed::new(transport, ids)?;
let (q, scales) = transport.quantize(input, false)?;
@@ -70,21 +70,15 @@ impl<'ctx> MtpExpertWorkspace<'ctx> {
) -> Result<Self> {
Ok(Self { binding, owner, storage: FixedBuffers::new(context)? })
}
#[allow(clippy::too_many_arguments)]
pub(in crate::qwen_forward) fn compose(
&mut self,
binding: &ModelBinding,
owner: &Rc<()>,
context: &Context<'_>,
frame: &MtpFrame,
session: &QwenSession<'_>,
bank: &DeviceBuffer<'_>,
shared: [&DeviceBuffer<'_>; 4],
mixed: &[f32],
ids: [u32; K],
weights: [f32; K],
anchor: FrameAnchor<'_, '_>,
claim: WorkspaceClaim<'_, '_>,
inputs: ExpertInputs<'_, '_, '_>,
failed: Rc<Cell<bool>>,
) -> Result<Box<[f32]>> {
let FrameAnchor { binding, frame, session } = anchor;
let WorkspaceClaim { owner, context } = claim;
frame.validate(binding, session)?;
if !self.binding.matches(&binding.identity())
|| !Rc::ptr_eq(&self.owner, owner)
@@ -94,7 +88,7 @@ impl<'ctx> MtpExpertWorkspace<'ctx> {
return Err(Error::IdentityMismatch);
}
self.storage.check()?;
let result = compose(&mut self.storage, bank, shared, mixed, ids, weights, failed);
let result = compose(&mut self.storage, inputs, failed);
result.and_then(|values| frame.validate(binding, session).map(|()| values))
}
pub(in crate::qwen_forward) fn close(mut self) -> Result<()> {
@@ -77,7 +77,7 @@ pub(in crate::qwen_forward) fn compare_kv_cell_on_loaded_input(
cache: &MoeWeightCache<'_>,
) -> Result<usize> {
let failed = Rc::new(Cell::new(false));
let result = compare_kv_cell_inner(binding, target, draft, input, cache, &failed);
let result = compare_kv_cell_inner(binding, target, ComparedKvCell { draft, input }, cache, &failed);
if failed.get() {
target.note_mtp_failure(&Error::CudaExecution);
}
@@ -86,15 +86,21 @@ pub(in crate::qwen_forward) fn compare_kv_cell_on_loaded_input(
}
result
}
/// The draft session and the draft input whose attention K/V cell is compared with the canonical producer.
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct ComparedKvCell<'a> {
draft: &'a MtpSession,
input: &'a MtpInput,
}
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn compare_kv_cell_inner(
binding: &ModelBinding,
target: &mut QwenSession<'_>,
draft: &MtpSession,
input: &MtpInput,
compared: ComparedKvCell<'_>,
cache: &MoeWeightCache<'_>,
failed: &Rc<Cell<bool>>,
) -> Result<usize> {
let ComparedKvCell { draft, input } = compared;
use super::super::{mtp_attention, mtp_gr};
let read = mtp_gr::attention_read(binding, input, target, cache)?;
let reference = mtp_attention::MtpAttentionStage::run(binding, &read, draft, target, cache, Rc::clone(failed))?;
@@ -185,10 +185,10 @@ fn finish_position() -> Result<()> {
})
}
/// The three weight caches one captured forward step reads and fills.
struct Caches<'a, 'k, 'm, 'd> {
cache: &'a mut KarPleCache<'k>,
moe: &'a mut MoeWeightCache<'m>,
dense: &'a DenseWeightCache<'d>,
pub(crate) struct Caches<'a, 'k, 'm, 'd> {
pub(crate) cache: &'a mut KarPleCache<'k>,
pub(crate) moe: &'a mut MoeWeightCache<'m>,
pub(crate) dense: &'a DenseWeightCache<'d>,
}
fn admit_capture(binding: &ModelBinding, session: &QwenSession<'_>) -> Result<()> {
if binding.layer_count() != 48 || binding.kar_ple_binding().is_none() {
@@ -217,14 +217,23 @@ fn emit_logits(output: &OutputStage<'_, '_>, greedy: u32) -> Result<()> {
file_words("logits.f32", &logits)?;
file_words("greedy.i32", &[greedy])
}
/// One captured forward step: its position and token, with the vocabulary and context dimensions they are checked
/// against.
#[derive(Clone, Copy)]
struct CaptureStep {
position: u64,
token: u64,
vocabulary: Dimension,
context: Dimension,
}
fn capture_position(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
caches: &mut Caches<'_, '_, '_, '_>,
(vocabulary, context): (Dimension, Dimension),
(position, token): (u64, u64),
step: CaptureStep,
) -> Result<()> {
let CaptureStep { position, token, vocabulary, context } = step;
if position >= CONFIGURED_CONTEXT {
return Err(Error::InvalidPosition);
}
@@ -236,23 +245,20 @@ fn capture_position(
session.oracle_capture_committed(binding, position)?;
finish_position()
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn check_on_loaded(
binding: &ModelBinding,
session: &mut QwenSession<'_>,
output: &OutputStage<'_, '_>,
cache: &mut KarPleCache<'_>,
moe_cache: &mut MoeWeightCache<'_>,
dense_cache: &DenseWeightCache<'_>,
mut caches: Caches<'_, '_, '_, '_>,
directory: PathBuf,
) -> Result<()> {
admit_capture(binding, session)?;
initialize(directory)?;
output.test_reset_replay_record(true)?;
let dimensions = capture_dimensions(binding)?;
let mut caches = Caches { cache, moe: moe_cache, dense: dense_cache };
let (vocabulary, context) = capture_dimensions(binding)?;
for (position, token) in [0u64, 1].into_iter().enumerate() {
capture_position(binding, session, output, &mut caches, dimensions, (position as u64, token))?;
let step = CaptureStep { position: position as u64, token, vocabulary, context };
capture_position(binding, session, output, &mut caches, step)?;
}
output.test_reset_replay_record(false)?;
with(|c| write(c, "CAPTURE-COMPLETE.txt", b"candidate_capture_complete=2\ncomparison_performed=false\n"))?;
@@ -310,7 +316,8 @@ fn run_capture(binding: &ModelBinding, context: &Rc<leleka_cuda_driver::Context<
let dense_cache = DenseWeightCache::new(binding, context.as_ref()).expect("dense cache");
let mut session = QwenSession::for_binding_on_shared_device(binding, Rc::clone(context));
let directory = operator_path("LELEKA_STRA169_CANDIDATE_CAPTURE");
let captured = check_on_loaded(binding, &mut session, &output, &mut cache, &mut moe_cache, &dense_cache, directory);
let caches = Caches { cache: &mut cache, moe: &mut moe_cache, dense: &dense_cache };
let captured = check_on_loaded(binding, &mut session, &output, caches, directory);
drop(session);
let moe_closed = moe_cache.close();
let dense_closed = dense_cache.close();
@@ -10,7 +10,7 @@
use super::{
contract::{Error, Result, Stage},
executor::original_prompt::embedding::OriginalPromptEmbedding,
moe_weight_cache::{MoeWeightCache, RetainedOriginalMtpWeights},
moe_weight_cache::{MoeWeightCache, MtpHeadSources, RetainedOriginalMtpWeights},
output_native::{OriginalMtpNativeHead, OriginalNativeOutput},
session::{QwenSession, original_prompt::draft::OriginalDraftSession},
};
@@ -143,8 +143,8 @@ impl<'ctx> OriginalMtpFullOwner<'ctx> {
let head = &prepared.head;
let scalar = retained.scalar_prefill_weights(binding, context, embedding)?;
let prefix = Rc::new(OriginalMtpRetainedPrefix::from_scalar(scalar).map_err(driver_error)?);
let draft_head = prepared.draft_head.as_ref();
Ok(retained.full_forward_weights(binding, context, prefix, head, head.vocabulary(), draft_head)?)
let heads = MtpHeadSources { native: head, draft: prepared.draft_head.as_ref() };
Ok(retained.full_forward_weights(binding, context, prefix, heads)?)
}
pub(super) fn shared_drafter(
context: &'ctx Context<'ctx>,
@@ -249,9 +249,7 @@ impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> {
return Err(refused(failure, owners));
}
let p = super::original_serve_profile::span("assemble.prepare");
let shape = (max_t, self.max_cells, self.blobs);
let prepare =
prepare_assembly(self.binding, self.weights.dense, self.context, self.base, self.ple_history, shape);
let prepare = self.prepare_assembly(max_t);
drop(p);
let prepared = match prepare {
Ok(parts) => parts,
@@ -336,7 +334,7 @@ fn recover<'a, 'ctx>(qsa: Rc<OriginalVerifyQsaJournal<'a, 'ctx>>, slots: [usize;
}
mod assemble_parts;
use assemble_parts::{Prepared, RecordEnv, capture_verifier, prepare_assembly, split_owners};
use assemble_parts::{Prepared, RecordEnv, capture_verifier, split_owners};
#[cfg(test)]
mod tests;
@@ -16,28 +16,24 @@ pub(super) type QsaParts<'ctx> =
pub(super) type Prepared<'a, 'ctx> =
(OriginalVerifyGeometry, OriginalVerifyCanonicalGdn<'ctx>, [&'a DeviceBuffer<'ctx>; 12]);
/// Everything that can be refused WITHOUT consuming the owners.
pub(super) fn prepare_assembly<'a, 'ctx>(
binding: &ModelBinding,
dense: &'a DenseWeightCache<'ctx>,
context: &'ctx Context<'ctx>,
base: &OriginalVerifiedBase<'ctx>,
ple_history: &DeviceBuffer<'ctx>,
shape: (usize, usize, &ExpertBlobSizes),
) -> std::result::Result<Prepared<'a, 'ctx>, ServeFailure> {
let (max_t, max_cells, blobs) = shape;
let geometry = verify_geometry(max_t, max_cells, blobs)?;
blobs.layout()?;
let priors = gdn_layer_priors(binding, base)?;
let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values());
let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history());
let canonical = context.original_verify_canonical_gdn(states, histories)?;
// PLE history: the seeded device image the commit graph keeps current.
if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES {
return Err(Error::InvalidDimension.into());
impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> {
/// Everything that can be refused WITHOUT consuming the owners.
pub(super) fn prepare_assembly(&self, max_t: usize) -> std::result::Result<Prepared<'a, 'ctx>, ServeFailure> {
let (binding, dense, context) = (self.binding, self.weights.dense, self.context);
let (base, ple_history, blobs) = (self.base, self.ple_history, self.blobs);
let geometry = verify_geometry(max_t, self.max_cells, blobs)?;
blobs.layout()?;
let priors = gdn_layer_priors(binding, base)?;
let states: [&[f32]; 36] = std::array::from_fn(|i| priors[i].values());
let histories: [&[f32]; 36] = std::array::from_fn(|i| priors[i].history());
let canonical = context.original_verify_canonical_gdn(states, histories)?;
// PLE history: the seeded device image the commit graph keeps current.
if base.ple.is_none() || ple_history.len() != PLE_HISTORY_BYTES {
return Err(Error::InvalidDimension.into());
}
let gamma = dense.original_verify_qsa_gamma(binding)?;
Ok((geometry, canonical, gamma))
}
let gamma = dense.original_verify_qsa_gamma(binding)?;
Ok((geometry, canonical, gamma))
}
/// From here the owners move into the journal: the twelve resident layers in ascending slot order.
@@ -2,7 +2,7 @@
#![cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
use super::super::{ple_upload, ple_upload_f32};
use super::*;
use leleka_cuda_driver::Driver;
use leleka_cuda_driver::{Driver, PleClosedWeights};
struct Matrices<'ctx> {
key: DeviceBuffer<'ctx>,
value: DeviceBuffer<'ctx>,
@@ -17,7 +17,8 @@ fn refused(
(key, value, aux): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4]),
(embedding, streams, history): (&[f32], &[f32], &[f32]),
) -> Result<PleCandidate> {
compose(ctx, key, value, aux, embedding, streams, history, Rc::new(Cell::new(false)))
let rows = PleRows { embedding, streams, history };
compose(ctx, PleClosedWeights { key, value, aux }, rows, Rc::new(Cell::new(false)))
}
#[test]
@@ -55,17 +56,9 @@ fn prove_trace(ctx: &Context<'_>, matrices: &Matrices<'_>, charged: usize, zero:
let expected = original(ctx, matrices, &embedding, &streams, &history);
assert_eq!(ctx.allocated_bytes(), charged);
let failed = Rc::new(Cell::new(false));
let observed = compose_observed(
ctx,
&matrices.key,
&matrices.value,
matrices.aux(),
&embedding,
&streams,
&history,
failed.clone(),
)
.unwrap();
let weights = PleClosedWeights { key: &matrices.key, value: &matrices.value, aux: matrices.aux() };
let rows = PleRows { embedding: &embedding, streams: &streams, history: &history };
let observed = compose_observed(ctx, weights, rows, failed.clone()).unwrap();
check_trace(observed, &expected);
assert_eq!(embedding.iter().chain(&streams).chain(&history).map(|x| x.to_bits()).collect::<Vec<_>>(), snapshot);
assert!(!failed.get());
@@ -30,6 +30,13 @@ struct Finite {
role: Role,
invocation: Rc<()>,
}
/// The three host rows one PLE composition reads: the token embedding, the residual streams and the conv history.
#[derive(Clone, Copy)]
pub(super) struct PleRows<'a> {
pub(super) embedding: &'a [f32],
pub(super) streams: &'a [f32],
pub(super) history: &'a [f32],
}
struct Transport<'ctx> {
context: &'ctx Context<'ctx>,
buffers: Vec<Option<DeviceBuffer<'ctx>>>,
@@ -2,17 +2,15 @@
#[allow(unused_imports)]
use super::*;
use leleka_cuda_driver::PleClosedWeights;
#[allow(clippy::too_many_arguments)]
pub(super) fn compose_inner(
transport: &mut Transport<'_>,
key_matrix: &DeviceBuffer<'_>,
value_matrix: &DeviceBuffer<'_>,
aux: [&DeviceBuffer<'_>; 4],
embedding: &[f32],
streams: &[f32],
history: &[f32],
weights: PleClosedWeights<'_, '_>,
rows: PleRows<'_>,
) -> Result<PleCandidate> {
let PleClosedWeights { key: key_matrix, value: value_matrix, aux } = weights;
let PleRows { embedding, streams, history } = rows;
let (raw_key, value_index) = project_key_value(transport, key_matrix, value_matrix, embedding)?;
let residual = transport.upload(streams)?;
let prior = transport.upload(history)?;
@@ -174,21 +172,16 @@ fn conv_operands<'a, 'ctx>(
}
#[cfg(test)]
#[allow(clippy::too_many_arguments)]
pub(super) fn compose_observed(
context: &Context<'_>,
key_matrix: &DeviceBuffer<'_>,
value_matrix: &DeviceBuffer<'_>,
aux: [&DeviceBuffer<'_>; 4],
embedding: &[f32],
streams: &[f32],
history: &[f32],
weights: PleClosedWeights<'_, '_>,
rows: PleRows<'_>,
failed: Rc<Cell<bool>>,
) -> Result<ObservedOutput> {
admit(key_matrix, value_matrix, &aux, embedding, streams, history)?;
admit(&weights, rows)?;
let mut transport = Transport::new(context, failed)?;
transport.observations = Some(Vec::new());
let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history);
let result = compose_inner(&mut transport, weights, rows);
let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?;
let output = transport.finish(result)?;
Ok((output, observations))
@@ -196,24 +189,18 @@ pub(super) fn compose_observed(
/// Explicit selected producer only. The caller retains the real PleOwner,
/// current TokenLayer, prior and exact cache weight lineage before/after this call.
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn compose_queued(
queue: &mut leleka_cuda_driver::PleClosedQueue<'_>,
context: &Context<'_>,
key_matrix: &DeviceBuffer<'_>,
value_matrix: &DeviceBuffer<'_>,
aux: [&DeviceBuffer<'_>; 4],
embedding: &[f32],
streams: &[f32],
history: &[f32],
weights: PleClosedWeights<'_, '_>,
rows: PleRows<'_>,
failed: Rc<Cell<bool>>,
) -> Result<PleCandidate> {
admit(key_matrix, value_matrix, &aux, embedding, streams, history)?;
admit(&weights, rows)?;
if failed.get() {
return Err(Error::CudaExecution);
}
let weights = leleka_cuda_driver::PleClosedWeights { key: key_matrix, value: value_matrix, aux };
let result = compose_on_queue(queue, context, weights, embedding, streams, history);
let result = compose_on_queue(queue, context, weights, rows);
if matches!(result, Err(Error::CudaExecution)) || queue.is_failed() {
failed.set(true);
}
@@ -223,13 +210,11 @@ pub(in super::super) fn compose_queued(
fn compose_on_queue(
queue: &mut leleka_cuda_driver::PleClosedQueue<'_>,
context: &Context<'_>,
weights: leleka_cuda_driver::PleClosedWeights<'_, '_>,
embedding: &[f32],
streams: &[f32],
history: &[f32],
weights: PleClosedWeights<'_, '_>,
rows: PleRows<'_>,
) -> Result<PleCandidate> {
queue.validate_context(context).map_err(ple_driver_error)?;
let completion = queue.compose(weights, embedding, streams, history).map_err(ple_driver_error)?;
let completion = queue.compose(weights, rows.embedding, rows.streams, rows.history).map_err(ple_driver_error)?;
let (streams, history) = completion.into_parts().map_err(|_| Error::NonFinite)?;
ple_values(&streams, PLE_HC)?;
ple_values(&history, PLE_HISTORY)?;
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use leleka_cuda_driver::PleClosedWeights;
impl Role {
pub(super) fn count(self) -> usize {
@@ -146,30 +147,20 @@ pub(super) fn at<'a, 'ctx>(buffers: &'a [Option<DeviceBuffer<'ctx>>], index: usi
buffers.get(index).and_then(Option::as_ref).ok_or(Error::IdentityMismatch)
}
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn compose(
context: &Context<'_>,
key_matrix: &DeviceBuffer<'_>,
value_matrix: &DeviceBuffer<'_>,
aux: [&DeviceBuffer<'_>; 4],
embedding: &[f32],
streams: &[f32],
history: &[f32],
weights: PleClosedWeights<'_, '_>,
rows: PleRows<'_>,
failed: Rc<Cell<bool>>,
) -> Result<PleCandidate> {
admit(key_matrix, value_matrix, &aux, embedding, streams, history)?;
admit(&weights, rows)?;
let mut transport = Transport::new(context, failed)?;
let result = compose_inner(&mut transport, key_matrix, value_matrix, aux, embedding, streams, history);
let result = compose_inner(&mut transport, weights, rows);
transport.finish(result)
}
pub(super) fn admit(
key: &DeviceBuffer<'_>,
value: &DeviceBuffer<'_>,
aux: &[&DeviceBuffer<'_>; 4],
embedding: &[f32],
streams: &[f32],
history: &[f32],
) -> Result<()> {
pub(super) fn admit(weights: &PleClosedWeights<'_, '_>, rows: PleRows<'_>) -> Result<()> {
let PleRows { embedding, streams, history } = rows;
let (key, value, aux) = (weights.key, weights.value, &weights.aux);
ple_values(embedding, 2560)?;
ple_values(streams, PLE_HC)?;
ple_values(history, PLE_HISTORY)?;
@@ -165,7 +165,8 @@ mod gpu {
);
let next = QsaPending::new(&prior, identity, &[0; KV * 2], &[0; KV * 2], &index).unwrap().into_prior();
let expected = select(context, &next.score_keys().unwrap(), &next.0.dead, iq, p as u32).unwrap();
let actual = cache.select(binding, context, &next, iq, p as u32).unwrap();
let request = QsaSelectionRequest { candidate: &next, index_query: iq, position: p as u32 };
let actual = cache.select(binding, context, request).unwrap();
assert_eq!(actual.as_ref(), expected.as_ref());
total += actual.len();
prior = next;
@@ -177,10 +178,11 @@ mod gpu {
let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq);
let replacement = synthetic_late_prior_for(binding.clone(), 190004);
let expected = select(context, &replacement.score_keys().unwrap(), &replacement.0.dead, iq, 190003).unwrap();
let actual = cache.select(binding, context, &replacement, iq, 190003).unwrap();
let request = QsaSelectionRequest { candidate: &replacement, index_query: iq, position: 190003 };
let actual = cache.select(binding, context, request).unwrap();
assert_eq!(actual.as_ref(), expected.as_ref());
let uploads = cache.uploads;
assert_eq!(cache.select(binding, context, &replacement, iq, 190003).unwrap().as_ref(), expected.as_ref());
assert_eq!(cache.select(binding, context, request).unwrap().as_ref(), expected.as_ref());
assert_eq!(cache.uploads, uploads);
(replacement, uploads)
}
@@ -193,10 +195,12 @@ mod gpu {
let (binding, context, iq) = (&rig.binding, rig.context, &rig.iq);
let wrong = BindingIdentity::test_identity();
// Bound position and malformed source must refuse before any transfer.
assert!(cache.select(&wrong, context, replacement, iq, 190002).is_err());
let wrong_position = QsaSelectionRequest { candidate: replacement, index_query: iq, position: 190002 };
assert!(cache.select(&wrong, context, wrong_position).is_err());
let mut bad = *iq;
bad[511] = f32::NAN;
assert!(cache.select(binding, context, replacement, &bad, 190003).is_err());
let malformed = QsaSelectionRequest { candidate: replacement, index_query: &bad, position: 190003 };
assert!(cache.select(binding, context, malformed).is_err());
assert_eq!(cache.uploads, uploads);
}
#[test]
@@ -144,18 +144,17 @@ impl<'ctx> QsaIndexKeyCache<'ctx> {
&mut self,
binding: &BindingIdentity,
context: &Context<'_>,
next: &QsaPrior,
iq: &[f32],
p: u32,
request: QsaSelectionRequest<'_>,
) -> Result<Box<[i32]>> {
if self.failed.get() {
return Err(Error::CudaExecution);
}
self.check_select(binding, context, next, iq, p)?;
self.check_select(binding, context, request)?;
let next = request.candidate;
let slot = next.layer().get() as usize / 4;
let rows = next.0.pooled.len().checked_add(1).ok_or(Error::Overflow)?;
let action = self.plan(slot, rows, next)?;
let result = self.apply_action(slot, action, next, iq, p);
let result = self.apply_action(slot, action, request);
if result.is_err() {
self.failed.set(true);
}
@@ -165,10 +164,9 @@ impl<'ctx> QsaIndexKeyCache<'ctx> {
&self,
binding: &BindingIdentity,
context: &Context<'_>,
next: &QsaPrior,
iq: &[f32],
p: u32,
request: QsaSelectionRequest<'_>,
) -> Result<()> {
let QsaSelectionRequest { candidate: next, index_query: iq, position: p } = request;
if !self.binding.matches(binding)
|| !next.0.binding.matches(binding)
|| !std::ptr::eq(self.context, context)
@@ -192,7 +190,8 @@ impl<'ctx> QsaIndexKeyCache<'ctx> {
}
Ok(entry.prior.as_ref().map(|old| update(old, next)).transpose()?.unwrap_or(Update::Reload))
}
fn apply_action(&mut self, slot: usize, action: Update, next: &QsaPrior, iq: &[f32], p: u32) -> Result<Box<[i32]>> {
fn apply_action(&mut self, slot: usize, action: Update, request: QsaSelectionRequest<'_>) -> Result<Box<[i32]>> {
let QsaSelectionRequest { candidate: next, index_query: iq, position: p } = request;
match action {
Update::Reload => self.reload(slot, next)?,
Update::Append(row) => self.append_row(slot, next, row)?,
@@ -97,7 +97,7 @@ fn prove_parity(context: &Context<'_>, binding: &BindingIdentity, scratch: &RefC
(QsaMatrixRole::Q, 12288, 3),
(QsaMatrixRole::IndexQ, 512, 4),
] {
prove_role(context, binding, &lease, &input, role, zero);
prove_role(context, binding, &lease, ParityInput { values: &input, zero }, role);
}
assert_eq!(input.iter().map(|v| v.to_bits()).collect::<Vec<_>>(), source_bits);
drop(lease);
@@ -105,14 +105,21 @@ fn prove_parity(context: &Context<'_>, binding: &BindingIdentity, scratch: &RefC
assert_eq!(context.allocated_bytes(), INPUT_BYTES);
}
/// The input row of the parity proof and whether it is the signed-zero variant.
#[derive(Clone, Copy)]
struct ParityInput<'a> {
values: &'a [f32],
zero: bool,
}
fn prove_role(
context: &Context<'_>,
binding: &BindingIdentity,
lease: &QsaInputLease<'_, '_, '_>,
input: &[f32],
source: ParityInput<'_>,
(role, rows, seed): (QsaMatrixRole, usize, usize),
zero: bool,
) {
let ParityInput { values: input, zero } = source;
let bytes = matrix_bytes(rows, seed);
let matrix = bytes_upload(context, &bytes);
let fresh = upload(context, input).unwrap();