Archived
docs and harness: the design note, the flag rows, the kv-* scripts
This commit is contained in:
1 parent
5b415b2ef8
commit
b54a80de59
8 files changed
+2299
No files matched your search
+103
@@ -959,6 +959,108 @@ speculation f16 also changes which drafts the greedy text accepts, so one and fo
|
||||
down; whether that is the text or the step was not separated. Use it for many concurrent sequences
|
||||
where the KL above is acceptable, and measure your own load.
|
||||
|
||||
### 4.4.1 Streaming KV: context bigger than the card
|
||||
|
||||
```sh
|
||||
radiance --model flashnext.rad --tp 2 --max-model-len 262144 --max-num-seqs 2 --kv-resident 32768
|
||||
```
|
||||
|
||||
`--kv-resident N` keeps the whole KV cache of the model's sparse attention group in pinned host
|
||||
RAM and only a window of N tokens on the cards. A decode step turns the blocks it selected into
|
||||
window slots, copies in the ones that are missing, and evicts the block whose use counter has decayed
|
||||
most; an evicted block is
|
||||
already safe in the host copy. The window is a fixed size at any context length, so context stops
|
||||
being bounded by VRAM: on two 16 GB cards, holding two 262k-token conversations, the cache went
|
||||
from 3.84 GB of VRAM a card to 0.74 GB of VRAM and 3.22 GB of host RAM. The VRAM the cache gives
|
||||
up goes to the expert slab.
|
||||
|
||||
**How to enable it.** N is tokens of the resident window, rounded up to whole blocks (4 tokens on
|
||||
this family). Absent or `0`, nothing streams.
|
||||
|
||||
- At or above the group's context — `--max-num-seqs` x `--max-model-len` — nothing streams
|
||||
either: the group stays a plain resident pool and the engine takes its ordinary path, with no
|
||||
host copy, no window and no per-step copy.
|
||||
- A ring under one decode step's selection — `n_seq x (1 + n_spec) x 513` blocks, **16 416
|
||||
tokens** at two sequences with 3 speculative tokens — is raised to it at startup, with one
|
||||
warning naming both numbers. **The recommendation is 32 768**; pressure comes from a longer
|
||||
context, never from a smaller ring.
|
||||
- What it takes: the window at the cache's per-token bytes for every layer (6.00 KiB a rank at
|
||||
fp8 on two ranks, so 24 576 tokens is 144 MiB), and the host copy of the whole context at the
|
||||
same per-token bytes, per rank, sized `max_seqs x --max-model-len`. VRAM also holds the
|
||||
prefill stage, one layer of the retained context (512 B a retained token a rank, 200 MiB at
|
||||
2 x 204 800); the pool is the larger of the two, never their sum.
|
||||
- Models: the sparse-selection ones — Qwen3.8-Flash-Next (`qwen4exp_fp8`) and GLM-5.3-Flash
|
||||
(`glm5next`). Anywhere else the flag is **ignored at startup with one warning** and the server
|
||||
runs exactly as without it, every block on the card. A packed cache (`--kv-cache-dtype fp8_v4`
|
||||
or `k6_v4`) has no streamed writer and is warned about the same way.
|
||||
- The startup receipt's `kv streaming:` lines name the window, the stage and the host tier;
|
||||
`/metrics` carries `kv_resident_blocks`, `kv_stream_misses_total` and
|
||||
`kv_stream_bytes_total`.
|
||||
|
||||
**Measured.** One model, fp8 cache, one machine (2x16 GB, gfx1201), one request, two cold starts a
|
||||
configuration, 2 048 tokens decoded:
|
||||
|
||||
| configuration | prompt | decoded | prefill tok/s | tok/step | decode tok/s |
|
||||
|---|---|---|---|---|---|
|
||||
| streaming off | 61 971 | 2 048 | 2 722 | 1.00 | 39.89 |
|
||||
| **streaming on** | 61 971 | 2 048 | **2 783** | 1.00 | 39.78 |
|
||||
| streaming off + MTP | 61 971 | 2 048 | 2 600 | 2.87–3.23 | 62.3 (56.8–67.7) |
|
||||
| **streaming on + MTP** | 61 971 | 2 048 | **2 671** | 3.02–3.45 | 64.8 (53.2–76.5) |
|
||||
| streaming off | 249 939 | 2 048 | 2 635 | 1.00 | 38.60 |
|
||||
| **streaming on** | 249 939 | 2 048 | **2 669** | 1.00 | 39.07 |
|
||||
| streaming off + MTP | 249 939 | 2 048 | 2 577 | 3.10 | 50.56 |
|
||||
| **streaming on + MTP** | 249 939 | 2 048 | **2 623** | 3.10 | 50.86 |
|
||||
|
||||
Speculation's `tok/step` is a property of the text (how predictable the continuation is), so the
|
||||
MTP rows' tok/s moves with it — the 61k pair spans 53-77 tok/s between starts, all of it text and
|
||||
step-time, not configuration. Compare MTP configurations on `tok/step` and ms/step, and read the
|
||||
250k pair, which is stable, when the question is about the engine.
|
||||
|
||||
Decode is unchanged, with and without MTP; prefill is 1.8 % faster at 61k and 1.3 % at 250k,
|
||||
because the VRAM the cache gives up is taken by routed experts. The model those arms ran has a
|
||||
dense cache, which this build refuses the flag on: read the table as what a carved window costs in
|
||||
time, not as a deployment to copy.
|
||||
|
||||
Memory, sized for the same number of tokens on both sides:
|
||||
|
||||
| conversations held | configuration | VRAM a card | host RAM a card |
|
||||
|---|---|---|---|
|
||||
| 2 x 262k (524 288 tokens) | streaming off | 3.84 GB | -- |
|
||||
| 2 x 262k | **streaming on** | **0.74 GB** | **3.22 GB** |
|
||||
|
||||
Measured at TP2 on two 16 GB cards, from the engine's own startup report. Per card the host copy
|
||||
is *smaller* than the VRAM it displaces (3.22 against 3.58 GiB), because each rank keeps only its
|
||||
own slice of the cache.
|
||||
|
||||
**What it costs, and when not to use it.**
|
||||
|
||||
- Per token the two cost the same bytes; the difference is where they live. Streaming is not a
|
||||
way to save memory — at one conversation it costs more than it saves — it is the way to keep
|
||||
the cache when VRAM cannot hold it.
|
||||
- The host copy is per rank and sized `max_seqs x --max-model-len`, so a short request pays the
|
||||
whole reservation.
|
||||
- At `--tp 1` the mirror does not fit beside the weights (6.00 GiB for 2 x 262k): the
|
||||
configuration **refuses to start**. The feature holds conversations a card cannot; it does not
|
||||
shrink one that already fits.
|
||||
- With streaming off the pool cannot fund two 262k sessions (1.79 GiB funds one). That, not
|
||||
throughput, is what it buys.
|
||||
- It is budgeted beside the prefix cache's host tier: at four conversations the two want 9.38 GiB
|
||||
and 4 GiB on a box with 8.2 GiB spare, so the start is refused short by ~1.2 GiB. Lower
|
||||
`--prefix-cache-mib` (4096 today, 2048 is a fine floor); never delete the tier.
|
||||
- Streaming's copies cost about 3% of decode at `--tp 2` with a small context, and 0% at
|
||||
`--tp 1`, where the longer step hides them.
|
||||
- Quality: perplexity 3.994 streaming off, 4.015 with a window covering the context, 4.014 with a
|
||||
window a fraction of it, against a cold-start floor of 0.021 KL — no difference the engine can
|
||||
resolve.
|
||||
|
||||
**Check it on your own machine.** `scripts/kv-parity.sh` proves the covering case: a ring at the
|
||||
group's context streams nothing, issues no resolve and produces byte-identical completions to the
|
||||
same server without the flag. `scripts/kv-stage-parity-64k.sh` proves the streaming case: with
|
||||
the ring at its 32 768-token floor and a ~64k document, every prefill chunk past the ring is
|
||||
staged one layer at a time, in layer order, and the completions are byte-identical to streaming
|
||||
off. Both build nothing, run one server per arm, compare the completions, and need the cards and
|
||||
the toolchain container.
|
||||
|
||||
### 4.5 Prefill chunk size
|
||||
|
||||
A long prompt is prefilled in chunks of at most `--max-num-batched-tokens`. On a mixture-of-experts
|
||||
@@ -1799,6 +1901,7 @@ by 0.002-0.003 nats.
|
||||
| `--state-cache-dtype T` | f32 | `f32` or `f16`: the recurrent (delta-net) state cache; f16 halves the state memory and is lossy, `qwen35` plugins only (§4.4) |
|
||||
| `--attn-prefill-fp8 MODE` | off | `off`, `qk`, `pv` or `both`: the prefill attention's Q·Kᵀ, P·V or both in E4M3 over an `fp8`, `fp8_v4` or `k6_v4` cache; lossy, Qwen3.8-27B (§4.4) |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--kv-resident N` | 0 (off) | tokens of the sparse attention group's KV kept on the card; the rest lives in pinned host memory and is copied in on demand. **The whole switch** — absent or 0 keeps every block on the card, and at or above the group's context it streams nothing either. A value below one decode step's selection — `n_seq x (1 + n_spec) x blocks`, 16 416 tokens at 2 sequences with 3 speculative tokens — is raised to it at startup, so a ring asked for under the floor is not the ring measured. **The recommendation is 32 768**, and eviction pressure is made by a longer context, not by shrinking the ring. Ignored with a warning on an architecture that cannot stream, decided at startup (§4.4.1, [KV-STREAMING.md](KV-STREAMING.md)) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) |
|
||||
| `--embedding-placement WHERE` | ram | `ram` or `vram`: the token embedding pinned in host memory beside `--host-pool-mib` and read in place, or on the card (§4.3) |
|
||||
| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) |
|
||||
|
||||
@@ -0,0 +1,723 @@
|
||||
# KV streaming: host-authoritative KV with a resident VRAM window
|
||||
|
||||
The full context's KV cache lives in pinned host RAM; VRAM holds only the part attention is
|
||||
about to read, and the VRAM that frees up goes to experts. `--max-model-len` sizes the RAM
|
||||
side, `--kv-resident` the VRAM side.
|
||||
|
||||
The design is tied to **sparse selection**: streaming pays only if the bytes a step must read
|
||||
are far smaller than the context. That holds for radiance's indexer-selected attention (the
|
||||
QSA family and GLM-5.3's MLA block) and fails for a dense full-attention layer, where a step
|
||||
reads the whole context and the link is the wall (§2). A dense model is refused by name.
|
||||
|
||||
Two views sit over one allocation: the **ring**, `n_slots` blocks deep and `n_layers` stripes,
|
||||
addressed through a residency map; and the **stage**, the group's context deep, one stripe,
|
||||
addressed by block id. The allocation is `max(ring, stage)`, never the sum (§3.1, §4.1), and a
|
||||
pass's view follows from its phase and row shape, so it is in the pass key, not a runtime mode.
|
||||
|
||||
The operator's view is [GUIDE.md](GUIDE.md) §4.4.1. Section numbers here are load-bearing
|
||||
(source comments cite them): §5.1 answers "§5 Phase 1" and "§5 Phase 4", §5.2 "§5 Phase 4",
|
||||
§5.3 "§5 Phase 3".
|
||||
|
||||
---
|
||||
|
||||
## 1. The tier that exists, and why it is not the stream
|
||||
|
||||
The VRAM paged pool (`core/mem/kv.{h,cpp}`) is the only place a live sequence's KV ever lives.
|
||||
The idle tiers (`core/mem/kvtier.*`, `core/runtime/tierexec.*`) copy a *finished* conversation's
|
||||
blocks to pinned host RAM and back on a prefix-cache hit: a **hot cache, not a stream**, whose unit
|
||||
is one published prefix entry (`plan_writeback`, `tierexec.h:22-25`), which fires on publish and
|
||||
admission rather than inside a request (`engine.cpp:1214`, `:1292`), moves bytes between identical
|
||||
layouts (`tierexec.cpp:326`, `:458`), and lives in `RAD_MEM_HOST_PINNED` memory (`hostarena.cpp:16`)
|
||||
no kernel may dereference (`mem/kv.h:381`). Streaming needs tens of thousands of small, per-launch,
|
||||
selection-driven copies a second with a residency map, so **do not extend the tier**; carry over
|
||||
only its two rules (never block the host on the step path; order copies with events, not syncs —
|
||||
`spec.md` §5.4).
|
||||
|
||||
---
|
||||
|
||||
## 2. What bounds a step's read
|
||||
|
||||
Per rank at `--tp 2`, fp8 KV (`docs/QSA.md:54-59`, `docs/GUIDE.md:718-725`).
|
||||
Qwen3.8-Flash-Next (`arch/qwen4exp_fp8`) has 12 QSA layers plus the MTP head, so 13 layers bind
|
||||
to `kv_attn`:
|
||||
|
||||
| group | per 4-token block | per token | at 262 144 tokens |
|
||||
|---|---|---|---|
|
||||
| `kv_attn` (fp8, 2 kv heads, head_dim 256, 13 layers) | 26.00 KiB | 6.50 KiB | 1.66 GiB |
|
||||
| `kv_qsa_bkey` (bf16, 1 head, head_dim 16) | 3.25 KiB | 0.83 KiB | 208 MiB |
|
||||
|
||||
Decode is sparse at every context: `sparse` is forced on by `T == batch->n_seq`
|
||||
(`rad_block_attn_gated_fp8.h:535-536`) and the selection keeps `topk = budget / ratio = 512` blocks
|
||||
(`docs/QSA.md:36-38`), so a step reads 2048 tokens, 13 MiB across 13 layers, plus the partial tail
|
||||
block — essentially free at 30 tok/s. The indexer is the catch: `qsa_score` walks **every complete
|
||||
block** of the live history each step, bounded only by `nc` (`r4d_qsa_score_bf16.hip:51-60`) — 208
|
||||
MiB a step at 262K, ~6 GB/s — so `kv_qsa_bkey` stays resident and cannot candidate for a ring
|
||||
(`dense_read`, §3.1).
|
||||
|
||||
A dense family (Qwen3.8-27B, `arch/qwen35_*`) reads the whole context every step — 16 KiB a
|
||||
token per rank at fp8, 120 GB/s at 30 tok/s at 262K — so the ring only subtracts from that read:
|
||||
break-even is roughly `resident + 65k` tokens at 30 tok/s. A dense model declares no streamed
|
||||
path, so `--kv-resident` is warned about and ignored by name and the group stays fully resident
|
||||
(§4.5).
|
||||
|
||||
---
|
||||
|
||||
## 3. The contracts
|
||||
|
||||
### 3.1 One id space, two depths
|
||||
|
||||
The paged pool is dense and **block-id indexed**, layer-major:
|
||||
|
||||
```
|
||||
layer i at base + i * layer_stride, layer_stride = n_blocks * layer_bytes_per_block
|
||||
block b at block_index * layer_bytes_per_block (core/mem/kv.h:92-108)
|
||||
```
|
||||
|
||||
`slot()` is `block_table[bi] * block_size + pos % block_size` (`core/sched/mem_iface.h:226-231`)
|
||||
— no indirection anywhere, and the kernels bound only by the carve (`tierexec.h:122-123`). A
|
||||
block id outside `[0, n_blocks)` corrupts the next layer, silently, with fluent text.
|
||||
|
||||
`KVGroupPlan` therefore carries two depths: `n_blocks`, the logical id space (the context),
|
||||
which the manager, the refcounts, the block table, the prefix cache and every `id < n_blocks`
|
||||
guard count; and `n_slots`, the blocks the device pool backs. `pool_blocks()` is
|
||||
`n_slots ? n_slots : n_blocks`, `streamed()` is `paged() && n_slots > 0 && n_slots < n_blocks`
|
||||
(`core/mem/kv.h:175-182`), and `layer_stride()` uses `n_slots`. Only *addressing* moves.
|
||||
|
||||
Every site that must know the split — the places where `n_blocks` was the address bound — is the
|
||||
same list that carry the arithmetic today:
|
||||
`layer_stride()`/`layer_bytes_per_block()` (`kv.h:106-108`), the refcount/free-list sized by the
|
||||
carve (`kv.cpp:449-471`), the loan strip offset (`engine_bringup.cpp:3345-3350`), the kernel shape
|
||||
and tier `GroupInfo` (`kvbind.cpp:36`, `tierexec.cpp:183`), `ceiling()`/`paged_split()` and
|
||||
`VramFacts` (`kv.cpp:266`, `:300`, `:349`; `vram_budget.h:69-78`), and the `id < n_blocks` guards,
|
||||
which stay valid because the *carve* is no longer their bound.
|
||||
|
||||
The pool is **one reservation of `max(ring, stage)`**, not the sum: the stage is one layer of
|
||||
the context, so it sets the price and the ring fits inside it above ~24k of context. The count
|
||||
is `kv_pool_bytes(plan, slots)`, the ceiling sums `kv_ceiling_bytes(plan, blocks, slots)`, and
|
||||
`carve()` writes `n_blocks`, `n_slots` and `depth` together (`kvstream_apply`). A streamed plan
|
||||
whose host copy or residency map is missing is refused with `RAD_E_INVAL` rather than handing
|
||||
out ids the pool cannot address.
|
||||
|
||||
A streamed group takes its id space from the context
|
||||
(`kv_context_blocks(block_size, max_ctx, max_seqs)`) instead of the pool split, so it stops
|
||||
competing for VRAM; its device share is its resident window, fixed by `--kv-resident`.
|
||||
`lendable()` is false for it (`kv.cpp:968-976`) and the tier must not gather it (§4.1).
|
||||
Refusals, each by name so an operator tunes the right flag:
|
||||
|
||||
- **a resident window that does not fit the budget** is refused against `--kv-resident` before
|
||||
anything is split: a window that silently ate the split would leave a neighbour with zero
|
||||
blocks and be reported as a pool too small (`kvstream_window_fit`).
|
||||
- **a streamed `RAD_KV_WINDOW` group**, because a window group already bounds its own history.
|
||||
- **the dense-read floor.** A group a step reads over its whole live history (an indexer's
|
||||
block keys; `rad_kv_group_dense_read`) cannot stream, and while a sibling streams its carve
|
||||
is `max_seqs` full contexts, not the split's shared token count (`kvstream_dense`,
|
||||
`kvstream_dense_blocks`): the mirror beside it is sized for `max_seqs` sequences, so an
|
||||
indexer funded for one would make the advertised capacity a promise the engine cannot keep.
|
||||
With nothing streaming the floor is false — that configuration deliberately sizes the cache
|
||||
for one full-length sequence, and charging it there would take the experts' VRAM for capacity
|
||||
nothing uses.
|
||||
- **the maps are charged before the pool is sized.** They are reserved from the KV pool before
|
||||
`carve()`, but the budget probe that sizes `vram_kv` has no pool to reserve them from;
|
||||
`kvstream_maps_charged()` takes them out of the paged split in both paths and `carve_into()`
|
||||
adds back what `alloc_stream()` already reserved.
|
||||
|
||||
A ring that covers the group's context (`ceil(max_seqs * max_ctx / block_size) <= ring_blocks`)
|
||||
is **not a streamed group**: no mirror, no maps, no stage, no `kv_resolve`, a null
|
||||
`RadKVStream`. The base engine's path exactly, decided at startup before the first token.
|
||||
|
||||
### 3.2 The host mirror
|
||||
|
||||
`HostArena` is slot-per-entry and `RAD_MEM_HOST_PINNED`, copy-only. Streaming needs a
|
||||
**layer-major, block-indexed mirror in `RAD_MEM_HOST_MAPPED`**, so a device kernel reads it over
|
||||
the link in place — the property the host pool, the activation arena, the token embedding and
|
||||
the n-gram table already rely on (`core/mem/pools.cpp:218-227`, `ctx.cpp:164-180`,
|
||||
`planner.cpp:938-955`).
|
||||
|
||||
The layout is the pool's: a layer's mirror is a dense run of `blocks` rows of `block_bytes`,
|
||||
`host_layer_stride = blocks * block_bytes`, so layer `l`'s row for block `b` is
|
||||
`host + l * host_layer_stride + b * block_bytes`. `block_bytes` is both the `kv_resolve` row
|
||||
pitch and the length of every copy into the ring. The mirror is `n_blocks * bytes_per_block`,
|
||||
zeroed at bring-up, so a block no store has written reads as a miss. It is kept **per rank**,
|
||||
each with its own maps in its own pool (`kvstream_step_view`, `per_rank`). Every existing
|
||||
reader of the mapped property is read-only; this is the first in-place *writer* of host memory
|
||||
of a size that matters, so its coherence is pinned by a test, not assumed (§6.2).
|
||||
|
||||
### 3.3 The writer maintains both copies
|
||||
|
||||
`kv_store` and `qk_norm_rope_gate_kv_store` write the pool at `slot_mapping[i]` and nothing else
|
||||
(`libr4d/r4d_rows.cpp:1913-1931`; `r4d_model_bf16.hip:505-516`). `kv_store_streamed`, and its
|
||||
folded form `qk_norm_rope_gate_kv_store_streamed`, writes **the host mirror always** and the
|
||||
resident slot **only when `res[block] >= 0`**, with the mirror and the map as extra operands. A
|
||||
slot never goes stale, so nothing needs invalidating — not on a rejected draft, not on a
|
||||
restore.
|
||||
|
||||
The residency test is in the writer, not only in the resolve, because at decode the block a
|
||||
step writes is usually the block the previous step made resident: a writer that only wrote the
|
||||
mirror would leave the ring's copy missing this step's tokens, and the resolve, finding the
|
||||
block resident, would not copy it. The alternative — mirror only, and the resolve copies every
|
||||
block it needs, tail page included — needs no predicate, but the resolve cannot tell which
|
||||
entry is the partial page (the last is partial only when `(pos + 1) % ratio != 0`), so it would
|
||||
re-copy every selected block or take a new operand to find the tail. The test is one compare
|
||||
on a hot path, not a race: `res` is written by `kv_resolve` alone and only read here.
|
||||
|
||||
A layer's order is **store, then resolve, then attention**. The indexer cannot resolve: it runs
|
||||
before the store, so a non-resident tail block would be copied short of the tokens just written
|
||||
(`arch/common/rad_qsa.h`). The streamed store has rows for E4M3 and bf16 only; any other core
|
||||
dtype is refused, and a packed cache (`fp8_v4`, `k6_v4`) declares no streamed store for its
|
||||
layout and is warned about and ignored (§4.5).
|
||||
|
||||
### 3.4 The resolve
|
||||
|
||||
`qsa_select` **already dereferences the attention table**: it writes `sel[q][i] = tb[b]`, the
|
||||
group's pool page id (`r4d_qsa_select_bf16.hip:254`, `:686`), and `attn_paged` uses each entry
|
||||
as a raw pool page index with no bounds check (`r4d_attn_decode_h256_gqa6.hip:268-272`). `sel`
|
||||
is the only place the sparse path names KV storage, so one op between select and attention
|
||||
suffices.
|
||||
|
||||
`kv_resolve` (`libr4d/r4d_kv_resolve.hip`) reads `sel`, `nsel`, `res`, `slot_*`, `ctl`, the
|
||||
host base and the pool, claims a free slot or a CLOCK victim, copies each miss and rewrites
|
||||
`sel`. Those eight operands are in read order, the cache last as in `kv_store`; `M`, `blocks`,
|
||||
`slots`, `sel_pitch` and `block_bytes` are parameters, and the unit is `block_bytes` rather
|
||||
than `block_size` because the op moves bytes and never reads an element. The miss list is
|
||||
scratch, not an operand: an operand would enter the arena planner, the recorded pass's ranges
|
||||
and the tape key for bytes nothing outside one launch reads.
|
||||
|
||||
**The order is the contract, and it is a total order:**
|
||||
|
||||
1. bump the epoch (`ctl[0] + 1`);
|
||||
2. one lookup per entry below `nsel[q]`: a hit takes the epoch and, the first time this call
|
||||
stamps the slot, bumps its two-bit heat counter (clamped at 3) — one bump a slot a call, not
|
||||
one an entry; a miss claims its map entry once (`-1 -> -2`), so the map is its own set;
|
||||
3. the **miss list is in ascending block id**, never first-appearance order;
|
||||
4. one victim per miss, in that order: identity (block `b` into slot `b` when that slot is
|
||||
free), then a free slot, then a CLOCK sweep where a slot stamped with this call's epoch is
|
||||
passed, a warm slot is halved and passed, and a cold slot is taken. The hand picks the
|
||||
victim — a per-visit decision, so no reduction, no barrier, no extra traffic; an exact LRU
|
||||
would need a collective minimum per miss;
|
||||
5. re-point both maps, a placement counting as a use;
|
||||
6. copy `block_bytes` from `host[b]` into the pool's slot, as bytes: a streamed block is
|
||||
bit-identical to the block the writer put in the mirror;
|
||||
7. rewrite every entry below `nsel[q]` as its slot; the `-1` padding past it stays.
|
||||
|
||||
Step 3 is what makes the resolve **deterministic — the same blocks in the same slots for the
|
||||
same inputs**. Without it a block claimed by row 3 could evict a different slot depending on
|
||||
which thread got there first, and two implementations of one contract would produce different
|
||||
`sel`. Ascending is a fact about the claim set, not about the map, so a device implementation
|
||||
sorts the claim list itself (the kernel's `atomicCAS` is the distinct-claim count; the
|
||||
compaction scan fixes the order) and never scans `blocks`, which would make a launch's cost
|
||||
depend on the cache instead of on the selection. The kernel keeps the value it read per entry,
|
||||
so `res` is read once a selection entry.
|
||||
|
||||
**Overflow.** The ring must hold the union of the call's selection (`hits + misses <= slots`).
|
||||
When it cannot, unplaced claims revert to `-1`, `ctl[3]` latches, and those entries are rewritten to
|
||||
**slot 0** — defined memory holding a real block's KV, so the step produces wrong numbers rather
|
||||
than a fault, since a block id there would be an address past the ring that `attn_paged`
|
||||
dereferences unchecked. The engine reads `ctl` (one 64-byte copy a group a step, behind the step's
|
||||
last resolve and before the step-end event, so the step path never waits) and **fails every request
|
||||
that was prefilling in the step** with the ring's size and the union that did not fit, then clears
|
||||
the latch so the next request is measured on its own. No step is served from a table whose entries
|
||||
do not name their blocks.
|
||||
|
||||
**State, concurrency, recording.** The epoch, hand, heat counters and counters live between
|
||||
calls, so two launches must never overlap: the row is not in `rad_kernel_concurrent`'s stateful
|
||||
prefix and the engine orders it. Stateful is not unrecordable: the op is a pure function of
|
||||
device-resident state whose addresses and pitches never change after bring-up, so a recorded
|
||||
pass replays it correctly. The map is per rank and the block ids are shared, so ranks resolve
|
||||
the same shared ids through maps brought up identically and one rank's counters are every
|
||||
rank's; each rank names its own view, and a follower that inherited its peer's maps took a
|
||||
page-not-present fault on its first staged pass.
|
||||
|
||||
**The tape key.** `Ctx::pass_key` mixes `phase`, `n_tok`, `n_seq`, `n_spec`, `block_table` and its
|
||||
pitch, `slot_mapping`, `seqused` and `kvstream_view_key` (`ctx.cpp:919-971`).
|
||||
`kvstream_view_key` is the memory a kernel reads, not the address of the struct that carries it: the
|
||||
batch's view is a copy in a rotating builder Out slot, so keying on `&view` made every streamed step
|
||||
a pass the tape store had never seen, and the 24-tape LRU dropped each one long before replay.
|
||||
Rewriting the maps' contents is fine; changing a pointer or a pitch is not. A view is fixed from
|
||||
bring-up.
|
||||
|
||||
**Three implementations, one contract.** `libref/ref_kvstream.cpp` is the serial definition —
|
||||
one pass over the entries, one sorted miss list, one second-chance walk, one memcpy a miss, one
|
||||
rewrite — and is the oracle. `libavx/avx_kvstream.cpp` follows it line by line: the same
|
||||
refusals in the same order, the same epoch, ascending order and victim from the same sweep, so
|
||||
the same blocks land in the same slots; it vectorises the rewrite and the block copy only,
|
||||
because the lookup, the claim gather and the sweep are serial by construction.
|
||||
`libr4d/r4d_kv_resolve.hip` is the card's row, and `r4d_selftest --case kv_resolve` compares it
|
||||
against the libref oracle case by case: hits, ascending misses, eviction, free-before-live,
|
||||
second chance, saturation, overflow, 2052 claims, a whole block byte for byte, and the refusals.
|
||||
|
||||
### 3.5 Prefill: the union, and the stage
|
||||
|
||||
Above `qsa_exact_to = budget + ratio - 1 = 2051` (`qwen4exp_fp8.cpp:621-624`, `:1085`) prefill
|
||||
is **per-query sparse**: every row of a chunk selects its own 512 blocks
|
||||
(`rad_block_attn_gated_fp8.h:523-536`, `:582-594`; `docs/QSA.md:140-148`). What one launch's
|
||||
union is (`scripts/kv-union.sh`, Flash-Next `--tp 2`, one request a context, ring raised until
|
||||
no launch overflowed):
|
||||
|
||||
| prompt tokens | ring that held | resolves | largest union | largest 1-call misses | prefill |
|
||||
|---|---|---|---|---|---|
|
||||
| 3 958 | 2 048 blocks | 108 | **990** | 976 | 1.83 s |
|
||||
| 16 048 | 4 096 | 180 | **4 000** | 1 024 | 6.10 s |
|
||||
| 66 131 | 16 384 | 480 | **14 608** | 1 024 | 25.29 s |
|
||||
| 133 331 | 32 768 | 864 | **23 429** | 1 024 | 52.93 s |
|
||||
|
||||
The union is **70-100% of the live history and grows with it** — it does not flatten, so no fixed
|
||||
"a few times bigger" ring serves long prefill. Decode never exceeds 513 blocks, and a decode-sized
|
||||
ring overflows in prefill: 2 560 blocks at 16k into a 2 048-block ring, 16 542 at 128k into 16 384.
|
||||
The stage is the answer: **one layer's whole history** in an identity-layout buffer, so prefill needs
|
||||
no selection awareness and its pool is a single layer deep. At 262K, fp8, TP2 that is 128 MiB a
|
||||
layer, 1.66 GiB of PCIe per 5120-token chunk against ~8.7 s of compute — under 1%.
|
||||
|
||||
**Dense prefill is a separate hole.** A prompt below `qsa_exact_to` runs dense `attn_paged`,
|
||||
which reads a block id straight out of the block table and never resolves, while
|
||||
`kv_store_streamed` writes the ring only for resident blocks. A streamed group therefore cannot
|
||||
serve a dense prefill at all: a 1 015-token prompt into a 1 024-block ring is refused rather
|
||||
than producing wrong text. Any ring smaller than the context must refuse that case explicitly
|
||||
until it is handled.
|
||||
|
||||
### 3.5.1 The aliased stage: verified, and the ordering rule
|
||||
|
||||
`tests/runtime_test.cpp` (`a_streamed_groups_layers_may_all_alias_one_pool_slot`: 13 layers, a
|
||||
pool one `layer_stride` deep, every bound layer's slot 0, 187 checks) pins the premise.
|
||||
|
||||
**The operand resolution accepts it.** `RAD_OPK_KV` looks the absolute layer up in
|
||||
`KVPoolBinding::layer_slot` and takes `off = layer * layer_stride`, bounded only by
|
||||
`off + layer_stride <= bytes` (`issue.cpp:781-789`) — which a one-layer pool satisfies at `off = 0`
|
||||
for all 13 layers. An *identity* table over the same pool is refused ("outside the ... bytes it was
|
||||
allocated"), which is that bound and not a layer-distinctness check, and `bind_kv_pools` only
|
||||
*produces* a positional table (`kvbind.cpp:21-25`). Both are tested.
|
||||
|
||||
**`layer_slot` cannot carry the aliasing.** The same table is the host mirror's row number:
|
||||
`rad_kv_layer_index` (`issue.cpp:1223-1228`) is what `kv_stream_host` indexes with
|
||||
(`rad_arch.h:1028-1032`), and `kv_store_streamed` and `kv_resolve` both take that pointer
|
||||
(`rad_block_attn_gated_fp8.h:527`, `:633`), so mapping every layer to 0 would write all 13 layers'
|
||||
KV into layer 0's mirror row. Aliasing is a **field on the binding**, the stage's depth (0 =
|
||||
`n_layers`, 1 = every layer at offset 0), with `layer_slot` left alone.
|
||||
|
||||
**The carve is `n_layers` deep, not one.** `bytes_per_block` covers every bound layer by
|
||||
declaration (`rad_builder.cpp:2094-2098`), so `pool_blocks() * bytes_per_block` is 13 layer
|
||||
stripes (`kv.cpp:713`, `:1093`, `ceiling()` at `:266`). A one-layer group divides that
|
||||
multiplication by its depth — one function, and the page definition does not move.
|
||||
|
||||
**Ordering: the hazard analysis does not protect it, and does not have to.** The KV operand is
|
||||
external memory, not a `Program::buffers` entry, so the buffer plan's aliasing analysis never
|
||||
sees it (`rad_bufplan.cpp` colours declared activations only). Two things do: **one stream, in
|
||||
issue order** — store, stage and attention of a layer are separate dispatches on the batch's
|
||||
compute stream, and a stream is a total order, so a layer's stage copy sits between the
|
||||
previous layer's attention and this one's (`rad_block_attn_gated_fp8.h:620-626`: "it sits on
|
||||
one stream: issue order is the ordering"); and **`haz_mark`, as a relaxation check only** — it
|
||||
does see a KV operand (`haz_note` builds ranges from the issued tensors, and a KV operand
|
||||
arrives as a real pointer whose span is exactly one layer's bytes,
|
||||
`issue.cpp:1078-1091`), and with every layer aliased that is the *same* range for all of them,
|
||||
so a stage declared as writing it conflicts with the previous layer's attention read and the
|
||||
pair is never marked overlap (`ctx.cpp:1084-1093`). The worst case left is read-read between
|
||||
two layers' attentions, harmless because a write lies between them — `kv_resolve` is not a
|
||||
`rad_kernel_concurrent` row (`r4d_rows.cpp:8852-8862`) and a ranged copy is a dispatch no op
|
||||
owns. Do not weaken it. What breaks it, in the order it is likely to happen:
|
||||
|
||||
- **the ride taken before all of L's attention launches:** a prefill layer's attention is
|
||||
issued in `qsa_gq_rows`-wide chunks, so a ride taken at the first chunk starts L+1's copy
|
||||
while the second chunk still reads the stage. Hence the seam after the loop, not in
|
||||
`resolve_sel`.
|
||||
- **waiting after the layer's store:** the copy reads the mirror, which the store has not
|
||||
written yet, so it would put older bytes back over this chunk's tokens.
|
||||
- **`pieces` and lane 1:** `mix_ar_piece` runs on lane 1 (`qwen4exp_fp8.cpp:1424-1428`) while
|
||||
lane 0 keeps issuing this layer's rows; a stage moved to lane 1 needs `rad_lane_join(1, 0)`
|
||||
before its reader.
|
||||
- **a host-side stage:** a copy re-issued per play (`xprefetch.cpp:275-291`) rests its order on
|
||||
`cur_stream()` and the `kTapeHost` join (`ctx.cpp:1187-1199`), not on the layer's place in the
|
||||
pass. `Ctx::tape_kv_stage` re-runs the arm and the submit with the tape paused instead.
|
||||
- **a sliced KV operand:** `issue.cpp:807` overwrites `shape[0]` with `o.rows`, narrowing an op's
|
||||
hazard range — true for an identity pool, a lie for an aliased one. No op does this today.
|
||||
- **a binding that moves:** `KVPoolBinding` is not in the pass key, so a changed binding between two
|
||||
passes sharing a key would replay against the wrong addresses; depth and ring are fixed views
|
||||
from bring-up, and the phase is in the key (`b->phase`, `ctx.cpp:929`).
|
||||
|
||||
The rule beside the code: **the stage copy is issued on the compute stream, or a DMA list the
|
||||
compute stream waits on, inside the layer, between the store and the attention.**
|
||||
|
||||
**What a staged pass is.** It needs no residency map and no resolve: `sel` already holds block
|
||||
ids, and a context-deep identity stage addresses a block by its id, so the pass fills the stage
|
||||
instead of resolving. That covers prefill rows *and* the decode rows a mixed chunk carries.
|
||||
**A staged pass therefore addresses the pool by block id, so the store writes the device copy on
|
||||
that pass too**: the "ring" operand `kv_store_streamed` writes *is* the stage view (same op, same
|
||||
operands, the pass's binding), and its resident-slot write is redundant but in bounds and
|
||||
harmless — which is why there is no third store variant. The ring then drops back to what decode
|
||||
needs (`max_seqs x (topk + 1)`).
|
||||
|
||||
**Volume, and the one way this path can be silently wrong.** The copy moves the mirror row up
|
||||
to the highest block id the coming attention can read, not the whole row: `n_blocks *
|
||||
block_bytes` is the context allocation. `stage_live_bytes` (`kvstream_bound_live`, once a
|
||||
released batch, ranks parked, after the step's blocks are ensured) is an **upper bound** on the
|
||||
ids the pass can name, and an underestimate is not a crash — the attention would read bytes the
|
||||
copy never moved and produce fluent wrong text. It cannot be too small: every id a block table
|
||||
can hold came out of the group's allocator and is held; `KVManager::held_top_blocks` is one
|
||||
bucket past the highest held block, updated on every acquisition and on the last release; and
|
||||
the stage is identity-addressed from block 0, so `[0, bound)` covers every id below it whether
|
||||
or not ids are dense. Ascending allocation is **not** assumed — a prefix-cache-retained block or
|
||||
a restore's `reserve_specific_block` can leave a live block above a free one — hence the
|
||||
allocator's high-water mark and not `ceil(end / block_size)`. It costs the group's whole held
|
||||
set; a group with nothing held stages the whole row, which is always correct.
|
||||
|
||||
### 3.6 The ABI surface
|
||||
|
||||
`RadKVStream` (`abi/rad_runtime.h:46-77`) is one group's fixed view: the pinned mirror, the
|
||||
per-layer residency maps (`res`: block -> slot or -1; `slot_block`: slot -> block or -1;
|
||||
`slot_state`: epoch and heat; one slice a layer), the shared control block, `block_bytes`,
|
||||
`host_layer_stride`, the ring's `slots` and `host_bytes`. Nothing in it changes address for the
|
||||
engine's life, which lets a recorded pass replay a resolve. Resident
|
||||
per layer, not per group, because the resolve copies one layer's bytes.
|
||||
|
||||
`RadKVGroupBatch` gains one trailing, zero-defaulted `const RadKVStream* stream` (`:79-97`).
|
||||
Null means fully resident: no ring, no map, no host copy. A pointer rather than fields because
|
||||
the data is per group and fixed at bring-up while the batch is rebuilt every step for every
|
||||
rank; one trailing pointer keeps every field a non-streaming plugin reads at its old offset.
|
||||
The build side: `RadBuildCtx::kv_resident_blocks` (`--kv-resident`, in blocks, so the builder
|
||||
needs no block size) and `RadBuildCtx::kv_stream_ok` (the architecture's capability, carried to
|
||||
the declare); `RadArchProbe::kv_stream_ok` states it once (`abi/rad_builder.h:1381-1387`).
|
||||
|
||||
ABI history: `RAD_ABI_VERSION 26` adds the batch's trailing pointer, `kv_resident_blocks` and
|
||||
`kv_stream_ok` — every earlier field keeps its offset, the structs grow, so out-of-tree plugins
|
||||
must be rebuilt. `kv_stream_ok` reached `RadArchProbe` in 28; 29 moved `control_vector_ok` to
|
||||
80 because upstream had taken the offset `kv_stream_ok` used, and the version is `29u` today
|
||||
(`abi/rad_abi.h:20-43`). A field, a retype or a reorder needs a bump; an op or a function does
|
||||
not — `rad_kv_stage_layer` (`abi/rad_runtime.h:768`) and
|
||||
`rad_kv_stage_wait`/`rad_kv_stage_next` (`arch/common/rad_arch.h`, with the inline
|
||||
`kv_stage_*` wrappers an arch plugin calls) move no version.
|
||||
|
||||
### 3.7 Flags, report, metrics
|
||||
|
||||
Flags are declared once in `core/config.cpp:45` and shown in `kShow[]` at `:989`, with sync tests
|
||||
(`config_test.cpp:396-560`, `diag_test.cpp:534-552`) that fail by name when either half is missing.
|
||||
`--kv-resident N` is the whole switch. The KV report (`kv.cpp:509-531`) gains the streamed group's
|
||||
two-tier line, and the receipt names the ring, the stage, the host tier and, when nothing streams,
|
||||
which group's context the flag covers. Metrics: `radiance:kv_resident_blocks`,
|
||||
`radiance:kv_stream_misses_total`, `radiance:kv_stream_bytes_total` (`metrics.cpp:267-280`),
|
||||
`kv_util` unchanged. The per-request line carries cumulative resolves, lookups, misses, the ring's
|
||||
depth and the measured maxima (`ctl[10..12]`).
|
||||
|
||||
### 3.8 The host-RAM budget and the gate
|
||||
|
||||
The mirror is the largest host allocation after the experts' pool: up to 4.69 GiB a rank at the
|
||||
four-sequence target, 9.38 GiB over two. `kvstream_host_gate` checks it once, before any rank takes
|
||||
it, against everything still to be pinned after it (the prefix cache's host tier, the activation
|
||||
arenas, the checkpoint store when fixed) plus `--host-headroom-mib`, and a refusal names this tier
|
||||
and the flag that started streaming, not `--host-pool-mib`: that pool holds experts and shrinking it
|
||||
cannot make room here.
|
||||
|
||||
The prefix cache's host tier **stays** — it holds finished conversations while the mirror holds
|
||||
live ones — and the mirror is budgeted alongside it:
|
||||
|
||||
kv streaming: the host mirror for 2 streamed KV group(s) is up to 4.69 GiB a rank (9.38 GiB
|
||||
over 2) ... and this wants 9.38 GiB with 4.00 GiB to spare (--host-headroom-mib)
|
||||
|
||||
At the target the gate had 8.2 GiB spare (16.18 GiB of `MemAvailable`, less 4.02 GiB still to
|
||||
allocate, less the 4.00 GiB headroom), so that configuration is refused, short by ~1.2 GiB; with
|
||||
`--prefix-cache-mib 2048` it serves, leaving 4.48 GiB `MemAvailable` and 1.07 GiB `MemFree`. The
|
||||
lever is that flag — lowering the prefix tier, never deleting it. The resident indexer is sized
|
||||
from the same `vram_kv` the streamed group no longer spends: **51 280 blocks = 205 120 tokens**,
|
||||
above the 51 200 / 204 800 one `--max-model-len` conversation needs, so the per-conversation cap is
|
||||
the advertised 204 800.
|
||||
|
||||
### 3.9 What it costs
|
||||
|
||||
Two floors bound `--kv-resident`:
|
||||
|
||||
- **Correctness floor**: the largest block union one decode launch selects, 513 blocks (2052
|
||||
tokens) at 16k, 64k and 160k of history. A ring under it is **raised to it** at startup, with
|
||||
one warning naming both numbers, because a request under it cannot be served from the selection
|
||||
table. Under speculation it is `max_seqs x (1 + n_spec) x 513` — **16 416 tokens at 2 sequences
|
||||
and spec 3** — so an 8 192-token request under speculation becomes a 16k ring, and any "8k"
|
||||
label on such an arm is wrong.
|
||||
- **Performance floor**: the 24 576 default. The reference implementation measured
|
||||
10 x 2048 = 20 480 cells as the point a smaller ring starts costing, and the decode union is
|
||||
four times smaller, so sizing from the union alone lands under it: at 64k of history 24 576 runs
|
||||
**37.9 tok/s with 81 908 misses**, 8 192 runs **37.1 with 143 071**, and a ring larger than the
|
||||
history buys nothing (49 152 at 160k: 36.97 against 24 576's 36.94, 15% fewer misses). Only the
|
||||
overflow check is a hard requirement. **Run 32 768** (8 192 blocks): above the decode selection
|
||||
and well under a 64k context. Starvation is done by the context, never by shrinking the ring —
|
||||
a shorter ring is a configuration the engine raises or that no operator deploys.
|
||||
|
||||
A marginal miss is **~0.72-0.83 us** and `kv_resolve`'s per-call cost is **flat across a 6x range
|
||||
of slot counts**, so ring size is nearly free; the gap is the miss copies. A decode launch body is
|
||||
**~4.0 us of device time** (~48 us of a 27 ms step, ~0.2%), and the twelve cannot be merged (L's
|
||||
resolve follows L's store and precedes L's attention), so streaming costs **~3% of decode at
|
||||
`--tp 2` and 0% at `--tp 1`**. Placement is the lever that pays: putting block `b` in slot `b`
|
||||
when that slot is free makes the attention's 513-block gather walk memory in order (**+2.03%** at
|
||||
16k, identical misses and bytes; at depth the ids exceed the slot space and the first-free-then-
|
||||
CLOCK path applies, +0.26%, inside the spread). With it, streaming at 16k is **-3.0% against
|
||||
resident** (39.92 against 38.72 tok/s). Do not warm the ring: the fill is cheap (~1.6 us a cold
|
||||
miss against 0.83 warm), but filling it from the last prefill chunk made decode 3.8% slower
|
||||
(36.7 against 38.25 tok/s at 16k, identical bytes) — slot order, not the copies.
|
||||
|
||||
**Capacity is bought in host RAM.** Measured at `--kv-resident 24576` (6 144 blocks of 24.00 KiB,
|
||||
one block being 4 tokens over 12 layers), per rank, Flash-Next fp8 on two ranks,
|
||||
`--max-num-seqs 2 --max-model-len 204800` (409 600 tokens retained) and the four-sequence target
|
||||
(819 200 retained):
|
||||
|
||||
| configuration | VRAM KV per card | host RAM per rank |
|
||||
|---|---|---|
|
||||
| streaming off, 2 x 204800 | 1.43 GiB `vram_kv`, 1.0 session retained | - |
|
||||
| streaming off, 4 x 204800 | 1.53 GiB `vram_kv`, 204 648 tokens of 819 200 (25%, 1.0 session) | - |
|
||||
| streamed, 2 x 204800 | ring 144 MiB + stage 200 MiB (pool = max = 200 MiB) + indexer 300 MiB -> `vram_kv` **618 MiB** | 2.34 GiB |
|
||||
| streamed, 4 x 204800 (819 200 retained) | ring 144 + stage 400 (pool = max) + indexer 600 -> `vram_kv` **1 232 MiB**, four conversations funded | 4.69 GiB |
|
||||
|
||||
The card side is not constant, and it is not the ring that sets it: the stage is one layer of the
|
||||
whole retained context, 512 B per retained token per rank (200 MiB at 2 x 204800, 400 MiB at the
|
||||
target, against a ring of 144 MiB), growing at 1/12th the rate of the cache; the mirror grows at
|
||||
**6.00 KiB a token per rank**, ~600 MiB per 100k tokens. Per card, once the ring fits the budget, a
|
||||
`vram_kv` of B MiB retains about `2048 x B` tokens (375 MiB → **~768k tokens**, 750 MiB ->
|
||||
**~1.54M**), plus the ~32 MiB of fixed costs that also scale (the maps, ~21.6 MiB at 4 x 204 800,
|
||||
and the step slab).
|
||||
|
||||
Three prices per token of retained capacity: **mirror 6.00 KiB of host RAM** (`kv_attn` only),
|
||||
**indexer 0.83 KiB of VRAM** (`kv_qsa_bkey`, read densely every step), **stage 0.50 KiB of VRAM**
|
||||
(the pool, and the real card-side price). Only the ring does not scale with capacity. At the
|
||||
target four conversations run concurrently (four requests of 204 107 tokens, TTFTs 204 / 308 /
|
||||
412 / 413 s), and funding the indexer for four rather than one cost **449.77 MiB** from the expert
|
||||
slab (11.06 -> 10.62 GiB, 94% -> 90%, 374 pinned slots a rank at 1.204 MiB), which the ring could
|
||||
not have paid since the pool is the stage.
|
||||
|
||||
**Prefill comes out above the off arm**, because the pool that streaming no longer needs goes to
|
||||
the expert slab and at `--deterministic` a non-resident expert is read in place from the pinned host
|
||||
pool over PCIe: at 2 x 204800 `vram_kv` falls 1.43 GiB -> 467 MiB, the experts get 11.37 instead
|
||||
of 10.40 GiB (9 623 instead of 8 795 units), and 17.64 instead of 18.61 GiB of expert weights
|
||||
crosses the link per rank. That ~1 GiB, not the ring or the copy, is the 3-7% gain.
|
||||
**The stage copy's volume, not its overlap, is what it costs**: a pass copies the context
|
||||
allocation once a layer (2.34 GiB at 2 x 204800), linear in prompt length at a ~200x constant, and
|
||||
at 29.6-34.7 GB/s that is the link — hence "overlap recovers a quarter to a third". Clamped to the
|
||||
group's highest held block it moves **633 MiB at 16k (37.9x less)** and **44.9 GiB at 160k (4.5x
|
||||
less)**, within 0.3% of the live KV restaged, and prefill is **above** the off arm at every depth
|
||||
(+5.4% / +3.2% / +2.8%). Decode's misses move 88.4 MB (16k) to 168 MB (64k) a request.
|
||||
|
||||
Capacity is bought through `--max-num-seqs`, not a longer context: four conversations
|
||||
(`--max-num-seqs 4 --max-model-len 204800`) stay inside the trained 262 144 window and need **no
|
||||
rope change**; beyond it is YaRN territory (`docs/YARN.md`). Quality, measured separately:
|
||||
perplexity 3.994 streaming off, 4.015 with a window covering the context, 4.014 with a fraction of
|
||||
it, against a cold-start floor of 0.021 KL.
|
||||
|
||||
---
|
||||
|
||||
## 4. Architecture
|
||||
|
||||
Two modes over one host copy; layer-major addressing, block ids and `slot_mapping` are
|
||||
untouched for every non-streamed group.
|
||||
|
||||
### 4.1 The module
|
||||
|
||||
The code is a module of its own, `core/kvstream/`; the existing files gain one call each and
|
||||
nothing is moved.
|
||||
|
||||
| file | owns |
|
||||
|---|---|
|
||||
| `plan.h`, `.cpp` | the policy: whether a group is staged (`depth`), which view a pass uses, the sizes, the refusals (a window group, a non-E4M3 cache, a dense prefill into a streamed group). Pure arithmetic. |
|
||||
| `bind.h`, `.cpp` | the layout: both views over a plan, `layer_slot` kept as the mirror's row, `kv_binding_offset`, the per-pass view choice, `kvstream_step_view`, `kvstream_view_key`. |
|
||||
| `stage.h`, `.cpp` | the driver: per pass, per layer, the ranged copy of that layer's live blocks out of the mirror into the stage, on the DMA engine (§5.3); the pass-scoped "already staged" state and the tape note. |
|
||||
| `mirror.h`, `.cpp` | the host tier: the mirror and the maps, their sizes (`kvstream_map_bytes`), life cycle (`cost`, `alloc`, `init`, `release`, `stats`) and the window cap (`cap_resident_tokens`). `KVManager` holds one `KVStreamStore` and delegates. |
|
||||
| `carve.h`, `.cpp` | what a carve does with a streamed group: windows and the dense-read floor leaving the budget first, the window-fit refusal, the write of `n_blocks`/`n_slots`/`depth`, the maps' charge, the two-tier report line. |
|
||||
| `bringup.h`, `.cpp` | the engine side: which group streams, the flag refusals (§4.5), the ring's ceiling, the host-RAM gate, the startup lines. |
|
||||
|
||||
`stage.cpp` is the only one that touches a device, with `rad_memcpy_ranges_async` — already what
|
||||
the batch upload uses (`core/sched/batch.cpp:1044-1052`) — so no new kernel, no new libr4d row
|
||||
and no new libref oracle for the stage. `mirror.cpp` fills the maps with
|
||||
`rad_memcpy_async`/`rad_memset_async`.
|
||||
|
||||
What the module deliberately does not take over: **the block ids, refcounts, free lists and prefix
|
||||
adopt** (a stage addresses every logical block identically, so it needs no second address space, and
|
||||
`cached_groups()` is unchanged so a prefix hit adopts the same ids); **`kv_resolve`'s rows and the
|
||||
oracle** (a staged pass does not resolve); **`TierExec`'s gather/scatter** (`kv_tier_cached` narrows
|
||||
the list, because a gather of layer L from a one-layer pool would be "the last staged layer, 13
|
||||
times", and the residency map restores a block on the next resolve); **`PrefillStager`/`Mover`**
|
||||
(`lendable()` is false for a streamed group, and a 30-line driver issuing one ranged copy a layer is
|
||||
smaller than teaching the expert stager KV geometry); **`qsa_select`** (`sel` already holds ids).
|
||||
|
||||
### 4.2 Core changes
|
||||
|
||||
1. **Split the carve.** `n_slots` beside `n_blocks`; `layer_stride()` uses `n_slots`; the manager
|
||||
keeps allocating ids in `[0, n_blocks)`, so the sites of §3.1 keep working.
|
||||
2. **Host mirror.** A `RAD_MEM_HOST_MAPPED` buffer of `n_blocks * bytes_per_block` per streamed
|
||||
group, laid out like the device pool; budgeted as a host term and checked with `lockable_room`
|
||||
(`engine_bringup.cpp:319`, `:548`).
|
||||
3. **Residency map.** A device `res: int32[n_blocks]` (-1 = not resident) plus a control block
|
||||
(epoch, clock hand, miss counters, overflow), appended to the group's batch and the ABI.
|
||||
4. **Report, flag, metric.** A `kv streaming:` line beside the pool report, the flag in tokens, the
|
||||
three metrics; `kv_util` unchanged.
|
||||
|
||||
### 4.3 Device changes
|
||||
|
||||
1. **`kv_resolve`** (one libr4d kernel, one libavx reference, one libref oracle), as in §3.4:
|
||||
the reference design's resolve minus the K8V4/Q4 layouts radiance does not need.
|
||||
2. **`kv_store_streamed`**: the host copy always, the slot only when `res[block] >= 0`, with the
|
||||
mirror and the map as extra operands; `qk_norm_rope_gate_kv_store_streamed` folds it into
|
||||
the q/k norm+rope+gate prologue.
|
||||
3. **Layer-bulk stage**: a ranged copy of one layer's live blocks between the store and
|
||||
`attn_paged` of that layer. No new kernel.
|
||||
|
||||
### 4.4 Arch changes
|
||||
|
||||
The resolve is declared and issued in `arch/common/rad_block_attn_gated_fp8.h`, in the attention
|
||||
block, after that layer's store (`store_cache`) and immediately before each sparse launch; the
|
||||
indexer does not resolve (`arch/common/rad_qsa.h`). `rad_block_attn_gated_fp8.h:523-536` already
|
||||
has the `sparse` predicate and the `reach` bound to hang the decision on, and above
|
||||
`qsa_exact_to` the layer-bulk path takes over. The store is declared beside `kv_store` and
|
||||
issued instead of it when the batch hands the group a stream. GLM-5.3's MLA block
|
||||
(`rad_block_glm_mla.h`) declares the same pair and resolves at finish, after its indexer
|
||||
selects.
|
||||
|
||||
### 4.5 The capability gate, and what a run without the flag is
|
||||
|
||||
Streaming is a property of the architecture before it is a choice of the operator. A plugin
|
||||
answers it once with `RadArchProbe::kv_stream_ok`; the engine copies the answer into
|
||||
`RadBuildCtx::kv_stream_ok` for every declare, so all layers of a build see the same table
|
||||
entry. `qwen4exp_fp8` and `glm5next` set it. A model file states only what its attention can do;
|
||||
whether a ring is carved is the operator's.
|
||||
|
||||
Three ops exist only to move KV between the host mirror and the ring: `kv_store_streamed`, its
|
||||
folded form and `kv_resolve`. They are declared only when the architecture is capable **and**
|
||||
`--kv-resident` asked for a ring. The conjunction is `kvstream_op_gated`, consulted from
|
||||
`Builder::op_declared`, so the gate is one place, no model file knows whether the operator
|
||||
asked, and every architecture's `rad_op_declared` falls through to the path it had. Fail-safe,
|
||||
one sentence each and no refusal (nothing is allocated yet):
|
||||
|
||||
- a group that declares no `kv_resolve` or no streamed store is ignored: without a resolve `sel`
|
||||
still holds block ids while the attention reads them as ring slots, past a smaller pool — a fault
|
||||
or silent corruption; without a store nothing writes the mirror, so a miss reads zeros.
|
||||
- a packed cache (`fp8_v4`, `k6_v4`) is refused the same way, naming the layout rather than the
|
||||
architecture: it is declared to the core as plain E4M3, the streamed store's rows are E4M3 and
|
||||
bf16 only, and the operator's answer is the cache layout, not the model.
|
||||
- an architecture whose probe answers no is turned off at startup, naming it, rather than a ring no
|
||||
store can write being found after declare.
|
||||
- a streamed store declared for another group's geometry does not enable this one, and a
|
||||
declaration recorded with no kernel in any domain is not a path.
|
||||
|
||||
What the no-flag guarantee is, and is not. Without the flag no streamed op is declared, no
|
||||
runtime path changes and no budget changes: `kvstream_dense()` is false when nothing streams, so
|
||||
no resident group is charged a floor of `max_seqs` contexts. It is **not** byte-identity with
|
||||
the release before it: `qsa_select` gained its `nsel` output, so a model that declares a
|
||||
selection declares its count too (`selected_count` in the GLM indexer, `qsa_nsel` in the QSA
|
||||
family), i32, one per token — 16 KiB at `--max-num-batched-tokens 4096` — whether or not
|
||||
anything streams. The graph is the one it had plus a buffer the unstreamed path never reads.
|
||||
|
||||
---
|
||||
|
||||
## 5. The stage copy's transport, and the ring's default
|
||||
|
||||
### 5.1 The ring's depth
|
||||
|
||||
`--kv-resident` is off by default. When it is used, size it at **32 768**, the performance floor
|
||||
(§3.9), not at the decode union. The union (<= 513 blocks, 2052 tokens) is the validation
|
||||
ceiling, and a flag under it is raised to it at startup with one warning; under speculation it
|
||||
is `max_seqs x (1 + n_spec) x 513`.
|
||||
|
||||
`kv_pass_view` decides the view: a decode pass within `1 + n_spec` rows a sequence takes the
|
||||
ring; every other pass — prefill, a mixed prefill+decode step, and a decode-classified pass
|
||||
wider than a decode step can be (the serial drafter's history pass over a prefill chunk) —
|
||||
takes the stage. The choice is visible to the tape without a new key term because `phase`,
|
||||
`n_tok`, `n_seq` and `n_spec` are already in the pass key. Capacity is priced in host RAM, not
|
||||
in the ring; a raised ring that does not fit is the budget's refusal, by name and size.
|
||||
|
||||
### 5.2 There is no streaming switch
|
||||
|
||||
`--kv-resident N` *is* the feature: absent (or 0) and nothing streams, present and the ring is N
|
||||
tokens. There is no `--kv-streaming` to understand (it is refused by name), no `auto` to
|
||||
second-guess, and no mode where an operator can ask for streaming that cannot help. A removed
|
||||
`--kv-stream-threshold` is refused by name too: the base path for a live set that fits the ring
|
||||
measured 2.6-2.9 % slower a step on the post-tape-fix tree (record §74), so the streamed path is
|
||||
the cheap one at every depth. And when the ring covers the group's context it does not stream at
|
||||
all (§3.1): a configuration whose context fits pays *nothing* — the same code path, not a cheap
|
||||
one.
|
||||
|
||||
### 5.3 The transport
|
||||
|
||||
The copy of layer L+1 is one `rad_xp_list` on the card's prefetch DMA queue, marked on a ride
|
||||
(`rad_ride`, `Ctx::xp_mark`) taken once every attention launch of layer L has been issued, so it
|
||||
starts when L's attention is done with the aliased buffer and crosses the link under L's out
|
||||
projection and L+1's projections, holding no CU slot. The compute stream waits for it through
|
||||
an event the *list* completes: `rad_event_dma` gives a completion word that the list's fence
|
||||
packet writes 0 to, and `rad_event_wait` is the barrier. The word is armed by a write of 1 in
|
||||
stream order — the weight-table patch dispatch, which is also what the ride completes on —
|
||||
because a host-side arm races a wait still queued for the previous layer, and an event record
|
||||
cannot be used at all (a record completes by decrementing its signal to 0, exactly the value
|
||||
the wait looks for).
|
||||
|
||||
Two consequences. **The wait is before the layer's store**: the copy reads the mirror, which the
|
||||
store has not written yet, so a copy landing after it would put older bytes back over this
|
||||
chunk's tokens; the seams are `rad_kv_stage_wait` immediately before `store_cache` and
|
||||
`rad_kv_stage_next` after the attention loop. And **the list must not yield to a link hold**:
|
||||
`rad_xp_list` takes a `flags` argument and this list passes `RAD_XP_NO_YIELD`, because the
|
||||
hold's release would be behind the wait this stream takes on the copy — the deadlock
|
||||
`core/device/device.h` names. A backend with no DMA queue (the host backend, a test) copies on
|
||||
the compute stream in the same four-step order, and `Ctx::tape_kv_stage` re-runs the arm and the
|
||||
submit with the tape paused, as `xprefetch.cpp` does.
|
||||
|
||||
### 5.4 What is not reused
|
||||
|
||||
The transport is the expert prefetch's; the policy is not. `XpRec`, `xp_plan` and `xp_step` patch
|
||||
weight-table entries and have no analogue in KV, and the geometry is expert-sized (`kXpSlots 2`,
|
||||
`kXpGroups 3`, `kXpMaxRows 16`), so the KV policy is written fresh in `core/kvstream/stage.*`.
|
||||
|
||||
**Experts speculate, KV waits.** A prefetch copy that lands late is unused, because the expert is
|
||||
read over the link instead; a KV stage cannot be skipped, so it must be a copy the compute stream
|
||||
waits on. They do not compete by design: the prefetch is decode-only (`kXpMaxRows 16`) and staging
|
||||
is prefill-shaped. The alternatives, kept so a later change can be measured against them: the
|
||||
one-layer aliased view (chosen); the same view carved from the arena's lent top (rejected — a KV
|
||||
base inside another owner's pool, and the loan is step-granular while the carve is
|
||||
bring-up-granular); a full `n_layers`-deep buffer lent to the experts between requests (costs
|
||||
1.66 GiB at 262K *during* prefill, and `reclaim()` is a host wait); the whole context resident
|
||||
during prefill (saves nothing: the group still carves `n_layers x context`).
|
||||
|
||||
---
|
||||
|
||||
## 6. Failure modes, risks, and the tests that hold them
|
||||
|
||||
| failure mode | what prevents it | test |
|
||||
|---|---|---|
|
||||
| a block id used as an address past the ring | `kv_resolve` rewrites every entry; overflow writes slot 0 and latches `ctl[3]`; the request is failed | `tests/ref_test.cpp`'s `kv_resolve_*`; `r4d_selftest --case kv_resolve` |
|
||||
| an unbacked streamed plan handing out ids the pool cannot address | `kvstream_apply` refuses with `RAD_E_INVAL` | `a_streamed_group_is_refused_at_carve_without_its_host_copy` |
|
||||
| a pool whose depth disagrees with its id space | `n_blocks`/`n_slots`/`depth` written by one function | `a_streamed_group_addresses_its_context_but_backs_only_the_resident_window` |
|
||||
| a streamed window group, or a window that does not fit | refused by name against the flag | `a_streamed_window_group_is_refused_by_name` |
|
||||
| a ring under one decode step's selection | raised at startup, one warning, both numbers | `a_ring_below_one_decode_step_s_selection_is_raised_to_the_ceiling` |
|
||||
| a covering ring paying for streaming | `streams()` false: ordinary resident path, null `RadKVStream` | `a_ring_that_covers_the_context_streams_nothing_and_the_engine_pays_nothing`; `scripts/kv-parity.sh` |
|
||||
| a wide decode-classified pass resolving a ring it cannot fit | `kv_pass_view` takes the stage | `a_decode_pass_wider_than_a_verify_stages_instead_of_resolving_the_ring` |
|
||||
| a mirror nothing writes (a miss reads zeros) | the op is declared only with a store row for the group's geometry | `a_declared_streamed_store_with_no_kernel_is_not_a_streamed_path`; `a_packed_cache_warns_that_the_layout_has_no_writer_and_serves_non_streamed`; `a_resolve_declared_for_another_group_does_not_enable_streaming` |
|
||||
| the flag honoured where no streamed path exists | the gate: warn and ignore | `a_model_whose_architecture_declares_no_streamed_ops_ignores_the_flag`; `a_streamed_op_exists_only_for_a_capable_architecture_and_a_ring` |
|
||||
| a stage reading the previous layer's cache | the four-step order (§3.5.1) | `a_streamed_groups_layers_may_all_alias_one_pool_slot`; `scripts/kv-stage-parity-64k.sh` |
|
||||
| a stage copying more than it must, or less than it may | the `held_top_blocks` upper bound | `scripts/kv-stage-parity-64k.sh` (64k prompt, 32 768-token ring) |
|
||||
| maps that leave the pool short of the budget probe | `kvstream_maps_charged` in both paths | `a_streamed_groups_maps_are_charged_before_the_pool_is_sized` |
|
||||
| the dense-read sibling funded for one sequence | the `kvstream_dense` floor | `a_dense_read_groups_floor_holds_every_sequence_while_a_sibling_streams` |
|
||||
| a recorded pass replayed against a different view | `kvstream_view_key` by memory, not struct address; fixed pitches | `Ctx::pass_key`, with its static assertion on `RadKVGroupBatch`'s fields |
|
||||
| a follower lane or a host re-issued copy breaking the order | the barriers in §3.5.1 and §5.3 | reviewed, not tested |
|
||||
|
||||
### 6.1 The link, the lanes, and the hold
|
||||
|
||||
At `--tp 2 --tp-wire exact` the all-reduce, the KV copies and the prefill expert stager share the
|
||||
link. `rad_xp_list` copies run on the DMA engine, the one path that takes its share at full rate
|
||||
(`RAD_COPY_YIELD`, `core/device/device.h:64-88`); a staging copy issued as an ordinary stream
|
||||
memcpy would hold a CU slot and starve the kernels. With the correction the transport needed — the
|
||||
list must not yield, because the compute stream waits on it — the stage competes as an equal, which
|
||||
is why overlap recovers only a quarter to a third of its cost (§3.9). A stage on lane 1 needs
|
||||
`rad_lane_join(1, 0)` before its reader.
|
||||
|
||||
### 6.2 The first in-place device write to mapped host memory
|
||||
|
||||
Every precedent is read-only, so the streamed store's write is held to libref's bytes before
|
||||
anything depends on it: `r4d_selftest --case kv_store_streamed_fp8` puts the mirror in mapped
|
||||
pinned host memory, runs the kernel against it and compares the bytes the *host* reads after
|
||||
the sync; `--case kv_store_streamed_bf16` does the same for the bf16 plane;
|
||||
`scripts/kv-stage-parity-64k.sh` exercises the same write in the served path.
|
||||
|
||||
### 6.3 Rank coverage
|
||||
|
||||
The map is per rank and the block ids are shared, so the leader decides residency and every rank
|
||||
applies the same decision, the way `IdleTiers` splits planning from transfer (`tierexec.h:55-58`).
|
||||
Exercised at `--tp 1` and `--tp 2` only, which is what the box has: `--tp 3`, `--tp 4`, the uneven
|
||||
split (`vram_budget_rank_split`), the attention-zero ranks (`rad_kv_group_zero`) and the
|
||||
`r4d_selftest` four-card cases are **untested**. The one real defect tp2 caught was the per-rank
|
||||
rebasing of `RadKVStream` (§3.4), so exercise that path before claiming four ranks.
|
||||
|
||||
### 6.4 The draft model
|
||||
|
||||
The MTP head binds the same `kv_attn` group (`qwen4exp_fp8.cpp:656`, `:1331`) and its own K/V is a
|
||||
window ring; whether the drafter reads the same residency map or gets its own needs deciding with
|
||||
speculation on. A verify step issues one selection a row and takes the ring, not the stage, which is
|
||||
why the ceiling is `max_seqs x (1 + n_spec) x 513` (§3.9) and why a decode-classified pass wider than
|
||||
that must stage (§5.1).
|
||||
@@ -38,6 +38,10 @@ and `agentreplay.py` need `python3`. Scripts find each other through `$(dirname
|
||||
| `mctrace.sh` | A MiniCPM5-2B decode trace under `rocprofv3`, on its own server, formatted for `libr4d/isa/tsum.sh`, mainly for its `blocks` column. |
|
||||
| `ident.sh` | Run-to-run reproducibility at a fixed configuration: one hash per (temperature, question), to compare against another run of the same configuration. A speculative run need not match a non-speculative one byte for byte (the split-K count is chosen from M, so reduction orders differ and a near-tie can flip late in a long answer), but a divergence within the first sentence or two is a defect. |
|
||||
| `cardclock.py` | What holds each card's clock under sustained load, and which card a tensor-parallel step waits for (the slowest rank ends the step). Reads every AMD card's `gpu_metrics` table ten times a second and counts a throttler bit only when the clock is lower while it is set (some firmware keeps a bit on at idle). Shows the engine's step counters per window, so a slow window is attributed to slower steps, fewer tokens per step or host time between steps. Drives its own greedy load, or with `--watch` only samples a server under real traffic; `--compare` shows two saved runs side by side. Read-only on the cards. |
|
||||
| `kv-resident-vs-stock.sh` | The shipped comparison, paired: interleaved ABBA rounds of this build with `--kv-resident 32768` against the stock 1.10.0 image without it, one cold start per request (a second request in one process starts from a partly filled ring, a different workload). One paired delta a round, reported as the mean, the per-round values and a t interval; `ROUNDS` sets the resolution (~2.8% at 2, ~2.0% at 4). Every start is asked `/tokenize` for the canonical 16 110-token prompt and must answer that count, and every response's `usage.prompt_tokens` must agree again with `cached_tokens` 0, so both arms are provably on the same input. |
|
||||
| `kv-union.sh` | How large a KV streaming ring has to be: the union of distinct blocks one `kv_resolve` launch selects, at 64k/128k-token prompts, climbed from the 32 768-token floor (8 192 blocks — the smallest ring this box runs and one the engine does not raise) until no launch overflows. Reports resolves, lookups, misses, the largest single-launch union and prefill wall time, plus the overflow refusal verbatim; its last arm decodes a sparse prompt whose ~34k-token history already exceeds the floor ring and compares with streaming off (no `--kv-resident`), and refuses to pass unless the ring actually evicted (misses above the peak union). Pressure is the context: the short-context points of the record are gone because a 4k/16k context fits the floor ring and streams nothing. |
|
||||
| `kv-parity.sh` | That a `--kv-resident` ring covering the group's context changes no output byte and streams nothing: one server per arm, a dense and a sparse prompt with no flag and with `--kv-resident 4096` (its `--max-model-len x --max-num-seqs`), compared byte for byte, plus `--profile-ops` proving `kv_resolve` is never issued and the startup line saying nothing streams -- the base engine's path. |
|
||||
| `kv-stage-parity-64k.sh` | Phase 2's prefill staging: streaming off (no `--kv-resident`) against `--kv-resident 32768` (the floor, 8 192 blocks) on a ~64k-token document, so every prefill chunk past 32 768 tokens has a history the ring cannot hold and must take the one-layer stage view instead of resolving; byte-identical output, the staged-copy trace counted and checked in layer order, and both arms' VRAM split printed. This is the shape that caught the §60 staged-prefill defect; a run that takes the ring instead of the stage fails. |
|
||||
| `statsdump.py` | Records `/stats` to a JSONL file, one row per poll (`--every`, default 1 s), so the dashboard's figures can be read back over time on a machine without a Prometheus scraper. A row is the engine's snapshot verbatim plus the poll's time `t` and the gap since the last good poll `dt_s`; nothing is derived. The file is appended to and rotated at `--max-mib` (default 256, five generations). A failed poll leaves no row; a run that wrote no row, or can no longer write its file, exits 1. The key is taken from `--api-key` or `RADIANCE_API_KEY`. |
|
||||
| `oracle.sh` | Every op compared against libref on the operands the model issued, which rad-kbench cannot do: its operands are its own (dense, rank 2), while the engine's are arena slices and weights loaded from a file. Starts its own server on :8302. Read it for `MISMATCH` lines, and for `NOT CHECKED` lines naming rows whose weight layout has no published inverse and so cannot be compared. |
|
||||
|
||||
|
||||
Executable
+288
@@ -0,0 +1,288 @@
|
||||
#!/bin/bash
|
||||
# Prove that a --kv-resident ring that covers the group's context changes no output byte and
|
||||
# streams nothing at all on the QSA model.
|
||||
#
|
||||
# Why this exists: docs/KV-STREAMING.md §5 Phase 4 makes a ring at or above the group's context a
|
||||
# plain resident pool -- no host mirror, no residency map, no stage view, no kv_resolve and a null
|
||||
# RadKVStream -- so the base engine's path runs exactly. This script runs one server per arm, sends
|
||||
# the same request to each, and compares the completion text byte for byte. The "on" arm passes
|
||||
# --kv-resident 4096 with --max-num-seqs 1 --max-model-len 4096, i.e. exactly the group's context,
|
||||
# and must say so at startup and issue no resolve at all; the off arm passes no flag. Any overhead
|
||||
# the covering configuration adds would show up here as either a different completion, a streaming
|
||||
# startup line, or a nonzero kv_resolve count.
|
||||
#
|
||||
# It builds nothing, and it touches only the server it starts: the engine is one process (its TP
|
||||
# ranks are threads), so each arm is recorded under its own log in $OUT and killed by that pid at the
|
||||
# end or on any error. Nothing else that matches bin/radiance is signalled -- no pkill anywhere.
|
||||
#
|
||||
# Run this INSIDE the toolchain container, with the model mounted, because that is where the binary
|
||||
# and its kernel libraries live, and because the engine needs io_uring, which Docker's default
|
||||
# seccomp profile refuses:
|
||||
# docker run --rm --security-opt seccomp=unconfined --user 1000:1000 -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
|
||||
# -v /tmp/opencode:/tmp/opencode -w /src rad-toolchain:latest bash -lc 'bash scripts/kv-parity.sh'
|
||||
#
|
||||
# Two prompts, both deterministic (a numbered record repeated, then "continue the register"): the
|
||||
# sparse one is ~3000 tokens because the sparse path only engages above qsa_exact_to = 2051
|
||||
# (arch/qwen4exp_fp8/qwen4exp_fp8.cpp:621-624) -- below it attention is dense and the selection is
|
||||
# a different path, so a short prompt alone would prove nothing. Both fit the 4096-token context the
|
||||
# ring covers. The short arm is there to show that path is untouched too.
|
||||
#
|
||||
# Exit status: 0 only if both arms produced a completion, the two are byte-identical, and the
|
||||
# covering arm reported no streaming and no resolve; 1 on any difference or streaming overhead;
|
||||
# 2 if an arm did not come up or did not answer.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-/tmp/opencode/build-kv2}"
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8123}"
|
||||
OUT="${OUT:-/tmp/opencode/kv-parity}"
|
||||
SPARSE_LINES="${SPARSE_LINES:-100}" # ~3028 prompt tokens: above qsa_exact_to, so sparse
|
||||
DENSE_LINES="${DENSE_LINES:-20}" # ~600 prompt tokens: below it, so dense, no kv_resolve
|
||||
MAXTOK="${MAXTOK:-256}"
|
||||
SEED="${SEED:-12345}"
|
||||
# Exactly the one-sequence context the server is configured with (--max-num-seqs 1 x
|
||||
# --max-model-len 4096), so this ring covers the group and nothing streams.
|
||||
RESIDENT="${RESIDENT:-4096}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home" # absolute: the engine will not find the kernels without it
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
# Only our own process, by the pid this script recorded: the engine is one process (its TP ranks
|
||||
# are threads), so there is no group to sweep and nothing else can be hit by mistake. No pkill.
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
# Generous: with --profile-ops the per-op table is printed by ~Engine on SIGTERM, and killing
|
||||
# before it lands would lose the only per-op issue counts the engine ever reports.
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# A one-line prompt, so the request body needs no JSON string escapes at all: the records are
|
||||
# joined with spaces deliberately (text is identical in both arms either way).
|
||||
gen_prompt() {
|
||||
local n="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= n; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
gen_prompt "$SPARSE_LINES" > "$OUT/prompt-sparse.txt"
|
||||
gen_prompt "$DENSE_LINES" > "$OUT/prompt-dense.txt"
|
||||
|
||||
# The raw JSON-escaped value of the completion's "content". Escaping is a deterministic function of
|
||||
# the text, so equal escaped bytes mean equal text -- and comparing the escaped form is strictly
|
||||
# safer than any unescaper this script could carry.
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# One arm: start a server, wait for /health (never a blind sleep), ask once, stop the server.
|
||||
# `$1` is the arm's name, `$2` its prompt, the rest is the streaming flags -- identical otherwise,
|
||||
# which is the point. Returns non-zero (and leaves the engine's last errors on stderr) if the arm
|
||||
# could not serve, so every arm gets to report before the script decides.
|
||||
run_arm() { local arm="$1" prompt="$2"; shift 2
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
echo "== $arm: $* =="
|
||||
( exec "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len 4096 --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 180); do # 15 min at 5 s: a cold load of this container is under a minute
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
# temperature 0 and a fixed seed: greedy, so the only thing that can move a token is the engine.
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$prompt")
|
||||
printf '{"model":"%s","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"qwen4exp" "$SEED" "$MAXTOK" "$prompt_text" > "$req"
|
||||
code=$(curl -s -m 900 -o "$resp" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || true)
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
content_of "$resp" > "$OUT/$arm.txt"
|
||||
if [ ! -s "$OUT/$arm.txt" ]; then
|
||||
echo "FAIL $arm: empty completion text" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
# What the prompt actually cost, straight from the engine: it must be past qsa_exact_to for the
|
||||
# sparse arm, and cached_tokens 0 shows the whole prompt was prefilled on this server (a prefix
|
||||
# hit would leave the arm's own token count unproven).
|
||||
local ptok ctok cache
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
ctok=$(grep -o '"completion_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
cache=$(grep -o '"cached_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
echo " prompt_tokens=$ptok completion_tokens=$ctok cached_tokens=$cache"
|
||||
echo " sha256 $(sha256sum "$OUT/$arm.txt" | cut -d' ' -f1) ($(wc -c < "$OUT/$arm.txt") bytes)"
|
||||
echo "$ptok $ctok $cache" > "$OUT/$arm.counts"
|
||||
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
# What a byte comparison cannot tell you, asserted on the streaming log:
|
||||
# - no `kv_resolve` refusal and no GPU fault / fatal.
|
||||
# - the "nothing streams" line, and no streamed-group line: the ring covered the context, so the
|
||||
# group kept the base engine's resident path rather than a cheapened streamed one.
|
||||
assert_streaming_log() {
|
||||
local arm="$1"
|
||||
local log="$OUT/$1.log"
|
||||
local bad=0
|
||||
if grep -q "refused op 'kv_resolve'" "$log"; then
|
||||
echo "FAIL $arm: kv_resolve was refused at issue" >&2; bad=1
|
||||
fi
|
||||
if grep -q "GPU memory fault" "$log"; then
|
||||
echo "FAIL $arm: a GPU memory fault was reported" >&2; bad=1
|
||||
fi
|
||||
if grep -q "^radiance: fatal:" "$log"; then
|
||||
echo "FAIL $arm: the engine reported a fatal error" >&2; bad=1
|
||||
fi
|
||||
if ! grep -q "^I kv streaming: nothing streams" "$log"; then
|
||||
echo "FAIL $arm: no 'nothing streams' startup line: --kv-resident $RESIDENT did not cover the context" >&2; bad=1
|
||||
fi
|
||||
if grep -q "^I kv streaming: [0-9].*stream (" "$log"; then
|
||||
echo "FAIL $arm: a group streamed even though the ring covers its context" >&2; bad=1
|
||||
fi
|
||||
return $bad
|
||||
}
|
||||
|
||||
# Count the kv_resolve issues the engine itself accounted for, per op instance. `--profile-ops`
|
||||
# prints a per-op table (calls, total ms, us/call, op, geometry) on shutdown and every
|
||||
# RADIANCE_PROFILE_EVERY steps, and it is the only place the engine states how many times an op was
|
||||
# issued: no ctl counter reaches /metrics and no launch is logged. There is one kv_resolve op per
|
||||
# layer, so every row carries the same count; the largest is this arm's per-layer total.
|
||||
# A row is ` <calls> <total ms> <us/call> <site> <join> <wait> <op> <geometry> ...`, so the op is
|
||||
# matched as a whole field and the count is field 1. Prints the count (0 if the op never appears).
|
||||
resolves_issued() {
|
||||
grep -E '^ +[0-9]+ ' "$1" 2>/dev/null |
|
||||
awk '{ for (i = 1; i <= NF; i++) if ($i == "kv_resolve") { if ($1 + 0 > mx) mx = $1 + 0; break } }
|
||||
END { print mx + 0 }'
|
||||
}
|
||||
|
||||
# Ask one profiled question: how many times was kv_resolve issued per layer on this shape? $1 = arm
|
||||
# name, $2 = the prompt. The count lands in $OUT/$arm.resolves. The profiled servers are used for
|
||||
# this evidence only -- their completions are not compared, because --profile-ops restores
|
||||
# synchronisations that make it a different run (its own caveat prints so).
|
||||
run_profile_probe() {
|
||||
local arm="$1" prompt="$2"
|
||||
local log="$OUT/$arm.log" got
|
||||
echo "== probe $arm: --profile-ops =="
|
||||
run_arm "$arm" "$prompt" --kv-resident "$RESIDENT" --profile-ops || return 1
|
||||
got=$(resolves_issued "$log")
|
||||
echo " kv_resolve issues per layer: $got"
|
||||
echo "$got" > "$OUT/$arm.resolves"
|
||||
return 0
|
||||
}
|
||||
|
||||
# The short arms first, then the arms the change is about: whatever the sparse arm
|
||||
# does must not hide the evidence the cheap arms produce.
|
||||
FAILED=0
|
||||
run_arm off-dense "$OUT/prompt-dense.txt" || FAILED=1
|
||||
run_arm on-dense "$OUT/prompt-dense.txt" --kv-resident "$RESIDENT" || FAILED=1
|
||||
|
||||
assert_streaming_log on-dense || FAILED=1
|
||||
|
||||
# Phase 2 admits a ring smaller than the context: a prefill or mixed step takes the group's
|
||||
# one-layer stage view and never resolves, so the union of §3.5 is not a ring requirement. The
|
||||
# staged-copy evidence (staged copies, in layer order, and byte parity) is
|
||||
# scripts/kv-stage-parity-64k.sh, which runs the floor ring against a ~64k document; this script
|
||||
# keeps the context-sized covering configuration it was written for.
|
||||
|
||||
run_arm off-sparse "$OUT/prompt-sparse.txt" || FAILED=1
|
||||
run_arm on-sparse "$OUT/prompt-sparse.txt" --kv-resident "$RESIDENT" || FAILED=1
|
||||
assert_streaming_log on-sparse || FAILED=1
|
||||
|
||||
echo "== kv streaming lines from on-sparse.log =="
|
||||
grep -E "kv streaming:" "$OUT/on-sparse.log" || echo " (none: no streaming report line at all)"
|
||||
|
||||
# Execution, not configuration: the byte comparison above is worthless if a resolve ran on a group
|
||||
# this configuration says is resident. A ring that covers the context must issue no kv_resolve at
|
||||
# all -- on either the dense or the sparse path -- because the batch hands the arch a null stream.
|
||||
run_profile_probe proof-dense "$OUT/prompt-dense.txt" || FAILED=1
|
||||
run_profile_probe proof-sparse "$OUT/prompt-sparse.txt" || FAILED=1
|
||||
if [ -s "$OUT/proof-dense.resolves" ] && [ -s "$OUT/proof-sparse.resolves" ]; then
|
||||
dense_n=$(cat "$OUT/proof-dense.resolves")
|
||||
sparse_n=$(cat "$OUT/proof-sparse.resolves")
|
||||
echo "== resolve execution: $sparse_n per layer on the sparse arm, $dense_n on the dense arm =="
|
||||
if [ "$sparse_n" -ne 0 ] || [ "$dense_n" -ne 0 ]; then
|
||||
echo "FAIL: a covering ring issued $sparse_n/$dense_n resolves per layer: it streamed when it" >&2
|
||||
echo " should have kept the base engine's resident path" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
else
|
||||
echo "FAIL: a probe arm produced no per-op table, so execution is unproven" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
|
||||
# The sparse prompt must be past qsa_exact_to, so the sparse path actually ran (and still issued no
|
||||
# resolve, because the ring covers the context).
|
||||
if [ -s "$OUT/on-sparse.counts" ]; then
|
||||
read -r ptok _ _ < "$OUT/on-sparse.counts"
|
||||
if [ "$ptok" -le 2051 ]; then
|
||||
echo "FAIL: the sparse prompt is $ptok tokens, at or below qsa_exact_to 2051: the dense path" >&2
|
||||
echo " ran, so the sparse path this check is about was never exercised. Raise SPARSE_LINES." >&2
|
||||
FAILED=1
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, a log was not clean, or a covering ring streamed anyway" >&2
|
||||
echo " (see above); no zero-overhead claim can be made" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== compare =="
|
||||
cmp "$OUT/off-sparse.txt" "$OUT/on-sparse.txt" || { echo "FAIL: the sparse arms differ" >&2; exit 1; }
|
||||
cmp "$OUT/off-dense.txt" "$OUT/on-dense.txt" || { echo "FAIL: the dense arms differ" >&2; exit 1; }
|
||||
echo "PASS: both arms byte-identical, with a covering ring streaming nothing and issuing no resolve"
|
||||
Executable
+692
@@ -0,0 +1,692 @@
|
||||
#!/bin/bash
|
||||
# Measure the streaming-vs-stock decode gap at the canonical under-resident shape, as a paired
|
||||
# number with an interval. The prompt is generated here, so a run does not depend on a file in /tmp
|
||||
# surviving a reboot.
|
||||
#
|
||||
# The shape:
|
||||
# 16 110-token prompt (sha256 c34ad060...f3a5) -- gen_prompt 522, generated below
|
||||
# 8 192 generated tokens, --kv-resident 32768 (8 192 blocks = 200.00 MiB, inside a 204 800-token
|
||||
# context, so the group streams and every decode launch resolves)
|
||||
# stock image stilldeadcode/radiance:1.10.0 (no --kv-resident) against this build with it.
|
||||
# Every other flag is identical between arms.
|
||||
#
|
||||
# SPEC (default 0) sets --num-speculative-tokens on *both* arms, which is the only thing that
|
||||
# should differ between them. Two things change when it is on, and both are needed or the numbers
|
||||
# mean nothing:
|
||||
# - ms/step is no longer 1000/predicted_per_second. With speculation a step emits 1 + SPEC
|
||||
# tokens, so predicted_per_second is tokens a second, not steps. ms/step is then the engine's
|
||||
# own step clock, engine_step_seconds_decode_total / engine_steps_decode_total, which /metrics
|
||||
# reports on both arms (the stock 1.10.0 image exposes the same counters). tok/s stays
|
||||
# predicted_per_second, tokens a step is MAXTOK / decode steps, and draft acceptance is
|
||||
# timings.draft_n_accepted / timings.draft_n -- the bimodal variable, printed per start so the
|
||||
# modes are visible instead of averaged.
|
||||
# - a start is ~6x shorter (spec 3 decodes 1 024 tokens in ~16 s, not ~206 s), so the same wall
|
||||
# time buys many more pairs. SPEC=3 at ROUNDS=12 is ~20 min against ~16 min for ROUNDS=2 off.
|
||||
#
|
||||
# Method: interleaved ABBA rounds. Round r sends one request on each arm, the two starts adjacent
|
||||
# in wall time, and alternates which arm goes first (round 1 stock first, round 2 ours first, ...).
|
||||
# Each round yields one paired delta (ours ms/step over stock ms/step); the mean of those deltas,
|
||||
# the per-round values, the spread and a t interval are reported. Interleaving cancels the
|
||||
# common-mode part of session drift; the residual non-common-mode part is ±1.5 points, which is why
|
||||
# the interval is wide.
|
||||
#
|
||||
# Why one cold start per request rather than one server per arm reused across its rounds: the two
|
||||
# arms cannot hold the cards at once (each is `--tp 2` with --host-pool-mib 23652), so a server
|
||||
# reused "across that arm's rounds" would have to be killed and restarted between them anyway. And
|
||||
# a second request in the same process starts from a partly filled ring, i.e. it is not the same
|
||||
# workload as the first. So each
|
||||
# arm's rounds are adjacent cold starts, one request each, and only one server is ever on the cards.
|
||||
#
|
||||
# Cost and resolution: a start is ~18 s load + ~6 s prefill + 8 192 x ~26 ms
|
||||
# decode, i.e. ~4 min, so ROUNDS=2 (two starts per arm, four in all) is ~16 min. At a cross-arm
|
||||
# sd of 1.4 points the minimum detectable difference is 2.8 x sd / sqrt(n) (95%
|
||||
# two-sided, 80% power): ~2.8% at 2 rounds, ~2.0% at 4. To resolve **1%** needs ~16 paired rounds
|
||||
# and to resolve **0.9%** needs ~19-20, i.e. 32-40 cold starts and ~2.5 h of card time. A small
|
||||
# default here is deliberate: this script states the shipped gap, it does not test a 1% change.
|
||||
#
|
||||
# What it proves about the two arms being on the same input: the prompt is regenerated here and its
|
||||
# sha256 must equal the canonical one; *every* server started is asked POST /tokenize for that
|
||||
# prompt and must answer the target count before its request runs; and every response's
|
||||
# usage.prompt_tokens must equal the target again, with cached_tokens 0 (a prefix-cache hit would
|
||||
# make the two arms' prefill a different workload). A mismatch kills the run.
|
||||
#
|
||||
# Run on the host, where the docker CLI talks to the daemon (the images and the build tree live
|
||||
# here; the engine needs the model mounted and io_uring unconfined, which the script does):
|
||||
# bash scripts/kv-resident-vs-stock.sh # 2 rounds, ~16 min
|
||||
# ROUNDS=4 bash scripts/kv-resident-vs-stock.sh # ~32 min, ~2.0% resolution
|
||||
# SPEC=3 ROUNDS=12 bash scripts/kv-resident-vs-stock.sh # speculation on, ~20 min, 12 pairs
|
||||
#
|
||||
# Env knobs (defaults in parentheses): ROUNDS (2), MAXTOK (8192), RESIDENT (32768), SPEC (0),
|
||||
# PORT (8141), OUT (/tmp/opencode/kv-resident-vs-stock), BUILD (/tmp/opencode/build-kv3),
|
||||
# MODEL (/home/j/Documents/rad/models/qwen3.8-next-flash-fp8-iq4r-moe.rad),
|
||||
# STOCK_IMAGE (stilldeadcode/radiance:1.10.0), TOOLCHAIN (rad-toolchain:latest), SEED (12345).
|
||||
# TARGET_TOKENS (16110), PROMPT_LINES (522) and PROMPT_SHA are pinned on purpose: they are the
|
||||
# workload, and a run against a different prompt is a different measurement.
|
||||
#
|
||||
# Exit status: 0 if every round measured and the arms agreed on the prompt; 2 if the environment,
|
||||
# an arm, a token count, a ring check or the model file failed (the reason is on stderr).
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
awk 'NR > 1 && /^#/ { sub(/^# ?/, ""); print; next } NR > 1 { exit }' "$0"
|
||||
}
|
||||
|
||||
ROUNDS="${ROUNDS:-2}"
|
||||
MAXTOK="${MAXTOK:-8192}"
|
||||
RESIDENT="${RESIDENT:-32768}"
|
||||
SPEC="${SPEC:-0}"
|
||||
PORT="${PORT:-8141}"
|
||||
OUT="${OUT:-/tmp/opencode/kv-resident-vs-stock}"
|
||||
BUILD="${BUILD:-/tmp/opencode/build-kv3}"
|
||||
MODEL="${MODEL:-/home/j/Documents/rad/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
STOCK_IMAGE="${STOCK_IMAGE:-stilldeadcode/radiance:1.10.0}"
|
||||
TOOLCHAIN="${TOOLCHAIN:-rad-toolchain:latest}"
|
||||
SEED="${SEED:-12345}"
|
||||
|
||||
# The workload, pinned: the canonical prompt, and what the server counted it as.
|
||||
PROMPT_LINES=522
|
||||
TARGET_TOKENS=16110
|
||||
PROMPT_SHA=c34ad06069bc07c791e61789ffbace20f5879781c9fbc2eb7ea009e09cb3f3a5
|
||||
# Pinned so "the model is the expected file" is a check and not a hope: the whole 122 GB is too
|
||||
# much to hash every run, so the size plus the first 4 MiB identifies the conversion.
|
||||
MODEL_BYTES=121969901568
|
||||
MODEL_HEAD_SHA=f2958962468b9b112ebc4bcf78d6da9b270477c7b636a0ded7418b7298e434b4
|
||||
|
||||
while [ $# -gt 0 ]; do
|
||||
case "$1" in
|
||||
--help|-h) usage; exit 0 ;;
|
||||
--rounds) [ $# -ge 2 ] || { echo "--rounds needs a value" >&2; exit 2; }; ROUNDS="$2"; shift 2 ;;
|
||||
--spec) [ $# -ge 2 ] || { echo "--spec needs a value" >&2; exit 2; }; SPEC="$2"; shift 2 ;;
|
||||
*) echo "unknown option: $1 (--help for usage)" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
|
||||
case "$ROUNDS" in
|
||||
''|*[!0-9]*) echo "ROUNDS must be a positive integer, got '$ROUNDS'" >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$ROUNDS" -ge 2 ] || { echo "ROUNDS must be at least 2: one round has no spread, so no interval" >&2; exit 2; }
|
||||
case "$SPEC" in
|
||||
''|*[!0-9]*) echo "SPEC must be a non-negative integer, got '$SPEC'" >&2; exit 2 ;;
|
||||
esac
|
||||
[ "$SPEC" -le 8 ] || { echo "SPEC $SPEC is deeper than the drafter is built for (0-8)" >&2; exit 2; }
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
MODEL_IN="/models/$(basename "$MODEL")"
|
||||
RING_BLOCKS=$(( RESIDENT / 4 )) # one KV block is 4 tokens (docs/KV-STREAMING.md §3.9)
|
||||
|
||||
die() { echo "FAIL: $*" >&2; exit 2; }
|
||||
|
||||
command -v docker >/dev/null || die "docker is needed: this script drives both arms as containers"
|
||||
docker image inspect "$STOCK_IMAGE" >/dev/null 2>&1 || die "no image $STOCK_IMAGE (docker pull it)"
|
||||
docker image inspect "$TOOLCHAIN" >/dev/null 2>&1 || die "no image $TOOLCHAIN"
|
||||
[ -x "$BUILD/bin/radiance" ] || die "no engine at $BUILD/bin/radiance (build it first; this script builds nothing)"
|
||||
[ -d "$BUILD/radiance_home" ] || die "no RADIANCE_HOME at $BUILD/radiance_home"
|
||||
[ -f "$MODEL" ] || die "no model at $MODEL"
|
||||
[ "$(stat -c %s "$MODEL")" = "$MODEL_BYTES" ] || \
|
||||
die "$MODEL is $(stat -c %s "$MODEL") bytes, expected $MODEL_BYTES: not the pinned conversion"
|
||||
head -c 4194304 "$MODEL" | sha256sum | cut -d' ' -f1 | grep -qx "$MODEL_HEAD_SHA" || \
|
||||
die "$MODEL's first 4 MiB do not hash to $MODEL_HEAD_SHA: not the pinned conversion"
|
||||
# The host that drives docker has wget but not necessarily curl (the toolchain container has both);
|
||||
# either will do, and the request's own `timings` block is the clock, so neither has to report one.
|
||||
HAVE_CURL=0
|
||||
if command -v curl >/dev/null; then HAVE_CURL=1
|
||||
elif ! command -v wget >/dev/null; then die "curl or wget is needed to talk to the engine"
|
||||
fi
|
||||
BASE="http://127.0.0.1:$PORT"
|
||||
AUTH="Authorization: Bearer test"
|
||||
|
||||
http_get() { # $1 path, $2 out file, $3 timeout s; prints the HTTP status
|
||||
local url="$BASE$1" out="$2" to="${3:-30}" c
|
||||
if [ "$HAVE_CURL" = 1 ]; then
|
||||
c=$(curl -s -m "$to" -o "$out" -w '%{http_code}' -H "$AUTH" "$url" 2>/dev/null) || c=000
|
||||
else
|
||||
wget -S -nv -O "$out" --timeout="$to" --header="$AUTH" "$url" 2>"$out.hdr" || true
|
||||
c=$(awk '/HTTP\//{ c = $2 } END { print (c == "" ? "000" : c) }' "$out.hdr")
|
||||
fi
|
||||
printf '%s\n' "${c:-000}"
|
||||
}
|
||||
|
||||
http_post() { # $1 path, $2 body file, $3 out file, $4 timeout s; prints the HTTP status
|
||||
local url="$BASE$1" body="$2" out="$3" to="${4:-60}" c
|
||||
if [ "$HAVE_CURL" = 1 ]; then
|
||||
c=$(curl -s -m "$to" -o "$out" -w '%{http_code}' \
|
||||
-H "$AUTH" -H "Content-Type: application/json" --data-binary "@$body" "$url" 2>/dev/null) || c=000
|
||||
else
|
||||
wget -S -nv -O "$out" --timeout="$to" --header="$AUTH" \
|
||||
--header="Content-Type: application/json" --post-file="$body" "$url" 2>"$out.hdr" || true
|
||||
c=$(awk '/HTTP\//{ c = $2 } END { print (c == "" ? "000" : c) }' "$out.hdr")
|
||||
fi
|
||||
printf '%s\n' "${c:-000}"
|
||||
}
|
||||
|
||||
# The cards are exclusive: one server at a time, so anything else already running is a refusal and
|
||||
# not something this script may stop (rules 1-3 of AGENTS.md, which also covers radiance-*).
|
||||
RUNNING=$(docker ps -q | wc -l)
|
||||
if [ "$RUNNING" -ne 0 ]; then
|
||||
echo "FAIL: $RUNNING container(s) already running; the cards are exclusive to one server:" >&2
|
||||
docker ps --format ' {{.Names}} {{.Image}}' >&2
|
||||
echo " free them (that is the operator's call) and run this again" >&2
|
||||
exit 2
|
||||
fi
|
||||
mkdir -p "$OUT"
|
||||
|
||||
if [ "$(http_get /health "$OUT/health.probe.json" 2)" != 000 ]; then
|
||||
die "something already answers on 127.0.0.1:$PORT/health; pick PORT=..."
|
||||
fi
|
||||
|
||||
RUN_NAME="" # the one container this script may kill, ever
|
||||
# `docker rm -f` both kills and removes, and is retried until the container is really gone: a
|
||||
# container left behind holds the cards and blocks the next start (and the next operator).
|
||||
stop_arm() {
|
||||
[ -n "$RUN_NAME" ] || return 0
|
||||
local name="$RUN_NAME" i
|
||||
docker rm -f "$name" >/dev/null 2>&1 || true
|
||||
for i in $(seq 1 60); do
|
||||
docker inspect "$name" >/dev/null 2>&1 || { RUN_NAME=""; return 0; }
|
||||
sleep 0.5
|
||||
done
|
||||
echo "FAIL: $name is still present after 30 s; remove it by hand before reusing the cards" >&2
|
||||
RUN_NAME=""
|
||||
return 0
|
||||
}
|
||||
cleanup() { stop_arm; }
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# One line of ~30 tokens, the same generator shape as scripts/kv-union.sh -- and 522 of them is the
|
||||
# c34ad060 prompt byte for byte. Distinct record numbers keep it away from repetitive-text
|
||||
# pathologies, and the closing instruction is what the model continues.
|
||||
gen_prompt() {
|
||||
local lines="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= lines; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
|
||||
gen_prompt "$PROMPT_LINES" > "$OUT/prompt.txt"
|
||||
PROMPT_BYTES=$(sha256sum "$OUT/prompt.txt" | cut -d' ' -f1)
|
||||
[ "$PROMPT_BYTES" = "$PROMPT_SHA" ] || \
|
||||
die "the generated prompt hashes to $PROMPT_BYTES, not the canonical $PROMPT_SHA"
|
||||
|
||||
# temperature 0 and a fixed seed: greedy, so the only thing that can move a token is the engine.
|
||||
# ignore_eos keeps the generated count at MAXTOK on both arms even if the model wants to stop.
|
||||
printf '{"model":"qwen4exp","temperature":0,"seed":%s,"max_tokens":%s,"ignore_eos":true,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"$SEED" "$MAXTOK" "$(cat "$OUT/prompt.txt")" > "$OUT/req.json"
|
||||
|
||||
# The two arms differ in exactly one thing: the streaming flags. Everything else is identical,
|
||||
# including --prefix-cache-ttl 0 (a prefix hit would leave the arm's own prompt uncounted) and
|
||||
# --num-speculative-tokens $SPEC (0 is the shipped shape; SPEC>0 puts it on on both arms).
|
||||
# A ring under one decode step's selection is raised, not refused, and a raised ring
|
||||
# would make the ours arm's block count differ from RESIDENT/4 -- which the ring check below
|
||||
# fails on, so this script can never silently measure a ring the operator did not ask for. At
|
||||
# --max-num-seqs 2 and SPEC 3 that ceiling is 2 x 4 x 513 = 4 104 blocks, under 8 192, so 32 768
|
||||
# tokens is not raised.
|
||||
FLAGS=(--model "$MODEL_IN" --tp 2 --tp-wire exact --max-num-seqs 2 --max-model-len 204800
|
||||
--placement expert_tiered --host-pool-mib 23652 --gpu-headroom-mib 96
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 1024 --prefix-cache-ttl 0
|
||||
--vision-tower-placement ram --num-speculative-tokens "$SPEC" --deterministic
|
||||
--host 127.0.0.1 --port "$PORT" --api-key test)
|
||||
|
||||
start_arm() { # $1 arm, $2 tag; sets RUN_NAME and writes $OUT/$2.server.log
|
||||
local arm="$1" tag="$2"
|
||||
RUN_NAME="kv-rvs-$$-$tag"
|
||||
case "$arm" in
|
||||
ours)
|
||||
docker run --rm --name "$RUN_NAME" --user 1000:1000 -e HOME=/tmp \
|
||||
--device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
--security-opt seccomp=unconfined --network host \
|
||||
-v "$ROOT:/src" -v "$(dirname "$MODEL"):/models" -v /tmp/opencode:/tmp/opencode \
|
||||
-w /src "$TOOLCHAIN" \
|
||||
bash -lc "RADIANCE_HOME=$BUILD/radiance_home exec $BUILD/bin/radiance ${FLAGS[*]} --kv-resident $RESIDENT" \
|
||||
> "$OUT/$tag.server.log" 2>&1 &
|
||||
;;
|
||||
stock)
|
||||
docker run --rm --name "$RUN_NAME" \
|
||||
--device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
--security-opt seccomp=unconfined --network host \
|
||||
-v "$(dirname "$MODEL"):/models" \
|
||||
"$STOCK_IMAGE" "${FLAGS[@]}" \
|
||||
> "$OUT/$tag.server.log" 2>&1 &
|
||||
;;
|
||||
*) die "unknown arm '$arm'" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
# Readiness is /health, never a blind wait. A container that dies while we poll is a hard failure:
|
||||
# it is either a bad flag, a card that someone else took, or a refusal worth reading.
|
||||
wait_health() { # $1 tag
|
||||
local tag="$1" i code status missing=0
|
||||
for i in $(seq 1 240); do
|
||||
# `docker run` returns before the container is in the running state, and --rm removes a
|
||||
# container as soon as its process ends, so only a state that stays gone is a failure.
|
||||
status=$(docker inspect -f '{{.State.Status}}' "$RUN_NAME" 2>/dev/null || echo gone)
|
||||
case "$status" in
|
||||
running|created|restarting) missing=0 ;;
|
||||
*)
|
||||
missing=$(( missing + 1 ))
|
||||
if [ "$missing" -ge 2 ]; then
|
||||
echo "FAIL: $tag's engine exited before /health; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$OUT/$tag.server.log" | tail -12 >&2 || \
|
||||
tail -12 "$OUT/$tag.server.log" >&2
|
||||
return 2
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
code=$(http_get /health "$OUT/$tag.health.json" 3)
|
||||
[ "$code" = 200 ] && { printf '%s\n' "$i" > "$OUT/$tag.health_polls"; return 0; }
|
||||
sleep 1
|
||||
done
|
||||
echo "FAIL: $tag's /health did not answer in 240 s; last errors:" >&2
|
||||
tail -12 "$OUT/$tag.server.log" >&2
|
||||
return 2
|
||||
}
|
||||
|
||||
# The server's own count of the prompt the chat endpoint will render -- the same template, the same
|
||||
# variables -- so the two arms are provably on one input before either is timed.
|
||||
tokenize_count() {
|
||||
printf '{"messages":[{"role":"user","content":"%s"}],"chat_template_kwargs":{"enable_thinking":false}}' \
|
||||
"$(cat "$OUT/prompt.txt")" > "$OUT/tokenize.req.json"
|
||||
http_post /tokenize "$OUT/tokenize.req.json" "$OUT/tokenize.resp.json" 120 >/dev/null
|
||||
grep -o '"count":[0-9]*' "$OUT/tokenize.resp.json" | head -1 | cut -d: -f2 || true
|
||||
}
|
||||
|
||||
# A number from a JSON body: `<key>: <number>`. Bounded to the first hit, which is the one the OAI
|
||||
# usage block carries first (there is no nesting under those keys).
|
||||
jnum() { # $1 file, $2 key
|
||||
grep -o "\"$2\": *[-0-9.eE+]*" "$1" | head -1 | sed 's/.*: *//' || true
|
||||
}
|
||||
|
||||
# The value of one /metrics counter, by its bare name. Anchored on `{` or a space after the name so
|
||||
# `engine_steps_total` cannot pick up `engine_steps_decode_total`; the first sample is the only one
|
||||
# (one model, one engine). Prints nothing when the counter is absent.
|
||||
metric() { # $1 metrics file, $2 counter name (without the radiance: prefix)
|
||||
[ -s "$1" ] || return 0
|
||||
grep -E "^radiance:$2(\\{| )" "$1" 2>/dev/null | head -1 | awk '{print $NF}' || true
|
||||
}
|
||||
|
||||
# The engine's own report of a streamed group at request end, from the log line. Prints
|
||||
# `resolves lookups misses ring union maxmiss claims overflow`, or six dashes if the line is absent.
|
||||
stream_end() { # $1 log
|
||||
grep -E "kv streaming: group '.*' request end:" "$1" | tail -1 |
|
||||
sed -E "s/.*request end: ([0-9]+) resolves, ([0-9]+) lookups, ([0-9]+) misses.*ring ([0-9]+) blocks, largest launch union ([0-9]+) distinct blocks, largest launch misses ([0-9]+), largest launch claims ([0-9]+), overflow (no|LATCHED).*/\1 \2 \3 \4 \5 \6 \7 \8/" \
|
||||
| grep -E '^[0-9]+ ' || echo "- - - - - - - -"
|
||||
}
|
||||
|
||||
# The ring the engine actually carved, from its startup report:
|
||||
# `streaming: 8192 blocks resident in vram_kv at +6885376 = 200.00 MiB, ...`
|
||||
ring_line() { # $1 log -> "blocks MiB"
|
||||
grep -oE "streaming: *[0-9]+ blocks resident in vram_kv at \+[0-9]+ = *[0-9.]+ MiB" "$1" |
|
||||
head -1 | sed -E 's/.*streaming: *([0-9]+) blocks.*= *([0-9.]+) MiB/\1 \2/' || true
|
||||
}
|
||||
|
||||
# `vram_kv 618.00 MiB the cache's share` -- the placement table, not the "budget ... free" line.
|
||||
vram_kv() { grep -E "^ *vram_kv +[0-9.]+ (MiB|GiB) +the cache's share" "$1" | head -1 |
|
||||
sed -E 's/^ *vram_kv +([0-9.]+ (MiB|GiB)).*/\1/' || true; }
|
||||
|
||||
# `experts 11.22 GiB 95% of it` -- residency in the elastic region.
|
||||
experts() { grep -E "^ *experts +[0-9.]+ GiB +[0-9]+% of it" "$1" | head -1 |
|
||||
sed -E 's/^ *experts +([0-9.]+) GiB +([0-9]+)% of it/\1 \2/' || true; }
|
||||
|
||||
# One start: a server, one request, a kill. Kills only the container this script named, and always
|
||||
# before the other arm starts, so the cards never hold two engines. Writes one line of
|
||||
# $OUT/starts.tsv: round arm order ms_step prefill_tps ttft decode_tps wall ptok ctok cached.
|
||||
run_start() { # $1 arm, $2 round, $3 order (1 = first in the round)
|
||||
local arm="$1" round="$2" order="$3"
|
||||
local tag="$arm$round" log="$OUT/$arm$round.server.log" resp="$OUT/$arm$round.json"
|
||||
local t code ptok ctok cached tokencount
|
||||
|
||||
local ord="2nd"; [ "$order" = 1 ] && ord="1st"
|
||||
echo "== $tag: $arm, round $round of $ROUNDS, $ord in the round =="
|
||||
start_arm "$arm" "$tag"
|
||||
wait_health "$tag" || { stop_arm; return 2; }
|
||||
|
||||
tokencount=$(tokenize_count)
|
||||
[ "${tokencount:-0}" = "$TARGET_TOKENS" ] || {
|
||||
echo "FAIL $tag: /tokenize counts this prompt as ${tokencount:-?} tokens, expected $TARGET_TOKENS" >&2
|
||||
stop_arm; return 2
|
||||
}
|
||||
echo "$tokencount" > "$OUT/$tag.tokens"
|
||||
|
||||
t0=$(date +%s%N)
|
||||
code=$(http_post /v1/chat/completions "$OUT/req.json" "$resp" 3600)
|
||||
t1=$(date +%s%N)
|
||||
printf '%s %s\n' "$code" "$(awk -v a="$t0" -v b="$t1" 'BEGIN{printf "%.1f", (b-a)/1e9}')" \
|
||||
> "$OUT/$tag.wall"
|
||||
|
||||
# The counters are read before the kill: /metrics belongs to the live process. Ours' are always
|
||||
# read (the ring's byte and overflow counters live there); stock's only when speculation makes
|
||||
# its step clock the paired quantity.
|
||||
if [ "$arm" = ours ] || [ "$SPEC" -gt 0 ]; then
|
||||
http_get /metrics "$OUT/$tag.metrics" 10 >/dev/null || true
|
||||
fi
|
||||
stop_arm
|
||||
|
||||
if [ "$code" != 200 ]; then
|
||||
echo "FAIL $tag: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
return 2
|
||||
fi
|
||||
|
||||
ptok=$(jnum "$resp" prompt_tokens); ctok=$(jnum "$resp" completion_tokens)
|
||||
cached=$(jnum "$resp" cached_tokens)
|
||||
[ "$ptok" = "$TARGET_TOKENS" ] || {
|
||||
echo "FAIL $tag: usage.prompt_tokens is ${ptok:-?}, expected $TARGET_TOKENS" >&2; return 2; }
|
||||
[ "$ctok" = "$MAXTOK" ] || {
|
||||
echo "FAIL $tag: usage.completion_tokens is ${ctok:-?}, expected $MAXTOK" >&2; return 2; }
|
||||
[ "${cached:-0}" = 0 ] || {
|
||||
echo "FAIL $tag: cached_tokens ${cached:-?} -- a prefix hit would make the arms' prefill" >&2
|
||||
echo " a different workload" >&2; return 2; }
|
||||
|
||||
# The clocks are the engine's own `timings` block, so they do not depend on which HTTP client ran:
|
||||
# prompt_per_second is the prefill, ttft_ms the first token, predicted_per_second the decode (one
|
||||
# token a step with speculation off), predicted_ms the decode wall. `wall` is the harness's total.
|
||||
local ms pre ttft decode_tps dwall wall
|
||||
ms=$(awk -v p="$(jnum "$resp" predicted_per_second)" 'BEGIN{ if (p > 0) printf "%.4f", 1000/p; else print "-" }')
|
||||
decode_tps=$(jnum "$resp" predicted_per_second)
|
||||
pre=$(jnum "$resp" prompt_per_second)
|
||||
ttft=$(awk -v t="$(jnum "$resp" ttft_ms)" 'BEGIN{ printf "%.3f", t/1000 }')
|
||||
dwall=$(awk -v t="$(jnum "$resp" predicted_ms)" 'BEGIN{ printf "%.1f", t/1000 }')
|
||||
wall=$(cut -d' ' -f2 "$OUT/$tag.wall")
|
||||
|
||||
# Speculation on: a step emits up to 1 + SPEC tokens, so 1000/predicted_per_second is ms a token
|
||||
# and is not the quantity two arms are compared on. The engine's own decode step clock is, and
|
||||
# both arms report it under the same name. Draft acceptance is printed per start because stock
|
||||
# starts can be bimodal in it (81.7% and 98.6% on different starts); averaging that hides which
|
||||
# mode a start landed in.
|
||||
local steps="" tokstep="" dnum="" dacc="" dacc_pct="" spf="" smx=""
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
local secs
|
||||
steps=$(metric "$OUT/$tag.metrics" engine_steps_decode_total)
|
||||
secs=$(metric "$OUT/$tag.metrics" engine_step_seconds_decode_total)
|
||||
spf=$(metric "$OUT/$tag.metrics" engine_steps_prefill_total)
|
||||
smx=$(metric "$OUT/$tag.metrics" engine_steps_mixed_total)
|
||||
dnum=$(jnum "$resp" draft_n)
|
||||
dacc=$(jnum "$resp" draft_n_accepted)
|
||||
case "${steps:-x}" in ''|*[!0-9]*) steps="";; esac
|
||||
[ -n "$steps" ] && [ "$steps" -gt 0 ] || {
|
||||
echo "FAIL $tag: no engine_steps_decode_total in /metrics, so ms/step has no clock" >&2
|
||||
return 2; }
|
||||
ms=$(awk -v s="$secs" -v n="$steps" 'BEGIN{ if (n > 0 && s > 0) printf "%.4f", 1000*s/n; else print "-" }')
|
||||
[ "$ms" != "-" ] || {
|
||||
echo "FAIL $tag: engine_step_seconds_decode_total is '${secs:-?}' for $steps steps" >&2
|
||||
return 2; }
|
||||
tokstep=$(awk -v n="$MAXTOK" -v s="$steps" 'BEGIN{ printf "%.3f", n/s }')
|
||||
# A start whose drafter never ran is not a spec-on measurement, and neither is one whose
|
||||
# acceptance counters are missing: both are the shape, not the result.
|
||||
case "${dnum:-x}${dacc:-x}" in *[!0-9]*) dnum="";; esac
|
||||
[ -n "$dnum" ] && [ "$dnum" -gt 0 ] || {
|
||||
echo "FAIL $tag: timings carries no draft_n under --num-speculative-tokens $SPEC," >&2
|
||||
echo " so the drafter did not run and this is not a spec-on start" >&2; return 2; }
|
||||
[ "${dacc:-0}" -le "$dnum" ] || {
|
||||
echo "FAIL $tag: draft_n_accepted ${dacc:-?} exceeds draft_n $dnum" >&2; return 2; }
|
||||
dacc_pct=$(awk -v a="$dacc" -v n="$dnum" 'BEGIN{ printf "%.1f", 100*a/n }')
|
||||
fi
|
||||
|
||||
if [ "$arm" = ours ]; then
|
||||
# The ring checks. A run whose ring did not stream, overflowed, or held a different number of
|
||||
# blocks is not the configuration this script claims to measure, so it stops here.
|
||||
grep -q "kv streaming: [0-9].*stream (" "$log" || {
|
||||
echo "FAIL $tag: no 'group(s) stream' startup line: --kv-resident $RESIDENT did not" >&2
|
||||
echo " leave the group streaming" >&2; return 2; }
|
||||
read -r res lk mi rb mu mm cl ov < <(stream_end "$log")
|
||||
[ "${ov:-}" = no ] || { echo "FAIL $tag: ring overflow '$ov' on the request-end line" >&2; return 2; }
|
||||
[ "${rb:-0}" = "$RING_BLOCKS" ] || {
|
||||
echo "FAIL $tag: the ring holds ${rb:-?} blocks, expected $RING_BLOCKS for $RESIDENT tokens" >&2
|
||||
return 2; }
|
||||
[ "${mu:-0}" -le "${rb:-0}" ] || {
|
||||
echo "FAIL $tag: largest launch union ${mu:-?} exceeds the ${rb:-?}-block ring" >&2; return 2; }
|
||||
[ "${mi:-0}" -gt 0 ] || {
|
||||
echo "FAIL $tag: no misses -- the ring covered the context, so nothing streamed" >&2; return 2; }
|
||||
read -r ring_blocks ring_mib < <(ring_line "$log") || true
|
||||
[ "${ring_blocks:-0}" = "$RING_BLOCKS" ] || {
|
||||
echo "FAIL $tag: startup reports ${ring_blocks:-?} blocks resident, expected $RING_BLOCKS" >&2
|
||||
return 2; }
|
||||
printf '%s %s %s %s %s %s %s %s\n' "$res" "$lk" "$mi" "$rb" "$mu" "$mm" "$cl" "$ov" \
|
||||
> "$OUT/$tag.stream"
|
||||
printf '%s %s\n' "${ring_blocks:-?}" "${ring_mib:-?}" > "$OUT/$tag.ring"
|
||||
else
|
||||
grep -q "kv streaming: [0-9].*stream (" "$log" && {
|
||||
echo "FAIL $tag: the stock arm streamed, so it was not the stock configuration" >&2; return 2; }
|
||||
fi
|
||||
printf '%s\n' "$(vram_kv "$log")" > "$OUT/$tag.vram_kv"
|
||||
printf '%s\n' "$(experts "$log")" > "$OUT/$tag.experts"
|
||||
|
||||
# Speculation's own columns go on the same line, after the twelve: every reader of columns 1-12
|
||||
# above is unchanged, so a SPEC=0 run writes the twelve-column starts.tsv, byte for byte.
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s\n' \
|
||||
"$round" "$arm" "$order" "$ms" "$pre" "$ttft" "$decode_tps" "$dwall" "$ptok" "$ctok" \
|
||||
"${cached:-0}" "$wall" "$steps" "$tokstep" "$dnum" "$dacc" "$dacc_pct" "$spf" "$smx" \
|
||||
"$SPEC" >> "$OUT/starts.tsv"
|
||||
else
|
||||
printf '%s %s %s %s %s %s %s %s %s %s %s %s\n' \
|
||||
"$round" "$arm" "$order" "$ms" "$pre" "$ttft" "$decode_tps" "$dwall" "$ptok" "$ctok" \
|
||||
"${cached:-0}" "$wall" >> "$OUT/starts.tsv"
|
||||
fi
|
||||
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf ' ms/step %s, %.2f tok/s, %.3f tok/step, %s decode steps, draft %s/%s = %.1f%% accepted, prefill %.1f tok/s, request %.1f s\n' \
|
||||
"$ms" "$decode_tps" "$tokstep" "$steps" "$dacc" "$dnum" "$dacc_pct" "$pre" "$wall"
|
||||
else
|
||||
printf ' ms/step %s, decode %.2f tok/s, prefill %.1f tok/s, TTFT %.3f s, decode wall %.1f s, request %.1f s\n' \
|
||||
"$ms" "$decode_tps" "$pre" "$ttft" "$dwall" "$wall"
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
# t quantiles, two-sided. The table covers the round counts this script is usable at; beyond 30 the
|
||||
# normal value is within 0.2% and the interval is dominated by the spread, not the quantile.
|
||||
tval() { # $1 df, $2 95|90
|
||||
local df="$1" q="$2"
|
||||
if [ "$q" = 95 ]; then
|
||||
case "$df" in
|
||||
1) echo 12.706 ;; 2) echo 4.303 ;; 3) echo 3.182 ;; 4) echo 2.776 ;; 5) echo 2.571 ;;
|
||||
6) echo 2.447 ;; 7) echo 2.365 ;; 8) echo 2.306 ;; 9) echo 2.262 ;; 10) echo 2.228 ;;
|
||||
11) echo 2.201 ;; 12) echo 2.179 ;; 13) echo 2.160 ;; 14) echo 2.145 ;; 15) echo 2.131 ;;
|
||||
16) echo 2.120 ;; 17) echo 2.110 ;; 18) echo 2.101 ;; 19) echo 2.093 ;; 20) echo 2.086 ;;
|
||||
21) echo 2.080 ;; 22) echo 2.074 ;; 23) echo 2.069 ;; 24) echo 2.064 ;; 25) echo 2.060 ;;
|
||||
26) echo 2.056 ;; 27) echo 2.052 ;; 28) echo 2.048 ;; 29) echo 2.045 ;; 30) echo 2.042 ;;
|
||||
*) echo 1.960 ;;
|
||||
esac
|
||||
else
|
||||
case "$df" in
|
||||
1) echo 6.314 ;; 2) echo 2.920 ;; 3) echo 2.353 ;; 4) echo 2.132 ;; 5) echo 2.015 ;;
|
||||
6) echo 1.943 ;; 7) echo 1.895 ;; 8) echo 1.860 ;; 9) echo 1.833 ;; 10) echo 1.812 ;;
|
||||
11) echo 1.796 ;; 12) echo 1.782 ;; 13) echo 1.771 ;; 14) echo 1.761 ;; 15) echo 1.753 ;;
|
||||
16) echo 1.746 ;; 17) echo 1.740 ;; 18) echo 1.734 ;; 19) echo 1.729 ;; 20) echo 1.725 ;;
|
||||
21) echo 1.721 ;; 22) echo 1.717 ;; 23) echo 1.714 ;; 24) echo 1.711 ;; 25) echo 1.708 ;;
|
||||
26) echo 1.706 ;; 27) echo 1.703 ;; 28) echo 1.701 ;; 29) echo 1.699 ;; 30) echo 1.697 ;;
|
||||
*) echo 1.645 ;;
|
||||
esac
|
||||
fi
|
||||
}
|
||||
|
||||
printf 'prompt sha256 %s (%s bytes), %s tokens, request sha256 %s\n' \
|
||||
"$PROMPT_BYTES" "$(wc -c < "$OUT/prompt.txt")" "$TARGET_TOKENS" \
|
||||
"$(sha256sum "$OUT/req.json" | cut -d' ' -f1)"
|
||||
printf 'arms: stock=%s ours=%s --kv-resident %s (%s blocks)\n' \
|
||||
"$STOCK_IMAGE" "$BUILD/bin/radiance" "$RESIDENT" "$RING_BLOCKS"
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
printf 'speculation: --num-speculative-tokens %s on both arms; ms/step = engine_step_seconds_decode_total /\n' "$SPEC"
|
||||
printf ' engine_steps_decode_total (one step emits up to %s tokens), acceptance = timings.draft_n_accepted / draft_n\n' \
|
||||
"$(( SPEC + 1 ))"
|
||||
printf 'rounds: %s per arm, %s starts, ~%s min\n\n' "$ROUNDS" "$(( ROUNDS * 2 ))" "$(( ROUNDS * 9 / 6 ))"
|
||||
else
|
||||
printf 'rounds: %s per arm, %s starts, ~%s min\n\n' "$ROUNDS" "$(( ROUNDS * 2 ))" "$(( ROUNDS * 9 ))"
|
||||
fi
|
||||
|
||||
: > "$OUT/starts.tsv"
|
||||
STARTED=$(date +%s)
|
||||
r=1
|
||||
while [ "$r" -le "$ROUNDS" ]; do
|
||||
# ABBA: the arm that goes first alternates by round, so the two arms share first position and no
|
||||
# arm is always measured on the cooler or hotter side of a round.
|
||||
if [ $(( r % 2 )) -eq 1 ]; then
|
||||
run_start stock "$r" 1 || exit 2
|
||||
run_start ours "$r" 2 || exit 2
|
||||
else
|
||||
run_start ours "$r" 1 || exit 2
|
||||
run_start stock "$r" 2 || exit 2
|
||||
fi
|
||||
r=$(( r + 1 ))
|
||||
done
|
||||
ELAPSED=$(( $(date +%s) - STARTED ))
|
||||
|
||||
# ---- ours' counters, per round ----------------------------------------------------------------
|
||||
echo
|
||||
echo "== ours, per round (the engine's own request-end line; bytes and overflow from /metrics) =="
|
||||
printf '%-5s %9s %11s %9s %6s %9s %10s %9s %8s\n' \
|
||||
round resolves lookups misses ring union maxmiss bytes overflow
|
||||
for r in $(seq 1 "$ROUNDS"); do
|
||||
read -r res lk mi rb mu mm cl ov < "$OUT/ours$r.stream"
|
||||
bytes=$(grep -E "^radiance:kv_stream_bytes_total" "$OUT/ours$r.metrics" 2>/dev/null | head -1 |
|
||||
awk '{print $NF}' || true)
|
||||
ovm=$(grep -E "^radiance:stream_overflow_total" "$OUT/ours$r.metrics" 2>/dev/null | head -1 |
|
||||
awk '{print $NF}' || true)
|
||||
printf '%-5s %9s %11s %9s %6s %9s %10s %9s %8s\n' \
|
||||
"$r" "$res" "$lk" "$mi" "$rb" "$mu" "$mm" "${bytes:--}" "${ovm:-$ov}"
|
||||
done
|
||||
read -r ring_blocks ring_mib < "$OUT/ours1.ring"
|
||||
echo "ring (ours): ${ring_blocks} blocks = ${ring_mib} MiB resident in vram_kv, ${RESIDENT} tokens"
|
||||
echo "vram_kv: ours $(cat "$OUT/ours1.vram_kv") stock $(cat "$OUT/stock1.vram_kv")"
|
||||
echo "experts: ours $(awk '{print $1 " GiB (" $2 "%)"}' "$OUT/ours1.experts") of the elastic region,"
|
||||
echo " stock $(awk '{print $1 " GiB (" $2 "%)"}' "$OUT/stock1.experts")"
|
||||
|
||||
# ---- both arms, per round ---------------------------------------------------------------------
|
||||
echo
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo "== both arms, per round (ms/step from the engine's decode step clock; delta = ours over stock) =="
|
||||
else
|
||||
echo "== both arms, per round (ms/step from predicted_per_second; delta = ours over stock) =="
|
||||
fi
|
||||
printf '%-5s %-6s %10s %10s %9s %10s %10s\n' round first ms_stock ms_ours delta% stock_tps ours_tps
|
||||
for r in $(seq 1 "$ROUNDS"); do
|
||||
sms=$(awk -v r="$r" '$1 == r && $2 == "stock" {print $4}' "$OUT/starts.tsv")
|
||||
oms=$(awk -v r="$r" '$1 == r && $2 == "ours" {print $4}' "$OUT/starts.tsv")
|
||||
stp=$(awk -v r="$r" '$1 == r && $2 == "stock" {print $7}' "$OUT/starts.tsv")
|
||||
otp=$(awk -v r="$r" '$1 == r && $2 == "ours" {print $7}' "$OUT/starts.tsv")
|
||||
first=$(awk -v r="$r" '$1 == r && $3 == 1 {print $2}' "$OUT/starts.tsv")
|
||||
awk -v r="$r" -v f="$first" -v s="$sms" -v o="$oms" -v st="$stp" -v ot="$otp" 'BEGIN{
|
||||
printf "%-5s %-6s %10.3f %10.3f %+8.2f%% %10.2f %10.2f\n", r, f, s, o, 100*(o/s-1), st, ot }'
|
||||
done
|
||||
|
||||
# ---- speculation: per start, because acceptance is the bimodal variable ----------------------
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo
|
||||
echo "== speculation, per start (acceptance per start: stock starts can be bimodal) =="
|
||||
printf '%-7s %-6s %8s %9s %8s %6s %14s %7s %7s\n' \
|
||||
start arm ms_step tok/s tok/step steps accepted/drafted accept% p/m/d
|
||||
while read -r rnd arm ord ms pre ttft dtps dwall ptok ctok cached wall \
|
||||
steps tokstep dnum dacc dpct spf smx spec; do
|
||||
printf '%-7s %-6s %8.4f %9.2f %8.3f %6s %14s %7.1f%% %s/%s/%s\n' \
|
||||
"$arm$rnd" "$arm" "$ms" "$dtps" "$tokstep" "$steps" "$dacc/$dnum" "$dpct" \
|
||||
"$spf" "$smx" "$steps"
|
||||
done < "$OUT/starts.tsv"
|
||||
|
||||
echo
|
||||
echo "== draft acceptance per arm, sorted (two clusters here = a bimodal winner) =="
|
||||
for arm in stock ours; do
|
||||
list=$(awk -v a="$arm" '$2 == a { printf "%.1f ", $17 }' "$OUT/starts.tsv")
|
||||
stats=$(awk -v a="$arm" '$2 == a { v[n++] = $17; s += $17 }
|
||||
END { if (!n) { print "no starts"; exit }
|
||||
m = s/n; mn = v[0]; mx = v[0]
|
||||
for (i = 0; i < n; i++) { if (v[i] < mn) mn = v[i]; if (v[i] > mx) mx = v[i] }
|
||||
ss = 0; for (i = 0; i < n; i++) ss += (v[i]-m)^2
|
||||
printf "n=%d mean %.1f%% min %.1f%% max %.1f%% sd %.2f points", n, m, mn, mx,
|
||||
(n > 1 ? sqrt(ss/(n-1)) : 0) }' "$OUT/starts.tsv")
|
||||
printf '%-6s %s %s\n' "$arm" "$list" "$stats"
|
||||
done
|
||||
|
||||
echo
|
||||
echo "== paired tok/s (secondary: under speculation the arms do not emit the same tokens, so a"
|
||||
echo " tok/s ratio mixes step time with tokens a step and is not a speed ratio)"
|
||||
awk '$2 == "stock" { s[$1] = $7 } $2 == "ours" { o[$1] = $7 }
|
||||
END { for (r = 1; r <= '"$ROUNDS"'; r++) { d = 100*(o[r]/s[r]-1); n = r;
|
||||
t += d; if (r == 1 || d < mn) mn = d; if (r == 1 || d > mx) mx = d }
|
||||
printf " mean %+.2f%%, range %+.2f%% .. %+.2f%%\n", t/n, mn, mx }' "$OUT/starts.tsv"
|
||||
fi
|
||||
|
||||
# ---- arm summaries ----------------------------------------------------------------------------
|
||||
echo
|
||||
echo "== per-arm means over the run =="
|
||||
printf '%-7s %12s %10s %12s %12s %10s\n' arm prefill_tps TTFT_s decode_tps decode_wall_s ms_step
|
||||
for arm in stock ours; do
|
||||
awk -v a="$arm" '$2 == a { p+=$5; t+=$6; d+=$7; w+=$8; m+=$4; n++ }
|
||||
END { printf "%-7s %12.1f %10.3f %12.2f %12.1f %10.3f\n", a, p/n, t/n, d/n, w/n, m/n }' \
|
||||
"$OUT/starts.tsv"
|
||||
done
|
||||
|
||||
# ---- paired statistics ------------------------------------------------------------------------
|
||||
awk -v a=stock '$2 == a { s[$1] = $4 } $2 == "ours" { o[$1] = $4 } END {
|
||||
for (r = 1; r <= '"$ROUNDS"'; r++) printf "%.6f\n", 100*(o[r]/s[r] - 1) }' \
|
||||
"$OUT/starts.tsv" > "$OUT/deltas.txt"
|
||||
|
||||
read -r n mean sd sem ci95 ci90 min max mdb n1 n09 < <(
|
||||
awk -v t95="$(tval $(( ROUNDS - 1 )) 95)" \
|
||||
-v t90="$(tval $(( ROUNDS - 1 )) 90)" '
|
||||
{ d[NR] = $1; s += $1 }
|
||||
END {
|
||||
m = s/NR; ss = 0
|
||||
for (i = 1; i <= NR; i++) ss += (d[i] - m)^2
|
||||
sd = NR > 1 ? sqrt(ss/(NR-1)) : 0
|
||||
sem = sd/sqrt(NR)
|
||||
mn = d[1]; mx = d[1]
|
||||
for (i = 2; i <= NR; i++) { if (d[i] < mn) mn = d[i]; if (d[i] > mx) mx = d[i] }
|
||||
a1 = (2.8*sd/1.0)^2; a9 = (2.8*sd/0.9)^2
|
||||
r1 = int(a1) + (a1 > int(a1) ? 1 : 0); if (r1 < 2) r1 = 2
|
||||
r9 = int(a9) + (a9 > int(a9) ? 1 : 0); if (r9 < 2) r9 = 2
|
||||
printf "%d %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.4f %.1f %.1f\n",
|
||||
NR, m, sd, sem, t95*sem, t90*sem, mn, mx, 2.8*sd/sqrt(NR), r1, r9
|
||||
}' "$OUT/deltas.txt")
|
||||
|
||||
echo
|
||||
echo "== the paired deltas (ours against stock, same round; + = ours slower) =="
|
||||
r=1
|
||||
while [ "$r" -le "$ROUNDS" ]; do
|
||||
printf 'round %-3s %+7.2f%%\n' "$r" "$(sed -n "${r}p" "$OUT/deltas.txt")"
|
||||
r=$(( r + 1 ))
|
||||
done
|
||||
echo "paired mean $mean% sd $sd sem $sem range $min% .. $max%"
|
||||
echo "95% CI $mean ± $ci95 (t, $(( ROUNDS - 1 )) df) -> $(awk -v m="$mean" -v c="$ci95" \
|
||||
'BEGIN{printf "%.2f%% .. %.2f%%", m-c, m+c}')"
|
||||
echo "90% CI $mean ± $ci90"
|
||||
echo "unpaired: $(awk '$2 == "stock" { s += $4; ns++ } $2 == "ours" { o += $4; no++ }
|
||||
END { printf "%+.2f%%", 100*((o/no)/(s/ns) - 1) }' "$OUT/starts.tsv") (meaning what pairing bought or cost)"
|
||||
echo
|
||||
# Two readings of the same n. The run's own interval is the honest resolution: at n=2 the sd has one
|
||||
# degree of freedom, so the t interval is wide and the sd is barely estimated. The sd-based minimum
|
||||
# detectable difference at a cross-arm sd of 1.4 points is what the header's round counts come from,
|
||||
# so both are printed rather than whichever flatters this run.
|
||||
echo "at n=$n this run's interval is ±$(awk -v c="$ci95" 'BEGIN{printf "%.2f%%", c}') (95%), and from its own"
|
||||
echo " sd ($sd points) the minimum detectable difference would be $(awk -v m="$mdb" 'BEGIN{printf "%.2f%%", m}')"
|
||||
echo " (2.8 x sd / sqrt(n), 95% two-sided, 80% power) -- with $(( ROUNDS - 1 )) df read the interval, not the sd."
|
||||
echo " At that cross-arm sd of 1.4 points: n=2 detects 2.8%, n=4 2.0%, n=16 1.0%, n=19-20 0.9%."
|
||||
echo " This run's own sd would need $(awk -v n="$n1" 'BEGIN{printf "%.0f", n}') paired rounds for 1% and $(awk -v n="$n09" 'BEGIN{printf "%.0f", n}') for 0.9%."
|
||||
awk -v m="$mean" -v c="$ci95" 'BEGIN{
|
||||
where = (m - c > 0 || m + c < 0) ? "excludes" : "includes"
|
||||
printf "reading: %+.2f%% %s zero (95%%): ", m, where
|
||||
}'
|
||||
if awk -v m="$mean" -v c="$ci95" 'BEGIN{ exit !(m - c > 0 || m + c < 0) }'; then
|
||||
echo "ours is slower by a margin this run can resolve"
|
||||
else
|
||||
echo "the gap is inside this run's noise; state it as a band, and raise ROUNDS to narrow it"
|
||||
fi
|
||||
if [ "$SPEC" -gt 0 ]; then
|
||||
echo
|
||||
echo "speculation read: the sd above carries the draft-acceptance mix, which is the bimodal"
|
||||
echo " variable (81.7% and 98.6% on different stock starts). The acceptance table is the"
|
||||
echo " evidence on whether the modes split evenly across the arms; whichever arm drew the high"
|
||||
echo " mode more often has part of this delta from acceptance, not from streaming."
|
||||
fi
|
||||
echo "wall: ${ELAPSED} s for $(( ROUNDS * 2 )) starts; raw under $OUT"
|
||||
# A container that is being removed still shows in `docker ps` for a moment after `docker inspect`
|
||||
# starts failing, so let the count settle instead of reporting a leak that is not there.
|
||||
LEFT=1
|
||||
for i in $(seq 1 20); do
|
||||
LEFT=$(docker ps -q | wc -l)
|
||||
if [ "$LEFT" -eq 0 ]; then break; fi
|
||||
sleep 0.5
|
||||
done
|
||||
echo "leftover containers: $LEFT"
|
||||
|
||||
exit 0
|
||||
Executable
+224
@@ -0,0 +1,224 @@
|
||||
#!/bin/bash
|
||||
# Prove Phase 2's prefill staging: with a ring smaller than the context, a long prompt prefilled
|
||||
# above qsa_exact_to is byte-identical to streaming off (no --kv-resident at all), and every staged
|
||||
# layer was copied into the one-layer view in order before its attention.
|
||||
#
|
||||
# The ring is the operator's floor, --kv-resident 32768 (8 192 blocks of 4). The document is ~64k
|
||||
# tokens, so every prefill chunk whose history is longer than 32 768 tokens must take the view and
|
||||
# stream: the ring cannot hold it. A ~16k prompt on the same ring fits it and would stage nothing
|
||||
# (that is the 17k variant this script replaced), and a ring below the floor is not a configuration
|
||||
# the engine runs anyway -- it raises it -- so this script keeps the 64k document and the 32 768
|
||||
# ring. Eviction pressure comes from the length of the context, not from shrinking the ring.
|
||||
#
|
||||
# This is the pass that matters: a byte-identical result is only evidence if the run actually staged
|
||||
# something, and a staged prefill that reads the previous layer's cache is still byte-identical to
|
||||
# itself. The ring at the floor forces a staged chunk from 32 768 tokens on, so do not shorten the
|
||||
# document to make the run cheaper.
|
||||
#
|
||||
# Run inside the toolchain container (io_uring and the cards), with the model mounted:
|
||||
# docker run --rm --security-opt seccomp=unconfined --user 1000:1000 -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
|
||||
# -v /tmp/opencode:/out -w /src rad-toolchain:latest bash -lc 'bash scripts/kv-stage-parity-64k.sh'
|
||||
#
|
||||
# One fresh server per arm, temperature 0, --deterministic, one request a server. Exit 0 only if
|
||||
# both arms served, the bytes match, the on arm staged in layer order, and the pool report shows
|
||||
# the streamed configuration; 1 on a byte difference or missing staging; 2 if an arm failed.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-/out/build-kl}" # the tree the fix was measured on; override with BUILD=...
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8124}"
|
||||
OUT="${OUT:-/out/kv-stage-parity-64k}"
|
||||
LINES="${LINES:-2120}" # ~64k prompt tokens: well past the 32 768-token ring
|
||||
MAXTOK="${MAXTOK:-64}"
|
||||
SEED="${SEED:-12345}"
|
||||
MAXLEN="${MAXLEN:-81920}" # the prompt, the generated tokens and the template
|
||||
# 8 192 blocks of 4 tokens: the floor. Above decode's one-step union and below the document, so the
|
||||
# second half of the prefill must stage instead of resolving. Speculation stays 0 here: this script
|
||||
# measures the stage path, and a spec arm would only change the ring's raise arithmetic.
|
||||
RESIDENT="${RESIDENT:-32768}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home"
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
gen_prompt() {
|
||||
local n="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= n; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
gen_prompt "$LINES" > "$OUT/prompt.txt"
|
||||
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# $1 arm name, $2 the streaming flags, $3.. extra environment VAR=value.
|
||||
run_arm() {
|
||||
# The off arm passes no flags: with `set -u` a bare $2 made the whole script die on its first
|
||||
# arm, so the flags and the trailing VAR=value list are both optional.
|
||||
local arm="$1" flags="${2:-}"
|
||||
shift; [ "$#" -gt 0 ] && shift
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
local envs=("$@")
|
||||
echo "== $arm: $flags ${envs[*]:-} =="
|
||||
( exec env "${envs[@]}" "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len "$MAXLEN" --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
$flags --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 240); do
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup; return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || true
|
||||
cleanup; return 1
|
||||
fi
|
||||
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$OUT/prompt.txt")
|
||||
printf '{"model":"%s","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"qwen4exp" "$SEED" "$MAXTOK" "$prompt_text" > "$req"
|
||||
code=$(curl -s -m 1800 -o "$resp" -w '%{http_code}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || true)
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /v1/chat/completions answered $code; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup; return 1
|
||||
fi
|
||||
content_of "$resp" > "$OUT/$arm.txt"
|
||||
if [ ! -s "$OUT/$arm.txt" ]; then echo "FAIL $arm: empty completion text" >&2; cleanup; return 1; fi
|
||||
|
||||
local ptok ctok cache
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
ctok=$(grep -o '"completion_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
cache=$(grep -o '"cached_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2)
|
||||
echo " prompt_tokens=$ptok completion_tokens=$ctok cached_tokens=$cache"
|
||||
echo " sha256 $(sha256sum "$OUT/$arm.txt" | cut -d' ' -f1) ($(wc -c < "$OUT/$arm.txt") bytes)"
|
||||
echo "$ptok $ctok $cache" > "$OUT/$arm.counts"
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
# The layer sequence the prefill stages. Each staged pass visits the group's layers in order, so
|
||||
# the trace is runs of one strictly-increasing sequence; every run after the first must equal the
|
||||
# first (a skipped or repeated stage breaks both properties).
|
||||
check_stage_order() {
|
||||
local log="$OUT/on.log"
|
||||
grep 'kv streaming: stage layer ' "$log" |
|
||||
sed -E 's/.*stage layer ([0-9]+).*/\1/' > "$OUT/stages.txt" || true
|
||||
local n
|
||||
n=$(wc -l < "$OUT/stages.txt")
|
||||
echo " stage layers traced: $n"
|
||||
if [ "$n" -lt 2 ]; then
|
||||
echo "FAIL: no staged layers were traced; the prefill did not take the stage view" >&2
|
||||
return 1
|
||||
fi
|
||||
awk '
|
||||
{ l[NR] = $1 + 0 }
|
||||
END {
|
||||
# The first run ends at the first non-increase.
|
||||
end = 1
|
||||
while (end < NR && l[end + 1] > l[end]) end++
|
||||
if (end < 2) { print "FAIL: the first staged run is not increasing"; exit 1 }
|
||||
for (i = 2; i <= end; ++i)
|
||||
if (l[i] <= l[i-1]) { print "FAIL: layers out of order at line " i; exit 1 }
|
||||
# Every later run must repeat the first exactly.
|
||||
i = end + 1
|
||||
while (i <= NR) {
|
||||
for (j = 1; j <= end; ++j) {
|
||||
if (i > NR) break
|
||||
if (l[i] != l[j]) { print "FAIL: stage run at line " i " differs from the first"; exit 1 }
|
||||
++i
|
||||
}
|
||||
}
|
||||
printf(" one staged run of %d layers, repeated %d time(s), in order\n", end, (NR / end) - 1)
|
||||
}' "$OUT/stages.txt" || return 1
|
||||
if grep -q "refused op 'kv_resolve'" "$log"; then
|
||||
echo "FAIL: kv_resolve was refused at issue on the staged arm" >&2; return 1
|
||||
fi
|
||||
if grep -q "GPU memory fault" "$log"; then
|
||||
echo "FAIL: a GPU memory fault was reported" >&2; return 1
|
||||
fi
|
||||
return 0
|
||||
}
|
||||
|
||||
FAILED=0
|
||||
run_arm off || FAILED=1
|
||||
run_arm on "--kv-resident $RESIDENT" RADIANCE_KV_STAGE_TRACE=1 || FAILED=1
|
||||
|
||||
if [ "$FAILED" -eq 0 ]; then
|
||||
if ! grep -q "kv streaming: prefill staging" "$OUT/on.log"; then
|
||||
echo "FAIL: the streaming configuration is not in the on arm's log" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
read -r ptok _ _ < "$OUT/on.counts"
|
||||
if [ "${ptok:-0}" -le 2051 ]; then
|
||||
echo "FAIL: the prompt is $ptok tokens, at or below qsa_exact_to 2051; prefill was dense," >&2
|
||||
echo " so raise LINES and rerun: this run would not prove the sparse staged path" >&2
|
||||
FAILED=1
|
||||
elif [ "${ptok:-0}" -le "$RESIDENT" ]; then
|
||||
echo "FAIL: the prompt is $ptok tokens, at or under the $RESIDENT-token ring: it fits, so" >&2
|
||||
echo " nothing streamed and the stage was not taken. Raise LINES, never lower RESIDENT" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
check_stage_order || FAILED=1
|
||||
fi
|
||||
|
||||
echo "== KV pool before and after (from each arm's vram split and kv report) =="
|
||||
grep -E "vram split|^I kv:|^I kv .*streaming" "$OUT/off.log" | sed 's/^/ off: /' || true
|
||||
grep -E "vram split|^I kv:|^I kv .*streaming|prefill staging" "$OUT/on.log" | sed 's/^/ on: /' || true
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, the bytes were not compared, or staging was not proven" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
echo "== compare =="
|
||||
cmp "$OUT/off.txt" "$OUT/on.txt" || { echo "FAIL: the two arms differ" >&2; exit 1; }
|
||||
echo "PASS: byte-identical with a 32 768-token floor ring, prefill staged in layer order"
|
||||
Executable
+264
@@ -0,0 +1,264 @@
|
||||
#!/bin/bash
|
||||
# Measure how large a KV streaming ring actually has to be: the union of distinct blocks one
|
||||
# kv_resolve launch selects, as a function of context length.
|
||||
#
|
||||
# Why this exists: a streamed group's ring must hold every distinct block one launch selects. At
|
||||
# decode that is at most max_seqs * (topk + 1) -- a thousand-odd. Above qsa_exact_to prefill issues
|
||||
# one sparse row per query, so a launch (qsa_gq_rows = max_tok rows wide) can in principle select the
|
||||
# whole live history, which is why docs/KV-STREAMING.md planned a layer-bulk prefill staging path
|
||||
# (Phase 2). The design note assumed that worst case; this script measures the real union. It runs
|
||||
# with the 32 768-token floor `--kv-resident` -- the smallest ring this engine is run with, and one
|
||||
# the engine does not raise -- on contexts longer than that ring, so misses actually happen and the
|
||||
# counters move. Nothing below the floor is measured: a smaller ring is not a stress shape (the
|
||||
# engine raises one under a decode step's selection) and eviction pressure comes from the context.
|
||||
# It reads the numbers the engine reports at prefill completion and request end (Engine::stream_probe,
|
||||
# `ctl[10]`/`ctl[11]` of libref/ref_kvstream.cpp's control block).
|
||||
#
|
||||
# A ring that a launch overflows is not served: the resolve latches `ctl[3]`, and the request is
|
||||
# FAILED at prefill completion with the ring size and the union that did not fit. Those arms report
|
||||
# the union from that message and the completed-count line; nothing is recomputed by hand here.
|
||||
#
|
||||
# The last arm is the store/resolve staleness check: a prompt below qsa_exact_to (so prefill is dense
|
||||
# and issues no resolve) streamed into a ring smaller than the history it decodes over, so decode
|
||||
# evicts and re-copies blocks continuously, compared byte for byte against streaming off (no
|
||||
# --kv-resident). A stale copy shows up as wrong text there, which no counter would reveal.
|
||||
#
|
||||
# Run this INSIDE the toolchain container, with the model mounted:
|
||||
# docker run --rm --security-opt seccomp=unconfined -e HOME=/tmp \
|
||||
# --device /dev/kfd --device /dev/dri --group-add 990 --group-add 44 \
|
||||
# -v /home/j/src/radiance-kv-cache-streaming:/src -v /home/j/Documents/rad/models:/models \
|
||||
# -v /tmp/opencode:/tmp/opencode -w /src rad-toolchain:latest bash -lc 'bash scripts/kv-union.sh'
|
||||
#
|
||||
# Paths are in-container: MODEL=/models/... and BUILD=/tmp/opencode/build-kv2 (host paths are not
|
||||
# visible inside it). Exit status: 0 if every arm reported, 1 if the stale arm's texts differ, 2 if
|
||||
# an arm did not serve or did not answer at all.
|
||||
set -euo pipefail
|
||||
|
||||
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
BUILD="${BUILD:-/tmp/opencode/build-kv2}"
|
||||
MODEL="${MODEL:-/models/qwen3.8-next-flash-fp8-iq4r-moe.rad}"
|
||||
PORT="${PORT:-8124}"
|
||||
OUT="${OUT:-/tmp/opencode/kv-union}"
|
||||
# The measurement arms climb 32768 -> 131072 tokens (8 192 -> 32 768 blocks of 4), starting at the
|
||||
# floor. Nothing here runs a ring below 32 768: that is the smallest ring the operator runs, and a
|
||||
# rung under it would measure a configuration the engine either raises (a decode step's selection
|
||||
# under speculation) or that nobody deploys. A prompt at or under the ring is not a streaming case
|
||||
# at all -- the group keeps its cache resident and no resolve is issued -- so every arm's context is
|
||||
# longer than the floor ring. The stale arm's ring is the floor too, and its history is pushed past
|
||||
# it by a ~34k-token prompt plus 512 decoded tokens, so decode evicts and re-copies every step.
|
||||
STALE_RING="${STALE_RING:-32768}"
|
||||
SEED="${SEED:-12345}"
|
||||
|
||||
BIN="$BUILD/bin/radiance"
|
||||
export RADIANCE_HOME="$BUILD/radiance_home" # absolute: the engine will not find the kernels without it
|
||||
[ -x "$BIN" ] || { echo "no engine at $BIN (build it first; this script builds nothing)" >&2; exit 2; }
|
||||
[ -f "$MODEL" ] || { echo "no model at $MODEL" >&2; exit 2; }
|
||||
command -v curl >/dev/null || { echo "curl is needed" >&2; exit 2; }
|
||||
|
||||
mkdir -p "$OUT"
|
||||
SERVER_PID=""
|
||||
cleanup() {
|
||||
# Only our own process, by the pid this script recorded: the engine is one process (its TP ranks
|
||||
# are threads), so there is no group to sweep and nothing else can be hit by mistake. No pkill.
|
||||
if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
kill -TERM "$SERVER_PID" 2>/dev/null || true
|
||||
for _ in $(seq 1 240); do kill -0 "$SERVER_PID" 2>/dev/null || break; sleep 0.25; done
|
||||
kill -KILL "$SERVER_PID" 2>/dev/null || true
|
||||
fi
|
||||
SERVER_PID=""
|
||||
}
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
# One line of text is ~30 tokens at this tokeniser, so a context of N tokens is about N / 30 lines.
|
||||
# The records are distinct numbers, which keeps the prompt away from repetitive-text pathologies.
|
||||
gen_prompt() { local lines="$1" i first=$(( $1 + 1 )) last=$(( $1 + 10 ))
|
||||
for ((i = 1; i <= lines; i++)); do
|
||||
printf 'Record %d: the archivist checked the shelf, noted the catalogue number, and returned the volume to the east wing of the reading room. ' "$i"
|
||||
done
|
||||
printf 'Continue the register: write records %d through %d in the same form, one per line.' "$first" "$last"
|
||||
}
|
||||
|
||||
# The raw JSON-escaped completion text: equal escaped bytes mean equal text, and comparing the
|
||||
# escaped form is safer than any unescaper this script could carry.
|
||||
content_of() {
|
||||
awk '
|
||||
{ s = $0
|
||||
i = index(s, "\"message\":"); if (i == 0) exit 1
|
||||
s = substr(s, i)
|
||||
i = index(s, "\"content\":\""); if (i == 0) exit 1
|
||||
s = substr(s, i + 11)
|
||||
out = ""
|
||||
for (j = 1; j <= length(s); j++) {
|
||||
c = substr(s, j, 1)
|
||||
if (c == "\\") { out = out substr(s, j, 2); j++; continue }
|
||||
if (c == "\"") break
|
||||
out = out c
|
||||
}
|
||||
printf "%s", out
|
||||
}' "$1"
|
||||
}
|
||||
|
||||
# The engine's own report of one streamed group, from the prefill-complete / request-end line.
|
||||
# Prints: resolves lookups misses union maxmisses overflow
|
||||
stream_line() {
|
||||
grep -E "kv streaming: group '.*' (prefill complete|request end):" "$1" | tail -1 |
|
||||
sed -E "s/.*: ([0-9]+) resolves, ([0-9]+) lookups, ([0-9]+) misses.*largest launch union ([0-9]+) distinct blocks, largest launch misses ([0-9]+), overflow (LATCHED|no).*/\1 \2 \3 \4 \5 \6/" |
|
||||
{ read -r a b c d e f 2>/dev/null && echo "$a $b $c $d $e $f" || echo "- - - - - -"; }
|
||||
}
|
||||
|
||||
# One arm: a server, one request, a stop. $1 name, $2 prompt file, $3 max_model_len, $4 max_tokens,
|
||||
# the rest are the streaming flags. Writes $OUT/$1.{log,json,txt,counts,wall}.
|
||||
run_arm() { local arm="$1" prompt="$2" ctx="$3" maxtok="$4"; shift 4
|
||||
local log="$OUT/$arm.log" req="$OUT/$arm.req.json" resp="$OUT/$arm.json"
|
||||
echo "== $arm: max-model-len $ctx, max_tokens $maxtok, $* =="
|
||||
( exec "$BIN" --model "$MODEL" \
|
||||
--tp 2 --tp-wire exact \
|
||||
--max-num-seqs 1 --max-model-len "$ctx" --placement expert_tiered --host-pool-mib 23652 \
|
||||
--kv-cache-dtype fp8 --prefix-cache-mib 4096 --vision-tower-placement ram \
|
||||
--num-speculative-tokens 0 --deterministic \
|
||||
"$@" --host 127.0.0.1 --port "$PORT" --api-key test ) > "$log" 2>&1 &
|
||||
SERVER_PID=$!
|
||||
|
||||
local i code
|
||||
for i in $(seq 1 240); do # 20 min at 5 s; a cold load of this container is under a minute
|
||||
if ! kill -0 "$SERVER_PID" 2>/dev/null; then
|
||||
echo "FAIL $arm: the engine exited before serving; last errors:" >&2
|
||||
grep -E "^(E |radiance: fatal)" "$log" | tail -12 >&2 || tail -12 "$log" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
code=$(curl -s -m 3 -o /dev/null -w '%{http_code}' "http://127.0.0.1:$PORT/health" 2>/dev/null || true)
|
||||
[ "$code" = 200 ] && break
|
||||
sleep 5
|
||||
done
|
||||
if [ "${code:-}" != 200 ]; then
|
||||
echo "FAIL $arm: /health did not answer" >&2
|
||||
cleanup
|
||||
return 1
|
||||
fi
|
||||
|
||||
local prompt_text
|
||||
prompt_text=$(cat "$prompt")
|
||||
printf '{"model":"qwen4exp","temperature":0,"seed":%s,"max_tokens":%s,"chat_template_kwargs":{"enable_thinking":false},"messages":[{"role":"user","content":"%s"}]}' \
|
||||
"$SEED" "$maxtok" "$prompt_text" > "$req"
|
||||
# The wall time of the answer: time_starttransfer is the first token, i.e. the prefill's cost, on
|
||||
# an arm that succeeds; a failed arm reports the time to the refusal, which is the whole prefill.
|
||||
local t
|
||||
t=$(curl -s -m 3600 -o "$resp" -w '%{http_code} %{time_starttransfer} %{time_total}' \
|
||||
-H "Authorization: Bearer test" -H "Content-Type: application/json" \
|
||||
--data-binary "@$req" "http://127.0.0.1:$PORT/v1/chat/completions" 2>/dev/null || echo "000 0 0")
|
||||
code=${t%% *}
|
||||
echo "$t" > "$OUT/$arm.wall"
|
||||
local ptok
|
||||
ptok=$(grep -o '"prompt_tokens":[0-9]*' "$resp" | head -1 | cut -d: -f2 || true)
|
||||
# A failed overflow request has no usage block; the stream line still carries the measurement.
|
||||
[ -n "$ptok" ] && echo "$ptok" > "$OUT/$arm.ptok"
|
||||
content_of "$resp" > "$OUT/$arm.txt" 2>/dev/null || true
|
||||
stream_line "$log" > "$OUT/$arm.stream"
|
||||
echo " http=$code prompt_tokens=${ptok:-?} stream=[$(cat "$OUT/$arm.stream")]"
|
||||
cleanup
|
||||
return 0
|
||||
}
|
||||
|
||||
FAILED=0
|
||||
# The curve: contexts of roughly 64k and 128k tokens. The short points of the record (4k, 16k) are
|
||||
# gone rather than re-run: at the 32 768-token floor the ring covers a 4k or 16k context, the group
|
||||
# stays resident and no resolve is issued, so there is no union to report. Each prompt is a little
|
||||
# short of the bound so the chat template and the record numbers do not push it over
|
||||
# --max-model-len. The bound is twice the prompt, so the KV pool is large enough for the ring beside
|
||||
# the linear state.
|
||||
#
|
||||
# A ring too small for a launch is not served: the arm reports the union of the launch that overflowed
|
||||
# and fails, which is a lower bound, not the curve. So an arm is retried with a ring twice as deep
|
||||
# until no launch overflows -- the ring the arm finally ran with is the honest answer for that
|
||||
# context, and the union the launch's size. Sizes are tokens, one block is 4.
|
||||
declare -a NAMES=(ctx64k ctx128k)
|
||||
declare -a LINES=(2100 4200)
|
||||
declare -a CTX=(69632 139264)
|
||||
for k in 0 1; do
|
||||
gen_prompt "${LINES[$k]}" > "$OUT/${NAMES[$k]}.prompt.txt"
|
||||
# max_tokens 8: enough to run a few decode steps (decode is where the union is small) without
|
||||
# letting a measurement arm spend its time generating.
|
||||
ok=1
|
||||
for ring in 32768 65536 131072; do # the floor first, then the same search in floor-sized steps
|
||||
|
||||
run_arm "${NAMES[$k]}" "$OUT/${NAMES[$k]}.prompt.txt" "${CTX[$k]}" 8 \
|
||||
--kv-resident "$ring" || { ok=0; break; }
|
||||
echo "$ring" > "$OUT/${NAMES[$k]}.ring"
|
||||
if grep -q "kv streaming overflow:" "$OUT/${NAMES[$k]}.log"; then
|
||||
echo " overflowed a $ring-token ring; retrying deeper"
|
||||
continue
|
||||
fi
|
||||
break
|
||||
done
|
||||
[ "$ok" = 1 ] || FAILED=1
|
||||
done
|
||||
|
||||
# The staleness check: a ~34k-token prompt (above qsa_exact_to, so prefill is the sparse path the
|
||||
# resolve serves) streamed into the floor ring -- 32 768 tokens, 8 192 blocks -- then 512 decoded
|
||||
# tokens. The prompt's history is already past the ring when prefill ends and decode pushes it
|
||||
# further, so decode evicts and re-copies blocks every step: the exact case a stale copy would show
|
||||
# in, where the block a step writes is often the block the previous step made resident, and the
|
||||
# store now precedes the resolve. If a miss copied a block the store had not yet written, or an
|
||||
# eviction raced an attention still reading the slot, the text differs from the control.
|
||||
#
|
||||
# The ring is not shrunk to manufacture that pressure: the floor is 32 768 and a ring below it is a
|
||||
# shape the engine raises (and the operator never runs), so the *context* is what goes past the
|
||||
# ring. Here that is the prompt plus the 512 generated tokens; nothing about the arm is starved.
|
||||
#
|
||||
# A prompt BELOW qsa_exact_to cannot be used: that prefill is dense, and the dense attention reads a
|
||||
# block id as a pool slot with no resolve at all (docs/KV-STREAMING.md §3.5), so the sparse path the
|
||||
# resolve serves would not be the one this arm compares.
|
||||
gen_prompt 1150 > "$OUT/stale.prompt.txt"
|
||||
# --max-model-len above the prompt plus the generated tokens, and above the ring: at the prompt's own
|
||||
# length the ring would be the context, which streams nothing.
|
||||
run_arm stale-off "$OUT/stale.prompt.txt" 45056 512 || FAILED=1
|
||||
run_arm stale-on "$OUT/stale.prompt.txt" 45056 512 \
|
||||
--kv-resident "$STALE_RING" || FAILED=1
|
||||
if [ -s "$OUT/stale-off.txt" ] && [ -s "$OUT/stale-on.txt" ]; then
|
||||
# The comparison is only evidence of the copy path if the ring actually evicted: a miss count above
|
||||
# the peak union can only be a block copied more than once, i.e. evicted and needed again.
|
||||
read -r _ _ smiss _ sunion _ _ < "$OUT/stale-on.stream" || true
|
||||
if [ "${smiss:--}" != "-" ] && [ "${smiss:-0}" -le "${sunion:-0}" ]; then
|
||||
echo "FAIL: the stale arm made $smiss misses against a union of $sunion: nothing was evicted," >&2
|
||||
echo " so the run says nothing about a miss copying a block the store wrote" >&2
|
||||
FAILED=1
|
||||
fi
|
||||
if cmp -s "$OUT/stale-off.txt" "$OUT/stale-on.txt"; then
|
||||
echo "PASS: the floor-ring decode is byte-identical to streaming off ($(wc -c < "$OUT/stale-on.txt") bytes)"
|
||||
echo identical > "$OUT/stale.verdict"
|
||||
else
|
||||
echo "FAIL: the floor-ring decode differs from streaming off -- a stale or torn copy" >&2
|
||||
echo different > "$OUT/stale.verdict"
|
||||
FAILED=1
|
||||
fi
|
||||
else
|
||||
echo "FAIL: a stale arm produced no completion text" >&2
|
||||
echo missing > "$OUT/stale.verdict"
|
||||
FAILED=1
|
||||
fi
|
||||
|
||||
# A refusal naming the ring and the union is the honest outcome for an arm that overflowed, and it is
|
||||
# the measurement itself; print it once, verbatim, so the number is in the summary too.
|
||||
echo "== overflow refusals =="
|
||||
grep -h -E "^E kv streaming overflow:" "$OUT"/ctx*.log 2>/dev/null | sort -u || true
|
||||
|
||||
echo
|
||||
echo "== union by context (streamed group: kv_attn) =="
|
||||
printf '%-7s %8s %8s %8s %10s %10s %9s %8s %10s %10s\n' \
|
||||
arm prompt ring resolves lookups misses max_union max_miss overflow prefill_s
|
||||
for arm in "${NAMES[@]}"; do
|
||||
read -r res lk mi mu mm ov < "$OUT/$arm.stream" || true
|
||||
ptok=$(cat "$OUT/$arm.ptok" 2>/dev/null || echo "?")
|
||||
# The prefill's wall time: the first token on an arm that answered, the refusal on one that
|
||||
# overflowed (its prefill ran to completion before the engine failed it).
|
||||
pt=$(awk '{ print ($1 == 200 ? $2 : $3) }' "$OUT/$arm.wall" 2>/dev/null || echo "?")
|
||||
ring=$(cat "$OUT/$arm.ring" 2>/dev/null || echo "?")
|
||||
printf '%-7s %8s %8s %8s %10s %10s %9s %8s %10s %10s\n' \
|
||||
"$arm" "${ptok:--}" "$ring" "${res:--}" "${lk:--}" "${mi:--}" "${mu:--}" "${mm:--}" "${ov:--}" "${pt:--}"
|
||||
done
|
||||
|
||||
if [ "$FAILED" -ne 0 ]; then
|
||||
echo "FAIL: an arm did not serve, or the floor-ring text was not byte-identical" >&2
|
||||
exit 2
|
||||
fi
|
||||
@@ -906,6 +906,7 @@ utilisation fraction:
|
||||
| `--host-headroom-mib` | host RAM left free for the system at startup (default 4096) |
|
||||
| `--weights-disk-tier` | the file tier for weights, read from the container; needs `O_DIRECT` |
|
||||
| `--max-model-len`, `--max-num-seqs` | the KV cache's bound |
|
||||
| `--kv-resident` | tokens of the sparse attention group's KV kept on the card, the rest in pinned host memory; off by default, at or above the group's context nothing streams, a value below one decode step's selection is raised to it (16 416 tokens at 2 sequences with 3 speculative tokens, so a ring requested under that is not the ring measured), and ignored with a warning on an architecture that cannot stream (decided at startup). The recommended ring is 32 768; pressure is made by a longer context, not a smaller ring |
|
||||
|
||||
Nothing is inferred from the free VRAM at startup, which would size pools differently depending on
|
||||
what else is open. Each term is a fixed property, a computed quantity, or a measurement printed on
|
||||
|
||||
Reference in new issue
Block a user