STRA-338 params e02: resident MMQ layer takes Resident/LayerResources/RoutedGroups, layer-0 arm takes Layer0Rows

This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:20:17 +01:00
parent 1479858a56
commit b4a54171e0
4 changed files with 122 additions and 121 deletions
@@ -61,15 +61,21 @@ fn witness_delta(before: (u64, u64, u64), after: (u64, u64, u64)) -> Result<[u64
after.2.checked_sub(before.2).ok_or(Error::Overflow)?,
])
}
/// The layer-0 FFN rows of a chunk with the binding and layer they belong to.
#[derive(Clone, Copy)]
struct Layer0Rows<'a> {
binding: &'a ModelBinding,
layer: LayerId,
rows: &'a [ChunkFfnRow],
}
impl MoeExpertStage {
fn test_layer0_arm<'ctx>(
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
layer0: Layer0Rows<'_>,
chunk: &mut QwenChunkTxn<'_, 'ctx>,
cache: &mut MoeWeightCache<'ctx>,
arm: usize,
) -> Result<()> {
let Layer0Rows { binding, layer, rows } = layer0;
let _arm = observation::arm(arm)?;
let products = if arm == 0 {
Self::execute_chunk(binding, layer, rows, chunk, cache, &mut || false)?
@@ -93,7 +99,7 @@ impl MoeExpertStage {
observation::cache(0, counters(cache))?;
let before = cache.test_mmq_dispatch_witness();
for arm in 0..2 {
Self::test_layer0_arm(binding, layer, rows, chunk, cache, arm)?;
Self::test_layer0_arm(Layer0Rows { binding, layer, rows }, chunk, cache, arm)?;
}
observation::complete(witness_delta(before, cache.test_mmq_dispatch_witness())?)
}
@@ -9,32 +9,26 @@ use leleka_cuda_driver::{MmqWorkspace, OriginalMmqLayer};
mod gather_fns;
#[path = "moe_mmq_adaptive/walk_fns.rs"]
mod walk_fns;
use super::resident_fns::{LayerResources, Resident, RoutedGroups};
use walk_fns::{SlotState, Walk};
#[allow(clippy::too_many_arguments)]
pub(super) fn execute_adaptive_groups<'ctx>(
txn: &QwenChunkTxn<'_, 'ctx>,
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
groups: &[Vec<Pair>],
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
inputs: &[f32],
resident: &Resident<'_, '_, 'ctx>,
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
routed: RoutedGroups<'_>,
packets: &mut SlotPacks<'_, '_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
cache.validate(binding, context)?;
check_adaptive_request(txn, cache, workspace, rows, groups)?;
let ephemeral = cache.ephemeral_routed_owner(binding, context)?;
let operation =
execute_inner(txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled);
let Resident { txn, context, binding, layer, rows } = *resident;
resources.cache.validate(binding, context)?;
check_adaptive_request(txn, resources.cache, resources.workspace, rows, routed.groups)?;
let ephemeral = resources.cache.ephemeral_routed_owner(binding, context)?;
let walk = Walk { txn, context, binding, layer, rows, groups: routed.groups };
let operation = execute_inner(&walk, resources, routed.inputs, packets);
// Even an identity, numeric, copy, or cancellation refusal drains all real
// pending events. Healthy idle allocations remain owned for the next layer.
let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.drain());
if context.is_poisoned() || matches!(&cleanup, Err(Error::CudaExecution)) {
cache.note_transport_failure();
resources.cache.note_transport_failure();
}
operation.and(cleanup)
}
@@ -70,24 +64,17 @@ fn check_adaptive_rows(
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn execute_inner<'ctx>(
txn: &QwenChunkTxn<'_, 'ctx>,
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
groups: &[Vec<Pair>],
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
walk: &Walk<'_, '_, 'ctx>,
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
inputs: &[f32],
packets: &mut SlotPacks<'_, '_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let (counts, sorted_rows) = count_groups(rows, groups)?;
let walk = Walk { txn, context, binding, layer, rows, groups };
let (cache, workspace) = (&mut *resources.cache, &mut *resources.workspace);
let cancelled = &mut *resources.cancelled;
let (counts, sorted_rows) = count_groups(walk.rows, walk.groups)?;
walk.authenticate(packets)?;
let tokens = u32::try_from(rows.len()).map_err(|_| Error::Overflow)?;
let tokens = u32::try_from(walk.rows.len()).map_err(|_| Error::Overflow)?;
let mut source =
workspace.prepare_original_expert_layer(inputs, tokens, &counts, &sorted_rows).map_err(mmq_error)?;
walk.observe_rows(cache)?;
@@ -11,7 +11,7 @@ mod original_adaptive;
#[path = "moe_mmq_chunk/resident_fns.rs"]
mod resident_fns;
use admission_fns::{mmq_triplets, rows_supported};
use resident_fns::execute_resident;
use resident_fns::{Resident, execute_resident};
impl MoeExpertStage {
pub(in crate::qwen_forward) fn execute_chunk_mmq<'ctx>(
@@ -191,12 +191,9 @@ impl<'ctx> ChunkCall<'_, '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 };
execute_resident(
actual,
context,
self.binding,
self.layer,
self.rows,
resident,
cache,
workspace,
cancelled,
@@ -5,21 +5,56 @@ use super::*;
use leleka_cuda_driver::MmqChunkActivation;
/// The sealed rows of one resident MMQ layer batch.
struct Resident<'a, 't, 'ctx> {
txn: &'a QwenChunkTxn<'t, 'ctx>,
context: &'ctx Context<'ctx>,
binding: &'a ModelBinding,
layer: LayerId,
rows: &'a [ChunkFfnRow],
pub(super) struct Resident<'a, 't, 'ctx> {
pub(super) txn: &'a QwenChunkTxn<'t, 'ctx>,
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) layer: LayerId,
pub(super) rows: &'a [ChunkFfnRow],
}
/// The expert cache, the MMQ workspace and the cancellation poll that one resident layer runs on.
pub(super) struct LayerResources<'a, 'ctx, C> {
pub(super) cache: &'a mut MoeWeightCache<'ctx>,
pub(super) workspace: &'a mut MmqWorkspace<'ctx>,
pub(super) cancelled: &'a mut C,
}
/// The expert cache and the cancellation poll that every projection of a layer mutates.
struct LayerState<'a, 'ctx, C> {
cache: &'a mut MoeWeightCache<'ctx>,
cancelled: &'a mut C,
}
/// The routed expert groups of a layer and the shared activations their gate/up projections read.
#[derive(Clone, Copy)]
pub(super) struct RoutedGroups<'a> {
pub(super) groups: &'a [Vec<Pair>],
pub(super) inputs: &'a [f32],
}
/// One expert whose gate/up/down projection runs: its routed pairs and whether the Original prompt MMQ layout
/// applies.
#[derive(Clone, Copy)]
struct ExpertProjection<'p> {
expert: usize,
pairs: &'p [Pair],
original_prompt: bool,
}
/// How the rows of a layer are finished: the shared activations uploaded through the down scope and, on the
/// native prompt path, the native prompt finish.
struct LayerFinish<'a, 'ctx, 'dense> {
scope: &'a DownScope<'ctx>,
activations: &'a mut Vec<TransportBuffer<'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native: Option<super::super::prompt_finish::NativePromptFinish<'a, 'ctx, 'dense>>,
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
marker: std::marker::PhantomData<&'dense ()>,
}
#[allow(clippy::too_many_arguments)]
pub(super) fn execute_resident<'ctx>(
txn: &QwenChunkTxn<'_, 'ctx>,
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
layer: LayerId,
rows: &[ChunkFfnRow],
resident: Resident<'_, '_, 'ctx>,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
cancelled: &mut impl FnMut() -> bool,
@@ -30,7 +65,6 @@ pub(super) fn execute_resident<'ctx>(
#[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);
let resident = Resident { txn, context, binding, layer, rows };
resident.execute(
cache,
workspace,
@@ -59,11 +93,10 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
self.admit(cache)?;
let failed = Rc::new(Cell::new(false));
let scope = DownScope::new(self.context, Rc::clone(&failed));
let mut resources = LayerResources { cache, workspace, cancelled };
let result = self.run(
&scope,
cache,
workspace,
cancelled,
&mut resources,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
@@ -71,7 +104,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
// numerical body. Drop cleanup may set the shared flag while preserving a
// non-transport primary; never lose that uncertain-free cache fence.
if failed.get() || self.context.is_poisoned() {
cache.note_transport_failure();
resources.cache.note_transport_failure();
}
result
}
@@ -149,9 +182,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
fn run(
&self,
scope: &DownScope<'ctx>,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
cancelled: &mut impl FnMut() -> bool,
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
@@ -160,18 +191,16 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
let groups = grouped_pairs(&ids)?;
let mut packets = SlotPacks::new(self.txn, self.binding, self.layer, self.rows, self.context, scope)?;
let mut activations = reserved(self.rows.len())?;
let operation = self.operate(
let finish = LayerFinish {
scope,
cache,
workspace,
cancelled,
&groups,
&inputs,
&mut packets,
&mut activations,
activations: &mut activations,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
);
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
marker: std::marker::PhantomData,
};
let operation =
self.operate(resources, RoutedGroups { groups: &groups, inputs: &inputs }, &mut packets, finish);
scope.record(&operation);
let cleanup = close_resident(packets, activations);
operation.and_then(|values| cleanup.map(|()| values))
@@ -188,73 +217,63 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
Ok((inputs, ids))
}
#[allow(clippy::too_many_arguments)]
fn operate(
&self,
scope: &DownScope<'ctx>,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
cancelled: &mut impl FnMut() -> bool,
groups: &[Vec<Pair>],
inputs: &[f32],
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
routed: RoutedGroups<'_>,
packets: &mut SlotPacks<'_, '_, 'ctx>,
activations: &mut Vec<TransportBuffer<'ctx>>,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] mut native: Option<
super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
mut finish: LayerFinish<'_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
if cancelled() {
if (resources.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let original_prompt = native.is_some() && cache.has_original_prompt_mmq();
let original_prompt = finish.native.is_some() && resources.cache.has_original_prompt_mmq();
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let original_prompt = false;
self.project_all(cache, workspace, cancelled, original_prompt, groups, inputs, packets)?;
self.project_all(resources, routed, packets, original_prompt)?;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if let Some(finish) = native.as_mut() {
return packets.finish_native_micro(cache, finish, cancelled);
if let Some(native) = finish.native.as_mut() {
return packets.finish_native_micro(resources.cache, native, resources.cancelled);
}
self.finish_rows(scope, cache, cancelled, packets, activations)
self.finish_rows(resources, packets, &mut finish)
}
/// Shared expert is unchanged native math. Its existing private scalar staging is retained, not advertised as
/// device-resident.
fn finish_rows(
&self,
scope: &DownScope<'ctx>,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
packets: &SlotPacks<'_, '_, 'ctx>,
activations: &mut Vec<TransportBuffer<'ctx>>,
finish: &mut LayerFinish<'_, 'ctx, '_>,
) -> Result<Vec<ExpertReady>> {
let (cache, cancelled) = (&mut *resources.cache, &mut *resources.cancelled);
let mut outputs = reserved(self.rows.len())?;
for (index, row) in self.rows.iter().enumerate() {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
activations.push(scope.upload(row.row().read.ready().mixed())?);
let activation = activations.last().ok_or(Error::IdentityMismatch)?.buffer()?;
finish.activations.push(finish.scope.upload(row.row().read.ready().mixed())?);
let activation = finish.activations.last().ok_or(Error::IdentityMismatch)?.buffer()?;
outputs.push(packets.finish_row(index, activation, cache, cancelled)?);
}
Ok(outputs)
}
#[allow(clippy::too_many_arguments)]
fn project_all(
&self,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
cancelled: &mut impl FnMut() -> bool,
original_prompt: bool,
groups: &[Vec<Pair>],
inputs: &[f32],
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
routed: RoutedGroups<'_>,
packets: &mut SlotPacks<'_, '_, 'ctx>,
original_prompt: bool,
) -> Result<()> {
let tokens = u32::try_from(self.rows.len()).map_err(|_| Error::Overflow)?;
if self.project_adaptive(cache, workspace, cancelled, original_prompt, groups, inputs, packets)? {
if self.project_adaptive(resources, routed, packets, original_prompt)? {
return Ok(());
}
let RoutedGroups { groups, inputs } = routed;
let workspace = &mut *resources.workspace;
let mut state = LayerState { cache: &mut *resources.cache, cancelled: &mut *resources.cancelled };
let mut source = if original_prompt {
workspace.prepare_original_gate_up_chunk(inputs, tokens)
} else {
@@ -262,51 +281,43 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
}
.map_err(mmq_error)?;
for (expert, pairs) in groups.iter().enumerate().filter(|(_, pairs)| !pairs.is_empty()) {
if cancelled() {
if (state.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
// finite group lease has expired after each call; the same workspace is reused.
self.project_expert(cache, cancelled, original_prompt, &mut source, expert, pairs, packets)?;
let projection = ExpertProjection { expert, pairs, original_prompt };
self.project_expert(&mut state, &mut source, projection, packets)?;
}
Ok(())
}
/// The Strata adaptive producer handles the whole layer when selected; `true` means it did.
#[allow(clippy::too_many_arguments)]
fn project_adaptive(
&self,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
cancelled: &mut impl FnMut() -> bool,
original_prompt: bool,
groups: &[Vec<Pair>],
inputs: &[f32],
resources: &mut LayerResources<'_, 'ctx, impl FnMut() -> bool>,
routed: RoutedGroups<'_>,
packets: &mut SlotPacks<'_, '_, 'ctx>,
original_prompt: bool,
) -> Result<bool> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
if original_prompt && cache.uses_strata_adaptive_experts() {
let (txn, context, binding, layer, rows) = (self.txn, self.context, self.binding, self.layer, self.rows);
super::original_adaptive::execute_adaptive_groups(
txn, context, binding, layer, rows, groups, cache, workspace, inputs, packets, cancelled,
)?;
if original_prompt && resources.cache.uses_strata_adaptive_experts() {
super::original_adaptive::execute_adaptive_groups(self, resources, routed, packets)?;
return Ok(true);
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let _ = (cache, workspace, cancelled, original_prompt, groups, inputs, packets);
let _ = (resources, routed, packets, original_prompt);
Ok(false)
}
#[allow(clippy::too_many_arguments)]
fn project_expert(
&self,
cache: &mut MoeWeightCache<'ctx>,
cancelled: &mut impl FnMut() -> bool,
original_prompt: bool,
state: &mut LayerState<'_, 'ctx, impl FnMut() -> bool>,
source: &mut MmqChunkActivation<'_, 'ctx>,
expert: usize,
pairs: &[Pair],
projection: ExpertProjection<'_>,
packets: &mut SlotPacks<'_, '_, 'ctx>,
) -> Result<()> {
let ExpertProjection { expert, pairs, original_prompt } = projection;
let (cache, cancelled) = (&mut *state.cache, &mut *state.cancelled);
let origin = packets.group(u32::try_from(expert).map_err(|_| Error::Overflow)?, pairs)?;
let (first, row) = self.group_head(pairs)?;
let indices = self.group_indices(row, first, pairs)?;