STRA-338 params e04: serve stack takes CpuGroup, SwapSources, QsaOwnerHome, TierResources and ExecutorOpening

Files: none
This commit is contained in:
Pavlo Ratushnyi
2026-11-08 02:20:14 +01:00
parent 788c500590
commit b59d3f65f5
9 changed files with 115 additions and 80 deletions
@@ -3,6 +3,14 @@
#[allow(unused_imports)]
use super::*;
/// One group of CPU expert entries: its input rows, the sink their outputs are written to and which entries the CPU
/// owns (`None`: all).
pub(super) struct CpuGroup<'a, 'r, 'b, 'c> {
rows: &'a OriginalVerifyCpuRows<'r>,
sink: &'a mut OriginalVerifyCpuSink<'b, 'c>,
include: Option<&'a [bool]>,
}
impl CpuExpertPool<'_> {
/// Compute the entries `include` selects (all when `None`) and write the group's output: every computed
/// `(row, slot)` gets its expert's row, every other one zeros (the GPU tier owns it; expert_source.cpp
@@ -18,7 +26,7 @@ impl CpuExpertPool<'_> {
let mut clock = window_trace::now();
let plan = Self::plan_group(&rows, count, include, &mut clock)?;
if self.direct.is_some() {
self.run_direct(&rows, sink, include, &plan, &mut clock)?;
self.run_direct(CpuGroup { rows: &rows, sink: &mut *sink, include }, &plan, &mut clock)?;
if self.legacy.is_some() {
let results = self.legacy_results(&rows, &plan, &mut clock)?;
return self.compare(sink, &plan, &results);
@@ -59,12 +67,11 @@ impl CpuExpertPool<'_> {
/// synchronous dispatch writing every computed row in place.
pub(super) fn run_direct(
&mut self,
rows: &OriginalVerifyCpuRows<'_>,
sink: &mut OriginalVerifyCpuSink<'_, '_>,
include: Option<&[bool]>,
entries: CpuGroup<'_, '_, '_, '_>,
plan: &[ExpertJob],
clock: &mut Option<std::time::Instant>,
) -> Result<()> {
let CpuGroup { rows, sink, include } = entries;
let binding = self.binding;
let tier = self.direct.as_mut().ok_or(Error::IdentityMismatch)?;
let (opened, group) = tier.open_for_group(binding, rows, plan)?;
@@ -67,18 +67,25 @@ pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: u
choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps)
}
/// Where the source spans of the incoming experts come from: the binding, the weight cache, the CPU tier and the span
/// cache that remembers spans already opened.
pub(super) struct SwapSources<'a, 'ctx, 'p> {
pub(super) binding: &'a ModelBinding,
pub(super) moe: &'a MoeWeightCache<'ctx>,
pub(super) cpu: &'a mut CpuExpertPool<'p>,
pub(super) known: &'a mut SpanCache,
}
/// Queue `swaps` (any number, one expert per slot, distinct within a layer) on the tier's copy stream and arm the
/// batch;
/// the caller (or the next round's `apply_pending`) lands it. The source spans of a layer's incoming experts are opened
/// under one fence (the direct CPU tier's admission when it is on).
pub(super) fn queue_swaps<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
sources: &mut SwapSources<'_, 'ctx, '_>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
swaps: &[Swap],
) -> Result<()> {
let (binding, moe) = (sources.binding, sources.moe);
let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?;
let mut layer_swaps: Vec<Vec<&Swap>> = vec![Vec::new(); LAYERS];
for swap in swaps {
@@ -89,7 +96,8 @@ pub(super) fn queue_swaps<'ctx>(
continue;
}
let incoming: Vec<u32> = group.iter().map(|s| s.incoming as u32).collect();
let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, known, layer, &incoming)?;
let spans: Vec<[ResidentExpertBankSpan; 3]> =
source_spans(sources.cpu, &bank, moe, binding, sources.known, layer, &incoming)?;
for (swap, spans) in group.iter().zip(spans) {
let slot = cache.resident_slot(swap.layer, swap.outgoing).ok_or(Error::IdentityMismatch)?;
cache.swap_slot_queued(slot, Rc::clone(&bank), spans).map_err(|e| driver_error(&e))?;
@@ -104,11 +112,8 @@ pub(super) fn queue_swaps<'ctx>(
/// and a
/// cycle is broken through one temporary expert. Returns the swaps made.
pub(super) fn restore_placement<'ctx>(
binding: &ModelBinding,
moe: &MoeWeightCache<'ctx>,
sources: &mut SwapSources<'_, 'ctx, '_>,
cache: &mut OriginalExpertCache<'ctx>,
cpu: &mut CpuExpertPool<'_>,
known: &mut SpanCache,
initial: &[Option<(usize, usize)>],
) -> Result<usize> {
let mut made = 0usize;
@@ -116,7 +121,7 @@ pub(super) fn restore_placement<'ctx>(
cache.wait_swaps().map_err(|e| driver_error(&e))?;
let Some(swaps) = restore_round(cache, initial)? else { return Ok(made) };
made += swaps.len();
queue_swaps(binding, moe, cache, cpu, known, &swaps)?;
queue_swaps(sources, cache, &swaps)?;
}
Err(Error::IdentityMismatch)
}
@@ -5,13 +5,13 @@ use super::*;
mod decode_parts;
use decode_parts::{
RefillOwners, assemble_decode, decode_pcie_mode, gpu_expert_pool, narrow_window_policy, resolve_assembled,
return_owners, settle_deferred_refill, teardown_decode,
QsaOwnerHome, RefillOwners, TierResources, assemble_decode, decode_pcie_mode, gpu_expert_pool,
narrow_window_policy, resolve_assembled, return_owners, settle_deferred_refill, teardown_decode,
};
mod open_parts;
use open_parts::{
Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor, open_expert_cache,
open_prefix, serve_policies, share_rt_dense_roles,
ExecutorOpening, Policies, Weights, check_open, load_weights, loan_ladder, log_open_inventory, open_executor,
open_expert_cache, open_prefix, serve_policies, share_rt_dense_roles,
};
mod serve_parts;
use serve_parts::{ServeEnv, serve_over_host};
@@ -9,6 +9,28 @@ use leleka_cuda_driver::{OriginalQsaMappedJournal, OriginalQsaResidentIndex};
type QsaOwners<'ctx> = [Option<(OriginalQsaResidentIndex<'ctx>, OriginalQsaMappedJournal<'ctx>)>; 48];
/// The executor, binding, dense cache and session the physical QSA owners go back to when a decode phase ends.
pub(super) struct QsaOwnerHome<'a, 'ctx> {
pub(super) executor: &'a mut OriginalPromptExecutor<'ctx>,
pub(super) binding: &'a ModelBinding,
pub(super) dense: &'a DenseWeightCache<'ctx>,
pub(super) session: &'a mut QwenSession<'ctx>,
}
impl<'ctx> QsaOwnerHome<'_, 'ctx> {
/// Hands the owners back to the executor at the session's lineage.
fn adopt(&mut self, owners: QsaOwners<'ctx>) -> Result<()> {
self.executor.adopt_qsa_owners(self.binding, self.dense, self.session, owners)
}
}
/// The weight cache, VRAM expert cache, CPU pool and residency state the window's expert tier is built over.
pub(super) struct TierResources<'p, 'a, 'ctx> {
pub(super) moe: &'p MoeWeightCache<'ctx>,
pub(super) cache: &'p mut OriginalExpertCache<'ctx>,
pub(super) cpu: &'p mut CpuExpertPool<'a>,
pub(super) state: &'p mut ResidencyState,
}
/// generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel.
pub(super) fn decode_pcie_mode(
config: &StackConfig,
@@ -132,10 +154,7 @@ pub(super) fn return_owners<'a, 'ctx>(
/// The assembly's outcome: the resources, or the failure with the owners given back (or the stack marked broken).
pub(super) fn resolve_assembled<'a, 'ctx>(
assembled: std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>>,
executor: &mut OriginalPromptExecutor<'ctx>,
binding: &ModelBinding,
dense: &DenseWeightCache<'ctx>,
session: &mut QwenSession<'ctx>,
mut home: QsaOwnerHome<'_, 'ctx>,
broken: &mut Option<Error>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, SpecError> {
let lost = match assembled {
@@ -144,7 +163,7 @@ pub(super) fn resolve_assembled<'a, 'ctx>(
};
operator_line("assemble", &lost.failure);
if let Some(owners) = lost.owners {
if let Err(error) = executor.adopt_qsa_owners(binding, dense, session, owners) {
if let Err(error) = home.adopt(owners) {
broken.get_or_insert(error);
}
} else {
@@ -182,12 +201,10 @@ pub(super) fn narrow_window_policy(
/// The window's expert tier over the VRAM cache: the GPU share first, the CPU pool on the rest.
pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>(
binding: &'a ModelBinding,
moe: &'p MoeWeightCache<'ctx>,
cache: &'p mut OriginalExpertCache<'ctx>,
cpu: &'p mut CpuExpertPool<'a>,
state: &'p mut ResidencyState,
resources: TierResources<'p, 'a, 'ctx>,
tier: &ExpertTierConfig,
) -> Result<GpuExpertPool<'p, 'a, 'ctx>> {
let TierResources { moe, cache, cpu, state } = resources;
let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?;
let pcie_num = tier.pcie_num_for(bank.pageable());
let tail_rank = original_serve_residency::effective_tail_rank(&*cache);
@@ -211,25 +228,21 @@ pub(super) fn gpu_expert_pool<'p, 'a, 'ctx>(
/// The end of the decode phase: release the MTP drafter's bindings to this verifier's bank, close the verifier and
/// take the
/// physical QSA owners back at the session's lineage (an abandoned window is rolled back there).
#[allow(clippy::too_many_arguments)]
pub(super) fn teardown_decode<'a, 'ctx>(
resources: DecodeResources<'a, 'ctx>,
outcome: Option<HostOutcome>,
executor: &mut OriginalPromptExecutor<'ctx>,
binding: &ModelBinding,
mut home: QsaOwnerHome<'_, 'ctx>,
context: &'ctx Context<'ctx>,
dense: &DenseWeightCache<'ctx>,
session: &mut QwenSession<'ctx>,
broken: &mut Option<Error>,
) {
release_mtp(executor, binding, broken);
release_mtp(&mut *home.executor, home.binding, broken);
// the card at the end of the decode phase, graph pools and all windows captured: the real low-water mark of a
// request
vram_note(context, "decode end before disassemble");
let p = profile::span("decode.disassemble");
let disassembled = disassemble(resources);
drop(p);
adopt_disassembled(disassembled, (executor, binding, dense, session), broken);
adopt_disassembled(disassembled, home, broken);
if outcome.is_some_and(|o| o.failed) {
broken.get_or_insert(Error::IdentityMismatch);
}
@@ -250,14 +263,13 @@ fn release_mtp(executor: &mut OriginalPromptExecutor<'_>, binding: &ModelBinding
/// The owners the disassembly gave back return to the executor; a lost one marks the stack broken.
fn adopt_disassembled<'ctx>(
disassembled: std::result::Result<QsaOwners<'ctx>, ServeFailure>,
host: (&mut OriginalPromptExecutor<'ctx>, &ModelBinding, &DenseWeightCache<'ctx>, &mut QwenSession<'ctx>),
mut home: QsaOwnerHome<'_, 'ctx>,
broken: &mut Option<Error>,
) {
let (executor, binding, dense, session) = host;
match disassembled {
Ok(owners) => {
let _p = profile::span("decode.adopt");
if let Err(error) = executor.adopt_qsa_owners(binding, dense, session, owners) {
if let Err(error) = home.adopt(owners) {
broken.get_or_insert(error);
}
}
@@ -58,7 +58,8 @@ pub(super) fn load_core<'a, 'ctx>(
let weights = load_weights(binding, context, config, ctx.layout)?;
let mut session = QwenSession::for_binding_on_shared_device(binding, shared);
let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context));
let opened = open_executor(binding, context, config, &weights, &mut session, verifier.0, verifier.1)?;
let opening = ExecutorOpening::new(config, verifier.0, verifier.1);
let opened = open_executor(binding, context, &opening, &weights, &mut session)?;
let (executor, draft) = opened;
let Weights { output, embedding, kar, dense, mut moe } = weights;
share_rt_dense_roles(config, &executor, &mut moe)?;
@@ -281,14 +281,15 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
self.tier.residency.clear_usage();
self.policy.controller = self.policy.settings.controller()?;
match self.expert_cache.as_mut() {
Some(cache) => original_serve_seed::restore_placement(
self.binding,
&self.moe,
cache,
&mut self.pool,
&mut self.tier.residency.spans,
&self.tier.initial_owners,
),
Some(cache) => {
let mut sources = original_serve_seed::SwapSources {
binding: self.binding,
moe: &self.moe,
cpu: &mut self.pool,
known: &mut self.tier.residency.spans,
};
original_serve_seed::restore_placement(&mut sources, cache, &self.tier.initial_owners)
}
None => Ok(0),
}
}
@@ -111,16 +111,13 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> {
dbg_el(),
if assembled.is_ok() { "ok" } else { "ERR" }
);
let executor = &mut *self.owners.executor;
let session = &mut *self.owners.session;
let resources = resolve_assembled(
assembled,
executor,
self.ids.binding,
self.reads.dense,
session,
&mut *self.book.broken,
)?;
let home = QsaOwnerHome {
executor: &mut *self.owners.executor,
binding: self.ids.binding,
dense: self.reads.dense,
session: &mut *self.owners.session,
};
let resources = resolve_assembled(assembled, home, &mut *self.book.broken)?;
self.narrow(resources, used_max_t)
}
@@ -180,9 +177,13 @@ impl<'s, 'a, 'ctx> DecodeView<'s, 'a, 'ctx> {
let channels = (&mut emit, &mut cancel);
let (served, verifier, outcome) = serve_over_host(verifier, host, request, channels, env)?;
let resources = DecodeResources { verifier, qsa, slots };
let (executor, session) = (&mut *self.owners.executor, &mut *self.owners.session);
let (binding, context, dense) = (self.ids.binding, self.ids.context, self.reads.dense);
teardown_decode(resources, outcome, executor, binding, context, dense, session, &mut *self.book.broken);
let home = QsaOwnerHome {
executor: &mut *self.owners.executor,
binding: self.ids.binding,
dense: self.reads.dense,
session: &mut *self.owners.session,
};
teardown_decode(resources, outcome, home, self.ids.context, &mut *self.book.broken);
served
}
}
@@ -206,7 +207,7 @@ fn expert_pool<'q, 'p: 'q, 'a, 'ctx>(
Some(cache) => {
let tier_config = &policy.config.expert_tier;
let (cpu, state) = (&mut *tier.pool, &mut *tier.residency);
let pool = gpu_expert_pool(ids.binding, reads.moe, cache, cpu, state, tier_config);
let pool = gpu_expert_pool(ids.binding, TierResources { moe: reads.moe, cache, cpu, state }, tier_config);
Ok(slot.insert(pool.map_err(SpecError::Forward)?))
}
None => Ok(&mut *tier.pool),
@@ -105,14 +105,13 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
let swaps = original_serve_seed::plan(counts, cache, max, keep);
let planned = self.config.clock.since(started);
let mut report = original_serve_seed::summarize(counts, &swaps);
original_serve_seed::queue_swaps(
self.binding,
&self.moe,
cache,
&mut self.pool,
&mut self.tier.residency.spans,
&swaps,
)?;
let mut sources = original_serve_seed::SwapSources {
binding: self.binding,
moe: &self.moe,
cpu: &mut self.pool,
known: &mut self.tier.residency.spans,
};
original_serve_seed::queue_swaps(&mut sources, cache, &swaps)?;
report.plan_ms = planned.as_secs_f64() * 1e3;
report.queue_ms = (self.config.clock.since(started) - planned).as_secs_f64() * 1e3;
self.tier.residency.add_usage(counts, usage);
@@ -178,19 +178,31 @@ fn load_moe<'ctx>(
Ok(moe)
}
/// How the prompt executor and its MTP drafter are opened: the stack config, the verifier's widest window and the
/// drafter request derived from them.
pub(super) struct ExecutorOpening<'a> {
config: &'a StackConfig,
verifier_max_t: usize,
request: OriginalMtpRequest,
}
impl<'a> ExecutorOpening<'a> {
/// The opening for a verifier of window width `verifier_max_t`; `coupled` is whether the policy is coupled.
pub(super) fn new(config: &'a StackConfig, verifier_max_t: usize, coupled: bool) -> Self {
let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS);
Self { config, verifier_max_t, request }
}
}
/// The prompt executor with its MTP drafter: from the RT directory, or the full MTP owner over the pinned pack.
#[allow(clippy::too_many_arguments)]
pub(super) fn open_executor<'a, 'ctx>(
binding: &'a ModelBinding,
context: &'ctx Context<'ctx>,
config: &StackConfig,
opening: &ExecutorOpening<'_>,
weights: &Weights<'ctx>,
session: &mut QwenSession<'ctx>,
verifier_max_t: usize,
coupled: bool,
) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> {
let Weights { output, embedding, dense, .. } = weights;
let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS);
let (config, request) = (opening.config, &opening.request);
Ok(match &config.rt_directory {
Some(directory) => OriginalPromptExecutor::select_rt_mtp(
binding,
@@ -202,12 +214,10 @@ pub(super) fn open_executor<'a, 'ctx>(
directory,
config.capacity,
true,
&request,
request,
)
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?,
None => {
open_full_mtp_executor(binding, context, session, weights, (config.capacity, verifier_max_t), &request)?
}
None => open_full_mtp_executor(binding, context, session, weights, opening)?,
})
}
@@ -217,11 +227,10 @@ fn open_full_mtp_executor<'a, 'ctx>(
context: &'ctx Context<'ctx>,
session: &mut QwenSession<'ctx>,
weights: &Weights<'ctx>,
sizes: (usize, usize),
request: &OriginalMtpRequest,
opening: &ExecutorOpening<'_>,
) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> {
let Weights { output, embedding, dense, moe, .. } = weights;
let (capacity, verifier_max_t) = sizes;
let (capacity, verifier_max_t, request) = (opening.config.capacity, opening.verifier_max_t, &opening.request);
let mut executor =
OriginalPromptExecutor::new(binding, dense, session, context, moe, embedding, capacity, verifier_max_t, true)
.map_err(at("OriginalPromptExecutor::new"))?;