prefill: EXPERIMENTAL copy-ring prefetch behind LELEKA_PREFILL_RING_PREFETCH (off by default)
After a layer's copy ring drained, the experts the next layer missed most often in its last N chunks (per-layer miss history, top K <= ring/2, none on the 8-slot ring) are copied into the next ring's stage slots on the copy stream, overlapping the combine and the next mixer. The next Ring::new adopts the set: a routed, non-resident source with the same host bytes reads its prefetched slot (reserved until its gather, ordered by the slot's copied event); the rest are dropped. stage_one skips reserved slots; the stage-ahead walk waits for a gather when the next free slot is still live. Same experts, kernels and group order: bitwise neutral by construction. A set no ring took is drained on end_prompt_stream / begin_prompt_stream / close. - leleka-cuda-model ring_prefetch: policy, MissHistory ranking, match_prefetch, next_unreserved_slot (+ host model of the reserved-slot ring walk), 10 tests - driver: policy passed via OriginalMmqCopySchedule::set_ring_prefetch (no env read); counters ring.prefetch_issued / _hit / _wasted / _failed (MB), span ring.prefetch_issue - engine: ServeSettings::prefill_ring_prefetch (+ _WINDOW), settings test; issue from run_prompt_layer - docs/experiments/ring-prefetch.md: design, switch, counters, GPU validation plan (R-hash identity, A/B by tail) Not run on a GPU: no identity probe, no A/B, no speedup claimed. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
1799aee147
commit
3ba2a0e371
@@ -33,7 +33,7 @@ use std::{
|
||||
pub(crate) use leleka_cuda_model::bringup_trace_enabled;
|
||||
pub use leleka_cuda_model::{
|
||||
command_profile, device_arena, host_profile, mmq_original_prefill_misc, native_flash_attn,
|
||||
original_prefill_schedule, qsa_prompt_attention_select, s_gemv_legacy,
|
||||
original_prefill_schedule, qsa_prompt_attention_select, ring_prefetch, s_gemv_legacy,
|
||||
};
|
||||
use leleka_cuda_model::{original_expert_slots, original_mtp_loader, serving_context};
|
||||
|
||||
|
||||
@@ -124,7 +124,7 @@ pub struct OriginalMmqOutput<'lease, 'layer, 'ctx> {
|
||||
mod copy_ring;
|
||||
use copy_ring::GatherDest;
|
||||
pub(crate) use copy_ring::prefetch_point;
|
||||
pub use copy_ring::{OriginalMmqCopySchedule, RingExperts};
|
||||
pub use copy_ring::{OriginalMmqCopySchedule, PrefetchSource, PrefetchTarget, RingExperts};
|
||||
|
||||
// Closed global issuer consumer. Old per-layer/synchronous producers unchanged.
|
||||
#[path = "mmq_original_stream_all.rs"]
|
||||
|
||||
@@ -92,13 +92,14 @@ impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
Self::check_ring_statuses(statuses)
|
||||
}
|
||||
|
||||
/// Stages experts up to `limit` (the literal STAGE-1 lookahead) that are not yet staged.
|
||||
/// Stages experts up to `limit` (the literal STAGE-1 lookahead) that are not yet staged. With prefetched slots
|
||||
/// reserved in the ring (`LELEKA_PREFILL_RING_PREFETCH`) a copy that has no free slot yet waits for a later gather.
|
||||
fn ring_stage_ahead(
|
||||
ring: &mut copy_ring::Ring<'_, 'ctx>,
|
||||
formats: [MmqFormat; 3],
|
||||
(staged, limit, sources): (&mut usize, usize, usize),
|
||||
) -> Result<()> {
|
||||
while *staged < sources && *staged <= limit {
|
||||
while *staged < sources && *staged <= limit && ring.stage_room(*staged) {
|
||||
ring.stage_one(*staged, formats)?;
|
||||
*staged += 1;
|
||||
}
|
||||
|
||||
@@ -47,6 +47,9 @@ struct Slot {
|
||||
bytes: usize,
|
||||
live: bool,
|
||||
gathered: bool,
|
||||
/// holds a prefetched expert a routed source consumes (`LELEKA_PREFILL_RING_PREFETCH`): no copy reuses it before
|
||||
/// that source's gather
|
||||
reserved: bool,
|
||||
}
|
||||
struct Events<'ctx> {
|
||||
copied: Option<OriginalGpuEvent<'ctx>>,
|
||||
@@ -89,6 +92,9 @@ pub struct OriginalMmqCopySchedule<'ctx> {
|
||||
/// The per-layer status words, kept between layers: a cuMemFree per layer would synchronize the whole device
|
||||
/// (the copy stream included) and wait for every queued expert copy. `(bytes, buffer)`.
|
||||
status_pool: Option<(usize, DeviceBuffer<'ctx>)>,
|
||||
/// EXPERIMENTAL ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by default): the policy, the per-layer miss
|
||||
/// history and the experts copied ahead for the next layer's ring.
|
||||
prefetch: RingPrefetch<'ctx>,
|
||||
}
|
||||
struct Source<'read> {
|
||||
spans: &'read [ResidentExpertBankSpan; 3],
|
||||
@@ -101,6 +107,8 @@ struct Source<'read> {
|
||||
/// slot offsets of gate, up and down after a page-aligned copy (claude/ledger); `None`: the literal blob layout 0,
|
||||
/// gu, 2*gu
|
||||
dest: Option<[usize; 3]>,
|
||||
/// the expert was prefetched into `slot` before the router ran: no stage copy
|
||||
prefetched: bool,
|
||||
}
|
||||
/// Private owner: no external pointer/ready event can manufacture a stage.
|
||||
/// The actual source Rc prevents unregister/free during H2D or gathered use.
|
||||
@@ -121,6 +129,8 @@ pub(super) struct Ring<'read, 'ctx> {
|
||||
streamed: bool,
|
||||
layer: u8,
|
||||
stage_done: usize,
|
||||
/// slots still reserved for a prefetched expert (0 without the prefetch: the literal ring)
|
||||
reserved: usize,
|
||||
submitted: bool,
|
||||
drained: bool,
|
||||
closed: bool,
|
||||
@@ -147,3 +157,7 @@ mod original_mmq_copy_schedule_drop;
|
||||
mod ring;
|
||||
#[path = "mmq_original_ring/ring_drop.rs"]
|
||||
mod ring_drop;
|
||||
#[path = "mmq_original_ring/ring_prefetch_issue.rs"]
|
||||
mod ring_prefetch_issue;
|
||||
use ring_prefetch_issue::RingPrefetch;
|
||||
pub use ring_prefetch_issue::{PrefetchSource, PrefetchTarget};
|
||||
|
||||
@@ -65,6 +65,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
bytes_per_second: f64,
|
||||
) -> Result<()> {
|
||||
use crate::ffi::original_stager::Api as StagerApi;
|
||||
// the stream owns the stage slots from here: a ring prefetch no ring took is drained and dropped
|
||||
self.cancel_ring_prefetch()?;
|
||||
self.stream_admit(read, bank, first)?;
|
||||
let lease = read.lease();
|
||||
let ring = lease.copy_ring_slots()?;
|
||||
@@ -80,9 +82,15 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
self.stream_launch(api, bank, StreamPlan { first, ring, entries, targets }, events)
|
||||
}
|
||||
/// End the chunk's expert stream: stop and join the issuer, drain the copy and compute streams, release the
|
||||
/// raw events. Idempotent; a failure poisons the schedule.
|
||||
/// raw events. Idempotent; a failure poisons the schedule. A ring prefetch no ring took is dropped first (its
|
||||
/// copies drained), so no copy outlives the chunk's row lease.
|
||||
pub fn end_prompt_stream(&mut self) -> Result<()> {
|
||||
let Some(mut stream) = self.stream.take() else { return Ok(()) };
|
||||
let cancelled = self.cancel_ring_prefetch();
|
||||
let Some(stream) = self.stream.take() else { return cancelled };
|
||||
combine(cancelled, self.end_stream(stream))
|
||||
}
|
||||
|
||||
fn end_stream(&mut self, mut stream: ChunkStream) -> Result<()> {
|
||||
let stopped = stream.stop();
|
||||
let copy = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
let compute = self.compute.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
|
||||
@@ -8,6 +8,9 @@ mod ring_construction;
|
||||
#[path = "ring/ring_gather_and_finish.rs"]
|
||||
mod ring_gather_and_finish;
|
||||
mod ring_init;
|
||||
#[path = "ring/ring_prefetch.rs"]
|
||||
mod ring_prefetch;
|
||||
pub(super) use ring_prefetch::profile_prefetch;
|
||||
#[path = "ring/ring_stage_expert_copies.rs"]
|
||||
mod ring_stage_expert_copies;
|
||||
use ring_init::RingPlan;
|
||||
pub(super) use ring_init::RingPlan;
|
||||
|
||||
@@ -105,6 +105,9 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.record(self.schedule.compute.as_ref().ok_or(Error::ContextPoisoned)?)?;
|
||||
slot.gathered = true;
|
||||
if std::mem::take(&mut slot.reserved) {
|
||||
self.reserved -= 1;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The copy ring's side of the EXPERIMENTAL prefetch (`LELEKA_PREFILL_RING_PREFETCH`,
|
||||
//! docs/experiments/ring-prefetch.md): one prefetch copy into a stage slot, the miss history a ring feeds, and the
|
||||
//! adoption of the prefetched set when the router result is known. A prefetched expert is read by the same gather from
|
||||
//! the same bytes; only the time of its copy changes.
|
||||
|
||||
use super::super::ring_prefetch_issue::{PendingPrefetch, PrefetchEntry};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::ring_prefetch::{ExpertMask, mask_set, match_prefetch, next_unreserved_slot};
|
||||
|
||||
/// `(address, length)` of the gate, up and down host ranges: the identity of the bytes a copy moved.
|
||||
pub(in super::super) type Pieces = [(usize, usize); 3];
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
/// The host ranges of an expert as addresses, compared between the prefetch and the routed source.
|
||||
pub(in super::super) fn piece_ids(
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<Pieces> {
|
||||
Ok(Self::source_pieces(bank, spans)?.map(|p| (p.as_ptr() as usize, p.len())))
|
||||
}
|
||||
|
||||
/// Copies one expert into stage slot `slot` (span `span`) on the schedule's copy stream exactly as `stage_one` does
|
||||
/// and records the slot's `copied` event. The spans are checked like a routed source's first.
|
||||
pub(in super::super) fn prefetch_into_slot(
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
(slot, span): (usize, (ffi::BufferHandle, usize)),
|
||||
plan: &RingPlan,
|
||||
) -> Result<PrefetchEntry> {
|
||||
Self::check_source_spans(bank, spans, true, plan)?;
|
||||
let target = Slot { span: span.0, bytes: span.1, live: false, gathered: false, reserved: false };
|
||||
if target.bytes < plan.blob {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let dest = Self::prefetch_copy(schedule, bank, spans, &target, plan)?;
|
||||
let copy = schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let events = schedule.events.get_mut(slot).ok_or(Error::InvalidProjectionShape)?;
|
||||
events.copied.as_mut().ok_or(Error::ContextPoisoned)?.record(copy)?;
|
||||
let expert = spans[0].expert();
|
||||
Ok(PrefetchEntry { expert, slot, span, pieces: Self::piece_ids(bank, spans)?, dest })
|
||||
}
|
||||
|
||||
/// The page-aligned supersets side by side when they fit, else the exact pieces (`stage_copy_pieces`).
|
||||
fn prefetch_copy(
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
slot: &Slot,
|
||||
plan: &RingPlan,
|
||||
) -> Result<Option<[usize; 3]>> {
|
||||
let api = schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let copy = schedule.copy.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
if let Some(parts) = Self::aligned_parts(bank, spans, slot.bytes)? {
|
||||
Self::copy_aligned(copy, api, slot, &parts)?;
|
||||
return Ok(Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]));
|
||||
}
|
||||
let operands = Self::exact_operands(bank, slot, spans, (plan.gu, plan.down))?;
|
||||
Self::copy_exact(copy, api, bank, operands)?;
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// With the prefetch on, this layer's missed set (routed and not resident) joins the layer's history.
|
||||
pub(super) fn record_ring_misses(&mut self, plan: &RingPlan) {
|
||||
let Some(history) = self.schedule.prefetch.history.as_mut() else { return };
|
||||
let mut missed: ExpertMask = [0; 8];
|
||||
for source in self.sources.iter().filter(|s| s.resident.is_none()) {
|
||||
mask_set(&mut missed, source.spans[0].expert() as usize);
|
||||
}
|
||||
history.record(plan.layer, missed);
|
||||
}
|
||||
|
||||
/// Takes the schedule's prefetched set: a routed, non-resident source whose bytes a prefetch copied is read from
|
||||
/// that slot (reserved until its gather); every other prefetched slot stays free. A set issued for another layer,
|
||||
/// bank or arena is dropped once its copies are drained.
|
||||
pub(super) fn adopt_prefetch(&mut self, plan: &RingPlan) -> Result<()> {
|
||||
let Some(pending) = self.schedule.take_ring_prefetch() else { return Ok(()) };
|
||||
// the ring's drain also covers the prefetch copies, whatever happens below
|
||||
self.submitted = true;
|
||||
self.drained = false;
|
||||
if !self.prefetch_usable(&pending, plan) {
|
||||
profile_prefetch("ring.prefetch_wasted", pending.entries.len(), plan.blob);
|
||||
return self.schedule.drain_dropped_prefetch(pending);
|
||||
}
|
||||
let experts: Vec<u32> = pending.entries.iter().map(|e| e.expert).collect();
|
||||
let needs: Vec<Option<u32>> = self
|
||||
.sources
|
||||
.iter()
|
||||
.map(|s| (s.resident.is_none() && s.job.is_none()).then(|| s.spans[0].expert()))
|
||||
.collect();
|
||||
let matched = match_prefetch(&experts, &needs);
|
||||
let mut hits = 0;
|
||||
for (source, entry) in matched.hits {
|
||||
hits += usize::from(self.consume_prefetched(source, &pending.entries[entry])?);
|
||||
}
|
||||
profile_prefetch("ring.prefetch_hit", hits, plan.blob);
|
||||
profile_prefetch("ring.prefetch_wasted", pending.entries.len() - hits, plan.blob);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the set was issued for this layer, from this ring's bank, into this arena's slots, with no chunk stream.
|
||||
fn prefetch_usable(&self, pending: &PendingPrefetch<'ctx>, plan: &RingPlan) -> bool {
|
||||
let same_bank = self.bank.as_ref().is_some_and(|b| Rc::ptr_eq(b, &pending.bank));
|
||||
let same_slots = pending
|
||||
.entries
|
||||
.iter()
|
||||
.all(|e| self.slots.get(e.slot).is_some_and(|s| (s.span, s.bytes) == e.span && !s.live && !s.reserved));
|
||||
pending.layer == plan.layer
|
||||
&& pending.blob == plan.blob
|
||||
&& same_bank
|
||||
&& same_slots
|
||||
&& self.schedule.stream.is_none()
|
||||
}
|
||||
|
||||
/// Source `source` reads the prefetched slot when the copied bytes are its own; returns whether it does.
|
||||
fn consume_prefetched(&mut self, source: usize, entry: &PrefetchEntry) -> Result<bool> {
|
||||
let bank = self.bank.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
if Self::piece_ids(bank, self.sources[source].spans)? != entry.pieces {
|
||||
return Ok(false);
|
||||
}
|
||||
let slot = &mut self.slots[entry.slot];
|
||||
(slot.live, slot.gathered, slot.reserved) = (true, false, true);
|
||||
self.reserved += 1;
|
||||
let source = &mut self.sources[source];
|
||||
(source.slot, source.dest, source.prefetched) = (Some(entry.slot), entry.dest, true);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Whether stage_one copies the source: not resident, not a chunk stream entry, not prefetched.
|
||||
pub(super) fn needs_stage_copy(source: &Source<'read>) -> bool {
|
||||
source.resident.is_none() && source.entry.is_none() && !source.prefetched
|
||||
}
|
||||
|
||||
/// The next stage slot in ring order that no prefetched source holds (`stage_next` itself without a prefetch).
|
||||
pub(super) fn next_stage_slot(&self) -> Result<usize> {
|
||||
next_unreserved_slot(self.stage_next, self.slots.len(), |s| self.slots[s].reserved)
|
||||
.ok_or(Error::InvalidProjectionShape)
|
||||
}
|
||||
|
||||
/// Whether source `index` can be staged now. Always true without reserved slots (the literal ring); with them a
|
||||
/// copy waits for a gather when the next free slot is still ungathered (the reserved slots shrink the lookahead).
|
||||
pub(in super::super::super) fn stage_room(&self, index: usize) -> bool {
|
||||
if self.reserved == 0 {
|
||||
return true;
|
||||
}
|
||||
let Some(source) = self.sources.get(index) else { return true };
|
||||
if !Self::needs_stage_copy(source) {
|
||||
return true;
|
||||
}
|
||||
self.next_stage_slot().is_ok_and(|sl| !self.slots[sl].live || self.slots[sl].gathered)
|
||||
}
|
||||
}
|
||||
|
||||
/// `LELEKA_SERVE_PROFILE`: one call of `name` per expert, its MB as the value.
|
||||
pub(in super::super) fn profile_prefetch(name: &'static str, experts: usize, blob: usize) {
|
||||
for _ in 0..experts {
|
||||
crate::host_profile::add(name, blob as f64 / 1e6);
|
||||
}
|
||||
}
|
||||
@@ -46,13 +46,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
pub(in super::super::super) fn stage_one(&mut self, index: usize, formats: [MmqFormat; 3]) -> Result<()> {
|
||||
let source = self.sources.get(index).ok_or(Error::InvalidProjectionShape)?;
|
||||
if source.resident.is_some() || source.entry.is_some() {
|
||||
if !Self::needs_stage_copy(source) {
|
||||
return Ok(());
|
||||
}
|
||||
if source.slot.is_some() {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let sl = self.stage_next;
|
||||
let sl = self.next_stage_slot()?;
|
||||
let next = (sl + 1) % self.slots.len();
|
||||
self.stage_wait_slot(sl)?;
|
||||
let new_dest = self.stage_copy(index, sl, formats)?;
|
||||
@@ -150,7 +150,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
|
||||
/// `(superset, lead, offset)` of the three pieces side by side at page offsets, when they fit `slot_bytes`.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn aligned_parts<'b>(
|
||||
pub(super) fn aligned_parts<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
slot_bytes: usize,
|
||||
@@ -168,7 +168,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok((off <= slot_bytes).then_some(parts))
|
||||
}
|
||||
|
||||
fn copy_aligned(
|
||||
pub(super) fn copy_aligned(
|
||||
copy: &mut OriginalGpuStream<'ctx>,
|
||||
api: &Api,
|
||||
slot: &Slot,
|
||||
@@ -184,7 +184,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
|
||||
/// The exact gate, up and down host ranges and their destinations back to back in the slot.
|
||||
#[allow(clippy::type_complexity)]
|
||||
fn exact_operands<'b>(
|
||||
pub(super) fn exact_operands<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
slot: &Slot,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
@@ -199,7 +199,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok((sources, destinations))
|
||||
}
|
||||
|
||||
fn copy_exact(
|
||||
pub(super) fn copy_exact(
|
||||
copy: &mut OriginalGpuStream<'ctx>,
|
||||
api: &Api,
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
|
||||
@@ -5,18 +5,18 @@
|
||||
use super::*;
|
||||
|
||||
/// Layer-wide numbers every construction phase needs.
|
||||
pub(super) struct RingPlan {
|
||||
pub(super) layer: usize,
|
||||
pub(super) groups: usize,
|
||||
pub(super) formats: [MmqFormat; 3],
|
||||
pub(in super::super) struct RingPlan {
|
||||
pub(in super::super) layer: usize,
|
||||
pub(in super::super) groups: usize,
|
||||
pub(in super::super) formats: [MmqFormat; 3],
|
||||
/// raw bytes of one gate or up matrix
|
||||
pub(super) gu: usize,
|
||||
pub(in super::super) gu: usize,
|
||||
/// raw bytes of one down matrix
|
||||
pub(super) down: usize,
|
||||
pub(in super::super) down: usize,
|
||||
/// bytes of one expert blob (gate + up + down)
|
||||
pub(super) blob: usize,
|
||||
pub(in super::super) blob: usize,
|
||||
/// number of stage slots of the arena
|
||||
pub(super) count: usize,
|
||||
pub(in super::super) count: usize,
|
||||
}
|
||||
|
||||
impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
@@ -44,7 +44,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
|
||||
/// `(gate/up bytes, down bytes, blob bytes)` of one expert.
|
||||
pub(super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> {
|
||||
pub(in super::super) fn blob_geometry(formats: &[MmqFormat; 3]) -> Result<(usize, usize, usize)> {
|
||||
let gu = formats[0].layout(1)?.raw_weight;
|
||||
let down = formats[2].layout(1)?.raw_weight;
|
||||
let blob = gu.checked_mul(2).and_then(|n| n.checked_add(down)).ok_or(Error::InvalidSize)?;
|
||||
@@ -74,6 +74,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
streamed: false,
|
||||
layer: layer as u8,
|
||||
stage_done: 0,
|
||||
reserved: 0,
|
||||
submitted: false,
|
||||
drained: false,
|
||||
closed: false,
|
||||
@@ -86,6 +87,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
self.check_metadata_budget()?;
|
||||
self.admit_slots(plan)?;
|
||||
self.admit_sources(spans, plan)?;
|
||||
self.record_ring_misses(plan);
|
||||
self.adopt_prefetch(plan)?;
|
||||
self.attach_stream(plan)?;
|
||||
let jobs = self.plan_host_jobs(plan)?;
|
||||
self.admit_status(plan)?;
|
||||
@@ -147,7 +150,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
self.slots.push(Slot { span: h, bytes: n, live: false, gathered: false });
|
||||
self.slots.push(Slot { span: h, bytes: n, live: false, gathered: false, reserved: false });
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -158,7 +161,8 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
let ordered = i == 0 || spans[0].expert() > self.sources[i - 1].spans[0].expert();
|
||||
Self::check_source_spans(bank, spans, ordered, plan)?;
|
||||
let resident = self.resident_blob(spans[0].expert() as usize, plan)?;
|
||||
self.sources.push(Source { spans, resident, slot: None, job: None, entry: None, dest: None });
|
||||
let source = Source { spans, resident, slot: None, job: None, entry: None, dest: None, prefetched: false };
|
||||
self.sources.push(source);
|
||||
}
|
||||
self.trace_routes(plan);
|
||||
Ok(())
|
||||
@@ -183,7 +187,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
eprintln!("PREFILL-ROUTE layer={} routed={} missing={}", plan.layer, hex(&routed), hex(&missing));
|
||||
}
|
||||
|
||||
fn check_source_spans(
|
||||
pub(super) fn check_source_spans(
|
||||
bank: &crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
ordered: bool,
|
||||
@@ -247,7 +251,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
}
|
||||
|
||||
/// The gate, up and down host ranges of one expert.
|
||||
fn source_pieces<'b>(
|
||||
pub(super) fn source_pieces<'b>(
|
||||
bank: &'b crate::MappedExpertBank<'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
) -> Result<[&'b [u8]; 3]> {
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
//! EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by default;
|
||||
//! docs/experiments/ring-prefetch.md): the schedule's half. After a layer's ring has drained, the experts the NEXT
|
||||
//! layer missed most often in its recent chunks are copied into the next ring's stage slots on the copy stream while
|
||||
//! the layer's combine and the next mixer run. The next `Ring::new` takes the set (`adopt_prefetch`). The policy comes
|
||||
//! from the engine's settings; nothing here reads the environment.
|
||||
|
||||
use super::ring::{RingPlan, profile_prefetch};
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::ring_prefetch::{MissHistory, RingPrefetchPolicy};
|
||||
|
||||
/// One expert copied ahead into a stage slot.
|
||||
pub(super) struct PrefetchEntry {
|
||||
pub(super) expert: u32,
|
||||
pub(super) slot: usize,
|
||||
/// the stage slot's `(span, bytes)` at the copy: the adopting ring must see the same arena slot
|
||||
pub(super) span: (ffi::BufferHandle, usize),
|
||||
/// `(address, length)` of the copied gate, up and down host ranges
|
||||
pub(super) pieces: [(usize, usize); 3],
|
||||
/// the page-aligned lead offsets, as `stage_record` keeps them
|
||||
pub(super) dest: Option<[usize; 3]>,
|
||||
}
|
||||
|
||||
/// The experts copied for the next ring of `layer`, with the bank the copies read (held while they may run).
|
||||
pub(super) struct PendingPrefetch<'ctx> {
|
||||
pub(super) layer: usize,
|
||||
pub(super) bank: Rc<crate::MappedExpertBank<'ctx>>,
|
||||
pub(super) blob: usize,
|
||||
pub(super) entries: Vec<PrefetchEntry>,
|
||||
}
|
||||
|
||||
/// The policy (none: off), the per-layer miss history and the copied set waiting for its ring.
|
||||
#[derive(Default)]
|
||||
pub(super) struct RingPrefetch<'ctx> {
|
||||
pub(super) policy: Option<RingPrefetchPolicy>,
|
||||
pub(super) history: Option<MissHistory>,
|
||||
pub(super) pending: Option<PendingPrefetch<'ctx>>,
|
||||
}
|
||||
|
||||
/// The bank spans and matrix formats of one predicted expert, as the caller resolved them; `None` skips it.
|
||||
pub type PrefetchSource = Option<([ResidentExpertBankSpan; 3], [MmqFormat; 3])>;
|
||||
|
||||
/// The ring the prefetch fills: the row lease's read, the registered bank and the layer about to run.
|
||||
pub struct PrefetchTarget<'a, 'arena, 'loan, 'ctx> {
|
||||
pub read: &'a crate::OriginalDeviceGrRead<'arena, 'loan, 'ctx>,
|
||||
pub bank: &'a Rc<crate::MappedExpertBank<'ctx>>,
|
||||
pub layer: usize,
|
||||
}
|
||||
|
||||
impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
/// Switches the prefetch on (with its policy) or off; the miss history starts empty.
|
||||
pub fn set_ring_prefetch(&mut self, policy: Option<RingPrefetchPolicy>) {
|
||||
self.prefetch.history = policy.map(|p| MissHistory::new(p.window));
|
||||
self.prefetch.policy = policy;
|
||||
}
|
||||
|
||||
pub fn ring_prefetch(&self) -> Option<RingPrefetchPolicy> {
|
||||
self.prefetch.policy
|
||||
}
|
||||
|
||||
/// Copies the predicted missing experts of `target.layer` into its ring's stage slots; returns how many. Never
|
||||
/// fails the caller: a refused or failed prefetch copies less (or nothing) and the ring copies the rest as usual.
|
||||
pub fn prefetch_ring_layer(
|
||||
&mut self,
|
||||
target: PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
mut sources: impl FnMut(u32) -> PrefetchSource,
|
||||
) -> usize {
|
||||
if self.prefetch.policy.is_none() || self.cancel_ring_prefetch().is_err() || !self.prefetch_allowed(&target) {
|
||||
return 0;
|
||||
}
|
||||
let _span = crate::host_profile::span("ring.prefetch_issue");
|
||||
let issued = self.issue_prefetch(&target, &mut sources);
|
||||
if issued.is_err() {
|
||||
// a copy may have been queued for the failed expert: let it land before anything is dropped
|
||||
crate::host_profile::add("ring.prefetch_failed", 1.0);
|
||||
let _ = self.copy.as_ref().map(OriginalGpuStream::synchronize);
|
||||
}
|
||||
let count = self.prefetch.pending.as_ref().map_or(0, |p| p.entries.len());
|
||||
if count == 0 {
|
||||
self.prefetch.pending = None;
|
||||
} else if let Some(Ok(copy)) = self.copy.as_mut().map(|c| c.with_enqueue(Ok)) {
|
||||
// the mixer's drains stop waiting for these copies; the next ring's `take_ring_prefetch` restores them
|
||||
crate::compute_drain::set_background(copy);
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
/// No chunk stream, a registered (page-locked) bank, a healthy schedule and a layer that exists.
|
||||
fn prefetch_allowed(&self, target: &PrefetchTarget<'_, '_, '_, 'ctx>) -> bool {
|
||||
self.stream.is_none()
|
||||
&& !self.is_failed()
|
||||
&& target.layer < 48
|
||||
&& !target.bank.pageable()
|
||||
&& target.bank.cache_context_matches(self.context)
|
||||
&& target.read.context_matches(self.context)
|
||||
&& !skip_expert_dma()
|
||||
&& crate::compute_drain::background() == 0
|
||||
}
|
||||
|
||||
/// Predicts, then copies expert after expert into slots 0, 1, ...; the set is kept as it grows.
|
||||
fn issue_prefetch(
|
||||
&mut self,
|
||||
target: &PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
sources: &mut impl FnMut(u32) -> PrefetchSource,
|
||||
) -> Result<()> {
|
||||
let lease = target.read.lease();
|
||||
let slots = lease.copy_ring_slots()?.min(self.events.len());
|
||||
let policy = self.prefetch.policy.ok_or(Error::ContextPoisoned)?;
|
||||
let history = self.prefetch.history.as_ref().ok_or(Error::ContextPoisoned)?;
|
||||
let resident = |e: u32| lease.cache_expert_span(target.layer, e as usize).map_or(true, |s| s.is_some());
|
||||
let experts = history.predict(target.layer, policy.budget(slots), resident);
|
||||
for expert in experts {
|
||||
let Some((spans, formats)) = sources(expert) else { continue };
|
||||
self.prefetch_one(target, &spans, formats)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Copies one expert into the next free prefetch slot; an expert of another format than the set is skipped.
|
||||
fn prefetch_one(
|
||||
&mut self,
|
||||
target: &PrefetchTarget<'_, '_, '_, 'ctx>,
|
||||
spans: &[ResidentExpertBankSpan; 3],
|
||||
formats: [MmqFormat; 3],
|
||||
) -> Result<()> {
|
||||
let plan = Self::prefetch_plan(target.layer, formats)?;
|
||||
let pending = self.prefetch.pending.get_or_insert_with(|| PendingPrefetch {
|
||||
layer: target.layer,
|
||||
bank: Rc::clone(target.bank),
|
||||
blob: plan.blob,
|
||||
entries: Vec::new(),
|
||||
});
|
||||
if pending.blob != plan.blob {
|
||||
return Ok(());
|
||||
}
|
||||
let slot = pending.entries.len();
|
||||
let span = target.read.lease().copy_ring_span(slot)?;
|
||||
Self::check_prefetch_slot(target.read, span, plan.blob)?;
|
||||
let entry = Ring::prefetch_into_slot(self, target.bank, spans, (slot, span), &plan)?;
|
||||
self.prefetch.pending.as_mut().ok_or(Error::ContextPoisoned)?.entries.push(entry);
|
||||
profile_prefetch("ring.prefetch_issued", 1, plan.blob);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The ring plan of one expert of `layer` in `formats` (the same checks as `Ring::new`).
|
||||
fn prefetch_plan(layer: usize, formats: [MmqFormat; 3]) -> Result<RingPlan> {
|
||||
if formats[0] != formats[1] || !FORMATS[..5].contains(&formats[0]) || !FORMATS[5..].contains(&formats[2]) {
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
let (gu, down, blob) = Ring::blob_geometry(&formats)?;
|
||||
Ok(RingPlan { layer, groups: 0, formats, gu, down, blob, count: 0 })
|
||||
}
|
||||
|
||||
/// A stage slot holds the blob and overlaps no temporary role of the arena (`Ring::admit_slots`).
|
||||
fn check_prefetch_slot(
|
||||
read: &crate::OriginalDeviceGrRead<'_, '_, 'ctx>,
|
||||
(h, n): (ffi::BufferHandle, usize),
|
||||
blob: usize,
|
||||
) -> Result<()> {
|
||||
if n < blob {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
h.validate_projection_extent(n, 256)?;
|
||||
for role in 0..TMP {
|
||||
let (a, m) = GroupArena::span(read, role)?;
|
||||
if h.overlaps(blob, a, m) {
|
||||
return Err(Error::OutputAliasesInput);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The copied set for the ring being built (the drains wait for the copy stream again from here on).
|
||||
pub(super) fn take_ring_prefetch(&mut self) -> Option<PendingPrefetch<'ctx>> {
|
||||
let pending = self.prefetch.pending.take()?;
|
||||
self.restore_drains();
|
||||
Some(pending)
|
||||
}
|
||||
|
||||
/// Drops a set no ring consumes: its copies finish before the bank reference goes.
|
||||
pub(super) fn drain_dropped_prefetch(&mut self, pending: PendingPrefetch<'ctx>) -> Result<()> {
|
||||
let drained = self.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
if drained.is_err() {
|
||||
self.failed = true;
|
||||
std::mem::forget(pending);
|
||||
return drained;
|
||||
}
|
||||
drop(pending);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Drops a set no ring took (a failed chunk, a chunk stream starting, the forward's exit). Idempotent.
|
||||
pub fn cancel_ring_prefetch(&mut self) -> Result<()> {
|
||||
let Some(pending) = self.take_ring_prefetch() else { return Ok(()) };
|
||||
profile_prefetch("ring.prefetch_wasted", pending.entries.len(), pending.blob);
|
||||
self.drain_dropped_prefetch(pending)
|
||||
}
|
||||
|
||||
/// Drains wait for the copy stream again; buffers freed meanwhile are released now.
|
||||
fn restore_drains(&mut self) {
|
||||
if crate::compute_drain::background() != 0 && self.stream.is_none() {
|
||||
crate::compute_drain::set_background(0);
|
||||
if self.context.flush_deferred_frees().is_err() {
|
||||
self.failed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,6 +134,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
stream_events: Vec::new(),
|
||||
stream_started: None,
|
||||
status_pool: None,
|
||||
prefetch: RingPrefetch::default(),
|
||||
}
|
||||
}
|
||||
/// Create the copy and compute streams and the copied/used events of `slots` ring slots.
|
||||
|
||||
@@ -49,6 +49,18 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
self.completed_experts = self.order.len();
|
||||
Ok(())
|
||||
}
|
||||
/// EXPERIMENTAL (`LELEKA_PREFILL_RING_PREFETCH`, docs/experiments/ring-prefetch.md): after this layer's copy ring
|
||||
/// drained, copy the experts `layer` (the next one) is predicted to miss into its ring's stage slots, through this
|
||||
/// layer's row lease. Returns how many were copied; never fails (the next ring copies whatever is missing).
|
||||
pub fn prefetch_ring_layer(
|
||||
&self,
|
||||
schedule: &mut crate::OriginalMmqCopySchedule<'ctx>,
|
||||
bank: &std::rc::Rc<MappedExpertBank<'ctx>>,
|
||||
layer: usize,
|
||||
sources: impl FnMut(u32) -> crate::PrefetchSource,
|
||||
) -> usize {
|
||||
schedule.prefetch_ring_layer(crate::PrefetchTarget { read: &self.read, bank, layer }, sources)
|
||||
}
|
||||
pub fn execute_mmq(
|
||||
&mut self,
|
||||
workspace: &mut MmqWorkspace<'ctx>,
|
||||
|
||||
@@ -8,8 +8,8 @@ pub use device_slab::{DeviceSlice, SlabAllocator, SlabPolicy, SlabStats};
|
||||
pub use gdn_state_finite_guard::GdnStateFiniteGuard;
|
||||
pub use head_greedy::{HEAD_GREEDY_WORKSPACE_BYTES, HeadGreedySelection, HeadGreedyWorkspace};
|
||||
pub use mmq::resident::original_group::{
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, OriginalStreamAllLayer, RingExperts,
|
||||
original_mmq_group_bank_bytes,
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, OriginalStreamAllLayer, PrefetchSource,
|
||||
PrefetchTarget, RingExperts, original_mmq_group_bank_bytes,
|
||||
};
|
||||
pub use mmq::resident::{FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace};
|
||||
pub use mmq::{MmqExperiment, MmqFormat, MmqProfile, MmqRequest, MmqWeights};
|
||||
|
||||
@@ -29,6 +29,7 @@ pub mod original_mtp_loader;
|
||||
pub mod original_prefill_schedule;
|
||||
mod projection;
|
||||
pub mod qsa_prompt_attention_select;
|
||||
pub mod ring_prefetch;
|
||||
pub mod s_gemv_legacy;
|
||||
pub mod serving_context;
|
||||
mod shapes;
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
//! Pure host-side half of the EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by
|
||||
//! default; docs/experiments/ring-prefetch.md).
|
||||
//!
|
||||
//! 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,
|
||||
}
|
||||
|
||||
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.
|
||||
pub fn new(top_k: usize, window: usize) -> Self {
|
||||
Self { top_k: top_k.min(EXPERTS), window: window.clamp(1, Self::MAX_WINDOW) }
|
||||
}
|
||||
|
||||
/// 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))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "ring_prefetch/tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,192 @@
|
||||
//! The ring prefetch's pure halves: the budget, the miss ranking, the consume-once matching and the slot search, plus
|
||||
//! a host model of the copy ring's stage-ahead walk with reserved (prefetched) slots.
|
||||
use super::*;
|
||||
|
||||
fn mask(experts: &[usize]) -> ExpertMask {
|
||||
let mut m = [0u64; EXPERTS / 64];
|
||||
for &e in experts {
|
||||
mask_set(&mut m, e);
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_budget_is_bounded_by_half_the_ring_and_zero_on_the_small_ring() {
|
||||
let policy = RingPrefetchPolicy::new(150, 8);
|
||||
assert_eq!(policy.budget(8), 0, "the literal 8-slot ring of the 512-row rung is never prefetched into");
|
||||
assert_eq!(policy.budget(31), 0);
|
||||
assert_eq!(policy.budget(32), 16);
|
||||
assert_eq!(policy.budget(96), 48);
|
||||
assert_eq!(policy.budget(384), 150);
|
||||
assert_eq!(RingPrefetchPolicy::new(10_000, 0), RingPrefetchPolicy { top_k: 512, window: 1 });
|
||||
assert_eq!(RingPrefetchPolicy::new(1, 1_000).window, RingPrefetchPolicy::MAX_WINDOW);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn masks_hold_exactly_the_experts_set() {
|
||||
let m = mask(&[0, 63, 64, 511, 512]);
|
||||
assert!(mask_has(&m, 0) && mask_has(&m, 63) && mask_has(&m, 64) && mask_has(&m, 511));
|
||||
assert!(!mask_has(&m, 1) && !mask_has(&m, 512), "out of range is never set");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ranking_is_frequency_then_recency_then_id() {
|
||||
let mut history = MissHistory::new(4);
|
||||
history.record(3, mask(&[10, 20, 30]));
|
||||
history.record(3, mask(&[10, 40]));
|
||||
history.record(3, mask(&[10, 20, 50]));
|
||||
// 10: 3 chunks; 20: 2 (newest 3); 50: 1 (newest 3); 40: 1 (newest 2); 30: 1 (newest 1)
|
||||
assert_eq!(history.predict(3, 10, |_| false), [10, 20, 50, 40, 30]);
|
||||
assert_eq!(history.predict(3, 2, |_| false), [10, 20], "bounded by k");
|
||||
assert!(history.predict(4, 10, |_| false).is_empty(), "history is per layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resident_experts_are_skipped_and_ties_break_by_id() {
|
||||
let mut history = MissHistory::new(2);
|
||||
history.record(0, mask(&[7, 5, 9]));
|
||||
assert_eq!(history.predict(0, 10, |_| false), [5, 7, 9]);
|
||||
assert_eq!(history.predict(0, 10, |e| e == 7), [5, 9], "an expert resident now is not prefetched");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_window_forgets_the_oldest_chunk() {
|
||||
let mut history = MissHistory::new(2);
|
||||
history.record(1, mask(&[1]));
|
||||
history.record(1, mask(&[2]));
|
||||
history.record(1, mask(&[3]));
|
||||
assert_eq!(history.depth(1), 2);
|
||||
assert_eq!(history.predict(1, 10, |_| false), [3, 2], "expert 1 left the window");
|
||||
history.record(LAYERS, mask(&[1]));
|
||||
assert!(history.predict(LAYERS, 10, |_| false).is_empty(), "an out-of-range layer is ignored");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_prefetched_entry_is_consumed_at_most_once_and_misses_are_dropped() {
|
||||
let prefetched = [40, 10, 20, 99];
|
||||
// sources: 10 (copy), 15 (copy), 20 (resident -> None), 40 (copy), 40 again (impossible routing, consumed once)
|
||||
let needs = [Some(10), Some(15), None, Some(40), Some(40)];
|
||||
let m = match_prefetch(&prefetched, &needs);
|
||||
assert_eq!(m.hits, [(0, 1), (3, 0)]);
|
||||
assert_eq!(m.wasted, [2, 3], "20 became resident, 99 was not routed");
|
||||
let consumed: Vec<usize> = m.hits.iter().map(|h| h.1).chain(m.wasted.iter().copied()).collect();
|
||||
let mut sorted = consumed.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, [0, 1, 2, 3], "every entry is either consumed or dropped, exactly once");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slot_search_is_the_literal_order_without_reservations() {
|
||||
assert_eq!(next_unreserved_slot(5, 8, |_| false), Some(5));
|
||||
assert_eq!(next_unreserved_slot(7, 8, |s| s == 7 || s == 0), Some(1), "wraps past reserved slots");
|
||||
assert_eq!(next_unreserved_slot(0, 4, |_| true), None);
|
||||
}
|
||||
|
||||
/// One source of the ring model: resident, a prefetch hit holding a reserved slot, or a mandatory copy.
|
||||
#[derive(Clone, Copy, PartialEq, Debug)]
|
||||
enum Kind {
|
||||
Resident,
|
||||
Hit(usize),
|
||||
Copy,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct ModelSlot {
|
||||
live: bool,
|
||||
gathered: bool,
|
||||
reserved: bool,
|
||||
}
|
||||
|
||||
/// The driver's stage-ahead walk (`stream_through_ring`) with reserved slots: copies only into an unreserved slot that
|
||||
/// is free or gathered, a gather releases its slot. Returns the slot each source was read from.
|
||||
fn walk(slots: usize, sources: &[Kind]) -> Vec<Option<usize>> {
|
||||
let mut model = RingModel { ring: vec![ModelSlot::default(); slots], at: vec![None; sources.len()], next: 0 };
|
||||
for (i, kind) in sources.iter().enumerate() {
|
||||
if let Kind::Hit(slot) = kind {
|
||||
model.ring[*slot] = ModelSlot { live: true, gathered: false, reserved: true };
|
||||
model.at[i] = Some(*slot);
|
||||
}
|
||||
}
|
||||
let mut staged = 0usize;
|
||||
for j in 0..sources.len() {
|
||||
while staged < sources.len() && staged < j + slots {
|
||||
if sources[staged] == Kind::Copy && !model.stage(staged) {
|
||||
break; // no room: stage after the next gather
|
||||
}
|
||||
staged += 1;
|
||||
}
|
||||
assert!(staged > j, "source {j} is staged before its gather");
|
||||
model.gather(j);
|
||||
}
|
||||
model.at
|
||||
}
|
||||
|
||||
/// The ring's slots, the slot each source reads and the next slot of the rotation.
|
||||
struct RingModel {
|
||||
ring: Vec<ModelSlot>,
|
||||
at: Vec<Option<usize>>,
|
||||
next: usize,
|
||||
}
|
||||
|
||||
impl RingModel {
|
||||
/// `stage_one`: copies source `index` into the next unreserved slot unless that one is still ungathered.
|
||||
fn stage(&mut self, index: usize) -> bool {
|
||||
let slots = self.ring.len();
|
||||
let sl = next_unreserved_slot(self.next, slots, |s| self.ring[s].reserved).expect("a free slot");
|
||||
if self.ring[sl].live && !self.ring[sl].gathered {
|
||||
return false;
|
||||
}
|
||||
self.ring[sl] = ModelSlot { live: true, gathered: false, reserved: false };
|
||||
self.at[index] = Some(sl);
|
||||
self.next = (sl + 1) % slots;
|
||||
true
|
||||
}
|
||||
|
||||
/// `gather`: reads the source's slot (live and not yet gathered) and releases it.
|
||||
fn gather(&mut self, j: usize) {
|
||||
if let Some(sl) = self.at[j] {
|
||||
assert!(self.ring[sl].live && !self.ring[sl].gathered, "source {j} reads a live, ungathered slot");
|
||||
self.ring[sl].gathered = true;
|
||||
self.ring[sl].reserved = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reserved_slots_are_never_overwritten_before_their_gather() {
|
||||
let slots = 32;
|
||||
let budget = RingPrefetchPolicy::new(150, 8).budget(slots);
|
||||
let mut sources = Vec::new();
|
||||
for i in 0..120 {
|
||||
sources.push(match i % 5 {
|
||||
0 if i / 5 < budget => Kind::Hit(i / 5),
|
||||
1 => Kind::Resident,
|
||||
_ => Kind::Copy,
|
||||
});
|
||||
}
|
||||
let at = walk(slots, &sources);
|
||||
for (i, kind) in sources.iter().enumerate() {
|
||||
match kind {
|
||||
Kind::Resident => assert_eq!(at[i], None),
|
||||
Kind::Hit(slot) => assert_eq!(at[i], Some(*slot), "a hit is consumed from its prefetched slot"),
|
||||
Kind::Copy => assert!(at[i].is_some()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_prefetch_the_walk_is_the_literal_rotation() {
|
||||
let at = walk(8, &[Kind::Copy; 20]);
|
||||
let want: Vec<Option<usize>> = (0..20).map(|i| Some(i % 8)).collect();
|
||||
assert_eq!(at, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_ring_half_reserved_still_stages_every_copy() {
|
||||
let slots = 32;
|
||||
let mut sources: Vec<Kind> = (0..16).map(Kind::Hit).collect();
|
||||
sources.extend([Kind::Copy; 100]);
|
||||
sources.rotate_left(8); // copies before and after the hits
|
||||
let at = walk(slots, &sources);
|
||||
assert!(at.iter().all(Option::is_some));
|
||||
}
|
||||
+4
-2
@@ -85,8 +85,10 @@ impl<'ctx> MoeWeightCache<'ctx> {
|
||||
// Create persistent actual streams/events before model cache fills.
|
||||
// Slot count comes from the same options used to carve the arena.
|
||||
let slots = options.original_ring_slots().map_err(|e| arena_driver_error(2, e))?;
|
||||
self.original_copy_schedule =
|
||||
Some(context.original_mmq_copy_schedule(slots).map_err(|e| arena_driver_error(3, e))?);
|
||||
let mut schedule = context.original_mmq_copy_schedule(slots).map_err(|e| arena_driver_error(3, e))?;
|
||||
// EXPERIMENTAL, off by default: docs/experiments/ring-prefetch.md
|
||||
schedule.set_ring_prefetch(crate::settings::process().serve.prefill_ring_prefetch);
|
||||
self.original_copy_schedule = Some(schedule);
|
||||
let device = context.original_moe_prompt_device(capacity as usize).map_err(|e| arena_driver_error(4, e))?;
|
||||
self.original_prompt_device = Some(device);
|
||||
let bank = context.mapped_expert_bank(lease, members).map_err(|e| arena_driver_error(5, e))?;
|
||||
|
||||
@@ -7,6 +7,8 @@ use leleka_cuda_driver::{
|
||||
MappedExpertBank, MmqFormat, MmqWorkspace, OriginalMmqCopySchedule, OriginalMoePromptDevice, OriginalMoePromptLayer,
|
||||
};
|
||||
|
||||
mod prompt_ring_prefetch;
|
||||
|
||||
type SpanCache = (usize, Vec<Option<([ResidentExpertBankSpan; 3], [MmqFormat; 3])>>);
|
||||
type Spans = [ResidentExpertBankSpan; 3];
|
||||
const BITS: usize = 48 * 512;
|
||||
@@ -81,6 +83,7 @@ pub(super) fn run_prompt_layer<'arena, 'loan, 'ctx>(
|
||||
let ring = RingOwners { mmq: io.mmq, schedule: io.schedule, layer: io.layer, bank: scan.bank };
|
||||
copy_ring(&mut layer_program, ring, &sources, routed)?;
|
||||
drop(ring_span);
|
||||
prompt_ring_prefetch::prefetch_next_layer(&layer_program, io.schedule, scan);
|
||||
let _span = prof::span(PStage::MoeFinish, drain);
|
||||
let block = layer_program.finish(shared).map_err(driver_error)?;
|
||||
end_stream_if_last(io)?;
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
//! EXPERIMENTAL prompt copy-ring prefetch (`LELEKA_PREFILL_RING_PREFETCH`, off by default;
|
||||
//! docs/experiments/ring-prefetch.md): once a layer's copy ring has drained, the experts the next layer is predicted to
|
||||
//! miss are copied into its ring's stage slots through this layer's row lease, so the PCIe copies run under this
|
||||
//! layer's combine and the next layer's mixer instead of after the next router.
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
use crate::qwen_forward::contract::Dimension;
|
||||
use leleka_cuda_driver::{OriginalMmqCopySchedule, OriginalMoePromptLayer, PrefetchSource};
|
||||
|
||||
/// Copies the next layer's predicted misses ahead; nothing when the switch is off or this is the last layer. Never
|
||||
/// fails the layer: the next ring copies whatever was not prefetched.
|
||||
pub(super) fn prefetch_next_layer<'ctx>(
|
||||
layer_program: &OriginalMoePromptLayer<'_, '_, '_, 'ctx>,
|
||||
schedule: &mut OriginalMmqCopySchedule<'ctx>,
|
||||
scan: &mut SpanScan<'_, 'ctx>,
|
||||
) {
|
||||
if schedule.ring_prefetch().is_none() {
|
||||
return;
|
||||
}
|
||||
let Some(next) = next_layer(scan) else { return };
|
||||
let bank = scan.bank;
|
||||
let lookup = SpanScan {
|
||||
binding: scan.binding,
|
||||
layer: next,
|
||||
bank,
|
||||
finite: &mut *scan.finite,
|
||||
span_cache: &mut *scan.span_cache,
|
||||
span_cache_on: scan.span_cache_on,
|
||||
};
|
||||
let sources = |expert: u32| lookup.prefetch_source(expert);
|
||||
let copied = layer_program.prefetch_ring_layer(schedule, bank, next.get() as usize, sources);
|
||||
crate::bringup_trace!("DBG ring prefetch: layer {} copied {copied}", next.get());
|
||||
}
|
||||
|
||||
/// The layer after this one, unless this is the last.
|
||||
fn next_layer(scan: &SpanScan<'_, '_>) -> Option<LayerId> {
|
||||
let count = scan.binding.layer_count();
|
||||
let next = scan.layer.get().checked_add(1).filter(|n| *n < count)?;
|
||||
LayerId::new(u64::from(next), Dimension::new(u64::from(count)).ok()?).ok()
|
||||
}
|
||||
|
||||
impl SpanScan<'_, '_> {
|
||||
/// The bank spans and formats of an expert of this scan's layer that was admitted before (its bytes passed the
|
||||
/// finite scan), from the span cache or a walk of the binding that changes nothing; `None` for any other expert.
|
||||
fn prefetch_source(&self, expert: u32) -> PrefetchSource {
|
||||
let bit = self.layer.get() as usize * 512 + expert as usize;
|
||||
if bit >= BITS || self.finite[bit / 64] >> (bit % 64) & 1 == 0 {
|
||||
return None;
|
||||
}
|
||||
if self.span_cache_on
|
||||
&& let Some((spans, format)) = self.span_cache.1.get(bit).and_then(Option::as_ref)
|
||||
{
|
||||
return Some((spans.clone(), *format));
|
||||
}
|
||||
let bound = self.bound_weights(expert).ok()?;
|
||||
let ((spans, _), format) = self.walk(&bound, expert, true).ok()?;
|
||||
Some((spans, format))
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
//! experimental switches the Original serve load honours.
|
||||
use super::parse::{equals, number, one_of, positive_gib};
|
||||
use super::source::EnvSource;
|
||||
use leleka_cuda_driver::ring_prefetch::RingPrefetchPolicy;
|
||||
use std::ffi::OsString;
|
||||
|
||||
/// What the operator chose for one serve process.
|
||||
@@ -49,6 +50,12 @@ pub(crate) struct ServeSettings {
|
||||
/// as a chunked scan on the tensor cores (f16x3 products; not bitwise equal to the sequential kernel). Decided
|
||||
/// by the first-token KL / logprob gates of docs/quality-gate.md, never by an identity probe.
|
||||
pub(crate) prefill_gdn_tc: bool,
|
||||
/// `LELEKA_PREFILL_RING_PREFETCH` (EXPERIMENTAL, off by default; docs/experiments/ring-prefetch.md): `1` or `on`
|
||||
/// copies the most often recently missed experts of the next layer (top 150) into its copy ring's stage slots
|
||||
/// before its router runs; a number `2..=512` sets that top K. `LELEKA_PREFILL_RING_PREFETCH_WINDOW`
|
||||
/// (`1..=64`, default 8) is the number of recent chunks whose misses are counted. Bitwise neutral by
|
||||
/// construction; the R-hash identity probe and the paired A/B are still owed.
|
||||
pub(crate) prefill_ring_prefetch: Option<RingPrefetchPolicy>,
|
||||
}
|
||||
|
||||
impl ServeSettings {
|
||||
@@ -70,6 +77,19 @@ impl ServeSettings {
|
||||
decode_graph_reuse: one_of(env, "LELEKA_DECODE_GRAPH_REUSE", &["1", "on"]),
|
||||
draft_check_merge: one_of(env, "LELEKA_DRAFT_CHECK_MERGE", &["1", "on"]),
|
||||
prefill_gdn_tc: one_of(env, "LELEKA_PREFILL_GDN_TC", &["1", "on"]),
|
||||
prefill_ring_prefetch: ring_prefetch(env),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `LELEKA_PREFILL_RING_PREFETCH`: `1` / `on` (the default top K) or a top K in `2..=512`; anything else is off.
|
||||
pub(super) fn ring_prefetch(env: &impl EnvSource) -> Option<RingPrefetchPolicy> {
|
||||
let top_k = match env.get("LELEKA_PREFILL_RING_PREFETCH")?.as_str() {
|
||||
"1" | "on" => RingPrefetchPolicy::DEFAULT_TOP_K,
|
||||
value => value.parse::<usize>().ok().filter(|k| (2..=512).contains(k))?,
|
||||
};
|
||||
let window = number::<usize>(env, "LELEKA_PREFILL_RING_PREFETCH_WINDOW")
|
||||
.filter(|n| (1..=RingPrefetchPolicy::MAX_WINDOW).contains(n))
|
||||
.unwrap_or(RingPrefetchPolicy::DEFAULT_WINDOW);
|
||||
Some(RingPrefetchPolicy::new(top_k, window))
|
||||
}
|
||||
|
||||
@@ -125,6 +125,29 @@ fn the_draft_check_merge_is_one_or_on_and_off_by_default() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_ring_prefetch_is_one_on_or_a_top_k_and_off_by_default() {
|
||||
use leleka_cuda_driver::ring_prefetch::RingPrefetchPolicy as P;
|
||||
let key = "LELEKA_PREFILL_RING_PREFETCH";
|
||||
assert_eq!(serve(&[]).prefill_ring_prefetch, None);
|
||||
let default = Some(P::new(P::DEFAULT_TOP_K, P::DEFAULT_WINDOW));
|
||||
#[rustfmt::skip]
|
||||
let rows = [
|
||||
("1", default), ("on", default), ("200", Some(P::new(200, 8))), ("2", Some(P::new(2, 8))),
|
||||
("512", Some(P::new(512, 8))), ("0", None), ("513", None), ("off", None), ("yes", None), (" 1", None),
|
||||
("", None),
|
||||
];
|
||||
for (value, want) in rows {
|
||||
assert_eq!(serve(&[(key, value)]).prefill_ring_prefetch, want, "{value:?}");
|
||||
}
|
||||
let window = |w: &str| serve(&[(key, "on"), ("LELEKA_PREFILL_RING_PREFETCH_WINDOW", w)]).prefill_ring_prefetch;
|
||||
assert_eq!(window("16"), Some(P::new(P::DEFAULT_TOP_K, 16)));
|
||||
for invalid in ["0", "65", "x", ""] {
|
||||
assert_eq!(window(invalid), default, "window {invalid:?} keeps the default");
|
||||
}
|
||||
assert_eq!(serve(&[("LELEKA_PREFILL_RING_PREFETCH_WINDOW", "4")]).prefill_ring_prefetch, None, "no switch: off");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prefill_gdn_tensor_core_scan_is_one_or_on_and_off_by_default() {
|
||||
assert!(!serve(&[]).prefill_gdn_tc);
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
# Prompt copy-ring prefetch (EXPERIMENTAL, off by default)
|
||||
|
||||
Switch: `LELEKA_PREFILL_RING_PREFETCH` (engine settings, `ServeSettings::prefill_ring_prefetch`). Status: implemented
|
||||
and host-tested only. No GPU run, no identity probe, no A/B yet. No speedup is claimed.
|
||||
|
||||
## Problem
|
||||
|
||||
Chunks below the expert stream's row minimum (0.2-1.5k rows on the 5090 profiles; chunks from 1536 rows already use
|
||||
the expert stream) go through the per-layer copy ring. Our profiles show that ring is bound by PCIe DMA. Per request,
|
||||
7,000-12,000 experts that are not resident (14-26 GB, 146-266 per layer, about 2.05 MB each) cross the bus at about
|
||||
45 GB/s. `ring.finish_statuses`, the wait for the copies and the kernels, takes 230-420 ms of a 530-830 ms
|
||||
`prefill.read`. Each layer's GDN/QSA/attention stage takes about 7 ms (about 330 ms per request), and PCIe is idle
|
||||
during it.
|
||||
|
||||
## Design
|
||||
|
||||
1. **History** (`leleka_cuda_model::ring_prefetch::MissHistory`). Every `Ring::new` records the layer's missed set:
|
||||
the experts that were routed and not resident. The history is per layer, as a 512-bit mask per chunk, and keeps the
|
||||
last `window` chunks (default 8). Missed sets are per layer because each layer has its own resident set, and the
|
||||
lent slots change between requests.
|
||||
2. **Prediction** (`MissHistory::predict`). Experts are ranked by how many recorded chunks missed them, then by the
|
||||
most recent chunk that missed them, then by id. Experts resident right now (`cache_expert_span`) are skipped. The
|
||||
top `K` are kept, with `K = min(top_k, ring_slots / 2)`, and `K = 0` for a ring under 32 slots: the literal 8-slot
|
||||
ring of the 512-row rung is never prefetched into.
|
||||
3. **Issue** (`OriginalMmqCopySchedule::prefetch_ring_layer`, called from `run_prompt_layer` through
|
||||
`OriginalMoePromptLayer::prefetch_ring_layer`). This runs right after layer `l`'s ring has closed, which drains both
|
||||
streams, and before layer `l`'s combine. The predicted experts of layer `l+1` are copied into stage slots
|
||||
`0..K-1` of the same row lease. Each copy is the same as `stage_one`'s: the aligned supersets or the exact pieces,
|
||||
with the same destination offsets. The copies run on the schedule's copy stream, and each slot's `copied` event is
|
||||
recorded. The engine resolves the spans from the span cache, or from a walk of the binding that changes nothing.
|
||||
Only experts whose bytes already passed the finite admission scan are resolved; others are not prefetched. The copy
|
||||
stream then becomes the `compute_drain` background stream, so the combine's and the next mixer's drains do not wait
|
||||
for these copies. This is the same mechanism the chunk expert stream uses.
|
||||
4. **Adopt** (`Ring::adopt_prefetch`, in `Ring::init` after `admit_sources`). The next ring takes the set, which
|
||||
restores the context-wide drains and flushes the deferred frees. The set is used only if it was issued for this
|
||||
layer, from the same bank (`Rc::ptr_eq`), into the same slot spans, with the same blob size, and with no chunk
|
||||
stream. Otherwise it is drained and dropped. A routed, non-resident source whose host byte ranges are equal to an
|
||||
entry's ranges is consumed from that slot (`source.slot`, `dest`, `prefetched`). The slot is marked `reserved`
|
||||
until that source's gather, and its `copied` event orders the gather. Each entry is consumed at most once
|
||||
(`match_prefetch`). Entries that were not routed, or that became resident, are wasted: the slot stays free, and a
|
||||
later stage copy into it is ordered behind the prefetch by the copy stream's FIFO order.
|
||||
5. **Ring walk.** `stage_one` skips prefetched sources and picks the next slot that is not reserved
|
||||
(`next_unreserved_slot`). Without reservations, that slot is the literal `stage_next`. `ring_stage_ahead` stops
|
||||
early when the next free slot is not gathered yet (`Ring::stage_room`, always true without reservations). The
|
||||
reserved slots therefore shrink the lookahead and never cause an overwrite. Since `K <= slots / 2`, a free slot
|
||||
always exists.
|
||||
|
||||
The same experts reach the same gather, the same kernels and the same group order. Only the time and the order of the
|
||||
H2D copies change, so the outputs must be bitwise identical.
|
||||
|
||||
**Lifetime and errors.** `end_prompt_stream` is called on every forward exit and on a failed layer. Like
|
||||
`begin_prompt_stream` and the schedule's `close`, it cancels a set that no ring took: it synchronizes the copy stream,
|
||||
drops the set and restores the drains. A failure while issuing is not returned to the layer. It is counted as
|
||||
`ring.prefetch_failed`, the copy stream is synchronized, and fewer experts are prefetched; the ring copies the rest as
|
||||
usual. A set that was adopted is covered by the ring's own drain, because `submitted` is set.
|
||||
|
||||
## Switch
|
||||
|
||||
| Variable | Values | Default |
|
||||
|---|---|---|
|
||||
| `LELEKA_PREFILL_RING_PREFETCH` | `1` / `on` (top K = 150), or a top K in `2..=512` | off |
|
||||
| `LELEKA_PREFILL_RING_PREFETCH_WINDOW` | recent chunks counted, `1..=64` | 8 |
|
||||
|
||||
The driver reads no environment variable for this feature. The policy is passed with
|
||||
`OriginalMmqCopySchedule::set_ring_prefetch` when the arena owners are attached.
|
||||
|
||||
## Counters (`LELEKA_SERVE_PROFILE=1`)
|
||||
|
||||
| Name | Call count | Value |
|
||||
|---|---|---|
|
||||
| `ring.prefetch_issued` | experts copied ahead | MB |
|
||||
| `ring.prefetch_hit` | prefetched experts consumed by the ring | MB |
|
||||
| `ring.prefetch_wasted` | prefetched experts not consumed (mispredicted, resident by then, or a set dropped) | MB |
|
||||
| `ring.prefetch_failed` | issue attempts that stopped on an error | 1 each |
|
||||
| `ring.prefetch_issue` | host span of the issue | ms |
|
||||
| `ring.copied_mb` | unchanged: copies `stage_one` still made (hits are not counted here) | MB |
|
||||
|
||||
The hit rate is `hit / issued`. The PCIe bytes saved from the ring's critical path equal `hit` MB. The extra bus
|
||||
traffic equals `wasted` MB.
|
||||
|
||||
## What the GPU validation must show
|
||||
|
||||
1. **Identity.** Run with `LELEKA_TRACE_PREFILL_R=1`, once with the switch off and once with it on, on the same
|
||||
prompts. Use 0.2-1.5k-row chunks (the 2048-row rung, 384 slots) and also 512-row rung chunks (8 slots, where the
|
||||
prefetch is a no-op). Every chunk's R hash must be equal. Also check the first-token logprob rows / greedy output.
|
||||
2. **Counters.** `ring.prefetch_hit / ring.prefetch_issued` should be near the offline 55-57 % at K = 150-200.
|
||||
`ring.copied_mb` should fall by the hit MB.
|
||||
3. **Latency.** Run a paired A/B of `prefill.read` and `ring.finish_statuses`, by tail class (chunk rows: <512,
|
||||
512-1535, >=1536 as the control, where the prefetch must stay inactive). Measure on the same workload and record the
|
||||
run metadata the charter requires. Watch `ring.init_sync`: it now waits for prefetch copies that are still in
|
||||
flight. Also watch the mixer stages: while the background stream is set, their all-zero uploads become memsets,
|
||||
exactly as under the chunk stream.
|
||||
4. **Sweeps.** K in {100, 150, 200} and window in {4, 8, 16}.
|
||||
|
||||
## Risks and open points
|
||||
|
||||
- The prefetch competes with the combine's and the next mixer's own H2D uploads on the copy engines. A large K that
|
||||
outlasts the mixer delays the ring's mandatory copies, which queue on the same stream behind the prefetch.
|
||||
- `ring.init_sync` (a context synchronize) waits for every prefetch copy, wasted ones included.
|
||||
- Experts that were routed only once so far (and never finite-scanned) are not prefetched.
|
||||
- Layer 0 of a chunk is never prefetched, because the prefetch is issued from the previous layer of the same chunk and
|
||||
row lease.
|
||||
- Not tested on a GPU: the event ordering, the background-stream switch and the reserved-slot walk are covered only by
|
||||
review and by the host model in `crates/cuda-model/src/ring_prefetch/tests.rs`.
|
||||
Reference in New Issue
Block a user