Merge claude/hexagonal-finish-14ee3a into claude/par-r04: e03 trait signatures (NativeCommittedWindow, DraftLimits) with r04's MtpDraftOwners/DraftLaunch on the host; DraftRound dropped; AdaptiveWave project_residents inlined
This commit is contained in:
@@ -1,5 +1,6 @@
|
||||
//! The single-token generation step loop.
|
||||
use super::*;
|
||||
use crate::qwen_forward::executor::{StepCaches, StepRequest};
|
||||
|
||||
pub(super) struct Generation<'a, 'context, 'driver, C: Clock = SystemClock> {
|
||||
pub(super) execution: EvaluationExecution,
|
||||
@@ -68,14 +69,10 @@ impl<C: Clock> Generation<'_, '_, '_, C> {
|
||||
let token = TokenId::new(u64::from(token), vocabulary).map_err(|_| invalid("native token invalid"))?;
|
||||
let position = native_position(self.binding.input_constants(), self.context_tokens, position)?;
|
||||
let forwarded = QwenForward::step_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position,
|
||||
StepRequest { binding: self.binding, token, position },
|
||||
self.session,
|
||||
self.output,
|
||||
self.kar_cache.as_deref_mut(),
|
||||
self.moe_cache,
|
||||
self.dense_cache,
|
||||
StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) },
|
||||
);
|
||||
let token = forwarded.map_err(|failure| self.forward_failure(failure, position))?;
|
||||
if self.cancelled() {
|
||||
@@ -104,14 +101,10 @@ impl<C: Clock> Generation<'_, '_, '_, C> {
|
||||
.map_err(|e| self.mtp_error(e))?;
|
||||
let position = native_position(self.binding.input_constants(), self.context_tokens, position)?;
|
||||
let result = QwenForward::step_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position,
|
||||
StepRequest { binding: self.binding, token, position },
|
||||
self.session,
|
||||
self.output,
|
||||
self.kar_cache.as_deref_mut(),
|
||||
Some(self.moe_cache),
|
||||
Some(self.dense_cache),
|
||||
StepCaches { kar: self.kar_cache.as_deref_mut(), moe: Some(self.moe_cache), dense: Some(self.dense_cache) },
|
||||
);
|
||||
let product = result.map_err(|e| self.mtp_error(e))?;
|
||||
if self.cancelled() {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! The MTP speculative generation loop.
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
mod tile_parts;
|
||||
use tile_parts::{begin_decoder, commit_window, emit_token_text, prefill_tiles, verified_window};
|
||||
|
||||
@@ -50,7 +51,9 @@ fn warm_retained_edge<C: Clock>(
|
||||
}
|
||||
let (vocabulary, _) = mtp_vocabulary(run)?;
|
||||
let next = TokenId::new(u64::from(next), vocabulary).map_err(|e| run.mtp_error(e))?;
|
||||
decoder.warm_retained(run.binding, run.session, product, next, run.moe_cache).map_err(|e| run.mtp_error(e))
|
||||
decoder
|
||||
.warm_retained(run.binding, run.session, KnownNext { source: product, next_token: next }, run.moe_cache)
|
||||
.map_err(|e| run.mtp_error(e))
|
||||
}
|
||||
|
||||
/// What one iteration of the decode loop decided.
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp_decode::MtpVerifiedWindow;
|
||||
use crate::qwen_forward::mtp_decode::{MtpVerifiedWindow, MtpWindowRequest, WindowOwners};
|
||||
|
||||
/// The decoder to continue with, the product of the retained prefix, the tokens reused and the committed tokens so far.
|
||||
pub(super) type Resumed = (MtpDecoder, Option<TargetStepProduct>, usize, Vec<u32>);
|
||||
@@ -134,23 +134,21 @@ pub(super) fn verified_window<C: Clock>(
|
||||
let cancel = run.cancel;
|
||||
let shared = run.shared;
|
||||
let sink = run.sink;
|
||||
let request = MtpWindowRequest { binding: run.binding, source: product, spec };
|
||||
let owners = WindowOwners {
|
||||
target: run.session,
|
||||
output: run.output,
|
||||
kar_cache: run.kar_cache.as_deref_mut(),
|
||||
cache: run.moe_cache,
|
||||
dense_cache: run.dense_cache,
|
||||
};
|
||||
decoder
|
||||
.window(
|
||||
run.binding,
|
||||
product,
|
||||
run.session,
|
||||
run.output,
|
||||
run.kar_cache.as_deref_mut(),
|
||||
run.moe_cache,
|
||||
run.dense_cache,
|
||||
spec,
|
||||
|| {
|
||||
cancel.load(Ordering::Acquire)
|
||||
|| shared.shutdown.load(Ordering::Acquire)
|
||||
|| sink.is_closed()
|
||||
|| run.clock.since(start) > GENERATION_TIMEOUT
|
||||
},
|
||||
)
|
||||
.window(request, owners, || {
|
||||
cancel.load(Ordering::Acquire)
|
||||
|| shared.shutdown.load(Ordering::Acquire)
|
||||
|| sink.is_closed()
|
||||
|| run.clock.since(start) > GENERATION_TIMEOUT
|
||||
})
|
||||
.map_err(|e| window_failure(run, e, start))
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Private sole new changed-path model gate; actual source identity/load preserved.
|
||||
use super::*;
|
||||
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners as LoadedTarget;
|
||||
use std::env;
|
||||
#[path = "combined_changed_boundary_proof/rig.rs"]
|
||||
pub(super) mod rig;
|
||||
@@ -32,16 +33,17 @@ fn pinned_single_load_layer0_and_window_boundaries() {
|
||||
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));
|
||||
// Both helpers use genuine fresh target owners on the one admitted
|
||||
// binding/context/cache. No second source load or CUDA context is created.
|
||||
// Both helpers use genuine fresh target owners on the one admitted binding/context/cache: no second load.
|
||||
let layer0 = owners.run(&binding, &context, QwenForward::test_layer0_pair_on_loaded);
|
||||
let window = matches!(&layer0, Ok(Ok(_)))
|
||||
.then(|| owners.run(&binding, &context, QwenForward::test_window_boundaries_on_loaded));
|
||||
let window = matches!(&layer0, Ok(Ok(_))).then(|| {
|
||||
owners.run(&binding, &context, |binding, session, output, kar, moe, dense| {
|
||||
QwenForward::test_window_boundaries_on_loaded(LoadedTarget { binding, session, output, kar, moe, dense })
|
||||
})
|
||||
});
|
||||
let mut teardown = owners.close(true);
|
||||
teardown.close_context(context);
|
||||
drop((binding, inherited));
|
||||
// Preserve the phase failure after every teardown attempt; a later
|
||||
// cleanup assertion must not obscure its original diagnostic cause.
|
||||
// Preserve the phase failure after every teardown attempt; a later cleanup must not obscure its cause.
|
||||
let report = unwrap_phase(layer0, "same-source layer0 diagnostic refused");
|
||||
let window = unwrap_phase(window.expect("window proof was not admitted"), "changed window proof refused");
|
||||
teardown.assert_clean();
|
||||
@@ -49,6 +51,11 @@ fn pinned_single_load_layer0_and_window_boundaries() {
|
||||
.write_after_cleanup(&required_path("LELEKA_STRA169_LAYER0_DIR"))
|
||||
.expect("exclusive bounded layer0 diagnostic write failed");
|
||||
window.assert_success_and_print();
|
||||
print_layer0_diagnostic_complete();
|
||||
}
|
||||
|
||||
/// The closing line of the combined proof: what the layer0 diagnostic did and did not claim.
|
||||
fn print_layer0_diagnostic_complete() {
|
||||
eprintln!(
|
||||
"layer0 diagnostic COMPLETE native-first same-four-rows actual-origins checked packed_down shared_scaled \
|
||||
final_products raw_words=256080 allocated_bytes=0 unpublished=true mtp=false head=false quality_pass=false \
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
//! Forced inputs are public IDs; no expected model tensors or invented state.
|
||||
use super::combined_changed_boundary_proof::rig::Owners;
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
use crate::qwen_forward::mtp_decode::DraftHeadOwners;
|
||||
use crate::qwen_forward::{mtp::PrefixDraftSnapshot, session::ResetReplaySnapshot};
|
||||
|
||||
const PREFIX: [u32; 3] = [0, 1, 0];
|
||||
@@ -94,8 +96,9 @@ fn reference_pass<'ctx, 'driver>(
|
||||
};
|
||||
if let Some(&next) = COMPLETE.get(position + 1) {
|
||||
let next = TokenId::new(u64::from(next), vocabulary).expect("reference known-next refused");
|
||||
let edge = KnownNext { source: &product, next_token: next };
|
||||
decoder
|
||||
.warm(run.binding, run.session, &product, next, run.output, run.moe_cache)
|
||||
.warm(run.binding, run.session, edge, DraftHeadOwners { output: run.output, cache: run.moe_cache })
|
||||
.expect("reference actual full draft step failed");
|
||||
}
|
||||
latest = Some(product);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
//! The expert a projection, a cache fill or a loan refers to.
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertSelection, MoeExpertWeights};
|
||||
|
||||
/// One expert (a routed slot or the shared expert) of validated expert weights, under the binding that admitted
|
||||
/// them. The three always travel together: weights are only meaningful for their binding, and the selection says
|
||||
/// which expert of those weights is meant.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct BoundExpert<'a> {
|
||||
pub(in crate::qwen_forward) binding: &'a ModelBinding,
|
||||
pub(in crate::qwen_forward) weights: &'a MoeExpertWeights,
|
||||
pub(in crate::qwen_forward) selection: MoeExpertSelection,
|
||||
}
|
||||
|
||||
impl<'a> BoundExpert<'a> {
|
||||
/// The routed expert in `slot` of the weights admitted under `binding`.
|
||||
pub(in crate::qwen_forward) fn routed(
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a MoeExpertWeights,
|
||||
slot: usize,
|
||||
) -> Self {
|
||||
Self { binding, weights, selection: MoeExpertSelection::Routed { slot } }
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,15 @@ enum Slot<'ctx> {
|
||||
InUse,
|
||||
}
|
||||
|
||||
/// Which completed slot of the ephemeral owner is loaned and which member of the routed source it must equal,
|
||||
/// under which model binding.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct TripletLoanRequest<'binding> {
|
||||
pub(in crate::qwen_forward) binding: &'binding ModelBinding,
|
||||
pub(in crate::qwen_forward) member: usize,
|
||||
pub(in crate::qwen_forward) slot: usize,
|
||||
}
|
||||
|
||||
pub(in crate::qwen_forward) struct EphemeralRoutedOwner<'ctx> {
|
||||
binding: BindingIdentity,
|
||||
context: &'ctx Context<'ctx>,
|
||||
|
||||
+2
-3
@@ -263,16 +263,15 @@ impl<'ctx> MappedStage<'ctx> {
|
||||
}
|
||||
pub(super) fn with_triplet<'source, 'group, T>(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
binding: &ModelBinding,
|
||||
request: TripletLoanRequest<'_>,
|
||||
source: &mut MoeRoutedSourceScope<'source, 'group>,
|
||||
member: usize,
|
||||
consume: impl FnOnce(
|
||||
[&DeviceBuffer<'ctx>; 3],
|
||||
[MoeWeightDescriptor; 3],
|
||||
&mut MoeRoutedSourceScope<'source, 'group>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let TripletLoanRequest { binding, member, slot } = request;
|
||||
self.validate(binding, slot)?;
|
||||
let fresh = EphemeralRoutedOwner::keys(binding, source, member)?;
|
||||
let (keys, buffers, scratch) = self.loan_completed(slot, &fresh)?;
|
||||
|
||||
+3
-5
@@ -233,10 +233,8 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
|
||||
/// buffers are temporary execution owners, never adaptive cache hits.
|
||||
pub(in crate::qwen_forward) fn with_triplet<'source, 'group, T>(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
binding: &ModelBinding,
|
||||
request: TripletLoanRequest<'_>,
|
||||
source: &mut MoeRoutedSourceScope<'source, 'group>,
|
||||
member: usize,
|
||||
cancel_observed: &Cell<bool>,
|
||||
consume: impl FnOnce(
|
||||
[&DeviceBuffer<'ctx>; 3],
|
||||
@@ -245,9 +243,9 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let result = if let Some(mapped) = &mut self.mapped {
|
||||
mapped.with_triplet(slot, binding, source, member, consume)
|
||||
mapped.with_triplet(request, source, consume)
|
||||
} else {
|
||||
self.with_triplet_inner(slot, binding, source, member, consume)
|
||||
self.with_triplet_inner(request, source, consume)
|
||||
};
|
||||
#[cfg(test)]
|
||||
if self.mapped.is_some() && result.is_ok() {
|
||||
|
||||
+2
-3
@@ -30,16 +30,15 @@ impl<'ctx> EphemeralRoutedOwner<'ctx> {
|
||||
}
|
||||
pub(in super::super) fn with_triplet_inner<'source, 'group, T>(
|
||||
&mut self,
|
||||
slot: usize,
|
||||
binding: &ModelBinding,
|
||||
request: TripletLoanRequest<'_>,
|
||||
source: &mut MoeRoutedSourceScope<'source, 'group>,
|
||||
member: usize,
|
||||
consume: impl FnOnce(
|
||||
[&DeviceBuffer<'ctx>; 3],
|
||||
[MoeWeightDescriptor; 3],
|
||||
&mut MoeRoutedSourceScope<'source, 'group>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let TripletLoanRequest { binding, member, slot } = request;
|
||||
self.validate_slot(binding, slot)?;
|
||||
let fresh = Self::keys(binding, source, member)?;
|
||||
let (keys, buffers) = self.loan_completed(slot, &fresh)?;
|
||||
|
||||
@@ -81,14 +81,19 @@ mod impl_prefillstepproduct;
|
||||
#[allow(unused_imports)]
|
||||
use impl_prefillstepproduct::diagnose;
|
||||
mod impl_qwenforward;
|
||||
mod read_layer_attention_fn;
|
||||
mod step_layer_fns;
|
||||
mod read_layer_attention;
|
||||
mod step_layers;
|
||||
mod step_request;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[allow(unused_imports)]
|
||||
use read_layer_attention_fn::prepare_layer_attention_micro;
|
||||
use read_layer_attention::LayerEntry;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[allow(unused_imports)]
|
||||
use read_layer_attention_fn::read_layer_attention;
|
||||
use read_layer_attention::prepare_layer_attention_micro;
|
||||
#[allow(unused_imports)]
|
||||
use read_layer_attention_fn::validate_descriptors;
|
||||
use read_layer_attention::read_layer_attention;
|
||||
#[allow(unused_imports)]
|
||||
use read_layer_attention_fn::validate_layer_plan;
|
||||
use read_layer_attention::validate_descriptors;
|
||||
#[allow(unused_imports)]
|
||||
use read_layer_attention::validate_layer_plan;
|
||||
pub(crate) use step_request::{StepCaches, StepPurpose, StepRequest};
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_qwenforward/impl_qwenforward_2.rs"]
|
||||
mod impl_qwenforward_2;
|
||||
#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"]
|
||||
mod impl_qwenforward_2_2;
|
||||
#[path = "impl_qwenforward/impl_qwenforward_3.rs"]
|
||||
mod impl_qwenforward_3;
|
||||
#[path = "impl_qwenforward/step_core.rs"]
|
||||
mod step_core;
|
||||
#[path = "impl_qwenforward/step_entries.rs"]
|
||||
mod step_entries;
|
||||
|
||||
-178
@@ -1,178 +0,0 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenForward.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl QwenForward {
|
||||
pub(crate) fn step(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(binding, token, pos, session, None, None)
|
||||
}
|
||||
|
||||
/// Complete-forward entry retains the loaded output head across tokens.
|
||||
/// Unsupported stages abort the same transaction without state publication.
|
||||
pub(crate) fn step_with_output(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(binding, token, pos, session, Some(output), None)
|
||||
}
|
||||
|
||||
/// Explicit loaded KAR provider. Cache lifetime is borrowed from the
|
||||
/// caller's stable owner-thread Context; it is never self-referential.
|
||||
pub(crate) fn step_with_kar_ple_output(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
cache: &mut KarPleCache<'_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(binding, token, pos, session, Some(output), Some(cache))
|
||||
}
|
||||
|
||||
pub(in super::super) fn step_inner(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: Option<&OutputStage<'_, '_>>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_core(binding, token, pos, session, output, kar_cache, None, None, false, false)
|
||||
.and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch))
|
||||
}
|
||||
|
||||
/// Retain the pre-output four-stream residual only for explicit MTP use.
|
||||
/// Native/KAR callers above keep their original allocation and math path.
|
||||
pub(crate) fn step_for_mtp(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
Self::step_for_mtp_cached(binding, token, pos, session, output, kar_cache, None, None)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn step_cached(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'_>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_core(
|
||||
binding,
|
||||
token,
|
||||
pos,
|
||||
session,
|
||||
Some(output),
|
||||
kar_cache,
|
||||
Some(moe_cache),
|
||||
Some(dense_cache),
|
||||
false,
|
||||
false,
|
||||
)
|
||||
.and_then(|(token, _)| token.ok_or(Error::IdentityMismatch))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn step_for_mtp_cached(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: Option<&mut MoeWeightCache<'_>>,
|
||||
dense_cache: Option<&DenseWeightCache<'_>>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
let (predicted, streams) = Self::step_core(
|
||||
binding,
|
||||
token,
|
||||
pos,
|
||||
session,
|
||||
Some(output),
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
true,
|
||||
false,
|
||||
)?;
|
||||
target_product(binding, token, pos, session, predicted, streams)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn prefill_for_mtp_cached(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'_>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
) -> Result<PrefillStepProduct> {
|
||||
let (predicted, streams) = Self::step_core(
|
||||
binding,
|
||||
token,
|
||||
pos,
|
||||
session,
|
||||
Some(output),
|
||||
kar_cache,
|
||||
Some(moe_cache),
|
||||
Some(dense_cache),
|
||||
true,
|
||||
true,
|
||||
)?;
|
||||
if predicted.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
prefill_product(binding, token, pos, session, streams)
|
||||
}
|
||||
}
|
||||
|
||||
fn target_product(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &QwenSession<'_>,
|
||||
predicted: Option<TokenId>,
|
||||
streams: Option<Box<[f32]>>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
Ok(TargetStepProduct {
|
||||
binding: binding.identity(),
|
||||
token,
|
||||
position: pos,
|
||||
predicted: predicted.ok_or(Error::IdentityMismatch)?,
|
||||
streams: streams.ok_or(Error::IdentityMismatch)?,
|
||||
origin: session.target_origin()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn prefill_product(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &QwenSession<'_>,
|
||||
streams: Option<Box<[f32]>>,
|
||||
) -> Result<PrefillStepProduct> {
|
||||
Ok(PrefillStepProduct {
|
||||
binding: binding.identity(),
|
||||
token,
|
||||
position: pos,
|
||||
streams: streams.ok_or(Error::IdentityMismatch)?,
|
||||
origin: session.target_origin()?,
|
||||
})
|
||||
}
|
||||
+9
-13
@@ -1,6 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: impl QwenForward (2).
|
||||
//! The shared body of every forward step: one completed transaction over the input row, the layers and the head.
|
||||
|
||||
use super::super::step_layer_fns::{
|
||||
use super::super::step_layers::{
|
||||
LayerCtx, capture_streams, finish_step, prepare_step_caches, run_layers, stage_input_row,
|
||||
};
|
||||
#[allow(unused_imports)]
|
||||
@@ -9,19 +9,15 @@ use super::*;
|
||||
impl QwenForward {
|
||||
/// A forward without its output head can never publish, so it is refused before reading any row or running any
|
||||
/// layer. The cache preparation above keeps its precedence; nothing has been staged yet.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super) fn step_core(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: Option<&OutputStage<'_, '_>>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
mut moe_cache: Option<&mut MoeWeightCache<'_>>,
|
||||
dense_cache: Option<&DenseWeightCache<'_>>,
|
||||
capture_mtp: bool,
|
||||
prefill_only: bool,
|
||||
caches: StepCaches<'_, '_, '_, '_>,
|
||||
purpose: StepPurpose,
|
||||
) -> Result<StepCoreResult> {
|
||||
let StepRequest { binding, token, position: pos } = request;
|
||||
let StepCaches { kar: kar_cache, moe: mut moe_cache, dense: dense_cache } = caches;
|
||||
let mut streams = None;
|
||||
let ctx = LayerCtx { binding, token, pos, dense: dense_cache };
|
||||
let predicted = session.transact_completion(token, pos, &binding.identity(), |txn| {
|
||||
@@ -29,8 +25,8 @@ impl QwenForward {
|
||||
let output = output.ok_or(Error::Unsupported(Stage::Output))?;
|
||||
stage_input_row(binding, token, pos, kar_cache, txn)?;
|
||||
let final_residual = run_layers(&ctx, txn, layer_bound, moe_cache.as_deref_mut())?;
|
||||
let predicted = finish_step(&ctx, txn, output, &final_residual, prefill_only)?;
|
||||
if capture_mtp {
|
||||
let predicted = finish_step(&ctx, txn, output, &final_residual, purpose.is_prefill_only())?;
|
||||
if purpose.retains_streams() {
|
||||
streams = Some(capture_streams(&final_residual)?);
|
||||
}
|
||||
Ok(predicted)
|
||||
@@ -0,0 +1,127 @@
|
||||
//! The forward-step entry points of QwenForward: greedy, KAR, MTP target and MTP prefill steps.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl QwenForward {
|
||||
pub(crate) fn step(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(StepRequest { binding, token, position: pos }, session, None, None)
|
||||
}
|
||||
|
||||
/// Complete-forward entry retains the loaded output head across tokens.
|
||||
/// Unsupported stages abort the same transaction without state publication.
|
||||
pub(crate) fn step_with_output(
|
||||
binding: &ModelBinding,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(StepRequest { binding, token, position: pos }, session, Some(output), None)
|
||||
}
|
||||
|
||||
/// Explicit loaded KAR provider. Cache lifetime is borrowed from the
|
||||
/// caller's stable owner-thread Context; it is never self-referential.
|
||||
pub(crate) fn step_with_kar_ple_output(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
cache: &mut KarPleCache<'_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_inner(request, session, Some(output), Some(cache))
|
||||
}
|
||||
|
||||
pub(in super::super) fn step_inner(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: Option<&OutputStage<'_, '_>>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
) -> Result<TokenId> {
|
||||
let caches = StepCaches { kar: kar_cache, moe: None, dense: None };
|
||||
Self::step_core(request, session, output, caches, StepPurpose::Greedy)
|
||||
.and_then(|(predicted, _)| predicted.ok_or(Error::IdentityMismatch))
|
||||
}
|
||||
|
||||
/// Retain the pre-output four-stream residual only for explicit MTP use.
|
||||
/// Native/KAR callers above keep their original allocation and math path.
|
||||
pub(crate) fn step_for_mtp(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
let caches = StepCaches { kar: kar_cache, moe: None, dense: None };
|
||||
Self::step_for_mtp_cached(request, session, output, caches)
|
||||
}
|
||||
|
||||
/// A complete greedy step through the supplied weight caches.
|
||||
pub(crate) fn step_cached(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
caches: StepCaches<'_, '_, '_, '_>,
|
||||
) -> Result<TokenId> {
|
||||
Self::step_core(request, session, Some(output), caches, StepPurpose::Greedy)
|
||||
.and_then(|(token, _)| token.ok_or(Error::IdentityMismatch))
|
||||
}
|
||||
|
||||
/// A complete step through the supplied weight caches that retains the MTP target product.
|
||||
pub(crate) fn step_for_mtp_cached(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
caches: StepCaches<'_, '_, '_, '_>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpTarget)?;
|
||||
target_product(request, session, predicted, streams)
|
||||
}
|
||||
|
||||
/// A known-next prefill step through the supplied weight caches that retains the MTP prefill product.
|
||||
pub(crate) fn prefill_for_mtp_cached(
|
||||
request: StepRequest<'_>,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
caches: StepCaches<'_, '_, '_, '_>,
|
||||
) -> Result<PrefillStepProduct> {
|
||||
let (predicted, streams) = Self::step_core(request, session, Some(output), caches, StepPurpose::MtpPrefill)?;
|
||||
if predicted.is_some() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
prefill_product(request, session, streams)
|
||||
}
|
||||
}
|
||||
|
||||
fn target_product(
|
||||
request: StepRequest<'_>,
|
||||
session: &QwenSession<'_>,
|
||||
predicted: Option<TokenId>,
|
||||
streams: Option<Box<[f32]>>,
|
||||
) -> Result<TargetStepProduct> {
|
||||
Ok(TargetStepProduct {
|
||||
binding: request.binding.identity(),
|
||||
token: request.token,
|
||||
position: request.position,
|
||||
predicted: predicted.ok_or(Error::IdentityMismatch)?,
|
||||
streams: streams.ok_or(Error::IdentityMismatch)?,
|
||||
origin: session.target_origin()?,
|
||||
})
|
||||
}
|
||||
|
||||
fn prefill_product(
|
||||
request: StepRequest<'_>,
|
||||
session: &QwenSession<'_>,
|
||||
streams: Option<Box<[f32]>>,
|
||||
) -> Result<PrefillStepProduct> {
|
||||
Ok(PrefillStepProduct {
|
||||
binding: request.binding.identity(),
|
||||
token: request.token,
|
||||
position: request.position,
|
||||
streams: streams.ok_or(Error::IdentityMismatch)?,
|
||||
origin: session.target_origin()?,
|
||||
})
|
||||
}
|
||||
+13
-5
@@ -53,18 +53,26 @@ fn read_layer_one<'cache, 'ctx>(
|
||||
GrStage::read_attention_after_ple(binding, layer, &ple, txn, cache)
|
||||
}
|
||||
|
||||
/// A layer about to be read together with the residual left by the layer before it (none for the first layer).
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct LayerEntry<'a> {
|
||||
pub(super) layer: LayerId,
|
||||
pub(super) previous: Option<&'a InjectedResidual>,
|
||||
}
|
||||
|
||||
/// Mint the actual row input without performing a scalar GR read. The real
|
||||
/// layer-one PLE history still advances in chronological transaction order;
|
||||
/// the caller completes GR only after collecting the genuine micro-window.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(super) fn prepare_layer_attention_micro(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
previous: Option<&InjectedResidual>,
|
||||
entry: LayerEntry<'_>,
|
||||
txn: &mut QwenStepTxn,
|
||||
cache: &DenseWeightCache<'_>,
|
||||
ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>,
|
||||
) -> Result<super::super::gr::GrMicroInput> {
|
||||
let LayerEntry { layer, previous } = entry;
|
||||
match layer.get() {
|
||||
0 => {
|
||||
if previous.is_some() {
|
||||
@@ -72,7 +80,7 @@ pub(super) fn prepare_layer_attention_micro(
|
||||
}
|
||||
GrStage::prepare_micro_initial(binding, layer, txn)
|
||||
}
|
||||
1 => prepare_layer_one_micro(binding, layer, previous, txn, cache, ple_micro),
|
||||
1 => prepare_layer_one_micro(binding, entry, txn, cache, ple_micro),
|
||||
_ => GrStage::prepare_micro_after_ffn(binding, layer, previous.ok_or(Error::IdentityMismatch)?, txn),
|
||||
}
|
||||
}
|
||||
@@ -80,12 +88,12 @@ pub(super) fn prepare_layer_attention_micro(
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn prepare_layer_one_micro(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
previous: Option<&InjectedResidual>,
|
||||
entry: LayerEntry<'_>,
|
||||
txn: &mut QwenStepTxn,
|
||||
cache: &DenseWeightCache<'_>,
|
||||
ple_micro: Option<&mut super::super::input::PleMicroBatchReady<'_>>,
|
||||
) -> Result<super::super::gr::GrMicroInput> {
|
||||
let LayerEntry { layer, previous } = entry;
|
||||
let previous = previous.ok_or(Error::IdentityMismatch)?;
|
||||
let prior = txn.ple_prior()?;
|
||||
let mut ple = diagnose(
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Cache-reset-replay numerical proof, moved out of `executor.rs` by STRA-338 (size); same module path as before.
|
||||
|
||||
use super::*;
|
||||
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
|
||||
use crate::qwen_forward::{
|
||||
dense_weight_cache::DenseCacheCounters, moe_weight_cache::WeightCacheCounters, session::ResetReplaySnapshot,
|
||||
};
|
||||
@@ -108,17 +109,14 @@ impl Run<'_, '_, '_> {
|
||||
baseline.try_reserve_exact(TOKENS.len()).expect("baseline retention allocation failed");
|
||||
self.output.test_reset_replay_record(true).expect("logit observer refused");
|
||||
for (index, token) in TOKENS.into_iter().enumerate() {
|
||||
let greedy = QwenForward::step_cached(
|
||||
self.binding,
|
||||
TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"),
|
||||
Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"),
|
||||
session,
|
||||
self.output,
|
||||
Some(&mut *cache),
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
)
|
||||
.expect("cached baseline full forward refused");
|
||||
let request = StepRequest {
|
||||
binding: self.binding,
|
||||
token: TokenId::new(token, self.fixed.vocabulary).expect("fixed token refused"),
|
||||
position: Position::new(index as u64, self.fixed.context_length).expect("fixed position refused"),
|
||||
};
|
||||
let caches = StepCaches { kar: Some(&mut *cache), moe: Some(&mut *moe_cache), dense: Some(dense_cache) };
|
||||
let greedy = QwenForward::step_cached(request, session, self.output, caches)
|
||||
.expect("cached baseline full forward refused");
|
||||
baseline.push(capture_committed(self.binding, session, self.output, greedy, index));
|
||||
}
|
||||
baseline
|
||||
@@ -131,15 +129,13 @@ impl Run<'_, '_, '_> {
|
||||
cache: &mut KarPleCache<'_>,
|
||||
expected: &CapturedStep,
|
||||
) {
|
||||
let greedy = QwenForward::step_with_kar_ple_output(
|
||||
self.binding,
|
||||
TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"),
|
||||
Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"),
|
||||
session,
|
||||
self.output,
|
||||
cache,
|
||||
)
|
||||
.expect("legacy uncached full forward refused");
|
||||
let request = StepRequest {
|
||||
binding: self.binding,
|
||||
token: TokenId::new(TOKENS[index], self.fixed.vocabulary).expect("fixed replay token refused"),
|
||||
position: Position::new(index as u64, self.fixed.context_length).expect("fixed replay position refused"),
|
||||
};
|
||||
let greedy = QwenForward::step_with_kar_ple_output(request, session, self.output, cache)
|
||||
.expect("legacy uncached full forward refused");
|
||||
let actual = capture_committed(self.binding, session, self.output, greedy, index);
|
||||
assert!(actual.greedy == expected.greedy, "replay greedy mismatch at step {index}");
|
||||
assert!(actual.logits.as_ref() == expected.logits.as_ref(), "full logit word mismatch at step {index}");
|
||||
@@ -200,14 +196,8 @@ fn report_numerical_pass(charged: usize, moe: &WeightCacheCounters, dense: &Dens
|
||||
|
||||
/// Narrow test entry can borrow an already verified/loaded operator owner.
|
||||
/// It never opens model paths, swaps providers or reloads weights/cache.
|
||||
pub(in crate::qwen_forward) fn check_on_loaded(
|
||||
binding: &ModelBinding,
|
||||
session: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
cache: &mut KarPleCache<'_>,
|
||||
moe_cache: &mut MoeWeightCache<'_>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
) {
|
||||
pub(in crate::qwen_forward) fn check_on_loaded(owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>) {
|
||||
let LoadedTargetOwners { binding, session, output, kar: cache, moe: moe_cache, dense: dense_cache } = owners;
|
||||
let charged = assert_topology(binding);
|
||||
let run = Run { binding, output, fixed: fixed_dimensions(binding) };
|
||||
let fresh = session.test_reset_replay_snapshot(binding).expect("fresh session snapshot refused");
|
||||
@@ -305,7 +295,14 @@ fn pinned_kar_cached_vs_legacy_same_session_reset_replays_all_logits_and_numeric
|
||||
let dense_cache =
|
||||
DenseWeightCache::new(&binding, context.as_ref()).expect("actor-owned dense weight cache load failed");
|
||||
let mut session = QwenSession::for_binding_on_shared_device(&binding, Rc::clone(&context));
|
||||
check_on_loaded(&binding, &mut session, &output, &mut cache, &mut moe_cache, &dense_cache);
|
||||
check_on_loaded(LoadedTargetOwners {
|
||||
binding: &binding,
|
||||
session: &mut session,
|
||||
output: &output,
|
||||
kar: &mut cache,
|
||||
moe: &mut moe_cache,
|
||||
dense: &dense_cache,
|
||||
});
|
||||
drop(session);
|
||||
let (moe_closed, dense_closed) = close_owners(moe_cache, dense_cache, cache, output);
|
||||
assert_teardown_clean(&close_context(moe_closed.is_ok(), dense_closed.is_ok(), context));
|
||||
|
||||
+17
-8
@@ -3,6 +3,7 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::gdn::GdnLayerInput;
|
||||
use crate::qwen_forward::moe_expert::ExpertRowRequest;
|
||||
use crate::qwen_forward::qsa_attention::QsaReady;
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -17,6 +18,13 @@ pub(super) struct LayerCtx<'a, 'ctx> {
|
||||
pub(super) dense: Option<&'a DenseWeightCache<'ctx>>,
|
||||
}
|
||||
|
||||
/// The layer one phase runs: its checked id and its kind (GDN or QSA).
|
||||
#[derive(Clone, Copy)]
|
||||
struct LayerSite {
|
||||
layer: LayerId,
|
||||
kind: BoundLayerKind,
|
||||
}
|
||||
|
||||
/// Validate the complete producer-bound descriptor sequence before touching any model rows or invoking a stage.
|
||||
pub(super) fn prepare_step_caches(
|
||||
binding: &ModelBinding,
|
||||
@@ -101,7 +109,8 @@ pub(super) fn run_layers(
|
||||
eprintln!("integration: starting layer {}", descriptor.index());
|
||||
let kind = descriptor.kind();
|
||||
let index = descriptor.index();
|
||||
let completed = run_layer(ctx, txn, index, kind, layer_bound, previous.as_ref(), moe_cache.as_deref_mut())?;
|
||||
let site = LayerSite { layer: LayerId::new(u64::from(index), layer_bound)?, kind };
|
||||
let completed = run_layer(ctx, txn, site, previous.as_ref(), moe_cache.as_deref_mut())?;
|
||||
txn.mark_layer_complete(&completed)?;
|
||||
previous = Some(completed);
|
||||
}
|
||||
@@ -112,13 +121,11 @@ pub(super) fn run_layers(
|
||||
fn run_layer(
|
||||
ctx: &LayerCtx<'_, '_>,
|
||||
txn: &mut QwenStepTxn,
|
||||
descriptor_index: u32,
|
||||
kind: BoundLayerKind,
|
||||
layer_bound: Dimension,
|
||||
site: LayerSite,
|
||||
previous: Option<&InjectedResidual>,
|
||||
moe_cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<InjectedResidual> {
|
||||
let layer = LayerId::new(u64::from(descriptor_index), layer_bound)?;
|
||||
let LayerSite { layer, kind } = site;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if oracle_capture::enabled() {
|
||||
oracle_capture::begin(ctx.pos.get(), layer.get() as i32)?;
|
||||
@@ -272,8 +279,10 @@ fn qsa_attention_indexed(
|
||||
layer,
|
||||
prepared,
|
||||
txn,
|
||||
dense_cache,
|
||||
dense_cache.and_then(DenseWeightCache::qsa_attention_workspace),
|
||||
crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan {
|
||||
cache: dense_cache,
|
||||
scratch: dense_cache.and_then(DenseWeightCache::qsa_attention_workspace),
|
||||
},
|
||||
),
|
||||
)?;
|
||||
Ok(attention)
|
||||
@@ -341,7 +350,7 @@ fn moe_ffn_inject(
|
||||
ForwardPhase::MoeExpert,
|
||||
layer.get(),
|
||||
pos,
|
||||
MoeExpertStage::execute(binding, layer, route, ffn.ready(), txn, moe_cache),
|
||||
MoeExpertStage::execute(binding, ExpertRowRequest { layer, route, input: ffn.ready() }, txn, moe_cache),
|
||||
)?;
|
||||
experts.validate_origin(&binding.identity())?;
|
||||
experts.identity().validate(token, pos, layer)?;
|
||||
@@ -0,0 +1,41 @@
|
||||
//! The inputs of one forward step, grouped by meaning: what is forwarded, which caches serve it, what it is for.
|
||||
|
||||
use super::{DenseWeightCache, KarPleCache, ModelBinding, MoeWeightCache, Position, TokenId};
|
||||
|
||||
/// What one forward step runs: the model binding and the token at its position.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct StepRequest<'a> {
|
||||
pub(crate) binding: &'a ModelBinding,
|
||||
pub(crate) token: TokenId,
|
||||
pub(crate) position: Position,
|
||||
}
|
||||
|
||||
/// The weight caches one forward step reads and fills. An absent cache selects the uncached path of that provider.
|
||||
pub(crate) struct StepCaches<'a, 'kar, 'moe, 'dense> {
|
||||
pub(crate) kar: Option<&'a mut KarPleCache<'kar>>,
|
||||
pub(crate) moe: Option<&'a mut MoeWeightCache<'moe>>,
|
||||
pub(crate) dense: Option<&'a DenseWeightCache<'dense>>,
|
||||
}
|
||||
|
||||
/// What a forward step is for: it decides whether the pre-output streams are retained and the output head is read.
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum StepPurpose {
|
||||
/// A complete greedy step: the predicted token is published, nothing is retained for MTP.
|
||||
Greedy,
|
||||
/// A complete step whose pre-output four-stream residual is retained as the MTP target product.
|
||||
MtpTarget,
|
||||
/// A known-next prefill step: the streams are retained and no token is predicted.
|
||||
MtpPrefill,
|
||||
}
|
||||
|
||||
impl StepPurpose {
|
||||
/// Whether the four-stream residual is copied out for the MTP draft.
|
||||
pub(crate) fn retains_streams(self) -> bool {
|
||||
self != Self::Greedy
|
||||
}
|
||||
|
||||
/// Whether the step stops before the output head.
|
||||
pub(crate) fn is_prefill_only(self) -> bool {
|
||||
self == Self::MtpPrefill
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Only the explicitly selected new full-model MMQ gate. Old observers unchanged.
|
||||
use super::*;
|
||||
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
|
||||
use crate::qwen_forward::mtp_decode::MtpDecoder;
|
||||
use crate::qwen_forward::session::ResetReplaySnapshot;
|
||||
@@ -104,33 +105,24 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
|
||||
pub(super) fn warm_scalar_prefix(&mut self, scalar_draft: &mut MtpDecoder) {
|
||||
self.output.test_reset_replay_record(true).expect("head observer refused");
|
||||
for index in 0..3 {
|
||||
let source = QwenForward::prefill_for_mtp_cached(
|
||||
self.binding,
|
||||
self.ids[index],
|
||||
pos(index as u64),
|
||||
self.session,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
self.moe,
|
||||
self.dense,
|
||||
)
|
||||
.expect("scalar known-next target refused");
|
||||
let request = StepRequest { binding: self.binding, token: self.ids[index], position: pos(index as u64) };
|
||||
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
|
||||
let source = QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches)
|
||||
.expect("scalar known-next target refused");
|
||||
scalar_draft
|
||||
.warm_prefill(self.binding, self.session, &source, self.ids[index + 1], self.moe)
|
||||
.warm_prefill(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &source, next_token: self.ids[index + 1] },
|
||||
self.moe,
|
||||
)
|
||||
.expect("scalar known-next warm refused");
|
||||
}
|
||||
}
|
||||
pub(super) fn mtp_step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
|
||||
QwenForward::step_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
pos(position),
|
||||
self.session,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
Some(&mut *self.moe),
|
||||
Some(self.dense),
|
||||
)
|
||||
let request = StepRequest { binding: self.binding, token, position: pos(position) };
|
||||
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
|
||||
QwenForward::step_for_mtp_cached(request, self.session, self.output, caches)
|
||||
}
|
||||
pub(super) fn scalar_final_step(
|
||||
&mut self,
|
||||
@@ -155,11 +147,16 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
|
||||
source: &TargetStepProduct,
|
||||
) -> Observation {
|
||||
scalar_draft
|
||||
.warm_retained(self.binding, self.session, source, self.next, self.moe)
|
||||
.warm_retained(self.binding, self.session, KnownNext { source, next_token: self.next }, self.moe)
|
||||
.expect("scalar retained edge refused");
|
||||
let continuation = self.mtp_step(self.next, 4).expect("scalar continuation refused");
|
||||
scalar_draft
|
||||
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
|
||||
.warm_retained(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &continuation, next_token: self.follow },
|
||||
self.moe,
|
||||
)
|
||||
.expect("scalar continuation warm refused");
|
||||
let greedy = continuation.predicted(self.session).expect("baseline continuation origin invalid");
|
||||
let logits = self.output.test_reset_replay_take_logits().expect("baseline continuation head missing");
|
||||
@@ -323,11 +320,21 @@ impl MmqRun<'_, '_, '_, '_, '_, '_> {
|
||||
.validate_resume(self.binding, self.session, &chunk.product, &[0, 1, 0, 1])
|
||||
.expect("chunk resume fence refused");
|
||||
candidate_draft
|
||||
.warm_retained(self.binding, self.session, &chunk.product, self.next, self.moe)
|
||||
.warm_retained(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &chunk.product, next_token: self.next },
|
||||
self.moe,
|
||||
)
|
||||
.expect("chunk retained edge refused");
|
||||
let continuation = self.mtp_step(self.next, 4).expect("chunk continuation refused");
|
||||
candidate_draft
|
||||
.warm_retained(self.binding, self.session, &continuation, self.follow, self.moe)
|
||||
.warm_retained(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &continuation, next_token: self.follow },
|
||||
self.moe,
|
||||
)
|
||||
.expect("chunk continuation warm refused");
|
||||
let actual_greedy = continuation.predicted(self.session).expect("candidate continuation origin invalid");
|
||||
let actual_logits = self.output.test_reset_replay_take_logits().expect("candidate continuation head missing");
|
||||
|
||||
+9
-20
@@ -4,6 +4,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::session::original_prompt::{DraftRollback, PromptPublication};
|
||||
|
||||
impl Drop for OriginalPromptExecutor<'_> {
|
||||
fn drop(&mut self) {
|
||||
@@ -14,15 +15,11 @@ impl OriginalPromptPending<'_, '_, '_> {
|
||||
/// Any fallible publication leaves the owning transaction present so Drop
|
||||
/// restores both real physical accepted prefixes. Success consumes it.
|
||||
pub(in crate::qwen_forward) fn publish(mut self) -> Result<(TargetStepOrigin, Option<TokenId>)> {
|
||||
let result = self.txn.as_mut().ok_or(Error::IdentityMismatch)?.publish(
|
||||
self.binding,
|
||||
self.dense,
|
||||
self.layers,
|
||||
&self.completed,
|
||||
self.draft,
|
||||
&self.draft_kv,
|
||||
&self.sample,
|
||||
);
|
||||
let weights = PromptWeights { binding: self.binding, dense: self.dense };
|
||||
let publication =
|
||||
PromptPublication { completed: &self.completed, draft_kv: &self.draft_kv, sample: &self.sample };
|
||||
let txn = self.txn.as_mut().ok_or(Error::IdentityMismatch)?;
|
||||
let result = txn.publish(weights, self.layers, publication, self.draft);
|
||||
if result.is_ok() {
|
||||
self.txn.take();
|
||||
}
|
||||
@@ -32,17 +29,9 @@ impl OriginalPromptPending<'_, '_, '_> {
|
||||
impl Drop for OriginalPromptPending<'_, '_, '_> {
|
||||
fn drop(&mut self) {
|
||||
if let Some(txn) = self.txn.take() {
|
||||
if txn
|
||||
.abort_with_draft(
|
||||
self.binding,
|
||||
self.dense,
|
||||
self.layers,
|
||||
&self.checkpoint,
|
||||
self.draft,
|
||||
&self.draft_checkpoint,
|
||||
)
|
||||
.is_err()
|
||||
{
|
||||
let weights = PromptWeights { binding: self.binding, dense: self.dense };
|
||||
let rollback = DraftRollback { draft: self.draft, prior: &self.draft_checkpoint };
|
||||
if txn.abort_with_draft(weights, self.layers, &self.checkpoint, rollback).is_err() {
|
||||
*self.failed = true;
|
||||
}
|
||||
}
|
||||
|
||||
+3
-1
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::session::original_prompt::ParkedPoint;
|
||||
|
||||
/// The index image and mapped K/V journal of each of the twelve resident QSA layers, by layer slot.
|
||||
type QsaOwners<'ctx> =
|
||||
@@ -153,7 +154,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
return Err(Error::CudaExecution);
|
||||
}
|
||||
let PromptWeights { binding, dense } = weights;
|
||||
let imported = session.import_parked(binding, dense, &mut self.layers, parked, blocks);
|
||||
let point = ParkedPoint { session: parked, blocks };
|
||||
let imported = session.import_parked(PromptWeights::new(binding, dense), &mut self.layers, point);
|
||||
if imported.is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
|
||||
+4
-1
@@ -59,7 +59,10 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
first_predecessors = Some(step.input_predecessors()?);
|
||||
}
|
||||
match kar.as_deref() {
|
||||
Some(cache) => InputStage::consume_kar_deferred(binding, cache, token, pos, step, &mut staged),
|
||||
Some(cache) => {
|
||||
let input = crate::qwen_forward::input::PositionedToken { token, position: pos };
|
||||
InputStage::consume_kar_deferred(binding, cache, input, step, &mut staged)
|
||||
}
|
||||
None => Err(Error::IdentityMismatch),
|
||||
}
|
||||
})?;
|
||||
|
||||
+3
-2
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::session::original_prompt::DraftRollback;
|
||||
|
||||
#[path = "impl_originalpromptexecutor/forward_draft.rs"]
|
||||
mod forward_draft;
|
||||
@@ -195,8 +196,8 @@ impl<'ctx> OriginalPromptExecutor<'ctx> {
|
||||
self.failed = true;
|
||||
}
|
||||
let ChunkRollback { draft, checkpoint, draft_checkpoint } = rollback;
|
||||
let cleanup =
|
||||
txn.abort_with_draft(weights.binding, weights.dense, &mut self.layers, checkpoint, draft, draft_checkpoint);
|
||||
let rollback = DraftRollback { draft, prior: draft_checkpoint };
|
||||
let cleanup = txn.abort_with_draft(weights, &mut self.layers, checkpoint, rollback);
|
||||
if cleanup.is_err() || self.context.is_poisoned() {
|
||||
self.failed = true;
|
||||
}
|
||||
|
||||
+27
-22
@@ -5,7 +5,8 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::executor::{PrefillStepProduct, TargetStepProduct};
|
||||
use crate::qwen_forward::executor::{PrefillStepProduct, StepCaches, StepRequest, TargetStepProduct};
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
|
||||
use crate::qwen_forward::mtp_decode::MtpDecoder;
|
||||
use crate::qwen_forward::session::ResetReplaySnapshot;
|
||||
@@ -65,25 +66,15 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
|
||||
fn prefill(&mut self, ids: &Ids, (token, n): (TokenId, u64), what: &str) -> PrefillStepProduct {
|
||||
let position = ids.position(n);
|
||||
let kar = Some(&mut *self.kar);
|
||||
QwenForward::prefill_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position,
|
||||
self.session,
|
||||
self.output,
|
||||
kar,
|
||||
self.moe,
|
||||
self.dense,
|
||||
)
|
||||
.expect(what)
|
||||
let request = StepRequest { binding: self.binding, token, position };
|
||||
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
|
||||
QwenForward::prefill_for_mtp_cached(request, self.session, self.output, caches).expect(what)
|
||||
}
|
||||
|
||||
fn step_final(&mut self, ids: &Ids) -> TargetStepProduct {
|
||||
let (kar, moe) = (Some(&mut *self.kar), Some(&mut *self.moe));
|
||||
let position = ids.position(3);
|
||||
let (binding, output, dense) = (self.binding, self.output, Some(self.dense));
|
||||
QwenForward::step_for_mtp_cached(binding, ids.ids[3], position, self.session, output, kar, moe, dense)
|
||||
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(&mut *self.moe), dense: Some(self.dense) };
|
||||
let request = StepRequest { binding: self.binding, token: ids.ids[3], position: ids.position(3) };
|
||||
QwenForward::step_for_mtp_cached(request, self.session, self.output, caches)
|
||||
.expect("scalar final target refused")
|
||||
}
|
||||
|
||||
@@ -120,7 +111,12 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
let source = self.prefill(ids, (ids.ids[index], index as u64), "scalar known-next target refused");
|
||||
let successor = ids.ids[index + 1];
|
||||
draft
|
||||
.warm_prefill(self.binding, self.session, &source, successor, self.moe)
|
||||
.warm_prefill(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &source, next_token: successor },
|
||||
self.moe,
|
||||
)
|
||||
.expect("scalar known-next warm refused");
|
||||
}
|
||||
let source = self.step_final(ids);
|
||||
@@ -142,10 +138,12 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
source: &TargetStepProduct,
|
||||
) -> (ResetReplaySnapshot, MtpChunkNumericSnapshot) {
|
||||
let (binding, next) = (self.binding, ids.next);
|
||||
draft.warm_retained(binding, self.session, source, next, self.moe).expect("scalar retained edge refused");
|
||||
draft
|
||||
.warm_retained(binding, self.session, KnownNext { source, next_token: next }, self.moe)
|
||||
.expect("scalar retained edge refused");
|
||||
let continuation = self.prefill(ids, (next, 4), "scalar continuation refused");
|
||||
draft
|
||||
.warm_prefill(binding, self.session, &continuation, ids.follow, self.moe)
|
||||
.warm_prefill(binding, self.session, KnownNext { source: &continuation, next_token: ids.follow }, self.moe)
|
||||
.expect("scalar continuation warm refused");
|
||||
let state = self.snapshot("scalar continuation state invalid");
|
||||
(state, draft.test_chunk_snapshot())
|
||||
@@ -232,13 +230,20 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
assert!(candidate.test_chunk_eq(&baseline.draft), "actual draft KV/residual mismatch");
|
||||
let (binding, next) = (self.binding, ids.next);
|
||||
candidate.validate_resume(binding, self.session, &actual, &[0, 1, 0, 1]).expect("chunk resume fence refused");
|
||||
candidate.warm_retained(binding, self.session, &actual, next, self.moe).expect("chunk retained edge refused");
|
||||
candidate
|
||||
.warm_retained(binding, self.session, KnownNext { source: &actual, next_token: next }, self.moe)
|
||||
.expect("chunk retained edge refused");
|
||||
}
|
||||
|
||||
/// The continuation row after the chunk matches the scalar continuation.
|
||||
fn compare_continuation(&mut self, ids: &Ids, baseline: &Baseline, candidate: &mut MtpDecoder) {
|
||||
let continuation = self.prefill(ids, (ids.next, 4), "chunk continuation refused");
|
||||
let warm = candidate.warm_prefill(self.binding, self.session, &continuation, ids.follow, self.moe);
|
||||
let warm = candidate.warm_prefill(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &continuation, next_token: ids.follow },
|
||||
self.moe,
|
||||
);
|
||||
warm.expect("chunk continuation warm refused");
|
||||
let state = self.snapshot("chunk continuation invalid");
|
||||
assert!(baseline.continued_state.numeric_eq(&state), "continued target mismatch");
|
||||
|
||||
+4
-2
@@ -105,8 +105,10 @@ impl QwenForward {
|
||||
layer,
|
||||
prepared,
|
||||
txn,
|
||||
Some(dense),
|
||||
dense.qsa_attention_workspace(),
|
||||
crate::qwen_forward::qsa_attention::attention_scratch::QsaScratchLoan {
|
||||
cache: Some(dense),
|
||||
scratch: dense.qsa_attention_workspace(),
|
||||
},
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
+2
-1
@@ -91,7 +91,8 @@ impl QwenForward {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let prior = previous[index].as_ref();
|
||||
prepare_layer_attention_micro(env.binding, layer, prior, txn, env.dense, ple_micro.as_deref_mut())
|
||||
let entry = LayerEntry { layer, previous: prior };
|
||||
prepare_layer_attention_micro(env.binding, entry, txn, env.dense, ple_micro.as_deref_mut())
|
||||
},
|
||||
|inputs| {
|
||||
let (bank, rows) = Self::read_micro_bank(env, inputs)?;
|
||||
|
||||
+11
-6
@@ -3,6 +3,8 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::gr::GrBatchRow;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
use crate::qwen_forward::moe_expert::NativePromptFinish;
|
||||
use crate::qwen_forward::moe_expert::{ChunkFfnLayer, ExpertReady};
|
||||
use crate::qwen_forward::session::chunk::{ChunkFfnRow, PreparedLayerRow};
|
||||
|
||||
@@ -82,9 +84,12 @@ impl QwenForward {
|
||||
}
|
||||
ChunkMoePolicy::ExperimentalResidentMmq
|
||||
| ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr
|
||||
| ChunkMoePolicy::ExperimentalMtpVerification => {
|
||||
MoeExpertStage::execute_chunk_mmq(binding, layer, ffn_rows, chunk, moe_cache, cancelled)
|
||||
}
|
||||
| ChunkMoePolicy::ExperimentalMtpVerification => MoeExpertStage::execute_chunk_mmq(
|
||||
ChunkFfnLayer { binding, layer, rows: ffn_rows },
|
||||
chunk,
|
||||
moe_cache,
|
||||
cancelled,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,9 +109,9 @@ impl QwenForward {
|
||||
let products = native_moe.as_mut().ok_or(Error::IdentityMismatch);
|
||||
Some(products.and_then(|products| {
|
||||
let binding = env.binding;
|
||||
MoeExpertStage::execute_chunk_mmq_native_prompt(
|
||||
binding, layer, ffn_rows, chunk, moe_cache, cancelled, products, env.dense,
|
||||
)
|
||||
let ffn = ChunkFfnLayer { binding, layer, rows: ffn_rows };
|
||||
let finish = NativePromptFinish { products, dense: env.dense };
|
||||
MoeExpertStage::execute_chunk_mmq_native_prompt(ffn, chunk, moe_cache, cancelled, finish)
|
||||
}))
|
||||
}
|
||||
|
||||
|
||||
+14
-9
@@ -36,15 +36,20 @@ fn route_shared_micro<'driver>(
|
||||
let router = cache.router(binding, layer.get())?;
|
||||
let transient = MoePrefillStage::transient_bytes(inputs.len(), MoeBf16Profile::HighOnly)?;
|
||||
moe_cache.reserve_mmq_transient(binding, current, transient)?;
|
||||
moe_cache.with_native_shared_weights(binding, current, layer, transient, |context, weights, resources| {
|
||||
cache.retained_context(binding, context)?;
|
||||
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?;
|
||||
let window = WindowReads { binding, layer, reads: inputs };
|
||||
let operands = WindowOperands { router, weights: &weights, combine: None };
|
||||
let loans = PrefillLoans { current: context, resources, gemm: &gemm };
|
||||
MoePrefillStage::route_shared_micro(window, operands, loans)
|
||||
})
|
||||
moe_cache.with_native_shared_weights(
|
||||
binding,
|
||||
current,
|
||||
crate::qwen_forward::moe_weight_cache::SharedWeightsRequest { layer, transient_bytes: transient },
|
||||
|context, weights, resources| {
|
||||
cache.retained_context(binding, context)?;
|
||||
let mut workspace = cache.native_batch_workspace(binding, context)?.ok_or(Error::IdentityMismatch)?;
|
||||
let gemm = workspace.gdn_gemm().map_err(crate::qwen_forward::qsa_index::driver_error)?;
|
||||
let window = WindowReads { binding, layer, reads: inputs };
|
||||
let operands = WindowOperands { router, weights: &weights, combine: None };
|
||||
let loans = PrefillLoans { current: context, resources, gemm: &gemm };
|
||||
MoePrefillStage::route_shared_micro(window, operands, loans)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// The FFN row of every proof and detached read: routed from the shared products or from the FFN read.
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! The returned report owns only counts/booleans; its assertions belong AFTER
|
||||
//! the caller has closed all actual GPU owners and checked allocated_bytes=0.
|
||||
use super::*;
|
||||
use crate::qwen_forward::loaded_target_owners::LoadedTargetOwners;
|
||||
use crate::qwen_forward::mtp_decode::MtpDecoder;
|
||||
use std::{cell::Cell, rc::Rc};
|
||||
|
||||
@@ -94,16 +95,12 @@ impl WindowProofReport {
|
||||
}
|
||||
|
||||
impl QwenForward {
|
||||
pub(crate) fn test_window_boundaries_on_loaded<'driver>(
|
||||
binding: &ModelBinding,
|
||||
session: &mut QwenSession<'driver>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
moe: &mut MoeWeightCache<'driver>,
|
||||
dense: &DenseWeightCache<'_>,
|
||||
pub(crate) fn test_window_boundaries_on_loaded(
|
||||
owners: LoadedTargetOwners<'_, '_, '_, '_, '_, '_>,
|
||||
) -> Result<WindowProofReport> {
|
||||
let LoadedTargetOwners { binding, session, output, kar, moe, dense } = owners;
|
||||
// Early errors still return to the root-owned cleanup envelope.
|
||||
let result = run(binding, session, output, kar, moe, dense);
|
||||
let result = run(binding, session, ProofDevices { output, kar, moe, dense });
|
||||
if result.is_ok() {
|
||||
output.test_reset_replay_record(false)?;
|
||||
}
|
||||
@@ -128,17 +125,14 @@ fn tokens(count: usize, vocab: Dimension) -> Result<Vec<TokenId>> {
|
||||
|
||||
#[path = "executor_window_numeric/proof.rs"]
|
||||
mod proof;
|
||||
use proof::{CancelReport, CandidateReport, Proof};
|
||||
use proof::{CancelReport, CandidateReport, Proof, ProofDevices};
|
||||
|
||||
fn run<'driver>(
|
||||
binding: &ModelBinding,
|
||||
session: &mut QwenSession<'driver>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
moe: &mut MoeWeightCache<'driver>,
|
||||
dense: &DenseWeightCache<'_>,
|
||||
devices: ProofDevices<'_, '_, '_, '_, 'driver, '_>,
|
||||
) -> Result<WindowProofReport> {
|
||||
let mut proof = Proof::open(binding, session, output, kar, moe, dense)?;
|
||||
let mut proof = Proof::open(binding, session, devices)?;
|
||||
// A: unchanged actual Native4 target/draft path FIRST. The new candidate
|
||||
// changes only the sealed window size; no retrospective baseline policy.
|
||||
let baseline = proof.baseline()?;
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
use crate::qwen_forward::mtp::MtpChunkNumericSnapshot;
|
||||
use crate::qwen_forward::session::ResetReplaySnapshot;
|
||||
|
||||
@@ -56,31 +57,41 @@ fn count_differences<A, B>(a: &[A], b: &[B], same: impl Fn(&A, &B) -> bool) -> u
|
||||
if a.len() == b.len() { a.iter().zip(b).filter(|(x, y)| !same(x, y)).count() } else { usize::MAX }
|
||||
}
|
||||
|
||||
/// The output head and the weight caches the proof drives, borrowed from the loaded target owners.
|
||||
pub(super) struct ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd> {
|
||||
pub(super) output: &'a OutputStage<'o, 'p>,
|
||||
pub(super) kar: &'a mut KarPleCache<'k>,
|
||||
pub(super) moe: &'a mut MoeWeightCache<'driver>,
|
||||
pub(super) dense: &'a DenseWeightCache<'d>,
|
||||
}
|
||||
|
||||
/// The rows of one windowed prefill chunk: the model they run on, their tokens and the known next token.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ChunkRequest<'a> {
|
||||
binding: &'a ModelBinding,
|
||||
ids: &'a [TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
}
|
||||
|
||||
/// The windowed prefill transaction under the experimental retained-GR policy. The transaction borrows only the
|
||||
/// session; every other owner is reborrowed for this call alone.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn prepare_txn<'s, 'driver>(
|
||||
binding: &ModelBinding,
|
||||
request: ChunkRequest<'_>,
|
||||
session: &'s mut QwenSession<'driver>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
moe: &mut MoeWeightCache<'driver>,
|
||||
dense: &DenseWeightCache<'_>,
|
||||
ids: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
devices: &mut ProofDevices<'_, '_, '_, '_, 'driver, '_>,
|
||||
boundary: BoundaryPlan,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> Result<QwenChunkTxn<'s, 'driver>> {
|
||||
let policy = ChunkMoePolicy::ExperimentalRetainedGr;
|
||||
QwenForward::prepare_prefill_chunk_with_policy_windowed(
|
||||
binding,
|
||||
ids,
|
||||
known_next,
|
||||
request.binding,
|
||||
request.ids,
|
||||
request.known_next,
|
||||
session,
|
||||
output,
|
||||
Some(kar),
|
||||
moe,
|
||||
dense,
|
||||
devices.output,
|
||||
Some(&mut *devices.kar),
|
||||
&mut *devices.moe,
|
||||
devices.dense,
|
||||
HOST_BUDGET,
|
||||
cancelled,
|
||||
policy,
|
||||
@@ -93,10 +104,7 @@ fn prepare_txn<'s, 'driver>(
|
||||
pub(super) struct Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) session: &'a mut QwenSession<'driver>,
|
||||
pub(super) output: &'a OutputStage<'o, 'p>,
|
||||
pub(super) kar: &'a mut KarPleCache<'k>,
|
||||
pub(super) moe: &'a mut MoeWeightCache<'driver>,
|
||||
pub(super) dense: &'a DenseWeightCache<'d>,
|
||||
pub(super) devices: ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd>,
|
||||
pub(super) vocab: Dimension,
|
||||
pub(super) bounds: Dimension,
|
||||
pub(super) ids: Vec<TokenId>,
|
||||
@@ -109,10 +117,7 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
|
||||
pub(super) fn open(
|
||||
binding: &'a ModelBinding,
|
||||
session: &'a mut QwenSession<'driver>,
|
||||
output: &'a OutputStage<'o, 'p>,
|
||||
kar: &'a mut KarPleCache<'k>,
|
||||
moe: &'a mut MoeWeightCache<'driver>,
|
||||
dense: &'a DenseWeightCache<'d>,
|
||||
devices: ProofDevices<'a, 'o, 'p, 'k, 'driver, 'd>,
|
||||
) -> Result<Self> {
|
||||
let vocab = Dimension::new(248320)?;
|
||||
let bounds = crate::qwen_forward::contract::position_dimension();
|
||||
@@ -121,8 +126,8 @@ impl<'a, 'driver, 'k, 'o, 'p, 'd> Proof<'a, 'driver, 'k, 'o, 'p, 'd> {
|
||||
if !session.test_reset_replay_snapshot(binding)?.has_prefix(0, [-1, -1]) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
output.test_reset_replay_record(true)?;
|
||||
Ok(Self { binding, session, output, kar, moe, dense, vocab, bounds, ids, next, follow })
|
||||
devices.output.test_reset_replay_record(true)?;
|
||||
Ok(Self { binding, session, devices, vocab, bounds, ids, next, follow })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -142,7 +147,12 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
let product = self.baseline_prefill(&mut draft)?;
|
||||
let (logits, greedy, bits) = self.baseline_outputs(&product)?;
|
||||
let (target, mtp) = self.snapshots(&draft)?;
|
||||
draft.warm_retained(self.binding, self.session, &product, self.next, self.moe)?;
|
||||
draft.warm_retained(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: &product, next_token: self.next },
|
||||
self.devices.moe,
|
||||
)?;
|
||||
self.continuation(&mut draft)?;
|
||||
let (continued_target, continued_mtp) = self.snapshots(&draft)?;
|
||||
drop(product);
|
||||
@@ -158,10 +168,10 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
None,
|
||||
self.session,
|
||||
draft,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
self.moe,
|
||||
self.dense,
|
||||
self.devices.output,
|
||||
Some(&mut *self.devices.kar),
|
||||
self.devices.moe,
|
||||
self.devices.dense,
|
||||
HOST_BUDGET,
|
||||
|| false,
|
||||
)?
|
||||
@@ -169,7 +179,7 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
}
|
||||
|
||||
fn baseline_outputs(&self, product: &TargetStepProduct) -> Result<(Box<[u32]>, TokenId, Vec<u32>)> {
|
||||
let logits = self.output.test_reset_replay_take_logits()?;
|
||||
let logits = self.devices.output.test_reset_replay_take_logits()?;
|
||||
let greedy = product.predicted(self.session)?;
|
||||
let stream = product.streams(self.binding, self.ids[3], Position::new(3, self.bounds)?, self.session)?;
|
||||
let mut bits = Vec::new();
|
||||
@@ -181,24 +191,26 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
/// The continuation row after the window: one more actual prefill step, then the draft warm.
|
||||
fn continuation(&mut self, draft: &mut MtpDecoder) -> Result<()> {
|
||||
let position = Position::new(4, self.bounds)?;
|
||||
let step = QwenForward::prefill_for_mtp_cached(
|
||||
let request = StepRequest { binding: self.binding, token: self.next, position };
|
||||
let caches = StepCaches {
|
||||
kar: Some(&mut *self.devices.kar),
|
||||
moe: Some(&mut *self.devices.moe),
|
||||
dense: Some(self.devices.dense),
|
||||
};
|
||||
let step = QwenForward::prefill_for_mtp_cached(request, self.session, self.devices.output, caches)?;
|
||||
draft.warm_prefill(
|
||||
self.binding,
|
||||
self.next,
|
||||
position,
|
||||
self.session,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
self.moe,
|
||||
self.dense,
|
||||
KnownNext { source: &step, next_token: self.follow },
|
||||
self.devices.moe,
|
||||
)?;
|
||||
draft.warm_prefill(self.binding, self.session, &step, self.follow, self.moe)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn candidate(&mut self, base: &Baseline) -> Result<CandidateReport> {
|
||||
let mut draft = MtpDecoder::new(self.binding)?;
|
||||
let (product, full_journal) = self.stage_full_micro(&mut draft)?;
|
||||
let logits = self.output.test_reset_replay_take_logits()?;
|
||||
let logits = self.devices.output.test_reset_replay_take_logits()?;
|
||||
let position = Position::new(3, self.bounds)?;
|
||||
let stream = product.streams(self.binding, self.ids[3], position, self.session)?;
|
||||
let logit_differences = count_differences(&base.logits, &logits, |a, b| a == b);
|
||||
@@ -229,19 +241,24 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
product: &TargetStepProduct,
|
||||
) -> Result<(bool, bool)> {
|
||||
draft.validate_resume(self.binding, self.session, product, &[0, 1, 0, 1])?;
|
||||
draft.warm_retained(self.binding, self.session, product, self.next, self.moe)?;
|
||||
draft.warm_retained(
|
||||
self.binding,
|
||||
self.session,
|
||||
KnownNext { source: product, next_token: self.next },
|
||||
self.devices.moe,
|
||||
)?;
|
||||
self.continuation(draft)?;
|
||||
let target_equal = base.continued_target.numeric_eq(&self.snapshot()?);
|
||||
Ok((target_equal, draft.test_chunk_eq(&base.continued_mtp)))
|
||||
}
|
||||
|
||||
fn stage_full_micro(&mut self, draft: &mut MtpDecoder) -> Result<(TargetStepProduct, Journal)> {
|
||||
let (binding, output, dense) = (self.binding, self.output, self.dense);
|
||||
let binding = self.binding;
|
||||
let plan = BoundaryPlan::FullMicro2;
|
||||
let mut txn =
|
||||
prepare_txn(binding, self.session, output, self.kar, self.moe, dense, &self.ids, None, plan, || false)?;
|
||||
let request = ChunkRequest { binding, ids: &self.ids, known_next: None };
|
||||
let mut txn = prepare_txn(request, self.session, &mut self.devices, plan, || false)?;
|
||||
let journal = owned_journal(&txn)?;
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false)?;
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, self.devices.moe, || false)?;
|
||||
let source = txn.publish_joint(ready)?.into_target_product().ok_or(Error::IdentityMismatch)?;
|
||||
Ok((source, journal))
|
||||
}
|
||||
@@ -277,13 +294,14 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
}
|
||||
|
||||
fn stage_first_layer(&mut self, ids: &[TokenId], draft: &mut MtpDecoder) -> Result<FirstLayer> {
|
||||
let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next));
|
||||
let binding = self.binding;
|
||||
let plan = BoundaryPlan::FirstLayer;
|
||||
let mut txn = prepare_txn(binding, self.session, output, self.kar, self.moe, dense, ids, next, plan, || false)?;
|
||||
let request = ChunkRequest { binding, ids, known_next: Some(self.next) };
|
||||
let mut txn = prepare_txn(request, self.session, &mut self.devices, plan, || false)?;
|
||||
let finite_words = txn.test_partial_words();
|
||||
let journal = owned_journal(&txn)?;
|
||||
let publication_refused = txn.test_publication_preflight_refused();
|
||||
let staged = draft.stage_prefill_chunk(binding, &mut txn, self.moe, || false);
|
||||
let staged = draft.stage_prefill_chunk(binding, &mut txn, self.devices.moe, || false);
|
||||
let mtp_refused = matches!(staged, Err(Error::IdentityMismatch));
|
||||
Ok(FirstLayer { finite_words, journal, publication_refused, mtp_refused })
|
||||
}
|
||||
@@ -311,8 +329,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
/// The caches still validate against the MTP context, which must not be poisoned.
|
||||
fn healthy(&mut self) -> Result<bool> {
|
||||
let context = self.session.mtp_context()?;
|
||||
self.moe.validate(self.binding, context)?;
|
||||
self.dense.validate(self.binding)?;
|
||||
self.devices.moe.validate(self.binding, context)?;
|
||||
self.devices.dense.validate(self.binding)?;
|
||||
Ok(!context.is_poisoned())
|
||||
}
|
||||
|
||||
@@ -323,10 +341,8 @@ impl<'driver> Proof<'_, 'driver, '_, '_, '_, '_> {
|
||||
observed: Rc::clone(observation),
|
||||
cancelled: Rc::clone(&cancellation),
|
||||
};
|
||||
let (binding, output, dense, next) = (self.binding, self.output, self.dense, Some(self.next));
|
||||
let (session, kar, moe) = (&mut *self.session, &mut *self.kar, &mut *self.moe);
|
||||
let prepared =
|
||||
prepare_txn(binding, session, output, kar, moe, dense, &actual_ids, next, plan, || cancellation.get());
|
||||
let request = ChunkRequest { binding: self.binding, ids: &actual_ids, known_next: Some(self.next) };
|
||||
let prepared = prepare_txn(request, self.session, &mut self.devices, plan, || cancellation.get());
|
||||
Ok(matches!(prepared, Err(Error::Unsupported(Stage::Executor))))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
use super::super::dense_weight_cache::GrResident;
|
||||
use super::*;
|
||||
|
||||
/// What one GR read consumes: the residual role being read, whose token/layer it belongs to and its streams.
|
||||
pub(super) struct GrReadSource<'streams> {
|
||||
role: GrRole,
|
||||
identity: TokenLayer,
|
||||
streams: &'streams [f32],
|
||||
}
|
||||
|
||||
impl GrStage {
|
||||
pub(in super::super) fn apply<'cache, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
@@ -22,7 +29,8 @@ impl GrStage {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let identity = TokenLayer::new(input.token(), input.position(), layer);
|
||||
Self::read(binding, GrRole::Attention(layer.get()), identity, input.streams().values(), txn, cache)
|
||||
let source = GrReadSource { role: GrRole::Attention(layer.get()), identity, streams: input.streams().values() };
|
||||
Self::read(binding, source, txn, cache)
|
||||
}
|
||||
|
||||
pub(in super::super) fn read_ffn<'cache, 'ctx>(
|
||||
@@ -34,7 +42,9 @@ impl GrStage {
|
||||
) -> Result<GrRead<'cache, 'ctx>> {
|
||||
residual.validate_origin(&binding.identity(), GrRole::Attention(layer.get()))?;
|
||||
residual.identity.validate(txn.token(), txn.position(), layer)?;
|
||||
Self::read(binding, GrRole::Ffn(layer.get()), residual.identity, residual.streams(), txn, cache)
|
||||
let source =
|
||||
GrReadSource { role: GrRole::Ffn(layer.get()), identity: residual.identity, streams: residual.streams() };
|
||||
Self::read(binding, source, txn, cache)
|
||||
}
|
||||
|
||||
pub(in super::super) fn read_attention<'cache, 'ctx>(
|
||||
@@ -54,14 +64,12 @@ impl GrStage {
|
||||
residual.validate_origin(&binding.identity(), GrRole::Ffn(previous))?;
|
||||
let previous_layer = LayerId::new(u64::from(previous), Dimension::new(u64::from(binding.layer_count()))?)?;
|
||||
residual.identity.validate(txn.token(), txn.position(), previous_layer)?;
|
||||
Self::read(
|
||||
binding,
|
||||
GrRole::Attention(layer.get()),
|
||||
TokenLayer::new(txn.token(), txn.position(), layer),
|
||||
residual.streams(),
|
||||
txn,
|
||||
cache,
|
||||
)
|
||||
let source = GrReadSource {
|
||||
role: GrRole::Attention(layer.get()),
|
||||
identity: TokenLayer::new(txn.token(), txn.position(), layer),
|
||||
streams: residual.streams(),
|
||||
};
|
||||
Self::read(binding, source, txn, cache)
|
||||
}
|
||||
|
||||
pub(in super::super) fn read_attention_after_ple<'cache, 'ctx>(
|
||||
@@ -78,17 +86,17 @@ impl GrStage {
|
||||
}
|
||||
ple.validate_origin(&binding.identity())?;
|
||||
ple.identity().validate(txn.token(), txn.position(), layer)?;
|
||||
Self::read(binding, GrRole::Attention(1), ple.identity(), ple.streams(), txn, cache)
|
||||
let source = GrReadSource { role: GrRole::Attention(1), identity: ple.identity(), streams: ple.streams() };
|
||||
Self::read(binding, source, txn, cache)
|
||||
}
|
||||
|
||||
pub(super) fn read<'cache, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
role: GrRole,
|
||||
identity: TokenLayer,
|
||||
streams: &[f32],
|
||||
source: GrReadSource<'_>,
|
||||
txn: &mut QwenStepTxn,
|
||||
cache: Option<&'cache DenseWeightCache<'ctx>>,
|
||||
) -> Result<GrRead<'cache, 'ctx>> {
|
||||
let GrReadSource { role, identity, streams } = source;
|
||||
let context = Self::admit_read(binding, identity, streams, txn)?;
|
||||
let resident = cache.map(|c| c.gr(binding, role)).transpose()?;
|
||||
let weights = resolve_gr_weights(binding, role, resident)?;
|
||||
|
||||
@@ -18,6 +18,13 @@ pub(super) struct Stage<'c> {
|
||||
pub(super) failed: &'c Rc<Cell<bool>>,
|
||||
}
|
||||
|
||||
// The expectations every handoff round is compared with: the weights and the allocation before the proof.
|
||||
#[derive(Clone, Copy)]
|
||||
struct HandoffBaseline<'m, 'c> {
|
||||
weights: Weights<'m, 'c>,
|
||||
allocated_bytes_before: usize,
|
||||
}
|
||||
|
||||
impl<'c> Stage<'c> {
|
||||
fn weights<'m>(matrices: &'m [DeviceBuffer<'c>]) -> Result<Weights<'m, 'c>> {
|
||||
matrices.try_into().map_err(|_| Error::InvalidDimension)
|
||||
@@ -312,7 +319,7 @@ impl<'c> Stage<'c> {
|
||||
let (expected, block) = self.refusal_phase(&mut lease, matrices, before, tally)?;
|
||||
let weights = Self::weights(matrices)?;
|
||||
self.lease_refusals(&mut lease, weights, (&expected, &block), tally)?;
|
||||
self.handoff_rounds(cell, &mut lease, weights, before, tally)?;
|
||||
self.handoff_rounds(cell, &mut lease, HandoffBaseline { weights, allocated_bytes_before: before }, tally)?;
|
||||
self.replace_refusals(&mut lease, tally)?;
|
||||
// Abort exposes no readiness capability. Next actual call fully
|
||||
// overwrites the failed candidate and all FFN read outputs.
|
||||
@@ -331,13 +338,12 @@ impl<'c> Stage<'c> {
|
||||
&self,
|
||||
cell: &RefCell<GrScratch<'c>>,
|
||||
lease: &mut GrScratch<'c>,
|
||||
weights: Weights<'_, 'c>,
|
||||
before: usize,
|
||||
baseline: HandoffBaseline<'_, 'c>,
|
||||
tally: &mut Tally,
|
||||
) -> Result<()> {
|
||||
for pattern in [0, 1, 1, 2] {
|
||||
self.handoff_check(lease, weights, pattern, tally)?;
|
||||
if self.context.allocated_bytes() != before || cell.try_borrow_mut().is_ok() {
|
||||
self.handoff_check(lease, baseline.weights, pattern, tally)?;
|
||||
if self.context.allocated_bytes() != baseline.allocated_bytes_before || cell.try_borrow_mut().is_ok() {
|
||||
tally.differences += 1;
|
||||
}
|
||||
tally.guards += 1;
|
||||
|
||||
@@ -221,6 +221,7 @@ mod ple_tests {
|
||||
|
||||
mod impl_inputstage;
|
||||
mod impl_residualstreams;
|
||||
pub(super) use impl_inputstage::PositionedToken;
|
||||
#[allow(unused_imports)]
|
||||
use impl_inputstage::gather_ple;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -3,6 +3,13 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// A prompt token with the position it occupies in the transaction.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct PositionedToken {
|
||||
pub(in super::super) token: TokenId,
|
||||
pub(in super::super) position: Position,
|
||||
}
|
||||
|
||||
impl InputStage {
|
||||
pub(in super::super) fn consume(
|
||||
binding: &ModelBinding,
|
||||
@@ -48,11 +55,11 @@ impl InputStage {
|
||||
pub(in super::super) fn consume_kar_deferred(
|
||||
binding: &ModelBinding,
|
||||
cache: &kar_cache::KarPleCache<'_>,
|
||||
token: TokenId,
|
||||
pos: Position,
|
||||
input: PositionedToken,
|
||||
txn: &mut QwenStepTxn,
|
||||
staged: &mut StagedInput,
|
||||
) -> Result<InputReady> {
|
||||
let PositionedToken { token, position: pos } = input;
|
||||
let (_, rows) = admit_kar_input(binding, cache, token, pos, txn)?;
|
||||
let unique = match staged.unique.get(&token.get()) {
|
||||
Some(&u) => u,
|
||||
|
||||
@@ -118,6 +118,25 @@ fn micro_entry<'c>(
|
||||
}
|
||||
Ok(entry)
|
||||
}
|
||||
/// The PLE weights of one binding: the weights are only valid for the binding they were read from.
|
||||
#[derive(Clone, Copy)]
|
||||
struct BoundPleWeights<'a> {
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a Rc<PleWeights>,
|
||||
}
|
||||
/// The resident PLE entry of a dense weight cache, with the cache that retains it.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ResidentPle<'a, 'ctx> {
|
||||
cache: &'a DenseWeightCache<'ctx>,
|
||||
entry: &'a PleResident,
|
||||
}
|
||||
/// The host rows one PLE step consumes: the token embedding, the residual streams and the conv history.
|
||||
#[derive(Clone, Copy)]
|
||||
struct PleStepRows<'a> {
|
||||
embedding: &'a [f32],
|
||||
streams: &'a [f32],
|
||||
history: &'a [f32],
|
||||
}
|
||||
fn ple_candidate(
|
||||
context: &Context<'_>,
|
||||
(binding, weights): (&ModelBinding, &Rc<PleWeights>),
|
||||
@@ -126,7 +145,9 @@ fn ple_candidate(
|
||||
identity: TokenLayer,
|
||||
) -> Result<PleCandidate> {
|
||||
if let Some((cache, entry)) = cached {
|
||||
ple_cuda_cached(context, binding, weights, entry, cache, embedding, streams, history, identity)
|
||||
let bound = BoundPleWeights { binding, weights };
|
||||
let resident = ResidentPle { cache, entry };
|
||||
ple_cuda_cached(context, bound, resident, PleStepRows { embedding, streams, history }, identity)
|
||||
} else {
|
||||
ple_cuda(context, (binding, weights), (embedding, streams, history), None)
|
||||
}
|
||||
@@ -168,18 +189,16 @@ fn resolve_ple_weights<'c>(
|
||||
}
|
||||
Ok((resident, weights))
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn ple_cuda_cached(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &Rc<PleWeights>,
|
||||
entry: &PleResident,
|
||||
cache: &DenseWeightCache<'_>,
|
||||
embedding: &[f32],
|
||||
streams: &[f32],
|
||||
history: &[f32],
|
||||
bound: BoundPleWeights<'_>,
|
||||
resident: ResidentPle<'_, '_>,
|
||||
rows: PleStepRows<'_>,
|
||||
identity: TokenLayer,
|
||||
) -> Result<PleCandidate> {
|
||||
let BoundPleWeights { binding, weights } = bound;
|
||||
let ResidentPle { cache, entry } = resident;
|
||||
let PleStepRows { embedding, streams, history } = rows;
|
||||
check_cached_ple(cache, context, (binding, weights, entry), identity)?;
|
||||
let context = cache.retained_context(binding, context)?;
|
||||
let failed = cache.transport_failure_flag(binding, context)?;
|
||||
|
||||
@@ -31,8 +31,10 @@ fn project_key_value(
|
||||
resident: Option<(&DenseWeightCache<'_>, &PleResident)>,
|
||||
) -> Result<(Box<[f32]>, Box<[f32]>)> {
|
||||
let emb = ple_upload_f32(context, embedding)?;
|
||||
let key_values = ple_project(context, binding, weights, PleMatrixRole::Key, &emb, resident)?;
|
||||
let value_values = ple_project(context, binding, weights, PleMatrixRole::Value, &emb, resident)?;
|
||||
let key = PleMatrixSelection { binding, weights, role: PleMatrixRole::Key };
|
||||
let key_values = ple_project(context, key, &emb, resident)?;
|
||||
let value = PleMatrixSelection { binding, weights, role: PleMatrixRole::Value };
|
||||
let value_values = ple_project(context, value, &emb, resident)?;
|
||||
emb.release().map_err(ple_driver_error)?;
|
||||
Ok((key_values, value_values))
|
||||
}
|
||||
@@ -175,14 +177,20 @@ impl<'c> PleWork<'c> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
/// Which PLE projection matrix is read: its role (key or value), the binding it comes from and that binding's weights.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct PleMatrixSelection<'a> {
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a PleWeights,
|
||||
role: PleMatrixRole,
|
||||
}
|
||||
pub(super) fn ple_project(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &PleWeights,
|
||||
role: PleMatrixRole,
|
||||
matrix: PleMatrixSelection<'_>,
|
||||
embedding: &DeviceBuffer<'_>,
|
||||
resident: Option<(&DenseWeightCache<'_>, &PleResident)>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let PleMatrixSelection { binding, weights, role } = matrix;
|
||||
if role == PleMatrixRole::Key
|
||||
&& let Some((cache, entry)) = resident
|
||||
{
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Physical Qwen stage registry. Declaring a stage does not implement it.
|
||||
//! The shared contract and explicit incomplete shells arrive in phase B.
|
||||
|
||||
mod bound_expert;
|
||||
pub(crate) mod contract;
|
||||
pub(crate) mod dense_weight_cache;
|
||||
pub(crate) mod executor;
|
||||
|
||||
@@ -181,10 +181,10 @@ pub(super) fn format_case(context: &Context<'_>, kind: MoeMatrixKind, routed: bo
|
||||
let gate_matrix = upload_bytes(context, &gate_bytes).unwrap();
|
||||
let up_matrix = upload_bytes(context, &up_bytes).unwrap();
|
||||
let down_matrix = upload_bytes(context, &down_bytes).unwrap();
|
||||
let gate = project_retained_gate_up(context, |out| launch_projection(context, kind, &gate_matrix, &x, out, FF, N))
|
||||
.unwrap();
|
||||
let up =
|
||||
project_retained_gate_up(context, |out| launch_projection(context, kind, &up_matrix, &x, out, FF, N)).unwrap();
|
||||
let dims = MatrixDims { kind, rows: FF, columns: N };
|
||||
let gate =
|
||||
project_retained_gate_up(context, |out| launch_projection(context, dims, &gate_matrix, &x, out)).unwrap();
|
||||
let up = project_retained_gate_up(context, |out| launch_projection(context, dims, &up_matrix, &x, out)).unwrap();
|
||||
for buffer in [&gate, &up] {
|
||||
for value in download_f32(buffer, FF).unwrap().iter() {
|
||||
assert!(value.abs() < 20., "fixture exceeds predeclared Gate/Up bound");
|
||||
|
||||
+29
-5
@@ -21,11 +21,23 @@ impl<'ctx> DomainFixture<'ctx> {
|
||||
let up_matrix = upload_bytes(context, &encoded(MoeMatrixKind::Iq3Xxs, FF, N, 1)).unwrap();
|
||||
let down_matrix = upload_bytes(context, &encoded(MoeMatrixKind::RoutedIq4Nl, N, FF, 2)).unwrap();
|
||||
let gate = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &gate_matrix, &x, output, FF, N)
|
||||
launch_projection(
|
||||
context,
|
||||
MatrixDims { kind: MoeMatrixKind::Iq3Xxs, rows: FF, columns: N },
|
||||
&gate_matrix,
|
||||
&x,
|
||||
output,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let up = project_retained_gate_up(context, |output| {
|
||||
launch_projection(context, MoeMatrixKind::Iq3Xxs, &up_matrix, &x, output, FF, N)
|
||||
launch_projection(
|
||||
context,
|
||||
MatrixDims { kind: MoeMatrixKind::Iq3Xxs, rows: FF, columns: N },
|
||||
&up_matrix,
|
||||
&x,
|
||||
output,
|
||||
)
|
||||
})
|
||||
.unwrap();
|
||||
let mut hidden = context.allocate(FF * 4).unwrap();
|
||||
@@ -111,8 +123,14 @@ fn late_nan_projection_refused(context: &Context<'_>) {
|
||||
let x = upload_f32(context, &[0.25; N]).unwrap();
|
||||
let initial = context.allocated_bytes();
|
||||
assert_eq!(
|
||||
project_retained_gate_up(context, |out| launch_projection(context, MoeMatrixKind::Q6K, &w, &x, out, FF, N))
|
||||
.err(),
|
||||
project_retained_gate_up(context, |out| launch_projection(
|
||||
context,
|
||||
MatrixDims { kind: MoeMatrixKind::Q6K, rows: FF, columns: N },
|
||||
&w,
|
||||
&x,
|
||||
out
|
||||
))
|
||||
.err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(context.allocated_bytes(), initial);
|
||||
@@ -128,7 +146,13 @@ fn down_shape_refused(context: &Context<'_>) {
|
||||
wrong.copy_from(&sentinel).unwrap();
|
||||
let initial = context.allocated_bytes();
|
||||
let result = finish_cached_mlp(context, raw(context, &[0.25; FF]), raw(context, &[0.5; FF]), |hidden| {
|
||||
launch_projection(context, MoeMatrixKind::RoutedIq4Nl, &w, hidden, &mut wrong, N, FF)?;
|
||||
launch_projection(
|
||||
context,
|
||||
MatrixDims { kind: MoeMatrixKind::RoutedIq4Nl, rows: N, columns: FF },
|
||||
&w,
|
||||
hidden,
|
||||
&mut wrong,
|
||||
)?;
|
||||
panic!("wrong Down output must refuse");
|
||||
});
|
||||
assert_eq!(result.err(), Some(Error::InvalidDimension));
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
//! Artifact-bound selected experts and one independent shared expert.
|
||||
#![allow(dead_code)]
|
||||
use super::bound_expert::BoundExpert;
|
||||
use super::contract::{Error, LayerId, Result, Stage, TokenLayer};
|
||||
use super::gr::ResidualReady;
|
||||
use super::moe_route::RoutedExperts;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[allow(unused_imports)]
|
||||
use super::moe_weight_cache::SourceMatrix;
|
||||
use super::moe_weight_cache::{CachedMoeMatrix, MoeWeightCache};
|
||||
#[allow(unused_imports)]
|
||||
use super::moe_weight_cache::{MmqChunkRequest, SharedTailRow};
|
||||
use super::session::QwenStepTxn;
|
||||
use crate::model_binding::kar_expert_source::{KarExpertSource, KarSourceError};
|
||||
use crate::model_binding::qwen4exp_input::{
|
||||
@@ -22,6 +28,8 @@ use moe_down::{DownScope, DownSelection, PackedDown, RetainedDown, TransportBuff
|
||||
mod grouped;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) use grouped::LoadedArms;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use grouped::NativePromptFinish;
|
||||
pub(in crate::qwen_forward) use grouped::{ChunkFfnLayer, PreparedMoeRow};
|
||||
const N: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
@@ -63,50 +71,57 @@ mod moe_activation_reuse_gpu;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
mod impl_expertready;
|
||||
mod expert_step;
|
||||
pub(in crate::qwen_forward) use expert_step::ExpertRowRequest;
|
||||
#[allow(unused_imports)]
|
||||
use impl_expertready::execute_cuda;
|
||||
use expert_step::StepCuda;
|
||||
#[allow(unused_imports)]
|
||||
use impl_expertready::execute_cuda_kar;
|
||||
use expert_step::execute_cuda;
|
||||
#[allow(unused_imports)]
|
||||
use impl_expertready::kar_error;
|
||||
mod finish_with_parts_fn;
|
||||
use expert_step::execute_cuda_kar;
|
||||
#[allow(unused_imports)]
|
||||
use finish_with_parts_fn::execute_cuda_cached;
|
||||
use expert_step::kar_error;
|
||||
mod cached_expert_run;
|
||||
#[allow(unused_imports)]
|
||||
use finish_with_parts_fn::finish_with_parts;
|
||||
mod cached_mlp_down_fn;
|
||||
use cached_expert_run::execute_cuda_cached;
|
||||
#[allow(unused_imports)]
|
||||
use cached_mlp_down_fn::cached_gate_up_scoped;
|
||||
use cached_expert_run::finish_with_parts;
|
||||
mod scoped_expert_mlp;
|
||||
#[allow(unused_imports)]
|
||||
use cached_mlp_down_fn::cached_mlp_down;
|
||||
mod expert_mlp_fn;
|
||||
use scoped_expert_mlp::DownProvenance;
|
||||
#[allow(unused_imports)]
|
||||
use expert_mlp_fn::expert_mlp;
|
||||
use scoped_expert_mlp::cached_gate_up_scoped;
|
||||
#[allow(unused_imports)]
|
||||
use expert_mlp_fn::finish_cached_mlp;
|
||||
use scoped_expert_mlp::cached_mlp_down;
|
||||
mod expert_mlp_values;
|
||||
#[allow(unused_imports)]
|
||||
use expert_mlp_fn::project_cached_gate_up;
|
||||
use expert_mlp_values::expert_mlp;
|
||||
#[allow(unused_imports)]
|
||||
use expert_mlp_fn::project_retained_gate_up;
|
||||
mod project_matrix_fn;
|
||||
use expert_mlp_values::finish_cached_mlp;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::admit_budget;
|
||||
use expert_mlp_values::project_cached_gate_up;
|
||||
#[allow(unused_imports)]
|
||||
use expert_mlp_values::project_retained_gate_up;
|
||||
mod expert_matrix_projection;
|
||||
#[allow(unused_imports)]
|
||||
use expert_matrix_projection::admit_budget;
|
||||
#[cfg(test)]
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::collect_rows;
|
||||
use expert_matrix_projection::collect_rows;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::dual_format_kind;
|
||||
use expert_matrix_projection::dual_format_kind;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::dual_routed_format;
|
||||
use expert_matrix_projection::dual_routed_format;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::launch_cached_prepared;
|
||||
use expert_matrix_projection::launch_cached_prepared;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::launch_cached_projection;
|
||||
use expert_matrix_projection::launch_cached_projection;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::launch_projection;
|
||||
use expert_matrix_projection::launch_projection;
|
||||
#[allow(unused_imports)]
|
||||
use project_matrix_fn::project_matrix;
|
||||
use expert_matrix_projection::project_matrix;
|
||||
#[allow(unused_imports)]
|
||||
use expert_matrix_projection::{DeclaredMatrix, ExpertActivation, ExpertMatrix, MatrixDims};
|
||||
mod validate_values_fn;
|
||||
#[allow(unused_imports)]
|
||||
use validate_values_fn::binding_error;
|
||||
|
||||
+10
-14
@@ -55,8 +55,9 @@ fn scaled_shared<'ctx>(
|
||||
activation: &DeviceBuffer<'_>,
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let expert = BoundExpert { binding, weights, selection: MoeExpertSelection::Shared };
|
||||
let shared =
|
||||
expert_mlp(context, binding, weights, MoeExpertSelection::Shared, activation, cache.as_deref_mut(), None)?;
|
||||
expert_mlp(context, expert, ExpertActivation { buffer: activation, prepared: None }, cache.as_deref_mut())?;
|
||||
let shared_input = upload_f32(context, &shared)?;
|
||||
let (scalar, owned_scalar) = shared_scalar_buffers(context, binding, weights, activation, cache)?;
|
||||
let mut scaled = context.allocate(N * 4).map_err(driver_error)?;
|
||||
@@ -68,14 +69,11 @@ fn scaled_shared<'ctx>(
|
||||
/// Shared expert, router-weighted combine and readback over already computed
|
||||
/// routed expert outputs (`parts` is K*N values in router slot order).
|
||||
pub(super) fn finish_with_parts(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
step: &StepCuda<'_, '_, '_>,
|
||||
parts: &[f32],
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let StepCuda { context, binding, weights, activation, route } = *step;
|
||||
let scaled = scaled_shared(context, binding, weights, activation, cache)?;
|
||||
let parts = upload_f32(context, &parts)?;
|
||||
let route_values: [f32; K] = std::array::from_fn(|i| route.weights()[i].get());
|
||||
@@ -137,8 +135,10 @@ impl<'ctx> CachedRun<'_, 'ctx, '_, '_> {
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<ActualDown<'ctx>> {
|
||||
let (context, binding, weights, activation) = (self.context, self.binding, self.weights, self.activation);
|
||||
cached_mlp_down(context, binding, weights, selection, activation, cache, prepared, self.scope, self.origin)
|
||||
let expert = BoundExpert { binding: self.binding, weights: self.weights, selection };
|
||||
let activation = ExpertActivation { buffer: self.activation, prepared };
|
||||
let provenance = DownProvenance { scope: self.scope, origin: self.origin };
|
||||
cached_mlp_down(self.context, expert, activation, cache, provenance)
|
||||
}
|
||||
fn take(&self, down: ActualDown<'ctx>, selection: MoeExpertSelection) -> Result<RetainedDown<'ctx>> {
|
||||
down.take(self.origin, self.binding, self.route.identity(), selection)
|
||||
@@ -204,16 +204,12 @@ impl<'ctx> CachedOwners<'ctx> {
|
||||
]
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn execute_cuda_cached(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
step: &StepCuda<'_, '_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let StepCuda { context, binding, weights, activation, route } = *step;
|
||||
cache.validate(binding, context)?;
|
||||
route.validate_binding(&binding.identity())?;
|
||||
if !weights.matches(&binding.identity(), route.identity().layer().get()) {
|
||||
+37
-22
@@ -12,6 +12,28 @@ pub(super) struct MatrixDims {
|
||||
pub(super) kind: MoeMatrixKind,
|
||||
}
|
||||
|
||||
/// A Gate, Up or Down matrix of a bound expert.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ExpertMatrix<'a> {
|
||||
pub(super) expert: BoundExpert<'a>,
|
||||
pub(super) role: MoeMatrixRole,
|
||||
}
|
||||
|
||||
/// The activation a projection reads and, for a routed Gate/Up, its prepared Q8 form.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ExpertActivation<'a, 'ctx> {
|
||||
pub(super) buffer: &'a DeviceBuffer<'ctx>,
|
||||
pub(super) prepared: Option<&'a RoutedGateUpQ8<'ctx>>,
|
||||
}
|
||||
|
||||
/// An expert matrix (which expert, which role) together with the shape the binding declares for it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct DeclaredMatrix {
|
||||
pub(super) selection: MoeExpertSelection,
|
||||
pub(super) role: MoeMatrixRole,
|
||||
pub(super) dims: MatrixDims,
|
||||
}
|
||||
|
||||
fn matrix_dims(weights: &MoeExpertWeights, selection: MoeExpertSelection, role: MoeMatrixRole) -> Result<MatrixDims> {
|
||||
let (columns, rows) = weights.shape(selection, role).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, role).map_err(binding_error)?;
|
||||
@@ -73,12 +95,12 @@ fn upload_raw_matrix<'ctx>(
|
||||
fn project_into(
|
||||
context: &Context<'_>,
|
||||
matrix: CachedMoeMatrix<'_, '_>,
|
||||
dims: MatrixDims,
|
||||
(selection, role): (MoeExpertSelection, MoeMatrixRole),
|
||||
(activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>),
|
||||
declared: DeclaredMatrix,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
match prepared {
|
||||
let DeclaredMatrix { selection, role, dims } = declared;
|
||||
match activation.prepared {
|
||||
Some(prepared) => {
|
||||
if !matches!(selection, MoeExpertSelection::Routed { .. })
|
||||
|| !matches!(role, MoeMatrixRole::Gate | MoeMatrixRole::Up)
|
||||
@@ -91,7 +113,7 @@ fn project_into(
|
||||
launch_cached_prepared(context, matrix, prepared, output, format)?;
|
||||
}
|
||||
None => {
|
||||
launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns)?;
|
||||
launch_cached_projection(context, dims, matrix, activation.buffer, output)?;
|
||||
}
|
||||
}
|
||||
download_f32(output, dims.rows)
|
||||
@@ -119,17 +141,13 @@ fn allocate_output<'ctx>(context: &'ctx Context<'_>, rows: usize) -> Result<Devi
|
||||
context.allocate(output_bytes).map_err(driver_error)
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_matrix(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
role: MoeMatrixRole,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
requested: ExpertMatrix<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested;
|
||||
let dims = matrix_dims(weights, selection, role)?;
|
||||
if ![FF, N].contains(&dims.rows) {
|
||||
return Err(Error::InvalidDimension);
|
||||
@@ -147,7 +165,8 @@ pub(super) fn project_matrix(
|
||||
}
|
||||
};
|
||||
let mut output = allocate_output(context, dims.rows)?;
|
||||
let result = project_into(context, matrix, dims, (selection, role), (activation, prepared), &mut output);
|
||||
let declared = DeclaredMatrix { selection, role, dims };
|
||||
let result = project_into(context, matrix, declared, activation, &mut output);
|
||||
close_projection(result, output, owned)
|
||||
} // Retained legacy 64-row transport reference for its original refusal tests.
|
||||
// Production projects the complete matrix above, without host projection/math.
|
||||
@@ -193,20 +212,17 @@ pub(super) fn dual_routed_format(format: leleka_cuda_driver::MmqFormat) -> Route
|
||||
F::Q2Down => RoutedFormat::Q2_0,
|
||||
}
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn launch_cached_projection(
|
||||
context: &Context<'_>,
|
||||
kind: MoeMatrixKind,
|
||||
dims: MatrixDims,
|
||||
matrix: CachedMoeMatrix<'_, '_>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
rows: usize,
|
||||
columns: usize,
|
||||
) -> Result<()> {
|
||||
match matrix {
|
||||
CachedMoeMatrix::Raw(raw) => launch_projection(context, kind, raw, activation, output, rows, columns),
|
||||
CachedMoeMatrix::Raw(raw) => launch_projection(context, dims, raw, activation, output),
|
||||
CachedMoeMatrix::Dual(format, owner) => {
|
||||
if dual_format_kind(format) != (kind, rows, columns) {
|
||||
if dual_format_kind(format) != (dims.kind, dims.rows, dims.columns) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
owner.native_q8_1(activation, output).map_err(driver_error)
|
||||
@@ -283,13 +299,12 @@ fn launch_plan(kind: MoeMatrixKind) -> Option<Launch> {
|
||||
}
|
||||
pub(super) fn launch_projection(
|
||||
context: &Context<'_>,
|
||||
kind: MoeMatrixKind,
|
||||
dims: MatrixDims,
|
||||
matrix: &DeviceBuffer<'_>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
rows: usize,
|
||||
columns: usize,
|
||||
) -> Result<()> {
|
||||
let MatrixDims { columns, rows, kind } = dims;
|
||||
let Some(plan) = launch_plan(kind) else {
|
||||
return Err(Error::Unsupported(Stage::MoeExpert));
|
||||
};
|
||||
+17
-25
@@ -1,30 +1,28 @@
|
||||
//! Moved out of the parent module by STRA-338: fn expert_mlp, fn project_cached_gate_up, fn project_retained_gate_up,
|
||||
//! fn finish_cached_mlp.
|
||||
|
||||
use super::project_matrix_fn::{gate_up_dims, gate_up_prepared_format};
|
||||
use super::expert_matrix_projection::{gate_up_dims, gate_up_prepared_format};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
pub(super) fn expert_mlp(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
expert: BoundExpert<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
if let Some(cache) = cache.as_deref_mut() {
|
||||
return cached_expert_mlp(context, binding, weights, selection, activation, cache, prepared);
|
||||
return cached_expert_mlp(context, expert, activation, cache);
|
||||
}
|
||||
// Genuine uncached diagnostic: keep its original download/reupload chain.
|
||||
let project = |role, cache: Option<&mut MoeWeightCache<'_>>| {
|
||||
project_matrix(context, binding, weights, selection, role, activation, cache, prepared)
|
||||
project_matrix(context, ExpertMatrix { expert, role }, activation, cache)
|
||||
};
|
||||
let gate = project(MoeMatrixRole::Gate, cache.as_deref_mut())?;
|
||||
let up = project(MoeMatrixRole::Up, cache.as_deref_mut())?;
|
||||
let hidden = uncached_hidden(context, gate, up)?;
|
||||
let result = project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, &hidden, cache, None);
|
||||
let down = ExpertMatrix { expert, role: MoeMatrixRole::Down };
|
||||
let result = project_matrix(context, down, ExpertActivation { buffer: &hidden, prepared: None }, cache);
|
||||
let release = hidden.release().map_err(driver_error);
|
||||
match result {
|
||||
Err(error) => Err(error),
|
||||
@@ -36,15 +34,12 @@ pub(super) fn expert_mlp(
|
||||
}
|
||||
fn cached_expert_mlp(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
expert: BoundExpert<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let project = |role, cache: &mut MoeWeightCache<'_>| {
|
||||
project_cached_gate_up(context, binding, weights, selection, role, activation, cache, prepared)
|
||||
project_cached_gate_up(context, ExpertMatrix { expert, role }, activation, cache)
|
||||
};
|
||||
let gate = project(MoeMatrixRole::Gate, cache)?;
|
||||
let up = match project(MoeMatrixRole::Up, cache) {
|
||||
@@ -55,7 +50,8 @@ fn cached_expert_mlp(
|
||||
}
|
||||
};
|
||||
finish_cached_mlp(context, gate, up, |hidden| {
|
||||
project_matrix(context, binding, weights, selection, MoeMatrixRole::Down, hidden, Some(cache), None)
|
||||
let down = ExpertMatrix { expert, role: MoeMatrixRole::Down };
|
||||
project_matrix(context, down, ExpertActivation { buffer: hidden, prepared: None }, Some(cache))
|
||||
})
|
||||
}
|
||||
/// Re-uploads the host Gate/Up of the uncached diagnostic and returns the checked SwiGLU hidden buffer.
|
||||
@@ -69,26 +65,22 @@ fn uncached_hidden<'ctx>(context: &'ctx Context<'_>, gate: Box<[f32]>, up: Box<[
|
||||
up.release().map_err(driver_error)?;
|
||||
Ok(hidden)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_cached_gate_up<'ctx>(
|
||||
context: &'ctx Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
role: MoeMatrixRole,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
requested: ExpertMatrix<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<DeviceBuffer<'ctx>> {
|
||||
let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested;
|
||||
let dims = gate_up_dims(weights, selection, role)?;
|
||||
cache.validate(binding, context)?;
|
||||
let matrix = cache.matrix(binding, weights, selection, role)?;
|
||||
project_retained_gate_up(context, |output| match prepared {
|
||||
project_retained_gate_up(context, |output| match activation.prepared {
|
||||
Some(prepared) => {
|
||||
let format = gate_up_prepared_format(selection, dims.kind)?;
|
||||
launch_cached_prepared(context, matrix, prepared, output, format)
|
||||
}
|
||||
None => launch_cached_projection(context, dims.kind, matrix, activation, output, dims.rows, dims.columns),
|
||||
None => launch_cached_projection(context, dims, matrix, activation.buffer, output),
|
||||
})
|
||||
}
|
||||
// Fixed 640-value projection lifecycle shared by the cached artifact path and
|
||||
+32
-38
@@ -60,12 +60,19 @@ fn admitted_weights(binding: &ModelBinding, layer: LayerId, route: &RoutedExpert
|
||||
Ok(weights)
|
||||
}
|
||||
/// The validated inputs of one expert step on the device.
|
||||
struct StepCuda<'a, 'c, 'b> {
|
||||
context: &'a Context<'c>,
|
||||
binding: &'a ModelBinding,
|
||||
weights: &'a MoeExpertWeights,
|
||||
activation: &'a DeviceBuffer<'b>,
|
||||
route: &'a RoutedExperts,
|
||||
pub(super) struct StepCuda<'a, 'c, 'b> {
|
||||
pub(super) context: &'a Context<'c>,
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) weights: &'a MoeExpertWeights,
|
||||
pub(super) activation: &'a DeviceBuffer<'b>,
|
||||
pub(super) route: &'a RoutedExperts,
|
||||
}
|
||||
/// The FFN row of one layer handed to its experts: the layer, the routed experts chosen for it (consumed) and the
|
||||
/// residual that feeds them.
|
||||
pub(in super::super) struct ExpertRowRequest<'a> {
|
||||
pub(in super::super) layer: LayerId,
|
||||
pub(in super::super) route: RoutedExperts,
|
||||
pub(in super::super) input: &'a ResidualReady,
|
||||
}
|
||||
impl StepCuda<'_, '_, '_> {
|
||||
/// The expert output and the result of closing the step-local prepared owner.
|
||||
@@ -75,7 +82,7 @@ impl StepCuda<'_, '_, '_> {
|
||||
layer: LayerId,
|
||||
cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> (Result<Box<[f32]>>, Result<()>) {
|
||||
let Self { context, binding, weights, activation, route } = *self;
|
||||
let binding = self.binding;
|
||||
// One immutable, step-local owner only on the explicitly selected
|
||||
// cache path. It never enters the weight cache or recurrence state.
|
||||
if let Some(kar) = binding.kar_expert_source() {
|
||||
@@ -85,18 +92,17 @@ impl StepCuda<'_, '_, '_> {
|
||||
// refuse: it is simply not consulted for any expert here (the
|
||||
// shared expert takes the uncached path inside the KAR branch).
|
||||
let host = input.mixed();
|
||||
return (execute_cuda_kar(context, binding, weights, activation, route, host, (layer.get(), kar)), Ok(()));
|
||||
return (execute_cuda_kar(self, host, layer.get(), kar), Ok(()));
|
||||
}
|
||||
match cache {
|
||||
Some(cache) => self.dispatch_prepared(cache),
|
||||
None => (execute_cuda(context, binding, weights, activation, route, None, None), Ok(())),
|
||||
None => (execute_cuda(self, None, None), Ok(())),
|
||||
}
|
||||
}
|
||||
fn dispatch_prepared(&self, cache: &mut MoeWeightCache<'_>) -> (Result<Box<[f32]>>, Result<()>) {
|
||||
let Self { context, binding, weights, activation, route } = *self;
|
||||
match context.prepare_routed_gate_up_q8(activation) {
|
||||
match self.context.prepare_routed_gate_up_q8(self.activation) {
|
||||
Ok(prepared) => {
|
||||
let result = execute_cuda(context, binding, weights, activation, route, Some(cache), Some(&prepared));
|
||||
let result = execute_cuda(self, Some(cache), Some(&prepared));
|
||||
// Always attempt owner close before releasing its borrowed
|
||||
// activation, including a projection/readback failure.
|
||||
let closed = prepared.close().map_err(driver_error);
|
||||
@@ -109,12 +115,11 @@ impl StepCuda<'_, '_, '_> {
|
||||
impl MoeExpertStage {
|
||||
pub(in super::super) fn execute(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
route: RoutedExperts,
|
||||
input: &ResidualReady,
|
||||
request: ExpertRowRequest<'_>,
|
||||
txn: &mut QwenStepTxn,
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
) -> Result<ExpertReady> {
|
||||
let ExpertRowRequest { layer, route, input } = request;
|
||||
#[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);
|
||||
@@ -133,45 +138,34 @@ impl MoeExpertStage {
|
||||
}
|
||||
}
|
||||
pub(super) fn execute_cuda(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
step: &StepCuda<'_, '_, '_>,
|
||||
mut cache: Option<&mut MoeWeightCache<'_>>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let StepCuda { context, binding, weights, activation, .. } = *step;
|
||||
if let Some(cache) = cache.as_deref_mut() {
|
||||
return execute_cuda_cached(context, binding, weights, activation, route, cache, prepared);
|
||||
return execute_cuda_cached(step, cache, prepared);
|
||||
}
|
||||
let mut parts = Vec::new();
|
||||
parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?;
|
||||
for slot in 0..K {
|
||||
let output = expert_mlp(
|
||||
context,
|
||||
binding,
|
||||
weights,
|
||||
MoeExpertSelection::Routed { slot },
|
||||
activation,
|
||||
cache.as_deref_mut(),
|
||||
prepared,
|
||||
)?;
|
||||
let expert = BoundExpert { binding, weights, selection: MoeExpertSelection::Routed { slot } };
|
||||
let output =
|
||||
expert_mlp(context, expert, ExpertActivation { buffer: activation, prepared }, cache.as_deref_mut())?;
|
||||
validate_values(&output, N)?;
|
||||
parts.extend_from_slice(&output);
|
||||
}
|
||||
finish_with_parts(context, binding, weights, activation, route, &parts, cache)
|
||||
finish_with_parts(step, &parts, cache)
|
||||
}
|
||||
/// Routed experts from the KAR source, then the unchanged shared expert and
|
||||
/// combine. Every routed output is checked finite before it is combined.
|
||||
pub(super) fn execute_cuda_kar(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
route: &RoutedExperts,
|
||||
step: &StepCuda<'_, '_, '_>,
|
||||
host_input: &[f32],
|
||||
(layer, kar): (u32, &KarExpertSource),
|
||||
layer: u32,
|
||||
kar: &KarExpertSource,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let StepCuda { context, route, .. } = *step;
|
||||
let mut parts = Vec::new();
|
||||
parts.try_reserve_exact(K * N).map_err(|_| Error::InputAllocation)?;
|
||||
for slot in 0..K {
|
||||
@@ -180,7 +174,7 @@ pub(super) fn execute_cuda_kar(
|
||||
validate_values(&output, N)?;
|
||||
parts.extend_from_slice(&output);
|
||||
}
|
||||
finish_with_parts(context, binding, weights, activation, route, &parts, None)
|
||||
finish_with_parts(step, &parts, None)
|
||||
}
|
||||
pub(super) fn kar_error(error: KarSourceError) -> Error {
|
||||
match error {
|
||||
+32
-45
@@ -1,6 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: fn cached_mlp_down, fn cached_gate_up_scoped.
|
||||
|
||||
use super::project_matrix_fn::{MatrixDims, gate_up_dims, gate_up_prepared_format};
|
||||
use super::expert_matrix_projection::{MatrixDims, gate_up_dims, gate_up_prepared_format};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -29,15 +29,21 @@ fn swiglu_hidden(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The step-local scope that records a Down computation and the origin its results are minted under.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct DownProvenance<'a, 'ctx> {
|
||||
pub(super) scope: &'a DownScope<'ctx>,
|
||||
pub(super) origin: &'a Rc<DownOrigin>,
|
||||
}
|
||||
|
||||
fn project_down<'ctx>(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
scope: &DownScope<'ctx>,
|
||||
hidden: &TransportBuffer<'_>,
|
||||
) -> Result<RetainedDown<'ctx>> {
|
||||
let BoundExpert { binding, weights, selection } = expert;
|
||||
cache.validate(binding, context)?;
|
||||
let (columns, rows) = weights.shape(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
let kind = weights.kind(selection, MoeMatrixRole::Down).map_err(binding_error)?;
|
||||
@@ -50,7 +56,7 @@ fn project_down<'ctx>(
|
||||
MoeExpertSelection::Shared => DownSelection::Shared,
|
||||
};
|
||||
scope.project(numeric_selection, |output| {
|
||||
launch_cached_projection(context, kind, matrix, hidden.buffer()?, output, rows, columns)
|
||||
launch_cached_projection(context, MatrixDims { kind, rows, columns }, matrix, hidden.buffer()?, output)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -76,15 +82,13 @@ fn close_down_parts<'ctx>(
|
||||
/// Gate and Up of one expert plus the hidden buffer they feed; a failure closes every owner already made.
|
||||
fn gate_up_hidden<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
(activation, prepared): (&DeviceBuffer<'_>, Option<&RoutedGateUpQ8<'_>>),
|
||||
expert: BoundExpert<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
scope: &DownScope<'ctx>,
|
||||
) -> Result<(TransportBuffer<'ctx>, TransportBuffer<'ctx>, TransportBuffer<'ctx>)> {
|
||||
let scoped = |cache: &mut MoeWeightCache<'_>, role| {
|
||||
cached_gate_up_scoped(context, binding, weights, selection, role, activation, cache, prepared, scope)
|
||||
cached_gate_up_scoped(context, ExpertMatrix { expert, role }, activation, cache, scope)
|
||||
};
|
||||
let gate = scoped(cache, MoeMatrixRole::Gate)?;
|
||||
let up = match scoped(cache, MoeMatrixRole::Up) {
|
||||
@@ -104,75 +108,58 @@ fn gate_up_hidden<'ctx>(
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn cached_mlp_down<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
expert: BoundExpert<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
scope: &DownScope<'ctx>,
|
||||
origin: &Rc<DownOrigin>,
|
||||
provenance: DownProvenance<'_, 'ctx>,
|
||||
) -> Result<ActualDown<'ctx>> {
|
||||
check_origin(origin, binding, weights)?;
|
||||
let inputs = (activation, prepared);
|
||||
let (gate, up, mut hidden) = gate_up_hidden(context, binding, weights, selection, inputs, cache, scope)?;
|
||||
let DownProvenance { scope, origin } = provenance;
|
||||
check_origin(origin, expert.binding, expert.weights)?;
|
||||
let (gate, up, mut hidden) = gate_up_hidden(context, expert, activation, cache, scope)?;
|
||||
let result = swiglu_hidden(context, scope, &gate, &up, &mut hidden)
|
||||
.and_then(|()| project_down(context, binding, weights, selection, cache, scope, &hidden));
|
||||
.and_then(|()| project_down(context, expert, cache, scope, &hidden));
|
||||
close_down_parts(scope, result, gate, up, hidden).map(|output| ActualDown {
|
||||
origin: Rc::clone(origin),
|
||||
selection,
|
||||
selection: expert.selection,
|
||||
output,
|
||||
})
|
||||
}
|
||||
fn launch_scoped_gate_up(
|
||||
context: &Context<'_>,
|
||||
matrix: CachedMoeMatrix<'_, '_>,
|
||||
dims: MatrixDims,
|
||||
selection: MoeExpertSelection,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
declared: DeclaredMatrix,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
output: &mut TransportBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
match prepared {
|
||||
let DeclaredMatrix { selection, dims, .. } = declared;
|
||||
match activation.prepared {
|
||||
Some(prepared) => {
|
||||
let format = gate_up_prepared_format(selection, dims.kind)?;
|
||||
launch_cached_prepared(context, matrix, prepared, output.buffer_mut()?, format)?;
|
||||
}
|
||||
None => {
|
||||
launch_cached_projection(
|
||||
context,
|
||||
dims.kind,
|
||||
matrix,
|
||||
activation,
|
||||
output.buffer_mut()?,
|
||||
dims.rows,
|
||||
dims.columns,
|
||||
)?;
|
||||
launch_cached_projection(context, dims, matrix, activation.buffer, output.buffer_mut()?)?;
|
||||
}
|
||||
}
|
||||
download_f32(output.buffer()?, FF).map(|_| ())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn cached_gate_up_scoped<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
role: MoeMatrixRole,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
requested: ExpertMatrix<'_>,
|
||||
activation: ExpertActivation<'_, '_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
prepared: Option<&RoutedGateUpQ8<'_>>,
|
||||
scope: &DownScope<'ctx>,
|
||||
) -> Result<TransportBuffer<'ctx>> {
|
||||
let ExpertMatrix { expert: BoundExpert { binding, weights, selection }, role } = requested;
|
||||
let dims = gate_up_dims(weights, selection, role)?;
|
||||
cache.validate(binding, context)?;
|
||||
let matrix = cache.matrix(binding, weights, selection, role)?;
|
||||
let mut output = scope.allocate(FF * 4)?;
|
||||
let result = launch_scoped_gate_up(context, matrix, dims, selection, prepared, activation, &mut output);
|
||||
let declared = DeclaredMatrix { selection, role, dims };
|
||||
let result = launch_scoped_gate_up(context, matrix, declared, activation, &mut output);
|
||||
scope.record(&result);
|
||||
if let Err(primary) = result {
|
||||
let _ = output.close();
|
||||
@@ -5,7 +5,7 @@ use super::*;
|
||||
mod adaptive_wave_fn;
|
||||
use crate::model_binding::qwen4exp_input::{MoeRoutedSourceScope, MoeWeightDescriptor};
|
||||
use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, PreparedCpuMiss, runtime_error};
|
||||
use adaptive_wave_fn::AdaptiveWave;
|
||||
use adaptive_wave_fn::{AdaptiveWave, WaveState};
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn project_adaptive_groups<'ctx>(
|
||||
@@ -27,8 +27,8 @@ pub(super) fn project_adaptive_groups<'ctx>(
|
||||
}
|
||||
let (residents, misses) = split_resident_misses(binding, rows, groups, cache)?;
|
||||
let job_allowance = wave_job_allowance(residents.capacity(), misses.capacity())?;
|
||||
let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared };
|
||||
wave.run(cache, down, cancelled, actual, &residents, &misses, job_allowance)
|
||||
let wave = AdaptiveWave { context, binding, rows, scope, origins, prepared, actual };
|
||||
wave.run(&mut WaveState { cache, down, cancelled }, &residents, &misses, job_allowance)
|
||||
}
|
||||
|
||||
/// Actual outer wave directories coexist with owned jobs until join.
|
||||
|
||||
@@ -6,45 +6,57 @@ use crate::qwen_forward::cpu_expert_miss::{CpuMissRows, CpuMissWorkspace, runtim
|
||||
|
||||
/// The shared inputs of one adaptive wave: resident groups on the GPU, misses on the owned CPU pool.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct AdaptiveWave<'a, 'ctx> {
|
||||
pub(super) struct AdaptiveWave<'a, 'ctx, 'txn, 'driver> {
|
||||
pub(super) context: &'ctx Context<'ctx>,
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) rows: &'a [ChunkFfnRow],
|
||||
pub(super) scope: &'a DownScope<'ctx>,
|
||||
pub(super) origins: &'a [Rc<DownOrigin>],
|
||||
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
|
||||
pub(super) actual: Option<&'a QwenChunkTxn<'txn, 'driver>>,
|
||||
}
|
||||
|
||||
impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> {
|
||||
/// What an adaptive wave mutates while it runs: the weight cache, the down-projection slots and the cancellation
|
||||
/// poll, which is checked before every batch and every completed member.
|
||||
pub(super) struct WaveState<'w, 'cache, 'ctx, F: FnMut() -> bool> {
|
||||
pub(super) cache: &'w mut MoeWeightCache<'cache>,
|
||||
pub(super) down: &'w mut [[Option<ActualDown<'ctx>>; K]],
|
||||
pub(super) cancelled: &'w mut F,
|
||||
}
|
||||
|
||||
/// One batch of CPU miss groups, with the resident GPU groups that run overlapped with it (first batch only).
|
||||
#[derive(Clone, Copy)]
|
||||
struct MissBatch<'a> {
|
||||
groups: &'a [&'a [Pair]],
|
||||
residents: Option<&'a [&'a [Pair]]>,
|
||||
}
|
||||
|
||||
impl<'ctx> AdaptiveWave<'_, 'ctx, '_, '_> {
|
||||
/// Run the miss batches in order; the resident GPU groups run once, overlapped with the first batch.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn run(
|
||||
pub(super) fn run<F: FnMut() -> bool>(
|
||||
&self,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; K]],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
actual: Option<&QwenChunkTxn<'_, '_>>,
|
||||
state: &mut WaveState<'_, '_, 'ctx, F>,
|
||||
residents: &[&[Pair]],
|
||||
misses: &[&[Pair]],
|
||||
job_allowance: usize,
|
||||
) -> Result<()> {
|
||||
let mut gpu_done = false;
|
||||
let cpu_owner = cache.cpu_miss_owner(self.binding)?;
|
||||
let cpu_owner = state.cache.cpu_miss_owner(self.binding)?;
|
||||
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
let mut offset = 0usize;
|
||||
while offset < misses.len() {
|
||||
let end = miss_batch_end(self.rows, misses, offset)?;
|
||||
let batch = &misses[offset..end];
|
||||
let groups = &misses[offset..end];
|
||||
offset = end;
|
||||
if cancelled() {
|
||||
if (state.cancelled)() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let resident = if gpu_done { None } else { Some(residents) };
|
||||
self.run_batch(cache, down, cancelled, actual, &mut cpu, batch, resident, job_allowance)?;
|
||||
self.run_batch(state, &mut cpu, MissBatch { groups, residents: resident }, job_allowance)?;
|
||||
gpu_done = true;
|
||||
}
|
||||
if !gpu_done {
|
||||
self.project_residents(residents, cache, down, cancelled)?;
|
||||
self.project_residents(residents, state)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -53,23 +65,19 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> {
|
||||
/// the CPU side, then upload the completed rows. Model-lifetime stacks/native scratch were admitted before the
|
||||
/// pool. This request admits <=16 jobs and <=48MiB INCLUDING actual directory, preparation and start/join
|
||||
/// metadata/capacities. Callees measure their own retained capacities against this remaining allowance before send.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn run_batch(
|
||||
fn run_batch<F: FnMut() -> bool>(
|
||||
&self,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; K]],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
actual: Option<&QwenChunkTxn<'_, '_>>,
|
||||
state: &mut WaveState<'_, '_, 'ctx, F>,
|
||||
cpu: &mut CpuMissWorkspace,
|
||||
batch: &[&[Pair]],
|
||||
residents: Option<&[&[Pair]]>,
|
||||
batch: MissBatch<'_>,
|
||||
job_allowance: usize,
|
||||
) -> Result<()> {
|
||||
let MissBatch { groups: batch, residents } = batch;
|
||||
let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, job_allowance)?;
|
||||
let pending = cpu.start(jobs, job_allowance).map_err(runtime_error)?;
|
||||
let gpu_result = match residents {
|
||||
None => Ok(()),
|
||||
Some(residents) => self.project_residents(residents, cache, down, cancelled),
|
||||
Some(residents) => self.project_residents(residents, state),
|
||||
};
|
||||
// Always drain actual CPU consumers, including GPU failure/cancellation.
|
||||
// Preserve the primary GPU failure; no source allocation outlives join.
|
||||
@@ -79,55 +87,49 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> {
|
||||
if completed.len() != batch.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.finish_members(cache, down, cancelled, actual, completed, batch)
|
||||
self.finish_members(state, completed, batch)
|
||||
}
|
||||
|
||||
fn finish_members(
|
||||
fn finish_members<F: FnMut() -> bool>(
|
||||
&self,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; K]],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
actual: Option<&QwenChunkTxn<'_, '_>>,
|
||||
state: &mut WaveState<'_, '_, 'ctx, F>,
|
||||
completed: Vec<CpuMissRows>,
|
||||
batch: &[&[Pair]],
|
||||
) -> Result<()> {
|
||||
for (values, pairs) in completed.into_iter().zip(batch) {
|
||||
if cancelled() {
|
||||
if (state.cancelled)() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
self.finish_member(cache, down, actual, pairs, values)?;
|
||||
self.finish_member(state, pairs, values)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn project_residents(
|
||||
fn project_residents<F: FnMut() -> bool>(
|
||||
&self,
|
||||
residents: &[&[Pair]],
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; K]],
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
state: &mut WaveState<'_, '_, 'ctx, F>,
|
||||
) -> Result<()> {
|
||||
let (context, binding, rows) = (self.context, self.binding, self.rows);
|
||||
for pairs in residents {
|
||||
if cancelled() {
|
||||
if (state.cancelled)() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let (context, binding, rows) = (self.context, self.binding, self.rows);
|
||||
let group = ExpertGroup { context, binding, rows, pairs, scope: self.scope, origins: self.origins };
|
||||
project_group(group, cache, self.prepared, down, cancelled)?;
|
||||
project_group(group, &mut *state.cache, self.prepared, &mut *state.down, &mut *state.cancelled)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_member(
|
||||
fn finish_member<F: FnMut() -> bool>(
|
||||
&self,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
down: &mut [[Option<ActualDown<'ctx>>; K]],
|
||||
actual: Option<&QwenChunkTxn<'_, '_>>,
|
||||
state: &mut WaveState<'_, '_, 'ctx, F>,
|
||||
pairs: &[Pair],
|
||||
values: CpuMissRows,
|
||||
) -> Result<()> {
|
||||
let (context, binding, rows, origins) = (self.context, self.binding, self.rows, self.origins);
|
||||
let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, actual)?;
|
||||
let (cache, down) = (&mut *state.cache, &mut *state.down);
|
||||
let keys = completed_keys(context, binding, rows, pairs, &values, cache, origins, down, self.actual)?;
|
||||
upload_completed_rows(self.scope, binding, &keys, pairs, &values, origins, down)?;
|
||||
drop(values.into_values());
|
||||
Ok(())
|
||||
|
||||
@@ -10,6 +10,8 @@ mod adaptive_packets;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[path = "moe_prompt_finish.rs"]
|
||||
mod prompt_finish;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use prompt_finish::NativePromptFinish;
|
||||
#[path = "moe_mmq_chunk.rs"]
|
||||
mod resident;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
|
||||
@@ -78,15 +78,14 @@ impl<'a, 'ctx> BoundRows<'a, 'ctx> {
|
||||
|
||||
fn ungrouped_row(&self, cache: &mut MoeWeightCache<'ctx>, i: usize) -> Result<ExpertReady> {
|
||||
let row = self.rows[i].row();
|
||||
let values = execute_cuda_cached(
|
||||
self.context,
|
||||
self.binding,
|
||||
&row.weights,
|
||||
self.activations[i].buffer()?,
|
||||
&row.route,
|
||||
cache,
|
||||
Some(&self.prepared[i]),
|
||||
)?;
|
||||
let step = StepCuda {
|
||||
context: self.context,
|
||||
binding: self.binding,
|
||||
weights: &row.weights,
|
||||
activation: self.activations[i].buffer()?,
|
||||
route: &row.route,
|
||||
};
|
||||
let values = execute_cuda_cached(&step, cache, Some(&self.prepared[i]))?;
|
||||
ExpertReady::from_completed(self.binding.identity(), row.route.identity(), values)
|
||||
}
|
||||
|
||||
|
||||
@@ -140,7 +140,9 @@ impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> {
|
||||
packet.validate(&self.origins[index], binding, rows[index].row().route.identity())?;
|
||||
refs.push(&packet.packet);
|
||||
}
|
||||
prompt_finish::finish(self.context, binding, layer, rows, actual, self.scope, &refs, cache, finish, cancelled)
|
||||
let window =
|
||||
prompt_finish::PromptRows { context: self.context, binding, layer, rows, txn: actual, scope: self.scope };
|
||||
prompt_finish::finish(window, &refs, cache, finish, cancelled)
|
||||
}
|
||||
|
||||
/// Complete each row's packet and run the shared tail, row by row.
|
||||
|
||||
+10
-5
@@ -27,11 +27,16 @@ impl<'ctx> SharedOwners<'ctx> {
|
||||
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(
|
||||
cached_mlp_down(context, binding, &row.weights, selection, activation, cache, None, scope, origin)?
|
||||
.take(origin, binding, row.route.identity(), selection)?,
|
||||
);
|
||||
self.shared = Some(
|
||||
cached_mlp_down(
|
||||
context,
|
||||
BoundExpert { binding, weights: &row.weights, selection },
|
||||
ExpertActivation { buffer: activation, prepared: None },
|
||||
cache,
|
||||
DownProvenance { scope, origin },
|
||||
)?
|
||||
.take(origin, binding, row.route.identity(), selection)?,
|
||||
);
|
||||
let scalar_weights = cache.shared_scalar(binding, &row.weights)?;
|
||||
self.scalar = Some(scope.shared_scalar(activation, scalar_weights)?);
|
||||
self.scaled = Some(
|
||||
|
||||
+9
-3
@@ -36,8 +36,9 @@ fn replay_selection(
|
||||
) -> 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));
|
||||
let result = scope.project(selection, |out| {
|
||||
launch_cached_projection(context, MatrixDims { kind, rows: N, columns: FF }, matrix, activation.buffer()?, out)
|
||||
});
|
||||
let close_activation = activation.close();
|
||||
match result {
|
||||
Err(primary) => {
|
||||
@@ -150,7 +151,12 @@ pub(super) fn finish_shared_queued(
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
let route = std::array::from_fn(|i| row.route.weights()[i].get());
|
||||
let result = cache.compose_target_shared_tail(binding, context, &row.weights, identity, activation, packet, &route);
|
||||
let result = cache.compose_target_shared_tail(
|
||||
binding,
|
||||
context,
|
||||
SharedTailRow { weights: &row.weights, identity },
|
||||
crate::qwen_forward::shared_expert_workspace::SharedTailInputs { activation, packed: packet, route: &route },
|
||||
);
|
||||
scope.record(&result);
|
||||
let values = result?;
|
||||
row.validate(&binding.identity(), identity.token(), identity.position(), identity.layer())?;
|
||||
|
||||
+22
-14
@@ -16,6 +16,10 @@ 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 Down matrix of the only member of the routed source scope a direct group reads.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
const ONLY_MEMBER_DOWN: SourceMatrix = SourceMatrix { member: 0, role: MoeMatrixRole::Down };
|
||||
|
||||
/// 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> {
|
||||
@@ -153,20 +157,25 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
|
||||
target: GateUpTarget<'_, 'ctx>,
|
||||
) -> Result<()> {
|
||||
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) => {
|
||||
if dual_routed_format(actual) != format {
|
||||
return Err(Error::IdentityMismatch);
|
||||
matrices.cache.with_matrix_routed_source(
|
||||
self.binding,
|
||||
matrices.source,
|
||||
SourceMatrix { member: 0, role },
|
||||
|matrix, _, _| {
|
||||
match matrix {
|
||||
CachedMoeMatrix::Raw(raw) => columns.project_gate_up(raw, grouped.buffer_mut()?, format),
|
||||
CachedMoeMatrix::Dual(actual, owner) => {
|
||||
if dual_routed_format(actual) != format {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
owner.native_gate_up_columns_loan(columns, grouped.buffer_mut()?)
|
||||
}
|
||||
owner.native_gate_up_columns_loan(columns, grouped.buffer_mut()?)
|
||||
}
|
||||
}
|
||||
.map_err(driver_error)?;
|
||||
self.scope.finite_stage(grouped.buffer()?, stage, self.pairs.len())?;
|
||||
Ok(())
|
||||
})
|
||||
.map_err(driver_error)?;
|
||||
self.scope.finite_stage(grouped.buffer()?, stage, self.pairs.len())?;
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
fn source_swiglu(&self, buffers: &mut GroupBuffers<'ctx>) -> Result<()> {
|
||||
@@ -193,8 +202,7 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
|
||||
matrices.cache.with_matrix_routed_source(
|
||||
binding,
|
||||
matrices.source,
|
||||
0,
|
||||
MoeMatrixRole::Down,
|
||||
ONLY_MEMBER_DOWN,
|
||||
|matrix, health, source| {
|
||||
let projection = DownProjection { kind, format, matrix };
|
||||
let launch = SourceDownLaunch { workspace, projection, selections: &selections };
|
||||
|
||||
@@ -5,7 +5,7 @@ use super::project_group_shared_fns::{down_format, gate_up_format, packet_target
|
||||
use super::project_group_source_consumers_fn::{SourceTail, check_source_members};
|
||||
use super::*;
|
||||
use crate::model_binding::qwen4exp_input::MoeRoutedSourceScope;
|
||||
use crate::qwen_forward::moe_weight_cache::{RoutedResidentOwner, RoutedSourceHealth};
|
||||
use crate::qwen_forward::moe_weight_cache::{RoutedResidentOwner, RoutedSourceHealth, TripletLoanRequest};
|
||||
use leleka_cuda_driver::{RoutedResidentOutputs, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights};
|
||||
|
||||
/// Projects one expert group of a packet wave through the resident queue into the row packets.
|
||||
@@ -129,12 +129,12 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
|
||||
self.compose_copy(compose, observed, SourceTail { health, source })
|
||||
})
|
||||
};
|
||||
let binding = self.group.binding;
|
||||
match ephemeral_slot {
|
||||
Some(slot) => {
|
||||
cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume)
|
||||
let loan = TripletLoanRequest { binding: self.group.binding, member: 0, slot };
|
||||
cache.with_ephemeral_triplet_routed_source(loan, source, &cancel_observed, consume)
|
||||
}
|
||||
None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume),
|
||||
None => cache.with_adaptive_triplet_routed_source(self.group.binding, source, 0, consume),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ impl MoeExpertStage {
|
||||
let products = if arm == 0 {
|
||||
Self::execute_chunk(ChunkFfnLayer { binding, layer, rows }, chunk, cache, &mut || false)?
|
||||
} else {
|
||||
Self::execute_chunk_mmq(binding, layer, rows, chunk, cache, &mut || false)?
|
||||
Self::execute_chunk_mmq(ChunkFfnLayer { binding, layer, rows }, chunk, cache, &mut || false)?
|
||||
};
|
||||
check_products(binding, rows, &products)?;
|
||||
validate_sources(binding, layer, rows, chunk, false)?;
|
||||
|
||||
@@ -5,12 +5,12 @@ use crate::model_binding::qwen4exp_input::MoeWeightDescriptor;
|
||||
use crate::qwen_forward::moe_weight_cache::original_dual_layout;
|
||||
use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer};
|
||||
|
||||
#[path = "moe_mmq_adaptive/gather_fns.rs"]
|
||||
mod gather_fns;
|
||||
#[path = "moe_mmq_adaptive/walk_fns.rs"]
|
||||
mod walk_fns;
|
||||
#[path = "moe_mmq_adaptive/expert_gather.rs"]
|
||||
mod expert_gather;
|
||||
#[path = "moe_mmq_adaptive/layer_walk.rs"]
|
||||
mod layer_walk;
|
||||
use super::resident_layer::{LayerResources, Resident, RoutedGroups};
|
||||
use walk_fns::{SlotState, Walk};
|
||||
use layer_walk::{SlotState, StagingPlan, Walk, WalkOwners};
|
||||
|
||||
pub(super) fn execute_adaptive_groups<'ctx>(
|
||||
resident: &Resident<'_, '_, 'ctx>,
|
||||
@@ -81,7 +81,9 @@ fn execute_inner<'ctx>(
|
||||
let classified = walk.classify(cache, packets)?;
|
||||
let (mut wait, mut state) = walk.open_staging(cache, classified.maximum_charge)?;
|
||||
walk.fill_slots(cache, cancelled, &classified, &mut state)?;
|
||||
walk.walk(&mut source, cache, packets, cancelled, &mut wait, &classified, &mut state, counts.len())?;
|
||||
let mut owners = WalkOwners { mmq_layer: &mut source, cache: &mut *cache, packets: &mut *packets, cancelled };
|
||||
let mut plan = StagingPlan { classified: &classified, state: &mut state };
|
||||
walk.walk(&mut owners, &mut wait, &mut plan, counts.len())?;
|
||||
walk.finish(source, cache, &classified, &state)
|
||||
}
|
||||
|
||||
|
||||
+43
-32
@@ -1,33 +1,29 @@
|
||||
//! Gather of one expert's matrices into the admitted bank (STRA-338 size: extract-method only).
|
||||
|
||||
use super::walk_fns::Walk;
|
||||
use super::layer_walk::{ExpertGroup, Walk, WalkOwners};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
impl<'ctx> Walk<'_, '_, 'ctx> {
|
||||
/// Gather one expert's three matrices into the admitted bank, from the adaptive owner or its staged slot.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn gather_expert(
|
||||
pub(super) fn gather_expert<F: FnMut() -> bool>(
|
||||
&self,
|
||||
expert: usize,
|
||||
pairs: &[Pair],
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
activation: &mut OriginalMmqLayer<'_, 'ctx>,
|
||||
packets: &mut SlotPacks<'_, '_, 'ctx>,
|
||||
group: ExpertGroup<'_>,
|
||||
owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>,
|
||||
ephemeral_slot: Option<usize>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<()> {
|
||||
let _origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?;
|
||||
let ExpertGroup { expert, pairs } = group;
|
||||
let _origin = owners.packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?;
|
||||
let mut members = Vec::new();
|
||||
members.try_reserve_exact(pairs.len()).map_err(|_| Error::InputAllocation)?;
|
||||
let first = pairs.first().ok_or(Error::IdentityMismatch)?;
|
||||
let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?;
|
||||
let (keys, formats, charge) = gather_layouts(self.binding, row, first)?;
|
||||
self.fill_members(pairs, &mut members)?;
|
||||
cache.reserve_mmq_transient(self.binding, self.context, charge)?;
|
||||
owners.cache.reserve_mmq_transient(self.binding, self.context, charge)?;
|
||||
self.binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
check_expert_keys(source, &keys, pairs.len())?;
|
||||
self.gather_source(source, formats, pairs, cache, activation, ephemeral_slot, cancelled)
|
||||
self.gather_source(source, GatheredExpert { formats, pairs, ephemeral_slot }, owners)
|
||||
})
|
||||
}
|
||||
|
||||
@@ -40,17 +36,14 @@ impl<'ctx> Walk<'_, '_, 'ctx> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn gather_source(
|
||||
fn gather_source<F: FnMut() -> bool>(
|
||||
&self,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
|
||||
formats: [leleka_cuda_driver::MmqFormat; 3],
|
||||
pairs: &[Pair],
|
||||
cache: &MoeWeightCache<'ctx>,
|
||||
activation: &mut OriginalMmqLayer<'_, 'ctx>,
|
||||
ephemeral_slot: Option<usize>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
gathered: GatheredExpert<'_>,
|
||||
owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>,
|
||||
) -> Result<()> {
|
||||
let GatheredExpert { formats, pairs, ephemeral_slot } = gathered;
|
||||
let WalkOwners { mmq_layer: activation, cache, cancelled, .. } = owners;
|
||||
let binding = self.binding;
|
||||
let cancel_observed = Cell::new(false);
|
||||
let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled);
|
||||
@@ -58,33 +51,42 @@ impl<'ctx> Walk<'_, '_, 'ctx> {
|
||||
|raw: [&DeviceBuffer<'ctx>; 3],
|
||||
health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| {
|
||||
self.after_gather(activation, formats, raw, health, source, &mut observed_cancel, pairs)
|
||||
self.stage_gathered(activation, formats, raw, &mut observed_cancel)?;
|
||||
self.confirm_gather(health, source, &mut observed_cancel, pairs)
|
||||
};
|
||||
match ephemeral_slot {
|
||||
Some(slot) => {
|
||||
cache.with_ephemeral_triplet_routed_source(binding, source, 0, slot, &cancel_observed, consume)
|
||||
}
|
||||
Some(slot) => cache.with_ephemeral_triplet_routed_source(
|
||||
crate::qwen_forward::moe_weight_cache::TripletLoanRequest { binding, member: 0, slot },
|
||||
source,
|
||||
&cancel_observed,
|
||||
consume,
|
||||
),
|
||||
None => cache.with_adaptive_triplet_routed_source(binding, source, 0, consume),
|
||||
}
|
||||
}
|
||||
|
||||
/// The genuine bytes are retained in the admitted bank, not a synthetic MmqWeights view. The actual staging
|
||||
/// owner can be reused only after this confirmed gather + source/current-row health boundary.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn after_gather(
|
||||
/// The genuine bytes are retained in the admitted bank, not a synthetic MmqWeights view.
|
||||
fn stage_gathered(
|
||||
&self,
|
||||
activation: &mut OriginalMmqLayer<'_, 'ctx>,
|
||||
formats: [leleka_cuda_driver::MmqFormat; 3],
|
||||
raw: [&DeviceBuffer<'ctx>; 3],
|
||||
observed_cancel: &mut impl FnMut() -> bool,
|
||||
) -> Result<()> {
|
||||
if observed_cancel() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
activation.stage_expert(formats, raw).map_err(mmq_error)
|
||||
}
|
||||
|
||||
/// The actual staging owner can be reused only after this confirmed gather + source/current-row health boundary.
|
||||
fn confirm_gather(
|
||||
&self,
|
||||
health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
|
||||
observed_cancel: &mut impl FnMut() -> bool,
|
||||
pairs: &[Pair],
|
||||
) -> Result<()> {
|
||||
if observed_cancel() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
activation.stage_expert(formats, raw).map_err(mmq_error)?;
|
||||
source.finish().map_err(binding_error)?;
|
||||
health.validate(self.binding, self.context)?;
|
||||
if observed_cancel() {
|
||||
@@ -94,6 +96,15 @@ impl<'ctx> Walk<'_, '_, 'ctx> {
|
||||
}
|
||||
}
|
||||
|
||||
/// One gathered expert: its routed pairs, the formats of its three matrices and the ephemeral slot it was staged
|
||||
/// in (none for a resident expert).
|
||||
#[derive(Clone, Copy)]
|
||||
struct GatheredExpert<'a> {
|
||||
formats: [leleka_cuda_driver::MmqFormat; 3],
|
||||
pairs: &'a [Pair],
|
||||
ephemeral_slot: Option<usize>,
|
||||
}
|
||||
|
||||
type ExpertLayouts = ([MoeWeightDescriptor; 3], [leleka_cuda_driver::MmqFormat; 3], usize);
|
||||
|
||||
/// The Gate/Up/Down descriptors of one expert, their formats and the summed byte charge.
|
||||
+47
-42
@@ -25,6 +25,28 @@ pub(super) struct Batch {
|
||||
pub(super) consumed: usize,
|
||||
}
|
||||
|
||||
/// The classification of the layer's experts and the staging slots being filled from its misses.
|
||||
pub(super) struct StagingPlan<'a> {
|
||||
pub(super) classified: &'a Classified,
|
||||
pub(super) state: &'a mut SlotState,
|
||||
}
|
||||
|
||||
/// One used expert: its index and the row/slot pairs routed to it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ExpertGroup<'a> {
|
||||
pub(super) expert: usize,
|
||||
pub(super) pairs: &'a [Pair],
|
||||
}
|
||||
|
||||
/// The mutable owners one adaptive prompt layer walk drives: the MMQ layer run, the weight cache, the packet slots
|
||||
/// and the cancellation poll.
|
||||
pub(super) struct WalkOwners<'w, 'layer, 'ctx, 'pa, 'pb, F: FnMut() -> bool> {
|
||||
pub(super) mmq_layer: &'w mut OriginalMmqLayer<'layer, 'ctx>,
|
||||
pub(super) cache: &'w mut MoeWeightCache<'ctx>,
|
||||
pub(super) packets: &'w mut SlotPacks<'pa, 'pb, 'ctx>,
|
||||
pub(super) cancelled: &'w mut F,
|
||||
}
|
||||
|
||||
/// The sealed layer rows and expert groups one adaptive prompt layer walks.
|
||||
pub(super) struct Walk<'a, 't, 'ctx> {
|
||||
pub(super) txn: &'a QwenChunkTxn<'t, 'ctx>,
|
||||
@@ -134,6 +156,7 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
Ok(charge)
|
||||
}
|
||||
|
||||
/// Stage the first group of one missed expert into its ephemeral slot.
|
||||
pub(super) fn stage_miss(
|
||||
&self,
|
||||
cache: &MoeWeightCache<'ctx>,
|
||||
@@ -141,7 +164,17 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
expert: usize,
|
||||
slot: usize,
|
||||
) -> Result<()> {
|
||||
stage(cache, self.context, self.binding, self.rows, &self.groups[expert], slot, cancelled)
|
||||
let (binding, pairs) = (self.binding, &self.groups[expert]);
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let first = pairs.first().ok_or(Error::IdentityMismatch)?;
|
||||
let row = self.rows.get(first.row).ok_or(Error::IdentityMismatch)?;
|
||||
let members = [(&row.row().weights, first.slot)];
|
||||
let owner = cache.ephemeral_routed_owner(binding, self.context)?;
|
||||
binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0)
|
||||
})
|
||||
}
|
||||
|
||||
/// The first staging wave: one miss per slot.
|
||||
@@ -166,32 +199,27 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
|
||||
/// Literal prompt order: residents and staged misses share one ID walk. The real bank retains gathered bytes
|
||||
/// until the <=16-expert numerical run.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn walk(
|
||||
pub(super) fn walk<F: FnMut() -> bool>(
|
||||
&self,
|
||||
source: &mut OriginalMmqLayer<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
packets: &mut SlotPacks<'_, '_, 'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>,
|
||||
wait: &mut impl FnMut(usize) -> Result<()>,
|
||||
classified: &Classified,
|
||||
state: &mut SlotState,
|
||||
plan: &mut StagingPlan<'_>,
|
||||
used_count: usize,
|
||||
) -> Result<()> {
|
||||
let mut batch = Batch { experts: [0; 16], count: 0, consumed: 0 };
|
||||
for (expert, pairs) in self.used() {
|
||||
if cancelled() {
|
||||
if (owners.cancelled)() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let slot = self.wait_slot(wait, classified, state, expert)?;
|
||||
self.gather_expert(expert, pairs, cache, source, packets, slot, cancelled)?;
|
||||
let slot = self.wait_slot(wait, plan.classified, plan.state, expert)?;
|
||||
self.gather_expert(ExpertGroup { expert, pairs: pairs.as_slice() }, owners, slot)?;
|
||||
batch.experts[batch.count] = expert;
|
||||
batch.count += 1;
|
||||
batch.consumed += 1;
|
||||
if batch.count == 16 || batch.consumed == used_count {
|
||||
self.run_batch(source, cache, packets, cancelled, &mut batch)?;
|
||||
self.run_batch(owners, &mut batch)?;
|
||||
}
|
||||
self.refill(cache, cancelled, classified, state, slot)?;
|
||||
self.refill(owners.cache, owners.cancelled, plan, slot)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -213,14 +241,12 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
Ok(Some(slot))
|
||||
}
|
||||
|
||||
pub(super) fn run_batch(
|
||||
pub(super) fn run_batch<F: FnMut() -> bool>(
|
||||
&self,
|
||||
source: &mut OriginalMmqLayer<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
packets: &mut SlotPacks<'_, '_, 'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
owners: &mut WalkOwners<'_, '_, 'ctx, '_, '_, F>,
|
||||
batch: &mut Batch,
|
||||
) -> Result<()> {
|
||||
let WalkOwners { mmq_layer: source, cache, packets, cancelled } = owners;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
@@ -248,13 +274,13 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
&self,
|
||||
cache: &MoeWeightCache<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
classified: &Classified,
|
||||
state: &mut SlotState,
|
||||
plan: &mut StagingPlan<'_>,
|
||||
slot: Option<usize>,
|
||||
) -> Result<()> {
|
||||
let Some(slot) = slot else {
|
||||
return Ok(());
|
||||
};
|
||||
let StagingPlan { classified, state } = plan;
|
||||
state.slots[slot] = None;
|
||||
if state.next < classified.miss_count {
|
||||
let expert = classified.misses[state.next];
|
||||
@@ -265,24 +291,3 @@ impl<'a, 'ctx> Walk<'a, '_, 'ctx> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn stage(
|
||||
cache: &MoeWeightCache<'_>,
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
rows: &[ChunkFfnRow],
|
||||
pairs: &[Pair],
|
||||
slot: usize,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<()> {
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let first = pairs.first().ok_or(Error::IdentityMismatch)?;
|
||||
let row = rows.get(first.row).ok_or(Error::IdentityMismatch)?;
|
||||
let members = [(&row.row().weights, first.slot)];
|
||||
let owner = cache.ephemeral_routed_owner(binding, context)?;
|
||||
binding.with_moe_routed_source(&members, binding_error, |source| {
|
||||
owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.stage(slot, binding, source, 0)
|
||||
})
|
||||
}
|
||||
@@ -15,17 +15,13 @@ use resident_layer::{Resident, execute_resident};
|
||||
|
||||
impl MoeExpertStage {
|
||||
pub(in crate::qwen_forward) fn execute_chunk_mmq<'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>> {
|
||||
Self::execute_chunk_mmq_with_finish(
|
||||
binding,
|
||||
layer,
|
||||
rows,
|
||||
ffn,
|
||||
chunk,
|
||||
cache,
|
||||
cancelled,
|
||||
@@ -35,29 +31,16 @@ impl MoeExpertStage {
|
||||
}
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) fn execute_chunk_mmq_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: super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
Self::execute_chunk_mmq_with_finish(
|
||||
binding,
|
||||
layer,
|
||||
rows,
|
||||
chunk,
|
||||
cache,
|
||||
cancelled,
|
||||
Some(super::prompt_finish::NativePromptFinish { products, dense }),
|
||||
)
|
||||
Self::execute_chunk_mmq_with_finish(ffn, chunk, cache, cancelled, Some(finish))
|
||||
}
|
||||
fn execute_chunk_mmq_with_finish<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &[ChunkFfnRow],
|
||||
ffn: ChunkFfnLayer<'_>,
|
||||
chunk: &mut QwenChunkTxn<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
@@ -65,6 +48,7 @@ impl MoeExpertStage {
|
||||
super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
|
||||
>,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
let ChunkFfnLayer { binding, layer, rows } = ffn;
|
||||
if rows.len() != chunk.micro_len()? || !(1..=64).contains(&rows.len()) {
|
||||
return Err(Error::InvalidDimension);
|
||||
}
|
||||
@@ -81,6 +65,12 @@ impl MoeExpertStage {
|
||||
}
|
||||
}
|
||||
|
||||
/// The sealed chunk transaction a resident batch reads and the device context it runs on.
|
||||
pub(super) struct ActualChunk<'a, 'ctx> {
|
||||
pub(super) txn: &'a QwenChunkTxn<'a, 'ctx>,
|
||||
pub(super) context: &'ctx Context<'ctx>,
|
||||
}
|
||||
|
||||
/// One MMQ layer batch: the rows plus the optional native prompt finish.
|
||||
pub(super) struct ChunkCall<'a, 'ctx, 'l, 'd> {
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
@@ -130,7 +120,11 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> {
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
cache.admit_mmq_chunk(binding, chunk.context()?, rows.len(), &triplets, original_prompt)
|
||||
cache.admit_mmq_chunk(
|
||||
binding,
|
||||
chunk.context()?,
|
||||
MmqChunkRequest { row_count: rows.len(), triplets: &triplets, original_prompt },
|
||||
)
|
||||
}
|
||||
|
||||
/// Actual21/23, T1 and GU22 under the IQ3-only policy take native. This is an admission decision BEFORE MMQ
|
||||
@@ -169,7 +163,7 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
cache.with_mmq_workspace(binding, context, admission, |cache, workspace| {
|
||||
self.resident(actual, context, cache, workspace, cancelled)
|
||||
self.resident(ActualChunk { txn: actual, context }, cache, workspace, cancelled)
|
||||
})
|
||||
});
|
||||
#[cfg(test)]
|
||||
@@ -183,13 +177,18 @@ impl<'ctx> ChunkCall<'_, 'ctx, '_, '_> {
|
||||
|
||||
fn resident(
|
||||
self,
|
||||
actual: &QwenChunkTxn<'_, 'ctx>,
|
||||
context: &'ctx Context<'ctx>,
|
||||
actual: ActualChunk<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
workspace: &mut MmqWorkspace<'ctx>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
let resident = Resident { txn: actual, context, binding: self.binding, layer: self.layer, rows: self.rows };
|
||||
let resident = Resident {
|
||||
txn: actual.txn,
|
||||
context: actual.context,
|
||||
binding: self.binding,
|
||||
layer: self.layer,
|
||||
rows: self.rows,
|
||||
};
|
||||
execute_resident(
|
||||
resident,
|
||||
cache,
|
||||
|
||||
@@ -327,8 +327,8 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
|
||||
let (first, row) = self.group_head(pairs)?;
|
||||
let indices = self.group_indices(row, first, pairs)?;
|
||||
let group = source.gather_gate_up(&indices).map_err(mmq_error)?;
|
||||
let selection = MoeExpertSelection::Routed { slot: first.slot };
|
||||
cache.with_mmq_triplet(self.binding, &row.row().weights, selection, original_prompt, |gate, up, down| {
|
||||
let expert = BoundExpert::routed(self.binding, &row.row().weights, first.slot);
|
||||
cache.with_mmq_triplet(expert, original_prompt, |gate, up, down| {
|
||||
let hidden = group.gate_up(gate, up).map_err(mmq_error)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
|
||||
@@ -242,18 +242,15 @@ impl<'source, 'session, 'ctx> SlotPacks<'source, 'session, 'ctx> {
|
||||
packet.complete(self.scope)?;
|
||||
packets.push(packet);
|
||||
}
|
||||
super::prompt_finish::finish(
|
||||
self.context,
|
||||
self.binding,
|
||||
self.layer,
|
||||
self.rows,
|
||||
self.txn,
|
||||
self.scope,
|
||||
&packets,
|
||||
cache,
|
||||
finish,
|
||||
cancelled,
|
||||
)
|
||||
let window = super::prompt_finish::PromptRows {
|
||||
context: self.context,
|
||||
binding: self.binding,
|
||||
layer: self.layer,
|
||||
rows: self.rows,
|
||||
txn: self.txn,
|
||||
scope: self.scope,
|
||||
};
|
||||
super::prompt_finish::finish(window, &packets, cache, finish, cancelled)
|
||||
}
|
||||
fn finish_values(
|
||||
&self,
|
||||
|
||||
@@ -6,19 +6,27 @@ use super::super::super::moe_prefill_batch::{
|
||||
use super::super::moe_down::ResidentPackedDown;
|
||||
use super::*;
|
||||
|
||||
pub(super) struct NativePromptFinish<'loan, 'ctx, 'dense> {
|
||||
pub(super) products: &'loan mut MoeMicroProducts<'ctx>,
|
||||
pub(super) dense: &'loan DenseWeightCache<'dense>,
|
||||
pub(in crate::qwen_forward) struct NativePromptFinish<'loan, 'ctx, 'dense> {
|
||||
pub(in crate::qwen_forward) products: &'loan mut MoeMicroProducts<'ctx>,
|
||||
pub(in crate::qwen_forward) dense: &'loan DenseWeightCache<'dense>,
|
||||
}
|
||||
|
||||
/// The sealed window rows one native prompt finish is checked against.
|
||||
struct PromptRows<'a, 'session, 'ctx> {
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &'a ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &'a [ChunkFfnRow],
|
||||
txn: &'a QwenChunkTxn<'session, 'ctx>,
|
||||
scope: &'a DownScope<'ctx>,
|
||||
pub(super) struct PromptRows<'a, 'session, 'ctx> {
|
||||
pub(super) context: &'ctx Context<'ctx>,
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) layer: LayerId,
|
||||
pub(super) rows: &'a [ChunkFfnRow],
|
||||
pub(super) txn: &'a QwenChunkTxn<'session, 'ctx>,
|
||||
pub(super) scope: &'a DownScope<'ctx>,
|
||||
}
|
||||
|
||||
/// The complete Down packets of a window, the token-layer identities they were validated against and the transport
|
||||
/// buffer they are gathered into for the combine.
|
||||
struct PacketBank<'a, 'ctx> {
|
||||
packets: &'a [&'a ResidentPackedDown<'ctx>],
|
||||
expected: &'a [TokenLayer],
|
||||
dm: &'a mut TransportBuffer<'ctx>,
|
||||
}
|
||||
impl<'ctx> PromptRows<'_, '_, 'ctx> {
|
||||
fn validate_shape(&self, packets: &[&ResidentPackedDown<'ctx>]) -> Result<()> {
|
||||
@@ -150,12 +158,12 @@ impl<'ctx> PromptRows<'_, '_, 'ctx> {
|
||||
}
|
||||
fn run(
|
||||
&self,
|
||||
packets: &[&ResidentPackedDown<'ctx>],
|
||||
bank: PacketBank<'_, 'ctx>,
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
(expected, dm): (&[TokenLayer], &mut TransportBuffer<'ctx>),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
let PacketBank { packets, expected, dm } = bank;
|
||||
self.copy_packets_into(packets, dm, cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
@@ -182,25 +190,20 @@ impl<'ctx> PromptRows<'_, '_, 'ctx> {
|
||||
}
|
||||
let dm_bytes = self.reserve_dm(cache)?;
|
||||
let mut dm = self.scope.allocate(dm_bytes)?;
|
||||
let operation = self.run(packets, cache, finish, (&expected, &mut dm), cancelled);
|
||||
let operation = self.run(PacketBank { packets, expected: &expected, dm: &mut dm }, cache, finish, cancelled);
|
||||
self.scope.record(&operation);
|
||||
let cleanup = dm.close();
|
||||
operation.and_then(|values| cleanup.map(|()| values))
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// Finish the native prompt window of `rows` over its complete Down packets.
|
||||
pub(super) fn finish<'ctx>(
|
||||
context: &'ctx Context<'ctx>,
|
||||
binding: &ModelBinding,
|
||||
layer: LayerId,
|
||||
rows: &[ChunkFfnRow],
|
||||
txn: &QwenChunkTxn<'_, 'ctx>,
|
||||
scope: &DownScope<'ctx>,
|
||||
rows: PromptRows<'_, '_, 'ctx>,
|
||||
packets: &[&ResidentPackedDown<'ctx>],
|
||||
cache: &mut MoeWeightCache<'ctx>,
|
||||
finish: &mut NativePromptFinish<'_, 'ctx, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<Vec<ExpertReady>> {
|
||||
PromptRows { context, binding, layer, rows, txn, scope }.finish(packets, cache, finish, cancelled)
|
||||
rows.finish(packets, cache, finish, cancelled)
|
||||
}
|
||||
|
||||
@@ -99,6 +99,8 @@ use impl_routerlogits::admit_projection_budget;
|
||||
pub(super) use impl_routerlogits::validate_activation;
|
||||
mod project_logits_fn;
|
||||
#[allow(unused_imports)]
|
||||
use project_logits_fn::RouterInput;
|
||||
#[allow(unused_imports)]
|
||||
use project_logits_fn::binding_error;
|
||||
#[allow(unused_imports)]
|
||||
use project_logits_fn::collect_logits;
|
||||
|
||||
@@ -138,7 +138,8 @@ impl MoeRouteStage {
|
||||
{
|
||||
return Self::route_leased(binding, layer, identity, txn, lease);
|
||||
}
|
||||
let values = project_logits(context, binding, &weights, residual.mixed(), layer.get(), cache)?;
|
||||
let input = RouterInput { layer: layer.get(), activation: residual.mixed() };
|
||||
let values = project_logits(context, binding, &weights, input, cache)?;
|
||||
let logits = logits_from_values(binding, layer, identity, values)?;
|
||||
Self::route(binding, layer, &logits, identity.token(), txn)
|
||||
}
|
||||
|
||||
@@ -44,14 +44,21 @@ fn finish_logits(
|
||||
Ok(values)
|
||||
}
|
||||
|
||||
/// The mixed residual of one layer that the router projects, with the layer whose router matrix applies to it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct RouterInput<'a> {
|
||||
pub(super) layer: u32,
|
||||
pub(super) activation: &'a [f32],
|
||||
}
|
||||
|
||||
pub(super) fn project_logits(
|
||||
context: &Context<'_>,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeRouteWeights,
|
||||
activation: &[f32],
|
||||
layer: u32,
|
||||
input: RouterInput<'_>,
|
||||
cache: Option<&DenseWeightCache<'_>>,
|
||||
) -> Result<[f32; EXPERTS]> {
|
||||
let RouterInput { layer, activation } = input;
|
||||
let input_bytes = activation_bytes(activation);
|
||||
let mut input = context.allocate(input_bytes.len()).map_err(map_driver_error)?;
|
||||
input.copy_from(&input_bytes).map_err(map_driver_error)?;
|
||||
|
||||
@@ -10,8 +10,16 @@ use leleka_cuda_driver::{
|
||||
RoutedGroupWorkspace, RoutedStageFiniteGuard,
|
||||
};
|
||||
use std::cell::{Cell, RefCell};
|
||||
#[path = "moe_weight_cache/cache_requests.rs"]
|
||||
mod cache_requests;
|
||||
#[path = "mtp_kv_resident.rs"]
|
||||
mod mtp_kv_resident;
|
||||
pub(in crate::qwen_forward) use super::bound_expert::BoundExpert;
|
||||
pub(in crate::qwen_forward) use cache_requests::{
|
||||
FixedMtpWeights, MmqChunkRequest, MtpExpertPicks, MtpStepSite, PendingMtpKv, SharedTailRow,
|
||||
};
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use cache_requests::{SharedWeightsRequest, SourceMatrix};
|
||||
use mtp_kv_resident::{MtpKvClaim, MtpKvResident};
|
||||
#[path = "cache_lru_index.rs"]
|
||||
mod cache_lru_index;
|
||||
@@ -44,7 +52,7 @@ pub(crate) use cache_strata_adaptive::AdaptiveWitness;
|
||||
#[path = "cache_original_verify.rs"]
|
||||
mod cache_original_verify;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use cache_ephemeral_routed::observe_cancel;
|
||||
pub(in crate::qwen_forward) use cache_ephemeral_routed::{TripletLoanRequest, observe_cancel};
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use cache_original_verify::SharedKeys;
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
//! The request objects the encoded-weight cache serves: which MTP step, which shared tail, which source matrix.
|
||||
use crate::model_binding::qwen4exp_input::{ModelBinding, MoeExpertWeights, MoeWeightDescriptor};
|
||||
use crate::qwen_forward::contract::TokenLayer;
|
||||
use crate::qwen_forward::mtp::{DenseKv, MtpFrame};
|
||||
use crate::qwen_forward::session::QwenSession;
|
||||
use leleka_cuda_driver::{Context, DeviceBuffer};
|
||||
|
||||
/// Where and under which draft frame one fixed MTP step runs: the model binding, the device context, the session
|
||||
/// and the frame, all of which the cache admits together before it touches a weight.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct MtpStepSite<'a, 'c, 's> {
|
||||
pub(in crate::qwen_forward) binding: &'a ModelBinding,
|
||||
pub(in crate::qwen_forward) context: &'a Context<'c>,
|
||||
pub(in crate::qwen_forward) session: &'a QwenSession<'s>,
|
||||
pub(in crate::qwen_forward) frame: &'a MtpFrame,
|
||||
}
|
||||
|
||||
/// The cache-owned expert bank and the four dense shared-expert matrices a fixed MTP step is checked against.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct FixedMtpWeights<'a, 'k> {
|
||||
pub(in crate::qwen_forward) bank: &'a DeviceBuffer<'k>,
|
||||
pub(in crate::qwen_forward) shared: [&'a DeviceBuffer<'k>; 4],
|
||||
}
|
||||
|
||||
/// The mixed hidden row of an MTP step and the ten routed expert ids and router weights it was routed to.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct MtpExpertPicks<'a> {
|
||||
pub(in crate::qwen_forward) mixed: &'a [f32],
|
||||
pub(in crate::qwen_forward) ids: [u32; 10],
|
||||
pub(in crate::qwen_forward) weights: [f32; 10],
|
||||
}
|
||||
|
||||
/// The draft KV step waiting to be prepared and attended: its dense KV, frame, binding and device context.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct PendingMtpKv<'a, 'c> {
|
||||
pub(in crate::qwen_forward) binding: &'a ModelBinding,
|
||||
pub(in crate::qwen_forward) context: &'a Context<'c>,
|
||||
pub(in crate::qwen_forward) next: &'a DenseKv,
|
||||
pub(in crate::qwen_forward) frame: &'a MtpFrame,
|
||||
}
|
||||
|
||||
/// The row whose target shared-expert tail is composed: its expert weights and its token/layer identity.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct SharedTailRow<'a> {
|
||||
pub(in crate::qwen_forward) weights: &'a MoeExpertWeights,
|
||||
pub(in crate::qwen_forward) identity: TokenLayer,
|
||||
}
|
||||
|
||||
/// What one MMQ chunk is admitted for: its row count, the Gate/Up/Down descriptors of each row and whether it is
|
||||
/// the original prompt operator.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct MmqChunkRequest<'a> {
|
||||
pub(in crate::qwen_forward) row_count: usize,
|
||||
pub(in crate::qwen_forward) triplets: &'a [[MoeWeightDescriptor; 3]],
|
||||
pub(in crate::qwen_forward) original_prompt: bool,
|
||||
}
|
||||
|
||||
/// Which matrix of the routed source scope is read: the group member and the matrix role.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct SourceMatrix {
|
||||
pub(in crate::qwen_forward) member: usize,
|
||||
pub(in crate::qwen_forward) role: crate::model_binding::qwen4exp_input::MoeMatrixRole,
|
||||
}
|
||||
|
||||
/// Which layer's shared weights are lent and how many transient bytes must still fit while they are lent.
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in crate::qwen_forward) struct SharedWeightsRequest {
|
||||
pub(in crate::qwen_forward) layer: crate::qwen_forward::contract::LayerId,
|
||||
pub(in crate::qwen_forward) transient_bytes: usize,
|
||||
}
|
||||
+2
-3
@@ -169,15 +169,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
layer: super::super::super::contract::LayerId,
|
||||
transient: usize,
|
||||
request: SharedWeightsRequest,
|
||||
execute: impl FnOnce(
|
||||
&'ctx Context<'ctx>,
|
||||
super::super::super::moe_prefill_batch::SharedWeights<'_, 'ctx>,
|
||||
&mut super::super::super::moe_prefill_batch::MoePrefillResources<'ctx>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let keys = self.admit_native_shared(binding, context, layer, transient)?;
|
||||
let keys = self.admit_native_shared(binding, context, request.layer, request.transient_bytes)?;
|
||||
let buffers = raw_shared_buffers(&self.main, &keys)?;
|
||||
let mut owner = self.native_prefill_resources(binding, context)?;
|
||||
let result = execute(
|
||||
|
||||
+27
-54
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MoeWeightCache (4).
|
||||
|
||||
use super::super::super::shared_expert_workspace::{SharedTailInputs, SharedTailKeys, WorkspaceOwner};
|
||||
use super::impl_moeweightcache_3::shared_keys_fn::{raw_shared_buffers, shared_descriptors};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -9,17 +10,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// Source-descriptor admission precedes all fills. Requested entries cannot
|
||||
/// evict one another; every actual weight remains immutably borrowed until
|
||||
/// the closed driver's completion/readback has consumed the result.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super::super) fn compose_target_shared_tail(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
weights: &MoeExpertWeights,
|
||||
identity: super::super::super::contract::TokenLayer,
|
||||
activation: &DeviceBuffer<'_>,
|
||||
packed: &DeviceBuffer<'_>,
|
||||
route: &[f32; 10],
|
||||
row: SharedTailRow<'_>,
|
||||
inputs: SharedTailInputs<'_, '_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let SharedTailRow { weights, identity } = row;
|
||||
self.validate(binding, context)?;
|
||||
if !weights.matches(&binding.identity(), identity.layer().get()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
@@ -27,7 +25,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
let keys = shared_descriptors(binding, weights)?;
|
||||
self.fill_shared_weights(binding, weights, &keys)?;
|
||||
self.validate(binding, context)?;
|
||||
let result = self.compose_shared(binding, context, identity, &keys, (activation, packed, route));
|
||||
let result = self.compose_shared(binding, context, SharedTailKeys { identity, keys: &keys }, inputs);
|
||||
if context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
@@ -41,54 +39,30 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
identity: super::super::super::contract::TokenLayer,
|
||||
keys: &[MoeWeightDescriptor; 4],
|
||||
(activation, packed, route): (&DeviceBuffer<'_>, &DeviceBuffer<'_>, &[f32; 10]),
|
||||
keyed: SharedTailKeys<'_>,
|
||||
inputs: SharedTailInputs<'_, '_>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let buffers = raw_shared_buffers(&self.main, keys)?;
|
||||
self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose(
|
||||
binding,
|
||||
&self.mmq_owner,
|
||||
context,
|
||||
identity,
|
||||
keys,
|
||||
buffers,
|
||||
activation,
|
||||
packed,
|
||||
route,
|
||||
)
|
||||
let buffers = raw_shared_buffers(&self.main, keyed.keys)?;
|
||||
let authenticated = WorkspaceOwner { binding, owner: &self.mmq_owner, context };
|
||||
self.target_shared.as_mut().ok_or(Error::IdentityMismatch)?.compose(authenticated, keyed, buffers, inputs)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super::super) fn compose_fixed_mtp_experts(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
frame: &super::super::super::mtp::MtpFrame,
|
||||
session: &super::super::super::session::QwenSession<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared: [&DeviceBuffer<'_>; 4],
|
||||
mixed: &[f32],
|
||||
ids: [u32; 10],
|
||||
weights: [f32; 10],
|
||||
site: MtpStepSite<'_, '_, '_>,
|
||||
weights: FixedMtpWeights<'_, '_>,
|
||||
picks: MtpExpertPicks<'_>,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
self.admit_fixed_mtp(binding, context, frame, session, bank, shared)?;
|
||||
let result =
|
||||
self.compose_mtp_slot(binding, context, (frame, session), (bank, shared), (mixed, ids, weights), &failed);
|
||||
if failed.get() || context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.admit_fixed_mtp(site, weights)?;
|
||||
let result = self.compose_mtp_slot(site, weights, picks, &failed);
|
||||
if failed.get() || site.context.is_poisoned() || matches!(result, Err(Error::CudaExecution)) {
|
||||
self.failed.set(true);
|
||||
}
|
||||
result
|
||||
}
|
||||
fn admit_fixed_mtp(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
frame: &super::super::super::mtp::MtpFrame,
|
||||
session: &super::super::super::session::QwenSession<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared: [&DeviceBuffer<'_>; 4],
|
||||
) -> Result<()> {
|
||||
fn admit_fixed_mtp(&self, site: MtpStepSite<'_, '_, '_>, weights: FixedMtpWeights<'_, '_>) -> Result<()> {
|
||||
let MtpStepSite { binding, context, session, frame } = site;
|
||||
let FixedMtpWeights { bank, shared } = weights;
|
||||
self.validate(binding, context)?;
|
||||
frame.validate(binding, session)?;
|
||||
if !self.requires_iq3_mmq_admission() {
|
||||
@@ -111,13 +85,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
fn compose_mtp_slot(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
(frame, session): (&super::super::super::mtp::MtpFrame, &super::super::super::session::QwenSession<'_>),
|
||||
(bank, shared): (&DeviceBuffer<'_>, [&DeviceBuffer<'_>; 4]),
|
||||
(mixed, ids, weights): (&[f32], [u32; 10], [f32; 10]),
|
||||
site: MtpStepSite<'_, '_, '_>,
|
||||
weights: FixedMtpWeights<'_, '_>,
|
||||
picks: MtpExpertPicks<'_>,
|
||||
failed: &Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let MtpStepSite { binding, context, session, frame } = site;
|
||||
let FixedMtpWeights { bank, shared } = weights;
|
||||
let MtpExpertPicks { mixed, ids, weights } = picks;
|
||||
let mut slot = self.mtp_experts.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
let anchor = FrameAnchor { binding, frame, session };
|
||||
let claim = WorkspaceClaim { owner: &self.mmq_owner, context };
|
||||
@@ -149,13 +124,11 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
pub(in super::super::super) fn attend_mtp_kv(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
next: &super::super::super::mtp::DenseKv,
|
||||
frame: &super::super::super::mtp::MtpFrame,
|
||||
step: PendingMtpKv<'_, '_>,
|
||||
query: &DeviceBuffer<'_>,
|
||||
output: &mut DeviceBuffer<'_>,
|
||||
) -> Result<()> {
|
||||
let PendingMtpKv { binding, context, next, frame } = step;
|
||||
self.prepare_mtp_kv(binding, context, next, frame)?;
|
||||
let mut slot = self.mtp_kv.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
let result = slot.as_mut().ok_or(Error::IdentityMismatch)?.attend(
|
||||
|
||||
+7
-11
@@ -71,10 +71,9 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
context: &Context<'_>,
|
||||
rows: usize,
|
||||
triplets: &[[MoeWeightDescriptor; 3]],
|
||||
original_prompt: bool,
|
||||
request: MmqChunkRequest<'_>,
|
||||
) -> Result<Option<MmqChunkAdmission>> {
|
||||
let MmqChunkRequest { row_count: rows, triplets, original_prompt } = request;
|
||||
self.validate(binding, context)?;
|
||||
self.check_mmq_chunk_shape(rows, original_prompt)?;
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
@@ -122,9 +121,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
/// missing/evicted descriptor refuses, never manufactures a weight view.
|
||||
pub(in super::super::super) fn with_mmq_triplet<T>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
original_prompt: bool,
|
||||
execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
@@ -132,17 +129,16 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if original_prompt || self.requires_iq3_mmq_admission() {
|
||||
return self.with_integer_mmq_triplet(binding, weights, selection, original_prompt, execute);
|
||||
return self.with_integer_mmq_triplet(expert, original_prompt, execute);
|
||||
}
|
||||
self.with_native_mmq_triplet(binding, weights, selection, execute)
|
||||
self.with_native_mmq_triplet(expert, execute)
|
||||
}
|
||||
fn with_native_mmq_triplet<T>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let BoundExpert { binding, weights, selection } = expert;
|
||||
self.validate(binding, self.context)?;
|
||||
let roles = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
let mut keys = Vec::new();
|
||||
|
||||
+19
-20
@@ -5,6 +5,14 @@ use super::*;
|
||||
|
||||
const TRIPLET_ROLES: [MoeMatrixRole; 3] = [MoeMatrixRole::Gate, MoeMatrixRole::Up, MoeMatrixRole::Down];
|
||||
|
||||
/// The cache totals a published triplet leaves behind: bytes held in the main set, the next LRU age and the bytes read
|
||||
/// from the source to produce it.
|
||||
struct TripletAccounting {
|
||||
main_bytes: usize,
|
||||
next_age: u64,
|
||||
read_bytes: usize,
|
||||
}
|
||||
|
||||
/// The Gate/Up/Down identity of one requested triplet and how much of it is missing from the cache.
|
||||
struct TripletPlan {
|
||||
keys: [MoeWeightDescriptor; 3],
|
||||
@@ -19,16 +27,15 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
// Every requested owner stays resident while missing roles are admitted.
|
||||
pub(in super::super) fn with_integer_mmq_triplet<T>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
original_prompt: bool,
|
||||
execute: impl FnOnce(&MmqWeights<'ctx>, &MmqWeights<'ctx>, &MmqWeights<'ctx>) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let BoundExpert { binding, weights, selection } = expert;
|
||||
self.validate(binding, self.context)?;
|
||||
let plan = self.triplet_plan(binding, weights, selection, original_prompt)?;
|
||||
let next_age = self.triplet_admit(&plan)?;
|
||||
self.triplet_fill(binding, weights, selection, original_prompt, &plan, next_age)?;
|
||||
self.triplet_fill(expert, original_prompt, &plan, next_age)?;
|
||||
self.triplet_note_hits(&plan);
|
||||
self.validate(binding, self.context)?;
|
||||
let [gate, up, down] = self.triplet_owners(&plan.keys)?;
|
||||
@@ -37,15 +44,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
|
||||
fn triplet_fill(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
original_prompt: bool,
|
||||
plan: &TripletPlan,
|
||||
next_age: u64,
|
||||
) -> Result<()> {
|
||||
let BoundExpert { binding, weights, selection } = expert;
|
||||
match plan.missing {
|
||||
3 => self.triplet_full_miss(binding, weights, selection, original_prompt, plan, next_age),
|
||||
3 => self.triplet_full_miss(expert, original_prompt, plan, next_age),
|
||||
0 => self.triplet_hit(plan, next_age),
|
||||
_ => self.triplet_partial(binding, weights, selection, plan),
|
||||
}
|
||||
@@ -135,13 +141,12 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
|
||||
fn triplet_full_miss(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
weights: &MoeExpertWeights,
|
||||
selection: MoeExpertSelection,
|
||||
expert: BoundExpert<'_>,
|
||||
original_prompt: bool,
|
||||
plan: &TripletPlan,
|
||||
next_age: u64,
|
||||
) -> Result<()> {
|
||||
let BoundExpert { binding, weights, selection } = expert;
|
||||
let update = self.prepare_lru_updates(&self.triplet_ages(plan, next_age))?;
|
||||
// Read actual bound spans before any upload. The driver owns its
|
||||
// padded staging until all attempted copies have completed.
|
||||
@@ -156,7 +161,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
self.close_triplet_owners(owners);
|
||||
return Err(primary);
|
||||
}
|
||||
self.publish_triplet(plan, owners, main_bytes, next_age, read_bytes);
|
||||
self.publish_triplet(plan, owners, TripletAccounting { main_bytes, next_age, read_bytes });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -191,14 +196,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
|
||||
/// No fallible allocation/validation follows the first insertion.
|
||||
/// Publish the complete triplet only after driver completion.
|
||||
fn publish_triplet(
|
||||
&mut self,
|
||||
plan: &TripletPlan,
|
||||
owners: [MmqWeights<'ctx>; 3],
|
||||
main_bytes: usize,
|
||||
next_age: u64,
|
||||
read_bytes: usize,
|
||||
) {
|
||||
fn publish_triplet(&mut self, plan: &TripletPlan, owners: [MmqWeights<'ctx>; 3], accounting: TripletAccounting) {
|
||||
let TripletAccounting { main_bytes, next_age, read_bytes } = accounting;
|
||||
for (index, owner) in owners.into_iter().enumerate() {
|
||||
let weight = EncodedWeight::Dual(plan.formats[index], owner);
|
||||
let age = self.age + index as u64 + 1;
|
||||
|
||||
+2
-2
@@ -32,14 +32,14 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>,
|
||||
member: usize,
|
||||
role: MoeMatrixRole,
|
||||
matrix: SourceMatrix,
|
||||
consume: impl FnOnce(
|
||||
CachedMoeMatrix<'_, 'ctx>,
|
||||
&RoutedSourceHealth<'_, 'ctx>,
|
||||
&mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let SourceMatrix { member, role } = matrix;
|
||||
self.validate(binding, self.context)?;
|
||||
if !self.uses_direct_native_down_packets() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
|
||||
+3
-4
@@ -94,10 +94,8 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
}
|
||||
pub(in super::super) fn with_ephemeral_triplet_routed_source<'source, 'group, T>(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
request: cache_ephemeral_routed::TripletLoanRequest<'_>,
|
||||
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>,
|
||||
member: usize,
|
||||
slot: usize,
|
||||
cancel_observed: &std::cell::Cell<bool>,
|
||||
consume: impl FnOnce(
|
||||
[&DeviceBuffer<'ctx>; 3],
|
||||
@@ -105,6 +103,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
&mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'source, 'group>,
|
||||
) -> Result<T>,
|
||||
) -> Result<T> {
|
||||
let cache_ephemeral_routed::TripletLoanRequest { binding, member, .. } = request;
|
||||
self.validate(binding, self.context)?;
|
||||
source.validate_binding(binding).map_err(binding_error)?;
|
||||
let keys = [
|
||||
@@ -115,7 +114,7 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
let health = RoutedSourceHealth { binding: &self.binding, context: self.context, failed: &self.failed };
|
||||
let owner = self.ephemeral_routed.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
let mut owner = owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
|
||||
owner.with_triplet(slot, binding, source, member, cancel_observed, |raw, actual_keys, source| {
|
||||
owner.with_triplet(request, source, cancel_observed, |raw, actual_keys, source| {
|
||||
if actual_keys != keys {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
|
||||
@@ -15,12 +15,12 @@ mod kv_only;
|
||||
#[path = "mtp_state.rs"]
|
||||
mod state;
|
||||
pub(super) use kv_only::produce_chunk_kv_only;
|
||||
pub(in crate::qwen_forward) use state::MtpCheckpoint;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use state::MtpChunkNumericSnapshot;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(crate) use state::PrefixDraftSnapshot;
|
||||
pub(super) use state::{DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill};
|
||||
pub(super) use state::{ChunkModel, DenseKv, MtpChunkStage, MtpKvPrefill, MtpSession, ReadyMtpKvPrefill};
|
||||
pub(in crate::qwen_forward) use state::{MtpCheckpoint, RetainedFirstSeed};
|
||||
|
||||
/// Created only from a successful current target product or a checked draft
|
||||
/// successor. Reset/rewind invalidates every prior branch capability.
|
||||
@@ -39,9 +39,9 @@ pub(super) struct MtpInput {
|
||||
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,
|
||||
pub(crate) struct KnownNext<'a, P> {
|
||||
pub(crate) source: &'a P,
|
||||
pub(crate) next_token: TokenId,
|
||||
}
|
||||
/// The target session and the draft session that one MTP draft step advances together.
|
||||
pub(super) struct StepSessions<'a, 'driver, 'draft> {
|
||||
|
||||
@@ -100,10 +100,7 @@ impl<'ctx> AttendBuffers<'ctx> {
|
||||
self.q = Some(upload_transport_f32(context, query, failed)?);
|
||||
self.y = Some(allocate(context, Q)?);
|
||||
cache.attend_mtp_kv(
|
||||
binding,
|
||||
context,
|
||||
pending,
|
||||
frame,
|
||||
crate::qwen_forward::moe_weight_cache::PendingMtpKv { binding, context, next: pending, frame },
|
||||
self.q.as_ref().ok_or(Error::CudaExecution)?,
|
||||
self.y.as_mut().ok_or(Error::CudaExecution)?,
|
||||
)?;
|
||||
|
||||
@@ -185,6 +185,7 @@ mod impl_mtpwindowspec;
|
||||
use impl_mtpwindowspec::kv_prefill_host_charge;
|
||||
mod first_seed_reuse_enabled_fn;
|
||||
mod impl_mtpdecoder;
|
||||
mod window_request;
|
||||
#[allow(unused_imports)]
|
||||
use first_seed_reuse_enabled_fn::first_seed_reuse_enabled;
|
||||
#[allow(unused_imports)]
|
||||
@@ -193,3 +194,4 @@ use first_seed_reuse_enabled_fn::needed_draft_predictions;
|
||||
use first_seed_reuse_enabled_fn::window_limit;
|
||||
#[allow(unused_imports)]
|
||||
use first_seed_reuse_enabled_fn::window_stage_error;
|
||||
pub(crate) use window_request::{DraftHeadOwners, MtpWindowRequest, WindowOwners};
|
||||
|
||||
@@ -4,6 +4,6 @@
|
||||
use super::*;
|
||||
|
||||
mod batched_support;
|
||||
mod impl_mtpdecoder_2;
|
||||
mod impl_mtpdecoder_2_2;
|
||||
mod impl_mtpdecoder_3;
|
||||
mod batched_window;
|
||||
mod draft_warm_and_window;
|
||||
mod scalar_window;
|
||||
|
||||
+10
-5
@@ -3,10 +3,16 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
use crate::qwen_forward::mtp::MtpCheckpoint;
|
||||
use crate::qwen_forward::mtp::{MtpCheckpoint, RetainedFirstSeed};
|
||||
|
||||
pub(super) type WindowResult<T> = std::result::Result<T, MtpWindowError>;
|
||||
pub(super) type FirstSeed = Option<(MtpCheckpoint, mtp::MtpFrame)>;
|
||||
pub(super) type FirstSeed = Option<RetainedFirstSeed>;
|
||||
|
||||
/// The authoritative first prediction of a window and the number of draft steps its depth and the context allow.
|
||||
pub(super) struct WindowHead {
|
||||
pub(super) first: TokenId,
|
||||
pub(super) limit: usize,
|
||||
}
|
||||
|
||||
/// The sizing of one batched window, fixed before any draft or canonical mutation.
|
||||
pub(super) struct BatchedPlan {
|
||||
@@ -38,13 +44,12 @@ pub(super) struct BatchedCtx<'a, 'c, 'd, 'x> {
|
||||
|
||||
impl<'a, 'c, 'd, 'x> BatchedCtx<'a, 'c, 'd, 'x> {
|
||||
pub(super) fn new(
|
||||
binding: &'a ModelBinding,
|
||||
source: &'a TargetStepProduct,
|
||||
request: &'a MtpWindowRequest<'a>,
|
||||
output: &'a OutputStage<'c, 'd>,
|
||||
dense_cache: &'a DenseWeightCache<'x>,
|
||||
spec: &MtpWindowSpec,
|
||||
plan: BatchedPlan,
|
||||
) -> Self {
|
||||
let (binding, source, spec) = (request.binding, &request.source, &request.spec);
|
||||
Self { binding, source, output, dense_cache, eos: spec.eos, remaining: spec.remaining, plan }
|
||||
}
|
||||
|
||||
|
||||
+51
-60
@@ -1,50 +1,46 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MtpDecoder (2).
|
||||
//! The batched MTP window: draft chain, rewind, then the joint target window (IQ3 integer/native Down policy).
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
use super::batched_support::*;
|
||||
use crate::qwen_forward::mtp::MtpCheckpoint;
|
||||
use crate::qwen_forward::mtp::RetainedFirstSeed;
|
||||
|
||||
impl MtpDecoder {
|
||||
/// Selected only by the existing explicit IQ3 integer/native Down policy.
|
||||
/// Draft depth remains configured; target batch capacity is separately
|
||||
/// admitted. Only predictions consumed by that capacity are generated/countable.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super) fn window_batched<'driver>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
source: TargetStepProduct,
|
||||
target: &mut QwenSession<'driver>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
mut kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
spec: MtpWindowSpec,
|
||||
request: MtpWindowRequest<'_>,
|
||||
mut owners: WindowOwners<'_, 'driver, '_, '_, '_, '_>,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
) -> WindowResult<MtpVerifiedWindow> {
|
||||
let plan = match self.batched_plan(binding, &source, target, cache, &spec, &mut cancelled)? {
|
||||
let plan = match self.batched_plan(&request, owners.target, owners.cache, &mut cancelled)? {
|
||||
Ok(plan) => plan,
|
||||
Err(eos) => return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: source, eos, draft_steps: 0 }),
|
||||
Err(eos) => {
|
||||
return Ok(MtpVerifiedWindow { tokens: Vec::new(), latest: request.source, eos, draft_steps: 0 });
|
||||
}
|
||||
};
|
||||
let (target_prior, mut st) = (target.checkpoint()?, self.batched_state(&plan)?);
|
||||
let cx = BatchedCtx::new(binding, &source, output, dense_cache, &spec, plan);
|
||||
match self.batched_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut st) {
|
||||
let (target_prior, mut st) = (owners.target.checkpoint()?, self.batched_state(&plan)?);
|
||||
let cx = BatchedCtx::new(&request, owners.output, owners.dense_cache, plan);
|
||||
match self.batched_body(&cx, &mut owners, &mut cancelled, &mut st) {
|
||||
Ok((latest, eos, draft_steps)) => Ok(MtpVerifiedWindow { tokens: st.tokens, latest, eos, draft_steps }),
|
||||
Err(error) => Err(self.batched_rollback(target, &st, error, |t| t.restore_checkpoint(&target_prior))),
|
||||
Err(error) => {
|
||||
Err(self.batched_rollback(owners.target, &st, error, |t| t.restore_checkpoint(&target_prior)))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validate the source and size the window. `Err(eos)` is a trivially empty window.
|
||||
fn batched_plan(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
source: &TargetStepProduct,
|
||||
request: &MtpWindowRequest<'_>,
|
||||
target: &QwenSession<'_>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
spec: &MtpWindowSpec,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> WindowResult<std::result::Result<BatchedPlan, bool>> {
|
||||
let MtpWindowRequest { binding, source, spec } = request;
|
||||
source.mtp_source(binding, target)?;
|
||||
let first = source.predicted(target)?;
|
||||
let source_position = source.position(target)?.get();
|
||||
@@ -56,7 +52,7 @@ impl MtpDecoder {
|
||||
}
|
||||
self.require_batched_admission(cache)?;
|
||||
let limit = window_limit(source_position, spec.depth, spec.remaining)?;
|
||||
Ok(Ok(self.batched_sizing(binding, source, target, cache, spec.eos, first, limit)?))
|
||||
Ok(Ok(self.batched_sizing(request, target, cache, WindowHead { first, limit })?))
|
||||
}
|
||||
|
||||
fn require_batched_admission(&self, cache: &MoeWeightCache<'_>) -> Result<()> {
|
||||
@@ -66,17 +62,15 @@ impl MtpDecoder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn batched_sizing(
|
||||
&self,
|
||||
binding: &ModelBinding,
|
||||
source: &TargetStepProduct,
|
||||
request: &MtpWindowRequest<'_>,
|
||||
target: &QwenSession<'_>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
eos: Option<TokenId>,
|
||||
first: TokenId,
|
||||
limit: usize,
|
||||
head: WindowHead,
|
||||
) -> Result<BatchedPlan> {
|
||||
let (binding, source, eos) = (request.binding, &request.source, request.spec.eos);
|
||||
let WindowHead { first, limit } = head;
|
||||
let reuse_first_seed = limit > 1 && first_seed_reuse_enabled(cache);
|
||||
let seed_host_charge = if reuse_first_seed { self.draft.first_seed_host_charge()? } else { 0 };
|
||||
let host_remaining = self.prefill_host_remaining(512 * 1024 * 1024)?;
|
||||
@@ -105,28 +99,28 @@ impl MtpDecoder {
|
||||
fn batched_body<'driver>(
|
||||
&mut self,
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'driver>,
|
||||
kar_cache: &mut Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'driver>,
|
||||
owners: &mut WindowOwners<'_, 'driver, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut BatchedState,
|
||||
) -> WindowResult<(TargetStepProduct, bool, usize)> {
|
||||
let (first_seed, draft_steps) = self.batched_draft_chain(cx, target, cache, cancelled, st)?;
|
||||
self.batched_rewind(cx, target, cache, cancelled, st, first_seed)?;
|
||||
let (first_seed, draft_steps) = self.batched_draft_chain(cx, owners, cancelled, st)?;
|
||||
match first_seed {
|
||||
Some(seed) => self.batched_restore_seed(cx, owners.target, st, &seed)?,
|
||||
None => self.batched_rewarm(cx, owners, cancelled, st)?,
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(MtpWindowError::Cancelled);
|
||||
}
|
||||
let product = self.batched_window(cx, target, kar_cache, cache, cancelled, st)?;
|
||||
batched_after_publish(cx.binding, cache, cancelled)?;
|
||||
let eos = Some(product.predicted(target)?) == cx.eos;
|
||||
let product = self.batched_window(cx, owners, cancelled, st)?;
|
||||
batched_after_publish(cx.binding, owners.cache, cancelled)?;
|
||||
let eos = Some(product.predicted(owners.target)?) == cx.eos;
|
||||
Ok((product, eos, draft_steps))
|
||||
}
|
||||
|
||||
fn batched_draft_chain(
|
||||
&mut self,
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut BatchedState,
|
||||
) -> WindowResult<(FirstSeed, usize)> {
|
||||
@@ -137,11 +131,12 @@ impl MtpDecoder {
|
||||
let Some(candidate) = next_candidate(st, cx.eos, cancelled)? else {
|
||||
break;
|
||||
};
|
||||
let input = self.batched_chain_input(cx, target, cache, previous.as_ref(), candidate)?;
|
||||
let input = self.batched_chain_input(cx, owners, previous.as_ref(), candidate)?;
|
||||
let seed_frame = plan.seed_frame(previous.is_none(), &input);
|
||||
let product = mtp::step(binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?;
|
||||
let sessions = StepSessions { target: &mut *owners.target, draft: &mut self.draft };
|
||||
let product = mtp::step(binding, sessions, input, cx.output, owners.cache)?;
|
||||
first_seed = self.capture_seed(plan, seed_frame)?.or(first_seed);
|
||||
st.candidates.push(product.predicted(binding, target)?);
|
||||
st.candidates.push(product.predicted(binding, owners.target)?);
|
||||
previous = Some(product);
|
||||
}
|
||||
Ok((first_seed, st.candidates.len().checked_sub(1).ok_or(Error::Overflow)?))
|
||||
@@ -149,17 +144,20 @@ impl MtpDecoder {
|
||||
|
||||
/// Retain the first-seed checkpoint beside its frame when the first draft step asked for reuse.
|
||||
fn capture_seed(&self, plan: &BatchedPlan, frame: Option<mtp::MtpFrame>) -> Result<FirstSeed> {
|
||||
frame.map(|frame| Ok((self.draft.checkpoint_first_seed(plan.seed_host_charge)?, frame))).transpose()
|
||||
let checkpoint = |frame| {
|
||||
Ok(RetainedFirstSeed { checkpoint: self.draft.checkpoint_first_seed(plan.seed_host_charge)?, frame })
|
||||
};
|
||||
frame.map(checkpoint).transpose()
|
||||
}
|
||||
|
||||
fn batched_chain_input(
|
||||
&self,
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &QwenSession<'_>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
owners: &WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
previous: Option<&mtp::MtpStepProduct>,
|
||||
candidate: TokenId,
|
||||
) -> Result<MtpInput> {
|
||||
let (target, cache) = (&*owners.target, &*owners.cache);
|
||||
match previous {
|
||||
Some(product) => MtpInput::from_previous(cx.binding, target, &self.draft, product, cache),
|
||||
None => {
|
||||
@@ -176,32 +174,26 @@ impl MtpDecoder {
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &QwenSession<'_>,
|
||||
st: &mut BatchedState,
|
||||
seed: &MtpCheckpoint,
|
||||
frame: &mtp::MtpFrame,
|
||||
seed: &RetainedFirstSeed,
|
||||
) -> WindowResult<()> {
|
||||
let (binding, source) = (cx.binding, cx.source);
|
||||
let (binding, source, frame) = (cx.binding, cx.source, &seed.frame);
|
||||
source.mtp_source(binding, target)?;
|
||||
if source.predicted(target)? != frame.token() || source.position(target)? != frame.position() {
|
||||
return Err(Error::IdentityMismatch.into());
|
||||
}
|
||||
self.draft.restore_first_seed(binding, target, frame, seed, &mut st.draft_priors[0])?;
|
||||
self.draft.restore_first_seed(binding, target, seed, &mut st.draft_priors[0])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Rewind the transient draft chain: restore the retained first seed, or restore, remint and re-warm.
|
||||
fn batched_rewind(
|
||||
/// Rewind the transient draft chain without a retained first seed: restore, remint and re-warm.
|
||||
fn batched_rewarm(
|
||||
&mut self,
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut BatchedState,
|
||||
first_seed: FirstSeed,
|
||||
) -> WindowResult<()> {
|
||||
let (binding, source) = (cx.binding, cx.source);
|
||||
if let Some((seed, frame)) = first_seed {
|
||||
return self.batched_restore_seed(cx, target, st, &seed, &frame);
|
||||
}
|
||||
self.draft.restore(&st.draft_priors[0])?;
|
||||
st.draft_priors.clear();
|
||||
// The old speculative epoch is unusable after rewind. Failure
|
||||
@@ -211,8 +203,8 @@ impl MtpDecoder {
|
||||
return Err(MtpWindowError::Cancelled);
|
||||
}
|
||||
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)?;
|
||||
let input = MtpInput::from_target(binding, owners.target, &self.draft, next, owners.cache)?;
|
||||
mtp::warm_step(binding, owners.target, &mut self.draft, input, owners.cache)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -223,13 +215,12 @@ impl MtpDecoder {
|
||||
fn batched_window<'driver>(
|
||||
&mut self,
|
||||
cx: &BatchedCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'driver>,
|
||||
kar_cache: &mut Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'driver>,
|
||||
owners: &mut WindowOwners<'_, 'driver, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut BatchedState,
|
||||
) -> WindowResult<TargetStepProduct> {
|
||||
let (binding, plan) = (cx.binding, &cx.plan);
|
||||
let WindowOwners { target, kar_cache, cache, .. } = owners;
|
||||
let rows = plan.capacity.min(plan.limit).min(st.candidates.len());
|
||||
poll_before_window(binding, cache)?;
|
||||
let mut fired = false;
|
||||
+14
-21
@@ -1,4 +1,4 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MtpDecoder.
|
||||
//! MtpDecoder: draft warming along known-next edges, and the window entry that picks the batched or scalar window.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
@@ -98,11 +98,11 @@ impl MtpDecoder {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
target: &mut QwenSession<'_>,
|
||||
source: &TargetStepProduct,
|
||||
known_next: TokenId,
|
||||
output: &OutputStage<'_, '_>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
edge: KnownNext<'_, TargetStepProduct>,
|
||||
head: DraftHeadOwners<'_, '_, '_, '_>,
|
||||
) -> Result<()> {
|
||||
let KnownNext { source, next_token: known_next } = edge;
|
||||
let DraftHeadOwners { output, cache } = head;
|
||||
let prior = self.draft.checkpoint()?;
|
||||
let result = (|| {
|
||||
let input = MtpInput::from_target(
|
||||
@@ -129,10 +129,10 @@ impl MtpDecoder {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
target: &mut QwenSession<'_>,
|
||||
source: &TargetStepProduct,
|
||||
known_next: TokenId,
|
||||
edge: KnownNext<'_, TargetStepProduct>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<()> {
|
||||
let KnownNext { source, next_token: known_next } = edge;
|
||||
let prior = self.draft.checkpoint()?;
|
||||
let result = (|| {
|
||||
let input = MtpInput::from_target(
|
||||
@@ -156,10 +156,10 @@ impl MtpDecoder {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
target: &mut QwenSession<'_>,
|
||||
source: &PrefillStepProduct,
|
||||
known_next: TokenId,
|
||||
edge: KnownNext<'_, PrefillStepProduct>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
) -> Result<()> {
|
||||
let KnownNext { source, next_token: known_next } = edge;
|
||||
let prior = self.draft.checkpoint()?;
|
||||
let result = (|| {
|
||||
let input = MtpInput::from_prefill(
|
||||
@@ -179,23 +179,16 @@ impl MtpDecoder {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn window<'driver>(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
source: TargetStepProduct,
|
||||
target: &mut QwenSession<'driver>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
spec: MtpWindowSpec,
|
||||
request: MtpWindowRequest<'_>,
|
||||
owners: WindowOwners<'_, 'driver, '_, '_, '_, '_>,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
|
||||
if cache.requires_iq3_mmq_admission() {
|
||||
self.window_batched(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled)
|
||||
if owners.cache.requires_iq3_mmq_admission() {
|
||||
self.window_batched(request, owners, cancelled)
|
||||
} else {
|
||||
self.window_scalar(binding, source, target, output, kar_cache, cache, dense_cache, spec, cancelled)
|
||||
self.window_scalar(request, owners, cancelled)
|
||||
}
|
||||
}
|
||||
}
|
||||
+58
-82
@@ -1,8 +1,9 @@
|
||||
//! Moved out of the parent module by STRA-338: impl MtpDecoder (3).
|
||||
//! The scalar MTP window: draft chain, rewind, then verified catch-up one target step at a time.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
use crate::qwen_forward::executor::{StepCaches, StepRequest};
|
||||
use crate::qwen_forward::mtp::MtpCheckpoint;
|
||||
|
||||
type WindowResult<T> = std::result::Result<T, MtpWindowError>;
|
||||
@@ -15,7 +16,6 @@ struct ScalarCtx<'a, 'c, 'd, 'x> {
|
||||
eos: Option<TokenId>,
|
||||
limit: usize,
|
||||
source_position: u64,
|
||||
first: TokenId,
|
||||
}
|
||||
|
||||
impl ScalarCtx<'_, '_, '_, '_> {
|
||||
@@ -32,6 +32,15 @@ struct ScalarState {
|
||||
candidates: Vec<TokenId>,
|
||||
tokens: Vec<TokenId>,
|
||||
latest: Option<TargetStepProduct>,
|
||||
/// The authoritative target prediction the next candidate is checked against.
|
||||
expected: TokenId,
|
||||
}
|
||||
|
||||
/// The target product and the candidate token the first draft step of a chain is anchored to.
|
||||
#[derive(Clone, Copy)]
|
||||
struct DraftAnchor<'a> {
|
||||
latest: Option<&'a TargetStepProduct>,
|
||||
candidate: TokenId,
|
||||
}
|
||||
|
||||
/// Validate the source and size the window. `Err(eos)` is a trivially empty window (nothing remaining, or the
|
||||
@@ -73,31 +82,27 @@ fn empty_window(latest: TargetStepProduct, eos: bool) -> MtpVerifiedWindow {
|
||||
}
|
||||
|
||||
impl MtpDecoder {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn window_scalar(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
source: TargetStepProduct,
|
||||
target: &mut QwenSession<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
mut kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
spec: MtpWindowSpec,
|
||||
request: MtpWindowRequest<'_>,
|
||||
mut owners: WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
) -> WindowResult<MtpVerifiedWindow> {
|
||||
let (first, source_position, limit) = match scalar_start(binding, &source, target, &spec, &mut cancelled)? {
|
||||
let MtpWindowRequest { binding, source, spec } = request;
|
||||
let start = scalar_start(binding, &source, owners.target, &spec, &mut cancelled)?;
|
||||
let (first, source_position, limit) = match start {
|
||||
Ok(start) => start,
|
||||
Err(eos) => return Ok(empty_window(source, eos)),
|
||||
};
|
||||
let (target_prior, mut state) = (target.checkpoint()?, self.scalar_state(first, source, limit)?);
|
||||
let cx = ScalarCtx { binding, output, dense_cache, eos: spec.eos, limit, source_position, first };
|
||||
match self.scalar_body(&cx, target, &mut kar_cache, cache, &mut cancelled, &mut state) {
|
||||
let (target_prior, mut state) = (owners.target.checkpoint()?, self.scalar_state(first, source, limit)?);
|
||||
let (output, dense_cache) = (owners.output, owners.dense_cache);
|
||||
let cx = ScalarCtx { binding, output, dense_cache, eos: spec.eos, limit, source_position };
|
||||
match self.scalar_body(&cx, &mut owners, &mut cancelled, &mut state) {
|
||||
Ok((product, eos, draft_steps)) => Ok(verified_window(state.tokens, product, eos, draft_steps)),
|
||||
Err(error) => {
|
||||
let restore = |cause: Option<Error>| {
|
||||
cause.inspect(|cause| target.note_mtp_failure(cause));
|
||||
target.restore_checkpoint(&target_prior)
|
||||
cause.inspect(|cause| owners.target.note_mtp_failure(cause));
|
||||
owners.target.restore_checkpoint(&target_prior)
|
||||
};
|
||||
self.scalar_rollback(&state, error, restore)?;
|
||||
Err(error)
|
||||
@@ -111,7 +116,7 @@ impl MtpDecoder {
|
||||
let mut candidates = reserve(limit + 1)?;
|
||||
candidates.push(first);
|
||||
let tokens = reserve(limit)?;
|
||||
Ok(ScalarState { draft_priors, candidates, tokens, latest: Some(source) })
|
||||
Ok(ScalarState { draft_priors, candidates, tokens, latest: Some(source), expected: first })
|
||||
}
|
||||
|
||||
/// Draft chain, rewind to a fresh-epoch checkpoint, then verified catch-up against the real target. A matching
|
||||
@@ -123,18 +128,16 @@ impl MtpDecoder {
|
||||
fn scalar_body(
|
||||
&mut self,
|
||||
cx: &ScalarCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
kar_cache: &mut Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut ScalarState,
|
||||
) -> WindowResult<(TargetStepProduct, bool, usize)> {
|
||||
self.scalar_draft_chain(cx, target, cache, cancelled, st)?;
|
||||
self.scalar_draft_chain(cx, owners, cancelled, st)?;
|
||||
let draft_steps = st.candidates.len() - 1;
|
||||
self.draft.restore(&st.draft_priors[0])?;
|
||||
st.draft_priors.clear();
|
||||
st.draft_priors.push(self.draft.checkpoint()?);
|
||||
let (expected, mut eos) = self.scalar_verify(cx, target, kar_cache, cache, cancelled, st)?;
|
||||
let (expected, mut eos) = self.scalar_verify(cx, owners, cancelled, st)?;
|
||||
if Some(expected) == cx.eos {
|
||||
eos = true;
|
||||
}
|
||||
@@ -149,8 +152,7 @@ impl MtpDecoder {
|
||||
fn scalar_draft_chain(
|
||||
&mut self,
|
||||
cx: &ScalarCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut ScalarState,
|
||||
) -> WindowResult<()> {
|
||||
@@ -163,10 +165,11 @@ impl MtpDecoder {
|
||||
if Some(candidate) == cx.eos {
|
||||
break;
|
||||
}
|
||||
let input = self.scalar_chain_input(cx, target, cache, previous.as_ref(), st, candidate)?;
|
||||
let product =
|
||||
mtp::step(cx.binding, StepSessions { target, draft: &mut self.draft }, input, cx.output, cache)?;
|
||||
st.candidates.push(product.predicted(cx.binding, target)?);
|
||||
let anchor = DraftAnchor { latest: st.latest.as_ref(), candidate };
|
||||
let input = self.scalar_chain_input(cx, owners, previous.as_ref(), anchor)?;
|
||||
let sessions = StepSessions { target: &mut *owners.target, draft: &mut self.draft };
|
||||
let product = mtp::step(cx.binding, sessions, input, cx.output, owners.cache)?;
|
||||
st.candidates.push(product.predicted(cx.binding, owners.target)?);
|
||||
previous = Some(product);
|
||||
}
|
||||
Ok(())
|
||||
@@ -175,23 +178,17 @@ impl MtpDecoder {
|
||||
fn scalar_chain_input(
|
||||
&self,
|
||||
cx: &ScalarCtx<'_, '_, '_, '_>,
|
||||
target: &QwenSession<'_>,
|
||||
cache: &MoeWeightCache<'_>,
|
||||
owners: &WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
previous: Option<&mtp::MtpStepProduct>,
|
||||
st: &ScalarState,
|
||||
candidate: TokenId,
|
||||
anchor: DraftAnchor<'_>,
|
||||
) -> Result<MtpInput> {
|
||||
let (target, cache) = (&*owners.target, &*owners.cache);
|
||||
match previous {
|
||||
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,
|
||||
KnownNext { source: latest, next_token: candidate },
|
||||
cache,
|
||||
)
|
||||
let latest = anchor.latest.ok_or(Error::IdentityMismatch)?;
|
||||
let next = KnownNext { source: latest, next_token: anchor.candidate };
|
||||
MtpInput::from_target(cx.binding, target, &self.draft, next, cache)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,86 +198,65 @@ impl MtpDecoder {
|
||||
fn scalar_verify(
|
||||
&mut self,
|
||||
cx: &ScalarCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
kar_cache: &mut Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut ScalarState,
|
||||
) -> WindowResult<(TokenId, bool)> {
|
||||
let mut expected = cx.first;
|
||||
let mut eos = false;
|
||||
for index in 0..cx.limit.min(st.candidates.len()) {
|
||||
if cancelled() {
|
||||
return Err(MtpWindowError::Cancelled);
|
||||
}
|
||||
if Some(expected) == cx.eos {
|
||||
if Some(st.expected) == cx.eos {
|
||||
eos = true;
|
||||
break;
|
||||
}
|
||||
let candidate = st.candidates[index];
|
||||
if candidate != expected {
|
||||
if candidate != st.expected {
|
||||
break;
|
||||
}
|
||||
expected = self.scalar_accept(cx, target, kar_cache, cache, cancelled, st, expected)?;
|
||||
self.scalar_accept(cx, owners, cancelled, st)?;
|
||||
st.tokens.push(candidate);
|
||||
}
|
||||
Ok((expected, eos))
|
||||
Ok((st.expected, eos))
|
||||
}
|
||||
|
||||
/// Rebuild persistent cell i from CURRENT actual target R_i and verified token i+1 before target advancement
|
||||
/// invalidates R_i. Do not call warm(): its nested rewind would invalidate this window's fresh-epoch rollback
|
||||
/// checkpoint on failure. The new prediction is read while the product is still current.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
/// checkpoint on failure. The new prediction is read while the product is still current and becomes the next
|
||||
/// expected token.
|
||||
fn scalar_accept(
|
||||
&mut self,
|
||||
cx: &ScalarCtx<'_, '_, '_, '_>,
|
||||
target: &mut QwenSession<'_>,
|
||||
kar_cache: &mut Option<&mut KarPleCache<'_>>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &mut ScalarState,
|
||||
expected: TokenId,
|
||||
) -> WindowResult<TokenId> {
|
||||
) -> WindowResult<()> {
|
||||
let binding = cx.binding;
|
||||
let position = cx.next_position(st.tokens.len())?;
|
||||
self.scalar_warm(binding, target, cache, cancelled, st, expected)?;
|
||||
self.scalar_warm(binding, owners, cancelled, st)?;
|
||||
let position = Position::new(position, crate::qwen_forward::contract::position_dimension())?;
|
||||
let (output, dense) = (cx.output, cx.dense_cache);
|
||||
let kar = kar_cache.as_deref_mut();
|
||||
let product = QwenForward::step_for_mtp_cached(
|
||||
binding,
|
||||
expected,
|
||||
position,
|
||||
target,
|
||||
output,
|
||||
kar,
|
||||
Some(cache),
|
||||
Some(dense),
|
||||
)?;
|
||||
let next = product.predicted(target)?;
|
||||
let request = StepRequest { binding, token: st.expected, position };
|
||||
let kar = owners.kar_cache.as_deref_mut();
|
||||
let caches = StepCaches { kar, moe: Some(&mut *owners.cache), dense: Some(cx.dense_cache) };
|
||||
let product = QwenForward::step_for_mtp_cached(request, owners.target, cx.output, caches)?;
|
||||
st.expected = product.predicted(owners.target)?;
|
||||
st.latest = Some(product);
|
||||
Ok(next)
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Warm the persistent draft cell from the current target product, then honour cancellation.
|
||||
fn scalar_warm(
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
target: &mut QwenSession<'_>,
|
||||
cache: &mut MoeWeightCache<'_>,
|
||||
owners: &mut WindowOwners<'_, '_, '_, '_, '_, '_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
st: &ScalarState,
|
||||
expected: TokenId,
|
||||
) -> WindowResult<()> {
|
||||
let latest = st.latest.as_ref().ok_or(Error::IdentityMismatch)?;
|
||||
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)?;
|
||||
let next = KnownNext { source: latest, next_token: st.expected };
|
||||
let input = MtpInput::from_target(binding, owners.target, &self.draft, next, owners.cache)?;
|
||||
mtp::warm_step(binding, owners.target, &mut self.draft, input, owners.cache)?;
|
||||
if cancelled() {
|
||||
return Err(MtpWindowError::Cancelled);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! What one MTP window runs on and for: the request to verify and the target owners that serve it.
|
||||
|
||||
use super::{
|
||||
DenseWeightCache, KarPleCache, ModelBinding, MoeWeightCache, MtpWindowSpec, OutputStage, QwenSession,
|
||||
TargetStepProduct,
|
||||
};
|
||||
|
||||
/// One MTP window to verify: the model, the authoritative target product it extends and its depth, remaining and
|
||||
/// EOS bounds.
|
||||
pub(crate) struct MtpWindowRequest<'a> {
|
||||
pub(crate) binding: &'a ModelBinding,
|
||||
pub(crate) source: TargetStepProduct,
|
||||
pub(crate) spec: MtpWindowSpec,
|
||||
}
|
||||
|
||||
/// The target session and the device owners one MTP window reads and fills: output head, KAR PLE cache, MoE weight
|
||||
/// cache and dense weight cache.
|
||||
pub(crate) struct WindowOwners<'a, 'driver, 'out, 'head, 'kar, 'dense> {
|
||||
pub(crate) target: &'a mut QwenSession<'driver>,
|
||||
pub(crate) output: &'a OutputStage<'out, 'head>,
|
||||
pub(crate) kar_cache: Option<&'a mut KarPleCache<'kar>>,
|
||||
pub(crate) cache: &'a mut MoeWeightCache<'driver>,
|
||||
pub(crate) dense_cache: &'a DenseWeightCache<'dense>,
|
||||
}
|
||||
|
||||
/// The output head and the MoE weight cache one full draft step, head included, reads.
|
||||
pub(crate) struct DraftHeadOwners<'a, 'out, 'head, 'moe> {
|
||||
pub(crate) output: &'a OutputStage<'out, 'head>,
|
||||
pub(crate) cache: &'a MoeWeightCache<'moe>,
|
||||
}
|
||||
@@ -52,7 +52,7 @@ impl MtpDecoder {
|
||||
self.kv_prefill
|
||||
.as_mut()
|
||||
.ok_or(Error::IdentityMismatch)?
|
||||
.stage_chunk(binding, &mut self.draft, txn, cache, cancelled)
|
||||
.stage_chunk(mtp::ChunkModel { binding, cache }, &mut self.draft, txn, cancelled)
|
||||
.map(ReadyMtpPrefill::Kv)
|
||||
}
|
||||
}
|
||||
@@ -74,33 +74,40 @@ fn snapshot_rows(
|
||||
fn check_cancelled(cancelled: &mut impl FnMut() -> bool) -> Result<()> {
|
||||
if cancelled() { Err(Error::Unsupported(super::super::contract::Stage::Executor)) } else { Ok(()) }
|
||||
}
|
||||
/// Warms the draft with every row that has a known next token; only the final row may lack one.
|
||||
fn warm_rows(
|
||||
binding: &ModelBinding,
|
||||
txn: &mut QwenChunkTxn<'_, '_>,
|
||||
rows: &[crate::qwen_forward::session::chunk::ChunkRowResidual],
|
||||
stage: &mut mtp::MtpChunkStage<'_>,
|
||||
(start, cache): (u64, &MoeWeightCache<'_>),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<usize> {
|
||||
let mut warmed = 0;
|
||||
for (index, row) in rows.iter().enumerate() {
|
||||
check_cancelled(cancelled)?;
|
||||
let (_, position, next, _) = txn.validate_row(row)?;
|
||||
if position.get() != start.checked_add(index as u64).ok_or(Error::Overflow)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
if next.is_none() {
|
||||
if index + 1 != rows.len() {
|
||||
/// The sealed rows of one chunk that warm the draft: where they start and the binding and cache they are warmed from.
|
||||
struct RowWarmup<'a, 'c> {
|
||||
binding: &'a ModelBinding,
|
||||
cache: &'a MoeWeightCache<'c>,
|
||||
start: u64,
|
||||
rows: &'a [crate::qwen_forward::session::chunk::ChunkRowResidual],
|
||||
}
|
||||
impl RowWarmup<'_, '_> {
|
||||
/// Warms the draft with every row that has a known next token; only the final row may lack one.
|
||||
fn run(
|
||||
&self,
|
||||
txn: &mut QwenChunkTxn<'_, '_>,
|
||||
stage: &mut mtp::MtpChunkStage<'_>,
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<usize> {
|
||||
let mut warmed = 0;
|
||||
for (index, row) in self.rows.iter().enumerate() {
|
||||
check_cancelled(cancelled)?;
|
||||
let (_, position, next, _) = txn.validate_row(row)?;
|
||||
if position.get() != self.start.checked_add(index as u64).ok_or(Error::Overflow)? {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
continue;
|
||||
if next.is_none() {
|
||||
if index + 1 != self.rows.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
mtp::warm_chunk_row(self.binding, txn, row, stage, self.cache)?;
|
||||
check_cancelled(cancelled)?;
|
||||
warmed += 1;
|
||||
}
|
||||
mtp::warm_chunk_row(binding, txn, row, stage, cache)?;
|
||||
check_cancelled(cancelled)?;
|
||||
warmed += 1;
|
||||
Ok(warmed)
|
||||
}
|
||||
Ok(warmed)
|
||||
}
|
||||
|
||||
impl MtpDecoder {
|
||||
@@ -113,7 +120,7 @@ impl MtpDecoder {
|
||||
) -> Result<ReadyMtpChunk<'draft, 'binding>> {
|
||||
let (start, end, rows) = snapshot_rows(txn)?;
|
||||
let mut stage = self.draft.stage_chunk(binding, txn)?;
|
||||
let warmed = warm_rows(binding, txn, &rows, &mut stage, (start, cache), &mut cancelled)?;
|
||||
let warmed = RowWarmup { binding, cache, start, rows: &rows }.run(txn, &mut stage, &mut cancelled)?;
|
||||
let draft_end = start.checked_add(warmed as u64).ok_or(Error::Overflow)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(super::super::contract::Stage::Executor));
|
||||
|
||||
@@ -139,8 +139,9 @@ fn authentic_scalar_first_mtp_batch_prefix_rejection_cancel_and_cleanup() {
|
||||
let mut kar = KarPleCache::new(context.as_ref(), binding.kar_ple_binding().unwrap()).unwrap();
|
||||
let mut cache = Some(MoeWeightCache::new(&binding, context.as_ref()).unwrap());
|
||||
let dense = DenseWeightCache::new(&binding, context.as_ref()).unwrap();
|
||||
let numerical =
|
||||
catch_unwind(AssertUnwindSafe(|| check_loaded(&binding, &context, &output, &mut kar, &mut cache, &dense)));
|
||||
let numerical = catch_unwind(AssertUnwindSafe(|| {
|
||||
check_loaded(Shared { binding: &binding, output: &output, dense: &dense, kar: &mut kar }, &context, &mut cache)
|
||||
}));
|
||||
let down = teardown(&context, output, kar, (cache, dense));
|
||||
let closed = Rc::try_unwrap(context).ok().map(|c| c.close());
|
||||
drop(binding);
|
||||
@@ -174,4 +175,4 @@ use impl_collection::row_matches;
|
||||
#[path = "mtp_decoder_batch_gpu/check_loaded_fn.rs"]
|
||||
mod check_loaded_fn;
|
||||
#[allow(unused_imports)]
|
||||
use check_loaded_fn::check_loaded;
|
||||
use check_loaded_fn::{Shared, check_loaded};
|
||||
|
||||
@@ -26,11 +26,11 @@ macro_rules! prepare_window {
|
||||
}
|
||||
|
||||
/// The loan of the loaded stages every scalar step, window preparation and decoder window runs against.
|
||||
struct Shared<'a, 'o, 'p, 'k, 'd> {
|
||||
binding: &'a ModelBinding,
|
||||
output: &'a OutputStage<'o, 'p>,
|
||||
dense: &'a DenseWeightCache<'d>,
|
||||
kar: &'a mut KarPleCache<'k>,
|
||||
pub(super) struct Shared<'a, 'o, 'p, 'k, 'd> {
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) output: &'a OutputStage<'o, 'p>,
|
||||
pub(super) dense: &'a DenseWeightCache<'d>,
|
||||
pub(super) kar: &'a mut KarPleCache<'k>,
|
||||
}
|
||||
|
||||
/// The tokens and draft snapshots every later phase compares against.
|
||||
|
||||
+15
-4
@@ -2,6 +2,16 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp::KnownNext;
|
||||
|
||||
/// What the cancelled T3 window is compared with: the reference tokens, the two accepted row expectations and the tail
|
||||
/// product the cancelled publication must drop.
|
||||
struct CancelledWindow<'a> {
|
||||
refs: &'a Refs,
|
||||
expected0: &'a Expected,
|
||||
expected1: &'a Expected,
|
||||
expected_tail: Expected,
|
||||
}
|
||||
|
||||
impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
pub(super) fn step(&mut self, token: TokenId, position: u64) -> Result<TargetStepProduct> {
|
||||
@@ -10,7 +20,7 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
}
|
||||
pub(super) fn warm(&mut self, draft: &mut MtpDecoder, source: &TargetStepProduct, token: TokenId) -> Result<()> {
|
||||
let native = self.cache_slot.as_mut().unwrap();
|
||||
draft.warm_retained(self.shared.binding, &mut self.target, source, token, native)
|
||||
draft.warm_retained(self.shared.binding, &mut self.target, KnownNext { source, next_token: token }, native)
|
||||
}
|
||||
pub(super) fn observe(&self, source: &TargetStepProduct) -> Expected {
|
||||
observe(self.shared.binding, &self.target, self.shared.output, source)
|
||||
@@ -117,11 +127,11 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
pub(super) fn cancelled_publish(
|
||||
&mut self,
|
||||
source: &TargetStepProduct,
|
||||
(refs, expected0, expected1): (&Refs, &Expected, &Expected),
|
||||
expected_tail: Expected,
|
||||
window: CancelledWindow<'_>,
|
||||
decoder: &mut MtpDecoder,
|
||||
(target_before, draft_before): (&ResetReplaySnapshot, &mtp::MtpChunkNumericSnapshot),
|
||||
) {
|
||||
let CancelledWindow { refs, expected0, expected1, expected_tail } = window;
|
||||
let collection = Collection::begin(3).unwrap();
|
||||
let candidate = self.cache_slot.as_mut().unwrap();
|
||||
let proposals = [refs.seed, refs.next, refs.wrong];
|
||||
@@ -160,7 +170,8 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
let draft_prior = decoder.draft.checkpoint().unwrap();
|
||||
self.refuse_windows(source, refs, &decoder, (&target_before, &draft_before));
|
||||
let before = (&target_before, &draft_before);
|
||||
self.cancelled_publish(source, (refs, expected0, expected1), expected_tail, &mut decoder, before);
|
||||
let window = CancelledWindow { refs, expected0, expected1, expected_tail };
|
||||
self.cancelled_publish(source, window, &mut decoder, before);
|
||||
self.report.check(self.target.restore_checkpoint(&target_prior).is_ok());
|
||||
self.report.check(decoder.draft.restore(&draft_prior).is_ok());
|
||||
drop(target_prior);
|
||||
|
||||
+3
-6
@@ -99,15 +99,12 @@ impl<'ctx> Flow<'_, 'ctx, '_, '_, '_, '_> {
|
||||
}
|
||||
|
||||
pub(in super::super) fn check_loaded<'ctx>(
|
||||
binding: &ModelBinding,
|
||||
shared: Shared<'_, '_, '_, '_, '_>,
|
||||
context: &'ctx Rc<leleka_cuda_driver::Context<'ctx>>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar: &mut KarPleCache<'_>,
|
||||
cache_slot: &mut Option<MoeWeightCache<'ctx>>,
|
||||
dense: &DenseWeightCache<'_>,
|
||||
) -> Report {
|
||||
admit_binding(binding);
|
||||
let mut flow = Flow::open(Shared { binding, output, dense, kar }, context, cache_slot);
|
||||
admit_binding(shared.binding);
|
||||
let mut flow = Flow::open(shared, context, cache_slot);
|
||||
let prefix = flow.reference_prefix();
|
||||
let Chain { refs, seed_expected, expected0, expected1, expected_tail, expected_continued } =
|
||||
flow.reference_tail(prefix);
|
||||
|
||||
+9
-21
@@ -2,6 +2,8 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::executor::{StepCaches, StepRequest};
|
||||
use crate::qwen_forward::mtp_decode::{MtpWindowRequest, WindowOwners};
|
||||
|
||||
pub(super) fn position_at(position: u64) -> Position {
|
||||
Position::new(position, crate::qwen_forward::contract::position_dimension()).unwrap()
|
||||
@@ -25,16 +27,9 @@ impl Shared<'_, '_, '_, '_, '_> {
|
||||
native: &mut MoeWeightCache<'ctx>,
|
||||
(token, position): (TokenId, u64),
|
||||
) -> Result<TargetStepProduct> {
|
||||
QwenForward::step_for_mtp_cached(
|
||||
self.binding,
|
||||
token,
|
||||
position_at(position),
|
||||
target,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
Some(native),
|
||||
Some(self.dense),
|
||||
)
|
||||
let request = StepRequest { binding: self.binding, token, position: position_at(position) };
|
||||
let caches = StepCaches { kar: Some(&mut *self.kar), moe: Some(native), dense: Some(self.dense) };
|
||||
QwenForward::step_for_mtp_cached(request, target, self.output, caches)
|
||||
}
|
||||
pub(super) fn window<'ctx>(
|
||||
&mut self,
|
||||
@@ -43,17 +38,10 @@ impl Shared<'_, '_, '_, '_, '_> {
|
||||
(source, spec): (TargetStepProduct, MtpWindowSpec),
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> std::result::Result<MtpVerifiedWindow, MtpWindowError> {
|
||||
decoder.window(
|
||||
self.binding,
|
||||
source,
|
||||
target,
|
||||
self.output,
|
||||
Some(&mut *self.kar),
|
||||
cache,
|
||||
self.dense,
|
||||
spec,
|
||||
cancelled,
|
||||
)
|
||||
let request = MtpWindowRequest { binding: self.binding, source, spec };
|
||||
let (output, dense_cache) = (self.output, self.dense);
|
||||
let owners = WindowOwners { target, output, kar_cache: Some(&mut *self.kar), cache, dense_cache };
|
||||
decoder.window(request, owners, cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,12 +60,10 @@ mod impl_role;
|
||||
#[allow(unused_imports)]
|
||||
use impl_role::at;
|
||||
#[allow(unused_imports)]
|
||||
use impl_role::routed;
|
||||
use impl_role::{RoutedExpert, routed};
|
||||
#[path = "mtp_expert_transport/shared_project_fn.rs"]
|
||||
mod shared_project_fn;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use shared_project_fn::compose;
|
||||
#[allow(unused_imports)]
|
||||
use shared_project_fn::compose_inner;
|
||||
#[cfg(test)]
|
||||
#[allow(unused_imports)]
|
||||
@@ -77,3 +75,5 @@ pub(super) use shared_project_fn::fixed_reference;
|
||||
use shared_project_fn::shared;
|
||||
#[allow(unused_imports)]
|
||||
use shared_project_fn::shared_project;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use shared_project_fn::{ExpertWeights, SelectedRoute, compose};
|
||||
|
||||
@@ -224,14 +224,21 @@ fn routed_down(
|
||||
cleanup?;
|
||||
Ok(output)
|
||||
}
|
||||
/// One routed expert of a token: the slot it fills in the route and its expert id.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct RoutedExpert {
|
||||
pub(super) slot: usize,
|
||||
pub(super) expert: u32,
|
||||
}
|
||||
|
||||
pub(super) fn routed(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
slot: usize,
|
||||
expert: u32,
|
||||
selected: RoutedExpert,
|
||||
q: usize,
|
||||
scales: usize,
|
||||
) -> Result<Finite> {
|
||||
let RoutedExpert { slot, expert } = selected;
|
||||
if slot >= K || expert >= 512 {
|
||||
return Err(Error::InvalidExpert);
|
||||
}
|
||||
|
||||
+32
-23
@@ -134,20 +134,32 @@ impl Packed {
|
||||
})
|
||||
}
|
||||
}
|
||||
/// The routed expert bank and the four shared-expert weight buffers one MTP expert block reads.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct ExpertWeights<'a, 'ctx> {
|
||||
pub(in super::super) bank: &'a DeviceBuffer<'ctx>,
|
||||
pub(in super::super) shared: [&'a DeviceBuffer<'ctx>; 4],
|
||||
}
|
||||
|
||||
/// The routed experts a token selected and the routing weights that scale their outputs.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct SelectedRoute {
|
||||
pub(in super::super) ids: [u32; K],
|
||||
pub(in super::super) weights: [f32; K],
|
||||
}
|
||||
|
||||
pub(in super::super) fn compose(
|
||||
context: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared_weights: [&DeviceBuffer<'_>; 4],
|
||||
expert_weights: ExpertWeights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
ids: [u32; K],
|
||||
weights: [f32; K],
|
||||
route: SelectedRoute,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
validate_values(mixed, N)?;
|
||||
let signed = ids.map(|id| i32::try_from(id).unwrap_or(-1));
|
||||
validate_route(signed, &weights)?;
|
||||
let signed = route.ids.map(|id| i32::try_from(id).unwrap_or(-1));
|
||||
validate_route(signed, &route.weights)?;
|
||||
let mut transport = Transport::new(context, failed)?;
|
||||
let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights);
|
||||
let result = compose_inner(&mut transport, expert_weights, mixed, route);
|
||||
transport.finish(result)
|
||||
}
|
||||
/// Every routed expert's Down, packed in slot order; the first failure stops before any later expert runs.
|
||||
@@ -159,19 +171,19 @@ 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, RoutedExpert { slot, expert }, q, scales)?;
|
||||
packed.pack(transport, down)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn compose_inner(
|
||||
transport: &mut Transport<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared_weights: [&DeviceBuffer<'_>; 4],
|
||||
expert_weights: ExpertWeights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
ids: [u32; K],
|
||||
weights: [f32; K],
|
||||
route: SelectedRoute,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let ExpertWeights { bank, shared: shared_weights } = expert_weights;
|
||||
let SelectedRoute { ids, weights } = route;
|
||||
let input = transport.upload(mixed)?;
|
||||
let mut packed = Packed::new(transport, ids)?;
|
||||
let (q, scales) = transport.quantize(input, false)?;
|
||||
@@ -186,18 +198,16 @@ pub(super) fn compose_inner(
|
||||
#[cfg(test)]
|
||||
pub(super) fn compose_observed(
|
||||
context: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared_weights: [&DeviceBuffer<'_>; 4],
|
||||
expert_weights: ExpertWeights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
ids: [u32; K],
|
||||
weights: [f32; K],
|
||||
route: SelectedRoute,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<ObservedOutput> {
|
||||
validate_values(mixed, N)?;
|
||||
validate_route(ids.map(|id| i32::try_from(id).unwrap_or(-1)), &weights)?;
|
||||
validate_route(route.ids.map(|id| i32::try_from(id).unwrap_or(-1)), &route.weights)?;
|
||||
let mut transport = Transport::new(context, failed)?;
|
||||
transport.observations = Some(Vec::new());
|
||||
let result = compose_inner(&mut transport, bank, shared_weights, mixed, ids, weights);
|
||||
let result = compose_inner(&mut transport, expert_weights, mixed, route);
|
||||
let observations = transport.observations.take().ok_or(Error::IdentityMismatch)?;
|
||||
let values = transport.finish(result)?;
|
||||
Ok((values, observations))
|
||||
@@ -205,12 +215,11 @@ pub(super) fn compose_observed(
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in super::super) fn fixed_reference(
|
||||
context: &Context<'_>,
|
||||
bank: &DeviceBuffer<'_>,
|
||||
shared: [&DeviceBuffer<'_>; 4],
|
||||
expert_weights: ExpertWeights<'_, '_>,
|
||||
mixed: &[f32],
|
||||
ids: [u32; K],
|
||||
weights: [f32; K],
|
||||
route: SelectedRoute,
|
||||
) -> Result<FixedReference> {
|
||||
let (output, observed) = compose_observed(context, bank, shared, mixed, ids, weights, Rc::new(Cell::new(false)))?;
|
||||
let failed = Rc::new(Cell::new(false));
|
||||
let (output, observed) = compose_observed(context, expert_weights, mixed, route, failed)?;
|
||||
Ok((output, observed.into_iter().map(|(role, values)| (format!("{role:?}"), values)).collect()))
|
||||
}
|
||||
|
||||
@@ -227,7 +227,8 @@ pub(super) fn compare_observed(
|
||||
expected: &Original,
|
||||
failed: Rc<Cell<bool>>,
|
||||
) {
|
||||
let (output, observed) = compose_observed(ctx, bank, w, mixed, IDS, ROUTE, failed).unwrap();
|
||||
let (weights, route) = (ExpertWeights { bank, shared: w }, SelectedRoute { ids: IDS, weights: ROUTE });
|
||||
let (output, observed) = compose_observed(ctx, weights, mixed, route, failed).unwrap();
|
||||
assert_eq!(observed.len(), 38);
|
||||
let parts: Vec<f32> = expected.routed.iter().flat_map(|v| v.iter().copied()).collect();
|
||||
let mut words = 0;
|
||||
|
||||
@@ -28,7 +28,8 @@ impl<'c> Env<'c> {
|
||||
mixed: &[f32],
|
||||
(ids, route): ([u32; K], [f32; K]),
|
||||
) -> Result<Box<[f32]>> {
|
||||
compose(self.ctx, bank, w, mixed, ids, route, self.failed.clone())
|
||||
let route = SelectedRoute { ids, weights: route };
|
||||
compose(self.ctx, ExpertWeights { bank, shared: w }, mixed, route, self.failed.clone())
|
||||
}
|
||||
pub(super) fn pair_cases(&self, bank: &DeviceBuffer<'_>, w: Weights<'_, '_>) {
|
||||
let ctx = self.ctx;
|
||||
@@ -113,11 +114,12 @@ impl<'c> Env<'c> {
|
||||
mixed: &[f32],
|
||||
) {
|
||||
let foreign = device.create_context(144 * 1024 * 1024).unwrap();
|
||||
let result = compose(&foreign, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false)));
|
||||
let (weights, route) = (ExpertWeights { bank, shared: w }, SelectedRoute { ids: IDS, weights: ROUTE });
|
||||
let result = compose(&foreign, weights, mixed, route, Rc::new(Cell::new(false)));
|
||||
refusal(result, Error::IdentityMismatch, &foreign, 0, &self.refusals);
|
||||
foreign.close().unwrap();
|
||||
let low = device.create_context(DEVICE_PEAK - 1).unwrap();
|
||||
let result = compose(&low, bank, w, mixed, IDS, ROUTE, Rc::new(Cell::new(false)));
|
||||
let result = compose(&low, weights, mixed, route, Rc::new(Cell::new(false)));
|
||||
refusal(result, Error::InputAllocation, &low, 0, &self.refusals);
|
||||
low.close().unwrap();
|
||||
}
|
||||
|
||||
+2
-2
@@ -28,7 +28,7 @@ fn slot_guards(
|
||||
count: Count<'_>,
|
||||
) {
|
||||
let (q, scales) = t.quantize(input, false).unwrap();
|
||||
let wrong_slot = routed(t, bank, 1, IDS[1], q, scales).unwrap();
|
||||
let wrong_slot = routed(t, bank, RoutedExpert { slot: 1, expert: IDS[1] }, q, scales).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.pack(t, wrong_slot), Error::IdentityMismatch, ctx, charge, count);
|
||||
assert_eq!(packed.next, 0);
|
||||
@@ -54,7 +54,7 @@ pub(super) fn private_owner_guards(
|
||||
slot_guards(ctx, &mut t, &mut packed, (bank, w, input), count);
|
||||
let rival_input = rival.upload(mixed).unwrap();
|
||||
let (rq, rs) = rival.quantize(rival_input, false).unwrap();
|
||||
let foreign_invocation = routed(&mut rival, bank, 0, IDS[0], rq, rs).unwrap();
|
||||
let foreign_invocation = routed(&mut rival, bank, RoutedExpert { slot: 0, expert: IDS[0] }, rq, rs).unwrap();
|
||||
let charge = ctx.allocated_bytes();
|
||||
refusal(packed.pack(&mut t, foreign_invocation), Error::IdentityMismatch, ctx, charge, count);
|
||||
assert_eq!(packed.next, 0);
|
||||
|
||||
@@ -127,7 +127,7 @@ struct QuantizedIndices {
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
mod fixed_workspace_gpu {
|
||||
use super::super::mtp_expert_transport::fixed_reference;
|
||||
use super::super::mtp_expert_transport::{ExpertWeights, FixedReference, SelectedRoute, fixed_reference};
|
||||
use super::*;
|
||||
use leleka_cuda_driver::Driver;
|
||||
const BANK_BYTES: usize = 707_788_800;
|
||||
@@ -277,7 +277,7 @@ mod fixed_workspace_gpu {
|
||||
}
|
||||
fn compare_pattern(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32]) -> usize {
|
||||
// Original allocation path and its direct unchanged quantizers FIRST.
|
||||
let (expected, original) = fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).unwrap();
|
||||
let (expected, original) = self.reference(mixed).unwrap();
|
||||
let scales = reference_scale_sets(self.ctx, mixed, &original);
|
||||
assert_eq!(original.len(), 38);
|
||||
assert_eq!(scales.len(), 11);
|
||||
@@ -327,19 +327,21 @@ mod fixed_workspace_gpu {
|
||||
let saved: [u8; 2] = corpus[at..at + 2].try_into().unwrap();
|
||||
corpus[at..at + 2].copy_from_slice(&0x7c00u16.to_le_bytes());
|
||||
self.bank.copy_from(corpus).unwrap();
|
||||
assert_eq!(
|
||||
fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).err(),
|
||||
Some(Error::NonFinite)
|
||||
);
|
||||
assert_eq!(self.reference(mixed).err(), Some(Error::NonFinite));
|
||||
assert_eq!(self.compose_with(storage, mixed, false).err(), Some(Error::NonFinite));
|
||||
storage.check().unwrap();
|
||||
corpus[at..at + 2].copy_from_slice(&saved);
|
||||
self.bank.copy_from(corpus).unwrap();
|
||||
let (expected, _) = fixed_reference(self.ctx, &self.bank, self.w(), mixed, IDS, ROUTE).unwrap();
|
||||
let (expected, _) = self.reference(mixed).unwrap();
|
||||
let actual = self.compose_with(storage, mixed, false).unwrap();
|
||||
exact(&expected, &actual);
|
||||
actual.len()
|
||||
}
|
||||
/// The original-path reference composition over the bank and the fixed route.
|
||||
fn reference(&self, mixed: &[f32]) -> Result<FixedReference> {
|
||||
let weights = ExpertWeights { bank: &self.bank, shared: self.w() };
|
||||
fixed_reference(self.ctx, weights, mixed, SelectedRoute { ids: IDS, weights: ROUTE })
|
||||
}
|
||||
fn compose_with(&self, storage: &mut FixedBuffers<'ctx>, mixed: &[f32], failed: bool) -> Result<Box<[f32]>> {
|
||||
let inputs = ExpertInputs { bank: &self.bank, shared: self.w(), mixed, ids: IDS, weights: ROUTE };
|
||||
compose(storage, inputs, Rc::new(Cell::new(failed)))
|
||||
|
||||
@@ -34,11 +34,7 @@ struct Bound<'a, 'c, 's, 'k> {
|
||||
session: &'a QwenSession<'s>,
|
||||
cache: &'a MoeWeightCache<'k>,
|
||||
}
|
||||
/// The device-side expert bank and the four dense shared-expert matrices.
|
||||
struct BoundWeights<'a, 'k> {
|
||||
bank: &'a DeviceBuffer<'k>,
|
||||
shared: [&'a DeviceBuffer<'k>; 4],
|
||||
}
|
||||
use mtp_expert_transport::ExpertWeights;
|
||||
/// Lossless byte layout only: Q2_0[half2,codes16] into separate source planes.
|
||||
struct S2Tile {
|
||||
codes: Vec<u8>,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Moved out of the parent module by STRA-338.
|
||||
|
||||
use super::mtp_expert_transport::SelectedRoute;
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
@@ -97,7 +98,7 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> {
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
pub(super) fn weights(&self) -> Result<BoundWeights<'a, 'k>> {
|
||||
pub(super) fn weights(&self) -> Result<ExpertWeights<'a, 'k>> {
|
||||
self.cache.validate(self.binding, self.context)?;
|
||||
let bank = self.cache.mtp_bank(self.binding, self.context)?;
|
||||
let shared = [
|
||||
@@ -106,36 +107,32 @@ impl<'a, 'k> Bound<'a, '_, '_, 'k> {
|
||||
self.matrix(MtpRole::SharedDown, (MtpKind::Q8_0, N, FF))?,
|
||||
self.matrix(MtpRole::SharedScalar, (MtpKind::Bf16, 1, N))?,
|
||||
];
|
||||
Ok(BoundWeights { bank, shared })
|
||||
Ok(ExpertWeights { bank, shared })
|
||||
}
|
||||
pub(super) fn compose(
|
||||
&self,
|
||||
input: &MtpMlpReady,
|
||||
weights: BoundWeights<'_, '_>,
|
||||
weights: ExpertWeights<'_, '_>,
|
||||
picks: ([u32; K], [f32; K]),
|
||||
failed: Rc<Cell<bool>>,
|
||||
) -> Result<Box<[f32]>> {
|
||||
let frame = input.frame();
|
||||
let (ids, route_weights) = picks;
|
||||
let BoundWeights { bank, shared } = weights;
|
||||
let ExpertWeights { bank, shared } = weights;
|
||||
if self.cache.requires_iq3_mmq_admission() {
|
||||
let (binding, context, session) = (self.binding, self.context, self.session);
|
||||
let mixed = input.mixed();
|
||||
let cache = self.cache;
|
||||
cache.compose_fixed_mtp_experts(
|
||||
binding,
|
||||
context,
|
||||
frame,
|
||||
session,
|
||||
bank,
|
||||
shared,
|
||||
mixed,
|
||||
let site = crate::qwen_forward::moe_weight_cache::MtpStepSite { binding, context, session, frame };
|
||||
let weights = crate::qwen_forward::moe_weight_cache::FixedMtpWeights { bank, shared };
|
||||
let picks = crate::qwen_forward::moe_weight_cache::MtpExpertPicks {
|
||||
mixed: input.mixed(),
|
||||
ids,
|
||||
route_weights,
|
||||
failed,
|
||||
)
|
||||
weights: route_weights,
|
||||
};
|
||||
cache.compose_fixed_mtp_experts(site, weights, picks, failed)
|
||||
} else {
|
||||
mtp_expert_transport::compose(self.context, bank, shared, input.mixed(), ids, route_weights, failed)
|
||||
let route = SelectedRoute { ids, weights: route_weights };
|
||||
mtp_expert_transport::compose(self.context, ExpertWeights { bank, shared }, input.mixed(), route, failed)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ mod warming;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(in crate::qwen_forward) use chunk::MtpChunkNumericSnapshot;
|
||||
pub(in crate::qwen_forward) use chunk::MtpChunkStage;
|
||||
pub(in crate::qwen_forward) use warming::{MtpKvPrefill, ReadyMtpKvPrefill};
|
||||
pub(in crate::qwen_forward) use warming::{ChunkModel, MtpKvPrefill, ReadyMtpKvPrefill};
|
||||
struct CellPair {
|
||||
key: Box<[u8]>,
|
||||
value: Box<[u8]>,
|
||||
@@ -63,6 +63,13 @@ pub(in crate::qwen_forward) struct MtpCheckpoint {
|
||||
retained: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
/// The draft checkpoint taken after the first draft step, kept with the frame it was taken at so a window can
|
||||
/// restore it instead of warming the draft again.
|
||||
pub(in crate::qwen_forward) struct RetainedFirstSeed {
|
||||
pub(in crate::qwen_forward) checkpoint: MtpCheckpoint,
|
||||
pub(in crate::qwen_forward) frame: MtpFrame,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "mtp_state/tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -124,15 +124,14 @@ impl MtpSession {
|
||||
&mut self,
|
||||
binding: &ModelBinding,
|
||||
target: &crate::qwen_forward::session::QwenSession<'_>,
|
||||
expected: &MtpFrame,
|
||||
seed: &MtpCheckpoint,
|
||||
seed: &RetainedFirstSeed,
|
||||
original: &mut MtpCheckpoint,
|
||||
) -> Result<()> {
|
||||
expected.validate(binding, target)?;
|
||||
seed.frame.validate(binding, target)?;
|
||||
if !self.binding.matches(&binding.identity()) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.restore_first_seed_checked(expected, seed, original)
|
||||
self.restore_first_seed_checked(&seed.frame, &seed.checkpoint, original)
|
||||
}
|
||||
|
||||
pub(super) fn restore_first_seed_checked(
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user