upstream port rows 0.6, 3.1, 2.3: callback-thread warm-up, experimental route tail skip, opt-in worker plan
* cuda-driver: on Linux the first stream created starts the driver's host-callback thread (one no-op cuLaunchHostFunc + synchronize) while the host thread is not pinned yet; LELEKA_CB_WARMUP=off skips it (A/B arm). * leleka-runtime: EXPERIMENTAL route tail skip LELEKA_ROUTE_TAIL_SKIP=N (default off, output changing): a missed expert that every token of the window routes at rank >= N is neither copied nor computed (kind -2 in split_group_tail, zero row); off at >= LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED percent (90) of the experts in VRAM. Replay arms: spec arm suffix +tailN and replay arm flag !tailN for in-process A/B and the quality gate. * native-cpu-expert: pool_plan (upstream pool_plan.hpp: default worker count from the physical cores, hybrid and cgroup quota), opt-in via LELEKA_CPU_POOL_PLAN=on; the stack default stays 15. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
83297939c6
commit
a14b57f5ec
@@ -74,6 +74,15 @@ mod platform {
|
||||
let word = unsafe { &*(raise.word as *const std::sync::atomic::AtomicU32) };
|
||||
word.fetch_max(raise.value, std::sync::atomic::Ordering::SeqCst);
|
||||
}
|
||||
/// The no-op host function of the callback-thread warm-up.
|
||||
#[cfg(target_os = "linux")]
|
||||
unsafe extern "C" fn noop_host_fn(_: *mut c_void) {}
|
||||
/// `LELEKA_CB_WARMUP=off|0|no` skips the warm-up of [`Api::warm_callback_thread`] (A/B arm; docs/upstream-port-plan.md row 0.6).
|
||||
#[cfg(target_os = "linux")]
|
||||
fn callback_warmup_enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| !matches!(std::env::var("LELEKA_CB_WARMUP").as_deref(), Ok("off" | "0" | "no")))
|
||||
}
|
||||
pub(crate) struct Api {
|
||||
_library: Library,
|
||||
create: StreamCreate,
|
||||
@@ -180,8 +189,33 @@ mod platform {
|
||||
return Err(Error::InvalidDriverValue("cuStreamCreate"));
|
||||
}
|
||||
crate::compute_drain::register(s as usize);
|
||||
self.warm_callback_thread(s);
|
||||
Ok(s as usize)
|
||||
}
|
||||
/// Linux: the driver creates the thread that runs host functions lazily, at the first `cuLaunchHostFunc` of the process, and the
|
||||
/// new thread inherits the CPU mask of the thread that made the call. The CPU expert pool later pins the host thread to one
|
||||
/// core (`rust_platform::pin`); a callback thread created after that would share the core with the host's spin-wait (upstream
|
||||
/// measured 985 us instead of 4 us per callback, `0e20d9ae`/`c08fd902`, `STRATA_ADAPT_CALLBACK_WARMUP`). One no-op host function and a
|
||||
/// stream synchronize at the first stream's creation start the thread while the host thread is still unpinned. Windows CPU
|
||||
/// sets are per thread and not inherited, so nothing is done there. A failure is ignored: the first real callback creates the thread.
|
||||
#[cfg(target_os = "linux")]
|
||||
fn warm_callback_thread(&self, s: Handle) {
|
||||
static WARMED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
|
||||
if !callback_warmup_enabled() || WARMED.swap(true, std::sync::atomic::Ordering::Relaxed) {
|
||||
return;
|
||||
}
|
||||
// SAFETY: `s` is the stream just created through this Api in the entered Context; the host function ignores its argument.
|
||||
let launched = unsafe { (self.host_fn)(s, noop_host_fn, std::ptr::null_mut()) };
|
||||
// SAFETY: C ABI call on the live handle; no host memory is passed.
|
||||
let synced = if launched == 0 { unsafe { (self.sync)(s) } } else { launched };
|
||||
if synced == 0 {
|
||||
eprintln!("leleka-serve: GPU host-callback thread started before host-core pinning (LELEKA_CB_WARMUP=off skips it)");
|
||||
} else {
|
||||
eprintln!("leleka-serve: could not warm up the GPU host-callback thread (driver code {synced}); continuing");
|
||||
}
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn warm_callback_thread(&self, _: Handle) {}
|
||||
pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> {
|
||||
crate::compute_drain::unregister(s);
|
||||
// SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included).
|
||||
|
||||
@@ -91,6 +91,7 @@ fn original_serve_replay_smoke() {
|
||||
for (arm_index, (label, arm)) in arms.iter().enumerate() {
|
||||
// the mode may carry the arm's own prefill chunk and grid: `reply@8192` (chunk 8192, grid = chunk) or `reply@8192/2048`
|
||||
let mut down_override: i8 = -1;
|
||||
let mut tail_flag: Option<u32> = None;
|
||||
let (arm_mode, arm_capacity, arm_block, arm_tiers): (String, usize, usize, Option<bool>) = match arm.split_once('@') {
|
||||
Some((mode, shape)) => {
|
||||
// flags after the shape, each introduced by `!`: `tiers` / `notiers` (the prompt loan ladder on / off; default: the stack's), `w8` (the previous
|
||||
@@ -98,6 +99,8 @@ fn original_serve_replay_smoke() {
|
||||
let (shape, flags) = shape.split_once('!').map_or((shape, ""), |(s, f)| (s, f));
|
||||
let tiers = if flags.split('!').any(|f| f == "notiers") { Some(false) } else if flags.split('!').any(|f| f == "tiers") { Some(true) } else { None };
|
||||
down_override = if flags.split('!').any(|f| f == "w8") { 0 } else { -1 };
|
||||
// `tailN`: the experimental route tail skip (docs/upstream-port-plan.md 3.1) at rank N for this arm (`tail0` = off); without it the environment decides
|
||||
tail_flag = flags.split('!').find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::<u32>().expect("arm flag !tailN"));
|
||||
let (cap, block) = shape.split_once('/').unwrap_or((shape, "0"));
|
||||
(mode.to_owned(), cap.parse::<usize>().expect("arm chunk: mode@CAP[/BLOCK]"), block.parse::<usize>().expect("arm grid: mode@CAP[/BLOCK]"), tiers)
|
||||
}
|
||||
@@ -105,6 +108,7 @@ fn original_serve_replay_smoke() {
|
||||
};
|
||||
let arm = &arm_mode;
|
||||
leleka_cuda_driver::set_chain_down_override(down_override);
|
||||
crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail_flag);
|
||||
eprintln!("REPLAY-ARM start label={label} mode={arm} capacity={arm_capacity} block={arm_block} tiers={}", arm_tiers.map_or("default", |on| if on { "on" } else { "off" }));
|
||||
let mut config = StackConfig::new(number("LELEKA_REPLAY_MAX_CONTEXT", 262_144) as i64);
|
||||
config.capacity = arm_capacity;
|
||||
@@ -155,6 +159,11 @@ fn original_serve_replay_smoke() {
|
||||
for (pass_no, (pass_label, arm)) in passes.iter().enumerate() {
|
||||
if let Some(arm) = arm {
|
||||
assert!(stack.select_spec_arm(arm), "unknown spec arm {arm}");
|
||||
// `+tailN` in an arm label (`adaptive@0+tail7`): the experimental route tail skip of this pass (docs/upstream-port-plan.md 3.1); without it the environment decides
|
||||
if spec_arms.iter().any(|a| a.contains("+tail")) {
|
||||
let tail = arm.split('+').skip(1).find_map(|f| f.strip_prefix("tail")).map(|n| n.parse::<u32>().expect("arm flag +tailN"));
|
||||
crate::qwen_forward::original_serve_residency::set_tail_skip_arm(tail);
|
||||
}
|
||||
}
|
||||
let (mut tokens, mut decode_ms, mut rounds_total, mut prefill_tokens, mut prefill_ms) = (0usize, 0f64, 0usize, 0usize, 0f64);
|
||||
for (n, file) in files.iter().enumerate() {
|
||||
|
||||
@@ -402,10 +402,11 @@ impl OriginalServeSettings {
|
||||
let base=Self::from_environment(max_context,vocabulary,coupled);
|
||||
let mut arms=Vec::new();
|
||||
for entry in list.split(',').map(str::trim).filter(|l|!l.is_empty()) {
|
||||
// `name@MIN_P` pins the arm's request floor
|
||||
let (label,min_p)=match entry.split_once('@') {
|
||||
// `name@MIN_P` pins the arm's request floor; `+flag` suffixes (`adaptive@0+tail7`) are the replay harness's, the label keeps them
|
||||
let main=entry.split_once('+').map_or(entry,|(m,_)|m);
|
||||
let (label,min_p)=match main.split_once('@') {
|
||||
Some((l,p))=>(l,p.parse::<f32>().ok()),
|
||||
None=>(entry,None),
|
||||
None=>(main,None),
|
||||
};
|
||||
let mut s=base;s.adaptive=None;s.request_min_p=min_p;
|
||||
if let Some(n)=label.strip_prefix("fixed").and_then(|n|n.parse::<usize>().ok()) {
|
||||
|
||||
@@ -34,7 +34,11 @@ use leleka_cuda_driver::{
|
||||
Context, MappedExpertBank, ORIGINAL_VERIFY_MAX_PCIE_FETCHES, OriginalExpertCache, OriginalGpuStream,
|
||||
OriginalVerifyCpuRows, OriginalVerifyCpuSink, OriginalVerifyGpuPlan, OriginalVerifyPcieSource,
|
||||
};
|
||||
use std::{path::PathBuf, rc::Rc};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
sync::atomic::{AtomicU32, Ordering},
|
||||
};
|
||||
|
||||
const LAYERS: usize = 48;
|
||||
const EXPERTS: usize = 512;
|
||||
@@ -44,6 +48,48 @@ const MAX_WINDOW_ENTRIES: usize = 128;
|
||||
/// generate.cpp: a loan keeps at least this many slots for the decode tier.
|
||||
const LOAN_FLOOR: usize = 128;
|
||||
|
||||
/// **EXPERIMENTAL, changes the output** (docs/upstream-port-plan.md row 3.1; upstream `STRATA_ROUTE_TAIL_SKIP`):
|
||||
/// `LELEKA_ROUTE_TAIL_SKIP=N` (1..=9, unset or 0 = off): a missed expert that every token of the window routes at rank `N` or
|
||||
/// lower (the rank of the router's descending top-10, 0 = the heaviest) is neither copied over PCIe nor computed on the CPU;
|
||||
/// its contribution is zero and the other weights are not renormalised. Off while at least `LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED`
|
||||
/// percent (default 90) of the experts are in VRAM. Not a default of any profile until its own quality gate passes.
|
||||
const TAIL_UNRESOLVED: u32 = u32::MAX;
|
||||
static TAIL_SKIP_RANK: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED);
|
||||
/// The tail-skip rank in force (0 = off): the environment, read once, unless a replay arm set it.
|
||||
pub(crate) fn tail_skip_rank() -> u32 {
|
||||
let rank = TAIL_SKIP_RANK.load(Ordering::Relaxed);
|
||||
if rank != TAIL_UNRESOLVED {
|
||||
return rank;
|
||||
}
|
||||
let rank = std::env::var("LELEKA_ROUTE_TAIL_SKIP").ok().and_then(|v| v.trim().parse::<u32>().ok()).filter(|r| (1..TOP_K as u32).contains(r)).unwrap_or(0);
|
||||
TAIL_SKIP_RANK.store(rank, Ordering::Relaxed);
|
||||
rank
|
||||
}
|
||||
/// Set the rank of an A/B arm of the replay harness (`adaptive@0+tail7`; 0 or out of range = off); `None` goes back to the environment.
|
||||
pub(crate) fn set_tail_skip_arm(rank: Option<u32>) {
|
||||
TAIL_SKIP_RANK.store(rank.map_or(TAIL_UNRESOLVED, |r| if (1..TOP_K as u32).contains(&r) { r } else { 0 }), Ordering::Relaxed);
|
||||
}
|
||||
/// The rank this decode phase uses: `tail_skip_rank()` unless the cache holds at least the configured share of all experts.
|
||||
pub(crate) fn effective_tail_rank(cache: &OriginalExpertCache<'_>) -> u32 {
|
||||
let rank = tail_skip_rank();
|
||||
if rank == 0 {
|
||||
return 0;
|
||||
}
|
||||
let cached: usize = (0..LAYERS).map(|l| (0..EXPERTS).filter(|&e| cache.resident_slot(l, e).is_some()).count()).sum();
|
||||
let percent = 100.0 * cached as f64 / (LAYERS * EXPERTS) as f64;
|
||||
let limit = std::env::var("LELEKA_ROUTE_TAIL_SKIP_MAX_CACHED").ok().and_then(|v| v.trim().parse::<f64>().ok()).unwrap_or(90.0);
|
||||
let effective = if percent >= limit { 0 } else { rank };
|
||||
static ANNOUNCED: AtomicU32 = AtomicU32::new(TAIL_UNRESOLVED);
|
||||
if ANNOUNCED.swap(effective, Ordering::Relaxed) != effective {
|
||||
if effective == 0 {
|
||||
eprintln!("leleka-serve: route tail skip {rank} is OFF: {percent:.1}% of the experts are in VRAM (limit {limit:.0}%)");
|
||||
} else {
|
||||
eprintln!("leleka-serve: EXPERIMENTAL route tail skip is ON (LELEKA_ROUTE_TAIL_SKIP={rank}, {percent:.1}% of the experts in VRAM): a missed expert every token of a window routes at rank {rank} or lower is skipped; the OUTPUT CHANGES");
|
||||
}
|
||||
}
|
||||
effective
|
||||
}
|
||||
|
||||
/// generate.cpp `--pcie-mode auto|dma|kernel` (`direct`, the mapped arena, is not ported): how a window stages its
|
||||
/// PCIe share. `Auto` is DMA on the copy stream (job 981/982, RTX 5090, 6 prompts x 2 passes: +16 % static and +12-15 %
|
||||
/// adaptive over the copy kernel, which generate.cpp makes its default); `kernel` is the in-graph copy kernel, available
|
||||
@@ -235,18 +281,21 @@ impl ExpertTierConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// One window group's split: the GPU plan, the kind of every entry (-1 CPU, 0 VRAM, 1 PCIe) and the expert
|
||||
/// of every PCIe group (staging slot order).
|
||||
/// One window group's split: the GPU plan, the kind of every entry (-2 skipped by the route tail skip, -1 CPU, 0 VRAM,
|
||||
/// 1 PCIe) and the expert of every PCIe group (staging slot order).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(in crate::qwen_forward) struct GroupSplit {
|
||||
pub(in crate::qwen_forward) plan: OriginalVerifyGpuPlan,
|
||||
pub(in crate::qwen_forward) kinds: Vec<i8>,
|
||||
pub(in crate::qwen_forward) pcie_experts: Vec<u32>,
|
||||
/// Distinct experts the route tail skip left out (their entries are kind -2).
|
||||
pub(in crate::qwen_forward) skipped_experts: usize,
|
||||
}
|
||||
|
||||
/// expert_source.cpp `expert_pool_dispatch_multi`, the GPU share: `ids` are the group's `rows * k` routed
|
||||
/// ids, `resident(e)` the VRAM slot of expert `e` of this layer, `pcie_num` the PCIe share in 256ths (0: no
|
||||
/// PCIe), `staging` the group's staging blobs. `cap` is the window's plan capacity (`max_t * k`).
|
||||
#[cfg(test)]
|
||||
pub(in crate::qwen_forward) fn split_group(
|
||||
ids: &[i32],
|
||||
k: usize,
|
||||
@@ -254,6 +303,21 @@ pub(in crate::qwen_forward) fn split_group(
|
||||
resident: impl Fn(u32) -> Option<usize>,
|
||||
pcie_num: u32,
|
||||
staging: usize,
|
||||
) -> Result<GroupSplit> {
|
||||
split_group_tail(ids, k, cap, resident, pcie_num, staging, 0)
|
||||
}
|
||||
|
||||
/// `split_group` with the route tail skip: `tail_rank > 0` (1..k) leaves out every missed expert whose best rank over the
|
||||
/// entries that route it is at least `tail_rank` (expert_source.cpp `STRATA_ROUTE_TAIL_SKIP`); its entries are kind -2: not
|
||||
/// in the plan, not staged, not computed. They are taken out of the miss count before the PCIe share is rounded.
|
||||
pub(in crate::qwen_forward) fn split_group_tail(
|
||||
ids: &[i32],
|
||||
k: usize,
|
||||
cap: usize,
|
||||
resident: impl Fn(u32) -> Option<usize>,
|
||||
pcie_num: u32,
|
||||
staging: usize,
|
||||
tail_rank: u32,
|
||||
) -> Result<GroupSplit> {
|
||||
let n = ids.len();
|
||||
if k == 0 || n == 0 || n % k != 0 || n > MAX_WINDOW_ENTRIES || n > cap || pcie_num > 256 {
|
||||
@@ -273,6 +337,22 @@ pub(in crate::qwen_forward) fn split_group(
|
||||
}
|
||||
}
|
||||
}
|
||||
// the route tail skip: a missed expert no token of the window routes above rank `tail_rank` is dropped
|
||||
let mut skip = vec![false; n];
|
||||
let mut skipped_experts = 0usize;
|
||||
if tail_rank > 0 {
|
||||
let mut best = vec![usize::MAX; n];
|
||||
for i in 0..n {
|
||||
best[first_of[i]] = best[first_of[i]].min(i % k);
|
||||
}
|
||||
for &i0 in &distinct {
|
||||
if valid(ids[i0]) && resident(ids[i0] as u32).is_none() && best[i0] >= tail_rank as usize {
|
||||
skip[i0] = true;
|
||||
skipped_experts += 1;
|
||||
nmiss -= 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let m = if pcie_num > 0 { (nmiss * pcie_num as usize) >> 8 } else { 0 };
|
||||
let mut kinds = vec![-1i8; n];
|
||||
let mut plan = OriginalVerifyGpuPlan::new();
|
||||
@@ -283,7 +363,9 @@ pub(in crate::qwen_forward) fn split_group(
|
||||
let e = ids[i0];
|
||||
let mut kind = -1i8;
|
||||
let mut slot = None;
|
||||
if valid(e) {
|
||||
if skip[i0] {
|
||||
kind = -2;
|
||||
} else if valid(e) {
|
||||
match resident(e as u32) {
|
||||
Some(s) => {
|
||||
kind = 0;
|
||||
@@ -313,7 +395,7 @@ pub(in crate::qwen_forward) fn split_group(
|
||||
for members in pcie_groups {
|
||||
plan.push_pcie(members);
|
||||
}
|
||||
Ok(GroupSplit { plan, kinds, pcie_experts })
|
||||
Ok(GroupSplit { plan, kinds, pcie_experts, skipped_experts })
|
||||
}
|
||||
|
||||
/// One adaptive swap: in layer `layer`, expert `incoming` takes the slot of `outgoing`.
|
||||
@@ -385,12 +467,16 @@ pub(crate) struct ResidencyStats {
|
||||
pub(crate) cpu_entries: u64,
|
||||
pub(crate) adaptations: u64,
|
||||
pub(crate) swaps: u64,
|
||||
/// Route tail skip (experimental): entries and distinct experts left out.
|
||||
pub(crate) tail_entries: u64,
|
||||
pub(crate) tail_experts: u64,
|
||||
}
|
||||
impl ResidencyStats {
|
||||
pub(crate) fn describe(&self) -> String {
|
||||
let all = (self.vram_entries + self.pcie_entries + self.cpu_entries).max(1) as f64;
|
||||
let tail = if self.tail_entries > 0 { format!(", route tail skip {} entries / {} experts", self.tail_entries, self.tail_experts) } else { String::new() };
|
||||
format!(
|
||||
"expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps",
|
||||
"expert tier: {} layer groups, entries vram {} ({:.1}%) pcie {} ({:.1}%) cpu {} ({:.1}%), {} adaptations, {} swaps{}",
|
||||
self.groups,
|
||||
self.vram_entries,
|
||||
100.0 * self.vram_entries as f64 / all,
|
||||
@@ -399,7 +485,8 @@ impl ResidencyStats {
|
||||
self.cpu_entries,
|
||||
100.0 * self.cpu_entries as f64 / all,
|
||||
self.adaptations,
|
||||
self.swaps
|
||||
self.swaps,
|
||||
tail
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -672,6 +759,8 @@ pub(in crate::qwen_forward) struct GpuExpertPool<'p, 'a, 'ctx> {
|
||||
pub(in crate::qwen_forward) pcie_num: u32,
|
||||
pub(in crate::qwen_forward) adapt_every: u32,
|
||||
pub(in crate::qwen_forward) adapt_swaps: usize,
|
||||
/// The route tail skip rank of this decode phase (0 = off; `effective_tail_rank`).
|
||||
pub(in crate::qwen_forward) tail_rank: u32,
|
||||
}
|
||||
impl GpuExpertPool<'_, '_, '_> {
|
||||
fn source_spans(&mut self, layer: usize, experts: &[u32]) -> Result<Vec<[ResidentExpertBankSpan; 3]>> {
|
||||
@@ -753,16 +842,17 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
}
|
||||
let profile_split = super::original_serve_profile::span("pool.split");
|
||||
let cache = &*self.cache;
|
||||
let split = split_group(
|
||||
let split = split_group_tail(
|
||||
rows.ids,
|
||||
TOP_K,
|
||||
sink.plan_capacity(),
|
||||
|e| cache.resident_slot(layer, e as usize),
|
||||
self.state.pcie_lag.as_ref().map(PcieLag::pcie_num).or_else(|| self.state.pcie_auto.as_ref().map(PcieAuto::pcie_num)).unwrap_or(self.pcie_num),
|
||||
sink.staging_capacity(),
|
||||
self.tail_rank,
|
||||
)?;
|
||||
if let Some(auto) = self.state.pcie_auto.as_mut() {
|
||||
auto.add_misses(split.kinds.iter().filter(|&&k| k != 0).count());
|
||||
auto.add_misses(split.kinds.iter().filter(|&&k| k == -1 || k == 1).count());
|
||||
}
|
||||
super::original_serve_pool::window_trace::lap(super::original_serve_pool::window_trace::GPU_SPLIT, &mut clock);
|
||||
drop(profile_split);
|
||||
@@ -775,13 +865,17 @@ impl<'ctx> OriginalServePool<'ctx> for GpuExpertPool<'_, '_, 'ctx> {
|
||||
let pcie = (self.pcie_num > 0).then_some(OriginalVerifyPcieSource { bank: &self.bank, spans: &spans });
|
||||
sink.publish_gpu_plan(&split.plan, cache, pcie, copy).map_err(|e| driver_error(&e))?;
|
||||
drop(profile_publish);
|
||||
let include: Vec<bool> = split.kinds.iter().map(|&k| k < 0).collect();
|
||||
// only the CPU's own entries are computed; the GPU's and the skipped ones are written as zeros (the window's copy kernel
|
||||
// takes a skipped entry from the mapped sink, so its zero row is its contribution)
|
||||
let include: Vec<bool> = split.kinds.iter().map(|&k| k == -1).collect();
|
||||
let stats = &mut self.state.stats;
|
||||
stats.groups += 1;
|
||||
stats.tail_experts += split.skipped_experts as u64;
|
||||
for &kind in &split.kinds {
|
||||
match kind {
|
||||
0 => stats.vram_entries += 1,
|
||||
1 => stats.pcie_entries += 1,
|
||||
-2 => stats.tail_entries += 1,
|
||||
_ => stats.cpu_entries += 1,
|
||||
}
|
||||
}
|
||||
@@ -1089,6 +1183,55 @@ mod tests {
|
||||
assert_eq!(s.plan.vram().len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_skip_drops_missed_experts_every_token_routes_at_or_below_the_rank() {
|
||||
// row 0 ranks: 12 at 6, 30 at 7, 31 at 8, 40 (resident) at 9; row 1 ranks: 15 at 7, 12 at 8, 30 at 9
|
||||
let mut ids = row([1, 2, 3, 4, 5, 6, 12, 30, 31, 40]);
|
||||
ids.extend(row([7, 8, 9, 10, 11, 13, 14, 15, 12, 30]));
|
||||
let resident = |e: u32| (e == 40).then_some(3usize);
|
||||
let off = split_group_tail(&ids, 10, 20, resident, 0, 16, 0).unwrap();
|
||||
assert_eq!(off.skipped_experts, 0);
|
||||
assert!(off.kinds.iter().all(|&k| k != -2));
|
||||
let on = split_group_tail(&ids, 10, 20, resident, 0, 16, 7).unwrap();
|
||||
// 30: best rank min(7, 9) = 7 -> skipped (entries 7 and 19); 31: rank 8 -> skipped (entry 8); 15: rank 7 -> skipped (entry 17);
|
||||
// 12: best rank min(6, 8) = 6 < 7 -> kept in both rows (entries 6 and 18)
|
||||
assert_eq!(on.skipped_experts, 3);
|
||||
assert_eq!(on.kinds.iter().enumerate().filter(|&(_, &k)| k == -2).map(|(i, _)| i).collect::<Vec<_>>(), vec![7, 8, 17, 19]);
|
||||
assert_eq!((on.kinds[6], on.kinds[18]), (-1, -1));
|
||||
assert_eq!(on.kinds[9], 0, "a resident expert is never skipped");
|
||||
// everything else is exactly what the skip-off split produced
|
||||
for i in 0..20 {
|
||||
if on.kinds[i] != -2 {
|
||||
assert_eq!(on.kinds[i], off.kinds[i], "entry {i}");
|
||||
}
|
||||
}
|
||||
assert_eq!(on.plan.vram(), off.plan.vram());
|
||||
// rank 8: only expert 31 (rank 8 in its only row); rank 9: nothing (the rank-9 entries are resident 40 and 30, best rank 7)
|
||||
assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 8).unwrap().skipped_experts, 1);
|
||||
assert_eq!(split_group_tail(&ids, 10, 20, resident, 0, 16, 9).unwrap().skipped_experts, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_skip_shrinks_the_miss_count_before_the_pcie_share_is_taken() {
|
||||
// ten misses, rank 7..9 are three experts: 7 misses remain, pcie_num 141 -> m = 7 * 141 >> 8 = 3 (instead of 5 of ten)
|
||||
let ids = row([10, 11, 12, 13, 14, 15, 16, 17, 18, 19]);
|
||||
let none = |_: u32| None;
|
||||
let s = split_group_tail(&ids, 10, 40, none, 141, 16, 7).unwrap();
|
||||
assert_eq!(s.skipped_experts, 3);
|
||||
assert_eq!(s.kinds, vec![-1, -1, -1, -1, 1, 1, 1, -2, -2, -2]);
|
||||
assert_eq!(s.pcie_experts, vec![14, 15, 16]);
|
||||
// a rank past the last slot skips nothing
|
||||
let off = split_group_tail(&ids, 10, 40, none, 141, 16, 10).unwrap();
|
||||
assert_eq!(off.skipped_experts, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_tail_skip_leaves_invalid_ids_to_the_cpu_check() {
|
||||
let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
let s = split_group_tail(&ids, 10, 40, |_| None, 0, 16, 1).unwrap();
|
||||
assert_eq!(s.kinds[0], -1, "an out-of-range id is never a skip: the CPU path reports it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn out_of_range_ids_stay_with_the_cpu_and_oversized_groups_are_refused() {
|
||||
let ids = row([600, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
|
||||
|
||||
@@ -153,7 +153,11 @@ impl StackConfig {
|
||||
rt_directory: None,
|
||||
coupled: OriginalServeSettings::coupled_from_environment(),
|
||||
// LELEKA_ORIGINAL_SERVE_CPU_WORKERS: experiment knob (the Original's default on this host is 15)
|
||||
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(CPU_WORKERS),
|
||||
// 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,
|
||||
@@ -1023,6 +1027,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
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);
|
||||
gpu_pool = GpuExpertPool {
|
||||
binding,
|
||||
moe: &*moe,
|
||||
@@ -1033,6 +1038,7 @@ impl<'a, 'ctx> OriginalServeStack<'a, 'ctx> {
|
||||
pcie_num,
|
||||
adapt_every: config.expert_tier.adapt_every,
|
||||
adapt_swaps: config.expert_tier.adapt_swaps as usize,
|
||||
tail_rank,
|
||||
};
|
||||
&mut gpu_pool
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ pub mod rust_general_pool;
|
||||
#[allow(unsafe_code)]
|
||||
pub mod rust_expert_layout;
|
||||
pub mod rust_dequant;
|
||||
pub mod pool_plan;
|
||||
mod rust_weight_quant;
|
||||
pub mod rust_model_quant;
|
||||
pub mod rust_bench;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
//! How many CPU expert workers to start by default (docs/upstream-port-plan.md row 2.3; upstream `pool_plan.hpp`, commit `5ece068f`).
|
||||
//!
|
||||
//! Pure arithmetic on a CPU description, unit tested on mock CPUs. The plan is opt-in (`LELEKA_CPU_POOL_PLAN=on`): the stack's default stays the
|
||||
//! Original's 15 until the plan has a paired A/B on the machine it changes. On the 16-core 9950X3D of the server the plan gives 15 as well.
|
||||
//!
|
||||
//! Why a plan and not "every physical core but the host's": the pool's workers spin while they wait, so a worker without a core of its own takes
|
||||
//! cycles from one that has one (a bigger count is slower, not just useless); the kernel is DRAM-bound, past the memory system's width more cores
|
||||
//! add nothing and the barrier at the end of every layer waits for more threads; a container limited by a CFS quota still shows every core of the
|
||||
//! machine. The pool refuses more than 15 workers (`NativePool::new`), so the count handed to the pool is also capped at [`POOL_MAX_WORKERS`].
|
||||
|
||||
/// The pool's own ceiling (`NativePool::new` refuses more).
|
||||
pub const POOL_MAX_WORKERS: usize = 15;
|
||||
/// Upstream's measured cap of a default count (`kPoolWorkersCap`); above the pool's ceiling here, kept so the mock-CPU tests match upstream's.
|
||||
pub const WORKERS_CAP: usize = 32;
|
||||
/// A CPU with at least this many workers keeps [`RESERVE`] cores free for the engine's other threads.
|
||||
pub const RESERVE_FROM: usize = 16;
|
||||
pub const RESERVE: usize = 1;
|
||||
|
||||
/// A CPU as the plan sees it.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct PoolPlanInput {
|
||||
/// Logical processors this process may run on.
|
||||
pub logical: usize,
|
||||
/// Physical cores this process may use per CPU package, the host thread's package first (its own core is counted); empty = unknown.
|
||||
pub cores_per_package: Vec<usize>,
|
||||
/// CPUs a container quota allows (cgroup `cpu.max`); 0 = no quota.
|
||||
pub cpu_quota: f64,
|
||||
/// Physical performance / efficiency cores of a hybrid CPU (0, 0 on an ordinary one).
|
||||
pub p_cores: usize,
|
||||
pub e_cores: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PoolPlan {
|
||||
/// The default number of pool workers (the host thread works beside them).
|
||||
pub workers: usize,
|
||||
/// Physical cores counted (all packages) and those of the host's package.
|
||||
pub cores: usize,
|
||||
pub cores_local: usize,
|
||||
pub packages: usize,
|
||||
pub topology_known: bool,
|
||||
/// What bounded the count (for the start-up line).
|
||||
pub limit: &'static str,
|
||||
}
|
||||
|
||||
pub fn plan_pool_workers(input: &PoolPlanInput) -> PoolPlan {
|
||||
let mut cores: usize = input.cores_per_package.iter().sum();
|
||||
let mut local = input.cores_per_package.first().copied().unwrap_or(0);
|
||||
let packages = input.cores_per_package.len().max(1);
|
||||
let known = !input.cores_per_package.is_empty() && cores > 0;
|
||||
if !known {
|
||||
// The OS did not say which logical processors share a core: counting every one as a core is what put a 256-thread machine at 255 workers.
|
||||
cores = if input.logical >= 16 { input.logical / 2 } else { input.logical };
|
||||
local = cores;
|
||||
}
|
||||
let mut limit = "every physical core but the host's";
|
||||
let mut n = local.saturating_sub(1).max(1); // the host thread has the first core
|
||||
if !known {
|
||||
limit = "half the logical processors (the OS gave no core layout)";
|
||||
} else if packages > 1 {
|
||||
limit = "the host's CPU socket";
|
||||
}
|
||||
if n >= RESERVE_FROM {
|
||||
n -= RESERVE;
|
||||
if known && packages == 1 {
|
||||
limit = "physical cores, one kept free";
|
||||
}
|
||||
}
|
||||
if input.p_cores > 0 && input.e_cores > input.p_cores {
|
||||
// a hybrid CPU with more E-cores than P-cores: the P-cores but the host's plus half of the E-cores
|
||||
let h = (input.p_cores - 1 + input.e_cores / 2).max(1);
|
||||
if h < n {
|
||||
n = h;
|
||||
limit = "the performance cores and half of the efficiency cores";
|
||||
}
|
||||
}
|
||||
if input.cpu_quota > 0.0 {
|
||||
let q = ((input.cpu_quota as usize).saturating_sub(1)).max(1);
|
||||
if q < n {
|
||||
n = q;
|
||||
limit = "the container's CPU quota";
|
||||
}
|
||||
}
|
||||
if n > WORKERS_CAP {
|
||||
n = WORKERS_CAP;
|
||||
limit = "the measured cap";
|
||||
}
|
||||
PoolPlan { workers: n.max(1), cores, cores_local: local, packages, topology_known: known, limit }
|
||||
}
|
||||
|
||||
/// The CPU this process runs on, as far as this build can read it.
|
||||
pub fn detect_input() -> PoolPlanInput {
|
||||
let cores = super::rust_platform::cores(false).len();
|
||||
let logical = std::thread::available_parallelism().map_or(cores, |n| n.get());
|
||||
let topology = super::rust_topology::detect_cpu_topology(false, super::rust_topology::PoolAffinity::All);
|
||||
PoolPlanInput {
|
||||
logical,
|
||||
cores_per_package: if cores > 0 { vec![cores] } else { Vec::new() },
|
||||
cpu_quota: cgroup_quota(),
|
||||
p_cores: if topology.is_hybrid { topology.p_cores } else { 0 },
|
||||
e_cores: if topology.is_hybrid { topology.e_cores } else { 0 },
|
||||
}
|
||||
}
|
||||
|
||||
/// cgroup v2 `cpu.max` ("max 100000" or "400000 100000"): the CPUs it allows, 0 when unlimited or unreadable.
|
||||
fn cgroup_quota() -> f64 {
|
||||
let Ok(text) = std::fs::read_to_string("/sys/fs/cgroup/cpu.max") else { return 0.0 };
|
||||
parse_cpu_max(&text)
|
||||
}
|
||||
|
||||
fn parse_cpu_max(text: &str) -> f64 {
|
||||
let mut fields = text.split_whitespace();
|
||||
match (fields.next().and_then(|q| q.parse::<f64>().ok()), fields.next().and_then(|p| p.parse::<f64>().ok())) {
|
||||
(Some(quota), Some(period)) if quota > 0.0 && period > 0.0 => quota / period,
|
||||
_ => 0.0,
|
||||
}
|
||||
}
|
||||
|
||||
/// The plan's worker count for this machine, within the pool's ceiling.
|
||||
pub fn default_workers() -> i32 {
|
||||
plan_pool_workers(&detect_input()).workers.min(POOL_MAX_WORKERS) as i32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cpu(logical: usize, per_package: &[usize]) -> PoolPlanInput {
|
||||
PoolPlanInput { logical, cores_per_package: per_package.to_vec(), ..PoolPlanInput::default() }
|
||||
}
|
||||
fn workers(input: &PoolPlanInput) -> usize {
|
||||
plan_pool_workers(input).workers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn small_cpus_use_every_physical_core_but_the_hosts_and_never_zero() {
|
||||
assert_eq!(workers(&cpu(16, &[8])), 7, "8c/16t: never the SMT siblings (the i9-11900H laptop)");
|
||||
assert_eq!(workers(&cpu(12, &[6])), 5);
|
||||
assert_eq!(workers(&cpu(4, &[4])), 3);
|
||||
assert_eq!(workers(&cpu(1, &[1])), 1);
|
||||
assert_eq!(workers(&cpu(2, &[2])), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_16_core_server_cpu_gets_15_like_the_stacks_constant() {
|
||||
let plan = plan_pool_workers(&cpu(32, &[16]));
|
||||
assert_eq!(plan.workers, 15, "9950X3D: 16 cores - the host's; 15 < RESERVE_FROM so no core is held back");
|
||||
assert_eq!((plan.cores, plan.packages, plan.topology_known), (16, 1, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn big_cpus_keep_a_core_free_and_stop_at_the_cap() {
|
||||
assert_eq!(workers(&cpu(40, &[20])), 18);
|
||||
assert_eq!(workers(&cpu(128, &[64])), WORKERS_CAP);
|
||||
let two = cpu(256, &[64, 64]);
|
||||
assert_eq!(workers(&two), WORKERS_CAP);
|
||||
assert_eq!((plan_pool_workers(&two).packages, plan_pool_workers(&two).cores), (2, 128));
|
||||
assert_eq!(workers(&cpu(80, &[20, 20])), 18, "2x20 cores: the host's socket only, minus the host and the reserve");
|
||||
assert_eq!(workers(&cpu(48, &[6, 18])), 5, "a smaller host socket decides");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_layout_never_counts_every_logical_processor_as_a_core() {
|
||||
let unknown = cpu(256, &[]);
|
||||
assert!(!plan_pool_workers(&unknown).topology_known);
|
||||
assert_eq!(workers(&unknown), WORKERS_CAP);
|
||||
assert_eq!(workers(&cpu(8, &[])), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hybrid_cpus_with_more_e_cores_than_p_cores_use_the_p_cores_and_half_the_e_cores() {
|
||||
let hybrid = |logical, cores, p, e| PoolPlanInput { p_cores: p, e_cores: e, ..cpu(logical, &[cores]) };
|
||||
assert_eq!(workers(&hybrid(20, 20, 8, 12)), 13);
|
||||
assert_eq!(workers(&hybrid(32, 24, 8, 16)), 15);
|
||||
assert_eq!(workers(&hybrid(24, 16, 8, 8)), 15, "not more E-cores than P-cores: every core but the host's");
|
||||
assert_eq!(workers(&hybrid(16, 16, 6, 10)), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_container_quota_bounds_the_count() {
|
||||
let quota = |cpus| PoolPlanInput { cpu_quota: cpus, ..cpu(128, &[64]) };
|
||||
assert_eq!(workers("a(4.0)), 3);
|
||||
assert_eq!(workers("a(200.0)), WORKERS_CAP);
|
||||
assert_eq!(parse_cpu_max("400000 100000\n"), 4.0);
|
||||
assert_eq!(parse_cpu_max("max 100000\n"), 0.0);
|
||||
assert_eq!(parse_cpu_max(""), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_count_handed_to_the_pool_stays_within_its_ceiling() {
|
||||
let workers = default_workers();
|
||||
assert!((1..=POOL_MAX_WORKERS as i32).contains(&workers), "{workers}");
|
||||
eprintln!("default_workers on this machine: {workers} ({:?})", plan_pool_workers(&detect_input()));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user