STRA-338 size: prefill chunk entry points share one joint publication; q6 columns, mtp-cancel check split
This commit is contained in:
+25
-24
@@ -178,30 +178,7 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
draft: &mut MtpDecoder,
|
||||
(fresh, fresh_draft): (&ResetReplaySnapshot, &MtpChunkNumericSnapshot),
|
||||
) {
|
||||
let mut mtp_callbacks = 0;
|
||||
let mtp_aborted: Result<()> = (|| {
|
||||
let (binding, output, dense) = (self.binding, self.output, self.dense);
|
||||
let kar = Some(&mut *self.kar);
|
||||
let tokens = &ids.ids;
|
||||
let host = HOST_REMAINING;
|
||||
let mut pending = QwenForward::prepare_prefill_chunk_cached(
|
||||
binding,
|
||||
tokens,
|
||||
None,
|
||||
self.session,
|
||||
output,
|
||||
kar,
|
||||
self.moe,
|
||||
dense,
|
||||
host,
|
||||
|| false,
|
||||
)?;
|
||||
let _ready = draft.stage_prefill_chunk(binding, &mut pending, self.moe, &mut || {
|
||||
mtp_callbacks += 1;
|
||||
mtp_callbacks == 2
|
||||
})?;
|
||||
Err(Error::IdentityMismatch)
|
||||
})();
|
||||
let mtp_aborted = self.mtp_aborted_attempt(ids, draft);
|
||||
assert!(
|
||||
matches!(mtp_aborted, Err(Error::Unsupported(Stage::Executor))),
|
||||
"actual MTP-row cancellation not refused"
|
||||
@@ -214,6 +191,30 @@ impl Rig<'_, '_, '_, '_, '_, '_> {
|
||||
assert!(draft.test_chunk_eq(fresh_draft), "MTP cancel changed committed draft");
|
||||
}
|
||||
|
||||
/// A pending chunk whose second MTP callback cancels: the attempt always ends in an error.
|
||||
fn mtp_aborted_attempt(&mut self, ids: &Ids, draft: &mut MtpDecoder) -> Result<()> {
|
||||
let mut mtp_callbacks = 0;
|
||||
let (binding, output, dense) = (self.binding, self.output, self.dense);
|
||||
let kar = Some(&mut *self.kar);
|
||||
let mut pending = QwenForward::prepare_prefill_chunk_cached(
|
||||
binding,
|
||||
&ids.ids,
|
||||
None,
|
||||
self.session,
|
||||
output,
|
||||
kar,
|
||||
self.moe,
|
||||
dense,
|
||||
HOST_REMAINING,
|
||||
|| false,
|
||||
)?;
|
||||
let _ready = draft.stage_prefill_chunk(binding, &mut pending, self.moe, &mut || {
|
||||
mtp_callbacks += 1;
|
||||
mtp_callbacks == 2
|
||||
})?;
|
||||
Err(Error::IdentityMismatch)
|
||||
}
|
||||
|
||||
/// The genuine chunk reproduces the scalar logits, greedy token, residual, state and draft exactly.
|
||||
fn compare_chunk(&mut self, ids: &Ids, baseline: &Baseline, candidate: &mut MtpDecoder) {
|
||||
let actual = self.prefill_chunk(ids, candidate, || false).expect("candidate chunk refused");
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
#[path = "impl_qwenforward/joint_chunk.rs"]
|
||||
mod joint_chunk;
|
||||
#[allow(unused_imports)]
|
||||
use joint_chunk::{AllocationTrace, Chunk, Plan};
|
||||
#[path = "impl_qwenforward/impl_qwenforward_2.rs"]
|
||||
mod impl_qwenforward_2;
|
||||
#[path = "impl_qwenforward/impl_qwenforward_2_2.rs"]
|
||||
|
||||
+19
-101
@@ -28,29 +28,11 @@ impl QwenForward {
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
host_remaining: usize,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> Result<Option<TargetStepProduct>> {
|
||||
let mut txn = Self::prepare_prefill_chunk_with_policy(
|
||||
binding,
|
||||
tokens,
|
||||
known_next,
|
||||
session,
|
||||
output,
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
host_remaining,
|
||||
&mut cancelled,
|
||||
ChunkMoePolicy::ExperimentalResidentMmq,
|
||||
)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
let plan = Plan::new(ChunkMoePolicy::ExperimentalResidentMmq, false);
|
||||
Self::joint_chunk(inputs, session, (draft, moe_cache), cancelled, plan)
|
||||
}
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn prefill_chunk_cached_joint<'driver>(
|
||||
@@ -58,35 +40,16 @@ impl QwenForward {
|
||||
tokens: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
session: &mut QwenSession<'driver>,
|
||||
draft: &mut super::super::super::super::mtp_decode::MtpDecoder,
|
||||
draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
host_remaining: usize,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> Result<Option<TargetStepProduct>> {
|
||||
let mut txn = Self::prepare_prefill_chunk_cached(
|
||||
binding,
|
||||
tokens,
|
||||
known_next,
|
||||
session,
|
||||
output,
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
host_remaining,
|
||||
&mut cancelled,
|
||||
)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let ready: super::super::super::super::mtp_decode::ReadyMtpChunk<'_, '_> =
|
||||
draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
Self::joint_chunk(inputs, session, (draft, moe_cache), cancelled, Plan::new(ChunkMoePolicy::Native, false))
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
@@ -124,40 +87,17 @@ impl QwenForward {
|
||||
tokens: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
session: &mut QwenSession<'driver>,
|
||||
draft: &mut super::super::super::super::mtp_decode::MtpDecoder,
|
||||
draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
host_remaining: usize,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> Result<Option<TargetStepProduct>> {
|
||||
let mut txn = Self::prepare_prefill_chunk_with_policy_windowed(
|
||||
binding,
|
||||
tokens,
|
||||
known_next,
|
||||
session,
|
||||
output,
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
host_remaining.min(512 * 1024 * 1024),
|
||||
&mut cancelled,
|
||||
ChunkMoePolicy::Native,
|
||||
true,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
// Every actual outer row has completed all48 target layers. Only now
|
||||
// warm the one private draft branch and publish target+draft together.
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
let host_remaining = host_remaining.min(512 * 1024 * 1024);
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
Self::joint_chunk(inputs, session, (draft, moe_cache), cancelled, Plan::new(ChunkMoePolicy::Native, true))
|
||||
}
|
||||
|
||||
/// Explicit private outer256 with retainedGR transport; Native MoE
|
||||
@@ -168,39 +108,17 @@ impl QwenForward {
|
||||
tokens: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
session: &mut QwenSession<'driver>,
|
||||
draft: &mut super::super::super::super::mtp_decode::MtpDecoder,
|
||||
draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
host_remaining: usize,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
) -> Result<Option<TargetStepProduct>> {
|
||||
let mut txn = Self::prepare_prefill_chunk_with_policy_windowed(
|
||||
binding,
|
||||
tokens,
|
||||
known_next,
|
||||
session,
|
||||
output,
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
host_remaining.min(512 * 1024 * 1024),
|
||||
&mut cancelled,
|
||||
ChunkMoePolicy::ExperimentalRetainedGr,
|
||||
true,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
// Every actual outer row has completed all48 target layers. Only now
|
||||
// warm the one private draft branch and publish target+draft together.
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
let host_remaining = host_remaining.min(512 * 1024 * 1024);
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
let plan = Plan::new(ChunkMoePolicy::ExperimentalRetainedGr, true);
|
||||
Self::joint_chunk(inputs, session, (draft, moe_cache), cancelled, plan)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-32
@@ -13,7 +13,7 @@ impl QwenForward {
|
||||
tokens: &[TokenId],
|
||||
known_next: Option<TokenId>,
|
||||
session: &mut QwenSession<'driver>,
|
||||
draft: &mut super::super::super::super::mtp_decode::MtpDecoder,
|
||||
draft: &mut crate::qwen_forward::mtp_decode::MtpDecoder,
|
||||
output: &OutputStage<'_, '_>,
|
||||
kar_cache: Option<&mut KarPleCache<'_>>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
@@ -24,39 +24,20 @@ impl QwenForward {
|
||||
if !moe_cache.requires_iq3_mmq_admission() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
#[cfg(test)]
|
||||
let allocation_context = moe_cache.mmq_context(binding, session.mtp_context()?)?;
|
||||
let mut txn = Self::prepare_prefill_chunk_with_policy_windowed(
|
||||
binding,
|
||||
tokens,
|
||||
known_next,
|
||||
session,
|
||||
output,
|
||||
kar_cache,
|
||||
moe_cache,
|
||||
dense_cache,
|
||||
host_remaining.min(512 * 1024 * 1024),
|
||||
&mut cancelled,
|
||||
ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr,
|
||||
true,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
None,
|
||||
).inspect_err(|_error| {
|
||||
#[cfg(test)]
|
||||
eprintln!("PUBLIC candidate allocation stage=prepare-target-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes());
|
||||
})?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let trace = AllocationTrace::begin(binding, session, moe_cache)?;
|
||||
let rows = tokens.len();
|
||||
let host_remaining = host_remaining.min(512 * 1024 * 1024);
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
let plan = Plan::new(ChunkMoePolicy::ExperimentalNativeIntegerIq3RetainedGr, true);
|
||||
let mut txn = Self::prefill_chunk_planned(inputs, session, moe_cache, &mut cancelled, plan)
|
||||
.inspect_err(|error| trace.report("prepare-target-chunk", rows, error))?;
|
||||
Self::ensure_live(&mut cancelled)?;
|
||||
// Every actual outer row has completed all48 target layers. Only now
|
||||
// warm the one private draft branch and publish target+draft together.
|
||||
let ready = draft.stage_owned_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled).inspect_err(|_error| {
|
||||
#[cfg(test)]
|
||||
eprintln!("PUBLIC candidate allocation stage=warm-draft-chunk rows={} allocated={} budget={} error={_error:?}", tokens.len(), allocation_context.allocated_bytes(), allocation_context.budget_bytes());
|
||||
})?;
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let ready = draft
|
||||
.stage_owned_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)
|
||||
.inspect_err(|error| trace.report("warm-draft-chunk", rows, error))?;
|
||||
Self::ensure_live(&mut cancelled)?;
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
}
|
||||
|
||||
|
||||
+68
-21
@@ -88,6 +88,14 @@ struct GdnPlan<'ctx> {
|
||||
lease: Option<std::rc::Rc<crate::qwen_forward::gdn::verification::ActiveLease>>,
|
||||
}
|
||||
|
||||
/// The chunk's environment, the GDN owners' contexts and the adjusted host budget, once the chunk is admitted.
|
||||
struct Admitted<'e, 'ctx, 'driver> {
|
||||
env: ChunkEnv<'e, 'ctx, 'driver>,
|
||||
gdn: GdnPlan<'ctx>,
|
||||
layer_bound: Dimension,
|
||||
host_remaining: usize,
|
||||
}
|
||||
|
||||
impl QwenForward {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(in super::super) fn prepare_prefill_chunk_with_policy_windowed<'session, 'driver>(
|
||||
@@ -100,39 +108,78 @@ impl QwenForward {
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
dense_cache: &DenseWeightCache<'_>,
|
||||
host_remaining: usize,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
cancelled: impl FnMut() -> bool,
|
||||
policy: ChunkMoePolicy,
|
||||
windowed: bool,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] boundary: Option<
|
||||
window_numeric::BoundaryPlan,
|
||||
>,
|
||||
) -> Result<QwenChunkTxn<'session, 'driver>> {
|
||||
let host_remaining = Self::reserve_cpu_wave(moe_cache, host_remaining)?;
|
||||
let inputs = Chunk { binding, tokens, known_next, output, kar_cache, dense_cache, host_remaining };
|
||||
let plan = Plan::new(policy, windowed);
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
let plan = plan.with_boundary(boundary);
|
||||
Self::prefill_chunk_planned(inputs, session, moe_cache, cancelled, plan)
|
||||
}
|
||||
|
||||
/// The batched prefill of one chunk: admission, input rows, every layer, then the output head.
|
||||
pub(super) fn prefill_chunk_planned<'session, 'driver>(
|
||||
inputs: Chunk<'_, '_, '_, '_, '_>,
|
||||
session: &'session mut QwenSession<'driver>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
plan: Plan,
|
||||
) -> Result<QwenChunkTxn<'session, 'driver>> {
|
||||
let Admitted { env, mut gdn, layer_bound, host_remaining } =
|
||||
Self::admit_chunk(&inputs, session, moe_cache, &plan)?;
|
||||
let Chunk { tokens, known_next, output, kar_cache, .. } = inputs;
|
||||
let opened = Self::open_chunk(env, session, (tokens, known_next), host_remaining, kar_cache, &mut cancelled)?;
|
||||
let (mut chunk, mut previous, lease) = opened;
|
||||
gdn.lease = lease;
|
||||
if Self::run_prefill_layers(env, &gdn, layer_bound, (&mut chunk, &mut previous), moe_cache, &mut cancelled)? {
|
||||
return Ok(chunk); // Deliberately unfinished: cannot warm or publish.
|
||||
}
|
||||
Self::finish_prefill_chunk(env, &gdn, output, (&mut chunk, &previous), &mut cancelled)?;
|
||||
Ok(chunk)
|
||||
}
|
||||
|
||||
/// Validates the layer plan and the caches and builds the environment every phase of the chunk reads.
|
||||
fn admit_chunk<'e, 'ctx, 'driver>(
|
||||
inputs: &Chunk<'e, '_, '_, '_, 'ctx>,
|
||||
session: &QwenSession<'driver>,
|
||||
moe_cache: &mut MoeWeightCache<'driver>,
|
||||
plan: &'e Plan,
|
||||
) -> Result<Admitted<'e, 'ctx, 'driver>> {
|
||||
let (binding, dense_cache, rows) = (inputs.binding, inputs.dense_cache, inputs.tokens.len());
|
||||
let host_remaining = Self::reserve_cpu_wave(moe_cache, inputs.host_remaining)?;
|
||||
let layer_bound = validate_layer_plan(binding)?;
|
||||
if layer_bound.get() != 48 {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let rows = tokens.len();
|
||||
let (context, recurrence, verification) =
|
||||
Self::admit_chunk_contexts(binding, rows, session, moe_cache, dense_cache, (policy, windowed))?;
|
||||
let host_remaining = Self::reserve_native_prefill_host(policy, host_remaining, rows)?;
|
||||
let env = ChunkEnv::new(binding, dense_cache, context, (policy, windowed), verification.is_some());
|
||||
let policy = (plan.policy, plan.windowed);
|
||||
let contexts = Self::admit_chunk_contexts(binding, rows, session, moe_cache, dense_cache, policy)?;
|
||||
let (context, recurrence, verification) = contexts;
|
||||
let host_remaining = Self::reserve_native_prefill_host(plan.policy, host_remaining, rows)?;
|
||||
let env = ChunkEnv::new(binding, dense_cache, context, policy, verification.is_some());
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
let env = env.with_boundary(boundary.as_ref());
|
||||
let opened = Self::open_chunk(env, session, (tokens, known_next), host_remaining, kar_cache, &mut cancelled)?;
|
||||
let (mut chunk, mut previous, lease) = opened;
|
||||
let plan = GdnPlan { recurrence, verification, lease };
|
||||
if Self::run_prefill_layers(env, &plan, layer_bound, (&mut chunk, &mut previous), moe_cache, &mut cancelled)? {
|
||||
return Ok(chunk); // Deliberately unfinished: cannot warm or publish.
|
||||
}
|
||||
if cancelled() {
|
||||
return Err(Error::Unsupported(Stage::Executor));
|
||||
}
|
||||
let env = env.with_boundary(plan.boundary.as_ref());
|
||||
let gdn = GdnPlan { recurrence, verification, lease: None };
|
||||
Ok(Admitted { env, gdn, layer_bound, host_remaining })
|
||||
}
|
||||
|
||||
/// The cancellation fence, the test observer of the device GDN verification and the output head.
|
||||
fn finish_prefill_chunk<'driver>(
|
||||
env: ChunkEnv<'_, '_, 'driver>,
|
||||
gdn: &GdnPlan<'_>,
|
||||
output: &OutputStage<'_, '_>,
|
||||
(chunk, previous): (&mut QwenChunkTxn<'_, 'driver>, &[Option<InjectedResidual>]),
|
||||
cancelled: &mut impl FnMut() -> bool,
|
||||
) -> Result<()> {
|
||||
Self::ensure_live(&mut *cancelled)?;
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
if plan.lease.is_some() {
|
||||
chunk.materialize_device_gdn_observer(binding, dense_cache, &mut cancelled)?;
|
||||
if gdn.lease.is_some() {
|
||||
chunk.materialize_device_gdn_observer(env.binding, env.dense, &mut *cancelled)?;
|
||||
}
|
||||
Self::execute_chunk_head(env, output, &mut chunk, &previous, &mut cancelled)?;
|
||||
Ok(chunk)
|
||||
Self::execute_chunk_head(env, output, chunk, previous, cancelled)
|
||||
}
|
||||
}
|
||||
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
//! STRA-338 size: the inputs and the joint target+draft publication shared by the prefill chunk entry points.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::mtp_decode::MtpDecoder;
|
||||
use leleka_cuda_driver::Context;
|
||||
|
||||
/// The borrowed inputs of one prefill chunk (the session and the MoE cache travel beside them).
|
||||
pub(super) struct Chunk<'a, 'x, 'y, 'k, 'd> {
|
||||
pub(super) binding: &'a ModelBinding,
|
||||
pub(super) tokens: &'a [TokenId],
|
||||
pub(super) known_next: Option<TokenId>,
|
||||
pub(super) output: &'a OutputStage<'x, 'y>,
|
||||
pub(super) kar_cache: Option<&'a mut KarPleCache<'k>>,
|
||||
pub(super) dense_cache: &'a DenseWeightCache<'d>,
|
||||
pub(super) host_remaining: usize,
|
||||
}
|
||||
|
||||
/// How the chunk runs: the MoE policy, the outer256 window, and the test boundary.
|
||||
pub(super) struct Plan {
|
||||
pub(super) policy: ChunkMoePolicy,
|
||||
pub(super) windowed: bool,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(super) boundary: Option<window_numeric::BoundaryPlan>,
|
||||
}
|
||||
|
||||
impl Plan {
|
||||
pub(super) fn new(policy: ChunkMoePolicy, windowed: bool) -> Self {
|
||||
Self {
|
||||
policy,
|
||||
windowed,
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
boundary: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
pub(super) fn with_boundary(self, boundary: Option<window_numeric::BoundaryPlan>) -> Self {
|
||||
Self { boundary, ..self }
|
||||
}
|
||||
}
|
||||
|
||||
impl QwenForward {
|
||||
/// Prepares the chunk, warms the one private draft branch and publishes target and draft together.
|
||||
pub(super) fn joint_chunk<'driver>(
|
||||
inputs: Chunk<'_, '_, '_, '_, '_>,
|
||||
session: &mut QwenSession<'driver>,
|
||||
(draft, moe_cache): (&mut MtpDecoder, &mut MoeWeightCache<'driver>),
|
||||
mut cancelled: impl FnMut() -> bool,
|
||||
plan: Plan,
|
||||
) -> Result<Option<TargetStepProduct>> {
|
||||
let binding = inputs.binding;
|
||||
let mut txn = Self::prefill_chunk_planned(inputs, session, moe_cache, &mut cancelled, plan)?;
|
||||
Self::ensure_live(&mut cancelled)?;
|
||||
// Every actual outer row has completed all48 target layers. Only now
|
||||
// warm the one private draft branch and publish target+draft together.
|
||||
let ready = draft.stage_prefill_chunk(binding, &mut txn, moe_cache, &mut cancelled)?;
|
||||
Self::ensure_live(&mut cancelled)?;
|
||||
Ok(txn.publish_joint(ready)?.into_target_product())
|
||||
}
|
||||
|
||||
/// Refuses with the executor error when the caller cancelled.
|
||||
pub(super) fn ensure_live(cancelled: &mut impl FnMut() -> bool) -> Result<()> {
|
||||
if cancelled() { Err(Error::Unsupported(Stage::Executor)) } else { Ok(()) }
|
||||
}
|
||||
}
|
||||
|
||||
/// Test-only trace of the context's allocation when a candidate stage refuses; a no-op in production builds.
|
||||
pub(super) struct AllocationTrace<'ctx> {
|
||||
#[cfg(test)]
|
||||
context: &'ctx Context<'ctx>,
|
||||
#[cfg(not(test))]
|
||||
context: std::marker::PhantomData<&'ctx ()>,
|
||||
}
|
||||
|
||||
impl<'ctx> AllocationTrace<'ctx> {
|
||||
#[cfg(test)]
|
||||
pub(super) fn begin<'driver>(
|
||||
binding: &ModelBinding,
|
||||
session: &QwenSession<'driver>,
|
||||
moe_cache: &MoeWeightCache<'ctx>,
|
||||
) -> Result<Self> {
|
||||
Ok(Self { context: moe_cache.mmq_context(binding, session.mtp_context()?)? })
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
pub(super) fn begin<'driver>(
|
||||
_binding: &ModelBinding,
|
||||
_session: &QwenSession<'driver>,
|
||||
_moe_cache: &MoeWeightCache<'ctx>,
|
||||
) -> Result<Self> {
|
||||
Ok(Self { context: std::marker::PhantomData })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) fn report(&self, stage: &str, rows: usize, error: &Error) {
|
||||
let (allocated, budget) = (self.context.allocated_bytes(), self.context.budget_bytes());
|
||||
eprintln!(
|
||||
"PUBLIC candidate allocation stage={stage} rows={rows} allocated={allocated} budget={budget} error={error:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(not(test))]
|
||||
pub(super) fn report(&self, _stage: &str, _rows: usize, _error: &Error) {}
|
||||
}
|
||||
+67
-27
@@ -2,6 +2,10 @@
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::model_binding::qwen4exp_input::{GdnMatrixKind, GdnMatrixRole, QsaMatrixKind, QsaMatrixRole};
|
||||
use crate::qwen_forward::gr::ResidualReady;
|
||||
use crate::qwen_forward::q6_attention_columns::{self, ProjectionRow, Role};
|
||||
use crate::qwen_forward::session::chunk::ChunkAttentionRow;
|
||||
|
||||
pub(super) fn prepare_q6_layer_columns<'source, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
@@ -9,20 +13,48 @@ pub(super) fn prepare_q6_layer_columns<'source, 'ctx>(
|
||||
chunk: &QwenChunkTxn<'_, '_>,
|
||||
layer: LayerId,
|
||||
kind: BoundLayerKind,
|
||||
attention: &'source [super::super::super::session::chunk::ChunkAttentionRow],
|
||||
attention: &'source [ChunkAttentionRow],
|
||||
retain_gdn_qkv: bool,
|
||||
) -> Result<Vec<Vec<super::super::super::q6_attention_columns::ProjectionRow<'source, 'ctx>>>> {
|
||||
use super::super::super::q6_attention_columns::{self, Role};
|
||||
use crate::model_binding::qwen4exp_input::{GdnMatrixKind, GdnMatrixRole, QsaMatrixKind, QsaMatrixRole};
|
||||
) -> Result<Vec<Vec<ProjectionRow<'source, 'ctx>>>> {
|
||||
let mut columns = Vec::new();
|
||||
columns.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?;
|
||||
columns.resize_with(attention.len(), Vec::new);
|
||||
let inputs = q6_inputs(chunk, layer, attention)?;
|
||||
for role in q6_roles(binding, cache, layer, kind)? {
|
||||
let rows = q6_project(binding, cache, chunk, layer, (&inputs, role), retain_gdn_qkv)?;
|
||||
if rows.len() != attention.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (slot, row) in columns.iter_mut().zip(rows) {
|
||||
slot.try_reserve_exact(1).map_err(|_| Error::InputAllocation)?;
|
||||
slot.push(row);
|
||||
}
|
||||
}
|
||||
Ok(columns)
|
||||
}
|
||||
|
||||
/// The validated residual input of every attention row.
|
||||
fn q6_inputs<'source>(
|
||||
chunk: &QwenChunkTxn<'_, '_>,
|
||||
layer: LayerId,
|
||||
attention: &'source [ChunkAttentionRow],
|
||||
) -> Result<Vec<&'source ResidualReady>> {
|
||||
let mut inputs = Vec::new();
|
||||
inputs.try_reserve_exact(attention.len()).map_err(|_| Error::InputAllocation)?;
|
||||
for (index, row) in attention.iter().enumerate() {
|
||||
chunk.validate_attention_column(chunk.micro_row_index(index)?, layer, row)?;
|
||||
inputs.push(row.ready());
|
||||
}
|
||||
Ok(inputs)
|
||||
}
|
||||
|
||||
/// The projection roles of the layer whose matrices are Q6K.
|
||||
fn q6_roles(
|
||||
binding: &ModelBinding,
|
||||
cache: &DenseWeightCache<'_>,
|
||||
layer: LayerId,
|
||||
kind: BoundLayerKind,
|
||||
) -> Result<Vec<Role>> {
|
||||
let mut roles = Vec::new();
|
||||
roles.try_reserve_exact(3).map_err(|_| Error::InputAllocation)?;
|
||||
match kind {
|
||||
@@ -34,34 +66,42 @@ pub(super) fn prepare_q6_layer_columns<'source, 'ctx>(
|
||||
}
|
||||
BoundLayerKind::Qsa => {
|
||||
let entry = cache.qsa(binding, layer.get())?;
|
||||
for (matrix, role) in
|
||||
[(QsaMatrixRole::Q, Role::QsaQ), (QsaMatrixRole::K, Role::QsaK), (QsaMatrixRole::V, Role::QsaV)]
|
||||
{
|
||||
let matrices =
|
||||
[(QsaMatrixRole::Q, Role::QsaQ), (QsaMatrixRole::K, Role::QsaK), (QsaMatrixRole::V, Role::QsaV)];
|
||||
for (matrix, role) in matrices {
|
||||
if cache.qsa_matrix(entry, matrix)?.1 == QsaMatrixKind::Q6K {
|
||||
roles.push(role);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
for role in roles {
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
let rows = if retain_gdn_qkv && matches!(role, Role::GdnQkv) {
|
||||
q6_attention_columns::project_retained(binding, cache, chunk, layer, &inputs)?
|
||||
} else {
|
||||
q6_attention_columns::project(binding, cache, chunk, layer, &inputs, role)?
|
||||
};
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
|
||||
let rows = {
|
||||
let _ = retain_gdn_qkv;
|
||||
q6_attention_columns::project(binding, cache, chunk, layer, &inputs, role)?
|
||||
};
|
||||
if rows.len() != attention.len() {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
for (slot, row) in columns.iter_mut().zip(rows) {
|
||||
slot.try_reserve_exact(1).map_err(|_| Error::InputAllocation)?;
|
||||
slot.push(row);
|
||||
}
|
||||
Ok(roles)
|
||||
}
|
||||
|
||||
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
|
||||
fn q6_project<'source, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
cache: &DenseWeightCache<'ctx>,
|
||||
chunk: &QwenChunkTxn<'_, '_>,
|
||||
layer: LayerId,
|
||||
(inputs, role): (&[&'source ResidualReady], Role),
|
||||
retain_gdn_qkv: bool,
|
||||
) -> Result<Vec<ProjectionRow<'source, 'ctx>>> {
|
||||
if retain_gdn_qkv && matches!(role, Role::GdnQkv) {
|
||||
q6_attention_columns::project_retained(binding, cache, chunk, layer, inputs)
|
||||
} else {
|
||||
q6_attention_columns::project(binding, cache, chunk, layer, inputs, role)
|
||||
}
|
||||
Ok(columns)
|
||||
}
|
||||
|
||||
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
|
||||
fn q6_project<'source, 'ctx>(
|
||||
binding: &ModelBinding,
|
||||
cache: &DenseWeightCache<'ctx>,
|
||||
chunk: &QwenChunkTxn<'_, '_>,
|
||||
layer: LayerId,
|
||||
(inputs, role): (&[&'source ResidualReady], Role),
|
||||
_retain_gdn_qkv: bool,
|
||||
) -> Result<Vec<ProjectionRow<'source, 'ctx>>> {
|
||||
q6_attention_columns::project(binding, cache, chunk, layer, inputs, role)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user