Merge branch 'claude/ledger' into claude/prefill-overlap

This commit is contained in:
Pavlo Ratushnyi
2026-10-23 16:09:03 +02:00
26 changed files with 1962 additions and 10 deletions
@@ -158,6 +158,15 @@ impl Context<'_> {
}
}
}
const PAGE: usize = 4096;
/// Extra bytes a ring slot needs to hold three page-aligned supersets next to each other: the pieces start up to one page
/// early and end up to one page late.
pub(crate) const ALIGNED_COPY_SLACK: usize = 3 * 2 * PAGE;
/// `LELEKA_PREFILL_ALIGNED_COPY=0` turns the page-aligned expert copies off (the A/B switch; default on).
pub(crate) fn aligned_copy_enabled() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var("LELEKA_PREFILL_ALIGNED_COPY").map_or(true, |v| v != "0"))
}
impl<'ctx> MappedExpertBank<'ctx> {
pub(crate) fn cache_context_matches(&self, context: &Context<'_>) -> bool {
!self.closed && std::ptr::eq(self.context, context)
@@ -191,6 +200,37 @@ impl<'ctx> MappedExpertBank<'ctx> {
.get(span.offset()..end)
.ok_or(Error::InvalidSize)
}
/// The 4 KiB-aligned superset of `cache_source(span)` inside the same registered tensor and the offset of the span in it
/// (claude/ledger): the DMA engine reads host memory ~15 % faster from page-aligned runs (the expert pieces start at
/// `expert * piece_bytes`, i.e. at arbitrary offsets; job 907/9051 and the CUPTI ledger: 36-40 GB/s unaligned, 47-50 aligned).
/// The superset is clamped to the tensor (a registered range), so it never reads outside the bank.
pub(crate) fn cache_source_aligned(&self, span: &ResidentExpertBankSpan) -> Result<(&[u8], usize)> {
let exact = self.cache_source(span)?;
let layer = match span.role() {
TensorRole::Layer { layer, .. } => layer,
_ => return Err(Error::InvalidSize),
};
let role = match span.role() {
TensorRole::Layer { role, .. } => role,
_ => return Err(Error::InvalidSize),
};
let n = usize::from(layer) * 3
+ match role {
LayerRole::FfnGateExperts => 0,
LayerRole::FfnUpExperts => 1,
LayerRole::FfnDownExperts => 2,
_ => return Err(Error::InvalidSize),
};
let member = self.banks.get(n).ok_or(Error::InvalidSize)?.member.bytes();
let base = member.as_ptr() as usize;
let (start, end) = (exact.as_ptr() as usize, exact.as_ptr() as usize + exact.len());
let a = (start & !(PAGE - 1)).max(base);
let b = ((end + PAGE - 1) & !(PAGE - 1)).min(base + member.len());
if a > start || b < end {
return Err(Error::InvalidSize);
}
Ok((&member[a - base..b - base], start - a))
}
pub(crate) fn retained_span_handle(
&self,
span: &ResidentExpertBankSpan,
@@ -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
+35 -3
View File
@@ -450,6 +450,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.
@@ -615,6 +617,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.
@@ -788,6 +791,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.
@@ -812,6 +816,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])?,
@@ -840,6 +868,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
Ok(())
})?;
}
}
events
.copied
.as_mut()
@@ -848,6 +877,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(())
}
@@ -867,6 +897,7 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
let down = formats[2].layout(1)?.raw_weight;
let sl = source.slot;
let entry = source.entry;
let dest = source.dest;
let raw = if let Some(raw) = source.resident {
raw
} else if let Some(k) = entry {
@@ -900,10 +931,11 @@ impl<'read, 'ctx> Ring<'read, 'ctx> {
.as_ref()
.ok_or(Error::ContextPoisoned)?,
)?;
let at = dest.unwrap_or([0, gu, gu * 2]);
[
slot.span.checked_subspan(slot.bytes, 0, gu)?,
slot.span.checked_subspan(slot.bytes, gu, gu)?,
slot.span.checked_subspan(slot.bytes, gu * 2, down)?,
slot.span.checked_subspan(slot.bytes, at[0], gu)?,
slot.span.checked_subspan(slot.bytes, at[1], gu)?,
slot.span.checked_subspan(slot.bytes, at[2], down)?,
]
};
// Destination checks are closed to actual group-bank ranges. All source
@@ -242,7 +242,9 @@ impl PrefillLayoutOptions {
}
let ring_slots = self.original_ring_slots()?;
// Names intentionally share one role; the index is the span occurrence.
for _ in 0..ring_slots { a.take("stage_dev", self.max_expert_blob, 1)?; }
// room for three page-aligned supersets (claude/ledger: LELEKA_PREFILL_ALIGNED_COPY, default on)
let slot_bytes = if crate::mapped_expert_bank::aligned_copy_enabled() { add(self.max_expert_blob, crate::mapped_expert_bank::ALIGNED_COPY_SLACK)? } else { self.max_expert_blob };
for _ in 0..ring_slots { a.take("stage_dev", slot_bytes, 1)?; }
a.rows("ple_emb", t, N, 4)?;
a.take("ple_norm", D, 4)?;
let mut owned = Alloc::new(PrefillPhase::Common);
+11 -2
View File
@@ -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"));
}
+23
View File
@@ -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"
+113
View File
@@ -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
+112
View File
@@ -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}'
}
+247
View File
@@ -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
+254
View File
@@ -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()
+219
View File
@@ -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()
+30
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
libleleka_cupti_trace.so
test/test_app
+12
View File
@@ -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"
+720
View File
@@ -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();
}
}
+42
View File
@@ -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;
}