docs/ledger.md: prefill ledger, tools, probe, fixes; lct_decode.py

This commit is contained in:
Pavlo Ratushnyi
2026-10-23 19:38:11 +02:00
parent eb9470545f
commit 3118c5ec0d
3 changed files with 249 additions and 0 deletions
+120
View File
@@ -0,0 +1,120 @@
# Kernel-level ledger: where the port loses time against the unmodified Original (`claude/ledger`)
RTX 5090 (PCIe 5 x16), driver 595.99, CUDA 13.2, CUPTI 13.2.86, Ryzen 9 9950X3D. Port head `7330ddb` (the `rt-base` test binary) against the
Original `~/work/numerics-orig/build/strata`, both traced with the same CUPTI Activity tracer inside holder jobs (one profiling pass per scenario,
not an A/B of the Original; the tracer costs 2.4 % of a 16,000-token prefill: 4,335.6 ms traced against 4,234.2 ms untraced, same binary).
## 1. Tools and how to rerun
| piece | where | what |
| --- | --- | --- |
| tracer | `tools/cupti-trace/` (C++, not shipped; `build.sh` in WSL, copy `libleleka_cupti_trace.so` to the server) | CUPTI Activity: concurrent kernels (graph-launched ones per node with `graphId`), memcpy/memcpy2 (kind, bytes, stream, source/destination memory kind), memset, stream/event/context synchronization, driver+runtime API of launch/copy/sync/event/graph/alloc calls. Loaded without touching the process: `CUDA_INJECTION64_PATH=.../libleleka_cupti_trace.so` (or `LD_PRELOAD`). Off until a window is requested, so an armed process costs one 50 ms `stat()` poll. |
| windows | trigger file `LELEKA_CUPTI_TRIGGER=<path>`: write `{"seconds": N, "out": "/abs/prefix", "label": "x"}` atomically; the library renames it `.active`, records N s (cap 120, `LCT_MAX_SECONDS`), writes the data to `<out>.lct/` and the summary `<out>.done` (unix-ms bounds of the window), renames the trigger `.done`; `<trigger>.stop` ends a window early; any number of windows per process, a failure to initialise CUPTI only writes `<trigger>.error`. Env-only variants: `LCT_START_AFTER_S`, `LCT_START_FILE`, `LCT_START_API=cuMemcpyHtoDAsync:N`, `LCT_START_SYM=<kernel substring>:N`, `LCT_DURATION_S`. `LCT_API=0` drops the API records. | used by the holder jobs below and by the e2e CRM job (`scripts/e2e/cupti_trigger.sh`) |
| format | per window a directory of fixed-size little-endian record files (`kernel.bin memcpy.bin memset.bin sync.bin api.bin graph.bin`, `strings.tsv`, `threads.tsv`, `meta.txt`), no per-record syscalls | `scripts/profile/lct.py` loads it (pure Python, no numpy; `window_ms=` skips records while loading; kernel names are demangled with `c++filt`, cached) |
| single window | `python3 scripts/profile/lct_report.py <dir.lct> [--stamps job.full --chunk N]` | kernel families, copies (kind, memory kinds, sizes, achieved GB/s of every H2D copy), GPU idle gaps with the host-side cause, copy/compute overlap, API time |
| port vs Original | `python3 scripts/profile/lct_ledger.py PORT.lct ORIG.lct --p-marker leleka_prefill_embed_broadcast --o-marker gr_broadcast --chunk 1` (or `--p-t0/--p-t1/--o-t0/--o-t1` in ms from each window start); step names are mapped by `scripts/profile/steps.map` | the tables below |
| decode round | `python3 scripts/profile/lct_decode.py <dir.lct> --t0 MS --t1 MS` | per graph launch (verify window, MTP draft/commit steps) GPU span, idle between graphs, per-category kernel time, copies, host calls |
| jobs | `scripts/profile/jobs/*.sh` (copy next to `ledger-common.sh` into `~/work/ledger/` and the numbered job into `~/work/gpu-runs/holder2/jobs/`): `901` port 16k, `902/9021` Original 16k, `903/904` 180k, `905/906` decode, `9062` decode with a corpus-own profile, `9001` H2D probe, `9002/9003` fix gates, `9004` aligned decode windows; binaries: `scripts/profile/build_rt.sh TAG` builds the test binary of the worktree in WSL | |
Align a trace with the engine's own profile lines: the job logs (`<label>.full`) stamp every output line with the unix time, `PREFILL-PROFILE` lines
end a chunk and carry `total_ms`, so `lct.chunk_windows` gives each chunk's window; CUPTI nanoseconds equal CLOCK_REALTIME nanoseconds on this host.
## 2. Prefill chunk (16,000-token prompt, chunk 8192, second chunk = 7,807 tokens at positions 8192-16000, pass 2 of the process)
Port tier off (`port-16k-off`) against the Original with the tier on (`orig-16k-on`; the Original refuses `--serve` without the tier, and its
8192-token chunks exist only with lent slots). The port's tier-on trace is the same within 1 % (`port-16k-on`: 2,113.7 ms, 38.4 GB per chunk).
| metric (ms unless noted) | port `7330ddb` | Original | difference |
| --- | ---: | ---: | ---: |
| chunk wall | 2,140.9 | 1,474.2 | +666.7 |
| GPU busy (union of all streams) | 1,211.6 | 1,246.5 | -34.9 |
| GPU idle, gaps >= 50 us | 775.7 | 153.5 | +622.2 |
| GPU idle, gaps < 50 us | 153.6 | 74.2 | +79.5 |
| kernel launches | 41,978 | 73,904 (incl. the Original's MTP draft KV, ~150 ms of kernels) | |
| H2D copies / bytes | 57,355 / 38.9 GB (routed experts, 3 pieces each) | 24,392 / 50.0 GB (all 512 experts of every layer, 1 blob each) | |
| H2D rate over the copy-busy union | **36.2 GB/s** | **49.5 GB/s** | -13.3 |
| copy busy overlapped by a kernel | 31 % | 80 % | |
| copy-only time (a copy runs, no kernel) | 747.3 | 199.6 | +547.7 |
Idle by cause (gaps >= 50 us): port 618.8 ms "PCIe copy running, no kernel", 146.1 ms `cuMemcpyDtoH` round trips, 8.2 ms `cuCtxSynchronize`, 2.3 ms
`cuMemcpyHtoD`; Original 146.8 ms copy wait, 7.3 ms stream syncs. Blocking host calls per chunk: port 775 `cuMemcpyDtoH` + 742 `cuMemcpyHtoD` (pageable,
tiny: GR scan flags, 250 KB per-row scalars, the routed slot table) + 1,537 `cuCtxSynchronize` + 739 `cuStreamSynchronize` (1,668 ms host wait, mostly behind the
ring); the Original has 50 `cudaStreamSynchronize` and no synchronous copy.
Kernel time per step, sum of kernel durations, port / Original (identical code and speed; the port is never slower where the step exists in both):
| step | port ms | Original ms |
| --- | ---: | ---: |
| cutlass/cuBLAS projections | 282.6 | 276.1 |
| MoE MMQ GEMM | 255.8 | 249.6 |
| GDN recurrence | 147.6 | 146.2 |
| QSA attention (prompt) | 84.0 | 82.9 |
| GR write+norm / GR mix | 51.6 / 45.2 | 54.1 / 46.9 |
| MoE gather / combine | 47.1 / 27.9 | 51.7 / 29.8 |
| QSA select: scores + index/scan + topk | 26.1 + 11.1 + 9.8 | 14.7 + 0 + 14.6 |
| weight dequantization | 15.5 | 42.9 |
| KV append | 11.7 | 23.0 (per-token kernels) |
| **port-only guards** (finite/zero scans): MoE ring 60.7, QSA prompt+output guard 33.9, MoE other 9.3, GR scan 4.5, GDN 3.9 | **112.3** | 0 |
| Original-only: MTP draft-head prefill (native_mmvq_multi, gr_down_staged, norm, embed_rows ...) | 0 | ~150 |
First chunk of a pass (8192 tokens): port 2,189 ms against 1,432 (+757); same causes (copy-only 728 against 83 ms, copy overlap 32 % against 92 %).
Late chunk of a 180,000-token prompt (jobs 903/904; port chunk 18 at positions 147,456-155,647: 2,505 ms for 8192 tokens; the Original chunks 6144
tokens, chunk 24 at the same position: 1,531 ms = 2,041 ms per 8192 tokens): +464 ms. Kernels scale per token (GEMM 297 / 295, GDN recurrence 155.5 / 153, QSA attention
89.5 / 88.6 normalised to 8192 tokens), the port again loses in copy-only time (825 ms against 328 ms scaled), the 37.7 GB/s H2D rate (Original 49.7), 154 ms of
readbacks. The port chunk grows from 2,215 ms (position 8192) to 2,540 ms (position 172,000) with the QSA selection over the streamed KV; the Original's
chunk grows 1,219 -> 1,550 ms. Whole 180k prefill: port 54.6 s (traced), Original 40.3 s.
### Top contributors to the 667 ms of the 8192-class chunk
1. **Expert PCIe stream not overlapped with compute: ~550 ms** (copy-only GPU time 747 against 200 ms). The ring drains every layer; only 31 % of the copy time runs under a kernel.
(owner: `claude/prefill-overlap`, the chunk expert stream.)
2. **Expert copy rate, 36.2 against 49.5 GB/s: ~290 ms of the ring's copy time.** Not piece size (35.2 GB/s at 460 KB, 36.5 at 700 KB, overhead ~0.8 us per copy), not the source
memory kind (cudaHostAlloc, registered anonymous 4 KiB pages, THP, PORTABLE or DEVICEMAP all within 1 %, probe job 9001, 16 GiB footprint), not kernel overlap (36.4 with no kernel
running); it is the unaligned source: the pieces start at `expert * 682000` bytes. Aligned 4 KiB supersets reach 47-50 GB/s (probe: 3 x 682000 unaligned 38.5, 4 KiB-aligned stride 41.2,
one 2,046,000-byte blob 43.2, 4 KiB-aligned blob 50.4, 8 MiB 51; the roofline agent's 24 GiB probe: 36.9 raw, 41.5 64 B-rounded, 47.0 4 KiB superset, 50-51 for runs of 4-16 consecutive experts).
**Fixed here** (section 4).
3. **Host round trips: ~154 ms** of GPU idle (775 `cuMemcpyDtoH`, 742 `cuMemcpyHtoD`, 1,537 context syncs per chunk; 16 per layer: GR status flags, the 250 KB per-row scalar readbacks, the routed slot table).
QSA layers add ~25 stage guards each with a 64-byte D2H + sync + H2D reset. Open (deferred status words; prefill-overlap / schedule own the drains).
4. **Small gaps < 50 us: +80 ms** (154 against 74 ms): 42k driver-API launches and 40k event records/waits per chunk against graph launches.
5. **Port-only guard kernels: 112 ms of GPU time**, of which 34 ms (QSA prompt + output guard, a 64-block grid that left 100+ SMs idle: 1.84 + 1.0 ms per layer) is exposed on the critical path.
**Fixed here** (full grid, 13.4 ms). The MoE-ring guards (61 ms) sit under the copy-bound ring and only matter once the copies overlap.
Not a contributor: kernel speed (all shared steps within +-3 %, the port's dequantization and KV append are faster).
## 3. Probe: what limits an expert copy (`scripts/profile/h2d_src_probe.cu`, job 9001, 16 GiB per source kind, 1 stream, depth 16)
| shape (GB/s) | cudaHostAlloc | anon 4K + register(0) | register(DEVICEMAP) = the port's bank | anon THP + register(DEVICEMAP) |
| --- | ---: | ---: | ---: | ---: |
| 3 x 682,000 role-major (unaligned, the port) | 38.5 | 38.3 | 38.5 | 38.8 |
| 3 x 682,000, 4 KiB-aligned stride | 41.2 | 40.9 | 41.2 | 41.5 |
| 1 x 2,046,000 contiguous (the Original's blob) | 43.3 | 40.7 | 43.2 | 43.6 |
| 1 x 2,046,000, 4 KiB-aligned stride | 50.5 | 50.7 | 50.4 | 50.9 |
| 1 x 2 MiB aligned / 1 x 8 MiB | 50.5 / 51.2 | 50.0 / 50.9 | 50.0 / 50.9 | 51.4 / 51.6 |
A read-only file mapping cannot be registered with `CU_MEMHOSTREGISTER_READ_ONLY` here ("operation not supported"; the port's pageable path stages it). In the real
pipeline `LELEKA_BANK_THP=on` changed nothing either (job 9001: pass 2 of the 16,000-token prompt 4,311 ms against 4,336).
## 4. Fixes on this branch (paired with the previous head, same binary, switches)
Both are bit-identical by construction and by gate: the FNV-1a hash of the final residual R of both chunks (`LELEKA_TRACE_PREFILL_R=1`: `7ea88178bf76c5a1` for the 8192 rows and
`8a27594e2b566315` for the 7807 rows) and the 16 greedy ids (`271,248068,271,248069,271,760,6038,1440,1787,369,220,19,23,16,22,27325`) are identical with the changes on and off (jobs 9002, 9003).
| change | switch | 16,000 tokens, pass 2, untraced (ms; tok/s) |
| --- | --- | --- |
| previous behaviour | `LELEKA_PREFILL_ALIGNED_COPY=0 LELEKA_PREFILL_GUARD_GRID=64` | 4,214.5 / 4,211.1 (3,796 / 3,799) |
| page-aligned expert copies (ring) | `LELEKA_PREFILL_ALIGNED_COPY` (default on) | 3,768.6 (4,245) |
| both | defaults | 3,749.9 / 3,747.7 (4,266 / 4,269): **-463 ms, -11.0 %, +12.4 % tok/s** |
| QSA guard grid on top (binary `rt-ledger2`, aligned copies on in both arms; job 9003, ABAB) | `LELEKA_PREFILL_GUARD_GRID` (default full grid; `64` = literal) | grid 64: 3,743.9 / 3,745.5 (4,274 / 4,272); full grid: 3,703.7 / 3,697.9 (4,320 / 4,327): **-43 ms, -1.1 %** |
CUPTI of the second chunk with the aligned copies: H2D 36.2 -> 47.4 GB/s over the copy-busy union (826 against 1,076 ms), copy-only GPU time 747 -> 507 ms, chunk 2,141 -> 1,903 ms.
The guard grid takes the QSA prompt/output guards from 33.9 to 13.4 ms per chunk (chunk 1,903 -> 1,882 ms).
* Aligned copies: `MappedExpertBank::cache_source_aligned` / `expert_pieces_aligned` return the 4 KiB-aligned superset of a piece clamped to its registered tensor (at most 8 KiB more per piece, 1.2 %
more bytes); the ring copies the three supersets to page offsets of the ring slot (slot + 24 KiB, `original_prefill_layout.rs`) and `gather` reads each piece at its lead offset
(the gather kernel already takes three separate source pointers). `claude/prefill-overlap` merged the same trick into the chunk stream (`ChunkStream` entries carry the superset pieces).
* Guard grid: `qsa_prompt_attention.rs`, `qsa_resident_attention.rs`, `qsa_prompt_device_attention.rs` launched the grid-stride guards with 64 blocks; they now use `clamp(ceil(t * 6144 / 1024), 64, 2048)`.
Next copy-path steps (open, owners prefill-overlap / schedule): one copy per role per run of consecutive experts (50-51 GB/s in the probe, also fewer copies), `cuMemcpyBatchAsync` of the group's pieces (48.9 GB/s of
3 x 16 raw pieces), and the deferral of the per-stage status readbacks.
DECODE_SECTION
@@ -8,3 +8,8 @@ CP=$LD/corpus-profile.bin
port_corpus port-corpus-b 7 10
[ -e $CP ] && port_corpus port-corpus-hit-b 7 10 LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$CP
date -u +%FT%TZ
# the port with the Original's draft vocabulary: LELEKA_ORIGINAL_SERVE_RT_DIR = the MTP pack (dense.bin, experts.bin, draft_vocab.bin). Without it the smokes
# bind no draft_vocab subset and the MTP head is the full 248,320-row Q6_K head (309 us per chain step) instead of the Original's 106,299-row head (133 us).
port_corpus port-corpus-rt 7 10 LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
[ -e $CP ] && port_corpus port-corpus-hit-rt 7 10 LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$CP LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
date -u +%FT%TZ
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Decode-round ledger of one CUPTI window: graph launches (verify windows and MTP draft/commit steps), their GPU spans, idle between them,
the PCIe stage and the host calls around them.
python3 scripts/profile/lct_decode.py <dir.lct> [--t0 MS --t1 MS] [--big 1000]
Every decode round is a handful of CUDA graph launches: one big verify-window graph (>= --big kernels: 48 layers of GDN/QSA/GR/MoE kernels, the PCIe
stage as copy-kernel branch (Original: fetch_blobs) or as DMA with flag waits (port: verify_wait_flag_ge)) and small MTP graphs (draft chain steps,
commit). Kernels carry the correlation id of their graph launch, so the GPU span of each launch is exact. Output: per graph class the number of
launches, GPU span, kernel-sum, launch-call cost and launch->first-kernel latency; the idle time between consecutive graph executions (host: sampling,
planning, CPU-pool wait); H2D copies by stream; per-category kernel time of the big graphs.
"""
import argparse
import collections
import os
import re
import statistics
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lct as L
CATS = [
(r"fetch_blobs|copy_rows_from_mapped|copy_from_mapped|copy_i32_from_mapped|copy_indexed|doorbell_publish", "PCIe stage / doorbell / copies"),
(r"wait_flag_ge", "flag waits (CPU/PCIe)"),
(r"gdn", "GDN"),
(r"qsa|attn_chunk|attn_merge|kv_append|block_topk|append|^gate$", "QSA"),
(r"gr_|^norm$|add_streams|weighted_rms|post|pre_final|pre_gated|down_silu", "GR / HC"),
(r"moe|gu_|down_grouped|group_resident|route|swiglu|combine|quantize_q8_0|native_(gu|down|swiglu)|window_moe", "MoE"),
(r"head|sampler|row_top_prob|native_q6_k|map_ids|mtp_select", "head / sampler"),
(r"mtp", "MTP chain"),
(r"mmvq|mmvf|quantize", "dense projections"),
]
def cat(fam):
for rx, name in CATS:
if re.search(rx, fam):
return name
return "other"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("dir")
ap.add_argument("--t0", type=float, default=None)
ap.add_argument("--t1", type=float, default=None)
ap.add_argument("--big", type=int, default=1000)
a = ap.parse_args()
win = None if a.t0 is None and a.t1 is None else (a.t0 or 0, a.t1 if a.t1 is not None else 1e12)
t = L.Trace(a.dir, window_ms=win)
W = (t.t1 - t.t0) / 1e6
gl = {x.corr: x for x in t.apis if "GraphLaunch" in t.names.get(x.name, "")}
byc = collections.defaultdict(list)
for k in t.kernels:
byc[k.corr].append(k)
rows = []
for corr, x in gl.items():
ks = byc.get(corr)
if not ks:
continue
rows.append(dict(call_start=x.start, call=x.end - x.start, s=min(k.start for k in ks), e=max(k.end for k in ks), n=len(ks),
ksum=sum(k.end - k.start for k in ks), ks=ks))
rows.sort(key=lambda r: r["s"])
big = [r for r in rows if r["n"] >= a.big]
small = [r for r in rows if r["n"] < a.big]
print("== %s: %.0f ms window, %d graph launches with kernels (%d verify-window graphs, %d small)" % (a.dir, W, len(rows), len(big), len(small)))
def stat(name, rs):
if not rs:
return
span = [(r["e"] - r["s"]) / 1e6 for r in rs]
print(" %-28s x%-4d GPU span mean %7.3f ms (p10 %.3f p90 %.3f), kernel sum %7.3f ms, launch call %6.1f us, call->first kernel %7.1f us" % (
name, len(rs), statistics.mean(span), sorted(span)[len(span) // 10], sorted(span)[len(span) * 9 // 10],
statistics.mean(r["ksum"] for r in rs) / 1e6, statistics.mean(r["call"] for r in rs) / 1e3,
statistics.mean(r["s"] - r["call_start"] for r in rs) / 1e3))
stat("verify-window graphs", big)
groups = collections.defaultdict(list)
for r in small:
groups[r["n"]].append(r)
for n, rs in sorted(groups.items(), key=lambda kv: -sum(r["e"] - r["s"] for r in kv[1]))[:6]:
stat("small graph, %d kernels" % n, rs)
spans = sorted((r["s"], r["e"]) for r in rows)
gaps = []
cur = spans[0][1] if spans else 0
for s, e in spans[1:]:
if s > cur:
gaps.append(s - cur)
cur = max(cur, e)
busy = L.total(L.union(spans))
print(" graph execution busy %.1f ms of %.1f ms; idle between graph executions %.1f ms in %d gaps (mean %.0f us, p90 %.0f us)" % (
busy / 1e6, W, sum(gaps) / 1e6, len(gaps), (statistics.mean(gaps) / 1e3 if gaps else 0), (sorted(gaps)[len(gaps) * 9 // 10] / 1e3 if gaps else 0)))
if big:
wall = [(b["s"] - a_["e"]) for a_, b in zip(big, big[1:])]
per_round = (big[-1]["e"] - big[0]["s"]) / max(1, len(big) - 1)
print(" one verify window every %.2f ms on average (graph start to start, includes draft/commit and host work)" % (per_round / 1e6))
print(" between consecutive verify graphs: idle %.2f ms mean (draft + commit + host)" % (statistics.mean(wall) / 1e6))
print(" per-category kernel time of the verify-window graphs (ms per window):")
cs = collections.defaultdict(float)
for r in big:
for k in r["ks"]:
cs[cat(L.canon(L.family(t.kname(k))) if hasattr(L, "canon") else L.family(t.kname(k)))] += k.end - k.start
for c, v in sorted(cs.items(), key=lambda kv: -kv[1]):
print(" %-34s %8.2f" % (c, v / len(big) / 1e6))
cp = collections.defaultdict(lambda: [0, 0, 0])
for c in t.copies:
x = cp[(L.CKIND.get(c.ckind), L.MKIND.get(c.skind), c.stream)]
x[0] += 1
x[1] += c.bytes
x[2] += c.end - c.start
for k, v in sorted(cp.items(), key=lambda kv: -kv[1][1])[:5]:
print(" copies %-28s %7d, %9.1f MB, busy %8.1f ms, %5.1f GB/s" % (k, v[0], v[1] / 1e6, v[2] / 1e6, v[1] / max(1, v[2])))
api = collections.defaultdict(lambda: [0, 0])
for x in t.apis:
y = api[t.names.get(x.name)]
y[0] += 1
y[1] += x.end - x.start
print(" host calls (CPU ms): " + ", ".join("%s %d x %.1f" % (k.replace("_v3020", "").replace("_v10000", ""), v[0], v[1] / 1e6)
for k, v in sorted(api.items(), key=lambda kv: -kv[1][1])[:7]))
if __name__ == "__main__":
main()