residency: choose_swaps selects the victims it can pair instead of sorting every resident expert (same swaps, same order)

Per layer only min(candidates, residents) victims can pair; select_nth + a sort of those, with (value, expert) as the total order (= the earlier stable sort), and the
per-layer vectors are reused. Test: 40 random usage/resident cases with ties against the kept reference implementation, identical swaps and order for max_swaps 1/5/96/4096.
Micro timing (laptop, synthetic 46 % resident): 580 -> 480 us per call; one call per adaptation (every 4th round). Not measured on the 5090.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-29 01:52:08 +01:00
co-authored by Claude Sonnet 5.5
parent 1c5a6c7378
commit 0a3cda3769
@@ -454,6 +454,54 @@ fn adapt_tuning() -> (f32, f32, f32) {
/// `cand >= vict + 1.5`; all layers' swaps by gain, the best `max_swaps`. Ties keep ascending expert / layer
/// order (`std::sort` leaves tie order unspecified).
pub(in crate::qwen_forward) fn choose_swaps(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec<Swap> {
let (min_count, margin, _) = adapt_tuning();
let mut swaps = Vec::new();
if usage.len() != LAYERS * EXPERTS {
return swaps;
}
let mut cand: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS);
let mut vict: Vec<(f32, usize)> = Vec::with_capacity(EXPERTS);
for layer in 0..LAYERS {
let u = &usage[layer * EXPERTS..(layer + 1) * EXPERTS];
cand.clear();
vict.clear();
for (e, &value) in u.iter().enumerate() {
if !resident(layer, e) {
if value >= min_count {
cand.push((value, e));
}
} else {
vict.push((value, e));
}
}
if cand.is_empty() || vict.is_empty() {
continue;
}
cand.sort_by(|a, b| b.0.total_cmp(&a.0));
// Only as many victims as there are candidates can pair. The stable sort by value of experts pushed in ascending order is the order
// by (value, expert): selecting the `m` least of that total order and sorting only those gives the same first `m` without sorting all residents.
let m = cand.len().min(vict.len());
let by_value_then_expert = |a: &(f32, usize), b: &(f32, usize)| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1));
if m < vict.len() {
vict.select_nth_unstable_by(m - 1, by_value_then_expert);
vict.truncate(m);
}
vict.sort_by(by_value_then_expert);
for (c, v) in cand.iter().zip(&vict) {
if c.0 < v.0 + margin {
break;
}
swaps.push(Swap { gain: c.0 - v.0, layer, incoming: c.1, outgoing: v.1 });
}
}
swaps.sort_by(|a, b| b.gain.total_cmp(&a.gain));
swaps.truncate(max_swaps);
swaps
}
/// The earlier implementation (full sorts), kept to prove the faster one picks exactly the same swaps in the same order.
#[cfg(test)]
fn choose_swaps_reference(usage: &[f32], resident: impl Fn(usize, usize) -> bool, max_swaps: usize) -> Vec<Swap> {
let (min_count, margin, _) = adapt_tuning();
let mut swaps = Vec::new();
if usage.len() != LAYERS * EXPERTS {
@@ -1170,6 +1218,58 @@ pub(in crate::qwen_forward) fn refill_defer_enabled() -> bool {
#[cfg(test)]
mod tests {
#[test]
fn the_selection_based_ranking_picks_the_reference_swaps_in_the_same_order() {
// xorshift: deterministic usage with many ties (small integer counts) and a random resident set per layer
let mut x = 0x9e3779b97f4a7c15u64;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
for case in 0..40 {
let skew = 1 + case % 7;
let usage: Vec<f32> = (0..LAYERS * EXPERTS).map(|_| ((next() % 11) as f32 / skew as f32).floor() + if next() % 5 == 0 { 0.5 } else { 0.0 }).collect();
let resident_bits: Vec<bool> = (0..LAYERS * EXPERTS).map(|_| next() % (2 + (case % 4) as u64) != 0).collect();
let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e];
for max_swaps in [1usize, 5, 96, 4096] {
let fast = choose_swaps(&usage, resident, max_swaps);
let slow = choose_swaps_reference(&usage, resident, max_swaps);
assert_eq!(fast.len(), slow.len(), "case {case} max {max_swaps}");
for (a, b) in fast.iter().zip(&slow) {
assert_eq!((a.layer, a.incoming, a.outgoing, a.gain.to_bits()), (b.layer, b.incoming, b.outgoing, b.gain.to_bits()), "case {case} max {max_swaps}");
}
}
}
}
#[test]
#[ignore = "timing probe: cargo test --release -p leleka-runtime --lib choose_swaps_timing -- --ignored --nocapture"]
fn choose_swaps_timing() {
let mut x = 0x2545f4914f6cdd1du64;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
let usage: Vec<f32> = (0..LAYERS * EXPERTS).map(|_| if next() % 6 == 0 { (next() % 9) as f32 } else { 0.0 }).collect();
let resident_bits: Vec<bool> = (0..LAYERS * EXPERTS).map(|_| next() % 100 < 46).collect();
let resident = |l: usize, e: usize| resident_bits[l * EXPERTS + e];
let time = |f: &dyn Fn() -> usize| {
let t = std::time::Instant::now();
let mut n = 0;
for _ in 0..200 {
n += f();
}
(t.elapsed().as_secs_f64() * 1e6 / 200.0, n)
};
let (fast, a) = time(&|| choose_swaps(&usage, resident, 96).len());
let (slow, b) = time(&|| choose_swaps_reference(&usage, resident, 96).len());
eprintln!("choose_swaps: new {fast:.0} us, reference {slow:.0} us per call ({a} {b})");
}
use super::*;
fn row(ids: [i32; 10]) -> Vec<i32> {