perf(prefill): ring expert copies as page-aligned supersets (LELEKA_PREFILL_ALIGNED_COPY, default on)

The CUPTI ledger shows the ring's three 0.5-0.9 MB expert pieces run at 36 GB/s while the Original's single blobs run at 49.5; pieces start at
expert*piece_bytes (arbitrary offsets) and the roofline probes measure 40.3 GB/s unaligned against 47.7 aligned. Each piece is now copied as the
4 KiB-aligned superset (clamped to the registered tensor) into page offsets of the ring slot (slot +24 KiB), and the gather kernel reads the three
pieces at their lead offsets; same bytes reach the MMQ slot. Not yet measured: job 9002 (hash gate + ABAB).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-18 02:54:57 +02:00
co-authored by Claude Sonnet 5.5
parent aef32a0795
commit 81137d53fc
5 changed files with 91 additions and 5 deletions
@@ -158,6 +158,15 @@ impl Context<'_> {
}
}
}
const PAGE: usize = 4096;
/// Extra bytes a ring slot needs to hold three page-aligned supersets next to each other: the pieces start up to one page
/// early and end up to one page late.
pub(crate) const ALIGNED_COPY_SLACK: usize = 3 * 2 * PAGE;
/// `LELEKA_PREFILL_ALIGNED_COPY=0` turns the page-aligned expert copies off (the A/B switch; default on).
pub(crate) fn aligned_copy_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_ALIGNED_COPY").map_or(true, |v| v != "0"))
}
impl<'ctx> MappedExpertBank<'ctx> {
pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool {
!self.closed && std::ptr::eq(self.context, context)
@@ -191,6 +200,37 @@ impl<'ctx> MappedExpertBank<'ctx> {
.get(span.offset()..end)
.ok_or(Error::InvalidSize)
}
/// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it
/// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at
/// `expert * piece_bytes`, i.e. at arbitrary offsets; job 907/9051 and the CUPTI ledger: 36-40 GB/s unaligned, 47-50 aligned).
/// The superset is clamped to the tensor (a registered range), so it never reads outside the bank.
pub(crate) fn cache_source_aligned(&self, span: &ResidentExpertBankSpan) -> Result<(&[u8], usize)> {
let exact = self.cache_source(span)?;
let layer = match span.role() {
TensorRole::Layer { layer, .. } => layer,
_ => return Err(Error::InvalidSize),
};
let role = match span.role() {
TensorRole::Layer { role, .. } => role,
_ => return Err(Error::InvalidSize),
};
let n = usize::from(layer) * 3
+ match role {
LayerRole::FfnGateExperts => 0,
LayerRole::FfnUpExperts => 1,
LayerRole::FfnDownExperts => 2,
_ => return Err(Error::InvalidSize),
};
let member = self.banks.get(n).ok_or(Error::InvalidSize)?.member.bytes();
let base = member.as_ptr() as usize;
let (start, end) = (exact.as_ptr() as usize, exact.as_ptr() as usize + exact.len());
let a = (start & !(PAGE - 1)).max(base);
let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len());
if a > start || b < end {
return Err(Error::InvalidSize);
}
Ok((&member[a - base..b - base], start - a))
}
pub(crate) fn retained_span_handle(
&self,
span: &ResidentExpertBankSpan,
+35 -3
View File
@@ -425,6 +425,8 @@ struct Source<'read> {
job: Option<usize>,
/// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`)
entry: Option<usize>,
/// 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]>,
}
/// Private owner: no external pointer/ready event can manufacture a stage.
/// The actual source Rc prevents unregister/free during H2D or gathered use.
@@ -590,6 +592,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
slot: None,
job: None,
entry: None,
dest: None,
});
}
// With an active chunk stream for this layer, every non-resident expert is the stream's entry.
@@ -756,6 +759,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
let api = self.schedule.api.as_ref().ok_or(Error::ContextPoisoned)?;
let gu = formats[0].layout(1)?.raw_weight;
let down = formats[2].layout(1)?.raw_weight;
let mut new_dest: Option<[usize; 3]> = None;
if skip_expert_dma() {
// EXPERIMENTAL diagnostic only (wrong outputs): no expert bytes move; the slot keeps whatever blob it
// held, so the ring's compute runs alone. Measures the grouped MMQ cost without the PCIe stream.
@@ -780,6 +784,30 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
host_events[j % ring].record(copy)?;
host.issued(j);
} else {
// page-aligned supersets, side by side in the slot at page offsets (registered banks; falls back when they do not fit)
let aligned = if !bank.pageable() && crate::mapped_expert_bank::aligned_copy_enabled() {
let mut parts: [(&[u8], usize, usize); 3] = [(&[], 0, 0); 3];
let mut off = 0usize;
for (i, part) in parts.iter_mut().enumerate() {
let (superset, lead) = bank.cache_source_aligned(&source.spans[i])?;
*part = (superset, lead, off);
off += superset.len().div_ceil(4096) * 4096;
}
(off <= slot.bytes).then_some(parts)
} else {
None
};
if let Some(parts) = aligned {
self.submitted = true;
self.drained = false;
copy.with_enqueue(|stream| {
for (superset, _, off) in parts {
api.copy_registered(slot.span.checked_subspan(slot.bytes, off, superset.len())?, superset, stream)?;
}
Ok(())
})?;
new_dest = Some([parts[0].2 + parts[0].1, parts[1].2 + parts[1].1, parts[2].2 + parts[2].1]);
} else {
let sources = [
bank.cache_source(&source.spans[0])?,
bank.cache_source(&source.spans[1])?,
@@ -808,6 +836,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
Ok(())
})?;
}
}
events
.copied
.as_mut()
@@ -816,6 +845,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
slot.live = true;
slot.gathered = false;
self.sources[index].slot = Some(sl);
self.sources[index].dest = new_dest;
self.stage_next = next;
Ok(())
}
@@ -835,6 +865,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
let down = formats[2].layout(1)?.raw_weight;
let sl = source.slot;
let entry = source.entry;
let dest = source.dest;
let raw = if let Some(raw) = source.resident {
raw
} else if let Some(k) = entry {
@@ -868,10 +899,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
.as_ref()
.ok_or(Error::ContextPoisoned)?,
)?;
let at = dest.unwrap_or([0, gu, gu * 2]);
[
slot.span.checked_subspan(slot.bytes, 0, gu)?,
slot.span.checked_subspan(slot.bytes, gu, gu)?,
slot.span.checked_subspan(slot.bytes, gu * 2, down)?,
slot.span.checked_subspan(slot.bytes, at[0], gu)?,
slot.span.checked_subspan(slot.bytes, at[1], gu)?,
slot.span.checked_subspan(slot.bytes, at[2], down)?,
]
};
// Destination checks are closed to actual group-bank ranges. All source
@@ -242,7 +242,9 @@ impl PrefillLayoutOptions {
}
let ring_slots = self.original_ring_slots()?;
// Names intentionally share one role; the index is the span occurrence.
for _ in 0..ring_slots { a.take("stage_dev", self.max_expert_blob, 1)?; }
// room for three page-aligned supersets (claude/ledger: LELEKA_PREFILL_ALIGNED_COPY, default on)
let slot_bytes = if crate::mapped_expert_bank::aligned_copy_enabled() { add(self.max_expert_blob, crate::mapped_expert_bank::ALIGNED_COPY_SLACK)? } else { self.max_expert_blob };
for _ in 0..ring_slots { a.take("stage_dev", slot_bytes, 1)?; }
a.rows("ple_emb", t, N, 4)?;
a.take("ple_norm", D, 4)?;
let mut owned = Alloc::new(PrefillPhase::Common);
@@ -0,0 +1,12 @@
# claude/ledger: page-aligned expert copies (LELEKA_PREFILL_ALIGNED_COPY, default on in rt-aligned) against the literal unaligned pieces, same binary.
# 1) bit gate: FNV-1a hash of the final residual R of every chunk + greedy ids, both arms (must be identical);
# 2) CUPTI trace of the new arm (H2D GB/s of the ring copies); 3) timing ABAB, untraced, second pass of each process.
source ~/work/ledger/ledger-common.sh
mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; }
export BIN=$LD/bin/rt-aligned
header
port_long hash-aligned-1 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1 LELEKA_PREFILL_ALIGNED_COPY=1
port_long hash-aligned-0 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1 LELEKA_PREFILL_ALIGNED_COPY=0
port_long port-16k-aligned 16000 2 PREFILL-PROFILE 2 9 LELEKA_PREFILL_ALIGNED_COPY=1
for arm in 0 1 0 1; do port_long ab-aligned-$arm 16000 2 PREFILL-PROFILE 0 9 LELEKA_PREFILL_ALIGNED_COPY=$arm; done
date -u +%FT%TZ
+1 -1
View File
@@ -51,7 +51,7 @@ port_long() {
LELEKA_ORIGINAL_SERVE_KV_RESIDENT=20480 "$@" \
$BIN --ignored --exact --test-threads=1 --nocapture $T_LONG 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do
case "$line" in *"$re"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac
case "$line" in *PREFILL-PROFILE*|*long-smoke*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac
case "$line" in *PREFILL-PROFILE*|*PREFILL-R*|*long-smoke*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac
done
echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ
}