Files
leleka/crates/cuda-model/src/ring_prefetch.rs
T

262 lines
12 KiB
Rust

//! Pure host-side half of the EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by
//! default).
//!
//! The per-layer copy ring of a prompt chunk below the expert stream's row minimum copies every routed expert the
//! arena cache does not hold, but only after the layer's router ran. The PCIe link is idle during the layer's mixer
//! (GDN / QSA). The prefetch copies, while the previous layer's tail and this layer's mixer run, the experts this layer
//! MISSED most often in its recent chunks into the ring's own stage slots. When the router result arrives a
//! prefetched expert that is routed and still not resident is consumed from its slot (no second copy); every other
//! prefetched slot is dropped. The same experts reach the same kernels in the same group order: only the time and the
//! order of the copies change.
//!
//! This module holds what needs no GPU: the policy and its slot budget, the per-layer miss history and its ranking,
//! the matching of the prefetched set against the routed one, and the stage-slot search that skips reserved slots.
use std::collections::VecDeque;
/// Experts per layer.
pub const EXPERTS: usize = 512;
/// Layers of the model.
pub const LAYERS: usize = 48;
/// A 512-bit set of experts of one layer.
pub type ExpertMask = [u64; EXPERTS / 64];
/// A ring smaller than this (the literal 8-slot ring of the 512-row rung) is never prefetched into.
pub const MIN_RING_SLOTS: usize = 32;
/// The prefetch switch: how many experts per layer at most, and over how many recent chunks the misses are counted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RingPrefetchPolicy {
/// at most this many experts per layer (also bounded by half of the ring, see [`RingPrefetchPolicy::budget`])
pub top_k: usize,
/// the misses of the last `window` chunks of a layer are counted
pub window: usize,
/// EXPERIMENTAL on top of the prefetch: while the copies are pending, the copy stream is the `compute_drain`
/// background stream (the mixer's drains stop waiting for it; all-zero uploads become memsets; frees are deferred),
/// as under the chunk expert stream. Off: the drains stay context-wide and wait for the prefetch copies.
pub detach_drains: bool,
}
impl RingPrefetchPolicy {
/// The offline study's operating point (57 % precision, 43 % of the need at K = 150 over N = 3..16 chunks).
pub const DEFAULT_TOP_K: usize = 150;
pub const DEFAULT_WINDOW: usize = 8;
pub const MAX_WINDOW: usize = 64;
/// `top_k` and `window` clamped to what the ring and the history can hold; the drains stay context-wide.
pub fn new(top_k: usize, window: usize) -> Self {
Self { top_k: top_k.min(EXPERTS), window: window.clamp(1, Self::MAX_WINDOW), detach_drains: false }
}
/// The same policy with [`RingPrefetchPolicy::detach_drains`] set to `on`.
pub fn with_detached_drains(self, on: bool) -> Self {
Self { detach_drains: on, ..self }
}
/// The experts one layer may prefetch into a ring of `ring_slots` slots: none below [`MIN_RING_SLOTS`], else at
/// most half the ring, so the ring's own lookahead always keeps free slots for the mandatory copies.
pub fn budget(&self, ring_slots: usize) -> usize {
if ring_slots < MIN_RING_SLOTS {
return 0;
}
self.top_k.min(ring_slots / 2)
}
}
/// Sets bit `expert` of `mask` (out-of-range experts are ignored).
pub fn mask_set(mask: &mut ExpertMask, expert: usize) {
if expert < EXPERTS {
mask[expert / 64] |= 1 << (expert % 64);
}
}
/// Whether bit `expert` of `mask` is set.
pub fn mask_has(mask: &ExpertMask, expert: usize) -> bool {
expert < EXPERTS && mask[expert / 64] >> (expert % 64) & 1 == 1
}
/// The missed (routed and not resident) experts of the last `window` chunks, per layer, newest last.
#[derive(Clone, Debug)]
pub struct MissHistory {
window: usize,
layers: Vec<VecDeque<ExpertMask>>,
}
impl MissHistory {
pub fn new(window: usize) -> Self {
let window = window.max(1);
Self { window, layers: (0..LAYERS).map(|_| VecDeque::with_capacity(window)).collect() }
}
/// Appends one chunk's missed set of `layer`, forgetting the oldest beyond the window.
pub fn record(&mut self, layer: usize, missed: ExpertMask) {
let Some(chunks) = self.layers.get_mut(layer) else { return };
if chunks.len() == self.window {
chunks.pop_front();
}
chunks.push_back(missed);
}
/// Chunks recorded for `layer` (at most the window).
pub fn depth(&self, layer: usize) -> usize {
self.layers.get(layer).map_or(0, VecDeque::len)
}
/// At most `k` experts of `layer` ranked by how many of the recorded chunks missed them, then by the most recent
/// chunk that missed them, then by id; experts for which `skip` holds (resident now) are left out.
pub fn predict(&self, layer: usize, k: usize, skip: impl Fn(u32) -> bool) -> Vec<u32> {
let Some(chunks) = self.layers.get(layer) else { return Vec::new() };
let mut ranked: Vec<(u32, usize, usize)> = Vec::new();
for expert in 0..EXPERTS {
let (count, last) = Self::count_and_last(chunks, expert);
if count > 0 && !skip(expert as u32) {
ranked.push((expert as u32, count, last));
}
}
ranked.sort_by(|a, b| b.1.cmp(&a.1).then(b.2.cmp(&a.2)).then(a.0.cmp(&b.0)));
ranked.into_iter().take(k).map(|(expert, _, _)| expert).collect()
}
/// `(chunks that missed expert, 1 + index of the newest one)`; `(0, 0)` when none did.
fn count_and_last(chunks: &VecDeque<ExpertMask>, expert: usize) -> (usize, usize) {
let mut count = 0;
let mut last = 0;
for (index, mask) in chunks.iter().enumerate() {
if mask_has(mask, expert) {
count += 1;
last = index + 1;
}
}
(count, last)
}
}
/// How the routed sources of a layer met the prefetched set.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PrefetchMatch {
/// `(source index, prefetch entry index)`: the source is consumed from the entry's slot
pub hits: Vec<(usize, usize)>,
/// prefetch entries no source consumed: their slots are returned unused
pub wasted: Vec<usize>,
}
/// Matches the prefetched experts (`prefetched[i]` is entry `i`) against the sources that need a copy:
/// `needs_copy[s]` is `Some(expert)` for a routed source that is not resident (and not staged otherwise), `None`
/// otherwise. Every entry is consumed at most once and by at most one source; an entry whose expert is not among the
/// needing sources is wasted.
pub fn match_prefetch(prefetched: &[u32], needs_copy: &[Option<u32>]) -> PrefetchMatch {
let mut used = vec![false; prefetched.len()];
let mut out = PrefetchMatch::default();
for (source, expert) in needs_copy.iter().enumerate() {
let Some(expert) = expert else { continue };
let found = prefetched.iter().enumerate().position(|(i, e)| e == expert && !used[i]);
if let Some(entry) = found {
used[entry] = true;
out.hits.push((source, entry));
}
}
out.wasted = (0..prefetched.len()).filter(|i| !used[*i]).collect();
out
}
/// The first slot from `start` (wrapping over `slots`) that `reserved` does not hold, or `None` when every slot is
/// reserved. With no reservation this is `start` itself, the literal ring order.
pub fn next_unreserved_slot(start: usize, slots: usize, reserved: impl Fn(usize) -> bool) -> Option<usize> {
(0..slots).map(|step| (start + step) % slots).find(|slot| !reserved(*slot))
}
/// The copy-ring check that refused: the driver error stays `InvalidProjectionShape`, the trace names the check.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RingRefusal {
/// `stage_one` of a source that already holds a slot and was not prefetched
SourceAlreadyStaged,
/// `stage_one` found every slot reserved by prefetched sources
AllSlotsReserved,
/// `stage_one`'s slot still holds a copy no gather read yet
SlotNotGathered,
/// `gather` of a source that needs a slot and has none
GatherNoSlot,
/// `gather` of a slot no copy filled
GatherSlotNotLive,
/// `gather` of a slot an earlier gather already read
GatherSlotGathered,
}
impl RingRefusal {
/// The check's name in the `RING-REFUSE` trace line.
pub fn check(self) -> &'static str {
match self {
Self::SourceAlreadyStaged => "stage.source_already_staged",
Self::AllSlotsReserved => "stage.all_slots_reserved",
Self::SlotNotGathered => "stage.slot_not_gathered",
Self::GatherNoSlot => "gather.no_slot",
Self::GatherSlotNotLive => "gather.slot_not_live",
Self::GatherSlotGathered => "gather.slot_already_gathered",
}
}
}
/// One stage slot of the copy ring: a copy filled it (`live`), a gather read it (`gathered`), a prefetched source
/// holds it until its gather (`reserved`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct SlotState {
pub live: bool,
pub gathered: bool,
pub reserved: bool,
}
impl SlotState {
/// A slot a prefetch copy filled for a routed source.
pub const PREFETCHED: Self = Self { live: true, gathered: false, reserved: true };
/// After a stage copy into it.
pub fn staged(&mut self) {
*self = Self { live: true, gathered: false, reserved: false };
}
/// A gather may read it: a copy filled it and no gather read it yet.
pub fn check_gather(self) -> Result<(), RingRefusal> {
match (self.live, self.gathered) {
(false, _) => Err(RingRefusal::GatherSlotNotLive),
(true, true) => Err(RingRefusal::GatherSlotGathered),
(true, false) => Ok(()),
}
}
/// After its gather: the slot is free for the next copy; returns whether it was reserved.
pub fn gathered(&mut self) -> bool {
self.gathered = true;
std::mem::take(&mut self.reserved)
}
}
/// What `stage_one` does with a source: `Ok(true)` copy it, `Ok(false)` nothing (resident, a chunk-stream entry or
/// prefetched); a source that already holds a slot without being prefetched is refused.
pub fn stage_needed(no_copy: bool, prefetched: bool, has_slot: bool) -> Result<bool, RingRefusal> {
if no_copy || prefetched {
return Ok(false);
}
if has_slot { Err(RingRefusal::SourceAlreadyStaged) } else { Ok(true) }
}
/// The slot `stage_one` copies into: the first one from `start` (in ring order, wrapping) that no prefetched source
/// holds and that is free (never filled, or its copy already gathered). Refused when every slot is reserved, or when
/// every unreserved slot still holds a copy no gather read; the stage-ahead walk then waits for a gather
/// (`Ring::stage_room`).
///
/// The literal ring always finds `start` itself: its copies and gathers run in the same order and its lookahead is one
/// slot short of the ring, so the next slot in order holds the oldest copy, already gathered. With prefetched sources
/// the copies skip the hits, the slot order is no longer the gather order, and the next slot in order can hold a copy
/// of an earlier source of the same layer that is not gathered yet (PET.1: layers 46/47, 410-460 sources on 384 slots,
/// `stage.slot_not_gathered` with no slot reserved); the search skips it.
pub fn stage_target(slots: usize, start: usize, state: impl Fn(usize) -> SlotState) -> Result<usize, RingRefusal> {
next_unreserved_slot(start, slots, |s| state(s).reserved).ok_or(RingRefusal::AllSlotsReserved)?;
let free = |s: usize| {
let target = state(s);
!target.reserved && (!target.live || target.gathered)
};
(0..slots).map(|step| (start + step) % slots).find(|s| free(*s)).ok_or(RingRefusal::SlotNotGathered)
}
#[cfg(test)]
#[path = "ring_prefetch/tests.rs"]
mod tests;