residency: no prompt-routing seed for a prefill that routed more than 4096 rows (LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS, 0 = no cap)

At 45k-247k prompt tokens the seed (default on, keep 0) replaced the ranked profile's resident set by the prompt's top experts and cost 25-35 % of decode on the frozen
245k session: VRAM share 80-85 % against 93-96 % with the seed off, windows 0-20 serving ~240 CPU + ~245 PCIe experts against 23-79 + 13-60, 17.5-20 against 13.4-15.4 ms per round,
107-110 against 132-149 tok/s (turns 1-4; one run each, bin-e2e4, upstream profile). Behaviour for prompts up to 4096 routed rows is unchanged. Placement-only; greedy ids can differ (GPU/CPU rounding).
Not yet measured with this binary; the paired evidence is the env switch run of the same code path.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 02:08:26 +01:00
co-authored by Claude Sonnet 5.5
parent 0a3cda3769
commit 5ef2c6eb7a
4 changed files with 2187 additions and 2156 deletions
@@ -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)
}
@@ -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<Swap> {
let mut usage: Vec<f32> = 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<&Swap>> = 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<u32> = 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<usize> {
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::<f64>() / (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<Swap> {
let mut usage: Vec<f32> = 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<&Swap>> = 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<u32> = 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<usize> {
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::<f64>() / (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));
}
}
File diff suppressed because it is too large Load Diff
+5
View File
@@ -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).