Merge branch 'claude/prefill-overlap' into claude/port-gpu-bringup
This commit is contained in:
@@ -112,6 +112,7 @@ mod enabled {
|
||||
if handle.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuStreamCreate"));
|
||||
}
|
||||
crate::compute_drain::register(handle as usize);
|
||||
Ok(Stream(handle as usize))
|
||||
}
|
||||
pub(crate) fn create_event(&self) -> Result<Event> {
|
||||
@@ -193,6 +194,7 @@ mod enabled {
|
||||
})
|
||||
}
|
||||
pub(crate) fn destroy_stream(&self, stream: Stream) -> Result<()> {
|
||||
crate::compute_drain::unregister(stream.0);
|
||||
// SAFETY: only called before enqueue or after proven completion.
|
||||
check("cuStreamDestroy_v2", unsafe {
|
||||
(self.stream_destroy)(stream.0 as *mut c_void)
|
||||
|
||||
@@ -0,0 +1,203 @@
|
||||
//! Stream-scoped drains for the prompt chunk's expert stream (prefill.cpp `stream_all`).
|
||||
//!
|
||||
//! Every compute producer of the prefill path drains with `cuCtxSynchronize`, which also waits for the expert
|
||||
//! copies queued on the chunk's copy stream: no copy could ever overlap a mixer. While a chunk's copy stream is
|
||||
//! the registered *background* stream, `Api::synchronize` instead waits for the legacy default stream and every
|
||||
//! registered compute stream except the background one. Every stream the crate creates is registered here
|
||||
//! (blas, Original schedule, owned-copy, swap), so the only work a drain no longer waits for is the chunk's copy
|
||||
//! stream, whose consumers order themselves with the per-slot `copied`/`used` events. Outside a chunk stream
|
||||
//! (background == 0) a drain is the unchanged context-wide `cuCtxSynchronize`.
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
static STREAMS: Mutex<Vec<usize>> = Mutex::new(Vec::new());
|
||||
static BACKGROUND: AtomicUsize = AtomicUsize::new(0);
|
||||
|
||||
|
||||
pub(crate) fn register(stream: usize) {
|
||||
if stream == 0 {
|
||||
return;
|
||||
}
|
||||
let mut all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !all.contains(&stream) {
|
||||
all.push(stream);
|
||||
}
|
||||
}
|
||||
pub(crate) fn unregister(stream: usize) {
|
||||
let mut all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
all.retain(|s| *s != stream);
|
||||
let _ = BACKGROUND.compare_exchange(stream, 0, Ordering::SeqCst, Ordering::SeqCst);
|
||||
}
|
||||
/// The chunk's copy stream (0 clears): drains stop waiting for it.
|
||||
pub(crate) fn set_background(stream: usize) {
|
||||
BACKGROUND.store(stream, Ordering::SeqCst);
|
||||
}
|
||||
pub(crate) fn background() -> usize {
|
||||
BACKGROUND.load(Ordering::SeqCst)
|
||||
}
|
||||
/// Every registered stream except `except` and the chunk's background copy stream, plus the legacy default stream (0): the
|
||||
/// streams whose later work must be ordered after a stream's deferred-guard run (deferred_status.rs).
|
||||
pub(crate) fn streams_except(except: usize) -> Vec<usize> {
|
||||
let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let background = background();
|
||||
std::iter::once(0usize).chain(all.iter().copied().filter(|&s| s != except && s != background)).collect()
|
||||
}
|
||||
/// Drain the legacy default stream and every registered stream but the background one.
|
||||
pub(crate) fn drain(sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> {
|
||||
let all = STREAMS.lock().unwrap_or_else(|e| e.into_inner());
|
||||
drain_set(&all, background(), sync)
|
||||
}
|
||||
/// The legacy default stream first, then each stream of `all` except `background`; the first error wins but every
|
||||
/// stream is still waited for.
|
||||
fn drain_set(all: &[usize], background: usize, mut sync: impl FnMut(usize) -> crate::Result<()>) -> crate::Result<()> {
|
||||
let mut result = sync(0);
|
||||
for &stream in all {
|
||||
if stream != background {
|
||||
let r = sync(stream);
|
||||
if result.is_ok() {
|
||||
result = r;
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
/// LELEKA_PREFILL_ALLOC_TRACE=1: while a chunk stream is in flight, every device allocation / free (cuMemFree and
|
||||
/// cuMemAlloc synchronize the whole device, copy stream included) prints once per call site (first 64 events).
|
||||
pub(crate) fn note_alloc(what: &str, bytes: usize) {
|
||||
if background() == 0 {
|
||||
return;
|
||||
}
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
static SEEN: AtomicUsize = AtomicUsize::new(0);
|
||||
if !*ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_ALLOC_TRACE").is_some_and(|v| v == "1")) {
|
||||
return;
|
||||
}
|
||||
if SEEN.fetch_add(1, Ordering::Relaxed) < 64 {
|
||||
let trace = std::backtrace::Backtrace::force_capture().to_string();
|
||||
let frames: Vec<&str> = trace
|
||||
.lines()
|
||||
.filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::"))
|
||||
.take(5)
|
||||
.collect();
|
||||
eprintln!("PREFILL-ALLOC {what} bytes={bytes} at {}", frames.join(" <- "));
|
||||
}
|
||||
}
|
||||
|
||||
const KINDS: usize = 8;
|
||||
static SHOWN: AtomicUsize = AtomicUsize::new(0);
|
||||
static SITES: Mutex<std::collections::BTreeMap<String, (usize, usize)>> = Mutex::new(std::collections::BTreeMap::new());
|
||||
static BLOCK_NS: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS];
|
||||
static BLOCK_N: [AtomicUsize; KINDS] = [const { AtomicUsize::new(0) }; KINDS];
|
||||
/// Run a host-blocking driver call (0 alloc, 1 free, 2 H2D, 3 D2H, 4 memset, 5 scoped drain, 6 D2D, 7 other stream/event sync), timing it while a chunk
|
||||
/// stream is in flight.
|
||||
pub(crate) fn timed<T>(kind: usize, f: impl FnOnce() -> T) -> T {
|
||||
if background() == 0 {
|
||||
return f();
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let out = f();
|
||||
let took = started.elapsed();
|
||||
BLOCK_NS[kind].fetch_add(took.as_nanos() as usize, Ordering::Relaxed);
|
||||
BLOCK_N[kind].fetch_add(1, Ordering::Relaxed);
|
||||
// LELEKA_PREFILL_STALL_TRACE=1: every blocking call over 2 ms (first 40 per chunk) with its callers, and a
|
||||
// per-call-site histogram of the host-to-device / device-to-host / memset / device-to-device calls
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
if matches!(kind, 2 | 3 | 4 | 6) && *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1")) {
|
||||
let trace = std::backtrace::Backtrace::force_capture().to_string();
|
||||
let frames: Vec<&str> = trace
|
||||
.lines()
|
||||
.filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::"))
|
||||
.skip(1)
|
||||
.take(4)
|
||||
.collect();
|
||||
let key = format!("kind={kind} {}", frames.join(" <- "));
|
||||
let mut sites = SITES.lock().unwrap_or_else(|e| e.into_inner());
|
||||
let entry = sites.entry(key).or_insert((0, 0));
|
||||
entry.0 += 1;
|
||||
entry.1 += took.as_nanos() as usize;
|
||||
}
|
||||
if took.as_micros() > 2000
|
||||
&& *ON.get_or_init(|| std::env::var_os("LELEKA_PREFILL_STALL_TRACE").is_some_and(|v| v == "1"))
|
||||
&& SHOWN.fetch_add(1, Ordering::Relaxed) < 40
|
||||
{
|
||||
let trace = std::backtrace::Backtrace::force_capture().to_string();
|
||||
let frames: Vec<&str> = trace
|
||||
.lines()
|
||||
.filter(|l| l.contains("leleka_cuda_driver::") || l.contains("leleka_runtime::"))
|
||||
.skip(1)
|
||||
.take(6)
|
||||
.collect();
|
||||
eprintln!("PREFILL-STALL kind={kind} ms={:.1} at {}", took.as_secs_f64() * 1e3, frames.join(" <- "));
|
||||
}
|
||||
out
|
||||
}
|
||||
/// `alloc n/ms free n/ms h2d n/ms d2h n/ms memset n/ms drain n/ms` since the last call.
|
||||
pub(crate) fn take_blocking_report() -> String {
|
||||
SHOWN.store(0, Ordering::Relaxed);
|
||||
let sites = std::mem::take(&mut *SITES.lock().unwrap_or_else(|e| e.into_inner()));
|
||||
let mut ranked: Vec<_> = sites.into_iter().collect();
|
||||
ranked.sort_by_key(|(_, v)| std::cmp::Reverse(v.0));
|
||||
for (site, (n, ns)) in ranked.iter().take(16) {
|
||||
eprintln!("PREFILL-SITE n={n} ms={:.1} {site}", *ns as f64 / 1e6);
|
||||
}
|
||||
let names = ["alloc", "free", "h2d", "d2h", "memset", "drain", "d2d", "streamsync"];
|
||||
(0..KINDS)
|
||||
.map(|k| {
|
||||
let n = BLOCK_N[k].swap(0, Ordering::Relaxed);
|
||||
let ms = BLOCK_NS[k].swap(0, Ordering::Relaxed) as f64 / 1e6;
|
||||
format!("{}={}/{:.1}ms", names[k], n, ms)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
static ZERO_MEMSET: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
|
||||
/// Harness switch (`LELEKA_PREFILL_STREAM_SEQ` bit 1): -1 = default (on; `LELEKA_PREFILL_ZERO_MEMSET=0` disables).
|
||||
pub fn set_zero_memset(on: bool) {
|
||||
ZERO_MEMSET.store(i8::from(on), Ordering::Relaxed);
|
||||
}
|
||||
/// Whether all-zero host-to-device uploads become device memsets while a chunk stream is in flight (the upload is a
|
||||
/// copy-engine transfer that waits behind the expert copies; the memset is not).
|
||||
pub(crate) fn zero_memset() -> bool {
|
||||
static ENV: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
background() != 0
|
||||
&& match ZERO_MEMSET.load(Ordering::Relaxed) {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => *ENV.get_or_init(|| std::env::var_os("LELEKA_PREFILL_ZERO_MEMSET").is_none_or(|v| v != "0")),
|
||||
}
|
||||
}
|
||||
|
||||
static DEPTH_OVERRIDE: AtomicUsize = AtomicUsize::new(0);
|
||||
/// Harness switch (`LELEKA_PREFILL_STREAM_SEQ` `value:depth`): issuer-thread depth for the next chunks (0 = env).
|
||||
pub fn set_issue_depth(depth: usize) {
|
||||
DEPTH_OVERRIDE.store(depth, Ordering::Relaxed);
|
||||
}
|
||||
pub(crate) fn issue_depth_override() -> usize {
|
||||
DEPTH_OVERRIDE.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn drain_waits_for_default_and_compute_streams_but_not_the_background_one() {
|
||||
let mut seen = Vec::new();
|
||||
drain_set(&[11, 12, 13], 12, |s| {
|
||||
seen.push(s);
|
||||
Ok(())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(seen, [0, 11, 13]);
|
||||
}
|
||||
#[test]
|
||||
fn drain_reports_the_first_error_after_waiting_for_every_stream() {
|
||||
let mut seen = Vec::new();
|
||||
let result = drain_set(&[5, 6, 7], 0, |s| {
|
||||
seen.push(s);
|
||||
if s == 6 { Err(crate::Error::ContextPoisoned) } else { Ok(()) }
|
||||
});
|
||||
assert!(matches!(result, Err(crate::Error::ContextPoisoned)));
|
||||
assert_eq!(seen, [0, 5, 6, 7]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! `LELEKA_PREFILL_DEFER_GUARDS=1` (EXPERIMENTAL, claude/schedule): deferred guard status for the prompt producer's `run`.
|
||||
//!
|
||||
//! Today every `OriginalPromptDevice::run` (the hyper-connection reads and injections: about 560 per 8192-token chunk) zeroes its status
|
||||
//! words with a synchronous upload, runs its kernels, drains the whole context, reads the words back and refuses on the first set one:
|
||||
//! three host synchronizations and two transfers per call, each one a hole in the GPU queue and a latecomer in the H2D copy FIFO.
|
||||
//! Deferred mode keeps the same words, the same kernels and the same refusal, but moves the *host's look* at them:
|
||||
//! 1. the words are zeroed by a stream-ordered memset (no upload, no wait);
|
||||
//! 2. after the kernels the words are copied by a stream-ordered DtoH into a pinned slot and an event is recorded behind the copy;
|
||||
//! 3. every other stream (and the legacy default stream) is ordered after that event on the device, which replaces the context
|
||||
//! drain that used to order the next producer after this one (the host does not wait);
|
||||
//! 4. the slot is evaluated by `resolve`, in order, with the unchanged evaluation (`evaluate`): when the ring of 64 slots is full, and
|
||||
//! at the points where results leave the device (final-row reads, preview/finish of the phase, row-lease teardown).
|
||||
//! A failing slot poisons the context exactly like the immediate check does (every later driver call refuses with `ContextPoisoned`) and
|
||||
//! returns the same error class and label as the immediate path would have, only later: work enqueued after the failing run has executed
|
||||
//! on its output, but nothing of it is observable (no row is read back, no phase is sealed, no session state is published) before `resolve`.
|
||||
use crate::Error;
|
||||
use crate::Result;
|
||||
|
||||
/// The evaluation of one status readback, shared by the immediate and the deferred path: any word above 1 is an unknown status; then
|
||||
/// the first set word in the producer's order (`stride == 10`: PLE, row first then stage order; otherwise GR, stage first over all rows).
|
||||
pub(crate) fn evaluate(readback: &[u8], stride: usize, order: &[usize], labels: &[&'static str]) -> Result<()> {
|
||||
for word in readback.as_chunks::<4>().0 {
|
||||
if u32::from_le_bytes(*word) > 1 {
|
||||
return Err(Error::InvalidDriverValue("Original prompt status"));
|
||||
}
|
||||
}
|
||||
let word_at = |row: &[u8], stage: usize| -> Result<u32> {
|
||||
Ok(u32::from_le_bytes(row[stage * 4..stage * 4 + 4].try_into().map_err(|_| Error::InvalidQwenShape)?))
|
||||
};
|
||||
if stride == 10 {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
for &stage in order {
|
||||
if word_at(row, stage)? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for &stage in order {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
if word_at(row, stage)? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read once: the switch. Off by default (experimental mode).
|
||||
pub(crate) fn enabled() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_DEFER_GUARDS").is_ok_and(|v| v == "1"))
|
||||
}
|
||||
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
mod device {
|
||||
use super::evaluate;
|
||||
use crate::ffi::{BufferHandle, deferred_status::{Api, HostBuffer}};
|
||||
use crate::{Context, Error, Result};
|
||||
use std::cell::RefCell;
|
||||
use std::collections::VecDeque;
|
||||
|
||||
const SLOTS: usize = 64;
|
||||
|
||||
struct Check {
|
||||
slot: usize,
|
||||
bytes: usize,
|
||||
stride: usize,
|
||||
order: Vec<usize>,
|
||||
labels: Vec<&'static str>,
|
||||
}
|
||||
struct Slot {
|
||||
host: HostBuffer,
|
||||
event: usize,
|
||||
}
|
||||
struct State {
|
||||
api: Api,
|
||||
context: usize,
|
||||
slots: Vec<Slot>,
|
||||
live: VecDeque<Check>,
|
||||
head: usize,
|
||||
}
|
||||
thread_local! {
|
||||
// The contexts are single-thread owners (Rc), so one state per thread, bound to the context that created it.
|
||||
static STATE: RefCell<Option<State>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
fn open(context: &Context<'_>, slot_bytes: usize) -> Result<State> {
|
||||
let api = Api::load()?;
|
||||
let mut slots = Vec::with_capacity(SLOTS);
|
||||
for _ in 0..SLOTS {
|
||||
slots.push(Slot { host: api.host_buffer(slot_bytes)?, event: api.event()? });
|
||||
}
|
||||
Ok(State { api, context: std::ptr::from_ref(context) as usize, slots, live: VecDeque::new(), head: 0 })
|
||||
}
|
||||
|
||||
/// Wait for the oldest live check and evaluate it. The first failure poisons the context; every other live copy is still waited for.
|
||||
fn resolve_oldest(context: &Context<'_>, st: &mut State) -> Result<()> {
|
||||
let Some(check) = st.live.pop_front() else { return Ok(()) };
|
||||
let slot = &st.slots[check.slot];
|
||||
st.api.wait_host(slot.event)?;
|
||||
let verdict = slot.host.view(check.bytes).and_then(|b| evaluate(b, check.stride, &check.order, &check.labels));
|
||||
if verdict.is_err() {
|
||||
context.poisoned.set(true);
|
||||
while let Some(rest) = st.live.pop_front() {
|
||||
let _ = st.api.wait_host(st.slots[rest.slot].event);
|
||||
}
|
||||
}
|
||||
verdict
|
||||
}
|
||||
|
||||
/// Step 1 of a deferred run: zero the status words, stream ordered.
|
||||
pub(crate) fn begin(context: &Context<'_>, status: BufferHandle, bytes: usize, stream: usize, slot_bytes: usize) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
if guard.as_ref().is_some_and(|s| s.context != std::ptr::from_ref(context) as usize || s.slots[0].host.bytes() < bytes) {
|
||||
if guard.as_ref().is_some_and(|s| !s.live.is_empty()) {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
*guard = None;
|
||||
}
|
||||
if guard.is_none() {
|
||||
*guard = Some(open(context, slot_bytes.max(bytes))?);
|
||||
}
|
||||
let st = guard.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
st.api.zero_async(status, bytes, stream)
|
||||
})
|
||||
}
|
||||
|
||||
/// Steps 2-3: copy the words out behind the kernels, record the event, order every other stream after it, remember the check.
|
||||
pub(crate) fn finish(
|
||||
context: &Context<'_>,
|
||||
status: BufferHandle,
|
||||
bytes: usize,
|
||||
stream: usize,
|
||||
stride: usize,
|
||||
order: &[usize],
|
||||
labels: &[&'static str],
|
||||
) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let st = guard.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
if st.live.len() == SLOTS {
|
||||
resolve_oldest(context, st)?;
|
||||
}
|
||||
let slot_index = st.head % SLOTS;
|
||||
st.head += 1;
|
||||
let slot = &st.slots[slot_index];
|
||||
st.api.read_async(&slot.host, status, bytes, stream)?;
|
||||
st.api.record(slot.event, stream)?;
|
||||
for other in crate::compute_drain::streams_except(stream) {
|
||||
st.api.wait_stream(other, slot.event)?;
|
||||
}
|
||||
st.live.push_back(Check { slot: slot_index, bytes, stride, order: order.to_vec(), labels: labels.to_vec() });
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
|
||||
/// Evaluate everything outstanding, in order. Enters the context itself.
|
||||
pub(crate) fn resolve(context: &Context<'_>) -> Result<()> {
|
||||
STATE.with(|cell| {
|
||||
let mut guard = cell.borrow_mut();
|
||||
let Some(st) = guard.as_mut() else { return Ok(()) };
|
||||
if st.live.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
if st.context != std::ptr::from_ref(context) as usize {
|
||||
return Err(Error::ContextMismatch);
|
||||
}
|
||||
let entered = context.enter()?;
|
||||
let mut result = Ok(());
|
||||
while !st.live.is_empty() {
|
||||
let r = resolve_oldest(context, st);
|
||||
if result.is_ok() {
|
||||
result = r;
|
||||
}
|
||||
}
|
||||
let popped = entered.finish();
|
||||
result.and(popped.map(|_| ()))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn pending() -> usize {
|
||||
STATE.with(|cell| cell.borrow().as_ref().map_or(0, |s| s.live.len()))
|
||||
}
|
||||
}
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use device::{begin, finish, pending, resolve};
|
||||
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
mod unsupported {
|
||||
use crate::ffi::BufferHandle;
|
||||
use crate::{Context, Error, Result};
|
||||
pub(crate) fn begin(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn finish(_: &Context<'_>, _: BufferHandle, _: usize, _: usize, _: usize, _: &[usize], _: &[&'static str]) -> Result<()> {
|
||||
Err(Error::UnsupportedPlatform)
|
||||
}
|
||||
pub(crate) fn resolve(_: &Context<'_>) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn pending() -> usize {
|
||||
0
|
||||
}
|
||||
}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) use unsupported::{begin, finish, pending, resolve};
|
||||
|
||||
#[cfg(all(test, feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
#[path = "deferred_status_gpu.rs"]
|
||||
mod gpu_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
fn words(rows: &[&[u32]]) -> Vec<u8> {
|
||||
rows.iter().flat_map(|r| r.iter().flat_map(|w| w.to_le_bytes())).collect()
|
||||
}
|
||||
#[test]
|
||||
fn evaluate_reports_the_first_set_stage_in_the_producers_order() {
|
||||
let labels = ["a", "b", "c", "d"];
|
||||
// GR (stride 4): stage first over all rows; order [2, 0, 1, 3]; row 1 sets stage 0 and row 2 sets stage 2
|
||||
let b = words(&[&[0, 0, 0, 0], &[1, 0, 0, 0], &[0, 0, 1, 0]]);
|
||||
assert!(matches!(evaluate(&b, 4, &[2, 0, 1, 3], &labels), Err(Error::NonFiniteMmqOutput("c"))));
|
||||
assert!(matches!(evaluate(&b, 4, &[0, 1, 2, 3], &labels), Err(Error::NonFiniteMmqOutput("a"))));
|
||||
assert!(evaluate(&words(&[&[0; 4], &[0; 4]]), 4, &[0, 1, 2, 3], &labels).is_ok());
|
||||
}
|
||||
#[test]
|
||||
fn evaluate_orders_ple_rows_before_stages_and_refuses_unknown_words() {
|
||||
let labels = ["s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9"];
|
||||
let mut r0 = [0u32; 10];
|
||||
let mut r1 = [0u32; 10];
|
||||
r0[5] = 1;
|
||||
r1[2] = 1;
|
||||
let b = words(&[&r0, &r1]);
|
||||
// PLE: row 0 is examined before row 1 whatever the stage order
|
||||
assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::NonFiniteMmqOutput("s5"))));
|
||||
// an unknown status (2) beats a set flag that comes earlier
|
||||
r0[0] = 2;
|
||||
let b = words(&[&r0, &r1]);
|
||||
assert!(matches!(evaluate(&b, 10, &[2, 5], &labels), Err(Error::InvalidDriverValue(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! Audited child of ffi (claude/schedule): the few asynchronous driver calls the deferred guard status block needs
|
||||
//! (`LELEKA_PREFILL_DEFER_GUARDS`, see deferred_status.rs): a device memset and a device-to-host copy on a stream, pinned host
|
||||
//! buffers, and events with cross-stream waits. Nothing here owns a device allocation or a stream; the host buffers are owned
|
||||
//! by `HostBuffer` and freed by `Api::free_host`. Callers keep the context current (their `enter()` guard) and keep every
|
||||
//! device allocation alive until the event of the copy that reads it has been waited for.
|
||||
use super::BufferHandle;
|
||||
use crate::{Error, Result};
|
||||
use std::ffi::{CStr, c_void};
|
||||
type Handle = *mut c_void;
|
||||
type HostAlloc = unsafe extern "C" fn(*mut Handle, usize, u32) -> i32;
|
||||
type HandleCall = unsafe extern "C" fn(Handle) -> i32;
|
||||
type EventCreate = unsafe extern "C" fn(*mut Handle, u32) -> i32;
|
||||
type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32;
|
||||
type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32;
|
||||
type DtoHAsync = unsafe extern "C" fn(*mut c_void, u64, usize, Handle) -> i32;
|
||||
type MemsetAsync = unsafe extern "C" fn(u64, u8, usize, Handle) -> i32;
|
||||
fn check(name: &'static str, code: i32) -> Result<()> {
|
||||
if code == 0 { Ok(()) } else { Err(Error::Driver { operation: name, code }) }
|
||||
}
|
||||
pub(crate) struct HostBuffer {
|
||||
address: usize,
|
||||
bytes: usize,
|
||||
}
|
||||
impl HostBuffer {
|
||||
pub(crate) fn bytes(&self) -> usize {
|
||||
self.bytes
|
||||
}
|
||||
/// The first `len` bytes. SAFETY contract (checked by the caller's protocol, not here): the event of the last copy
|
||||
/// into this buffer has completed, and no copy into it is in flight.
|
||||
pub(crate) fn view(&self, len: usize) -> Result<&[u8]> {
|
||||
if len > self.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
// SAFETY: `address` is a live pinned allocation of `bytes` bytes owned by `self`; `len <= bytes`; the protocol above
|
||||
// guarantees no concurrent writer.
|
||||
Ok(unsafe { std::slice::from_raw_parts(self.address as *const u8, len) })
|
||||
}
|
||||
}
|
||||
// usize is the real dlopen handle; the table holds only immutable C ABI function pointers.
|
||||
pub(crate) struct Api {
|
||||
library: usize,
|
||||
host_alloc: HostAlloc,
|
||||
host_free: HandleCall,
|
||||
event_create: EventCreate,
|
||||
event_destroy: HandleCall,
|
||||
event_sync: HandleCall,
|
||||
event_record: EventRecord,
|
||||
stream_wait: StreamWait,
|
||||
dtoh: DtoHAsync,
|
||||
memset: MemsetAsync,
|
||||
}
|
||||
impl Drop for Api {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the handle returned by dlopen in `load`, closed once.
|
||||
unsafe {
|
||||
libc::dlclose(self.library as Handle);
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Api {
|
||||
pub(crate) fn load() -> Result<Self> {
|
||||
// SAFETY: NUL-terminated literal name.
|
||||
let l = unsafe { libc::dlopen(c"libcuda.so.1".as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL) };
|
||||
if l.is_null() {
|
||||
return Err(Error::LibraryUnavailable);
|
||||
}
|
||||
struct Opening(Handle);
|
||||
impl Drop for Opening {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: dlopen handle not yet transferred to `Api`.
|
||||
unsafe {
|
||||
libc::dlclose(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
let opening = Opening(l);
|
||||
fn symbol(l: Handle, n: &'static CStr) -> Result<Handle> {
|
||||
// SAFETY: valid dlopen handle and NUL-terminated name.
|
||||
let p = unsafe { libc::dlsym(l, n.as_ptr()) };
|
||||
if p.is_null() { Err(Error::MissingSymbol(n.to_str().unwrap_or("deferred status symbol"))) } else { Ok(p) }
|
||||
}
|
||||
macro_rules! sym {
|
||||
($n:literal,$t:ty) => {
|
||||
// SAFETY: the CUDA driver ABI of this symbol is exactly the declared function type.
|
||||
unsafe { std::mem::transmute::<Handle, $t>(symbol(l, $n)?) }
|
||||
};
|
||||
}
|
||||
let result = Self {
|
||||
library: l as usize,
|
||||
host_alloc: sym!(c"cuMemHostAlloc", HostAlloc),
|
||||
host_free: sym!(c"cuMemFreeHost", HandleCall),
|
||||
event_create: sym!(c"cuEventCreate", EventCreate),
|
||||
event_destroy: sym!(c"cuEventDestroy_v2", HandleCall),
|
||||
event_sync: sym!(c"cuEventSynchronize", HandleCall),
|
||||
event_record: sym!(c"cuEventRecord", EventRecord),
|
||||
stream_wait: sym!(c"cuStreamWaitEvent", StreamWait),
|
||||
dtoh: sym!(c"cuMemcpyDtoHAsync_v2", DtoHAsync),
|
||||
memset: sym!(c"cuMemsetD8Async", MemsetAsync),
|
||||
};
|
||||
std::mem::forget(opening);
|
||||
Ok(result)
|
||||
}
|
||||
pub(crate) fn host_buffer(&self, bytes: usize) -> Result<HostBuffer> {
|
||||
if bytes == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let mut p = std::ptr::null_mut();
|
||||
// SAFETY: valid out pointer, nonzero size, flags 0 (plain page-locked memory).
|
||||
check("cuMemHostAlloc", unsafe { (self.host_alloc)(&mut p, bytes, 0) })?;
|
||||
if p.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuMemHostAlloc"));
|
||||
}
|
||||
Ok(HostBuffer { address: p as usize, bytes })
|
||||
}
|
||||
pub(crate) fn free_host(&self, buffer: HostBuffer) -> Result<()> {
|
||||
// SAFETY: the address came from `host_buffer`; the caller has waited for every copy into it.
|
||||
check("cuMemFreeHost", unsafe { (self.host_free)(buffer.address as Handle) })
|
||||
}
|
||||
pub(crate) fn event(&self) -> Result<usize> {
|
||||
let mut e = std::ptr::null_mut();
|
||||
// SAFETY: valid out pointer; flags 2 = CU_EVENT_DISABLE_TIMING.
|
||||
check("cuEventCreate", unsafe { (self.event_create)(&mut e, 2) })?;
|
||||
Ok(e as usize)
|
||||
}
|
||||
pub(crate) fn destroy_event(&self, event: usize) -> Result<()> {
|
||||
// SAFETY: event created by `event`, no pending waits the caller still needs.
|
||||
check("cuEventDestroy_v2", unsafe { (self.event_destroy)(event as Handle) })
|
||||
}
|
||||
pub(crate) fn record(&self, event: usize, stream: usize) -> Result<()> {
|
||||
// SAFETY: live event and stream handles of the current context.
|
||||
check("cuEventRecord", unsafe { (self.event_record)(event as Handle, stream as Handle) })
|
||||
}
|
||||
/// Block the host until the event has completed (a spin wait is the driver default).
|
||||
pub(crate) fn wait_host(&self, event: usize) -> Result<()> {
|
||||
// SAFETY: live event of the current context.
|
||||
check("cuEventSynchronize", unsafe { (self.event_sync)(event as Handle) })
|
||||
}
|
||||
/// Order `stream` (0 = the legacy default stream) after the work recorded in `event`, device side.
|
||||
pub(crate) fn wait_stream(&self, stream: usize, event: usize) -> Result<()> {
|
||||
// SAFETY: live event and stream (or the null stream) of the current context.
|
||||
check("cuStreamWaitEvent", unsafe { (self.stream_wait)(stream as Handle, event as Handle, 0) })
|
||||
}
|
||||
pub(crate) fn zero_async(&self, buffer: BufferHandle, bytes: usize, stream: usize) -> Result<()> {
|
||||
if bytes == 0 {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
buffer.validate_extent(bytes)?;
|
||||
// SAFETY: validated extent of a live allocation of the current context; stream handle of the same context.
|
||||
check("cuMemsetD8Async", unsafe { (self.memset)(buffer.0, 0, bytes, stream as Handle) })
|
||||
}
|
||||
pub(crate) fn read_async(&self, host: &HostBuffer, source: BufferHandle, bytes: usize, stream: usize) -> Result<()> {
|
||||
if bytes == 0 || bytes > host.bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
source.validate_extent(bytes)?;
|
||||
// SAFETY: pinned destination of at least `bytes`, validated device extent, same-context stream; the caller keeps both
|
||||
// alive and does not read or reuse the host buffer before the event recorded after this copy has completed.
|
||||
check("cuMemcpyDtoHAsync_v2", unsafe { (self.dtoh)(host.address as *mut c_void, source.0, bytes, stream as Handle) })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Model-free GPU proof of the deferred guard status machinery (deferred_status.rs): the stream-ordered zero, the DtoH into the pinned
|
||||
//! ring, the ordering events, the ring wrap and the poisoning, against the immediate evaluation. Enable with
|
||||
//! `LELEKA_PREFILL_STAGE_GPU=yes` (`cargo test -p leleka-cuda-driver --features cuda-driver deferred -- --ignored`).
|
||||
use super::*;
|
||||
use crate::{Context, DeviceBuffer, Driver};
|
||||
|
||||
fn status_bytes(words: &[u32]) -> Vec<u8> {
|
||||
words.iter().flat_map(|w| w.to_le_bytes()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "Root-only: needs a CUDA device"]
|
||||
fn deferred_status_equals_the_immediate_evaluation_and_poisons() {
|
||||
assert_eq!(std::env::var("LELEKA_PREFILL_STAGE_GPU").ok().as_deref(), Some("yes"));
|
||||
let driver = Driver::load().expect("driver");
|
||||
let device = driver.device(0).expect("device");
|
||||
let context = device.create_context(1usize << 30).expect("context");
|
||||
let workspace = context.native_batch_workspace().expect("workspace");
|
||||
let blas = workspace.blas().expect("blas");
|
||||
let stride = 4usize;
|
||||
let rows = 8usize;
|
||||
let bytes = rows * stride * 4;
|
||||
let order = [0usize, 1, 2, 3];
|
||||
let labels = ["n", "d", "s", "u"];
|
||||
let mut status: DeviceBuffer<'_> = context.allocate(4096).expect("alloc");
|
||||
let handle = status.handle.expect("handle");
|
||||
let put = |status: &mut DeviceBuffer<'_>, words: &[u32]| {
|
||||
let mut b = status_bytes(words);
|
||||
b.resize(4096, 0);
|
||||
status.copy_from(&b).expect("upload");
|
||||
};
|
||||
let run = |status: &mut DeviceBuffer<'_>, words: &[u32]| {
|
||||
let guard = context.enter().expect("enter");
|
||||
begin(&context, handle, bytes, blas.stream(), 4096).expect("begin");
|
||||
blas.synchronize().expect("sync");
|
||||
put(status, words); // stands in for the kernels' flag writes
|
||||
finish(&context, handle, bytes, blas.stream(), stride, &order, &labels).expect("finish");
|
||||
guard.finish().expect("pop");
|
||||
};
|
||||
// clean run, the zeroing must have cleared the previous words
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
assert_eq!(pending(), 2);
|
||||
resolve(&context).expect("clean runs");
|
||||
assert_eq!(pending(), 0);
|
||||
// more runs than slots: the ring wraps and resolves its oldest entries by itself
|
||||
for _ in 0..150 {
|
||||
run(&mut status, &vec![0; rows * stride]);
|
||||
}
|
||||
assert!(pending() <= 64);
|
||||
resolve(&context).expect("wrapped ring");
|
||||
// a set flag: same label as the immediate evaluation
|
||||
let mut words = vec![0u32; rows * stride];
|
||||
words[3 * stride + 2] = 1;
|
||||
run(&mut status, &words);
|
||||
let expected = evaluate(&status_bytes(&words), stride, &order, &labels).unwrap_err();
|
||||
let got = resolve(&context).unwrap_err();
|
||||
assert_eq!(format!("{got:?}"), format!("{expected:?}"));
|
||||
assert!(context.is_poisoned());
|
||||
assert!(matches!(context.enter(), Err(Error::ContextPoisoned)));
|
||||
}
|
||||
@@ -602,6 +602,7 @@ mod enabled {
|
||||
type ContextPushCurrentV2 = unsafe extern "C" fn(CuContext) -> CuResult;
|
||||
type ContextPopCurrentV2 = unsafe extern "C" fn(*mut CuContext) -> CuResult;
|
||||
type ContextSynchronize = unsafe extern "C" fn() -> CuResult;
|
||||
type StreamSynchronizeRaw = unsafe extern "C" fn(*mut c_void) -> CuResult;
|
||||
type MemAllocV2 = unsafe extern "C" fn(*mut CuDevicePtr, usize) -> CuResult;
|
||||
type MemFreeV2 = unsafe extern "C" fn(CuDevicePtr) -> CuResult;
|
||||
type MemGetInfoV2 = unsafe extern "C" fn(*mut usize, *mut usize) -> CuResult;
|
||||
@@ -655,6 +656,7 @@ mod enabled {
|
||||
push: ContextPushCurrentV2,
|
||||
pop: ContextPopCurrentV2,
|
||||
synchronize: ContextSynchronize,
|
||||
stream_synchronize: StreamSynchronizeRaw,
|
||||
allocate: MemAllocV2,
|
||||
free: MemFreeV2,
|
||||
copy_from: MemcpyHtoDV2,
|
||||
@@ -1473,6 +1475,7 @@ mod enabled {
|
||||
push: symbol!(library, c"cuCtxPushCurrent_v2", ContextPushCurrentV2),
|
||||
pop: symbol!(library, c"cuCtxPopCurrent_v2", ContextPopCurrentV2),
|
||||
synchronize: symbol!(library, c"cuCtxSynchronize", ContextSynchronize),
|
||||
stream_synchronize: symbol!(library, c"cuStreamSynchronize", StreamSynchronizeRaw),
|
||||
allocate: symbol!(library, c"cuMemAlloc_v2", MemAllocV2),
|
||||
free: symbol!(library, c"cuMemFree_v2", MemFreeV2),
|
||||
copy_from: symbol!(library, c"cuMemcpyHtoD_v2", MemcpyHtoDV2),
|
||||
@@ -1954,40 +1957,58 @@ mod enabled {
|
||||
Ok(ContextHandle(context as usize))
|
||||
}
|
||||
pub(crate) fn synchronize(&self) -> Result<()> {
|
||||
if crate::compute_drain::background() != 0 {
|
||||
// a chunk expert stream is in flight: queue a few more of its copies behind the work being
|
||||
// drained, then wait for the compute streams only (never for the copy stream)
|
||||
crate::prefetch_point();
|
||||
// SAFETY: caller guard makes its live owned context current; registered live streams.
|
||||
return crate::compute_drain::timed(5, || crate::compute_drain::drain(|s| {
|
||||
check("cuStreamSynchronize", unsafe { (self.stream_synchronize)(s as *mut c_void) })
|
||||
}));
|
||||
}
|
||||
// SAFETY: caller guard makes its live owned context current.
|
||||
check("cuCtxSynchronize", unsafe { (self.synchronize)() })
|
||||
}
|
||||
pub(crate) fn allocate(&self, bytes: usize) -> Result<BufferHandle> {
|
||||
crate::compute_drain::note_alloc("cuMemAlloc", bytes);
|
||||
let mut ptr = 0;
|
||||
// SAFETY: current-context guard; nonzero, bounded size validated
|
||||
// before mutation; valid u64 CUdeviceptr output on Linux64.
|
||||
check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) })?;
|
||||
crate::compute_drain::timed(0, || check("cuMemAlloc_v2", unsafe { (self.allocate)(&mut ptr, bytes) }))?;
|
||||
if ptr == 0 {
|
||||
return Err(Error::InvalidDriverValue("cuMemAlloc_v2"));
|
||||
}
|
||||
Ok(BufferHandle(ptr))
|
||||
}
|
||||
pub(crate) fn free(&self, buffer: BufferHandle) -> Result<()> {
|
||||
crate::compute_drain::note_alloc("cuMemFree", 0);
|
||||
// SAFETY: uniquely owned allocation, owner context is current.
|
||||
// Poisoned/uncertain contexts never enter this operation.
|
||||
check("cuMemFree_v2", unsafe { (self.free)(buffer.0) })
|
||||
crate::compute_drain::timed(1, || check("cuMemFree_v2", unsafe { (self.free)(buffer.0) }))
|
||||
}
|
||||
pub(crate) fn copy_from(&self, buffer: BufferHandle, owned: &[u8]) -> Result<()> {
|
||||
// SAFETY: buffer owner is current, exact allocation size checked,
|
||||
// and the caller owns this staging allocation. It synchronizes on
|
||||
// both success/error and leaks staging on ambiguous completion, so
|
||||
// the pointer stays valid even if the call retains it after return.
|
||||
check("cuMemcpyHtoD_v2", unsafe {
|
||||
if crate::compute_drain::zero_memset() && owned.len() <= 1 << 20 && owned.iter().all(|b| *b == 0) {
|
||||
// EXPERIMENT (chunk stream in flight): an all-zero upload is a device memset, which does not queue
|
||||
// behind the expert copies on the host-to-device copy engine
|
||||
return crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
|
||||
(self.zero)(buffer.0, 0, owned.len())
|
||||
}));
|
||||
}
|
||||
crate::compute_drain::timed(2, || check("cuMemcpyHtoD_v2", unsafe {
|
||||
(self.copy_from)(buffer.0, owned.as_ptr().cast(), owned.len())
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn copy_to(&self, buffer: BufferHandle, owned: &mut [u8]) -> Result<()> {
|
||||
// SAFETY: valid owned writable staging of exactly the allocation
|
||||
// size; current owner context; caller synchronizes or leaks as
|
||||
// above. No borrowed output is passed directly to the driver.
|
||||
check("cuMemcpyDtoH_v2", unsafe {
|
||||
crate::compute_drain::timed(3, || check("cuMemcpyDtoH_v2", unsafe {
|
||||
(self.copy_to)(owned.as_mut_ptr().cast(), buffer.0, owned.len())
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn zero(&self, destination: u64, bytes: usize) -> Result<()> {
|
||||
if destination == 0 || bytes == 0 {
|
||||
@@ -1995,9 +2016,9 @@ mod enabled {
|
||||
}
|
||||
// SAFETY: caller owns the current-context allocation and has
|
||||
// validated this exact nonzero extent before dispatch.
|
||||
check("cuMemsetD8_v2", unsafe {
|
||||
crate::compute_drain::timed(4, || check("cuMemsetD8_v2", unsafe {
|
||||
(self.zero)(destination, 0, bytes)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn copy_mmq_weight(
|
||||
&self,
|
||||
@@ -2011,9 +2032,9 @@ mod enabled {
|
||||
// SAFETY: the closed MMQ facade validates actual same-context,
|
||||
// disjoint whole raw source and padded destination allocations.
|
||||
// Owners stay borrowed until synchronize/pop, with poison on uncertainty.
|
||||
check("cuMemcpyDtoD_v2", unsafe {
|
||||
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
|
||||
(self.copy_moe_down)(destination.0, source.0, bytes)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn copy_moe_down(
|
||||
&self,
|
||||
@@ -2024,9 +2045,9 @@ mod enabled {
|
||||
// a checked ten-slot destination address and exactly10240 bytes.
|
||||
// Both allocations remain borrowed until sync and context restore;
|
||||
// ambiguous completion poisons their context before any later free.
|
||||
check("cuMemcpyDtoD_v2", unsafe {
|
||||
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
|
||||
(self.copy_moe_down)(destination.0, source.0, 10_240)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn copy_original_down_group(
|
||||
&self,
|
||||
@@ -2039,9 +2060,9 @@ mod enabled {
|
||||
}
|
||||
// SAFETY: actual affine grouped Down producer and prompt arena
|
||||
// supply disjoint checked extents; both survive sync and pop.
|
||||
check("cuMemcpyDtoD_v2", unsafe {
|
||||
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
|
||||
(self.copy_moe_down)(destination.0, source.0, bytes)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn copy_moe_group_column(
|
||||
&self,
|
||||
@@ -2052,9 +2073,9 @@ mod enabled {
|
||||
// a checked 64-column destination address and exactly2560 bytes.
|
||||
// Both allocations remain borrowed until sync and context restore;
|
||||
// ambiguous completion poisons their context before any later free.
|
||||
check("cuMemcpyDtoD_v2", unsafe {
|
||||
crate::compute_drain::timed(6, || check("cuMemcpyDtoD_v2", unsafe {
|
||||
(self.copy_moe_down)(destination.0, source.0, 2560)
|
||||
})
|
||||
}))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2747,3 +2768,11 @@ pub(crate) mod original_stager;
|
||||
))]
|
||||
#[path = "original_file_expert_source_ffi.rs"]
|
||||
pub(crate) mod original_file_source;
|
||||
|
||||
#[cfg(all(
|
||||
feature = "cuda-driver",
|
||||
target_os = "linux",
|
||||
target_pointer_width = "64"
|
||||
))]
|
||||
#[path = "deferred_status_ffi.rs"]
|
||||
pub(crate) mod deferred_status;
|
||||
|
||||
@@ -639,10 +639,6 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
.api
|
||||
.copy_from(hin, &history_bytes)
|
||||
.and_then(|()| context.driver.api.synchronize());
|
||||
// the batch below runs without a drain until its end: next-MoE expert copies can run under it
|
||||
if operation.is_ok() {
|
||||
crate::prefetch_point();
|
||||
}
|
||||
if timed {
|
||||
crate::command_profile::add("gdn", 0, "history upload", started.elapsed());
|
||||
}
|
||||
@@ -701,7 +697,6 @@ impl<'ctx> OriginalGdnPromptDevice<'ctx> {
|
||||
.and_then(|()| context.driver.api.copy_to(hout, &mut final_history))
|
||||
}
|
||||
let all = context.driver.api.synchronize();
|
||||
crate::prefetch_window_end();
|
||||
if timed {
|
||||
crate::command_profile::add("gdn", 999, "drain+readback", started.elapsed());
|
||||
}
|
||||
|
||||
@@ -29,6 +29,8 @@ use std::{cell::{Cell, RefCell}, fmt, marker::PhantomData, rc::Rc};
|
||||
|
||||
#[allow(unsafe_code)]
|
||||
mod ffi;
|
||||
pub mod compute_drain;
|
||||
mod deferred_status;
|
||||
#[allow(unsafe_code)]
|
||||
mod original_gpu_schedule;
|
||||
pub use original_gpu_schedule::{
|
||||
@@ -64,7 +66,7 @@ mod mmq_native;
|
||||
pub use mmq::resident::original_group::{
|
||||
OriginalMmqCopySchedule, OriginalMmqLayer, OriginalMmqOutput, original_mmq_group_bank_bytes,
|
||||
};
|
||||
pub(crate) use mmq::resident::original_group::{prefetch_point, prefetch_window_end};
|
||||
pub(crate) use mmq::resident::original_group::prefetch_point;
|
||||
pub use mmq::resident::{
|
||||
FiniteMmqOutput, MmqChunkActivation, MmqGroupActivation, MmqHidden, MmqWorkspace,
|
||||
};
|
||||
@@ -420,6 +422,7 @@ impl<'driver> Device<'driver> {
|
||||
kar_levels: Cell::new(None),
|
||||
experimental: std::array::from_fn(|_| Cell::new(None)),
|
||||
window_modules: RefCell::new(Vec::new()),
|
||||
deferred_frees: RefCell::new(Vec::new()),
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -471,6 +474,9 @@ pub struct Context<'driver> {
|
||||
/// Sealed verify-window modules loaded under this context, shared by every verifier bank created later
|
||||
/// (the serve path assembles one per request) and unloaded with the context.
|
||||
window_modules: RefCell<Vec<(&'static str, Rc<original_verify::abi::Module>, Vec<&'static str>)>>,
|
||||
/// Buffers released while a prompt chunk's expert copies are in flight (cuMemFree synchronizes the whole
|
||||
/// device and would wait for every queued copy): freed by `flush_deferred_frees`. They stay charged.
|
||||
deferred_frees: RefCell<Vec<(ffi::BufferHandle, usize)>>,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct FixedKernel {
|
||||
@@ -1030,6 +1036,37 @@ impl Context<'_> {
|
||||
_thread: PhantomData,
|
||||
})
|
||||
}
|
||||
/// Queue a buffer's release for after the chunk's expert stream (it stays charged until then); when the
|
||||
/// queued bytes pass `LELEKA_PREFILL_DEFER_FREE_MIB` (512) they are freed at once.
|
||||
fn defer_free(&self, handle: ffi::BufferHandle, bytes: usize) -> Result<()> {
|
||||
let pending = {
|
||||
let mut list = self.deferred_frees.borrow_mut();
|
||||
list.push((handle, bytes));
|
||||
list.iter().map(|b| b.1).sum::<usize>()
|
||||
};
|
||||
static LIMIT: std::sync::OnceLock<usize> = std::sync::OnceLock::new();
|
||||
let limit = *LIMIT.get_or_init(|| {
|
||||
std::env::var("LELEKA_PREFILL_DEFER_FREE_MIB").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(512) << 20
|
||||
});
|
||||
if pending > limit { self.flush_deferred_frees() } else { Ok(()) }
|
||||
}
|
||||
/// Free every deferred buffer (one device synchronization).
|
||||
pub(crate) fn flush_deferred_frees(&self) -> Result<()> {
|
||||
let list = std::mem::take(&mut *self.deferred_frees.borrow_mut());
|
||||
if list.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let guard = self.enter()?;
|
||||
let mut result = Ok(());
|
||||
for (handle, bytes) in list {
|
||||
let free = self.driver.api.free(handle);
|
||||
if free.is_ok() {
|
||||
self.allocated.set(self.allocated.get() - bytes);
|
||||
}
|
||||
result = combine(result, free);
|
||||
}
|
||||
combine(result, guard.finish())
|
||||
}
|
||||
/// Read-only sticky completion fence; never resets or changes the context.
|
||||
pub fn is_poisoned(&self) -> bool {
|
||||
self.poisoned.get()
|
||||
@@ -2366,6 +2403,10 @@ impl DeviceBuffer<'_> {
|
||||
let Some(handle) = self.handle.take() else {
|
||||
return Ok(());
|
||||
};
|
||||
if compute_drain::background() != 0 && !self.context.poisoned.get() {
|
||||
// a chunk expert stream is in flight: do not synchronize the device now
|
||||
return self.context.defer_free(handle, self.bytes);
|
||||
}
|
||||
let guard = self.context.enter()?;
|
||||
let free = self.context.driver.api.free(handle);
|
||||
if free.is_ok() {
|
||||
@@ -2615,6 +2656,7 @@ mod tests {
|
||||
kar_levels: Cell::new(None),
|
||||
experimental: std::array::from_fn(|_| Cell::new(None)),
|
||||
window_modules: RefCell::new(Vec::new()),
|
||||
deferred_frees: RefCell::new(Vec::new()),
|
||||
};
|
||||
let make = |handle| DeviceBuffer {
|
||||
context: &context,
|
||||
|
||||
@@ -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,
|
||||
@@ -228,6 +268,21 @@ impl<'ctx> MappedExpertBank<'ctx> {
|
||||
}
|
||||
Ok(pieces)
|
||||
}
|
||||
/// `expert_pieces` as 4 KiB-aligned supersets clamped to the member: (address, length, lead) where `lead` is the offset of the
|
||||
/// exact piece inside the superset (claude/ledger; the stream issuer copies the superset and reads the piece at `lead`).
|
||||
pub(crate) fn expert_pieces_aligned(&self, layer: u8, expert: u32) -> Result<[(usize, usize, usize); 3]> {
|
||||
let exact = self.expert_pieces(layer, expert)?;
|
||||
let mut out = [(0usize, 0usize, 0usize); 3];
|
||||
for (role, piece) in out.iter_mut().enumerate() {
|
||||
let member = self.banks[usize::from(layer) * 3 + role].member.bytes();
|
||||
let base = member.as_ptr() as usize;
|
||||
let (start, end) = (exact[role].0, exact[role].0 + exact[role].1);
|
||||
let a = (start & !(PAGE - 1)).max(base);
|
||||
let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len());
|
||||
*piece = (a, b - a, start - a);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
/// True for the low-RAM source: pageable file-mapped banks, no device aliases (see the field).
|
||||
pub fn pageable(&self) -> bool {
|
||||
self.pageable
|
||||
|
||||
@@ -2,31 +2,50 @@
|
||||
//! 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 port's compute path drains with context-wide synchronizations (cuCtxSynchronize) after every stage, and
|
||||
//! such a drain also waits for every copy queued on the copy stream: copies queued ahead of a mixer would be waited
|
||||
//! for at its first drain. (A free-running issuer thread, the Original's D-5, made every mixer drain wait for the
|
||||
//! issuer to fill the ring: measured slower, job 707.) So the copies are enqueued on the calling thread, at two
|
||||
//! kinds of points:
|
||||
//! * the layer's MoE: entries up to the ring's capacity, within the current layer only (as the per-layer ring);
|
||||
//! * `prefetch_point` (called by a long mixer producer right after its last drain before a sync-free batch of
|
||||
//! kernels, the GDN prompt producer): as many entries of the next MoE layer as its measured batch time covers,
|
||||
//! so those copies run under the mixer's kernels and are complete by its closing drain.
|
||||
//! 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
|
||||
//! Two issue modes (`LELEKA_PREFILL_ISSUER`, default `thread`):
|
||||
//! * `thread` (the Original's D-5 issuer): a helper thread keeps at most `LELEKA_PREFILL_DEPTH` (2) 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)]
|
||||
pub(super) struct Entry {
|
||||
pub(super) layer: u8,
|
||||
pub(super) expert: u32,
|
||||
/// gate/up/down host ranges (page-locked bank), copied back to back into the slot
|
||||
/// gate/up/down host ranges (page-locked bank) as copied: the exact pieces back to back, or their 4 KiB-aligned
|
||||
/// supersets (claude/ledger, `LELEKA_PREFILL_ALIGNED_COPY`: ~15% faster DMA)
|
||||
pub(super) pieces: [(usize, usize); 3],
|
||||
/// the exact gate/up/down host ranges (what the consumer gathers)
|
||||
pub(super) exact: [(usize, usize); 3],
|
||||
/// slot offset each copied piece lands at
|
||||
pub(super) dest: [usize; 3],
|
||||
/// slot offset each exact piece starts at (dest + the lead inside its superset)
|
||||
pub(super) at: [usize; 3],
|
||||
}
|
||||
/// LELEKA_PREFILL_COPY_STATS: a timing event before every entry's copies (after its slot wait) and the entry's
|
||||
/// `copied` event (created with timestamps): their gap is the entry's pure DMA time.
|
||||
struct Stats {
|
||||
starts: Vec<usize>,
|
||||
sampled_ns: AtomicU64,
|
||||
sampled_bytes: AtomicU64,
|
||||
sampled: AtomicU64,
|
||||
}
|
||||
struct Core {
|
||||
api: Api,
|
||||
@@ -37,14 +56,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>,
|
||||
/// measured length of the last prefetch window (point to closing drain) and the bytes/s estimate
|
||||
window: Cell<Duration>,
|
||||
window_start: Cell<Option<Instant>>,
|
||||
bytes_per_second: f64,
|
||||
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,
|
||||
/// 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: AtomicU64,
|
||||
}
|
||||
impl Core {
|
||||
fn ring(&self) -> usize {
|
||||
@@ -53,95 +81,162 @@ 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());
|
||||
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()
|
||||
}
|
||||
/// Fold entry `k`'s DMA time into the sample when its events completed.
|
||||
fn harvest(&self, k: usize, wait: bool) {
|
||||
let Some(stats) = &self.stats else { return };
|
||||
let slot = k % self.ring();
|
||||
let done = if wait {
|
||||
self.api.event_sync(self.copied[slot]).is_ok()
|
||||
} else {
|
||||
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_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.load(Ordering::Relaxed);
|
||||
if jitter != 0 {
|
||||
let mut x = jitter;
|
||||
x ^= x << 13;
|
||||
x ^= x >> 7;
|
||||
x ^= x << 17;
|
||||
self.jitter.store(x, Ordering::Relaxed);
|
||||
if x % 5 == 0 {
|
||||
std::thread::sleep(Duration::from_micros(x >> 8 & 0x3ff));
|
||||
}
|
||||
}
|
||||
let started = Instant::now();
|
||||
let entry = self.entries[k];
|
||||
let slot = k % self.ring();
|
||||
if k >= self.ring() {
|
||||
self.harvest(k - self.ring(), false);
|
||||
// the slot's previous entry was gathered (or released) on the compute stream
|
||||
self.api.wait(self.copy, self.used[slot])?;
|
||||
}
|
||||
if let Some(stats) = &self.stats {
|
||||
self.api.record(stats.starts[slot], self.copy)?;
|
||||
}
|
||||
let (target, capacity) = self.targets[slot];
|
||||
let mut offset = 0usize;
|
||||
for (address, length) in entry.pieces {
|
||||
let end = offset.checked_add(length).ok_or(Error::InvalidSize)?;
|
||||
let mut copied_bytes = 0usize;
|
||||
for (piece, &(address, length)) in entry.pieces.iter().enumerate() {
|
||||
let end = entry.dest[piece].checked_add(length).ok_or(Error::InvalidSize)?;
|
||||
if end > capacity {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
self.api.copy_raw(target.checked_subspan(capacity, offset, length)?, address, length, self.copy)?;
|
||||
offset = end;
|
||||
self.api.copy_raw(target.checked_subspan(capacity, entry.dest[piece], length)?, address, length, self.copy)?;
|
||||
self.calls.fetch_add(1, Ordering::Relaxed);
|
||||
copied_bytes += length;
|
||||
}
|
||||
self.api.record(self.copied[slot], self.copy)
|
||||
self.bytes.fetch_add(copied_bytes as u64, Ordering::Relaxed);
|
||||
let recorded = self.api.record(self.copied[slot], self.copy);
|
||||
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 a long mixer producer right after its last drain and before its sync-free kernel batch: enqueue as
|
||||
/// many next-MoE entries as the previous window covered. The caller must call `prefetch_window_end` after its
|
||||
/// closing drain. No-op without an active stream. The caller's Context must be current.
|
||||
/// 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 };
|
||||
core.window_start.set(Some(Instant::now()));
|
||||
let window = core.window.get();
|
||||
if window.is_zero() {
|
||||
return;
|
||||
}
|
||||
let layer = core.next_layer.get();
|
||||
if layer >= 48 {
|
||||
return;
|
||||
}
|
||||
let blob: usize = core
|
||||
.entries
|
||||
.get(core.issued.get())
|
||||
.map_or(0, |e| e.pieces.iter().map(|p| p.1).sum());
|
||||
if blob == 0 {
|
||||
return;
|
||||
}
|
||||
// 90% of the window: the copies must be done by the window's closing drain
|
||||
let budget = (window.as_secs_f64() * 0.9 * core.bytes_per_second / blob as f64) as usize;
|
||||
let limit = (core.issued.get() + budget).min(core.layer_end(layer));
|
||||
let _ = core.issue_until(limit);
|
||||
});
|
||||
}
|
||||
/// The producer's closing drain returned: record the window length for the next `prefetch_point`.
|
||||
pub(crate) fn prefetch_window_end() {
|
||||
ACTIVE.with(|active| {
|
||||
if let Some(core) = active.borrow().as_ref()
|
||||
&& let Some(start) = core.window_start.take()
|
||||
{
|
||||
core.window.set(start.elapsed());
|
||||
}
|
||||
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).
|
||||
/// `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); `context` the raw
|
||||
/// context token for the issuer thread.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn start(
|
||||
api: Api,
|
||||
@@ -151,9 +246,13 @@ impl ChunkStream {
|
||||
targets: Vec<(BufferHandle, usize)>,
|
||||
copied: Vec<usize>,
|
||||
used: Vec<usize>,
|
||||
bytes_per_second: f64,
|
||||
starts: Vec<usize>,
|
||||
topup: usize,
|
||||
context: usize,
|
||||
) -> Result<Self> {
|
||||
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48 {
|
||||
if targets.is_empty() || copied.len() != targets.len() || used.len() != targets.len() || first >= 48
|
||||
|| !(starts.is_empty() || starts.len() == targets.len())
|
||||
{
|
||||
return Err(Error::InvalidProjectionShape);
|
||||
}
|
||||
if entries.windows(2).any(|w| (w[0].layer, w[0].expert) >= (w[1].layer, w[1].expert))
|
||||
@@ -169,7 +268,18 @@ 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 {
|
||||
(match crate::compute_drain::issue_depth_override() {
|
||||
0 => env_number("LELEKA_PREFILL_DEPTH").unwrap_or(2),
|
||||
n => n,
|
||||
})
|
||||
.clamp(1, targets.len() - 1)
|
||||
} else {
|
||||
0
|
||||
};
|
||||
let core = Arc::new(Core {
|
||||
api,
|
||||
entries,
|
||||
targets,
|
||||
@@ -177,26 +287,53 @@ 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),
|
||||
window: Cell::new(Duration::ZERO),
|
||||
window_start: Cell::new(None),
|
||||
bytes_per_second: bytes_per_second.max(1e9),
|
||||
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: 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_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 {
|
||||
self.core.entries.get(k).is_some_and(|e| {
|
||||
e.pieces.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len())
|
||||
e.exact.iter().zip(parts).all(|(&(a, n), p)| a == p.as_ptr() as usize && n == p.len())
|
||||
})
|
||||
}
|
||||
/// Slot offsets of entry `k`'s exact gate/up/down pieces.
|
||||
pub(super) fn entry_at(&self, k: usize) -> Result<[usize; 3]> {
|
||||
self.core.entries.get(k).map(|e| e.at).ok_or(Error::InvalidProjectionShape)
|
||||
}
|
||||
/// Entry index of `expert` in `layer`, if the stream carries it (not arena-resident).
|
||||
pub(super) fn entry(&self, layer: u8, expert: u32) -> Option<usize> {
|
||||
let (a, b) = (self.core.layer_start[usize::from(layer)], self.core.layer_start[usize::from(layer) + 1]);
|
||||
@@ -205,14 +342,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(())
|
||||
}
|
||||
@@ -220,27 +358,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.
|
||||
@@ -250,18 +389,48 @@ impl ChunkStream {
|
||||
}
|
||||
let end = self.core.layer_end(layer);
|
||||
self.release_until(end, compute)?;
|
||||
self.core.next_layer.set(layer + 1);
|
||||
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.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 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.load(Ordering::Relaxed);
|
||||
let bytes = core.bytes.load(Ordering::Relaxed);
|
||||
crate::bringup_trace!(
|
||||
"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_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()
|
||||
);
|
||||
}
|
||||
pub(super) fn api(&self) -> &Api {
|
||||
&self.core.api
|
||||
|
||||
@@ -1435,7 +1435,7 @@ impl OriginalMmqOutput<'_, '_, '_> {
|
||||
#[path = "mmq_original_ring.rs"]
|
||||
mod copy_ring;
|
||||
pub use copy_ring::OriginalMmqCopySchedule;
|
||||
pub(crate) use copy_ring::{prefetch_point, prefetch_window_end};
|
||||
pub(crate) use copy_ring::prefetch_point;
|
||||
impl<'layer, 'ctx> OriginalMmqLayer<'layer, 'ctx> {
|
||||
/// Execute the actual ascending expert layer through Original's copy ring.
|
||||
/// The actual read/arena and registered bank remain retained until BOTH stream
|
||||
|
||||
@@ -22,12 +22,10 @@ mod chunk_stream;
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
use chunk_stream::{ChunkStream, Entry as StreamEntry};
|
||||
#[cfg(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64"))]
|
||||
pub(crate) use chunk_stream::{prefetch_point, prefetch_window_end};
|
||||
pub(crate) use chunk_stream::prefetch_point;
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) fn prefetch_point() {}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
pub(crate) fn prefetch_window_end() {}
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
struct ChunkStream;
|
||||
#[cfg(not(all(feature = "cuda-driver", target_os = "linux", target_pointer_width = "64")))]
|
||||
impl ChunkStream {
|
||||
@@ -106,6 +104,10 @@ pub struct OriginalMmqCopySchedule<'ctx> {
|
||||
stream: Option<ChunkStream>,
|
||||
stream_bank: Option<Rc<crate::MappedExpertBank<'ctx>>>,
|
||||
stream_events: Vec<usize>,
|
||||
stream_started: Option<std::time::Instant>,
|
||||
/// 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>)>,
|
||||
}
|
||||
impl Context<'_> {
|
||||
pub fn original_mmq_copy_schedule(&self, slots: usize) -> Result<OriginalMmqCopySchedule<'_>> {
|
||||
@@ -129,6 +131,8 @@ impl Context<'_> {
|
||||
stream: None,
|
||||
stream_bank: None,
|
||||
stream_events: Vec::new(),
|
||||
stream_started: None,
|
||||
status_pool: None,
|
||||
};
|
||||
let result = (|| {
|
||||
owner
|
||||
@@ -238,6 +242,7 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
for index in 0..ring {
|
||||
targets.push(lease.copy_ring_span(index)?);
|
||||
}
|
||||
let aligned_copy = crate::mapped_expert_bank::aligned_copy_enabled();
|
||||
let mut entries = Vec::new();
|
||||
entries
|
||||
.try_reserve_exact((48 - usize::from(first)) * 512)
|
||||
@@ -247,21 +252,52 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
if lease.cache_expert_span(usize::from(layer), expert as usize)?.is_some() {
|
||||
continue;
|
||||
}
|
||||
let pieces = bank.expert_pieces(layer, expert)?;
|
||||
let bytes: usize = pieces.iter().map(|p| p.1).sum();
|
||||
if targets.iter().any(|t| t.1 < bytes) {
|
||||
return Err(Error::InvalidSize);
|
||||
let exact = bank.expert_pieces(layer, expert)?;
|
||||
let slot_bytes = targets.iter().map(|t| t.1).min().unwrap_or(0);
|
||||
// page-aligned supersets side by side at page offsets when they fit the slot (claude/ledger), else the
|
||||
// exact pieces back to back
|
||||
let mut entry = None;
|
||||
if aligned_copy {
|
||||
let sup = bank.expert_pieces_aligned(layer, expert)?;
|
||||
let mut dest = [0usize; 3];
|
||||
let mut at = [0usize; 3];
|
||||
let mut off = 0usize;
|
||||
for i in 0..3 {
|
||||
dest[i] = off;
|
||||
at[i] = off + sup[i].2;
|
||||
off += sup[i].1.div_ceil(4096) * 4096;
|
||||
}
|
||||
if off <= slot_bytes {
|
||||
entry = Some(StreamEntry {
|
||||
layer, expert, pieces: [(sup[0].0, sup[0].1), (sup[1].0, sup[1].1), (sup[2].0, sup[2].1)],
|
||||
exact, dest, at,
|
||||
});
|
||||
}
|
||||
}
|
||||
entries.push(StreamEntry { layer, expert, pieces });
|
||||
let entry = match entry {
|
||||
Some(e) => e,
|
||||
None => {
|
||||
let bytes: usize = exact.iter().map(|p| p.1).sum();
|
||||
if bytes > slot_bytes {
|
||||
return Err(Error::InvalidSize);
|
||||
}
|
||||
let dest = [0, exact[0].1, exact[0].1 + exact[1].1];
|
||||
StreamEntry { layer, expert, pieces: exact, exact, dest, at: dest }
|
||||
}
|
||||
};
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
let api = StagerApi::load()?;
|
||||
let guard = self.context.enter()?;
|
||||
let mut events = Vec::new();
|
||||
let stats = std::env::var_os("LELEKA_PREFILL_COPY_STATS").is_some_and(|v| v == "1");
|
||||
let per_slot = if stats { 3 } else { 2 };
|
||||
let created = (|| -> Result<()> {
|
||||
events.try_reserve_exact(2 * ring).map_err(|_| Error::HostAllocation)?;
|
||||
for _ in 0..2 * ring {
|
||||
events.push(api.event_create()?);
|
||||
events.try_reserve_exact(per_slot * ring).map_err(|_| Error::HostAllocation)?;
|
||||
for i in 0..per_slot * ring {
|
||||
// with the statistics on, `copied` (first block) and `start` (third block) carry timestamps
|
||||
events.push(if stats && (i < ring || i >= 2 * ring) { api.event_create_timing()? } else { api.event_create()? });
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
@@ -274,12 +310,19 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
let _ = guard.finish();
|
||||
return Err(primary);
|
||||
}
|
||||
let (copied, used) = (events[..ring].to_vec(), events[ring..].to_vec());
|
||||
let (copied, used) = (events[..ring].to_vec(), events[ring..2 * ring].to_vec());
|
||||
let starts = events[2 * ring..].to_vec();
|
||||
let topup = std::env::var("LELEKA_PREFILL_TOPUP").ok().and_then(|v| v.trim().parse::<usize>().ok()).unwrap_or(48);
|
||||
let _ = bytes_per_second;
|
||||
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, bytes_per_second) {
|
||||
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);
|
||||
self.stream_started = Some(std::time::Instant::now());
|
||||
self.stream = Some(stream);
|
||||
self.stream_bank = Some(Rc::clone(bank));
|
||||
self.stream_events = events;
|
||||
@@ -305,6 +348,14 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
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);
|
||||
let stream_ms = self.stream_started.take().map_or(0.0, |t| t.elapsed().as_secs_f64() * 1e3);
|
||||
// drains are context-wide again (the copy stream is idle or the schedule is failed)
|
||||
crate::compute_drain::set_background(0);
|
||||
let flushed = self.context.flush_deferred_frees();
|
||||
let compute = combine(compute, flushed);
|
||||
if copy.is_ok() && compute.is_ok() {
|
||||
stream.report(stream_ms);
|
||||
}
|
||||
drop(stream);
|
||||
let drained = combine(copy, compute);
|
||||
let mut result = combine(stopped, drained);
|
||||
@@ -403,6 +454,9 @@ impl<'ctx> OriginalMmqCopySchedule<'ctx> {
|
||||
if let Some(s) = self.compute.take() {
|
||||
result = combine(result, s.close());
|
||||
}
|
||||
if let Some((_, status)) = self.status_pool.take() {
|
||||
result = combine(result, status.release());
|
||||
}
|
||||
if result.is_err() {
|
||||
self.failed = true;
|
||||
if let Some(api) = self.api.take() {
|
||||
@@ -425,6 +479,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 +646,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.
|
||||
@@ -643,7 +700,14 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
{
|
||||
return Err(Error::BudgetExceeded);
|
||||
}
|
||||
owner.status = Some(context.allocate(charge)?);
|
||||
owner.status = match owner.schedule.status_pool.take() {
|
||||
Some((bytes, buffer)) if bytes >= charge => Some(buffer),
|
||||
Some((_, other)) => {
|
||||
other.release()?;
|
||||
Some(context.allocate(charge.max(512))?)
|
||||
}
|
||||
None => Some(context.allocate(charge.max(512))?),
|
||||
};
|
||||
// The old input quantization/metadata upload used default stream.
|
||||
// Admit that dependency once before starting nonblocking producers.
|
||||
context.synchronize()?;
|
||||
@@ -756,6 +820,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 +845,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 +897,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
Ok(())
|
||||
})?;
|
||||
}
|
||||
}
|
||||
events
|
||||
.copied
|
||||
.as_mut()
|
||||
@@ -816,6 +906,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,21 +926,23 @@ 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 {
|
||||
// the chunk stream's copy of entry k (the compute stream waits for it)
|
||||
let schedule = &mut *self.schedule;
|
||||
let stream = schedule.stream.as_mut().ok_or(Error::ContextPoisoned)?;
|
||||
let at = stream.entry_at(k)?;
|
||||
let (span, bytes) = schedule
|
||||
.compute
|
||||
.as_mut()
|
||||
.ok_or(Error::ContextPoisoned)?
|
||||
.with_enqueue(|s| stream.acquire(k, s))?;
|
||||
[
|
||||
span.checked_subspan(bytes, 0, gu)?,
|
||||
span.checked_subspan(bytes, gu, gu)?,
|
||||
span.checked_subspan(bytes, gu * 2, down)?,
|
||||
span.checked_subspan(bytes, at[0], gu)?,
|
||||
span.checked_subspan(bytes, at[1], gu)?,
|
||||
span.checked_subspan(bytes, at[2], down)?,
|
||||
]
|
||||
} else {
|
||||
let sl = sl.ok_or(Error::InvalidProjectionShape)?;
|
||||
@@ -868,10 +961,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
|
||||
@@ -950,11 +1044,13 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
return Ok(());
|
||||
}
|
||||
// Do not short-circuit the second producer on a first drain failure.
|
||||
let copy = self
|
||||
.schedule
|
||||
.copy
|
||||
.as_ref()
|
||||
.map_or(Ok(()), OriginalGpuStream::synchronize);
|
||||
// With the chunk's expert stream active the copy stream carries the NEXT layers' copies: this layer's own
|
||||
// were waited for on the compute stream (the `copied` events) and its gathers are drained below.
|
||||
let copy = if self.schedule.stream.is_some() {
|
||||
Ok(())
|
||||
} else {
|
||||
self.schedule.copy.as_ref().map_or(Ok(()), OriginalGpuStream::synchronize)
|
||||
};
|
||||
let compute = self
|
||||
.schedule
|
||||
.compute
|
||||
@@ -1011,7 +1107,15 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
|
||||
self.bank.take();
|
||||
}
|
||||
if let Some(status) = self.status.take() {
|
||||
result = combine(result, status.release());
|
||||
if result.is_ok() && self.drained && !self.context.is_poisoned() && !self.schedule.closed {
|
||||
// kept for the next layer (the words are zeroed on the device before each group's use)
|
||||
let charge = status.bytes;
|
||||
if let Some((_, old)) = self.schedule.status_pool.replace((charge, status)) {
|
||||
result = combine(result, old.release());
|
||||
}
|
||||
} else {
|
||||
result = combine(result, status.release());
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
@@ -158,6 +158,11 @@ impl<'arena, 'loan, 'ctx> OriginalDeviceResidual<'arena, 'loan, 'ctx> {
|
||||
}
|
||||
/// Consume the actual retained lease only after Root validated the genuine
|
||||
/// preview identity and draft receipt. No second host row read occurs.
|
||||
/// Look at every deferred guard status now (LELEKA_PREFILL_DEFER_GUARDS; a no-op when nothing is deferred). The runtime calls it
|
||||
/// before it seals a phase whose rows stay on the device.
|
||||
pub fn resolve_guards(&self) -> Result<()> {
|
||||
crate::deferred_status::resolve(self.lease.context())
|
||||
}
|
||||
pub fn finish_after_preview(mut self) -> Result<()> {
|
||||
if self.lease.is_failed() {
|
||||
return Err(Error::ContextPoisoned);
|
||||
@@ -790,8 +795,16 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
return Err(e);
|
||||
}
|
||||
};
|
||||
let mut op = self.context.driver.api.copy_from(status, &zero);
|
||||
if op.is_ok() {
|
||||
// LELEKA_PREFILL_DEFER_GUARDS (experimental, deferred_status.rs): the status words are zeroed and read back on the stream and
|
||||
// looked at later (ring full, or before results leave the device); PLE (stride 10) and the profiling mode stay immediate.
|
||||
let defer = crate::deferred_status::enabled() && stride != 10 && !crate::command_profile::enabled();
|
||||
let status_bytes = t * stride * 4;
|
||||
let mut op = if defer {
|
||||
crate::deferred_status::begin(self.context, status, status_bytes, blas.stream(), self.capacity * 40)
|
||||
} else {
|
||||
self.context.driver.api.copy_from(status, &zero)
|
||||
};
|
||||
if op.is_ok() && !defer {
|
||||
op = self.context.driver.api.synchronize()
|
||||
}
|
||||
// LELEKA_PREFILL_PROFILE_SYNC: each command drained on its own and charged to (tag, position)
|
||||
@@ -843,6 +856,28 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
crate::command_profile::add(self.profile_tag, position + 1, label, started.elapsed());
|
||||
}
|
||||
}
|
||||
if defer {
|
||||
// no host wait: the words and the cross-stream ordering are queued on the stream (deferred_status.rs)
|
||||
let queued = if op.is_ok() {
|
||||
crate::deferred_status::finish(self.context, status, status_bytes, blas.stream(), stride, order, labels)
|
||||
} else {
|
||||
op
|
||||
};
|
||||
let pop = guard.finish();
|
||||
if queued.is_err() || pop.is_err() {
|
||||
self.failed = true;
|
||||
lease.mark_failed();
|
||||
workspace.mark_failed();
|
||||
std::mem::forget((commands, zero, readback));
|
||||
self.context.retain_driver();
|
||||
return combine(queued, pop);
|
||||
}
|
||||
// cuLaunchKernel copies its parameter values at the call and cuBLAS (host pointer mode) reads alpha/beta at the
|
||||
// call, so the argument vectors need not outlive the enqueue (the immediate path keeps them until its drain
|
||||
// as a conservative audit rule; the failure path above still leaks them)
|
||||
drop(commands);
|
||||
return Ok(());
|
||||
}
|
||||
let sync = blas.synchronize();
|
||||
if op.is_ok() && sync.is_ok() {
|
||||
op = self.context.driver.api.copy_to(status, &mut readback)
|
||||
@@ -860,44 +895,15 @@ impl<'ctx> OriginalPromptDevice<'ctx> {
|
||||
return combine(combine(combine(op, sync), all), pop);
|
||||
}
|
||||
combine(combine(combine(op, sync), all), pop)?;
|
||||
// Unknown status is never a usable finite product, including a later
|
||||
// word after an earlier numerical flag. All actual kernels write0/1.
|
||||
for word in readback.as_chunks::<4>().0 {
|
||||
if u32::from_le_bytes(*word) > 1 {
|
||||
// Unknown status is never a usable finite product, including a later word after an earlier numerical flag. All actual
|
||||
// kernels write 0/1. The evaluation is shared with the deferred path (deferred_status::evaluate).
|
||||
if let Err(e) = crate::deferred_status::evaluate(&readback, stride, order, labels) {
|
||||
if matches!(e, Error::InvalidDriverValue(_)) {
|
||||
self.failed = true;
|
||||
lease.mark_failed();
|
||||
self.context.retain_driver();
|
||||
return Err(Error::InvalidDriverValue("Original prompt status"));
|
||||
}
|
||||
}
|
||||
if stride == 10 {
|
||||
// PLE preserves chronological row THEN original ten-stage order.
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
for &stage in order {
|
||||
if u32::from_le_bytes(
|
||||
row[stage * 4..stage * 4 + 4]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidQwenShape)?,
|
||||
) != 0
|
||||
{
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// GR preserves the original stage-first whole-output validation.
|
||||
for &stage in order {
|
||||
for row in readback.chunks_exact(stride * 4) {
|
||||
if u32::from_le_bytes(
|
||||
row[stage * 4..stage * 4 + 4]
|
||||
.try_into()
|
||||
.map_err(|_| Error::InvalidQwenShape)?,
|
||||
) != 0
|
||||
{
|
||||
return Err(Error::NonFiniteMmqOutput(labels[stage]));
|
||||
}
|
||||
}
|
||||
}
|
||||
return Err(e);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@ type EventRecord = unsafe extern "C" fn(Handle, Handle) -> i32;
|
||||
type StreamWait = unsafe extern "C" fn(Handle, Handle, u32) -> i32;
|
||||
type Copy = unsafe extern "C" fn(u64, *const c_void, usize, Handle) -> i32;
|
||||
type Pop = unsafe extern "C" fn(*mut Handle) -> i32;
|
||||
type Elapsed = unsafe extern "C" fn(*mut f32, Handle, Handle) -> i32;
|
||||
fn check(name: &'static str, code: i32) -> Result<()> {
|
||||
if code == 0 {
|
||||
Ok(())
|
||||
@@ -37,6 +38,7 @@ pub(crate) struct Api {
|
||||
copy: Copy,
|
||||
push: HandleCall,
|
||||
pop: Pop,
|
||||
event_elapsed: Elapsed,
|
||||
}
|
||||
impl Drop for Api {
|
||||
fn drop(&mut self) {
|
||||
@@ -127,6 +129,7 @@ impl Api {
|
||||
copy: sym!(c"cuMemcpyHtoDAsync_v2", Copy),
|
||||
push: sym!(c"cuCtxPushCurrent_v2", HandleCall),
|
||||
pop: sym!(c"cuCtxPopCurrent_v2", Pop),
|
||||
event_elapsed: sym!(c"cuEventElapsedTime", Elapsed),
|
||||
};
|
||||
std::mem::forget(opening);
|
||||
Ok(result)
|
||||
@@ -188,6 +191,18 @@ impl Api {
|
||||
Ok(p as usize)
|
||||
}
|
||||
}
|
||||
/// A timing event (LELEKA_PREFILL_COPY_STATS): the same as `event_create` with timestamps enabled.
|
||||
pub(crate) fn event_create_timing(&self) -> Result<usize> {
|
||||
let mut p = std::ptr::null_mut();
|
||||
check("cuEventCreate", unsafe { (self.event_create)(&mut p, 0) })?;
|
||||
if p.is_null() { Err(Error::InvalidDriverValue("cuEventCreate")) } else { Ok(p as usize) }
|
||||
}
|
||||
/// Milliseconds between two completed timing events.
|
||||
pub(crate) fn event_elapsed_ms(&self, start: usize, end: usize) -> Result<f32> {
|
||||
let mut ms = 0f32;
|
||||
check("cuEventElapsedTime", unsafe { (self.event_elapsed)(&mut ms, start as Handle, end as Handle) })?;
|
||||
Ok(ms)
|
||||
}
|
||||
pub(crate) fn event_destroy(&self, event: usize) -> Result<()> {
|
||||
// SAFETY: event created by `event_create`, destroyed once by the owner after it was synchronized.
|
||||
check("cuEventDestroy_v2", unsafe {
|
||||
|
||||
@@ -179,15 +179,17 @@ mod platform {
|
||||
if s.is_null() {
|
||||
return Err(Error::InvalidDriverValue("cuStreamCreate"));
|
||||
}
|
||||
crate::compute_drain::register(s as usize);
|
||||
Ok(s as usize)
|
||||
}
|
||||
pub(crate) fn stream_destroy(&self, s: usize) -> Result<()> {
|
||||
crate::compute_drain::unregister(s);
|
||||
// SAFETY: stream created through this Api; `Stream::close` destroys it once, after `stream_sync` succeeded (host functions included).
|
||||
check("cuStreamDestroy_v2", unsafe { (self.destroy)(s as Handle) })
|
||||
}
|
||||
pub(crate) fn stream_sync(&self, s: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) })
|
||||
crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe { (self.sync)(s as Handle) }))
|
||||
}
|
||||
pub(crate) fn stream_query(&self, s: usize) -> Result<bool> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
@@ -246,9 +248,9 @@ mod platform {
|
||||
}
|
||||
pub(crate) fn event_sync(&self, e: usize) -> Result<()> {
|
||||
// SAFETY: C ABI call on a live handle created through this `Api` and not yet destroyed; no host memory is passed.
|
||||
check("cuEventSynchronize", unsafe {
|
||||
crate::compute_drain::timed(7, || check("cuEventSynchronize", unsafe {
|
||||
(self.event_sync)(e as Handle)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn elapsed(&self, a: usize, b: usize) -> Result<f32> {
|
||||
let mut ms = 0.;
|
||||
|
||||
@@ -50,6 +50,7 @@ pub struct OriginalMoePromptLayer<'program, 'arena, 'loan, 'ctx> {
|
||||
counts: Vec<u32>,
|
||||
source_rows: Vec<u32>,
|
||||
slot_map: Vec<i32>,
|
||||
slot_uploaded: bool,
|
||||
completed_experts: usize,
|
||||
}
|
||||
enum Command {
|
||||
@@ -571,6 +572,7 @@ impl<'ctx> OriginalMoePromptDevice<'ctx> {
|
||||
counts: actual_counts,
|
||||
source_rows,
|
||||
slot_map,
|
||||
slot_uploaded: false,
|
||||
completed_experts: 0,
|
||||
})
|
||||
}
|
||||
@@ -668,6 +670,7 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
}
|
||||
self.upload_slot_table()?;
|
||||
let mut program = workspace.prepare_original_expert_layer_device(
|
||||
&self.read,
|
||||
&self.counts,
|
||||
@@ -724,12 +727,12 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
self.completed_experts = self.order.len();
|
||||
Ok(())
|
||||
}
|
||||
pub fn finish(
|
||||
self,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
) -> Result<OriginalDeviceBlock<'arena, 'loan, 'ctx>> {
|
||||
if self.completed_experts != self.order.len() || self.order.is_empty() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
/// The routed slot table's upload (read only by the combine kernel). The copy ring does it BEFORE its expert
|
||||
/// copies, because after the ring the chunk's expert stream has the host-to-device copy engine busy and a
|
||||
/// 327 KB upload then waits for several milliseconds behind it. Same bytes, same completion fence.
|
||||
fn upload_slot_table(&mut self) -> Result<()> {
|
||||
if self.slot_uploaded {
|
||||
return Ok(());
|
||||
}
|
||||
let rows = self.read.lease();
|
||||
let t = rows.rows();
|
||||
@@ -750,6 +753,21 @@ impl<'program, 'arena, 'loan, 'ctx> OriginalMoePromptLayer<'program, 'arena, 'lo
|
||||
return combine(combine(copy, wait), pop).map(|()| unreachable!());
|
||||
}
|
||||
combine(combine(copy, wait), pop)?;
|
||||
self.slot_uploaded = true;
|
||||
Ok(())
|
||||
}
|
||||
pub fn finish(
|
||||
mut self,
|
||||
workspace: &mut NativeBatchWorkspace<'ctx>,
|
||||
) -> Result<OriginalDeviceBlock<'arena, 'loan, 'ctx>> {
|
||||
if self.completed_experts != self.order.len() || self.order.is_empty() {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
}
|
||||
self.upload_slot_table()?;
|
||||
let rows = self.read.lease();
|
||||
let t = rows.rows();
|
||||
let (slot, extent) = rows.span(PrefillPhase::Moe, "slot_dev")?;
|
||||
let slot = slot.checked_subspan(extent, 0, t * 10 * 4)?;
|
||||
let bo = common(rows, S::Block, 2560 * 4)?;
|
||||
let mut commands = Vec::new();
|
||||
kernel(
|
||||
|
||||
@@ -252,6 +252,11 @@ impl<'arena, 'loan, 'ctx> OriginalPromptRows<'arena, 'loan, 'ctx> {
|
||||
/// required for source-equivalent stream ordering at the caller seam.
|
||||
pub(crate) fn drain(&mut self) -> Result<()> {
|
||||
if self.drained { return Ok(()); }
|
||||
// deferred guard words (LELEKA_PREFILL_DEFER_GUARDS) are looked at before anything leaves the device
|
||||
if let Err(e) = crate::deferred_status::resolve(self.arena.context) {
|
||||
self.arena.failed = true;
|
||||
return Err(e);
|
||||
}
|
||||
let result = self.arena.context.synchronize();
|
||||
if result.is_err() { self.arena.failed = true; }
|
||||
self.drained = result.is_ok();
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -168,6 +168,7 @@ mod enabled {
|
||||
return Err(Error::InvalidDriverValue("cuStreamCreate"));
|
||||
}
|
||||
owner.stream = Some(stream as usize);
|
||||
crate::compute_drain::register(stream as usize);
|
||||
let mut h = std::ptr::null_mut();
|
||||
// SAFETY: current owner Context, valid writable output.
|
||||
check("cublasCreate_v2", unsafe { create(&mut h) })?;
|
||||
@@ -379,9 +380,9 @@ mod enabled {
|
||||
}
|
||||
pub(crate) fn synchronize(&self) -> Result<()> {
|
||||
// SAFETY: actual private stream remains owned through this call.
|
||||
check("cuStreamSynchronize", unsafe {
|
||||
crate::compute_drain::timed(7, || check("cuStreamSynchronize", unsafe {
|
||||
(self.sync)(self.stream() as *mut c_void)
|
||||
})
|
||||
}))
|
||||
}
|
||||
pub(crate) fn close(mut self) -> Result<()> {
|
||||
self.close_inner()
|
||||
@@ -395,6 +396,7 @@ mod enabled {
|
||||
});
|
||||
}
|
||||
if let Some(s) = self.stream.take() {
|
||||
crate::compute_drain::unregister(s);
|
||||
// SAFETY: actual created stream, no undisclosed outstanding commands.
|
||||
result = combine(
|
||||
result,
|
||||
|
||||
@@ -340,7 +340,7 @@ impl<'ctx> QsaPromptAttention<'ctx> {
|
||||
Arg::I32(end as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_in(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?;
|
||||
self.run_in(variants, w, guard_ix, [guard_grid(t), 1, 1], 256, 0, guard)?;
|
||||
let flags = self.flags()?;
|
||||
if flags & 2 != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -369,7 +369,7 @@ impl<'ctx> QsaPromptAttention<'ctx> {
|
||||
Arg::I32((t * 6144) as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_in(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?;
|
||||
self.run_in(variants, w, scan_ix, [guard_grid(t), 1, 1], 256, 0, scan)?;
|
||||
if self.flags()? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
|
||||
}
|
||||
@@ -479,3 +479,12 @@ mod device_attention;
|
||||
mod resident_attention;
|
||||
|
||||
pub use resident_attention::OriginalQsaResidentAttention;
|
||||
|
||||
/// Grid of the prompt attention's input and output guards (claude/ledger). Both are grid-stride loops over `t * 6144` floats (and
|
||||
/// the id-order scan over `t` rows); the literal 64 blocks left 100+ SMs idle and cost 1.8 + 1.0 ms per QSA layer of an 8192-token
|
||||
/// chunk. Any grid gives the same status words (an OR of the same per-element conditions); `LELEKA_PREFILL_GUARD_GRID=64` restores it.
|
||||
pub(crate) fn guard_grid(t: usize) -> u32 {
|
||||
static FIXED: std::sync::OnceLock<Option<u32>> = std::sync::OnceLock::new();
|
||||
let fixed = *FIXED.get_or_init(|| std::env::var("LELEKA_PREFILL_GUARD_GRID").ok().and_then(|v| v.parse().ok()));
|
||||
fixed.unwrap_or_else(|| ((t * 6144).div_ceil(256 * 4)).clamp(64, 2048) as u32)
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{
|
||||
Arg::I32(end as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_in(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?;
|
||||
self.run_in(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?;
|
||||
let flags = self.flags()?;
|
||||
if flags & 2 != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -75,7 +75,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{
|
||||
Arg::I32((t * 6144) as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_in(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?;
|
||||
self.run_in(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?;
|
||||
if self.flags()? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{
|
||||
Arg::I32(end as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_resident(variants, w, guard_ix, [64, 1, 1], 256, 0, guard)?;
|
||||
self.run_resident(variants, w, guard_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, guard)?;
|
||||
let flags = self.flags()?;
|
||||
if flags & 2 != 0 {
|
||||
return Err(Error::InvalidQwenShape);
|
||||
@@ -74,7 +74,7 @@ impl<'ctx> QsaPromptAttention<'ctx>{
|
||||
Arg::I32((t * 6144) as i32),
|
||||
Arg::U64(status),
|
||||
])?;
|
||||
self.run_resident(variants, w, scan_ix, [64, 1, 1], 256, 0, scan)?;
|
||||
self.run_resident(variants, w, scan_ix, [crate::qsa_prompt_attention::guard_grid(t), 1, 1], 256, 0, scan)?;
|
||||
if self.flags()? != 0 {
|
||||
return Err(Error::NonFiniteMmqOutput("qsa-prompt-attention"));
|
||||
}
|
||||
|
||||
@@ -488,10 +488,24 @@ fn original_serve_long_context_streamed_kv_smoke() {
|
||||
Some(text.trim().split(',').map(|t| t.trim().parse().expect("forced token id")).collect())
|
||||
});
|
||||
let max_new = forced_answer.as_ref().map_or(max_new, |a| a.len());
|
||||
// LELEKA_PREFILL_STREAM_SEQ=1,0,1,0: the expert stream per pass (paired A/B inside one process)
|
||||
let stream_seq: Vec<(i8, usize)> = env::var("LELEKA_PREFILL_STREAM_SEQ")
|
||||
.map(|v| v.split(',').filter_map(|t| {
|
||||
let mut parts = t.trim().splitn(2, ':');
|
||||
Some((parts.next()?.parse().ok()?, parts.next().and_then(|d| d.parse().ok()).unwrap_or(0)))
|
||||
}).collect()).unwrap_or_default();
|
||||
for pass in 0..repeat {
|
||||
crate::qwen_forward::quality_force::set(forced_answer.as_ref().map(|answer| {
|
||||
prompt.iter().map(|&t| t as i32).chain(answer.iter().copied()).collect()
|
||||
}));
|
||||
if !stream_seq.is_empty() {
|
||||
let (v, depth) = stream_seq[pass % stream_seq.len()];
|
||||
leleka_cuda_driver::compute_drain::set_issue_depth(depth);
|
||||
// bit 0: the expert stream, bit 1: all-zero uploads as memsets while it is in flight
|
||||
crate::qwen_forward::moe_weight_cache::PREFILL_STREAM_OVERRIDE.store((v & 1) as i8, std::sync::atomic::Ordering::Relaxed);
|
||||
leleka_cuda_driver::compute_drain::set_zero_memset(v & 2 != 0);
|
||||
eprintln!("long-smoke pass={pass} stream_override={v} depth={depth}");
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
let mut tokens = Vec::new();
|
||||
let outcome = stack
|
||||
|
||||
@@ -9,24 +9,27 @@ use leleka_cuda_driver::{GdnNativeFormat, NativeBatchWorkspace,
|
||||
use leleka_model_format::qwen4exp::ResidentExpertBankSpan;
|
||||
use crate::qwen_forward::prefill_profile::{self as prof, Stage as PStage};
|
||||
|
||||
/// EXPERIMENTAL, off by default: prefill.cpp `stream_all` order (`begin_prompt_stream`) with next-MoE copies
|
||||
/// queued under the GDN kernel batches, for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows (1024) over a
|
||||
/// registered bank, with `LELEKA_PREFILL_STREAM=1`. Measured (job 0708): the copies moved out of the ring into
|
||||
/// the GDN windows instead of overlapping them (8192-token chunks 2,676 vs 2,730 ms, 2048-token chunks 1,755 vs
|
||||
/// 1,410 ms), so the per-layer copy ring stays the default.
|
||||
/// `LELEKA_PREFILL_PCIE_GBPS` (default 45) sizes the copies queued under a GDN layer's kernels.
|
||||
/// prefill.cpp `stream_all` order (`begin_prompt_stream`): for chunks of at least `STRATA_PREFILL_STREAM_MIN` rows
|
||||
/// (default 4096: it copies every expert of every layer, while the per-layer ring copies only the routed ones, about
|
||||
/// 60% of them at 2048 rows, so a 2048-row chunk is DMA-bound and 20% slower with the stream; ~100% at 8192) over a registered bank every layer's experts are copied by an issuer thread with a bounded copy queue,
|
||||
/// overlapped with the mixers; the compute path's drains are stream-scoped meanwhile. `LELEKA_PREFILL_STREAM=0`
|
||||
/// keeps the per-layer copy ring. Measured (docs/prefill-throughput.md, jobs 956-965): 16,000 tokens at chunk 8192
|
||||
/// +13..27% prefill tok/s over the per-layer ring, identical greedy ids.
|
||||
fn prompt_stream_settings() -> Option<(usize, f64)> {
|
||||
static SETTINGS: std::sync::OnceLock<Option<(usize, f64)>> = std::sync::OnceLock::new();
|
||||
*SETTINGS.get_or_init(|| {
|
||||
if !std::env::var("LELEKA_PREFILL_STREAM").is_ok_and(|v| v == "1") {
|
||||
return None;
|
||||
}
|
||||
let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default);
|
||||
let gbps = std::env::var("LELEKA_PREFILL_PCIE_GBPS").ok().and_then(|v| v.trim().parse::<f64>().ok())
|
||||
.filter(|g| g.is_finite() && *g > 1.0).unwrap_or(45.0);
|
||||
Some((number("STRATA_PREFILL_STREAM_MIN", 1024), gbps * 1e9))
|
||||
})
|
||||
use std::sync::atomic::Ordering;
|
||||
let on = match PREFILL_STREAM_OVERRIDE.load(Ordering::Relaxed) {
|
||||
0 => false,
|
||||
1 => true,
|
||||
_ => std::env::var("LELEKA_PREFILL_STREAM").map_or(true, |v| v != "0"),
|
||||
};
|
||||
if !on {
|
||||
return None;
|
||||
}
|
||||
let number = |name: &str, default: usize| std::env::var(name).ok().and_then(|v| v.trim().parse().ok()).unwrap_or(default);
|
||||
Some((number("STRATA_PREFILL_STREAM_MIN", 4096), 45e9))
|
||||
}
|
||||
/// Test harness switch for in-process paired A/B (`LELEKA_PREFILL_STREAM_SEQ`): -1 = the environment, 0 off, 1 on.
|
||||
pub static PREFILL_STREAM_OVERRIDE: std::sync::atomic::AtomicI8 = std::sync::atomic::AtomicI8::new(-1);
|
||||
|
||||
fn native_format(key: MoeWeightDescriptor) -> Result<GdnNativeFormat> {
|
||||
match key.raw_kind {
|
||||
|
||||
@@ -35,6 +35,8 @@ mod cache_strata_adaptive;
|
||||
#[path = "cache_original_prompt.rs"]
|
||||
mod cache_original_prompt;
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
pub(crate) use cache_original_prompt::PREFILL_STREAM_OVERRIDE;
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
#[path = "cache_original_verify.rs"]
|
||||
mod cache_original_verify;
|
||||
#[cfg(all(target_os = "linux", target_arch = "x86_64"))]
|
||||
|
||||
@@ -126,6 +126,7 @@ impl<'source,'arena,'loan,'ctx> PromptDeviceRows<'source,'arena,'loan,'ctx>{
|
||||
if last.input.position().get().checked_add(1)!=Some(txn.end_position()){return Err(Error::IdentityMismatch)}
|
||||
let known_next=txn.known_prompt_next()?.ok_or(Error::IdentityMismatch)?;
|
||||
let lease_identity=self.device.lease_identity();
|
||||
self.device.resolve_guards().map_err(micro_driver_error)?;
|
||||
phase.seal_final()?;
|
||||
Ok(PromptDeviceFinal{binding:binding.identity(),phase,token:last.input.token(),position:last.input.position(),
|
||||
product:FinalProduct::DeviceConditioning{known_next},lease_identity})
|
||||
|
||||
@@ -248,3 +248,101 @@ equal job 0708's reference of the same chunking:
|
||||
EXPERIMENTAL and off. Defaults of the other four switches are on. What remains: the expert DMA (claude/prefill-overlap), the GDN
|
||||
recurrence (155 ms, a 128-step FMA chain per token that cannot be reordered without changing bits), cuBLAS GEMMs at the tensor-core
|
||||
limit, per-layer host drains.
|
||||
|
||||
## Expert stream overlap (branch `claude/prefill-overlap`, jobs 950-968, RTX 5090)
|
||||
|
||||
Goal: hide the expert DMA of an 8192-token chunk (24,576 experts = 50.3 GB, i.e. every expert of all 48 layers at
|
||||
2.05 MB; a 16,000-token prompt moves it twice) under the mixers. The per-layer ring paid it layer by layer (moe.ring
|
||||
~1,110 ms of a 2,140 ms chunk after the prefill-kernels merge, 3,780 tok/s on 16,000 tokens).
|
||||
|
||||
### What blocked the overlap (and what was removed)
|
||||
|
||||
1. Every compute producer drained with `cuCtxSynchronize`, which also waits for the copy stream. All of them go through
|
||||
`ffi::Api::synchronize`; while a chunk's expert stream runs (`compute_drain`, background stream registered by
|
||||
`begin_prompt_stream`) it now waits for the legacy default stream and every registered compute stream except the
|
||||
copy stream (all four stream creators register: Blas, Original schedule, owned copy, swap). Outside a chunk stream
|
||||
it is the unchanged context-wide drain. The ring's own layer drain no longer syncs the copy stream either.
|
||||
2. `cuMemFree` synchronizes the whole device (per-layer GDN/QSA/PLE scratch, 6 MB per GDN layer): frees are queued
|
||||
on the `Context` while the stream runs and executed when it ends (or past `LELEKA_PREFILL_DEFER_FREE_MIB`, 512);
|
||||
the ring's per-layer status buffer is pooled.
|
||||
3. **The host-to-device copy engine is a FIFO.** Any other transfer of the compute path (synchronous H2D uploads,
|
||||
D2H status readbacks) waits for all expert copies queued before it: model-free probe, job 955
|
||||
(`scripts/h2d_copy_engine_probe.cu`): a 327 KB `cudaMemcpy` waits 0.13 ms behind 2 queued experts, 0.42 ms behind 8,
|
||||
1.6 ms behind 32, 5.7 ms behind 128+ (= outstanding bytes / 36 GB/s); memsets, kernels and D2D copies do not queue.
|
||||
With a deep queue the waits only moved from the ring into `moe.finish` (372 ms) and `inject` (650 ms) (job 953:
|
||||
`PREFILL-SITE`/`PREFILL-STALL` call-site histograms). Fixes: an issuer thread (the Original's D-5) keeps only
|
||||
`LELEKA_PREFILL_DEPTH` (default 2) entries outstanding on the copy stream, event-query paced, the compute thread
|
||||
only waits until an entry is enqueued before ordering its stream after it; all-zero uploads become device memsets
|
||||
while the stream runs (`LELEKA_PREFILL_ZERO_MEMSET=0` disables); the routed slot table (327 KB, non-zero) is
|
||||
uploaded before the ring instead of after it.
|
||||
4. Not done (open, see below): ~1,100 small blocking H2D/D2H calls per chunk remain (status readbacks, shared-layer
|
||||
weight uploads, GDN state staging, QSA tables); each costs up to the queue depth in latency and keeps the depth at 2.
|
||||
|
||||
The stream copies *every* expert of every layer (prefill.cpp `stream_all`), while the per-layer ring copies only the
|
||||
routed ones: at 2,048 rows only ~60% of the experts are routed, so the stream is 20% slower there (jobs 961/962:
|
||||
1,330 vs 1,670 tok/s) and nearly free at 8,192 (~100% routed). It therefore starts at 4,096 rows
|
||||
(`STRATA_PREFILL_STREAM_MIN`); `LELEKA_PREFILL_STREAM=0` restores the per-layer ring everywhere.
|
||||
|
||||
### Results (paired passes alternating inside one process, same binary and prompts, greedy 16 tokens)
|
||||
|
||||
| config | prompt | per-layer ring | expert stream | notes |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| chunk 8192, tier off, depth 16 (job 960) | 8,000 | 3,764-3,784 | 4,367-4,406 | +16% |
|
||||
| chunk 8192, tier off, depth 16 (job 960) | 16,000 | 3,780 | 4,275-4,358 | +13% |
|
||||
| chunk 8192, tier off, depth sweep (job 958) | 16,000 | 3,795-3,799 | 2: 4,805-4,811; 4: 4,163-4,181; 8: 4,227-4,293; 16: 4,300-4,350; 32: 4,199 | depth 2 best |
|
||||
| chunk 8192, tier off, depth 2, 12 passes (job 963) | 16,000 | - | 4,789-4,851 | +27% |
|
||||
| chunk 8192, tier on (job 962, depth 16) | 8,000 / 16,000 | 3,573 / 3,625-3,686 | 4,499-4,528 / 4,631-4,654 | +26% |
|
||||
| chunk 2048 (jobs 961/962, stream forced) | 8,000 / 16,000 | 1,670-1,718 / 1,659-1,711 | 1,325-1,380 / 1,324-1,384 | -20%: off below 4096 rows |
|
||||
|
||||
Greedy ids: identical between the two modes on every paired pass (8000 and 16000, chunk 8192 and 2048, tier off and
|
||||
on) and equal to job 0708's ids for the same chunking. With the tier on the 16000-token answer at chunk 8192 is a
|
||||
near-tie that the unmodified head already flips between passes (one OFF pass of job 962 answered `271,248069` instead
|
||||
of `198`); the stream's passes all gave `198`. Race hunt (job 963): 36 consecutive full 16,000-token prefills
|
||||
(12 plain, 12 with pseudo-random host delays between the copy enqueues `LELEKA_PREFILL_STREAM_JITTER`, 12 with the
|
||||
same jitter at depth 1): identical ids, no `CudaExecution`. `compute-sanitizer` racecheck/synccheck only see
|
||||
shared-memory hazards inside a kernel, which this change does not touch; the cross-stream ordering is by events
|
||||
(`copied`/`used` per ring slot), and the repeated runs under jitter are the evidence.
|
||||
|
||||
### Copy rate, bytes per chunk, tier
|
||||
|
||||
Every 8192-row chunk streams 24,576 entries x 3 copies of 682 KB = 50.3 GB (job 950+ `PREFILL-COPY`: per-entry event
|
||||
timing 35.5-36.5 GB/s, independent of queue depth and of concurrent kernels; `cudaHostAlloc` memory in the model-free
|
||||
probe 40.3-40.9 GB/s for 3x682 KB, 1x2 MB, depth 4-64, 1-2 streams; the registered bank is ~12% slower). With the stream
|
||||
the DMA is busy ~77% of the chunk (stream window 1.6-1.8 s for a 1.42 s copy floor at 35.5 GB/s). The VRAM expert tier
|
||||
(2048 slots per layer, 1891 lent) removes only ~0.6% of the entries at chunk 8192 (24,419 vs 24,576) and 4.7% at 2048
|
||||
(23,415): prefill with the tier streams essentially the same bytes. Chunk sizes above 8192 are not possible: the prompt
|
||||
arena, GEMM and MMQ shape checks are capped at 8192 rows (30+ sites, 81920-row MMQ layouts); bytes per token fall 4x
|
||||
from 2048 to 8192 as the per-chunk traffic is constant.
|
||||
|
||||
### Late chunks (180,000-token prompt, job 915/957)
|
||||
|
||||
Per-chunk time grows from 2,120 ms (position 0) to 2,480 ms (position 172k) on the unmodified head, of which QSA
|
||||
250 -> 537 ms and moe.ring 1,117 -> 1,200 ms; GDN is flat. Per-command profile (job 957, 8 -> 90k -> 164k):
|
||||
`qsa index+norm+rope run` 49 -> 167 -> 269 ms (the indexer scores every earlier block: ~1.4 ms per 1k positions per
|
||||
chunk), `kv append` 15 -> 36 -> 54 ms, `attend` flat 124 ms, proj Q/out flat. The indexer is the stage that grows with
|
||||
position; its kernels were not touched here.
|
||||
|
||||
### Final defaults and the 180k prompt (jobs 965-968)
|
||||
|
||||
- Queue depth (job 965, 16,000 tokens @8192, same process): depth 1 3,343; **2 4,805-4,821**; 3 4,238-4,310 tok/s
|
||||
(per-layer ring 3,790); depth 2 is the default. The stream runs one expert (2 MB) ahead of its consumer, so the
|
||||
copy engine is never idle for long but any other transfer waits at most ~2 MB / 36 GB/s.
|
||||
- Shipped defaults vs `LELEKA_PREFILL_STREAM=0`, separate processes (job 966, second and third pass): chunk 8192
|
||||
8,000 tokens 4,851 / 4,844 vs 3,760 / 3,766 tok/s, 16,000 tokens 4,820 / 4,816 vs 3,796 / 3,778; chunk 2048
|
||||
identical (1,670 vs 1,671 / 1,656 vs 1,655: the stream is off below 4096 rows). All greedy ids equal.
|
||||
- Chunk 4096 (job 967): stream = ring (2,598-2,601 vs 2,583-2,584 for 8,000 tokens; 2,593-2,598 vs 2,598 for 16,000),
|
||||
ids equal: copying every expert costs what the overlap saves.
|
||||
- 180,000 tokens, tier on, chunk 8192 (job 968, passes alternating in one process): stream 40.9 s / 39.9 s
|
||||
(4,397 / 4,508 tok/s) vs ring 51.0 s (3,532 tok/s) = +25..28%; identical ids. Per chunk (position 8k / 82k / 164k):
|
||||
stream 1,680 / 1,773 / 1,905 ms (qsa 272 / 398 / 530, moe.ring 539 / 582 / 581, gdn 464, inject 85) vs ring
|
||||
2,080 / 2,320 / 2,473 ms (moe.ring 1,057 / 1,169 / 1,186). The unmodified Original needs 39.4 s for the same prompt.
|
||||
What still grows with position is the QSA indexer (above) and, slightly, the ring.
|
||||
|
||||
### Merged copy path
|
||||
|
||||
`claude/ledger`'s page-aligned expert supersets (+12% on the ring: DMA 36 -> 47 GB/s) are merged into the stream:
|
||||
stream entries carry the 4 KiB-aligned supersets, their slot offsets and the offsets of the exact pieces, and the
|
||||
gather reads the exact pieces there (`LELEKA_PREFILL_ALIGNED_COPY=0` turns both paths off). The schedule agent's
|
||||
deferred guard status (`LELEKA_PREFILL_DEFER_GUARDS=1`, experimental, default off; +1.6% in its A/B) is merged.
|
||||
Open: runs of consecutive experts per role in one copy / `cuMemcpyBatchAsync` (50-51 GB/s in the roofline probes), the
|
||||
~1,100 remaining blocking small copies per chunk, QSA indexer growth with position.
|
||||
|
||||
@@ -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(©, 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;
|
||||
}
|
||||
@@ -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(©, 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;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the leleka-runtime test binary of THIS worktree in WSL (never on the server) and print its path.
|
||||
# scripts/profile/build_rt.sh TAG (run from Windows Git Bash in the worktree; needs WSL distro "Ubuntu")
|
||||
# Result: WSL ~/ledger-bin/rt-TAG. Copy to the server with: scp (see docs/ledger.md).
|
||||
set -euo pipefail
|
||||
tag=${1:?tag}
|
||||
root=$(git rev-parse --show-toplevel)
|
||||
tmp=$(mktemp -d)
|
||||
git -C "$root" -c core.autocrlf=false ls-files -z | tar -C "$root" --null -T - -cf "$tmp/wt.tar"
|
||||
win=$(cygpath -w "$tmp/wt.tar" | sed 's#\\#/#g; s#^\([A-Za-z]\):#/mnt/\L\1#')
|
||||
wsl -d Ubuntu -e bash -lc "
|
||||
set -e
|
||||
source ~/.cargo/env
|
||||
export PATH=\$HOME/cuda-toolkits/13.2.2/bin:\$HOME/.cargo/bin:/usr/local/bin:/usr/bin:/bin
|
||||
rm -rf ~/ledger-src && mkdir -p ~/ledger-src ~/ledger-bin && tar -xf '$win' -C ~/ledger-src
|
||||
cd ~/ledger-src
|
||||
export CARGO_TARGET_DIR=\$HOME/ledger-target
|
||||
nice -n 10 cargo test --no-run --locked --release -p leleka-runtime --lib 2>&1 | tee ~/ledger-build-$tag.log | grep -E 'Executable|^error|warning: unused' | tail -5
|
||||
exe=\$(grep -o 'target/release/deps/leleka_runtime-[0-9a-f]*' ~/ledger-build-$tag.log | tail -1)
|
||||
cp \$CARGO_TARGET_DIR/\${exe#target/} ~/ledger-bin/rt-$tag
|
||||
ls -la ~/ledger-bin/rt-$tag
|
||||
"
|
||||
rm -rf "$tmp"
|
||||
@@ -0,0 +1,113 @@
|
||||
// Model-free probe (claude/ledger): sustained host-to-device DMA rate of the expert stream by SOURCE MEMORY KIND and COPY SHAPE.
|
||||
// The ledger found the port's ring at ~37 GB/s (3 copies of 0.5-0.9 MB from the registered bank) while the Original's ring runs at
|
||||
// ~50 GB/s (1 copy of ~2.1 MB from its arena). This isolates which property matters.
|
||||
// nvcc -O2 -arch=sm_120 h2d_src_probe.cu -o h2d_src_probe ; ./h2d_src_probe [shard.gguf]
|
||||
// Source kinds: hostalloc | anon4k+register(0) | anon4k+register(PORTABLE) | anon4k+register(DEVICEMAP, the port's bank) |
|
||||
// anon+MADV_HUGEPAGE+register(DEVICEMAP) | file mapping (MAP_SHARED, PROT_READ) + register(READ_ONLY).
|
||||
// Shapes (per "expert" of ENTRY bytes): 3 x ENTRY/3 from three role-major regions (the port) | 1 x ENTRY contiguous (the Original) |
|
||||
// 1 x 2 MiB 4K-aligned | 1 x 8 MiB.
|
||||
#include <cuda_runtime.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#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 uint8_t* anon(size_t bytes, bool thp) {
|
||||
void* p = mmap(nullptr, bytes + (2 << 20), PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
|
||||
if (p == MAP_FAILED) { perror("mmap"); exit(1); }
|
||||
uint8_t* a = (uint8_t*)(((size_t)p + (2 << 20) - 1) & ~((size_t)(2 << 20) - 1));
|
||||
if (thp) madvise(a, bytes, MADV_HUGEPAGE);
|
||||
memset(a, 0x5a, bytes);
|
||||
return a;
|
||||
}
|
||||
|
||||
// run: copy `n` entries, each `pieces` copies of ENTRY/pieces bytes, cycling over `regions` role-major regions (pieces==3) or one region
|
||||
static double run(uint8_t* base, size_t region_bytes, size_t entry, int pieces, bool role_major, size_t stride, uint8_t* ring, int slots,
|
||||
cudaStream_t s, int n, int depth) {
|
||||
std::vector<cudaEvent_t> ev(depth + 1);
|
||||
for (auto& e : ev) CK(cudaEventCreateWithFlags(&e, cudaEventDisableTiming));
|
||||
cudaEvent_t a, b; CK(cudaEventCreate(&a)); CK(cudaEventCreate(&b));
|
||||
size_t piece = entry / pieces;
|
||||
size_t unit = role_major ? stride : stride * pieces; // distance between consecutive experts inside one region
|
||||
size_t per_region = region_bytes / (role_major ? pieces : 1) / unit;
|
||||
CK(cudaEventRecord(a, s));
|
||||
for (int k = 0; k < n; ++k) {
|
||||
int slot = k % slots;
|
||||
if (k >= depth) CK(cudaStreamWaitEvent(s, ev[(k - depth) % (depth + 1)], 0));
|
||||
for (int p = 0; p < pieces; ++p) {
|
||||
const uint8_t* src;
|
||||
if (role_major) src = base + (size_t)p * (region_bytes / pieces) + (size_t)(k % per_region) * stride;
|
||||
else src = base + (size_t)(k % per_region) * unit + (size_t)p * stride;
|
||||
CK(cudaMemcpyAsync(ring + (size_t)slot * entry + p * piece, src, piece, cudaMemcpyHostToDevice, s));
|
||||
}
|
||||
CK(cudaEventRecord(ev[k % (depth + 1)], s));
|
||||
if (k >= depth + 2) CK(cudaEventSynchronize(ev[(k - depth - 2) % (depth + 1)]));
|
||||
}
|
||||
CK(cudaEventRecord(b, s)); CK(cudaEventSynchronize(b));
|
||||
float ms; CK(cudaEventElapsedTime(&ms, a, b));
|
||||
for (auto& e : ev) cudaEventDestroy(e);
|
||||
cudaEventDestroy(a); cudaEventDestroy(b);
|
||||
return (double)n * entry / (ms * 1e6);
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const size_t ENTRY = 2046000;
|
||||
const size_t REGION = 16ull << 30; // 16 GiB per source kind: the footprint matters (IOMMU/IOTLB), the real bank is ~50 GB
|
||||
CK(cudaSetDevice(0));
|
||||
cudaStream_t s; CK(cudaStreamCreateWithFlags(&s, cudaStreamNonBlocking));
|
||||
const int SLOTS = 64;
|
||||
uint8_t* ring; CK(cudaMalloc((void**)&ring, (9ull << 20) * SLOTS));
|
||||
struct Shape { const char* name; size_t entry; int pieces; bool role_major; size_t stride; };
|
||||
std::vector<Shape> shapes = {{"3 x 682000 role-major (port)", ENTRY, 3, true, ENTRY / 3},
|
||||
{"3 x 682000 role-major, 4K-aligned stride", ENTRY, 3, true, 684032},
|
||||
{"1 x 2046000 contiguous (Original)", ENTRY, 1, false, ENTRY},
|
||||
{"1 x 2046000, 4K-aligned stride", ENTRY, 1, false, 2048000 + 4096 - 2048000 % 4096},
|
||||
{"1 x 2 MiB aligned", 2u << 20, 1, false, 2u << 20}, {"1 x 8 MiB", 8u << 20, 1, false, 8u << 20}};
|
||||
struct Kind { const char* name; int id; };
|
||||
std::vector<Kind> kinds = {{"cudaHostAlloc", 0}, {"anon 4K + register(0)", 1}, {"anon 4K + register(PORTABLE)", 2},
|
||||
{"anon 4K + register(DEVICEMAP) (port bank)", 3}, {"anon THP + register(DEVICEMAP)", 4}, {"file map RO + register(READ_ONLY)", 5}};
|
||||
for (auto& kd : kinds) {
|
||||
uint8_t* base = nullptr; size_t bytes = REGION; void* map = nullptr; size_t map_bytes = 0; int fd = -1;
|
||||
if (kd.id == 0) { CK(cudaHostAlloc((void**)&base, bytes, cudaHostAllocDefault)); memset(base, 0x5a, bytes); }
|
||||
else if (kd.id >= 1 && kd.id <= 4) {
|
||||
base = anon(bytes, kd.id == 4);
|
||||
unsigned flags = kd.id == 1 ? 0 : kd.id == 2 ? cudaHostRegisterPortable : cudaHostRegisterMapped;
|
||||
CK(cudaHostRegister(base, bytes, flags));
|
||||
} else {
|
||||
if (argc < 2) { printf("%-44s skipped (no shard path)\n", kd.name); continue; }
|
||||
fd = open(argv[1], O_RDONLY);
|
||||
struct stat st; fstat(fd, &st);
|
||||
map_bytes = (size_t)st.st_size < bytes ? st.st_size : bytes;
|
||||
map = mmap(nullptr, map_bytes, PROT_READ, MAP_SHARED, fd, 0);
|
||||
if (map == MAP_FAILED) { printf("%-44s mmap failed\n", kd.name); continue; }
|
||||
base = (uint8_t*)map; bytes = map_bytes;
|
||||
volatile uint8_t sink = 0;
|
||||
for (size_t i = 0; i < bytes; i += 4096) sink += base[i]; // fault the pages in
|
||||
cudaError_t e = cudaHostRegister(base, bytes, cudaHostRegisterReadOnly);
|
||||
if (e != cudaSuccess) { printf("%-44s register failed: %s\n", kd.name, cudaGetErrorString(e)); munmap(map, map_bytes); continue; }
|
||||
}
|
||||
for (auto& sh : shapes) {
|
||||
double best = 0, sum = 0;
|
||||
for (int rep = 0; rep < 3; ++rep) {
|
||||
double r = run(base, bytes, sh.entry, sh.pieces, sh.role_major, sh.stride, ring, SLOTS, s, 6000, 16);
|
||||
if (r > best) best = r;
|
||||
sum += r;
|
||||
}
|
||||
printf("%-44s %-36s %6.1f GB/s (best %6.1f)\n", kd.name, sh.name, sum / 3, best);
|
||||
fflush(stdout);
|
||||
}
|
||||
if (kd.id == 0) cudaFreeHost(base);
|
||||
else if (kd.id <= 4) { cudaHostUnregister(base); }
|
||||
else { cudaHostUnregister(base); munmap(map, map_bytes); close(fd); }
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# claude/ledger: model-free probe, H2D DMA rate by source memory kind and copy shape (the port's 3 x 0.68 MB role-major pieces from the registered bank
|
||||
# vs the Original's single ~2 MB blob from its arena). GPU otherwise idle (holder job).
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
header 2>/dev/null | head -3
|
||||
nvidia-smi --query-gpu=pcie.link.gen.current,pcie.link.width.current,clocks.sm,clocks.mem --format=csv,noheader
|
||||
timeout 600 $LD/bin/h2d_src_probe $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf 2>&1
|
||||
echo "rc=$?"; date -u +%FT%TZ
|
||||
# the same probe question inside the port: the bank's anonymous Vecs with transparent huge pages (LELEKA_BANK_THP=on), traced like port-16k-off
|
||||
mem_ok 30 && port_long port-16k-thp 16000 2 PREFILL-PROFILE 2 9 LELEKA_BANK_THP=on
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,20 @@
|
||||
# claude/ledger: two port-only changes against the previous head, same binary (rt-ledger1), switches:
|
||||
# LELEKA_PREFILL_ALIGNED_COPY=0 + LELEKA_PREFILL_GUARD_GRID=64 = previous head behaviour (arm A)
|
||||
# defaults = page-aligned ring copies + full-grid QSA guards (arm C)
|
||||
# LELEKA_PREFILL_GUARD_GRID=64 only = aligned copies alone (arm B)
|
||||
# 1) bit gate: FNV-1a hash of the final residual R of every chunk + greedy ids, arms A and C (must be identical);
|
||||
# 2) CUPTI trace of arm C (H2D GB/s of the ring copies); 3) timing, untraced, second pass of each process, A C A C B.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; }
|
||||
export BIN=$LD/bin/rt-ledger1
|
||||
A_ARM="LELEKA_PREFILL_ALIGNED_COPY=0 LELEKA_PREFILL_GUARD_GRID=64"
|
||||
header
|
||||
port_long hash-A 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1 $A_ARM
|
||||
port_long hash-C 16000 1 PREFILL-PROFILE 0 9 LELEKA_TRACE_PREFILL_R=1
|
||||
port_long port-16k-C 16000 2 PREFILL-PROFILE 2 9 X=1
|
||||
port_long ab-A-1 16000 2 PREFILL-PROFILE 0 9 $A_ARM
|
||||
port_long ab-C-1 16000 2 PREFILL-PROFILE 0 9 X=1
|
||||
port_long ab-A-2 16000 2 PREFILL-PROFILE 0 9 $A_ARM
|
||||
port_long ab-C-2 16000 2 PREFILL-PROFILE 0 9 X=1
|
||||
port_long ab-B-1 16000 2 PREFILL-PROFILE 0 9 LELEKA_PREFILL_GUARD_GRID=64
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,9 @@
|
||||
# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill (chunks 8192 + 7807) of the PORT (rt-base = head 7330ddb), second pass of
|
||||
# each process (pass 0 pays the one-time finite admission). A: tier off, B: expert tier on, C: tier off WITHOUT the tracer (overhead A/B).
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; }
|
||||
header
|
||||
port_long port-16k-off 16000 2 PREFILL-PROFILE 2 9
|
||||
port_long port-16k-on 16000 2 PREFILL-PROFILE 2 9 $PORT_TIER
|
||||
port_long port-16k-off-plain 16000 2 PREFILL-PROFILE 0 9
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,9 @@
|
||||
# claude/ledger: CUPTI kernel timeline of ONE 16000-token prefill of the unmodified ORIGINAL (--serve, prompt ids of job 0708), second request
|
||||
# traced (the first is the warm-up of the same process). One profiling pass per scenario, not a throughput A/B.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; }
|
||||
header
|
||||
R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R
|
||||
orig_serve orig-16k-off 2 9 "--prefill 8192 --max-context 65536 --kv-resident 20480" $R
|
||||
orig_serve orig-16k-on 2 9 "--prefill auto --max-context 65536 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,6 @@
|
||||
# claude/ledger: the ORIGINAL without the expert tier (job 902's off arm was refused: a native pack needs --spec T >= 2), traced, 16000 tokens, second request.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; }
|
||||
R=$LD/req16k.txt; { echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo "GEN 16 $(cat $G/prefill-708/prompt16000.ids)"; echo QUIT; } > $R
|
||||
orig_serve orig-16k-off 2 9 "--prefill 8192 --spec 4 --max-context 65536 --kv-resident 20480" $R
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,6 @@
|
||||
# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the PORT (22 chunks), tier on (the job 915 configuration), trace from the start of the request.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 30 || { echo "abort: MemAvailable < 30 GiB"; exit 3; }
|
||||
header
|
||||
port_long port-180k 180000 1 "long-smoke prompt tokens" 1 150 $PORT_TIER
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,7 @@
|
||||
# claude/ledger: CUPTI timeline of the whole 180k-token prefill of the unmodified ORIGINAL (job 916 configuration, --serve), trace from the start of the request.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 40 || { echo "abort: MemAvailable < 40 GiB"; exit 3; }
|
||||
header
|
||||
R=$LD/req180k.txt; { echo "GEN 16 $(cat $G/long-180k/prompt180000.ids)"; echo QUIT; } > $R
|
||||
orig_serve orig-180k 1 150 "--prefill auto --max-context 262144 --kv-resident 20480 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55" $R
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,7 @@
|
||||
# claude/ledger: CUPTI timeline of the decode rounds of the PORT: 6-prompt corpus x 2 passes x 128 tokens, spec 4 + suffix 3, min_p 0.5, 2048 slots/layer, static residency.
|
||||
# Window of 10 s after the 2nd finished request (the first prompt, twice), i.e. over the 2nd prompt's two requests.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
port_corpus port-corpus 2 10
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,6 @@
|
||||
# claude/ledger: the same corpus on the unmodified ORIGINAL (--serve, round-profile/original-requests.txt), static residency, trace window before request 3.
|
||||
source ~/work/ledger/ledger-common.sh
|
||||
mem_ok 60 || { echo "abort: MemAvailable < 60 GiB"; exit 3; }
|
||||
header
|
||||
orig_serve orig-corpus 3 10 "--prefill 2048 --max-context 4096 --spec 4 --suffix-draft 3 --spec-min-p 0.5 --expert-cache 2048 --expert-cache-per-layer --expert-profile $PROFILE --pcie-frac 0.55 --adapt-every 0" $G/round-profile/original-requests.txt
|
||||
date -u +%FT%TZ
|
||||
@@ -0,0 +1,112 @@
|
||||
# Sourced by the 90x-ledger-*.sh holder jobs (copied next to them on the server, ~/work/ledger/).
|
||||
# Runs the PORT (test binary) or the unmodified ORIGINAL (strata) with the CUPTI tracer injected and a trigger-file window.
|
||||
set -uo pipefail
|
||||
export PATH=$HOME/cuda-toolkits/13.2.2/bin:$PATH RUST_BACKTRACE=1
|
||||
export LD_LIBRARY_PATH=$HOME/cuda-toolkits/cublas-12.9.1.4/lib:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
|
||||
A=$HOME/leleka-gates/assets
|
||||
G=$HOME/work/gpu-runs
|
||||
LD=$HOME/work/ledger
|
||||
OUT=$LD/traces; mkdir -p $OUT
|
||||
CUPTI_LIB=$HOME/work/cupti-trace/libleleka_cupti_trace.so
|
||||
TRIG=$LD/cupti.trigger
|
||||
ORIG=${ORIG:-$HOME/work/numerics-orig/build/strata}
|
||||
PROFILE=$G/baseline/profile.bin
|
||||
T_LONG=backend::original_serve_smoke::original_serve_long_context_streamed_kv_smoke
|
||||
T_CORPUS=original_serve_smoke_prompt_decode
|
||||
mkdir -p $G/mtp-staging-own; chmod 700 $G/mtp-staging-own
|
||||
export LELEKA_STRA169_KAR_PROVENANCE=$A/qwen-iq3-s-l2-v4.kar.provenance.json
|
||||
export LELEKA_STRA169_IQ3S_SHARD0=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf
|
||||
export LELEKA_STRA169_IQ3S_SHARD1=$A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf
|
||||
export LELEKA_STRA169_MTP_PACK=$A/data/mtp-rt LELEKA_STRA169_MTP_STAGING=$G/mtp-staging-own
|
||||
export LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30 LELEKA_BRINGUP_TRACE=1 LELEKA_SERVE_PROFILE=1
|
||||
PORT_TIER="LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=2048 LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$PROFILE LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.55"
|
||||
BIN=${BIN:-$LD/bin/rt-base}
|
||||
|
||||
mem_ok() { local avail; avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"; [ "${avail:-0}" -ge "$1" ]; }
|
||||
|
||||
# trig LABEL SECONDS OUTNAME: ask the injected tracer for one window (same protocol as the daemon's trigger file)
|
||||
trig() {
|
||||
rm -f $TRIG.active $TRIG.done $TRIG.stop
|
||||
printf '{"seconds": %s, "out": "%s/%s", "label": "%s"}\n' "$2" "$OUT" "$3" "$1" > $TRIG.tmp && mv $TRIG.tmp $TRIG
|
||||
for _ in $(seq 100); do [ -e $TRIG.active ] && return 0; sleep 0.05; done
|
||||
echo "TRIGGER-NOT-TAKEN $1"
|
||||
}
|
||||
trig_stop() { touch $TRIG.stop; }
|
||||
stamp() { perl -MTime::HiRes=time -ne 'BEGIN{$|=1} printf "%.3f %s", time, $_'; }
|
||||
header() { date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,clocks.max.sm --format=csv,noheader; sha256sum $BIN $CUPTI_LIB; }
|
||||
|
||||
# port_long LABEL TOKENS REPEAT TRIG_LINE_REGEX TRIG_AFTER_N WINDOW_S [ENV=V ...]
|
||||
# one model process of the port's long-context smoke (chunk 8192, INT8 KV streamed, 16 new tokens); the tracer window starts
|
||||
# when the TRIG_AFTER_N-th line matching TRIG_LINE_REGEX has been printed. TRIG_AFTER_N=0: no window (tracer not injected).
|
||||
port_long() {
|
||||
local label=$1 toks=$2 rep=$3 re=$4 after=$5 win=$6; shift 6
|
||||
local inj=()
|
||||
[ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400)
|
||||
echo "=== port $label tokens=$toks repeat=$rep trigger=$re#$after win=${win}s: $*"; date -u +%FT%TZ
|
||||
rm -f $TRIG $TRIG.active $TRIG.done
|
||||
mkdir -p $G/ledger-ids
|
||||
local n=0
|
||||
env "${inj[@]}" LELEKA_ORIGINAL_SERVE_LONG_SMOKE=yes LELEKA_ORIGINAL_SERVE_LONG_TOKENS=$toks LELEKA_ORIGINAL_SERVE_LONG_REPEAT=$rep \
|
||||
LELEKA_ORIGINAL_SERVE_LONG_MAX_NEW=16 LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=262144 LELEKA_ORIGINAL_SERVE_CAPACITY=8192 \
|
||||
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*|*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
|
||||
}
|
||||
|
||||
# port_corpus LABEL TRIG_AFTER_N WINDOW_S [ENV=V ...]: the 6 prompts of prompts.txt, each served twice, 128 new tokens, static residency;
|
||||
# the window starts after the N-th "DBG profile request" line (a finished request).
|
||||
port_corpus() {
|
||||
local label=$1 after=$2 win=$3; shift 3
|
||||
local inj=()
|
||||
[ "$after" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400)
|
||||
echo "=== port $label corpus trigger=after request #$after win=${win}s: $*"; date -u +%FT%TZ
|
||||
rm -f $TRIG $TRIG.active $TRIG.done
|
||||
local n=0
|
||||
env "${inj[@]}" LELEKA_ORIGINAL_SERVE_SMOKE=yes LELEKA_SMOKE_PROMPTS=$G/prompts.txt LELEKA_SMOKE_MAX_NEW=128 LELEKA_SMOKE_MIN_P=0.5 LELEKA_SMOKE_REPEAT=2 \
|
||||
LELEKA_ORIGINAL_SERVE_MAX_CONTEXT=4096 LELEKA_ORIGINAL_SERVE_CAPACITY=2048 LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_GRAPH_EXEC_REUSE=off \
|
||||
LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=0 $PORT_TIER "$@" \
|
||||
$BIN --ignored --test-threads=1 --nocapture $T_CORPUS 2>&1 | stamp | tee $OUT/$label.full | while IFS= read -r line; do
|
||||
case "$line" in *"DBG profile request"*) n=$((n+1)); [ "$after" -gt 0 ] && [ $n -eq "$after" ] && trig "$label" "$win" "$label";; esac
|
||||
case "$line" in *"DBG profile request"*|*"DBG timing"*|*"DBG tier request"*|*"smoke:"*|*"test result"*|*panicked*|*"[lct]"*|*TRIGGER*) printf '%s\n' "${line:0:420}";; esac
|
||||
done
|
||||
echo "rc=${PIPESTATUS[0]} port=$label"; date -u +%FT%TZ
|
||||
}
|
||||
|
||||
# orig_serve LABEL STRATA_FLAGS... -- REQUEST_FILE_LINES... : the unmodified Original in --serve mode; requests are fed through a FIFO
|
||||
# one at a time; before request number TRIG_BEFORE a tracer window of WINDOW_S seconds is requested (TRIG_BEFORE=0: none).
|
||||
# usage: orig_serve LABEL TRIG_BEFORE WINDOW_S "flags" reqfile
|
||||
orig_serve() {
|
||||
local label=$1 before=$2 win=$3 flags=$4 req=$5
|
||||
local inj=()
|
||||
[ "$before" -gt 0 ] && inj=(CUDA_INJECTION64_PATH=$CUPTI_LIB LELEKA_CUPTI_TRIGGER=$TRIG LCT_MAX_SECONDS=400)
|
||||
echo "=== original $label trigger before request #$before win=${win}s: $flags"; date -u +%FT%TZ
|
||||
rm -f $TRIG $TRIG.active $TRIG.done
|
||||
local d=$OUT/$label.orig; mkdir -p $d; rm -f $d/fifo; mkfifo $d/fifo
|
||||
local kar=${KAR_PATH:-/proc/self/fd/${LELEKA_STRA169_KAR_FD:-0}}
|
||||
env "${inj[@]}" STRATA_DECODE_TIMING=1 $ORIG --pack $A/data/iq3_s --native $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf \
|
||||
--ple-gguf $A/model/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf --ple-kar $kar --ple-kar-level 2 \
|
||||
--serve --mtp $A/data/mtp-rt --kv int8 $flags \
|
||||
< $d/fifo > $d/out.txt 2> $d/err.txt &
|
||||
local pid=$!
|
||||
exec 7>$d/fifo
|
||||
for _ in $(seq 1200); do grep -q "^READY" $d/out.txt 2>/dev/null && break; kill -0 $pid 2>/dev/null || break; sleep 0.5; done
|
||||
grep -q "^READY" $d/out.txt || { echo "original did not become ready"; tail -3 $d/err.txt | cut -c1-300; exec 7>&-; kill $pid 2>/dev/null; return 1; }
|
||||
local i=0 line
|
||||
while IFS= read -r line; do
|
||||
i=$((i+1))
|
||||
[ "$line" = QUIT ] && break
|
||||
[ "$before" -gt 0 ] && [ $i -eq "$before" ] && trig "$label" "$win" "$label"
|
||||
echo "$(date +%s.%N) request $i sent"
|
||||
printf '%s\n' "$line" >&7
|
||||
for _ in $(seq 6000); do [ "$(grep -c '^DONE' $d/out.txt)" -ge $i ] && break; kill -0 $pid 2>/dev/null || break; sleep 0.2; done
|
||||
echo "$(date +%s.%N) request $i done: $(grep '^DONE' $d/out.txt | sed -n ${i}p | cut -c1-120)"
|
||||
done < $req
|
||||
echo QUIT >&7; exec 7>&-
|
||||
wait $pid; echo "rc=$? original=$label"; date -u +%FT%TZ
|
||||
grep -E "prefill [0-9]+ tokens|PCIe probe" $d/err.txt | cut -c1-300
|
||||
grep -E "strata decode|strata serve: (prompt|decode)" $d/err.txt | cut -c1-600 | head -40
|
||||
grep "^DONE" $d/out.txt | awk '{printf "ORIG-DONE produced %s prompt_ms %s decode_ms %s -> %.2f tok/s\n", $2, $4, $5, $2*1000/$5}'
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
"""Loader and interval helpers for CUPTI trace directories written by tools/cupti-trace (libleleka_cupti_trace.so).
|
||||
|
||||
Pure Python (no numpy): `struct.iter_unpack` over the fixed-size record files. All times are CUPTI ns.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import struct
|
||||
from collections import namedtuple
|
||||
|
||||
K = namedtuple("K", "start end dev stream corr graph node name gx gy gz bx by bz sshm dshm regs launch pad")
|
||||
C = namedtuple("C", "start end bytes dev stream corr graph node ckind skind dkind flags apicorr")
|
||||
M = namedtuple("M", "start end bytes dev stream corr graph mkind pad")
|
||||
Y = namedtuple("Y", "start end corr stream event type ctx ret")
|
||||
A = namedtuple("A", "start end corr thread name ret domain pad")
|
||||
G = namedtuple("G", "start end corr graph dev stream")
|
||||
|
||||
# struct formats mirror the C++ side's #pragma pack(1) records: 80, 56, 44, 40, 36, 32 bytes
|
||||
FMT = {
|
||||
"kernel.bin": ("<QQIIIIQIiiiiiiiiHBB", K),
|
||||
"memcpy.bin": ("<QQQIIIIQBBBBI", C),
|
||||
"memset.bin": ("<QQQIIIIHH", M),
|
||||
"sync.bin": ("<QQIIIIII", Y),
|
||||
"api.bin": ("<QQIIIIB3s", A),
|
||||
"graph.bin": ("<QQIIII", G),
|
||||
}
|
||||
CKIND = {0: "?", 1: "H2D", 2: "D2H", 3: "H2A", 4: "A2H", 5: "A2A", 6: "A2D", 7: "D2A", 8: "D2D", 9: "H2H", 10: "P2P"}
|
||||
MKIND = {0: "?", 1: "pageable", 2: "pinned", 3: "device", 4: "array", 5: "managed", 6: "dev-static", 7: "mgd-static"}
|
||||
SYNCTYPE = {0: "?", 1: "event-sync", 2: "stream-wait-event", 3: "stream-sync", 4: "ctx-sync"}
|
||||
|
||||
|
||||
class Trace:
|
||||
def __init__(self, path, window_ms=None):
|
||||
"""window_ms=(t0, t1): milliseconds from the trace window start; records outside are skipped while loading (big traces)."""
|
||||
self.path = path
|
||||
self._win = window_ms
|
||||
self.meta = {}
|
||||
for line in open(os.path.join(path, "meta.txt")):
|
||||
k, _, v = line.strip().partition(" ")
|
||||
self.meta[k] = v
|
||||
self.names = {}
|
||||
p = os.path.join(path, "strings.tsv")
|
||||
if os.path.exists(p):
|
||||
for line in open(p, encoding="utf-8", errors="replace"):
|
||||
i, _, n = line.rstrip("\n").partition("\t")
|
||||
if i.isdigit():
|
||||
self.names[int(i)] = n
|
||||
self._demangle()
|
||||
self.threads = {}
|
||||
p = os.path.join(path, "threads.tsv")
|
||||
if os.path.exists(p):
|
||||
for line in open(p):
|
||||
t, _, n = line.rstrip("\n").partition("\t")
|
||||
if t.isdigit():
|
||||
self.threads[int(t)] = n
|
||||
self._lo = self._hi = None
|
||||
if window_ms is not None:
|
||||
w0 = int(self.meta.get("window_start", 0))
|
||||
self._lo = w0 + int(window_ms[0] * 1e6)
|
||||
self._hi = w0 + int(window_ms[1] * 1e6)
|
||||
self.kernels = self._load("kernel.bin")
|
||||
self.copies = self._load("memcpy.bin")
|
||||
self.memsets = self._load("memset.bin")
|
||||
self.syncs = self._load("sync.bin")
|
||||
self.apis = self._load("api.bin")
|
||||
self.graphs = self._load("graph.bin")
|
||||
self.t0 = int(self.meta.get("window_start", 0)) or (min([r.start for r in self.kernels] or [0]))
|
||||
self.t1 = int(self.meta.get("window_stop", 0)) or (max([r.end for r in self.kernels] or [0]))
|
||||
if self._lo is not None:
|
||||
self.t0, self.t1 = self._lo, min(self._hi, self.t1)
|
||||
self.real_off = int(self.meta.get("realtime_ns", 0)) - int(self.meta.get("cupti_ts_ns", 0))
|
||||
|
||||
def _demangle(self):
|
||||
"""Replace mangled kernel names by c++filt output (cached next to the trace as strings.dem.tsv; needs c++filt, or WSL)."""
|
||||
import subprocess
|
||||
cache = os.path.join(self.path, "strings.dem.tsv")
|
||||
if not os.path.exists(cache):
|
||||
ids = [i for i, n in self.names.items() if n.startswith("_Z")]
|
||||
if not ids:
|
||||
return
|
||||
text = "\n".join(self.names[i] for i in ids) + "\n"
|
||||
out = None
|
||||
for cmd in (["c++filt"], ["wsl", "-d", "Ubuntu", "-e", "c++filt"]):
|
||||
try:
|
||||
out = subprocess.run(cmd, input=text.encode(), capture_output=True, timeout=120).stdout.decode("utf-8", "replace").split("\n")
|
||||
if len(out) >= len(ids):
|
||||
break
|
||||
except Exception:
|
||||
out = None
|
||||
if not out:
|
||||
return
|
||||
try:
|
||||
with open(cache, "w", encoding="utf-8", newline="\n") as f:
|
||||
for i, d in zip(ids, out):
|
||||
f.write("%d\t%s\n" % (i, d.strip()))
|
||||
except OSError:
|
||||
for i, d in zip(ids, out):
|
||||
self.names[i] = d.strip()
|
||||
return
|
||||
for line in open(cache, encoding="utf-8", errors="replace"):
|
||||
i, _, n = line.rstrip("\n").partition("\t")
|
||||
if i.isdigit() and n:
|
||||
self.names[int(i)] = n
|
||||
|
||||
def _load(self, fn):
|
||||
p = os.path.join(self.path, fn)
|
||||
if not os.path.exists(p) or os.path.getsize(p) == 0:
|
||||
return []
|
||||
fmt, nt = FMT[fn]
|
||||
sz = struct.calcsize(fmt)
|
||||
with open(p, "rb") as f:
|
||||
data = f.read()
|
||||
data = data[: len(data) // sz * sz]
|
||||
lo, hi = self._lo, self._hi
|
||||
if lo is None:
|
||||
return [nt(*t) for t in struct.iter_unpack(fmt, data)]
|
||||
return [nt(*t) for t in struct.iter_unpack(fmt, data) if t[1] >= lo and t[0] <= hi]
|
||||
|
||||
def kname(self, r):
|
||||
return self.names.get(r.name, "?")
|
||||
|
||||
def clip(self, lo, hi):
|
||||
"""Keep only records overlapping [lo, hi] (CUPTI ns) and make that the window."""
|
||||
for nm in ("kernels", "copies", "memsets", "syncs", "apis", "graphs"):
|
||||
setattr(self, nm, [r for r in getattr(self, nm) if r.end >= lo and r.start <= hi])
|
||||
self.t0, self.t1 = lo, hi
|
||||
|
||||
|
||||
def union(intervals):
|
||||
"""Merge [(a,b),...] into disjoint sorted [a,b] lists."""
|
||||
out = []
|
||||
for a, b in sorted(intervals):
|
||||
if out and a <= out[-1][1]:
|
||||
if b > out[-1][1]:
|
||||
out[-1][1] = b
|
||||
else:
|
||||
out.append([a, b])
|
||||
return out
|
||||
|
||||
|
||||
def total(ivs):
|
||||
return sum(b - a for a, b in ivs)
|
||||
|
||||
|
||||
def intersect_total(u1, u2):
|
||||
"""Total overlap of two disjoint sorted interval lists."""
|
||||
i = j = 0
|
||||
t = 0
|
||||
while i < len(u1) and j < len(u2):
|
||||
a = max(u1[i][0], u2[j][0])
|
||||
b = min(u1[i][1], u2[j][1])
|
||||
if b > a:
|
||||
t += b - a
|
||||
if u1[i][1] < u2[j][1]:
|
||||
i += 1
|
||||
else:
|
||||
j += 1
|
||||
return t
|
||||
|
||||
|
||||
_fam_cache = {}
|
||||
|
||||
|
||||
def _strip_templates(n):
|
||||
out, depth = [], 0
|
||||
args = []
|
||||
cur = []
|
||||
for ch in n:
|
||||
if ch == "<":
|
||||
depth += 1
|
||||
if depth == 1:
|
||||
cur = []
|
||||
continue
|
||||
elif ch == ">":
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
args.append("".join(cur))
|
||||
continue
|
||||
if depth == 0:
|
||||
out.append(ch)
|
||||
elif depth >= 1:
|
||||
cur.append(ch)
|
||||
return "".join(out), args
|
||||
|
||||
|
||||
def family(name):
|
||||
"""Short kernel family label: namespaces, parameter lists, template arguments and a trailing _kernel are dropped; the first
|
||||
template argument is kept for the kernels that are one template instantiated per format (mul_mat_q, dequant_kernel, cutlass)."""
|
||||
f = _fam_cache.get(name)
|
||||
if f is not None:
|
||||
return f
|
||||
n = name.replace("(anonymous namespace)::", "")
|
||||
n = re.sub(r"^(void|std::enable_if<.*?>::type)\s+", "", n)
|
||||
# parameter list: the last top-level '(' ... end
|
||||
depth = 0
|
||||
cut = len(n)
|
||||
for k, ch in enumerate(n):
|
||||
if ch == "<":
|
||||
depth += 1
|
||||
elif ch == ">":
|
||||
depth -= 1
|
||||
elif ch == "(" and depth == 0:
|
||||
cut = k
|
||||
break
|
||||
n = n[:cut].strip()
|
||||
base, args = _strip_templates(n)
|
||||
base = base.strip()
|
||||
if "::" in base:
|
||||
base = base.split("::")[-1]
|
||||
base = re.sub(r"_kernel$", "", base)
|
||||
first = args[0].split(",")[0].strip() if args else ""
|
||||
first = first.replace("(ggml_type)", "t")
|
||||
if base in ("mul_mat_q", "dequant", "mul_mat_q_stream_k_fixup", "Kernel2") and first:
|
||||
base = base + "<" + first[:60] + ">"
|
||||
_fam_cache[name] = base or name
|
||||
return _fam_cache[name]
|
||||
|
||||
|
||||
def percentile(sorted_vals, p):
|
||||
if not sorted_vals:
|
||||
return 0.0
|
||||
return sorted_vals[min(len(sorted_vals) - 1, int(p / 100.0 * len(sorted_vals)))]
|
||||
|
||||
|
||||
def chunk_windows(full_log, trace_dir):
|
||||
"""Chunk windows (ms from the trace window start) of the stamped PREFILL-PROFILE lines of a job log (<label>.full: lines
|
||||
"<unix s.ms> PREFILL-PROFILE first=.. tokens=.. total_ms=.."). A chunk ends at its line's stamp and started total_ms earlier."""
|
||||
import json
|
||||
done = None
|
||||
for cand in (trace_dir.rstrip("/\\").rsplit(".lct", 1)[0] + ".done", os.path.join(trace_dir, "done.json")):
|
||||
if os.path.exists(cand):
|
||||
done = json.load(open(cand))
|
||||
break
|
||||
t0 = done["unix_ms_start"] / 1000.0
|
||||
t1 = done["unix_ms_stop"] / 1000.0
|
||||
out = []
|
||||
for line in open(full_log, errors="replace"):
|
||||
m = re.match(r"^(\d+\.\d+) .*PREFILL-PROFILE (.*)$", line)
|
||||
if not m:
|
||||
continue
|
||||
end = float(m.group(1))
|
||||
kv = dict(x.split("=", 1) for x in m.group(2).split() if "=" in x)
|
||||
tot = float(kv.get("total_ms", 0)) / 1000.0
|
||||
if end < t0 or end - tot > t1:
|
||||
continue
|
||||
out.append({"first": kv.get("first"), "tokens": kv.get("tokens"), "total_ms": kv.get("total_ms"),
|
||||
"t0_ms": (end - tot - t0) * 1000.0, "t1_ms": (end - t0) * 1000.0, "kv": kv})
|
||||
return out
|
||||
@@ -0,0 +1,254 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Port-vs-Original ledger from two CUPTI windows (tools/cupti-trace output directories).
|
||||
|
||||
python3 scripts/profile/lct_ledger.py PORT_DIR ORIG_DIR [--map scripts/profile/steps.map]
|
||||
[--p-t0 MS --p-t1 MS] [--o-t0 MS --o-t1 MS] (windows relative to each trace's start; default: whole trace)
|
||||
[--per-chunk] split each window into compute bursts and print a per-burst table (chunk analysis)
|
||||
[--md] markdown tables
|
||||
|
||||
For each trace: kernel time per STEP (kernel names mapped to engine-neutral steps by steps.map; unmatched kernels keep their
|
||||
family name), copies by kind with achieved GB/s, compute-stream idle time by cause, copy/compute overlap, API/sync time on the host.
|
||||
Kernel time is the sum of kernel durations (concurrent kernels counted separately); the wall figures are the compute-stream span,
|
||||
busy and idle time.
|
||||
"""
|
||||
import argparse
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import lct as L
|
||||
from lct_report import gaps_with_reasons, pick_compute_stream
|
||||
|
||||
|
||||
def load_map(path):
|
||||
rules = []
|
||||
if path and os.path.exists(path):
|
||||
for line in open(path):
|
||||
line = line.rstrip("\n")
|
||||
if not line.strip() or line.startswith("#"):
|
||||
continue
|
||||
pat, _, step = line.partition("\t")
|
||||
rules.append((re.compile(pat), step.strip()))
|
||||
return rules
|
||||
|
||||
|
||||
def canon(fam):
|
||||
"""The port's kernel names carry a leleka_ prefix and a prefill_ infix that the Original's do not."""
|
||||
return re.sub(r"leleka_|prefill_", "", fam)
|
||||
|
||||
|
||||
def step_of(rules, name):
|
||||
fam = canon(L.family(name))
|
||||
for rx, step in rules:
|
||||
if rx.search(fam):
|
||||
return step
|
||||
return None
|
||||
|
||||
|
||||
def summarize(tr, rules, gap_us):
|
||||
s = {}
|
||||
steps = defaultdict(lambda: [0, 0])
|
||||
for k in tr.kernels:
|
||||
n = tr.kname(k)
|
||||
st = step_of(rules, n) or ("? " + canon(L.family(n)))
|
||||
steps[st][0] += 1
|
||||
steps[st][1] += k.end - k.start
|
||||
s["steps"] = steps
|
||||
cs = pick_compute_stream(tr)
|
||||
s["cs"] = cs
|
||||
ks = sorted(tr.kernels, key=lambda k: k.start) # the GPU timeline: union of all streams
|
||||
s["span"] = (ks[-1].end - ks[0].start) if ks else 0
|
||||
s["busy"] = L.total(L.union([(k.start, k.end) for k in ks]))
|
||||
s["kernel_sum_all"] = sum(k.end - k.start for k in tr.kernels)
|
||||
s["kernels"] = len(tr.kernels)
|
||||
gp = gaps_with_reasons(tr, None, gap_us * 1e3) if ks else []
|
||||
why = defaultdict(lambda: [0, 0])
|
||||
for g in gp:
|
||||
w = why[g[2].split("(thr")[0].strip()]
|
||||
w[0] += 1
|
||||
w[1] += g[1] - g[0]
|
||||
s["gaps"] = why
|
||||
s["gap_total"] = sum(g[1] - g[0] for g in gp)
|
||||
s["gaps_n"] = len(gp)
|
||||
small = 0
|
||||
for a, b in zip(ks, ks[1:]):
|
||||
d = b.start - a.end
|
||||
if 0 < d < gap_us * 1e3:
|
||||
small += d
|
||||
s["small_gap_total"] = small
|
||||
cp = defaultdict(lambda: [0, 0, 0])
|
||||
for c in tr.copies:
|
||||
key = "%s %s->%s" % (L.CKIND.get(c.ckind, c.ckind), L.MKIND.get(c.skind, c.skind), L.MKIND.get(c.dkind, c.dkind))
|
||||
cp[key][0] += 1
|
||||
cp[key][1] += c.bytes
|
||||
cp[key][2] += c.end - c.start
|
||||
s["copies"] = cp
|
||||
h2d = [c for c in tr.copies if c.ckind == 1]
|
||||
hu = L.union([(c.start, c.end) for c in h2d])
|
||||
s["h2d_bytes"] = sum(c.bytes for c in h2d)
|
||||
s["h2d_union"] = L.total(hu)
|
||||
s["h2d_n"] = len(h2d)
|
||||
cu = L.union([(c.start, c.end) for c in tr.copies if c.ckind in (1, 2)])
|
||||
cku = L.union([(k.start, k.end) for k in ks])
|
||||
s["copy_busy"] = L.total(cu)
|
||||
s["copy_overlap"] = L.intersect_total(cu, cku)
|
||||
api = defaultdict(lambda: [0, 0])
|
||||
for x in tr.apis:
|
||||
a = api[tr.names.get(x.name, "?")]
|
||||
a[0] += 1
|
||||
a[1] += x.end - x.start
|
||||
s["api"] = api
|
||||
s["win"] = tr.t1 - tr.t0
|
||||
return s
|
||||
|
||||
|
||||
def bursts(tr, cs, split_ms):
|
||||
"""Compute-stream bursts separated by idle gaps >= split_ms."""
|
||||
ks = sorted((k for k in tr.kernels if (k.dev, k.stream) == cs), key=lambda k: k.start)
|
||||
out = []
|
||||
cur = None
|
||||
for k in ks:
|
||||
if cur and k.start - cur[1] < split_ms * 1e6:
|
||||
cur[1] = max(cur[1], k.end)
|
||||
cur[2] += 1
|
||||
cur[3] += k.end - k.start
|
||||
else:
|
||||
if cur:
|
||||
out.append(cur)
|
||||
cur = [k.start, k.end, 1, k.end - k.start]
|
||||
if cur:
|
||||
out.append(cur)
|
||||
return out
|
||||
|
||||
|
||||
def marker_window(tr, family, n, end_gap_ms=30.0):
|
||||
"""(t0_ms, t1_ms) relative to the trace start of the chunk that begins at the n-th kernel of `family`: it ends at the next
|
||||
marker, or, for the last one, at the last kernel before the first idle gap of the whole GPU >= end_gap_ms (decode follows)."""
|
||||
starts = sorted(k.start for k in tr.kernels if L.family(tr.kname(k)) == family)
|
||||
if n >= len(starts):
|
||||
raise SystemExit("marker %s occurs %d times, chunk %d requested" % (family, len(starts), n))
|
||||
a = starts[n]
|
||||
if n + 1 < len(starts):
|
||||
b = starts[n + 1]
|
||||
else:
|
||||
ks = sorted((k for k in tr.kernels if k.start >= a), key=lambda k: k.start)
|
||||
cur = ks[0].end
|
||||
b = cur
|
||||
for k in ks[1:]:
|
||||
if k.start - cur >= end_gap_ms * 1e6 and k.start - a > 300e6:
|
||||
break
|
||||
cur = max(cur, k.end)
|
||||
b = cur
|
||||
return (a - tr.t0) / 1e6, (b - tr.t0) / 1e6
|
||||
|
||||
|
||||
def ms(x):
|
||||
return "%.1f" % (x / 1e6)
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("port")
|
||||
ap.add_argument("orig")
|
||||
ap.add_argument("--map", default=os.path.join(os.path.dirname(os.path.abspath(__file__)), "steps.map"))
|
||||
ap.add_argument("--p-t0", type=float)
|
||||
ap.add_argument("--p-t1", type=float)
|
||||
ap.add_argument("--o-t0", type=float)
|
||||
ap.add_argument("--o-t1", type=float)
|
||||
ap.add_argument("--gap-us", type=float, default=50)
|
||||
ap.add_argument("--top", type=int, default=40)
|
||||
ap.add_argument("--per-chunk", type=float, default=0, help="print compute bursts split at gaps >= this many ms")
|
||||
ap.add_argument("--p-marker", help="kernel family that starts a chunk in the port trace")
|
||||
ap.add_argument("--o-marker", help="kernel family that starts a chunk in the original trace")
|
||||
ap.add_argument("--chunk", type=int, default=None, help="with --p-marker/--o-marker: which chunk (0-based) to compare")
|
||||
a = ap.parse_args()
|
||||
rules = load_map(a.map)
|
||||
P = L.Trace(a.port)
|
||||
O = L.Trace(a.orig)
|
||||
if a.chunk is not None:
|
||||
if a.p_marker:
|
||||
a.p_t0, a.p_t1 = marker_window(P, a.p_marker, a.chunk)
|
||||
if a.o_marker:
|
||||
a.o_t0, a.o_t1 = marker_window(O, a.o_marker, a.chunk)
|
||||
print("chunk %d: port window %.1f..%.1f ms (%.1f ms), original window %.1f..%.1f ms (%.1f ms)\n" % (
|
||||
a.chunk, a.p_t0, a.p_t1, a.p_t1 - a.p_t0, a.o_t0, a.o_t1, a.o_t1 - a.o_t0))
|
||||
for tr, t0, t1 in ((P, a.p_t0, a.p_t1), (O, a.o_t0, a.o_t1)):
|
||||
if t0 is not None or t1 is not None:
|
||||
lo = tr.t0 + int((t0 or 0) * 1e6)
|
||||
hi = tr.t0 + int(t1 * 1e6) if t1 is not None else tr.t1
|
||||
tr.clip(lo, hi)
|
||||
sp, so = summarize(P, rules, a.gap_us), summarize(O, rules, a.gap_us)
|
||||
|
||||
print("| metric | port | original | port - original |")
|
||||
print("| --- | ---: | ---: | ---: |")
|
||||
|
||||
def row(name, x, y, f=ms, unit=""):
|
||||
print("| %s | %s%s | %s%s | %s%s |" % (name, f(x), unit, f(y), unit, f(x - y), unit))
|
||||
|
||||
row("window (ms)", sp["win"], so["win"])
|
||||
row("GPU kernel timeline span (ms)", sp["span"], so["span"])
|
||||
row("GPU busy: union of all streams (ms)", sp["busy"], so["busy"])
|
||||
row("GPU idle in gaps >= %d us (ms)" % a.gap_us, sp["gap_total"], so["gap_total"])
|
||||
row("GPU idle in gaps < %d us (ms)" % a.gap_us, sp["small_gap_total"], so["small_gap_total"])
|
||||
row("kernel launches", sp["kernels"], so["kernels"], f=lambda v: "%d" % v)
|
||||
row("sum of kernel durations, all streams (ms)", sp["kernel_sum_all"], so["kernel_sum_all"])
|
||||
row("H2D copies", sp["h2d_n"], so["h2d_n"], f=lambda v: "%d" % v)
|
||||
row("H2D bytes (GB)", sp["h2d_bytes"], so["h2d_bytes"], f=lambda v: "%.2f" % (v / 1e9))
|
||||
row("H2D union busy (ms)", sp["h2d_union"], so["h2d_union"])
|
||||
print("| H2D GB/s over the union | %.1f | %.1f | %.1f |" % (
|
||||
sp["h2d_bytes"] / max(1, sp["h2d_union"]), so["h2d_bytes"] / max(1, so["h2d_union"]),
|
||||
sp["h2d_bytes"] / max(1, sp["h2d_union"]) - so["h2d_bytes"] / max(1, so["h2d_union"])))
|
||||
print("| copy busy overlapped by compute | %.0f%% | %.0f%% | |" % (
|
||||
100 * sp["copy_overlap"] / max(1, sp["copy_busy"]), 100 * so["copy_overlap"] / max(1, so["copy_busy"])))
|
||||
row("copy-only time, no kernel running (ms)", sp["copy_busy"] - sp["copy_overlap"], so["copy_busy"] - so["copy_overlap"])
|
||||
|
||||
print("\n| step | port n | port ms | orig n | orig ms | delta ms |")
|
||||
print("| --- | ---: | ---: | ---: | ---: | ---: |")
|
||||
keys = set(sp["steps"]) | set(so["steps"])
|
||||
order = sorted(keys, key=lambda k: -(sp["steps"].get(k, [0, 0])[1] - so["steps"].get(k, [0, 0])[1]))
|
||||
shown = 0
|
||||
rest = [0, 0, 0, 0]
|
||||
for k in order:
|
||||
pn, pt = sp["steps"].get(k, [0, 0])
|
||||
on, ot = so["steps"].get(k, [0, 0])
|
||||
if shown < a.top or abs(pt - ot) > 5e6:
|
||||
print("| %s | %d | %s | %d | %s | %s |" % (k[:60], pn, ms(pt), on, ms(ot), ms(pt - ot)))
|
||||
shown += 1
|
||||
else:
|
||||
rest[0] += pn; rest[1] += pt; rest[2] += on; rest[3] += ot
|
||||
if rest[0] or rest[2]:
|
||||
print("| (others) | %d | %s | %d | %s | %s |" % (rest[0], ms(rest[1]), rest[2], ms(rest[3]), ms(rest[1] - rest[3])))
|
||||
|
||||
print("\n| copy kind | port n | port MB | port busy ms | port GB/s | orig n | orig MB | orig busy ms | orig GB/s |")
|
||||
print("| --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: | ---: |")
|
||||
for k in sorted(set(sp["copies"]) | set(so["copies"])):
|
||||
pn, pb, pt = sp["copies"].get(k, [0, 0, 0])
|
||||
on, ob, ot = so["copies"].get(k, [0, 0, 0])
|
||||
print("| %s | %d | %.1f | %s | %.1f | %d | %.1f | %s | %.1f |" % (k, pn, pb / 1e6, ms(pt), pb / max(1, pt), on, ob / 1e6, ms(ot), ob / max(1, ot)))
|
||||
|
||||
print("\n| compute-idle cause (gaps >= %d us) | port gaps | port ms | orig gaps | orig ms |" % a.gap_us)
|
||||
print("| --- | ---: | ---: | ---: | ---: |")
|
||||
for k in sorted(set(sp["gaps"]) | set(so["gaps"]), key=lambda k: -(sp["gaps"].get(k, [0, 0])[1] + so["gaps"].get(k, [0, 0])[1])):
|
||||
pn, pt = sp["gaps"].get(k, [0, 0])
|
||||
on, ot = so["gaps"].get(k, [0, 0])
|
||||
print("| %s | %d | %s | %d | %s |" % (k[:70], pn, ms(pt), on, ms(ot)))
|
||||
|
||||
print("\n| host API (CPU) | port calls | port ms | orig calls | orig ms |")
|
||||
print("| --- | ---: | ---: | ---: | ---: |")
|
||||
keys = set(sp["api"]) | set(so["api"])
|
||||
for k in sorted(keys, key=lambda k: -max(sp["api"].get(k, [0, 0])[1], so["api"].get(k, [0, 0])[1]))[:20]:
|
||||
pn, pt = sp["api"].get(k, [0, 0])
|
||||
on, ot = so["api"].get(k, [0, 0])
|
||||
print("| %s | %d | %s | %d | %s |" % (k[:50], pn, ms(pt), on, ms(ot)))
|
||||
|
||||
if a.per_chunk:
|
||||
for nm, tr, s in (("port", P, sp), ("original", O, so)):
|
||||
print("\n%s compute bursts (split at idle gaps >= %.1f ms): start ms, length ms, kernels, busy ms" % (nm, a.per_chunk))
|
||||
for b in bursts(tr, s["cs"], a.per_chunk):
|
||||
print(" @%9.1f %8.1f ms %7d kernels busy %8.1f" % ((b[0] - tr.t0) / 1e6, (b[1] - b[0]) / 1e6, b[2], b[3] / 1e6))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,219 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Single-trace report of a CUPTI window (tools/cupti-trace output directory).
|
||||
|
||||
python3 scripts/profile/lct_report.py <dir.lct> [--top N] [--gap-us 50] [--t0 MS --t1 MS] (MS relative to the window start)
|
||||
|
||||
Sections: window summary; per-kernel-family time; copies (kind, memory kinds, sizes, achieved GB/s); compute-stream idle gaps
|
||||
with the host-side reason (blocking sync call, copy in flight, launch-bound); copy/compute overlap; API time by call.
|
||||
"""
|
||||
import argparse
|
||||
import bisect
|
||||
import os
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
import lct as L
|
||||
|
||||
|
||||
def fmtb(n):
|
||||
for u, d in (("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)):
|
||||
if n >= d:
|
||||
return "%.1f%s" % (n / d, u)
|
||||
return "%dB" % n
|
||||
|
||||
|
||||
def bucket(b):
|
||||
for u, d in (("1M+", 1 << 20), ("64K-1M", 1 << 16), ("4K-64K", 1 << 12)):
|
||||
if b >= d:
|
||||
return u
|
||||
return "<4K"
|
||||
|
||||
|
||||
def pick_compute_stream(tr):
|
||||
t = defaultdict(int)
|
||||
for k in tr.kernels:
|
||||
t[(k.dev, k.stream)] += k.end - k.start
|
||||
return max(t.items(), key=lambda kv: kv[1])[0] if t else None
|
||||
|
||||
|
||||
def overlap(u, starts, a, b):
|
||||
"""Overlap of [a,b] with a disjoint sorted interval list (starts = its start points)."""
|
||||
i = max(0, bisect.bisect_right(starts, a) - 1)
|
||||
t = 0
|
||||
while i < len(u) and u[i][0] < b:
|
||||
t += max(0, min(b, u[i][1]) - max(a, u[i][0]))
|
||||
i += 1
|
||||
return t
|
||||
|
||||
|
||||
def gaps_with_reasons(tr, stream, min_gap_ns):
|
||||
"""Idle gaps of the GPU kernel timeline with the cause. stream=None: union of all streams (the GPU is idle), else one stream.
|
||||
Returns [(a, b, why, prev_kernel, next_kernel, copy_ns)] where copy_ns is the overlap of the gap with any H2D/D2H copy."""
|
||||
ks = sorted((k for k in tr.kernels if stream is None or (k.dev, k.stream) == stream), key=lambda k: k.start)
|
||||
apis = sorted(tr.apis, key=lambda a: a.start)
|
||||
starts = [a.start for a in apis]
|
||||
copies_u = L.union([(c.start, c.end) for c in tr.copies if c.ckind in (1, 2)])
|
||||
cu_starts = [x[0] for x in copies_u]
|
||||
gaps = []
|
||||
if ks:
|
||||
cur_end, prev = ks[0].end, ks[0]
|
||||
for k in ks[1:]:
|
||||
if k.start - cur_end >= min_gap_ns:
|
||||
gaps.append((cur_end, k.start, prev, k))
|
||||
if k.end > cur_end:
|
||||
cur_end, prev = k.end, k
|
||||
res = []
|
||||
for a, b, prev, nxt in gaps:
|
||||
best, best_ov, launch_cover = None, 0, 0
|
||||
i = max(0, bisect.bisect_left(starts, a - 50_000_000))
|
||||
while i < len(apis) and apis[i].start < b:
|
||||
x = apis[i]
|
||||
i += 1
|
||||
ov = min(b, x.end) - max(a, x.start)
|
||||
if ov <= 0:
|
||||
continue
|
||||
nm = tr.names.get(x.name, "?")
|
||||
if "Launch" in nm or "Graph" in nm:
|
||||
launch_cover += ov
|
||||
if any(sx in nm for sx in ("Synchronize", "Wait", "MemcpyDtoH", "MemcpyHtoD_v2", "cudaMemcpy_")) and ov > best_ov:
|
||||
best, best_ov = (nm, x.thread), ov
|
||||
cov = overlap(copies_u, cu_starts, a, b)
|
||||
if cov > 0.5 * (b - a):
|
||||
why = "PCIe copy running, no kernel"
|
||||
elif best and best_ov > 0.5 * (b - a):
|
||||
why = "host-sync %s (thr %s)" % (best[0], tr.threads.get(best[1], best[1]))
|
||||
elif launch_cover > 0.3 * (b - a):
|
||||
why = "launch-bound (cpu issuing)"
|
||||
elif best:
|
||||
why = "host-sync(partial) %s" % best[0]
|
||||
else:
|
||||
why = "unattributed (cpu between calls / no api record)"
|
||||
res.append((a, b, why, prev, nxt, cov))
|
||||
return res
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("dir")
|
||||
ap.add_argument("--top", type=int, default=25)
|
||||
ap.add_argument("--gap-us", type=float, default=50)
|
||||
ap.add_argument("--t0", type=float, default=None)
|
||||
ap.add_argument("--t1", type=float, default=None)
|
||||
ap.add_argument("--stream", type=int, default=None, help="restrict the gap analysis to one stream id (default: union of all streams)")
|
||||
ap.add_argument("--stamps", default=None, help="job .full log with stamped PREFILL-PROFILE lines (see lct.chunk_windows)")
|
||||
ap.add_argument("--chunk", type=int, default=None, help="with --stamps: clip to the Nth PREFILL-PROFILE chunk inside the window (0-based)")
|
||||
a = ap.parse_args()
|
||||
tr = L.Trace(a.dir)
|
||||
if a.stamps and a.chunk is not None:
|
||||
cw = L.chunk_windows(a.stamps, a.dir)
|
||||
c = cw[a.chunk]
|
||||
a.t0, a.t1 = c["t0_ms"], c["t1_ms"]
|
||||
print("chunk %d: first=%s tokens=%s total_ms=%s -> window %.1f..%.1f ms" % (a.chunk, c["first"], c["tokens"], c["total_ms"], a.t0, a.t1))
|
||||
if a.t0 is not None or a.t1 is not None:
|
||||
lo = tr.t0 + int((a.t0 or 0) * 1e6)
|
||||
hi = tr.t0 + int(a.t1 * 1e6) if a.t1 is not None else tr.t1
|
||||
tr.clip(lo, hi)
|
||||
W = (tr.t1 - tr.t0) / 1e6
|
||||
print("== window %s: %.1f ms, label=%r reason=%s" % (a.dir, W, tr.meta.get("label"), tr.meta.get("stop_reason")))
|
||||
print(" kernels %d, copies %d, memsets %d, syncs %d, api %d, graphs %d; unix start %.3f" % (
|
||||
len(tr.kernels), len(tr.copies), len(tr.memsets), len(tr.syncs), len(tr.apis), len(tr.graphs), (tr.t0 + tr.real_off) / 1e9))
|
||||
ku = L.union([(k.start, k.end) for k in tr.kernels])
|
||||
print(" GPU kernel-busy (any stream): %.1f ms = %.1f%% of window" % (L.total(ku) / 1e6, 100 * L.total(ku) / max(1, tr.t1 - tr.t0)))
|
||||
streams = defaultdict(lambda: [0, 0])
|
||||
for k in tr.kernels:
|
||||
s = streams[(k.dev, k.stream)]
|
||||
s[0] += 1
|
||||
s[1] += k.end - k.start
|
||||
for key, (n, t) in sorted(streams.items(), key=lambda kv: -kv[1][1])[:8]:
|
||||
print(" stream dev%d/%d: %d kernels, %.1f ms of kernel time" % (key[0], key[1], n, t / 1e6))
|
||||
|
||||
print("\n== kernel families (sum of kernel durations; concurrent kernels overlap)")
|
||||
fam = defaultdict(lambda: [0, 0])
|
||||
for k in tr.kernels:
|
||||
f = fam[L.family(tr.kname(k))]
|
||||
f[0] += 1
|
||||
f[1] += k.end - k.start
|
||||
tot = sum(v[1] for v in fam.values()) or 1
|
||||
print(" %-52s %8s %10s %9s %6s" % ("family", "count", "total ms", "mean us", "share"))
|
||||
for n, (c, t) in sorted(fam.items(), key=lambda kv: -kv[1][1])[: a.top]:
|
||||
print(" %-52s %8d %10.2f %9.1f %5.1f%%" % (n[:52], c, t / 1e6, t / 1e3 / c, 100 * t / tot))
|
||||
|
||||
print("\n== copies")
|
||||
grp = defaultdict(lambda: [0, 0, 0])
|
||||
for c in tr.copies:
|
||||
g = grp[(L.CKIND.get(c.ckind, c.ckind), L.MKIND.get(c.skind, c.skind), L.MKIND.get(c.dkind, c.dkind), c.dev, c.stream)]
|
||||
g[0] += 1
|
||||
g[1] += c.bytes
|
||||
g[2] += c.end - c.start
|
||||
print(" %-38s %7s %10s %9s %9s" % ("kind src->dst dev/stream", "count", "MB", "busy ms", "GB/s"))
|
||||
for key, (n, b, t) in sorted(grp.items(), key=lambda kv: -kv[1][1])[:12]:
|
||||
print(" %-38s %7d %10.1f %9.2f %9.1f" % ("%s %s->%s d%d/s%d" % key, n, b / 1e6, t / 1e6, b / max(1, t)))
|
||||
h2d = [c for c in tr.copies if c.ckind == 1]
|
||||
if h2d:
|
||||
sizes = sorted(c.bytes for c in h2d)
|
||||
gbs = sorted(c.bytes / max(1, c.end - c.start) for c in h2d if c.bytes >= 65536)
|
||||
print(" H2D: %d copies, %.1f MB; size p10/p50/p90/max = %s / %s / %s / %s" % (
|
||||
len(h2d), sum(sizes) / 1e6, fmtb(L.percentile(sizes, 10)), fmtb(L.percentile(sizes, 50)), fmtb(L.percentile(sizes, 90)), fmtb(sizes[-1])))
|
||||
if gbs:
|
||||
print(" H2D copies >= 64 KiB: GB/s p10/p50/p90 = %.1f / %.1f / %.1f (per copy, own start..end)" % (
|
||||
L.percentile(gbs, 10), L.percentile(gbs, 50), L.percentile(gbs, 90)))
|
||||
hu = L.union([(c.start, c.end) for c in h2d])
|
||||
print(" H2D union busy %.1f ms (%.1f%% of window), aggregate %.1f GB/s over the union" % (
|
||||
L.total(hu) / 1e6, 100 * L.total(hu) / max(1, tr.t1 - tr.t0), sum(c.bytes for c in h2d) / max(1, L.total(hu))))
|
||||
buckets = defaultdict(lambda: [0, 0])
|
||||
for c in h2d:
|
||||
b = buckets[bucket(c.bytes)]
|
||||
b[0] += 1
|
||||
b[1] += c.bytes
|
||||
print(" H2D size histogram (count): " + ", ".join("%s:%d" % (k, v[0]) for k, v in sorted(buckets.items(), key=lambda kv: -kv[1][1])))
|
||||
|
||||
cs = None
|
||||
if a.stream is not None:
|
||||
cs = next((sx for sx in streams if sx[1] == a.stream), None)
|
||||
ks = [k for k in tr.kernels if cs is None or (k.dev, k.stream) == cs]
|
||||
if ks:
|
||||
print("\n== GPU kernel timeline (%s) idle gaps >= %.0f us" % ("stream dev%d/%d" % cs if cs else "union of all streams", a.gap_us))
|
||||
span = max(k.end for k in ks) - min(k.start for k in ks)
|
||||
busy = L.total(L.union([(k.start, k.end) for k in ks]))
|
||||
print(" span %.1f ms, busy %.1f ms, idle %.1f ms (%.1f%%)" % (span / 1e6, busy / 1e6, (span - busy) / 1e6, 100 * (span - busy) / max(1, span)))
|
||||
gp = gaps_with_reasons(tr, cs, a.gap_us * 1e3)
|
||||
why = defaultdict(lambda: [0, 0])
|
||||
for g in gp:
|
||||
w = why[g[2].split("(thr")[0].strip()]
|
||||
w[0] += 1
|
||||
w[1] += g[1] - g[0]
|
||||
print(" gaps >= %.0f us: %d, total %.1f ms (idle in smaller gaps: %.1f ms)" % (a.gap_us, len(gp), sum(g[1] - g[0] for g in gp) / 1e6, ((span - busy) - sum(g[1] - g[0] for g in gp)) / 1e6))
|
||||
for r, (n, t) in sorted(why.items(), key=lambda kv: -kv[1][1])[:10]:
|
||||
print(" %-60s %6d gaps %9.2f ms" % (r[:60], n, t / 1e6))
|
||||
print(" 10 longest gaps (ms from window start: length, reason, prev kernel -> next kernel):")
|
||||
for g in sorted(gp, key=lambda g: g[0] - g[1])[:10]:
|
||||
print(" @%9.2f %7.2f ms %s | %s -> %s" % ((g[0] - tr.t0) / 1e6, (g[1] - g[0]) / 1e6, g[2][:60], L.family(tr.kname(g[3]))[:28], L.family(tr.kname(g[4]))[:28]))
|
||||
cu = L.union([(c.start, c.end) for c in tr.copies if c.ckind in (1, 2)])
|
||||
cku = L.union([(k.start, k.end) for k in ks])
|
||||
if cu:
|
||||
ov = L.intersect_total(cu, cku)
|
||||
print(" copy/compute overlap: %.1f%% of H2D+D2H copy-busy time runs while a kernel executes (%.1f of %.1f ms)" % (
|
||||
100 * ov / max(1, L.total(cu)), ov / 1e6, L.total(cu) / 1e6))
|
||||
print(" copy-only time (no kernel running): %.1f ms" % ((L.total(cu) - ov) / 1e6))
|
||||
|
||||
print("\n== API/sync (CPU) time by call (sum of call durations)")
|
||||
ap_ = defaultdict(lambda: [0, 0, 0])
|
||||
for x in tr.apis:
|
||||
g = ap_[tr.names.get(x.name, "?")]
|
||||
g[0] += 1
|
||||
g[1] += x.end - x.start
|
||||
g[2] = max(g[2], x.end - x.start)
|
||||
for n, (c, t, mx) in sorted(ap_.items(), key=lambda kv: -kv[1][1])[:15]:
|
||||
print(" %-44s %8d calls %10.2f ms mean %8.1f us max %8.1f us" % (n[:44], c, t / 1e6, t / 1e3 / c, mx / 1e3))
|
||||
sy = defaultdict(lambda: [0, 0])
|
||||
for y in tr.syncs:
|
||||
g = sy[L.SYNCTYPE.get(y.type, y.type)]
|
||||
g[0] += 1
|
||||
g[1] += y.end - y.start
|
||||
for n, (c, t) in sy.items():
|
||||
print(" sync activity %-22s %6d %9.2f ms" % (n, c, t / 1e6))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,30 @@
|
||||
# regex over the kernel FAMILY name (lct.family), tab, engine-neutral step. First match wins; unmatched kernels keep a canonical family name.
|
||||
# "GUARD ..." = numerical-safety scans that exist only in the port (the Original has none).
|
||||
(mmq_finite|mmq_gu_finite|mmq_zero) GUARD MoE ring (finite/zero)
|
||||
moe_finite GUARD MoE other (finite)
|
||||
(gdn_finite|gdn_zero) GUARD GDN (finite/zero)
|
||||
qsa_prompt_(output_)?guard GUARD QSA (prompt guard)
|
||||
^gr_scan$ GUARD GR scan
|
||||
^(copy16|original_mmq_gather)$ MoE gather (expert blob -> MMQ slot)
|
||||
^mul_mat_q< MoE MMQ GEMM (mul_mat_q)
|
||||
^mul_mat_q_stream_k_fixup MoE MMQ GEMM (mul_mat_q)
|
||||
^quantize_mmq_q8_1 MoE activation quantize
|
||||
(^|_)swiglu(_pair)?$ MoE swiglu
|
||||
moe_combine MoE combine
|
||||
(^|_)route$ MoE route
|
||||
^Kernel2<cutlass cuBLAS/cutlass GEMM (projections)
|
||||
^(splitKreduce|gemvx|kernel$) cuBLAS GEMM (small/gemv/splitK)
|
||||
gdn_rec_cols_pipe GDN recurrence
|
||||
gdn_conv GDN conv
|
||||
gdn_out_norm GDN out norm
|
||||
gdn_l2 GDN l2
|
||||
gdn_gates GDN gates
|
||||
prompt_attn QSA attention (prompt)
|
||||
(qsa_score|block_scores) QSA select: scores
|
||||
(qsa_topk|block_topk) QSA select: topk
|
||||
(qsa_index|qsa_scan_half) QSA select: index/scan
|
||||
(kv_append|qsa_kv_append) KV append
|
||||
gr_write_norm_rs GR write+norm
|
||||
gr_mix_r GR mix
|
||||
gr_norm_rs|gr_norm_split GR norm
|
||||
(dequant) weight dequant
|
||||
@@ -0,0 +1,2 @@
|
||||
libleleka_cupti_trace.so
|
||||
test/test_app
|
||||
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the CUPTI tracer. Needs the CUDA toolkit headers (cuda.h not required) and the CUPTI redist (include/, lib/).
|
||||
# CUPTI=~/cupti ./build.sh -> libleleka_cupti_trace.so (RUNPATH: the build's CUPTI lib dir, ../cupti/lib, ~/work/cupti/lib)
|
||||
set -euo pipefail
|
||||
here=$(cd "$(dirname "$0")" && pwd)
|
||||
CUPTI=${CUPTI:-$HOME/cupti}
|
||||
CUDA=${CUDA:-$HOME/cuda-toolkits/13.2.2}
|
||||
out=${1:-$here/libleleka_cupti_trace.so}
|
||||
g++ -O2 -std=c++17 -fPIC -shared -Wall -Wextra -Wno-unused-parameter -I"$CUPTI/include" -I"$CUDA/include" \
|
||||
"$here/cupti_trace.cpp" -o "$out" -L"$CUPTI/lib" -lcupti -lpthread \
|
||||
-Wl,-rpath,"$CUPTI/lib" -Wl,-rpath,'$ORIGIN/../cupti/lib' -Wl,-rpath,'/home/para/work/cupti/lib' -Wl,--enable-new-dtags
|
||||
echo "built $out"
|
||||
@@ -0,0 +1,720 @@
|
||||
// cupti_trace.cpp - thin CUPTI Activity tracer, loadable into ANY CUDA process without modifying it.
|
||||
//
|
||||
// CUDA_INJECTION64_PATH=/path/libleleka_cupti_trace.so (the driver loads it at cuInit and calls InitializeInjection)
|
||||
// LD_PRELOAD=/path/libleleka_cupti_trace.so (the constructor does the same)
|
||||
// libcupti.so.13 is found through the library's RUNPATH (see build.sh) or LD_LIBRARY_PATH. Tracing is OFF until a window
|
||||
// is triggered; armed-but-idle cost is one thread that stat()s the trigger path every 50 ms.
|
||||
//
|
||||
// Windows (any number per process, one at a time; each writes its own output directory):
|
||||
// 1. Trigger file (long-lived daemons). LELEKA_CUPTI_TRIGGER=<path> (alias LCT_TRIGGER). Write one JSON line atomically
|
||||
// (tmp + rename): {"seconds": 8, "out": "/abs/prefix", "label": "free text"}
|
||||
// The library renames it to <path>.active, records until `seconds` (hard cap LCT_MAX_SECONDS, default 120) or until
|
||||
// <path>.stop exists, writes <out>.lct/ (the data) and <out>.done (JSON: bytes, counts, unix-ms start/stop), and renames
|
||||
// <path>.active to <path>.done. A trigger that arrives during a window is left in place and taken after it ends.
|
||||
// A failure to initialise CUPTI never affects the process: <path>.error gets the reason.
|
||||
// 2. Environment (one window): LCT_START_AFTER_S=<sec since load>, LCT_START_FILE=<path exists>,
|
||||
// LCT_START_API=<driver api name or prefix>:<N> (Nth call), LCT_START_SYM=<kernel-name substring>:<N>,
|
||||
// LCT_DURATION_S, LCT_STOP_FILE, LCT_STOP_API=<name>:<N> (counted after the start). With none of the start triggers and
|
||||
// no LELEKA_CUPTI_TRIGGER, recording starts at once. Output: $LCT_OUT/lct.<pid>/.
|
||||
// 3. LCT_SIGNALS=1: SIGUSR1 starts and SIGUSR2 stops the environment window.
|
||||
// Other: LCT_API=0 (no API records) | 1 (selected: launch/copy/sync/event/graph/alloc, default) | 2 (all);
|
||||
// LCT_BUF_MB (activity buffer, default 32); LCT_MAX_MB (cap per window, default 3072); LCT_VERBOSE=1.
|
||||
//
|
||||
// Window directory (fixed-size little-endian records, one file per kind, multi-MB stdio buffers, no per-record syscalls):
|
||||
// kernel.bin CONCURRENT_KERNEL incl. graph-launched (graphId/graphNodeId) KRec memcpy.bin MEMCPY + MEMCPY2 CRec
|
||||
// memset.bin MEMSET MRec sync.bin SYNCHRONIZATION (stream/event/context sync, stream wait) YRec
|
||||
// api.bin DRIVER/RUNTIME API ARec graph.bin GRAPH_TRACE GRec strings.tsv id<TAB>name threads.tsv tid<TAB>comm
|
||||
// meta.txt clocks (CUPTI ns <-> CLOCK_REALTIME), label, window marks.
|
||||
#include <cupti.h>
|
||||
#include <cupti_callbacks.h>
|
||||
#include <cupti_driver_cbid.h>
|
||||
#include <cupti_runtime_cbid.h>
|
||||
|
||||
#include <dirent.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/types.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <csignal>
|
||||
#include <cstdarg>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct KRec { // 80 bytes
|
||||
uint64_t start, end;
|
||||
uint32_t dev, stream, corr, graphId;
|
||||
uint64_t graphNodeId;
|
||||
uint32_t nameId;
|
||||
int32_t gx, gy, gz, bx, by, bz;
|
||||
int32_t sshm, dshm;
|
||||
uint16_t regs;
|
||||
uint8_t launchType, pad;
|
||||
};
|
||||
struct CRec { // 56 bytes
|
||||
uint64_t start, end, bytes;
|
||||
uint32_t dev, stream, corr, graphId;
|
||||
uint64_t graphNodeId;
|
||||
uint8_t copyKind, srcKind, dstKind, flags;
|
||||
uint32_t apiCorr;
|
||||
};
|
||||
struct MRec { // 48 bytes
|
||||
uint64_t start, end, bytes;
|
||||
uint32_t dev, stream, corr, graphId;
|
||||
uint16_t memKind, pad;
|
||||
};
|
||||
struct YRec { // 40 bytes
|
||||
uint64_t start, end;
|
||||
uint32_t corr, stream, eventId, type, ctx, ret;
|
||||
};
|
||||
struct ARec { // 40 bytes
|
||||
uint64_t start, end;
|
||||
uint32_t corr, thread, nameId, ret;
|
||||
uint8_t domain, pad[3];
|
||||
};
|
||||
struct GRec { // 40 bytes
|
||||
uint64_t start, end;
|
||||
uint32_t corr, graphId, dev, stream;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
namespace {
|
||||
|
||||
struct Out {
|
||||
FILE* f = nullptr;
|
||||
std::vector<char> buf;
|
||||
void open(const std::string& path, size_t bytes) {
|
||||
f = fopen(path.c_str(), "wb");
|
||||
if (f) {
|
||||
buf.assign(bytes, 0);
|
||||
setvbuf(f, buf.data(), _IOFBF, bytes);
|
||||
}
|
||||
}
|
||||
void put(const void* p, size_t n) {
|
||||
if (f) fwrite(p, 1, n, f);
|
||||
}
|
||||
void flush() {
|
||||
if (f) fflush(f);
|
||||
}
|
||||
void close() {
|
||||
if (f) fclose(f);
|
||||
f = nullptr;
|
||||
std::vector<char>().swap(buf);
|
||||
}
|
||||
};
|
||||
|
||||
struct Window {
|
||||
std::string out; // directory
|
||||
std::string prefix; // for <prefix>.done ("" for env windows)
|
||||
std::string label, trigger;
|
||||
double seconds = -1;
|
||||
bool fromTrigger = false;
|
||||
};
|
||||
|
||||
struct State {
|
||||
std::mutex mu; // protects the writers, string table and counters
|
||||
Out kern, copy, mset, sync, api, graph, strs, meta;
|
||||
std::unordered_map<std::string, uint32_t> strId;
|
||||
std::unordered_map<uint32_t, uint32_t> apiName[2];
|
||||
bool winOpen = false;
|
||||
uint64_t bytesOut = 0, maxBytes = 0;
|
||||
uint64_t counts[6] = {0, 0, 0, 0, 0, 0};
|
||||
std::atomic<bool> inited{false}, recording{false}, finished{false}, cuptiOk{false};
|
||||
std::atomic<bool> reqStart{false}, reqStop{false};
|
||||
std::atomic<uint64_t> startCnt{0}, stopCnt{0}, startTarget{0}, stopTarget{0}, symCnt{0}, symTarget{0};
|
||||
std::string symSubstr;
|
||||
std::vector<CUpti_CallbackId> startIds, stopIds;
|
||||
CUpti_SubscriberHandle sub = nullptr;
|
||||
uint64_t winStart = 0;
|
||||
uint64_t offReal = 0; // CLOCK_REALTIME ns - CUPTI ns
|
||||
int apiLevel = 1;
|
||||
bool verbose = false;
|
||||
size_t bufBytes = 32u << 20;
|
||||
int winSeq = 0;
|
||||
std::string trigger, errPath;
|
||||
};
|
||||
State S;
|
||||
|
||||
const char* envs(const char* k) {
|
||||
const char* v = getenv(k);
|
||||
return (v && *v) ? v : nullptr;
|
||||
}
|
||||
|
||||
#define CK(call) \
|
||||
do { \
|
||||
CUptiResult _r = (call); \
|
||||
if (_r != CUPTI_SUCCESS) { \
|
||||
const char* _m = nullptr; \
|
||||
cuptiGetResultString(_r, &_m); \
|
||||
fprintf(stderr, "[lct] %s failed: %s (%d)\n", #call, _m ? _m : "?", (int)_r); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
void writeFile(const std::string& path, const std::string& body) {
|
||||
FILE* f = fopen(path.c_str(), "w");
|
||||
if (!f) return;
|
||||
fwrite(body.data(), 1, body.size(), f);
|
||||
fclose(f);
|
||||
}
|
||||
|
||||
void mkdirs(const std::string& p) {
|
||||
for (size_t i = 1; i <= p.size(); ++i)
|
||||
if (i == p.size() || p[i] == '/') mkdir(p.substr(0, i).c_str(), 0755);
|
||||
}
|
||||
|
||||
uint32_t intern(const std::string& s) { // caller holds S.mu
|
||||
auto it = S.strId.find(s);
|
||||
if (it != S.strId.end()) return it->second;
|
||||
uint32_t id = (uint32_t)S.strId.size() + 1;
|
||||
S.strId.emplace(s, id);
|
||||
std::string line = std::to_string(id) + "\t" + s + "\n";
|
||||
S.strs.put(line.data(), line.size());
|
||||
return id;
|
||||
}
|
||||
|
||||
uint32_t apiNameId(int domain, uint32_t cbid) { // caller holds S.mu
|
||||
auto& m = S.apiName[domain];
|
||||
auto it = m.find(cbid);
|
||||
if (it != m.end()) return it->second;
|
||||
const char* name = nullptr;
|
||||
cuptiGetCallbackName(domain == 0 ? CUPTI_CB_DOMAIN_DRIVER_API : CUPTI_CB_DOMAIN_RUNTIME_API, cbid, &name);
|
||||
uint32_t id = intern(name ? name : ("cbid" + std::to_string(cbid)));
|
||||
m[cbid] = id;
|
||||
return id;
|
||||
}
|
||||
|
||||
void note(const char* fmt, ...) __attribute__((format(printf, 1, 2)));
|
||||
void note(const char* fmt, ...) { // caller holds S.mu or is single-threaded
|
||||
char b[768];
|
||||
va_list ap;
|
||||
va_start(ap, fmt);
|
||||
vsnprintf(b, sizeof b, fmt, ap);
|
||||
va_end(ap);
|
||||
S.meta.put(b, strlen(b));
|
||||
if (S.verbose) fputs(b, stderr);
|
||||
}
|
||||
|
||||
void handleRecord(CUpti_Activity* rec) { // caller holds S.mu, S.winOpen
|
||||
switch (rec->kind) {
|
||||
case CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL:
|
||||
case CUPTI_ACTIVITY_KIND_KERNEL: {
|
||||
auto* k = (CUpti_ActivityKernel11*)rec;
|
||||
KRec r{};
|
||||
r.start = k->start; r.end = k->end; r.dev = k->deviceId; r.stream = k->streamId; r.corr = k->correlationId;
|
||||
r.graphId = k->graphId; r.graphNodeId = k->graphNodeId;
|
||||
r.nameId = intern(k->name ? k->name : "?");
|
||||
r.gx = k->gridX; r.gy = k->gridY; r.gz = k->gridZ; r.bx = k->blockX; r.by = k->blockY; r.bz = k->blockZ;
|
||||
r.sshm = k->staticSharedMemory; r.dshm = k->dynamicSharedMemory; r.regs = k->registersPerThread;
|
||||
r.launchType = k->launchType;
|
||||
S.kern.put(&r, sizeof r); S.counts[0]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_MEMCPY: {
|
||||
auto* m = (CUpti_ActivityMemcpy6*)rec;
|
||||
CRec r{};
|
||||
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
|
||||
r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId;
|
||||
r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = m->flags;
|
||||
r.apiCorr = m->runtimeCorrelationId;
|
||||
S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_MEMCPY2: {
|
||||
auto* m = (CUpti_ActivityMemcpyPtoP4*)rec;
|
||||
CRec r{};
|
||||
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
|
||||
r.corr = m->correlationId; r.graphId = m->graphId; r.graphNodeId = m->graphNodeId;
|
||||
r.copyKind = m->copyKind; r.srcKind = m->srcKind; r.dstKind = m->dstKind; r.flags = 0x80;
|
||||
r.apiCorr = 0;
|
||||
S.copy.put(&r, sizeof r); S.counts[1]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_MEMSET: {
|
||||
auto* m = (CUpti_ActivityMemset4*)rec;
|
||||
MRec r{};
|
||||
r.start = m->start; r.end = m->end; r.bytes = m->bytes; r.dev = m->deviceId; r.stream = m->streamId;
|
||||
r.corr = m->correlationId; r.graphId = m->graphId; r.memKind = m->memoryKind;
|
||||
S.mset.put(&r, sizeof r); S.counts[2]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_SYNCHRONIZATION: {
|
||||
auto* m = (CUpti_ActivitySynchronization2*)rec;
|
||||
YRec r{};
|
||||
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.stream = m->streamId; r.eventId = m->cudaEventId;
|
||||
r.type = (uint32_t)m->type; r.ctx = m->contextId; r.ret = m->returnValue;
|
||||
S.sync.put(&r, sizeof r); S.counts[3]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_DRIVER:
|
||||
case CUPTI_ACTIVITY_KIND_RUNTIME: {
|
||||
auto* m = (CUpti_ActivityAPI*)rec;
|
||||
ARec r{};
|
||||
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.thread = m->threadId;
|
||||
r.domain = rec->kind == CUPTI_ACTIVITY_KIND_DRIVER ? 0 : 1;
|
||||
r.nameId = apiNameId(r.domain, m->cbid);
|
||||
r.ret = m->returnValue;
|
||||
S.api.put(&r, sizeof r); S.counts[4]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
case CUPTI_ACTIVITY_KIND_GRAPH_TRACE: {
|
||||
auto* m = (CUpti_ActivityGraphTrace2*)rec;
|
||||
GRec r{};
|
||||
r.start = m->start; r.end = m->end; r.corr = m->correlationId; r.graphId = m->graphId; r.dev = m->deviceId;
|
||||
r.stream = m->streamId;
|
||||
S.graph.put(&r, sizeof r); S.counts[5]++; S.bytesOut += sizeof r;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void CUPTIAPI bufferRequested(uint8_t** buffer, size_t* size, size_t* maxNumRecords) {
|
||||
*size = S.bufBytes;
|
||||
*maxNumRecords = 0;
|
||||
void* p = nullptr;
|
||||
if (posix_memalign(&p, 8, *size) != 0) p = nullptr;
|
||||
*buffer = (uint8_t*)p;
|
||||
}
|
||||
|
||||
void CUPTIAPI bufferCompleted(CUcontext, uint32_t, uint8_t* buffer, size_t, size_t validSize) {
|
||||
if (validSize > 0) {
|
||||
std::lock_guard<std::mutex> g(S.mu);
|
||||
if (S.winOpen) {
|
||||
CUpti_Activity* rec = nullptr;
|
||||
while (cuptiActivityGetNextRecord(buffer, validSize, &rec) == CUPTI_SUCCESS)
|
||||
if (S.bytesOut < S.maxBytes) handleRecord(rec);
|
||||
size_t dropped = 0;
|
||||
cuptiActivityGetNumDroppedRecords(nullptr, 0, &dropped);
|
||||
if (dropped) note("dropped_records %zu\n", dropped);
|
||||
}
|
||||
}
|
||||
free(buffer);
|
||||
}
|
||||
|
||||
bool selectedApi(const char* n) {
|
||||
static const char* const want[] = {"Launch", "Memcpy", "Memset", "Synchronize", "Event", "StreamWait", "Graph", "MemAlloc",
|
||||
"MemFree", "MemHost", "StreamCreate", "StreamDestroy", "StreamBeginCapture",
|
||||
"StreamEndCapture", "StreamWriteValue", "StreamWaitValue", "MemMap", "Malloc", "Free"};
|
||||
for (const char* w : want)
|
||||
if (strstr(n, w)) return !strstr(n, "Query"); // polling loops would drown everything
|
||||
return false;
|
||||
}
|
||||
|
||||
void enableKinds(bool on) {
|
||||
const CUpti_ActivityKind kinds[] = {CUPTI_ACTIVITY_KIND_CONCURRENT_KERNEL, CUPTI_ACTIVITY_KIND_MEMCPY,
|
||||
CUPTI_ACTIVITY_KIND_MEMCPY2, CUPTI_ACTIVITY_KIND_MEMSET,
|
||||
CUPTI_ACTIVITY_KIND_SYNCHRONIZATION};
|
||||
// GRAPH_TRACE records a graph launch as ONE item and hides its nodes (CUPTI docs): opt-in only (LCT_GRAPH_TRACE=1).
|
||||
if (envs("LCT_GRAPH_TRACE")) {
|
||||
CUptiResult r = on ? cuptiActivityEnable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE) : cuptiActivityDisable(CUPTI_ACTIVITY_KIND_GRAPH_TRACE);
|
||||
(void)r;
|
||||
}
|
||||
for (auto k : kinds) {
|
||||
CUptiResult r = on ? cuptiActivityEnable(k) : cuptiActivityDisable(k);
|
||||
if (on && r != CUPTI_SUCCESS) fprintf(stderr, "[lct] cuptiActivityEnable(%d) = %d\n", (int)k, (int)r);
|
||||
}
|
||||
if (S.apiLevel >= 1) {
|
||||
if (on) {
|
||||
cuptiActivityEnable(CUPTI_ACTIVITY_KIND_DRIVER);
|
||||
cuptiActivityEnable(CUPTI_ACTIVITY_KIND_RUNTIME);
|
||||
if (S.apiLevel == 1) { // all on, then switch the uninteresting entry points (queries, getters, pushes) off
|
||||
int nd = 0, nr = 0;
|
||||
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
|
||||
const char* n = nullptr;
|
||||
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) {
|
||||
cuptiActivityEnableDriverApi(cb, 0);
|
||||
nd++;
|
||||
}
|
||||
}
|
||||
for (uint32_t cb = 1; cb < CUPTI_RUNTIME_TRACE_CBID_SIZE; ++cb) {
|
||||
const char* n = nullptr;
|
||||
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_RUNTIME_API, cb, &n) == CUPTI_SUCCESS && n && !selectedApi(n)) {
|
||||
cuptiActivityEnableRuntimeApi(cb, 0);
|
||||
nr++;
|
||||
}
|
||||
}
|
||||
if (S.verbose) fprintf(stderr, "[lct] api filter: %d driver + %d runtime cbids off\n", nd, nr);
|
||||
}
|
||||
} else {
|
||||
cuptiActivityDisable(CUPTI_ACTIVITY_KIND_DRIVER);
|
||||
cuptiActivityDisable(CUPTI_ACTIVITY_KIND_RUNTIME);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
uint64_t cuptiNow() {
|
||||
uint64_t t = 0;
|
||||
cuptiGetTimestamp(&t);
|
||||
return t;
|
||||
}
|
||||
|
||||
void startWindow(const Window& w, const char* why) {
|
||||
mkdirs(w.out);
|
||||
{
|
||||
std::lock_guard<std::mutex> g(S.mu);
|
||||
const size_t B = 8u << 20;
|
||||
S.strId.clear(); S.apiName[0].clear(); S.apiName[1].clear();
|
||||
S.bytesOut = 0;
|
||||
for (auto& c : S.counts) c = 0;
|
||||
S.kern.open(w.out + "/kernel.bin", B);
|
||||
S.copy.open(w.out + "/memcpy.bin", B);
|
||||
S.mset.open(w.out + "/memset.bin", 1u << 20);
|
||||
S.sync.open(w.out + "/sync.bin", B);
|
||||
S.api.open(w.out + "/api.bin", B);
|
||||
S.graph.open(w.out + "/graph.bin", 1u << 20);
|
||||
S.strs.open(w.out + "/strings.tsv", 1u << 20);
|
||||
S.meta.open(w.out + "/meta.txt", 1u << 12);
|
||||
timespec rt{}, mono{};
|
||||
uint64_t ts = cuptiNow();
|
||||
clock_gettime(CLOCK_REALTIME, &rt);
|
||||
clock_gettime(CLOCK_MONOTONIC, &mono);
|
||||
S.offReal = (uint64_t)rt.tv_sec * 1000000000ull + rt.tv_nsec - ts;
|
||||
char exe[512] = {0};
|
||||
ssize_t n = readlink("/proc/self/exe", exe, sizeof exe - 1);
|
||||
if (n > 0) exe[n] = 0;
|
||||
note("format 1\npid %d\nexe %s\nlabel %s\ncupti_ts_ns %llu\nrealtime_ns %llu\nmonotonic_ns %lld\n", (int)getpid(), exe,
|
||||
w.label.c_str(), (unsigned long long)ts, (unsigned long long)(ts + S.offReal),
|
||||
(long long)mono.tv_sec * 1000000000LL + mono.tv_nsec);
|
||||
note("structs KRec=%zu CRec=%zu MRec=%zu YRec=%zu ARec=%zu GRec=%zu\napi_level %d\nreason %s\n", sizeof(KRec),
|
||||
sizeof(CRec), sizeof(MRec), sizeof(YRec), sizeof(ARec), sizeof(GRec), S.apiLevel, why);
|
||||
S.winStart = ts;
|
||||
S.winOpen = true;
|
||||
}
|
||||
enableKinds(true);
|
||||
S.recording.store(true);
|
||||
fprintf(stderr, "[lct] pid %d window '%s' started (%s) -> %s\n", (int)getpid(), w.label.c_str(), why, w.out.c_str());
|
||||
}
|
||||
|
||||
std::string threadTable() {
|
||||
std::string s;
|
||||
DIR* d = opendir("/proc/self/task");
|
||||
if (!d) return s;
|
||||
while (dirent* e = readdir(d)) {
|
||||
if (e->d_name[0] == '.') continue;
|
||||
std::string p = std::string("/proc/self/task/") + e->d_name + "/comm";
|
||||
FILE* f = fopen(p.c_str(), "r");
|
||||
if (!f) continue;
|
||||
char c[64] = {0};
|
||||
if (fgets(c, sizeof c, f)) {
|
||||
c[strcspn(c, "\n")] = 0;
|
||||
s += std::string(e->d_name) + "\t" + c + "\n";
|
||||
}
|
||||
fclose(f);
|
||||
}
|
||||
closedir(d);
|
||||
return s;
|
||||
}
|
||||
|
||||
std::string stopWindow(const Window& w, const char* why) {
|
||||
S.recording.store(false);
|
||||
enableKinds(false);
|
||||
CK(cuptiActivityFlushAll(CUPTI_ACTIVITY_FLAG_FLUSH_FORCED));
|
||||
uint64_t t = cuptiNow();
|
||||
std::string done;
|
||||
{
|
||||
std::lock_guard<std::mutex> g(S.mu);
|
||||
char b[640];
|
||||
snprintf(b, sizeof b,
|
||||
"{\"label\":\"%s\",\"reason\":\"%s\",\"dir\":\"%s\",\"pid\":%d,\"cupti_start_ns\":%llu,\"cupti_stop_ns\":%llu,"
|
||||
"\"unix_ms_start\":%llu,\"unix_ms_stop\":%llu,\"bytes\":%llu,\"kernels\":%llu,\"copies\":%llu,\"memsets\":%llu,"
|
||||
"\"syncs\":%llu,\"api\":%llu,\"graphs\":%llu}\n",
|
||||
w.label.c_str(), why, w.out.c_str(), (int)getpid(), (unsigned long long)S.winStart, (unsigned long long)t,
|
||||
(unsigned long long)((S.winStart + S.offReal) / 1000000ull), (unsigned long long)((t + S.offReal) / 1000000ull),
|
||||
(unsigned long long)S.bytesOut, (unsigned long long)S.counts[0], (unsigned long long)S.counts[1],
|
||||
(unsigned long long)S.counts[2], (unsigned long long)S.counts[3], (unsigned long long)S.counts[4],
|
||||
(unsigned long long)S.counts[5]);
|
||||
done = b;
|
||||
note("window_start %llu\nwindow_stop %llu\nstop_reason %s\n", (unsigned long long)S.winStart, (unsigned long long)t, why);
|
||||
S.winOpen = false;
|
||||
std::string th = threadTable();
|
||||
FILE* f = fopen((w.out + "/threads.tsv").c_str(), "w");
|
||||
if (f) {
|
||||
fwrite(th.data(), 1, th.size(), f);
|
||||
fclose(f);
|
||||
}
|
||||
S.kern.close(); S.copy.close(); S.mset.close(); S.sync.close(); S.api.close(); S.graph.close(); S.strs.close(); S.meta.close();
|
||||
}
|
||||
fprintf(stderr, "[lct] pid %d window '%s' stopped (%s): %s", (int)getpid(), w.label.c_str(), why, done.c_str());
|
||||
if (!w.prefix.empty()) writeFile(w.prefix + ".done", done);
|
||||
else writeFile(w.out + "/done.json", done);
|
||||
return done;
|
||||
}
|
||||
|
||||
void CUPTIAPI apiCallback(void*, CUpti_CallbackDomain domain, CUpti_CallbackId cbid, const CUpti_CallbackData* d) {
|
||||
if (domain != CUPTI_CB_DOMAIN_DRIVER_API || d->callbackSite != CUPTI_API_ENTER) return;
|
||||
if (!S.recording.load(std::memory_order_relaxed)) {
|
||||
if (S.startTarget.load() && !S.reqStart.load())
|
||||
for (auto id : S.startIds)
|
||||
if (id == cbid) {
|
||||
if (S.startCnt.fetch_add(1) + 1 == S.startTarget.load()) S.reqStart.store(true);
|
||||
break;
|
||||
}
|
||||
if (S.symTarget.load() && !S.reqStart.load() && d->symbolName && strstr(d->symbolName, S.symSubstr.c_str()))
|
||||
if (S.symCnt.fetch_add(1) + 1 == S.symTarget.load()) S.reqStart.store(true);
|
||||
} else if (S.stopTarget.load()) {
|
||||
for (auto id : S.stopIds)
|
||||
if (id == cbid) {
|
||||
if (S.stopCnt.fetch_add(1) + 1 == S.stopTarget.load()) S.reqStop.store(true);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<CUpti_CallbackId> findDriverIds(const std::string& name) {
|
||||
std::vector<CUpti_CallbackId> ids;
|
||||
for (int pass = 0; pass < 2 && ids.empty(); ++pass)
|
||||
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
|
||||
const char* n = nullptr;
|
||||
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) != CUPTI_SUCCESS || !n) continue;
|
||||
if (pass == 0 ? name == n : strncmp(n, name.c_str(), name.size()) == 0) ids.push_back(cb);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
bool parseNameN(const char* spec, std::string& name, uint64_t& n) {
|
||||
std::string s = spec;
|
||||
size_t c = s.rfind(':');
|
||||
if (c == std::string::npos) return false;
|
||||
name = s.substr(0, c);
|
||||
n = strtoull(s.c_str() + c + 1, nullptr, 10);
|
||||
return n > 0;
|
||||
}
|
||||
|
||||
// Minimal JSON field extraction for {"seconds": N, "out": "...", "label": "..."} (flat, no nested objects).
|
||||
std::string jsonStr(const std::string& j, const char* key) {
|
||||
std::string k = std::string("\"") + key + "\"";
|
||||
size_t p = j.find(k);
|
||||
if (p == std::string::npos) return "";
|
||||
p = j.find(':', p);
|
||||
if (p == std::string::npos) return "";
|
||||
p = j.find_first_not_of(" \t\r\n", p + 1);
|
||||
if (p == std::string::npos) return "";
|
||||
if (j[p] == '"') {
|
||||
std::string r;
|
||||
for (++p; p < j.size() && j[p] != '"'; ++p) {
|
||||
if (j[p] == '\\' && p + 1 < j.size()) ++p;
|
||||
r += j[p];
|
||||
}
|
||||
return r;
|
||||
}
|
||||
size_t e = j.find_first_of(",} \t\r\n", p);
|
||||
return j.substr(p, e == std::string::npos ? std::string::npos : e - p);
|
||||
}
|
||||
|
||||
bool takeTrigger(Window& w) {
|
||||
struct stat st;
|
||||
if (S.trigger.empty() || stat(S.trigger.c_str(), &st) != 0) return false;
|
||||
FILE* f = fopen(S.trigger.c_str(), "r");
|
||||
if (!f) return false;
|
||||
std::string j;
|
||||
char b[1024];
|
||||
size_t n;
|
||||
while ((n = fread(b, 1, sizeof b, f)) > 0 && j.size() < 65536) j.append(b, n);
|
||||
fclose(f);
|
||||
const double cap = envs("LCT_MAX_SECONDS") ? atof(envs("LCT_MAX_SECONDS")) : 120.0;
|
||||
std::string sec = jsonStr(j, "seconds"), out = jsonStr(j, "out");
|
||||
w = Window();
|
||||
w.fromTrigger = true;
|
||||
w.trigger = S.trigger;
|
||||
w.seconds = sec.empty() ? 10.0 : atof(sec.c_str());
|
||||
if (w.seconds > cap || w.seconds <= 0) w.seconds = cap;
|
||||
w.label = jsonStr(j, "label");
|
||||
for (auto& c : w.label)
|
||||
if (c == '"' || c == '\\' || c == '\n' || c == '\r') c = '_';
|
||||
if (out.empty()) out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string("/tmp")) + "/lct-win-" + std::to_string(++S.winSeq);
|
||||
w.prefix = out;
|
||||
w.out = out + ".lct";
|
||||
if (rename(S.trigger.c_str(), (S.trigger + ".active").c_str()) != 0) {
|
||||
writeFile(S.errPath, std::string("cannot rename trigger: ") + strerror(errno) + "\n");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void onSignal(int sig) {
|
||||
if (sig == SIGUSR1) S.reqStart.store(true);
|
||||
if (sig == SIGUSR2) S.reqStop.store(true);
|
||||
}
|
||||
|
||||
void watcher() {
|
||||
const double startAfter = envs("LCT_START_AFTER_S") ? atof(envs("LCT_START_AFTER_S")) : -1;
|
||||
const double envDur = envs("LCT_DURATION_S") ? atof(envs("LCT_DURATION_S")) : -1;
|
||||
const char* startFile = envs("LCT_START_FILE");
|
||||
const char* stopFile = envs("LCT_STOP_FILE");
|
||||
const bool hasEnvTrigger = startAfter >= 0 || startFile || S.startTarget.load() || S.symTarget.load() || envs("LCT_SIGNALS");
|
||||
bool immediate = S.trigger.empty() && !hasEnvTrigger && !envs("LCT_WAIT");
|
||||
bool envWindowPending = hasEnvTrigger || immediate;
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
auto secs = [&] { return std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count(); };
|
||||
struct stat st;
|
||||
Window cur;
|
||||
double winT0 = 0;
|
||||
bool active = false;
|
||||
int tick = 0;
|
||||
while (!S.finished.load()) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(50));
|
||||
if (!S.cuptiOk.load()) continue;
|
||||
if (!active) {
|
||||
const char* why = nullptr;
|
||||
if (takeTrigger(cur)) why = "trigger";
|
||||
else if (envWindowPending) {
|
||||
if (immediate) why = "immediate";
|
||||
else if (S.reqStart.load()) why = "signal/api";
|
||||
else if (startAfter >= 0 && secs() >= startAfter) why = "after_s";
|
||||
else if (startFile && stat(startFile, &st) == 0) why = "start_file";
|
||||
if (why) {
|
||||
cur = Window();
|
||||
cur.seconds = envDur;
|
||||
cur.out = (envs("LCT_OUT") ? std::string(envs("LCT_OUT")) : std::string(".")) + "/lct." + std::to_string((int)getpid());
|
||||
cur.label = "env";
|
||||
envWindowPending = false;
|
||||
immediate = false;
|
||||
}
|
||||
}
|
||||
if (why) {
|
||||
startWindow(cur, why);
|
||||
winT0 = secs();
|
||||
active = true;
|
||||
S.reqStart.store(false);
|
||||
S.reqStop.store(false);
|
||||
S.startTarget.store(0);
|
||||
S.symTarget.store(0);
|
||||
tick = 0;
|
||||
}
|
||||
} else {
|
||||
const char* why = nullptr;
|
||||
if (S.reqStop.load()) why = "signal/api";
|
||||
else if (cur.seconds > 0 && secs() - winT0 >= cur.seconds) why = "duration";
|
||||
else if (stopFile && !cur.fromTrigger && stat(stopFile, &st) == 0) why = "stop_file";
|
||||
else if (cur.fromTrigger && stat((S.trigger + ".stop").c_str(), &st) == 0) why = "stop_file";
|
||||
else if (S.bytesOut >= S.maxBytes) why = "max_mb";
|
||||
if (why) {
|
||||
stopWindow(cur, why);
|
||||
if (cur.fromTrigger) {
|
||||
rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str());
|
||||
unlink((S.trigger + ".stop").c_str());
|
||||
}
|
||||
active = false;
|
||||
S.stopTarget.store(0);
|
||||
} else if (++tick % 20 == 0) { // ~ every second: complete buffers reach the file even if the process is killed
|
||||
cuptiActivityFlushAll(0);
|
||||
std::lock_guard<std::mutex> g(S.mu);
|
||||
S.kern.flush(); S.copy.flush(); S.mset.flush(); S.sync.flush(); S.api.flush(); S.graph.flush(); S.strs.flush();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (active) {
|
||||
stopWindow(cur, "exit");
|
||||
if (cur.fromTrigger) rename((S.trigger + ".active").c_str(), (S.trigger + ".done").c_str());
|
||||
}
|
||||
}
|
||||
|
||||
void atExit() {
|
||||
if (!S.inited.load()) return;
|
||||
S.finished.store(true);
|
||||
// The watcher is detached and may still be inside a window: give it a moment to close the files.
|
||||
if (S.recording.load()) {
|
||||
for (int i = 0; i < 100 && S.recording.load(); ++i) std::this_thread::sleep_for(std::chrono::milliseconds(20));
|
||||
}
|
||||
}
|
||||
|
||||
void init() {
|
||||
bool exp = false;
|
||||
if (!S.inited.compare_exchange_strong(exp, true)) return;
|
||||
S.verbose = envs("LCT_VERBOSE") != nullptr;
|
||||
S.apiLevel = envs("LCT_API") ? atoi(envs("LCT_API")) : 1;
|
||||
if (envs("LCT_BUF_MB")) S.bufBytes = (size_t)atoi(envs("LCT_BUF_MB")) << 20;
|
||||
S.maxBytes = (uint64_t)((envs("LCT_MAX_MB") ? atof(envs("LCT_MAX_MB")) : 3072.0) * 1048576.0);
|
||||
const char* trig = envs("LELEKA_CUPTI_TRIGGER") ? envs("LELEKA_CUPTI_TRIGGER") : envs("LCT_TRIGGER");
|
||||
if (trig) {
|
||||
S.trigger = trig;
|
||||
S.errPath = S.trigger + ".error";
|
||||
}
|
||||
|
||||
// CUPTI setup; a failure only disables tracing.
|
||||
bool ok = true;
|
||||
auto chk = [&](CUptiResult r, const char* what) {
|
||||
if (r != CUPTI_SUCCESS) {
|
||||
const char* m = nullptr;
|
||||
cuptiGetResultString(r, &m);
|
||||
std::string e = std::string(what) + " failed: " + (m ? m : "?") + "\n";
|
||||
fputs(("[lct] " + e).c_str(), stderr);
|
||||
if (!S.errPath.empty()) writeFile(S.errPath, e);
|
||||
ok = false;
|
||||
}
|
||||
};
|
||||
chk(cuptiActivityRegisterCallbacks(bufferRequested, bufferCompleted), "cuptiActivityRegisterCallbacks");
|
||||
if (ok) {
|
||||
size_t sz = S.bufBytes, vs = sizeof sz;
|
||||
cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_SIZE, &vs, &sz);
|
||||
size_t lim = 32;
|
||||
vs = sizeof lim;
|
||||
cuptiActivitySetAttribute(CUPTI_ACTIVITY_ATTR_DEVICE_BUFFER_POOL_LIMIT, &vs, &lim);
|
||||
cuptiActivityFlushPeriod(1000);
|
||||
}
|
||||
|
||||
std::string nm;
|
||||
uint64_t cnt = 0;
|
||||
bool needSub = false;
|
||||
std::vector<CUpti_CallbackId> all;
|
||||
if (ok && envs("LCT_START_API") && parseNameN(envs("LCT_START_API"), nm, cnt)) {
|
||||
S.startIds = findDriverIds(nm);
|
||||
S.startTarget.store(cnt);
|
||||
needSub = true;
|
||||
all.insert(all.end(), S.startIds.begin(), S.startIds.end());
|
||||
}
|
||||
if (ok && envs("LCT_START_SYM") && parseNameN(envs("LCT_START_SYM"), nm, cnt)) {
|
||||
S.symSubstr = nm;
|
||||
S.symTarget.store(cnt);
|
||||
needSub = true;
|
||||
for (uint32_t cb = 1; cb < CUPTI_DRIVER_TRACE_CBID_SIZE; ++cb) {
|
||||
const char* n = nullptr;
|
||||
if (cuptiGetCallbackName(CUPTI_CB_DOMAIN_DRIVER_API, cb, &n) == CUPTI_SUCCESS && n && strncmp(n, "cuLaunchKernel", 14) == 0)
|
||||
all.push_back(cb);
|
||||
}
|
||||
}
|
||||
if (ok && envs("LCT_STOP_API") && parseNameN(envs("LCT_STOP_API"), nm, cnt)) {
|
||||
S.stopIds = findDriverIds(nm);
|
||||
S.stopTarget.store(cnt);
|
||||
needSub = true;
|
||||
all.insert(all.end(), S.stopIds.begin(), S.stopIds.end());
|
||||
}
|
||||
if (needSub) {
|
||||
chk(cuptiSubscribe(&S.sub, (CUpti_CallbackFunc)apiCallback, nullptr), "cuptiSubscribe");
|
||||
for (auto id : all) cuptiEnableCallback(1, S.sub, CUPTI_CB_DOMAIN_DRIVER_API, id);
|
||||
}
|
||||
if (envs("LCT_SIGNALS")) {
|
||||
signal(SIGUSR1, onSignal);
|
||||
signal(SIGUSR2, onSignal);
|
||||
}
|
||||
S.cuptiOk.store(ok);
|
||||
atexit(atExit);
|
||||
std::thread(watcher).detach();
|
||||
fprintf(stderr, "[lct] pid %d tracer %s (trigger %s)\n", (int)getpid(), ok ? "armed" : "DISABLED (CUPTI init failed)",
|
||||
S.trigger.empty() ? "env/immediate" : S.trigger.c_str());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
__attribute__((visibility("default"))) int InitializeInjection(void) {
|
||||
init();
|
||||
return 1;
|
||||
}
|
||||
__attribute__((constructor)) static void lctCtor() {
|
||||
// Under LD_PRELOAD the constructor runs before main. Under CUDA_INJECTION64_PATH the driver calls InitializeInjection.
|
||||
if (!envs("LCT_NO_CTOR") && !envs("CUDA_INJECTION64_PATH")) init();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// Tiny CUDA workload for the tracer self-test: kernels, graph launch, pinned/pageable H2D, memset, syncs. Runs ~SECONDS s.
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cuda_runtime.h>
|
||||
#include <unistd.h>
|
||||
__global__ void saxpy(float* y, const float* x, float a, int n) {
|
||||
int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < n) y[i] = a * x[i] + y[i];
|
||||
}
|
||||
int main(int argc, char** argv) {
|
||||
double secs = argc > 1 ? atof(argv[1]) : 6.0;
|
||||
const int n = 1 << 22;
|
||||
float *dx, *dy, *hp, *hq;
|
||||
cudaMalloc(&dx, n * 4); cudaMalloc(&dy, n * 4);
|
||||
cudaMallocHost(&hp, n * 4);
|
||||
hq = (float*)malloc(n * 4);
|
||||
for (int i = 0; i < n; i++) hp[i] = hq[i] = 1.0f;
|
||||
cudaStream_t s1, s2; cudaStreamCreate(&s1); cudaStreamCreate(&s2);
|
||||
cudaGraph_t g; cudaGraphExec_t ge;
|
||||
cudaStreamBeginCapture(s1, cudaStreamCaptureModeGlobal);
|
||||
for (int k = 0; k < 8; k++) saxpy<<<n / 256, 256, 0, s1>>>(dy, dx, 2.0f, n);
|
||||
cudaStreamEndCapture(s1, &g);
|
||||
cudaGraphInstantiate(&ge, g, 0);
|
||||
cudaMemset(dy, 0, n * 4);
|
||||
double t0 = 0; timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); t0 = ts.tv_sec + ts.tv_nsec * 1e-9;
|
||||
long it = 0;
|
||||
for (;;) {
|
||||
cudaMemcpyAsync(dx, hp, n * 4, cudaMemcpyHostToDevice, s2); // pinned
|
||||
cudaMemcpyAsync(dx, hq, n * 4 / 4, cudaMemcpyHostToDevice, s2); // pageable
|
||||
cudaStreamSynchronize(s2);
|
||||
cudaGraphLaunch(ge, s1);
|
||||
saxpy<<<n / 256, 256, 0, s2>>>(dy, dx, 1.0f, n);
|
||||
cudaStreamSynchronize(s1);
|
||||
cudaDeviceSynchronize();
|
||||
usleep(2000);
|
||||
it++;
|
||||
clock_gettime(CLOCK_MONOTONIC, &ts);
|
||||
if (ts.tv_sec + ts.tv_nsec * 1e-9 - t0 > secs) break;
|
||||
}
|
||||
printf("done iterations=%ld\n", it);
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user