Files
leleka/docs/ledger.md
T

22 KiB

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.

5. Decode round (6-prompt corpus x 2 passes x 128 greedy tokens, spec 4 + suffix 3, min_p 0.5, 2048 slots/layer, STATIC residency, --adapt-every 0)

Jobs 905/906 (default profile) and 9062 (a static tier ranked by the corpus's own routing: the Original served the corpus once with --dump-routing, make_profile.py --no-base), windows re-aligned in job 9004 so that both engines are traced over the same request (corpus prompt 1, pass 0: 65 prompt tokens, 128 generated). Each round is a few CUDA graph launches; kernels carry the launch's correlation id, so lct_decode.py gives the GPU span of each graph exactly.

Decode tok/s of the whole corpus (jobs 905, 906, 9062, 9004; decode phase only; prompts 0-4, 12 requests per column; tokens differ a little between arms because the placement and the drafts differ, so aggregate rates are indicative, n = 1 per arm):

prompt / pass Original std port std Original corpus-profile port corpus-profile port std + draft vocabulary port hit + draft vocabulary
0 / 0, 1 47.3, 47.9 52.9, 58.3 68.3, 70.8 54.7, 60.0 63.1, 70.0 62.0, 69.2
1 / 0, 1 61.0, 62.9 69.6, 81.7 73.7, 77.1 71.8, 83.6 68.4, 76.1 65.2, 76.5
2 / 0, 1 53.1, 53.6 56.7, 65.2 59.8, 60.2 61.6, 64.8 58.5, 61.9 58.6, 61.7
3 / 0, 1 42.9, 44.4 75.3, 79.0 56.8, 57.8 77.7, 81.7 57.0, 59.1 56.6, 59.0
4 / 0, 1 63.0, 62.6 76.0, 77.4 76.1, 78.5 73.7, 77.5 73.3, 75.4 72.7, 77.9
aggregate 52.7 68.5 67.2 69.4 65.6 65.4

At static residency the port is not behind the Original on this corpus (+30 % with the default profile; on par, +3 %, when the Original also gets the corpus-own profile, where it gains 28 %). The port seeds its tier from the prompt's routing (prefill.seed), which the Original does not, so the profile matters little to it. (docs/decode-parity.md measured the adaptive tier, a different regime; this ledger did not repeat it.)

One round of corpus prompt 1 pass 0 (default profile), traced:

per round port Original
verify windows for 128 tokens (tokens per window) 36 (3.56) 41 (3.12)
graph start to start (verify graph + draft + commit + host) 51.1 ms 51.2 ms (own timer 51.18)
verify-window graph GPU span 44.2 ms 47.8 ms
idle between verify graphs (draft chain, commit, sampling, host) 5.64 ms 4.10 ms
PCIe/CPU stage inside the window 31.4 ms of verify_wait_flag_ge (DMA of 33.5 GB total, 1,724 cuMemcpyBatchAsync, busy 1,016 ms, 33.0 GB/s) 36.0 ms of fetch_blobs copy-kernel time in a parallel graph branch (wait_flag_ge only 0.55 ms)
everything else in the window graph (GR 3.4, head 2.9, MoE 2.8, GDN 0.65, QSA 0.8, dense 0.6) ~11 ms ~10 ms
MTP chain-step graph 112 kernels, 0.683 ms (launch call 108 us) 61 kernels, 0.421 ms (launch call 55 us)
MTP extension step / commit graph 172 kernels 0.818 ms / 158 kernels 0.463 ms 95 kernels 0.620 ms / 158 kernels 0.605 ms
cuGraphLaunch host time 100.4 ms in 177 launches 86.4 ms in 197

Findings:

  1. The window is bounded by the PCIe/CPU leg in both engines (31-36 ms of 44-48 ms); the port's DMA runs at 33 GB/s because its expert pieces (3 per expert, unaligned) share the host memory bus with the CPU pool; the decode copies have the same unaligned shape as the prefill ring and could use the aligned-superset trick (expert_pieces_aligned), which is for decode-parity/schedule to try (it costs 1.2 % more bytes).
  2. The draft chain step is 0.26 ms longer in the port: 0.18 ms is the vocabulary of the draft head. The smokes (and the daemon default, --mtp-rt-dir unset) bind no draft_vocab.bin, so the MTP head is the main model's full 248,320-row Q6_K head (head_n14_s0, 309 us, sampler 38 us, row_top_prob 36 us) while the Original drafts over 106,299 rows (native_q6_k_mmvq 133 us, 28 us, 16 us); about 0.03 ms is the ~40 mtp_original_finite/q8_guard kernels (0.75 us each) of the port's chain. With LELEKA_ORIGINAL_SERVE_RT_DIR=<mtp pack> the port's chain step is 0.466 ms (Original 0.421), but the draft quality changes: tokens per window and decode tok/s become prompt-dependent (prompt 0 +19 %, prompt 3 -22..-25 %, aggregate -4 %, last two columns), which is why the Original itself is at 43-44 tok/s on prompt 3. The default stays the full-vocabulary head; this is a configuration property to decide (e2e bound the subset in run-e2e.sh/deploy).
  3. Extra draft + commit work per round: +1.5 ms (5.64 vs 4.10 ms between graphs: 3.9 small graphs per window against 3.8, each with a 100-200 us launch call (Original 55-125 us) and longer chain steps). The per-round overhead matters more as the tier hit rate rises (the PCIe leg shrinks), but at the measured hit rates the port's higher tokens per window pays for it.
  4. Not found: any decode kernel that is slower in the port than the same step in the Original (GR, MoE, GDN, QSA, head per-window sums are within a few percent).

Live Codex windows: the CRM job (945) ran with the tracer armed ([lct] tracer armed in inference.log, decode 78-83 tok/s during the session, so armed-idle costs nothing visible) but no window was requested (~/work/codex-e2e/cupti/ is empty); a future run needs scripts/e2e/cupti_trigger.sh SECONDS LABEL calls at a late-context prefill, a decode-heavy turn and a tool-call turn. The expected differences from the synthetic runs (many short suffix prefills after cache hits, import/restore of K/V windows) are in prefix.* spans of the engine's own profile, not in this ledger.

6. Follow-up: claude/perf3 (RTX 5090; details in docs/prefill-throughput.md and docs/chain-kernels.md section 8)

item before after evidence status
window GR read (hyper-connection, 96 per window), 4 rows 33.8 us per read (3.25 ms) Original kernels; 29.3 us (2.81 ms) first chain pass 22.0 us (2.11 ms) model-free chain_probe, cold weights, graph timing, every output byte equal to the Original's kernels (every T from 1 to 8, with and without injection) kernel-level; end-to-end window A/B = job p36, queued
QSA late-chunk selection (qsa_late.cu), 100k / 180k cold prefill QSA stage 4,004 / 8,588 ms 3,890 / 8,372 ms (-2.8 / -3.1 %); wall -1.6 % (180k) / +1.0 % (100k), inside the pass-to-pass noise paired passes in one process, R hash of every chunk equal default on
prefill chunk 8192 vs 2048 in a replayed live session (40 requests) TTFT sum 60.3 s, window 22.2-22.5 ms per round TTFT sum 45.7-54.8 s (-9..-24 %), window 22.1-22.3 ms per round, warm turns +90 ms job p32 (ABBA, one process) needs the loan ladder (p34/p35 queued) for the warm-turn cost
4.2 -> 0.26 ms top-k headline of the qsa-late branch - not reproducible: the first launch of the probe process; real -0.07 ms per launch at 180k qsa_late::gpu_tests rerun corrected

Where the next prefill time is (180k prompt, last quarter, per 8192-row chunk): tc scores 131 ms at 147k (the Original's 3xTF32 qsa_score_tc, which re-splits the query operand into hi/lo for every key tile), kv copy_prefix 37 ms, topk ~70 ms after this branch; for live sessions the 0.45-0.6 s fixed cost of every batched chunk, even of 10 tokens (the Original reads tails of up to 64 tokens through verify windows), and the 131 ms/request prefill.seed of the prompt-routing seed.

256k reference on the 5090 (job 9w1, 2026-10-26)

Long-context smoke (original_serve_long_context_streamed_kv_smoke, one process per length): final build rt-final, rtx5090 tier (30 GiB budget, 2048 expert slots per layer, PCIe fraction 0.55), LELEKA_CHAIN=all, KV resident and max context 262,144, 64 generated tokens, single runs. It exercises prefill and a short decode, not the serve loop with speculation.

prompt tokens prefill s prefill tok/s 64-token decode s
28,000 (job 9w0, 13 GiB budget / 30 GiB budget) 15.7 / 15.8 1,781 / 1,775 0.7 / 0.8 (4 tokens)
100,000 53.8 1,857 3.2
180,000 99.3 1,813 3.1
250,000 141.5 1,767 3.1

Prefill throughput stays flat (about 1.8k tok/s) from 28k to 250k, so a 256k prompt is a two-and-a-half-minute prefill on the 5090. This is the reference for the laptop (about 160 tok/s there, STRA-235). Not measured here: decode speed with speculation at depth, the prefix-cache hit at 256k, quality at depth (the teacher-forced gate runs at 128-token corpus lengths).

256k-class agent session through the real stack (job 9w2, 2026-10-26)

One conversation of real Rust source (scripts/e2e/long_session.py), each turn adds about 50k tokens and keeps the model's reply in the history; gateway + engine as in the live Codex jobs (--prefix-cache-mib auto --prefix-cache-tail reply, speculation on, LELEKA_CHAIN=all, context 262,144, 30 GiB budget), single run, thinking on, streamed.

turn input tokens served from cache TTFT s decode tok/s output tokens
1 46,749 0 27.0 91.0 371
2 98,923 45,056 27.8 108.9 700 (cap)
3 171,626 98,304 38.6 105.8 700 (cap)
4 222,988 163,840 31.9 107.2 700 (cap)
5 268,761 - refused: context_length_exceeded (prompt + 700 over 262,144; the driver's size estimate overshot, default target lowered to 215k)

Each turn prefills only what the previous turns did not cover (the cache serves in blocks of 2,048 tokens), so TTFT stays 27-39 s at 100-220k tokens of context. Decode with speculation holds about 105-109 tok/s at 100-220k tokens, against ~167 tok/s on the short CRM replay (different workload; the drop at depth is not yet explained or A/B'd). The requests are captured (private) for replay. Not measured here: quality at depth, the same session on the laptop, the sweep of one variable at a time.