Files
leleka/docs/adaptive-spec.md
T

144 lines
13 KiB
Markdown

# Adaptive speculative window (`claude/adaptive-spec`)
Status: implemented, measured on the 5090, **default on** (`LELEKA_SPEC_ADAPTIVE=off` or `LELEKA_SPEC=N` selects the fixed Original window).
## Why
The Original verifies a fixed window: MTP chain of `spec - 1` = 3 drafts cut at `--spec-min-p 0.5`, plus an optional suffix
(prompt lookup) window up to `spec + 2` = 6 rows chosen by `DraftPolicy` (a yes/no on the suffix, with the MTP window as the
alternative). Whether a wider window pays depends on two things that differ between workloads and between moments of one run:
* how often the next draft is right (code edit, a file re-emitted from the context, tool-call JSON: high; prose: low), and
* what one more verified row costs (expert tier hit rate, CPU pool and PCIe load: with a converged tier the extra rows are nearly
free; with a cold tier each row touches more distinct experts and the window gets slower).
At about 50 ms a round, one more accepted token per round is worth 30-40 %, so the choice of the width is worth more than most
kernel work, and a fixed value is wrong for part of every session.
## Policy (crates/leleka-runtime/src/qwen_forward/original_spec_adaptive.rs)
Per round the policy sees everything the drafters offer: the MTP chain (tokens and their own probabilities) and the suffix
continuation (up to `max_t - 1` tokens, the match length, whether its first token equals the MTP's first draft). It evaluates every
prefix of each as a candidate window and takes the one with the best
rate(t) = E[tokens committed by the round](t) / (T(t) + chain ms)
E(t) = 1 + sum_{j<t} prod_{i<=j} a_i
* `a_i` is the **calibrated** probability that draft i is accepted given drafts 1..i-1 were: for the MTP a table indexed by
(depth, bucket of the draft's own probability), shrunk toward a depth-free table per probability bucket, shrunk toward a prior
from the bucket centre; for the suffix the first row and the continuation rows by match-length bucket, separately when the suffix
agrees with the MTP and when it does not. Counts are decayed (0.995 per sample). A scalar logit bias per source moves fast
(rate 0.06 per tested row, fading) so a change of content (code to prose, JSON, a pasted file) is followed in tens of rounds
without waiting for the tables.
* The learning signal is exact: of `t-1` offered rows, rows 1..min(accepted+1, t-1) were tested (row j counts as a hit when
j <= accepted), the rest were censored by the first rejection.
* `T(t)` is the measured round time of a t-row window minus the draft chain (0.45 ms per chain step), kept as a decayed mean per
width (winsorised) blended with a fit `a + c (t-1)` over the recent rounds (forgetting 0.97 per round, slope pulled toward 15 %
of the level per row). The fit is what predicts widths not run lately: it carries the current tier / CPU / PCIe state. A width's own mean is trusted less as
it ages. Every observation also moves the other widths a part of the way (a state change is mostly common to all widths).
* Hysteresis: the previous round's (source, width) is kept unless another candidate is better by `LELEKA_SPEC_MARGIN` (2 %).
* Exploration is deterministic (no RNG, traces are reproducible): every `LELEKA_SPEC_EXPLORE` rounds (32; 8 for the first 24
rounds) a neighbouring width (+-1) whose model rate is within 12 % of the best and which has not been measured for 48 rounds is
run instead. Verification keeps the result exact; only one round's speed is at stake.
* **Next chain plan** (`draft_plan`): chain length = peak-held recent width (decays 8 % per round) capped by `max_t - 1`; confidence
floor = the smallest draft probability whose calibrated acceptance clears `rate * (row slope + chain step ms) / survival`, i.e.
a lower floor when rows are cheap, clamped to `[LELEKA_SPEC_MIN_P_LO, request spec_min_p]` (the operator's value stays the upper
bound; 0 means 0.9). The plan is applied to the MTP actor per round (`set_draft_plan`; the actor's `max_drafts` is set from it).
Verification is untouched. The controller still checks every offered row against the target's own output, commits the accepted
prefix and the bonus token. Sampled requests use the existing sampled verification path unchanged (acceptance is equality with the
sampled target token; the policy only chooses how many rows to offer).
## Knobs
| variable | default | meaning |
| --- | --- | --- |
| `LELEKA_SPEC_ADAPTIVE` | on | `off`: the fixed mode17 window; adaptive = 8-row verifier, MTP chain up to 7 drafts, suffix 3 |
| `LELEKA_SPEC_ADAPTIVE_MAX_T` | 8 | widest window (rows); the Original's constant `kVerifyMaxT` is 8 |
| `LELEKA_SPEC` / `_MTP_MAX_T` / `_SUFFIX` | unset / spec / 3 | the Original's `--spec`, `--mtp-max-t`, `--suffix-draft`; setting `LELEKA_SPEC` selects the fixed window |
| `LELEKA_SPEC_ARMS` | - | `fixed3@0.5,fixed4@0,adaptive@0`: policies one process switches between per request (A/B in one load); `@P` pins the arm's request floor (`spec_min_p`) |
| `LELEKA_SPEC_EXPLORE`, `_MARGIN`, `_MIN_P_LO`, `_DRAFT_STEP_MS`, `_COST_ALPHA`, `_DECAY`, `_BIAS_RATE` | 32, 0.02, 0.10, 0.45, 0.12, 0.995, 0.06 | policy constants |
| `LELEKA_SPEC_STATS=1` | off | one `DBG spec-stats` line per request: rounds, tokens per round, width and accepted histograms, mean ms per width |
| `LELEKA_SPEC_TRACE=1` | off | one `DBG spec-trace` line per timed round (width, source, accepted, round ms, expected tokens, next chain plan) |
| smoke: `@file:PATH` lines in `LELEKA_SMOKE_PROMPTS` | - | a whole file as one prompt (code with its newlines); with `LELEKA_SPEC_ARMS` pass p of prompt i uses arm (p+i) mod arms |
## Wider windows than 6
`kVerifyMaxT = 8` is compiled into the window kernels (`acc[kVerifyMaxT]` register arrays, the grouped-expert `GMAX >= kVerifyMaxT`
static_assert, head and MoE group tables), so 8 rows is the ceiling without kernel changes and a re-seal of the PTX
(sm_120 + sm_86); 12 or 16 rows are not available from this branch. With `--spec 6` equivalent (`LELEKA_SPEC=6`, adaptive) the
verifier records windows 1..8 (one more capture + instantiate than 1..6, about +20 ms per request), the MTP is loaded at 8.
## Results (RTX 5090, driver 595.99, CUDA 13.2, KAR PLE, int8 KV, conversation/prefix caches as noted; 1 model load per job)
Method. All arms of a job run in ONE process (`LELEKA_SPEC_ARMS`): same tier, caches and clocks, the verifier built for the widest arm
(8 rows) for all of them, so the arms differ only in the window policy. Arm order rotates per repetition; 3 repetitions each.
`fixedN@P` is the Original's `--spec N` with `spec_min_p = P` (0.5 = the Original's serve setting, 0 = what the live Codex runs shipped).
Decode tok/s is tokens / verify-loop time (`decode.serve`) for the corpus jobs and `weighted_decode_tok_s` (total tokens / total decode
time) for the replays. Jobs: 9a1, 9a2 (chat + code corpus, 192 new tokens, 10 prompts x 3 repetitions per arm), 9b1-9b3 (real Codex session
replays, `scripts/spec/`, teacher forced to the recorded text, so every arm does identical work).
| workload / tier | fixed3@0.5 | fixed4@0.5 | fixed6@0.5 | fixed4@0 (shipped) | adaptive | adaptive vs fixed4@0.5 (per repetition) |
| --- | --- | --- | --- | --- | --- | --- |
| corpus, static tier 2048 slots (hit ~11 %), job 9a1 | 60.25 | 63.05 | 63.15 | - | **65.06** | +2.5 / +3.1 / +3.9 % |
| corpus, auto tier + adaptation (hit 91-97 %), job 9a2 | 148.34 | 153.18 | 151.12 | - | **155.99** | +5.0 / +0.3 / +0.1 % |
| tic-tac-toe session, requests 0-15 (9-30k ctx), auto tier, job 9b1 | 135.72 | 138.40 | 134.79 | 134.52 | **141.04** | +1.8 / +1.8 / +2.1 % |
| CRM session, requests 0-15 (10-30k ctx), auto tier, prefix cache, job 9b2 | 139.71 | 144.48 | 145.25 | 141.57 | **150.71** | +4.4 / +4.2 / +4.4 % |
| CRM session, requests 56-67 (80-90k ctx), auto tier, job 9b3 | 121.62 | 125.59 | 124.89 | 122.64 | **130.10** | +3.8 / +3.3 / +3.6 % |
Against the shipped live configuration (fixed4@0): +4.9 % (tic-tac-toe), +6.5 % (CRM), +6.1 % (CRM long context). Adaptive is above every fixed arm in every repetition of every
replay; ranges over the three repetitions are under 1 % of the mean.
The gain is small because the cost of a verified row is not small: measured round ms by width (replay 9b1, auto tier): T1 13.0, T2 15.1, T3 18.3,
T4 22.3, T5 26.2, T6 31.2, T7 34.8, T8 38.9 (about 3.6 ms per row, 28 % of the one-row window; with the static 2048-slot tier 10.5 ms per row, 45 %).
A row pays only when the cumulative acceptance of the rows before it times its own exceeds roughly 0.6, so the policy mostly moves the width
between 2 and 4 in uncertain text and to 7-8 in re-emitted code. Width histograms (share of rounds) in 9b2: adaptive T2 26 %, T3 17 %, T4 11 %,
T5 8 %, T6 11 %, T7 8 %, T8 15 % against fixed4@0.5 T4 79 %. Tokens per round: 3.69 (adaptive) / 3.17 (fixed4@0.5) / 3.91 (fixed6) with mean round 24.4 / 21.9 / 26.9 ms.
Policy trace (tic-tac-toe request 4, adaptive, `width:accepted/source`, `LELEKA_SPEC_TRACE=1`): `3:1 2:1 2:0 3:1 2:1 4:0 5:4 5:4 2:1 3:2 2:1 3:1
3:2 3:1 2:1 2:0 4:3 4:2 3:2 5:4 3:2 6:5 5:4 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:7(suffix) 8:1(suffix) 8:5 8:7 8:7 8:2 8:5(suffix) 5:4 5:4 8:7 8:7 8:7
7:6(suffix) 7:1(suffix) 7:5 3:2 7:6 7:6 5:4`: narrow in uncertain code, 8 rows inside a re-emitted block, back to 3 when the match ends.
Draft floor: the policy's computed floor is at its ceiling (0.9 when the request carries 0, otherwise the request's value) in every trace inspected: with 3-4 ms
per row a draft below 0.9 never clears the marginal bar, so "a lower floor when rows are cheap" never triggered on this hardware; the verify-time prefix
choice (calibrated acceptance, not the raw draft probability) does the work that a floor would do. Job 9b5 (adaptive@0.5 / @0.7 / @0) measures the
ceiling; it was not run when this was written.
Exactness. Verification is unchanged and the controller tests (fake target, perfect/poor/failing drafters, suffix on and off) check that the adaptive
window emits exactly the greedy text. On the device (static tier, seed off, adaptation off, 10 prompts, 192 tokens, 3 passes each, compared with the
first fixed4 pass of the same prompt): adaptive identical in 16/30 requests, fixed3 13/30, fixed6 13/30, and fixed4 against its own repeats 15/20; the
differences are the known batch-rounding envelope (a different window width rounds a near tie differently; the first difference is at token 5-170),
not a policy effect: the adaptive arm is no further from fixed4 than fixed3 or fixed6 are. With the auto tier (placement changes with timing):
21/30, 17/30, 19/30 and 11/20. Sampled requests are untouched (acceptance is equality with the sampled target token).
Not feasible / not done: windows beyond 8 rows (`kVerifyMaxT = 8` is compiled into the window kernels); the 100k/180k jobs 9a3/9a4 are void (the
raw-text prompt makes the model stop after two tokens; the replay 9b3 at 80-90k context replaces them); 9b4 (static-tier replay) was skipped by the
queue; the chain-step graphs are captured lazily per request, the policy's deeper chains pay a capture the first time a depth is used in a request.
## Results on the live CRM session (job 9b7) and the profile default
Replay of the first 24 requests of the live Codex CRM session 9e3 (34,443 tokens in every arm, auto expert tier, 3-4 repeats, weighted decode tok/s):
fixed window 4 @ 0.5 (the reference configuration) 148.71 (147.98 / 149.25 / 149.06 / 148.55), adaptive @ 0 **156.26** (+5.1 %; 156.00 / 156.12 / 156.65),
adaptive @ 0.7 154.43 (+3.8 %). On the tic-tac-toe replay (job 9b5) the same arms gave +1.6 % (@0) and +0.9 % (@0.7), and adaptive @ 0.5 was 0.7 % below the
fixed window. `spec_min_p` is the ceiling of the adaptive policy's floor (0 = 0.9), so the `rtx5090-32g` profile now sets `spec_min_p: 0` (the adaptive
window is the default of the serve stack). The speculative controller only chooses window shapes and drafts; the verified tokens are the verifier's, and
window shapes are inside the Original's own envelope in `docs/quality-gate.md` (R3, `--spec 2`).
## Final formal paired A/B (job 9f0, 2026-10-26) and quality gate (job 9q1)
Workload: the live CRM Codex session capture 9e3 (first 24 requests, 34,443 recorded tokens per pass), RTX 5090, binary `rt-final`, expert slots auto, adapt-every 2.
Ten rounds, each a process of arm A and a process of arm B with 3 passes each, interleaved (30 passes per arm).
| Arm | Configuration | passes | weighted decode tok/s (mean) | sd | 95% CI |
|---|---|---|---|---|---|
| A | fixed window 4 at min_p 0.5, no chain kernels | 30 | 148.93 | 0.24 | +-0.08 |
| B | adaptive window (ceiling 0 = 0.9 floor) + `LELEKA_CHAIN=all` | 30 | 166.81 | 0.39 | +-0.14 |
Gain of B over A: **+12.0 %** decode (end-to-end replay of an agent session, not a kernel microbenchmark); the intervals are far apart. TTFT and reprefill were not the
variable of this A/B.
Quality gate on the same binary (9q1, `q_analyze.py`, Original-envelope rule of `docs/quality-gate.md`): P1-final (plain) and P6-final-chain (chain kernels) against the
Original: d_top1 p99 0.216 / 0.223 (tolerance 0.238), flip rate 2.29 % / 2.29 % (tolerance 4.81 %), flip margin max 0.405. The strict rule still reports `top1 max` outside for
both (1.759, one row of prompt p1), as it does for every earlier port arm including the pre-merge static one (P1-static 1.152, P1-merged 1.759): the same row, unchanged by
this work. Chain kernels give the same rows and the same 14 flips as the plain arm. Run-to-run noise of the port itself (job 9n0) is of the same size, so this reads as
"no change against the previous merged state", not as a new pass of the strict envelope.