perf(prefill): expert stream issuer thread keeping a bounded copy queue (the Original's D-5)

The host-to-device copy engine is a FIFO: with hundreds of expert copies queued ahead every small
upload or status readback of the compute path waited for the whole queue. A helper thread now keeps
LELEKA_PREFILL_DEPTH (16) entries outstanding on the copy stream (event-query paced) while the
compute thread only waits for an entry's enqueue before ordering its stream after it. The inline
mode stays (LELEKA_PREFILL_ISSUER=inline). Adds the copy-engine contention probe.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Pavlo Ratushnyi
2026-10-17 17:45:59 +02:00
co-authored by Claude Sonnet 5.5
parent ff93858ca5
commit 23e7b20dc4
4 changed files with 370 additions and 83 deletions
@@ -2,20 +2,27 @@
//! layer of the chunk that the arena cache does not hold is copied, layer by layer in id order, into the copy ring
//! (entry k lands in slot k % ring), whether or not the routing uses it.
//!
//! The copies are enqueued on the calling thread (the copy stream waits device-side for a slot's `used` event, so
//! queueing never blocks the host). While the stream is active the compute path's drains are stream-scoped
//! (`compute_drain`: they wait for the legacy default stream and the compute streams, never for the copy stream),
//! and every such drain first tops the copy queue up by `LELEKA_PREFILL_TOPUP` (48) entries (`prefetch_point`,
//! called by `Api::synchronize`), so the next layers' experts arrive under the mixers' kernels. The consumer (the
//! per-layer copy ring) waits for entry k's `copied` event on the compute stream before gathering it and records
//! `used` after; entries a layer does not route are released in order. Same bytes into the same kind of slot,
//! gathered by the same kernels: the layer's products do not change.
//! Two issue modes (`LELEKA_PREFILL_ISSUER`, default `thread`):
//! * `thread` (the Original's D-5 issuer): a helper thread keeps at most `LELEKA_PREFILL_DEPTH` (16) entries
//! outstanding on the copy stream, i.e. the host-to-device copy engine stays busy while any other copy of the
//! compute path (uploads, status readbacks) waits behind at most that many entries (the engine is a FIFO: a
//! deep queue made every small transfer wait for it). The compute thread only waits for an entry's issue (it
//! spins until the helper has recorded the entry's `copied` event) before ordering its stream after it.
//! * `inline`: the calling thread queues entries at every scoped drain (`prefetch_point`, `LELEKA_PREFILL_TOPUP`
//! entries each) and at the layer ends.
//! While the stream is active the compute path's drains are stream-scoped (`compute_drain`: they wait for the
//! legacy default stream and the compute streams, never for the copy stream). The consumer (the per-layer copy
//! ring) waits for entry k's `copied` event on the compute stream before gathering it and records `used` after;
//! entries a layer does not route are released in order. The copy of entry k waits (device side) for the `used`
//! event of entry k - ring, which the compute thread has recorded before it publishes `consumed`. Same bytes into
//! the same kind of slot, gathered by the same kernels: the layer's products do not change.
//! `LELEKA_PREFILL_COPY_STATS=1` (with LELEKA_BRINGUP_TRACE): per-copy event timing, one PREFILL-COPY line per chunk.
use crate::ffi::BufferHandle;
use crate::ffi::original_stager::Api;
use crate::{Error, Result};
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
#[derive(Clone, Copy)]
@@ -29,9 +36,9 @@ pub(super) struct Entry {
/// `copied` event (created with timestamps): their gap is the entry's pure DMA time.
struct Stats {
starts: Vec<usize>,
sampled_ms: Cell<f64>,
sampled_bytes: Cell<u64>,
sampled: Cell<u64>,
sampled_ns: AtomicU64,
sampled_bytes: AtomicU64,
sampled: AtomicU64,
}
struct Core {
api: Api,
@@ -42,19 +49,23 @@ struct Core {
/// first entry of every layer (49 bounds)
layer_start: [usize; 49],
copy: usize,
issued: Cell<usize>,
consumed: Cell<usize>,
next_layer: Cell<u8>,
failed: Cell<bool>,
issued: AtomicUsize,
consumed: AtomicUsize,
next_layer: AtomicUsize,
failed: AtomicBool,
stop: AtomicBool,
topup: usize,
/// LELEKA_PREFILL_AHEAD: most entries queued beyond the consumed ones (default: the whole ring)
ahead: usize,
calls: Cell<u64>,
bytes: Cell<u64>,
issue_time: Cell<Duration>,
/// issuer thread mode: entries outstanding on the copy stream (0 = inline mode)
depth: usize,
context: usize,
calls: AtomicU64,
bytes: AtomicU64,
issue_ns: AtomicU64,
stats: Option<Stats>,
/// LELEKA_PREFILL_STREAM_JITTER=seed (race hunt): pseudo-random host delays between the copies' enqueues
jitter: Cell<u64>,
jitter: AtomicU64,
}
impl Core {
fn ring(&self) -> usize {
@@ -63,23 +74,47 @@ impl Core {
fn layer_end(&self, layer: u8) -> usize {
self.layer_start[usize::from(layer) + 1]
}
/// Enqueue entries until `limit` (never past the ring: entry k - ring must be consumed first).
fn issue_until(&self, limit: usize) -> Result<()> {
if self.failed.get() {
fn limit(&self, wanted: usize) -> usize {
wanted
.min(self.entries.len())
.min(self.consumed.load(Ordering::Acquire) + self.ring().min(self.ahead))
}
/// Inline mode: enqueue entries until `wanted` (never past the ring: entry k - ring must be consumed first).
fn issue_until(&self, wanted: usize) -> Result<()> {
if self.failed.load(Ordering::Acquire) {
return Err(Error::ContextPoisoned);
}
let limit = limit.min(self.entries.len()).min(self.consumed.get() + self.ring().min(self.ahead));
while self.issued.get() < limit {
let k = self.issued.get();
let limit = self.limit(wanted);
while self.issued.load(Ordering::Relaxed) < limit {
let k = self.issued.load(Ordering::Relaxed);
let result = self.issue(k);
if result.is_err() {
self.failed.set(true);
self.failed.store(true, Ordering::Release);
return result;
}
self.issued.set(k + 1);
self.issued.store(k + 1, Ordering::Release);
}
Ok(())
}
/// Make sure entry `k` has been enqueued (its `copied` event recorded) before the compute stream waits for it.
fn need(&self, k: usize) -> Result<()> {
if self.depth == 0 {
return self.issue_until(k + 1);
}
let started = Instant::now();
while self.issued.load(Ordering::Acquire) <= k {
if self.failed.load(Ordering::Acquire) || started.elapsed() > Duration::from_secs(60) {
self.failed.store(true, Ordering::Release);
return Err(Error::ContextPoisoned);
}
std::thread::yield_now();
}
Ok(())
}
/// Inline mode only: queue ahead up to `wanted`.
fn want(&self, wanted: usize) -> Result<()> {
if self.depth == 0 { self.issue_until(wanted) } else { Ok(()) }
}
fn entry_bytes(&self, k: usize) -> u64 {
self.entries[k].pieces.iter().map(|p| p.1 as u64).sum()
}
@@ -93,19 +128,19 @@ impl Core {
self.api.event_query(self.copied[slot]).unwrap_or(false)
};
if done && let Ok(ms) = self.api.event_elapsed_ms(stats.starts[slot], self.copied[slot]) {
stats.sampled_ms.set(stats.sampled_ms.get() + f64::from(ms));
stats.sampled_bytes.set(stats.sampled_bytes.get() + self.entry_bytes(k));
stats.sampled.set(stats.sampled.get() + 1);
stats.sampled_ns.fetch_add((f64::from(ms) * 1e6) as u64, Ordering::Relaxed);
stats.sampled_bytes.fetch_add(self.entry_bytes(k), Ordering::Relaxed);
stats.sampled.fetch_add(1, Ordering::Relaxed);
}
}
fn issue(&self, k: usize) -> Result<()> {
let jitter = self.jitter.get();
let jitter = self.jitter.load(Ordering::Relaxed);
if jitter != 0 {
let mut x = jitter;
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
self.jitter.set(x);
self.jitter.store(x, Ordering::Relaxed);
if x % 5 == 0 {
std::thread::sleep(Duration::from_micros(x >> 8 & 0x3ff));
}
@@ -129,39 +164,72 @@ impl Core {
return Err(Error::InvalidSize);
}
self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?;
self.calls.set(self.calls.get() + 1);
self.calls.fetch_add(1, Ordering::Relaxed);
offset = end;
}
self.bytes.set(self.bytes.get() + offset as u64);
self.bytes.fetch_add(offset as u64, Ordering::Relaxed);
let recorded = self.api.record(self.copied[slot], self.copy);
self.issue_time.set(self.issue_time.get() + started.elapsed());
self.issue_ns.fetch_add(started.elapsed().as_nanos() as u64, Ordering::Relaxed);
recorded
}
/// The issuer thread: keep `depth` entries outstanding, never past the ring.
fn issuer(&self) {
if self.api.worker_enter(self.context).is_err() {
self.failed.store(true, Ordering::Release);
return;
}
let mut idle = 0u32;
while !self.stop.load(Ordering::Acquire) {
let k = self.issued.load(Ordering::Relaxed);
if k >= self.entries.len() {
break;
}
let ready = k < self.limit(k + 1)
&& (k < self.depth || self.api.event_query(self.copied[(k - self.depth) % self.ring()]).unwrap_or(false));
if !ready {
idle += 1;
if idle < 200 {
std::hint::spin_loop();
} else {
std::thread::sleep(Duration::from_micros(20));
}
continue;
}
idle = 0;
if self.issue(k).is_err() {
self.failed.store(true, Ordering::Release);
break;
}
self.issued.store(k + 1, Ordering::Release);
}
let _ = self.api.worker_leave(self.context);
}
}
thread_local! {
/// The active chunk stream of this thread, for `prefetch_point` (the producers have no schedule handle).
static ACTIVE: RefCell<Option<Rc<Core>>> = const { RefCell::new(None) };
/// The active inline-mode chunk stream of this thread, for `prefetch_point` (the producers have no handle).
static ACTIVE: RefCell<Option<Arc<Core>>> = const { RefCell::new(None) };
}
/// Called by `Api::synchronize` while a chunk stream is active, right before a compute drain waits: queue the
/// next `topup` entries (never past the ring: entry k - ring must be consumed first). The caller's Context is
/// current. No-op without an active stream.
/// Called by `Api::synchronize` while a chunk stream is active, right before a compute drain waits: inline mode
/// queues the next `topup` entries (never past the ring). The caller's Context is current. No-op otherwise.
pub(crate) fn prefetch_point() {
ACTIVE.with(|active| {
let Some(core) = active.borrow().clone() else { return };
let _ = core.issue_until(core.issued.get() + core.topup);
let _ = core.issue_until(core.issued.load(Ordering::Relaxed) + core.topup);
});
}
/// One chunk's stream and the consumer's cursor (the caller's thread only).
pub(super) struct ChunkStream {
core: Rc<Core>,
core: Arc<Core>,
thread: Option<std::thread::JoinHandle<()>>,
}
impl ChunkStream {
/// `entries` in stream order (layers ascending, experts ascending within a layer, from `first` to 48);
/// `targets` the ring slots; `copied`/`used` one raw event per slot (created by the caller on this Context);
/// `starts` the per-slot timing events of LELEKA_PREFILL_COPY_STATS (empty without it).
/// `starts` the per-slot timing events of LELEKA_PREFILL_COPY_STATS (empty without it); `context` the raw
/// context token for the issuer thread.
#[allow(clippy::too_many_arguments)]
pub(super) fn start(
api: Api,
@@ -173,6 +241,7 @@ impl ChunkStream {
used: Vec<usize>,
starts: Vec<usize>,
topup: usize,
context: usize,
) -> Result<Self> {
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48
|| !(starts.is_empty() || starts.len() == targets.len())
@@ -192,7 +261,14 @@ impl ChunkStream {
}
*start = k;
}
let core = Rc::new(Core {
let env_number = |name: &str| std::env::var(name).ok().and_then(|v| v.trim().parse::<usize>().ok());
let threaded = std::env::var("LELEKA_PREFILL_ISSUER").map_or(true, |v| v != "inline");
let depth = if threaded && targets.len() > 1 {
env_number("LELEKA_PREFILL_DEPTH").unwrap_or(16).clamp(1, targets.len() - 1)
} else {
0
};
let core = Arc::new(Core {
api,
entries,
targets,
@@ -200,28 +276,42 @@ impl ChunkStream {
used,
layer_start,
copy,
issued: Cell::new(layer_start[usize::from(first)]),
consumed: Cell::new(layer_start[usize::from(first)]),
next_layer: Cell::new(first),
failed: Cell::new(false),
issued: AtomicUsize::new(layer_start[usize::from(first)]),
consumed: AtomicUsize::new(layer_start[usize::from(first)]),
next_layer: AtomicUsize::new(usize::from(first)),
failed: AtomicBool::new(false),
stop: AtomicBool::new(false),
topup: topup.max(1),
ahead: std::env::var("LELEKA_PREFILL_AHEAD").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(usize::MAX).max(1),
calls: Cell::new(0),
bytes: Cell::new(0),
issue_time: Cell::new(Duration::ZERO),
jitter: Cell::new(std::env::var("LELEKA_PREFILL_STREAM_JITTER").ok().and_then(|v| v.trim().parse::<u64>().ok()).unwrap_or(0)),
ahead: env_number("LELEKA_PREFILL_AHEAD").unwrap_or(usize::MAX).max(1),
depth,
context,
calls: AtomicU64::new(0),
bytes: AtomicU64::new(0),
issue_ns: AtomicU64::new(0),
stats: (!starts.is_empty()).then(|| Stats {
starts,
sampled_ms: Cell::new(0.0),
sampled_bytes: Cell::new(0),
sampled: Cell::new(0),
sampled_ns: AtomicU64::new(0),
sampled_bytes: AtomicU64::new(0),
sampled: AtomicU64::new(0),
}),
jitter: AtomicU64::new(env_number("LELEKA_PREFILL_STREAM_JITTER").unwrap_or(0) as u64),
});
ACTIVE.with(|active| *active.borrow_mut() = Some(Rc::clone(&core)));
Ok(Self { core })
let thread = if depth > 0 {
let shared = Arc::clone(&core);
Some(
std::thread::Builder::new()
.name("leleka-expert-issuer".into())
.spawn(move || shared.issuer())
.map_err(|_| Error::HostAllocation)?,
)
} else {
ACTIVE.with(|active| *active.borrow_mut() = Some(Arc::clone(&core)));
None
};
Ok(Self { core, thread })
}
pub(super) fn next_layer_is(&self, layer: u8) -> bool {
self.core.next_layer.get() == layer
self.core.next_layer.load(Ordering::Relaxed) == usize::from(layer)
}
/// Whether entry `k` copies exactly these gate/up/down byte ranges.
pub(super) fn entry_matches(&self, k: usize, parts: [&[u8]; 3]) -> bool {
@@ -237,14 +327,15 @@ impl ChunkStream {
/// Release (record `used`, consume) every entry before `upto` in order on `compute`.
fn release_until(&mut self, upto: usize, compute: usize) -> Result<()> {
let core = &self.core;
while core.consumed.get() < upto {
let k = core.consumed.get();
while core.consumed.load(Ordering::Relaxed) < upto {
let k = core.consumed.load(Ordering::Relaxed);
// its copy is queued before its release is ordered after it
core.issue_until(k + 1)?;
core.need(k)?;
let slot = k % core.ring();
core.api.wait(compute, core.copied[slot])?;
core.api.record(core.used[slot], compute)?;
core.consumed.set(k + 1);
// `used` is recorded before the entry counts as consumed: the copy of k + ring may then wait for it
core.consumed.store(k + 1, Ordering::Release);
}
Ok(())
}
@@ -252,27 +343,28 @@ impl ChunkStream {
pub(super) fn stage_ahead(&mut self, k: usize) -> Result<()> {
let layer = self.core.entries.get(k).ok_or(Error::InvalidProjectionShape)?.layer;
let end = self.core.layer_end(layer);
self.core.issue_until(end)
self.core.want(end)
}
/// Make entry `k` ready on `compute`: its slot and the slot's byte capacity.
pub(super) fn acquire(&mut self, k: usize, compute: usize) -> Result<(BufferHandle, usize)> {
self.release_until(k, compute)?;
if self.core.consumed.get() != k {
if self.core.consumed.load(Ordering::Relaxed) != k {
return Err(Error::InvalidProjectionShape);
}
self.stage_ahead(k)?;
self.core.need(k)?;
let slot = k % self.core.ring();
self.core.api.wait(compute, self.core.copied[slot])?;
Ok(self.core.targets[slot])
}
/// The gather of entry `k` (the cursor) is enqueued on `compute`: mark its slot used.
pub(super) fn consumed(&mut self, k: usize, compute: usize) -> Result<()> {
if self.core.consumed.get() != k || self.core.issued.get() <= k {
if self.core.consumed.load(Ordering::Relaxed) != k || self.core.issued.load(Ordering::Acquire) <= k {
return Err(Error::InvalidProjectionShape);
}
let slot = k % self.core.ring();
self.core.api.record(self.core.used[slot], compute)?;
self.core.consumed.set(k + 1);
self.core.consumed.store(k + 1, Ordering::Release);
Ok(())
}
/// The layer's last routed expert was gathered: release its remaining entries and move to the next layer.
@@ -282,38 +374,45 @@ impl ChunkStream {
}
let end = self.core.layer_end(layer);
self.release_until(end, compute)?;
self.core.next_layer.set(layer + 1);
// the next layer's first entries go into the freed slots now (device-side waits on `used`)
self.core.issue_until(self.core.issued.get() + self.core.topup)?;
self.core.next_layer.store(usize::from(layer) + 1, Ordering::Relaxed);
// inline mode: the next layer's first entries go into the freed slots now (device-side waits on `used`)
self.core.want(self.core.issued.load(Ordering::Relaxed) + self.core.topup)?;
Ok(())
}
/// Deactivate: no producer prefetches into these slots after this. The caller drains the copy stream.
/// Deactivate: no producer prefetches into these slots after this; the issuer thread is stopped and joined.
/// The caller drains the copy stream.
pub(super) fn stop(&mut self) -> Result<()> {
self.core.stop.store(true, Ordering::Release);
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
ACTIVE.with(|active| {
let mut active = active.borrow_mut();
if active.as_ref().is_some_and(|a| Rc::ptr_eq(a, &self.core)) {
if active.as_ref().is_some_and(|a| Arc::ptr_eq(a, &self.core)) {
*active = None;
}
});
if self.core.failed.get() { Err(Error::ContextPoisoned) } else { Ok(()) }
if self.core.failed.load(Ordering::Acquire) { Err(Error::ContextPoisoned) } else { Ok(()) }
}
/// After the copy stream drained: one PREFILL-COPY line (entries, calls, bytes, DMA GB/s of the sampled entries).
pub(super) fn report(&self, stream_ms: f64) {
let core = &self.core;
let issued = core.issued.get();
let issued = core.issued.load(Ordering::Acquire);
for k in issued.saturating_sub(core.ring())..issued {
core.harvest(k, true);
}
let (gbps, n) = core.stats.as_ref().map_or((0.0, 0), |s| {
let rate = if s.sampled_ms.get() > 0.0 { s.sampled_bytes.get() as f64 / (s.sampled_ms.get() * 1e6) } else { 0.0 };
(rate, s.sampled.get())
let ns = s.sampled_ns.load(Ordering::Relaxed);
let rate = if ns > 0 { s.sampled_bytes.load(Ordering::Relaxed) as f64 / ns as f64 } else { 0.0 };
(rate, s.sampled.load(Ordering::Relaxed))
});
let calls = core.calls.get();
let bytes = core.bytes.get();
let calls = core.calls.load(Ordering::Relaxed);
let bytes = core.bytes.load(Ordering::Relaxed);
crate::bringup_trace!(
"PREFILL-COPY entries={issued} calls={calls} bytes={bytes} avg_call={} dma_gbps={gbps:.1} sampled={n} issue_ms={:.1} stream_ms={stream_ms:.1} avg_gbps_over_stream={:.1} blocking: {}",
"PREFILL-COPY mode={} entries={issued} calls={calls} bytes={bytes} avg_call={} dma_gbps={gbps:.1} sampled={n} issue_ms={:.1} stream_ms={stream_ms:.1} avg_gbps_over_stream={:.1} blocking: {}",
if core.depth > 0 { "thread" } else { "inline" },
bytes.checked_div(calls).unwrap_or(0),
core.issue_time.get().as_secs_f64() * 1e3,
core.issue_ns.load(Ordering::Relaxed) as f64 / 1e6,
if stream_ms > 0.0 { bytes as f64 / (stream_ms * 1e6) } else { 0.0 },
crate::compute_drain::take_blocking_report()
);
+2 -1
View File
@@ -288,7 +288,8 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
let copy = self.copy.as_mut().ok_or(Error::ContextPoisoned)?.with_enqueue(Ok)?;
// the copies must follow everything the compute path queued so far on its own streams
self.context.synchronize()?;
match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup) {
let context_token = StagerApi::context_token(self.context.handle.ok_or(Error::ContextPoisoned)?);
match ChunkStream::start(api, copy, first, entries, targets, copied, used, starts, topup, context_token) {
Ok(stream) => {
// from here the compute path's drains stop waiting for the copy stream (end_prompt_stream restores them)
crate::compute_drain::set_background(copy);
+95
View File
@@ -0,0 +1,95 @@
// Model-free probe: latency of small synchronous host/device copies and kernels while an "expert stream" keeps the
// host-to-device copy engine busy (claude/prefill-overlap). Build: nvcc -O2 -arch=sm_120 h2d_probe.cu -o h2d_probe
#include <cuda_runtime.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <thread>
#include <atomic>
#include <algorithm>
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0)
using Clock = std::chrono::steady_clock;
static double ms(Clock::time_point a) { return std::chrono::duration<double, std::milli>(Clock::now() - a).count(); }
__global__ void tiny(float* p, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p[i] += 1.0f; }
int main(int argc, char** argv) {
setvbuf(stdout, NULL, _IOLBF, 0);
int only_depth = argc > 1 ? atoi(argv[1]) : -1;
const size_t ENTRY = 2046000; // one expert (gate+up+down), bytes
const int PIECES = 3, RING = 384, NENT = 4096;
const size_t SMALL = 327680; // the routed slot table
uint8_t* host;
uint8_t* ring; CK(cudaMalloc((void**)&ring, ENTRY * RING));
uint8_t* dev_small; CK(cudaMalloc((void**)&dev_small, 64 << 20));
float* dev_f; CK(cudaMalloc((void**)&dev_f, 1 << 20));
std::vector<uint8_t> pageable(SMALL, 7);
uint8_t* pinned_small; CK(cudaHostAlloc((void**)&pinned_small, SMALL, cudaHostAllocDefault));
cudaStream_t copy, hi, other;
CK(cudaStreamCreateWithFlags(&copy, cudaStreamNonBlocking));
int lo, hip; CK(cudaDeviceGetStreamPriorityRange(&lo, &hip));
CK(cudaStreamCreateWithPriority(&hi, cudaStreamNonBlocking, hip));
CK(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking));
CK(cudaStreamSynchronize(0));
size_t hostN = 1ull << 30;
CK(cudaHostAlloc((void**)&host, hostN * 4, cudaHostAllocDefault)); // 4 GiB
memset(host, 1, hostN * 4);
const size_t entries_in_host = (hostN * 4) / ENTRY;
auto bg = [&](int depth, int pieces, std::atomic<bool>* stop, std::atomic<long>* bytes) {
std::vector<cudaEvent_t> ev(depth + 1);
for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming));
long k = 0;
while (!stop->load()) {
int slot = (int)(k % RING);
size_t src = (size_t)(k % entries_in_host) * ENTRY;
size_t piece = ENTRY / pieces;
for (int p = 0; p < pieces; ++p)
CK(cudaMemcpyAsync(ring + (size_t)slot * ENTRY + p * piece, host + src + p * piece, piece, cudaMemcpyHostToDevice, copy));
CK(cudaEventRecord(ev[k % (depth + 1)], copy));
++k; bytes->fetch_add(ENTRY);
if (k > depth) CK(cudaEventSynchronize(ev[(k - depth - 1) % (depth + 1)])); // keep `depth` entries outstanding
}
CK(cudaStreamSynchronize(copy));
for (auto& e : ev) cudaEventDestroy(e);
};
struct Probe { const char* name; };
auto measure = [&](const char* name, int reps, auto&& f) {
std::vector<double> t;
for (int i = 0; i < reps; ++i) { auto a = Clock::now(); f(); t.push_back(ms(a)); std::this_thread::sleep_for(std::chrono::microseconds(300)); }
std::sort(t.begin(), t.end());
double mean = 0; for (double x : t) mean += x; mean /= t.size();
printf(" %-34s mean %7.3f ms p50 %7.3f p90 %7.3f max %7.3f\n", name, mean, t[t.size() / 2], t[t.size() * 9 / 10], t.back());
};
int depths[] = {0, 2, 8, 32, 128, 384};
int pieces_list[] = {3, 1};
for (int pieces : pieces_list) {
for (int depth : depths) {
if (only_depth >= 0 && depth != only_depth) continue;
printf("expert stream: depth=%d entries outstanding, %d copies per entry (%zu B each)\n", depth, pieces, ENTRY / pieces);
std::atomic<bool> stop{false}; std::atomic<long> bytes{0};
std::thread th;
auto t0 = Clock::now();
if (depth > 0) th = std::thread([&] { bg(depth, pieces, &stop, &bytes); });
std::this_thread::sleep_for(std::chrono::milliseconds(150));
long b0 = bytes.load(); auto tm = Clock::now();
measure("cudaMemcpy H2D 327KB pageable", 60, [&] { CK(cudaMemcpy(dev_small, pageable.data(), SMALL, cudaMemcpyHostToDevice)); });
measure("cudaMemcpy H2D 6MB pageable", 20, [&] { std::vector<uint8_t> big(6 << 20, 1); CK(cudaMemcpy(dev_small, big.data(), big.size(), cudaMemcpyHostToDevice)); });
measure("cudaMemcpyAsync pinned 327KB hi-prio", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, hi)); CK(cudaStreamSynchronize(hi)); });
measure("cudaMemcpyAsync pinned 327KB other", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, other)); CK(cudaStreamSynchronize(other)); });
measure("cudaMemcpy D2H 4KB", 60, [&] { uint8_t h[4096]; CK(cudaMemcpy(h, dev_small, 4096, cudaMemcpyDeviceToHost)); });
measure("cudaMemset 4KB (legacy)", 60, [&] { CK(cudaMemset(dev_small, 0, 4096)); });
measure("cudaMemcpy D2D 100MB (legacy)", 20, [&] { CK(cudaMemcpy(dev_small + (32 << 20), dev_small, 16 << 20, cudaMemcpyDeviceToDevice)); });
measure("tiny kernel + sync (other)", 60, [&] { tiny<<<64, 256, 0, other>>>(dev_f, 16384); CK(cudaStreamSynchronize(other)); });
measure("tiny kernel + sync (legacy)", 60, [&] { tiny<<<64, 256, 0, 0>>>(dev_f, 16384); CK(cudaStreamSynchronize(0)); });
long b1 = bytes.load(); double dt = ms(tm);
stop = true; if (th.joinable()) th.join();
if (depth > 0) printf(" expert DMA while probing: %.1f GB/s\n", (b1 - b0) / (dt * 1e6));
(void)t0;
}
}
return 0;
}
+92
View File
@@ -0,0 +1,92 @@
// Model-free probe: latency of small synchronous host/device copies and kernels while an "expert stream" keeps the
// host-to-device copy engine busy (claude/prefill-overlap). Build: nvcc -O2 -arch=sm_120 h2d_probe.cu -o h2d_probe
#include <cuda_runtime.h>
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <vector>
#include <thread>
#include <atomic>
#include <algorithm>
#define CK(x) do { cudaError_t e_ = (x); if (e_ != cudaSuccess) { printf("CUDA error %s at %d: %s\n", #x, __LINE__, cudaGetErrorString(e_)); exit(1);} } while (0)
using Clock = std::chrono::steady_clock;
static double ms(Clock::time_point a) { return std::chrono::duration<double, std::milli>(Clock::now() - a).count(); }
__global__ void tiny(float* p, int n) { int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < n) p[i] += 1.0f; }
int main(int argc, char** argv) {
const size_t ENTRY = 2046000; // one expert (gate+up+down), bytes
const int PIECES = 3, RING = 384, NENT = 4096;
const size_t SMALL = 327680; // the routed slot table
uint8_t* host;
uint8_t* ring; CK(cudaMalloc((void**)&ring, ENTRY * RING));
uint8_t* dev_small; CK(cudaMalloc((void**)&dev_small, 64 << 20));
float* dev_f; CK(cudaMalloc((void**)&dev_f, 1 << 20));
std::vector<uint8_t> pageable(SMALL, 7);
uint8_t* pinned_small; CK(cudaHostAlloc((void**)&pinned_small, SMALL, cudaHostAllocDefault));
cudaStream_t copy, hi, other;
CK(cudaStreamCreateWithFlags(&copy, cudaStreamNonBlocking));
int lo, hip; CK(cudaDeviceGetStreamPriorityRange(&lo, &hip));
CK(cudaStreamCreateWithPriority(&hi, cudaStreamNonBlocking, hip));
CK(cudaStreamCreateWithFlags(&other, cudaStreamNonBlocking));
CK(cudaStreamSynchronize(0));
size_t hostN = 1ull << 30;
CK(cudaHostAlloc((void**)&host, hostN * 4, cudaHostAllocDefault)); // 4 GiB
memset(host, 1, hostN * 4);
const size_t entries_in_host = (hostN * 4) / ENTRY;
auto bg = [&](int depth, int pieces, std::atomic<bool>* stop, std::atomic<long>* bytes) {
std::vector<cudaEvent_t> ev(depth + 1);
for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming));
long k = 0;
while (!stop->load()) {
int slot = (int)(k % RING);
size_t src = (size_t)(k % entries_in_host) * ENTRY;
size_t piece = ENTRY / pieces;
for (int p = 0; p < pieces; ++p)
CK(cudaMemcpyAsync(ring + (size_t)slot * ENTRY + p * piece, host + src + p * piece, piece, cudaMemcpyHostToDevice, copy));
CK(cudaEventRecord(ev[k % (depth + 1)], copy));
++k; bytes->fetch_add(ENTRY);
if (k > depth) CK(cudaEventSynchronize(ev[(k - depth - 1) % (depth + 1)])); // keep `depth` entries outstanding
}
CK(cudaStreamSynchronize(copy));
for (auto& e : ev) cudaEventDestroy(e);
};
struct Probe { const char* name; };
auto measure = [&](const char* name, int reps, auto&& f) {
std::vector<double> t;
for (int i = 0; i < reps; ++i) { auto a = Clock::now(); f(); t.push_back(ms(a)); std::this_thread::sleep_for(std::chrono::microseconds(300)); }
std::sort(t.begin(), t.end());
double mean = 0; for (double x : t) mean += x; mean /= t.size();
printf(" %-34s mean %7.3f ms p50 %7.3f p90 %7.3f max %7.3f\n", name, mean, t[t.size() / 2], t[t.size() * 9 / 10], t.back());
};
int depths[] = {0, 2, 8, 32, 128, 384};
int pieces_list[] = {3, 1};
for (int pieces : pieces_list) {
for (int depth : depths) {
printf("expert stream: depth=%d entries outstanding, %d copies per entry (%zu B each)\n", depth, pieces, ENTRY / pieces);
std::atomic<bool> stop{false}; std::atomic<long> bytes{0};
std::thread th;
auto t0 = Clock::now();
if (depth > 0) th = std::thread([&] { bg(depth, pieces, &stop, &bytes); });
std::this_thread::sleep_for(std::chrono::milliseconds(150));
long b0 = bytes.load(); auto tm = Clock::now();
measure("cudaMemcpy H2D 327KB pageable", 60, [&] { CK(cudaMemcpy(dev_small, pageable.data(), SMALL, cudaMemcpyHostToDevice)); });
measure("cudaMemcpy H2D 6MB pageable", 20, [&] { std::vector<uint8_t> big(6 << 20, 1); CK(cudaMemcpy(dev_small, big.data(), big.size(), cudaMemcpyHostToDevice)); });
measure("cudaMemcpyAsync pinned 327KB hi-prio", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, hi)); CK(cudaStreamSynchronize(hi)); });
measure("cudaMemcpyAsync pinned 327KB other", 60, [&] { CK(cudaMemcpyAsync(dev_small, pinned_small, SMALL, cudaMemcpyHostToDevice, other)); CK(cudaStreamSynchronize(other)); });
measure("cudaMemcpy D2H 4KB", 60, [&] { uint8_t h[4096]; CK(cudaMemcpy(h, dev_small, 4096, cudaMemcpyDeviceToHost)); });
measure("cudaMemset 4KB (legacy)", 60, [&] { CK(cudaMemset(dev_small, 0, 4096)); });
measure("cudaMemcpy D2D 100MB (legacy)", 20, [&] { CK(cudaMemcpy(dev_small + (32 << 20), dev_small, 16 << 20, cudaMemcpyDeviceToDevice)); });
measure("tiny kernel + sync (other)", 60, [&] { tiny<<<64, 256, 0, other>>>(dev_f, 16384); CK(cudaStreamSynchronize(other)); });
measure("tiny kernel + sync (legacy)", 60, [&] { tiny<<<64, 256, 0, 0>>>(dev_f, 16384); CK(cudaStreamSynchronize(0)); });
long b1 = bytes.load(); double dt = ms(tm);
stop = true; if (th.joinable()) th.join();
if (depth > 0) printf(" expert DMA while probing: %.1f GB/s\n", (b1 - b0) / (dt * 1e6));
(void)t0;
}
}
return 0;
}