STRA-338 params r04: resident queue group (project_group_packets .. compose_copy), packet wave, PacketPlan::classify, launch_down_in_workspace, Resident::run, adaptive project_residents take PacketWave, DirectRun, SourceTail, ResidentExperts, ResidentCompose, DownColumns, MmqOwners

Files:
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:48:50 +01:00
parent 81ffd42bdd
commit fbc2c8dc28
13 changed files with 150 additions and 212 deletions
@@ -93,29 +93,6 @@ pub(super) fn miss_batch_end(rows: &[ChunkFfnRow], misses: &[&[Pair]], offset: u
Ok(end)
}
#[allow(clippy::too_many_arguments)]
fn project_residents<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
residents: &[&[Pair]],
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
for pairs in residents {
if cancelled() {
return Err(Error::Unsupported(Stage::Executor));
}
let group = ExpertGroup { context, binding, rows, pairs, scope, origins };
project_group(group, cache, prepared, down, cancelled)?;
}
Ok(())
}
/// Prepare the owned CPU jobs of one batch under the 48MiB wave allowance.
pub(super) fn prepare_cpu_jobs(
binding: &ModelBinding,
@@ -107,19 +107,15 @@ impl<'a, 'ctx> AdaptiveWave<'a, 'ctx> {
down: &mut [[Option<ActualDown<'ctx>>; K]],
cancelled: &mut impl FnMut() -> bool,
) -> Result<()> {
let (context, binding, rows) = (self.context, self.binding, self.rows);
project_residents(
context,
binding,
rows,
residents,
cache,
self.prepared,
self.scope,
self.origins,
down,
cancelled,
)
for pairs in residents {
if 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)?;
}
Ok(())
}
fn finish_member(
@@ -11,6 +11,7 @@ pub(super) use project_adaptive_packets_fn::project_adaptive_packets;
mod packet_plan_fn;
#[path = "moe_group_adaptive_packets/packet_wave_fn.rs"]
mod packet_wave_fn;
pub(super) use packet_wave_fn::PacketWave;
#[path = "moe_group_adaptive_packets/project_inner_fn.rs"]
mod project_inner_fn;
#[allow(unused_imports)]
@@ -1,5 +1,6 @@
//! Expert-group plan of one adaptive packet wave (STRA-338 size: extract-method only).
use super::super::direct_packets_fns::PacketRun;
#[allow(unused_imports)]
use super::*;
/// The expert groups of one wave split into resident GPU groups, CPU miss batches and the GPU miss queue.
@@ -25,17 +26,14 @@ impl<'g> PacketPlan<'g> {
/// Literal Strata row-major first occurrence. Group storage remains indexed
/// by expert; packet combine keeps its original ten-slot f64 ordering.
#[allow(clippy::too_many_arguments)]
pub(super) fn classify(
&mut self,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
groups: &'g [Vec<Pair>],
batch: &PacketRun<'g, '_, '_, '_, '_, '_>,
cache: &mut MoeWeightCache<'_>,
origins: &[Rc<DownOrigin>],
packets: &[ActualSlotPacket<'_>],
actual: &QwenChunkTxn<'_, '_>,
) -> Result<()> {
let (binding, rows, groups, origins, actual) =
(batch.binding, batch.rows, batch.groups, batch.origins, batch.actual);
let mut seen = [false; 512];
for row in rows {
for selected in row.row().route.experts() {
@@ -1,6 +1,7 @@
//! GPU queue and CPU miss batches of one adaptive packet wave (STRA-338 size: extract-method only).
use super::super::adaptive::{miss_batch_end, prepare_cpu_jobs, source_keys};
use super::super::project_group_direct_fn::DirectRun;
use super::packet_plan_fn::PacketPlan;
#[allow(unused_imports)]
use super::*;
@@ -19,15 +20,21 @@ pub(super) struct GpuWave<'a, 'g> {
pub(super) done: bool,
}
/// One CPU miss batch and the workspace its jobs run in.
pub(super) struct CpuMissBatch<'a, 'g> {
pub(super) cpu: &'a mut CpuMissWorkspace,
pub(super) batch: &'a [&'g [Pair]],
}
/// The shared inputs of one packet wave.
#[derive(Clone, Copy)]
pub(super) struct PacketWave<'a, 'ctx> {
pub(super) context: &'ctx Context<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) rows: &'a [ChunkFfnRow],
pub(super) prepared: &'a [RoutedGateUpQ8<'a>],
pub(super) scope: &'a DownScope<'ctx>,
pub(super) origins: &'a [Rc<DownOrigin>],
pub(in super::super) struct PacketWave<'a, 'ctx> {
pub(in super::super) context: &'ctx Context<'ctx>,
pub(in super::super) binding: &'a ModelBinding,
pub(in super::super) rows: &'a [ChunkFfnRow],
pub(in super::super) prepared: &'a [RoutedGateUpQ8<'a>],
pub(in super::super) scope: &'a DownScope<'ctx>,
pub(in super::super) origins: &'a [Rc<DownOrigin>],
}
impl<'a, 'ctx> PacketWave<'a, 'ctx> {
@@ -46,21 +53,19 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
for (slot, directory) in gpu.slots.iter_mut().enumerate() {
let Some(index) = *directory else {
continue;
};
if cancelled() {
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
let owner = cache.ephemeral_routed_owner(self.binding, self.context)?;
owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?.wait(slot, self.binding)?;
let pairs = gpu.misses.get(index).ok_or(Error::IdentityMismatch)?;
self.project_one(pairs, Some(slot), cache, packets, cancelled, actual)?;
self.project_one(pairs, Some(slot), cache, run)?;
*directory = None;
}
Ok(())
@@ -70,15 +75,13 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
&self,
gpu: &GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
for pairs in gpu.residents {
if cancelled() {
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
self.project_one(pairs, None, cache, packets, cancelled, actual)?;
self.project_one(pairs, None, cache, run)?;
}
Ok(())
}
@@ -88,15 +91,10 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
pairs: &[Pair],
slot: Option<usize>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let (context, binding, rows) = (self.context, self.binding, self.rows);
let (prepared, scope, origins) = (self.prepared, self.scope, self.origins);
resident_queue::project_group_packets(
context, binding, rows, pairs, cache, prepared, scope, origins, packets, cancelled, actual, slot,
)
let direct = DirectRun { actual: run.actual, packets: &mut *run.packets, cancelled: &mut *run.cancelled };
resident_queue::project_group_packets(*self, pairs, cache, direct, slot)
}
/// Residents (once), then the staged GPU misses, then the next stage of the queue.
@@ -104,16 +102,14 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
if !gpu.done {
self.project_residents(gpu, cache, packets, cancelled, actual)?;
self.project_residents(gpu, cache, run)?;
gpu.done = true;
}
self.consume(gpu, cache, packets, cancelled, actual)?;
self.stage(gpu, cache, cancelled)?;
self.consume(gpu, cache, run)?;
self.stage(gpu, cache, &mut *run.cancelled)?;
Ok(())
}
@@ -121,16 +117,14 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
if !gpu.done {
self.project_residents(gpu, cache, packets, cancelled, actual)?;
self.project_residents(gpu, cache, run)?;
}
while gpu.slots.iter().any(Option::is_some) {
self.consume(gpu, cache, packets, cancelled, actual)?;
self.stage(gpu, cache, cancelled)?;
self.consume(gpu, cache, run)?;
self.stage(gpu, cache, &mut *run.cancelled)?;
}
Ok(())
}
@@ -139,9 +133,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let cpu_owner = cache.cpu_miss_owner(self.binding)?;
let mut cpu = cpu_owner.try_borrow_mut().map_err(|_| Error::IdentityMismatch)?;
@@ -151,7 +143,7 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
let end = miss_batch_end(self.rows, misses, offset)?;
let batch = &misses[offset..end];
offset = end;
self.run_batch(gpu, cache, packets, cancelled, actual, &mut cpu, batch)?;
self.run_batch(gpu, cache, run, CpuMissBatch { cpu: &mut cpu, batch })?;
}
Ok(())
}
@@ -161,23 +153,20 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
/// <=48MiB INCLUDING actual directory, preparation and start/join metadata/capacities. Callees measure their own
/// retained capacities against this remaining allowance before send. Always drain actual CPU consumers,
/// including GPU failure/cancellation; preserve the primary GPU failure; no source allocation outlives join.
#[allow(clippy::too_many_arguments)]
pub(super) fn run_batch(
&self,
gpu: &mut GpuWave<'_, '_>,
cache: &mut MoeWeightCache<'_>,
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
cpu: &mut CpuMissWorkspace,
batch: &[&[Pair]],
run: &mut DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
misses: CpuMissBatch<'_, '_>,
) -> Result<()> {
if cancelled() {
let CpuMissBatch { cpu, batch } = misses;
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
let jobs = prepare_cpu_jobs(self.binding, self.rows, batch, cpu, gpu.job_allowance)?;
let pending = cpu.start(jobs, gpu.job_allowance).map_err(runtime_error)?;
let gpu_result = self.gpu_phase(gpu, cache, packets, cancelled, actual);
let gpu_result = self.gpu_phase(gpu, cache, run);
let completed = pending.join().map_err(runtime_error);
gpu_result?;
let completed = completed?;
@@ -185,10 +174,10 @@ impl<'a, 'ctx> PacketWave<'a, 'ctx> {
return Err(Error::IdentityMismatch);
}
for (values, pairs) in completed.into_iter().zip(batch) {
if cancelled() {
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
self.finish_member(cache, packets, cancelled, actual, pairs, values)?;
self.finish_member(cache, run.packets, &mut *run.cancelled, run.actual, pairs, values)?;
}
Ok(())
}
@@ -1,25 +1,17 @@
//! Moved out of the parent module by STRA-338: fn project_adaptive_packets.
use super::super::direct_packets_fns::PacketRun;
use super::super::project_group_direct_fn::DirectRun;
#[allow(unused_imports)]
use super::*;
#[allow(clippy::too_many_arguments)]
pub(in super::super) fn project_adaptive_packets<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
groups: &[Vec<Pair>],
batch: &PacketRun<'_, '_, 'ctx, '_, '_, '_>,
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let ephemeral = cache.ephemeral_routed_owner(binding, context)?;
let operation =
project_inner(context, binding, rows, groups, cache, prepared, scope, origins, packets, cancelled, actual);
let ephemeral = cache.ephemeral_routed_owner(batch.binding, batch.context)?;
let operation = project_inner(batch, cache, run);
// Every genuine pending owner is drained, including prepare/copy/cancel errors.
let cleanup = ephemeral.try_borrow_mut().map_err(|_| Error::IdentityMismatch).and_then(|mut owner| owner.drain());
operation.and(cleanup)
@@ -1,27 +1,23 @@
//! Moved out of the parent module by STRA-338: fn project_inner.
use super::super::direct_packets_fns::PacketRun;
use super::super::project_group_direct_fn::DirectRun;
use super::packet_plan_fn::PacketPlan;
use super::packet_wave_fn::{GpuWave, PacketWave};
#[allow(unused_imports)]
use super::*;
#[allow(clippy::too_many_arguments)]
pub(super) fn project_inner<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
groups: &[Vec<Pair>],
batch: &PacketRun<'_, '_, 'ctx, '_, '_, '_>,
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let (context, binding, rows, groups) = (batch.context, batch.binding, batch.rows, batch.groups);
let (prepared, scope, origins) = (batch.prepared, batch.scope, batch.origins);
let DirectRun { actual, packets, cancelled } = run;
observe_adaptive(binding, rows, cache)?;
let mut plan = PacketPlan::new(groups.len())?;
plan.classify(binding, rows, groups, cache, origins, packets, actual)?;
plan.classify(batch, cache, packets)?;
plan.assign_misses(context, binding, rows, cache, actual)?;
let slot_count = ephemeral_slot_count(context, binding, cache)?;
let mut legacy_slots = [None; 2];
@@ -32,8 +28,9 @@ pub(super) fn project_inner<'ctx>(
let mut gpu = GpuWave { misses, residents, cpu_misses, job_allowance: 0, next: 0, slots, done: false };
wave.stage(&mut gpu, cache, cancelled)?;
gpu.job_allowance = plan.job_allowance()?;
wave.run_misses(&mut gpu, cache, packets, cancelled, actual)?;
wave.finish_gpu(&mut gpu, cache, packets, cancelled, actual)
let mut run = DirectRun { actual, packets, cancelled };
wave.run_misses(&mut gpu, cache, &mut run)?;
wave.finish_gpu(&mut gpu, cache, &mut run)
}
fn observe_adaptive(binding: &ModelBinding, rows: &[ChunkFfnRow], cache: &mut MoeWeightCache<'_>) -> Result<()> {
@@ -102,21 +102,8 @@ impl<'ctx> PacketRun<'_, '_, 'ctx, '_, '_, '_> {
) -> Result<()> {
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
{
let (context, binding, rows, scope) = (self.context, self.binding, self.rows, self.scope);
let (groups, prepared, actual) = (self.groups, self.prepared, self.actual);
adaptive_packets::project_adaptive_packets(
context,
binding,
rows,
groups,
cache,
prepared,
scope,
self.origins,
packets,
cancelled,
actual,
)?;
let run = DirectRun { actual: self.actual, packets, cancelled };
adaptive_packets::project_adaptive_packets(self, cache, run)?;
}
Ok(())
}
@@ -259,7 +259,8 @@ impl<'a, 'ctx> ResidentGroup<'a, 'ctx> {
) -> Result<()> {
let (context, pairs, scope) = (self.context, self.pairs, self.scope);
scope.with_workspace(|workspace| {
let result = launch_down_in_workspace(workspace, matrix, args.input, out, pairs.len(), args.format)?;
let columns = DownColumns { total: pairs.len(), format: args.format };
let result = launch_down_in_workspace(workspace, matrix, args.input, out, columns)?;
down_outcome(result, || {
let hidden_values = args.refusal_values(pairs.len())?;
let projection = DownProjection { kind: args.kind, format: args.format, matrix };
@@ -150,9 +150,9 @@ pub(super) fn launch_down_in_workspace<'ctx>(
matrix: CachedMoeMatrix<'_, '_>,
input: &DeviceBuffer<'ctx>,
out: &mut DeviceBuffer<'ctx>,
columns: usize,
format: RoutedFormat,
columns: DownColumns,
) -> Result<std::result::Result<(), DriverError>> {
let DownColumns { total: columns, format } = columns;
Ok(match matrix {
CachedMoeMatrix::Raw(raw) => {
workspace.project_down_columns(raw, input, out, leleka_cuda_driver::RoutedDownShape { columns, format })
@@ -41,9 +41,9 @@ struct SourceDownLaunch<'a, 'ctx> {
/// What ends the source scope after the last private consumer: the cache health and the opened source itself.
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
struct SourceTail<'a, 'ctx, 'src, 'file> {
health: &'a RoutedSourceHealth<'a, 'ctx>,
source: &'a mut MoeRoutedSourceScope<'src, 'file>,
pub(super) struct SourceTail<'a, 'ctx, 'src, 'file> {
pub(super) health: &'a RoutedSourceHealth<'a, 'ctx>,
pub(super) source: &'a mut MoeRoutedSourceScope<'src, 'file>,
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
@@ -243,7 +243,8 @@ impl<'ctx> DirectGroup<'_, 'ctx> {
let DownProjection { format, matrix, .. } = projection;
let DownBuffers { input, out } = buffers;
let pairs = self.pairs;
let result = launch_down_in_workspace(workspace, matrix, input, out, pairs.len(), format)?;
let columns = DownColumns { total: pairs.len(), format };
let result = launch_down_in_workspace(workspace, matrix, input, out, columns)?;
down_outcome(result, || {
let hidden_values = download_f32(input, pairs.len() * FF)?;
let replay = RefusalReplay { hidden_values: &hidden_values, selections };
@@ -1,25 +1,23 @@
//! Closed original-kernel resident expert pipeline and genuine packet handoff.
use super::project_group_direct_fn::{DirectGroup, DownProjection, RefusalReplay};
use super::adaptive_packets::PacketWave;
use super::project_group_direct_fn::{DirectGroup, DirectRun, DownProjection, RefusalReplay};
use super::project_group_shared_fns::{down_format, gate_up_format, packet_targets};
use super::project_group_source_consumers_fn::check_source_members;
use super::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 leleka_cuda_driver::{RoutedResidentOutputs, RoutedResidentQueue, RoutedResidentRefusal, RoutedResidentWeights};
#[allow(clippy::too_many_arguments)]
/// Projects one expert group of a packet wave through the resident queue into the row packets.
pub(super) fn project_group_packets<'ctx>(
context: &'ctx Context<'ctx>,
binding: &ModelBinding,
rows: &[ChunkFfnRow],
wave: PacketWave<'_, 'ctx>,
pairs: &[Pair],
cache: &mut MoeWeightCache<'_>,
prepared: &[RoutedGateUpQ8<'_>],
scope: &DownScope<'ctx>,
origins: &[Rc<DownOrigin>],
packets: &mut [ActualSlotPacket<'ctx>],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
ephemeral_slot: Option<usize>,
) -> Result<()> {
let PacketWave { context, binding, rows, scope, origins, .. } = wave;
let DirectRun { actual, packets, cancelled } = run;
validate_packet_pairs(actual, binding, PacketGroupMembers { rows, pairs, origins }, packets)?;
cache.validate(binding, context)?;
if !uses_adaptive(cache) || !use_direct_packets(cache) {
@@ -27,15 +25,31 @@ pub(super) fn project_group_packets<'ctx>(
}
let queue_owner = cache.routed_resident_owner(binding, context)?;
let output_owner = cache.routed_output_owner(binding, context)?;
let run = QueueRun::for_pairs(context, binding, rows, pairs, scope, origins, prepared)?;
let queue_run = QueueRun::for_pairs(wave, pairs)?;
let operation = output_owner.with_outputs(context, pairs.len(), |outputs| {
run.in_source(cache, &queue_owner, ephemeral_slot, outputs, cancelled, actual, packets)
let experts = ResidentExperts { cache: &*cache, queue_owner: &queue_owner, ephemeral_slot };
queue_run.in_source(experts, outputs, DirectRun { actual, packets, cancelled })
});
scope.record(&operation);
let health = cache.validate(binding, context);
operation.and(health)
}
/// Where the experts of one resident group come from: the weight cache, its resident queue owner and, for a staged
/// miss, the ephemeral slot that holds it.
struct ResidentExperts<'a, 'c> {
cache: &'a MoeWeightCache<'c>,
queue_owner: &'a Rc<RoutedResidentOwner<'c>>,
ephemeral_slot: Option<usize>,
}
/// The resident queue, the three raw weight buffers and the four output buffers one group is composed on.
struct ResidentCompose<'q, 'w, 'b, 'c> {
queue: &'q mut RoutedResidentQueue<'c>,
raw: [&'w DeviceBuffer<'b>; 3],
outputs: [&'q mut DeviceBuffer<'c>; 4],
}
/// One resident-queue group: the shared group identity, its prepared columns and the three kernel formats.
struct QueueRun<'a, 'ctx> {
group: DirectGroup<'a, 'ctx>,
@@ -48,15 +62,8 @@ struct QueueRun<'a, 'ctx> {
}
impl<'a, 'ctx> QueueRun<'a, 'ctx> {
fn for_pairs(
context: &'ctx Context<'ctx>,
binding: &'a ModelBinding,
rows: &'a [ChunkFfnRow],
pairs: &'a [Pair],
scope: &'a DownScope<'ctx>,
origins: &'a [Rc<DownOrigin>],
prepared: &'a [RoutedGateUpQ8<'a>],
) -> Result<Self> {
fn for_pairs(wave: PacketWave<'a, 'ctx>, pairs: &'a [Pair]) -> Result<Self> {
let PacketWave { context, binding, rows, prepared, scope, origins } = wave;
let first = pairs[0];
let weights = &rows[first.row].row().weights;
let selection = MoeExpertSelection::Routed { slot: first.slot };
@@ -85,50 +92,43 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
/// Every grouped member must name the same actual whole expert triplet; the source stays open for the
/// resident compose and the packet copy.
#[allow(clippy::too_many_arguments)]
fn in_source<'c>(
&self,
cache: &MoeWeightCache<'c>,
queue_owner: &Rc<crate::qwen_forward::moe_weight_cache::RoutedResidentOwner<'c>>,
ephemeral_slot: Option<usize>,
experts: ResidentExperts<'_, 'c>,
outputs: [&mut DeviceBuffer<'c>; 4],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
mut run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
) -> Result<()> {
let binding = self.group.binding;
binding.with_moe_routed_source(&self.members, binding_error, |source| {
check_source_members(source, self.group.pairs.len())?;
if cancelled() {
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
self.dispatch(cache, queue_owner, ephemeral_slot, outputs, cancelled, actual, packets, source)
self.dispatch(experts, outputs, run, source)
})
}
#[allow(clippy::too_many_arguments)]
fn dispatch<'c>(
&self,
cache: &MoeWeightCache<'c>,
queue_owner: &Rc<crate::qwen_forward::moe_weight_cache::RoutedResidentOwner<'c>>,
ephemeral_slot: Option<usize>,
experts: ResidentExperts<'_, 'c>,
outputs: [&mut DeviceBuffer<'c>; 4],
cancelled: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
source: &mut MoeRoutedSourceScope<'_, '_>,
) -> Result<()> {
let ResidentExperts { cache, queue_owner, ephemeral_slot } = experts;
let DirectRun { actual, packets, cancelled } = run;
// Fresh per loan; set only when the real cancelled closure answers true inside the callback.
let cancel_observed = std::cell::Cell::new(false);
let mut observed_cancel = crate::qwen_forward::moe_weight_cache::observe_cancel(&cancel_observed, cancelled);
let consume =
|raw: [&DeviceBuffer<'_>; 3],
health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>,
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>| {
queue_owner.with_queue(|queue| {
self.compose_copy(queue, raw, outputs, &mut observed_cancel, actual, packets, health, source)
})
};
let consume = |raw: [&DeviceBuffer<'_>; 3],
health: &RoutedSourceHealth<'_, '_>,
source: &mut MoeRoutedSourceScope<'_, '_>| {
queue_owner.with_queue(|queue| {
let compose = ResidentCompose { queue, raw, outputs };
let observed = DirectRun { actual, packets, cancelled: &mut observed_cancel };
self.compose_copy(compose, observed, SourceTail { health, source })
})
};
let binding = self.group.binding;
match ephemeral_slot {
Some(slot) => {
@@ -140,18 +140,13 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
/// Compose the resident kernels; a numerical refusal replays in row order, otherwise the Down columns are
/// copied into the packets.
#[allow(clippy::too_many_arguments)]
fn compose_copy<'c>(
&self,
queue: &mut RoutedResidentQueue<'c>,
raw: [&DeviceBuffer<'_>; 3],
outputs: [&mut DeviceBuffer<'c>; 4],
observed_cancel: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>,
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
compose: ResidentCompose<'_, '_, '_, 'c>,
mut run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
tail: SourceTail<'_, '_, '_, '_>,
) -> Result<()> {
let ResidentCompose { queue, raw, outputs } = compose;
let weights = self.resident_weights(raw);
let [gate, up, hidden, down] = outputs;
let complete = queue
@@ -159,16 +154,16 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
.map_err(driver_error)?;
match complete.numerical_refusal() {
Some(RoutedResidentRefusal::DownQuant) => {
return self.down_refusal(complete.completed_hidden(), raw[2], observed_cancel);
return self.down_refusal(complete.completed_hidden(), raw[2], &mut *run.cancelled);
}
Some(_) => return Err(Error::NonFinite),
None => {}
}
let down_source = complete.completed_down().ok_or(Error::IdentityMismatch)?;
if observed_cancel() {
if (run.cancelled)() {
return Err(Error::Unsupported(Stage::Executor));
}
self.copy_down(down_source, observed_cancel, actual, packets, health, source)
self.copy_down(down_source, run, tail)
}
fn resident_weights<'w, 'b>(&self, raw: [&'w DeviceBuffer<'b>; 3]) -> RoutedResidentWeights<'w, 'b> {
@@ -193,12 +188,11 @@ impl<'a, 'ctx> QueueRun<'a, 'ctx> {
fn copy_down(
&self,
down_source: &DeviceBuffer<'_>,
observed_cancel: &mut impl FnMut() -> bool,
actual: &QwenChunkTxn<'_, '_>,
packets: &mut [ActualSlotPacket<'ctx>],
health: &crate::qwen_forward::moe_weight_cache::RoutedSourceHealth<'_, '_>,
source: &mut crate::model_binding::qwen4exp_input::MoeRoutedSourceScope<'_, '_>,
run: DirectRun<'_, '_, '_, 'ctx, impl FnMut() -> bool>,
tail: SourceTail<'_, '_, '_, '_>,
) -> Result<()> {
let DirectRun { actual, packets, cancelled: observed_cancel } = run;
let SourceTail { health, source } = tail;
let group = &self.group;
let (context, binding, pairs) = (group.context, group.binding, group.pairs);
let members = PacketGroupMembers { rows: group.rows, pairs, origins: group.origins };
@@ -4,6 +4,12 @@
use super::*;
use leleka_cuda_driver::MmqChunkActivation;
/// The weight cache and the MMQ workspace a resident layer batch projects its experts on.
struct MmqOwners<'a, 'ctx> {
cache: &'a mut MoeWeightCache<'ctx>,
workspace: &'a mut MmqWorkspace<'ctx>,
}
/// The sealed rows of one resident MMQ layer batch.
struct Resident<'a, 't, 'ctx> {
txn: &'a QwenChunkTxn<'t, 'ctx>,
@@ -61,8 +67,7 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
let scope = DownScope::new(self.context, Rc::clone(&failed));
let result = self.run(
&scope,
cache,
workspace,
MmqOwners { cache, workspace },
cancelled,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
native,
@@ -149,13 +154,13 @@ impl<'ctx> Resident<'_, '_, 'ctx> {
fn run(
&self,
scope: &DownScope<'ctx>,
cache: &mut MoeWeightCache<'ctx>,
workspace: &mut MmqWorkspace<'ctx>,
owners: MmqOwners<'_, 'ctx>,
cancelled: &mut impl FnMut() -> bool,
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] native: Option<
super::super::prompt_finish::NativePromptFinish<'_, 'ctx, '_>,
>,
) -> Result<Vec<ExpertReady>> {
let MmqOwners { cache, workspace } = owners;
let (inputs, ids) = self.gather_rows()?;
let groups = grouped_pairs(&ids)?;
let mut packets = SlotPacks::new(self.sealed_layer(), self.rows, self.context, scope)?;