diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs index 03668390..5ac09933 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_residency.rs @@ -155,6 +155,10 @@ pub(crate) struct ExpertTierConfig { /// `_SEED_DECAY`: at each prompt chunk the earlier chunks' counts are multiplied by this (1 = a plain sum over the /// prompt, 0 = the last chunk alone): the end of a long prompt predicts the answer better than its beginning. pub(crate) seed_decay: f32, + /// `_SEED_MAX_ROWS`: no seed for a prompt whose prefill routed more than this many rows through the experts (0 = no cap). The + /// prompt's top experts cover only 9-10 % of the decode routing at 16k tokens (docs/original-serve.md), and a 100k+ prompt + /// replaces a good starting set with a worse one. + pub(crate) seed_max_rows: usize, } impl ExpertTierConfig { pub(crate) fn off() -> Self { @@ -179,6 +183,7 @@ impl ExpertTierConfig { seed_keep: 0.0, seed_usage: 0.0, seed_decay: 1.0, + seed_max_rows: 0, } } /// The tier is on with a slot count or a profile. @@ -260,6 +265,10 @@ impl ExpertTierConfig { // Default ON (operator decision: long-running agent sessions; a fresh process starts from the prompt's own // routing). `LELEKA_ORIGINAL_SERVE_SEED=off` restores the plain profile start. config.seed_swaps = super::original_serve_seed::DEFAULT_SEED_SWAPS; + // ... but not for a long prompt: at 45k-247k tokens the seed replaced the ranked profile's set by the prompt's top experts and cost 25-35 % of + // decode (STRA-245 decode gap, `r-prof` against `r-prof-noseed`: VRAM share 80-85 % against 93-96 %, 107-110 against 135-149 tok/s). Up to + // `DEFAULT_SEED_MAX_ROWS` prompt rows the seed behaves as before; `LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS=0` removes the cap. + config.seed_max_rows = super::original_serve_seed::DEFAULT_SEED_MAX_ROWS; if let Some(v) = var("SEED") { config.seed_swaps = match v.as_str() { "off" | "no" | "0" => 0, @@ -276,6 +285,9 @@ impl ExpertTierConfig { if let Some(v) = var("SEED_DECAY") { config.seed_decay = v.parse().map_err(|_| Error::InvalidDimension)?; } + if let Some(v) = var("SEED_MAX_ROWS") { + config.seed_max_rows = v.parse().map_err(|_| Error::InvalidDimension)?; + } config.validate()?; Ok(config) } diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs index a6bff6dc..185adbf6 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_seed.rs @@ -1,192 +1,196 @@ -//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing. -//! -//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time -//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement -//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert -//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`). -//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the -//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive -//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy -//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them. -//! -//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an -//! experiment can compare first-request behaviour with and without the seed inside one process. -use super::{ - contract::{Error, Result}, - moe_weight_cache::MoeWeightCache, - original_serve_pool::CpuExpertPool, - original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap}, - original_serve_verifier::driver_error, -}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_cuda_driver::OriginalExpertCache; -use leleka_model_format::qwen4exp::ResidentExpertBankSpan; -use std::rc::Rc; - -const LAYERS: usize = 48; -const EXPERTS: usize = 512; - -/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides). -pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096; - -/// One request's seed, for the operator's lines and the experiments. -#[derive(Clone, Copy, Debug, Default, PartialEq)] -pub(crate) struct SeedReport { - /// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed. - pub(crate) rows: u64, - pub(crate) planned: usize, - pub(crate) plan_ms: f64, - pub(crate) queue_ms: f64, - /// Sum of the swaps' gains (routed rows won) and the most any layer changed. - pub(crate) gain: f64, - pub(crate) max_layer_swaps: usize, -} - -/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every -/// resident expert (the blend with the profile's placement). -pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec { - let mut usage: Vec = counts.to_vec(); - if keep > 0.0 { - for layer in 0..LAYERS { - for expert in 0..EXPERTS { - if cache.resident_slot(layer, expert).is_some() { - usage[layer * EXPERTS + expert] += keep; - } - } - } - } - choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) -} - -/// 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>, - cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, - swaps: &[Swap], -) -> Result<()> { - let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; - let mut layer_swaps: Vec> = vec![Vec::new(); LAYERS]; - for swap in swaps { - layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap); - } - for (layer, group) in layer_swaps.iter().enumerate() { - if group.is_empty() { - continue; - } - let incoming: Vec = group.iter().map(|s| s.incoming as u32).collect(); - let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, 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))?; - } - } - cache.arm_swaps().map_err(|e| driver_error(&e)) -} - -/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot): -/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order. -/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a -/// cycle is broken through one temporary expert. Returns the swaps made. -pub(super) fn restore_placement<'ctx>( - binding: &ModelBinding, - moe: &MoeWeightCache<'ctx>, - cache: &mut OriginalExpertCache<'ctx>, - cpu: &mut CpuExpertPool<'_>, - known: &mut SpanCache, - initial: &[Option<(usize, usize)>], -) -> Result { - let mut made = 0usize; - for _round in 0..64 { - cache.wait_swaps().map_err(|e| driver_error(&e))?; - let mut mapped = vec![false; LAYERS * EXPERTS]; - for slot in 0..cache.slots() { - if let Some((layer, expert)) = cache.slot_owner(slot) { - mapped[layer * EXPERTS + expert] = true; - } - } - let mut swaps = Vec::new(); - let mut stuck = None; - for (slot, target) in initial.iter().enumerate() { - let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue }; - if have == want { - continue; - } - if mapped[layer * EXPERTS + want] { - stuck.get_or_insert((layer, have)); - continue; - } - swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have }); - mapped[layer * EXPERTS + have] = false; - mapped[layer * EXPERTS + want] = true; - } - if swaps.is_empty() { - let Some((layer, have)) = stuck else { return Ok(made) }; - // only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest - let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?; - swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have }); - } - made += swaps.len(); - queue_swaps(binding, moe, cache, cpu, known, &swaps)?; - } - Err(Error::IdentityMismatch) -} - -/// The report of a planned batch (`rows`: from the counts). -pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport { - let mut per_layer = [0usize; LAYERS]; - for swap in swaps { - per_layer[swap.layer] += 1; - } - SeedReport { - rows: (counts.iter().map(|&c| f64::from(c)).sum::() / (10 * LAYERS) as f64).round() as u64, - planned: swaps.len(), - plan_ms: 0.0, - queue_ms: 0.0, - gain: swaps.iter().map(|s| f64::from(s.gain)).sum(), - max_layer_swaps: per_layer.into_iter().max().unwrap_or(0), - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn the_report_counts_prompt_rows_and_the_busiest_layer() { - let mut counts = vec![0f32; LAYERS * EXPERTS]; - // 3 rows routed to 10 experts in every layer - for layer in 0..LAYERS { - for expert in 0..10 { - counts[layer * EXPERTS + expert] = 3.0; - } - } - let swaps = [ - Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 }, - Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 }, - Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 }, - ]; - let report = summarize(&counts, &swaps); - assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2)); - assert_eq!(report.gain, 15.5); - assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0); - } - - #[test] - fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() { - let mut usage = vec![0.0f32; LAYERS * EXPERTS]; - // layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows) - for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] { - usage[3 * EXPERTS + e] = u; - } - let resident = |l: usize, e: usize| l == 3 && e < 2; - let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS); - // (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops - assert_eq!(swaps.len(), 1); - assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0)); - } -} +//! ON by default when the configuration is read from the environment (`LELEKA_ORIGINAL_SERVE_SEED=off` disables; formerly experimental): residency seeded from the prompt's own routing. +//! +//! The Original's adaptive tier learns which experts to keep in VRAM from the verified windows, a few rounds at a time +//! (`ADAPT_EVERY` rounds, at most `ADAPT_SWAPS` swaps), so a first request decodes on the starting profile's placement +//! while the adaptation catches up. The prompt's prefill already knows, per layer, how many of its rows each expert +//! served (the MoE stage reads the route IDs on the host to group the rows by expert, `OriginalMoePromptLayer::counts`). +//! This module adds that signal to the placement: at the end of the prompt phase, after the lent slots are refilled, the +//! most-routed missing experts of every layer replace the least-routed resident ones (the same ranking as the adaptive +//! tier, `choose_swaps`, with the prompt's counts as the usage) in ONE batch of swaps queued on the tier's own copy +//! stream. The verifier assembly that follows overlaps the copies; the first round's `apply_pending` lands them. +//! +//! Also here: `restore_placement`, which puts the tier back on the starting profile's set between requests, so an +//! experiment can compare first-request behaviour with and without the seed inside one process. +use super::{ + contract::{Error, Result}, + moe_weight_cache::MoeWeightCache, + original_serve_pool::CpuExpertPool, + original_serve_residency::{choose_swaps, source_spans, SpanCache, Swap}, + original_serve_verifier::driver_error, +}; +use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_cuda_driver::OriginalExpertCache; +use leleka_model_format::qwen4exp::ResidentExpertBankSpan; +use std::rc::Rc; + +const LAYERS: usize = 48; +const EXPERTS: usize = 512; + +/// What `LELEKA_ORIGINAL_SERVE_SEED=on` allows: every slot may change (the ranking's own gain floor decides). +pub(crate) const DEFAULT_SEED_SWAPS: usize = 4096; + +/// The longest prompt (rows routed through the experts by this request's prefill) that is still seeded by default: the "agent-sized prompts up to a few +/// thousand tokens" of docs/original-serve.md. Longer prompts measured worse than no seed on the ranked upstream profile. +pub(crate) const DEFAULT_SEED_MAX_ROWS: usize = 4096; + +/// One request's seed, for the operator's lines and the experiments. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) struct SeedReport { + /// Routed (layer, row) entries counted, divided by the layers and the top-k: the prompt rows the prefill routed. + pub(crate) rows: u64, + pub(crate) planned: usize, + pub(crate) plan_ms: f64, + pub(crate) queue_ms: f64, + /// Sum of the swaps' gains (routed rows won) and the most any layer changed. + pub(crate) gain: f64, + pub(crate) max_layer_swaps: usize, +} + +/// The seed's swaps: `counts[layer * 512 + expert]` are the prompt's routed rows per expert, `keep` a credit for every +/// resident expert (the blend with the profile's placement). +pub(super) fn plan(counts: &[f32], cache: &OriginalExpertCache<'_>, max_swaps: usize, keep: f32) -> Vec { + let mut usage: Vec = counts.to_vec(); + if keep > 0.0 { + for layer in 0..LAYERS { + for expert in 0..EXPERTS { + if cache.resident_slot(layer, expert).is_some() { + usage[layer * EXPERTS + expert] += keep; + } + } + } + } + choose_swaps(&usage, |layer, expert| cache.resident_slot(layer, expert).is_some(), max_swaps) +} + +/// 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>, + cache: &mut OriginalExpertCache<'ctx>, + cpu: &mut CpuExpertPool<'_>, + known: &mut SpanCache, + swaps: &[Swap], +) -> Result<()> { + let bank = moe.original_expert_bank().ok_or(Error::IdentityMismatch)?; + let mut layer_swaps: Vec> = vec![Vec::new(); LAYERS]; + for swap in swaps { + layer_swaps.get_mut(swap.layer).ok_or(Error::InvalidExpert)?.push(swap); + } + for (layer, group) in layer_swaps.iter().enumerate() { + if group.is_empty() { + continue; + } + let incoming: Vec = group.iter().map(|s| s.incoming as u32).collect(); + let spans: Vec<[ResidentExpertBankSpan; 3]> = source_spans(cpu, &bank, moe, binding, 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))?; + } + } + cache.arm_swaps().map_err(|e| driver_error(&e)) +} + +/// Put the tier back on the starting placement `initial` (every slot's owner right after the profile fill, by slot): +/// the same expert in the same slot, so a run after a restore cannot differ from a run in a new process by slot order. +/// Swaps are queued in rounds and awaited (blocking); a slot whose target is still held by another slot waits for it, and a +/// cycle is broken through one temporary expert. Returns the swaps made. +pub(super) fn restore_placement<'ctx>( + binding: &ModelBinding, + moe: &MoeWeightCache<'ctx>, + cache: &mut OriginalExpertCache<'ctx>, + cpu: &mut CpuExpertPool<'_>, + known: &mut SpanCache, + initial: &[Option<(usize, usize)>], +) -> Result { + let mut made = 0usize; + for _round in 0..64 { + cache.wait_swaps().map_err(|e| driver_error(&e))?; + let mut mapped = vec![false; LAYERS * EXPERTS]; + for slot in 0..cache.slots() { + if let Some((layer, expert)) = cache.slot_owner(slot) { + mapped[layer * EXPERTS + expert] = true; + } + } + let mut swaps = Vec::new(); + let mut stuck = None; + for (slot, target) in initial.iter().enumerate() { + let (Some((layer, want)), Some((_, have))) = (*target, cache.slot_owner(slot)) else { continue }; + if have == want { + continue; + } + if mapped[layer * EXPERTS + want] { + stuck.get_or_insert((layer, have)); + continue; + } + swaps.push(Swap { gain: 0.0, layer, incoming: want, outgoing: have }); + mapped[layer * EXPERTS + have] = false; + mapped[layer * EXPERTS + want] = true; + } + if swaps.is_empty() { + let Some((layer, have)) = stuck else { return Ok(made) }; + // only cycles are left: move one slot to an expert nobody holds, the next round resolves the rest + let temporary = (0..EXPERTS).find(|&e| !mapped[layer * EXPERTS + e]).ok_or(Error::IdentityMismatch)?; + swaps.push(Swap { gain: 0.0, layer, incoming: temporary, outgoing: have }); + } + made += swaps.len(); + queue_swaps(binding, moe, cache, cpu, known, &swaps)?; + } + Err(Error::IdentityMismatch) +} + +/// The report of a planned batch (`rows`: from the counts). +pub(super) fn summarize(counts: &[f32], swaps: &[Swap]) -> SeedReport { + let mut per_layer = [0usize; LAYERS]; + for swap in swaps { + per_layer[swap.layer] += 1; + } + SeedReport { + rows: (counts.iter().map(|&c| f64::from(c)).sum::() / (10 * LAYERS) as f64).round() as u64, + planned: swaps.len(), + plan_ms: 0.0, + queue_ms: 0.0, + gain: swaps.iter().map(|s| f64::from(s.gain)).sum(), + max_layer_swaps: per_layer.into_iter().max().unwrap_or(0), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_report_counts_prompt_rows_and_the_busiest_layer() { + let mut counts = vec![0f32; LAYERS * EXPERTS]; + // 3 rows routed to 10 experts in every layer + for layer in 0..LAYERS { + for expert in 0..10 { + counts[layer * EXPERTS + expert] = 3.0; + } + } + let swaps = [ + Swap { gain: 4.0, layer: 2, incoming: 1, outgoing: 2 }, + Swap { gain: 2.5, layer: 2, incoming: 3, outgoing: 4 }, + Swap { gain: 9.0, layer: 7, incoming: 5, outgoing: 6 }, + ]; + let report = summarize(&counts, &swaps); + assert_eq!((report.rows, report.planned, report.max_layer_swaps), (3, 3, 2)); + assert_eq!(report.gain, 15.5); + assert_eq!(summarize(&counts, &[]).max_layer_swaps, 0); + } + + #[test] + fn the_seed_ranking_is_the_adaptive_tiers_with_the_prompts_counts() { + let mut usage = vec![0.0f32; LAYERS * EXPERTS]; + // layer 3: resident 0 (never routed by the prompt) and 1 (routed 6 times); candidates 20 (9 rows), 21 (2 rows) + for (e, u) in [(1, 6.0), (20, 9.0), (21, 2.0)] { + usage[3 * EXPERTS + e] = u; + } + let resident = |l: usize, e: usize| l == 3 && e < 2; + let swaps = choose_swaps(&usage, resident, DEFAULT_SEED_SWAPS); + // (20 over 0): gain 9; (21 over 1): 2 < 6 + 1.5 stops + assert_eq!(swaps.len(), 1); + assert_eq!((swaps[0].layer, swaps[0].incoming, swaps[0].outgoing), (3, 20, 0)); + } +} diff --git a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs index 3b1467c2..f84bf597 100644 --- a/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs +++ b/crates/leleka-runtime/src/qwen_forward/original_serve_stack.rs @@ -1,1964 +1,1974 @@ -//! The Original serving stack: every model-lifetime owner of the `generate.cpp` mode17 serve path, opened -//! once, and the per-request flow over them (prompt conditioning with the batched Original prefill, then the -//! verified-window decode with MTP drafting). -//! -//! Lifetime of the pieces: the dense weights, the MoE arena cache, the native head/embedding, the target -//! session, the prompt executor (which owns the MTP actor and the twelve resident QSA layers), the MTP draft -//! session, the prefill arena, the penalty-history stage and the PLE history image live as long as the -//! stack. Each request resets them to the empty prompt (the checkpoints taken at load, re-stamped onto the -//! current branch generation), conditions the prompt through the executor, and then hands the QSA owners to a -//! freshly assembled native Verifier for the decode phase; the verifier is closed and the owners are taken -//! back afterwards (see `original_serve_verifier`). With `StackConfig::conversation` set, generate.cpp's -//! conversation cache decides where a request starts reading instead (`original_serve_conversation`); -//! without it every request starts at position 0. -//! -//! With `StackConfig::expert_tier` on, the stack also owns the VRAM expert tier (`original_serve_residency`): -//! the cache is opened last, filled from the profile, lent to the prompt path for each chunk and refilled -//! before the decode phase (on every exit path), whose windows compute the resident experts on the GPU. -//! -//! Nothing here computes a model number. Where an asset or a producer the Original needs is not available the -//! error comes from its owner and is surfaced untouched (`ServeFailure`). -use super::{ - contract::{Error, Result}, - dense_weight_cache::DenseWeightCache, - executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor}, - kar_ple_cache::KarPleCache, - moe_weight_cache::MoeWeightCache, - original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, - original_serve_config::{expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants}, - original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome}, - original_serve_host::{HostOwners, OriginalServeHost, RequestSampling}, - original_serve_native::NativeServePort, - original_serve_pool::{CpuExpertPool, OriginalServePool}, - original_serve_profile as profile, - original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState}, - original_serve_seed::{self, SeedReport}, - original_serve_request::{run_request, RequestOwners, ServeError, ServeRequest}, - original_serve_verifier::{assemble, disassemble, seed_ple_history, DecodeResources, ServeFailure, VerifyWeights, PLE_HISTORY_BYTES}, - original_spec_controller::{OriginalSpecController, SpecError}, - output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, - session::{ - original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, - QwenSession, - }, -}; -use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; -use crate::model_binding::qwen4exp_input::ModelBinding; -use leleka_context::memory_plan::KvFormat; -use leleka_cuda_driver::{ - Context, DeviceBuffer, NativeHeadDispatch, OriginalExpertCache, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, - OriginalPrefillArena, OriginalVerifyExpertFormats, PLE_SCRATCH_BYTES, PrefillLayoutOptions, -}; -use std::{path::PathBuf, rc::Rc, time::Instant}; - -/// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. -macro_rules! staged { - ($name:expr, $ctx:expr, $body:expr) => {{ - let __stage = crate::memory_governor::begin($name, Some($ctx)); - let __result = $body; - crate::memory_governor::end(__stage, Some($ctx)); - __result - }}; -} - -#[path = "original_serve_conversation.rs"] -mod conversation; -pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; -use conversation::{ResumeDevice, ServeConversation}; - -#[path = "original_serve_prefix.rs"] -mod prefix; -pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; -use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; -use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; - -/// Stage marks of one request's time to first token (milliseconds since `serve` was entered). -#[derive(Clone, Copy, Debug)] -struct TtftMarks { - started: Option, - resumed: f64, - prefilled: f64, - assembled: f64, - first_round: f64, -} -impl Default for TtftMarks { - fn default() -> Self { - Self { started: None, resumed: f64::NAN, prefilled: f64::NAN, assembled: f64::NAN, first_round: f64::NAN } - } -} -impl TtftMarks { - fn start() -> Self { - Self { started: Some(Instant::now()), ..Self::default() } - } - fn since(&self) -> f64 { - self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) - } - fn as_array(&self) -> [f64; 4] { - [self.resumed, self.prefilled, self.assembled, self.first_round] - } -} - -/// The digest of the pinned model's first shard: part of the prefix cache's namespace. -const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; - -/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. -pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; -/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU -/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at -/// 8192) and a hardware run settles the default. -pub(crate) const DEFAULT_CAPACITY: usize = 2048; -/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells. -const MTP_RESIDENT_CELLS: u64 = 20_480; -const CPU_WORKERS: i32 = 15; -const VOCABULARY: u32 = 248_320; - -/// Operator-visible choices of the stack. -#[derive(Clone, Debug)] -pub(crate) struct StackConfig { - pub(crate) capacity: usize, - /// The request ceiling (`--max-context`): at most the process serving cell count. - pub(crate) max_context: i64, - /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. - pub(crate) rt_directory: Option, - pub(crate) coupled: bool, - pub(crate) cpu_workers: i32, - /// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by - /// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer). - pub(crate) settle_state: bool, - /// `--kv`: QSA K/V storage. Only `int8` (the production `--kv int8`) has sealed owners; fp16, q4_0 and - /// k8v4 are refused (docs/kv-streaming.md). - pub(crate) kv_format: KvFormat, - /// `--kv-resident N`: cells of each QSA layer kept in VRAM, the rest streamed from pinned host memory - /// (raised to 20480; 0 = the whole context). Default 32768, the window every earlier build used. - pub(crate) kv_resident: usize, - /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's - /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. - pub(crate) conversation: Option, - /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the - /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint - /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation - /// cache in charge. - pub(crate) prefix: Option, - /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, - /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. - pub(crate) expert_tier: ExpertTierConfig, - /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). - pub(crate) loan_tiers: bool, -} -impl StackConfig { - pub(crate) fn new(max_context: i64) -> Self { - Self { - capacity: DEFAULT_CAPACITY, - max_context, - rt_directory: None, - coupled: OriginalServeSettings::coupled_from_environment(), - // LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15) - // LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware; - // docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other) - cpu_workers: std::env::var("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").ok().and_then(|v| v.parse().ok()).filter(|n| (1..=64).contains(n)).unwrap_or_else(|| { - if std::env::var("LELEKA_CPU_POOL_PLAN").is_ok_and(|v| v == "on") { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS } - }), - settle_state: false, - kv_format: KvFormat::Int8, - kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, - conversation: Some(ConversationConfig::original()), - prefix: None, - expert_tier: ExpertTierConfig::off(), - loan_tiers: loan_tiers_enabled(), - } - } - /// The streamed KV of this configuration (`None` when the window is not servable). - pub(crate) fn kv_footprint(&self) -> Option { - leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() - } - pub(crate) fn validate(&self) -> Result<()> { - if self.kv_format != KvFormat::Int8 { - return Err(Error::Unsupported(super::contract::Stage::Session)); - } - if !ADMITTED_CAPACITIES.contains(&self.capacity) - || self.kv_footprint().is_none() - || self.capacity > 8192 - || self.max_context < 1 - || self.max_context as u64 > super::contract::serving_cells() - || !(1..=64).contains(&self.cpu_workers) - { - return Err(Error::InvalidDimension); - } - if let Some(conversation) = &self.conversation { - conversation.validate()?; - } - if let Some(prefix) = &self.prefix { - prefix.validate(self.capacity)?; - } - self.expert_tier.validate() - } -} - -/// Bytes the prompt path's buffers need at `options.capacity` (what a loan must cover). -fn prefill_bytes(options: PrefillLayoutOptions) -> Result { - let carve = options.carve().map_err(|e| super::original_serve_verifier::driver_error(&e))?; - Ok(carve.borrowed_bytes.max(carve.source_bytes_needed)) -} - -/// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. -#[derive(Clone, Copy, Debug)] -struct LoanTier { - rows: usize, - layout: PrefillLayoutOptions, - slots: usize, -} - -/// Chunk sizes (rows) that get their own, smaller loan below the configured capacity. -const LOAN_TIER_ROWS: [usize; 2] = [512, 2048]; - -/// The smallest rung of the ladder that holds a chunk of `count` rows (`None`: the full loan). -fn tier_for(tiers: &[LoanTier], count: usize) -> Option<&LoanTier> { - tiers.iter().find(|t| count <= t.rows) -} - -/// `LELEKA_PREFILL_LOAN_TIERS=1` turns the ladder on. It is OFF by default until the real-model identity gate (job p34: the final residual R of -/// every chunk equal with and without the ladder) and the paired A/B (job p35) have run (docs/prefill-throughput.md). -fn loan_tiers_enabled() -> bool { - std::env::var("LELEKA_PREFILL_LOAN_TIERS").is_ok_and(|v| v == "1" || v == "on") -} - -/// One conversation checkpoint of the stack: the session's Original checkpoint and the draft ring's snapshot, -/// taken together at a published prompt-chunk boundary. -struct StackPoint<'ctx> { - session: OriginalSessionCheckpoint<'ctx>, - draft: OriginalDraftCheckpoint, -} - -/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. -struct StackState { - session: ParkedSession, - draft: OriginalDraftCheckpoint, -} -impl ByteSize for StackState { - fn byte_size(&self) -> usize { - self.session.host_bytes() + self.draft.host_bytes() - } -} -/// The K/V cells and index rows of one block of the twelve resident QSA layers. -struct StackBlock(ParkedBlock); -impl ByteSize for StackBlock { - fn byte_size(&self) -> usize { - self.0.host_bytes() - } -} -/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). -const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); -/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). -const PARKED_STATE_ESTIMATE: usize = 120 << 20; - -fn plan_error(error: PlanError) -> Error { - match error { - PlanError::InvalidInput => Error::InvalidDimension, - PlanError::Overflow => Error::Overflow, - } -} - -pub(crate) struct OriginalServeStack<'a, 'ctx> { - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - config: StackConfig, - settings: OriginalServeSettings, - max_cells: usize, - rope: RopeConstants, - blobs: ExpertBlobSizes, - formats: OriginalVerifyExpertFormats, - full_policy: OriginalMtpFullPolicy, - scalar_policy: OriginalMtpScalarPolicy, - controller: OriginalSpecController, - /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned - /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. - parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, - arm_label: String, - arm_order: Vec, - verifier_max_t: usize, - /// Why the stack can serve no more (a lost physical owner); `None` while healthy. - broken: Option, - // The empty-prompt lineage taken at load: the reset target of every request. - empty_session: OriginalSessionCheckpoint<'ctx>, - empty_draft: OriginalDraftCheckpoint, - /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). - conversation: Option>>, - /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. - prefix: Option>, - /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). - tail_consumed: Option>, - /// Prompt tokens the last request did not read again. - reused: usize, - /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). - resume_point: usize, - // Owners, dependents first (fields drop in declaration order). - history: OriginalNativePenaltyHistory<'ctx>, - ple_history: DeviceBuffer<'ctx>, - ple_scratch: DeviceBuffer<'ctx>, - /// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead. - arena: Option>, - layout: PrefillLayoutOptions, - /// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts - /// that survive requests. - expert_cache: Option>, - loan: Option, - /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most - /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few - /// hundred slots, not the 1.9 GB of an 8192-row arena. - loan_tiers: Vec, - residency: ResidencyState, - /// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`). - initial_owners: Vec>, - /// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made. - seed_report: Option, - /// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line). - seed_counts: Option>, - /// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any - /// window reads the cache; every other user of the cache waits inside its own entry points. - refill_pending: bool, - /// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake - /// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA). - refill_due: bool, - /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). - timing: (f64, f64), - /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). - marks: TtftMarks, - executor: OriginalPromptExecutor<'ctx>, - draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, - session: QwenSession<'ctx>, - pool: CpuExpertPool<'a>, - kar: Option>, - moe: MoeWeightCache<'ctx>, - dense: DenseWeightCache<'ctx>, - output: OriginalNativeOutput<'ctx>, - embedding: OriginalPromptEmbedding<'ctx>, -} - -fn failure(error: Error) -> ServeFailure { - ServeFailure::from(error) -} - -/// Name the startup step in a refusal so a failed open says where it stopped. -fn at>(step: &'static str) -> impl FnOnce(E) -> ServeFailure { - move |error| { - let mut failure: ServeFailure = error.into(); - failure.detail = Some(match failure.detail.take() { - Some(detail) => format!("{step}: {detail}"), - None => format!("{step}: {:?}", failure.error), - }); - failure - } -} - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at - /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP - /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the - /// very context `context` borrows. - pub(crate) fn open( - binding: &'a ModelBinding, - context: &'ctx Context<'ctx>, - shared: Rc>, - config: StackConfig, - ) -> std::result::Result { - crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); - config.validate().map_err(at("config.validate"))?; - // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) - leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { - error: Error::InvalidDimension, - detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), - })?; - if let Some(footprint) = config.kv_footprint() { - operator_note(&footprint.to_string()); - } - if !std::ptr::eq(context, &*shared) { - return Err(failure(Error::IdentityMismatch)); - } - if binding.layer_count() != 48 { - return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); - } - if !binding.has_mtp() { - return Err(ServeFailure { - error: Error::Unsupported(super::contract::Stage::Session), - detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), - }); - } - let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; - let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); - let mut arm_label = String::from("env"); - let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); - let mut parked = Vec::new(); - let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); - let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); - if let Some(((label, first), rest)) = arms.split_first() { - settings = *first; - arm_label = label.clone(); - for (label, s) in rest { - parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); - } - } - let controller = settings.controller().map_err(at("settings.controller"))?; - let rope = RopeConstants::from_serving_context(); - let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; - let formats = expert_formats(binding).map_err(at("expert_formats"))?; - let layout = prefill_layout_options(config.capacity, max_cells, &blobs); - - vram_note(context, "open begin"); - let embedding = staged!("embedding table", context, OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?); - let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); - let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { - Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), - None => None, - }); - let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); - let moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); - vram_note(context, "after embedding, output, kar, dense, moe arena"); - let mut session = QwenSession::for_binding_on_shared_device(binding, shared); - let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); - let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); - let (executor, draft) = match &config.rt_directory { - Some(directory) => OriginalPromptExecutor::select_rt_mtp( - binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, - ) - .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, - None => { - let mut executor = OriginalPromptExecutor::new( - binding, &dense, &mut 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) - } - }; - vram_note(context, "after prompt executor and draft"); - let mut executor = executor; - crate::memory_governor::end(executor_stage, Some(context)); - // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers - // after the cache when it cannot borrow them; without the tier the order is unchanged. - let tier = config.expert_tier.enabled(); - let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); - vram_note(context, "before cache"); - let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); - let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; - let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; - let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); - let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); - let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); - let prefix = match &config.prefix { - Some(prefix_config) => { - let available = crate::conversation::memory::available_memory(); - // the budget comes from the memory governor (what is left above the floors), not from an independent default - let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; - let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) - .unwrap_or_else(|| prefix_config.resolve_budget(available)); - let mut prefix_config = prefix_config.clone(); - if let Some(g) = leleka_memory::Governor::global() { - // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) - prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); - } - let prefix_config = &prefix_config; - if bytes == 0 { - operator_note(&format!( - "prefix cache off (budget {:?}, available host memory {:?} MiB)", - prefix_config.budget, - available.map(|b| b >> 20) - )); - None - } else { - let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); - let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); - operator_note(&format!( - "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", - serve.block_tokens(), - bytes >> 20, - PARKED_STATE_ESTIMATE >> 20, - PARKED_BYTES_PER_TOKEN, - available.map(|b| b >> 20), - crate::prefix_cache::summary::hex(serve.namespace()) - )); - Some(serve) - } - } - None => None, - }; - let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; - let residency = ResidencyState::new(&config.expert_tier); - report_kernel_selection(); - vram_note(context, "before expert tier"); - let mut loan = None; - let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); - let expert_cache = match tier_open { - Some((cache, filled)) => { - if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { - loan = 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(), - } - )); - Some(cache) - } - None => None, - }; - vram_note(context, "after expert tier"); - let mut loan_tiers: Vec = Vec::new(); - if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { - for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { - let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; - let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; - if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { - loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); - } - } - if !loan_tiers.is_empty() { - operator_note(&format!( - "prompt loan ladder: {}, up to {} rows {full} slots", - loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), - config.capacity - )); - } - } - let initial_owners: Vec> = expert_cache - .as_ref() - .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) - .unwrap_or_default(); - if arena.is_none() && loan.is_none() { - arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); - } - let this = Self { - binding, - context, - conversation, - prefix, - tail_consumed: None, - reused: 0, - resume_point: 0, - full_policy: mtp_full_policy(&rope), - scalar_policy: mtp_scalar_policy(&rope), - config, - settings, - max_cells, - rope, - blobs, - formats, - controller, - parked, - arm_label, - arm_order, - verifier_max_t, - broken: None, - empty_session, - empty_draft, - history, - ple_history, - ple_scratch, - arena, - layout, - expert_cache, - loan, - loan_tiers, - residency, - initial_owners, - seed_report: None, - seed_counts: None, - refill_pending: false, - refill_due: false, - timing: (0.0, 0.0), - marks: TtftMarks::default(), - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - embedding, - }; - this.register_memory_classes(); - crate::memory_governor::post_open(); - if let Some(governor) = leleka_memory::Governor::global() { - governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): -{}", governor.inventory().table())); - governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): -{}", governor.ledger().table())); - governor.publish(); - } - Ok(this) - } - - /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. - pub(crate) fn health(&self) -> Option { - self.broken - } - - /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. - pub(crate) fn serve( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - self.apply_memory_directive(); - self.marks = TtftMarks::start(); - let max_context = self.config.max_context; - let result = run_request(self, request, max_context, emit, cancel); - self.note_memory(); - result - } - - /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the - /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. - fn apply_memory_directive(&mut self) { - let Some(governor) = leleka_memory::Governor::global() else { return }; - let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); - let directive = governor.directive(used); - if let Some(prefix) = self.prefix.as_mut() { - let before = prefix.bytes(); - let freed = prefix.apply_shed(directive.prefix_budget, governor); - if freed > 0 { - operator_note(&format!( - "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", - directive.level.as_str(), - freed >> 20, - before >> 20, - prefix.bytes() >> 20, - prefix.budget_bytes() >> 20 - )); - } - } - if directive.drop_conversation - && let Some(conversation) = self.conversation.as_mut() - && conversation.checkpoint_count() > 0 - { - conversation.invalidate(); - operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); - } - } - - /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). - fn note_memory(&self) { - if leleka_memory::Governor::global().is_none() { - return; - } - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); - if let Some(g) = leleka_memory::Governor::global() { - g.note_prefix_used(prefix.bytes() as u64); - } - } - if let Some(conversation) = self.conversation.as_ref() { - crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); - } - } - - /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). - fn register_memory_classes(&self) { - use leleka_memory::{Space, When}; - let Some(governor) = leleka_memory::Governor::global() else { return }; - let _ = governor; - if let Some(f) = self.config.kv_footprint() { - crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); - crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); - crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); - } - if let Ok(bytes) = prefill_bytes(self.layout) { - crate::memory_governor::account( - "prefill", - if self.loan.is_some() { "arena_borrowed" } else { "arena" }, - Space::Device, - When::Startup, - if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, - if self.loan.is_some() { 0 } else { bytes as u64 }, - ); - } - if let Some(cache) = self.expert_cache.as_ref() { - crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); - } - crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); - crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); - if let Some(prefix) = self.prefix.as_ref() { - crate::memory_governor::account( - "prefix", - "store", - Space::HostPageable, - When::Elastic, - "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", - prefix.bytes() as u64, - ); - } - if self.conversation.is_some() { - crate::memory_governor::account( - "conversation", - "checkpoints", - Space::HostPageable, - When::Elastic, - "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", - 0, - ); - } - } - - /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. - #[allow(dead_code)] - pub(crate) fn spec_arms(&self) -> Vec { - self.arm_order.clone() - } - /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. - #[allow(dead_code)] - pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { - if self.arm_label == label { - return true; - } - let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; - let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); - let old_label = std::mem::replace(&mut self.arm_label, new_label); - let old_settings = std::mem::replace(&mut self.settings, new_settings); - let old_controller = std::mem::replace(&mut self.controller, new_controller); - self.parked.push((old_label, old_settings, old_controller)); - true - } - /// The live arm's own request floor, if its label pinned one (`fixed4@0`). - #[allow(dead_code)] - pub(crate) fn spec_arm_min_p(&self) -> Option { - self.settings.request_min_p - } - #[allow(dead_code)] - pub(crate) fn spec_arm(&self) -> &str { - &self.arm_label - } - - /// Wall-clock milliseconds of the last request's prompt phase and decode phase. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn last_timing(&self) -> (f64, f64) { - self.timing - } - - /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the - /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; - /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical - /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. - #[allow(dead_code)] - pub(crate) fn ttft_marks(&self) -> [f64; 4] { - self.marks.as_array() - } - - /// The VRAM expert tier's counters (`None` when the tier is off). - pub(crate) fn expert_tier_stats(&self) -> Option { - self.expert_cache.as_ref().map(|cache| { - let mut stats = self.residency.stats; - stats.swaps = cache.swaps(); - stats - }) - } - - /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the - /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). - #[allow(dead_code)] - pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { - &mut self.config.expert_tier - } - - /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). - #[allow(dead_code)] - pub(crate) fn last_seed(&self) -> Option { - self.seed_report - } - - /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. - #[allow(dead_code)] - pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { - self.residency.round_marks() - } - - /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and - /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. - #[allow(dead_code)] - pub(crate) fn reset_expert_tier(&mut self) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - self.residency.clear_usage(); - self.controller = self.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.residency.spans, &self.initial_owners), - None => Ok(0), - } - } - - /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). - pub(crate) fn reused_tokens(&self) -> usize { - self.reused - } - - /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless - /// `STRATA_CKPT_REREAD` re-read that prefix from 0). - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn resume_point(&self) -> usize { - self.resume_point - } - - /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. - #[cfg_attr(not(test), allow(dead_code))] - pub(crate) fn forget_conversation(&mut self) { - if let Some(conversation) = self.conversation.as_mut() { - conversation.invalidate(); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.invalidate(); - } - } - - /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix - /// cache (the reference a cached request must reproduce). - #[allow(dead_code)] - pub(crate) fn prefix_bypass(&mut self, bypass: bool) { - if let Some(prefix) = self.prefix.as_mut() { - prefix.set_bypass(bypass); - } - } - - /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. - pub(crate) fn prefix_expire_idle(&mut self) -> usize { - self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) - } - - /// The prefix cache's summary for a front router (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { - self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) - } - - /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. - #[allow(dead_code)] - pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { - self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) - } - - /// The prefix cache's metrics line (`None` when the cache is off). - #[allow(dead_code)] - pub(crate) fn prefix_metrics(&self) -> Option { - self.prefix.as_ref().map(|prefix| prefix.describe()) - } - - /// Bytes the prefix cache holds now (0 when it is off). - #[allow(dead_code)] - pub(crate) fn prefix_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) - } - - /// The prefix cache's current byte budget (0 when it is off or fully shed). - #[allow(dead_code)] - pub(crate) fn prefix_budget_bytes(&self) -> usize { - self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) - } - - /// Close every owner in dependency order; the first failure is reported after all were attempted. - pub(crate) fn close(self) -> Result<()> { - let Self { - conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, - moe, dense, output, embedding, .. - } = self; - drop(conversation); - // the span cache retains registered-source spans of the bank `moe` closes below - drop(residency); - let mut first: Option = None; - let mut note = |result: Result<()>| { - if let Err(error) = result { - first.get_or_insert(error); - } - }; - note(history.close()); - note(ple_history.release().map_err(|_| Error::CudaExecution)); - note(ple_scratch.release().map_err(|_| Error::CudaExecution)); - drop(arena); - if let Some(cache) = expert_cache { - note(cache.close().map_err(|e| super::original_serve_verifier::driver_error(&e))); - } - note(executor.close()); - note(draft.close()); - drop((session, pool, kar)); - note(moe.close()); - note(dense.close()); - note(output.close()); - note(embedding.close()); - first.map_or(Ok(()), Err) - } - - fn mark_broken(&mut self, error: Error) { - self.broken.get_or_insert(error); - } - - /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. - fn decode_phase( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - let Self { - binding, - context, - config, - settings, - max_cells, - rope, - blobs, - formats, - full_policy, - controller, - arm_label, - verifier_max_t, - history, - ple_history, - ple_scratch, - executor, - draft, - session, - pool, - kar, - moe, - dense, - output, - broken, - conversation, - expert_cache, - residency, - refill_pending, - refill_due, - marks, - prefix, - tail_consumed, - .. - } = self; - let binding: &ModelBinding = *binding; - let context: &'ctx Context<'ctx> = *context; - if controller.is_failed() { - // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost - *controller = settings.controller()?; - } - crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); - let sampling = RequestSampling::new(request.params, request.path)?; - let n = request.prompt.len(); - let base = session.original_verified_base()?; - crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); - if base.position != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. - let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { - (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { - config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( - super::contract::Stage::Session, - ))? - } - _ => 0, - }; - let p = profile::span("decode.seed_ple"); - seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; - drop(p); - // the window reads the shared experts of all 48 layers in place: load/refresh them together first - let p = profile::span("decode.shared"); - let shared = moe.ensure_original_verify_shared(binding)?; - drop(p); - crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); - let owners = executor.take_qsa_owners()?; - let ple_history: &DeviceBuffer<'ctx> = &*ple_history; - let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; - let p = profile::span("decode.assemble"); - // queued after assembly's own uploads (canonical GDN image), before the graph capture - let mut queue_refill = || -> Result<()> { - if !std::mem::take(&mut *refill_due) { - return Ok(()); - } - if let Some(cache) = expert_cache.as_mut() { - let _p = profile::span("prefill.refill"); - original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; - *refill_pending = true; - } - Ok(()) - }; - let assembled = assemble( - binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells, - pcie_mode, &mut queue_refill, - ); - drop(p); - marks.assembled = marks.since(); - // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them - // before a window or the tier's own bookkeeping touches the cache - if std::mem::take(refill_pending) { - if let Some(cache) = expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - broken.get_or_insert(error); - if let Ok(resources) = assembled { - let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); - } - return Err(SpecError::Forward(error)); - } - } - } - vram_note(context, "decode after assemble"); - crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); - let resources = match assembled { - Ok(resources) => resources, - Err(lost) => { - operator_line("assemble", &lost.failure); - if let Some(owners) = lost.owners { - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } else { - broken.get_or_insert(Error::IdentityMismatch); - } - return Err(SpecError::Forward(lost.failure.error)); - } - }; - let DecodeResources { verifier, qsa, slots } = resources; - // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) - qsa.set_window_snapshots(settings.nan_guard.retries > 0); - let committed = request.prompt[..n - 1].to_vec(); - // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. - let mut gpu_pool; - let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { - (Some(cache), Some(bank)) => { - let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); - let tail_rank = original_serve_residency::effective_tail_rank(&*cache); - let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; - gpu_pool = GpuExpertPool { - binding, - moe: &*moe, - cache, - bank, - cpu: &mut *pool, - state: &mut *residency, - pcie_num, - adapt_every: config.expert_tier.adapt_every, - adapt_swaps: config.expert_tier.adapt_swaps as usize, - tail_rank, - pcie_locked, - }; - &mut gpu_pool - } - (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), - (None, _) => &mut *pool, - }; - let owners = HostOwners { - binding, - dense: &*dense, - context, - session: &mut *session, - draft: &mut *draft, - executor: &mut *executor, - kar: kar.as_mut(), - history: &mut *history, - pool, - qsa: Rc::clone(&qsa), - slots, - ple_history, - policy: &*full_policy, - }; - let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); - controller.set_final_draft(want_tail); - *tail_consumed = None; - let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); - let (served, verifier, outcome) = match host { - Err(error) => (Err(SpecError::Forward(error)), verifier, None), - Ok(host) => { - let port = super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); - let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); - match engine { - Err(error) => { - // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. - let _ = error; - broken.get_or_insert(Error::IdentityMismatch); - return Err(SpecError::Forward(Error::IdentityMismatch)); - } - Ok(mut engine) => { - crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); - let started = Instant::now(); - let serve_span = profile::span("decode.serve"); - let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { - serve_request( - controller, - &mut engine, - &request.prompt, - request.max_new, - request.spec_min_p, - &request.eos, - |tokens| { - if marks.first_round.is_nan() { - marks.first_round = marks.since(); - } - emit(tokens) - }, - &mut *cancel, - || started.elapsed().as_secs_f64() * 1e3, - ) - }); - drop(serve_span); - { - // the controller's round counters belong to this request in every window policy - let stats = controller.take_stats(); - if super::original_spec_controller::stats_enabled() { - eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); - } - } - if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } - let (mut verifier, mut host) = engine.into_port().0.into_parts(); - // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) - let gpu_profile = verifier.profile_report(); - if !gpu_profile.is_empty() { - eprintln!("DBG verify-profile:{gpu_profile}"); - } - // 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 = conversation.is_some() - && matches!(result, Ok(_) | Err(SpecError::Cancelled)) - && host.draft_in_step(); - // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) - let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); - if want_tail && result.is_ok() && !tail { - operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); - } - if (result.is_ok() && config.settle_state) || live || tail { - match host.settle_state(&mut verifier) { - Ok(()) if live => { - if let Some(conversation) = conversation.as_mut() { - conversation.note_live(host.committed().to_vec()); - } - } - Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), - Ok(()) => {} - Err(error) => { - broken.get_or_insert(error); - } - } - } - let outcome = host.finish(); - (result, verifier, Some(outcome)) - } - } - } - }; - // 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. - let p = profile::span("decode.release_mtp"); - let released = executor.mtp_release_verifier(binding); - drop(p); - if let Err(error) = released { - operator_line("release MTP verifier bindings", &failure(error)); - broken.get_or_insert(error); - } - // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at - // the session's lineage; an abandoned window is rolled back there. - let p = profile::span("decode.disassemble"); - let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); - drop(p); - match disassembled { - Ok(owners) => { - let _p = profile::span("decode.adopt"); - if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { - broken.get_or_insert(error); - } - } - Err(lost) => { - operator_line("disassemble", &lost); - broken.get_or_insert(lost.error); - } - } - if outcome.is_some_and(|o| o.failed) { - broken.get_or_insert(Error::IdentityMismatch); - } - served - } - - /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time - /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` - /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache - /// takes its periodic and turn/root checkpoints. - /// - /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk - /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode - /// phase, whatever the read's outcome (generate.cpp `refill`). - fn prefill_phase( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - self.residency.begin_request(); - self.seed_report = None; - if let Some(cache) = self.expert_cache.as_mut() { - let _p = profile::span("prefill.wait_swaps"); - cache.wait_swaps().map_err(|e| SpecError::Forward(super::original_serve_verifier::driver_error(&e)))?; - } - // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) - let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); - if seeding { - self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); - } - let p = profile::span("prefill.read"); - let read = self.prefill_actions(request, resume, cancel); - drop(p); - let _p = profile::span("prefill.refill"); - // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the - // decode phase's host-side assembly - // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) - let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); - let refilled = match (self.loan, self.expert_cache.as_mut()) { - (Some(_), Some(cache)) if !defer => { - original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) - } - _ => Ok(()), - }; - let routing = if seeding { self.moe.take_prompt_routing() } else { None }; - let seeded = match (&read, &refilled, routing) { - (Ok(()), Ok(()), Some(counts)) if !defer => { - let _p = profile::span("prefill.seed"); - self.seed_residency(&counts) - } - _ => Ok(()), - }; - self.refill_due = defer; - match (read, refilled, seeded) { - (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { - self.mark_broken(error); - Err(SpecError::Forward(error)) - } - (read, _, _) => read, - } - } - - /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). - fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { - let tier = &self.config.expert_tier; - let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); - let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; - let started = Instant::now(); - let swaps = original_serve_seed::plan(counts, cache, max, keep); - let planned = started.elapsed(); - let mut report = original_serve_seed::summarize(counts, &swaps); - original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; - report.plan_ms = planned.as_secs_f64() * 1e3; - report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; - self.residency.add_usage(counts, usage); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - eprintln!( - "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", - report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms - ); - } - self.seed_report = Some(report); - if std::env::var_os("LELEKA_SEED_TRACE").is_some() { - self.seed_counts = Some(counts.to_vec()); - } - Ok(()) - } - - /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident - /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the - /// profile) and the best any static set could do (the decode's own top experts). - fn seed_coverage_trace(&mut self) { - let Some(prompt) = self.seed_counts.take() else { return }; - let usage = self.residency.usage(); - if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { - return; - } - let mut slots = [0usize; 48]; - let mut initial = vec![false; 48 * 512]; - for &(layer, expert) in self.initial_owners.iter().flatten() { - slots[layer] += 1; - initial[layer * 512 + expert] = true; - } - let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); - if total <= 0.0 { - return; - } - let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); - for layer in 0..48 { - let range = layer * 512..(layer + 1) * 512; - let mut order: Vec = (0..512).collect(); - order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); - by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); - let mut best: Vec = usage[range.clone()].to_vec(); - best.sort_by(|a, b| b.total_cmp(a)); - oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); - by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); - } - // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. - eprintln!( - "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", - 100.0 * by_initial / total, - 100.0 * by_prompt / total, - 100.0 * oracle / total - ); - } - - fn prefill_actions( - &mut self, - request: &ServeRequest, - resume: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let binding: &ModelBinding = self.binding; - let n = request.prompt.len(); - crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); - // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's - // sampling parameters configure the actor for the whole request. - let mtp_setup_span = profile::span("prefill.mtp_setup"); - self.executor.set_mtp_prompt_len(binding, n as i64)?; - self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; - self.executor.set_mtp_draft_sampling(binding, &request.params)?; - drop(mtp_setup_span); - if n < 2 { - return Ok(()); - } - let setup_span = profile::span("prefill.setup"); - let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); - let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; - let options = PromptOptions { - context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, - prompt_cache: false, - turn_token: None, - root_min: 0, - // every conditioning read goes through the batched prefill (the verify-window read of short - // prompts needs the verifier during the prompt phase; see the open items) - short_read: 64, - force_batched: true, - verify_width: 4, - auto_max: 8192, - grid: 0, - }; - let (options, reread_to) = match (&self.prefix, &self.conversation) { - // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens - // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the - // capacity allows: its states are not grid-canonical anyway) - (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), - (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), - (None, None) => (options, None), - }; - let capacity = self.config.capacity; - let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; - crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); - drop(setup_span); - for action in plan { - crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); - if action.path == PromptPath::FinalSeed { - // the last prompt token is the first verify input of the decode phase - break; - } - let PromptPath::Batched { .. } = action.path else { - return Err(Error::IdentityMismatch.into()); - }; - if self.session.target_origin()?.next_position() != action.first as u64 { - return Err(Error::IdentityMismatch.into()); - } - if cancel() { - return Err(SpecError::Cancelled); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.before_chunk(action.first); - } - self.prefill_chunk(&source, action.count, cancel)?; - self.after_prompt_action(&request.prompt, &action); - self.prefix_after_chunk(&request.prompt, action.first + action.count); - } - if self.session.target_origin()?.next_position() != (n as u64 - 1) { - return Err(Error::IdentityMismatch.into()); - } - self.prefix_after_prefill(&request.prompt); - Ok(()) - } - - /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. - /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent - /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. - fn prefill_chunk( - &mut self, - source: &Rc, - count: usize, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let Self { - binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, - scalar_policy, .. - } = self; - let mut chunk = PromptChunk { - binding: *binding, - executor: &mut *executor, - dense: &*dense, - session: &mut *session, - source, - kar: kar.as_mut(), - moe: &mut *moe, - draft: &mut *draft, - embedding: &*embedding, - scalar_policy: &*scalar_policy, - }; - let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); - super::prefill_profile::begin_chunk(); - let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { - (Some(slots), Some(cache), _) => match { - let _span = super::prefill_profile::span(super::prefill_profile::Stage::Lend, None); - // the smallest rung of the ladder that holds the chunk - let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); - cache.lend_prefill_tail(slots, options) - } { - Ok(mut lent) => chunk.run(count, &mut lent, cancel), - Err(e) => Err(SpecError::Forward(super::original_serve_verifier::driver_error(&e))), - }, - (_, _, Some(own)) => chunk.run(count, own, cancel), - _ => Err(Error::IdentityMismatch.into()), - }; - if ran.is_ok() { - super::prefill_profile::end_chunk(first, count); - } - ran - } - - /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of - /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. - fn prefix_after_prefill(&mut self, prompt: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_prefill"); - match prefix.after_prefill(self, prompt) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), - } - self.prefix = Some(prefix); - } - - /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the - /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. - fn prefix_after_decode(&mut self, consumed: &[i32]) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_decode"); - match prefix.after_decode(self, consumed) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), - Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), - } - self.prefix = Some(prefix); - } - - /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint - /// that cannot be built costs the cache, never the request. - fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { - let Some(mut prefix) = self.prefix.take() else { return }; - let _span = profile::span("prefix.after_chunk"); - match prefix.after_chunk(self, prompt, end) { - Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { - operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); - } - } - Ok(other) => { - if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { - operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); - } - } - Err(error) => { - operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); - prefix.invalidate(); - } - } - self.prefix = Some(prefix); - } - - /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation - /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next - /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. - fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { - let Some(mut conversation) = self.conversation.take() else { return }; - if let Ok(position) = ResumeDevice::position(self) { - let in_step = ResumeDevice::live_in_step(self); - if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { - operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); - } - } - self.conversation = Some(conversation); - } - - /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs - /// the cache, never the request: the cache is dropped and the request goes on. - fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { - let Some(mut conversation) = self.conversation.take() else { return }; - let _span = profile::span("conv.after_action"); - if let Err(error) = conversation.after_action(self, prompt, action) { - operator_text(&format!("conversation cache: {error}; dropping the cache")); - conversation.invalidate(); - } - self.conversation = Some(conversation); - } -} - -/// The owners one batched prompt chunk needs, so the chunk runs over the stack's own buffers or a loan. -struct PromptChunk<'s, 'ctx> { - binding: &'s ModelBinding, - executor: &'s mut OriginalPromptExecutor<'ctx>, - dense: &'s DenseWeightCache<'ctx>, - session: &'s mut QwenSession<'ctx>, - source: &'s Rc, - kar: Option<&'s mut KarPleCache<'ctx>>, - moe: &'s mut MoeWeightCache<'ctx>, - draft: &'s mut super::session::original_prompt::draft::OriginalDraftSession<'ctx>, - embedding: &'s OriginalPromptEmbedding<'ctx>, - scalar_policy: &'s OriginalMtpScalarPolicy, -} -impl<'ctx> PromptChunk<'_, 'ctx> { - fn run( - &mut self, - count: usize, - arena: &mut OriginalPrefillArena<'_, 'ctx>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result<(), SpecError> { - let pending = self.executor.forward( - self.binding, - self.dense, - &mut *self.session, - self.source, - count, - self.kar.as_deref_mut(), - &mut *self.moe, - &mut *arena, - &mut *self.draft, - self.embedding, - self.scalar_policy, - || cancel(), - ); - if let Err(e) = &pending { crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); } - let pending = match pending { - Ok(pending) => pending, - Err(error) if cancel() => { - let _ = error; - return Err(SpecError::Cancelled); - } - Err(error) => return Err(SpecError::Forward(error)), - }; - crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); - let _span = super::prefill_profile::span(super::prefill_profile::Stage::Publish, None); - pending.publish()?; - crate::bringup_trace!("DBG[{:.0}s] published", dbg_el()); - Ok(()) - } -} - -static DBG_T0: std::sync::OnceLock = std::sync::OnceLock::new(); -/// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. -/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). -fn vram_note(context: &Context<'_>, label: &str) { - if profile::enabled() { - if let Ok((free, total)) = context.memory_info() { - eprintln!("DBG vram {label}: free {} MiB of {} MiB", free >> 20, total >> 20); - } - } -} -pub(crate) fn dbg_el() -> f32 { - DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32() -} - -/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only). -fn report_kernel_selection() { - #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] - for line in leleka_native_cpu_expert::cpu_kernel_report() { - operator_note(&line); - } - for line in leleka_cuda_driver::gpu_kernel_report() { - operator_note(&line); - } -} - -fn operator_note(text: &str) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}"); -} - -fn operator_line(what: &str, failure: &ServeFailure) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); -} - -fn operator_text(line: &str) { - use std::io::Write; - let _ = writeln!(std::io::stderr().lock(), "leleka-serve {line}"); -} - -/// The conversation cache's device side over the stack's own owners. -impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { - type Point = StackPoint<'ctx>; - fn zero(&mut self) -> Result<()> { - if RequestOwners::is_fresh(self) { - return Ok(()); - } - RequestOwners::reset(self) - } - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - fn save(&mut self) -> Result> { - if let Some(error) = self.broken { - return Err(error); - } - let session = self.executor.checkpoint_session(self.binding, &mut self.session)?; - let draft = self.draft.checkpoint(self.binding, &self.session)?; - Ok(StackPoint { session, draft }) - } - fn point_position(point: &StackPoint<'ctx>) -> u64 { - point.session.next_position() - } - fn restore(&mut self, point: &StackPoint<'ctx>) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - // a refused re-stamp touches nothing; a failed physical restore poisons the executor - let rebased = point.session.rebased_onto_current(&self.session)?; - let restored = self.executor.restore_session(self.binding, &self.dense, &mut self.session, &rebased); - if let Err(error) = restored { - self.mark_broken(error); - } - restored - } - fn restore_draft(&mut self, point: &StackPoint<'ctx>, resume: usize) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let result = (|| { - self.draft.resume_at(self.binding, &self.dense, &self.session, &point.draft)?; - let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; - self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } - fn live_in_step(&self) -> bool { - self.broken.is_none() - && self.session.original_state_lag().is_none() - && self.draft.in_step(self.binding, &self.session) - } -} - -impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { - /// `RequestOwners::resume` with the prefix cache: install the deepest checkpoint that is a prefix of the prompt. - fn prefix_resume(&mut self, request: &ServeRequest) -> Option { - let mut prefix = self.prefix.take()?; - let _resume_span = profile::span("request.resume"); - let n = request.prompt.len(); - let resume = if self.broken.is_some() { - prefix.invalidate(); - None - } else { - match prefix.begin(self, &request.prompt) { - Ok(Some(start)) => { - self.reused = start.resume; - self.resume_point = start.resume; - operator_text(&format!( - "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", - start.resume, - start.switched, - start.branch, - start.copied_tokens, - start.import_ms, - prefix.last_import_split().0, - prefix.last_import_split().1, - start.match_us, - prefix.live_tokens() - )); - Some(start.resume) - } - Ok(None) => { - operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); - None - } - Err(error) => { - // the cache is an optimisation: drop it and start from the empty prompt (`reset`) - operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); - prefix.invalidate(); - None - } - } - }; - self.prefix = Some(prefix); - resume - } -} - -/// The prefix cache's device side over the stack's own owners. -impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { - type State = StackState; - type Block = StackBlock; - fn position(&self) -> Result { - Ok(self.session.target_origin()?.next_position()) - } - fn estimate(&self, block_tokens: usize) -> (usize, usize) { - (PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN) - } - fn park_state(&mut self) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_state"); - let session = self.executor.park_session(self.binding, &mut self.session)?; - let draft = self.draft.checkpoint(self.binding, &self.session)?; - Ok(StackState { session, draft }) - } - fn park_block(&mut self, first: usize, tokens: usize) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_block"); - self.executor.park_block(&self.session, first, tokens).map(StackBlock) - } - fn park_tail(&mut self, first: usize, tokens: usize) -> Result { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("prefix.park_tail"); - self.executor.park_block(&self.session, first, tokens).map(StackBlock) - } - fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); - let _p = profile::span("prefix.import_session"); - // a refused import touches nothing; a failed physical one poisons the executor - let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); - if let Err(error) = imported { - self.mark_broken(error); - } - imported - } - fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> { - if let Some(error) = self.broken { - return Err(error); - } - let result = (|| { - { - let _p = profile::span("prefix.draft_resume_at"); - self.draft.resume_at(self.binding, &self.dense, &self.session, &state.draft)?; - } - let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; - let _p = profile::span("prefix.mtp_kv_restore"); - self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } -} - -impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { - fn is_fresh(&self) -> bool { - self.broken.is_none() - && self.session.original_state_lag().is_none() - && self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0) - } - fn reset(&mut self) -> std::result::Result<(), Error> { - if let Some(error) = self.broken { - return Err(error); - } - let _p = profile::span("request.reset"); - let result = (|| { - let empty = self.empty_session.rebased_empty(&self.session)?; - self.executor.restore_session(self.binding, &self.dense, &mut self.session, &empty)?; - self.draft.reset_to_empty(self.binding, &self.dense, &self.session, &self.empty_draft) - })(); - if let Err(error) = result { - self.mark_broken(error); - } - result - } - fn resume(&mut self, request: &ServeRequest) -> Option { - self.reused = 0; - self.resume_point = 0; - if self.prefix.is_some() { - return self.prefix_resume(request); - } - let mut conversation = self.conversation.take()?; - let _resume_span = profile::span("request.resume"); - let resume = if self.broken.is_some() { - conversation.invalidate(); - None - } else { - match conversation.begin(self, &request.prompt) { - Ok(start) => { - self.reused = start.read_from; - self.resume_point = start.resume; - Some(start.resume) - } - Err(error) => { - // the cache is an optimisation: drop it and start from the empty prompt (`reset`) - operator_text(&format!("conversation cache: {error}; reading the whole prompt")); - conversation.invalidate(); - None - } - } - }; - self.conversation = Some(conversation); - resume - } - fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { - let started = Instant::now(); - self.timing = (0.0, 0.0); - self.marks.resumed = self.marks.since(); - let result = self.prefill_phase(request, resume, cancel); - if matches!(result, Err(SpecError::Cancelled)) { - self.keep_conversation_after_cancelled_prefill(request); - } - self.marks.prefilled = self.marks.since(); - self.timing.0 = started.elapsed().as_secs_f64() * 1e3; - result - } - fn decode( - &mut self, - request: &ServeRequest, - emit: &mut dyn FnMut(&[i32]) -> Result<()>, - cancel: &mut dyn FnMut() -> bool, - ) -> std::result::Result { - let started = Instant::now(); - let tier0 = self.residency.stats; - let result = self.decode_phase(request, emit, cancel); - match (result.is_ok(), self.tail_consumed.take()) { - (true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed), - _ => {} - } - // an exit before the decode phase queued the refill still refills now; one before it waited still waits - if std::mem::take(&mut self.refill_due) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) { - self.mark_broken(error); - } - } - } - if std::mem::take(&mut self.refill_pending) { - if let Some(cache) = self.expert_cache.as_mut() { - if let Err(error) = original_serve_residency::settle_refill(cache) { - self.mark_broken(error); - } - } - } - self.timing.1 = started.elapsed().as_secs_f64() * 1e3; - profile::add("decode.phase", self.timing.1); - if profile::enabled() { - let t1 = self.residency.stats; - let (v, p, c) = (t1.vram_entries - tier0.vram_entries, t1.pcie_entries - tier0.pcie_entries, t1.cpu_entries - tier0.cpu_entries); - let all = (v + p + c).max(1) as f64; - // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) - eprintln!( - "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", - 100.0 * v as f64 / all, 100.0 * p as f64 / all, 100.0 * c as f64 / all, - 100.0 * v as f64 / ((v + c).max(1) as f64), t1.adaptations - tier0.adaptations, t1.swaps - tier0.swaps, - self.residency.pcie_lag.as_ref().map(|l| l.pcie_num()).or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())).unwrap_or(self.config.expert_tier.pcie_num()) - ); - } - // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts - let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); - profile::add("mtp.capture", capture_ms); - profile::add("mtp.instantiate", instantiate_ms); - profile::add("prefill.phase", self.timing.0); - profile::report("request"); - self.residency.flush_routing(); - self.seed_coverage_trace(); - result - } - fn finish(&mut self, ended: std::result::Result<(), ServeError>) { - let completed = self.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled)); - if let Some(conversation) = self.conversation.as_mut() { - conversation.finish(completed); - } - if let Some(prefix) = self.prefix.as_mut() { - prefix.finish(completed); - let (admitted, park_ms, consider_ms) = prefix.request_parking(); - operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn a_chunk_borrows_the_smallest_rung_that_holds_it() { - let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); - let layout = prefill_layout_options(8192, 262_144, &blobs); - let tiers: Vec = [(512usize, 600usize), (2048, 900)] - .into_iter() - .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) - .collect(); - assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); - assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); - assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); - assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); - assert!(tier_for(&[], 100).is_none()); - // the arena of a smaller rung is smaller - assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); - assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); - } - - #[test] - fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { - let config = StackConfig::new(4096); - assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); - for capacity in [256usize, 1024, 8192] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); - } - for capacity in [0usize, 255, 300, 16384, 32768] { - assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); - } - assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); - assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); - assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); - } - - #[test] - fn the_conversation_cache_is_on_by_default_with_the_original_settings() { - let config = StackConfig::new(4096); - let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); - assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); - assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); - assert!(config.validate().is_ok()); - assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); - } - - #[test] - fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { - let config = StackConfig::new(4096); - assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); - assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); - for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { - assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); - } - assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); - for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { - assert_eq!( - StackConfig { kv_format, ..config.clone() }.validate(), - Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) - ); - } - } - - #[test] - fn plan_errors_keep_their_class() { - assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); - assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); - } -} +//! The Original serving stack: every model-lifetime owner of the `generate.cpp` mode17 serve path, opened +//! once, and the per-request flow over them (prompt conditioning with the batched Original prefill, then the +//! verified-window decode with MTP drafting). +//! +//! Lifetime of the pieces: the dense weights, the MoE arena cache, the native head/embedding, the target +//! session, the prompt executor (which owns the MTP actor and the twelve resident QSA layers), the MTP draft +//! session, the prefill arena, the penalty-history stage and the PLE history image live as long as the +//! stack. Each request resets them to the empty prompt (the checkpoints taken at load, re-stamped onto the +//! current branch generation), conditions the prompt through the executor, and then hands the QSA owners to a +//! freshly assembled native Verifier for the decode phase; the verifier is closed and the owners are taken +//! back afterwards (see `original_serve_verifier`). With `StackConfig::conversation` set, generate.cpp's +//! conversation cache decides where a request starts reading instead (`original_serve_conversation`); +//! without it every request starts at position 0. +//! +//! With `StackConfig::expert_tier` on, the stack also owns the VRAM expert tier (`original_serve_residency`): +//! the cache is opened last, filled from the profile, lent to the prompt path for each chunk and refilled +//! before the decode phase (on every exit path), whose windows compute the resident experts on the GPU. +//! +//! Nothing here computes a model number. Where an asset or a producer the Original needs is not available the +//! error comes from its owner and is surfaced untouched (`ServeFailure`). +use super::{ + contract::{Error, Result}, + dense_weight_cache::DenseWeightCache, + executor::original_prompt::{embedding::OriginalPromptEmbedding, OriginalPromptExecutor}, + kar_ple_cache::KarPleCache, + moe_weight_cache::MoeWeightCache, + original_mtp_full_owner::{OriginalMtpFullOwner, OriginalMtpRequest}, + original_serve_config::{expert_formats, mtp_full_policy, mtp_scalar_policy, prefill_layout_options, ExpertBlobSizes, RopeConstants}, + original_serve_engine::{serve_request, OriginalServeEngine, OriginalServeSettings, ServeOutcome}, + original_serve_host::{HostOwners, OriginalServeHost, RequestSampling}, + original_serve_native::NativeServePort, + original_serve_pool::{CpuExpertPool, OriginalServePool}, + original_serve_profile as profile, + original_serve_residency::{self, ExpertTierConfig, GpuExpertPool, ResidencyState}, + original_serve_seed::{self, SeedReport}, + original_serve_request::{run_request, RequestOwners, ServeError, ServeRequest}, + original_serve_verifier::{assemble, disassemble, seed_ple_history, DecodeResources, ServeFailure, VerifyWeights, PLE_HISTORY_BYTES}, + original_spec_controller::{OriginalSpecController, SpecError}, + output_native::{OriginalNativeOutput, OriginalNativePenaltyHistory}, + session::{ + original_prompt::{draft::OriginalDraftCheckpoint, OriginalPromptInput, OriginalSessionCheckpoint, ParkedBlock, ParkedSession}, + QwenSession, + }, +}; +use crate::backend::original_prompt::{PlanError, PromptOptions, PromptPath, PromptPlan}; +use crate::model_binding::qwen4exp_input::ModelBinding; +use leleka_context::memory_plan::KvFormat; +use leleka_cuda_driver::{ + Context, DeviceBuffer, NativeHeadDispatch, OriginalExpertCache, OriginalMtpFullPolicy, OriginalMtpScalarPolicy, + OriginalPrefillArena, OriginalVerifyExpertFormats, PLE_SCRATCH_BYTES, PrefillLayoutOptions, +}; +use std::{path::PathBuf, rc::Rc, time::Instant}; + +/// One timed, measured step of opening the stack: the load ledger records what it cost in host and device memory. +macro_rules! staged { + ($name:expr, $ctx:expr, $body:expr) => {{ + let __stage = crate::memory_governor::begin($name, Some($ctx)); + let __result = $body; + crate::memory_governor::end(__stage, Some($ctx)); + __result + }}; +} + +#[path = "original_serve_conversation.rs"] +mod conversation; +pub(crate) use conversation::{ConversationConfig, TURN_TOKEN}; +use conversation::{ResumeDevice, ServeConversation}; + +#[path = "original_serve_prefix.rs"] +mod prefix; +pub(crate) use prefix::{PrefixBudget, PrefixConfig, TailMode}; +use prefix::{ChunkOutcome, PrefixDevice, PrefixServe}; +use crate::prefix_cache::{ByteSize, PrefixMatch, PrefixSummary}; + +/// Stage marks of one request's time to first token (milliseconds since `serve` was entered). +#[derive(Clone, Copy, Debug)] +struct TtftMarks { + started: Option, + resumed: f64, + prefilled: f64, + assembled: f64, + first_round: f64, +} +impl Default for TtftMarks { + fn default() -> Self { + Self { started: None, resumed: f64::NAN, prefilled: f64::NAN, assembled: f64::NAN, first_round: f64::NAN } + } +} +impl TtftMarks { + fn start() -> Self { + Self { started: Some(Instant::now()), ..Self::default() } + } + fn since(&self) -> f64 { + self.started.map_or(f64::NAN, |at| at.elapsed().as_secs_f64() * 1e3) + } + fn as_array(&self) -> [f64; 4] { + [self.resumed, self.prefilled, self.assembled, self.first_round] + } +} + +/// The digest of the pinned model's first shard: part of the prefix cache's namespace. +const PINNED_MODEL: &str = "sha256:4c1eb2ceb4915e1192f4f386021897bde56a97f40a0bb78bb86465e0f7d2aca3"; + +/// Prompt-chunk capacities the Original prefill admits (`PromptPlan::new`), ascending. +pub(crate) const ADMITTED_CAPACITIES: [usize; 10] = [256, 512, 1024, 2048, 3072, 4096, 6144, 8192, 16384, 32768]; +/// The default chunk. The Original sizes it from the free expert-cache slots (`--prefill-auto`); with no GPU +/// expert tier there is no slot count to derive it from, so the operator picks it (the arena is a few GiB at +/// 8192) and a hardware run settles the default. +pub(crate) const DEFAULT_CAPACITY: usize = 2048; +/// `qsa_kv_resident_min()`: the shipped resident draft-K/V budget in cells. +const MTP_RESIDENT_CELLS: u64 = 20_480; +const CPU_WORKERS: i32 = 15; +const VOCABULARY: u32 = 248_320; + +/// Operator-visible choices of the stack. +#[derive(Clone, Debug)] +pub(crate) struct StackConfig { + pub(crate) capacity: usize, + /// The request ceiling (`--max-context`): at most the process serving cell count. + pub(crate) max_context: i64, + /// `--mtp DIR`: the Original-literal RT directory; `None` takes the digest-pinned pack of the binding. + pub(crate) rt_directory: Option, + pub(crate) coupled: bool, + pub(crate) cpu_workers: i32, + /// Read the verifier's GDN/PLE state back into the session at the end of every request (needed only by + /// a consumer that reuses the session; the default reset-per-request flow skips the 110 MB transfer). + pub(crate) settle_state: bool, + /// `--kv`: QSA K/V storage. Only `int8` (the production `--kv int8`) has sealed owners; fp16, q4_0 and + /// k8v4 are refused (docs/kv-streaming.md). + pub(crate) kv_format: KvFormat, + /// `--kv-resident N`: cells of each QSA layer kept in VRAM, the rest streamed from pinned host memory + /// (raised to 20480; 0 = the whole context). Default 32768, the window every earlier build used. + pub(crate) kv_resident: usize, + /// generate.cpp's conversation cache (`--prompt-cache` and friends); on by default with the Original's + /// settings (`--prompt-cache 6`). `None` reads every request from the empty prompt. + pub(crate) conversation: Option, + /// The cross-session prefix cache (`--prefix-cache-mib`, `docs/prefix-cache.md`). When it is on it REPLACES the + /// conversation cache: the prompt is read on a token grid and any request resumes from the deepest checkpoint + /// that is a prefix of its prompt, whichever session built it. `None` (the default) leaves the conversation + /// cache in charge. + pub(crate) prefix: Option, + /// The VRAM expert tier (`--expert-cache`, `--expert-cache-per-layer`, `--expert-profile`, `--pcie-frac`, + /// `--adapt-every/--adapt-swaps`). Off by default: every routed expert on the CPU pool. + pub(crate) expert_tier: ExpertTierConfig, + /// Smaller prompt loans for smaller chunks (`LELEKA_PREFILL_LOAN_TIERS=1`; off: every chunk borrows the full loan of `capacity`). + pub(crate) loan_tiers: bool, +} +impl StackConfig { + pub(crate) fn new(max_context: i64) -> Self { + Self { + capacity: DEFAULT_CAPACITY, + max_context, + rt_directory: None, + coupled: OriginalServeSettings::coupled_from_environment(), + // LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15) + // LELEKA_CPU_POOL_PLAN=on: when the count is not set, the plan of `native-cpu-expert::pool_plan` (physical cores but the host's, hybrid and quota aware; + // docs/upstream-port-plan.md row 2.3) instead of the constant 15 (opt-in: the same 15 on the server's 16-core CPU, not measured on any other) + cpu_workers: std::env::var("LELEKA_ORIGINAL_SERVE_CPU_WORKERS").ok().and_then(|v| v.parse().ok()).filter(|n| (1..=64).contains(n)).unwrap_or_else(|| { + if std::env::var("LELEKA_CPU_POOL_PLAN").is_ok_and(|v| v == "on") { leleka_native_cpu_expert::pool_plan::default_workers() } else { CPU_WORKERS } + }), + settle_state: false, + kv_format: KvFormat::Int8, + kv_resident: leleka_cuda_driver::KV_RESIDENT_DEFAULT_CELLS, + conversation: Some(ConversationConfig::original()), + prefix: None, + expert_tier: ExpertTierConfig::off(), + loan_tiers: loan_tiers_enabled(), + } + } + /// The streamed KV of this configuration (`None` when the window is not servable). + pub(crate) fn kv_footprint(&self) -> Option { + leleka_cuda_driver::serving_context().geometry.kv_stream_footprint(self.kv_resident).ok() + } + pub(crate) fn validate(&self) -> Result<()> { + if self.kv_format != KvFormat::Int8 { + return Err(Error::Unsupported(super::contract::Stage::Session)); + } + if !ADMITTED_CAPACITIES.contains(&self.capacity) + || self.kv_footprint().is_none() + || self.capacity > 8192 + || self.max_context < 1 + || self.max_context as u64 > super::contract::serving_cells() + || !(1..=64).contains(&self.cpu_workers) + { + return Err(Error::InvalidDimension); + } + if let Some(conversation) = &self.conversation { + conversation.validate()?; + } + if let Some(prefix) = &self.prefix { + prefix.validate(self.capacity)?; + } + self.expert_tier.validate() + } +} + +/// Bytes the prompt path's buffers need at `options.capacity` (what a loan must cover). +fn prefill_bytes(options: PrefillLayoutOptions) -> Result { + let carve = options.carve().map_err(|e| super::original_serve_verifier::driver_error(&e))?; + Ok(carve.borrowed_bytes.max(carve.source_bytes_needed)) +} + +/// One rung of the loan ladder: the arena layout for chunks of at most `rows` rows and the slots it needs. +#[derive(Clone, Copy, Debug)] +struct LoanTier { + rows: usize, + layout: PrefillLayoutOptions, + slots: usize, +} + +/// Chunk sizes (rows) that get their own, smaller loan below the configured capacity. +const LOAN_TIER_ROWS: [usize; 2] = [512, 2048]; + +/// The smallest rung of the ladder that holds a chunk of `count` rows (`None`: the full loan). +fn tier_for(tiers: &[LoanTier], count: usize) -> Option<&LoanTier> { + tiers.iter().find(|t| count <= t.rows) +} + +/// `LELEKA_PREFILL_LOAN_TIERS=1` turns the ladder on. It is OFF by default until the real-model identity gate (job p34: the final residual R of +/// every chunk equal with and without the ladder) and the paired A/B (job p35) have run (docs/prefill-throughput.md). +fn loan_tiers_enabled() -> bool { + std::env::var("LELEKA_PREFILL_LOAN_TIERS").is_ok_and(|v| v == "1" || v == "on") +} + +/// One conversation checkpoint of the stack: the session's Original checkpoint and the draft ring's snapshot, +/// taken together at a published prompt-chunk boundary. +struct StackPoint<'ctx> { + session: OriginalSessionCheckpoint<'ctx>, + draft: OriginalDraftCheckpoint, +} + +/// A prefix-cache checkpoint of the stack: the session's recurrent state and the draft ring's snapshot at one grid point. +struct StackState { + session: ParkedSession, + draft: OriginalDraftCheckpoint, +} +impl ByteSize for StackState { + fn byte_size(&self) -> usize { + self.session.host_bytes() + self.draft.host_bytes() + } +} +/// The K/V cells and index rows of one block of the twelve resident QSA layers. +struct StackBlock(ParkedBlock); +impl ByteSize for StackBlock { + fn byte_size(&self) -> usize { + self.0.host_bytes() + } +} +/// Bytes of one cell across the twelve layers: INT8 K+V with scales (1056 B) and the pooled index key (128 B). +const PARKED_BYTES_PER_TOKEN: usize = 12 * (1056 + 128); +/// Expected size of a parked state before one was measured (GDN/PLE images, the draft ring, the index tails). +const PARKED_STATE_ESTIMATE: usize = 120 << 20; + +fn plan_error(error: PlanError) -> Error { + match error { + PlanError::InvalidInput => Error::InvalidDimension, + PlanError::Overflow => Error::Overflow, + } +} + +pub(crate) struct OriginalServeStack<'a, 'ctx> { + binding: &'a ModelBinding, + context: &'ctx Context<'ctx>, + config: StackConfig, + settings: OriginalServeSettings, + max_cells: usize, + rope: RopeConstants, + blobs: ExpertBlobSizes, + formats: OriginalVerifyExpertFormats, + full_policy: OriginalMtpFullPolicy, + scalar_policy: OriginalMtpScalarPolicy, + controller: OriginalSpecController, + /// Window policies other than the live one (`LELEKA_SPEC_ARMS`), parked with their controllers (each keeps its learned + /// state across requests), and the live one's label. The verifier is built for `verifier_max_t`, the widest arm. + parked: Vec<(String, OriginalServeSettings, OriginalSpecController)>, + arm_label: String, + arm_order: Vec, + verifier_max_t: usize, + /// Why the stack can serve no more (a lost physical owner); `None` while healthy. + broken: Option, + // The empty-prompt lineage taken at load: the reset target of every request. + empty_session: OriginalSessionCheckpoint<'ctx>, + empty_draft: OriginalDraftCheckpoint, + /// The conversation cache (checkpoints hold priors and snapshots of the owners below: dropped first). + conversation: Option>>, + /// The prefix cache (`StackConfig::prefix`); replaces `conversation` when set. + prefix: Option>, + /// The tokens the session holds at the end of a decode that left it settled with the draft ring in step (`TailMode::Reply`). + tail_consumed: Option>, + /// Prompt tokens the last request did not read again. + reused: usize, + /// Where the conversation cache placed the last request (`reused`, or the re-read checkpoint's length). + resume_point: usize, + // Owners, dependents first (fields drop in declaration order). + history: OriginalNativePenaltyHistory<'ctx>, + ple_history: DeviceBuffer<'ctx>, + ple_scratch: DeviceBuffer<'ctx>, + /// The prompt path's own buffers; `None` while it borrows the expert cache's last slots instead. + arena: Option>, + layout: PrefillLayoutOptions, + /// The VRAM expert tier (`None`: off), the slots the prompt path borrows per chunk, the adaptive counts + /// that survive requests. + expert_cache: Option>, + loan: Option, + /// Smaller loans for smaller chunks, ascending by rows (empty unless `LELEKA_PREFILL_LOAN_TIERS=1`: only `loan`): a chunk of at most + /// `rows` rows borrows `slots` slots instead of the full loan, so a request that reads a few hundred tokens refills a few + /// hundred slots, not the 1.9 GB of an 8192-row arena. + loan_tiers: Vec, + residency: ResidencyState, + /// The (layer, expert) pairs the tier held right after the profile fill (`reset_expert_tier`). + initial_owners: Vec>, + /// The last request's prompt-routing seed (`LELEKA_ORIGINAL_SERVE_SEED`), if one was made. + seed_report: Option, + /// The prompt counts of the last seed (kept for the `LELEKA_SEED_TRACE` coverage line). + seed_counts: Option>, + /// Lent-slot refill copies are queued and not yet waited (`LELEKA_REFILL_DEFER`): the decode phase waits before any + /// window reads the cache; every other user of the cache waits inside its own entry points. + refill_pending: bool, + /// The lent slots still have to be refilled: the decode phase queues the copies right after its host-side intake + /// uploads (so they overlap the graph capture instead of queueing small uploads behind 1.4 GB of DMA). + refill_due: bool, + /// Wall-clock milliseconds of the last request's prompt and decode phases (operator measurements). + timing: (f64, f64), + /// Milliseconds since the request entered `serve` at which each stage of the time to first token ended (`ttft_marks`). + marks: TtftMarks, + executor: OriginalPromptExecutor<'ctx>, + draft: super::session::original_prompt::draft::OriginalDraftSession<'ctx>, + session: QwenSession<'ctx>, + pool: CpuExpertPool<'a>, + kar: Option>, + moe: MoeWeightCache<'ctx>, + dense: DenseWeightCache<'ctx>, + output: OriginalNativeOutput<'ctx>, + embedding: OriginalPromptEmbedding<'ctx>, +} + +fn failure(error: Error) -> ServeFailure { + ServeFailure::from(error) +} + +/// Name the startup step in a refusal so a failed open says where it stopped. +fn at>(step: &'static str) -> impl FnOnce(E) -> ServeFailure { + move |error| { + let mut failure: ServeFailure = error.into(); + failure.detail = Some(match failure.detail.take() { + Some(detail) => format!("{step}: {detail}"), + None => format!("{step}: {:?}", failure.error), + }); + failure + } +} + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `generate.cpp` startup over the binding: embedding table, native head + embedding, dense weights at + /// the prompt capacity, the MoE arena cache, the target session, the prompt executor with the MTP + /// drafter, the prefill arena, and the per-request stages. `shared` is the session's reference to the + /// very context `context` borrows. + pub(crate) fn open( + binding: &'a ModelBinding, + context: &'ctx Context<'ctx>, + shared: Rc>, + config: StackConfig, + ) -> std::result::Result { + crate::bringup_trace!("DBG[{:.0}s] OriginalServeStack::open begin", dbg_el()); + config.validate().map_err(at("config.validate"))?; + // generate.cpp: qsa_set_kv_resident before any QSA state exists (every streamed owner sizes from it) + leleka_cuda_driver::configure_kv_resident(config.kv_resident).map_err(|_| ServeFailure { + error: Error::InvalidDimension, + detail: Some(format!("--kv-resident {}: the process already serves another resident KV window", config.kv_resident)), + })?; + if let Some(footprint) = config.kv_footprint() { + operator_note(&footprint.to_string()); + } + if !std::ptr::eq(context, &*shared) { + return Err(failure(Error::IdentityMismatch)); + } + if binding.layer_count() != 48 { + return Err(ServeFailure { error: Error::IdentityMismatch, detail: Some("the Original serve stack serves the 48-layer model only".to_owned()) }); + } + if !binding.has_mtp() { + return Err(ServeFailure { + error: Error::Unsupported(super::contract::Stage::Session), + detail: Some("the binding carries no MTP pack: the Original serve loop drafts with the MTP layer".to_owned()), + }); + } + let max_cells = usize::try_from(super::contract::serving_cells()).map_err(|_| failure(Error::Overflow))?; + let mut settings = OriginalServeSettings::from_environment(config.max_context, VOCABULARY, config.coupled); + let mut arm_label = String::from("env"); + let arm_order: Vec = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled).into_iter().map(|(l, _)| l).collect(); + let mut parked = Vec::new(); + let arms = OriginalServeSettings::arms_from_environment(config.max_context, VOCABULARY, config.coupled); + let verifier_max_t = arms.iter().map(|(_, s)| s.max_t).chain([settings.max_t]).max().unwrap_or(settings.max_t); + if let Some(((label, first), rest)) = arms.split_first() { + settings = *first; + arm_label = label.clone(); + for (label, s) in rest { + parked.push((label.clone(), *s, s.controller().map_err(at("settings.controller"))?)); + } + } + let controller = settings.controller().map_err(at("settings.controller"))?; + let rope = RopeConstants::from_serving_context(); + let blobs = ExpertBlobSizes::from_binding(binding).map_err(at("ExpertBlobSizes::from_binding"))?; + let formats = expert_formats(binding).map_err(at("expert_formats"))?; + let layout = prefill_layout_options(config.capacity, max_cells, &blobs); + + vram_note(context, "open begin"); + let embedding = staged!("embedding table", context, OriginalPromptEmbedding::load(binding, context).map_err(at("OriginalPromptEmbedding::load"))?); + let output = staged!("native head + embedding", context, OriginalNativeOutput::load(binding, context, NativeHeadDispatch::default(), true).map_err(at("OriginalNativeOutput::load"))?); + let kar = staged!("KAR PLE cache", context, match binding.kar_ple_binding() { + Some(provider) => Some(KarPleCache::new(context, provider).map_err(at("KarPleCache::new"))?), + None => None, + }); + let dense = staged!("dense weights", context, DenseWeightCache::new_original_prompt_capacity(binding, context, config.capacity).map_err(at("DenseWeightCache::new_original_prompt_capacity"))?); + let moe = staged!("MoE arena cache", context, MoeWeightCache::new_original_prompt_arena(binding, context, layout).map_err(at("MoeWeightCache::new_original_prompt_arena"))?); + vram_note(context, "after embedding, output, kar, dense, moe arena"); + let mut session = QwenSession::for_binding_on_shared_device(binding, shared); + let request = OriginalMtpRequest::ring_int8(verifier_max_t, config.capacity, settings.coupled, MTP_RESIDENT_CELLS); + let executor_stage = crate::memory_governor::begin("prompt executor + MTP drafter", Some(context)); + let (executor, draft) = match &config.rt_directory { + Some(directory) => OriginalPromptExecutor::select_rt_mtp( + binding, &dense, &mut session, context, &embedding, &output, directory, config.capacity, true, &request, + ) + .map_err(|e| ServeFailure { error: e.error, detail: e.message })?, + None => { + let mut executor = OriginalPromptExecutor::new( + binding, &dense, &mut 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) + } + }; + vram_note(context, "after prompt executor and draft"); + let mut executor = executor; + crate::memory_governor::end(executor_stage, Some(context)); + // generate.cpp: the expert cache is sized after everything else, and the prompt path's own buffers + // after the cache when it cannot borrow them; without the tier the order is unchanged. + let tier = config.expert_tier.enabled(); + let mut arena = staged!("prefill arena", context, if tier { None } else { Some(context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?) }); + vram_note(context, "before cache"); + let history = staged!("penalty history", context, OriginalNativePenaltyHistory::new(binding, context).map_err(at("OriginalNativePenaltyHistory::new"))?); + let ple_history = context.allocate(PLE_HISTORY_BYTES).map_err(at("ple_history"))?; + let ple_scratch = context.allocate(PLE_SCRATCH_BYTES).map_err(at("ple_scratch"))?; + let pool = staged!("CPU expert pool", context, CpuExpertPool::new(binding, config.cpu_workers).map_err(at("CpuExpertPool::new"))?); + let empty_session = staged!("empty-prompt session checkpoint", context, executor.checkpoint_session(binding, &mut session).map_err(at("checkpoint_session"))?); + let empty_draft = staged!("empty-prompt draft checkpoint", context, draft.checkpoint(binding, &session).map_err(at("draft.checkpoint"))?); + let prefix = match &config.prefix { + Some(prefix_config) => { + let available = crate::conversation::memory::available_memory(); + // the budget comes from the memory governor (what is left above the floors), not from an independent default + let complement_pending = (config.expert_tier.resident_budget_gib.max(0.0) * (1u64 << 30) as f64) as u64; + let bytes = crate::memory_governor::resolve_prefix_budget(prefix_config.budget, available, complement_pending) + .unwrap_or_else(|| prefix_config.resolve_budget(available)); + let mut prefix_config = prefix_config.clone(); + if let Some(g) = leleka_memory::Governor::global() { + // stop admitting before anything has to be shed: soft floor + reserve (the real CRM session sat 4.4 GiB above a 3 GiB floor) + prefix_config.memory_floor = prefix_config.memory_floor.max(g.policy().admit_floor()); + } + let prefix_config = &prefix_config; + if bytes == 0 { + operator_note(&format!( + "prefix cache off (budget {:?}, available host memory {:?} MiB)", + prefix_config.budget, + available.map(|b| b >> 20) + )); + None + } else { + let identity = format!("qwen4exp:{PINNED_MODEL}:kv={:?}:resident={}", config.kv_format, config.kv_resident); + let serve = PrefixServe::new(prefix_config.clone(), config.capacity, bytes, &identity); + operator_note(&format!( + "prefix cache on: block/grid {} tokens, budget {} MiB, state ~{} MiB + {} B per token, host memory available {:?} MiB, namespace {}", + serve.block_tokens(), + bytes >> 20, + PARKED_STATE_ESTIMATE >> 20, + PARKED_BYTES_PER_TOKEN, + available.map(|b| b >> 20), + crate::prefix_cache::summary::hex(serve.namespace()) + )); + Some(serve) + } + } + None => None, + }; + let conversation = if prefix.is_some() { None } else { config.conversation.clone().map(ServeConversation::new) }; + let residency = ResidencyState::new(&config.expert_tier); + report_kernel_selection(); + vram_note(context, "before expert tier"); + let mut loan = None; + let tier_open = staged!("expert tier (VRAM slots + profile fill)", context, original_serve_residency::open_tier(binding, context, &moe, &config.expert_tier, config.capacity).map_err(at("expert tier"))?); + let expert_cache = match tier_open { + Some((cache, filled)) => { + if config.expert_tier.prefill_borrow && config.expert_tier.profile.is_some() { + loan = 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(), + } + )); + Some(cache) + } + None => None, + }; + vram_note(context, "after expert tier"); + let mut loan_tiers: Vec = Vec::new(); + if let (Some(full), Some(cache), true) = (loan, expert_cache.as_ref(), config.loan_tiers) { + for rows in LOAN_TIER_ROWS.into_iter().filter(|&r| r < config.capacity) { + let tier_layout = PrefillLayoutOptions { capacity: rows, ..layout }; + let slots = original_serve_residency::loan_slots(cache, prefill_bytes(tier_layout).map_err(at("prefill bytes (tier)"))?).map_err(at("expert-cache loan (tier)"))?; + if let Some(slots) = slots.filter(|&s| s < full && loan_tiers.last().is_none_or(|t| s > t.slots)) { + loan_tiers.push(LoanTier { rows, layout: tier_layout, slots }); + } + } + if !loan_tiers.is_empty() { + operator_note(&format!( + "prompt loan ladder: {}, up to {} rows {full} slots", + loan_tiers.iter().map(|t| format!("up to {} rows {} slots", t.rows, t.slots)).collect::>().join(", "), + config.capacity + )); + } + } + let initial_owners: Vec> = expert_cache + .as_ref() + .map(|cache| (0..cache.slots()).map(|slot| cache.slot_owner(slot)).collect()) + .unwrap_or_default(); + if arena.is_none() && loan.is_none() { + arena = Some(staged!("prefill arena (after the expert tier)", context, context.original_prefill_arena(layout).map_err(at("original_prefill_arena"))?)); + } + let this = Self { + binding, + context, + conversation, + prefix, + tail_consumed: None, + reused: 0, + resume_point: 0, + full_policy: mtp_full_policy(&rope), + scalar_policy: mtp_scalar_policy(&rope), + config, + settings, + max_cells, + rope, + blobs, + formats, + controller, + parked, + arm_label, + arm_order, + verifier_max_t, + broken: None, + empty_session, + empty_draft, + history, + ple_history, + ple_scratch, + arena, + layout, + expert_cache, + loan, + loan_tiers, + residency, + initial_owners, + seed_report: None, + seed_counts: None, + refill_pending: false, + refill_due: false, + timing: (0.0, 0.0), + marks: TtftMarks::default(), + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + embedding, + }; + this.register_memory_classes(); + crate::memory_governor::post_open(); + if let Some(governor) = leleka_memory::Governor::global() { + governor.log(&format!("stack open; inventory of allocation classes (accounted by their owners): +{}", governor.inventory().table())); + governor.log(&format!("load ledger (measured: kernel and driver deltas per opening step): +{}", governor.ledger().table())); + governor.publish(); + } + Ok(this) + } + + /// `Some` once a physical owner was lost: the stack must be closed and rebuilt. + pub(crate) fn health(&self) -> Option { + self.broken + } + + /// One request. Admission, reset, prompt conditioning and decode in order; see `run_request`. + pub(crate) fn serve( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + self.apply_memory_directive(); + self.marks = TtftMarks::start(); + let max_context = self.config.max_context; + let result = run_request(self, request, max_context, emit, cancel); + self.note_memory(); + result + } + + /// Follow the memory governor between requests: under pressure the prefix cache evicts (and restores its budget when the + /// pressure is over), and the conversation checkpoints are dropped. Cheap: a few atomics when nothing changed. + fn apply_memory_directive(&mut self) { + let Some(governor) = leleka_memory::Governor::global() else { return }; + let used = self.prefix.as_ref().map_or(0, |p| p.bytes() as u64); + let directive = governor.directive(used); + if let Some(prefix) = self.prefix.as_mut() { + let before = prefix.bytes(); + let freed = prefix.apply_shed(directive.prefix_budget, governor); + if freed > 0 { + operator_note(&format!( + "memory pressure ({}): prefix cache evicted {} MiB ({} -> {} MiB), budget {} MiB", + directive.level.as_str(), + freed >> 20, + before >> 20, + prefix.bytes() >> 20, + prefix.budget_bytes() >> 20 + )); + } + } + if directive.drop_conversation + && let Some(conversation) = self.conversation.as_mut() + && conversation.checkpoint_count() > 0 + { + conversation.invalidate(); + operator_note(&format!("memory pressure ({}): conversation checkpoints dropped", directive.level.as_str())); + } + } + + /// Keep the inventory's elastic classes current (the prefix store and the conversation checkpoints). + fn note_memory(&self) { + if leleka_memory::Governor::global().is_none() { + return; + } + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::set_bytes("prefix.store", prefix.bytes() as u64); + if let Some(g) = leleka_memory::Governor::global() { + g.note_prefix_used(prefix.bytes() as u64); + } + } + if let Some(conversation) = self.conversation.as_ref() { + crate::memory_governor::set_bytes("conversation.checkpoints", conversation.checkpoint_count() as u64 * crate::memory_governor::CHECKPOINT_BYTES); + } + } + + /// Register the stack's allocation classes with the inventory (sizes from the owners' own formulas and counters). + fn register_memory_classes(&self) { + use leleka_memory::{Space, When}; + let Some(governor) = leleka_memory::Governor::global() else { return }; + let _ = governor; + if let Some(f) = self.config.kv_footprint() { + crate::memory_governor::account("kv", "host_pinned", Space::HostPinned, When::Startup, "12 QSA layers x serving cells x 1056 B, pinned and device-mapped (the whole serving context, allocated at open)", f.pinned_host_bytes as u64); + crate::memory_governor::account("kv", "vram_window", Space::Device, When::Startup, "12 layers x resident pages x 4244 B (+ page table + resolver state)", f.vram_bytes as u64); + crate::memory_governor::account("kv", "prompt_stage", Space::Device, When::Startup, "one INT8 staging pool of the prompt path (identity layout)", f.stage_bytes as u64); + } + if let Ok(bytes) = prefill_bytes(self.layout) { + crate::memory_governor::account( + "prefill", + if self.loan.is_some() { "arena_borrowed" } else { "arena" }, + Space::Device, + When::Startup, + if self.loan.is_some() { "carve of the prefill arena, borrowed from the last slots of the expert cache (not additional)" } else { "carve of the prefill arena at the chunk capacity" }, + if self.loan.is_some() { 0 } else { bytes as u64 }, + ); + } + if let Some(cache) = self.expert_cache.as_ref() { + crate::memory_governor::account("expert_cache", "slots", Space::Device, When::Startup, "slots x slot bytes (VRAM expert tier)", cache.bytes() as u64); + } + crate::memory_governor::account("ple", "history_and_scratch", Space::Device, When::Startup, "PLE history image + scratch", (PLE_HISTORY_BYTES + PLE_SCRATCH_BYTES) as u64); + crate::memory_governor::account("context", "accounted_total", Space::Device, When::Lazy, "sum of the context's budgeted allocations (not additive with the classes above; see the ledger for the driver-seen total)", 0); + if let Some(prefix) = self.prefix.as_ref() { + crate::memory_governor::account( + "prefix", + "store", + Space::HostPageable, + When::Elastic, + "blocks (14,208 B per token) + node states (~127 MiB each) under the governor-granted budget", + prefix.bytes() as u64, + ); + } + if self.conversation.is_some() { + crate::memory_governor::account( + "conversation", + "checkpoints", + Space::HostPageable, + When::Elastic, + "checkpoints x ~118 MiB (GDN/PLE images, draft ring, index tails)", + 0, + ); + } + } + + /// Labels of the window policies of `LELEKA_SPEC_ARMS` in the order given (empty when unset), the live one included. + #[allow(dead_code)] + pub(crate) fn spec_arms(&self) -> Vec { + self.arm_order.clone() + } + /// Make `label` the window policy of the following requests (between requests only). Returns false for an unknown label. + #[allow(dead_code)] + pub(crate) fn select_spec_arm(&mut self, label: &str) -> bool { + if self.arm_label == label { + return true; + } + let Some(at) = self.parked.iter().position(|(l, _, _)| l == label) else { return false }; + let (new_label, new_settings, new_controller) = self.parked.swap_remove(at); + let old_label = std::mem::replace(&mut self.arm_label, new_label); + let old_settings = std::mem::replace(&mut self.settings, new_settings); + let old_controller = std::mem::replace(&mut self.controller, new_controller); + self.parked.push((old_label, old_settings, old_controller)); + true + } + /// The live arm's own request floor, if its label pinned one (`fixed4@0`). + #[allow(dead_code)] + pub(crate) fn spec_arm_min_p(&self) -> Option { + self.settings.request_min_p + } + #[allow(dead_code)] + pub(crate) fn spec_arm(&self) -> &str { + &self.arm_label + } + + /// Wall-clock milliseconds of the last request's prompt phase and decode phase. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn last_timing(&self) -> (f64, f64) { + self.timing + } + + /// Where the last request's time to first token went: `(resumed, prefilled, assembled, first_round)`, each the + /// milliseconds since `serve` was entered when that stage ended (`resumed`: the cache lookup, import and any reset; + /// `prefilled`: the prompt chunks, the lent-slot refill and the seed; `assembled`: the verifier (graphs, canonical + /// state upload); `first_round`: the first verified round was emitted). NaN for a stage the request did not reach. + #[allow(dead_code)] + pub(crate) fn ttft_marks(&self) -> [f64; 4] { + self.marks.as_array() + } + + /// The VRAM expert tier's counters (`None` when the tier is off). + pub(crate) fn expert_tier_stats(&self) -> Option { + self.expert_cache.as_ref().map(|cache| { + let mut stats = self.residency.stats; + stats.swaps = cache.swaps(); + stats + }) + } + + /// The tier's configuration, for an experiment that switches the adaptive tier or the seed between requests (the + /// adaptive counts are allocated at open, so `adapt_every` may be changed freely, a seed needs the tier on). + #[allow(dead_code)] + pub(crate) fn expert_tier_mut(&mut self) -> &mut ExpertTierConfig { + &mut self.config.expert_tier + } + + /// The last request's seed from the prompt's routing (`None`: seed off, or no prompt rows were read). + #[allow(dead_code)] + pub(crate) fn last_seed(&self) -> Option { + self.seed_report + } + + /// Cumulative (vram, pcie, cpu) window entries after each verified round of the last request. + #[allow(dead_code)] + pub(crate) fn round_marks(&self) -> Vec<[u64; 3]> { + self.residency.round_marks() + } + + /// A first-request state for an experiment: the tier back on the starting profile's set, the adaptive counts and + /// the draft/adaptation controller as in a new process. Returns the swaps the restore needed. + #[allow(dead_code)] + pub(crate) fn reset_expert_tier(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + self.residency.clear_usage(); + self.controller = self.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.residency.spans, &self.initial_owners), + None => Ok(0), + } + } + + /// Prompt tokens the last request reused from the conversation cache (generate.cpp `REUSED`). + pub(crate) fn reused_tokens(&self) -> usize { + self.reused + } + + /// The position the conversation cache resumed the last request at (equals `reused_tokens` unless + /// `STRATA_CKPT_REREAD` re-read that prefix from 0). + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn resume_point(&self) -> usize { + self.resume_point + } + + /// Drop every conversation checkpoint and the live state: the next request reads its whole prompt. + #[cfg_attr(not(test), allow(dead_code))] + pub(crate) fn forget_conversation(&mut self) { + if let Some(conversation) = self.conversation.as_mut() { + conversation.invalidate(); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.invalidate(); + } + } + + /// Verification arm: while set, requests read their whole prompt on the grid without using or changing the prefix + /// cache (the reference a cached request must reproduce). + #[allow(dead_code)] + pub(crate) fn prefix_bypass(&mut self, bypass: bool) { + if let Some(prefix) = self.prefix.as_mut() { + prefix.set_bypass(bypass); + } + } + + /// Drop the cached sessions nobody used for the retention time (60 minutes by default); the idle loop calls this. + pub(crate) fn prefix_expire_idle(&mut self) -> usize { + self.prefix.as_mut().map_or(0, |prefix| prefix.expire_idle()) + } + + /// The prefix cache's summary for a front router (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_summary(&self, max_heads: usize) -> Option { + self.prefix.as_ref().map(|prefix| prefix.summary(max_heads)) + } + + /// The `prefix_match` query: how many tokens of the prompt whose block hash chain is `chain` are cached. + #[allow(dead_code)] + pub(crate) fn prefix_match(&self, chain: &[u64]) -> Option { + self.prefix.as_ref().map(|prefix| prefix.prefix_match(chain)) + } + + /// The prefix cache's metrics line (`None` when the cache is off). + #[allow(dead_code)] + pub(crate) fn prefix_metrics(&self) -> Option { + self.prefix.as_ref().map(|prefix| prefix.describe()) + } + + /// Bytes the prefix cache holds now (0 when it is off). + #[allow(dead_code)] + pub(crate) fn prefix_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.bytes()) + } + + /// The prefix cache's current byte budget (0 when it is off or fully shed). + #[allow(dead_code)] + pub(crate) fn prefix_budget_bytes(&self) -> usize { + self.prefix.as_ref().map_or(0, |prefix| prefix.budget_bytes()) + } + + /// Close every owner in dependency order; the first failure is reported after all were attempted. + pub(crate) fn close(self) -> Result<()> { + let Self { + conversation, residency, history, ple_history, ple_scratch, arena, expert_cache, executor, draft, session, pool, kar, + moe, dense, output, embedding, .. + } = self; + drop(conversation); + // the span cache retains registered-source spans of the bank `moe` closes below + drop(residency); + let mut first: Option = None; + let mut note = |result: Result<()>| { + if let Err(error) = result { + first.get_or_insert(error); + } + }; + note(history.close()); + note(ple_history.release().map_err(|_| Error::CudaExecution)); + note(ple_scratch.release().map_err(|_| Error::CudaExecution)); + drop(arena); + if let Some(cache) = expert_cache { + note(cache.close().map_err(|e| super::original_serve_verifier::driver_error(&e))); + } + note(executor.close()); + note(draft.close()); + drop((session, pool, kar)); + note(moe.close()); + note(dense.close()); + note(output.close()); + note(embedding.close()); + first.map_or(Ok(()), Err) + } + + fn mark_broken(&mut self, error: Error) { + self.broken.get_or_insert(error); + } + + /// Hand the twelve QSA owners to a fresh verifier and run the request's decode phase over it. + fn decode_phase( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + let Self { + binding, + context, + config, + settings, + max_cells, + rope, + blobs, + formats, + full_policy, + controller, + arm_label, + verifier_max_t, + history, + ple_history, + ple_scratch, + executor, + draft, + session, + pool, + kar, + moe, + dense, + output, + broken, + conversation, + expert_cache, + residency, + refill_pending, + refill_due, + marks, + prefix, + tail_consumed, + .. + } = self; + let binding: &ModelBinding = *binding; + let context: &'ctx Context<'ctx> = *context; + if controller.is_failed() { + // a failed restore/finish poisoned the controller; its adaptive cadence is the only thing lost + *controller = settings.controller()?; + } + crate::bringup_trace!("DBG[{:.0}s] decode_phase start", dbg_el()); + let sampling = RequestSampling::new(request.params, request.path)?; + let n = request.prompt.len(); + let base = session.original_verified_base()?; + crate::bringup_trace!("DBG[{:.0}s] decode: base position {} (n-1 = {})", dbg_el(), base.position, n as u64 - 1); + if base.position != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + // generate.cpp `ver.set_pcie_mode`: only a window that can stage anything over PCIe records the copy kernel. + let pcie_mode = match (expert_cache.as_ref(), moe.original_expert_bank()) { + (Some(_), Some(bank)) if config.expert_tier.pcie_num_for(bank.pageable()) > 0 => { + config.expert_tier.pcie_mode.graph_mode(bank.pageable(), blobs.spans_tile_blobs()).ok_or(Error::Unsupported( + super::contract::Stage::Session, + ))? + } + _ => 0, + }; + let p = profile::span("decode.seed_ple"); + seed_ple_history(&base, ple_history).map_err(|f| SpecError::Forward(f.error))?; + drop(p); + // the window reads the shared experts of all 48 layers in place: load/refresh them together first + let p = profile::span("decode.shared"); + let shared = moe.ensure_original_verify_shared(binding)?; + drop(p); + crate::bringup_trace!("DBG[{:.0}s] decode: shared experts loaded", dbg_el()); + let owners = executor.take_qsa_owners()?; + let ple_history: &DeviceBuffer<'ctx> = &*ple_history; + let weights = VerifyWeights { dense: &*dense, moe: &*moe, shared: &shared, formats: &*formats, ple_scratch: &*ple_scratch }; + let p = profile::span("decode.assemble"); + // queued after assembly's own uploads (canonical GDN image), before the graph capture + let mut queue_refill = || -> Result<()> { + if !std::mem::take(&mut *refill_due) { + return Ok(()); + } + if let Some(cache) = expert_cache.as_mut() { + let _p = profile::span("prefill.refill"); + original_serve_residency::refill_lent(binding, &*moe, cache, &mut residency.spans, true)?; + *refill_pending = true; + } + Ok(()) + }; + let assembled = assemble( + binding, &weights, context, &*output, &base, owners, ple_history, rope, blobs, *verifier_max_t, *max_cells, + pcie_mode, &mut queue_refill, + ); + drop(p); + marks.assembled = marks.since(); + // the lent slots' refill copies (queued at the end of the prompt phase) have run behind the assembly: wait for them + // before a window or the tier's own bookkeeping touches the cache + if std::mem::take(refill_pending) { + if let Some(cache) = expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + broken.get_or_insert(error); + if let Ok(resources) = assembled { + let _ = disassemble(resources).map(|owners| executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners)); + } + return Err(SpecError::Forward(error)); + } + } + } + vram_note(context, "decode after assemble"); + crate::bringup_trace!("DBG[{:.0}s] decode: assemble -> {}", dbg_el(), if assembled.is_ok() { "ok" } else { "ERR" }); + let resources = match assembled { + Ok(resources) => resources, + Err(lost) => { + operator_line("assemble", &lost.failure); + if let Some(owners) = lost.owners { + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } else { + broken.get_or_insert(Error::IdentityMismatch); + } + return Err(SpecError::Forward(lost.failure.error)); + } + }; + let DecodeResources { verifier, qsa, slots } = resources; + // the NaN guard's retry takes a refused window back from these (OriginalVerifier::discard_window) + qsa.set_window_snapshots(settings.nan_guard.retries > 0); + let committed = request.prompt[..n - 1].to_vec(); + // The window's expert tier: the GPU share first and the CPU pool on the rest, or the CPU pool alone. + let mut gpu_pool; + let pool: &mut dyn OriginalServePool<'ctx> = match (expert_cache.as_mut(), moe.original_expert_bank()) { + (Some(cache), Some(bank)) => { + let pcie_num = config.expert_tier.pcie_num_for(bank.pageable()); + let tail_rank = original_serve_residency::effective_tail_rank(&*cache); + let pcie_locked = if pcie_num > 0 && original_serve_residency::pcie_locked_only() { bank.locked_experts() } else { Vec::new() }; + gpu_pool = GpuExpertPool { + binding, + moe: &*moe, + cache, + bank, + cpu: &mut *pool, + state: &mut *residency, + pcie_num, + adapt_every: config.expert_tier.adapt_every, + adapt_swaps: config.expert_tier.adapt_swaps as usize, + tail_rank, + pcie_locked, + }; + &mut gpu_pool + } + (Some(_), None) => return Err(SpecError::Forward(Error::IdentityMismatch)), + (None, _) => &mut *pool, + }; + let owners = HostOwners { + binding, + dense: &*dense, + context, + session: &mut *session, + draft: &mut *draft, + executor: &mut *executor, + kar: kar.as_mut(), + history: &mut *history, + pool, + qsa: Rc::clone(&qsa), + slots, + ple_history, + policy: &*full_policy, + }; + let want_tail = config.prefix.as_ref().is_some_and(|p| p.tail == TailMode::Reply) && prefix.is_some(); + controller.set_final_draft(want_tail); + *tail_consumed = None; + let host = OriginalServeHost::new(owners, committed, config.max_context as u64, sampling); + let (served, verifier, outcome) = match host { + Err(error) => (Err(SpecError::Forward(error)), verifier, None), + Ok(host) => { + let port = super::original_serve_engine::TracePort(NativeServePort::new(verifier, host)); + let engine = OriginalServeEngine::new(port, VOCABULARY, settings.max_t, settings.max_drafts()); + match engine { + Err(error) => { + // `new` consumed the port on failure; the verifier is gone with it. Treated as lost below. + let _ = error; + broken.get_or_insert(Error::IdentityMismatch); + return Err(SpecError::Forward(Error::IdentityMismatch)); + } + Ok(mut engine) => { + crate::bringup_trace!("DBG[{:.0}s] decode: engine ready, serving", dbg_el()); + let started = Instant::now(); + let serve_span = profile::span("decode.serve"); + let result = engine.set_min_p(request.spec_min_p).map_err(SpecError::Forward).and_then(|()| { + serve_request( + controller, + &mut engine, + &request.prompt, + request.max_new, + request.spec_min_p, + &request.eos, + |tokens| { + if marks.first_round.is_nan() { + marks.first_round = marks.since(); + } + emit(tokens) + }, + &mut *cancel, + || started.elapsed().as_secs_f64() * 1e3, + ) + }); + drop(serve_span); + { + // the controller's round counters belong to this request in every window policy + let stats = controller.take_stats(); + if super::original_spec_controller::stats_enabled() { + eprintln!("DBG spec-stats arm={} {}", arm_label, stats.line()); + } + } + if let Err(e) = &result { crate::bringup_trace!("DBG[{:.0}s] serve_request err {e:?}", dbg_el()); } + let (mut verifier, mut host) = engine.into_port().0.into_parts(); + // STRATA_VERIFY_PROFILE=1: the GPU stage times of the request's windows (empty otherwise) + let gpu_profile = verifier.profile_report(); + if !gpu_profile.is_empty() { + eprintln!("DBG verify-profile:{gpu_profile}"); + } + // 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 = conversation.is_some() + && matches!(result, Ok(_) | Err(SpecError::Cancelled)) + && host.draft_in_step(); + // prefix cache, TailMode::Reply: the session settled and the ring in step (the final window was drafted) + let tail = want_tail && result.is_ok() && prefix.is_some() && host.draft_in_step(); + if want_tail && result.is_ok() && !tail { + operator_text("prefix tail: the draft ring is not at the session's position; no checkpoint at the end of this decode"); + } + if (result.is_ok() && config.settle_state) || live || tail { + match host.settle_state(&mut verifier) { + Ok(()) if live => { + if let Some(conversation) = conversation.as_mut() { + conversation.note_live(host.committed().to_vec()); + } + } + Ok(()) if tail => *tail_consumed = Some(host.committed().to_vec()), + Ok(()) => {} + Err(error) => { + broken.get_or_insert(error); + } + } + } + let outcome = host.finish(); + (result, verifier, Some(outcome)) + } + } + } + }; + // 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. + let p = profile::span("decode.release_mtp"); + let released = executor.mtp_release_verifier(binding); + drop(p); + if let Err(error) = released { + operator_line("release MTP verifier bindings", &failure(error)); + broken.get_or_insert(error); + } + // Close the verifier (drains both streams, drops the graphs) and take the physical owners back at + // the session's lineage; an abandoned window is rolled back there. + let p = profile::span("decode.disassemble"); + let disassembled = disassemble(DecodeResources { verifier, qsa, slots }); + drop(p); + match disassembled { + Ok(owners) => { + let _p = profile::span("decode.adopt"); + if let Err(error) = executor.adopt_qsa_owners(binding, &*dense, &mut *session, owners) { + broken.get_or_insert(error); + } + } + Err(lost) => { + operator_line("disassemble", &lost); + broken.get_or_insert(lost.error); + } + } + if outcome.is_some_and(|o| o.failed) { + broken.get_or_insert(Error::IdentityMismatch); + } + served + } + + /// Condition `prompt[resume..n-1]` through the batched Original prefill, one chunk transaction at a time + /// (the session and the draft ring stand at `resume`; with the conversation cache's `STRATA_CKPT_REREAD` + /// they stand at 0 and the reread segment comes first). After each published chunk the conversation cache + /// takes its periodic and turn/root checkpoints. + /// + /// With the expert tier, the swaps in flight land first (generate.cpp `apply_pending(true)`), every chunk + /// borrows the cache's last slots (`prefill_chunk`) and every lent slot is refilled before the decode + /// phase, whatever the read's outcome (generate.cpp `refill`). + fn prefill_phase( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + self.residency.begin_request(); + self.seed_report = None; + if let Some(cache) = self.expert_cache.as_mut() { + let _p = profile::span("prefill.wait_swaps"); + cache.wait_swaps().map_err(|e| SpecError::Forward(super::original_serve_verifier::driver_error(&e)))?; + } + // LELEKA_ORIGINAL_SERVE_SEED: the MoE stage adds its host-known route counts per (layer, expert) + let seeding = self.config.expert_tier.seed_swaps > 0 && self.expert_cache.is_some(); + if seeding { + self.moe.capture_prompt_routing(true, self.config.expert_tier.seed_decay); + } + let p = profile::span("prefill.read"); + let read = self.prefill_actions(request, resume, cancel); + drop(p); + let _p = profile::span("prefill.refill"); + // a failed or cancelled read still refills at once (generate.cpp `refill`); a good one overlaps the copies with the + // decode phase's host-side assembly + // (the prompt-routing seed needs the lent slots refilled first, so it turns the deferral off for its requests) + let defer = read.is_ok() && !seeding && original_serve_residency::refill_defer_enabled() && self.loan.is_some() && self.expert_cache.is_some(); + let refilled = match (self.loan, self.expert_cache.as_mut()) { + (Some(_), Some(cache)) if !defer => { + original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false).map(|_| ()) + } + _ => Ok(()), + }; + let routing = if seeding { self.moe.take_prompt_routing() } else { None }; + let seeded = match (&read, &refilled, routing) { + (Ok(()), Ok(()), Some(counts)) if !defer => { + let _p = profile::span("prefill.seed"); + self.seed_residency(&counts) + } + _ => Ok(()), + }; + self.refill_due = defer; + match (read, refilled, seeded) { + (Ok(()), Err(error), _) | (Ok(()), Ok(()), Err(error)) => { + self.mark_broken(error); + Err(SpecError::Forward(error)) + } + (read, _, _) => read, + } + } + + /// Put the prompt's own routing into the tier's placement before the first window (see `original_serve_seed`). + fn seed_residency(&mut self, counts: &[f32]) -> Result<()> { + let tier = &self.config.expert_tier; + let (max, keep, usage) = (tier.seed_swaps, tier.seed_keep, tier.seed_usage); + let Some(cache) = self.expert_cache.as_mut() else { return Ok(()) }; + let started = Instant::now(); + let max_rows = tier.seed_max_rows; + if max_rows > 0 { + let rows = original_serve_seed::summarize(counts, &[]).rows; + if rows > max_rows as u64 { + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!("DBG seed: skipped, the prompt routed {rows} rows (cap {max_rows})"); + } + return Ok(()); + } + } + let swaps = original_serve_seed::plan(counts, cache, max, keep); + let planned = started.elapsed(); + let mut report = original_serve_seed::summarize(counts, &swaps); + original_serve_seed::queue_swaps(self.binding, &self.moe, cache, &mut self.pool, &mut self.residency.spans, &swaps)?; + report.plan_ms = planned.as_secs_f64() * 1e3; + report.queue_ms = (started.elapsed() - planned).as_secs_f64() * 1e3; + self.residency.add_usage(counts, usage); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + eprintln!( + "DBG seed: prompt rows {} routed -> {} swaps (gain {:.0}, most in one layer {}), plan {:.2} ms, queue {:.2} ms", + report.rows, report.planned, report.gain, report.max_layer_swaps, report.plan_ms, report.queue_ms + ); + } + self.seed_report = Some(report); + if std::env::var_os("LELEKA_SEED_TRACE").is_some() { + self.seed_counts = Some(counts.to_vec()); + } + Ok(()) + } + + /// `LELEKA_SEED_TRACE`: how much of the request's decode routing (the adaptive counts, so for a static arm) the resident + /// set covers: the starting profile's set, the prompt's top experts (what the seed installs, per layer slot counts of the + /// profile) and the best any static set could do (the decode's own top experts). + fn seed_coverage_trace(&mut self) { + let Some(prompt) = self.seed_counts.take() else { return }; + let usage = self.residency.usage(); + if usage.len() != prompt.len() || self.config.expert_tier.adapt_every != 0 { + return; + } + let mut slots = [0usize; 48]; + let mut initial = vec![false; 48 * 512]; + for &(layer, expert) in self.initial_owners.iter().flatten() { + slots[layer] += 1; + initial[layer * 512 + expert] = true; + } + let total: f64 = usage.iter().map(|&u| f64::from(u)).sum(); + if total <= 0.0 { + return; + } + let (mut by_prompt, mut oracle, mut by_initial) = (0f64, 0f64, 0f64); + for layer in 0..48 { + let range = layer * 512..(layer + 1) * 512; + let mut order: Vec = (0..512).collect(); + order.sort_by(|&a, &b| prompt[range.start + b].total_cmp(&prompt[range.start + a])); + by_prompt += order.iter().take(slots[layer]).map(|&e| f64::from(usage[range.start + e])).sum::(); + let mut best: Vec = usage[range.clone()].to_vec(); + best.sort_by(|a, b| b.total_cmp(a)); + oracle += best.iter().take(slots[layer]).map(|&u| f64::from(u)).sum::(); + by_initial += (0..512).filter(|&e| initial[range.start + e]).map(|e| f64::from(usage[range.start + e])).sum::(); + } + // Opt-in: `seed_counts` is only recorded under LELEKA_SEED_TRACE, so this returns early (and prints nothing) otherwise. + eprintln!( + "DBG seed-coverage: decode entries {total:.0}; covered by the starting set {:.1}%, the prompt's top experts {:.1}%, the decode's own top experts {:.1}% (oracle)", + 100.0 * by_initial / total, + 100.0 * by_prompt / total, + 100.0 * oracle / total + ); + } + + fn prefill_actions( + &mut self, + request: &ServeRequest, + resume: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let binding: &ModelBinding = self.binding; + let n = request.prompt.len(); + crate::bringup_trace!("DBG[{:.0}s] prefill_phase start n={n} resume={resume}", dbg_el()); + // generate.cpp: mtp.set_prompt_len(n) before the prompt is read; the draft cap and the request's + // sampling parameters configure the actor for the whole request. + let mtp_setup_span = profile::span("prefill.mtp_setup"); + self.executor.set_mtp_prompt_len(binding, n as i64)?; + self.executor.set_mtp_max_drafts(binding, i32::try_from(self.settings.max_drafts()).map_err(|_| Error::Overflow)?)?; + self.executor.set_mtp_draft_sampling(binding, &request.params)?; + drop(mtp_setup_span); + if n < 2 { + return Ok(()); + } + let setup_span = profile::span("prefill.setup"); + let tokens: Vec = request.prompt.iter().map(|&t| t as u32).collect(); + let source = OriginalPromptInput::from_tokenized(binding, &tokens)?; + let options = PromptOptions { + context_tokens: usize::try_from(self.config.max_context).map_err(|_| Error::Overflow)?, + prompt_cache: false, + turn_token: None, + root_min: 0, + // every conditioning read goes through the batched prefill (the verify-window read of short + // prompts needs the verifier during the prompt phase; see the open items) + short_read: 64, + force_batched: true, + verify_width: 4, + auto_max: 8192, + grid: 0, + }; + let (options, reread_to) = match (&self.prefix, &self.conversation) { + // the prefix cache reads on its grid and has no turn/root cuts: every checkpoint is a pure function of its tokens + // (a request that resumes between two grid points, from a request-end checkpoint, reads its suffix in as few chunks as the + // capacity allows: its states are not grid-canonical anyway) + (Some(prefix), _) => (PromptOptions { grid: if resume % prefix.block_tokens() == 0 { prefix.block_tokens() } else { 0 }, ..options }, None), + (None, Some(conversation)) => (conversation.config().plan_options(options), conversation.reread_to()), + (None, None) => (options, None), + }; + let capacity = self.config.capacity; + let plan = PromptPlan::new(&tokens, resume, reread_to, None, options, capacity).map_err(|e| { crate::bringup_trace!("DBG[{:.0}s] PromptPlan::new err {e:?} (n={n} capacity={capacity})", dbg_el()); plan_error(e) })?; + crate::bringup_trace!("DBG[{:.0}s] prompt plan ok", dbg_el()); + drop(setup_span); + for action in plan { + crate::bringup_trace!("DBG[{:.0}s] prompt action path={:?} first={} count={}", dbg_el(), action.path, action.first, action.count); + if action.path == PromptPath::FinalSeed { + // the last prompt token is the first verify input of the decode phase + break; + } + let PromptPath::Batched { .. } = action.path else { + return Err(Error::IdentityMismatch.into()); + }; + if self.session.target_origin()?.next_position() != action.first as u64 { + return Err(Error::IdentityMismatch.into()); + } + if cancel() { + return Err(SpecError::Cancelled); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.before_chunk(action.first); + } + self.prefill_chunk(&source, action.count, cancel)?; + self.after_prompt_action(&request.prompt, &action); + self.prefix_after_chunk(&request.prompt, action.first + action.count); + } + if self.session.target_origin()?.next_position() != (n as u64 - 1) { + return Err(Error::IdentityMismatch.into()); + } + self.prefix_after_prefill(&request.prompt); + Ok(()) + } + + /// One batched chunk of `count` rows from the session's position: the forward transaction and its publication. + /// With a loan the chunk's buffers are the expert cache's last slots, lent for this chunk only (the lent + /// slots stay misses until `prefill_phase` refills them); otherwise the stack's own buffers. + fn prefill_chunk( + &mut self, + source: &Rc, + count: usize, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let Self { + binding, moe, arena, layout, expert_cache, loan, loan_tiers, executor, draft, session, kar, dense, embedding, + scalar_policy, .. + } = self; + let mut chunk = PromptChunk { + binding: *binding, + executor: &mut *executor, + dense: &*dense, + session: &mut *session, + source, + kar: kar.as_mut(), + moe: &mut *moe, + draft: &mut *draft, + embedding: &*embedding, + scalar_policy: &*scalar_policy, + }; + let first = chunk.session.target_origin().map(|o| o.next_position()).unwrap_or(0); + super::prefill_profile::begin_chunk(); + let ran = match (*loan, expert_cache.as_mut(), arena.as_mut()) { + (Some(slots), Some(cache), _) => match { + let _span = super::prefill_profile::span(super::prefill_profile::Stage::Lend, None); + // the smallest rung of the ladder that holds the chunk + let (slots, options) = tier_for(loan_tiers, count).map_or((slots, *layout), |t| (t.slots, t.layout)); + cache.lend_prefill_tail(slots, options) + } { + Ok(mut lent) => chunk.run(count, &mut lent, cancel), + Err(e) => Err(SpecError::Forward(super::original_serve_verifier::driver_error(&e))), + }, + (_, _, Some(own)) => chunk.run(count, own, cancel), + _ => Err(Error::IdentityMismatch.into()), + }; + if ran.is_ok() { + super::prefill_profile::end_chunk(first, count); + } + ran + } + + /// The prefix cache at the end of the prefill: with `TailMode::Prompt` or `Reply` a checkpoint at `n - 1`, where the next turn of + /// the session resumes (its prompt starts with this one). A checkpoint that cannot be taken costs only itself. + fn prefix_after_prefill(&mut self, prompt: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_prefill"); + match prefix.after_prefill(self, prompt) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (prompt end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (prompt end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the prefill; skipped")), + } + self.prefix = Some(prefix); + } + + /// The end of the decode (`TailMode::Reply`): a checkpoint at the end of the prompt and the committed reply. The session is settled and the + /// draft ring stands at its position (`decode_phase` made sure); the cells past the prompt were produced by the decode. + fn prefix_after_decode(&mut self, consumed: &[i32]) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_decode"); + match prefix.after_decode(self, consumed) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + operator_text(&format!("prefix tail admit (decode end): tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + Ok(other) => operator_text(&format!("prefix tail (decode end) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())), + Err(error) => operator_text(&format!("prefix cache: {error:?} while checkpointing the end of the decode; skipped")), + } + self.prefix = Some(prefix); + } + + /// The prefix cache after a published chunk: a checkpoint at the grid point if the policy wants one. A checkpoint + /// that cannot be built costs the cache, never the request. + fn prefix_after_chunk(&mut self, prompt: &[i32], end: usize) { + let Some(mut prefix) = self.prefix.take() else { return }; + let _span = profile::span("prefix.after_chunk"); + match prefix.after_chunk(self, prompt, end) { + Ok(ChunkOutcome::Admitted { tokens, new_blocks, bytes, park_ms }) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() { + operator_text(&format!("prefix admit: tokens={tokens} new_blocks={new_blocks} mib={} park_ms={park_ms:.1}", bytes >> 20)); + } + } + Ok(other) => { + if std::env::var_os("LELEKA_PREFIX_TRACE").is_some() && !matches!(other, ChunkOutcome::Nothing) { + operator_text(&format!("prefix admit (grid point {end}) not taken: {other:?}: {}", prefix.take_note().unwrap_or_default())); + } + } + Err(error) => { + operator_text(&format!("prefix cache: {error:?} while checkpointing; dropping the cache")); + prefix.invalidate(); + } + } + self.prefix = Some(prefix); + } + + /// A cancel between two prompt chunks leaves the session at the last published one: that is still the request's conversation + /// (`ServeConversation::note_cancelled_prefill`). The claim needs the same state a live continuation needs at the next + /// request: nothing lost, the recurrent state settled and the draft ring at the session's position. + fn keep_conversation_after_cancelled_prefill(&mut self, request: &ServeRequest) { + let Some(mut conversation) = self.conversation.take() else { return }; + if let Ok(position) = ResumeDevice::position(self) { + let in_step = ResumeDevice::live_in_step(self); + if conversation.note_cancelled_prefill(&request.prompt, position, in_step) { + operator_text(&format!("cancelled request keeps its conversation: {position} tokens live")); + } + } + self.conversation = Some(conversation); + } + + /// The conversation cache's bookkeeping after a published chunk. A checkpoint that cannot be saved costs + /// the cache, never the request: the cache is dropped and the request goes on. + fn after_prompt_action(&mut self, prompt: &[i32], action: &crate::backend::original_prompt::PromptAction) { + let Some(mut conversation) = self.conversation.take() else { return }; + let _span = profile::span("conv.after_action"); + if let Err(error) = conversation.after_action(self, prompt, action) { + operator_text(&format!("conversation cache: {error}; dropping the cache")); + conversation.invalidate(); + } + self.conversation = Some(conversation); + } +} + +/// The owners one batched prompt chunk needs, so the chunk runs over the stack's own buffers or a loan. +struct PromptChunk<'s, 'ctx> { + binding: &'s ModelBinding, + executor: &'s mut OriginalPromptExecutor<'ctx>, + dense: &'s DenseWeightCache<'ctx>, + session: &'s mut QwenSession<'ctx>, + source: &'s Rc, + kar: Option<&'s mut KarPleCache<'ctx>>, + moe: &'s mut MoeWeightCache<'ctx>, + draft: &'s mut super::session::original_prompt::draft::OriginalDraftSession<'ctx>, + embedding: &'s OriginalPromptEmbedding<'ctx>, + scalar_policy: &'s OriginalMtpScalarPolicy, +} +impl<'ctx> PromptChunk<'_, 'ctx> { + fn run( + &mut self, + count: usize, + arena: &mut OriginalPrefillArena<'_, 'ctx>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result<(), SpecError> { + let pending = self.executor.forward( + self.binding, + self.dense, + &mut *self.session, + self.source, + count, + self.kar.as_deref_mut(), + &mut *self.moe, + &mut *arena, + &mut *self.draft, + self.embedding, + self.scalar_policy, + || cancel(), + ); + if let Err(e) = &pending { crate::bringup_trace!("DBG[{:.0}s] executor.forward err {e:?}", dbg_el()); } + let pending = match pending { + Ok(pending) => pending, + Err(error) if cancel() => { + let _ = error; + return Err(SpecError::Cancelled); + } + Err(error) => return Err(SpecError::Forward(error)), + }; + crate::bringup_trace!("DBG[{:.0}s] forward ok, publishing", dbg_el()); + let _span = super::prefill_profile::span(super::prefill_profile::Stage::Publish, None); + pending.publish()?; + crate::bringup_trace!("DBG[{:.0}s] published", dbg_el()); + Ok(()) + } +} + +static DBG_T0: std::sync::OnceLock = std::sync::OnceLock::new(); +/// Bring-up tracing clock (seconds since the first call); remove together with the DBG lines. +/// `LELEKA_SERVE_PROFILE=1`: the card's free VRAM at a point of the stack's life (where the auto-sized cache's room goes). +fn vram_note(context: &Context<'_>, label: &str) { + if profile::enabled() { + if let Ok((free, total)) = context.memory_info() { + eprintln!("DBG vram {label}: free {} MiB of {} MiB", free >> 20, total >> 20); + } + } +} +pub(crate) fn dbg_el() -> f32 { + DBG_T0.get_or_init(std::time::Instant::now).elapsed().as_secs_f32() +} + +/// One operator line per CPU kind and per CUDA device: which kernel family the process runs on each (logging only). +fn report_kernel_selection() { + #[cfg(all(any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))] + for line in leleka_native_cpu_expert::cpu_kernel_report() { + operator_note(&line); + } + for line in leleka_cuda_driver::gpu_kernel_report() { + operator_note(&line); + } +} + +fn operator_note(text: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {text}"); +} + +fn operator_line(what: &str, failure: &ServeFailure) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {what}: {}", failure.describe()); +} + +fn operator_text(line: &str) { + use std::io::Write; + let _ = writeln!(std::io::stderr().lock(), "leleka-serve {line}"); +} + +/// The conversation cache's device side over the stack's own owners. +impl<'a, 'ctx> ResumeDevice for OriginalServeStack<'a, 'ctx> { + type Point = StackPoint<'ctx>; + fn zero(&mut self) -> Result<()> { + if RequestOwners::is_fresh(self) { + return Ok(()); + } + RequestOwners::reset(self) + } + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + fn save(&mut self) -> Result> { + if let Some(error) = self.broken { + return Err(error); + } + let session = self.executor.checkpoint_session(self.binding, &mut self.session)?; + let draft = self.draft.checkpoint(self.binding, &self.session)?; + Ok(StackPoint { session, draft }) + } + fn point_position(point: &StackPoint<'ctx>) -> u64 { + point.session.next_position() + } + fn restore(&mut self, point: &StackPoint<'ctx>) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + // a refused re-stamp touches nothing; a failed physical restore poisons the executor + let rebased = point.session.rebased_onto_current(&self.session)?; + let restored = self.executor.restore_session(self.binding, &self.dense, &mut self.session, &rebased); + if let Err(error) = restored { + self.mark_broken(error); + } + restored + } + fn restore_draft(&mut self, point: &StackPoint<'ctx>, resume: usize) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let result = (|| { + self.draft.resume_at(self.binding, &self.dense, &self.session, &point.draft)?; + let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; + self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } + fn live_in_step(&self) -> bool { + self.broken.is_none() + && self.session.original_state_lag().is_none() + && self.draft.in_step(self.binding, &self.session) + } +} + +impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> { + /// `RequestOwners::resume` with the prefix cache: install the deepest checkpoint that is a prefix of the prompt. + fn prefix_resume(&mut self, request: &ServeRequest) -> Option { + let mut prefix = self.prefix.take()?; + let _resume_span = profile::span("request.resume"); + let n = request.prompt.len(); + let resume = if self.broken.is_some() { + prefix.invalidate(); + None + } else { + match prefix.begin(self, &request.prompt) { + Ok(Some(start)) => { + self.reused = start.resume; + self.resume_point = start.resume; + operator_text(&format!( + "prefix request: n={n} hit=yes resume={} switched={} branch={} copied_tokens={} import_ms={:.1} (state+kv {:.1}, draft {:.1}) match_us={:.0} live_tokens={}", + start.resume, + start.switched, + start.branch, + start.copied_tokens, + start.import_ms, + prefix.last_import_split().0, + prefix.last_import_split().1, + start.match_us, + prefix.live_tokens() + )); + Some(start.resume) + } + Ok(None) => { + operator_text(&format!("prefix request: n={n} hit=no resume=0 match_us={:.0}", prefix.last_match_us())); + None + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("prefix cache: {error:?}; reading the whole prompt")); + prefix.invalidate(); + None + } + } + }; + self.prefix = Some(prefix); + resume + } +} + +/// The prefix cache's device side over the stack's own owners. +impl<'a, 'ctx> PrefixDevice for OriginalServeStack<'a, 'ctx> { + type State = StackState; + type Block = StackBlock; + fn position(&self) -> Result { + Ok(self.session.target_origin()?.next_position()) + } + fn estimate(&self, block_tokens: usize) -> (usize, usize) { + (PARKED_STATE_ESTIMATE, block_tokens * PARKED_BYTES_PER_TOKEN) + } + fn park_state(&mut self) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_state"); + let session = self.executor.park_session(self.binding, &mut self.session)?; + let draft = self.draft.checkpoint(self.binding, &self.session)?; + Ok(StackState { session, draft }) + } + fn park_block(&mut self, first: usize, tokens: usize) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_block"); + self.executor.park_block(&self.session, first, tokens).map(StackBlock) + } + fn park_tail(&mut self, first: usize, tokens: usize) -> Result { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("prefix.park_tail"); + self.executor.park_block(&self.session, first, tokens).map(StackBlock) + } + fn import(&mut self, state: &StackState, blocks: &[(usize, &StackBlock)]) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let blocks: Vec<&ParkedBlock> = blocks.iter().map(|(_, block)| &block.0).collect(); + let _p = profile::span("prefix.import_session"); + // a refused import touches nothing; a failed physical one poisons the executor + let imported = self.executor.import_session(self.binding, &self.dense, &mut self.session, &state.session, &blocks); + if let Err(error) = imported { + self.mark_broken(error); + } + imported + } + fn restore_draft(&mut self, state: &StackState, resume: usize) -> Result<()> { + if let Some(error) = self.broken { + return Err(error); + } + let result = (|| { + { + let _p = profile::span("prefix.draft_resume_at"); + self.draft.resume_at(self.binding, &self.dense, &self.session, &state.draft)?; + } + let upto = i64::try_from(resume).map_err(|_| Error::Overflow)?; + let _p = profile::span("prefix.mtp_kv_restore"); + self.executor.mtp_kv_restore(self.binding, &self.session, &mut self.draft, upto) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } +} + +impl<'a, 'ctx> RequestOwners for OriginalServeStack<'a, 'ctx> { + fn is_fresh(&self) -> bool { + self.broken.is_none() + && self.session.original_state_lag().is_none() + && self.session.target_origin().is_ok_and(|origin| origin.next_position() == 0) + } + fn reset(&mut self) -> std::result::Result<(), Error> { + if let Some(error) = self.broken { + return Err(error); + } + let _p = profile::span("request.reset"); + let result = (|| { + let empty = self.empty_session.rebased_empty(&self.session)?; + self.executor.restore_session(self.binding, &self.dense, &mut self.session, &empty)?; + self.draft.reset_to_empty(self.binding, &self.dense, &self.session, &self.empty_draft) + })(); + if let Err(error) = result { + self.mark_broken(error); + } + result + } + fn resume(&mut self, request: &ServeRequest) -> Option { + self.reused = 0; + self.resume_point = 0; + if self.prefix.is_some() { + return self.prefix_resume(request); + } + let mut conversation = self.conversation.take()?; + let _resume_span = profile::span("request.resume"); + let resume = if self.broken.is_some() { + conversation.invalidate(); + None + } else { + match conversation.begin(self, &request.prompt) { + Ok(start) => { + self.reused = start.read_from; + self.resume_point = start.resume; + Some(start.resume) + } + Err(error) => { + // the cache is an optimisation: drop it and start from the empty prompt (`reset`) + operator_text(&format!("conversation cache: {error}; reading the whole prompt")); + conversation.invalidate(); + None + } + } + }; + self.conversation = Some(conversation); + resume + } + fn prefill(&mut self, request: &ServeRequest, resume: usize, cancel: &mut dyn FnMut() -> bool) -> std::result::Result<(), SpecError> { + let started = Instant::now(); + self.timing = (0.0, 0.0); + self.marks.resumed = self.marks.since(); + let result = self.prefill_phase(request, resume, cancel); + if matches!(result, Err(SpecError::Cancelled)) { + self.keep_conversation_after_cancelled_prefill(request); + } + self.marks.prefilled = self.marks.since(); + self.timing.0 = started.elapsed().as_secs_f64() * 1e3; + result + } + fn decode( + &mut self, + request: &ServeRequest, + emit: &mut dyn FnMut(&[i32]) -> Result<()>, + cancel: &mut dyn FnMut() -> bool, + ) -> std::result::Result { + let started = Instant::now(); + let tier0 = self.residency.stats; + let result = self.decode_phase(request, emit, cancel); + match (result.is_ok(), self.tail_consumed.take()) { + (true, Some(consumed)) if self.broken.is_none() => self.prefix_after_decode(&consumed), + _ => {} + } + // an exit before the decode phase queued the refill still refills now; one before it waited still waits + if std::mem::take(&mut self.refill_due) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::refill_lent(self.binding, &self.moe, cache, &mut self.residency.spans, false) { + self.mark_broken(error); + } + } + } + if std::mem::take(&mut self.refill_pending) { + if let Some(cache) = self.expert_cache.as_mut() { + if let Err(error) = original_serve_residency::settle_refill(cache) { + self.mark_broken(error); + } + } + } + self.timing.1 = started.elapsed().as_secs_f64() * 1e3; + profile::add("decode.phase", self.timing.1); + if profile::enabled() { + let t1 = self.residency.stats; + let (v, p, c) = (t1.vram_entries - tier0.vram_entries, t1.pcie_entries - tier0.pcie_entries, t1.cpu_entries - tier0.cpu_entries); + let all = (v + p + c).max(1) as f64; + // the Original's hit rate: VRAM entries over VRAM + CPU entries (PCIe entries are in neither count) + eprintln!( + "DBG tier request: vram {v} ({:.1}%) pcie {p} ({:.1}%) cpu {c} ({:.1}%) hit_rate_original_def {:.1}% adaptations {} swaps {} pcie_num {}", + 100.0 * v as f64 / all, 100.0 * p as f64 / all, 100.0 * c as f64 / all, + 100.0 * v as f64 / ((v + c).max(1) as f64), t1.adaptations - tier0.adaptations, t1.swaps - tier0.swaps, + self.residency.pcie_lag.as_ref().map(|l| l.pcie_num()).or_else(|| self.residency.pcie_auto.as_ref().map(|a| a.pcie_num())).unwrap_or(self.config.expert_tier.pcie_num()) + ); + } + // graphs captured after the window/commit graphs: the MTP round programs of this request's drafts + let (capture_ms, instantiate_ms, _) = leleka_cuda_driver::original_capture_timing::take(); + profile::add("mtp.capture", capture_ms); + profile::add("mtp.instantiate", instantiate_ms); + profile::add("prefill.phase", self.timing.0); + profile::report("request"); + self.residency.flush_routing(); + self.seed_coverage_trace(); + result + } + fn finish(&mut self, ended: std::result::Result<(), ServeError>) { + let completed = self.broken.is_none() && matches!(ended, Ok(()) | Err(ServeError::Cancelled)); + if let Some(conversation) = self.conversation.as_mut() { + conversation.finish(completed); + } + if let Some(prefix) = self.prefix.as_mut() { + prefix.finish(completed); + let (admitted, park_ms, consider_ms) = prefix.request_parking(); + operator_text(&format!("prefix request done: admitted={admitted} park_ms={park_ms:.1} policy_ms={consider_ms:.1} {}", prefix.describe())); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_chunk_borrows_the_smallest_rung_that_holds_it() { + let blobs = ExpertBlobSizes::from_layer_bytes(std::array::from_fn(|l| 700_000 + 4096 * l), [700_000; 48], [900_000; 48]).unwrap(); + let layout = prefill_layout_options(8192, 262_144, &blobs); + let tiers: Vec = [(512usize, 600usize), (2048, 900)] + .into_iter() + .map(|(rows, slots)| LoanTier { rows, layout: PrefillLayoutOptions { capacity: rows, ..layout }, slots }) + .collect(); + assert_eq!(tier_for(&tiers, 1).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 512).map(|t| t.rows), Some(512)); + assert_eq!(tier_for(&tiers, 513).map(|t| t.rows), Some(2048)); + assert_eq!(tier_for(&tiers, 2048).map(|t| t.slots), Some(900)); + assert!(tier_for(&tiers, 2049).is_none(), "above the ladder the chunk borrows the full loan"); + assert!(tier_for(&[], 100).is_none()); + // the arena of a smaller rung is smaller + assert!(prefill_bytes(tiers[0].layout).unwrap() < prefill_bytes(tiers[1].layout).unwrap()); + assert!(prefill_bytes(tiers[1].layout).unwrap() < prefill_bytes(layout).unwrap()); + } + + #[test] + fn the_default_chunk_is_an_admitted_capacity_and_validation_follows_the_prefill_rules() { + let config = StackConfig::new(4096); + assert!(ADMITTED_CAPACITIES.contains(&config.capacity)); + for capacity in [256usize, 1024, 8192] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_ok(), "{capacity}"); + } + for capacity in [0usize, 255, 300, 16384, 32768] { + assert!(StackConfig { capacity, ..config.clone() }.validate().is_err(), "{capacity}"); + } + assert!(StackConfig { max_context: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 0, ..config.clone() }.validate().is_err()); + assert!(StackConfig { cpu_workers: 65, ..config.clone() }.validate().is_err()); + assert!(StackConfig { max_context: i64::MAX, ..config }.validate().is_err()); + } + + #[test] + fn the_conversation_cache_is_on_by_default_with_the_original_settings() { + let config = StackConfig::new(4096); + let conversation = config.conversation.as_ref().expect("--prompt-cache 6 is the default, as in the Original"); + assert_eq!((conversation.prompt_cache, conversation.prompt_cache_every, conversation.prompt_cache_root), (6, 16_384, 2048)); + assert_eq!(conversation.turn_token, Some(TURN_TOKEN)); + assert!(config.validate().is_ok()); + assert!(StackConfig { conversation: None, ..config }.validate().is_ok(), "the cache can be turned off"); + } + + #[test] + fn kv_defaults_to_the_production_int8_window_and_refuses_unported_formats() { + let config = StackConfig::new(4096); + assert_eq!((config.kv_format, config.kv_resident), (KvFormat::Int8, 32_768)); + assert_eq!(config.kv_footprint().map(|f| f.resident_pages), Some(8192)); + for kv_resident in [0usize, 1, 20_480, 40_000, 262_144] { + assert!(StackConfig { kv_resident, ..config.clone() }.validate().is_ok(), "{kv_resident}"); + } + assert!(StackConfig { kv_resident: 524_292, ..config.clone() }.validate().is_err()); + for kv_format in [KvFormat::Fp16, KvFormat::Q4_0, KvFormat::K8V4, KvFormat::Int8Keyless] { + assert_eq!( + StackConfig { kv_format, ..config.clone() }.validate(), + Err(Error::Unsupported(crate::qwen_forward::contract::Stage::Session)) + ); + } + } + + #[test] + fn plan_errors_keep_their_class() { + assert_eq!(plan_error(PlanError::InvalidInput), Error::InvalidDimension); + assert_eq!(plan_error(PlanError::Overflow), Error::Overflow); + } +} diff --git a/docs/original-serve.md b/docs/original-serve.md index 9e6df1bc..573af209 100644 --- a/docs/original-serve.md +++ b/docs/original-serve.md @@ -419,3 +419,8 @@ Recommendation: keep it off by default; enable it (`=on`) for chat- and agent-si where the answer continues the prompt's domain, on both machines; it is a loss-free no-op (+0.1 s) on long prompts, so a length cap is a choice, not a need. Not measured: a real multi-turn agent loop, where the conversation cache already skips most of the prefill (the seed then sees only the new rows). + +**Long prompts (STRA-245 decode gap, 2026-10-29, `claude/decode-tail`).** On the frozen 5-turn 245k session (prompts 45,766 / 105k / 153k / 199k / 247k tokens, RTX 5090, upstream ranked profile sha256 `8f59b4aa...`, 11,280 slots, `bin-e2e4`, 300 greedy tokens per turn) the seed +hurt: with the seed (default) the VRAM share of routed entries was 80-85 %, windows 0-20 of every request served about 230-250 CPU and 230-255 PCIe experts, 17.5-20 ms per round, 107-110 tok/s; with `LELEKA_ORIGINAL_SERVE_SEED=off` +93-96 %, 23-79 CPU experts in windows 0-20, 13.4-15.4 ms per round, 132-149 tok/s (turn 5 of both arms stalled on the PLE reads, a host-memory artifact, and is not counted). The seed keeps `keep=0`, so at 45k+ rows it replaces the profile's good set by the prompt's top experts (9-10 % of the decode routing, as measured at 16k above). +`LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS` (default 4096; 0 = no cap) now skips the seed for a prefill that routed more rows than that; below it nothing changes. Placement-only change: GPU and CPU round differently, so greedy ids are not invariant to it (see Quality above).