Merge branch 'main' into claude/tail-skip-gate

This commit is contained in:
Pavlo Ratushnyi
2026-11-13 02:34:48 +01:00
26 changed files with 1907 additions and 18 deletions
+56
View File
@@ -0,0 +1,56 @@
# Stage 6d: tokens per round and the drafter on the RTX 5090 (2026-11-12)
Status: analysis done (no GPU); the knob measurements are queued (section 5) and their numbers are NOT in this file yet.
Labels: M measured, E estimate.
## 1. Vanilla against Leleka: tokens per round
Method: vanilla logs `generated N ... drafts accepted a of b` per request, so rounds = generated - accepted (one bonus token a window); Leleka logs `rounds` itself. Requests of 100+ tokens.
| arm | requests | tok/round | ms/round | decode tok/s | source |
| --- | ---: | ---: | ---: | ---: | --- |
| VAN (vanilla 0.2.6, shipped defaults) | 258 | 2.960 | 12.42 | 238.3 | `codex-compare/runs/main/VAN/*/engine-slice.log` |
| VANL (vanilla 0.2.6, lossy defaults off) | 240 | 2.959 | 13.65 | 216.8 | same, VANL |
| LEL release 17e372944279 | 227 | 3.337 | 18.75 | 178.0 | same, LEL |
| LEL release 83bdd85bb482 (owner default) | 259 | 3.194 | 16.41 | 194.6 | `prefill-latency/runs/e2e-codex-ttt-and-crm-release-83bdd85bb482-owner-default` |
**Vanilla's accept length is NOT higher; ours is 8-13 % higher.** The gap to vanilla is the round time (16.4 against 12.4-13.7 ms), not acceptance. Tokens per round in the replays: 3.30 (243k), 3.58 (110k), 3.19-3.47 (cap-s3 / 67k). The same finding was made at 245k in 2026-11 (ours 2.05-2.13, vanilla 1.79-1.88, `docs/upstream-review/decode.md`).
## 2. What upstream changed (pin 41cf05a0 / engine 0.1.50 to `strata-upstream/main` 504b14334 / engine 0.1.59), local git only
| upstream change | applies to us? |
| --- | --- |
| `6ec4d68ab`, `a04860fad` DFlash2 per-device defaults: Blackwell cc 12.0 conf 0.35 to 0.55, window 6 to 8 | **No.** They configure the DFlash2 block drafter (we run the MTP chain + suffix drafter), only on cc 12.0 cards with >= 48 GB (RTX PRO 5000 72 GB, set IQ3_S, every expert resident, +2.4 %, output identical). The code says explicitly that consumer cards under 48 GB (the RTX 5090 has 32 GB) keep conf 0.35 and window 6 (`strata_control/drafting.py` `big_blackwell`, `window_for`). |
| DFlash2 is the Auto drafter on CUDA IQ3_S (`13edeb7f8`, CLASS_DEFAULTS: MTP only on the 12 GB streaming class) | Means a new-base vanilla on the 5090 will run DFlash2 (slots >= 12,000 give conf 0.35, window 6, tuned pack), not the MTP of our VAN/VANL. Upstream measures DFlash2 +2..+14 % per text kind over MTP on resident cards, +6.5 % on one streaming set, and the MTP wins by 12-44 % where the experts stream from file. Its accept length is not published in the repo (`phaseA-tests/` is not in it). Porting it is a drafter port (5 transformer layers, Q8_0/Q4_0 pack, selector), not a knob. Not started. |
| `cc703b5e4`, `03627326d` (#4040) `--lookup-max-t 12` on by default: prompt-lookup windows up to 12 rows, run as two groups of 8 | The one change that targets accept length. Upstream: file rewrites and agent edit turns +11..+14 % (A6000, resident), prose and code within 1 %. Our `kVerifyMaxT` is 8 (compiled into the sealed PTX). See section 4. |
| `STRATA_SPEC_PROB`, `STRATA_DF2_GATE` (retired later), `STRATA_WINDOW_MAX_T=12/16` | sampled-request or other-drafter features; wide-window build: upstream says it gains less than the two-group form. Not applicable to greedy MTP serving. |
| MTP drafter code (`mtp.cpp`, +292 lines) | plumbing only (prompt room, KVA floor, Pascal Q8, DFlash2 head sharing); the draft numerics and the draft attention window (32768 cells, same constant in ours) are unchanged. |
| `draft_vocab_en.bin` (release notes 0.2.7: +2.7..+3.1 % decode English text) | already ported opt-in (`LELEKA_DRAFT_VOCAB`, `2026-10-30-draft-vocab-en.md`); its A/B never ran. Queued, section 5. |
| `MMQ_KQ` default for cc >= 8.0 | K-quant matmul default for prompt paths; our model is IQ3_S, no draft effect. |
## 3. Knobs that exist in our port
`LELEKA_SPEC_ARMS` per-arm policy constants (`explore margin min_p_lo step alpha decay bias ceil rowq smooth measured`, floor ceiling = `adaptive@P`), process level `LELEKA_SPEC_SUFFIX` (suffix minimum match, 3), `LELEKA_SPEC_ADAPTIVE_MAX_T` (8, the compiled ceiling), `LELEKA_SPEC_MTP_MAX_T`, `LELEKA_DRAFT_VOCAB`. The draft attention window (32768) and the suffix index (trigram, 4 candidates) are constants. The window policy landscape was measured flat (+-1.2 %) at 245k on 2026-11-03 (`window-policy-5090.md`); a faster round has since moved the optimum only slightly.
## 4. Offline estimates (CPU only, M for the counts, E for the conclusions)
Round cost by width (a request of the 67k replay, `ms_by_T`): T1..T8 = 9.0, 10.1, 11.4, 13.5, 16.1, 19.1, 22.8, 24.1 ms: a base of about 7-9 ms plus 2.2 ms a row. Rounds by accepted drafts (share of rounds, `spec-stats` of the owner-default A/B): 24 % accept nothing; 10 % (67k) and 3-4 % (243k) accept all 7 drafts of a full 8-row window.
Suffix drafter simulated on the real Codex session cap-s3 (33 requests, 10,414 positions, teacher-forced text, history = prompt + reply; `scripts/e2e/decode/accept-knobs-suffix-sim.py`): a proposal of match length >= 3 exists at 56.5 % of positions; mean accepted 3.81 of 7 per proposal with the 4-candidate index, 3.85 / 3.88 / 3.92 with 8 / 16 / all candidates (+1..+3 % of accepted tokens: too small to pay). If the window allowed 11 drafts: mean accepted 5.29 per proposal and 34.7 % of proposals are fully matched.
E for a 12-row window (single window, slope 2.2 ms a row): a fully copied stretch costs 24.1 + 4 x 2.2 = 32.9 ms for 12 tokens = 2.74 ms a token against 3.0 at 8 rows (-9 %); full-accept rounds carry roughly a quarter of the tokens, so **at most +2 % end to end** (+1 % at 243k), and only if one 12-row window is built. Upstream's two-group form in our regime would add a second pass with its own base (a 4-row window costs 13.5 ms): 37.6 ms for 12 tokens = 3.1 ms a token, worse than 8 rows. Cost of the port: window kernels and sealed PTX for T=12, GDN commit of 12 rows, drafter catch-up. **Not worth it for 220 tok/s** (needs +20 %).
Arithmetic of the target: tok/s = tokens per round / round ms. 220 tok/s at 3.3 tokens a round needs a 15.0 ms round; at the current 16.4-17.9 ms it needs 3.6-3.9 tokens a round (+13..+22 %), which no policy knob delivers (all measured within +-1.5 %); the remaining lever is the round time (stages 6c, 6e, 6f).
## 5. Measurements queued (server, `/data/leleka-e2e/prefill-latency/accept-knobs`, inputs frozen by `MANIFEST.sha256`)
Instrument: `scripts/e2e/decode/accept-knobs-replay.sh`: the real Codex session cap-s3 (33 requests of 177k-232k tokens, replies capped at 400) teacher-forced in ONE test-binary process (main code of release bcbfa2c99422, sha in the manifest), release profile `rtx5090-32g` engine_env read from the frozen json, several policies as `LELEKA_SPEC_ARMS` on identical text, 5 repetitions with rotated order, base arm and its twin (A/A floor). Summary: `accept-knobs-summary.py` (paired percent against the base, 95 % interval, n of N).
| job (stub in `~/work/gpu-runs/holder2/jobs`) | content |
| --- | --- |
| `acceptance-replay-harness-smoke-two-arms-three-requests` | harness smoke |
| `acceptance-draft-vocabulary-en-identity-fixed-window-top16-rows` | fixed window 4, suffix off, night5, top-16 rows, default vs English draft vocabulary, A/A inside each process |
| `acceptance-policy-knobs-codex-session-teacher-forced-ceiling-explore-rowq-margin-and-vanilla-window` | base, twin, fixed4@0.5 (vanilla window), ceiling 0.5 / 0.7, explore=0, rowq=0.75, margin=0.05 |
| `acceptance-draft-vocabulary-en-vs-default-codex-session-teacher-forced` | two processes (default vocabulary control, English subset), base + twin each |
Results directories `/data/leleka-e2e/prefill-latency/runs/<job name>/`. Identity reading for adaptive-window knobs: the policy changes which window widths run, so rows differ within the batch-rounding envelope (`window-policy-5090.md` section 5); the forced text makes equal output true by construction, and the fixed-window gate above is the bitwise one for the drafter knob. Nothing is defaulted until a knob beats the twin floor and passes its gate.
@@ -0,0 +1,258 @@
# Plan 6g, owner ideas 2026-11-12: asynchronous compression of parked blocks, and an orchestrator-mode benchmark
Analysis only: code and docs read, one small synthetic experiment, no GPU, no queue stub, no engine change. Companion of `docs/experiments/multiplexing-feasibility.md`
(numbers from it are quoted, not re-derived) and of `docs/design/memory-single-copy-and-elastic-state.md` C.4-C.6 / T8-T9, which already analysed compression of parked state
in November; this page adds the code-level payload formats, a measured codec test on a synthetic block, the switch-path decomposition and the benchmark design.
Labels: **M** = measured, source named; **C** = read from code; **E** = estimate by arithmetic from M numbers (arithmetic shown); **S** = measured on SYNTHETIC data (not the model); **U** = unknown.
## 0. Result
| Question | Answer |
|---|---|
| (A) Lossless ratio of a parked block | **E: 1.06x pessimistic, 1.17x central, 1.29x optimistic** (S: 1.05x / 1.17x / 1.23x on the K/V codes alone). Not measured on the model: no real parked block exists anywhere (searched the server). |
| (A) Time saved on a session switch | **None.** The switch copy is a host memcpy into the pinned K/V image at 13-14 GB/s (C, M), not a PCIe copy; PCIe carries only the 12 % index rows (about 6 ms at 180k). Decompression at 2.4-2.9 GB/s per core (S) needs about 8 threads to match the one-thread memcpy it replaces. |
| (A) RAM gained | One parked session shrinks by 5 % / 14 % / 22 % (180k: 2.81 -> 2.67 / 2.42 / 2.19 GB). Whole sessions kept (raw -> pessimistic / central / optimistic): 243k at 8 GiB 2 -> 2/2/2, at 13 GiB 3 -> 3/4/4; 180k at 8 GiB 3 -> 3/3/3, at 13 GiB 4 -> 5/5/6 (section A.5). About **+0.4 to +0.8 session**, i.e. +1 session at best. |
| (A) Recommendation | **MEASURE-FIRST, then probably NO-GO as a stand-alone feature.** Cost of the measurement: a 40-line logging hook, 0 extra GPU time when piggy-backed on a 243k run (about 0.4 GPU-h alone). Build the codec only if the measured K/V ratio is at least 1.3x (the T8 gate of the design doc). Cheaper levers first: lazy parking (T6/T7, about -3.2 GiB per live session), the cache budget itself, a parallel import memcpy (saves about 0.1 s per switch). |
| (B) Can Codex be made to fan out | Yes: Codex CLI 0.163.0 advertises the `multi_agent_v1` tool namespace in every request (M, `docs/e2e-run.md` 7); public docs: sub-agents are spawned by the model on request in the prompt, each child makes its own model requests in parallel, `[agents] max_threads` (default 6). Whether the Qwen3.5 IQ3 model calls the spawn tool reliably is **U** and is the first thing to test (step P0/P1). Fallback: N parallel `codex exec` sessions started by the harness. |
| (B) Cost | **about 3-3.5 GPU-hours** for the Leleka-only matrix (pilot 0.7 h + 3 repetitions x 43 min), about 5 GPU-hours with the vanilla `--parallel 1` / `--parallel 2 --batch-mtp` arms (needs the owner's word). Merge with step 1 of `multiplexing-feasibility.md` (2-3 GPU-h): the combined bill is about 4 h, not 6. |
| (B) Expected aggregate effect through today's time-sliced queue | **E: 0.97-1.18x of the same work done one session after another, central 1.03-1.08x**; against ONE agent doing the whole task alone about 0.95-1.08x (the orchestrator's serial plan/wait/merge requests eat the overlap). Not "several times". The benchmark's value is the switch cost, the tier penalty and the real overlap, with numbers instead of E. |
## A. Asynchronous compression of parked blocks
### A.1 What is parked, and in which format (C unless marked)
Code path: `QwenSession` park -> `ResidentQsaLayer::export_span` (`crates/engine-qwen35-cuda/src/qwen_forward/qsa_resident_device/resident_qsa_span_export_and_seal.rs`)
fills one `ParkedLayerSpan { first_token, tokens, kv: Vec<u8>, index: Vec<u8> }` per QSA layer; a `ParkedBlock` (`session_original_prompt.rs`) is 12 spans; a `ParkedSession`
(node) holds the GDN and PLE priors, the index checkpoint tails and the draft-ring snapshot. The store (`engine-core::prefix_cache`) is model-free and keeps them as plain host heap bytes.
| Component | Format | Bytes | Share of a block | Source |
|---|---|---:|---:|---|
| K codes | **int8**, symmetric, `clamp(rint(x/scale), -127, 127)`, 2 KV heads x 256 dims, one scale per 64 values | 512 B per cell and layer | 43.2 % | `crates/experimental-ref/src/kv_q8.rs`, `crates/context/src/geometry.rs` |
| V codes | int8, same | 512 B | 43.2 % | same |
| K / V scales | **fp16**, 8 per cell and layer (2 heads x 4 groups) | 16 B + 16 B | 2.7 % | same |
| pooled index rows | **fp32**, 128 values per 4-cell row (sum of four fp16-rounded keys, RMS-normalised, gamma, RoPE) | 512 B per 4 cells = 128 B per cell and layer | 10.8 % | `qsa_prompt_indexer.cu::pooled_value`, `OriginalQsaResidentIndex::ROW_BYTES` |
| **block total** | host layout is run-major per 4-cell page (K codes 2048 B, V codes 2048 B, K scales 64 B, V scales 64 B = 4224 B), index rows separate | **1,184 B per cell and layer, 14,208 B per token (12 layers)** | 100 % | `PAGE`, `prefix-cache.md` |
| node: GDN recurrent state | **fp32**, 36 layers, constant 112.2 MiB (117,669,888 B) plus a history window (`host_bytes = (values + history) x 4`) | about 127 MB per node with PLE history (fp32, 360 KiB), 12 index tails of 2,564 B and the draft-ring snapshot | n/a (constant per node) | `gdn_state.rs`, `memory-single-copy...md` C.1 |
There is no bf16/fp8 anywhere in a parked block: the "bf16 weight/KV" literature ratios do not transfer. K/V are already 8-bit, so the exponent-splitting tricks (ZipNN, DFloat11) have
nothing to split except the fp16 scales and the fp32 index rows, which are 14 % of the bytes. Other K/V formats exist (`Q4_0` 576 B, `K8V4` 816 B, keyless 528 B per cell); parking them
would be a lossy re-quantisation of an INT8 image and is out of scope (needs its own quality gate; not default).
### A.2 Lossless ratio
**No real parked block exists to measure.** Searched `/data/leleka-e2e` (read-only, files above 50 MB and `*.bin`/`*.raw`/`*.img`, names with kv/park/dump/ckpt): only model assets, build output and profiler
`sync.bin`. `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING` dumps expert routing only. The T8 hook of the design doc was never built.
What is known without the model:
* **S, order-0 entropy and `zstd` on synthetic blocks** (script `scripts/memory/kv_block_compress_sim.py`, one 2048-token block of one layer in the real layout; three activation models; `zstd` 1.5.7 on the 9950X3D,
one thread, `nice 19`, the box was loaded by a running GPU job (load 15), 2 MiB inputs, 2-3 iterations each, so the speeds are indicative, not benchmarks):
| synthetic K/V model | entropy of codes | ideal x | zstd -1 / -3 x | zstd -19 x | zstd -1 compress, decompress (MB/s) |
|---|---:|---:|---:|---:|---:|
| Gaussian, no outliers (worst case) | 7.62 bit/B | 1.05 | 1.047 / 1.046 | n/a | 858 / 2413 |
| per-channel outliers (log-normal scale sigma 0.7) | 6.79 | 1.18 | 1.171 / 1.171 | 1.170 (11-14 MB/s) | 880 / 2638 |
| outliers + Student-t(4) tails | 6.49 | 1.23 | 1.226 / 1.226 | n/a | 884 / 2894 |
| fp16 scales plane (K and V) | 5.85-6.58 | 1.22-1.37 | 1.24-1.36 | | 880-950 / 2330-2750 |
| fp32 pooled index rows, raw | 6.67 (byte-plane mean) | 1.20 | **1.079** | | 929 / 2340 |
| fp32 pooled index rows, byte-shuffled | | | **1.135-1.144** | | 1300 / 3880 |
Reading: zstd at level 1 already reaches the order-0 entropy of the codes (levels 3 and 19 add nothing; -19 is 70x slower); LZ matching finds nothing in quantised activations, so `lz4` (not installed
on the server) would sit at about 1.0x; the entropy stage is the whole gain. The index rows need the byte shuffle. The earlier `scripts/memory/entropy_bound.py` gave 1.06 / 1.14 / 1.20 for Gaussian / Laplace / Student-t vectors of width 128 and 1.20 (shuffled 1.16) for fp32 states; the two syntheses agree.
* **Real activations are probably better than Gaussian** (U): keys have outlier channels, which make the per-64 absmax large and leave the other channels on few levels; this is what the second and third rows model. Whether the
real distribution is closer to row 1 or row 3 decides 1.05 against 1.23; the model itself must tell.
* **Literature, other dtypes**: Bf16 caches carry about 11 bits of entropy per scalar (about 30 % smaller, speculative-KV-coding blog), FP8 weights compress to about 83 % (Heilper and Singer, lossless compression of low-precision tensors),
and the slack "collapses as the bit width falls" (same blog); that is consistent with 1.05-1.25 for int8 codes. Entropy-coded KV in KVComp is lossy end to end (quantisation first).
Estimate for a whole block and node (E; weights 1024 / 32 / 128 of 1184 B; codes, scales, index ratios per column; node = 112 MiB fp32 GDN state at 1.0 / 1.12 / 1.2 from `entropy_bound.py`):
| scenario | codes | scales | index | block ratio | node ratio |
|---|---:|---:|---:|---:|---:|
| pessimistic | 1.05 | 1.20 | 1.08 | **1.057** | 1.0 |
| central | 1.17 | 1.25 | 1.14 | **1.169** | 1.12 |
| optimistic | 1.30 | 1.35 | 1.20 | **1.290** | 1.2 |
### A.3 Where the time goes on a switch, and what compression does to it
Decomposition of the restore (C for the path, M for the totals from `prefix-cache.md` sections 2-3):
* K/V pages: `OriginalQsaMappedJournal::import_pages` -> `write_import_spans` -> `m.write(...)` into the **pinned mapped host image** (the authority for every cell; the 20-32k-cell VRAM window is
refilled on demand after the resolver reset). This is a **host-to-host memcpy**, one thread, plus `context.synchronize()` before it. 180k tokens x 12 layers x 1056 B = 2.28 GB; measured 175-194 ms for 2.4-2.6 GB = **13-14 GB/s** (M).
* Pooled index rows: `OriginalQsaResidentIndex::import` writes into the **device** image: 180k x 12 x 128 B = 0.28 GB over PCIe at 45 GB/s = **about 6 ms** (E).
* So the owner's picture ("dominated by the PCIe copy; 2.6 GB = 60 ms at 45 GB/s") is not what runs: 60 ms is what the same bytes would cost over PCIe, the restore takes 3x that because it is
a single-thread host memcpy. **The cheapest switch speed-up is a parallel memcpy**: 4 threads over the 12 layers x blocks would approach the DRAM limit (read 2.3 GB + write 2.3 GB at 74.5 GB/s
shared = about 62 ms floor, E), saving about 100-130 ms per full switch at 180k, bitwise identical by construction. Not measured; it is a candidate row, not a result.
Effect of compression on that path (E, decompress 2.4 GB/s per thread from the S measurement, writing straight into the pinned image instead of memcpy):
| threads on the switch | decompress 180k (2.28 GB raw) | 243k | note |
|---|---:|---:|---|
| 1 | 950 ms | 1.2 s | 5x slower than today's 190 ms |
| 4 | 240 ms | 320 ms | about today's |
| 8 | 120 ms | 160 ms | about 0.6x of today; the same as a parallel memcpy would give without compression |
| GPU (nvCOMP-class) | does not apply | | see below |
So compression never makes the switch faster than an uncompressed parallel import; at best it hides inside it, and it takes up to 8 hardware threads at the one moment the engine thread is waiting. The switch is 0.07-0.3 s of an 8 s request (1-4 %); there
is no meaningful time to win there. **Where time can be won is eviction:** a session evicted for lack of RAM costs a cold prefill (28-31 s at 100k, 51-55 s at 180k, M) instead of 0.2 s, so the value of
extra capacity is about 250x the cost of the copy, but it only exists when the working set falls into the band between the raw and the compressed capacity (about 14 % of the budget wide).
**GPU-side decode (nvCOMP-style) is the wrong shape here.** The project links only the CUDA Driver API and loads sealed PTX built offline (no cuBLAS/nvCOMP dependency; `AGENTS.md`, `crates/cuda-driver`). A hand-written
GPU entropy decoder (Huffman/tANS LUT kernel, about 500-800 lines CUDA plus a seal cycle for sm_120 and sm_86) is possible, but the destination of 89 % of the bytes is the **host** K/V image: GPU decode would mean
compressed bytes up (2.0 GB), decode, raw bytes down (2.3 GB), both over the PCIe the prefill expert ring is using (44.6 GB/s measured over the copies, ledger U6). That is about 100 ms of PCIe plus the decode, no better than the 190 ms memcpy it replaces, and it
competes with the prefill that follows. Only the index rows (device-resident, 11 %) would benefit. No-go.
### A.4 Async compression: CPU budget (C/E)
* Hardware (M): the server is a Ryzen 9 9950X3D, 16 cores / 32 threads, 128 MiB L3; the engine takes **15 expert workers** (`docs/deploy.md`; `min(cores - 2, 15)`), one engine thread and the draft/stager threads. The design doc's note
(C.5) says the 15 workers sit on 15 physical cores and the CPU leg is about 3.9 ms of a 15-18 ms round, so the spare capacity is **one physical core plus the SMT siblings (about 14-16 logical threads that share execution units with busy workers)** (U for the pinning layout). Decode is bound by host DRAM (CPU leg + PCIe reach 74.5 GB/s together, `roofline.md`), so a compressor competes for the scarce resource even when cores are free.
* The load is small if blocks are compressed **once, when they become cold**, not as a stream of whole sessions: a block is immutable; a request adds about one block (1.6-2.7k tokens = 23-39 MB raw, `prefix-cache.md`). At 0.85 GB/s per thread that is **about 30-45 ms of ONE thread per 8 s request (0.4-0.6 % of a thread)** and 1.2 GB/s of DRAM traffic for 30 ms. A cold 180k build (55 s of prefill) adds
3.0 s of one thread (2.8 GB at 0.85 GB/s). Both are negligible next to 15 busy workers, but "negligible" for decode is exactly what the paired A/B must show (deploy.md measured: removing 7 of the 15 workers costs -2.4 %; a pure DRAM-bound neighbour at 1-2 % of 74.5 GB/s is expected to cost under 1 %, U).
* "Idle only" (the design doc's rule) is hard to meet for an agent: the gap between requests is 56-448 ms (M) and with several sessions there is no idle at all, so the compressor must run at idle priority beside the decode, with a cap of 1-2 threads.
* Policy that makes the whole thing small: compress only blocks of sessions that are **not the live one** (the live session's buffer holds its prefix; the same session continuing never reads its blocks, which is why lazy parking T6 saves 100 % of them for a single agent), and decompress on switch only the blocks the other session overwrote.
### A.5 RAM capacity (E)
Per session = blocks (14,208 B x tokens) + 2 nodes of 127 MB (a thinned session keeps its frontier and one previous node). Budgets: 8 GiB and 13 GiB are the measured `auto` values on the 5090 server with the 53.5 GiB engine footprint (`deploy.md`, `prefix-cache.md`); 27 GiB is what a 41 GB `MemAvailable` (observed on the server 2026-11-12 with a job running) would give at 75 %.
Parked size of one session, raw -> pessimistic / central / optimistic:
| tokens | raw | pessimistic | central | optimistic |
|---|---:|---:|---:|---:|
| 30k | 0.68 GB | 0.66 | 0.59 | 0.54 |
| 70k | 1.25 | 1.20 | 1.08 | 0.98 |
| 100k | 1.67 | 1.60 | 1.44 | 1.31 |
| 180k | 2.81 | 2.67 | 2.42 | 2.19 |
| 243k | 3.71 | 3.52 | 3.18 | 2.89 |
Sessions that fit (fractional; the integer part is what is kept):
| budget | tokens | raw | pessimistic | central | optimistic |
|---|---|---:|---:|---:|---:|
| 8 GiB | 70k | 6.88 | 7.19 | 7.97 | 8.74 |
| 8 GiB | 180k | 3.06 | 3.21 | 3.56 | 3.91 |
| 8 GiB | 243k | 2.32 | 2.44 | 2.70 | 2.97 |
| 13 GiB | 70k | 11.18 | 11.68 | 12.95 | 14.20 |
| 13 GiB | 180k | 4.96 | 5.22 | 5.78 | 6.36 |
| 13 GiB | 243k | 3.77 | 3.96 | 4.39 | 4.83 |
| 27 GiB | 70k | 23.2 | 24.3 | 26.9 | 29.5 |
| 27 GiB | 180k | 10.3 | 10.8 | 12.0 | 13.2 |
| 27 GiB | 243k | 7.8 | 8.2 | 9.1 | 10.0 |
In whole sessions the central scenario gains: 8 GiB 70k 6 -> 7, 180k 3 -> 3, 243k 2 -> 2; 13 GiB 70k 11 -> 12, 180k 4 -> 5, 243k 3 -> 4; 27 GiB 180k 10 -> 11-12, 243k 7 -> 9. **At the budgets that matter for 243k sessions
the gain is zero or one session**, and in the pessimistic case it is zero everywhere but 70k.
Comparison with the other levers (E): lazy parking removes the live session's blocks (3.2 GiB at 245k) = one full session at 8-13 GiB, more than the central compression gain, and costs 0.27 s on a switch (the same memcpy); raising the budget from
8 to 27 GiB (the single-copy work freed about 42 GB) = 3.4x capacity, 20x the central compression gain. Compression multiplies what is left after those, ~1.17x.
### A.6 Exactness
Lossless coding is exact if the round trip is checked: store `{codec, raw_len, crc}` per span, decompress straight into the destination, verify the crc, and on any mismatch drop the node (a miss, never wrong state). The existing
byte-for-byte parked tests (`parked_tests`: write back, export, compare) and the `prefix_bypass` equality check (restored vs full read) keep their meaning; the lossless class needs no quality gate beyond them. **Any lossy variant** (re-quantising to Q4/K8V4, fp16 GDN
state) changes numerics and stays an experimental mode behind its own gate (`AGENTS.md`); not proposed here.
### A.7 Recommendation: measure-first, expected NO-GO as a stand-alone feature
1. **The minimal hook (T8), cost about 40 lines, no behaviour change**: in `ResidentQsaLayer::export_span` (K/V and index vectors are in hand) and where the node's GDN image is cloned (`session_park_and_qsa_owners.rs`), behind
`LELEKA_PREFIX_DUMP_STATS=1`, log per block and layer the 256-bin histogram entropy of the K codes, V codes, K scales, V scales, index byte-planes, and for nodes of the GDN byte-planes; optionally `LELEKA_PREFIX_DUMP_DIR=/data/leleka-e2e/prefill-latency/<task>/` writing 3 blocks (early, middle, late of one 243k replay; at the 2048 grid a block is 29 MB over the 12 layers, 87 MB in all; at the 8192 grid 116 MB each) and one node (127 MB) for `zstd -1/-3`, the byte shuffle and the speed test on the real bytes (about 215 MB at the 2048 grid). Entropy lines cost nothing and prove the ideal ratio (zstd reached the order-0 bound on every synthetic plane). It rides on any job that already replays a 243k session
(the `q245`/`fixbug-ledger` replays); alone, one 243k replay is about 0.4 GPU-h. `/data` has about 2 GB free, so dump only the sub-samples and move them to `garbage/` afterwards.
2. **Gate (from the design doc):** build the codec only if the measured K/V ratio is at least **1.3x** or the GDN ratio at least 1.3x. On the S data only the optimistic column reaches it.
3. If it passes: compress once per cold block with `zstd` level 1 (a Rust port or a vendored decoder, since the production binary may not link a library: a Huffman/FSE encoder is about 600 lines; this is a new dependency decision for the owner), 1-2 idle-priority threads, decompress on 4-8 threads straight into the pinned image on a switch; acceptance = bytes equal (property tests + `prefix_bypass`), paired A/B of decode tok/s with the compressor running against not running (A/A floor +-1-2 %), RAM series.
4. **Do first, in this order** (all cheaper and larger): T6/T7 lazy parking, a decision on the budget cap (T2/T11), a parallel import memcpy (candidate, E -100..-130 ms per switch at 180k), then T8.
## B. Orchestrator-mode benchmark (design, not run)
### B.1 Why this benchmark
The earlier analysis found no overlapping requests in 4 recorded sessions (227 requests, 0 negative gaps) and no `multi_agent_v1` call in 750 recorded rounds. With a Codex that orchestrates sub-agents, concurrent requests to the gateway are guaranteed, so what Leleka does with them
(FIFO queue, one generation at a time, cache switch per request) becomes the product behaviour, not an edge case.
### B.2 What Leleka and vanilla Strata do with concurrent requests today
| | Leleka (this repo) | vanilla Strata `--parallel 1` (our compare arms) | vanilla `--parallel N` / `--batch-mtp` |
|---|---|---|---|
| Admission | gateway `max_in_flight_requests` 17 (429 beyond); `mpsc(16)`; one worker task | the server queue: "one request at a time, the others wait" (`BATCHING.md` line 3) | up to N slots decode together |
| Execution | strictly serial, FIFO, no preemption of a prefill (cancel takes up to one chunk, 1.6 s at 2048) | serial; conversation cache parks the other session's history (on by default with an auto budget) | every verify window carries one token of each slot; per-slot GDN/QSA/PLE state; a slot costs 0.56 GiB VRAM at 32K |
| Switch | prefix store restore: 1-3 ms no-copy, 0.07-0.3 s when blocks were overwritten (M/E, 101 ms at 98k, 175-194 ms at 172-180k) + 98-109 ms decode-graph re-record per request (with or without a switch) | 50-60 ms per short conversation restore (DETAILS/BATCHING); a long prompt gives way to a short one (`BYIELD`) | n/a |
| Their own gain from batching | none | none | 4 concurrent requests on a 12 GB card: 63.1 vs 70.7 tok/s one after another (-11 %); PRO 6000 Blackwell all-in-VRAM: 179 -> 268-312 tok/s at 4 (+50..74 %); 2x3080: +15 %; PRO 5000: +31..39 % at 2-4 clients (vendor numbers, BATCHING.md). Setup advice: only where the expert cache holds at least half the experts; our 5090 tier holds 49.6 % |
### B.3 How to make Codex produce concurrent requests
Facts: the harness uses `codex exec --json --skip-git-repo-check -C <ws> "<prompt>"` with Codex CLI **0.163.0** (`run-codex.sh`; config rendered from `scripts/e2e/codex/config.toml.tmpl`: `approval_policy = "never"`, `sandbox_mode = "workspace-write"`, `wire_api = "responses"`, `stream_idle_timeout_ms = 900000`, `request_max_retries = 2`). Every request of this version already carries the `multi_agent_v1` namespace (10 KB) and `parallel_tool_calls: true` (M, `docs/e2e-run.md` 7), so the sub-agent tools exist and are on in the shipped version. Public documentation (OpenAI Codex docs, "Subagents") says:
* sub-agents are spawned **by the model when the prompt asks for it** ("spawn two agents", "one agent per point", say how to split, whether to wait, what to return); built-in agents `default`, `worker`, `explorer`; children inherit the parent's model and reasoning effort;
* config under `[agents]`: `max_threads` (legacy alias, third-party docs: default 6) / `max_concurrent_threads_per_session`, `max_depth` (default 1: the root spawns children, no grandchildren), `job_max_runtime_seconds` (CSV jobs); a flag `multi_agent` can be set by `--enable multi_agent` or `[features] multi_agent = true` in builds where it is not yet default;
* "each child performs its own model inference and tool invocations" in parallel threads: that is the source of concurrent `POST /v1/responses`.
* Not in the public text, **U** until tried: that `codex exec` (non-interactive) runs the spawn tools to completion under `approval_policy = "never"`; that the Qwen3.5 IQ3 model calls them correctly (a 10 KB tool namespace is one more place for tool-call integrity to fail); the headers/instructions of a child's requests (whether its first 8192 tokens equal the parent's, which decides prefix-cache sharing).
**Step P0, CPU only, about 1 hour:** run the real Codex binary (already installed on the server for the harness) against `scripts/e2e/codex/mock_responses.py` extended to script a `spawn_agent`-style call, record the `multi_agent_v1` schema (tool names, parameters), the number and timing of concurrent requests children issue, the per-request headers (`session_id`/thread id) and the common prefix length of parent and child requests. This answers the "can the CLI fan out" question without a GPU.
**If the model will not spawn (Fallback H): N parallel Codex sessions from the harness.** `cell.py` already takes a free proxy port, a cell directory and `--active-dir` per cell (concurrency-safe, `multiplexing-feasibility.md` section 4): start the N cells of one boot together, each with its own sub-task prompt; the stack is shared. This does not test Codex's orchestrator, but it produces the same request pattern with controlled work.
### B.4 Task and arms
Task: **`nestng-crm`** (`scripts/e2e/codex/tasks/nestng-crm`, 56-check `accept.py`, 30-70 rounds, two disjoint trees `backend/` (NestJS) and `frontend/` (Angular 20)) is naturally parallel: backend API + its jest/e2e tests, frontend pages + build, then a short README and a verification pass. A multi-part refactor
(`refactor-shop`) is a second choice (parts are independent files but the shared seed makes conflicts likely). `ttt` is too small (14-21 rounds) for N>2 but works as a cheap stress (4 x ttt).
The split prompt is the task's own text cut at the Backend / Frontend boundary (same acceptance); the orchestrator prompt adds only: "Spawn one worker for `backend/` and one for `frontend/`, wait for both, then write README.md and run both builds and test commands yourself; do not spawn further agents."
| Arm | What runs | Purpose |
|---|---|---|
| S1 | one session, the full prompt (the existing cell) | reference single-agent wall (LEL CRM M: 488 s, 54 rounds, 163 tok/s) |
| S2 | backend session, then frontend session, fresh contexts, strictly sequential (harness) | the correct sequential baseline for the same sub-tasks |
| H2 | the same two sub-task sessions started together (harness fan-out) | time-sliced queue with controlled work |
| O | one orchestrator prompt, Codex spawns 2 (and in a second variant 3-4) sub-agents | the real orchestrator mode (if P0 passes) |
| H4 (optional) | 4 x `ttt` started together | queue depth 4, switch and tier penalty |
| V1 / V2 / V4 (optional, owner's word) | vanilla `--parallel 1`, `--parallel 2 --batch-mtp`, `--parallel 4 --batch-mtp`, arms S2/H2/O | what batching gives on this card; the reference of any "several times" claim |
Quality: temperature 0 as in the existing cells; accepted by the same `accept.py` (strict) and the relaxed `reaccept-1` version, both reported (rule from the ledger, 2026-11-12); the workspace of parallel children must be disjoint, merge conflicts counted as failures. Paired reps: 3 blocks, arm order rotated, same boot per block (no cross-boot comparisons), release pinned by the PROVENANCE commit.
### B.5 Metrics (from `requests.log`: admitted, engine_start, first_token, session id; `proxy/rounds.jsonl`; `mon.csv`)
* **Wall to accepted result** per arm (primary, but CRM wall sd is 21-112 s on 430-540 s: effects below about 15-20 % cannot be resolved with n=3; this is why the other metrics matter).
* **Aggregate tok/s** = sum of committed output tokens / wall, and **engine duty cycle** = sum of engine-busy intervals / wall; **overlap recovered** = seconds in which the engine served request k while another session was in tool/think time.
* **Per-session tok/s** (decode tokens / decode time of its requests, expected unchanged) and **per-session pace** (tokens / wall, expected about 1/N).
* **TTFT** and **queue wait** (`engine_start - admitted`) per request, p50/p90, expected (N-1) x 8 s; **switch cost** per request (`prefix_import_ms`, `reused_tokens`, `prefix_hit`, graph re-record) and the **tier penalty** (VRAM expert share, hit share by request ordinal after a switch vs same session continuing).
* Rounds and requests per session (trajectory length differs between greedy runs), sub-agents actually spawned and their request counts, 429 or timeout events, tool-call failures.
* **VRAM min free** (rule: at least 315 MiB, M 338-340 MiB on the 243k runs), **RAM** `MemAvailable` min, prefix-store used/budget/evicted/rejected (extra sessions raise eviction).
* Acceptance: pass/total of both accept versions.
### B.6 Expected effect: when the time-sliced queue helps and when not (E from M)
Model for N sessions of equal work, per-request model time m, tool/think gap g (gamma = g/m = (wall - model)/model over a cell), switch overhead sigma per request (switch + unmeasured tier penalty, relative to m). Sequential = N m (1 + gamma). Queue (N large enough to keep the engine full, N >= 1 + gamma) = N m (1 + sigma) + a serial head and tail. So
speed-up = (1 + gamma) / (1 + sigma), capped by the serial parts of the orchestrator.
* M gamma from `docs/e2e-data/codex-compare/compare.csv` (3 reps each): LEL CRM **0.089** (0.067-0.117), LEL ttt 0.034, VAN CRM 0.194 (0.074-0.387), VANL CRM 0.224, VAN ttt 0.037. M trace gaps (4 recorded sessions): 1.0-2.0 % of wall (`docs/e2e-data/*-trace.csv`).
* M sigma pieces: switch 0.07-0.3 s on an 8.3-8.4 s request (CRM LEL 395.7 s / 47 rounds) = 0.8-3.6 %; tier penalty U (cold-tier hit gap 3.1 points = about 1.5 % of decode, E from 0.0021 point/slot and 0.67 %/192 slots); say sigma 1-6 %.
| gamma | sigma 1 % | sigma 3.6 % | sigma 6 % |
|---|---:|---:|---:|
| 0.034 (LEL ttt) | 1.024 | 0.998 | 0.976 |
| 0.089 (LEL CRM) | 1.078 | 1.051 | 1.027 |
| 0.194 (vanilla-like waits) | 1.18 | 1.15 | 1.13 |
* **Trace-driven check** (`scripts/memory/queue_gap_sim.py`, S/M: recorded service times and gaps of the four sessions, FIFO engine, pairs and all four together): concurrent makespan against the sum of solo walls = **0.993-1.010 with a 0.1-0.3 s switch at the recorded speeds; 0.98-1.025 if decode were 2.5x faster with the same gaps**. The recorded sessions have so little idle (1-2 %) that the queue cannot gain more than 1-2 %, and a 0.3 s switch erases it.
* **Orchestrator end to end (E):** CRM model time 448 s (LEL mean). Split into two children, the queue makespan is about 448 x (1 + 0.01..0.04) + serial plan/wait/merge requests (about 20 s, which do not overlap) = 472-486 s, against S1 488 s and S2 (sequential children plus the same serial parts) about 505-515 s: **O/S2 about 1.03-1.08, O/S1 about 1.00-1.03**, with the trajectory noise (wall sd 21-112 s) much larger than the effect. With vanilla-like waits (gamma 0.19) up to 1.1-1.15.
* **When the queue helps:** (1) long tool waits while other agents have work: builds, test suites (`ng build` 20-60 s, jest runs) in a child while another child decodes: this is the gamma term; (2) any cache-less alternative: against a single-slot engine that re-prefills on a switch the cache saves 3.5-5.5x at 70k (E, `multiplexing-feasibility.md` 2.4; M sum of TTFT 1,200 s -> 244 s on the 4-session trace); (3) fairness: a child's short request is not blocked behind the orchestrator for more than one request.
* **When it does not:** (1) tool time is small (gamma below sigma, ttt-like tasks): the queue is a wash or slightly negative; (2) the engine is the bottleneck with N >= 2: per-session pace is 1/N and the wall to the last result is the sum of model times, no matter how many agents; (3) a cold 180k prefill (55 s) blocks all (FIFO, no preemption); (4) more sessions than the RAM budget keeps (A.5) turn switches into cold prefills; (5) each child's first request is a cold prefill of its own context (1-9 s; 9.3k tokens of shared system+tools are cached only if the first 8192-token block is identical to the parent's, U).
* Simultaneous decode (not built) is a separate, later step: E 1.0-1.3x at N=2 on top (`multiplexing-feasibility.md` 3.2); vanilla already has it opt-in.
### B.7 GPU cost
| Step | Content | GPU |
|---|---|---:|
| P0 | mock-server run of the real Codex: tool schema, concurrency pattern, prefix overlap | 0 (CPU, about 1 h) |
| P1 pilot | one boot (about 6 min) + O prompt x1 + H2 x1: do children spawn, do 2 requests overlap, no 429/timeouts | 0.7 h |
| Main | per block: boot 6 + S1 8 + S2 9 + H2 9 + O 10 = 42 min, x3 blocks, order rotated | 2.1 h |
| H4 stress (optional) | 4 x ttt together, about 10 min per block | +0.5 h |
| Vanilla V1/V2/V4 (optional, owner's word) | boot 6 + S2 9 + H2 9 + O 10 = 34 min x3 | +1.7 h |
| Total | | **about 3-3.5 h Leleka-only; about 5 h with vanilla** |
Shares the stack start and guards with `cmp_codex_job.sh`; a new stub only needs the concurrent launcher (the harness runs cells sequentially in `run_cells`). Merge with step 1 of the multiplexing plan (2-3 GPU-h) rather than running both.
The run holds `requests.log` per session id, so no new telemetry is needed for the first pass; the three numbers the multiplexing plan asks for (queue wait, import ms, tier VRAM share by ordinal after a switch) are the new fields to add if missing.
## Sources
* Repo: `docs/prefix-cache.md`, `docs/design/memory-single-copy-and-elastic-state.md` C.4-C.6, T8/T9, `docs/experiments/multiplexing-feasibility.md`, `docs/experiments/plan-faster-than-strata.md` (6g), `docs/e2e-run.md` 7, `docs/deploy.md` (workers), `docs/roofline.md`, `engine/strata/docs/BATCHING.md`, `docs/e2e-data/*-trace.csv`, `docs/e2e-data/codex-compare/compare.csv`, `scripts/e2e/codex/{run-codex.sh,config.toml.tmpl,mock_responses.py,tasks/nestng-crm/task.md,compare/cmp_codex_job.sh}`; code: `crates/context/src/geometry.rs`, `crates/experimental-ref/src/kv_q8.rs`, `crates/cuda-driver/src/{qsa_mapped_journal/original_qsa_mapped_journal.rs,qsa_resident_index/qsa_resident_index_checkpoint_restore.rs,qsa_prompt_indexer.cu}`, `crates/engine-qwen35-cuda/src/qwen_forward/{session_original_prompt.rs,qsa_resident_device.rs,qsa_resident_device/resident_qsa_span_export_and_seal.rs,gdn_state.rs}`.
* Scripts added: `scripts/memory/kv_block_compress_sim.py` (synthetic block, writes planes for `zstd`), `scripts/memory/queue_gap_sim.py` (trace-driven queue model). The synthetic planes were run on `rnr5090` under `/data/leleka-e2e/prefill-latency/async-park-compression/` (6.8 MB, moved to `garbage/` afterwards, see `garbage/LOG.txt`).
* Public: OpenAI Codex documentation, subagents page (learn.chatgpt.com/docs/agent-configuration/subagents, formerly developers.openai.com/codex/multi-agent); third-party Codex multi-agent notes for `max_threads` / `max_depth` defaults (codex.danielvaughan.com, March 2026); lossless low-precision compression (Heilper and Singer, arXiv 2508.19263); KVComp (arXiv 2509.00579); speculative KV coding blog (fergusfinn.com/blog/kv-entropy-coder). Public figures are secondary sources and unverified against Codex 0.163.0.
@@ -0,0 +1,265 @@
# Plan 6g: concurrent agent sessions, time-sliced today and simultaneous decode tomorrow (feasibility, 2026-11-12)
Read-only analysis of code and docs; no GPU, no queue stub, no engine change. Owner idea (2026-11-12): sessions and telemetry let Leleka serve
several agent sessions at once and be several times faster in aggregate. Owner clarification the same day: the sessions already are a queue
that switches per-session caches without a full prefill. Both layers are analysed, in that order. This is a separate axis from the stage 7
metric (single-session decode tok/s); nothing here changes single-session speed except through the memory it would take.
Labels: **M** = measured in a document or log named; **C** = read from code; **E** = estimate by arithmetic from M numbers (the arithmetic is shown);
**U** = unknown / guess. A number without a label is quoted from the page named next to it.
## 0. Result
| | Time-sliced multiplexing (TODAY, in the product) | Simultaneous decode (NOT implemented) |
|---|---|---|
| What runs | one request owns the engine from prefill to EOS; the next one queued starts after it (C: `attach.rs::serve_claimed` awaits `serve_one`; engine `generation_full` -> `ResourceExhausted`; one owner thread) | N sessions inside one verify graph (rows of several sessions per window), or two graphs overlapped on two streams |
| Sessions' state | per-session K/V + GDN/PLE + draft ring parked in host RAM as hash-chain blocks and nodes, restored on the next request (`docs/prefix-cache.md`) | N LIVE state sets in VRAM/pinned RAM at the same time (new) |
| Aggregate decode tok/s over N sessions | about the single-stream speed (M: 158-165 tok/s on LEL cells; one stream at a time). E: 0.97-1.0x of N sequential sessions | E: **N=2 1.0-1.3x (central 1.1-1.15x), N=4 1.0-1.55x (central ~1.2x)** of the same N sessions run one after another; not "several times" |
| Per-session tok/s while N are active | 1/N of the single-stream speed on average (the others wait), full speed while it owns the engine | each session slower than alone (joint round is longer), faster than 1/N |
| Cost of switching sessions | M: no-copy hit 1-3 ms (resume path 5.5-7 ms, A3); copy of the blocks the other session overwrote 101 ms at 98k, 175-194 ms at 172-180k tokens; E 30 ms at 30k, 250 ms at 243k. Plus the decode-graph re-record 98-109 ms per request (Q7) which is paid with or without a switch | none for switches, but a new scheduler and tier-sharing cost (U) |
| TTFT of a returning session | M: 2.3-2.8 s at 100k, 2.7-4.8 s at 180k (grid only, chunk 8192) against 28-31 s and 51-55 s cold; M: median 0.71 s, p90 1.06 s at about 70k with `--prefix-cache-tail reply` | queueing wait is removed, prefill of the suffix still blocks the shared device unless chunk-interleaved |
| Wall-time gain over a single-slot engine that re-prefills on a switch | E: 2.0-2.9x at 30k, 3.5-5.5x at 70k, about 4x at 100k (section 2.4); M on the synthetic 4-session trace: sum of TTFT 1200 s -> 244 s | not applicable (starts from the time-sliced baseline) |
| Gain over N sessions served strictly one after another with warm caches | E: 1.00-1.08x (fills the 4-8 % tool/idle gaps of LEL cells; minus switch overhead 1-3 %) | E: the numbers above |
| Memory per extra session at 30-100k | host RAM 14.2 KB/token + 127 MB per kept node (M): 0.56 / 1.1 / 1.6 GB at 30k / 70k / 100k; VRAM 0 | pinned host K/V fixed at the serving context (M: 3.32 GB at 262,144, 1.66 GB at 131,072) + VRAM about 0.55-1.2 GiB (E) taken from the expert tier |
| 256k sessions | N is bounded by RAM only; 2-3 parked sessions in the usual 8-14 GiB budget | N=1 today; N=2 barely (needs about 4.4 GB RAM + 1 GiB VRAM, the host has 7-8 GB spare); N>=3 impossible as configured |
| Engine work | none (exists); missing pieces: queue order aware of cache residency, session-aware eviction, telemetry of switch cost | large: scheduler, N live session objects (the engine is `Rc`/`RefCell`, one owner thread, one set of QSA owners), kernel changes (`kVerifyMaxT = 8`, sealed PTX), gRPC/gateway concurrency, identity story |
| Vanilla Strata | has the same (conversation parking, on by default with an auto budget) AND an opt-in `--parallel N` (see 2.5) | **vanilla already has it, opt-in** (`docs/BATCHING.md` at the pinned commit) |
Recommendation (details in section 4): do not build simultaneous decode yet. First (a) characterise what exists with two and four concurrent
Codex sessions through the gateway (about 2-3 GPU-hours), (b) take one routing dump per session for an offline expert-union simulation (about 0.5
GPU-hour), (c) optionally run vanilla with `--parallel 2/4 --batch-mtp` on the same card as the reference of what batching gives on this hardware
(about 1.5 GPU-hours; needs the owner's word because vanilla is not re-measured by rule). Decide after these.
**Correction to the premise.** Vanilla Strata is not one-request-at-a-time only: `engine/strata/docs/BATCHING.md` (same tree as our pin, `docs/upstream.md`)
documents `--parallel N` (1..8 slots, opt-in, default 1), `--batch-mtp` (one MTP proposal per slot), per-slot conversation caches and batch windows. Our
codex-compare ran vanilla with `--parallel 1` (`scripts/e2e/codex/compare/cmp_codex_job.sh`, vanilla launch line). So "Strata does not have it" is wrong; "the
benchmark did not use it" is right.
## 1. Where the sessions are today (code)
* Gateway (`control-plane`): `POST /v1/responses` handlers are bounded by `max_in_flight_requests` (default 17, 429 `runtime_overloaded` beyond;
`docs/api-contract.md` "Admission lifecycle"). They enqueue on one `mpsc::channel(16)` (`serve/engine.rs`, `state.attach_engine(16)`); an optional queue budget
expires a waiting request (`queue.rs`). One worker task (`backend_worker/attach.rs::serve`) takes commands in arrival order and awaits each `serve_one` to its
terminal event before taking the next. The contract text says it plainly: "The worker still executes serially ... does not implement batching".
The session id (`session_id` header Codex sends) is only logged (`request_log.rs`, `SESSION_HEADERS`); no scheduling decision reads it.
* Engine process (`desktop-core` runtime gRPC): `reserve_generation` allows one active generation; a second `Generate` gets `ResourceExhausted`
`generation_capacity` (`runtime_rpc/generate_rpc.rs::generation_full`). The gateway never sends it, because it serialises.
* Engine (`engine-qwen35-cuda`): one owner thread, `command_loop` -> `serve_generate` -> `engine_core::request::run_request` (admit, resume, prefill, decode, finish)
runs a whole request synchronously. One `OriginalServeStack`: one positional K/V buffer (12 QSA layers), one GDN/PLE state, one MTP draft ring, one expert tier.
* The verify graph is captured per window width T = 1..8 plus a commit graph, per request, bound to that request's QSA owners, GDN image and PLE history
(`docs/experiments/decode-graph-reuse.md` section 1; 54-62 ms capture + 27-30 ms instantiate, 98-109 ms per request, ledger Q7). A window carries the rows of ONE sequence;
`kVerifyMaxT = 8` is compiled into the window kernels (`acc[kVerifyMaxT]`, `GMAX >= kVerifyMaxT`, `docs/adaptive-spec.md` "Wider windows than 6"). Mean T per round
is 2.7-4.1 (M: 2.74 at 245k, 4.09 in a Codex replay); 3.3-3.4 tokens per round on Codex sessions (M `docs/e2e-run.md`). Rows of two requests cannot share a graph
today: the GDN recurrence, the QSA page tables and the PLE history are per sequence and the kernels index them by one base.
* So today there is no batch>1 anywhere, and the only way two sessions meet is the cache switch below.
## 2. Layer 1: the time-sliced baseline (what the owner asked to analyse first)
### 2.1 What a switch costs
Mechanism (`docs/prefix-cache.md`, C): the prompt is read on a token grid; after each chunk the policy may keep a node (GDN + PLE host images, draft-ring snapshot,
index tails; about 127 MB at the 5090 profile) plus K/V blocks (INT8 K+V and pooled index rows, 14,208 B per token, shared by reference). A request walks the
hash chain and `import_parked` copies back only the blocks the live positional buffer no longer holds, installs the GDN/PLE images, re-anchors the draft ring, prefills the suffix.
| piece | measured | source |
|---|---|---|
| lookup over a 40k-186k token prompt | 29 us mean (59 us max) at 40k; 0.2 ms at 186k | prefix-cache.md sections 2, 3 |
| same session continues (buffer already holds its prefix) | 1.3 ms for a hit that copies nothing; resume path in a live run 5.5-7.0 ms (`request.resume` 2.2-2.9, `begin_request` 0.8, `import_session` 0.6-1.4, `draft_resume_at` 0.8, `mtp_kv_restore` 0.7, `layer_index` 0.4) | prefix-cache.md section 2; step-ledger A3 |
| another session had overwritten the cells | 20-37k tokens (up to 524 MB): 34 ms mean, 43 ms max; 98k tokens (1.4 GB): 101 ms; 172-180k (2.4-2.6 GB): 175-194 ms (13-14 GB/s) | prefix-cache.md sections 2, 3 |
| 30k / 243k (not measured) | E: 0.43 GB -> about 32 ms; 3.45 GB -> about 255 ms at 13.5 GB/s | arithmetic from 14.2 KB/token |
| cold VRAM resident-window refill after an import | +0.5 to +5 %, at most 30 ms per request on identical output | prefix-cache.md section 2 |
| graph re-record + verifier assembly | 98-109 ms per request, with or without a switch (ledger Q7, fix wired behind `LELEKA_DECODE_GRAPH_REUSE`, off) | decode-graph-reuse.md |
| prefill of the part the grid cannot restore (partial block + reply + new tokens) | median re-prefilled 1.6-2.7k tokens per request (about 0.7-1.1 s at 2-3k tok/s); with `--prefix-cache-tail reply` median prefill 706 ms, p90 1,064 ms at about 70k context. This is paid by the same session when it continues alone, so it is NOT switch overhead | e2e-run.md 7, prefix-cache.md |
| expert tier left in the previous session's shape | **not measured.** The tier adapts on routing counts (up to 96 swaps per 4 windows); a different task starts on the other task's layout. Cold request 1 is -3.7 hit points against vanilla and requests 1-3 are -3.1 (hit-gap-causes H7), which is the size of a "tier not yet fitted" penalty; for alternating sessions it is U | hit-gap-causes-2026-11-11.md |
Cold prefill for comparison (M): 28-31 s at 100k and 51-55 s at 180k with 8192-token chunks (3.2-3.5k tok/s); about 1.8k tok/s with 2048 chunks (a 256k prompt is
about 2.5 minutes, ledger). E: 30k about 9-17 s, 70k about 21-39 s, 243k about 75-135 s.
**Net cost of one switch (E): copy 30-250 ms (30k..243k) + state install and ring re-anchor under 10 ms + window refill up to 30 ms = about 0.07-0.3 s, against a
request that takes 7-10 s on a Codex workload (M: model time per request LEL ttt 9.7 s, nestng-crm 8.3 s; compare.csv).** About 1-3 % of the request, before the unmeasured tier penalty.
### 2.2 How the queue is ordered and what N = 5..20 does to RAM
* Order: strict arrival order (FIFO `mpsc(16)`), no priority, no cache-aware reordering, no preemption of a running prefill (cancel takes up to one chunk, 1.6 s at 2048, e2e-run.md).
A cold 180k prefill (55 s) therefore blocks everyone behind it. A router that picks the longest cached prefix exists as a protocol (`/v1/prefix_match`, `PrefixSummary::match_tokens`) but "the router itself
is not part of this work" (prefix-cache.md).
* Request wait with N busy sessions (E): each request waits for the N-1 ahead, 7-10 s each, so about (N-1) x 8 s: N=5 about 32 s, N=10 about 72 s, N=20 about 150 s
(and HTTP 429 beyond 17 in flight, Codex retries). Aggregate stays at one engine; per-session speed is 1/N.
* Is every request a switch? With N >= 2 sessions all busy, practically yes: the live buffer holds whoever ran last. The system prompt and tools (about 9.3k tokens, M e2e-run.md) are
shared across Codex sessions, so the shared part (a 2048- or 8192-grid prefix) is never copied.
* Host RAM (M budget, E arithmetic): the cache budget is `auto` = 75 % of `MemAvailable` above 4 GiB at open, 7.3-13.7 GiB measured (7.8 GiB in the 4-session trace; 13.7 GiB in job 922);
during live Codex CRM runs `MemAvailable` fell to 7.4-8.3 GB because RSS grew 6-7 GB (e2e-run.md 7, 7d). Per session = 14.2 KB x tokens + 127 MB per node kept (a long session settles on 1-2 nodes):
| context | per session | sessions in 8 GiB | in 13 GiB |
|---|---|---|---|
| 30k | 0.43 + 0.13..0.25 = 0.56-0.68 GB | 12-14 | 19-23 |
| 70k | 1.0 + 0.13..0.25 = 1.1-1.25 GB | 6-7 | 10-11 |
| 100k | 1.42 + 0.13..0.25 = 1.55-1.67 GB | 5 | 8 |
| 180k | 2.56 + 0.13..0.25 = 2.7-2.8 GB | 3 | 4-5 |
| 243k | 3.45 + 0.13..0.25 = 3.6-3.7 GB | 2 | 3 |
So N=5 sessions at 70k fit with margin, N=10 only at the larger budget, N=20 only at about 30k. Beyond capacity the value-based policy rejects candidates and evicts the idle sessions' frontiers
(M: 12 sessions growing to 184k, 13 GB budget: budget held, reuse 62.2 %, 8,212 candidates rejected, prefix-cache.md section 5); the evicted session's next request re-prefills
from the last surviving ancestor, up to a full cold prefill. Retention is 60 minutes per node, displacement favours recently used sessions. Extra imports caused by switching: none beyond
the block copies of 2.1; extra evictions: only through capacity, not through switching itself (a node is immutable host memory; the restore does not consume it).
* The budget competes with the engine's own RSS growth and with `--expert-source resident` (about 50 GB pinned copy) on the 121 GB host; `--expert-source mapped` would free tens of GiB (prefix-cache.md, 3).
### 2.3 Why this is not simultaneous decode (c)
The engine decodes one session at a time, so the total decode rate across sessions is the single-stream rate (M: LEL cells 158-165 tok/s; 184 tok/s on the stage-7 profile). The gains of the
time-sliced scheme are exactly two: (1) no re-prefill of the shared history on a switch (section 2.4), (2) the GPU does not idle during one session's tool calls.
Gain (2) is small here: in the recorded real sessions consecutive requests never overlap and the gap before the next request is 56-448 ms (median 115-191 ms; 0 overlaps in 223
consecutive pairs of 943b, 945, 943d, 945d, `docs/e2e-data/*-trace.csv`); wall minus model time is 2.0 % / 1.0 % / 1.4 % / 1.6 % of wall in those four sessions and 3.7 % (ttt) and 8.3 % (nestng-crm)
for LEL in codex-compare (vanilla CRM: 17-19 %, because its model time is shorter). So two sessions can fill at most 4-8 % of LEL's wall (1.04-1.09x), and 20 % of vanilla's CRM wall.
Fair interleaving trades per-session latency for fairness; it does not add tokens per second.
### 2.4 Aggregate wall-time gain against a single-slot engine that re-prefills on a switch (E, with M anchors)
"Single-slot" = the Original's conversation cache (`--prompt-cache`, checkpoints of the ONE conversation whose K/V the buffer holds; after another session runs only the pinned root survives).
* M, job 921 (3 sessions interleaved, 10k -> 26k): reuse 41.3 % -> 68.0 %, TTFT mean 8.3 s -> 4.4 s, p95 13.0 -> 4.5 s; legacy TTFT grows with context, prefix-cache TTFT stays flat.
* M, job 923/927 (4 sessions x 24 requests, 3k -> 40k, 96 requests): reuse 26.5 % -> 88.0 %, mean TTFT 12.5 -> 2.5 s, p95 27.6 -> 5.5 s, **sum of TTFT 1,200 s -> 244 s**.
* M, 100k and 180k, two sessions alternating: legacy TTFT 28.2-28.6 s and 53.1-53.7 s every request; with the cache 2.3-2.8 s and 2.7-4.8 s (11-20x).
* E per request, with model time 8.4 s and cold prefill 3.3k tok/s (8192 chunk) to 1.8k tok/s (2048 chunk): context 30k: single-slot 8.4 + 9..17 = 17-25 s against 8.5 s warm (2.0-2.9x less wall);
70k: 8.4 + 21..39 = 29-47 s against 8.5 s (3.5-5.5x); 100k: about 8.4 + 30 = 38 s against 8.6 s (about 4x); 180k: about 7x at 3.3k tok/s, more at 1.8k tok/s.
The first request of each session is cold in both schemes, so for short sessions (the 15-60 requests of a Codex task) the gain is diluted by the cold starts; on the 4-session trace the measured end-to-end TTFT sum improved 4.9x.
* Against serving N sessions strictly one after another (each warm from its own history, which is what a user with one agent sees): 1.00-1.08x aggregate (section 2.3). The honest statement is therefore:
**time slicing makes N sessions about as cheap as N sequential ones, instead of 3-6x more expensive than that; it does not make them cheaper than sequential.**
* The comparison to quote for an owner demo is not "faster than sequential" but "N sessions served concurrently finish in about the sum of their times, each seeing 1/N of the speed, with TTFT of 1-5 s per turn instead of 30-55 s".
### 2.5 Does vanilla keep per-session caches? (read from `engine/strata`, not assumed)
* Yes, two ways. (1) Conversation parking: `--conversation-cache-mib N --conversation-cache-slots N` "park conversations in a bounded host-RAM cache so alternating requests (controller and worker histories,
sub-agents) reuse their prompts"; without the flag the budget is 40 % of the RAM left above the minimum free, at most 8,192 MiB, off when under 1,024 (`docs/DETAILS.md` line 624), i.e. on by default on a big host.
A request that starts at a checkpoint inside a parked one borrows that prefix. "It preserves histories; it does not run requests at once." (2) With `--parallel N` each slot is a conversation cache; the next turn's state is copied
back in 50-60 ms for a short conversation; a long prompt gives way to a short one (`BYIELD`).
* Vanilla also has simultaneous decode, opt-in (`docs/BATCHING.md`): `--parallel N` (1..8), "every verify window carries one token of each conversation", `--batch-mtp` adds one MTP proposal per slot, per-slot GDN/QSA/PLE state.
The server solo-path rule: one request alone runs the fast solo path with MTP; a second request moves the first into a slot. A slot costs 0.56 GiB VRAM at 32K context with INT8 K/V and, with K/V streaming, pinned RAM (1.6 GB at 128K).
* Its own measurements bracket our situation (BATCHING.md, all vendor/community numbers, not ours):
* 12 GB card, most experts on the CPU (Q2_0): 4 concurrent requests 70.7 tok/s one after another against 63.1 with `parallel 4` (-11 %); the text says why: "a batch also reads about as many distinct experts as the requests one by one (different conversations route to different experts), so the gain is in latency".
* RTX PRO 6000 Blackwell, all 24,576 experts in VRAM, MTP: 1 stream 179 tok/s, 2: 204-219, 3: 243-277, 4: 268-312, 8: 308-375 (+50 % at 4 without, +74 % with the launch-merging switches; 1.7-1.9 ms per added row).
* 2x RTX 3080 layer split, experts mostly off-card: 89.2 vs 77.3 tok/s with `--batch-mtp` (+15 %); RTX PRO 5000 owners: +31 % to +39 % with 2 to 4 clients.
* Setup recommends `parallel` only where "the expert cache must still hold at least half of the model's experts beside the slots"; "IQ3_S needs 32 GB or a split". Our 5090 tier holds 12,192 of 24,576 experts (49.6 %), right at that threshold.
* Consequence: the claim "unlike vanilla Strata we could multiplex" is not available as a differentiator of kind; at best it is a differentiator of quality of implementation (our telemetry, our prefix cache, N-way fairness). A fair comparison for any future "several times" claim is vanilla `--parallel N --batch-mtp` on the same card.
## 3. Layer 2: simultaneous decode feasibility
### 3.1 Real concurrency patterns in Codex agent sessions (question 3)
* One Codex session is strictly sequential: request k+1 starts only after the tool results of request k return. In all four recorded live sessions (227 requests, `docs/e2e-data/{943b,945,943d,945d}-trace.csv`)
there is **no overlap** (0 negative gaps); gap before the next request: min 56-77 ms, median 115-191 ms, p90 184-282 ms, max 448 ms (one 10.2 s outlier at the start of 943b); `queue_wait_ms` is 0 in every row.
* Parallel tool calls: 114 of the 750 rounds in `docs/e2e-data/codex-compare/rounds.csv` (723 have at least one call; none has more than two) issue two tool calls in ONE response; they are executed by Codex
between model requests, so they do not create two model requests. The tools seen are `exec_command` (824 calls) and `write_stdin` (12); no `multi_agent_v1` / sub-agent spawn call occurs in any recorded round, although the
tool is advertised (`multi_agent_v1` namespace, 10 KB, e2e-run.md 7). Not recorded does not mean impossible: sub-agents would create overlapping requests from one task, and no task used them.
* Therefore any benchmark of simultaneous decode must run **N parallel Codex sessions** (or an explicit sub-agent task); a single session never produces concurrent requests. The existing harness can: `cell.py` takes a free port per cell, a
cell directory and an `--active-dir`, and the logging proxy records per-request times (section 4).
* A real deployment with 5-20 sessions is mostly one user's several terminals / sub-agents; their requests arrive nearly at random, each session issuing a request every 8-10 s of model time plus 0.1-0.3 s of tools. So at N sessions the engine is saturated from N=2 on (utilisation per session 92-96 %): the queue, not the GPU idle time, is the bottleneck, which is what the owner observes ("5-20 requests in the queue").
### 3.2 Why multiplexing may or may not multiply here (question 2)
Facts (M): 48 layers, 512 routed experts per layer, 10 routed per token (tier simulator, hit-gap-causes appendix: `L, E, K = 48, 512, 10`); VRAM tier 12,192 slots = 254 per layer (49.6 % of experts), 1.952 MiB per slot;
hit share of entries about 90-92 % (replay mean 90.2, entry-weighted 92.2); about 480 entries per row, so 2,000 entries is about 4.1 rows per round; round 17.93 ms = graph 13.20 (mixer 5.75, FFN 6.85 of which host/tier wait 3.81, other 0.6) + 4.7
between graphs (4.30 on consecutive pairs; of it GPU fully idle 1.95 ms, verify launch call to first kernel 1.345 ms, MTP chain 1.76 ms); only 31 % of layers are not host-bound (step-ledger "Critical path"). Decode misses are bound by host DRAM:
CPU leg + PCIe DMA reach 74.5 GB/s together (roofline.md).
Row economics (M, replay 9b1 era, `docs/adaptive-spec.md`): window time T1 13.0, T2 15.1, T3 18.3, T4 22.3, T5 26.2, T6 31.2, T7 34.8, T8 38.9 ms: the first extra row costs about 2.1 ms (16 %), later rows 3.2-5 ms; a verified row of the SAME sequence costs 28 % of a one-row window.
Speculation already spends the batch dimension on rows of one sequence, which is why batching across sessions has less left to amortise than in a non-speculative engine. Pure non-speculative batching of N sessions (N rows per window, one token each) gives N/T(N):
N=4 4/22.3 = 179 tok/s, N=8 8/38.9 = 206 tok/s against 3.3/17.9 = 184 tok/s for one speculative session (E; mixed eras, indicative): no gain over speculation alone. Speculative rows per session and rows across sessions compete for the same marginal cost per row.
Miss traffic (E): 2,000 entries x 9 % = 180 missed entries x 1.952 MiB = 351 MiB per round = 4.7 ms at 74.5 GB/s, which is 26 % of the round and matches the measured 3.8 ms host/tier wait. Different sessions
route to different experts, so the missed set of N sessions is the sum, not the union (E): the wait term grows about linearly in N, plus a hit-rate loss because the tier of 254 slots per layer must now serve N working sets
(E: 91 % -> 85-88 % for unlike tasks, U; slope M 0.0021 point per slot). Loose outer bound: DRAM time per session-round is 4.7 ms of 17.9, so even with everything else hidden perfectly the miss traffic caps aggregate at about 3.8x (about 3x with the hit-rate loss).
That bound is not a prediction: nothing in the dependency chain (48 layers, each waiting for the host) hides perfectly.
Model (E): joint round time = sum over components of base x (1 + s x (N-1)), `s` = how linearly the component grows (0 fully shared, 1 fully per-session). Baseline N sessions one after another = N x 17.9 ms.
| component (base, ms) | optimistic s | middle s | pessimistic s | reason |
|---|---|---|---|---|
| mixer: GDN step, attention, router (5.75) | 0.3 | 0.6 | 0.9 | per-sequence state and K/V, small latency-bound kernels amortise partly |
| FFN device (3.04) | 0.6 | 0.8 | 1.0 | more distinct experts, grouped GEMM scales with rows |
| host / tier wait (3.81) | 0.8 | 1.0 | 1.1 | miss bytes add; tier shared -> more misses |
| other graph (0.6) | 0.5 | 0.75 | 1.0 | |
| between graphs (4.7) | 0.5 | 0.75 | 1.0 | launch idle 1.3 ms and commit shareable; each MTP chain is per sequence unless batched |
| N | optimistic | middle | pessimistic |
|---|---|---|---|
| 2 | joint 27.2 ms, **1.32x** | 31.6 ms, **1.13x** | 36.0 ms, **0.99x** |
| 4 | 45.6 ms, **1.57x** | 58.9 ms, **1.22x** | 72.2 ms, **0.99x** |
Certain: the baseline, the components, the miss arithmetic, the existing kernel limit. Guesses: every `s` (they are the whole result), the hit-rate loss, and the assumption that cross-session rows cost as much per row as same-session rows (they likely cost more:
fewer shared experts). The data that would turn guesses into numbers is section 4 step 2-3. Two more caveats on N=4: (i) 4 sessions x 3.3 rows = 13 rows exceeds the 8-row kernels, so either the kernels change or each session drops to 2 rows
(then tokens per round fall from about 3.3 to about 1.9-2.2 and E aggregate is at or below 1.0x), (ii) vanilla's PRO 6000 numbers (+50..+74 % at 4) come from a card where the whole model is in VRAM, so `s` for the wait term is near 0 there: that is the regime our tier is not in.
An alternative to joint graphs is overlapping two independent verify graphs on two streams (no kernel change): it can fill the GPU idle 1.95 ms + part of the 3.8 ms wait (up to 32 % of the round, E), but the CPU leg and DRAM are shared, so the
upper bound is about 1.3x at N=2 and it needs two live stacks (below). No evidence either way; U.
### 3.3 What it would take (question 4)
1. **Scheduler**: a continuous-batching policy per round that picks, per session, the window width by marginal tokens per ms (the existing adaptive policy `choose`/`draft_plan` generalised to a joint cost model `T(rows, sessions)`), admission of a new
session's chunked prefill between decode rounds (vanilla: slots decode for half the chunk time between chunks; our prefill is 2048-8192 token chunks of 0.6-2.4 s), fair order, cancellation per session. New code in `engine-core` (pure) plus the adapter.
2. **Per-session state isolation in the engine**: today one `OriginalServeStack` owns one set of 12 QSA layers (positional K/V, index images, pinned journals), one GDN/PLE state, one draft ring, one MTP actor, one verifier assembly. N live sessions need N sets
or a slot indirection (vanilla: "each slot gets its own state, a session carved like the stage's own"). The engine is built on `Rc<Context>` and `RefCell` (C: `serve_loop.rs`), process-wide singletons (`RECONFIGURING`, `INSTANCE`, `settings::process()`, `Governor::global()`, hexagonal.md "not a port") and a
`ServeDevice` port that is one-request-at-a-time (`Lifecycle`/`run_request`). This is a rewrite of the request lifecycle, not a flag.
3. **Graph shape**: a joint window carries rows of several sessions, so GDN recurrence (state chain per session), QSA gather (per-session page table and K/V pointers), PLE history, the commit graph and the accept step all need a row -> session indirection (vanilla passes per-row state as kernel params
and captures per row layout, `STRATA_BATCH_ATTN_ROWS`, `STRATA_BATCH_GDN_GROUPS`). `kVerifyMaxT = 8` must grow for N x 3.3 rows; sealed PTX for sm_120 and sm_86 must be re-sealed; graph variants multiply with the layout (rows per session).
Verification: vanilla itself needs `STRATA_IQ_MT_MIN=1`, `--pcie-frac 0` and a frozen tier to make batch output equal solo output; with the defaults "the outputs stay coherent but drift apart". For us that means a new equivalence class (like the tier placement class) and its own gate, not bitwise identity.
4. **Prefix cache sharing**: works unchanged by construction (blocks keyed by hash chain, immutable host memory); what changes is that the live set is no longer one buffer: the "one engine, one buffer" limitation in prefix-cache.md goes away only if the live K/V is per session. The grid import path would write into the session's own buffers.
5. **Gateway/contract**: the worker loop must dispatch several `serve_one` at once; the gRPC `generation_full` single slot and `Backend` doc ("one generation at a time") become a capacity N; `max_in_flight` already allows 17; the request log and monitor already carry session id and per-request times, so telemetry is mostly there (queue wait = `engine_start - admitted`).
6. **Memory governor**: add N x (pinned K/V + VRAM window + verifier assembly) to the plan; the expert tier shrinks by the VRAM taken.
Memory per extra live session (K/V numbers M from `docs/kv-streaming.md` and prefix-cache.md; the rest E):
| item | size |
|---|---|
| pinned host K/V, 12 QSA layers x 1,056 B/cell, allocated for the whole serving context | 3.32 GB at 262,144; 1.66 GB at 131,072; 0.83 GB at 65,536 |
| pooled index rows (device image) | 128 B/cell/layer: 0.4 GB at 262k |
| VRAM resident K/V window, 12 x 35 MB at 32,768 cells (20,480: about 264 MB) | 0.26-0.42 GB |
| GDN/PLE state + MTP draft ring | about 0.13 GB (the parked node is 127 MB) + ring |
| verifier assembly (graphs, arenas) at decode | 514 MiB today; vanilla slot total 0.56 GiB at 32K context with INT8 K/V |
| **VRAM per extra session** | **about 0.55-1.2 GiB**, taken from the tier at 512 slots per GiB |
| effect of 1 GiB on the tier | -512 slots = -4.2 % of the tier, about -1.1 hit point (0.0021 point/slot), about -1.8 % single-stream decode (H4: +0.67 % per +192 slots) |
* **N concurrent 256k sessions: impossible on this card and host as configured.** The VRAM floor is 316-355 MiB free at decode (vram-footprint-5090.md; 340 MiB at 243k): there is no spare VRAM, every extra session takes it from the tier (about -2 % per GiB).
The host is the harder limit: 3.32 GB pinned per session plus the prefix cache, with `MemAvailable` at 7.4-8.3 GB in a live 123k session; N=2 at 256k needs about 4.4 GB of RAM (3.32 + 0.4 + 0.7) and a prefix-cache budget that can hold only one 243k session (3.6 GB). N=2 is borderline, N>=3 does not fit unless
`--expert-source mapped` (frees tens of GiB, costs expert-fetch speed) or the resident copy shrinks.
* **Practical N at 30-100k** (cap the serving context at 131,072 for a multi-session profile: 1.66 GB pinned per session): VRAM allows N=2-4 at a cost of 2-6 % single-stream speed (1-3 extra sessions x 0.55-1.2 GiB x 1.8 % per GiB, E); RAM allows N=4 live (6.6 GB pinned) only with the prefix cache shrunk to a few GiB. So N=2 comfortable, N=4 with trade-offs, N=8 only with mapped experts. Because the speed model gives at most about 1.2x at N=4, memory is not the first blocker; the missing amortisation is.
## 4. Measurement plan and recommendation (question 5)
**Step 1, no new engine feature: two and four concurrent Codex sessions through the gateway (the existing cmp harness).**
The harness runs cells sequentially in `run_cells` (`cmp_codex_job.sh`); `cell.py` itself is concurrency-safe (free proxy port per cell, separate cell dir, `--active-dir`). New stub `cmp_codex_pair_job.sh` (test tooling, not serving): same stack start and guards, then per block:
(1) one `ttt` and one `nestng-crm` cell alone (sequential reference inside the same boot), (2) two `ttt` cells started together, (3) two `nestng-crm` cells together, (4) four `ttt` cells together; task copies in separate `--active-dir`, `CMP_REPS=1 2 3` as three blocks; unlike tasks in a mixed pair (ttt + crm) as the cross-task tier case.
Metrics per cell and per block: aggregate output tokens / wall for the whole set against the sum of the sequential walls; per-session decode tok/s and TTFT from `requests.log` (`admitted`, `engine_start`, `first_token`, session id) rather than proxy first-byte; queue wait = `engine_start - admitted`; `reused_tokens`, `import_ms`, prefix-cache stats; tier VRAM share per request (alone vs alternating = the unmeasured switch penalty of 2.1);
VRAM, RSS, `MemAvailable` from `mon.csv`/`env.tsv`; accepted 56/56 and 14/14. Expected result by construction: aggregate about 1.0-1.08x of sequential, TTFT p50 1-5 s, queue wait about (N-1) x 8 s; its value is the switch cost and the tier penalty with real numbers, plus the baseline for any later feature.
GPU time (E): per block boot about 6 min + warm-up, ttt alone 2.5 min, ttt pair 5, crm alone 8, crm pair 16, ttt x 4 about 10, mixed pair 11 = about 60 min; 3 blocks = **about 3 GPU-hours**; a first block alone (one repetition) is 1 hour and already answers the switch-cost question.
Quality rule: temperature 0 injected as in the existing cells; no performance claim without the paired sequential cell in the same boot.
**Step 2, no GPU beyond two short dumps: offline expert-union simulation.** `LELEKA_ORIGINAL_SERVE_DUMP_ROUTING=<file>` exists (`settings/memory.rs`; records of layer + 10 expert ids per row; E1 of hit-gap-causes), a tier simulator is in the appendix of `hit-gap-causes-2026-11-11.md`, and one trace (735 windows, mean 2.68 rows) exists at
`/data/leleka-e2e/runs/single-copy-ab/route-sparse/routing.bin`. Need one dump of a `ttt` replay and one of a `nestng-crm` replay (E1 jobs, 2 x about 12 min = **about 0.5 GPU-hour**). Offline: pair windows of two sessions round by round and compute (a) distinct (layer, expert) pairs of the joint window against the sum (the `s` of the FFN and wait terms), (b) hit share of one shared adaptive tier serving both against each tier alone (the tier penalty), (c) missed bytes per joint round
(the DRAM term). This replaces the guessed `s` of section 3.2 for the two components that dominate by measurements, with zero engine change.
**Step 3, optional: vanilla reference.** `strata launch ... --parallel 2` and `--parallel 4 --batch-mtp` on the same 5090 and the same two tasks, N concurrent Codex sessions against `--parallel 1` (about **1.5 GPU-hours**, plus the owner's word because "vanilla is not re-measured" is an owner rule, and this is a new arm, not a re-measurement).
It shows what batching gives on this card with an engine that has it (the 49.6 %-in-VRAM regime), and whether the benchmark must include a concurrent arm to stay "stably faster than vanilla". Vanilla's `--parallel` also moves expert slots (0.56 GiB per slot), so its single-session speed is the reference too.
**Step 4, optional, cheap: refresh the row-cost curve** (T = 1..8 on the current build, `LELEKA_SPEC=N` fixed windows over the 30-request replay, about 1 GPU-hour): the `s` of the mixer term is bounded by the marginal row cost; the 2.1..5 ms per row above is from the 9b1 era.
**Recommendation.**
* GO: step 1 (it is the honest measurement of the owner's observation, "5-20 requests queued, caches switched"), step 2 (it is the cheapest predictor of any simultaneous scheme and is already planned as E1), and add to the telemetry the three missing numbers: queue wait per request, switch (import) ms and the tier VRAM share by request ordinal after a switch. Add a cache-aware dequeue (pick the queued request with the longest `prefix_match`, bounded by a maximum wait) as a small gateway feature to evaluate: it removes copies and, more importantly, keeps a session's tier shape; expected gain is small (the copy is 1-3 % of a request), so it is only worth it if step 1 shows a larger tier penalty than E.
* NO-GO for now: the simultaneous-decode engine work (E: several weeks of engine work, a new sealed-PTX cycle and a new equivalence class) until step 1-2 show a joint-round estimate of at least about 1.4x at N=2 on real routing, or until the owner wants the product claim against vanilla `--parallel`. On today's numbers the plausible gain at N=2 is 1.0-1.3x (middle 1.13x), at N=4 1.0-1.55x (middle 1.22x), at a price of about 2-6 % of single-session speed through the VRAM taken, and it is capped by DRAM miss traffic, not by launch overhead.
* Do not promise "several times". The one regime where it holds in vanilla's own data is a card with the whole model in VRAM; ours reads 9 % of 2,000 entries per round from host RAM and that term does not amortise.
## 5. What is not known
* The expert-tier penalty of alternating sessions (the largest hidden cost of time slicing) and the cross-session expert overlap (the largest hidden term of simultaneous decode). Both are answered by steps 1-2.
* Whether Codex sub-agents (`multi_agent_v1`) produce overlapping requests in real use; no recorded task used them.
* The marginal cost of a cross-session row on the current build; 9b1-era table only.
* 243k switch cost (E, not measured) and the live behaviour of `--prefix-cache-tail reply` under alternation (its equivalence gate STRA-328 is still open).
* Vanilla's `--parallel` behaviour on the 5090 with IQ3_S at our tier size; BATCHING.md has no row for it.
## 6. Sources
`docs/experiments/plan-faster-than-strata.md` (6g), `docs/prefix-cache.md`, `docs/worker-pool.md` (CPU gpt-oss: 4 agents, 1 slot against 4 cache slots 1.73x; second device alone about 1.1x; shows the same split: cache gain large, concurrency gain small),
`docs/e2e-run.md` 7, 7d, `docs/e2e-data/*-trace.csv`, `docs/e2e-data/codex-compare/{compare.csv,rounds.csv}`, `docs/experiments/codex-compare-5090-results.md`, `docs/experiments/step-ledger.md` (A1-A3, Q7, critical path), `docs/experiments/hit-gap-causes-2026-11-11.md`,
`docs/experiments/vram-footprint-5090.md`, `docs/experiments/decode-graph-reuse.md`, `docs/adaptive-spec.md`, `docs/kv-streaming.md`, `docs/roofline.md`, `docs/architecture/hexagonal.md`, `docs/api-contract.md`, `engine/strata/docs/BATCHING.md`, `engine/strata/docs/DETAILS.md`;
code: `control-plane/src/backend_worker/{attach,serve_one}.rs`, `control-plane/src/serve/engine.rs`, `control-plane/src/request_log.rs`, `desktop-core/src/runtime_rpc/generate_rpc.rs`, `crates/engine-core/src/request.rs`,
`crates/engine-qwen35-cuda/src/backend_original_serve/runner/command_loop.rs`, `crates/engine-qwen35-cuda/src/backend/serve_loop.rs`, `crates/cuda-driver/src/mtp_original_full_verify.cu` (`kVerifyMaxT`).
@@ -0,0 +1,108 @@
# Orchestrator mode with sub-agents: smoke test of Qwen3.5 on Leleka (plan 6g, step P1)
Question of the owner (2026-11-13): can OUR model (Qwen3.5 MoE IQ3, served by Leleka release 83bdd85bb482) work in the Codex orchestrator mode, i.e. when Codex is told that it
is an orchestrator and spawns sub-agents? In that mode concurrent requests reach Leleka for certain, which is the premise of the multiplexing idea (plan 6g,
`docs/experiments/async-park-compression-and-orchestrator-bench.md` section B). This page is the cheap smoke run that comes before the 3-3.5 GPU-hour matrix of that page.
Labels: **M** = measured in this run (source named), **C** = read from the Codex binary or its documentation, **E** = estimate by arithmetic from M numbers.
## 0. Result
| Question | Answer |
|---|---|
| Does the model orchestrate? | **Yes, on the first try.** In its very first response it wrote one sentence and called `multi_agent_v1.spawn_agent` twice (parallel tool calls), a backend worker and a frontend worker, each with a self-contained 3.6 KB / 3.0 KB specification and the right directory restriction (M, round 1, 8.9 s, 1,849 output tokens). It then used `wait_agent` twice and `close_agent` twice, and did the integration (README, builds, tests) itself. |
| How many sub-agents | 2 (as asked; `agents.max_threads = 3` was the cap). 122 model requests: orchestrator 34, backend worker 69, frontend worker 19. |
| Tool-call integrity | **No defect.** 122 of 122 responses `response.completed`; 161 function calls (155 `exec_command`, 2 `spawn_agent`, 2 `wait_agent`, 2 `close_agent`), every name declared, every `arguments` valid JSON with the required fields and types (checker in `analyze_orchestrator_run.py`); no `generation failed` in `api.log` during the cell; no 429, no timeout. |
| Concurrency at the gateway | Up to **3 requests open at once** (18 s), 2 or more open for **250 s = 32 % of the wall**; 44 of 122 requests overlapped another one in time; the engine had work for 92 % of the wall (M, proxy timestamps). |
| How Leleka's queue handled it | FIFO, one generation at a time, as designed. Queue wait p50 2 ms, p90 5.0 s, max 51 s (sum 268 s); 42 of 122 requests waited more than 1 s, 4 more than 10 s. TTFT p50 0.68 s, p90 6.3 s, max 51.8 s. While both workers were alive each request took 13.0 s instead of 6.1 s (6.5 s queue + 6.5 s service): each session ran at half pace. |
| Cache switch cost | **Negligible.** 48 of 122 requests (39 %) switched the live session; import 29 ms median, 48 ms maximum (1.4 ms without a switch); cached share of the prompt tokens 98.1 %. Expert tier VRAM share 87.6 % on a switch against 90.4 % without (-2.8 points). |
| End result | Codex exit 0 after **791 s**. Acceptance **55/56 strict, 56/56 relaxed** (the gate of the ledger); the one strict failure is the board check that the single-agent cells fail too. |
| Faster than one agent? | **No.** Same boot, same task, single agent: 766 s, 96 requests, 55/56 strict, 56/56 relaxed. Orchestrator 791 s (1.03x slower, inside the run-to-run noise: the stored owner-default single-agent cells of this release took 427 / 539 / 651 s). The orchestrator generated 32 % more tokens (127,288 against 96,647) at the same decode speed (186 and 184 tok/s median), so the engine was simply busier: 724 s against 664 s of engine time. Against the sequential execution of the same 122 requests the overlap is worth about **1.08x** (E, section 5). |
| Go / no-go for the big 6g benchmark | **No-go for the full matrix as designed (3-3.5 GPU-h); the premise is answered.** See section 7. |
## 1. How Codex 0.163.0 exposes sub-agents
* **Feature flags (C, `codex features list` on the harness binary):** `multi_agent` is `stable` and **on by default**; `multi_agent_v2` is `stable` and off (the newer tool surface with path addressing, not used here). Because of that every request of this version already carried the `multi_agent_v1` tool namespace (10 KB) in the earlier runs; the model had simply never been asked to use it (`docs/experiments/multiplexing-feasibility.md`: no `multi_agent_v1` call in 750 recorded rounds).
* **Tools (M, tool list of the first request):** namespace `multi_agent_v1` with `spawn_agent` (`message` or `items`, `fork_context`, `model`, `reasoning_effort`), `wait_agent` (`targets` list of agent ids, `timeout_ms` default 30 s, min 10 s, max 1 h; returns when ANY of them reaches a final state), `send_input`, `resume_agent`, `close_agent`. A sub-agent has its own thread id; its tool list has 7 entries against the root's 8, because the whole `multi_agent_v1` namespace is missing (no spawning at depth 1, M).
* **When the model spawns (C, text of the `spawn_agent` description):** "Do not spawn sub-agents unless the user or applicable AGENTS.md/skill instructions explicitly ask for sub-agents, delegation, or parallel agent work." The prompt must ask. The public documentation says the same (spawn on request, "spawn two agents", "one agent per point", then wait and summarise).
* **Config (C, public docs and `--strict-config` on the binary):** `[agents]`: `enabled` (default true), `max_threads` (legacy alias of `max_concurrent_threads_per_session`; concurrent spawned threads), `max_depth` (default 1), `default_subagent_model`, `default_subagent_reasoning_effort`; `features.multi_agent`. This run set `features.multi_agent = true` and `agents.max_threads = 3` through `--config-extra`; `codex --strict-config exec` accepted both.
* **`codex exec` (non-interactive) works (M, step P0 and the run):** the root turn ends when the root model ends it; children run as threads of the same process, each with its own `thread-id` / `session-id` HTTP headers and `x-codex-turn-metadata` (`agent_name` is `/root` in every request of this version, so the thread id, not the name, tells the agents apart). Children's own tool calls are NOT in the root's `codex --json` event stream (38 `command_execution` events against 155 `exec_command` calls); the proxy log and the rollout files are the complete record.
* **Step P0 (CPU only, done):** `mock_subagent_server.py` scripts a root that spawns two children and waits. The real binary fanned out under `codex exec`, both children's requests overlapped for the whole 3-4 s the mock held them, and the spawn results carry `{"agent_id", "nickname"}`. This validated the config keys and the proxy chain before GPU time was spent.
## 2. The job
* Queue stub `codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482` (server `~/work/gpu-runs/holder2/jobs/`, inserted into `PRIORITY` directly behind the running CPU-kernel A/B job; backup `PRIORITY.bak-orchestrator-smoke`). Job script `scripts/e2e/codex/orchestrator/orchestrator_smoke_job.sh` (sha256 9a3590bb... pinned in the stub), derived from `cmp_codex_job_profile.sh`: release package, `leleka up --foreground --kar-fd`, shipped configuration, the cell runner `cell.py` of the Codex comparison (logging proxy, temperature 0, real Codex CLI 0.163.0 sha256 399ff69c..., task acceptance).
* **Provenance and configuration proof (M, first lines of `job-LEL.log`):** package `PROVENANCE.json` `git_commit` 83bdd85bb48226a41bcec6034d87e1ea6528b570 equals the tag; tarball sha256 3837a32b... equals the one recorded by the owner-default series; `SHA256SUMS` ok; the line `engine environment:` of `up-foreground.txt` is byte-identical to the owner-default series (`LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=no`, `PCIE_FRAC=0.65`, `SEED=off`, ...) and `leleka.json` has the same sha256 (the job exits 8 before any cell otherwise). Inputs (cell runner, tasks, references) are frozen read-only with `INPUTS.sha256`; the job refuses to start when one differs.
* **Task `nestng-crm-orch`** (built by `make_orchestrator_tasks.py` from the frozen `nestng-crm`; same seed, same acceptance script, so the specification cannot drift): the original prompt cut at its Backend and Frontend sections, inside an orchestrator frame: "You are the orchestrator of a small team of sub-agents ... in your very first response call the spawn_agent tool twice ... each message must contain the full specification of its part ... do not write the backend or the frontend yourself while the sub-agents work; use wait_agent until both have finished; then write README.md and verify the result yourself; do not spawn any other sub-agents."
* Cells in ONE stack start: warm-up `smoke-mini`, orchestrator cell (wall limit 1,500 s), and, because it fitted, the single-agent control (unchanged `nestng-crm`, wall limit 900 s). One repetition each, so everything below is n = 1.
* Recording: the logging proxy of `cell.py`, patched only to add UNIX milliseconds (`t_start_unix_ms`, `t_end_unix_ms`) to every `rounds.jsonl` line (request and response bytes unchanged), so requests can be joined with `requests.log` (queue, TTFT) and `engine-slice.log` (prefix switch, import ms, tier shares). The analysis is `analyze_orchestrator_run.py`.
* Run: 2026-11-13 00:20-00:49 UTC, RTX 5090 server, ready after 118 s, orchestrator cell 791 s, control 766 s. Data: `/data/leleka-e2e/prefill-latency/runs/codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482/` (`LEL/<cell>/proxy`, `LEL/stack/{requests.log,engine.log,api.log,log-offsets.txt}`, `analysis/{orch,control}.{md,json}`, `analysis/accept/`).
## 3. Timeline of the orchestrator cell (M)
| t (s) | Event |
|---:|---|
| 0.0 | Root request 1 (10.6k prompt tokens). |
| 8.9 | Root answers: one message and two `spawn_agent` calls in one response. Both workers start at once. |
| 8.9-29 | The three sessions interleave on the one engine: the root inspects the scaffold (6 requests), the workers start (backend and frontend each begin with a 7.7k / 7.6k-token prompt, below the 8,192-token cache block, so `cached = 0`). |
| 26-81 | The backend worker writes one large file in a single request (10,239 tokens, 54 s). The frontend worker's request 12 arrives behind it and waits **51 s** (first-come-first-served, no preemption). |
| 29-260 | Both workers alive: requests alternate between them, each takes 13 s instead of 6 s. |
| 260 | The frontend worker finishes (19 requests, "Build is green"); root `wait_agent` returns for it. |
| 260-602 | Only the backend worker (and the root's idle `wait_agent`) is active: no queue wait (0 ms), 6.1 s per request. This tail is the critical path. |
| 602-790 | Root closes both workers, writes README.md and verifies everything itself (34 requests in all), including an in-process supertest shim because the sandbox forbids sockets (the same constraint hits the control). |
The split was unbalanced (backend 602 s of its own session against frontend 260 s) and the root's final verification is serial; both limit what any scheduler could gain on this task.
Per agent (M): root 34 requests, 30,199 output tokens, 179 s engine time; backend worker 69 / 73,135 / 413 s; frontend worker 19 / 23,954 / 132 s. Engine time in total 724 s of the 790 s span (92 %); the control 664 s of 766 s (87 %).
## 4. Numbers against the single-agent control (same boot)
| | Orchestrator | Control (single agent) |
|---|---:|---:|
| Wall (s) | 791 | 766 |
| Model requests | 122 | 96 |
| Output tokens | 127,288 | 96,647 |
| Aggregate output tok/s over the span | 161 | 126 |
| Decode tok/s (median, requests with > 200 tokens) | 186 | 184 |
| Engine busy (prefill + decode ms) | 724 s (92 %) | 664 s (87 %) |
| Time with no request open | 63 s | 100 s |
| Time with 2 / 3 requests open | 232 s / 18 s | 0 / 0 |
| Queue wait p50 / p90 / max | 2 ms / 5.0 s / 51 s | 2 ms / 3 ms / 4 ms |
| TTFT p50 / p90 / max | 0.68 s / 6.3 s / 51.8 s | 0.57 s / 5.8 s / 8.5 s |
| Sessions switched at the prefix store | 48 of 122 | 2 of 96 |
| Import ms on a switch (median / max) | 29 / 48 | 2 / 2 |
| Cached share of prompt tokens | 98.1 % | 90.3 % |
| Acceptance strict / relaxed | 55/56 / 56/56 | 55/56 / 56/56 |
Reading: the aggregate tok/s (+28 %) is a fuller engine plus more work, not a shorter time to the result. The orchestrator did 32 % more generation than the single agent (three contexts to read, two worker summaries, a full re-verification) and finished in the same time because the engine, not the tool waits, was the limit. The cached-share difference comes from different trajectories (the workers' contexts stay shorter: at most 95k prompt tokens against 140k in the control); it is reported, not interpreted.
## 5. Aggregate against sequential execution (E)
Sequential execution of the same 122 requests (one agent after another, engine never shared) would cost the engine time (724 s) plus the tool gaps of a single session. The control shows 766 - 664 = 102 s of gaps for 96 requests = 1.06 s per request; for 122 requests that is 129 s. Sequential wall about 724 + 129 = **853 s** against 790 s measured: **1.08x**, the upper end of the 0.97-1.18x (central 1.03-1.08x) predicted in section B.6 of the 6g analysis. Against the single agent doing the whole task alone (766 s) there is no gain. n = 1 and a wall sd of 21-112 s on 430-650 s mean that an effect of this size is not resolvable by a three-repetition matrix.
## 6. Failures and oddities
* **Head-of-line blocking:** one 54-s generation (10k tokens in one tool call) held the other worker for 51 s. FIFO without preemption is the only queueing defect seen, and it is a latency, not a correctness, issue.
* First requests of each worker (prompt below 8,192 tokens) have `cached = 0`; the cache block grid is 8,192 (profile `rtx5090-32g`). Cost: two cold prefills of 7.6-7.7k tokens, 3-7 s.
* A child's tool list differs from the root's (no `multi_agent_v1` namespace), so the root and its children do not share the first prompt bytes (the children's first prompts are 7.6-7.7k tokens, below the 8,192 grid in any case).
* Codex printed `Model metadata for qwen-local not found` (harmless, same in all cells) and rejected one `rm -f /tmp/...` command by its own sandbox policy (once in each cell). Root commands: 38 of 38 exit 0; the workers' commands are not in the event stream; in their last requests 1 non-zero exit (a `git` call, 128). Control: 8 of 77 commands non-zero.
* One `generation failed: reasoning ended without </think>` was logged by the API during the warm-up cell `smoke-mini` (known pattern, the cell was accepted); none during the two task cells.
* The sandbox blocks sockets: neither the control nor the orchestrator could run `node dist/main.js` + curl; both verified with an in-process harness.
* Run output is 874 MB by `du` (the node_modules are hard links to the shared tree; the new bytes are small).
## 7. Recommendation for the big 6g benchmark
1. **The premise holds:** the model orchestrates correctly with Codex 0.163.0 and the gateway/engine path deals with the concurrency without a single protocol or tool-call failure; the cache switch costs 29 ms on average. So the "can it" question is closed, and the earlier fallback (N parallel `codex exec` sessions started by the harness) is not needed.
2. **No-go for the full matrix of B.4-B.7 (3-3.5 GPU-h, arms S1/S2/H2/O x 3 blocks).** The smoke already shows the thing the matrix would measure: with a strictly serial engine at 92 % duty the queue cannot give more than about 1.08x (E) and no gain over one agent; the resolution of n = 3 on this task (wall sd 21-112 s) cannot tell 1.08x from 1.0x. The money would buy the same conclusion with error bars.
3. **What would still be worth a GPU hour:** (a) a balanced split with long tool waits (four equal sub-tasks, builds and test suites in the workers) to see the gamma term of B.6 become large; (b) the real lever, simultaneous decode of two sessions (E 1.0-1.3x at N = 2 per `multiplexing-feasibility.md` 3.2), with this task as its workload; (c) a scheduling fix for the head-of-line case (a long generation delaying another session by 51 s), which affects TTFT p90, not throughput.
4. The harness for any later run exists: `orchestrator_smoke_job.sh` (change the cell list), `make_orchestrator_tasks.py`, `analyze_orchestrator_run.py` (agents, overlap histogram, queue, TTFT, switch cost, integrity check).
## 8. Files
* Added: `scripts/e2e/codex/orchestrator/{mock_subagent_server.py, make_orchestrator_tasks.py, setup_orchestrator_inputs.sh, orchestrator_smoke_job.sh, orchestrator_smoke_stub.sh, analyze_orchestrator_run.py}`, this page.
* Server (all under `/data/leleka-e2e/prefill-latency/`): `orchestrator-subagents-smoke/{tools,tasks,reference,INPUTS.sha256,p0}` (frozen inputs and the P0 capture), `runs/codex-orchestrator-subagents-smoke-crm-release-83bdd85bb482/`; the queue stub and the `PRIORITY` backup in `~/work/gpu-runs/holder2/jobs/`. The stack state, package and prefix directories of release 83bdd85bb482 under `codex-compare/ours-*-83bdd85bb482` were reused as the owner-default series left them (the job writes the stack's own logs there).
## Sources
* Repo: `docs/experiments/async-park-compression-and-orchestrator-bench.md` (B), `docs/experiments/multiplexing-feasibility.md`, `docs/e2e-run.md` 7, `scripts/e2e/codex/compare/cmp_codex_job.sh` and the server `cmp_codex_job_profile.sh`.
* Public (secondary for this exact version; the tool list, flags and gating text above were read from the 0.163.0 binary and its requests): [Codex subagents documentation](https://learn.chatgpt.com/docs/agent-configuration/subagents) (formerly developers.openai.com/codex/subagents), [Codex multi-agent notes](https://developers.openai.com/codex/multi-agent), third-party notes on `max_threads` / `max_depth` and `multi_agent_v2` at [codex.danielvaughan.com](https://codex.danielvaughan.com/2026/03/26/codex-cli-subagents-toml-parallelism/) and [morphllm.com/codex-multi-agent](https://www.morphllm.com/codex-multi-agent).
+2 -2
View File
@@ -32,10 +32,10 @@
| 6 | Decode: ядра mixer-половини (S10 батчований append K/V, GDN K7/K7a), accept на пристрої (0,32→0,08 мс), commit (fused) | speed | у роботі |
| 6b | Decode: вимір критичного шляху раунду (хост/тир: flag-waits, doorbell, прихід CPU-ноги у ранніх шарах), бо секційні дельти ядер до раунду не доходять (pb-vs-pg-rerun, 2026-11-12). Запис 2026-11-12 за словом оркестратора, щоб закрити залишок −11 % decode | speed | відкрито |
| 6c | Decode: хост між графами (4,3 мс, GPU стоїть 1,95 мс): PLE-staging, ланцюг драфту на пристрої, scan у граф, swap-чекання тиру (політика), commit | агент host-round | відкрито (запис 2026-11-12) |
| 6d | Decode: токенів на раунд (accept) і драфтер: порівняти з ванільою та з upstream DFlash2 per-device (Blackwell cc 12.0: conf 0,35→0,55, window 6→8), що дає tok/round | агент acceptance | відкрито (запис 2026-11-12) |
| 6d | Decode: токенів на раунд (accept) і драфтер: порівняти з ванільою та з upstream DFlash2 per-device (Blackwell cc 12.0: conf 0,35→0,55, window 6→8), що дає tok/round | агент acceptance | аналіз зроблено (`acceptance-knobs-5090.md`: accept у нас 3,19 проти 2,96 у vanilla, DFlash2-пер-девайс не стосується 5090 32 ГБ, 12-рядкове вікно ≤ +2 %); виміри ручок у черзі GPU |
| 6e | Decode: CPU-ядро експерта IQ3_S/IQ4_NL (було ≈3× повільніше за Original; фікс 0c48c823e у main, A/B на 243k іде), далі prefetch 2048 Б і multi512 | агент cpu-kernel | у роботі |
| 6f | Lossy tail skip (+10..12 %): гейт якості (CRM за строгим і м'яким acceptance, ttt, ріст раундів ≤ приросту швидкості) | агент tail-gate | гейт у черзі (запис 2026-11-12) |
| 6g | Конкурентні запити агентів (multiplexing сесій) і телеметрія: сукупна пропускна здатність при N одночасних сесіях Codex проти N послідовних; ідея власника 2026-11-12 («у Strata цього нема»). Спершу перевірка здійсненності й кошту (без GPU), потім вимір. Метрики: сукупний ток/с, ток/с на сесію, TTFT, VRAM/RAM. Це НЕ збільшує швидкість однієї сесії (метрики етапу 7), окрема вісь | агент multiplex-feasibility | відкрито (запис 2026-11-12) |
| 6g | Конкурентні запити агентів (multiplexing сесій) і телеметрія: сукупна пропускна здатність при N одночасних сесіях Codex проти N послідовних; ідея власника 2026-11-12 («у Strata цього нема»). Спершу перевірка здійсненності й кошту (без GPU), потім вимір. Метрики: сукупний ток/с, ток/с на сесію, TTFT, VRAM/RAM. Це НЕ збільшує швидкість однієї сесії (метрики етапу 7), окрема вісь | агент multiplex-feasibility | аналіз зроблено (`multiplexing-feasibility.md`: перемикання сесій 0,07–0,3 с, одночасний decode 1,0–1,3× при N=2 за моделлю, переписування життєвого циклу запиту). Додано 2026-11-12 за словом власника: (а) у режимі оркестратора Codex з сабагентами паралельні запити гарантовані, тому записаних сесій без перетинів замало, потрібен бенчмарк «Codex знає, що він оркестратор, працює кількома сабагентами»; (б) асинхронне стиснення запаркованих блоків сесій у хост-RAM (економія місця й часу перемикання; вимога точності префікс-кешу: лише lossless або вимір відхилення)). АНАЛІЗ 2026-11-12 (`async-park-compression-and-orchestrator-bench.md`): lossless-стиснення блоків E 1,06–1,29× (центр 1,17×), час перемикання не скорочує (копія це memcpy хоста 13–14 ГБ/с, не PCIe), +0–1 сесія RAM: спершу вимір T8, ймовірно NO-GO; бенчмарк оркестратора ≈3–3,5 GPU-год, очікуваний виграш черги 0,97–1,18× (центр 1,03–1,08×) |
| 7 | Груповий e2e: CRM×3 і ttt×3 проти бази | обидва | після етапів 2–6; 2026-11-12 перший валідний прогін на 02c784249a7e: кандидат quota=no+PCIe 0,65 CRM 179/505 с, ttt 180/156 с (дефолт власника від 2026-11-12) |
| 8 | Рішення власника: tail skip (+10…12 %, не пройшов гейт CRM) | власник | відкрито |
+12
View File
@@ -54,3 +54,15 @@ The pool always has 48 tasks (3 x 16 threads: 15 workers + host), whatever the e
- Linear, about 63 us per expert, intercept about 0: the pool adds nothing per window. `LELEKA_POOL_TASKS_PER_THREAD` 1 / 3 / 6 gives the same wall (HOT k=1 66.6 / 63.7 / 66.5): finer tasks do not help.
- Scaling in threads is perfect: thread time per expert is about 800 us at 4 (k=1: 199 us), 8 (103 us) and 16 threads (64 us). Not SMT, not the memory bus. HOT against COLD costs +14..35 us per window (mostly the down phase 13.7 -> 21 us).
- The Original's kernel, one thread, no pool (`kab time`): 377 us RESIDENT / 395 us STREAMED (+5 %) for case 21-20-r1, 461 / 463 us for r3. Our pool path spends about 800 us of thread time per expert: about 2.1 x. The 2026-10-28 alternation record of case 18-20-r1 (IQ3_XXS) shows the same ratio (C++ 214 us, Rust twin 467 us, 60 runs each). The twin `kernel_ab time` runs through DirectCpuPool(1) with a spinning worker on the same pinned CPU, so it is not an equivalent harness; a clean one-thread number (spin off) is queued (`cpu-expert-kernel-one-thread-without-spin-and-window-amortisation-iq3s`). parity-audit-5090.md row 9 says +6 % per CPU entry (job 980, 37 vs 35 us), which contradicts 63 us per expert here; that run most likely used larger groups.
## Follow-up (2026-11-13): new CPU expert kernels in the real pool, base against new
Run `cpu-expert-kernel-register-indices-pool-thread-trace-base-vs-new` (blocks PTB.1, PTB.2 = release c1f15db2fa99 without the kernel commit `0c48c823e`, PTK.1, PTK.2 = release bcbfa2c99422 with it; owner default profile, replay VANL/nestng-crm-r2, 30 requests, `LELEKA_POOL_TIMING=layers`). The blocks cover different expert counts per window (placement changes between boots), so the table is by T and number of experts in the window (`pool_layer_report.py --by-experts`; p50, base = PTB.1/PTB.2, new = PTK.1/PTK.2, T = 2..4 pooled by eye, the columns agree within 1 us).
| experts in window | group wall p50 / p75 / p90 base (us) | new | m5 gate/up task p50 base -> new | m6 down task p50 |
|---|---|---|---|---|
| 1 | 82 / 89 / 97 (PTB.2: 88 / 98 / 104) | 70 / 86 / 95 | 15.2-15.7 -> 10.6-11.1 us | 5.2-5.4 -> 5.0-5.3 |
| 2 | 160 / 170 / 186 (PTB.2: 168 / 185 / 195) | 138-143 / 159-168 / 176-185 | 30.5-31.3 -> 24-25 | 11.0-11.5 -> 11.1-11.3 |
| 3 | 241 / 255 / 274 | 218-227 / 239-248 / 258-278 | 44.5-46 -> 36-39 | 18-22 -> 21-23 |
Reading: the gate/up task time fell by 30 % and the median window by 12-20 us (about 15 %), the down task did not change (the IQ4_NL accumulator change is on the single-row path; the pool decodes 2..5 rows, `multi512`). The tail did not follow: p75 -3..-9 us, p90 -2..-9 us. The earlier note that the tail comes from the number of CPU experts and from memory (COLD against HOT +25-80 us in the kernel bench) stands; the next steps are the 2048 B prefetch ahead of the Original and the multi-row down path. Group A/B at 243k: decode -0.34 % (CI -3.33..+2.65), A/A twin -0.43 % (`docs/experiments/step-ledger.md`).
+2
View File
@@ -87,6 +87,8 @@ Round-level totals first (they are the sum of the steps below).
**Critical path step A, first launch failed (2026-11-12).** `decode-critical-path-cupti-windows-67k-default-vs-quota-no-pcie065-and-twin`: all six sessions NOT READY in 3 s, no engine started: release 02c784249a7e validates profile `engine_env` keys against `ENGINE_ENV_PREFIXES` (`profile_limits.rs`) and `spd_arm_guard.py make` wrote `LELEKA_SPEC_STATS` into the arm profile. Fixed in `spd_arm_guard.py` (only the allowed prefixes go into the profile, the rest stays in the shell env); rerun stub `…-twin-rerun`, output `/data/leleka-e2e/spd-gap/runs/decode-critical-path-cupti-windows-67k-default-vs-quota-no-pcie065-and-twin-rerun`. The pool-layer job `decode-pool-layer-trace-67k-default-placement-release-0ac612d2df74` (`LELEKA_POOL_TIMING`) had the same bug in its tool copy and now uses the fixed guard.
**CPU expert kernels IQ3_S / IQ4_NL (commit `0c48c823e`, 2026-11-12/13, stage 6b step 3): identity bitwise, decode neutral at 243k, pool window median faster, tail not.** Base = main with the kernel commit reverted (release `c1f15db2fa99`, branch `claude/kernel-iq3s-register-indices-base`), new = main (release `bcbfa2c99422`); both from one tree (the group A/B driver and the identity script are the only other changes, commit `bcbfa2c99`), owner default profile (quota=no + PCIe 0.65, 15 CPU workers). Inputs frozen in `/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/` (`MANIFEST.sha256`: engine test binaries `dt/rt-base` f87edd9c, `dt/rt-new` da4f0b1e, both tarballs, tools); stubs `cpu-expert-kernel-register-indices-*` in `scripts/e2e/codex/prefill/kernel/`. (1) Identity `runs/cpu-expert-kernel-register-indices-identity-draftround` (teacher forced, night5-long-256k, 240 tokens, base and new at 1 and at 15 CPU workers, A/A pair inside every process): 2057 of 2057 top-16 logprob rows identical, 0 argmax flips, 1036 of 1036 draft trace lines identical, A/A floor 0, `q_tail_gate` PASS in all four processes. (2) Group A/B `runs/cpu-expert-kernel-register-indices-vs-base-243k-group-ab-5-pairs` (the 243k Codex session, 39 requests, 5 pairs + 3 A/A twins, arm guard and binary digest ok in 13 of 13 blocks): decode K-B -0.64 tok/s (190.42 -> 189.77, -0.34 %, 95 % CI -3.33..+2.65), ms/round -0.03 (-0.20 %, CI -4.31..+3.91), tokens/round -0.02 (-0.58 %); A/A twin BT-B -0.83 tok/s (-0.43 %, CI -4.30..+3.43). Verdict by the owner rule (identity bitwise AND decode not worse than -0.5 %, or the A/A floor if larger; the floor 0.43 % is below 0.5 %): PASS, kept as the default; there is NO measurable decode gain at this noise (CI +-3 %). (3) Pool thread trace `runs/cpu-expert-kernel-register-indices-pool-thread-trace-base-vs-new` (replay nestng-crm-r2, PTB base against PTK new; by expert count and T = 2..4, `pool_layer_report.py --by-experts`): gate/up task p50 15.2 -> 10.7 us (-30 %), down task 5.2 -> 5.2 us (unchanged: the IQ4_NL change is the single-row path, the pool decodes 2..5 rows); window of 1 expert p50/p75/p90 82/89/97 -> 70/86/95 us, of 2 experts 160/170/186 -> 138-143/160-168/178-185 us, of 3 experts p50 241 -> 218-227 us. The median of a window fell by 12-20 us, the p75/p90 tail by only 2-9 us: the tail (the part a layer waits for) is not compute. Open (separate steps): prefetch 2048 B ahead like the Original (COLD-HOT +25-80 us), the multi-row down path (`multi512`: 662 us against the Original's 454 us in the kernel bench). (4) Group A/B 67k `runs/cpu-expert-kernel-register-indices-vs-base-67k-group-ab-5-pairs` (replay VANL/nestng-crm-r2, 30 requests, 5 pairs + 3 A/A twins, arm guard and binary digest ok in 13 of 13 blocks): decode K-B +2.34 tok/s (204.11 -> 206.45, +1.14 %, 95 % CI -0.22..+2.51), ms/round -0.12 (-0.69 %, CI -6.38..+5.01), tokens/round +0.02 (+0.44 %, CI -6.27..+7.15), end-to-end +0.17 %; A/A twin BT-B -1.63 tok/s (-0.80 %, CI -4.41..+2.81), so the A/A floor (0.8 %) is as large as the gain: PASS by the owner rule (not worse than -0.5 %), a gain of about +1 % that the twin does not exclude as noise. Both group A/Bs: no loss, 243k neutral, 67k +1.1 %.
Structure first, then the layer steps in graph order: embed (R7), mixer half (V3 and the kernels in it), FFN half (V2/V4 and the kernels in it), tail (R8).
| id | step | LEL | VANL | difference | source | owner | status |
@@ -0,0 +1,212 @@
#!/usr/bin/env python3
"""Analyse one orchestrator sub-agent cell of the Codex smoke job (TEST TOOLING, stdlib only, read-only on the run).
analyze_orchestrator_run.py RUN_DIR/LEL CELL_NAME [--json OUT.json]
Reads <RUN>/<CELL>/{cell.json, codex-events.jsonl, engine-slice.log, proxy/rounds.jsonl, proxy/rounds/*.resp.sse.gz} and
<RUN>/stack/{requests.log, api.log, log-offsets.txt}. Prints markdown: the cell outcome, the agents and their request counts, one table row per model
request (gateway view from the proxy, queue wait and TTFT from the API log, cached tokens, prefix switch and import cost from the engine log), the
histogram of concurrently open requests, the tool-call integrity check and the Codex command failures.
"""
import argparse
import collections
import gzip
import json
import os
import re
from datetime import datetime, timezone
def jsonl(path):
if not os.path.exists(path):
return []
out = []
for line in open(path, encoding="utf-8", errors="replace"):
try:
out.append(json.loads(line))
except ValueError:
continue
return out
def utc_ms(text):
return int(datetime.strptime(text, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc).timestamp() * 1000)
def load_rounds(cell_dir):
rounds = [r for r in jsonl(os.path.join(cell_dir, "proxy", "rounds.jsonl")) if r.get("round")]
return sorted(rounds, key=lambda r: r["t_start_unix_ms"])
def sse_items(path):
"""The output items (output_item.done) of one stored response, plus the terminal event type."""
if not os.path.exists(path):
return [], None
text = gzip.open(path, "rb").read().decode("utf-8", errors="replace")
items, terminal = [], None
for line in text.splitlines():
if not line.startswith("data:"):
continue
try:
d = json.loads(line[5:].strip())
except ValueError:
continue
if d.get("type") == "response.output_item.done":
items.append(d.get("item") or {})
elif d.get("type") in ("response.completed", "response.incomplete", "response.failed"):
terminal = d["type"]
return items, terminal
def declared_tools(cell_dir):
"""name -> parameter schema of every tool of the first request (namespace tools flattened as namespace.name)."""
path = os.path.join(cell_dir, "proxy", "rounds", "%04d.req.json.gz" % 1)
tools = {}
for t in json.loads(gzip.open(path, "rb").read()).get("tools", []):
if t.get("type") == "namespace":
for x in t.get("tools", []):
tools["%s.%s" % (t["name"], x["name"])] = x.get("parameters") or {}
elif t.get("name"):
tools[t["name"]] = t.get("parameters") or {}
return tools
def check_call(item, tools):
"""-> list of problems of one function_call item (unknown tool, arguments not JSON, missing required, wrong type)."""
name = ("%s.%s" % (item["namespace"], item["name"])) if item.get("namespace") else item.get("name")
if name not in tools:
return ["unknown tool %s" % name]
try:
args = json.loads(item.get("arguments") or "")
except ValueError:
return ["%s: arguments are not JSON" % name]
if not isinstance(args, dict):
return ["%s: arguments are not an object" % name]
schema = tools[name]
bad = ["%s: missing %s" % (name, k) for k in schema.get("required", []) if k not in args]
types = {"string": str, "number": (int, float), "boolean": bool, "array": list, "object": dict}
for k, v in args.items():
want = (schema.get("properties", {}).get(k) or {}).get("type")
if want in types and not isinstance(v, types[want]):
bad.append("%s: %s is not a %s" % (name, k, want))
return bad
def integrity(cell_dir, rounds):
tools = declared_tools(cell_dir)
calls, problems, terminals = collections.Counter(), [], collections.Counter()
for r in rounds:
items, terminal = sse_items(os.path.join(cell_dir, "proxy", "rounds", "%04d.resp.sse.gz" % r["seq"]))
terminals[terminal or "none"] += 1
for it in items:
if it.get("type") == "function_call":
calls[it.get("name")] += 1
problems += ["round %d: %s" % (r["round"], p) for p in check_call(it, tools)]
return {"calls": dict(calls), "problems": problems, "terminals": dict(terminals)}
def roles(rounds, events):
"""thread id -> 'root' or 'child N' (children in the order Codex reported them spawned)."""
root = rounds[0]["req_headers"].get("thread-id") if rounds else None
out = {root: "root"}
for e in events:
it = e.get("item") or {}
if it.get("type") == "collab_tool_call" and it.get("tool") == "spawn_agent" and e.get("type") == "item.completed":
for tid in it.get("receiver_thread_ids") or []:
out.setdefault(tid, "child %d" % len(out))
return out
def api_requests(stack_dir, task):
"""requests.log lines written during the cell (byte offsets recorded by the job)."""
marks = [l.split() for l in open(os.path.join(stack_dir, "log-offsets.txt")) if l.startswith(task + " ")]
start, end = [int(m[1]) for m in marks if m[-1] == "start"][-1], [int(m[1]) for m in marks if m[-1] == "end"][-1]
data = open(os.path.join(stack_dir, "requests.log"), "rb").read()[start:end].decode("utf-8", errors="replace")
return [d for d in (json.loads(l) for l in data.splitlines() if l.startswith("{")) if d.get("ev") == "request"]
def engine_requests(cell_dir):
"""Engine log slice -> {rid: {prefix fields, engine JSON}} (the 'prefix request' line precedes the JSON line of its request)."""
out, pending = {}, {}
for line in open(os.path.join(cell_dir, "engine-slice.log"), encoding="utf-8", errors="replace"):
m = re.match(r"leleka-serve prefix request: n=(\d+) hit=(\w+) resume=(\d+) switched=(\w+) .*?import_ms=([\d.]+)", line)
if m:
pending = {"n": int(m[1]), "hit": m[2], "resume": int(m[3]), "switched": m[4] == "true", "import_ms": float(m[5])}
elif line.startswith("{") and '"ev":"request"' in line:
d = json.loads(line)
out[d["rid"]] = {**pending, **d}
pending = {}
return out
def join_requests(rounds, api, engine):
"""Attach the API log record (by token counts and nearest end time) and the engine record (by rid) to every proxy round."""
free = list(api)
for r in rounds:
resp = r.get("resp") or {}
key = (resp.get("input_tokens"), resp.get("output_tokens"))
cands = [a for a in free if (a.get("ptok"), a.get("otok")) == key]
a = min(cands, key=lambda x: abs(utc_ms(x["ts"]) - r["t_end_unix_ms"]), default=None)
if a:
free.remove(a)
r["api"], r["eng"] = a, (engine.get(a["rid"]) if a else None)
return rounds
def concurrency(rounds):
"""Seconds spent with k requests open at the proxy (k = 0 is time between requests inside the span)."""
marks = sorted([(r["t_start_unix_ms"], 1) for r in rounds] + [(r["t_end_unix_ms"], -1) for r in rounds])
hist, open_n, last = collections.Counter(), 0, marks[0][0]
for t, d in marks:
hist[open_n] += (t - last) / 1000.0
open_n, last = open_n + d, t
return dict(sorted(hist.items()))
def command_failures(events):
done = [(e.get("item") or {}) for e in events if e.get("type") == "item.completed"]
cmds = [i for i in done if i.get("type") == "command_execution"]
return len(cmds), [i for i in cmds if i.get("exit_code") not in (0, None)]
def row(r, t0, role):
a, e = r.get("api") or {}, r.get("eng") or {}
return "| %d | %s | %.1f | %.1f | %.1f | %s | %s | %s | %s | %s | %s | %s |" % (
r["round"], role, (r["t_start_unix_ms"] - t0) / 1000, (r["t_end_unix_ms"] - t0) / 1000, (r["t_end_unix_ms"] - r["t_start_unix_ms"]) / 1000,
a.get("q_ms", "?"), a.get("ttft_ms", "?"), (r.get("resp") or {}).get("input_tokens"), e.get("ctok", "?"), (r.get("resp") or {}).get("output_tokens"),
"%s/%s" % (e.get("switched", "?"), e.get("import_ms", "?")), ",".join(i.get("name") or i["type"] for i in (r.get("resp") or {}).get("items", [])))
def render(cell_dir, rounds, events, names, integ):
cj = json.load(open(os.path.join(cell_dir, "cell.json")))
t0 = rounds[0]["t_start_unix_ms"]
out = ["cell %s: wall %.1f s, termination %s, accepted %s, codex rc %s" % (cj["task"], cj["wall_s"], cj["termination"], cj["accepted"], cj["codex_rc"]), ""]
per = collections.Counter(names.get(r["req_headers"].get("thread-id"), "?") for r in rounds)
out += ["requests per agent: %s" % dict(per), "tool calls: %s" % integ["calls"], "response terminals: %s" % integ["terminals"],
"tool-call problems: %s" % (integ["problems"] or "none"), "", "concurrently open requests (seconds): %s" % {k: round(v, 1) for k, v in concurrency(rounds).items()}, ""]
n_cmd, bad = command_failures(events)
out += ["commands run %d, non-zero exit %d" % (n_cmd, len(bad)), ""]
out += ["| # | agent | start s | end s | dur s | queue ms | ttft ms | prompt tok | cached | out tok | switched/import ms | output |", "|---|---|---|---|---|---|---|---|---|---|---|---|"]
out += [row(r, t0, names.get(r["req_headers"].get("thread-id"), "?")) for r in rounds]
return "\n".join(out)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("variant_dir")
ap.add_argument("cell")
ap.add_argument("--json")
a = ap.parse_args()
cell_dir = os.path.join(a.variant_dir, a.cell)
task = json.load(open(os.path.join(cell_dir, "cell.json")))["task"]
rounds, events = load_rounds(cell_dir), jsonl(os.path.join(cell_dir, "codex-events.jsonl"))
api = api_requests(os.path.join(a.variant_dir, "stack"), task)
join_requests(rounds, api, engine_requests(cell_dir))
integ = integrity(cell_dir, rounds)
print(render(cell_dir, rounds, events, roles(rounds, events), integ))
if a.json:
json.dump({"rounds": rounds, "integrity": integ, "concurrency": concurrency(rounds)}, open(a.json, "w"), indent=1)
if __name__ == "__main__":
main()
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""Build the task root of the orchestrator sub-agent smoke job (TEST TOOLING, stdlib only).
make_orchestrator_tasks.py SOURCE_TASKS_ROOT OUT_TASKS_ROOT
Copies smoke-mini (warm-up cell) and nestng-crm (single-agent control) from the frozen task root of the Codex comparison, and adds
`nestng-crm-orch`: the same seed, the same acceptance script, and a prompt that is the nestng-crm specification cut at the Backend and
Frontend sections (word for word) inside an orchestrator frame that tells the model to spawn two sub-agents. A fresh MANIFEST.sha256 is
written for the three tasks. The orchestrator prompt is derived from the control prompt, so the specification cannot drift.
"""
import os
import shutil
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "delta"))
import taskfile # noqa: E402
ORCH_ID = "nestng-crm-orch"
FRAME_HEAD = (
"You are the orchestrator of a small team of sub-agents. Your job is to get the work below done by delegating it to "
"sub-agents and then integrating their results.\n\n"
)
PLAN = (
"Plan for the team (follow it exactly):\n"
"1. In your very first response call the spawn_agent tool twice, so that both sub-agents start at the same time: one backend "
"worker for `backend/` and one frontend worker for `frontend/`. A sub-agent cannot see this conversation, so each message must "
"contain the full specification of its part (copy the Backend or the Frontend section below word for word), tell it to work "
"only inside its own directory, to run the commands that verify its part, and to reply with a short summary and the list of "
"files it changed.\n"
"2. Do not write the backend or the frontend yourself while the sub-agents work. Use wait_agent until both sub-agents have "
"finished.\n"
"3. Then write the short top-level README.md that says how to run everything and verify the result yourself: run `npm test`, "
"`npm run test:e2e` and `npm run build` in `backend/`, `npm run build` in `frontend/`, start the server and exercise it with "
"curl. If something fails, fix it yourself with small edits. Do not spawn any other sub-agents.\n\n"
)
CLOSING = "When all of this works, reply with a short summary of what was built and how it was verified."
def split_control_prompt(prompt):
"""-> (intro, backend_section, frontend_section) of the nestng-crm prompt; fails loudly when the layout changes."""
i_back, i_front, i_work = prompt.index("\nBackend ("), prompt.index("\nFrontend ("), prompt.index("\nWork step by step")
if not 0 < i_back < i_front < i_work:
raise ValueError("unexpected section order in the nestng-crm prompt")
return prompt[:i_back].strip("\n"), prompt[i_back:i_front].strip("\n"), prompt[i_front:i_work].strip("\n")
def orchestrator_prompt(control_prompt):
intro, backend, frontend = split_control_prompt(control_prompt)
return FRAME_HEAD + intro + "\n\n" + PLAN + backend + "\n\n" + frontend + "\n\n" + CLOSING
def orchestrator_task_md(control_md, control_prompt):
head, rest = control_md.split("## Prompt", 1)
head = head.replace("id: nestng-crm\n", "id: %s\n" % ORCH_ID).replace("title: Simple NestJS + Angular CRM", "title: Simple NestJS + Angular CRM, orchestrator with two sub-agents")
ext = rest.split("<!-- PROMPT END -->", 1)[1]
note = "\nOrchestrator variant of nestng-crm (docs/experiments/orchestrator-subagents-smoke.md): same seed and acceptance, prompt built by make_orchestrator_tasks.py.\n\n"
return head.rstrip("\n") + "\n" + note + "## Prompt\n<!-- PROMPT BEGIN -->\n" + orchestrator_prompt(control_prompt) + "\n<!-- PROMPT END -->" + ext
def copy_task(src_root, out_root, task_id, as_id=None):
"""Copy a task directory (no reference solution, no node_modules; the source files are read-only, the copies are not)."""
dst = os.path.join(out_root, as_id or task_id)
shutil.copytree(os.path.join(src_root, task_id), dst, ignore=shutil.ignore_patterns("reference", "node_modules"), copy_function=shutil.copyfile)
return dst
def write_manifest(out_root):
lines = taskfile.manifest_lines(out_root)
with open(os.path.join(out_root, "MANIFEST.sha256"), "w", encoding="utf-8", newline="\n") as f:
f.write("\n".join(lines) + "\n")
return lines
def build(src_root, out_root):
os.makedirs(out_root)
copy_task(src_root, out_root, "smoke-mini")
copy_task(src_root, out_root, "nestng-crm")
orch_dir = copy_task(src_root, out_root, "nestng-crm", ORCH_ID)
control_md = open(os.path.join(src_root, "nestng-crm", "task.md"), encoding="utf-8", newline="").read()
prompt = taskfile.read_task(src_root, "nestng-crm")["prompt"]
with open(os.path.join(orch_dir, "task.md"), "w", encoding="utf-8", newline="\n") as f:
f.write(orchestrator_task_md(control_md, prompt))
return write_manifest(out_root)
if __name__ == "__main__":
if len(sys.argv) != 3:
print(__doc__)
sys.exit(2)
out = build(sys.argv[1], sys.argv[2])
print("%d manifest lines" % len(out))
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""A throw-away /v1/responses server that makes the Codex CLI spawn sub-agents (TEST TOOLING, no model, no GPU, stdlib only).
mock_subagent_server.py PORT CAPTURE.jsonl [N_CHILDREN] [CHILD_DELAY_S]
Step P0 of docs/experiments/orchestrator-subagents-smoke.md. The root thread (the thread of the first request) is scripted: its first request is
answered with N_CHILDREN `multi_agent_v1.spawn_agent` calls in one response, the next request with a `wait_agent` call on the agent ids that
the spawn outputs returned, the last one with a final text. Every other thread (a sub-agent) answers with a one-line message after
CHILD_DELAY_S seconds. CAPTURE.jsonl gets one line per request: arrival and finish time, thread id, agent name, input and tool counts, the
tool names called in the answer. It shows whether the CLI fans out under `codex exec`, how many requests overlap and what the children send.
"""
import json
import sys
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
PORT, CAPTURE = int(sys.argv[1]), sys.argv[2]
N_CHILDREN = int(sys.argv[3]) if len(sys.argv) > 3 else 2
CHILD_DELAY_S = float(sys.argv[4]) if len(sys.argv) > 4 else 3.0
LOCK = threading.Lock()
T0 = time.time()
ROOT_REQUESTS = {"n": 0, "thread": None}
def is_root_thread(thread_id):
"""The thread of the first request is the root; the sub-agents send their own thread ids (their agent_name header says /root too)."""
with LOCK:
if ROOT_REQUESTS["thread"] is None:
ROOT_REQUESTS["thread"] = thread_id
return ROOT_REQUESTS["thread"] == thread_id
def spawned_ids(body):
"""Agent ids in the function_call_output items of the request (the spawn_agent results)."""
ids = []
for item in body.get("input") or []:
if item.get("type") == "function_call_output":
out = item.get("output")
text = out if isinstance(out, str) else json.dumps(out)
try:
ids.append(json.loads(text).get("agent_id"))
except (ValueError, AttributeError):
pass
return [i for i in ids if i]
def call_item(n, name, args):
return {"id": "fc_%d" % n, "type": "function_call", "call_id": "call_%d" % n, "name": name, "namespace": "multi_agent_v1",
"arguments": json.dumps(args), "status": "completed"}
def text_item(text):
return {"id": "msg_1", "type": "message", "role": "assistant", "status": "completed",
"content": [{"type": "output_text", "text": text, "annotations": []}]}
def root_answer(body):
"""The scripted root: spawn, then wait, then finish."""
with LOCK:
ROOT_REQUESTS["n"] += 1
k = ROOT_REQUESTS["n"]
if k == 1:
return [call_item(i, "spawn_agent", {"message": "mock task %d: reply with one word" % i}) for i in range(N_CHILDREN)]
ids = spawned_ids(body)
waited = any(i.get("type") == "function_call" and i.get("name") == "wait_agent" for i in body.get("input") or [])
if ids and not waited:
return [call_item(10, "wait_agent", {"targets": ids, "timeout_ms": 60000})]
return [text_item("mock root finished")]
def sse(output):
resp = {"id": "resp_mock", "object": "response", "status": "completed", "model": "mock", "output": output,
"usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 2,
"output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 12}}
events = [("response.created", {"response": {**resp, "status": "in_progress", "output": []}})]
for i, item in enumerate(output):
events.append(("response.output_item.done", {"output_index": i, "item": item}))
events.append(("response.completed", {"response": resp}))
return b"".join(("event: %s\ndata: %s\n\n" % (n, json.dumps({"type": n, "sequence_number": i, **d}))).encode()
for i, (n, d) in enumerate(events))
class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *args):
pass
def do_POST(self):
t_in = time.time() - T0
body = json.loads(self.rfile.read(int(self.headers.get("content-length", 0))))
agent = "root" if is_root_thread(self.headers.get("thread-id")) else "child"
if agent == "root":
output = root_answer(body)
else:
time.sleep(CHILD_DELAY_S)
output = [text_item("mock child done")]
data = sse(output)
self.send_response(200)
self.send_header("content-type", "text/event-stream")
self.send_header("content-length", str(len(data)))
self.end_headers()
self.wfile.write(data)
self.record(body, agent, t_in, output)
def record(self, body, agent, t_in, output):
rec = {"t_in_s": round(t_in, 3), "t_out_s": round(time.time() - T0, 3), "agent": agent, "thread": self.headers.get("thread-id"),
"n_input": len(body.get("input") or []), "n_tools": len(body.get("tools") or []),
"prefix_sha": hash(json.dumps(body.get("tools"), sort_keys=True)),
"called": [i.get("name") for i in output if i.get("type") == "function_call"],
"tool_outputs": [str(i.get("output"))[:300] for i in body.get("input") or [] if i.get("type") == "function_call_output"]}
with LOCK, open(CAPTURE, "a") as f:
f.write(json.dumps(rec) + "\n")
ThreadingHTTPServer(("127.0.0.1", PORT), Handler).serve_forever()
@@ -0,0 +1,126 @@
#!/usr/bin/env bash
# Orchestrator sub-agent smoke job (docs/experiments/orchestrator-subagents-smoke.md). Test tooling, never in serving. Runs ON the 5090 server inside a holder
# job (inherits the sealed KAR memfd), derived from cmp_codex_job_profile.sh (arm "ours" only): the release package, `leleka up --foreground --kar-fd`,
# shipped configuration, the cell runner of the Codex comparison (logging proxy, temperature 0, real Codex CLI 0.163.0, task acceptance).
#
# ONE BLOCK = one stack start, then three cells: the warm-up (smoke-mini), the ORCHESTRATOR cell (nestng-crm-orch: Codex told to spawn a backend and a frontend
# sub-agent, `features.multi_agent = true`, `agents.max_threads = 3`) and, when CMP_CONTROL=1, the single-agent CONTROL (nestng-crm, the unchanged task).
# Guards before any cell: input digests (INPUTS.sha256), task manifest, Codex binary digest, package PROVENANCE git_commit == CMP_OURS_TAG, SHA256SUMS of the
# package, and after the start the engine environment line and the run configuration (leleka.json) against the references of the owner-default series.
set -uo pipefail
TAG=${CMP_OURS_TAG:-83bdd85bb482}
TARBALL=${CMP_TARBALL:-/data/leleka-e2e/prefill-latency/release-s22/leleka-0.1.0-83bdd85bb482-linux-x86_64.tar.xz}
ORCH=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke
RUN=${CMP_RUN:-/data/leleka-e2e/prefill-latency/runs/codex-orchestrator-subagents-smoke-crm-release-$TAG}
CMP=/data/leleka-e2e/codex-compare
CODEX=/home/para/work/codex-e2e/bin/codex
CODEX_SHA=399ff69c431c066e40de318fba45c2b07f45a76b19939d247ee4828fc70c4215
LOCK=/data/leleka-e2e/gpu.lock
G=$HOME/work/gpu-runs
CUBLAS=$HOME/cuda-toolkits/cublas-12.9.1.4/lib
WALL_ORCH=${CMP_WALL_ORCH:-1500}; WALL_CONTROL=${CMP_WALL_CONTROL:-900}; ROUNDS=${CMP_ROUNDS:-400}
NODE_BIN=$(ls -d "$CMP"/toolchain/node-v*-linux-x64/bin 2>/dev/null | tail -1)
NM=$CMP/nm
VAR=LEL
mkdir -p "$RUN" "$RUN/$VAR"
exec > >(tee -a "$RUN/job-$VAR.log") 2>&1
log() { echo "[orch $(date -u +%T)] $*"; }
note() { echo "[$(date -u +%FT%TZ)] [DEV orchestrator-smoke] $*" >>/data/leleka-e2e/decode/notes.md; }
die() { echo "REFUSED: $1"; exit "${2:-3}"; }
# ---- guards (before the GPU lock) -------------------------------------------------------------------------------------------------------------
( cd "$CMP" && sha256sum --quiet -c INSTALL.sha256 ) || die "installed comparison tools differ from INSTALL.sha256"
( cd "$ORCH" && sha256sum --quiet -c INPUTS.sha256 ) || die "orchestrator inputs differ from INPUTS.sha256"
python3 -I "$ORCH/tools/delta/taskfile.py" check "$ORCH/tasks" >"$RUN/tasks-check.txt" 2>&1 || die "task files differ from their manifest"
[ -x "$CODEX" ] && [ "$(sha256sum "$CODEX" | cut -c1-64)" = "$CODEX_SHA" ] || die "codex binary missing or not the pinned 0.163.0 digest"
[ -n "$NODE_BIN" ] && [ -x "$NODE_BIN/node" ] && [ -f "$CMP/toolchain/NESTNG_OK" ] || die "node toolchain or NESTNG_OK missing"
[ -d "$NM/backend/node_modules" ] && [ -d "$NM/frontend/node_modules" ] || die "shared node_modules missing"
FD=${LELEKA_STRA169_KAR_FD:-}
readlink "/proc/self/fd/$FD" 2>/dev/null | grep -q '^/memfd:' || die "needs the holder's sealed memfd"
[ -d "$G/MODEL.lock" ] || die "MODEL.lock is not held"
got=0
for _ in $(seq 1 4320); do
if mkdir "$LOCK" 2>/dev/null; then echo "codex-orchestrator-smoke $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi
sleep 5
done
[ $got = 1 ] || die "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"
SUP_PID=; MON_PID=
stop_stack() {
if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi
SUP_PID=
}
cleanup() {
stop_stack
[ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null
pkill -KILL -f "$CMP/ours-prefix-$TAG/bin/" 2>/dev/null
sleep 3
rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null
note "orchestrator smoke block ended: $RUN"
}
trap cleanup EXIT
note "orchestrator smoke started: $RUN release=$TAG wall_orch=$WALL_ORCH control=${CMP_CONTROL:-1}; holds gpu.lock"
if [ -n "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ]; then die "something uses the GPU"; fi
if pgrep -u "$USER" -x 'leleka-inference|strata-next|leleka-daemon' >/dev/null; then die "a stack process exists"; fi
for p in 18766 18080 8081 8090; do ss -ltn "sport = :$p" 2>/dev/null | grep -q LISTEN && die "port $p in use"; done
export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
export PATH=$NODE_BIN:$PATH NG_CLI_ANALYTICS=false npm_config_cache=/tmp/cmp-npm-cache npm_config_update_notifier=false npm_config_fund=false npm_config_audit=false CI=1
{ date -u +%FT%TZ; uname -r; nvidia-smi --query-gpu=name,driver_version,power.limit --format=csv,noheader; free -g | sed -n 2p; uptime; $CODEX --version; node --version; sha256sum "$CODEX"; } | tee "$RUN/$VAR/host.txt"
STK=$RUN/$VAR/stack; mkdir -p "$STK"
nvidia-smi --query-gpu=timestamp,temperature.gpu,clocks.sm,clocks.mem,power.draw,utilization.gpu --format=csv -l 10 >"$STK/mon.csv" 2>/dev/null & MON_PID=$!
# ---- the release package (prepared once into $CMP/ours-*-$TAG by the owner-default series, reused) --------------------------------------------
P=$CMP/ours-pkg-$TAG; AS=$CMP/ours-assets; ST=$CMP/ours-state-$TAG; PFX=$CMP/ours-prefix-$TAG; BIN=$P/bin
PROV=/data/leleka-e2e/prefill-latency/tools/prov_commit.py
[ -x "$P/bin/leleka" ] || { mkdir -p "$P" && tar -xJf "$TARBALL" -C "$P" --strip-components=1 || die "unpack failed" 5; }
python3 -I "$PROV" "$P/PROVENANCE.json" "$TAG" >/dev/null || { head -20 "$P/PROVENANCE.json"; die "package PROVENANCE git_commit does not match $TAG" 5; }
log "package provenance: commit $(python3 -I $PROV $P/PROVENANCE.json), tarball sha256 $(sha256sum $TARBALL | cut -c1-16)"
( cd "$P" && sha256sum --quiet -c SHA256SUMS && echo "SHA256SUMS ok" ) || die "package SHA256SUMS" 5
"$BIN/leleka" version | tee "$STK/version.txt"; sha256sum "$TARBALL" | tee -a "$STK/version.txt"
[ "$(sha256sum "$TARBALL" | cut -c1-64)" = "$(cat $ORCH/reference/tarball.sha256)" ] || die "tarball sha256 differs from the owner-default series" 5
COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD"
[ -f "$ST/leleka.json" ] || die "state of $TAG is not prepared (run the owner-default series first)" 6
log "leleka up --foreground (shipped configuration)"
t0=$(date +%s)
setsid "$BIN/leleka" up --foreground $COMMON --timeout-s 1800 >"$STK/up-foreground.txt" 2>&1 &
SUP_PID=$!
ready=0
for _ in $(seq 1 700); do
if "$PFX/bin/leleka" status --state-dir "$ST" >/dev/null 2>&1; then ready=1; break; fi
kill -0 "$SUP_PID" 2>/dev/null || break
sleep 3
done
[ $ready = 1 ] || { log "NOT READY after $(( $(date +%s) - t0 )) s"; tail -20 "$STK/up-foreground.txt" | cut -c1-240; exit 7; }
log "ready after $(( $(date +%s) - t0 )) s"; echo "$(( $(date +%s) - t0 ))" >"$STK/ready_s.txt"
"$PFX/bin/leleka" status --state-dir "$ST" >"$STK/status.txt" 2>&1; "$PFX/bin/leleka" status --state-dir "$ST" --json >"$STK/status.json" 2>&1
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick.txt" 2>&1
# ---- configuration proof: the engine environment line and the run configuration must equal the owner-default series --------------------------------
grep -m1 'engine environment:' "$STK/up-foreground.txt" >"$STK/engine-environment.txt"
if ! cmp -s "$STK/engine-environment.txt" "$ORCH/reference/engine-environment.txt"; then
log "ENGINE ENVIRONMENT DIFFERS from the owner-default series"; diff "$STK/engine-environment.txt" "$ORCH/reference/engine-environment.txt" | cut -c1-400; exit 8
fi
cp "$ST/leleka.json" "$STK/leleka.json"; cp "$ST/profile.json" "$STK/profile.json" 2>/dev/null
[ "$(sha256sum "$ST/leleka.json" | cut -c1-64)" = "$(cat $ORCH/reference/leleka-json.sha256)" ] || { log "leleka.json DIFFERS from the owner-default series"; exit 8; }
log "configuration proof ok: engine environment line and leleka.json identical to the owner-default series"
run_cell() { # $1 task $2 rep $3 wall s $4 extra config ('|' separates lines) $5 cell dir
local task=$1 rep=$2 wall=$3 extra=$4 cell=$5 link="" t1 rc
[ -f "$cell/cell.json" ] && { log "cell $cell already done: skipped"; return; }
case "$task" in nestng-crm*) link="--link-tree backend/node_modules=$NM/backend/node_modules --link-tree frontend/node_modules=$NM/frontend/node_modules";; esac
echo "$task $(wc -c <"$ST/logs/requests.log") $(wc -c <"$ST/logs/engine.log") $(date -u +%FT%TZ) start" >>"$STK/log-offsets.txt"
t1=$(date +%s)
E2E_API_KEY=$KEY CLD_CODEX=$CODEX timeout $((wall + 900)) python3 -I "$ORCH/tools/delta/cell.py" --cell-dir "$cell" --variant "$VAR" --task "$task" --rep "$rep" \
--tasks-root "$ORCH/tasks" --upstream http://127.0.0.1:8081 --upstream-model qwen-iq3 --codex-bin "$CODEX" --codex-sha256 "$CODEX_SHA" --wall-limit "$wall" --max-rounds "$ROUNDS" \
--engine-log "$ST/logs/engine.log" --active-dir "$RUN/active-$VAR" --config-extra "$extra" $link >"$cell.out" 2>&1; rc=$?
echo "$task $(wc -c <"$ST/logs/requests.log") $(wc -c <"$ST/logs/engine.log") $(date -u +%FT%TZ) end" >>"$STK/log-offsets.txt"
log "cell $task r$rep rc=$rc $(( $(date +%s) - t1 )) s: $(tail -1 "$cell.out" | cut -c1-200)"
}
KEY=$(cat "$ST/api-key")
BASE_EXTRA='model_auto_compact_token_limit = 100000000'
run_cell smoke-mini 101 3000 "$BASE_EXTRA" "$RUN/$VAR/smoke-mini-r101"
run_cell nestng-crm-orch 1 "$WALL_ORCH" "$BASE_EXTRA|features.multi_agent = true|agents.max_threads = 3" "$RUN/$VAR/nestng-crm-orch-r1"
[ "${CMP_CONTROL:-1}" = 1 ] && run_cell nestng-crm 1 "$WALL_CONTROL" "$BASE_EXTRA" "$RUN/$VAR/nestng-crm-r1"
cp "$ST/logs/engine.log" "$STK/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$STK/requests.log" 2>/dev/null; cp "$ST/logs/api.log" "$STK/api.log" 2>/dev/null
"$PFX/bin/leleka" verify --quick --state-dir "$ST" --assets "$AS" >"$STK/verify-quick-end.txt" 2>&1
stop_stack
log "done"
@@ -0,0 +1,9 @@
#!/usr/bin/env bash
# Queue stub of the orchestrator sub-agent smoke (docs/experiments/orchestrator-subagents-smoke.md): the real Codex CLI 0.163.0 told to act as an orchestrator on the
# nestng-crm task (spawn a backend and a frontend sub-agent), release 83bdd85bb482 (owner default), 1 repetition, orchestrator cell wall limit 1500 s, then the
# single-agent control cell (unchanged nestng-crm, wall limit 900 s). The job refuses to start when an input differs from INPUTS.sha256 or the PROVENANCE commit is not 83bdd85bb482.
unset CMP_ARM CMP_TASKS CMP_OPTIONAL CMP_REPS CMP_VANILLA_LOSSY CMP_WALL CMP_ROUNDS CMP_RUN CMP_TARBALL CMP_ARM_PROFILE_SET CMP_ARM_PROFILE_OFF CMP_OURS_TAG CMP_CONTROL CMP_WALL_ORCH CMP_WALL_CONTROL
export CMP_OURS_TAG=83bdd85bb482 CMP_CONTROL=1 CMP_WALL_ORCH=1500 CMP_WALL_CONTROL=900 CMP_ROUNDS=400
J=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke/tools/orchestrator_smoke_job.sh
[ "$(sha256sum $J | cut -c1-64)" = "9a3590bbb5c1fbb9b2f02809f8f4203abf7d2e5d502754137ba853b998a45772" ] || { echo "job script differs from the reviewed one"; exit 3; }
exec bash $J
@@ -0,0 +1,39 @@
#!/usr/bin/env bash
# Run ON the 5090 server, once: setup_orchestrator_inputs.sh REPO_SCRIPT_DIR
# Builds the frozen inputs of the orchestrator sub-agent smoke job under /data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke (AGENTS.md: a measurement
# input lives in one named directory, is read-only and is recorded with its sha256; the job refuses to start when one differs):
# tools/delta/{cell.py,logproxy.py,taskfile.py} the cell runner of the Codex comparison; logproxy.py additionally writes UNIX wall-clock milliseconds
# (t_start_unix_ms, t_end_unix_ms) into every rounds.jsonl line, so requests can be joined with requests.log
# tools/config.toml.tmpl the Codex config template of the comparison
# tasks/ smoke-mini, nestng-crm (control) and nestng-crm-orch (make_orchestrator_tasks.py), with a fresh MANIFEST.sha256
# reference/ what the owner-default series of release 83bdd85bb482 recorded: engine environment line, leleka.json digest, tarball digest
# INPUTS.sha256 digest of every file above
set -euo pipefail
SRC=${1:?directory with make_orchestrator_tasks.py}
TAG=83bdd85bb482
ORCH=/data/leleka-e2e/prefill-latency/orchestrator-subagents-smoke
CMP=/data/leleka-e2e/codex-compare
OWNER_RUN=/data/leleka-e2e/prefill-latency/runs/e2e-codex-ttt-and-crm-release-$TAG-owner-default/LEL/stack-r1
[ -e "$ORCH/INPUTS.sha256" ] && { echo "already frozen: $ORCH/INPUTS.sha256"; exit 0; }
mkdir -p "$ORCH/tools/delta" "$ORCH/reference"
cp "$CMP/delta/cell.py" "$CMP/delta/taskfile.py" "$ORCH/tools/delta/"
python3 -I - "$CMP/delta/logproxy.py" "$ORCH/tools/delta/logproxy.py" <<'PY'
import sys
src = open(sys.argv[1]).read()
a = '"t_start_ms": t_start,\n'
b = 'rec.update({"t_first_byte_ms": t_first, "t_end_ms": st.ms(),'
assert src.count(a) == 1 and src.count(b) == 1
src = src.replace(a, a + ' "t_start_unix_ms": int(time.time() * 1000),\n')
src = src.replace(b, 'rec["t_end_unix_ms"] = int(time.time() * 1000)\n ' + b)
open(sys.argv[2], "w").write(src)
PY
python3 -I -c "import ast,sys; ast.parse(open('$ORCH/tools/delta/logproxy.py').read())"
cp "$CMP/config.toml.tmpl" "$ORCH/tools/config.toml.tmpl"
python3 -I "$SRC/make_orchestrator_tasks.py" "$CMP/tasks" "$ORCH/tasks"
grep -m1 'engine environment:' "$OWNER_RUN/up-foreground.txt" >"$ORCH/reference/engine-environment.txt"
sha256sum "$CMP/ours-state-$TAG/leleka.json" | cut -c1-64 >"$ORCH/reference/leleka-json.sha256"
sed -n 's/^\([0-9a-f]\{64\}\) .*\.tar\.xz$/\1/p' "$OWNER_RUN/version.txt" >"$ORCH/reference/tarball.sha256"
[ "$(wc -c <"$ORCH/reference/tarball.sha256")" = 65 ] || { echo "no tarball digest in $OWNER_RUN/version.txt"; exit 1; }
( cd "$ORCH" && find tools tasks reference -type f ! -name orchestrator_smoke_job.sh | sort | xargs sha256sum >INPUTS.sha256 )
chmod -R a-w "$ORCH/tools/delta" "$ORCH/tasks" "$ORCH/reference" "$ORCH/INPUTS.sha256"
( cd "$ORCH" && sha256sum --quiet -c INPUTS.sha256 && echo "frozen: $(wc -l <INPUTS.sha256) files" )
@@ -55,29 +55,50 @@ if [ "${PF_ALLOW_FULL_MEMFD:-0}" != 1 ] && [ "$ALLOC_GIB" -gt "${PF_MEMFD_MAX_GI
exit 0
fi
[ -d "$G/MODEL.lock" ] || { echo "MODEL.lock is not held"; exit 3; }
PKG=${PF_PKG:-$PL/pkg}
AS=$CMP/ours-assets; ST=${PF_STATE:-$PL/state}; PFX=${PF_PREFIX:-$PL/prefix}; BIN=$PKG/bin
# release layout (PF_RELEASE_TAG=<12 hex>): the package is the unpacked release tarball, identity by PROVENANCE git_commit, state and prefix prepared here once
if [ -n "${PF_RELEASE_TAG:-}" ]; then
python3 -I "$PL/tools/prov_commit.py" "$PKG/PROVENANCE.json" "$PF_RELEASE_TAG" >/dev/null || { echo "package PROVENANCE git_commit does not match $PF_RELEASE_TAG"; exit 5; }
(cd "$PKG" && sha256sum -c SHA256SUMS >/dev/null 2>&1) || { echo "the release files do not match $PKG/SHA256SUMS"; exit 5; }
log "release package: commit $(python3 -I "$PL/tools/prov_commit.py" "$PKG/PROVENANCE.json" "$PF_RELEASE_TAG"), files verified against SHA256SUMS"
if [ ! -f "$ST/leleka.json" ]; then mkdir -p "$ST" "$PFX"; timeout 3000 "$BIN/leleka" up --mode none --assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD >"$RUN/up-prepare.txt" 2>&1; log "up --mode none rc=$?"; fi
AS=$CMP/ours-assets
# select_package <package dir> <release tag or empty> <state dir> <prefix dir>: sets PKG ST PFX BIN and verifies (and for a release layout prepares) that package
select_package() {
PKG=$1; local tag=$2; ST=$3; PFX=$4; BIN=$PKG/bin
# release layout (tag = <12 hex>): the package is the unpacked release tarball, identity by PROVENANCE git_commit, state and prefix prepared here once
if [ -n "$tag" ]; then
python3 -I "$PL/tools/prov_commit.py" "$PKG/PROVENANCE.json" "$tag" >/dev/null || { echo "package PROVENANCE git_commit does not match $tag"; exit 5; }
(cd "$PKG" && sha256sum -c SHA256SUMS >/dev/null 2>&1) || { echo "the release files do not match $PKG/SHA256SUMS"; exit 5; }
log "release package: commit $(python3 -I "$PL/tools/prov_commit.py" "$PKG/PROVENANCE.json" "$tag"), files verified against SHA256SUMS"
if [ ! -f "$ST/leleka.json" ]; then mkdir -p "$ST" "$PFX"; timeout 3000 "$BIN/leleka" up --mode none --assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD >"$RUN/up-prepare-$(basename "$PKG").txt" 2>&1; log "up --mode none rc=$?"; fi
fi
[ -x "$BIN/leleka" ] && [ -f "$ST/leleka.json" ] || { echo "the prefill-latency package or state is not prepared"; exit 3; }
[ -n "$tag" ] || (cd "$BIN" && sha256sum -c ../SHA256SUMS >/dev/null 2>&1) || { echo "the package binaries do not match $PKG/SHA256SUMS"; exit 3; }
}
# Package arms (PF_ARMS="base new"): the variants run different packages, e.g. a kernel A/B where the two arms are two releases of the same tree with and without the change.
# Per arm NAME: PF_ARM_NAME_PKG, PF_ARM_NAME_TAG, PF_ARM_NAME_STATE, PF_ARM_NAME_PREFIX; per variant letter V: PF_ARM_OF_V=NAME. Without PF_ARMS the single package of PF_PKG is used.
declare -A ARM_PKG ARM_TAG ARM_ST ARM_PFX
PFX_ALL=""
if [ -n "${PF_ARMS:-}" ]; then
for arm in $PF_ARMS; do
kp=PF_ARM_${arm}_PKG; kt=PF_ARM_${arm}_TAG; ks=PF_ARM_${arm}_STATE; kx=PF_ARM_${arm}_PREFIX
select_package "${!kp:?$kp}" "${!kt:?$kt}" "${!ks:?$ks}" "${!kx:?$kx}"
ARM_PKG[$arm]=$PKG; ARM_TAG[$arm]=${!kt}; ARM_ST[$arm]=$ST; ARM_PFX[$arm]=$PFX; PFX_ALL="$PFX_ALL $PFX"
done
else
select_package "${PF_PKG:-$PL/pkg}" "${PF_RELEASE_TAG:-}" "${PF_STATE:-$PL/state}" "${PF_PREFIX:-$PL/prefix}"
PFX_ALL=$PFX
fi
[ -x "$BIN/leleka" ] && [ -f "$ST/leleka.json" ] || { echo "the prefill-latency package or state is not prepared"; exit 3; }
[ -n "${PF_RELEASE_TAG:-}" ] || (cd "$BIN" && sha256sum -c ../SHA256SUMS >/dev/null 2>&1) || { echo "the package binaries do not match $PKG/SHA256SUMS"; exit 3; }
got=0; for _ in $(seq 1 4320); do if mkdir "$LOCK" 2>/dev/null; then echo "prefill-latency $(date -u +%FT%TZ) $RUN" >"$LOCK/owner"; got=1; break; fi; sleep 5; done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
SUP_PID=; MON_PID=
stop_stack() { if [ -n "$SUP_PID" ] && kill -0 "$SUP_PID" 2>/dev/null; then kill -TERM "$SUP_PID" 2>/dev/null; for _ in $(seq 1 120); do kill -0 "$SUP_PID" 2>/dev/null || break; sleep 2; done; fi; SUP_PID=; }
cleanup() { stop_stack; [ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null; pkill -KILL -f "$PFX/bin/" 2>/dev/null; sleep 3; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; note "prefill-latency job ended: $RUN"; }
cleanup() { stop_stack; [ -n "$MON_PID" ] && kill "$MON_PID" 2>/dev/null; for px in $PFX_ALL; do pkill -KILL -f "$px/bin/" 2>/dev/null; done; sleep 3; rm -f "$LOCK/owner"; rmdir "$LOCK" 2>/dev/null; note "prefill-latency job ended: $RUN"; }
trap cleanup EXIT
note "prefill-latency job started: variants [$VARS] cells [$CELLS] out $RUN"
[ -z "$(nvidia-smi --query-compute-apps=pid --format=csv,noheader 2>/dev/null)" ] || { echo "something uses the GPU"; exit 3; }
export LD_LIBRARY_PATH=$CUBLAS:$HOME/cuda-toolkits/13.2.2/lib64:${LD_LIBRARY_PATH:-}
COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD"
for v in $VARS; do
D=$RUN/$v; mkdir -p "$D"; vb=${v%%.*}
if [ -n "${PF_ARMS:-}" ]; then
of=PF_ARM_OF_$vb; arm=${!of:?variant $vb has no $of}
PKG=${ARM_PKG[$arm]}; ST=${ARM_ST[$arm]}; PFX=${ARM_PFX[$arm]}; BIN=$PKG/bin
fi
COMMON="--assets $AS --state-dir $ST --prefix $PFX --bin-src $BIN --cublas-dir $CUBLAS --trust-archive --kar-fd $FD"
[ -f "$D/replay.jsonl" ] && { log "variant $v already done: skipped"; continue; }
unset LELEKA_PREFILL_LOAN_TIERS LELEKA_TRACE_PREFILL_R LELEKA_SERVE_PROFILE STRATA_VERIFY_PROFILE LELEKA_REFILL_DEFER LELEKA_BRINGUP_TRACE LELEKA_DRAFT_CHAIN_PIPELINE LELEKA_PREFIX_PARK_FAST LELEKA_PREFIX_PARK_ASYNC LELEKA_DRAFT_CHECK_MERGE LELEKA_TRACE_DRAFT LELEKA_PREFILL_GDN_TC LELEKA_DECODE_GRAPH_REUSE LELEKA_PREFILL_DIAG_SKIP_EXPERT_DMA LELEKA_PREFILL_ROUTE_TRACE STRATA_PREFILL_STREAM_MIN LELEKA_PREFILL_RING_PREFETCH LELEKA_PREFILL_RING_PREFETCH_WINDOW LELEKA_PREFILL_RING_PREFETCH_DETACH LELEKA_ORIGINAL_SERVE_PCIE_FRAC LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER LELEKA_ORIGINAL_SERVE_PCIE_MODE LELEKA_REFILL_BATCH LELEKA_REFILL_DEFER LELEKA_TRACE_DRIVER_ERRORS
PROF_OFF=""; PROF_SET="" # profile engine_env keys to drop / set for this variant (the built-in profile OVERRIDES the shell env of the engine since pkg-s14)
@@ -129,7 +150,9 @@ for v in $VARS; do
AT) ;;
# release 83bdd85bb482+ (owner default quota=no + PCIe 0.65 in the profile): D = shipped default, PT = D + the per-phase pool thread trace (LELEKA_POOL_TIMING=layers, `pool-layer` lines)
D) ;;
PT) export LELEKA_POOL_TIMING=layers;;
# CPU kernel A/B (package arms): B = release without the kernel change, K = with it, BT = A/A twin of B; the profile is the release default for all three
B|BT|K) ;;
PT|PTB|PTK) export LELEKA_POOL_TIMING=layers;;
# ring prefetch group A/B (shipped stream 1536 is in the profile): RP = prefetch on (K 150, window 8, drains context-wide); AD = base with the same driver-error trace flag (prints only on a refusal when the prefetch is off); ADT = A/A twin of AD
RP) export LELEKA_PREFILL_RING_PREFETCH=1 LELEKA_TRACE_DRIVER_ERRORS=1;;
AD|ADT) export LELEKA_TRACE_DRIVER_ERRORS=1;;
@@ -174,12 +197,23 @@ for v in $VARS; do
cp "$ST/logs/engine.log" "$D/engine.log" 2>/dev/null; cp "$ST/logs/requests.log" "$D/requests.log" 2>/dev/null
# arm guard (placement arms): the meta line of the engine log must show the share and the layout this arm asked for; a mismatch marks the block INVALID
META=$(grep -a "leleka-serve meta: config" "$D/engine.log" | tail -1 | grep -o "expert_per_layer=[0-9]* expert_profile=[0-9]* pcie_frac=[0-9.]*")
case $vb in QN) WANT="expert_per_layer=0 expert_profile=1 pcie_frac=0.65";; A|AT) WANT="expert_per_layer=1 expert_profile=1 pcie_frac=0.45";; D|PT) WANT="expert_per_layer=0 expert_profile=1 pcie_frac=0.65";; *) WANT="";; esac
case $vb in QN) WANT="expert_per_layer=0 expert_profile=1 pcie_frac=0.65";; A|AT) WANT="expert_per_layer=1 expert_profile=1 pcie_frac=0.45";; D|PT|PTB|PTK|B|BT|K) WANT="expert_per_layer=0 expert_profile=1 pcie_frac=0.65";; *) WANT="";; esac
# the engine log is a bounded tail: with a long trace the start (the meta line) is gone; the same keys are then read from the `engine environment` line of up-foreground.txt
if [ -z "$META" ]; then
ENVL=$(grep -a "engine environment" "$D/up-foreground.txt" | head -1)
EPL=$(echo "$ENVL" | grep -o "EXPERT_PER_LAYER=[a-z]*" | cut -d= -f2); PCF=$(echo "$ENVL" | grep -o "PCIE_FRAC=[0-9.]*" | cut -d= -f2)
case $EPL in no) EPLN=0;; yes) EPLN=1;; *) EPLN=x;; esac
echo "$ENVL" | grep -q "EXPERT_PROFILE=" && EPR=1 || EPR=0
META="expert_per_layer=$EPLN expert_profile=$EPR pcie_frac=$PCF"; log "variant $v: meta line gone from the bounded engine log, arm keys read from the engine environment line"
fi
RPN=$(grep -a -c "RING-PREFETCH layer" "$D/engine.log"); RFN=$(grep -a -c "RING-REFUSE" "$D/engine.log")
case $vb in RP) [ "$RPN" -gt 100 ] || WANT="ring-prefetch-lines>100";; AD|ADT) [ "$RPN" -eq 0 ] || WANT="ring-prefetch-lines=0";; esac
PLN=$(grep -a -c "leleka-serve pool-layer" "$D/engine.log")
case $vb in PT) [ "$PLN" -gt 1000 ] || WANT="pool-layer-lines>1000";; D) [ "$PLN" -eq 0 ] || WANT="pool-layer-lines=0";; esac
case $vb in PT|PTB|PTK) [ "$PLN" -gt 1000 ] || WANT="pool-layer-lines>1000";; D) [ "$PLN" -eq 0 ] || WANT="pool-layer-lines=0";; esac
[ "$RFN" -eq 0 ] || { log "variant $v RING-REFUSE lines: $RFN"; touch "$D/INVALID"; }
RUNSHA=$(sha256sum "$PFX/bin/leleka-inference" 2>/dev/null | cut -d' ' -f1); PKGSHA=$(sha256sum "$BIN/leleka-inference" | cut -d' ' -f1)
[ -z "${PF_ARMS:-}" ] || [ "$RUNSHA" = "$PKGSHA" ] || { log "variant $v INVALID: the installed leleka-inference ($RUNSHA) is not the package's ($PKGSHA)"; touch "$D/INVALID"; }
{ echo "leleka-inference sha256 $RUNSHA package ${PKG}"; grep -a "engine environment" "$D/up-foreground.txt" | head -1 | cut -c1-1500; } >"$D/arm-binary.txt"
echo "$META ring_prefetch_lines=$RPN pool_layer_lines=$PLN" >"$D/arm-meta.txt"; case $WANT in ring-prefetch-lines*|pool-layer-lines*) META="$WANT-violated:$RPN";; esac; if [ -n "$WANT" ] && { [ "$META" != "$WANT" ] || false; }; then log "variant $v INVALID (arm guard): engine got [$META], arm wants [$WANT]"; touch "$D/INVALID"; else log "variant $v arm guard ok: $META"; fi
stop_stack; kill "$MON_PID" 2>/dev/null; MON_PID=
sleep 5
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Stage 6b step 3 (CPU expert kernels IQ3_S register grid indices + IQ4_NL even/odd accumulators, commit 0c48c823e): BITWISE identity under teacher forcing, two engine test binaries
# (base = main with the kernel commit reverted, new = main), night5-long-256k, 240 forced tokens a request, top-16 logprob rows + draft trace lines, A/A floor inside each process.
# idP1/idP2 = base/new at the script's pool size (1 CPU worker), idP3/idP4 = base/new with the production pool (15 CPU workers).
( cd /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "kernel-iq3s inputs do not match MANIFEST.sha256" >&2; exit 3; }
export D=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/dt BASE_BIN=rt-base NEW_BIN=rt-new ID_OUT=/data/leleka-e2e/prefill-latency/runs/cpu-expert-kernel-register-indices-identity-draftround MAX_NEW=240 ADAPT=4
export SECOND_ENV="LELEKA_ORIGINAL_SERVE_CPU_WORKERS=15"
unset LELEKA_KAR_SPARSE_EXTENTS_SHA256
if [ -n "${LELEKA_STRA169_KAR_FD:-}" ] && [ -e "/proc/self/fd/$LELEKA_STRA169_KAR_FD" ]; then
read -r kar_size kar_blocks < <(stat -L -c "%s %b" "/proc/self/fd/$LELEKA_STRA169_KAR_FD")
if [ $(( kar_blocks * 512 * 2 )) -lt "$kar_size" ]; then export LELEKA_KAR_SPARSE_EXTENTS_SHA256=7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143; fi
fi
exec bash /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/tools/draftround-id-two-binaries.sh
@@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Stage 6b step 3: pool thread trace (LELEKA_POOL_TIMING=layers) with the new CPU expert kernels (PTK, release bcbfa2c99422) against the base kernels (PTB, release c1f15db2fa99), same owner default
# profile, replay VANL/nestng-crm-r2 (30 requests). Report: scripts/e2e/codex/prefill/pool_layer_report.py <block>/engine.log; earlier numbers: docs/experiments/pool-thread-trace.md (release 0ac612d2df74).
( cd /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "kernel-iq3s inputs do not match MANIFEST.sha256" >&2; exit 3; }
export PF_ARMS="base new"
export PF_ARM_base_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-base PF_ARM_base_TAG=c1f15db2fa99 PF_ARM_base_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-base PF_ARM_base_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-base
export PF_ARM_new_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-new PF_ARM_new_TAG=bcbfa2c99422 PF_ARM_new_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-new PF_ARM_new_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-new
export PF_ARM_OF_PTB=base PF_ARM_OF_PTK=new
export PF_VARIANTS="PTB.1 PTK.1 PTK.2 PTB.2" PF_MAX=30
export PF_OUT=/data/leleka-e2e/prefill-latency/runs/cpu-expert-kernel-register-indices-pool-thread-trace-base-vs-new
exec bash /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/tools/pf_ab_job_q.sh
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Stage 6b step 3: paired group A/B of the CPU expert kernels (commit 0c48c823e): release c1f15db2fa99 = main with the kernel commit reverted (B, base) against bcbfa2c99422 = main (K, new),
# both with the owner default profile (quota=no + PCIe 0.65). The 243k Codex session fixbug-ledger-r3 (39 requests, prompts 177-243k, nothing fed back), 5 pairs + A/A twin of the base x3.
# Gate (owner 2026-11-12): identity bitwise AND decode K-B no worse than -0.5 % (the larger of that and the A/A floor).
( cd /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "kernel-iq3s inputs do not match MANIFEST.sha256" >&2; exit 3; }
export PF_ARMS="base new"
export PF_ARM_base_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-base PF_ARM_base_TAG=c1f15db2fa99 PF_ARM_base_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-base PF_ARM_base_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-base
export PF_ARM_new_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-new PF_ARM_new_TAG=bcbfa2c99422 PF_ARM_new_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-new PF_ARM_new_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-new
export PF_ARM_OF_B=base PF_ARM_OF_BT=base PF_ARM_OF_K=new
export PF_CELLS=/data/leleka-e2e/quality-245k/runs/memory-256k-codex-session-quota-no-pcie065-vram-floor/reply/fixbug-ledger-r3
export PF_VARIANTS="B.1 K.1 BT.1 K.2 B.2 BT.2 B.3 K.3 BT.3 K.4 B.4 B.5 K.5" PF_MAX=39
export PF_OUT=/data/leleka-e2e/prefill-latency/runs/cpu-expert-kernel-register-indices-vs-base-243k-group-ab-5-pairs
exec bash /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/tools/pf_ab_job_q.sh
@@ -0,0 +1,13 @@
#!/usr/bin/env bash
# Stage 6b step 3: paired group A/B of the CPU expert kernels (commit 0c48c823e): release c1f15db2fa99 = main with the kernel commit reverted (B, base) against bcbfa2c99422 = main (K, new),
# both with the owner default profile (quota=no + PCIe 0.65). The replay VANL/nestng-crm-r2 (67k class, 30 requests), 5 pairs + A/A twin of the base x3.
# Gate (owner 2026-11-12): identity bitwise AND decode K-B no worse than -0.5 % (the larger of that and the A/A floor).
( cd /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "kernel-iq3s inputs do not match MANIFEST.sha256" >&2; exit 3; }
export PF_ARMS="base new"
export PF_ARM_base_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-base PF_ARM_base_TAG=c1f15db2fa99 PF_ARM_base_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-base PF_ARM_base_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-base
export PF_ARM_new_PKG=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/pkg-new PF_ARM_new_TAG=bcbfa2c99422 PF_ARM_new_STATE=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/state-new PF_ARM_new_PREFIX=/data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/prefix-new
export PF_ARM_OF_B=base PF_ARM_OF_BT=base PF_ARM_OF_K=new
unset PF_CELLS # the default cell of pf_ab_job_q.sh: VANL/nestng-crm-r2
export PF_VARIANTS="B.1 K.1 BT.1 K.2 B.2 BT.2 B.3 K.3 BT.3 K.4 B.4 B.5 K.5" PF_MAX=30
export PF_OUT=/data/leleka-e2e/prefill-latency/runs/cpu-expert-kernel-register-indices-vs-base-67k-group-ab-5-pairs
exec bash /data/leleka-e2e/prefill-latency/kernel-iq3s-register-indices/tools/pf_ab_job_q.sh
+18 -1
View File
@@ -1,7 +1,7 @@
#!/usr/bin/env python3
"""Summary of the `leleka-serve pool-layer` lines of an engine log (offline analysis, stdlib only; never part of serving).
pool_layer_report.py ENGINE_LOG [--skip N] [--split 16] [--tokens 1,2,3,4]
pool_layer_report.py ENGINE_LOG [--skip N] [--split 16] [--tokens 1,2,3,4] [--by-experts]
The engine writes one line per layer window of the CPU expert pool when it runs with `LELEKA_POOL_TIMING=layers`
(`pool_layer_trace.rs`). Per token count T and layer band (layers < SPLIT, layers >= SPLIT) this prints the percentiles of
@@ -12,6 +12,8 @@ the group wall (the pool's dispatch as the engine saw it) and, for each phase (m
busy median thread's compute time; task = p50 / p90 / max of single tasks
idle threads that took no task, host = tasks the host took itself
and the median host stage split of the group (`POOL_TIMING_NAMES`, microseconds). The first SKIP lines are dropped (warm-up).
--by-experts prints one line per (T, number of experts in the window) instead of the layer bands: the group wall percentiles and the median single-task
time of the gate/up (m5) and down (m6) phase, so two logs that cover different expert counts can be compared like for like.
"""
import json
import sys
@@ -75,6 +77,18 @@ def report_band(rows, label):
print(" stage p50 us: " + " ".join("%s %.1f" % (n, q([s[i] for s in st], 0.5)) for i, n in enumerate(STAGES)))
def report_by_experts(rows, tokens):
print(" T experts windows | group wall p50/p75/p90 us | m5 task p50 | m6 task p50")
for t in tokens:
for k in sorted({g["experts"] for g in rows if g["tok"] == t}):
sel = [g for g in rows if g["tok"] == t and g["experts"] == k]
if len(sel) < 20:
continue
m5 = [p["task"][1] for p in phase_rows(sel, 5)]
m6 = [p["task"][1] for p in phase_rows(sel, 6)]
print(" %d %7d %8d | %s | %9.1f | %9.1f" % (t, k, len(sel), pct([g["wall"] for g in sel]), q(m5, 0.5), q(m6, 0.5)))
def main():
args = sys.argv[1:]
if not args:
@@ -86,6 +100,9 @@ def main():
rows = load(args[0], skip)
print("%s: %d pool-layer lines (after skipping %d); workers %s" % (
args[0], len(rows), skip, sorted({g["workers"] for g in rows})))
if "--by-experts" in args:
report_by_experts(rows, tokens)
return 0
for t in tokens:
sel = [g for g in rows if g["tok"] == t]
print("T=%d groups %d" % (t, len(sel)))
@@ -0,0 +1,99 @@
#!/usr/bin/env bash
# Stage 6d: copy of verify-switches-identity.sh for drafter knobs (LELEKA_DRAFT_VOCAB=en ...): the verify window is FIXED (LELEKA_SPEC=4, suffix off), so the windows do not depend on timing and
# the rows of a common context are comparable; the draft trace (idcmp) differs by design for a knob that changes the drafts. Inputs in the task directory $T (MANIFEST.sha256). Header of the original:
# draft-round identity gate (bitwise): teacher-forced replay of the 256k-class capture night5-long-256k (5 requests, recorded replies, decode capped at MAX_NEW forced tokens
# each), production shape, top-16 logprobs of every row and the draft trace (LELEKA_TRACE_DRAFT=1: every draft's ids and IEEE bits of its probabilities), seed OFF, ONE test binary
# (dt/$ID_BIN) for all processes, one process per setting, two arms in each (I1 I2: the A/A floor). HOLDER JOB (copy of footprint3-id.sh).
# ID_BIN test binary directory name under /data/leleka-e2e/decode/dt (required)
# P1_ENV extra env of the reference process (default: nothing)
# P2_ENV extra env of the changed process (required)
# P3_ENV .. P9_ENV optional further processes (verify-switches-identity.sh: one setting each)
# ID_OUT output directory (required) MAX_NEW (default 240) ADAPT (default 4: the adaptive tier swaps, as dt-id2)
# SKIP_P1=1 reuse $ID_OUT/idP1.full of an earlier job (same binary, same environment) as the reference instead of running it again
# ~10 GPU-min a process. Verdict: q_pair (top-16 logprob rows, all common rows must be identical) and draftround-idcmp.py (the draft trace lines must be identical).
set -uo pipefail
LOCK=/data/leleka-e2e/gpu.lock
D=${D:-/data/leleka-e2e/decode/dt} # binaries (dt/<name>), dt/tools, dt/scripts; override to run from another tree
DR=${DR:-/data/leleka-e2e/draft-round} # tools + MANIFEST.sha256; override to run from another tree
O=${ID_OUT:?ID_OUT}
ID_BIN=${ID_BIN:?ID_BIN}
MAX_NEW=${MAX_NEW:-240}
ADAPT=${ADAPT:-4}
mkdir -p "$O"
( cd / && sha256sum --quiet -c "$DR/MANIFEST.sha256" ) || { echo "draft-round: MANIFEST.sha256 check failed" >&2; exit 3; }
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
T=${ACCEPT_ROOT:-/data/leleka-e2e/prefill-latency/accept-knobs}
( cd "$T" && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "accept-knobs inputs do not match MANIFEST.sha256" >&2; exit 3; }
CAP=$T/capture
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 LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=$ADAPT LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0
unset LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_FOOTPRINT_LEGACY LELEKA_SM120_ATTN_DAILY_MTP LELEKA_DRAFT_FUSED_COMMIT LELEKA_DRAFT_ROUND
for f in $D/$ID_BIN $D/tools/q_pair.py $D/tools/q_tail_gate.py $DR/tools/draftround-idcmp.py $CAP/night5-long-256k; do
[ -e "$f" ] || { echo "missing $f" >&2; exit 3; }
done
sha256sum $D/$ID_BIN | tee $O/rt.sha256
shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan"
# The holder's memfd may be the sparse PLE-only one (leleka seal-exec --sparse-ple, 14.9 GiB of 51.5): the test binary
# must then verify the extents (LELEKA_KAR_SPARSE_EXTENTS_SHA256) instead of reading the whole archive, which would
# touch every hole and fill the holder. Detected from the allocated size of the descriptor; a full holder keeps the old path.
unset LELEKA_KAR_SPARSE_EXTENTS_SHA256
if [ -n "${LELEKA_STRA169_KAR_FD:-}" ] && [ -e "/proc/self/fd/$LELEKA_STRA169_KAR_FD" ]; then
read -r kar_size kar_blocks < <(stat -L -c '%s %b' "/proc/self/fd/$LELEKA_STRA169_KAR_FD")
if [ $((kar_blocks * 512)) -lt $((kar_size / 2)) ]; then
export LELEKA_KAR_SPARSE_EXTENTS_SHA256=${EXTENTS_SHA256:-7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143}
echo "sparse holder memfd detected ($kar_blocks blocks of 512 B for $kar_size bytes): verifying the extents"
fi
fi
run() { # label extra-env
got=0
for i in $(seq 1 1080); do
if mkdir $LOCK 2>/dev/null; then echo "draft-round identity $1 $(date -u +%FT%TZ)" >$LOCK/owner; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; return 3; }
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "=== $1 extra=[$2] MemAvailable GiB: $avail"
if [ "$avail" -lt 60 ]; then echo "abort: less than 60 GiB available"; rm -f $LOCK/owner; rmdir $LOCK; return 4; fi
date -u +%FT%TZ
env $2 LELEKA_TRACE_DRAFT=1 LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP/night5-long-256k LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16 \
LELEKA_REPLAY_MAX_NEW=$MAX_NEW LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="I1=$shape,I2=$shape" \
nice -n 5 $D/$ID_BIN --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke > $O/$1.full 2>&1
echo "rc=$? label=$1"; date -u +%FT%TZ
grep -a -E "^REPLAY #|test result|panicked|FAILED|expert cache [0-9]+ slots" $O/$1.full | cut -c1-200 | tail -14
grep -a -c "^DRAFT " $O/$1.full
rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null
sleep 15
}
if [ "${SKIP_P1:-0}" = 1 ]; then [ -s "$O/idP1.full" ] || { echo "SKIP_P1 set but $O/idP1.full is missing" >&2; exit 3; }; else run idP1 "${P1_ENV:-LELEKA_X=1}"; fi
run idP2 "${P2_ENV:?P2_ENV}"
PROCS="idP1 idP2"
for k in 3 4 5 6 7 8 9; do # further processes: P3_ENV .. P9_ENV, one setting each, in order (a gap ends the list)
var="P${k}_ENV"; [ -n "${!var:-}" ] || break
run idP$k "${!var}"; PROCS="$PROCS idP$k"
done
T=$D/tools
for p in $PROCS; do echo "== q_tail_gate $p"; python3 $T/q_tail_gate.py $O/$p.full $CAP/night5-long-256k 2>&1 | tail -8; done
python3 - <<PY
import sys
sys.path.insert(0, "$T")
import q_pair
procs = "$PROCS".split()
rows = {p: [q_pair.rows_of("$O/%s.full" % p, i) for i in (0, 1)] for p in procs}
q_pair.compare(rows["idP1"][0], rows["idP1"][1], "reference process, arm I2 against arm I1 (A/A noise floor)")
for p in procs[1:]:
q_pair.compare(rows[p][0], rows[p][1], p + ", arm I2 against arm I1 (A/A)")
q_pair.compare(rows["idP1"][0], rows[p][0], p + " against the reference, arm I1")
q_pair.compare(rows["idP1"][1], rows[p][1], p + " against the reference, arm I2")
PY
for p in $PROCS; do [ $p = idP1 ] && continue; echo "== draft trace $p against idP1"; python3 -I $DR/tools/draftround-idcmp.py $O/idP1.full $O/$p.full; done
sha256sum $O/*.full
date -u +%FT%TZ
+58
View File
@@ -0,0 +1,58 @@
#!/usr/bin/env bash
# Stage 6d (tokens per round): teacher-forced replay of the REAL Codex session capture cap-s3 (33 requests of a 177k-232k session, recorded replies capped at 400 tokens)
# in ONE test-binary process with several speculation policies as LELEKA_SPEC_ARMS, in the shipped decode shape: the engine_env of the release profile rtx5090-32g
# (read from the frozen profile json, so the arm cannot drift from the release), auto expert slots, upstream ranked profile, MTP draft vocabulary subset (rt dir).
# Every arm decodes exactly the recorded text (LELEKA_REPLAY_FORCE=1), so the arms differ only in how they speculate: tokens per round, ms per round and decode tok/s of
# all arms come from identical work, arm order rotated over the repetitions. HOLDER JOB (needs the sealed KAR memfd of the holder). Test tooling, never in serving.
# ARMS LELEKA_SPEC_ARMS list (required); arm 0 also runs the warm-up pass (discarded). `adaptive@P` = adaptive window with request floor P, `~key=value` = per-arm policy
# constants (explore margin min_p_lo step alpha decay bias ceil rowq smooth measured), `fixedN@P` = the Original's `--spec N` window with floor P (fixed4@0.5 = vanilla)
# REPS repetitions of the arm list (default 5) MAX_NEW forced tokens per request (default 400, the capture's cap)
# ENVX extra KEY=VALUE words for the whole process (process-level knobs: LELEKA_DRAFT_VOCAB=en, LELEKA_SPEC_SUFFIX=4, ...)
# OUT output directory (required) BIN test binary under $T/dt (default rt-main)
# Inputs live in the task directory $T and are checked against its MANIFEST.sha256 before the GPU is taken.
set -uo pipefail
T=${ACCEPT_ROOT:-/data/leleka-e2e/prefill-latency/accept-knobs}
LOCK=/data/leleka-e2e/gpu.lock
ARMS=${ARMS:?ARMS}; O=${OUT:?OUT}; REPS=${REPS:-5}; MAX_NEW=${MAX_NEW:-400}; BIN=${BIN:-rt-main}
( cd "$T" && sha256sum --quiet -c MANIFEST.sha256 ) || { echo "accept-knobs inputs do not match MANIFEST.sha256" >&2; exit 3; }
mkdir -p "$O"
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
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 LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=$T/assets/expert-profile-upstream.bin
export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=auto
# the release profile's engine_env, verbatim (tier layout, PCIe share, seed, sm_120 kernels, graph reuse, ...)
eval "$(python3 -I -c 'import json,shlex,sys; [print("export %s=%s" % (k, shlex.quote(str(v)))) for k, v in json.load(open(sys.argv[1]))["engine_env"].items()]' "$T/profile-rtx5090-32g.json")"
unset LELEKA_SPEC LELEKA_SPEC_ADAPTIVE LELEKA_SPEC_SUFFIX LELEKA_ORIGINAL_SERVE_ADAPT_EVERY LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_FOOTPRINT_LEGACY LELEKA_DRAFT_VOCAB
CAPDIR=$T/capture/cap-s3
shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan"
# the holder's memfd may be the sparse PLE-only one: the test binary verifies the extents instead of the whole archive
unset LELEKA_KAR_SPARSE_EXTENTS_SHA256
if [ -n "${LELEKA_STRA169_KAR_FD:-}" ] && [ -e "/proc/self/fd/$LELEKA_STRA169_KAR_FD" ]; then
read -r kar_size kar_blocks < <(stat -L -c '%s %b' "/proc/self/fd/$LELEKA_STRA169_KAR_FD")
if [ $((kar_blocks * 512)) -lt $((kar_size / 2)) ]; then export LELEKA_KAR_SPARSE_EXTENTS_SHA256=${EXTENTS_SHA256:-7568b1211419a7c10a9b39a86230f75b7fa9c02839e36c9b5f2494ec7af72143}; fi
fi
echo "arms=$ARMS reps=$REPS max_new=$MAX_NEW envx=[${ENVX:-}] bin=$BIN" | tee "$O/args.txt"
env | grep -E '^(LELEKA|STRATA)_' | grep -v -E 'KAR_(FD|PROVENANCE)' | sort >"$O/env.txt"
got=0
for _ in $(seq 1 2160); do
if mkdir $LOCK 2>/dev/null; then echo "accept-knobs replay $(date -u +%FT%TZ) $O" >$LOCK/owner; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; exit 3; }
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "MemAvailable GiB: $avail"
if [ "$avail" -lt 60 ]; then echo "abort: less than 60 GiB available"; rm -f $LOCK/owner; rmdir $LOCK; exit 4; fi
date -u +%FT%TZ
env ${ENVX:-LELEKA_X=1} LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAPDIR LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 \
LELEKA_REPLAY_MAX_NEW=$MAX_NEW LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="W=$shape" LELEKA_REPLAY_REPS=$REPS LELEKA_REPLAY_SPEC_MIN_P=0 \
LELEKA_SPEC_ARMS="$ARMS" LELEKA_SPEC_STATS=1 \
"$T/dt/$BIN" --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke >"$O/replay.full" 2>&1
echo "rc=$?"; date -u +%FT%TZ
grep -a -E "^REPLAY PASS|test result|panicked|FAILED|expert cache [0-9]+ slots|draft-vocab|draft head over" "$O/replay.full" | cut -c1-240 | tail -60
rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null
python3 -I "$T/tools/accept-knobs-summary.py" "$O/replay.full" | tee "$O/SUMMARY.txt"
@@ -0,0 +1,44 @@
# Stage 6d: offline simulation of the suffix drafter (trigram index, K candidates) on a capture: usage accept-knobs-suffix-sim.py <capture dir> <requests>. CPU only.
import json,glob,sys,collections
def run(files,Ks,maxlen=7,min_match=3,max_match=64):
res={K:[0,0,0,0] for K in Ks} # positions, proposals, accepted tokens sum, accepted>=maxlen
for f in files:
j=json.load(open(f)); P=j['prompt_ids']; G=j['generated_ids']
H=P+G
n0=len(P)
occ=collections.defaultdict(list) # trigram -> end positions (ascending)
for e in range(2,n0): # trigram ending at e covers e-2..e
occ[(H[e-2],H[e-1],H[e])].append(e)
for i in range(n0, n0+len(G)-1):
# history = H[:i]; cur = i-1
cur=i-1
# add trigram ending at cur if not present (positions up to cur-1 were added)
if cur>=2:
key=(H[cur-2],H[cur-1],H[cur])
cand=[p for p in occ.get(key,[]) if p<cur]
occ[key].append(cur)
else: cand=[]
for K in Ks:
res[K][0]+=1
best_len=0;best_end=-1
for p in (cand[::-1] if K=='all' else cand[::-1][:K]):
L=0
while L<max_match and L<=p and H[p-L]==H[cur-L]: L+=1
if L>best_len: best_len=L;best_end=p
if best_len>=min_match:
res[K][1]+=1
a=0
for t in range(maxlen):
q=best_end+1+t
if q>cur or i+t>=len(H): break
if H[q]==H[i+t]: a+=1
else: break
res[K][2]+=a
if a>=maxlen: res[K][3]+=1
return res
files=sorted(glob.glob(sys.argv[1]+'/req-*.json'))[:int(sys.argv[2])]
for ml in (7,11):
r=run(files,[4,8,16,'all'],maxlen=ml)
print('maxlen',ml)
for K,(pos,pr,acc,full) in r.items():
print(' K=%-4s positions %d proposals %.3f of positions, mean accepted per proposal %.2f, accepted tokens per position %.3f, full-length share of proposals %.3f'%(K,pos,pr/pos,acc/max(pr,1),acc/pos,full/max(pr,1)))
@@ -0,0 +1,75 @@
#!/usr/bin/env python3
"""Per-arm summary of accept-knobs-replay.sh (teacher-forced replay, several speculation policies in one process, identical text for every arm).
Per arm: tokens, rounds, decode seconds summed over its passes (the warm-up pass is dropped); the passes are rebuilt from the per-request REPLAY lines
(decode_ms to 0.1 ms). Then, paired by repetition against the first arm (the base), the mean difference of tok/s, tokens per round and ms per round in
percent of the base with a 95 % interval (Student t on the repetition differences). The twin arm (the same policy under another label) is the A/A floor:
a knob is read only against it. usage: accept-knobs-summary.py <replay.full> [base-arm] [twin-arm]"""
import re
import statistics as st
import sys
T95 = {1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306, 9: 2.262, 10: 2.228}
def read_passes(path):
reqs = {}
pat = re.compile(r"REPLAY #(\d+) pass=(\d+) (\S+) arm=(\S+) .*? produced=(\d+) rounds=(\d+) tok_per_round=\S+ decode_ms=([\d.]+)")
for ln in open(path, errors="replace"):
m = pat.match(ln)
if not m:
continue
_, ps, lab, arm, produced, rounds, ms = m.groups()
r = reqs.setdefault(int(ps), dict(lab=lab, arm=arm, tok=0, sec=0.0, rounds=0))
r["tok"] += int(produced)
r["sec"] += float(ms) / 1000.0
r["rounds"] += int(rounds)
return [dict(n=ps, tps=r["tok"] / r["sec"], tpr=r["tok"] / r["rounds"], mpr=1000 * r["sec"] / r["rounds"], **r) for ps, r in sorted(reqs.items())]
def paired(rows, by, base, arm, key):
reps = sorted({p["lab"] for p in rows})
d = []
for r in reps:
x = [p for p in by[arm] if p["lab"] == r]
y = [p for p in by[base] if p["lab"] == r]
if x and y:
d.append(100.0 * (x[0][key] / y[0][key] - 1.0))
if len(d) < 2:
return None
se = st.stdev(d) / len(d) ** 0.5
return st.mean(d), T95.get(len(d) - 1, 2.0) * se, sum(1 for z in d if z > 0), len(d)
def main():
passes = read_passes(sys.argv[1])
rows = [p for p in passes if p["lab"] != "warm"]
arms = []
for p in rows:
if p["arm"] not in arms:
arms.append(p["arm"])
base = sys.argv[2] if len(sys.argv) > 2 else arms[0]
twin = sys.argv[3] if len(sys.argv) > 3 else (arms[1] if len(arms) > 1 else None)
print("passes %d (+%d warm-up), arms %d, base %s, twin (A/A floor) %s" % (len(rows), len(passes) - len(rows), len(arms), base, twin))
print("%-40s %3s %8s %7s %9s %9s" % ("arm", "n", "tok/s", "sd", "tok/round", "ms/round"))
by = {}
for a in arms:
v = [p for p in rows if p["arm"] == a]
by[a] = v
tok, sec, rd = sum(p["tok"] for p in v), sum(p["sec"] for p in v), sum(p["rounds"] for p in v)
tps = [p["tps"] for p in v]
print("%-40s %3d %8.2f %7.2f %9.3f %9.3f" % (a, len(v), tok / sec, st.pstdev(tps) if len(tps) > 1 else 0.0, tok / rd, 1000 * sec / rd))
print("\npaired against %s, percent of base, mean (95%% interval), arm better in n of N repetitions" % base)
print("%-40s %-26s %-26s %-26s" % ("arm", "tok/s", "tok/round", "ms/round"))
for a in arms:
if a == base:
continue
cells = []
for key in ("tps", "tpr", "mpr"):
r = paired(rows, by, base, a, key)
cells.append("n/a" if r is None else "%+.2f (+-%.2f) %d/%d" % (r[0], r[1], r[2], r[3]))
print("%-40s %-26s %-26s %-26s%s" % (a, cells[0], cells[1], cells[2], " <- A/A floor" if a == twin else ""))
if __name__ == "__main__":
main()
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
# Two-binary draft-round identity gate (bitwise): draftround-id.sh with a different test binary per process, for a change that has no environment switch (a kernel, a data layout).
# Teacher-forced replay of the 256k-class capture night5-long-256k (5 requests, recorded replies, MAX_NEW forced tokens each), production shape, top-16 logprobs of every row and the
# draft trace (LELEKA_TRACE_DRAFT=1), seed OFF, one process per (binary, setting), two arms in each (I1 I2: the A/A floor). HOLDER JOB.
# BASE_BIN, NEW_BIN test binary names under $D (required): the tree without the change, the tree with it
# ID_OUT output directory (required) MAX_NEW (default 240) ADAPT (default 4)
# SECOND_ENV optional second setting, run again with both binaries (e.g. LELEKA_ORIGINAL_SERVE_CPU_WORKERS=15, the production pool size; the script default is 1 worker)
# Processes: idP1 = BASE_BIN, idP2 = NEW_BIN (default setting); with SECOND_ENV: idP3 = BASE_BIN, idP4 = NEW_BIN. ~10 GPU-min a process.
# Verdict: q_pair (top-16 logprob rows, all common rows identical, A/A floor inside each process) and draftround-idcmp.py (draft trace lines identical), new against base at each setting.
set -uo pipefail
LOCK=/data/leleka-e2e/gpu.lock
D=${D:-/data/leleka-e2e/decode/dt} # binaries (dt/<name>), dt/tools, dt/scripts; override to run from another tree
DR=${DR:-/data/leleka-e2e/draft-round} # tools + MANIFEST.sha256; override to run from another tree
O=${ID_OUT:?ID_OUT}
BASE_BIN=${BASE_BIN:?BASE_BIN}; NEW_BIN=${NEW_BIN:?NEW_BIN}
MAX_NEW=${MAX_NEW:-240}
ADAPT=${ADAPT:-4}
mkdir -p "$O"
( cd / && sha256sum --quiet -c "$DR/MANIFEST.sha256" ) || { echo "draft-round: MANIFEST.sha256 check failed" >&2; exit 3; }
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
CAP=/data/leleka-e2e/sm120/capture
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 LELEKA_ORIGINAL_SERVE_BUDGET_GIB=30
export LELEKA_ORIGINAL_SERVE_EXPERT_PER_LAYER=yes LELEKA_ORIGINAL_SERVE_PCIE_FRAC=0.45
export LELEKA_SMOKE_PROMPT_CACHE=0 LELEKA_SERVE_PROFILE=1 LELEKA_GRAPH_EXEC_REUSE=off
export LELEKA_ORIGINAL_SERVE_EXPERT_PROFILE=/data/leleka-e2e/decode/assets/expert-profile-upstream.bin
export LELEKA_ORIGINAL_SERVE_RT_DIR=$A/data/mtp-rt
export LELEKA_ORIGINAL_SERVE_EXPERT_SLOTS=8000 LELEKA_CHAIN=all
export LELEKA_ORIGINAL_SERVE_ADAPT_EVERY=$ADAPT LELEKA_ORIGINAL_SERVE_SEED=off LELEKA_ORIGINAL_SERVE_CPU_WORKERS=1 LELEKA_SPEC=4 LELEKA_SPEC_SUFFIX=0
unset LELEKA_SERVE_DRAFT_AFTER_COMMIT LELEKA_PROMPT_EMBED_ALIAS LELEKA_VRAM_LEDGER LELEKA_DENSE_SLAB LELEKA_FOOTPRINT_LEGACY LELEKA_SM120_ATTN_DAILY_MTP LELEKA_DRAFT_FUSED_COMMIT LELEKA_DRAFT_ROUND
for f in $D/$BASE_BIN $D/$NEW_BIN $D/tools/q_pair.py $D/tools/q_tail_gate.py $DR/tools/draftround-idcmp.py $CAP/night5-long-256k; do
[ -e "$f" ] || { echo "missing $f" >&2; exit 3; }
done
sha256sum $D/$BASE_BIN $D/$NEW_BIN | tee $O/rt.sha256
shape="reply@8192/8192!orig!fast!nocluster!store!qpf!gpool!mspan"
run() { # label extra-env binary
got=0
for i in $(seq 1 1080); do
if mkdir $LOCK 2>/dev/null; then echo "draft-round identity $1 $(date -u +%FT%TZ)" >$LOCK/owner; got=1; break; fi
sleep 5
done
[ $got = 1 ] || { echo "GPU lock held by: $(cat $LOCK/owner 2>/dev/null)"; return 3; }
avail=$(awk '/MemAvailable/{print int($2/1048576)}' /proc/meminfo); echo "=== $1 extra=[$2] MemAvailable GiB: $avail"
if [ "$avail" -lt 60 ]; then echo "abort: less than 60 GiB available"; rm -f $LOCK/owner; rmdir $LOCK; return 4; fi
date -u +%FT%TZ
env $2 LELEKA_TRACE_DRAFT=1 LELEKA_ORIGINAL_SERVE_REPLAY=yes LELEKA_BRINGUP_TRACE=1 LELEKA_REPLAY_DIR=$CAP/night5-long-256k LELEKA_PREFIX_TRACE=1 LELEKA_REPLAY_PREFIX_MIB=6000 LELEKA_TRACE_PREFILL_R=1 LELEKA_TRACE_LOGPROBS=16 \
LELEKA_REPLAY_MAX_NEW=$MAX_NEW LELEKA_REPLAY_FORCE=1 LELEKA_REPLAY_ARMS="I1=$shape,I2=$shape" \
nice -n 5 $D/$3 --ignored --exact --test-threads=1 --nocapture backend::original_serve_replay::original_serve_replay_smoke > $O/$1.full 2>&1
echo "rc=$? label=$1"; date -u +%FT%TZ
grep -a -E "^REPLAY #|test result|panicked|FAILED|expert cache [0-9]+ slots" $O/$1.full | cut -c1-200 | tail -14
grep -a -c "^DRAFT " $O/$1.full
rm -f $LOCK/owner; rmdir $LOCK 2>/dev/null
sleep 15
}
run idP1 "LELEKA_X=1" $BASE_BIN
run idP2 "LELEKA_X=1" $NEW_BIN
PROCS="idP1 idP2"
if [ -n "${SECOND_ENV:-}" ]; then run idP3 "$SECOND_ENV" $BASE_BIN; run idP4 "$SECOND_ENV" $NEW_BIN; PROCS="idP1 idP2 idP3 idP4"; fi
T=$D/tools
for p in $PROCS; do echo "== q_tail_gate $p"; python3 $T/q_tail_gate.py $O/$p.full $CAP/night5-long-256k 2>&1 | tail -8; done
python3 - <<PY
import sys
sys.path.insert(0, "$T")
import q_pair
procs = "$PROCS".split()
rows = {p: [q_pair.rows_of("$O/%s.full" % p, i) for i in (0, 1)] for p in procs}
for p in procs:
q_pair.compare(rows[p][0], rows[p][1], p + ", arm I2 against arm I1 (A/A noise floor)")
for base, new in (("idP1", "idP2"), ("idP3", "idP4")):
if base in rows:
q_pair.compare(rows[base][0], rows[new][0], new + " (new) against " + base + " (base), arm I1")
q_pair.compare(rows[base][1], rows[new][1], new + " (new) against " + base + " (base), arm I2")
PY
for pair in "idP1 idP2" "idP3 idP4"; do set -- $pair; [ -s $O/$2.full ] || continue; echo "== draft trace $2 (new) against $1 (base)"; python3 -I $DR/tools/draftround-idcmp.py $O/$1.full $O/$2.full; done
+95
View File
@@ -0,0 +1,95 @@
# Synthetic model of a parked prefix-cache block (docs/experiments/async-park-compression-and-orchestrator-bench.md):
# the real layout (INT8 K/V codes with one fp16 scale per 64 values, run-major, plus f32 pooled index rows), filled with
# SYNTHETIC activations (Gaussian, per-channel outliers, Student-t tails). It measures order-0 entropy per plane and
# writes the planes as files so that `zstd -1/-3/-19` can be timed on the target CPU. It is NOT a measurement of the model:
# real parked blocks need the dump hook described in the document. Offline experiment, pure standard library.
#
# kv_block_compress_sim.py OUT_DIR [CELLS] (CELLS per layer, default 2048 = one block; keep OUT_DIR small)
import collections
import math
import os
import random
import struct
import sys
HEADS, HEAD_DIM, GROUP = 2, 256, 64
MODELS = { # name: (std of log channel scale, Student-t degrees of freedom or 0 for Gaussian)
"gauss": (0.0, 0),
"outlier-channels": (0.7, 0),
"outlier-channels+t4": (0.7, 4),
}
def entropy_bits(data):
counts, n = collections.Counter(data), len(data)
return -sum(c / n * math.log2(c / n) for c in counts.values())
def draw(rng, sigma, dof):
if dof == 0:
return rng.gauss(0.0, 1.0)
return rng.gauss(0.0, 1.0) / math.sqrt(rng.gammavariate(dof / 2.0, 2.0) / dof)
def quantize(values):
"""absmax/127 per 64-group, scale rounded through fp16, codes round-half-even (kv_q8.rs)."""
codes, scales = bytearray(), []
for at in range(0, len(values), GROUP):
group = values[at:at + GROUP]
s = struct.unpack("<e", struct.pack("<e", max(abs(v) for v in group) / 127.0))[0]
scales.append(struct.pack("<e", s))
codes += bytes((round(v / s) if s > 0 else 0) & 0xFF for v in group)
return bytes(codes), b"".join(scales)
def plane(rng, cells, sigma, dof):
"""K or V codes and scales of `cells` cells of one layer, cell-major (2 heads x 256 dims per cell)."""
channel = [math.exp(rng.gauss(0.0, sigma)) for _ in range(HEADS * HEAD_DIM)]
codes, scales = bytearray(), bytearray()
for _ in range(cells):
c, s = quantize([draw(rng, sigma, dof) * channel[i] for i in range(HEADS * HEAD_DIM)])
codes += c
scales += s
return bytes(codes), bytes(scales)
def pooled_rows(rng, rows, dim=128):
"""f32 pooled index rows: four keys rounded through fp16, summed, RMS-normalised, scaled by gamma."""
gamma = [math.exp(rng.gauss(0.0, 0.3)) for _ in range(dim)]
out = bytearray()
for _ in range(rows):
keys = [sum(struct.unpack("<e", struct.pack("<e", rng.gauss(0, 1)))[0] for _ in range(4)) for _ in range(dim)]
inv = 1.0 / math.sqrt(sum(k * k for k in keys) / dim + 1e-6)
out += struct.pack("<%df" % dim, *[k * inv * g for k, g in zip(keys, gamma)])
return bytes(out)
def byte_planes(raw, width):
return [raw[i::width] for i in range(width)]
def report(name, codes, scales, index):
hc, hs = entropy_bits(codes), entropy_bits(scales)
hi = sum(entropy_bits(p) for p in byte_planes(index, 4)) / 4
total = (1024 * hc / 8 + 32 * hs / 8 + 128 * hi / 8)
print("%-22s codes %.2f b/B (x%.2f) scales %.2f b/B (x%.2f) index f32 byte-planes %.2f b/B (x%.2f)"
" block ideal x%.2f" % (name, hc, 8 / hc, hs, 8 / hs, hi, 8 / hi, 1184 / total))
def main(out_dir, cells):
rng = random.Random(1)
os.makedirs(out_dir, exist_ok=True)
index = pooled_rows(rng, max(cells // 4, 1))
for name, (sigma, dof) in MODELS.items():
k_codes, k_scales = plane(rng, cells, sigma, dof)
v_codes, v_scales = plane(rng, cells, sigma, dof)
report(name, k_codes + v_codes, k_scales + v_scales, index)
for part, data in (("codes", k_codes + v_codes), ("scales", k_scales + v_scales)):
with open(os.path.join(out_dir, "%s.%s.bin" % (name, part)), "wb") as f:
f.write(data)
with open(os.path.join(out_dir, "index.f32.bin"), "wb") as f:
f.write(index)
if __name__ == "__main__":
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 2048)
+43
View File
@@ -0,0 +1,43 @@
# Trace-driven model of N agent sessions through the gateway's FIFO queue (docs/experiments/async-park-compression-and-orchestrator-bench.md,
# section B.4): every request of a recorded single-agent session keeps its recorded service time (t_done - t_start) and the recorded
# gap before the next one (agent think + tools); one engine serves one request at a time in arrival order; a session change costs a
# switch time. Prints the makespan of the sessions run concurrently against the sum of their solo walls. Offline, standard library,
# no GPU; run from the repository root: python scripts/memory/queue_gap_sim.py
import csv, itertools, heapq, statistics
F={'943b':'docs/e2e-data/943b-trace.csv','945':'docs/e2e-data/945-trace.csv','943d':'docs/e2e-data/943d-codex-ttt-trace.csv','945d':'docs/e2e-data/945d-codex-crm-trace.csv'}
def load(p):
rows=list(csv.DictReader(open(p)))
out=[]
for r in rows:
try: svc=(float(r['t_done_ms'])-float(r['t_start_ms']))/1000
except: continue
g=r.get('gap_before_ms') or '0'
out.append((svc, float(g)/1000 if g else 0.0))
return out
S={k:load(v) for k,v in F.items()}
for k,v in S.items():
svc=sum(x[0] for x in v); gap=sum(x[1] for x in v[1:]); print(k,len(v),'svc %.0f s gap %.1f s (%.1f%%)'%(svc,gap,100*gap/(svc+gap)))
def solo(v,scale):
return sum(x[0]*scale for x in v)+sum(x[1] for x in v[1:])
def fifo(sessions,scale,sw):
# each session: next request becomes ready after previous done + gap
ready=[0.0]*len(sessions); idx=[0]*len(sessions); t=0.0; last=None; done=[0.0]*len(sessions)
while any(idx[i]<len(sessions[i]) for i in range(len(sessions))):
cands=[(ready[i],i) for i in range(len(sessions)) if idx[i]<len(sessions[i])]
r,i=min(cands)
start=max(t,r)
s=sessions[i][idx[i]][0]*scale + (sw if (last is not None and last!=i) else 0)
t=start+s; last=i
idx[i]+=1
if idx[i]<len(sessions[i]): ready[i]=t+sessions[i][idx[i]][1]
else: done[i]=t
return t
for scale in (1.0,0.4):
for sw in (0.1,0.3):
print('--- service scale %.1f (1.0=as recorded era, 0.4~faster decode) switch %.1f s'%(scale,sw))
for a,b in itertools.combinations(S,2):
seq=solo(S[a],scale)+solo(S[b],scale)
con=fifo([S[a],S[b]],scale,sw)
print(a,b,'seq %.0f conc %.0f speedup %.3f'%(seq,con,seq/con))
seq=sum(solo(S[k],scale) for k in S); con=fifo(list(S.values()),scale,sw)
print('all4 seq %.0f conc %.0f speedup %.3f'%(seq,con,seq/con))