STRA-338 size: engine split the new helpers further (decode_parts, serve_parts, open_parts, run_parts, generate_fn, generate_mtp); no dyn added

This commit is contained in:
Pavlo Ratushnyi
2026-11-06 14:34:18 +01:00
parent d259125d88
commit 5df0c8b7fc
8 changed files with 289 additions and 159 deletions
@@ -57,6 +57,27 @@ fn emit_token_text<C: Clock>(
Ok(())
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
fn adaptive_prefill_on<C: Clock>(run: &Generation<'_, '_, '_, C>) -> bool {
run.moe_cache.uses_strata_adaptive_experts()
}
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
fn adaptive_prefill_on<C: Clock>(_run: &Generation<'_, '_, '_, C>) -> bool {
false
}
/// The end of the tile that starts at `position`. Keep the last known-next edge and final head in one joint tile.
/// A completed fresh KV warmer cannot admit a second final tile.
fn tile_end<C: Clock>(run: &Generation<'_, '_, '_, C>, span: (usize, usize), adaptive_prefill: bool) -> usize {
let (position, len) = span;
let mut end = position.saturating_add(run.prefill_tile_cap()).min(len);
if adaptive_prefill && len - end == 1 && end - position > 1 {
end -= 1;
}
end
}
/// The prompt's tiles after the retained prefix. Each tile preserves the genuine last-known-next edge. A final tile
/// obtains its actual head product; no intermediate greedy IDs are minted.
fn prefill_tiles<C: Clock>(
@@ -67,21 +88,13 @@ fn prefill_tiles<C: Clock>(
state: (usize, &mut Option<TargetStepProduct>, &mut Vec<u32>),
) -> Result<(), GenerationFailure> {
let (reused, latest, committed) = state;
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
let adaptive_prefill = run.moe_cache.uses_strata_adaptive_experts();
#[cfg(not(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64")))]
let adaptive_prefill = false;
let adaptive_prefill = adaptive_prefill_on(run);
let mut position = reused;
while position < prompt.len() {
if run.clock.since(start) > GENERATION_TIMEOUT {
return Err(unavailable("generation deadline exceeded").into());
}
let mut end = position.saturating_add(run.prefill_tile_cap()).min(prompt.len());
// Keep the last known-next edge and final head in one joint tile.
// A completed fresh KV warmer cannot admit a second final tile.
if adaptive_prefill && prompt.len() - end == 1 && end - position > 1 {
end -= 1;
}
let end = tile_end(run, (position, prompt.len()), adaptive_prefill);
let next = prompt.get(end).copied();
let product = if end - position == 1 && next.is_none() && !adaptive_prefill {
// Other policies keep the original lone-row actual-head producer.
@@ -128,13 +141,31 @@ fn verified_window<C: Clock>(
|| run.clock.since(start) > GENERATION_TIMEOUT
},
)
.map_err(|e| match e {
MtpWindowError::Cancelled if run.clock.since(start) > GENERATION_TIMEOUT => {
GenerationFailure::Backend(unavailable("generation deadline exceeded"))
.map_err(|e| window_failure(run, e, start))
}
fn window_failure<C: Clock>(run: &Generation<'_, '_, '_, C>, e: MtpWindowError, start: Instant) -> GenerationFailure {
match e {
MtpWindowError::Cancelled if run.clock.since(start) > GENERATION_TIMEOUT => {
GenerationFailure::Backend(unavailable("generation deadline exceeded"))
}
MtpWindowError::Cancelled => GenerationFailure::Cancelled,
MtpWindowError::Forward(error) => run.mtp_error(error),
}
}
fn observe_window<C: Clock>(run: &Generation<'_, '_, '_, C>, draft_steps: usize, tokens: &[TokenId], stopped: bool) {
run.observe(|r| {
let mut ids = [0; 4];
if tokens.len() <= ids.len() {
for (slot, token) in ids.iter_mut().zip(tokens) {
*slot = token.get();
}
MtpWindowError::Cancelled => GenerationFailure::Cancelled,
MtpWindowError::Forward(error) => run.mtp_error(error),
})
r.window(draft_steps, &ids[..tokens.len()], stopped);
} else {
r.window(draft_steps, &[u32::MAX; 5], stopped);
}
});
}
/// Commit and emit the tokens of a verified window; returns the product to continue from and whether the window stopped.
@@ -156,17 +187,7 @@ fn commit_window<C: Clock>(
}
let draft_steps = window.draft_steps();
let (tokens, next, stopped) = window.into_parts();
run.observe(|r| {
let mut ids = [0; 4];
if tokens.len() <= ids.len() {
for (slot, token) in ids.iter_mut().zip(&tokens) {
*slot = token.get();
}
r.window(draft_steps, &ids[..tokens.len()], stopped);
} else {
r.window(draft_steps, &[u32::MAX; 5], stopped);
}
});
observe_window(run, draft_steps, &tokens, stopped);
if tokens.is_empty() && !stopped {
return Err(run.mtp_error(crate::qwen_forward::contract::Error::IdentityMismatch));
}
@@ -3,6 +3,7 @@
#[allow(unused_imports)]
use super::*;
use crate::qwen_forward::original_serve_engine::ServeOutcome;
use crate::qwen_forward::original_serve_residency::ResidencyStats;
/// One request over the stack; the caller owns the stream/terminal bookkeeping.
#[allow(clippy::too_many_arguments)]
@@ -145,30 +146,15 @@ fn served_outcome(
fn report_completed(
stack: &impl ServeDevice,
sink: &GenerationSink,
cancelled: &dyn Fn() -> bool,
cancelled: &impl Fn() -> bool,
clock: &impl Clock,
request: &GenerationRequest,
usage: &Usage,
outcome: ServeOutcome,
) -> Result<(), GenerationFailure> {
let (prompt_ms, decode_ms) = stack.last_timing();
leleka_memory::telemetry::request_finished(
usage.input_tokens,
usage.reused_input_tokens,
usage.output_tokens,
prompt_ms,
decode_ms,
);
let tier_stats = stack.expert_tier_stats();
let tier = tier_stats.map(|s| leleka_memory::telemetry::TierCounters {
groups: s.groups,
vram_entries: s.vram_entries,
pcie_entries: s.pcie_entries,
cpu_entries: s.cpu_entries,
adaptations: s.adaptations,
swaps: s.swaps,
});
leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier);
let tier = record_request_telemetry(request, usage, (prompt_ms, decode_ms), (outcome, tier_stats));
emit_event(sink, cancelled, clock, GenerationEvent::Usage(usage.clone()))?;
log_request_end(
&request.request_id,
@@ -179,17 +165,47 @@ fn report_completed(
outcome.rounds as u64,
tier,
);
log_legacy_outcome(stack.reused_tokens(), outcome, tier_stats);
Ok(())
}
/// The request's telemetry: usage and timings, then the round count and the expert tier's share of it.
fn record_request_telemetry(
request: &GenerationRequest,
usage: &Usage,
timing: (f64, f64),
served: (ServeOutcome, Option<ResidencyStats>),
) -> Option<leleka_memory::telemetry::TierCounters> {
let (prompt_ms, decode_ms) = timing;
let (outcome, tier_stats) = served;
leleka_memory::telemetry::request_finished(
usage.input_tokens,
usage.reused_input_tokens,
usage.output_tokens,
prompt_ms,
decode_ms,
);
let tier = tier_stats.map(|s| leleka_memory::telemetry::TierCounters {
groups: s.groups,
vram_entries: s.vram_entries,
pcie_entries: s.pcie_entries,
cpu_entries: s.cpu_entries,
adaptations: s.adaptations,
swaps: s.swaps,
});
leleka_memory::telemetry::request_detail(&request.request_id, outcome.rounds as u64, tier);
tier
}
/// The exact lines scripts/e2e/analyze_session.py parses.
fn log_legacy_outcome(reused: usize, outcome: ServeOutcome, tier_stats: Option<ResidencyStats>) {
if leleka_obs::settings().legacy {
// the exact lines scripts/e2e/analyze_session.py parses
leleka_obs::legacy_line(&format!(
"leleka-serve request outcome=completed produced={} rounds={} reused={}",
outcome.produced,
outcome.rounds,
stack.reused_tokens()
"leleka-serve request outcome=completed produced={} rounds={} reused={reused}",
outcome.produced, outcome.rounds
));
if let Some(stats) = tier_stats {
leleka_obs::legacy_line(&format!("leleka-serve {}", stats.describe()));
}
}
Ok(())
}
@@ -6,6 +6,7 @@ use super::*;
use leleka_backend_api::GenerationStream;
use leleka_cuda_driver::Context;
use std::sync::Arc;
use std::time::Instant;
type Stack<'a, 'ctx> = OriginalServeStack<'a, 'ctx>;
@@ -171,22 +172,27 @@ fn roll_back<'a, 'ctx>(
}
Err(_) => {
env.shared.shutdown.store(true, Ordering::Release);
// No stack is left and none can be built here: end the process a moment after the reply goes out so that the
// supervisor starts a fresh engine instead of keeping a half-dead one.
let _ = writeln!(
std::io::stderr().lock(),
"leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine"
);
thread::spawn(|| {
thread::sleep(Duration::from_secs(2));
std::process::exit(70);
});
return Err(unavailable("reconfigure failed and the previous settings could not be restored"));
return Err(exit_for_restart());
}
}
Ok(())
}
/// No stack is left and none can be built here: end the process a moment after the reply goes out so that the
/// supervisor starts a fresh engine instead of keeping a half-dead one.
fn exit_for_restart() -> BackendError {
use std::io::Write;
let _ = writeln!(
std::io::stderr().lock(),
"leleka-serve: reconfigure and rollback both failed; exiting so that the supervisor restarts the engine"
);
thread::spawn(|| {
thread::sleep(Duration::from_secs(2));
std::process::exit(70);
});
unavailable("reconfigure failed and the previous settings could not be restored")
}
/// Close the old stack and open one with the new settings; on failure the previous settings come back and the reply is the refusal.
fn swap_stack<'a, 'ctx>(
env: &ReopenEnv<'a, 'ctx, '_>,
@@ -239,6 +245,12 @@ pub(super) fn reconfigure<'a, 'ctx>(
}
}
swap_stack(env, live, (next_options, next_context))?;
Ok(publish_effective(env, live, started))
}
/// The new stack serves: ready again, the telemetry carries the effective settings, which are also the reply.
fn publish_effective(env: &ReopenEnv<'_, '_, '_>, live: &Live<'_, '_, '_>, started: Instant) -> String {
use std::io::Write;
env.shared.ready.store(true, Ordering::Release);
leleka_memory::telemetry::set_context_max(u64::from(*live.context_tokens));
let effective = crate::serve_tuning::describe(live.options, *live.context_tokens, *live.workers, None);
@@ -248,7 +260,7 @@ pub(super) fn reconfigure<'a, 'ctx>(
"leleka-serve reconfigure done in {:.1} s",
env.clock.since(started).as_secs_f64()
);
Ok(effective.to_string())
effective.to_string()
}
/// What a generate command reads besides the stack: the loaded model, the tokenizer and the shared flags.
@@ -324,18 +336,21 @@ pub(super) fn serve_generate(
return Ok(());
}
let Some(owner) = stack.as_mut() else {
let failed = GenerationTerminal::Failed {
code: ErrorCode::BackendUnavailable,
message: "Original serve stack is not available".into(),
retryable: false,
};
let _ = emit_terminal(&sink, failed, env.clock);
let _ = emit_terminal(&sink, stack_unavailable(), env.clock);
return Ok(());
};
run_generation(env, owner, (&sink, &cancel), &prompt, &request);
Ok(())
}
fn stack_unavailable() -> GenerationTerminal {
GenerationTerminal::Failed {
code: ErrorCode::BackendUnavailable,
message: "Original serve stack is not available".into(),
retryable: false,
}
}
/// One admitted request: the generation, its terminal event, the prefix summary and the stack's health afterwards.
fn run_generation(
env: &GenerateEnv<'_>,
@@ -9,8 +9,8 @@ use std::time::Instant;
/// One layer group through the expert pool, with the pool's wall time in the window trace. A pool refusal is kept in
/// `pool_error` (it is the cause; the driver error it provokes is its echo).
pub(super) fn run_pool_group<'ctx>(
pool: &mut dyn OriginalServePool<'ctx>,
pub(super) fn run_pool_group<'ctx, P: OriginalServePool<'ctx> + ?Sized>(
pool: &mut P,
group: (OriginalVerifyCpuRows<'_>, &mut OriginalVerifyCpuSink<'_, 'ctx>, &mut OriginalGpuStream<'ctx>),
pool_error: &mut Option<Error>,
) -> std::result::Result<(), leleka_cuda_driver::Error> {
@@ -48,6 +48,27 @@ pub(super) struct RefillOwners<'r, 'ctx> {
pub(super) pending: &'r mut bool,
}
impl<'ctx> RefillOwners<'_, 'ctx> {
/// Queued after assembly's own uploads (canonical GDN image), before the graph capture.
fn queue(&mut self, binding: &ModelBinding, moe: &MoeWeightCache<'ctx>) -> Result<()> {
if !std::mem::take(&mut *self.due) {
return Ok(());
}
if let Some(cache) = self.cache.as_mut() {
let _p = profile::span("prefill.refill");
original_serve_residency::refill_lent(binding, moe, cache, &mut self.residency.spans, true)?;
*self.pending = true;
}
Ok(())
}
}
fn note_window_retry(failed: usize, next: usize) {
operator_text(&format!(
"decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}"
))
}
/// Assemble the verifier over the QSA owners, repeating with the windows that fit when a graph runs out of device memory.
pub(super) fn assemble_decode<'a, 'ctx>(
inputs: &AssembleInputs<'_, 'a, 'ctx>,
@@ -58,41 +79,54 @@ pub(super) fn assemble_decode<'a, 'ctx>(
) -> std::result::Result<(usize, std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>>), SpecError> {
let owners = executor.take_qsa_owners()?;
let p = profile::span("decode.assemble");
// queued after assembly's own uploads (canonical GDN image), before the graph capture
let RefillOwners { due, cache, residency, pending } = refill;
let mut queue_refill = || -> Result<()> {
if !std::mem::take(&mut *due) {
return Ok(());
}
if let Some(cache) = cache.as_mut() {
let _p = profile::span("prefill.refill");
original_serve_residency::refill_lent(inputs.binding, moe, cache, &mut residency.spans, true)?;
*pending = true;
}
Ok(())
};
let mut refill = refill;
let mut queue_refill = || refill.queue(inputs.binding, moe);
// A window or commit graph that does not fit in device memory costs the widest windows, not the request or the engine
// (upstream a8c1d4b7): the assembly is repeated with the windows that fit. The owners come back from each failure.
let mut owners_slot = Some(owners);
let assembled = assemble_with_window_fallback(
verifier_max_t,
|max_t| assemble_attempt(inputs, &mut owners_slot, max_t, &mut queue_refill),
|failed, next| {
operator_text(&format!(
"decode window graphs: out of device memory recording windows up to T={failed}; retrying with windows up to T={next}"
))
},
note_window_retry,
);
drop(p);
Ok(assembled)
}
impl<'a, 'ctx> AssembleInputs<'_, 'a, 'ctx> {
fn assemble(
&self,
owners: QsaOwners<'ctx>,
max_t: usize,
queue_refill: &mut impl FnMut() -> Result<()>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, AssembleFailure<'ctx>> {
let (binding, context, ple_history) = (self.binding, self.context, self.ple_history);
let (weights, output, base) = (self.weights, self.output, self.base);
let (rope, blobs, max_cells, pcie_mode) = (self.rope, self.blobs, self.max_cells, self.pcie_mode);
assemble(
binding,
weights,
context,
output,
base,
owners,
ple_history,
rope,
blobs,
max_t,
max_cells,
pcie_mode,
queue_refill,
)
}
}
/// One assembly attempt at `max_t`; the owners come back from a failure into `owners_slot` when a narrower window may fit.
fn assemble_attempt<'a, 'ctx>(
inputs: &AssembleInputs<'_, 'a, 'ctx>,
owners_slot: &mut Option<QsaOwners<'ctx>>,
max_t: usize,
queue_refill: &mut dyn FnMut() -> Result<()>,
queue_refill: &mut impl FnMut() -> Result<()>,
) -> std::result::Result<DecodeResources<'a, 'ctx>, (AssembleFailure<'ctx>, Option<usize>)> {
let Some(owners) = owners_slot.take() else {
return Err((
@@ -100,22 +134,7 @@ fn assemble_attempt<'a, 'ctx>(
None,
));
};
assemble(
inputs.binding,
inputs.weights,
inputs.context,
inputs.output,
inputs.base,
owners,
inputs.ple_history,
inputs.rope,
inputs.blobs,
max_t,
inputs.max_cells,
inputs.pcie_mode,
queue_refill,
)
.map_err(|mut lost| {
inputs.assemble(owners, max_t, queue_refill).map_err(|mut lost| {
let cap = lost.window_cap.filter(|&cap| cap < max_t);
if cap.is_some() {
*owners_slot = lost.owners.take();
@@ -238,8 +257,21 @@ pub(super) fn teardown_decode<'a, 'ctx>(
session: &mut QwenSession<'ctx>,
broken: &mut Option<Error>,
) {
// The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the
// bank closes (it is shared while they live) and so the next request captures against its own bank.
release_mtp(executor, 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);
if outcome.is_some_and(|o| o.failed) {
broken.get_or_insert(Error::IdentityMismatch);
}
}
/// The MTP drafter's cached round programs and staged window are bound to THIS verifier's bank: release them before the
/// bank closes (it is shared while they live) and so the next request captures against its own bank.
fn release_mtp(executor: &mut OriginalPromptExecutor<'_>, binding: &ModelBinding, broken: &mut Option<Error>) {
let p = profile::span("decode.release_mtp");
let released = executor.mtp_release_verifier(binding);
drop(p);
@@ -247,11 +279,15 @@ pub(super) fn teardown_decode<'a, 'ctx>(
operator_line("release MTP verifier bindings", &failure(error));
broken.get_or_insert(error);
}
// 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);
}
/// 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>),
broken: &mut Option<Error>,
) {
let (executor, binding, dense, session) = host;
match disassembled {
Ok(owners) => {
let _p = profile::span("decode.adopt");
@@ -264,7 +300,4 @@ pub(super) fn teardown_decode<'a, 'ctx>(
broken.get_or_insert(lost.error);
}
}
if outcome.is_some_and(|o| o.failed) {
broken.get_or_insert(Error::IdentityMismatch);
}
}
@@ -8,8 +8,8 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
pub(in super::super) fn decode_phase(
&mut self,
request: &ServeRequest,
emit: &mut dyn FnMut(&[i32]) -> Result<()>,
cancel: &mut dyn FnMut() -> bool,
mut emit: &mut dyn FnMut(&[i32]) -> Result<()>,
mut cancel: &mut dyn FnMut() -> bool,
) -> std::result::Result<ServeOutcome, SpecError> {
let Self {
binding,
@@ -160,7 +160,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
broken,
want_tail,
};
let (served, verifier, outcome) = serve_over_host(verifier, host, request, (emit, cancel), env)?;
let (served, verifier, outcome) = serve_over_host(verifier, host, request, (&mut emit, &mut cancel), env)?;
let resources = DecodeResources { verifier, qsa, slots };
teardown_decode(resources, outcome, executor, binding, context, &*dense, session, broken);
served
@@ -47,6 +47,11 @@ pub(super) fn check_open<'ctx>(
if !std::ptr::eq(context, &**shared) {
return Err(failure(Error::IdentityMismatch));
}
check_model_shape(binding)
}
/// The Original serve stack serves the 48-layer model with its MTP pack only.
fn check_model_shape(binding: &ModelBinding) -> std::result::Result<(), ServeFailure> {
if binding.layer_count() != 48 {
return Err(ServeFailure {
error: Error::IdentityMismatch,
@@ -176,7 +181,7 @@ pub(super) fn open_executor<'a, 'ctx>(
verifier_max_t: usize,
coupled: bool,
) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> {
let Weights { output, embedding, dense, moe, .. } = weights;
let Weights { output, embedding, dense, .. } = weights;
let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, coupled, MTP_RESIDENT_CELLS);
Ok(match &config.rt_directory {
Some(directory) => OriginalPromptExecutor::select_rt_mtp(
@@ -193,26 +198,31 @@ pub(super) fn open_executor<'a, 'ctx>(
)
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?,
None => {
let mut executor = OriginalPromptExecutor::new(
binding,
dense,
session,
context,
moe,
embedding,
config.capacity,
verifier_max_t,
true,
)
.map_err(at("OriginalPromptExecutor::new"))?;
let assembly = OriginalMtpFullOwner::assemble(binding, session, context, moe, embedding, output, &request)
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?;
let draft = executor.install_full_mtp(binding, session, assembly).map_err(at("install_full_mtp"))?;
(executor, draft)
open_full_mtp_executor(binding, context, session, weights, (config.capacity, verifier_max_t), &request)?
}
})
}
/// The executor over the pinned pack's cache with the full MTP owner installed.
fn open_full_mtp_executor<'a, 'ctx>(
binding: &'a ModelBinding,
context: &'ctx Context<'ctx>,
session: &mut QwenSession<'ctx>,
weights: &Weights<'ctx>,
sizes: (usize, usize),
request: &OriginalMtpRequest,
) -> std::result::Result<(OriginalPromptExecutor<'ctx>, OriginalDraftSession<'ctx>), ServeFailure> {
let Weights { output, embedding, dense, moe, .. } = weights;
let (capacity, verifier_max_t) = sizes;
let mut executor =
OriginalPromptExecutor::new(binding, dense, session, context, moe, embedding, capacity, verifier_max_t, true)
.map_err(at("OriginalPromptExecutor::new"))?;
let assembly = OriginalMtpFullOwner::assemble(binding, session, context, moe, embedding, output, request)
.map_err(|e| ServeFailure { error: e.error, detail: e.message })?;
let draft = executor.install_full_mtp(binding, session, assembly).map_err(at("install_full_mtp"))?;
Ok((executor, draft))
}
/// RT-directory draft: the MTP dense roles sit twice in VRAM (this cache's pinned-pack upload and the RT bank's); merge them when proven byte-equal
pub(super) fn share_rt_dense_roles<'ctx>(
config: &StackConfig,
@@ -259,6 +269,11 @@ pub(super) fn open_prefix(config: &StackConfig) -> Option<PrefixServe<StackState
let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident);
let clock = config.clock.clone();
let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity).with_clock(clock);
note_prefix_on(&serve, bytes, available);
Some(serve)
}
fn note_prefix_on(serve: &PrefixServe<StackState, StackBlock>, bytes: u64, available: Option<u64>) {
operator_note(&format!(
"prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}",
serve.block_tokens(),
@@ -268,7 +283,6 @@ pub(super) fn open_prefix(config: &StackConfig) -> Option<PrefixServe<StackState
available.map(|b| b >> 20),
crate::prefix_cache::summary::hex(serve.namespace())
));
Some(serve)
}
/// The VRAM expert tier and the number of its last slots the prompt path borrows (`None`: it allocates its own buffers).
@@ -293,16 +307,7 @@ pub(super) fn open_expert_cache<'ctx>(
original_serve_residency::loan_slots(&cache, prefill_bytes(layout).map_err(at("prefill bytes"))?)
.map_err(at("expert-cache loan"))?;
}
operator_note(&format!(
"expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)",
cache.slots(),
cache.bytes() as f64 / f64::from(1u32 << 30),
if cache.per_layer_admission() { "per layer" } else { "global" },
match loan {
Some(k) => format!("borrows its last {k} slots"),
None => "allocates its own buffers".to_owned(),
}
));
note_expert_cache(&cache, filled, loan);
Some(cache)
}
None => None,
@@ -310,6 +315,19 @@ pub(super) fn open_expert_cache<'ctx>(
Ok((expert_cache, loan))
}
fn note_expert_cache(cache: &OriginalExpertCache<'_>, filled: usize, loan: Option<usize>) {
operator_note(&format!(
"expert cache {} slots ({:.2} GiB, {}), {filled} filled from the profile; the prompt path {}; GPU experts round differently from the CPU's (bench/results/2026-09-27-cache-parity)",
cache.slots(),
cache.bytes() as f64 / f64::from(1u32 << 30),
if cache.per_layer_admission() { "per layer" } else { "global" },
match loan {
Some(k) => format!("borrows its last {k} slots"),
None => "allocates its own buffers".to_owned(),
}
));
}
/// Smaller loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`), ascending by rows; empty when the ladder is off.
pub(super) fn loan_ladder(
config: &StackConfig,
@@ -31,7 +31,7 @@ pub(super) fn serve_over_host<'a, 'ctx>(
verifier: Verifier<'a, 'ctx>,
host: Result<OriginalServeHost<'_, 'ctx>>,
request: &ServeRequest,
channels: (&mut dyn FnMut(&[i32]) -> Result<()>, &mut dyn FnMut() -> bool),
channels: (&mut impl FnMut(&[i32]) -> Result<()>, &mut impl FnMut() -> bool),
mut env: ServeEnv<'_, 'ctx>,
) -> std::result::Result<Served<'a, 'ctx>, SpecError> {
let host = match host {
@@ -60,7 +60,7 @@ pub(super) fn serve_over_host<'a, 'ctx>(
fn run_engine<P: OriginalServePort>(
engine: &mut OriginalServeEngine<P>,
request: &ServeRequest,
channels: (&mut dyn FnMut(&[i32]) -> Result<()>, &mut dyn FnMut() -> bool),
channels: (&mut impl FnMut(&[i32]) -> Result<()>, &mut impl FnMut() -> bool),
env: &mut ServeEnv<'_, '_>,
) -> std::result::Result<ServeOutcome, SpecError> {
let (emit, cancel) = channels;
@@ -86,17 +86,23 @@ fn run_engine<P: OriginalServePort>(
)
});
drop(serve_span);
{
// the controller's round counters belong to this request in every window policy
let stats = controller.take_stats();
if super::super::super::original_spec_controller::stats_enabled() {
eprintln!("DBG spec-stats arm={} {}", env.arm_label, stats.line());
}
note_request_end(controller, env.arm_label, &result);
result
}
/// The controller's round counters belong to this request in every window policy.
fn note_request_end(
controller: &mut OriginalSpecController,
arm_label: &str,
result: &std::result::Result<ServeOutcome, SpecError>,
) {
let stats = controller.take_stats();
if super::super::super::original_spec_controller::stats_enabled() {
eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line());
}
if let Err(e) = &result {
if let Err(e) = result {
crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el());
}
result
}
/// After the request: the GPU profile line, then the state settle that the conversation cache or the prefix tail needs.
@@ -111,6 +117,19 @@ fn settle_served<'a, 'ctx>(
if !gpu_profile.is_empty() {
eprintln!("DBG verify-profile:{gpu_profile}");
}
let (live, tail) = settle_wanted(host, result, env);
if !((result.is_ok() && env.config.settle_state) || live || tail) {
return;
}
settle_state_into(verifier, host, env, (live, tail));
}
/// Whether the session can be continued as is (`live`: conversation cache) and whether the prefix tail checkpoints (`tail`).
fn settle_wanted(
host: &OriginalServeHost<'_, '_>,
result: &std::result::Result<ServeOutcome, SpecError>,
env: &ServeEnv<'_, '_>,
) -> (bool, bool) {
// conversation cache: the session can be continued as is only when the draft ring
// stands at its position (then its recurrent state is settled to match)
let live =
@@ -122,9 +141,17 @@ fn settle_served<'a, 'ctx>(
"prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode",
);
}
if !((result.is_ok() && env.config.settle_state) || live || tail) {
return;
}
(live, tail)
}
/// Settle the verifier's recurrent state into the session and note what the settled session is good for.
fn settle_state_into<'a, 'ctx>(
verifier: &mut Verifier<'a, 'ctx>,
host: &mut OriginalServeHost<'_, 'ctx>,
env: &mut ServeEnv<'_, 'ctx>,
wanted: (bool, bool),
) {
let (live, tail) = wanted;
match host.settle_state(verifier) {
Ok(()) if live => {
if let Some(conversation) = env.conversation.as_mut() {