diff --git a/docs/experiments/vram-hit-share-gap.md b/docs/experiments/vram-hit-share-gap.md new file mode 100644 index 00000000..8aefb39d --- /dev/null +++ b/docs/experiments/vram-hit-share-gap.md @@ -0,0 +1,154 @@ +# VRAM hit share of the routed experts: why ours is below vanilla, and what to try (ledger C6, H1-H7) + +Date 2026-11-11. Research only: no host code, no GPU, no server writes (read-only `ssh rnr5090`, `nice`, stdlib Python). Branch `claude/hit-share-gap`. +Labels: M measured in the run or log named, E estimate or model, U unverified. Nothing here is a performance claim; the speed numbers quoted are from earlier paired A/B runs, recomputed from their logs. + +## 0. Answer first + +The hit share of the 30-request replay (`nestng-crm-r2`, token-weighted by output tokens) is **92.1 % for ours (adaptive window, 76 blocks) against 93.4 % for vanilla (two replays)**; unweighted per request 90.2 against 91.8. With vanilla's fixed window (B, one block) the gap is smaller: 92.7 against 93.4 (unweighted 90.8 against 91.8). The H1 figures (90.8 against 92.8, -2.0) are not reproducible from the surviving logs (section 1); the gap is **-0.7 to -1.3 points token-weighted, -1.0 to -1.6 unweighted**. + +The tier policy is the same code as vanilla's and swaps at the same rate. What differs, in order of measured weight: + +| rank | cause | evidence | share of the gap (token-weighted) | +| ---: | --- | --- | ---: | +| 1 | **Fewer VRAM slots**: 12,192 (254 in every layer) against 12,575 | clean paired A/B: +192 slots give +0.44 points (CI +0.24..+0.64), so 383 slots are worth about +0.9 (M, extrapolated) | about 0.9 of 1.3 | +| 2 | **Wider speculation window**: ours adapts the window up to T=8, vanilla runs T<=6 at 2.95 tokens a round. Hit share per entry falls with T inside our own run: 96 % at T<=3, 94.8 % at T=4, 90.5 % at T=7-8 | B (fixed window 4) is 0.55 points above A (n=1 B, M); within-run curve (M, one run) | about 0.55 of 1.3 (absent when B is compared) | +| 3 | **Global against per-layer slot allocation**: vanilla gives layers 173 to 372 slots from the global rank of the profile, ours 254 each | the layers vanilla favours show the excess misses in ours (r = 0.82 over 48 layers, M); the net hit share effect is second order, E +0.12..+0.16 points at equal slot count | about 0.15 (E) | +| - | tier policy constants, swap volume, tie order, seed, prefix cache | identical constants; 15.6 against 13.1 swaps a round; tie order A/B +0.04 (CI -0.20..+0.29); seed off in both; nothing in the prefix path touches the tier | 0 within noise | +| - | first rounds of a request (H7) | ours: 79 % in windows 0-3, 85 % in 16-31, 90 % in 32-63, 93 % from window 128 (M, one run); the first 64 windows carry 20 % of all misses; vanilla cannot be measured per window | a property of both engines; not a gap cause that can be shown | + +The sum of 1-3 (1.5) is about the observed gap (1.3 token-weighted, 1.6 unweighted), so **no large unexplained policy or start-up effect is left**; the three do not separate cleanly (section 5). + +Two things the same data say that matter more than the parity question: (1) the cap of 96 swaps binds in every short request in both engines (21-25 swaps a round = 96 / 4), and adapting every 2 rounds already gave **+0.56 points of hit share and +1.31 % decode (CI +0.77..+1.85, n=5 pairs)** (M); (2) the rounds at the start of a request hold 20 % of all misses (section 2, H7). Both are ways to go above vanilla, not to reach it. + +## 1. Data and definitions + +* Ours: the `engine.log` request line of every replay block (`tier_vram_pct` = VRAM entries / (VRAM + PCIe + CPU entries), entries per row of every window, rejected draft rows included; `crates/leleka-memory/src/telemetry/lock.rs`, `source_spans.rs` `tally_group`). Vanilla: `strata serve: decode expert cache hit rate ... of all N routed` (hits / all routed entries, `N` = rows x 480). Same quantity. Route tail skip is OFF in A, B, L, D, H, W*, X, so all of them are comparable; the E/T/K arms skip entries, are not in `all`, and show 93.6-95 %: **not comparable to vanilla**. +* Replay: the 30 first requests of VANL `nestng-crm-r2`, the same recorded prompts through both engines. Ours: `runs/ab-l1`, `ab-l3`, `ab-l3v2`, `ab-l5v2`, `ab-l6`, `ab-l7`, `ab-sm`, `ab-sqe`, `ab-sqn`, `ab-w`, `memory-tier-tie-spread-ab`, `main/{A,B,P}` under `/data/leleka-e2e/spd-gap/runs/`. Vanilla: `main/VANL-noprof` and `main/VANLP` (the only two vanilla replay logs, engine 0.1.50 at pin `41cf05a0`, `--spec 4 --spec-min-p 0.5`, `--expert-cache auto`, profile sha256 `8f59b4aa...` = ours, `--expert-profile /home/para/work/vanilla-strata/control/data/expert-profile.bin`). +* Script: `scripts/e2e/codex/speed/hit_share_gap.py` (`arms`, `pairs`, `requests`, `windows`, `swaps`; run on the server with `nice python3 -I - CMD < script`), `hit_share_layers.py` (local). + +Hit share of the first 30 requests (M, `hit_share_gap.py arms`): + +| source | blocks | token-weighted | unweighted | time-weighted | tokens/round | +| --- | ---: | ---: | ---: | ---: | ---: | +| ours A (adaptive window): per experiment, A and L arms of nine experiments (76 A blocks pooled in the per-request table) | 5-10 each | 92.05-92.25 (sd 0.2-0.3 per block) | 90.2 | 92.1-92.3 | 3.9 | +| ours B (fixed window 4, floor 0.5), `main/B` | 1 | 92.66 | 90.76 | 92.67 | 3.09 | +| vanilla `VANL-noprof` | 1 | 93.32 | 91.84 | 93.40 | 2.95 (ledger Q9) | +| vanilla `VANLP` | 1 | 93.49 | 91.75 | 93.59 | | + +H1 (90.8 against 92.8): the ours side is close to B over the 59-request replay (both cells, unweighted 90.94); the 92.8 on the vanilla side I cannot reproduce from the two surviving replays of 30 requests (91.8 unweighted, 93.6 entry-weighted). Real sessions (H2, `session_hit.py` re-run, M): nestng-crm 91.38 against 92.41 (-1.03), ttt 92.68 against 93.38 (-0.70). + +## 2. Cause by cause + +### (a) Slots + +* Ours: `expert cache 12192 slots (23.24 GiB, per layer)` = 254 x 48 (`runs/main/A/engine.log`); the prompt path lends its last 2,226. Vanilla: `expert cache 12575 slots, 23.87 GiB`, lends 2,089 (`main/VANL-noprof/engine.log`). `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000` is only the identity-job setting (a static tier for bitwise comparisons); the product runs `auto`. +* The 383 slots are 744 MiB: 647 MiB less free VRAM before the cache (24,717 against 25,364 MiB: second token table 324, PLE row cache 64, prompt stage and MoE arena, `vram-footprint-5090.md` section 2 and `vram-footprint2-5090.md`) and 97 MiB more reserve (ours 700 + 300 against vanilla 700 + 218 for its draft head). The planner grows in whole 48-slot quota steps (`vram-footprint3-5090.md`: reserve 130 freed 170 MiB and added 48 slots). +* **Slope (M)**: `ab-l3v2`, 10 pairs, H (reserves 130 / 500 MiB, 12,384 slots) against A (12,192): hit share +0.44 points token-weighted (CI +0.24..+0.64), +0.41 unweighted; decode tok/s +0.67 % (CI +0.02..+1.31), ms/round -2.10 % (CI -3.61..-0.59), tokens/round -1.45 % (CI -3.20..+0.31). That is 0.23 points per 100 slots, so 383 slots = +0.88 points (CI 0.48..1.28 if linear). +* Why "H gained nothing" earlier: the first attempt G (`--gpu-budget-gib 31`) opened the same 12,192 slots in both arms (the card binds, not the budget): a null experiment. The first H pairs ran with leaked variables (`spd_ab_job.sh` did not unset them, `ab-l3h-contaminated`, not evidence). The clean rerun above is a real, significant hit-share and ms/round gain; the end-to-end figure (+1.06 %, CI -0.38..+2.50) is just not significant. `vram-footprint3-5090.md` (3 pairs, `both` = alias + reserve 130, 12,384 slots, lowest free 355 MiB, +1.69 % tok/s) agrees in sign and is inside its noise. Free VRAM at decode: H cuts the reserves by 370 MiB; the 130 MiB decode reserve alone keeps 407 MiB (vanilla runs at 315-389); the 500 MiB VRAM reserve is what goes below vanilla's floor (E, not read in a log). + +### (b) Initial placement, per-layer against global + +* Same profile in both (sha256 `8f59b4aa8873...`, ours `ours-assets/data/expert-profile.bin`). **Vanilla's log says `PROFILE, ranked by routing frequency, no eviction` and `pre-filled 12575 of 12575 slots`**: global fill (no `--expert-cache-per-layer`), so the layer quotas are the counts of each layer in the first 12,575 ranks of the profile. Ours: `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes` (profile `rtx5090-32g.json`), every layer 254. Quotas of the global fill (profile bytes, M): min 173 (layer 15), max 372 (layer 0), 31 layers above 254; 680 slots sit in a different layer than in ours at equal slot count (888 at 12,575). Swaps are paired inside a layer in both engines, so the quotas never change after the start. +* **Per-layer evidence (M)**: CUPTI windows of request 29 (`cupti/VANL`, `cupti/CL.1`, `verify-new-switches-cupti-windows/CY.1`, `hit_share_layers.py`): share of layer-windows with a miss leg (class C or X of `ffn_phase_timeline.py`) per layer, ours minus vanilla, against the quota difference: Pearson **0.82** (0.78 at T 3-4 only). 16 layers where vanilla has 20 or more extra slots (avg +48): ours has **+0.196** more miss-leg layer-windows; 9 donor layers (avg -45): **-0.095**; the 23 neutral layers +0.028. OLS slope 0.0027-0.0031 of miss-leg share per slot. The quota is therefore visible per layer. +* **Net effect (E)**: reallocating at equal slot count only exchanges pairs near the rank boundary, whose calibration frequencies are close. A power-law model f(rank) ~ rank^-alpha over the profile's global ranks gives +0.12 to +0.16 points for global against uniform fill at 12,192 slots (alpha 0.5-0.9), and +0.44..+1.10 for the 383 extra slots (0.79 at alpha 0.7 = 0.21 per 100 slots, close to the measured 0.23). So the quota is real but worth about one eighth of the gap. The October `o-global` arm (n=5, VRAM share 78-84 %) found "no difference", which is consistent with that size (noise 3 points there). +* Static placement for reference (M, `id-l1`, FA arms, tier frozen, per-layer uniform): 62.3 % token-weighted. Vanilla has no frozen arm. + +### (c) Adaptive swap policy + +* Source, line for line: vanilla `generate.cpp:10431-10458` (per layer: candidates = non-resident with count >= 2.0, victims = resident, sorted, paired while `cand >= vict + 1.5`, all layers sorted by gain, first 96); ours `split_group_pcie.rs` `choose_swaps_by` (the same). Every 4 verify rounds, decay 0.7, usage counted per routed entry of every window row (vanilla `expert_source.cpp:4826`, ours `note_usage`). The warm-up interval `STRATA_SPEC_ADAPT_EVERY=2 / WARM=200` exists in vanilla only for sm_86 and opt-in (`nv_defaults.cpp`): not active on the 5090. One difference: equal-gain swaps compete for the cap in unspecified `std::sort` order in vanilla, low layer first in ours. A/B `memory-tier-tie-spread-ab` (`LELEKA_ADAPT_TIE_SPREAD=on`, 5 pairs): hit +0.04 (CI -0.20..+0.29), tok/s +0.10 % (CI -0.73..+0.94): neutral (M). +* Swap volume (M, `hit_share_gap.py swaps`, 30 requests): ours 15.6 swaps a round (62 per adaptation), vanilla 13.1 a window. In short requests both sit at 21-25 a round = the cap (96 / 4): the cap binds in both. Knobs on ours (`ab-w`, 5 pairs each, A against variant): + +| variant | hit share (token-w) | tok/s | ms/round | tokens/round | +| --- | ---: | ---: | ---: | ---: | +| W1 adapt every 2 | **+0.56** (CI +0.26..+0.86), unweighted +0.89 | **+1.31 %** (CI +0.77..+1.85) | -2.23 % (CI -4.46..+0.01) | -0.94 % (CI -2.99..+1.11) | +| W2 192 swaps | +0.71 (CI +0.46..+0.96) | -1.07 % (CI -2.04..-0.09) | -1.28 % | -2.33 % (CI -4.43..-0.23) | +| W3 decay 0.85 | +0.14 (CI -0.27..+0.54) | -0.08 % | -0.62 % | -0.67 % | +| W4 margin 1.0 | +0.30 (CI -0.11..+0.71) | -1.07 % | -1.44 % | -2.54 % | + +The tier lags behind the text in both engines; more swap capacity buys hits at both. These are placement-class changes (output differs slightly). n=5 pairs is below the 10-pair rule of the ledger. + +### (d) Seed, warm start, prefix cache (H7) + +* Seed: `LELEKA_ORIGINAL_SERVE_SEED=off` in the 5090 profile; vanilla has none. Usage counts live with the stack across requests in both; the prefix cache and the lent-slot refill do not touch them (ours refills the lent slots with their own previous experts; `LELEKA_REFILL_DEFER` A/B: hit 92.18 against 92.11). +* **Request start (M, `prof-l5/Q.1`, one diagnostic profiled run (`LELEKA_BRINGUP_TRACE`, prefill sync drains; its hit share 91.66 is inside the A blocks' spread), per-window `DBG window` lines, requests 3-30; `hit_share_gap.py windows`)**: + +| windows since request start | rows | hit share | share of all misses | +| --- | ---: | ---: | ---: | +| 0-3 | 350 | 79.3 % | 1.7 % | +| 4-7 | 408 | 82.9 % | 1.6 % | +| 8-15 | 691 | 84.1 % | 2.5 % | +| 16-31 | 1,725 | 85.5 % | 5.7 % | +| 32-63 | 3,697 | 90.2 % | 8.3 % | +| 64-127 | 7,038 | 91.3 % | 14.0 % | +| 128-255 | 11,229 | 93.2 % | 17.4 % | +| 256 and more | 30,067 | 92.6-93.1 % | 49 % | + +The tier at the start of a request is the state of the previous request's last rounds (counts decayed by 0.7 every 4 rounds: a memory of about 12 rounds), not of the new content. The first 64 windows carry 20 % of all misses; against the steady 6.9 % miss rate they hold an excess worth **0.71 points of the overall hit share** (ceiling). The first two requests of a cold engine are the worst: ours 82.7 and 88.1 against vanilla 86.4 and 92.4 (-3.7, -4.3; profile placement only, about 11 adaptations, so slots + quota + the first swaps). +* Vanilla's short-request deficit (H3, nestng-crm -3.0) is not a stable effect: in the paired replay the buckets by output length are (token-weighted / unweighted, ours minus vanilla) < 600 tokens -0.22 / -1.43, 600-2000 -1.37 / -1.92, >= 2000 -1.16 / -1.43; ttt shows +0.1 for < 600 tokens in the real sessions. The large single-request gaps (requests 12, 22, 15: -5.7, -5.1, -3.3) are requests where the two engines generated different lengths (vanilla 2,580 against 399 tokens ours in request 12), i.e. different text. + +### (e) Window width + +* Ours adapts the window (A: 3.9 tokens a round, T up to 8); vanilla `--spec 4` (windows up to 6 rows, 2.95). Entries count every row, so wide windows weigh heavily: 33 % of our rows are T=8 windows. Hit share by window rows inside our run (M, Q.1, windows >= 64, requests 3-30): T=1 95.95 %, T=2 96.34, T=3 96.04, T=4 94.80, T=5 93.23, T=6 91.83, T=7 90.54, T=8 90.52 (content confounded: wide windows come with repetitive text). +* B (fixed window, tokens/round 3.09) against A in the same code: 92.66 against 92.13 token-weighted (+0.55), 90.76 against 90.2 unweighted (+0.55). D (adaptive window with floor 0.5) shows no change (92.10 against 92.15), so it is the width, not the floor. B is one block (A sd 0.2-0.3), so this is an indication. + +## 3. Decomposition (token-weighted, first 30 requests; M unless marked) + +| item | points | +| --- | ---: | +| ours A minus vanilla | -1.3 (-1.6 unweighted) | +| slots, 383 x 0.23 / 100 | +0.88 (CI 0.48..1.28) | +| window width (B minus A) | +0.55 (n=1 B) | +| global allocation at equal slots (E) | +0.12..+0.16 | +| sum of the three | 1.55..1.6 | +| ours B minus vanilla (like for like in width) | -0.7 (-1.0 unweighted); slots + quota = 1.0 | + +The effects are not additive in general and the vanilla side has two blocks, so the table says "consistent within the noise", not "proved". + +## 4. What is NOT comparable + +* Real sessions (H2, H3): the two engines run different agent trajectories, (the logs hold different numbers of requests), so request-length buckets mix different tasks; the short-request gap is one session (nestng-crm -3.0, ttt +0.1). +* Replay requests differ in text after the first requests (the two engines generate different outputs; prompts +228 tokens of template in ours, 10,187 against 9,959): per-request differences above about 2 points are mostly different text. Only pooled and weighted figures are usable. +* The E/T/K arms (tail skip on): entries skipped are not counted; 93.6-95 % there is not a hit share. +* Weights: token-weighted (long requests: request 3 alone is 8,401 tokens, 97 %) against unweighted differ by 2 points in level and by 0.3 in gap; always state which. +* Vanilla's per-window hit share is not logged (only the request total and the `decode timing` line), so H7 cannot be compared per window; the CUPTI class shares are one request (29), two ours windows against one vanilla window with a different T mix (vanilla T=4 in 64 % of layer-windows, ours T=2-3). +* `LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000` is not a product setting; no hit-share figure of the identity jobs says anything about the tier. + +## 5. What the data cannot separate + +* The quota effect (b) from the slot effect (a) in the measured hit share: no run has vanilla's quotas at ours slot count (or the reverse). The per-layer data prove the quota matters per layer; the net is estimated by a model only. +* The width effect (e) from the content: one B block. +* Anything at window resolution for vanilla (H7), and the part of H7 that is "unadapted tier" against "new text is different". +* Whether the early-request excess (0.71 ceiling) is recoverable: nothing has tried to pre-warm the tier on a warm engine at agent-turn size (the seed tests of `original-serve.md` reset the tier to the profile before every request; the 245k tests used huge prompts). + +## 6. Ranked changes to try + +| # | change | knob | expected gain | how to measure | owner | +| ---: | --- | --- | --- | --- | --- | +| 1 | **Close the slot gap** with the opt-ins that exist: alias + decode reserve 130 (`both` of footprint3: 12,384 slots, lowest free 355 MiB >= vanilla 315) and global fill (no 48-slot quota step, uneven quotas) | `LELEKA_PROMPT_EMBED_ALIAS=1 LELEKA_ORIGINAL_SERVE_DECODE_RESERVE_MIB=130`, then `+ LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no` | hit +0.44 for the first (M: same 12,384 slots as H), +0.6..+0.9 with the quota step gone and vanilla's quotas (E); ms/round -2 % (M for H) | new `spd_ab_job.sh` variants (`SL`, `SLG`), 10 pairs each against A, `hit_share_gap.py pairs`; read `expert cache N slots` from each log; free VRAM at decode (`DBG vram decode after assemble`, profile run) must stay >= 315 MiB; placement-class gate against the control placement. Add `LELEKA_PROMPT_EMBED_ALIAS` and `LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER` to the unset list first (the leak that invalidated `ab-l3h`); the profile sets PER_LAYER=yes and `engine_launch.rs` lets the `up`-resolved environment win, so check that `leleka up` forwards the shell variable (the October `o-global` arm did) by the log line `expert cache N slots` losing its `per layer`; the A blocks must leave it unset | env only; uneven quotas in code: `original_cache_startup`, `cache_strata_adaptive/reserve.rs`: host/tier (hex-finish) | +| 2 | **Faster tier in the cap-bound first rounds**: adapt every 2 (measured), then a request-start warm-up (interval 2 and/or cap 192 only for the first 64 windows of a request, vanilla's own `STRATA_SPEC_ADAPT_EVERY/WARM` mechanism, which vanilla enables only on sm_86) so steady-state swap cost does not rise | `LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=2` (variant W1 exists); warm-up needs code | W1: +0.56 hit, +1.31 % tok/s (n=5, M). Warm-up: bounded by the 0.71 early-excess ceiling, E +0.3..+0.5 | W1 with 10 pairs (`ab-w` variant, `SPD_VARIANTS` 10 blocks), then the warm-up variant; cost side: `adapt.queue` / `round.apply_pending` spans in a P run | env: nobody; warm-up code in `original_serve_residency/source_spans.rs` (`begin_adaptation`) and `split_group_pcie.rs` (`adapt_tuning`): host/tier (hex-finish) | +| 3 | **Offline tier simulator on one routing dump**, so every policy question above is answered in seconds, not 1-hour A/Bs | one replay with `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=` (variant A plus the variable, about 6 min, about 230 MB, ignored path) and a Python simulator (allowed for experiments) | decides global against uniform at equal slots, accepted-rows-only usage counting (rejected rows pollute the counts; hit falls with T), decay / margin / cap / interval grid, request-start carry-over, before any GPU A/B | calibrate first: simulated A must reproduce 92.1 / 90.2 and the start-of-request curve of section 2 within 0.3; the dump has per-row records only (layer resets mark windows), so the dump should also carry request id and accepted-row count: a few lines in `record_routing` | dump change: host/tier (hex-finish); simulator: any | +| 4 | Warm the tier from the new prompt tail (lowest priority) | `LELEKA_ORIGINAL_SERVE_SEED=1 LELEKA_ORIGINAL_SERVE_SEED_USAGE=0.02 LELEKA_ORIGINAL_SERVE_SEED_MAX_ROWS=4096` (one swap, prompt counts added to the usage) | at most the same 0.71 ceiling; U | 10-pair A/B; all earlier seed tests started from a reset tier, none from a warm one | env only | + +Not proposed: tie order (neutral), decay (+0.14, CI crosses 0), margin 1.0 (tok/s -1.07 %), cap 192 alone (tok/s -1.07 %, CI -2.04..-0.09; the cap is only worth it for the first rounds). + +Host/tier files (hex-finish): `original_serve_residency.rs` and `original_serve_residency/*` (policy, swap choice, counts, `open_tier`, seed hook), `original_serve_seed.rs`, `original_cache_startup.rs`, `cache_strata_adaptive/*`, `settings/memory.rs`, `original_serve_pool.rs`, and the `spd_ab_job.sh` variants. Device code is not involved in any of the four. + +## 7. Proposed ledger edits (not made) + +* H1: restate as -0.7 (B) / -1.3 (A) points token-weighted and -1.0 / -1.6 unweighted over the 30-request replay (sources above); the 92.8 figure has no surviving log. +* H4: add the slope 0.23 points per 100 slots (A/B `ab-l3v2`, M) and the composition of the 383 slots (744 MiB). +* H5: neutral (`memory-tier-tie-spread-ab`, 5 pairs, +0.04, CI -0.20..+0.29): `proved-equal`. +* H6: W1 +0.56 points / +1.31 % tok/s (n=5), W2 +0.71 / -1.07 %, W3 +0.14, W4 +0.30 (all M, 5 pairs). +* H7: isolated for ours (section 2: 79 % to 93 % over the first 128 windows, 20 % of all misses in the first 64); vanilla not measurable. +* New row: global against per-layer quotas, per-layer evidence r = 0.82, net E +0.12..+0.16. + +## 8. Reproduction + +``` +S=scripts/e2e/codex/speed/hit_share_gap.py +for c in arms "pairs ab-l3v2 A H 10" "pairs ab-w A W1 5" requests windows swaps; do ssh rnr5090 "nice python3 -I - $c" < $S; done +# per-layer (local; the json.gz come from ffn_phase_timeline.py extract, ffn-phase-loss-design.md section 6) +python3 -I scripts/e2e/codex/speed/hit_share_layers.py crates/deploy/data/expert-profile.bin VANL.json.gz CL.1.json.gz CY.1.json.gz +python3 -I - < scripts/e2e/codex/speed/session_hit.py # on the server: H2 / H3 +``` diff --git a/scripts/e2e/codex/speed/hit_share_gap.py b/scripts/e2e/codex/speed/hit_share_gap.py new file mode 100644 index 00000000..d4422b4e --- /dev/null +++ b/scripts/e2e/codex/speed/hit_share_gap.py @@ -0,0 +1,194 @@ +"""VRAM hit share of the routed experts, ours against vanilla (docs/experiments/vram-hit-share-gap.md). + +Read-only, stdlib only, no GPU; run on the server with `nice python3 -I - SUBCOMMAND ... < hit_share_gap.py`. + arms hit share per experiment and arm: token-weighted, unweighted, time-weighted, tok/round + pairs EXP A B N paired A/B (blocks A.1..A.N against B.1..B.N): decode tok/s, ms/round, hit share + requests per request of the 30-request replay: pooled A arms against the two vanilla replays + windows hit share by window index since the request start and by window rows T (Q.1 trace) + swaps adaptive swaps per round: ours (P run, DBG tier) against vanilla (VANLP timing lines) +Definitions: the hit share is VRAM entries / all routed entries (every row of every window counts, rejected draft rows +too), the same quantity as vanilla's "hits / all routed". Weights: otok = generated tokens of the request. +""" +import collections +import glob +import json +import math +import os +import re +import statistics as st +import sys + +R = "/data/leleka-e2e/spd-gap/runs" +T95 = {2: 4.303, 3: 3.182, 4: 2.776, 9: 2.262} + + +def lel(path): + """Per-request rows of an engine.log of ours (the engine's one structured line per request).""" + rows = [] + for line in open(path + "/engine.log", errors="replace"): + if line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line: + j = json.loads(line) + if "tier_vram_pct" in j: + rows.append(dict(ptok=j["ptok"], otok=j["otok"], rounds=j["rounds"], tpr=j.get("tok_per_round"), + dec_ms=j["dec_ms"], v=j["tier_vram_pct"], p=j["tier_pcie_pct"], c=j["tier_cpu_pct"])) + return rows + + +def van(path): + """Per-request rows of a vanilla engine.log: the `prompt ...` line, then its `hit rate` line.""" + rows, cur = [], {} + pat_p = r"strata serve: prompt (\d+) tokens = (\d+) reused \+ (\d+) read in .*?(\d+) generated in ([\d.]+) ms" + pat_h = r"hit rate: [\d.]+% \((\d+) hits / (\d+) lookups\); (\d+) more.*?of all (\d+) routed" + for line in open(path + "/engine.log", errors="replace"): + m = re.search(pat_p, line) + if m: + cur = dict(ptok=int(m[1]), otok=int(m[4]), dec_ms=float(m[5])) + m = re.search(pat_h, line) + if m and cur: + routed = int(m[4]) + cur.update(v=100 * int(m[1]) / routed, p=100 * int(m[3]) / routed, + c=100 * (int(m[2]) - int(m[1])) / routed, routed=routed) + rows.append(cur) + cur = {} + return rows + + +def wavg(rows, key="v", weight="otok"): + return sum(r[key] * r[weight] for r in rows) / sum(r[weight] for r in rows) + + +def metrics(path, n=30): + rows = lel(path)[:n] + ot, ms, rd = (sum(r[k] for r in rows) for k in ("otok", "dec_ms", "rounds")) + return dict(tps=1000 * ot / ms, msr=ms / rd, tpr=ot / rd, v=wavg(rows), vu=st.mean(r["v"] for r in rows)) + + +def replay_dirs(): + """Experiment dirs whose replay starts with the 10,187-token request of nestng-crm-r2 and has >= 30 requests.""" + for d in sorted(glob.glob(R + "/*/*")): + if os.path.isfile(d + "/engine.log") and "contaminated" not in d: + rows = lel(d) + if len(rows) >= 30 and rows[0]["ptok"] == 10187: + yield d, rows + + +def cmd_arms(): + agg = collections.defaultdict(list) + for d, rows in replay_dirs(): + exp, arm = d[len(R) + 1:].split("/") + agg[(exp, arm.split(".")[0])].append((wavg(rows[:30]), st.mean(r["v"] for r in rows[:30]), + wavg(rows[:30], weight="dec_ms"), st.mean(r["tpr"] for r in rows[:30]))) + for key, v in sorted(agg.items()): + print("%-52s n=%2d token-w %.2f (sd %.2f) | unweighted %.2f | time-w %.2f | tok/round %.2f" % ( + key, len(v), st.mean(x[0] for x in v), st.pstdev(x[0] for x in v), st.mean(x[1] for x in v), + st.mean(x[2] for x in v), st.mean(x[3] for x in v))) + for name in ("VANL-noprof", "VANLP"): + rows = van(R + "/main/" + name)[1:31] + print("%-52s token-w %.2f | unweighted %.2f | time-w %.2f | entry-w %.2f" % ( + name, wavg(rows), st.mean(r["v"] for r in rows), wavg(rows, weight="dec_ms"), + wavg(rows, weight="routed"))) + + +def cmd_pairs(exp, a, b, n): + pairs = [] + for k in range(1, int(n) + 1): + pa, pb = "%s/%s/%s.%d" % (R, exp, a, k), "%s/%s/%s.%d" % (R, exp, b, k) + if os.path.isfile(pa + "/engine.log") and os.path.isfile(pb + "/engine.log"): + pairs.append((metrics(pa), metrics(pb))) + print("%s: %s against %s, %d pairs" % (exp, b, a, len(pairs))) + for key, label, rel in (("tps", "decode tok/s %", 1), ("msr", "ms/round %", 1), ("tpr", "tok/round %", 1), + ("v", "hit share points (token-w)", 0), ("vu", "hit share points (unweighted)", 0)): + d = [(q[key] / p[key] - 1) * 100 if rel else q[key] - p[key] for p, q in pairs] + m, sd = st.mean(d), (st.stdev(d) if len(d) > 1 else 0.0) + ci = T95.get(len(d) - 1, 2.3) * sd / math.sqrt(len(d)) + print(" %-32s %+.2f (CI %+.2f..%+.2f)" % (label, m, m - ci, m + ci)) + + +def cmd_requests(): + pool = collections.defaultdict(list) + for d, rows in replay_dirs(): + if re.search(r"/A(\.\d+)?$", d): + for i, r in enumerate(rows[:30]): + pool[i].append(r) + vs = [van(R + "/main/" + n)[1:31] for n in ("VANL-noprof", "VANLP")] + print("idx ptok(V) otok(V) otok(A) | hit V hit A (pooled, sd) | A-V | cpu V/A pcie V/A") + out = [] + for i in range(30): + a, v = pool[i], [x[i] for x in vs] + out.append((st.mean(x["otok"] for x in v), st.mean(r["otok"] for r in a), st.mean(x["v"] for x in v), + st.mean(r["v"] for r in a))) + print("%2d %6d %6d %6.0f | %.1f %.1f (%.2f) | %+.1f | %.1f/%.1f %.1f/%.1f" % ( + i + 1, v[0]["ptok"], out[-1][0], out[-1][1], out[-1][2], out[-1][3], st.pstdev([r["v"] for r in a]), + out[-1][3] - out[-1][2], st.mean(x["c"] for x in v), st.mean(r["c"] for r in a), + st.mean(x["p"] for x in v), st.mean(r["p"] for r in a))) + for name, lo, hi in (("< 600 tokens", 0, 600), ("600-2000", 600, 2000), (">= 2000", 2000, 10 ** 9)): + sel = [o for o in out if lo <= o[0] < hi] + print("%-14s n=%2d token-w V %.2f A %.2f | unweighted V %.2f A %.2f" % ( + name, len(sel), sum(o[0] * o[2] for o in sel) / sum(o[0] for o in sel), + sum(o[1] * o[3] for o in sel) / sum(o[1] for o in sel), st.mean(o[2] for o in sel), + st.mean(o[3] for o in sel))) + + +def windows_of(path): + """Per request: the `DBG window` rows (rows, cpu entries, pcie experts) in file order, split at the request line.""" + reqs, cur = [], [] + for line in open(path, errors="replace"): + if line.startswith("DBG window"): + m = dict(re.findall(r"(\w+)=([\d.]+)", line)) + cur.append((int(m["rows"]), float(m["entries"]), float(m["pcie_experts"]))) + elif line.startswith("{") and '"ev":"request"' in line and '"comp":"engine"' in line: + if "tier_vram_pct" in json.loads(line): + reqs.append(cur) + cur = [] + return reqs + + +def cmd_windows(): + reqs = windows_of(R + "/prof-l5/Q.1/engine.log") + edges = [0, 4, 8, 16, 32, 64, 128, 256, 512, 10 ** 6] + acc = collections.defaultdict(lambda: [0, 0.0]) + for w in reqs[2:]: + for i, (rows, cpu, pcie) in enumerate(w): + b = max(k for k in range(len(edges) - 1) if edges[k] <= i) + acc[b][0] += rows * 480 + acc[b][1] += cpu + pcie + print("hit share by window index since the request start (requests 3..30 of Q.1, row-weighted)") + for b in sorted(acc): + print(" windows %4d-%-6d rows %6d hit %.2f%% misses %.1f%% of all" % ( + edges[b], edges[b + 1] - 1, acc[b][0] / 480, 100 * (1 - acc[b][1] / acc[b][0]), + 100 * acc[b][1] / sum(a[1] for a in acc.values()))) + by_t = collections.defaultdict(lambda: [0, 0.0]) + for w in reqs[2:]: + for i, (rows, cpu, pcie) in enumerate(w): + if i >= 64: + by_t[rows][0] += rows * 480 + by_t[rows][1] += cpu + pcie + print("hit share by window rows T (windows >= 64 of requests 3..30)") + for t in sorted(by_t): + print(" T=%d rows share %.1f%% hit %.2f%%" % (t, 100 * by_t[t][0] / sum(a[0] for a in by_t.values()), + 100 * (1 - by_t[t][1] / by_t[t][0]))) + + +def cmd_swaps(): + tiers = [] + for line in open(R + "/main/P/engine.log", errors="replace"): + m = re.search(r"DBG tier request: .*adaptations (\d+) swaps (\d+)", line) + if m: + tiers.append((int(m[1]), int(m[2]))) + rounds = sum(r["rounds"] for r in lel(R + "/main/P")[:30]) + print("ours: %d swaps in %d rounds = %.2f per round, %.1f per adaptation (cap 96)" % ( + sum(t[1] for t in tiers[:30]), rounds, sum(t[1] for t in tiers[:30]) / rounds, + sum(t[1] for t in tiers[:30]) / sum(t[0] for t in tiers[:30]))) + vt = [] + for line in open(R + "/main/VANLP/engine.log", errors="replace"): + m = re.search(r"decode timing: (\d+) windows, avg T ([\d.]+).*?([\d.]+) swaps/window", line) + if m: + vt.append((int(m[1]), float(m[2]), float(m[3]))) + w = sum(x[0] for x in vt) + print("vanilla: %.2f swaps per window, avg T %.2f" % (sum(x[0] * x[2] for x in vt) / w, + sum(x[0] * x[1] for x in vt) / w)) + + +if __name__ == "__main__": + cmds = dict(arms=cmd_arms, pairs=cmd_pairs, requests=cmd_requests, windows=cmd_windows, swaps=cmd_swaps) + cmds[sys.argv[1]](*sys.argv[2:]) diff --git a/scripts/e2e/codex/speed/hit_share_layers.py b/scripts/e2e/codex/speed/hit_share_layers.py new file mode 100644 index 00000000..415b6b44 --- /dev/null +++ b/scripts/e2e/codex/speed/hit_share_layers.py @@ -0,0 +1,90 @@ +"""Miss-leg frequency per layer, ours against vanilla, against the layer's slot quota (vram-hit-share-gap.md, cause b). + +Local, stdlib only, no GPU. Input: the per-layer records of CUPTI windows written by `ffn_phase_timeline.py extract` +(reproduction in ffn-phase-loss-design.md section 6): + python3 hit_share_layers.py PROFILE.bin VANL.json.gz LEL.json.gz... +A layer-window is "with a miss leg" when its class is C (CPU rows late) or X (PCIe leg); F has neither. +Vanilla fills 12,575 slots by the global rank of the profile; ours gives every layer 254 (12,192 / 48). +""" +import os +import statistics as st +import struct +import sys + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +sys.dont_write_bytecode = True +import ffn_phase_timeline as F # noqa: E402 + +LAYERS, OURS_QUOTA, VANILLA_SLOTS = 48, 254, 12575 + + +def global_quota(profile_path): + raw = open(profile_path, "rb").read() + pairs = [struct.unpack(" 20]), + ("neutral", [i for i in range(LAYERS) if abs(dq[i]) <= 20]), + ("donors (-20 slots or fewer)", [i for i in range(LAYERS) if dq[i] < -20])): + print(" %-30s %2d layers, %+4.0f slots each, ours - vanilla %+.3f" % ( + name, len(sel), st.mean(dq[i] for i in sel), st.mean(diff[i] for i in sel))) + + +def uniform_ranks(pairs, per_layer): + taken, ranks = [0] * LAYERS, [] + for rank, (layer, _) in enumerate(pairs): + if taken[layer] < per_layer: + taken[layer] += 1 + ranks.append(rank) + return ranks + + +def model_gain(profile_path): + """Static coverage of a power-law routing model f(rank) ~ rank^-alpha over the profile's global ranks (E).""" + raw = open(profile_path, "rb").read() + pairs = [struct.unpack(" OURS_QUOTA for q in quota), sum(max(0, q - OURS_QUOTA) for q in quota))) + for classes in (("C", "X"), ("X",)): + for rows_t in (None, (3, 4)): + report(vanl, lels, quota, classes, rows_t) + model_gain(profile) + + +if __name__ == "__main__": + main(*sys.argv[1:])