diff --git a/crates/cuda-driver/src/mapped_expert_bank.rs b/crates/cuda-driver/src/mapped_expert_bank.rs index a8a96ca5..f25e5eaa 100644 --- a/crates/cuda-driver/src/mapped_expert_bank.rs +++ b/crates/cuda-driver/src/mapped_expert_bank.rs @@ -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 = 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 diff --git a/crates/cuda-driver/src/mmq_original_ring.rs b/crates/cuda-driver/src/mmq_original_ring.rs index 0510cfcd..35f2cf63 100644 --- a/crates/cuda-driver/src/mmq_original_ring.rs +++ b/crates/cuda-driver/src/mmq_original_ring.rs @@ -450,6 +450,8 @@ struct Source<'read> { job: Option, /// the chunk stream entry of an expert the issuer copies (`begin_prompt_stream`) entry: Option, + /// 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 diff --git a/crates/cuda-driver/src/original_prefill_layout.rs b/crates/cuda-driver/src/original_prefill_layout.rs index 8a6b116a..6622423e 100644 --- a/crates/cuda-driver/src/original_prefill_layout.rs +++ b/crates/cuda-driver/src/original_prefill_layout.rs @@ -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); diff --git a/crates/cuda-driver/src/qsa_prompt_attention.rs b/crates/cuda-driver/src/qsa_prompt_attention.rs index 710c4416..aad5f34a 100644 --- a/crates/cuda-driver/src/qsa_prompt_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_attention.rs @@ -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> = 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) +} diff --git a/crates/cuda-driver/src/qsa_prompt_device_attention.rs b/crates/cuda-driver/src/qsa_prompt_device_attention.rs index 407cf227..3d06face 100644 --- a/crates/cuda-driver/src/qsa_prompt_device_attention.rs +++ b/crates/cuda-driver/src/qsa_prompt_device_attention.rs @@ -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")); } diff --git a/crates/cuda-driver/src/qsa_resident_attention.rs b/crates/cuda-driver/src/qsa_resident_attention.rs index e933024d..59d8eecd 100644 --- a/crates/cuda-driver/src/qsa_resident_attention.rs +++ b/crates/cuda-driver/src/qsa_resident_attention.rs @@ -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")); } diff --git a/scripts/profile/build_rt.sh b/scripts/profile/build_rt.sh new file mode 100644 index 00000000..2d64d875 --- /dev/null +++ b/scripts/profile/build_rt.sh @@ -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" diff --git a/scripts/profile/h2d_src_probe.cu b/scripts/profile/h2d_src_probe.cu new file mode 100644 index 00000000..6648fe3f --- /dev/null +++ b/scripts/profile/h2d_src_probe.cu @@ -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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#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 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 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 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; +} diff --git a/scripts/profile/jobs/9001-ledger-h2d-probe.sh b/scripts/profile/jobs/9001-ledger-h2d-probe.sh new file mode 100644 index 00000000..28d49660 --- /dev/null +++ b/scripts/profile/jobs/9001-ledger-h2d-probe.sh @@ -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 diff --git a/scripts/profile/jobs/9002-ledger-aligned-ab.sh b/scripts/profile/jobs/9002-ledger-aligned-ab.sh new file mode 100644 index 00000000..13380364 --- /dev/null +++ b/scripts/profile/jobs/9002-ledger-aligned-ab.sh @@ -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 diff --git a/scripts/profile/jobs/901-ledger-port-prefill16k.sh b/scripts/profile/jobs/901-ledger-port-prefill16k.sh new file mode 100644 index 00000000..e7d6b08b --- /dev/null +++ b/scripts/profile/jobs/901-ledger-port-prefill16k.sh @@ -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 diff --git a/scripts/profile/jobs/902-ledger-orig-prefill16k.sh b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh new file mode 100644 index 00000000..e17f9f55 --- /dev/null +++ b/scripts/profile/jobs/902-ledger-orig-prefill16k.sh @@ -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 diff --git a/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh new file mode 100644 index 00000000..2fcede75 --- /dev/null +++ b/scripts/profile/jobs/9021-ledger-orig-prefill16k-off.sh @@ -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 diff --git a/scripts/profile/jobs/903-ledger-port-180k.sh b/scripts/profile/jobs/903-ledger-port-180k.sh new file mode 100644 index 00000000..0810d90d --- /dev/null +++ b/scripts/profile/jobs/903-ledger-port-180k.sh @@ -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 diff --git a/scripts/profile/jobs/904-ledger-orig-180k.sh b/scripts/profile/jobs/904-ledger-orig-180k.sh new file mode 100644 index 00000000..d8ae891c --- /dev/null +++ b/scripts/profile/jobs/904-ledger-orig-180k.sh @@ -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 diff --git a/scripts/profile/jobs/905-ledger-port-decode.sh b/scripts/profile/jobs/905-ledger-port-decode.sh new file mode 100644 index 00000000..1f9ca4ad --- /dev/null +++ b/scripts/profile/jobs/905-ledger-port-decode.sh @@ -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 diff --git a/scripts/profile/jobs/906-ledger-orig-decode.sh b/scripts/profile/jobs/906-ledger-orig-decode.sh new file mode 100644 index 00000000..5de0bc37 --- /dev/null +++ b/scripts/profile/jobs/906-ledger-orig-decode.sh @@ -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 diff --git a/scripts/profile/jobs/ledger-common.sh b/scripts/profile/jobs/ledger-common.sh new file mode 100644 index 00000000..332f33e4 --- /dev/null +++ b/scripts/profile/jobs/ledger-common.sh @@ -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}' +} diff --git a/scripts/profile/lct.py b/scripts/profile/lct.py new file mode 100644 index 00000000..502aabfc --- /dev/null +++ b/scripts/profile/lct.py @@ -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": ("= 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 (