Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e95d397288 | ||
|
|
7001841e45 | ||
|
|
82b5835c02 | ||
|
|
9f5feb24ee | ||
|
|
92b8aaff2b | ||
|
|
2d93182213 | ||
|
|
017cf52218 | ||
|
|
5acdab7eb7 | ||
|
|
ffdf1f2ced | ||
|
|
3e629e7a27 | ||
|
|
7be92ec8f4 | ||
|
|
cd48c61daf | ||
|
|
fd54038b8c | ||
|
|
43d97cb9e6 | ||
|
|
31a3ddd24f | ||
|
|
9fc7e5f1ff | ||
|
|
d72b00bfdb | ||
|
|
45963012ee | ||
|
|
82445ca71f | ||
|
|
1936bc881f | ||
|
|
7843a3d400 | ||
|
|
6e14caaedd | ||
|
|
d7aa401568 | ||
|
|
075dfefe54 | ||
|
|
0eeee5bb3a | ||
|
|
d0f639bd06 | ||
|
|
6b394ccca6 | ||
|
|
2149a1a757 | ||
|
|
72947681c3 | ||
|
|
b60e329d93 | ||
|
|
709d9beb1b | ||
|
|
41c0d25233 | ||
|
|
ee65352d7d | ||
|
|
a4845834ea | ||
|
|
469441d90f | ||
|
|
e466fa07e2 | ||
|
|
2f56e3c477 | ||
|
|
c36e6fa2b3 | ||
|
|
f1d4a54581 | ||
|
|
e6c8a3d7fa | ||
|
|
4252353bc2 | ||
|
|
fe899bf60c | ||
|
|
63d35ff791 | ||
|
|
bc2e6ba614 | ||
|
|
bfae23e368 | ||
|
|
bb4dddc424 | ||
|
|
20d6c2119f | ||
|
|
3e0c114cd7 | ||
|
|
ee2ba24083 | ||
|
|
140987fa7b | ||
|
|
146318894d | ||
|
|
8f795c1022 | ||
|
|
b8fab2c871 | ||
|
|
10f3d6875b | ||
|
|
7cf4c005e1 | ||
|
|
966bda899a | ||
|
|
6df26315b9 | ||
|
|
6c11671bdd |
No files matched your search
@@ -4,3 +4,4 @@ compile_commands.json
|
||||
*.so
|
||||
*.rad
|
||||
/sync-jarvis.sh
|
||||
__pycache__/
|
||||
+1
-1
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
|
||||
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
|
||||
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
|
||||
# a plugin contract and a server release do not move together.
|
||||
project(radiance VERSION 1.0.4 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.2.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
@@ -1,8 +1,16 @@
|
||||
radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels) and ggz14
|
||||
(the MXFP4 GEMM and the GDN kernels' overflow guards).
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
|
||||
(the MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards), slydlake
|
||||
(the MXFP4 decode and prefill GEMMs and the MXFP4 linear, stop strings after the reasoning block,
|
||||
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
|
||||
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
|
||||
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
|
||||
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, and
|
||||
the fused router launch), mechkbfan (the token embedding in the pinned host pool), Code000 (the
|
||||
n-gram gather on the card and the MTP head's history-pass skip) and baKon (three-rank tensor
|
||||
parallelism, serving any world size from the shipped container, and the request log).
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -17,6 +17,7 @@ If you wish to support the developement of the radiance engine you can do so [he
|
||||
|---|---|---|---|
|
||||
| Qwen3.8-Flash-Next: 4-bit experts, int8 trunk, MTP, vision | `qwen3.8-next-flash-fp8-iq4r-moe.rad` (114 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-next-flash-fp8-iq4r-moe) | `flashnext.yaml` |
|
||||
| Qwen3.8-27B FP8, DFlash2 drafter, vision | `qwen3.8-27b-fp8.rad` (29 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-fp8) | `qwen3.8-27b-fp8.yaml` |
|
||||
| Qwen3.8-27B MXFP4 (AMD Quark AWQ), DFlash2 drafter, vision | `qwen3.8-27b-mxfp4.rad` (19 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.8-27b-mxfp4) | `qwen3.8-27b-mxfp4.yaml` |
|
||||
| Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` |
|
||||
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
|
||||
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
|
||||
@@ -36,11 +37,13 @@ curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/
|
||||
|
||||
The host needs Docker and an `amdgpu` driver that supports ROCm 7.2; it does not need ROCm. The
|
||||
image is [`stilldeadcode/radiance`](https://hub.docker.com/r/stilldeadcode/radiance), with its
|
||||
kernels built for `gfx1201`. Pull it, then start a model from its compose file:
|
||||
kernels built for `gfx1201`. Pull it, clone this repository for its compose files, then start a
|
||||
model from one of them:
|
||||
|
||||
```sh
|
||||
docker pull stilldeadcode/radiance
|
||||
cp -r deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git
|
||||
cp -r radiance/deploy/compose ~/radiance-compose && cd ~/radiance-compose
|
||||
cp .env.example .env # set RADIANCE_MODELS, RADIANCE_STATE, RADIANCE_API_KEY, the GIDs
|
||||
docker compose -f minicpm5-2b.yaml up -d # or any file from the table
|
||||
docker compose -f minicpm5-2b.yaml logs -f
|
||||
@@ -51,15 +54,16 @@ Every model uses both cards and the same port, so run one at a time. Running wit
|
||||
the reason for each `docker run` option, is in [`docs/DOCKER.md`](docs/DOCKER.md).
|
||||
|
||||
To build the image yourself, for example for other cards, run `docker/build.sh -t 'gfx1200;gfx1201'`
|
||||
(it needs `docker buildx` and tests the build as it goes). Then set `RADIANCE_IMAGE=radiance:latest`
|
||||
in `.env`.
|
||||
in the clone (it needs `docker buildx` and tests the build as it goes). Then set
|
||||
`RADIANCE_IMAGE=radiance:latest` in `.env`.
|
||||
|
||||
## Build from source
|
||||
|
||||
You need Linux, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need ROCm
|
||||
7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`).
|
||||
You need Linux, git, a C++20 compiler, CMake 3.21+ and Ninja. For the device kernels you also need
|
||||
ROCm 7.2 (`hipcc`; set `ROCM_PATH` if it is not `/opt/rocm`). Clone the repository and build in it:
|
||||
|
||||
```sh
|
||||
git clone https://codeberg.org/StillDeadcode/radiance.git && cd radiance
|
||||
./build.sh # configure, build for the cards present, run the tests
|
||||
./build.sh --no-hip # host backend only
|
||||
cmake -S . -B build -G Ninja -DRAD_GPU_TARGETS='gfx1201' # build for cards this machine lacks
|
||||
@@ -78,18 +82,37 @@ prefix-cache tiers:
|
||||
|
||||
| model | flags |
|
||||
|---|---|
|
||||
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next | `--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, four ranks | `--tp 4 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-Flash-Next, three ranks (the shipped container as it is, [`docs/TP3.md`](docs/TP3.md)) | `--tp 3 --max-num-seqs 8 --max-model-len 200000 --placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 --kv-cache-dtype fp8 --num-speculative-tokens 3 --max-num-batched-tokens 2048` |
|
||||
| Qwen3.8-27B FP8, Qwen3.6-35B-A3B | `--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| Qwen3.8-27B bf16 | `--tp 2 --max-num-seqs 8 --max-model-len 200000 --kv-cache-dtype fp8` |
|
||||
| MiniCPM5-2B FP8 and bf16 | `--tp 2 --max-num-seqs 32 --max-model-len 131072 --kv-cache-dtype fp8 --gpu-headroom-mib 160 --max-num-batched-tokens 512` |
|
||||
| Qwen3.8-Flash-Next bf16 | `--tp 2 --max-model-len 32768 --placement expert_tiered --weights-disk-tier --host-pool-mib 12288 --gpu-headroom-mib 768 --deterministic --max-num-seqs 32 --max-num-batched-tokens 32768 --num-speculative-tokens 0` |
|
||||
|
||||
Every model serves up to 32 sequences a step. Two rows keep 8, because on a hybrid model each
|
||||
sequence holds its own recurrent state and 32 of them leave the attention cache short of one
|
||||
200K-token request: Flash-Next at ratio 0.82 (`--max-num-seqs 32 --expert-vs-cache-ratio 0.78`
|
||||
keeps the 200K request and costs single-stream decode about 15%) and the 27B in bf16. See
|
||||
sequence holds its own recurrent state, and 32 of them take that memory from the attention cache
|
||||
and, on Flash-Next, from the expert slab: Flash-Next and the 27B in bf16. See
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §4.4.
|
||||
|
||||
At `--tp 4` the gated residual's write carries the exact all-reduce, with the MoE gather in front
|
||||
of it, on decode and verify steps; a prefill chunk runs the unfused chain. That chain's exact
|
||||
all-reduce is one-shot up to 1 MiB a message and two-shot above that, which sends half the bytes
|
||||
on a prefill chunk; both produce the same bits. The row above runs exact.
|
||||
`--tp-wire wht6` at four ranks selects a different lossy wire, tiered int8 over the two-shot,
|
||||
above `--tp-wire-min-kb`. Eight ranks have no lossy wire, so `--tp 8 --tp-wire wht6` stops at
|
||||
startup naming the all-reduce. Four ranks is a capacity configuration; its per-step rate against
|
||||
`--tp 2` on the same cards has not been measured. The
|
||||
tiering flags are the tp2 recipe carried over. Above two ranks each rank still owns a **slice of
|
||||
every expert's width** — each parity's 128-column blocks are cut contiguously over the ranks and the
|
||||
odd block alternates with the parity, so every rank's share is whole blocks and every block has
|
||||
exactly one owner — and the resident expert bytes per rank are smaller, so the elastic window is a
|
||||
different shape: read the boot log's `elastic` line and re-derive `--host-pool-mib` before
|
||||
trusting it. **`--host-pool-mib` is pinned on every card**, so the row
|
||||
above pins 4 × 12 GiB = 48 GiB, and the amdgpu driver caps pinned memory at `ttm.pages_limit`, half
|
||||
of RAM by default: that row needs 96 GiB of RAM or a raised limit
|
||||
([`docs/GUIDE.md`](docs/GUIDE.md) §7).
|
||||
|
||||
Add `--api-key KEY` to require `Authorization: Bearer KEY`. Add `--debug-graph` to print every op
|
||||
and the kernel it resolved to, then exit without serving. Then:
|
||||
|
||||
@@ -133,6 +156,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out of tr
|
||||
| [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files |
|
||||
| [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card |
|
||||
| [`docs/ARCHITECTURES.md`](docs/ARCHITECTURES.md) | the supported model families and their geometry |
|
||||
| [`docs/TP3.md`](docs/TP3.md) | any world size: the attention world and uneven delta-net heads; three ranks |
|
||||
| [`docs/OPS.md`](docs/OPS.md), [`docs/KERNELS.md`](docs/KERNELS.md) | the op vocabulary, and what `rad-kbench` last measured |
|
||||
| [`spec.md`](spec.md) | the design |
|
||||
|
||||
|
||||
+20
-1
@@ -364,6 +364,24 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
* groups the span would cut. */
|
||||
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi);
|
||||
|
||||
/* A STACKED weight's span, ONE [lo, hi) PER ROW PART, with each part's whole extent in the
|
||||
* container: the delta net's [q|k|v|z] is 2048, 2048, 6144, 6144 rows on Flash-Next, and parts
|
||||
* that are not the same width cannot take rad_weight_shard_span's one span. `n` is the declared
|
||||
* part count; part g of the container is `total[g]` rows, of which this rank takes [lo[g], hi[g])
|
||||
* and declared `hi[g] - lo[g]`; the totals must sum to the entry's rows. A rank's UNEVEN share of
|
||||
* the heads -- 6 of 16 K heads where three ranks take 6, 5 and 5 -- is declared this way, and
|
||||
* nothing is padded. Additive export: a plugin that does not call it declares as before. */
|
||||
int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
|
||||
/* THIS RANK KEEPS NO CACHE FOR THE GROUP. The group is declared as on every other rank -- the
|
||||
* scheduler indexes groups by position and one block table serves every rank, so it must exist
|
||||
* here with the same block size and layers -- and nothing is carved for it: it costs this rank no
|
||||
* pool. It is for a rank the geometry gives no attention heads (rad_arch.h Geom::attn_zero),
|
||||
* whose attention is a `fill` of zeros and never reads a key. No op on this rank may name the
|
||||
* group as a RAD_KV operand after this; the engine refuses one at issue. Additive export. */
|
||||
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g);
|
||||
|
||||
#define RAD_BUFS(...) ((const rad_buf[]){ __VA_ARGS__ }), \
|
||||
(int)(sizeof((const rad_buf[]){ __VA_ARGS__ }) / sizeof(rad_buf))
|
||||
|
||||
@@ -666,7 +684,8 @@ typedef struct RadChatFormat {
|
||||
|
||||
uint32_t string_value; /* RAD_CHAT_VALUE_RAW or _CDATA: a string-typed argument */
|
||||
uint32_t other_value; /* RAD_CHAT_VALUE_JSON: any other type (or _RAW, as text) */
|
||||
/* Non-zero: one newline at each end of a value is punctuation, not part of the value. */
|
||||
/* Non-zero: one newline at each end of a value is punctuation, not part of the value -- at
|
||||
* its start only where the tag before it does not end with that newline itself. */
|
||||
uint32_t value_newlines;
|
||||
|
||||
/* The literal words that start constrained decoding of a call. None: no grammar, and the
|
||||
|
||||
@@ -303,6 +303,19 @@ typedef struct RadConstraint {
|
||||
const char* sval; /* IN: space-separated set of admissible strings */
|
||||
} RadConstraint;
|
||||
|
||||
/* A CONSTRAINT ON THE MACHINE rather than on the geometry. A key that starts "device." is matched
|
||||
* against what the engine measured about the ranks' devices at launch, not against the op's
|
||||
* parameters: a capability such as reaching another card's memory belongs to the machine, and
|
||||
* carrying it as a parameter would have every architecture plugin declare it on every op and
|
||||
* every schema grow a field for it. Such a key is in no geometry, so it changes no tuning key
|
||||
* and no selection fold. Where nothing measured it -- a tool selecting without an engine -- it is
|
||||
* absent, and a constraint on an absent key does not hold.
|
||||
*
|
||||
* device.p2p 1 when every rank's device can read and write every other rank's memory
|
||||
* directly; 0 when some pair cannot. One rank has no peer to reach, and is 1. */
|
||||
#define RAD_DEVICE_FACT_PREFIX "device."
|
||||
#define RAD_FACT_P2P "device.p2p"
|
||||
|
||||
#define RAD_C(k, o, v) { (k), (o), (long long)(v), 0 }
|
||||
#define RAD_CEQ(k, v) { (k), RAD_C_EQ, (long long)(v), 0 }
|
||||
#define RAD_CLE(k, v) { (k), RAD_C_LE, (long long)(v), 0 }
|
||||
|
||||
+123
-9
@@ -570,6 +570,24 @@ struct Geom {
|
||||
int64_t n_head_kv = 0; /* per rank */
|
||||
int64_t n_head_all = 0;
|
||||
int64_t n_head_kv_all = 0;
|
||||
/* THIS RANK'S FIRST KV ROW inside the checkpoint's UNSHARDED k/v projection rows, used only
|
||||
* when the KV heads are replicated over ranks instead of split (world > n_head_kv_all, see
|
||||
* geom_from). It is in container rows, the same unit a LinearFP8 span takes, so a block that
|
||||
* declares a row-sharded k/v passes it straight through as `span_lo`. Zero on every split
|
||||
* deployment, which is what keeps TP2 reading the projection exactly as it always did. */
|
||||
int64_t kv_off = 0;
|
||||
/* THE ATTENTION WORLD. A world size the KV head count neither divides nor is a multiple of
|
||||
* -- three ranks over Flash-Next's two KV heads -- serves attention on the largest multiple
|
||||
* of the head count below it (`attn_world`, here 2: split, or replicated when that is still
|
||||
* above the count) and the remaining ranks are ATTENTION-ZERO: they declare the same heads and
|
||||
* the same program as their peers, compute no attention (a `fill` of the block's output and
|
||||
* a zero KV group, rad_kv_group_zero) and add exactly zero to the reduce. `attn_rank` is this
|
||||
* rank's index inside the attention world (an attention-zero rank clamps to the last). When
|
||||
* attn_world == world nothing here is used and every block declares as it always did. Set
|
||||
* only for a plugin that asks for it (geom_from's `attn_world_ok`). */
|
||||
int attn_world = 1;
|
||||
int attn_rank = 0;
|
||||
bool attn_zero = false;
|
||||
int64_t n_ff = 0; /* per rank */
|
||||
int64_t n_ff_all = 0;
|
||||
int64_t max_tok = 0;
|
||||
@@ -669,14 +687,30 @@ inline int divide_or_fail(int64_t v, int world, const char* what, int64_t* out)
|
||||
* absurd. So the last rank holds fewer rows. The sampler merges candidate sets rather than
|
||||
* gathering full logits (spec §9, §13), so a ragged shard costs it nothing; a padded one would
|
||||
* cost a fake token id that has to be masked everywhere forever. */
|
||||
inline int64_t shard_extent(int64_t total, int world, int rank) {
|
||||
/* THE VOCABULARY SPLIT: ceil(total / world) rows a rank, ROUNDED UP TO A WHOLE 128-ROW BLOCK, the
|
||||
* last rank short. The block is RAD_FP8_BLOCK: a block-scaled fp8 lm_head is stored in 128x128
|
||||
* tiles and a row span that cuts a tile is refused (rad_weight_shard_span), so the cut has to land
|
||||
* on one. At two ranks on 248320 or 151936 the rounding changes nothing -- both halves are block
|
||||
* multiples -- and a vocabulary the world divides is never rounded; at three it is what makes the
|
||||
* head shardable at all (248320 / 3 = 82773.3; the ranks take 82816, 82816, 82688). core/engine.cpp
|
||||
* RESTATES this rule and checks it against the width the plugin declared; the two must move together. */
|
||||
inline int64_t vocab_per_rank(int64_t total, int world) {
|
||||
/* A vocabulary the world divides keeps the even share, whatever the world: every container
|
||||
* served today splits that way (248320 at 2 and 4, 151936 at 2 -- the last halves mid-block and
|
||||
* is served with an untiled head). Only a vocabulary the world does NOT divide takes the
|
||||
* block-aligned ceil, which is what makes a tiled head shardable at all. */
|
||||
if (total % world == 0) return total / world;
|
||||
const int64_t per = (total + world - 1) / world;
|
||||
return (per + 127) / 128 * 128;
|
||||
}
|
||||
inline int64_t shard_extent(int64_t total, int world, int rank) {
|
||||
const int64_t per = vocab_per_rank(total, world);
|
||||
const int64_t beg = per * rank;
|
||||
const int64_t end = beg + per < total ? beg + per : total;
|
||||
return end > beg ? end - beg : 0;
|
||||
}
|
||||
inline int64_t shard_begin(int64_t total, int world, int rank) {
|
||||
const int64_t per = (total + world - 1) / world;
|
||||
const int64_t per = vocab_per_rank(total, world);
|
||||
const int64_t beg = per * rank;
|
||||
return beg < total ? beg : total;
|
||||
}
|
||||
@@ -695,8 +729,35 @@ inline long long meta_int2(const RadModelMeta* m, const char* gguf_key, const ch
|
||||
return v == sentinel ? dflt : v;
|
||||
}
|
||||
|
||||
/* THE REMAINDER-FIRST ORDER OF THE RANKS. What does not divide evenly over the world and is a
|
||||
* HEAD'S worth of work -- the extra delta-net head -- goes to the ranks with NO attention first:
|
||||
* they pay nothing for attention (rad_block_attn_gated_fp8.h: one fill) and keep no attention
|
||||
* cache (rad_kv_group_zero), so they have the time for it, and the rank that held the extra head
|
||||
* AND attention -- the step's slowest -- is lighter for it. An expert's extra block is not a
|
||||
* head's worth (qwen4exp_fp8.cpp says why it stays on the rotation). This is a rank's PLACE in
|
||||
* that order: the attention-zero ranks take places 0..n-1 whatever `parity` is, and the attention
|
||||
* ranks follow in the rotation by `parity` -- so where no rank is attention-zero (every world the
|
||||
* heads divide) the place is exactly (rank - parity) mod world and every cut is the even one. */
|
||||
inline int64_t remainder_place(const Geom& g, int rank, int parity) {
|
||||
const int nz = g.world - g.attn_world;
|
||||
if (rank >= g.attn_world) return rank - g.attn_world;
|
||||
const int aw = g.attn_world;
|
||||
return nz + ((rank - parity) % aw + aw) % aw;
|
||||
}
|
||||
|
||||
/* `arch_splits_ff`: the plugin divides the feed-forward width across the ranks ITSELF (qwen4exp:
|
||||
* the routed experts' width is cut by whole fp8 blocks, by parity, at any world up to the block
|
||||
* count). With it set, a width the world does not divide is left whole in g.n_ff and the plugin
|
||||
* takes its slice from there; without it the refusal stands, because for every other plugin g.n_ff
|
||||
* IS the per-rank width. A width that does divide is unaffected either way. */
|
||||
/* `attn_world`: the plugin's attention block serves a SMALLER ATTENTION WORLD (Geom::attn_world)
|
||||
* -- it declares the attention-zero rank's fill and zero KV group and spans the attention
|
||||
* projections by `attn_rank`. Only rad_block_attn_gated_fp8.h does. Without it a world the KV head
|
||||
* count neither divides nor is a multiple of is refused here, by name, rather than declared with
|
||||
* an even shard the block would then cut wrongly. */
|
||||
inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
const char* dtype, uint32_t act_dtype) {
|
||||
const char* dtype, uint32_t act_dtype, bool arch_splits_ff = false,
|
||||
bool attn_world_ok = false) {
|
||||
if (!m || !c) return RAD_E_INVAL;
|
||||
if (c->is_draft) {
|
||||
/* A drafter declared into this plugin would need a second set of per-rank handles and a
|
||||
@@ -759,12 +820,65 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
}
|
||||
|
||||
int s;
|
||||
if ((s = divide_or_fail(g.n_head_all, g.world, "n_head", &g.n_head)) < 0) return s;
|
||||
/* A world size larger than n_head_kv would need the KV heads replicated across ranks rather
|
||||
* than split, which is a different attention declaration and not a rounding decision. Refuse
|
||||
* it here rather than have the block quietly produce a zero-width KV projection. */
|
||||
if ((s = divide_or_fail(g.n_head_kv_all, g.world, "n_head_kv", &g.n_head_kv)) < 0) return s;
|
||||
if ((s = divide_or_fail(g.n_ff_all, g.world, "n_ff", &g.n_ff)) < 0) return s;
|
||||
/* THE ATTENTION WORLD (see the field). Below the KV head count, or a multiple of it, it is the
|
||||
* world and the two rules that follow run on the world as before. Otherwise it is the largest
|
||||
* multiple of the head count under the world, and the ranks past it carry zero attention. */
|
||||
g.attn_world = g.world;
|
||||
g.attn_rank = g.rank;
|
||||
g.attn_zero = false;
|
||||
if (attn_world_ok && g.world > g.n_head_kv_all && g.world % g.n_head_kv_all != 0) {
|
||||
g.attn_world = (int)(g.n_head_kv_all * (g.world / g.n_head_kv_all));
|
||||
g.attn_zero = g.rank >= g.attn_world;
|
||||
g.attn_rank = g.attn_zero ? g.attn_world - 1 : g.rank;
|
||||
fprintf(stderr, "radiance: world_size = %d over n_head_kv = %lld: attention on %d rank(s), "
|
||||
"rank(s) %d..%d carry no attention and take the delta net's remainder "
|
||||
"first\n", g.world, (long long)g.n_head_kv_all,
|
||||
g.attn_world, g.attn_world, g.world - 1);
|
||||
}
|
||||
const int aw = g.attn_world, ar = g.attn_rank;
|
||||
if ((s = divide_or_fail(g.n_head_all, aw, "n_head", &g.n_head)) < 0) return s;
|
||||
/* THE KV HEADS ARE REPLICATED WHEN THERE ARE NOT ENOUGH TO SPLIT. There is one row-span per KV
|
||||
* head and no way to hand four ranks half a head, so `divide_or_fail` on n_head_kv is the
|
||||
* wrong verb once world exceeds the head count -- the question is not rounding, it is whether
|
||||
* the declaration is allowed to say one KV head per rank. It is, when world is a multiple of
|
||||
* the KV head count: query heads 0-11 belong to KV head 0 and 12-23 to KV head 1, so ranks
|
||||
* {0,1} need only KV head 0 and ranks {2,3} only KV head 1. Each rank then declares
|
||||
* n_head_kv 1 and reads its own head's row-span of k/v, which `kv_off` locates; the attention
|
||||
* declaration comes out at gqa 6 over a page of 4 instead of gqa 12 over a page of 2, and
|
||||
* kv_dim(), gqa() and every block that reads them need no new branch because from here down a
|
||||
* replicated rank and a split rank look the same.
|
||||
*
|
||||
* THE COST IS HONEST AND IT IS MEMORY, NOT MATH: the replicating ranks hold BYTE-IDENTICAL KV
|
||||
* weights, a replicated read that costs no extra VRAM per rank versus the TP2 split it
|
||||
* replaces (Flash-Next: 2 KV heads x 5120 x 256 rows read twice instead of once). What it buys
|
||||
* is that world 4 is declarable at all.
|
||||
*
|
||||
* When world <= n_head_kv_all the split below is untouched, so a world that divides the KV
|
||||
* heads -- TP2 on this family -- declares exactly as it did before replication existed. */
|
||||
if (aw > g.n_head_kv_all) {
|
||||
/* aw is a multiple of the head count by construction (the world itself, checked here, or
|
||||
* the attention world, which is one). */
|
||||
if (aw % g.n_head_kv_all != 0) {
|
||||
fprintf(stderr, "radiance: world_size = %d cannot replicate n_head_kv = %lld; "
|
||||
"replication needs world to be a multiple of the KV head count\n",
|
||||
aw, (long long)g.n_head_kv_all);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.n_head_kv = 1; /* aw / n_head_kv_all ranks share each KV head */
|
||||
g.kv_off = (ar / (aw / g.n_head_kv_all)) * g.head_dim;
|
||||
} else if ((s = divide_or_fail(g.n_head_kv_all, aw, "n_head_kv", &g.n_head_kv)) < 0) {
|
||||
return s;
|
||||
} else {
|
||||
/* A split rank reads the rows the plain row-shard gives it -- when the attention world
|
||||
* is the world. Under a smaller attention world the even shard over `world` is the wrong
|
||||
* cut, and the block spans [kv_off, kv_off + kv_dim) instead. */
|
||||
g.kv_off = aw == g.world ? 0 : ar * g.n_head_kv * g.head_dim;
|
||||
}
|
||||
if (arch_splits_ff && g.world > 1 && g.n_ff_all % g.world != 0) {
|
||||
g.n_ff = g.n_ff_all; /* the plugin slices it (see the parameter's comment) */
|
||||
} else if ((s = divide_or_fail(g.n_ff_all, g.world, "n_ff", &g.n_ff)) < 0) {
|
||||
return s;
|
||||
}
|
||||
/* THE VOCABULARY IS SPLIT. r4d_sample_topk_f32 takes a vocabulary offset and packs its
|
||||
* candidates as (u32 GLOBAL id, f32 logit) pairs, and the all-gather places every rank's
|
||||
* pairs for one sampled position side by side, which is the layout sample_merge_topk reads.
|
||||
|
||||
@@ -99,6 +99,17 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* NO KV-HEAD REPLICATION HERE. The fused [q|k|v] row-shards by head with the plain even shard,
|
||||
* so above the KV head count a rank would get a slice of one KV head and declare fine while
|
||||
* reading the wrong rows. rad_block_attn_gated.h refuses for the same reason; the block that
|
||||
* plumbs geom_from's `kv_off` is rad_block_attn_gated_fp8.h. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
@@ -103,6 +103,21 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* KV-HEAD REPLICATION IS NOT PLUMBED HERE. `geom_from` answers a world size above the KV head
|
||||
* count by giving every rank ONE kv head and a `kv_off` row span into a projection that stays
|
||||
* `n_head_kv_all * head_dim` rows in the container -- and this block declares its k and v with
|
||||
* the plain even row-shard, which at four ranks would hand a rank half of one KV head. The
|
||||
* shapes would declare, the numbers would be wrong, and the text would be fluent. Refuse by
|
||||
* name instead: rad_block_attn_gated_fp8.h is the block that passes the span, and a bf16 model
|
||||
* that needs TP4 plumbs it the same way. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld; the KV-head replication in geom_from needs the "
|
||||
"span passed to its k/v weights.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* ---- weights. Shapes are [out, in]: gemm_nt is A[M,K] times B transposed [N,K], the layout
|
||||
* every transformer weight already has, so nothing is transposed at load.
|
||||
*
|
||||
@@ -283,7 +298,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
* here because the plugin put it here, and --debug-graph shows it exactly here (spec §9).
|
||||
* `exact` is stated rather than defaulted -- a caller that does not say it will accept a
|
||||
* quantised wire gets the exact kernel or no kernel. `hops` is not stated: one-shot against
|
||||
* two-shot is the kernel's business. */
|
||||
* two-shot is the kernel library's choice, by message size. */
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
|
||||
@@ -147,6 +147,7 @@ struct AttnGatedFP8 {
|
||||
rad_op op_attn_gq = 0; /* attn_paged + gate_quant_fp8 */
|
||||
rad_op op_sig = 0, op_mul = 0; /* the bf16 gate, Geom::w_bf16 */
|
||||
rad_op op_ar = 0, op_add = 0;
|
||||
rad_op op_fill = 0; /* the attention-zero rank: see declare */
|
||||
/* ...AND WHETHER THE COLLECTIVE AT THE END OF THIS BLOCK IS THE NEXT BLOCK'S FIRST PASS.
|
||||
* `ar_in` says this block's own norm absorbs its PREDECESSOR's all-reduce; `ar_out` says the
|
||||
* block after it absorbs THIS one's, so this one must not issue it. They are the residual
|
||||
@@ -180,6 +181,32 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
const int64_t qg_dim = 2 * q_dim;
|
||||
|
||||
/* THE KV ROW SPAN, AND IT ONLY EXISTS ABOVE THE KV HEAD COUNT.
|
||||
* A world size larger than `n_head_kv_all` cannot divide the KV heads, so rad_arch.h's
|
||||
* `geom_from` replicates them in PAIRS: two ranks serve the same head, `g.n_head_kv` is 1 on
|
||||
* each, and the checkpoint entry they both read is still `n_head_kv_all * head_dim` rows -- 512
|
||||
* for 2 KV heads at head_dim 256. This rank wants ONE head's row-span of that entry, which the
|
||||
* even shard would cut up instead (at 4 ranks it would hand rank 2 rows [256, 384), half of one
|
||||
* head), so the span `[g.kv_off, g.kv_off + kv_dim)` is declared in the CONTAINER's unsharded
|
||||
* units -- [0, 256) on ranks 0 and 1, [256, 512) on ranks 2 and 3 -- and the scale plane takes
|
||||
* the same span in 128-blocks. `kv_off` is a multiple of head_dim, so it is whole blocks and
|
||||
* never cuts one, and share.cpp's `shard_hi <= cpart` holds with cpart = 512 / 1 part.
|
||||
* AT WORLD <= n_head_kv_all the ordinary even shard already selects exactly these rows, so the
|
||||
* span stays 0/0 and the default path runs as before -- TP2 declares identically. */
|
||||
/* AND UNDER A SMALLER ATTENTION WORLD (rad_arch.h Geom::attn_world: three ranks over two KV
|
||||
* heads) the even shard over `world` is the wrong cut for every projection: q|gate and the
|
||||
* output take this rank's heads [attn_rank * n_head, +n_head) as a span too, and k/v the
|
||||
* kv_off span. An attention-zero rank declares none of them: its block is one `fill` of the
|
||||
* output wire (the branch below), so the spans here are only ever cut for a rank with heads. */
|
||||
const bool a_spanned = g.attn_world != g.world;
|
||||
const bool kv_spanned = g.world > g.n_head_kv_all || a_spanned;
|
||||
const int64_t kv_span_lo = kv_spanned ? g.kv_off : 0;
|
||||
const int64_t kv_span_hi = kv_spanned ? g.kv_off + kv_dim : 0;
|
||||
const int64_t qg_span_lo = a_spanned ? g.attn_rank * qg_dim : 0;
|
||||
const int64_t qg_span_hi = a_spanned ? (g.attn_rank + 1) * qg_dim : 0;
|
||||
const int64_t o_span_lo = a_spanned ? g.attn_rank * q_dim : 0;
|
||||
const int64_t o_span_hi = a_spanned ? (g.attn_rank + 1) * q_dim : 0;
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
@@ -218,12 +245,32 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
if (!ext_in)
|
||||
RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd,
|
||||
fold ? w.x : 0, 0, ar_in));
|
||||
|
||||
/* AN ATTENTION-ZERO RANK COMPUTES NO ATTENTION AT ALL. Its share of every projection is zero,
|
||||
* so its q, k and v are zero, its attention is zero and its output projection adds exactly
|
||||
* nothing to the reduce -- which is what the ranks that DO hold heads need from it and all
|
||||
* they need. Declaring the projections and running them on zero weights spent the same
|
||||
* dispatches and bytes as a real rank and a slot for every zero (and a KV pool nothing read,
|
||||
* see rad_kv_group_zero). Here the block's output wire is written to zero by one `fill`, and
|
||||
* the all-reduce and the residual below see what they always saw. The norm above stays: a
|
||||
* pre-norm block's `fold` and `ar_in` live in it. Nothing in this branch runs for a rank with
|
||||
* heads, so a world the heads divide (every TP2 and TP4 deployment) declares as it always did. */
|
||||
if (g.attn_zero) {
|
||||
op_fill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {w.h.x});
|
||||
} else {
|
||||
RAD_ARCH_TRY(qg.declare(b, nm, g, nm.f("blk.%d.attn_qg", l), qg_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg));
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.qg }, w.h, w.qg,
|
||||
0, {}, qg_span_lo, qg_span_hi));
|
||||
RAD_ARCH_TRY(kp.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k));
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.k }, w.h, w.k,
|
||||
0, {}, kv_span_lo, kv_span_hi));
|
||||
RAD_ARCH_TRY(vp.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v));
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.v }, w.h, w.v,
|
||||
0, {}, kv_span_lo, kv_span_hi));
|
||||
|
||||
/* THE FUSED PROLOGUE, AND IT IS A PROBE: the four ops below are declared either way and are
|
||||
* what runs when nothing serves this one. rad_block_attn_gated.h does not make the probe,
|
||||
@@ -399,7 +446,9 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x));
|
||||
RAD_SHARD_COL, grp_layer(l), { src.o }, w.attn, w.h.x,
|
||||
0, {}, o_span_lo, o_span_hi));
|
||||
} /* !g.attn_zero */
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
@@ -430,6 +479,14 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* The attention-zero rank: the output wire is zero, then the reduce and the residual. */
|
||||
RAD_ISSUE_N(c, op_fill, T, brows(w.h.x, T));
|
||||
if (op_ar && !ar_taken(g, T, ar_out, ar_out_take))
|
||||
RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE);
|
||||
if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T));
|
||||
return;
|
||||
}
|
||||
qg.step(c, w.h, w.qg, T);
|
||||
kp.step(c, w.h, w.k, T);
|
||||
vp.step(c, w.h, w.v, T);
|
||||
|
||||
@@ -72,6 +72,14 @@ struct GdnFP8 {
|
||||
* `gdn_recurrent_update` composes the same parameter, so this is a string to pass and
|
||||
* not a kernel to write. "silu" or "sigmoid"; anything else is refused below. */
|
||||
const char* act = "silu";
|
||||
/* AN UNEVEN SPLIT OF THE HEADS (rad_weight_shard_span_parts). n_head_k / n_head_v are
|
||||
* this rank's; k_first / v_first its first head of the container's n_head_k_all /
|
||||
* n_head_v_all. k_first < 0 is the even split the plain row shard gives, as before.
|
||||
* Three ranks over 16 K heads take 6, 5 and 5 (and 18, 15, 15 of the 48 V heads) --
|
||||
* every rank real heads, nothing padded, every kernel at its own head count. */
|
||||
int64_t k_first = -1, v_first = -1;
|
||||
int64_t n_head_k_all = 0, n_head_v_all = 0;
|
||||
bool uneven() const { return k_first >= 0; }
|
||||
|
||||
int64_t k_dim() const { return n_head_k * head_k; }
|
||||
int64_t v_dim() const { return n_head_v * head_v; }
|
||||
@@ -268,6 +276,25 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
RAD_ARCH_TRY(in.declare(b, nm, g, nm.f("blk.%d.ssm_inz", l), conv_dim + v_dim, g.n_embd,
|
||||
RAD_SHARD_ROW, grp_layer(l), { s.in_qkv, s.in_z }, w.h, w.in.x, 0,
|
||||
{ cfg.k_dim(), cfg.k_dim(), cfg.v_dim(), cfg.v_dim() }));
|
||||
if (cfg.uneven()) {
|
||||
/* THIS RANK'S HEADS OF EACH PART, in the container's rows: q and k by K head, v and z by
|
||||
* V head. The scale plane of a row shard has the same rows (its blocks run along K). */
|
||||
const int64_t kl = cfg.k_first * cfg.head_k, vl = cfg.v_first * cfg.head_v;
|
||||
const int64_t ka = cfg.n_head_k_all * cfg.head_k, va = cfg.n_head_v_all * cfg.head_v;
|
||||
const int64_t lo[4] = { kl, kl, vl, vl };
|
||||
const int64_t hi[4] = { kl + cfg.k_dim(), kl + cfg.k_dim(), vl + cfg.v_dim(), vl + cfg.v_dim() };
|
||||
const int64_t tot[4] = { ka, ka, va, va };
|
||||
RAD_ARCH_TRY(in.span_parts(b, lo, hi, tot, 4));
|
||||
const int64_t clo[3] = { kl, kl, vl }, chi[3] = { kl + cfg.k_dim(), kl + cfg.k_dim(), vl + cfg.v_dim() };
|
||||
const int64_t ctot[3] = { ka, ka, va };
|
||||
RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w_conv, clo, chi, ctot, 3));
|
||||
const int64_t alo[2] = { cfg.v_first, cfg.v_first };
|
||||
const int64_t ahi[2] = { cfg.v_first + cfg.n_head_v, cfg.v_first + cfg.n_head_v };
|
||||
const int64_t atot[2] = { cfg.n_head_v_all, cfg.n_head_v_all };
|
||||
RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w_ab, alo, ahi, atot, 2));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w_a_log, cfg.v_first, cfg.v_first + cfg.n_head_v));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w_dt_bias, cfg.v_first, cfg.v_first + cfg.n_head_v));
|
||||
}
|
||||
/* NOT SLICED, and why it could need to be is worth keeping. This is a 96-column bf16 GEMM --
|
||||
* half a percent of the layer's projection bytes -- and a bf16 kernel for this shape that
|
||||
* stopped at M = 64 would leave a hole in its bucket table above 64. Since every op in a step
|
||||
@@ -374,7 +401,9 @@ inline int GdnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
|
||||
RAD_ARCH_TRY(q_o.declare(b, g, w.o, v_dim));
|
||||
RAD_ARCH_TRY(out.declare(b, nm, g, nm.f("blk.%d.ssm_out", l), g.n_embd, v_dim,
|
||||
RAD_SHARD_COL, grp_layer(l), { s.out }, w.o, w.h.x));
|
||||
RAD_SHARD_COL, grp_layer(l), { s.out }, w.o, w.h.x, 0, {},
|
||||
cfg.uneven() ? cfg.v_first * cfg.head_v : 0,
|
||||
cfg.uneven() ? cfg.v_first * cfg.head_v + v_dim : 0));
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
|
||||
+31
-13
@@ -156,9 +156,10 @@ struct HyperConn {
|
||||
|
||||
int64_t hn() const { return c.hc * g.n_embd; }
|
||||
/* THE REDUCING WRITE THIS STEP ISSUES, on the wire its message goes out on; 0 where that wire
|
||||
* has no fused form, and the block's own collective then runs in front of the plain write. */
|
||||
* has no fused form, and the block's own collective then runs in front of the plain write. At
|
||||
* four ranks there is no rotated form, so a step ar_exact_write_takes declines gets 0. */
|
||||
rad_op ar_write(int64_t T) const {
|
||||
return ar_wire_is_exact(g, T) ? op_ar_write : op_ar_write6;
|
||||
return ar_exact_write_takes(g, T) ? op_ar_write : op_ar_write6;
|
||||
}
|
||||
/* WHETHER THIS STEP'S WRITE REDUCES THE BLOCK'S OUTPUT. The block in front asks the same
|
||||
* question of the same T -- ar_taken with ar_take() -- before skipping its own collective. */
|
||||
@@ -293,15 +294,23 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
{w.x.x, w.inj, w.h}, {w.h});
|
||||
if (!op_write) return RAD_E_INVAL;
|
||||
/* A handle that did not resolve is 0 and not an error: a backend without the fused kernel
|
||||
* keeps the pair, and takes_ar() then answers no on every step. */
|
||||
if (c.reduce && g.world == 2)
|
||||
* keeps the pair, and takes_ar() then answers no on every step. At four ranks only the
|
||||
* exact form exists, declared over the decode and verify steps' rows and taken where
|
||||
* ar_wide_write_exact says so. The exact form states `wire` 0 rather than leaving it out:
|
||||
* a row that serves one wire only says so with a constraint on `wire`, and a constraint on
|
||||
* an absent key does not hold. */
|
||||
const int64_t ar_rows = ar_exact_write_rows(g);
|
||||
if (c.reduce && ar_rows >= 1)
|
||||
op_ar_write = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, ar_rows), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("wire", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x.x, w.inj, w.h}, {w.x.x, w.h});
|
||||
if (op_ar_write && !g.wire_exact)
|
||||
/* The rotated form at two ranks only: the op has no four-rank form on that wire
|
||||
* (docs/OPS.md), and an op declared that nothing resolves is reported at startup as a
|
||||
* band a request cannot run in. */
|
||||
if (op_ar_write && !g.wire_exact && g.world == 2)
|
||||
op_ar_write6 = rw(b, RAD_OP(b, "ar_hc_write",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_INT("hc", c.hc), RAD_INT("world_size", g.world),
|
||||
@@ -314,13 +323,20 @@ inline int HyperConn::declare(RadBuilder* b, Names& nm, const Geom& geom, const
|
||||
|
||||
inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
|
||||
if (!op_ar_write || src.top_k <= 0 || !src.ye || !src.ew || !src.sorted) return RAD_OK;
|
||||
/* Two ranks, and four on the exact wire: there the fused write exists in its exact form only,
|
||||
* so the gather does too -- op_ar_write6 is 0 at four and the rotated form below is never
|
||||
* declared. Any other width keeps its gather and both bounds stay 0. */
|
||||
if (g.world != 2 && g.world != 4) return RAD_OK;
|
||||
const bool shared = src.sh && src.sg;
|
||||
gsrc = src;
|
||||
/* EVERY ROW COUNT ONE PASS CARRIES, prefill chunks included: the kernel reads its slots from
|
||||
* an LDS table at a decode step and from an inverse table at a chunk, where the gather's reads
|
||||
* then run beside the reduction's push instead of in a launch of their own. */
|
||||
/* EVERY ROW COUNT ONE PASS CARRIES, up to the rows the write itself was declared for
|
||||
* (ar_exact_write_rows): prefill chunks included at two ranks, the decode and verify steps at
|
||||
* four. The kernel reads its slots from an LDS table at a decode step and from an inverse
|
||||
* table at a chunk, where the gather's reads then run beside the reduction's push instead of
|
||||
* in a launch of their own. */
|
||||
int64_t rows = src.rows;
|
||||
if (rows > g.max_tok) rows = g.max_tok;
|
||||
const int64_t ar_rows = ar_exact_write_rows(g);
|
||||
if (rows > ar_rows) rows = ar_rows;
|
||||
if (rows < 1) return RAD_OK;
|
||||
const rad_buf rd[8] = { src.ye, src.ew, src.sorted, w.x.x, w.inj, w.h, src.sh, src.sg };
|
||||
const rad_buf wr[2] = { w.x.x, w.h };
|
||||
@@ -332,7 +348,8 @@ inline int HyperConn::declare_gather(RadBuilder* b, const GatherSrc& src) {
|
||||
RAD_INT("hc", c.hc), RAD_INT("top_k", src.top_k),
|
||||
RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none")),
|
||||
RAD_STR("act", shared ? "sigmoid" : "none"),
|
||||
RAD_INT("wire", 0)),
|
||||
RAD_NOWEIGHTS);
|
||||
if (op_ar_gather_write) {
|
||||
RAD_ARCH_TRY(rad_op_reads (b, op_ar_gather_write, rd, shared ? 8 : 6));
|
||||
@@ -380,7 +397,8 @@ inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) co
|
||||
if (takes_gather(T)) {
|
||||
const int64_t k = gsrc.top_k;
|
||||
const bool shared = gsrc.sh && gsrc.sg;
|
||||
RAD_ISSUE_N(c_, ar_wire_is_exact(g, T) ? op_ar_gather_write : op_ar_gather_write6, rows,
|
||||
const rad_op op = ar_exact_write_takes(g, T) ? op_ar_gather_write : op_ar_gather_write6;
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brows(gsrc.ye, rows * k), brow_slice(gsrc.ew, r0, rows, k),
|
||||
brows(gsrc.sorted, rows * k),
|
||||
shared ? brow_slice(gsrc.sh, r0, rows, g.n_embd) : RAD_NONE,
|
||||
|
||||
@@ -122,10 +122,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
|
||||
/* The fold, over the same weights and into the same activation the pair writes. Not
|
||||
* RAD_ARCH_TRY: a plugin without the row is the ordinary case and the pair still runs. It
|
||||
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold. */
|
||||
* multiplies fp8 codes by a block-fp8 gate_up, so a plain gate_up has no fold -- and neither
|
||||
* has an MXFP4 one: libr4d's gated fold is an fp8a8 tile, and the pair serves it. */
|
||||
{
|
||||
const int64_t hi = g.max_tok < 64 ? g.max_tok : 64;
|
||||
if (hi > 0 && !gate_up.bf16) {
|
||||
if (hi > 0 && !gate_up.bf16 && !gate_up.mx) {
|
||||
op_gated = rw(b, RAD_OP(b, "gemm_nt_q_gated",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", gate_up.N),
|
||||
RAD_INT("K", gate_up.K),
|
||||
|
||||
+238
-45
@@ -45,7 +45,9 @@
|
||||
* Config::ff_lo). So the arrays are declared in separate loops -- gate_up codes, gate_up scales,
|
||||
* down codes, down scales, each for the even experts and then the odd ones -- and NOT as a group
|
||||
* per expert. Interleaving them would give runs of stride two or four, which the operand cannot
|
||||
* express; the failure would be a table whose second entry is a scale plane.
|
||||
* express; the failure would be a table whose second entry is a scale plane. Where four ranks split
|
||||
* every expert the classes are four, by number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4), and the
|
||||
* runs sixteen, declared the same way class by class.
|
||||
*
|
||||
* The codes run and the scale run of a projection are two VIEWS of one stored weight -- its codes
|
||||
* plane and its scale plane (RadWeightDecl::source) -- so an expert holds two logical weights,
|
||||
@@ -74,6 +76,10 @@ namespace arch {
|
||||
* decide, at declare time and identically on both ranks, whether the op exists at all. */
|
||||
static const int64_t kMoeSortRows = 1024;
|
||||
|
||||
/* The skinny bf16 GEMM's decode band, which is where the fused op's GEMM is that GEMM's own
|
||||
* arithmetic; past it the router runs the tiled kernel and the pair is issued as before. */
|
||||
static const int64_t kMoeRouterFusedRows = 64;
|
||||
|
||||
|
||||
|
||||
/* ---- RADIANCE_DEBUG_ROUTING: the routing WEIGHTS of token 0, which nothing else reports.
|
||||
@@ -163,6 +169,19 @@ struct MoeFP8 {
|
||||
* and the sum of the partials is the expert's output. Rounding moves (two partial sums
|
||||
* where there was one), so this is checked by agreement rather than byte for byte. */
|
||||
int64_t ff_lo[2] = { 0, 0 }, ff_hi[2] = { 0, 0 };
|
||||
/* OR BY THE EXPERT'S NUMBER MOD 4, where four ranks split it: expert e's columns
|
||||
* [ff_lo4[e % 4], ff_hi4[e % 4]), served by `moe_gemm_q_mod4`, and taking precedence over
|
||||
* the parity slices. hi 0 offers none.
|
||||
*
|
||||
* Parity gives the extra block of a five-block expert two places to go, so at four ranks
|
||||
* two of them carry three blocks of every even/odd pair and two carry two -- and the
|
||||
* block's all-reduce has the narrow ranks wait for the wide ones. Four classes give it
|
||||
* four: each rank takes two blocks of one class and one of each other, five of every four
|
||||
* experts. Any count of quantised experts serves: a layer that keeps two plain bf16 has
|
||||
* 510, and its first two classes hold one expert more than the last two (the declaration
|
||||
* gives a table op's first tables the remainder). `n_ff_exp` is the widest slice. "e" is
|
||||
* the expert's place in the sort, as for the parity classes. */
|
||||
int64_t ff_lo4[4] = { 0, 0, 0, 0 }, ff_hi4[4] = { 0, 0, 0, 0 };
|
||||
int64_t n_ff_shared = 0; /* the shared expert's, per rank; 0 = no shared expert */
|
||||
/* THE SHARED ARM'S SLICE ON THIS RANK, when its width does not halve into whole fp8 scale
|
||||
* blocks: [shared_lo, shared_hi) of its columns in the model's numbering, with
|
||||
@@ -347,6 +366,13 @@ struct MoeFP8 {
|
||||
* a prefill chunk is past it. */
|
||||
rad_op op_topk_scatter = 0;
|
||||
int64_t topk_scatter_rows = 0;
|
||||
/* `router_gemm_topk_scatter`, if it resolves: the router GEMM in front of the pair above, up
|
||||
* to `router_fused_rows` tokens, and with `router_fused_gate` the shared expert's gate
|
||||
* (`op_sgate`'s work) as well. 0 -- the op did not resolve -- issues the router and the pair
|
||||
* as always, and so does a pass of more rows. */
|
||||
rad_op op_router_fused = 0;
|
||||
int64_t router_fused_rows = 0;
|
||||
bool router_fused_gate = false;
|
||||
/* The rotated re-quantisation of the block input, declared only when `expert_rot` is set and
|
||||
* the caller does not already write `w.hr`. */
|
||||
rad_op op_hq = 0;
|
||||
@@ -362,6 +388,9 @@ struct MoeFP8 {
|
||||
std::vector<int64_t> prot;
|
||||
const char* prot_list = nullptr;
|
||||
int64_t n_reg = 0;
|
||||
/* How many weight-table classes the quantised GEMMs take: 2 by parity (`moe_gemm_q`), or 4 by
|
||||
* number mod 4 (`moe_gemm_q_mod4`, Config::ff_lo4). */
|
||||
int ncls = 2;
|
||||
/* THIS LAYER'S gate_up AND down FORMATS (format_of's numbers), resolved by declare(): the
|
||||
* probed layer's for both, except that among the codebook forms at E4M3 scales -- w4nl64a8h,
|
||||
* w4nl32a8h, w5nl64a8h -- each projection of each layer takes its own experts'. */
|
||||
@@ -434,7 +463,7 @@ struct MoeFP8 {
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
/* One pass of at most `c.rows` tokens. */
|
||||
void pass(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void shared_up(RadCtx* c, int64_t T, int64_t r0, int64_t rows, bool gate_done = false) const;
|
||||
};
|
||||
|
||||
inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
@@ -554,6 +583,9 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
/* A rank whose slice of the shared arm is empty (see Config) declares no arm, and the
|
||||
* all-reduce carries the others' share. */
|
||||
const bool shared = c.n_ff_shared > 0 && src.shared;
|
||||
/* Whether `w.sgate` is out of the sharing pool -- set where the shared arm says so, and what
|
||||
* the fused router's gate write relies on (see there). */
|
||||
bool sgate_concurrent = false;
|
||||
|
||||
/* THE INPUT MAY BE PREPARED BY THE ARCHITECTURE, and `src.norm == nullptr` is how it says so.
|
||||
*
|
||||
@@ -647,8 +679,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
"places at most %lld last\n", l, prot.size(), (long long)kMaxProtected);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The quantised GEMM takes its experts as two equal tables by parity. */
|
||||
if (n_reg % 2) {
|
||||
/* The quantised GEMM takes its experts as two equal tables by parity -- at four classes
|
||||
* (Config::ff_lo4) as four tables, the first n_reg % 4 one expert longer, which any count
|
||||
* gives. */
|
||||
if (!(c.ff_hi[0] > 0 && c.ff_hi4[0] > 0) && n_reg % 2) {
|
||||
fprintf(stderr, "radiance: layer %d keeps %zu experts plain bf16 on this rank, which "
|
||||
"leaves %lld quantised; they come in pairs on a rank so the rest split "
|
||||
"into two equal tables by parity\n", l, prot.size(), (long long)n_reg);
|
||||
@@ -778,21 +812,43 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (std::find(prot.begin(), prot.end(), e) == prot.end()) reg.push_back(e);
|
||||
w_gu.resize((size_t)ne); w_gus.resize((size_t)ne);
|
||||
w_dn.resize((size_t)ne); w_dns.resize((size_t)ne);
|
||||
/* Each parity's width on this rank: the Config's slice when the width is split unevenly, and
|
||||
* `n_ff_exp` for both otherwise. The buffers between the two GEMMs are the wider one's. */
|
||||
const bool split = c.ff_hi[0] > 0;
|
||||
int64_t wq[2] = { c.n_ff_exp, c.n_ff_exp };
|
||||
if (split)
|
||||
for (int q = 0; q < 2; ++q) wq[q] = c.ff_hi[q] - c.ff_lo[q];
|
||||
if (split && (wq[0] <= 0 || wq[1] <= 0 || c.n_ff_exp != (wq[0] > wq[1] ? wq[0] : wq[1]))) {
|
||||
fprintf(stderr, "radiance: the routed experts' slices [%lld, %lld) and [%lld, %lld) do not "
|
||||
"describe a width of %lld\n", (long long)c.ff_lo[0], (long long)c.ff_hi[0],
|
||||
(long long)c.ff_lo[1], (long long)c.ff_hi[1], (long long)c.n_ff_exp);
|
||||
/* Each class's width on this rank: the Config's slice when the width is split unevenly, and
|
||||
* `n_ff_exp` for every class otherwise. The buffers between the two GEMMs are the widest
|
||||
* one's. FOUR CLASSES where the Config offers them (Config::ff_lo4), the parity classes
|
||||
* otherwise. */
|
||||
const bool split = c.ff_hi[0] > 0 || c.ff_hi4[0] > 0;
|
||||
ncls = c.ff_hi4[0] > 0 ? 4 : 2;
|
||||
if (ncls == 4 && n_reg < 4) {
|
||||
fprintf(stderr, "radiance: layer %d serves %lld quantised experts on this rank; four "
|
||||
"classes need at least one each\n", l, (long long)n_reg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int q = 0; q < 2; ++q)
|
||||
int64_t qlo[4] = { 0, 0, 0, 0 }, qhi[4] = { 0, 0, 0, 0 };
|
||||
int64_t wq[4] = { c.n_ff_exp, c.n_ff_exp, c.n_ff_exp, c.n_ff_exp };
|
||||
if (split)
|
||||
for (int q = 0; q < ncls; ++q) {
|
||||
qlo[q] = ncls == 4 ? c.ff_lo4[q] : c.ff_lo[q];
|
||||
qhi[q] = ncls == 4 ? c.ff_hi4[q] : c.ff_hi[q];
|
||||
wq[q] = qhi[q] - qlo[q];
|
||||
}
|
||||
if (split) {
|
||||
int64_t widest = 0;
|
||||
bool bad = false;
|
||||
for (int q = 0; q < ncls; ++q) {
|
||||
bad = bad || wq[q] <= 0;
|
||||
widest = wq[q] > widest ? wq[q] : widest;
|
||||
}
|
||||
if (bad || c.n_ff_exp != widest) {
|
||||
fprintf(stderr, "radiance: the routed experts' %d class slices, the first [%lld, %lld) "
|
||||
"and [%lld, %lld), do not describe a width of %lld\n", ncls,
|
||||
(long long)qlo[0], (long long)qhi[0], (long long)qlo[1], (long long)qhi[1],
|
||||
(long long)c.n_ff_exp);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
for (int q = 0; q < ncls; ++q)
|
||||
if (wq[q] % RAD_FP8_BLOCK || g.n_embd % RAD_FP8_BLOCK ||
|
||||
(split && c.ff_lo[q] % RAD_FP8_BLOCK)) {
|
||||
(split && qlo[q] % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: an expert is %lldx%lld per rank, which is not a whole number "
|
||||
"of %dx%d scale blocks\n",
|
||||
(long long)wq[q], (long long)g.n_embd, RAD_FP8_BLOCK, RAD_FP8_BLOCK);
|
||||
@@ -852,11 +908,11 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const uint32_t sdt = c.expert_g64 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
|
||||
const int64_t sgk = c.expert_g64 ? 1 : RAD_FP8_BLOCK;
|
||||
const char* escale = c.expert_g64 ? "scale,scale.1" : "scale";
|
||||
/* A slice of each expert: the gate and up rows [lo, hi) of this parity for the gate/up pair,
|
||||
/* A slice of each expert: the gate and up rows [lo, hi) of this class for the gate/up pair,
|
||||
* columns [lo, hi) for down, and the scale planes the same slice in their own units. */
|
||||
auto span = [&](rad_weight h, int q, int64_t unit) -> int {
|
||||
if (!split || !h) return RAD_OK;
|
||||
return rad_weight_shard_span(b, h, c.ff_lo[q] / unit, c.ff_hi[q] / unit);
|
||||
return rad_weight_shard_span(b, h, qlo[q] / unit, qhi[q] / unit);
|
||||
};
|
||||
const bool rot = c.expert_rot != 0;
|
||||
if (c.expert_bf16) {
|
||||
@@ -910,9 +966,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.eff.x, w.sorted, w.eoff}, {w.edn});
|
||||
if (!op_gu || !op_dn) return RAD_E_INVAL;
|
||||
} else {
|
||||
/* ---- the eight runs, declared as the views the header describes. */
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += 2) {
|
||||
/* ---- the eight runs -- sixteen at four classes -- declared as the views the header
|
||||
* describes, class by class. */
|
||||
for (int q = 0; q < ncls; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += ncls) {
|
||||
const int64_t e = reg[(size_t)s];
|
||||
const int64_t parts[2] = { wq[q], wq[q] };
|
||||
rad_weight& h = w_gu[(size_t)s];
|
||||
@@ -924,8 +981,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, 1));
|
||||
}
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += 2) {
|
||||
for (int q = 0; q < ncls; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += ncls) {
|
||||
const int64_t e = reg[(size_t)s];
|
||||
const int64_t parts[2] = { wq[q] / sdiv, wq[q] / sdiv };
|
||||
rad_weight& h = w_gus[(size_t)s];
|
||||
@@ -941,8 +998,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, sdiv));
|
||||
}
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += 2) {
|
||||
for (int q = 0; q < ncls; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += ncls) {
|
||||
const int64_t e = reg[(size_t)s];
|
||||
rad_weight& h = w_dn[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
@@ -952,8 +1009,8 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
if (!h) return RAD_E_INVAL;
|
||||
RAD_ARCH_TRY(span(h, q, 1));
|
||||
}
|
||||
for (int q = 0; q < 2; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += 2) {
|
||||
for (int q = 0; q < ncls; ++q)
|
||||
for (int64_t s = q; s < n_reg; s += ncls) {
|
||||
const int64_t e = reg[(size_t)s];
|
||||
rad_weight& h = w_dns[(size_t)s];
|
||||
h = decl_view(b, nm.f("blk.%d.ffn_down_exps.%lld.scale", l,
|
||||
@@ -998,13 +1055,14 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.h.x}, {w.hr.q, w.hr.s});
|
||||
}
|
||||
/* A table op's weights, in its table operands' order: the even experts' codes and scales, then
|
||||
* the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`). */
|
||||
* the odd experts' (`w`, `w_scale`, `w_odd`, `w_odd_scale`) -- or at four classes class 0's,
|
||||
* then 1's, 2's and 3's. */
|
||||
auto tables = [&](const std::vector<rad_weight>& wc, const std::vector<rad_weight>& ws) {
|
||||
std::vector<rad_weight> tab;
|
||||
tab.reserve((size_t)n_reg * 2);
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
for (int64_t s = q; s < n_reg; s += 2) tab.push_back(wc[(size_t)s]);
|
||||
for (int64_t s = q; s < n_reg; s += 2) tab.push_back(ws[(size_t)s]);
|
||||
for (int q = 0; q < ncls; ++q) {
|
||||
for (int64_t s = q; s < n_reg; s += ncls) tab.push_back(wc[(size_t)s]);
|
||||
for (int64_t s = q; s < n_reg; s += ncls) tab.push_back(ws[(size_t)s]);
|
||||
}
|
||||
return tab;
|
||||
};
|
||||
@@ -1014,7 +1072,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* width, which its down projection does not read. */
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_gu, w_gus);
|
||||
rad_op h = rad_decl_op(b, "moe_gemm_q",
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "token"), RAD_STR("dtype", edtype[0]),
|
||||
RAD_INT("N_1", 2 * wq[1]), RAD_INT("K_1", g.n_embd),
|
||||
RAD_INT("N_2", 2 * wq[2]), RAD_INT("K_2", g.n_embd),
|
||||
RAD_INT("N_3", 2 * wq[3]), RAD_INT("K_3", g.n_embd),
|
||||
RAD_INT("parts", 2)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", 2 * wq[0]),
|
||||
RAD_INT("K", g.n_embd), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
@@ -1032,7 +1101,18 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
false, rot));
|
||||
{
|
||||
const std::vector<rad_weight> tab = tables(w_dn, w_dns);
|
||||
rad_op h = rad_decl_op(b, "moe_gemm_q",
|
||||
rad_op h = ncls == 4
|
||||
? rad_decl_op(b, "moe_gemm_q_mod4",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("a_order", "sorted"), RAD_STR("dtype", edtype[1]),
|
||||
RAD_INT("N_1", g.n_embd), RAD_INT("K_1", wq[1]),
|
||||
RAD_INT("N_2", g.n_embd), RAD_INT("K_2", wq[2]),
|
||||
RAD_INT("N_3", g.n_embd), RAD_INT("K_3", wq[3]),
|
||||
RAD_INT("parts", 1)),
|
||||
tab.data(), (int)tab.size())
|
||||
: rad_decl_op(b, "moe_gemm_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.rows), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", wq[0]), RAD_INT("n_expert", n_reg),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("group", RAD_FP8_BLOCK),
|
||||
@@ -1057,19 +1137,44 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
const int64_t np = (int64_t)prot.size();
|
||||
int64_t wp = c.n_ff_exp;
|
||||
int psh_row = RAD_SHARD_NONE, psh_col = RAD_SHARD_NONE, pparts = 0;
|
||||
/* This rank's tile range within one plain expert, in the model's numbering; `phi` 0 is the
|
||||
* even split, which needs no span because the loader divides the entry itself. */
|
||||
int64_t plo = 0, phi = 0;
|
||||
if (split) {
|
||||
/* `n_ff_exp` is this rank's wider slice here; the expert's whole width is where the
|
||||
* parity slices end. */
|
||||
const int64_t full = c.ff_hi[0] > c.ff_hi[1] ? c.ff_hi[0] : c.ff_hi[1];
|
||||
if (full % g.world || (full / g.world) % 64) {
|
||||
/* THE EXPERT'S WHOLE WIDTH, not this rank's slice of it: `n_ff_all` is the model's, and
|
||||
* where the parity tables end says the same thing at two ranks and nothing else at
|
||||
* more -- reading it off `ff_hi` gave a per-rank answer, which happened to be right
|
||||
* only when there were two of them. A plain expert has no scale blocks to land on, so
|
||||
* the unit here is the GEMM's 64-wide output tile. */
|
||||
const int64_t full = g.n_ff_all > 0 ? g.n_ff_all
|
||||
: (c.ff_hi[0] > c.ff_hi[1] ? c.ff_hi[0]
|
||||
: c.ff_hi[1]);
|
||||
/* ONE SLICE A RANK, and it does not have to be the same size on every rank: an uneven
|
||||
* share of the 64-wide tiles is still whole tiles, and an uneven share is the only
|
||||
* kind available when the width does not divide -- this family's 640 columns are ten
|
||||
* tiles, which four ranks take as 3, 3, 2, 2, the first ranks by index taking the
|
||||
* extra ones. Every tile has exactly one owner, each rank writes its own columns of
|
||||
* gate/up and reads its own of down, and the block's all-reduce sums the partials
|
||||
* exactly as it does for the quantised experts and for the shared arm. The even case
|
||||
* keeps the even-split declaration verbatim -- no span at all -- so a rank count that
|
||||
* divides declares exactly as it did before. */
|
||||
psh_row = RAD_SHARD_ROW;
|
||||
psh_col = RAD_SHARD_COL;
|
||||
pparts = 2;
|
||||
if (full % g.world == 0 && (full / g.world) % 64 == 0) {
|
||||
wp = full / g.world;
|
||||
} else if (full % 64 || full / 64 < g.world) {
|
||||
fprintf(stderr, "radiance: layer %d's plain experts are %lld wide, which %d ranks "
|
||||
"cannot share in 64-wide tiles\n", l, (long long)full, g.world);
|
||||
return RAD_E_INVAL;
|
||||
} else {
|
||||
const int64_t nt = full / 64, base = nt / g.world, extra = nt % g.world;
|
||||
const int64_t t0 = (int64_t)g.rank * base + std::min<int64_t>(g.rank, extra);
|
||||
const int64_t t1 = t0 + base + ((int64_t)g.rank < extra ? 1 : 0);
|
||||
plo = t0 * 64;
|
||||
phi = t1 * 64;
|
||||
wp = phi - plo;
|
||||
}
|
||||
wp = full / g.world;
|
||||
psh_row = RAD_SHARD_ROW;
|
||||
psh_col = RAD_SHARD_COL;
|
||||
pparts = 2;
|
||||
}
|
||||
w_pgu.assign((size_t)np, 0);
|
||||
w_pdn.assign((size_t)np, 0);
|
||||
@@ -1080,6 +1185,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_BF16, {2 * wp, g.n_embd}, RAD_ACCESS_PER_TOKEN,
|
||||
psh_row, grp_layer(l), 0, parts, pparts);
|
||||
if (!w_pgu[(size_t)j]) return RAD_E_INVAL;
|
||||
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pgu[(size_t)j], plo, phi));
|
||||
}
|
||||
for (int64_t j = 0; j < np; ++j) {
|
||||
w_pdn[(size_t)j] = decl_w(b, nm.f("blk.%d.ffn_down_exps.%lld.weight", l,
|
||||
@@ -1087,6 +1193,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_BF16, {g.n_embd, wp}, RAD_ACCESS_PER_TOKEN, psh_col,
|
||||
grp_layer(l));
|
||||
if (!w_pdn[(size_t)j]) return RAD_E_INVAL;
|
||||
if (phi > 0) RAD_ARCH_TRY(rad_weight_shard_span(b, w_pdn[(size_t)j], plo, phi));
|
||||
}
|
||||
/* The gate_up output and the gate's, a sorted row each and in bf16: the rows of the
|
||||
* regular experts are never written and never read. */
|
||||
@@ -1242,6 +1349,7 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sff.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sout));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, w.sgate));
|
||||
sgate_concurrent = true;
|
||||
/* The gate/up rows and the down columns of this rank's slice -- the even split, or the
|
||||
* uneven one Config states -- and the split of gate from up stays, because that is a
|
||||
* property of the stacked checkpoint tensor and not of the rank count. */
|
||||
@@ -1274,6 +1382,53 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
{w.h.x}, {w.sgate});
|
||||
}
|
||||
|
||||
/* ---- THE ROUTER GEMM AND `router_topk_scatter` AS ONE OP, with the shared expert's gate in
|
||||
* the same launch wherever the layer has one. Asked for wherever the pair itself is declared,
|
||||
* up to the pair's own row bound and the skinny GEMM's decode band; a plugin that does not
|
||||
* serve it leaves the handle 0 and the router and the pair are issued as declared above.
|
||||
* Declared HERE, after the gate's weight, and not beside the router: the op names both
|
||||
* weights, and declaring it late only lengthens the planned lifetime of the buffers it
|
||||
* touches, never shortens one -- each of them is also declared by the op it stands in for, at
|
||||
* that op's place.
|
||||
*
|
||||
* EXCEPT `w.sgate`, WHICH THE FUSED OP WRITES AHEAD OF ITS DECLARED WRITER. The gate is issued
|
||||
* at the router's place, before `op_sgate`'s declared index, so a plan bounded by the linear
|
||||
* order could lend `w.sgate`'s bytes to a buffer that is live in between. It cannot here
|
||||
* because the shared arm took `w.sgate` out of the sharing pool (rad_buf_concurrent), and the
|
||||
* declaration refuses a fused gate on a layer where that has not happened.
|
||||
*
|
||||
* NOT rw()'s braced lists and not one RAD_OP per combination: the parameter list (a protect
|
||||
* list or not), the weights and the write set (the gate or not) are conditional, so each is
|
||||
* one array cut to its length. */
|
||||
if (op_topk_scatter) {
|
||||
router_fused_rows = topk_scatter_rows < kMoeRouterFusedRows ? topk_scatter_rows
|
||||
: kMoeRouterFusedRows;
|
||||
const bool gate = op_sgate != 0;
|
||||
if (gate && !sgate_concurrent) {
|
||||
fprintf(stderr, "radiance: layer %d: the fused router writes the shared gate ahead of "
|
||||
"its declared writer, which needs `sgate` out of the sharing pool, "
|
||||
"and it is not\n", l);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const RadParam fp[] = {
|
||||
RAD_RANGE("M", 1, router_fused_rows), RAD_INT("K", g.n_embd),
|
||||
RAD_INT("n_expert", c.n_expert_all), RAD_INT("n_local", c.n_expert),
|
||||
RAD_INT("top_k", c.top_k), RAD_INT("norm", c.norm_topk),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("expert_base", c.expert_base),
|
||||
RAD_STR("protect", prot_list),
|
||||
};
|
||||
const int n_fp = (int)(sizeof(fp) / sizeof(fp[0])) - (prot_list ? 0 : 1);
|
||||
const rad_weight fw[2] = { w_router, w_sgate };
|
||||
op_router_fused = rad_decl_op(b, "router_gemm_topk_scatter", fp, n_fp, fw, gate ? 2 : 1);
|
||||
if (op_router_fused) {
|
||||
const rad_buf rd[1] = { w.h.x };
|
||||
const rad_buf wr[7] = { w.logits, w.ids, w.ew, w.sorted, w.eoff, w.ecnt, w.sgate };
|
||||
rad_op_reads (b, op_router_fused, rd, 1);
|
||||
rad_op_writes(b, op_router_fused, wr, gate ? 7 : 6);
|
||||
}
|
||||
router_fused_gate = op_router_fused && gate;
|
||||
}
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -1306,7 +1461,10 @@ inline int MoeFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
* The shared expert is ordinary dense linears over that input, and every buffer it touches is the
|
||||
* step's height -- so the pass offset goes through all of them exactly as it does through an
|
||||
* MlpFP8 slice. */
|
||||
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
inline void MoeFP8::shared_up(RadCtx* c_, int64_t T, int64_t r0, int64_t rows,
|
||||
bool gate_done) const {
|
||||
/* `gate_done`: the fused router already wrote this pass's gate. */
|
||||
if (!gate_done)
|
||||
RAD_ISSUE_N(c_, op_sgate, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_sgate),
|
||||
brow_slice(w.sgate, r0, rows, 1));
|
||||
sh_gate_up.step(c_, w.h, w.sgu, T, r0, rows);
|
||||
@@ -1338,11 +1496,25 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
|
||||
* a routed layer, a whole dependent dispatch for a kilobyte. */
|
||||
int32_t* const counts = rad_route_counts(c_, layer, ne);
|
||||
const RadOperand ecnt = counts ? praw(counts, RAD_I32, ne) : brows(w.ecnt, ne);
|
||||
/* THE FUSED ROUTER where it resolved and the pass is within its rows: the router, the pair
|
||||
* below and -- with `router_fused_gate` -- the shared gate, in one launch with the operands
|
||||
* the three are handed. Otherwise the router and the pair, as declared. */
|
||||
const bool rfused = op_router_fused && rows <= router_fused_rows;
|
||||
if (rfused)
|
||||
RAD_ISSUE_N(c_, op_router_fused, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
RAD_W(w_router), router_fused_gate ? RAD_W(w_sgate) : RAD_NONE,
|
||||
brow_slice(w.logits, r0, rows, ne_all),
|
||||
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt,
|
||||
router_fused_gate ? brow_slice(w.sgate, r0, rows, 1) : RAD_NONE);
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_router, rows, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_W(w_router),
|
||||
brow_slice(w.logits, r0, rows, ne_all));
|
||||
/* One launch or two. `w.ids` is the fused op's OUTPUT where it was the sort's input, and
|
||||
* every other operand is the one the pair is handed. */
|
||||
if (op_topk_scatter && rows <= topk_scatter_rows) {
|
||||
if (rfused) {
|
||||
/* the fused router wrote all five */
|
||||
} else if (op_topk_scatter && rows <= topk_scatter_rows) {
|
||||
RAD_ISSUE_N(c_, op_topk_scatter, rows, brow_slice(w.logits, r0, rows, ne_all),
|
||||
brow_slice(w.ids, r0, rows, k), brow_slice(w.ew, r0, rows, k),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), ecnt);
|
||||
@@ -1364,11 +1536,23 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
|
||||
|
||||
/* The two grouped GEMMs, and the weight tables: the FIRST handle of each run and its length.
|
||||
* The runs are contiguous by construction -- see declare -- so `w_gu[q] + i` is expert
|
||||
* 2 * i + q, and each parity is its own pair of table operands. */
|
||||
* 2 * i + q, and each parity is its own pair of table operands; at four classes expert
|
||||
* 4 * i + q, class q holding ceil((n_reg - q) / 4). */
|
||||
const int64_t n4[4] = { (n_reg + 3) / 4, (n_reg + 2) / 4, (n_reg + 1) / 4, n_reg / 4 };
|
||||
if (c.expert_bf16)
|
||||
RAD_ISSUE_N(c_, op_gu, rows, brow_slice(w.h.x, r0, rows, g.n_embd),
|
||||
RAD_WTAB(w_gu[0], ne), brows(w.sorted, rows * k), brows(w.eoff, ne + 1),
|
||||
brows(w.egu, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(rot ? w.hr.s : w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK),
|
||||
RAD_WTAB(w_gu[0], n4[0]), RAD_WTAB(w_gus[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_gu[1], n4[1]), RAD_WTAB(w_gus[1], n4[1]),
|
||||
RAD_WTAB(w_gu[2], n4[2]), RAD_WTAB(w_gus[2], n4[2]),
|
||||
RAD_WTAB(w_gu[3], n4[3]), RAD_WTAB(w_gus[3], n4[3]),
|
||||
brows(w.egu, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_gu, rows,
|
||||
brow_slice(rot ? w.hr.q : w.h.q, r0, rows, g.n_embd),
|
||||
@@ -1377,12 +1561,21 @@ inline void MoeFP8::pass(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_gu[1], n_reg / 2), RAD_WTAB(w_gus[1], n_reg / 2),
|
||||
brows(w.egu, rows * k));
|
||||
if (shared) shared_up(c_, T, r0, rows);
|
||||
if (shared) shared_up(c_, T, r0, rows, rfused && router_fused_gate);
|
||||
gq_exp.step(c_, w.egu, rows * k, 0, rows * k);
|
||||
if (shared) gq_sh.step(c_, w.sgu, T, r0, rows);
|
||||
if (c.expert_bf16)
|
||||
RAD_ISSUE_N(c_, op_dn, rows, brows(w.eff.x, rows * k), RAD_WTAB(w_dn[0], ne),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, ne + 1), brows(w.edn, rows * k));
|
||||
else if (ncls == 4)
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
RAD_WTAB(w_dn[0], n4[0]), RAD_WTAB(w_dns[0], n4[0]),
|
||||
brows(w.sorted, rows * k), brows(w.eoff, n_reg + 1),
|
||||
RAD_WTAB(w_dn[1], n4[1]), RAD_WTAB(w_dns[1], n4[1]),
|
||||
RAD_WTAB(w_dn[2], n4[2]), RAD_WTAB(w_dns[2], n4[2]),
|
||||
RAD_WTAB(w_dn[3], n4[3]), RAD_WTAB(w_dns[3], n4[3]),
|
||||
brows(w.edn, rows * k));
|
||||
else
|
||||
RAD_ISSUE_N(c_, op_dn, rows,
|
||||
brows(w.eff.q, rows * k), brows(w.eff.s, rows * k),
|
||||
|
||||
@@ -436,16 +436,22 @@ inline void MtpBlockFP8<Ffn>::step(RadCtx* c, const RadBatch* batch) const {
|
||||
RAD_ISSUE(c, op_fc, brows(w.c, T), RAD_W(w_fc), brows(w.x, T));
|
||||
|
||||
attn.step(c, batch);
|
||||
|
||||
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave K and V behind, and the
|
||||
* attention above has stored them. The feed-forward, the norm and the lm_head compute the
|
||||
* head's output, which only a drafting row reads -- and every prefill chunk but a prompt's
|
||||
* last drafts nothing. `n_draft_out` is the batch's and the same on every rank, so a
|
||||
* collective the feed-forward would run is skipped on all of them. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) return;
|
||||
|
||||
mlp.step(c, batch);
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.hout, T));
|
||||
|
||||
/* A history pass that drafts nothing exists only to leave K and V behind. One that does
|
||||
* brings round 1's rows to the front first. */
|
||||
/* A history pass that drafts brings round 1's rows to the front first. */
|
||||
int64_t L = T; /* the rows the lm_head runs over */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hout), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.x, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.x, L), brows(w.hout, L));
|
||||
|
||||
@@ -528,6 +528,16 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
* when the attention runs. */
|
||||
qsa.step(c, attn.w.h, batch);
|
||||
attn.step(c, batch);
|
||||
|
||||
/* A HISTORY PASS THAT DRAFTS NOTHING ENDS HERE. It exists to leave the head's state behind --
|
||||
* the K and V the attention just stored and the indexer's block keys and tail -- and both are
|
||||
* written above. Everything below computes the head's stream, which only a drafting row
|
||||
* reads: the experts, the two connections around them and the lm_head. Every prefill chunk
|
||||
* but a prompt's last is such a pass, so on those the head costs its attention alone.
|
||||
* `n_draft_out` is the batch's and the same on every rank, so the collectives skipped here
|
||||
* are skipped on all of them. */
|
||||
if (r < 0 && batch->n_draft_out <= 0) return;
|
||||
|
||||
hc_attn.write(c, T, 0, T);
|
||||
|
||||
hc_mlp.read(c, T, 0, T);
|
||||
@@ -536,12 +546,10 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const {
|
||||
|
||||
/* THE CARRY, and only where a round after this one will read it. The last round of a group
|
||||
* is followed by a trunk step. A history pass that drafts takes round 1's rows out of its own
|
||||
* -- into the carry, and back to the front of `hw` for the mixer below -- and one that does
|
||||
* not exists only to leave K and V behind. */
|
||||
* -- into the carry, and back to the front of `hw` for the mixer below. */
|
||||
int64_t L = T; /* the rows the lm_head runs over */
|
||||
if (r < 0) {
|
||||
L = batch->n_draft_out;
|
||||
if (L <= 0) return;
|
||||
RAD_ISSUE_N(c, op_dsel, L, RAD_B(w.hw), praw(batch->draft_out_ids, RAD_I32, L),
|
||||
brows(w.hin, L));
|
||||
RAD_ISSUE_N(c, op_dback, L, brows(w.hin, L), brows(w.hw, L));
|
||||
|
||||
@@ -20,16 +20,19 @@
|
||||
*
|
||||
* ============================== THE TABLE DECIDES THE SHAPE OF ALL OF THIS ======================
|
||||
*
|
||||
* 51.2 GB cannot be on the card and cannot be staged onto it, so `embed_lookup_q` runs on the HOST
|
||||
* over the container's own mmap and its result crosses the link once -- 5 KB a token at decode.
|
||||
* libavx/avx_ngram.cpp carries that argument in full. Three consequences reach this file:
|
||||
* 51.2 GB cannot be staged onto a card, so `embed_lookup_q` reads it where --ngram-placement put
|
||||
* it: the HOST gather over the container's own mmap or a locked copy in RAM (libavx/avx_ngram.cpp
|
||||
* carries that argument in full), or a device kernel reading a pinned copy over the link -- or the
|
||||
* card's own copy, on a card that holds it. Either way its result reaches the card through the
|
||||
* host arena, 5 KB a token at decode. Three consequences reach this file:
|
||||
*
|
||||
* THE TABLE IS A WEIGHT OPERAND, because the planner puts an op on the host only when every
|
||||
* weight operand of it is Site::Host. A gather whose source were an activation could never be
|
||||
* placed there.
|
||||
* weight operand of it is Site::Host, and decides that from the table's placement. A gather
|
||||
* whose source were an activation could never be placed there.
|
||||
*
|
||||
* ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by a host kernel, so they live
|
||||
* in the host arena; everything downstream of `e` is ordinary device work.
|
||||
* ITS BUFFERS ARE HOST DOMAIN. `ids` and `e` are read and written by the host gather when it
|
||||
* runs, so they live in the host arena, which a device gather reads and writes over the link
|
||||
* just as well; everything downstream of `e` is ordinary device work.
|
||||
*
|
||||
* IT IS 128 CHECKPOINT TENSORS. RadNameMap holds eight sources, so the map is declared in pieces
|
||||
* by map_concat_shards() and the order IS the concatenation -- a permuted table is a model that
|
||||
@@ -302,9 +305,12 @@ inline int PleLayer::declare(RadBuilder* b, Names& nm, const Geom& geom, const C
|
||||
|
||||
/* ---- buffers ---------------------------------------------------------------------------- */
|
||||
/* HOST DOMAIN for the two the gather touches. `ids` is written by ngram_ids and read by the
|
||||
* host gather; `e` is written by the host gather and read by one device copy onto the card
|
||||
* gather; `e` is written by the gather and read by one device copy onto the card
|
||||
* (`ple_emb_dev`, below). The host arena is mapped, so the device side of that hand-off is a
|
||||
* link read (core/runtime/ctx.cpp) -- 5 KB a token at decode.
|
||||
* link read (core/runtime/ctx.cpp) -- 5 KB a token at decode. Where a device kernel gathers
|
||||
* (--ngram-placement ram or vram, with libr4d loaded) it reads `ids` and writes `e` over the
|
||||
* link too, which costs a round trip of those 5 KB and leaves no host op in the step: the
|
||||
* domain is declared here, before the placement that would say who gathers is decided.
|
||||
*
|
||||
* `ids` IS PERSIST because it is written at the top of the step and read at this layer: the
|
||||
* buffer plan computes liveness in DECLARED order, where the two ops are neighbours, and a
|
||||
|
||||
+178
-4
@@ -324,13 +324,70 @@ inline bool ar_fused_ok(const Geom& g, int64_t T) {
|
||||
return ar_wire_is_exact(g, T) || (g.n_embd % kArWire6Chunk) == 0;
|
||||
}
|
||||
|
||||
/* THE FOUR-RANK LOSSY WIRE'S TILE: tiered int8 in groups of 32, and a group may not straddle one
|
||||
* of the four shards, so a message whose element count is not a multiple of 128 goes out exact.
|
||||
* Stated here for the reason the rotation's group of 64 is stated in ar_wire_is_exact: the
|
||||
* architecture has to decide, identically on every rank, which wire a step's message takes. */
|
||||
static const int64_t kArWideWireTile = 128;
|
||||
|
||||
/* THE MOST ROWS A DECODE OR SPECULATIVE-VERIFY STEP CARRIES: one a sequence, and 1 + max_spec a
|
||||
* sequence at a verify (max_spec is 0 with speculation off), never more than max_tok. It is a fact
|
||||
* about this engine's own steps, which is why the architecture holds it. The four-rank fused write
|
||||
* and its gather are declared over M up to this, and ar_wide_write_exact takes no step above it, so
|
||||
* a step sent to them is always inside the range they were resolved for. */
|
||||
inline int64_t ar_wide_write_rows(const Geom& g) {
|
||||
const int64_t r = g.max_seqs * (1 + (g.max_spec > 0 ? g.max_spec : 0));
|
||||
return r < g.max_tok ? r : g.max_tok;
|
||||
}
|
||||
|
||||
/* THE ROWS THE EXACT FUSED WRITE IS DECLARED FOR: every step at two ranks, the decode and verify
|
||||
* steps at four (ar_wide_write_rows), and none at any other width. */
|
||||
inline int64_t ar_exact_write_rows(const Geom& g) {
|
||||
if (g.world == 2) return g.max_tok;
|
||||
if (g.world == 4) return ar_wide_write_rows(g);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* THE FOUR-RANK FUSED WRITE'S STEPS. At four ranks ar_hc_write exists on the exact wire only, and
|
||||
* it is the exact ONE-SHOT with the write behind it. A step takes it where both of these hold:
|
||||
*
|
||||
* rows T is at most ar_wide_write_rows. The fused kernel is a one-shot, and the messages a
|
||||
* one-shot is for are the decode and verify steps'. A larger step -- a prefill chunk --
|
||||
* keeps the pair, and there the standalone `all_reduce`'s own size bands choose the
|
||||
* one-shot or the two-shot: where that choice falls is the kernel library's to say,
|
||||
* so the architecture holds no copy of it. The fused one-shot serves any message it was
|
||||
* declared for with the same bytes, so this bound is a cost, not a correctness line.
|
||||
* exact --tp-wire exact, or a message the four-rank lossy row serves exactly itself: one
|
||||
* kArWideWireTile does not tile, or one under `min_bytes`, both of which that row hands
|
||||
* to the exact sum. ar_wire_is_exact's three facts, with that wire's tile.
|
||||
*
|
||||
* ar_wire_is_exact itself stays false off two ranks: the embedding's collective asks it whether
|
||||
* layer 0's fused norm absorbs that reduction, and at four no norm does. Every rank evaluates this
|
||||
* on the same T, so none can take a different branch. */
|
||||
inline bool ar_wide_write_exact(const Geom& g, int64_t T) {
|
||||
if (g.world != 4 || T < 1 || T > ar_wide_write_rows(g)) return false;
|
||||
const int64_t numel = T * g.n_embd;
|
||||
if (numel <= 0) return false;
|
||||
if (g.wire_exact) return true;
|
||||
if (numel % kArWideWireTile) return true;
|
||||
return numel * 2 < g.wire_min_bytes; /* bf16 on the wire */
|
||||
}
|
||||
|
||||
/* WHETHER A GATED RESIDUAL'S EXACT FUSED WRITE TAKES THE ALL-REDUCE AT T ROWS: at two ranks on every
|
||||
* step whose wire is exact, at four where ar_wide_write_exact says so. The write
|
||||
* (HyperConn::ar_write) and the block in front (ar_taken with kArOutExact) both ask exactly this. */
|
||||
inline bool ar_exact_write_takes(const Geom& g, int64_t T) {
|
||||
return g.world == 2 ? ar_wire_is_exact(g, T) : ar_wide_write_exact(g, T);
|
||||
}
|
||||
|
||||
/* WHICH WIRES THE CONSUMER OF A BLOCK'S ALL-REDUCE TAKES. A block is declared without knowing what
|
||||
* follows it, so the architecture tells it:
|
||||
*
|
||||
* kArOutNorm the next block's norm, which takes either wire it has a fused form for
|
||||
* (ar_fused_ok);
|
||||
* kArOutExact a gated residual's write with the exact fused form only, so a message that would
|
||||
* go out compressed stays with the block;
|
||||
* go out compressed stays with the block (ar_exact_write_takes -- at four ranks
|
||||
* also one of a step larger than a decode or verify step);
|
||||
* kArOutBoth a gated residual's write with a fused form on each wire, which takes every
|
||||
* message (HyperConn::ar_take). */
|
||||
enum ArOut : int {
|
||||
@@ -344,18 +401,21 @@ enum ArOut : int {
|
||||
inline bool ar_taken(const Geom& g, int64_t T, bool out, int take) {
|
||||
if (!out) return false;
|
||||
if (take == kArOutBoth) return true;
|
||||
if (take == kArOutExact) return ar_wire_is_exact(g, T);
|
||||
if (take == kArOutExact) return ar_exact_write_takes(g, T);
|
||||
return ar_fused_ok(g, T);
|
||||
}
|
||||
|
||||
/* WHETHER A MoE BLOCK'S GATHER RIDES IN FRONT OF THE REDUCTION THAT FOLLOWS IT (ar_gather_hc_write).
|
||||
* `rows` and `rows6` are the bounds the fused op was declared for on the exact and on the rotated
|
||||
* wire, 0 where it was not: at most the tokens one MoE pass carries, so a step it serves is one
|
||||
* pass whose gather is the whole step's. The wire the step's message goes out on picks the bound.
|
||||
* pass whose gather is the whole step's. The wire the step's message goes out on picks the bound:
|
||||
* the exact one wherever the exact fused write takes the step (ar_exact_write_takes -- at two
|
||||
* ranks ar_wire_is_exact itself, at four the decode and verify steps on the exact wire, where
|
||||
* `rows6` is always 0).
|
||||
* The block that would issue the gather and the write that would absorb it ask this of the same T
|
||||
* and the same bounds, so neither can skip it while the other issues it. */
|
||||
inline bool gather_taken(const Geom& g, int64_t T, int64_t rows, int64_t rows6) {
|
||||
const int64_t r = ar_wire_is_exact(g, T) ? rows : rows6;
|
||||
const int64_t r = ar_exact_write_takes(g, T) ? rows : rows6;
|
||||
return r > 0 && T <= r;
|
||||
}
|
||||
|
||||
@@ -604,6 +664,11 @@ struct LinearFP8 {
|
||||
rad_weight w = 0, ws = 0;
|
||||
rad_op op = 0;
|
||||
int64_t N = 0, K = 0;
|
||||
/* ROWS OF THE SCALE PLANE PER ROW OF THE WEIGHT: 1 for an int8 or bf16 linear, whose scale
|
||||
* plane (if any) has the weight's rows, RAD_FP8_BLOCK for a block-fp8 one, whose scale plane
|
||||
* is 1/128 of them. A row span on `ws` is in the plane's own rows (declare's span code
|
||||
* divides); span_parts below divides the same way. */
|
||||
int64_t ws_row_div = 1;
|
||||
/* A PLAIN bf16 WEIGHT read by `gemm_nt` over the activation's bf16 plane, in a model whose
|
||||
* linears are bf16 (Geom::w_bf16): one weight and no scale plane, and no quantiser in front. */
|
||||
bool bf16 = false;
|
||||
@@ -616,6 +681,15 @@ struct LinearFP8 {
|
||||
* GEMM. Read off the weight's encoding like `bf16`. */
|
||||
bool i8 = false;
|
||||
rad_op op_q = 0;
|
||||
/* AN OCP-MXFP4 WEIGHT, read by `gemm_nt_q` at dtype mxfp4a8 against the SAME E4M3 pair every
|
||||
* other linear here reads (`a.q`, `a.s` at an f32 scale per (row, 128)): e2m1 codes and one
|
||||
* E8M0 exponent per 32 of K, as libquant writes `codes=fp4_e2m1 group=32 scale=e8m0`. libr4d
|
||||
* folds each block's exponent into the e4m3 operand against a per-row reference, so the scale
|
||||
* plane is handed over TWICE: as `b_scale` and as `b_ref`, whose layout hook reduces the same
|
||||
* plane to that reference -- `wref` is the second view. The activation grid is the fp8 family's, so every producer's fused quantiser
|
||||
* feeds an MXFP4 linear unchanged. Read off the weight's encoding like `bf16` and `i8`. */
|
||||
bool mx = false;
|
||||
rad_weight wref = 0;
|
||||
/* What probe() read: the weight is int8. Lets a model learn its trunk's format from one linear
|
||||
* before it declares the activation buffers that format decides (ActFP8::declare_qs's `i8`). */
|
||||
bool probed_i8 = false;
|
||||
@@ -662,6 +736,28 @@ struct LinearFP8 {
|
||||
int64_t span_lo = 0, int64_t span_hi = 0);
|
||||
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
|
||||
int64_t rows = 0) const;
|
||||
/* A SPAN PER STACKED ROW PART (rad_weight_shard_span_parts), in the weight's rows; the scale
|
||||
* plane takes the same spans in its own rows. After declare(); every span and total has to be
|
||||
* whole scale blocks when the plane is 1/128, which head widths of 128 are. */
|
||||
int span_parts(RadBuilder* b, const int64_t* lo, const int64_t* hi, const int64_t* total,
|
||||
int n) const {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span_parts(b, w, lo, hi, total, n));
|
||||
if (!ws) return RAD_OK;
|
||||
if (ws_row_div == 1) return rad_weight_shard_span_parts(b, ws, lo, hi, total, n);
|
||||
int64_t slo[RAD_MAX_ROW_PARTS], shi[RAD_MAX_ROW_PARTS], stot[RAD_MAX_ROW_PARTS];
|
||||
for (int g = 0; g < n && g < RAD_MAX_ROW_PARTS; ++g) {
|
||||
if (lo[g] % ws_row_div || hi[g] % ws_row_div || total[g] % ws_row_div) {
|
||||
fprintf(stderr, "radiance: a part span [%lld, %lld) of %lld rows is not whole "
|
||||
"%lld-row scale blocks\n", (long long)lo[g], (long long)hi[g],
|
||||
(long long)total[g], (long long)ws_row_div);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
slo[g] = lo[g] / ws_row_div;
|
||||
shi[g] = hi[g] / ws_row_div;
|
||||
stot[g] = total[g] / ws_row_div;
|
||||
}
|
||||
return rad_weight_shard_span_parts(b, ws, slo, shi, stot, n);
|
||||
}
|
||||
};
|
||||
|
||||
/* THE NAME MAP OF A LINEAR, DECLARED BEFORE ITS WEIGHT: it is how the checkpoint -- or the recipe
|
||||
@@ -691,6 +787,16 @@ inline bool linear_is_w8(const RadEncoding& e) {
|
||||
sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
|
||||
/* The OCP-MXFP4 weight LinearFP8 serves at mxfp4a8: e2m1 codes one a value and an E8M0 exponent
|
||||
* per [1 x 32], no transform -- what libr4d's MXFP4 layout hook accepts. */
|
||||
enum { RAD_MX_GROUP = 32 };
|
||||
inline bool linear_is_mxfp4(const RadEncoding& e) {
|
||||
if (!rad_enc_is(&e, "affine") || e.n_planes != 2 || e.transform[0]) return false;
|
||||
const RadEncPlane* sc = rad_enc_plane(&e, "scale");
|
||||
return e.plane[0].dtype == RAD_FP4E2M1 && e.plane[0].block[1] == 1 && sc &&
|
||||
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == RAD_MX_GROUP;
|
||||
}
|
||||
|
||||
inline int LinearFP8::probe(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src) {
|
||||
if (src.size() == 0) return RAD_E_INVAL;
|
||||
@@ -831,6 +937,67 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* ---- AN OCP-MXFP4 WEIGHT over the E4M3 pair. Three views of one stored weight: the codes,
|
||||
* the exponent plane as `b_scale`, and the same plane again as `b_ref`. Every view takes the
|
||||
* weight's row parts as they are -- the exponent grid is one row tall -- and a column slice in
|
||||
* whole 128s, which is the ACTIVATION's scale block and so the stricter of the two. */
|
||||
mx = known && linear_is_mxfp4(enc);
|
||||
if (mx) {
|
||||
if (!a.q || !a.s) {
|
||||
fprintf(stderr, "radiance: '%s' is an MXFP4 weight read against its input's E4M3 "
|
||||
"pair, and its input has none\n", wn);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; an MXFP4 weight takes rows in "
|
||||
"16s and K in whole %d-column activation scale blocks.\n",
|
||||
base, (long long)N, (long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int64_t parts[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t p : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS) return RAD_E_INVAL;
|
||||
if (p % 16) {
|
||||
fprintf(stderr, "radiance: '%s' stacks a %lld-row part, which is not a whole "
|
||||
"number of 16-row MXFP4 tiles; it cannot be row-sharded.\n",
|
||||
base, (long long)p);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
parts[np++] = p;
|
||||
}
|
||||
const char* sn = nm.f("%s.scale", base);
|
||||
const char* rn = nm.f("%s.ref", base);
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN,
|
||||
shard, grp, parts, np);
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
wref = decl_view(b, rn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws || !wref) return RAD_E_INVAL;
|
||||
if (span_hi > 0) {
|
||||
const bool col = shard == RAD_SHARD_COL;
|
||||
if (col && (span_lo % RAD_FP8_BLOCK || span_hi % RAD_FP8_BLOCK)) {
|
||||
fprintf(stderr, "radiance: '%s' is sliced [%lld, %lld) on this rank, which cuts a "
|
||||
"%d-column activation scale block.\n", base, (long long)span_lo,
|
||||
(long long)span_hi, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t lo = col ? span_lo / RAD_MX_GROUP : span_lo;
|
||||
const int64_t hi = col ? span_hi / RAD_MX_GROUP : span_hi;
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, w, span_lo, span_hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, ws, lo, hi));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, wref, lo, hi));
|
||||
}
|
||||
const int64_t hi = max_rows > 0 ? max_rows : g.max_tok;
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, hi), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")),
|
||||
RAD_WEIGHTS(w, ws, wref)),
|
||||
{ a.q, a.s }, { y });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The one geometric precondition, checked here so it is reported once per weight with the
|
||||
* weight named rather than as a kernel miss with a band in it. These are PER-RANK extents, so
|
||||
* this is also the check that a tensor-parallel width does not cut a scale block in half. */
|
||||
@@ -868,6 +1035,7 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* bf16 release) declares the same two views; what makes the planes exist is rad-convert. */
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, wparts, np);
|
||||
ws_row_div = RAD_FP8_BLOCK;
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { fp8_blocks(N), fp8_blocks(K) },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, sparts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
@@ -928,6 +1096,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (mx) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
|
||||
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
|
||||
return;
|
||||
}
|
||||
if (op_m1 && rows <= mv_rows)
|
||||
RAD_ISSUE_N(c, op_m1, rows, brow_slice(a.x, r0, rows, K), RAD_NONE,
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
|
||||
@@ -292,6 +292,20 @@ static int64_t ngram_table_rows(int64_t base, int64_t heads, int64_t divisor) {
|
||||
return divisor > 1 ? ((total + divisor - 1) / divisor) * divisor : total;
|
||||
}
|
||||
|
||||
/* A RANK'S PLACE WHERE THE SHARED EXPERT'S BLOCKS DO NOT DIVIDE over the ranks, the first places
|
||||
* taking one block more. A plain expert is a routed expert's width in 64-wide tiles, which need
|
||||
* not divide either, and MoeFP8::declare hands its extra tiles to the first ranks by index; the
|
||||
* shared expert's extra blocks start at the rank after the last of those, so the two remainders
|
||||
* land on different ranks while there are ranks enough for both. The routed experts leave no
|
||||
* remainder to avoid: at two ranks the parity split and at four the four-class split give every
|
||||
* rank the same width of them. At four ranks and this family's 640 columns -- ten tiles, five
|
||||
* blocks -- ranks 0 and 1 take a tile more and rank 2 the block; at two the ten tiles divide and
|
||||
* the place is the rank. */
|
||||
static int64_t shared_place(int64_t n_ff_all, int world, int rank) {
|
||||
const int64_t first = (n_ff_all / 64) % world;
|
||||
return (rank - first + world) % world;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
@@ -304,7 +318,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
m.nm = Names(ctx->scope ? ctx->scope : "");
|
||||
Names& nm = m.nm;
|
||||
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
/* arch_splits_ff: the routed experts' width (640 = five fp8 blocks) is split by the plugin
|
||||
* below, by whole blocks and parity, at any world up to the block count -- three ranks included,
|
||||
* which 640 does not divide. geom_from must not refuse what the plugin then answers.
|
||||
* attn_world_ok: every attention block this plugin declares is rad_block_attn_gated_fp8.h's,
|
||||
* which serves the smaller attention world of a world the two KV heads do not divide. */
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16, /*arch_splits_ff=*/true,
|
||||
/*attn_world_ok=*/true));
|
||||
Geom& g = m.g;
|
||||
|
||||
/* Qwen4-Exp's norms are all `x_hat * (1 + w)` -- `Qwen3NextRMSNorm.forward` is
|
||||
@@ -389,15 +409,46 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)gc.conv_width);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
int s;
|
||||
if ((s = divide_or_fail(nk, g.world, "linear_num_key_heads", &gc.n_head_k)) < 0) return s;
|
||||
if ((s = divide_or_fail(nv, g.world, "linear_num_value_heads", &gc.n_head_v)) < 0) return s;
|
||||
/* THE HEADS SPLIT EVENLY WHEN THEY CAN, as before, and UNEVENLY WHEN THEY CANNOT: 16 K
|
||||
* heads over three ranks are 6, 5 and 5, each rank's V heads the same multiple of its K
|
||||
* heads (48 / 16 = 3 -> 18, 15, 15), declared as spans of the container's rows
|
||||
* (rad_block_gdn_fp8.h Config::k_first). Nothing is padded and every rank holds real
|
||||
* heads; the kernels take any head count. A V count that is not a multiple of the K count
|
||||
* cannot be grouped that way and is refused. */
|
||||
gc.n_head_k_all = nk;
|
||||
gc.n_head_v_all = nv;
|
||||
if (g.world > 1 && (nk % g.world != 0 || nv % g.world != 0)) {
|
||||
if (nv % nk != 0) {
|
||||
fprintf(stderr, "radiance: qwen4exp: %lld value heads over %lld key heads do not "
|
||||
"group, so an uneven split over %d ranks is not defined\n",
|
||||
(long long)nv, (long long)nk, g.world);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int64_t ratio = nv / nk, base = nk / g.world, rem = nk % g.world;
|
||||
/* The extra heads go to the ranks without attention first (rad_arch.h
|
||||
* remainder_place); with none, this is the rank's own place and the split as before. */
|
||||
const int64_t pl = remainder_place(g, g.rank, 0);
|
||||
gc.n_head_k = base + (pl < rem ? 1 : 0);
|
||||
gc.k_first = pl * base + (pl < rem ? pl : rem);
|
||||
gc.n_head_v = ratio * gc.n_head_k;
|
||||
gc.v_first = ratio * gc.k_first;
|
||||
fprintf(stderr, "radiance: qwen4exp: rank %d takes delta-net K heads [%lld, %lld) of "
|
||||
"%lld and V heads [%lld, %lld) of %lld\n", g.rank,
|
||||
(long long)gc.k_first, (long long)(gc.k_first + gc.n_head_k), (long long)nk,
|
||||
(long long)gc.v_first, (long long)(gc.v_first + gc.n_head_v), (long long)nv);
|
||||
} else {
|
||||
int s;
|
||||
if ((s = divide_or_fail(nk, g.world, "linear_num_key_heads", &gc.n_head_k)) < 0) return s;
|
||||
if ((s = divide_or_fail(nv, g.world, "linear_num_value_heads", &gc.n_head_v)) < 0) return s;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the routed feed-forward.
|
||||
*
|
||||
* n_ff is `moe_intermediate_size` and geom_from already divided it by world_size -- and that
|
||||
* division is exactly what the header's tensor-parallel section is about. */
|
||||
* n_ff is `moe_intermediate_size`: divided by world_size when the world divides it, and left
|
||||
* whole when it does not (geom_from's `arch_splits_ff`). Either way it is only the starting
|
||||
* point -- at more than one rank the split below decides the rank's width, by whole fp8
|
||||
* blocks and parity, which is what the header's tensor-parallel section is about. */
|
||||
{
|
||||
MoeFP8::Config& mc = m.moecfg;
|
||||
mc.n_expert = meta_int2(meta, "qwen4exp.expert_count", "num_experts", 0);
|
||||
@@ -406,8 +457,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
mc.n_ff_shared = meta_int2(meta, "qwen4exp.expert_shared_feed_forward_length",
|
||||
"shared_expert_intermediate_size", 0);
|
||||
/* THE SHARED ARM IS SPLIT BY WHOLE fp8 SCALE BLOCKS: evenly when its width halves into
|
||||
* them, and otherwise as evenly as whole blocks allow -- this family's 640 columns are
|
||||
* five blocks, three on rank 0 and two on rank 1. See MoeFP8::Config::shared_lo. */
|
||||
* them, and otherwise as evenly as whole blocks allow, cut by the rank's place
|
||||
* (shared_place) -- this family's 640 columns are five blocks, three on rank 0 and two on
|
||||
* rank 1; at four ranks two on rank 2 and one on each of the others. See
|
||||
* MoeFP8::Config::shared_lo. */
|
||||
if (mc.n_ff_shared > 0 && g.world > 1 && (mc.n_ff_shared / g.world) % RAD_FP8_BLOCK == 0) {
|
||||
int s;
|
||||
if ((s = divide_or_fail(mc.n_ff_shared, g.world,
|
||||
@@ -423,8 +476,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
const int64_t nb = mc.n_ff_shared / RAD_FP8_BLOCK;
|
||||
const int64_t base = nb / g.world, extra = nb % g.world;
|
||||
const int64_t b0 = (int64_t)g.rank * base + std::min<int64_t>(g.rank, extra);
|
||||
const int64_t b1 = b0 + base + ((int64_t)g.rank < extra ? 1 : 0);
|
||||
const int64_t place = shared_place(g.n_ff_all, g.world, g.rank);
|
||||
const int64_t b0 = place * base + std::min<int64_t>(place, extra);
|
||||
const int64_t b1 = b0 + base + (place < extra ? 1 : 0);
|
||||
mc.shared_lo = b0 * RAD_FP8_BLOCK;
|
||||
mc.shared_hi = b1 * RAD_FP8_BLOCK;
|
||||
mc.n_ff_shared = mc.shared_hi - mc.shared_lo;
|
||||
@@ -483,22 +537,33 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
*
|
||||
* An expert of this model is 640 columns, five 128-column blocks -- the fp8 scale block,
|
||||
* the 4-bit plane's scale group and the rotation's width all at once -- so two ranks
|
||||
* cannot halve one. Each rank takes three blocks of the experts of one parity and two of
|
||||
* the other's: rank r's slice of expert e is the first three blocks when e % 2 == r and
|
||||
* the last two otherwise (MoeFP8::Config::ff_lo says why by parity). The router stays
|
||||
* cannot halve one.
|
||||
*
|
||||
* THE SPLIT IS BY PARITY: each parity's five blocks are cut contiguously over the ranks,
|
||||
* and the rank that takes the extra block alternates with the expert's parity
|
||||
* (MoeFP8::Config::ff_lo says why by parity). At two ranks, rank r's slice of expert e is
|
||||
* the first three blocks when e % 2 == r and the last two otherwise. The router stays
|
||||
* replicated, every rank computes its slice of every routed expert, and the block's
|
||||
* all-reduce sums the partials.
|
||||
*
|
||||
* AT FOUR RANKS PARITY IS NOT ENOUGH. It gives the extra block only two places to go, so
|
||||
* ranks 0 and 1 would compute three blocks of every even/odd pair of experts and ranks 2
|
||||
* and 3 two, and the all-reduce would have ranks 2 and 3 wait for the other two. So at four
|
||||
* the extra block is rotated over four places, by the expert's number mod 4: four slice
|
||||
* tables (`moe_gemm_q_mod4`), and every rank computes five blocks of every four experts.
|
||||
* A layer keeping two experts plain bf16 has 510 quantised ones, and its first two classes
|
||||
* are one expert longer. What does not divide elsewhere stays apart: the plain experts'
|
||||
* extra tiles are ranks 0 and 1's (MoeFP8::declare) and the shared expert's extra block
|
||||
* rank 2's (shared_place).
|
||||
*
|
||||
* WHY NOT EXPERT PARALLELISM, which splits the EXPERTS: rank r owns [r*E/W, (r+1)*E/W)
|
||||
* whole. The bytes a rank reads are the same on average either way, but which rank a
|
||||
* routed expert lands on is a coin flip, and a verify step's forty routed slots leave one
|
||||
* rank about five experts ahead -- which the all-reduce turns into the other rank waiting,
|
||||
* rank about five experts ahead -- which the all-reduce turns into the other ranks waiting,
|
||||
* about a millisecond a step at one sequence. Split by parity the ranks differ by a fifth
|
||||
* of an expert per unit of the even/odd difference instead.
|
||||
*
|
||||
* A width that divides into whole blocks at the rank count is split evenly and has one
|
||||
* slice; five blocks at more than two ranks would need more slices than two parities, and
|
||||
* is refused by name.
|
||||
* of an expert per unit of the even/odd difference instead. Whole experts would also break
|
||||
* the protected experts' pairing: the recipe protects them in pairs so each rank's count of
|
||||
* quantised experts stays even, which the two parity tables need.
|
||||
*
|
||||
* A CALIBRATION RUN SPLITS THE EXPERTS INSTEAD, whole experts per rank. The down
|
||||
* projection's Hessian is over an expert's whole K, and a rank holding a slice of each
|
||||
@@ -532,29 +597,70 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const int64_t nb = g.n_ff_all / RAD_FP8_BLOCK;
|
||||
if (nb % g.world == 0) {
|
||||
mc.n_ff_exp = g.n_ff_all / g.world;
|
||||
} else if (g.world == 2) {
|
||||
const int64_t base = nb / 2, extra = nb % 2;
|
||||
} else if (g.world <= nb) {
|
||||
/* The uneven split is TWO SLICES, not two RANKS: each parity's blocks are cut
|
||||
* contiguously across the ranks and the rank taking the odd block alternates with
|
||||
* the parity, so every rank's slices are whole blocks and every block of every
|
||||
* expert has exactly one owner. At two ranks this is the split the tree has always
|
||||
* made, byte for byte; at four it gives widths of ceil(nb/W) and floor(nb/W).
|
||||
* A rank must come away with at least one block of each parity -- an empty slice
|
||||
* is a rank that computes nothing and still joins the all-reduce -- which needs
|
||||
* the ranks to fit inside the two parities' blocks together. */
|
||||
const int64_t base = nb / g.world, extra = nb % g.world;
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
/* This rank's place in expert parity q's split: first for its own parity. */
|
||||
const int64_t p = (g.rank - q + 2) % 2;
|
||||
/* This rank's place in expert parity q's split: first for its own parity.
|
||||
* THE EXPERTS DO NOT GO REMAINDER-FIRST (rad_arch.h remainder_place): an
|
||||
* expert block is a whole GEMM of every routed token, and a rank taking the
|
||||
* extra block of every class became the step's slowest rank -- measured at
|
||||
* three ranks, Flash-Next: 50/25/25 cost 25% a step single-stream, and even
|
||||
* one class's extra block (37/25/37) swung 16-19 ms between boots. The delta
|
||||
* net's remainder is a head's worth of work and goes to the rank without
|
||||
* attention; the experts stay on the rotation every world has always had. */
|
||||
const int64_t p = (g.rank - q + g.world) % g.world;
|
||||
const int64_t b0 = p * base + std::min<int64_t>(p, extra);
|
||||
const int64_t b1 = b0 + base + (p < extra ? 1 : 0);
|
||||
mc.ff_lo[q] = b0 * RAD_FP8_BLOCK;
|
||||
mc.ff_hi[q] = b1 * RAD_FP8_BLOCK;
|
||||
}
|
||||
mc.n_ff_exp = std::max(mc.ff_hi[0] - mc.ff_lo[0], mc.ff_hi[1] - mc.ff_lo[1]);
|
||||
rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each even "
|
||||
"expert and [%lld, %lld) of each odd one, of %lld. The width is %lld "
|
||||
"blocks of %d, which two ranks split unevenly, so the rank taking the "
|
||||
"extra block alternates with the expert's parity; the block's "
|
||||
"all-reduce sums the partials.",
|
||||
g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0],
|
||||
(long long)mc.ff_lo[1], (long long)mc.ff_hi[1], (long long)g.n_ff_all,
|
||||
(long long)nb, RAD_FP8_BLOCK);
|
||||
/* AND AT FOUR RANKS FOUR CLASSES, by the expert's number mod 4 (MoeFP8::Config::
|
||||
* ff_lo4), which every layer then takes instead: the same cut with the rank's place
|
||||
* shifted by the class, so the extra block goes round all four ranks instead of
|
||||
* two. Every block of every expert still has one owner, and each slice is one a
|
||||
* rank already takes of some parity. */
|
||||
if (g.world == 4) {
|
||||
for (int q = 0; q < 4; ++q) {
|
||||
const int64_t p = (g.rank - q + 4) % 4;
|
||||
const int64_t b0 = p * base + std::min<int64_t>(p, extra);
|
||||
const int64_t b1 = b0 + base + (p < extra ? 1 : 0);
|
||||
mc.ff_lo4[q] = b0 * RAD_FP8_BLOCK;
|
||||
mc.ff_hi4[q] = b1 * RAD_FP8_BLOCK;
|
||||
mc.n_ff_exp = std::max(mc.n_ff_exp, mc.ff_hi4[q] - mc.ff_lo4[q]);
|
||||
}
|
||||
rad_note(b, "routed experts at four classes: rank %d computes columns [%lld, "
|
||||
"%lld) [%lld, %lld) [%lld, %lld) [%lld, %lld) of the experts of "
|
||||
"number 0, 1, 2 and 3 mod 4 -- %lld blocks of every four experts, "
|
||||
"as every rank does.",
|
||||
g.rank, (long long)mc.ff_lo4[0], (long long)mc.ff_hi4[0],
|
||||
(long long)mc.ff_lo4[1], (long long)mc.ff_hi4[1],
|
||||
(long long)mc.ff_lo4[2], (long long)mc.ff_hi4[2],
|
||||
(long long)mc.ff_lo4[3], (long long)mc.ff_hi4[3], (long long)nb);
|
||||
} else {
|
||||
rad_note(b, "routed experts: rank %d computes columns [%lld, %lld) of each "
|
||||
"even expert and [%lld, %lld) of each odd one, of %lld. The width "
|
||||
"is %lld blocks of %d, which %lld ranks split unevenly, so the rank "
|
||||
"taking the extra block alternates with the expert's parity; the "
|
||||
"block's all-reduce sums the partials.",
|
||||
g.rank, (long long)mc.ff_lo[0], (long long)mc.ff_hi[0],
|
||||
(long long)mc.ff_lo[1], (long long)mc.ff_hi[1],
|
||||
(long long)g.n_ff_all, (long long)nb, RAD_FP8_BLOCK,
|
||||
(long long)g.world);
|
||||
}
|
||||
} else {
|
||||
fprintf(stderr, "radiance: qwen4exp: an expert is %lld blocks of %d, which %d ranks "
|
||||
"cannot split into two slices; the uneven split alternates by "
|
||||
"parity and so serves two ranks.\n",
|
||||
"cannot each take a whole block of in both parities. Lower the rank "
|
||||
"count, or serve whole experts (a bf16 container or a calibration "
|
||||
"run does).\n",
|
||||
(long long)nb, RAD_FP8_BLOCK, g.world);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -852,6 +958,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
if (!m.w_tok || !m.w_lm_head) return RAD_E_INVAL;
|
||||
/* THE RANK'S ROWS, STATED: a vocabulary that does not divide by the world (248320 at three
|
||||
* ranks) is split by rad_arch.h's rule -- ceil to a 128-row block, last rank short -- and that
|
||||
* is a span, not the even share the core would otherwise cut. Harmless where it does divide
|
||||
* (the span IS the even share). */
|
||||
if (g.world > 1) {
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.w_tok, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
RAD_ARCH_TRY(rad_weight_shard_span(b, m.w_lm_head, g.vocab_off, g.vocab_off + g.n_vocab));
|
||||
}
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", g.n_embd),
|
||||
@@ -1029,6 +1143,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
lay.attn.qsa_exact_to = m.qsacfg.budget + m.qsacfg.ratio - 1;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full));
|
||||
/* AN ATTENTION-ZERO RANK KEEPS NO ATTENTION CACHE. Its block is a fill of zeros
|
||||
* (rad_block_attn_gated_fp8.h) and never stores or reads a key; the indexer below
|
||||
* reads only the group's block table, which every rank shares. Once per model: the
|
||||
* group is one and the call is idempotent, but the first layer is the honest place. */
|
||||
if (g.attn_zero && m.kv_full) RAD_ARCH_TRY(rad_kv_group_zero(b, m.kv_full));
|
||||
lay.attn.ar_out_take = lay.hc_mix.ar_take();
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as,
|
||||
false, false, kArNone, lay.hc_mix.op_ar_write != 0));
|
||||
|
||||
@@ -149,6 +149,9 @@ public:
|
||||
int op_writes(rad_op h, const rad_buf* b, int n);
|
||||
int buf_concurrent(rad_buf b);
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
int kv_group_zero(rad_kvgroup g);
|
||||
|
||||
/* Finalise: weight first/last use, KV group geometry, buffer liveness and packing. Returns
|
||||
* RAD_OK, or the first structural error class. Resolution MISSES are not an error here -- an
|
||||
@@ -165,6 +168,14 @@ public:
|
||||
* laid over the real ones. */
|
||||
void set_reference(const Program* ref) { ref_ = ref; }
|
||||
|
||||
/* WITHOUT INSTANCES: finish() selects every kernel and initialises none. For a caller that
|
||||
* launches nothing -- rad-convert plans a container's stored form, which is the kernels'
|
||||
* layouts and not their setup. A kernel's init is about the process it runs in (a ring, a
|
||||
* peer's buffers) and the conversion is often not that process: libavx's n-gram gather
|
||||
* refuses a process that may not make an io_uring ring, and a sandbox that forbids one still
|
||||
* has to be able to convert the model. */
|
||||
void set_instances(bool on) { instances_ = on; }
|
||||
|
||||
Program& program() { return prog_; }
|
||||
const Program& program() const { return prog_; }
|
||||
|
||||
@@ -195,6 +206,7 @@ private:
|
||||
Registry& reg_;
|
||||
Program prog_;
|
||||
const Program* ref_ = nullptr;
|
||||
bool instances_ = true;
|
||||
|
||||
std::vector<std::string> errors_;
|
||||
int status_ = RAD_OK;
|
||||
|
||||
+96
-28
@@ -684,21 +684,28 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
|
||||
* A RAD_OPD_WTAB position consumes a RUN of declared weights, so the count alone does not
|
||||
* say how the list divides. The rule is EQUAL DIVISION: whatever is left after the fixed
|
||||
* weight positions have taken one each is split evenly across the table positions, in
|
||||
* declaration order. That is exactly right for the case tables exist for -- `moe_gemm_q`'s
|
||||
* codes and scale planes are one of each per expert, always the same count -- and a division
|
||||
* that does not come out whole is refused here rather than silently mis-grouped, which is the
|
||||
* only failure the rule can have. */
|
||||
int per_tab = 0;
|
||||
* declaration order. That is exactly right for the case tables exist for -- a grouped GEMM's
|
||||
* codes and scale planes are one of each per expert, always the same count.
|
||||
*
|
||||
* WHERE IT DOES NOT COME OUT WHOLE, THE FIRST POSITIONS TAKE ONE MORE. A grouped GEMM whose
|
||||
* n experts are C classes by number mod C, declared class by class as a codes table and a
|
||||
* scales table each, gives its first `n % C` classes one expert more than the rest -- exactly
|
||||
* the positions this rule lengthens. A list grouped any other way is refused at issue: the
|
||||
* plugin names each table's run there, and a run other than the one this division bound is
|
||||
* refused. A bound run must also be contiguous, checked when the tables are bound before the
|
||||
* first step, and its entries of one shape, checked at its first issue. A list shorter than
|
||||
* the tables is refused here. */
|
||||
int per_tab = 0, tab_extra = 0;
|
||||
if (n_tab > 0) {
|
||||
const int rest = n_w - w_max;
|
||||
if (rest <= 0 || rest % n_tab != 0) {
|
||||
if (rest < n_tab) {
|
||||
err(RAD_E_SCHEMA,
|
||||
"op '%s': %d weight operands declared; the schema has %d fixed weight operands and "
|
||||
"%d weight TABLE operands, so %d must divide evenly among the tables and it does "
|
||||
"not. A table takes one weight per expert and every table of one op takes the same "
|
||||
"number", opname, n_w, w_max, n_tab, rest);
|
||||
"%d weight TABLE operands, so %d leaves a table empty. A table takes one weight "
|
||||
"per expert", opname, n_w, w_max, n_tab, rest);
|
||||
} else {
|
||||
per_tab = rest / n_tab;
|
||||
tab_extra = rest % n_tab;
|
||||
}
|
||||
} else if (n_w < w_req || n_w > w_max) {
|
||||
err(RAD_E_SCHEMA, "op '%s': %d weight operands declared, but the schema has %d (%d "
|
||||
@@ -727,14 +734,16 @@ rad_op Builder::decl_op(const char* opname, const RadParam* p, int n_p,
|
||||
oi.weights.assign(w, w + n_w);
|
||||
/* The many-to-one map from declared weight to schema operand position, built here so the
|
||||
* layout pass, the converter and the issue path all read one answer. A fixed weight position
|
||||
* takes one; a table position takes `per_tab` in a row. */
|
||||
* takes one; a table position takes `per_tab` in a row, and the first `tab_extra` of them one
|
||||
* more. */
|
||||
oi.weight_opd.assign((size_t)n_w, -1);
|
||||
{
|
||||
int wi = 0;
|
||||
int wi = 0, ti = 0;
|
||||
for (int k = 0; sc->operands && k < sc->n_operands && wi < n_w; ++k) {
|
||||
const int role = sc->operands[k].role;
|
||||
if (role == RAD_OPD_WTAB) {
|
||||
for (int j = 0; j < per_tab && wi < n_w; ++j) oi.weight_opd[(size_t)wi++] = k;
|
||||
const int run = per_tab + (ti++ < tab_extra ? 1 : 0);
|
||||
for (int j = 0; j < run && wi < n_w; ++j) oi.weight_opd[(size_t)wi++] = k;
|
||||
} else if (role == RAD_OPD_WEIGHT) {
|
||||
oi.weight_opd[(size_t)wi++] = k;
|
||||
}
|
||||
@@ -883,6 +892,58 @@ int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::weight_shard_span_parts(rad_weight h, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n) {
|
||||
if (finished_) { err(RAD_E_STATE, "weight_shard_span_parts after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.weights.size() || !lo || !hi || !total) return RAD_E_INVAL;
|
||||
WeightInfo& w = prog_.weights[h];
|
||||
const RadWeightDecl& d = w.decl;
|
||||
if (d.shard != RAD_SHARD_ROW || d.n_row_parts < 2 || n != d.n_row_parts) {
|
||||
err(RAD_E_INVAL, "weight '%s': per-part spans need a row-sharded weight of %d stacked "
|
||||
"parts, and %d span(s) were given", w.name.c_str(), d.n_row_parts, n);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int g = 0; g < n; ++g) {
|
||||
if (lo[g] < 0 || hi[g] <= lo[g] || hi[g] > total[g]) {
|
||||
err(RAD_E_INVAL, "weight '%s': part %d span [%lld, %lld) is empty or outside its "
|
||||
"%lld rows", w.name.c_str(), g, (long long)lo[g], (long long)hi[g],
|
||||
(long long)total[g]);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d.row_parts[g] != hi[g] - lo[g]) {
|
||||
err(RAD_E_SHAPE, "weight '%s': part %d span [%lld, %lld) is %lld wide and the "
|
||||
"declared part is %lld", w.name.c_str(), g, (long long)lo[g],
|
||||
(long long)hi[g], (long long)(hi[g] - lo[g]), (long long)d.row_parts[g]);
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
w.part_lo[g] = lo[g];
|
||||
w.part_hi[g] = hi[g];
|
||||
w.part_total[g] = total[g];
|
||||
}
|
||||
w.n_part_spans = n;
|
||||
w.shard_lo = 0;
|
||||
w.shard_hi = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
if (finished_) { err(RAD_E_STATE, "kv_group_zero after declare finished"); return RAD_E_STATE; }
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
/* PAGED GROUPS ONLY. A zero group is one whose rank computes nothing that reads or writes it,
|
||||
* and a paged group's absence is invisible to the others: they index the shared block table
|
||||
* and this rank has no shard to index. A linear or conv group carries per-sequence state the
|
||||
* snapshot store saves and the step clears on every rank, and a zero-sized one would make
|
||||
* each of those copies a size mismatch. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
|
||||
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
|
||||
prog_.kv_groups[h].name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.kv_groups[h].zero = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== name map */
|
||||
int Builder::decl_name_map(const RadNameMap* m) {
|
||||
if (finished_) { err(RAD_E_STATE, "decl_name_map after declare finished"); return RAD_E_STATE; }
|
||||
@@ -1373,22 +1434,18 @@ void Builder::finish_kv_groups() {
|
||||
* (d.state_dim[1] ? d.state_dim[1] : 1)) * n_bound;
|
||||
break;
|
||||
case RAD_KV_CONV: {
|
||||
/* A rolling window of conv_width-1 + n_spec + 1 entries, so a speculative
|
||||
* rejection is a change of read offset rather than a recompute (spec §10). The
|
||||
* window is sized for the largest speculative window this deployment was
|
||||
* configured for.
|
||||
/* A rolling window of conv_width-1 + n_spec entries, so a speculative rejection
|
||||
* is a change of read offset rather than a recompute (spec §10). The window is
|
||||
* sized for the largest speculative window this deployment was configured for.
|
||||
*
|
||||
* THE +1 IS THE VERIFY STEP'S OWN OUTPUT, and it is not optional. A verify writes
|
||||
* 1 + n_spec conv outputs before anyone knows which survive, so peak occupancy is
|
||||
* the conv_width-1 of retained history PLUS all 1 + n_spec of them. Sizing this
|
||||
* `conv_width - 1 + max_spec` instead -- six entries at width 4 depth 3 -- puts it
|
||||
* one short of the modulus BatchBuilder::init and Scheduler::conv_window cycle
|
||||
* `conv_cursor` by, which is `conv_width - 1 + n_spec + 1`, seven: `(cursor + 1 +
|
||||
* a) % 7` reaches 6, one past the end of the allocation and into the slot that
|
||||
* belongs to the next sequence. At n_spec 0 the two agree (modulus conv_width,
|
||||
* history conv_width-1 plus the one output), so the discrepancy hides there. */
|
||||
int64_t entries = (d.conv_width > 0 ? d.conv_width - 1 : 0) +
|
||||
(prog_.ctx.max_spec > 0 ? prog_.ctx.max_spec : 0) + 1;
|
||||
* EXACTLY THE STATE TENSOR'S EXTENT, conv_window_entries(), and not one more. The
|
||||
* kernels lay the slots out from the tensor, so an allocation one entry wider a
|
||||
* slot puts the manager's slot `s` -- the bytes it clears when it hands the slot
|
||||
* out, and saves and restores at a checkpoint -- over the start of the kernels'
|
||||
* slot `s + 1`. Handing a slot to a new sequence then zeroes part of a running
|
||||
* sequence's window. conv_state_index's cursor cycles by the same number, so it
|
||||
* stays inside the slot. */
|
||||
int64_t entries = conv_window_entries(d, prog_.ctx.max_spec);
|
||||
if (entries <= 0) entries = 1;
|
||||
gi.bytes_per_block = 0;
|
||||
gi.bytes_per_state =
|
||||
@@ -1498,7 +1555,7 @@ int Builder::finish() {
|
||||
w.source.c_str(), rad_dtype_name(w.decl.dtype));
|
||||
}
|
||||
|
||||
finish_instances();
|
||||
if (instances_) finish_instances();
|
||||
finish_weight_uses();
|
||||
finish_layouts();
|
||||
finish_kv_groups();
|
||||
@@ -1610,6 +1667,17 @@ int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) {
|
||||
return B(b)->weight_shard_span(w, lo, hi);
|
||||
}
|
||||
|
||||
int rad_weight_shard_span_parts(RadBuilder* b, rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_shard_span_parts(w, lo, hi, total, n);
|
||||
}
|
||||
|
||||
int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->kv_group_zero(g);
|
||||
}
|
||||
|
||||
int rad_decl_name_map(RadBuilder* b, const RadNameMap* m) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->decl_name_map(m);
|
||||
|
||||
@@ -319,7 +319,7 @@ std::vector<std::string> CheckpointSources::refused() const {
|
||||
|
||||
int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const RadBuildCtx& ctx,
|
||||
Program* out, const std::function<int(RadBuilder*, int64_t)>& also,
|
||||
const Program* ref, const WeightSourceFn& sources) {
|
||||
const Program* ref, const WeightSourceFn& sources, bool instances) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
|
||||
Registry& r = rad_tools_registry();
|
||||
@@ -334,6 +334,7 @@ int rad_tools_declare(const LoadedPlugins& lp, const RadModelMeta& meta, const R
|
||||
Builder b(r, meta, ctx);
|
||||
if (ref) b.set_reference(ref);
|
||||
if (sources) b.set_sources(sources);
|
||||
b.set_instances(instances);
|
||||
|
||||
int s = ap->arch_declare(&b, &meta, &ctx);
|
||||
if (s < 0) {
|
||||
|
||||
@@ -88,10 +88,13 @@ const RadChatFormat* rad_tools_chat_format(const LoadedPlugins& plugins, const R
|
||||
* or initialised. The Program that comes back is for its buffers and nothing else. */
|
||||
/* `sources` answers rad_weight_encoding (Builder::set_sources): a container's entries, a
|
||||
* checkpoint's tensors, or a recipe. Empty, every weight is read as plain in its declared dtype. */
|
||||
/* `instances` false selects every kernel and initialises none (Builder::set_instances): for a
|
||||
* caller that launches nothing, such as rad-convert planning a container's stored form. */
|
||||
int rad_tools_declare(const LoadedPlugins& plugins, const RadModelMeta& meta,
|
||||
const RadBuildCtx& ctx, Program* out,
|
||||
const std::function<int(RadBuilder*, int64_t logits_width)>& also = {},
|
||||
const Program* ref = nullptr, const WeightSourceFn& sources = {});
|
||||
const Program* ref = nullptr, const WeightSourceFn& sources = {},
|
||||
bool instances = true);
|
||||
|
||||
/* A container's entries as the source of every declaration's encoding. `f` must outlive the
|
||||
* declare. */
|
||||
|
||||
+57
-22
@@ -35,26 +35,34 @@ static const Flag g_flags[] = {
|
||||
{ "--kernels", "LIST", "kernel plugin hierarchy, comma-separated, first wins" },
|
||||
|
||||
{ "--tp", "N", "tensor-parallel ranks" },
|
||||
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the wht6 wire is used for" },
|
||||
{ "--tp-wire", "MODE", "cross-rank all-reduce payload: exact (default) or wht6, a\n"
|
||||
"lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 4,\n"
|
||||
"none at 8" },
|
||||
{ "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" },
|
||||
{ "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n"
|
||||
"asks the driver, on requires peer access and stops without\n"
|
||||
"it, off exchanges through pinned host memory" },
|
||||
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
|
||||
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
|
||||
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
|
||||
|
||||
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
|
||||
/* THE FLAG THAT DECIDES WHETHER MULTI-TURN WORKS, which is more than the split it names.
|
||||
* The KV side is not just concurrency: prefix caching holds a finished sequence's blocks
|
||||
* so the next turn can reuse them, so when the pool cannot hold the LIVE SESSIONS the
|
||||
* cache drops prefixes the next turn wanted and that turn re-prefills its whole context.
|
||||
* At long contexts that is two orders of magnitude of time-to-first-token, bought back for
|
||||
* a fraction of a percent of the decode step. See core/mem/prefix.h. */
|
||||
{ "--expert-vs-cache-ratio", "R", "weights vs KV split of what is claimed (default "
|
||||
"0.75). The KV side also holds cached prefixes, so "
|
||||
"too little of it makes every agent turn re-prefill" },
|
||||
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
|
||||
{ "--vram-kv-mib", "N", "the paged KV pool; 0 derives it from the card" },
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 -- fp8 halves what a token of context costs" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--embedding-placement", "WHERE", "auto (default) | vram | ram: where the token embedding lives. ram\n"
|
||||
" keeps it in the pinned host pool, read over the link in place;\n"
|
||||
" auto keeps it on the card unless the KV cache could then not\n"
|
||||
" hold one --max-model-len sequence. disk is refused: the lookup\n"
|
||||
" writes the card's activations, which no host read can reach" },
|
||||
{ "--ngram-placement", "WHERE", "auto (default) | vram | ram | disk: where an n-gram\n"
|
||||
" embedding table lives (Qwen3.8-Flash-Next: 47.7 GiB).\n"
|
||||
" vram puts all of it on every card; ram copies it into\n"
|
||||
" host memory at load, pinned for the cards to read\n"
|
||||
" (locked, where only a host kernel reads it); disk reads\n"
|
||||
" its rows from the container on the host. auto takes the\n"
|
||||
" first of the three that holds it" },
|
||||
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
|
||||
" container on disk (O_DIRECT); a routed expert is read a layer\n"
|
||||
" at a time, so a step is paced by the drive" },
|
||||
@@ -75,13 +83,14 @@ static const Flag g_flags[] = {
|
||||
" this does NOT make the engine bit-reproducible across\n"
|
||||
" batch positions -- see spec §19" },
|
||||
{ "--checkpoint-interval","N", "linear-attention state checkpoint interval, in tokens" },
|
||||
/* TOTAL, NOT PER SEQUENCE. `ck_free_` is one global free list of N slots handed out by
|
||||
* pop_back (core/mem/kv.cpp), so an operator reading "per sequence" and setting 2 gets
|
||||
/* TOTAL, NOT PER SEQUENCE. The snapshot store is one pool of N slots for the whole server
|
||||
* (KVManager::set_checkpoint_store), so an operator reading "per sequence" and setting 2 gets
|
||||
* 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and
|
||||
* 8 sequences that is one snapshot a sequence, which is what an append-only chat wants --
|
||||
* the next turn's hit lands at the end of the last one. */
|
||||
{ "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not "
|
||||
"per sequence); compare against --max-num-seqs" },
|
||||
"per sequence), in pinned host memory; compare "
|
||||
"against --max-num-seqs" },
|
||||
{ "--no-prefix-cache", nullptr, "disable prefix caching" },
|
||||
{ "--checkpoint-policy", "NAME", "which snapshots a session retains: geometric-backoff "
|
||||
"(default), tip-only, keep-all" },
|
||||
@@ -114,6 +123,10 @@ static const Flag g_flags[] = {
|
||||
" set is the template's: Qwen3.8 takes xhigh|medium|low and defaults\n"
|
||||
" to xhigh, which on a short task can spend the whole token budget\n"
|
||||
" inside <think> and answer nothing. \"none\" turns thinking off" },
|
||||
{ "--thinking-token-budget", "N", "default `thinking_token_budget` for chat requests that do not set one: at\n"
|
||||
" N reasoning tokens the reasoning block is closed and the answer follows,\n"
|
||||
" so a client's max_tokens is not spent on reasoning alone. Unset is no\n"
|
||||
" limit. Needs a reasoning block that ends in one token, as </think> is" },
|
||||
{ "--typical-p", "F", "default typical_p, (0, 1]. This flag and the eleven below set the default\n"
|
||||
" for requests that do not name the field; a request that names it wins" },
|
||||
{ "--presence-penalty", "F", "default presence_penalty, [-2, 2]" },
|
||||
@@ -127,7 +140,7 @@ static const Flag g_flags[] = {
|
||||
{ "--dry-sequence-breakers", "JSON", "default dry_sequence_breakers, a JSON array of at most 16 strings" },
|
||||
{ "--xtc-probability", "F", "default xtc_probability, [0, 1]" },
|
||||
{ "--xtc-threshold", "F", "default xtc_threshold, [0, 1]" },
|
||||
{ "--default-max-tokens", "N", "max_tokens for requests that do not set one (default 512). `auto` is\n"
|
||||
{ "--default-max-tokens", "N", "max_tokens for requests that do not set one: N, or `auto` (default),\n"
|
||||
" whatever the context leaves after the prompt" },
|
||||
{ "--max-tokens-cap", "N", "the most any request may generate. A larger max_tokens is cut to it rather\n"
|
||||
" than refused, and the reply ends with finish_reason \"length\". 0 is none\n"
|
||||
@@ -204,6 +217,17 @@ void config_usage(const char* argv0) {
|
||||
"benchmarks do not reproduce.\n");
|
||||
}
|
||||
|
||||
/* The four names exactly, lower case: what a table's placement costs is the operator's to state,
|
||||
* so a spelling this build does not know stops the server rather than picking a tier. */
|
||||
static bool parse_table_placement(const char* v, TablePlacement* out) {
|
||||
if (!std::strcmp(v, "auto")) *out = TablePlacement::Auto;
|
||||
else if (!std::strcmp(v, "vram")) *out = TablePlacement::Vram;
|
||||
else if (!std::strcmp(v, "ram")) *out = TablePlacement::Ram;
|
||||
else if (!std::strcmp(v, "disk")) *out = TablePlacement::Disk;
|
||||
else return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
static std::vector<std::string> split_commas(const std::string& s) {
|
||||
std::vector<std::string> out;
|
||||
size_t i = 0;
|
||||
@@ -341,6 +365,13 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
|
||||
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--p2p")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
|
||||
else if (!std::strcmp(v, "on")) c->p2p = RAD_P2P_ON;
|
||||
else if (!std::strcmp(v, "off")) c->p2p = RAD_P2P_OFF;
|
||||
else { RAD_ERR("--p2p takes auto, on or off, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--tp-wire-min-kb")) { if (!(v = need(i))) return RAD_E_INVAL; c->tp_wire_min_kb = atoll(v); }
|
||||
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
|
||||
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
|
||||
@@ -360,17 +391,17 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
}
|
||||
else if (S("--expert-vs-cache-ratio")) {
|
||||
else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->expert_cache_ratio = atof(v);
|
||||
if (!(c->expert_cache_ratio > 0.0 && c->expert_cache_ratio < 1.0)) {
|
||||
RAD_ERR("--expert-vs-cache-ratio is the WEIGHTS share of what is claimed and must "
|
||||
"be strictly between 0 and 1, not '%s'. 0.75 gives three quarters to "
|
||||
"weights and a quarter to the KV cache.", v);
|
||||
TablePlacement p;
|
||||
if (!parse_table_placement(v, &p)) {
|
||||
RAD_ERR("%s takes auto, vram, ram or disk, not '%s'", a.c_str(), v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
(emb ? c->embedding_placement : c->ngram_placement) = p;
|
||||
}
|
||||
else if (S("--host-pool-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->host_pool_mib = atoll(v); }
|
||||
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
|
||||
else if (S("--prefix-cache-host-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_host_mib = atoll(v); }
|
||||
else if (S("--prefix-cache-dir")) { if (!(v = need(i))) return RAD_E_INVAL; c->prefix_cache_dir = v; }
|
||||
@@ -449,6 +480,10 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
else if (S("--reasoning-effort")) { if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->reasoning_effort = v; }
|
||||
else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
|
||||
!parse_int(a.c_str(), v, 0, INT32_MAX,
|
||||
&c->thinking_token_budget))
|
||||
return RAD_E_INVAL; }
|
||||
else if (S("--generation-config")) { if (!(v = need(i))) return RAD_E_INVAL;
|
||||
c->generation_config = v; }
|
||||
else if (S("--override-chat-template")) { if (!(v = need(i))) return RAD_E_INVAL;
|
||||
|
||||
+378
-2
@@ -35,15 +35,20 @@
|
||||
|
||||
/* The standard headers first: HIP's defines __noinline__, which <format> (reached through
|
||||
* <chrono>) uses as an attribute name. */
|
||||
#include <dirent.h>
|
||||
#include <dlfcn.h>
|
||||
#include <immintrin.h>
|
||||
#include <fcntl.h>
|
||||
#include <sys/ioctl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <linux/kfd_ioctl.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cctype>
|
||||
#include <cerrno>
|
||||
#include <chrono>
|
||||
#include <cinttypes>
|
||||
@@ -52,6 +57,7 @@
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <string>
|
||||
@@ -207,6 +213,7 @@ struct Dev {
|
||||
std::vector<std::string> isas; /* the targets it accepts, preferred first; see agent_isas */
|
||||
hsa_amd_memory_pool_t vram{};
|
||||
bool has_vram = false;
|
||||
uint32_t kfd_id = 0; /* the driver's gpu_id: its sysfs and ioctls name it so */
|
||||
};
|
||||
|
||||
struct Global {
|
||||
@@ -349,6 +356,8 @@ bool init_devices() {
|
||||
g.dev[(size_t)i].agent = a;
|
||||
g.dev[(size_t)i].isa = agent_isa(a);
|
||||
g.dev[(size_t)i].isas = agent_isas(a);
|
||||
hsa_agent_get_info(a, (hsa_agent_info_t)HSA_AMD_AGENT_INFO_DRIVER_UID,
|
||||
&g.dev[(size_t)i].kfd_id);
|
||||
hsa_amd_agent_iterate_memory_pools(a, find_vram, &g.dev[(size_t)i]);
|
||||
found = true;
|
||||
break;
|
||||
@@ -1014,6 +1023,28 @@ void loc_keep(const void* host_base, size_t bytes, intptr_t shift, uint64_t owne
|
||||
h.gen = gen;
|
||||
}
|
||||
|
||||
/* The host ranges this backend pinned itself (see "pinned host memory, in pieces"), by base,
|
||||
* ordered so an inner address finds its range. `pool` is the host-pool allocation the range sits
|
||||
* in when it was not locked in pieces, and null when it was. */
|
||||
struct Pinned {
|
||||
int64_t len = 0;
|
||||
void* pool = nullptr;
|
||||
};
|
||||
std::mutex g_pinned_mu;
|
||||
std::map<uintptr_t, Pinned> g_pinned;
|
||||
|
||||
bool pinned_range(const void* p, uintptr_t* lo, int64_t* len) {
|
||||
const uintptr_t a = (uintptr_t)p;
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
auto it = g_pinned.upper_bound(a);
|
||||
if (it == g_pinned.begin()) return false;
|
||||
--it;
|
||||
if (a - it->first >= (uintptr_t)it->second.len) return false;
|
||||
if (lo) *lo = it->first;
|
||||
if (len) *len = it->second.len;
|
||||
return true;
|
||||
}
|
||||
|
||||
Loc locate(const void* p, const Stream* s, const void** gpu) {
|
||||
*gpu = p;
|
||||
const uintptr_t a = (uintptr_t)p;
|
||||
@@ -1024,6 +1055,15 @@ Loc locate(const void* p, const Stream* s, const void** gpu) {
|
||||
if (!h.owner) return kHost;
|
||||
return h.owner == s->agent.handle ? kDevLocal : kDevPeer;
|
||||
}
|
||||
/* PINNED HERE, ANSWERED HERE. hsa_amd_pointer_info reports memory locked with
|
||||
* hsa_amd_memory_lock_to_pool as UNKNOWN on this runtime -- indistinguishable from pageable --
|
||||
* although the lock mapped it on every card at its own address. */
|
||||
uintptr_t plo = 0;
|
||||
int64_t plen = 0;
|
||||
if (pinned_range(p, &plo, &plen)) {
|
||||
loc_keep((const void*)plo, (size_t)plen, 0, 0, gen);
|
||||
return kHost;
|
||||
}
|
||||
hsa_amd_pointer_info_t info{};
|
||||
info.size = sizeof info;
|
||||
if (hsa_amd_pointer_info(const_cast<void*>(p), &info, nullptr, nullptr, nullptr) !=
|
||||
@@ -1774,6 +1814,87 @@ int a_memset_async(void* dst, int value, int64_t bytes, RadStream rs) {
|
||||
return rc < 0 ? RAD_E_DEVICE : RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- VRAM: the room check.
|
||||
*
|
||||
* A VRAM ALLOCATION THE DRIVER REFUSES KILLS THE PROCESS IN THIS RUNTIME once a queue has been
|
||||
* destroyed. On a refusal ROCr releases its caches and asks again (GpuAgent::Trim), and the release
|
||||
* walks every queue the process created on the card. ROCm 7.2's runtime adds a queue to that list
|
||||
* (GpuAgent::aql_queues_, amd_gpu_agent.cpp) and never takes a destroyed one off it, so the walk
|
||||
* calls into freed memory and the process dies of SIGSEGV inside libhsa-runtime64.so instead of
|
||||
* being told no. Startup destroys queues before it allocates anything large -- the two it makes to
|
||||
* measure what a queue costs, and the loader's when a load ends -- so every refused device
|
||||
* allocation took that path: a card another process had taken memory from crashed startup in
|
||||
* hipMalloc rather than refusing its arena. ROCr's develop branch takes the queue off the list on
|
||||
* destroy; until a release carries that, every device allocation here is held to what the driver
|
||||
* will still give on the card and refused by this layer, naming what the card has and which
|
||||
* processes hold it, before the runtime is asked.
|
||||
*
|
||||
* The figure is the driver's own (AMDKFD_IOC_AVAILABLE_MEMORY), the one its allocation check
|
||||
* compares against, and the request is rounded up to 2 MiB so one the driver rounds up is not
|
||||
* passed by a hair. It is a check, not a reservation: memory another process takes between it and
|
||||
* the allocation still reaches the runtime. */
|
||||
|
||||
/* What the driver will still allocate on card `ord`, -1 when it will not say. */
|
||||
int64_t card_available(int ord) {
|
||||
if (ord < 0 || ord >= (int)G().dev.size() || G().kfd < 0) return -1;
|
||||
kfd_ioctl_get_available_memory_args a{};
|
||||
a.gpu_id = G().dev[(size_t)ord].kfd_id;
|
||||
if (!a.gpu_id || ioctl(G().kfd, AMDKFD_IOC_AVAILABLE_MEMORY, &a) < 0) return -1;
|
||||
return (int64_t)a.available;
|
||||
}
|
||||
|
||||
/* The processes holding VRAM on card `ord`, largest first, as the driver lists them: host process
|
||||
* ids, which inside a container are not this process's own numbering, so this process is named
|
||||
* only where the ids agree. */
|
||||
std::string card_holders(int ord) {
|
||||
const uint32_t id = G().dev[(size_t)ord].kfd_id;
|
||||
std::vector<std::pair<int64_t, long>> held;
|
||||
if (DIR* d = opendir("/sys/class/kfd/kfd/proc")) {
|
||||
while (dirent* e = readdir(d)) {
|
||||
char* end = nullptr;
|
||||
const long pid = std::strtol(e->d_name, &end, 10);
|
||||
if (end == e->d_name || *end) continue;
|
||||
char path[128];
|
||||
std::snprintf(path, sizeof path, "/sys/class/kfd/kfd/proc/%ld/vram_%u", pid, id);
|
||||
FILE* f = std::fopen(path, "r");
|
||||
if (!f) continue;
|
||||
long long v = 0;
|
||||
if (std::fscanf(f, "%lld", &v) == 1 && v > 0) held.push_back({ (int64_t)v, pid });
|
||||
std::fclose(f);
|
||||
}
|
||||
closedir(d);
|
||||
}
|
||||
if (held.empty()) return std::string();
|
||||
std::sort(held.begin(), held.end(), [](const auto& x, const auto& y) { return x.first > y.first; });
|
||||
std::string s = fmt(" %zu process(es) hold memory on it, by host process id:", held.size());
|
||||
bool self = false;
|
||||
for (size_t i = 0; i < held.size() && i < 8; ++i) {
|
||||
const bool me = held[i].second == (long)getpid();
|
||||
self = self || me;
|
||||
s += fmt("%s %ld %s%s", i ? "," : "", held[i].second, humanb(held[i].first).c_str(),
|
||||
me ? " (this process)" : "");
|
||||
}
|
||||
if (held.size() > 8) s += fmt(", and %zu more", held.size() - 8);
|
||||
if (!self) s += "; this process is one of them under the host's numbering";
|
||||
return s + ".";
|
||||
}
|
||||
|
||||
/* True when card `ord` can take `bytes` more; otherwise false with the refusal set, `what` naming
|
||||
* the call. A card whose figure the driver will not give is let through, as before this check. */
|
||||
bool card_has_room(int ord, int64_t bytes, const char* what) {
|
||||
const int64_t avail = card_available(ord);
|
||||
if (avail < 0) return true;
|
||||
constexpr int64_t kUnit = (int64_t)2 << 20;
|
||||
const int64_t need = (bytes + kUnit - 1) / kUnit * kUnit;
|
||||
if (need <= avail) return true;
|
||||
device_set_error("%s(%s) on card %d: the driver has %s left to give on it.%s Memory another "
|
||||
"process took after the VRAM budget was measured is the usual cause: stop "
|
||||
"that process, or start this one again once it has gone",
|
||||
what, humanb(bytes).c_str(), ord, humanb(avail).c_str(),
|
||||
card_holders(ord).c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
/* ---- elastic memory, through HSA.
|
||||
*
|
||||
* HIP's virtual-memory calls build HIP's own default-stream queue on the card the first time a
|
||||
@@ -1857,6 +1978,7 @@ int a_vmem_commit(void* addr, int64_t bytes) {
|
||||
if (dev < 0 && hipGetDevice(&dev) != hipSuccess) return RAD_E_DEVICE;
|
||||
if (dev < 0 || dev >= (int)G().dev.size()) return RAD_E_DEVICE;
|
||||
const Dev& d = G().dev[(size_t)dev];
|
||||
if (!card_has_room(dev, bytes, "vmem commit")) return RAD_E_NOMEM;
|
||||
hsa_amd_vmem_alloc_handle_t h{};
|
||||
if (hsa_amd_vmem_handle_create(d.vram, (size_t)bytes, MEMORY_TYPE_NONE, 0, &h) !=
|
||||
HSA_STATUS_SUCCESS) {
|
||||
@@ -1903,13 +2025,261 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* HIP's own free, behind the forgetting every free needs (locate's cache). */
|
||||
/* ------------------------------------------------------------------ pinned host memory, in pieces
|
||||
*
|
||||
* EVERY PINNED OR MAPPED HOST ALLOCATION IS ONE ADDRESS RANGE LOCKED AS PIECES OF AT MOST
|
||||
* kPinPiece, BECAUSE OF THE IOMMU. Host memory a card reaches is a userptr buffer object, which the
|
||||
* kernel DMA-maps for each card as one scatterlist. On an Intel VT-d host in scalable mode (Linux
|
||||
* 7.0, two R9700) that mapping fails for any single buffer larger than about 2.5 GiB while smaller
|
||||
* ones succeed every time, so a 12 GiB host pool allocated whole was refused at startup far below
|
||||
* the driver's pinned-memory cap. Passthrough (iommu=pt) lets the large pin through but takes peer
|
||||
* access away, which every multi-rank kernel requires, so the configuration has to work with
|
||||
* translation on. A range locked in pieces never asks the IOMMU for more than one piece at a time.
|
||||
*
|
||||
* The lock is ROCr's, hsa_amd_memory_lock_to_pool: the same userptr pin hipHostMalloc makes, one
|
||||
* buffer object per call. hsa_amd_pointer_info does not report what it locked, so locate() answers
|
||||
* from this backend's own record of the ranges (g_pinned) and HIP is never asked about them.
|
||||
* hipHostRegister would be HIP's record instead, and HIP's record is not what the copies read.
|
||||
*
|
||||
* The cards still see one range: a locked piece is mapped at its own host address, so the pieces
|
||||
* of one reservation are consecutive on the card too. Each piece is checked rather than assumed,
|
||||
* because the pools, the mover and the activation arena all hand a kernel base + offset.
|
||||
*
|
||||
* THAT TAKES THE KERNEL DRIVER'S SVM API, AND WITHOUT IT THE RANGE IS ONE ALLOCATION OF THE HOST
|
||||
* POOL. A lock lands at its host address because ROCr's thunk registers the range through the
|
||||
* KFD's SVM API, which maps a range where it is. A driver that does not offer it -- amdgpu could
|
||||
* not register the card's memory with HMM, seen in a KVM guest with both cards passed through --
|
||||
* gets a userptr buffer object instead, at an address the thunk's own aperture hands out: below
|
||||
* the host address, and each piece a guard page away from the one before, so the pieces are
|
||||
* neither where the host has them nor next to each other on the card. hsa_amd_vmem cannot join
|
||||
* them (ROCm 7.2 refuses a vmem handle on the host pool). The host pool's own allocation can: the
|
||||
* thunk maps it for the CPU at the address the aperture gave the cards. It is one buffer object,
|
||||
* as hipHostMalloc made before the pieces, so a host whose IOMMU refuses a large pin AND whose
|
||||
* driver has no SVM API has no large pinned range at all; the refusal names both. Which path a
|
||||
* process takes is the runtime's HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, the same capability the thunk
|
||||
* decides by, and the log says it once.
|
||||
*
|
||||
* What hipHostMalloc does besides the pin is kept, so the pages are the same pages: shared
|
||||
* anonymous memory, huge pages advised from 2 MiB up, a preferred NUMA node that is the one
|
||||
* nearest the current card (ROCr allocates from that node's pool), fine-grained coherence (the
|
||||
* pool locked to), and access from every card.
|
||||
*
|
||||
* kPinPiece is a power of two well under the failing size. The cost is one buffer object per piece
|
||||
* per card: a few dozen for the largest pools. */
|
||||
constexpr int64_t kPinPiece = (int64_t)1 << 30;
|
||||
|
||||
/* The NUMA node sysfs reports for the current card, -1 when it reports none. */
|
||||
int current_card_numa_node() {
|
||||
int dev = 0;
|
||||
char bus[64] = {0};
|
||||
if (hipGetDevice(&dev) != hipSuccess ||
|
||||
hipDeviceGetPCIBusId(bus, (int)sizeof bus, dev) != hipSuccess || !bus[0])
|
||||
return -1;
|
||||
for (char* c = bus; *c; ++c) *c = (char)std::tolower((unsigned char)*c);
|
||||
char path[160];
|
||||
std::snprintf(path, sizeof path, "/sys/bus/pci/devices/%s/numa_node", bus);
|
||||
FILE* f = std::fopen(path, "r");
|
||||
if (!f) return -1;
|
||||
int node = -1;
|
||||
if (std::fscanf(f, "%d", &node) != 1) node = -1;
|
||||
std::fclose(f);
|
||||
return node;
|
||||
}
|
||||
|
||||
/* MPOL_PREFERRED | MPOL_F_STATIC_NODES, the policy ROCr's own host allocations take. A refusal (a
|
||||
* seccomp profile that blocks mbind, a node with no memory) leaves the pages on whichever node
|
||||
* first touches them, which is a placement cost and not a correctness one: said once, then the
|
||||
* lock goes ahead. */
|
||||
void prefer_numa_node(void* p, int64_t len, int node) {
|
||||
constexpr int kMaxNodes = 1024;
|
||||
constexpr int kBits = 8 * (int)sizeof(unsigned long);
|
||||
if (node < 0 || node >= kMaxNodes) return;
|
||||
unsigned long mask[kMaxNodes / kBits] = {};
|
||||
mask[node / kBits] |= 1ul << (node % kBits);
|
||||
constexpr int kMpolPreferred = 1, kMpolStaticNodes = 1 << 15;
|
||||
if (::syscall(SYS_mbind, p, (unsigned long)len, kMpolPreferred | kMpolStaticNodes, mask,
|
||||
(unsigned long)kMaxNodes + 1, 0u) == 0)
|
||||
return;
|
||||
static std::atomic<bool> said{false};
|
||||
if (!said.exchange(true))
|
||||
RAD_WARN("device: pinned host memory could not prefer NUMA node %d, the one nearest the "
|
||||
"card (mbind: %s); its pages land on whichever node touches them first", node,
|
||||
std::strerror(errno));
|
||||
}
|
||||
|
||||
const char* hsa_why(hsa_status_t st) {
|
||||
const char* m = nullptr;
|
||||
return hsa_status_string(st, &m) == HSA_STATUS_SUCCESS && m ? m : "unknown HSA status";
|
||||
}
|
||||
|
||||
/* Whether every card's driver offers the SVM API, so that a locked piece is mapped in place. */
|
||||
bool svm_in_place() {
|
||||
static const bool on = [] {
|
||||
bool svm = false;
|
||||
if (hsa_system_get_info((hsa_system_info_t)HSA_AMD_SYSTEM_INFO_SVM_SUPPORTED, &svm) !=
|
||||
HSA_STATUS_SUCCESS)
|
||||
svm = false;
|
||||
if (!svm)
|
||||
RAD_INFO("device: the kernel driver offers no SVM API, so a pinned host range is one "
|
||||
"allocation of the host pool rather than locked in pieces of %s",
|
||||
humanb(kPinPiece).c_str());
|
||||
return svm;
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
|
||||
/* The range as one allocation of the host pool, for a driver without the SVM API. The pool
|
||||
* aligns only a buffer's end to 2 MiB, so one alignment more is asked for and the base rounded
|
||||
* up inside it. */
|
||||
void* pin_whole(int64_t bytes, const std::vector<hsa_agent_t>& cards) {
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
const int64_t ask = align_up(len, align) + align;
|
||||
void* q = nullptr;
|
||||
hsa_status_t st = hsa_amd_memory_pool_allocate(G().host_fine, (size_t)ask, 0, &q);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): the kernel driver offers no SVM API, so a pinned "
|
||||
"range has to be one allocation of the host pool (locked pieces would "
|
||||
"land apart on the cards), and the pool refused %s: %s",
|
||||
humanb(bytes).c_str(), humanb(ask).c_str(), hsa_why(st));
|
||||
return nullptr;
|
||||
}
|
||||
st = hsa_amd_agents_allow_access((uint32_t)cards.size(), cards.data(), nullptr, q);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): giving the cards access to the host-pool range: %s",
|
||||
humanb(bytes).c_str(), hsa_why(st));
|
||||
(void)hsa_amd_memory_pool_free(q);
|
||||
return nullptr;
|
||||
}
|
||||
char* const p = (char*)(((uintptr_t)q + (uintptr_t)align - 1) & ~((uintptr_t)align - 1));
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, q});
|
||||
return p;
|
||||
}
|
||||
|
||||
void* pin_pieces(int64_t bytes) {
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
if (!svm_in_place()) return pin_whole(bytes, cards);
|
||||
|
||||
const int64_t align = RAD_ALIGN_POOL;
|
||||
const int64_t len = align_up(bytes, 4096);
|
||||
/* One alignment over, trimmed at both ends, so the range starts on a 2 MiB boundary: a pool's
|
||||
* fixed-stride slots inherit its base alignment, and a huge page needs it. */
|
||||
void* m = ::mmap(nullptr, (size_t)(len + align), PROT_READ | PROT_WRITE,
|
||||
MAP_SHARED | MAP_ANONYMOUS, -1, 0);
|
||||
if (m == MAP_FAILED) {
|
||||
device_set_error("rad_dev_alloc(%s): mmap: %s", humanb(bytes).c_str(), std::strerror(errno));
|
||||
return nullptr;
|
||||
}
|
||||
const uintptr_t lo = (uintptr_t)m;
|
||||
const uintptr_t at = (lo + (uintptr_t)align - 1) & ~((uintptr_t)align - 1);
|
||||
if (at > lo) ::munmap(m, at - lo);
|
||||
if (lo + (uintptr_t)align > at) ::munmap((void*)(at + (uintptr_t)len), lo + (uintptr_t)align - at);
|
||||
char* const p = (char*)at;
|
||||
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
const int64_t off = (int64_t)done * kPinPiece;
|
||||
const int64_t n = std::min(kPinPiece, len - off);
|
||||
void* on_card = nullptr;
|
||||
const hsa_status_t st = hsa_amd_memory_lock_to_pool(p + off, (size_t)n, cards.data(),
|
||||
(int)cards.size(), G().host_fine, 0,
|
||||
&on_card);
|
||||
if (st != HSA_STATUS_SUCCESS) {
|
||||
device_set_error("rad_dev_alloc(%s): locking piece %d of %d (%s at +%s): %s",
|
||||
humanb(bytes).c_str(), done + 1, pieces, humanb(n).c_str(),
|
||||
humanb(off).c_str(), hsa_why(st));
|
||||
break;
|
||||
}
|
||||
if (on_card != p + off) {
|
||||
++done;
|
||||
device_set_error("rad_dev_alloc(%s): piece %d of %d is mapped on the cards at %p, not "
|
||||
"at its host address %p, so the pieces are not one range there, "
|
||||
"although the kernel driver reports the SVM API that maps a lock in "
|
||||
"place",
|
||||
humanb(bytes).c_str(), done, pieces, on_card, (void*)(p + off));
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (done < pieces) {
|
||||
for (int i = 0; i < done; ++i) (void)hsa_amd_memory_unlock(p + (int64_t)i * kPinPiece);
|
||||
::munmap(p, (size_t)len);
|
||||
return nullptr;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
|
||||
return p;
|
||||
}
|
||||
|
||||
void unpin_pieces(void* p) {
|
||||
Pinned r;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
auto it = g_pinned.find((uintptr_t)p);
|
||||
if (it == g_pinned.end()) {
|
||||
RAD_WARN("rad_dev_free(%p): not the base of a pinned range this backend handed out; "
|
||||
"leaked rather than unpinned", p);
|
||||
return;
|
||||
}
|
||||
r = it->second;
|
||||
g_pinned.erase(it);
|
||||
}
|
||||
if (r.pool) {
|
||||
const hsa_status_t st = hsa_amd_memory_pool_free(r.pool);
|
||||
if (st != HSA_STATUS_SUCCESS)
|
||||
RAD_WARN("device: freeing pinned host-pool range %p: %s", r.pool, hsa_why(st));
|
||||
return;
|
||||
}
|
||||
const int64_t len = r.len;
|
||||
for (int64_t off = 0; off < len; off += kPinPiece) {
|
||||
const hsa_status_t st = hsa_amd_memory_unlock((char*)p + off);
|
||||
if (st != HSA_STATUS_SUCCESS)
|
||||
RAD_WARN("device: unlocking pinned piece %p: %s", (void*)((char*)p + off), hsa_why(st));
|
||||
}
|
||||
::munmap(p, (size_t)len);
|
||||
}
|
||||
|
||||
bool pinned_kind(int kind) { return kind == RAD_MEM_HOST_PINNED || kind == RAD_MEM_HOST_MAPPED; }
|
||||
|
||||
/* HIP's own allocation calls for device and pageable memory; the pinned kinds are the pieces. The
|
||||
* two pinned kinds are one thing here: RAD_MEM_HOST_PINNED (the mover's staging and the O_DIRECT
|
||||
* landing zone, spec §5.4) and RAD_MEM_HOST_MAPPED (the zero-copy execution site, row three of
|
||||
* spec §5.1's table) are both a locked range every card addresses at its host address. */
|
||||
void* (*g_hip_alloc)(int64_t, int) = nullptr;
|
||||
void* a_alloc(int64_t bytes, int kind) {
|
||||
if (kind == RAD_MEM_DEVICE && bytes > 0) {
|
||||
int dev = -1;
|
||||
if (hipGetDevice(&dev) == hipSuccess && !card_has_room(dev, bytes, "rad_dev_alloc"))
|
||||
return nullptr;
|
||||
}
|
||||
if (!pinned_kind(kind)) return g_hip_alloc(bytes, kind);
|
||||
if (bytes <= 0) {
|
||||
device_set_error("rad_dev_alloc(%lld): size must be positive", (long long)bytes);
|
||||
return nullptr;
|
||||
}
|
||||
return pin_pieces(bytes);
|
||||
}
|
||||
|
||||
/* Behind the forgetting every free needs (locate's cache). */
|
||||
void (*g_hip_free)(void*, int) = nullptr;
|
||||
void a_free(void* p, int kind) {
|
||||
loc_forget();
|
||||
if (g_hip_free) g_hip_free(p, kind);
|
||||
if (!p) return;
|
||||
if (pinned_kind(kind)) unpin_pieces(p);
|
||||
else if (g_hip_free) g_hip_free(p, kind);
|
||||
}
|
||||
|
||||
/* A pinned range is the same address on both sides, inner addresses included. */
|
||||
void* (*g_hip_host_ptr)(void*) = nullptr;
|
||||
void* (*g_hip_device_ptr)(void*) = nullptr;
|
||||
void* a_host_ptr(void* p) { return pinned_range(p, nullptr, nullptr) ? p : g_hip_host_ptr(p); }
|
||||
void* a_device_ptr(void* p) { return pinned_range(p, nullptr, nullptr) ? p : g_hip_device_ptr(p); }
|
||||
|
||||
/* ------------------------------------------------------------------ plugin device code */
|
||||
|
||||
size_t a_code_mark(void) {
|
||||
@@ -1969,8 +2339,14 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
G().ok = true;
|
||||
g_aql = *hip;
|
||||
g_aql.name = "aql";
|
||||
g_hip_alloc = hip->alloc;
|
||||
g_hip_free = hip->free;
|
||||
g_hip_host_ptr = hip->host_ptr;
|
||||
g_hip_device_ptr = hip->device_ptr;
|
||||
g_aql.alloc = a_alloc;
|
||||
g_aql.free = a_free;
|
||||
g_aql.host_ptr = a_host_ptr;
|
||||
g_aql.device_ptr = a_device_ptr;
|
||||
g_aql.stream_create = a_stream_create;
|
||||
g_aql.stream_destroy = a_stream_destroy;
|
||||
g_aql.stream_sync = a_stream_sync;
|
||||
|
||||
@@ -223,6 +223,11 @@ struct DeviceBackend {
|
||||
* as device memory is shared with every process on the machine. Null on a backend with no such
|
||||
* devices, which answers 0. */
|
||||
int (*integrated)(int device);
|
||||
|
||||
/* ---- 1 when `self` can read and write `peer`'s memory directly, 0 when it cannot, < 0 when
|
||||
* the backend cannot say. Asked, not enabled: rad_dev_enable_peer is the call that maps the
|
||||
* memory. Null on a backend whose devices share one address space, which answers 1. */
|
||||
int (*peer_access)(int self, int peer);
|
||||
};
|
||||
|
||||
|
||||
@@ -241,6 +246,9 @@ void tape_destroy(RadTape t);
|
||||
int tape_record(RadTape t, int i, int* kind, uint32_t* queue);
|
||||
int tape_set_overlap(RadTape t, int i, bool on);
|
||||
|
||||
/* The current backend's DeviceBackend::peer_access. */
|
||||
int dev_peer_access(int self, int peer);
|
||||
|
||||
/* The current backend's DeviceBackend::vram_used. */
|
||||
int dev_vram_used(int device, int64_t* out);
|
||||
|
||||
|
||||
@@ -18,8 +18,11 @@
|
||||
#include <cstring>
|
||||
#include <atomic>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -113,7 +116,19 @@ const char* device_backend_name() { return dev()->name; }
|
||||
* exactly that reason -- the ledger says what the core spent, the card says what was spent.
|
||||
*
|
||||
* RADIANCE_TRACE_ALLOC=N logs every allocation of at least N bytes as it happens. That is the
|
||||
* instrument; the counters are the summary. */
|
||||
* instrument; the counters are the summary.
|
||||
*
|
||||
* RADIANCE_DEBUG_POISON_ALLOC=B fills every fresh DEVICE allocation with byte B (0..255) before
|
||||
* it is handed out, so a buffer that is read before anything wrote it shows up as garbage rather
|
||||
* than as the zeros a wiped card hands back by luck. A card that has just been through a driver
|
||||
* reset ("VRAM is lost") is that garbage for real, which is where such a read is otherwise first
|
||||
* seen. A correct engine serves the same output with it set. RADIANCE_DEBUG_POISON_RANGE=lo:hi
|
||||
* narrows the fill to device allocations with ordinal in [lo, hi) -- ordinals count from 1 in
|
||||
* allocation order ON THE ALLOCATING THREAD, the `#n on this thread` the trace prints -- to bisect
|
||||
* to the one allocation that matters. Both are instruments: the fill is synchronous, through one
|
||||
* stream per thread and device that lives until exit (a stream is a hardware queue, and creating
|
||||
* and destroying one per allocation is both slow and the queue churn ROCr's Trim path faults on).
|
||||
* A byte outside 0..255 or a range that does not parse is refused at the first allocation. */
|
||||
namespace rad {
|
||||
namespace {
|
||||
|
||||
@@ -138,6 +153,36 @@ int64_t trace_floor() {
|
||||
return v;
|
||||
}
|
||||
|
||||
/* -1 when off; otherwise the byte. */
|
||||
int poison_byte() {
|
||||
static const int v = [] {
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_ALLOC");
|
||||
if (!e || !*e) return -1;
|
||||
char* end = nullptr;
|
||||
const long x = std::strtol(e, &end, 0);
|
||||
if (*end || x < 0 || x > 255) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_ALLOC=%s is not a byte (0..255)", e);
|
||||
std::abort();
|
||||
}
|
||||
return (int)x;
|
||||
}();
|
||||
return v;
|
||||
}
|
||||
|
||||
/* [lo, hi) over device-allocation ordinals; the whole run when unset. */
|
||||
bool poison_in_range(int64_t ordinal) {
|
||||
static const std::pair<int64_t, int64_t> r = [] {
|
||||
const char* e = std::getenv("RADIANCE_DEBUG_POISON_RANGE");
|
||||
long long lo = 0, hi = INT64_MAX;
|
||||
if (e && *e && (std::sscanf(e, "%lld:%lld", &lo, &hi) != 2 || lo < 0 || hi <= lo)) {
|
||||
RAD_ERR("RADIANCE_DEBUG_POISON_RANGE=%s is not lo:hi with 0 <= lo < hi", e);
|
||||
std::abort();
|
||||
}
|
||||
return std::make_pair((int64_t)lo, (int64_t)hi);
|
||||
}();
|
||||
return ordinal >= r.first && ordinal < r.second;
|
||||
}
|
||||
|
||||
const char* kind_name(int kind) {
|
||||
switch (kind) {
|
||||
case RAD_MEM_DEVICE: return "device";
|
||||
@@ -367,21 +412,47 @@ using rad::dev;
|
||||
extern "C" {
|
||||
|
||||
int rad_dev_count(void) { return dev()->count(); }
|
||||
int rad_dev_set(int device) { return dev()->set(device); }
|
||||
/* The device this thread last selected, for the poison fill's stream (rad_dev_alloc). */
|
||||
static thread_local int t_device = 0;
|
||||
static thread_local std::map<int, RadStream> t_poison_stream;
|
||||
int rad_dev_set(int device) {
|
||||
const int st = dev()->set(device);
|
||||
if (st == RAD_OK) t_device = device;
|
||||
return st;
|
||||
}
|
||||
int rad_dev_props(int device, RadDeviceProps* o) { return dev()->props(device, o); }
|
||||
int rad_dev_enable_peer(int self, int peer) { return dev()->enable_peer(self, peer); }
|
||||
|
||||
void* rad_dev_alloc(int64_t bytes, int kind) {
|
||||
/* The poison range is over THIS THREAD's device allocations, because a rank brings itself up on
|
||||
* its own thread in a fixed order while the threads interleave freely: a process-wide ordinal
|
||||
* would name a different allocation on every run, and a bisect over it would not converge. */
|
||||
thread_local int64_t t_device_ordinal = 0;
|
||||
void* p = dev()->alloc(bytes, kind);
|
||||
if (p && kind >= 0 && kind < 4) {
|
||||
rad::g_ledger[kind].bytes.fetch_add(bytes, std::memory_order_relaxed);
|
||||
rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed);
|
||||
const int64_t total = rad::g_ledger[kind].count.fetch_add(1, std::memory_order_relaxed) + 1;
|
||||
const int64_t ordinal = kind == RAD_MEM_DEVICE ? ++t_device_ordinal : total;
|
||||
const int64_t floor_ = rad::trace_floor();
|
||||
if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("alloc %s %s (%lld live in %lld allocations)", rad::kind_name(kind),
|
||||
rad::humanb(bytes).c_str(),
|
||||
RAD_INFO("alloc %s %s (#%lld on this thread; %lld live in %lld allocations)",
|
||||
rad::kind_name(kind), rad::humanb(bytes).c_str(), (long long)ordinal,
|
||||
(long long)rad::g_ledger[kind].bytes.load(std::memory_order_relaxed),
|
||||
(long long)rad::g_ledger[kind].count.load(std::memory_order_relaxed));
|
||||
(long long)total);
|
||||
/* The poison fill (see the top of this file). Through the backend's own stream so it
|
||||
* holds on both backends; synchronous, so the bytes are there before the caller sees p. */
|
||||
const int poison = rad::poison_byte();
|
||||
if (poison >= 0 && kind == RAD_MEM_DEVICE && rad::poison_in_range(ordinal)) {
|
||||
RadStream& s = t_poison_stream[t_device];
|
||||
if (!s && dev()->stream_create(&s, 0) != RAD_OK) s = nullptr;
|
||||
if (!s || dev()->memset_async(p, poison, bytes, s) != RAD_OK ||
|
||||
dev()->stream_sync(s) != RAD_OK)
|
||||
RAD_WARN("poison: device allocation #%lld (%s) was not filled",
|
||||
(long long)ordinal, rad::humanb(bytes).c_str());
|
||||
else if (floor_ >= 0 && bytes >= floor_)
|
||||
RAD_INFO("poison: device allocation #%lld filled with 0x%02x", (long long)ordinal,
|
||||
poison);
|
||||
}
|
||||
}
|
||||
return p;
|
||||
}
|
||||
@@ -430,6 +501,10 @@ int tape_set_overlap(RadTape t, int i, bool on) {
|
||||
return dev()->tape_set_overlap ? dev()->tape_set_overlap(t, i, on ? 1 : 0) : RAD_E_UNSUPPORTED;
|
||||
}
|
||||
bool dev_integrated(int device) { return dev()->integrated && dev()->integrated(device) > 0; }
|
||||
int dev_peer_access(int self, int peer) {
|
||||
if (self == peer) return 1;
|
||||
return dev()->peer_access ? dev()->peer_access(self, peer) : 1;
|
||||
}
|
||||
size_t dev_code_mark() { return dev()->code_mark ? dev()->code_mark() : 0; }
|
||||
int dev_code_runs(size_t from, size_t to, int device, std::string* why) {
|
||||
if (!dev()->code_runs || from >= to) return 1;
|
||||
|
||||
+17
-14
@@ -1,7 +1,8 @@
|
||||
/* hip.cpp -- the HIP half of the device backend: devices, memory and elastic memory.
|
||||
*
|
||||
* Streams, events, copies and fills are not here. They are AQL packets the engine writes into
|
||||
* queues it owns (aql.cpp), which starts from this table and fills in the rest.
|
||||
* queues it owns (aql.cpp), which starts from this table and fills in the rest -- pinned host
|
||||
* memory included, because the copies have to recognise it.
|
||||
*
|
||||
* Thin by design. Every entry point is one hip* call plus an error capture, because anything
|
||||
* cleverer than that is a place where the host backend and this one can disagree, and the host
|
||||
@@ -251,6 +252,12 @@ int d_props(int device, RadDeviceProps* out) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int d_peer_access(int self, int peer) {
|
||||
int can = 0;
|
||||
HIP_TRY(hipDeviceCanAccessPeer(&can, self, peer));
|
||||
return can ? 1 : 0;
|
||||
}
|
||||
|
||||
int d_enable_peer(int self, int peer) {
|
||||
if (self == peer) return RAD_OK;
|
||||
int can = 0;
|
||||
@@ -287,18 +294,11 @@ void* d_alloc(int64_t bytes, int kind) {
|
||||
e = hipMalloc(&p, (size_t)bytes);
|
||||
break;
|
||||
case RAD_MEM_HOST_PINNED:
|
||||
/* The mover's staging pool and the O_DIRECT landing zone. Pinned so a transfer is a
|
||||
* DMA the driver does not have to stage through its own bounce buffer (spec §5.4). */
|
||||
e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocDefault);
|
||||
break;
|
||||
case RAD_MEM_HOST_MAPPED:
|
||||
/* The zero-copy execution site: tier host, site device, no slab slot -- row three of
|
||||
* spec §5.1's table. hipHostMallocMapped is what makes the allocation addressable from
|
||||
* a kernel over the link, which is the whole mechanism. The cost is that every read is
|
||||
* a link read, so this is for read-once weights and the planner decides which
|
||||
* (spec §19.3). */
|
||||
e = hipHostMalloc(&p, (size_t)bytes, hipHostMallocMapped);
|
||||
break;
|
||||
/* The AQL backend's, which pins host memory through ROCr in pieces the IOMMU can map
|
||||
* (aql.cpp, "pinned host memory, in pieces"). */
|
||||
device_set_error("rad_dev_alloc: pinned host memory is the AQL backend's");
|
||||
return nullptr;
|
||||
case RAD_MEM_HOST:
|
||||
/* Pageable. Aligned to a page anyway so the same buffer can be an O_DIRECT target. */
|
||||
if (posix_memalign(&p, 4096, (size_t)((bytes + 4095) / 4096 * 4096)) != 0) p = nullptr;
|
||||
@@ -319,9 +319,11 @@ void d_free(void* p, int kind) {
|
||||
if (!p) return;
|
||||
switch (kind) {
|
||||
case RAD_MEM_DEVICE: HIP_NOTE(hipFree(p)); break;
|
||||
case RAD_MEM_HOST_PINNED:
|
||||
case RAD_MEM_HOST_MAPPED: HIP_NOTE(hipHostFree(p)); break;
|
||||
case RAD_MEM_HOST: std::free(p); break;
|
||||
case RAD_MEM_HOST_PINNED:
|
||||
case RAD_MEM_HOST_MAPPED:
|
||||
RAD_WARN("rad_dev_free(%p): pinned host memory is the AQL backend's; leaked", p);
|
||||
break;
|
||||
default:
|
||||
RAD_WARN("rad_dev_free(%p): unknown memory kind %d; leaked rather than freed with the "
|
||||
"wrong allocator", p, kind);
|
||||
@@ -370,6 +372,7 @@ const DeviceBackend g_hip = {
|
||||
/* Plugin device code: the AQL backend's, which owns the fat-binary registrations. */
|
||||
nullptr, nullptr,
|
||||
d_integrated,
|
||||
d_peer_access,
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
+213
-80
@@ -80,6 +80,10 @@ Engine::~Engine() {
|
||||
for (auto& r : ranks_) r->ctx.shutdown();
|
||||
step_state_fini();
|
||||
ranks_.clear();
|
||||
for (TableCopy& c : table_copies_) table_copy_free(&c);
|
||||
table_copies_.clear();
|
||||
for (void* p : card_copies_) rad_dev_free(p, RAD_MEM_HOST_MAPPED);
|
||||
card_copies_.clear();
|
||||
rad_tools_registry().close();
|
||||
}
|
||||
|
||||
@@ -118,13 +122,18 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
|
||||
sc.n_vocab_local = logits_width > 0 ? logits_width : meta_.n_vocab;
|
||||
/* THIS RANK'S FIRST VOCABULARY ROW, and it is the one thing the declared width cannot say:
|
||||
* a width tells you how many rows a rank owns, not which. The rule is arch/common/rad_arch.h's
|
||||
* shard_begin -- ceil(total/world) per rank with the last one short -- and it is restated here
|
||||
* shard_begin -- ceil(total/world) per rank, rounded up to a 128-row block, the last one short -- and it is restated here
|
||||
* rather than carried through the ABI, so the restatement is CHECKED against what the plugin
|
||||
* actually declared. A plugin that shards some other way gets a named refusal at startup
|
||||
* instead of a sampler that names rank 0's tokens with rank 1's ids. */
|
||||
sc.vocab_off = 0;
|
||||
if (sc.n_vocab_local < sc.n_vocab) {
|
||||
const int64_t per = (sc.n_vocab + cfg_.tp - 1) / cfg_.tp;
|
||||
/* rad_arch.h vocab_per_rank, restated: the even share when the world divides the vocabulary;
|
||||
* otherwise ceil(n / tp) rounded up to a whole 128-row block so a block-scaled head can be
|
||||
* cut there. */
|
||||
const int64_t ceil_per = (sc.n_vocab + cfg_.tp - 1) / cfg_.tp;
|
||||
const int64_t per = (sc.n_vocab % cfg_.tp == 0) ? sc.n_vocab / cfg_.tp
|
||||
: (ceil_per + 127) / 128 * 128;
|
||||
sc.vocab_off = per * rank;
|
||||
const int64_t want = std::min<int64_t>(per, sc.n_vocab - sc.vocab_off);
|
||||
if (sc.vocab_off >= sc.n_vocab || want != sc.n_vocab_local) {
|
||||
@@ -383,7 +392,7 @@ void Engine::phase_mark(int p) {
|
||||
int Engine::fail_loop(int st) {
|
||||
stopping_.store(true, std::memory_order_release);
|
||||
if (barrier_) barrier_->abort();
|
||||
sched_.shutdown("the engine stopped on an error and is not serving");
|
||||
sched_.shutdown("the engine stopped on an error and is not serving", st < 0 ? st : RAD_E_STATE);
|
||||
loop_status_.store(st < 0 ? st : RAD_E_STATE, std::memory_order_release);
|
||||
return st;
|
||||
}
|
||||
@@ -525,15 +534,20 @@ int Engine::step_loop() {
|
||||
* recorded the grab and cannot do the write itself (StateClear in core/mem/kv.h); this is
|
||||
* the first moment a stream exists and the last before the ranks are released, and it is
|
||||
* off the hot path -- the list is empty on every step but a sequence's first. Every rank
|
||||
* clears its own pool: the slot number is the scheduler's, the memory is the rank's. */
|
||||
* clears its own pool BY ITS OWN PLAN: the slot number is the scheduler's, the memory and
|
||||
* its size are the rank's. A state is as large as the heads this rank holds of the group,
|
||||
* and the ranks' shares need not be equal (rad_arch.h remainder_place): a rank clearing
|
||||
* rank 0's byte count of a larger state leaves its tail as the last sequence left it, and
|
||||
* the recurrence reads it from the first token. */
|
||||
for (const StateClear& c : ranks_[0]->kv.state_clears()) {
|
||||
const KVGroupPlan* gp = ranks_[0]->kv.plan(c.group);
|
||||
if (!gp || !gp->stateful()) continue;
|
||||
const int64_t bytes = gp->layer_bytes_per_state();
|
||||
for (auto& rk : ranks_)
|
||||
for (auto& rk : ranks_) {
|
||||
const KVGroupPlan* gp = rk->kv.plan(c.group);
|
||||
if (!gp || !gp->stateful()) continue;
|
||||
const int64_t bytes = gp->layer_bytes_per_state();
|
||||
for (int64_t l = 0; l < gp->n_layers; ++l)
|
||||
if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot))
|
||||
rad_memset_async(p, 0, bytes, rk->ctx.stream());
|
||||
}
|
||||
}
|
||||
ranks_[0]->kv.clear_state_clears();
|
||||
|
||||
@@ -637,13 +651,13 @@ int Engine::step_loop() {
|
||||
}
|
||||
|
||||
/* THE RECURRENT HALF OF A PREFIX HIT, restored BEFORE the step that reads it. The adopted
|
||||
* blocks carry the attention layers; this carries the recurrent ones. Enqueued on each
|
||||
* rank's own stream ahead of the release, so it is ordered before the kernels without a
|
||||
* synchronisation -- the same way collect_step's readback is ordered after them.
|
||||
* blocks carry the attention layers; this carries the recurrent ones, copied out of the
|
||||
* snapshot's slot in host memory. Enqueued on each rank's own stream ahead of the
|
||||
* release, so it is ordered before the kernels without a synchronisation -- the same way
|
||||
* collect_step's readback is ordered after them.
|
||||
*
|
||||
* UNDER THE SCHEDULER'S LOCK, because it reads the sequence table and backs checkpoint
|
||||
* slots in rank 0's manager, which an HTTP thread's cancel mutates under that lock. Taken
|
||||
* only on a step that has a restore in it. */
|
||||
* UNDER THE SCHEDULER'S LOCK, because it reads the sequence table, which an HTTP thread's
|
||||
* cancel mutates under that lock. Taken only on a step that has a restore in it. */
|
||||
bool any_restore = false;
|
||||
for (const StepEntry& e : plan.e) if (e.ckpt_restore >= 0) { any_restore = true; break; }
|
||||
if (any_restore) {
|
||||
@@ -652,12 +666,7 @@ int Engine::step_loop() {
|
||||
if (e.ckpt_restore < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
/* THIS RANK'S DEVICE, BECAUSE THE COPY MAY HAVE TO MAP MEMORY FIRST. A
|
||||
* checkpoint slot is backed by the rank that writes it
|
||||
* (KVManager::back_checkpoint), and a commit must land on the card whose pool
|
||||
* it backs -- a commit on card 0 mapped into rank 1's range succeeds, grants
|
||||
* access to the wrong card, and rank 1's next kernel faults on a page that is
|
||||
* present somewhere else. */
|
||||
/* This rank's device, for its own stream and its own state slots. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
@@ -745,8 +754,9 @@ int Engine::step_loop() {
|
||||
|
||||
/* AND THE SNAPSHOT, taken AFTER the step that produced the state. The chunker split this
|
||||
* chunk so its last token IS the checkpoint position, so what copy 0 holds now is exactly
|
||||
* the state at that position. It is issued before collect_step's readback synchronises, so
|
||||
* the copy overlaps whatever is left of the step rather than adding to it.
|
||||
* the state at that position. It is a copy across the link into the snapshot's slot in host
|
||||
* memory, issued before collect_step's readback synchronises and ahead of any step issued
|
||||
* behind this one, which is what orders the next write of the state after it.
|
||||
*
|
||||
* Under the scheduler's lock for the reason the restore above is, and only on a step that
|
||||
* writes a checkpoint. */
|
||||
@@ -759,8 +769,6 @@ int Engine::step_loop() {
|
||||
if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue;
|
||||
if (!state_slots_of(e.seq, &ckpt_slots_)) continue;
|
||||
for (auto& rk : ranks_) {
|
||||
/* THIS RANK'S DEVICE, for the reason the restore gives: the copy may have to
|
||||
* back the slot first, and the pages belong on this rank's card. */
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(rk->device);
|
||||
const int s = rk->kv.checkpoint_save(ckpt_slots_.data(),
|
||||
(int)ckpt_slots_.size(),
|
||||
@@ -1133,15 +1141,8 @@ void Engine::loan_tick(bool idle) {
|
||||
const auto lk = sched_.hold();
|
||||
Rank& lead = *ranks_[0];
|
||||
|
||||
/* A FINISHED CONVERSATION'S VRAM GOES FIRST, when the slabs have a use for it. An entry whose
|
||||
* host copy has landed loses nothing by leaving -- a return restores it from host memory --
|
||||
* so while any slab has slots the loan does not yet cover, every such entry is released and
|
||||
* its blocks count toward what the cache can spare below. Past that point the VRAM would sit
|
||||
* empty in the slab, and the entries stay where a return finds them for free. */
|
||||
int64_t ceiling = 0;
|
||||
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
|
||||
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
|
||||
|
||||
/* A FINISHED CONVERSATION'S VRAM IS ALREADY FREE by the time this runs: tier_tick gives up
|
||||
* every entry whose host copy has landed, so what the cache can spare below counts it. */
|
||||
/* WHAT THE CACHE CAN DO WITHOUT, AND WHAT THE SLABS STILL OCCUPY. A loan grows as soon as the
|
||||
* cache can spare it -- the slots are filled on the next dispatch or the next idle tick -- but
|
||||
* only by at least a prefill chunk, so a cache breathing by a few blocks does not have its
|
||||
@@ -1282,14 +1283,20 @@ void Engine::tier_tick() {
|
||||
{
|
||||
TierIO::Fetch f;
|
||||
while (P.io.take_fetch(&f)) {
|
||||
for (size_t i = 0; i < f.fences.size() && i < ranks_.size(); ++i) {
|
||||
if (!f.fences[i]) continue;
|
||||
(void)rad_dev_set(ranks_[i]->device);
|
||||
rad_event_destroy(f.fences[i]);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
destroy_fences(f.fences);
|
||||
const auto lk = sched_.hold();
|
||||
lead.tierx.report_pass(f.jobs, f.ok, now);
|
||||
/* A SNAPSHOT READ BACK INTO ITS SLOT goes to the cache's index entry, which the lookup
|
||||
* then serves. One whose entry went while the read was out has nothing to land in, and
|
||||
* the record must not go on naming a slot the store will hand to somebody else. */
|
||||
for (const TierJob& j : f.jobs) {
|
||||
if (!j.ck_want || j.ck_slot < 0 || !lead.tiers.snapshot_in_slot(j.key, j.ck_slot))
|
||||
continue;
|
||||
if (lead.prefix.reattach_snapshot(j.key, j.ck_slot) != RAD_OK) {
|
||||
lead.tiers.snapshot_detached(j.key);
|
||||
lead.kv.free_checkpoint(j.ck_slot);
|
||||
}
|
||||
}
|
||||
P.waiting.erase(std::remove(P.waiting.begin(), P.waiting.end(), f.tag), P.waiting.end());
|
||||
}
|
||||
}
|
||||
@@ -1298,7 +1305,9 @@ void Engine::tier_tick() {
|
||||
{
|
||||
std::vector<TierJob> jobs;
|
||||
std::vector<char> ok;
|
||||
if (P.io.take(&jobs, &ok)) {
|
||||
std::vector<RadEvent> fences;
|
||||
if (P.io.take(&jobs, &ok, &fences)) {
|
||||
destroy_fences(fences);
|
||||
const auto lk = sched_.hold();
|
||||
lead.tierx.report_pass(jobs, ok, now);
|
||||
}
|
||||
@@ -1320,6 +1329,22 @@ void Engine::tier_tick() {
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- what is not live leaves VRAM -------------------------------------------------------- */
|
||||
/* AS SOON AS ITS COPY HAS LANDED, WHILE THE EXPERT SLAB HAS A USE FOR THE BLOCKS. An entry no
|
||||
* running sequence reads and whose host copy is in place costs nothing to give up -- a later
|
||||
* turn restores it in a copy -- and its blocks are lent to the slab. With no lender, or a slab
|
||||
* whose loan already covers every slot it has, the blocks would sit empty in the pool, so the
|
||||
* entry stays where the next turn finds it for free; a request that needs the room takes it
|
||||
* through trim, which drops the same entries on demand.
|
||||
*
|
||||
* NOT THE SNAPSHOTS: they are in host memory already and hold no VRAM. */
|
||||
if (lending_) {
|
||||
int64_t ceiling = 0;
|
||||
for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV));
|
||||
const auto lk = sched_.hold();
|
||||
if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean();
|
||||
}
|
||||
|
||||
/* ---- the slow half ---------------------------------------------------------------------- */
|
||||
/* AS SOON AS A DISK COPY IS WAITING, not on the clock: until it lands, the entry's host slot
|
||||
* cannot be given up for nothing, and a full arena is then a restore that cannot read through
|
||||
@@ -1329,7 +1354,25 @@ void Engine::tier_tick() {
|
||||
tier_last_ns_ = now;
|
||||
std::vector<TierJob> jobs;
|
||||
lead.tiers.plan(P.slow_budget, &jobs);
|
||||
if (!jobs.empty() && !P.io.submit(std::move(jobs))) {
|
||||
/* A SNAPSHOT'S SLOT IS FILLED BY A COPY ON THE COMPUTE STREAM, issued after the step that
|
||||
* produced the state and before the cache was told of it; the write waits for that copy to
|
||||
* land, and every one of its kind is behind this mark. */
|
||||
bool snaps = false;
|
||||
for (const TierJob& j : jobs) snaps = snaps || j.ck_slot >= 0;
|
||||
int fst = RAD_OK;
|
||||
std::vector<RadEvent> fences = snaps ? rank_fences(false, true, &fst)
|
||||
: std::vector<RadEvent>{};
|
||||
/* A mark that could not be made leaves nothing to order the write by: the batch is
|
||||
* reported failed, and every record keeps what it had. */
|
||||
if (fst != RAD_OK) {
|
||||
destroy_fences(fences);
|
||||
const std::vector<char> ok(jobs.size(), 0);
|
||||
const auto lk = sched_.hold();
|
||||
lead.tierx.report_pass(jobs, ok, now);
|
||||
return;
|
||||
}
|
||||
if (!jobs.empty() && !P.io.submit(std::move(jobs), std::move(fences))) {
|
||||
destroy_fences(fences);
|
||||
/* The thread is not running -- no disk tier -- and a plan without one holds only drops,
|
||||
* which move nothing. They are reported here. */
|
||||
std::vector<char> ok(jobs.size(), 1);
|
||||
@@ -1339,6 +1382,74 @@ void Engine::tier_tick() {
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<RadEvent> Engine::rank_fences(bool transfer, bool compute, int* st) {
|
||||
std::vector<RadEvent> out;
|
||||
int rc = RAD_OK;
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
if ((pass == 0 && !transfer) || (pass == 1 && !compute)) continue;
|
||||
for (auto& r : ranks_) {
|
||||
RadEvent e = nullptr;
|
||||
const int s = r->tierx.fence(&e, pass == 1 ? r->ctx.stream() : nullptr);
|
||||
if (s != RAD_OK && rc == RAD_OK) rc = s;
|
||||
out.push_back(e);
|
||||
}
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
if (st) *st = rc;
|
||||
return out;
|
||||
}
|
||||
|
||||
void Engine::destroy_fences(std::vector<RadEvent>& f) {
|
||||
for (size_t i = 0; i < f.size(); ++i) {
|
||||
if (!f[i]) continue;
|
||||
(void)rad_dev_set(ranks_[i % ranks_.size()]->device);
|
||||
rad_event_destroy(f[i]);
|
||||
}
|
||||
f.clear();
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
}
|
||||
|
||||
bool Engine::flush_copies() {
|
||||
if (!pump_ || !ranks_[0]->tierx.enabled()) return false;
|
||||
TierPump& P = *pump_;
|
||||
Rank& lead = *ranks_[0];
|
||||
bool landed = false;
|
||||
const uint64_t t0 = rad_mono_ns();
|
||||
/* Counted only when something was in flight or waiting: a call that found nothing to land
|
||||
* stalled nobody. */
|
||||
struct Note {
|
||||
IdleTiers& t; uint64_t t0; bool worked = false;
|
||||
~Note() { if (worked) t.note_flush((int64_t)(rad_mono_ns() - t0)); }
|
||||
} note{lead.tiers, t0};
|
||||
/* BOUNDED: each round lands one batch of P.max_copy entries, and a pool short of more than
|
||||
* that many rounds' worth is a pool the tiers cannot relieve in one step. */
|
||||
for (int round = 0; round < 64; ++round) {
|
||||
if (!P.copy.empty()) {
|
||||
note.worked = true;
|
||||
bool good = true;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
if (P.copy_st[i] == 0) P.copy_st[i] = ranks_[i]->tierx.wait_copy();
|
||||
if (P.copy_st[i] < 0) good = false;
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
const std::vector<char> ok(P.copy.size(), good ? 1 : 0);
|
||||
lead.tierx.report_pass(P.copy, ok, rad_mono_ns());
|
||||
P.copy.clear();
|
||||
landed = landed || good;
|
||||
}
|
||||
if (!lead.tiers.writeback_waiting()) break;
|
||||
lead.tiers.plan_writeback(P.max_copy, &P.copy);
|
||||
if (P.copy.empty()) break;
|
||||
P.copy_st.assign(ranks_.size(), 0);
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
const int st = ranks_[i]->tierx.issue_copy(P.copy, ranks_[i]->ctx.stream());
|
||||
if (st < 0) P.copy_st[i] = st;
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(lead.device);
|
||||
}
|
||||
return landed;
|
||||
}
|
||||
|
||||
/* HAND A READ OFF DISK TO THE IO THREAD, fenced on every rank's transfer stream: the slots it
|
||||
* writes may have been given up by entries a restore is still copying out of. False when it could
|
||||
* not be handed over, and then the reads are reported unstarted -- the records stay on disk and the
|
||||
@@ -1348,25 +1459,20 @@ bool Engine::submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs) {
|
||||
TierIO::Fetch f;
|
||||
f.tag = tag;
|
||||
f.jobs = std::move(jobs);
|
||||
/* THE TRANSFER STREAMS, for the restores that read block slots, and THE COMPUTE STREAMS when a
|
||||
* snapshot comes in: its store slot may have been given up by a snapshot a restore on that
|
||||
* stream is still copying out of. */
|
||||
bool snap = false;
|
||||
for (const TierJob& j : f.jobs) snap = snap || (j.ck_want && j.ck_slot >= 0);
|
||||
int st = RAD_OK;
|
||||
for (auto& r : ranks_) {
|
||||
RadEvent e = nullptr;
|
||||
if (st == RAD_OK) st = r->tierx.fence(&e);
|
||||
f.fences.push_back(e);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
f.fences = rank_fences(true, snap, &st);
|
||||
if (st == RAD_OK && P.io.submit_fetch(std::move(f))) {
|
||||
P.waiting.push_back(tag);
|
||||
return true;
|
||||
}
|
||||
RAD_ERR("kv tiers: a read off disk could not be handed to the IO thread (%s); the request is "
|
||||
"admitted with what host memory holds", st < 0 ? rad_strerror(st) : "not running");
|
||||
for (size_t i = 0; i < f.fences.size(); ++i) {
|
||||
if (!f.fences[i]) continue;
|
||||
(void)rad_dev_set(ranks_[i]->device);
|
||||
rad_event_destroy(f.fences[i]);
|
||||
}
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
destroy_fences(f.fences);
|
||||
const std::vector<char> ok(f.jobs.size(), 0);
|
||||
ranks_[0]->tierx.report_pass(f.jobs, ok, rad_mono_ns());
|
||||
return false;
|
||||
@@ -1394,11 +1500,12 @@ int Engine::serve() {
|
||||
}
|
||||
|
||||
/* The scheduler drives ONE block manager. Block ids are pure bookkeeping and identical on
|
||||
* every rank -- the heads divide equally, so every rank's pool has the same geometry and its
|
||||
* free list evolves identically. What differs per rank is the pool BASE, and that lives in
|
||||
* KVPoolBinding. So rank 0's manager owns the bookkeeping and the others exist to own their
|
||||
* own card's allocation. If the geometries ever disagree the block tables mean different
|
||||
* things on different cards, so it is checked rather than assumed. */
|
||||
* every rank: every rank carves the same block count (Engine::configure_kv caps each at the
|
||||
* least rank's), so its free list evolves identically even where the ranks' shares of a
|
||||
* group differ in bytes, or are zero (rad_kv_group_zero). What differs per rank is the pool
|
||||
* BASE, and that lives in KVPoolBinding. So rank 0's manager owns the bookkeeping and the
|
||||
* others exist to own their own card's allocation. If the counts ever disagree the block
|
||||
* tables mean different things on different cards, so it is checked rather than assumed. */
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) {
|
||||
const auto& a = ranks_[0]->kv.plans();
|
||||
const auto& c = ranks_[i]->kv.plans();
|
||||
@@ -1438,12 +1545,9 @@ int Engine::serve() {
|
||||
/* CALLED FROM INSIDE Scheduler::step(), UNDER ITS LOCK -- which is what makes it safe to
|
||||
* touch the cache and rank 0's manager here, and why nothing below may call back into the
|
||||
* scheduler. */
|
||||
/* A restored session's state needs a device checkpoint slot, and which snapshot gives
|
||||
* one up is the cache's decision: it knows which ones a lookup this step handed out. */
|
||||
ranks_[0]->tierx.set_checkpoint_room(
|
||||
[this] { return ranks_[0]->prefix.free_checkpoint_for_restore(); });
|
||||
b->restore_fn = [this](const Request& req) -> IPrefixCache::Restore {
|
||||
using R = IPrefixCache::Restore;
|
||||
const uint64_t t0 = rad_mono_ns();
|
||||
PrefixCache& pc = ranks_[0]->prefix;
|
||||
TierPump& P = *pump_;
|
||||
if (std::find(P.waiting.begin(), P.waiting.end(), req.id) != P.waiting.end())
|
||||
@@ -1454,13 +1558,27 @@ int Engine::serve() {
|
||||
const std::vector<BlockHash> want = pc.restorable_from(req.prompt, mk, &chain);
|
||||
/* THE DISK PART IS READ FIRST, ON THE IO THREAD, while this request waits and every
|
||||
* other one runs; the restore below then copies host memory and nothing else. Asked
|
||||
* only when something could be on disk or in flight: a chain wholly in VRAM is the
|
||||
* common case, and it is thousands of keys. */
|
||||
if (!want.empty() || !P.waiting.empty()) {
|
||||
* on every attempt, because a chain wholly in VRAM can still want a read: its deepest
|
||||
* snapshot may have given its store slot up and be on disk alone.
|
||||
*
|
||||
* THAT SNAPSHOT NEEDS A STORE SLOT TO LAND IN, and the store's free list is rank 0's
|
||||
* manager's: one is taken here -- making room by detaching a snapshot the disk also
|
||||
* holds, which is the cache's choice -- and handed to the plan, which gives it back
|
||||
* when it does not read the snapshot after all. */
|
||||
{
|
||||
std::vector<TierJob> reads;
|
||||
if (ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns())) {
|
||||
if (reads.empty() || submit_fetch(req.id, std::move(reads))) return R::Wait;
|
||||
int32_t ck = -1;
|
||||
if (ranks_[0]->tiers.snapshot_fetch_wanted(chain) &&
|
||||
ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK) {
|
||||
ck = -1;
|
||||
if (pc.free_checkpoint_for_restore() &&
|
||||
ranks_[0]->kv.alloc_checkpoint(&ck) != RAD_OK)
|
||||
ck = -1;
|
||||
}
|
||||
const bool wait = ranks_[0]->tiers.plan_fetch(chain, &reads, rad_mono_ns(), &ck);
|
||||
if (ck >= 0) ranks_[0]->kv.free_checkpoint(ck);
|
||||
if (wait && (reads.empty() || submit_fetch(req.id, std::move(reads))))
|
||||
return R::Wait;
|
||||
}
|
||||
if (want.empty()) return R::Done;
|
||||
/* THE WHOLE CHAIN IN ONE RESTORE. A 4-token block makes a long conversation tens of
|
||||
@@ -1499,22 +1617,20 @@ int Engine::serve() {
|
||||
* them too, and would be released later from under whoever the pool gives them
|
||||
* to. Both are let go, so the blocks return to the pool and the key is simply
|
||||
* unknown. */
|
||||
ranks_[0]->tierx.quiesce();
|
||||
for (size_t k = 0; k < cg.size() && k < j.blocks.size(); ++k)
|
||||
if (j.blocks[k] >= 0) ranks_[0]->kv.release_block(cg[k], j.blocks[k]);
|
||||
ranks_[0]->tiers.forget(j.key);
|
||||
if (j.ck_dev >= 0) ranks_[0]->kv.free_checkpoint(j.ck_dev);
|
||||
continue;
|
||||
}
|
||||
/* AND THE RECURRENT HALF, into the slot the restore allocated for it. Without this
|
||||
* the session gets its attention hit back and replays every linear layer from
|
||||
* token zero, which on a long transcript is most of a prefill. NOBODY ELSE OWNS
|
||||
* THAT SLOT UNTIL THE CACHE TAKES IT: if the index entry the snapshot belongs to
|
||||
* was retired, the slot has no path back to the free list. */
|
||||
if (j.ck_dev >= 0 && pc.reattach_snapshot(j.key, j.ck_dev) != RAD_OK)
|
||||
ranks_[0]->kv.free_checkpoint(j.ck_dev);
|
||||
}
|
||||
ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0));
|
||||
return R::Done;
|
||||
};
|
||||
/* AN EVICTION THAT WOULD LOSE AN ENTRY WAITS FOR ITS COPY INSTEAD. Called by the
|
||||
* prefix cache binding under the scheduler's lock, on this thread, when dropping the
|
||||
* entries that already have a host copy did not free enough: every copy waiting is
|
||||
* planned, issued and landed now, so the entries it covers can leave VRAM and be kept. */
|
||||
b->flush_fn = [this]() -> bool { return flush_copies(); };
|
||||
}
|
||||
/* EVERY RANK'S CARD, STREAM AND ARENA. The batch is one build shared by pointer (spec §1) and
|
||||
* that is right for the host side; the DEVICE side is staged per rank, because a rank reading
|
||||
@@ -1615,6 +1731,12 @@ std::string Engine::engine_info() const {
|
||||
e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
|
||||
e["max_num_batched_tokens"] = cfg_.max_tok;
|
||||
e["placement"] = cfg_.placement;
|
||||
/* What each lookup table was asked for and where it went: auto's answer is the one a
|
||||
* dashboard reading this needs, and the request is the one the command line shows. */
|
||||
e["embedding_placement"] = { { "asked", table_placement_name(cfg_.embedding_placement) },
|
||||
{ "resolved", table_placement_name(cfg_.embedding_resolved) } };
|
||||
e["ngram_placement"] = { { "asked", table_placement_name(cfg_.ngram_placement) },
|
||||
{ "resolved", table_placement_name(cfg_.ngram_resolved) } };
|
||||
e["prefix_cache"] = cfg_.prefix_cache;
|
||||
e["checkpoint_slots"] = cfg_.checkpoint_slots;
|
||||
e["deterministic"] = cfg_.deterministic;
|
||||
@@ -1808,6 +1930,8 @@ std::string request_overrides(const Config& c) {
|
||||
std::to_string(c.max_stop_bytes) + " bytes");
|
||||
for (const auto& [k, v] : c.chat_template_kwargs) add("template " + k + "=" + v);
|
||||
if (c.reasoning_format != "auto") add("reasoning_format " + c.reasoning_format);
|
||||
if (c.thinking_token_budget >= 0)
|
||||
add("thinking_token_budget " + std::to_string(c.thinking_token_budget));
|
||||
return out;
|
||||
}
|
||||
} /* namespace */
|
||||
@@ -2025,14 +2149,16 @@ int Engine::run_server() {
|
||||
o.max_n = cfg_.max_n > 0 ? (int)cfg_.max_n : (int)std::max<int64_t>(o.max_n, cfg_.max_seqs);
|
||||
o.max_ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
o.default_reasoning_effort = cfg_.reasoning_effort;
|
||||
o.default_thinking_budget = cfg_.thinking_token_budget;
|
||||
o.default_sampling = resolve_sampling_defaults(meta_, file_ != nullptr, cfg_);
|
||||
o.default_dry_breakers_set = cfg_.sample_dry_seq_breakers.has_value();
|
||||
/* -1 leaves ServerOptions' own default. `auto` (0) is resolved per request against the
|
||||
* context, so it needs one to resolve against. */
|
||||
/* -1 leaves ServerOptions' own default, which is `auto` (0). That is resolved per request
|
||||
* against the context, so it needs one to resolve against. */
|
||||
if (cfg_.default_max_tokens >= 0) o.default_max_tokens = cfg_.default_max_tokens;
|
||||
if (o.default_max_tokens == 0 && o.max_ctx <= 0) {
|
||||
RAD_ERR("--default-max-tokens auto is what the context leaves, and this model states no "
|
||||
"context; pass --max-model-len");
|
||||
RAD_ERR("a request that names no max_tokens gets what the context leaves after its prompt "
|
||||
"(--default-max-tokens auto), and this model states no context; pass "
|
||||
"--max-model-len, or --default-max-tokens N");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
o.max_tokens_cap = cfg_.max_tokens_cap;
|
||||
@@ -2149,6 +2275,13 @@ int Engine::run_server() {
|
||||
"that sends no reasoning effort of its own will be answered 400: %s",
|
||||
cfg_.reasoning_effort.c_str(), eff_why.c_str());
|
||||
}
|
||||
/* A BUDGET THE MODEL CANNOT HOLD STOPS STARTUP, as --chat-template-kwargs does: the default
|
||||
* would apply to no request at all, and the operator who set it would not find out. */
|
||||
if (const std::string why = srv.check_thinking_budget(); !why.empty()) {
|
||||
RAD_ERR("--thinking-token-budget %lld: %s", (long long)cfg_.thinking_token_budget,
|
||||
why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_INFO("serving on http://%s:%d (/v1/completions%s)%s", o.host.c_str(), o.port,
|
||||
d.chat ? "; /v1/chat/completions with tools and reasoning" : "; chat is 501",
|
||||
o.api_key.empty() ? "" : " -- a bearer key is required");
|
||||
|
||||
+42
-4
@@ -22,12 +22,14 @@
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "build/startup.h"
|
||||
#include "mem/hostarena.h"
|
||||
#include "sched/mem_iface.h"
|
||||
#include "sched/scheduler.h"
|
||||
#include "sample/vocab_view.h"
|
||||
#include "runtime/rank_barrier.h"
|
||||
#include "text/tokenizer.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/table_copy.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
@@ -44,6 +46,8 @@ struct TierPump;
|
||||
struct TierJob;
|
||||
struct StepSlot;
|
||||
|
||||
struct VramFacts; /* mem/vram_budget.h */
|
||||
|
||||
class Engine {
|
||||
public:
|
||||
explicit Engine(Config cfg);
|
||||
@@ -115,6 +119,25 @@ private:
|
||||
int read_checkpoint_metadata();
|
||||
int declare();
|
||||
int plan();
|
||||
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
|
||||
* (engine_bringup.cpp says how auto chooses). */
|
||||
int resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes,
|
||||
const std::vector<int64_t>& floor_emb_ram, int64_t kv_floor,
|
||||
int64_t ngram_bytes, bool ngram_device, bool ngram_host);
|
||||
/* --ngram-placement ram: the copy of the container's [src, src + n), file offset `foff`, made
|
||||
* once and shared by every rank -- locked for the host gather, or pinned for a device kernel
|
||||
* to read over the link (`card`). */
|
||||
int copy_table(const uint8_t* src, int64_t n, int64_t foff, bool card, void** out,
|
||||
std::string* why);
|
||||
/* An auto-chosen pinned copy that could not be made: every rank's n-gram gather to the host. */
|
||||
bool ngram_gather_to_host();
|
||||
/* The copies made: the locked ones, each [base, base + bytes); the pinned ones, rad_dev_alloc
|
||||
* RAD_MEM_HOST_MAPPED ranges; and the container address each one copies. Freed in ~Engine
|
||||
* after the ranks that read them are gone. */
|
||||
std::vector<TableCopy> table_copies_;
|
||||
std::vector<void*> card_copies_;
|
||||
std::vector<std::pair<const void*, void*>> table_copy_of_;
|
||||
int load_weights();
|
||||
int configure_kv();
|
||||
/* One sampled row's worth of bookkeeping, so the step loop can map a logits row back to the
|
||||
@@ -285,6 +308,15 @@ private:
|
||||
* and the scheduler's lock is held only around the bookkeeping. */
|
||||
void tier_tick();
|
||||
bool submit_fetch(uint64_t tag, std::vector<TierJob>&& jobs);
|
||||
/* A MARK ON EVERY RANK'S STREAMS, for the disk thread to wait on before it touches a slot:
|
||||
* the transfer streams' when `transfer`, the compute streams' when `compute`, in that order,
|
||||
* one a rank each; `st` is the first failure to make one. destroy_fences gives them back on
|
||||
* their own cards. */
|
||||
std::vector<RadEvent> rank_fences(bool transfer, bool compute, int* st = nullptr);
|
||||
void destroy_fences(std::vector<RadEvent>& f);
|
||||
/* Every host copy that is waiting, issued and landed now. Under the scheduler's lock, from an
|
||||
* eviction that would otherwise erase what the copies cover. True when any landed. */
|
||||
bool flush_copies();
|
||||
uint64_t tier_last_ns_ = 0;
|
||||
/* THE LOAN: what the KV cache is not using, lent to every rank's expert slab at the addresses
|
||||
* the cache already owns (KVManager, the loan block). Here rather than inside the scheduler
|
||||
@@ -306,10 +338,16 @@ private:
|
||||
int64_t arena_floor_ = 0;
|
||||
int64_t arena_last_ = 0;
|
||||
uint64_t arena_floor_ns_ = 0;
|
||||
/* WHETHER THIS DRIVER RETURNS DECOMMITTED VRAM TO THE CARD, for the checkpoint slots -- the
|
||||
* one part of the KV pool still backed on demand. Measured once at the end of bringup; it is
|
||||
* not something the API promises. */
|
||||
bool release_frees_card_ = true;
|
||||
/* WHAT THE VRAM BUDGET KEPT FOR ALLOCATIONS MADE AFTER start(), on top of --gpu-headroom-mib:
|
||||
* the step batch's staging, which serve() allocates, and what is built on first use, if
|
||||
* ever -- the KV tiers' copy staging and the second compute lane's queue. The bringup's
|
||||
* closing reading is checked against both. */
|
||||
int64_t late_step_bytes_ = 0;
|
||||
int64_t late_lazy_bytes_ = 0;
|
||||
/* THE LINEAR-STATE SNAPSHOT STORE: pinned host memory, --checkpoint-slots slots, each holding
|
||||
* every rank's shard of one snapshot (KVManager::set_checkpoint_store). Not on the card: a
|
||||
* snapshot is read by no kernel, only copied back into a sequence's state. */
|
||||
HostArena ck_store_;
|
||||
int run_server();
|
||||
/* THE KL MODE (core/kld.h), in place of run_server: the corpus's documents submitted as
|
||||
* scoring requests, and every step's scored rows copied to the host and handed to `kld_`.
|
||||
|
||||
+804
-150
File diff suppressed because it is too large.
Load diff
@@ -522,6 +522,26 @@ std::string scale_name(const std::string& codes) { return codes + "_scale_inv";
|
||||
|
||||
} /* namespace */
|
||||
|
||||
std::string ckpt_tensor_of(const SrcTensor& t) {
|
||||
const size_t br = t.name.size() && t.name.back() == ']' ? t.name.rfind('[') : std::string::npos;
|
||||
return br == std::string::npos ? t.name : t.name.substr(0, br);
|
||||
}
|
||||
|
||||
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
|
||||
std::unordered_set<std::string>* hit) {
|
||||
bool any = false;
|
||||
for (const auto* list : { &w.pieces, &w.scales })
|
||||
for (const SrcTensor* t : *list) {
|
||||
if (!t) continue;
|
||||
const std::string n = ckpt_tensor_of(*t);
|
||||
if (names.count(n)) {
|
||||
any = true;
|
||||
if (hit) hit->insert(n);
|
||||
}
|
||||
}
|
||||
return any;
|
||||
}
|
||||
|
||||
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
|
||||
CkptWeight* out, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string m) {
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -147,6 +148,15 @@ struct CkptWeight {
|
||||
int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, bool optional,
|
||||
CkptWeight* out, std::string* why);
|
||||
|
||||
/* The checkpoint tensor a piece or scale reads: its name without the "[index]" a slice of a
|
||||
* stacked tensor carries, so an expert reads the stack it was cut from. */
|
||||
std::string ckpt_tensor_of(const SrcTensor& t);
|
||||
|
||||
/* Whether `w` reads any tensor named in `names` (checkpoint names, as ckpt_tensor_of gives them),
|
||||
* through a piece or a scale. Each name it reads is added to `hit` when that is given. */
|
||||
bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>& names,
|
||||
std::unordered_set<std::string>* hit = nullptr);
|
||||
|
||||
/* Logical rows [r0, r0 + nr) of `w` as f32 [nr, cols], whatever the pieces are stored as: a
|
||||
* plain float widened, FP8 times its block scale, a GGUF block type dequantised. */
|
||||
int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::string* why);
|
||||
|
||||
@@ -346,6 +346,56 @@ int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* A SCALE AND THE LEVELS ABOVE IT, without the codes: each first-level scale times every level
|
||||
* that covers it. It is what a kernel that takes its scales as an operand of their own reads
|
||||
* where the encoding states them in two levels -- the scale view of a w4nl64a8h expert, an
|
||||
* E4M3 scale a (row, 64 of K) under one fixed f32 -- and the product is the scale the
|
||||
* reference multiplies, where the first level on its own is that scale off by the second. One
|
||||
* element a first-level scale, in that plane's extents. A level has to cover whole
|
||||
* first-level blocks -- the whole weight, or a block a multiple of the first's -- or a scale
|
||||
* would straddle two of its elements and have no one product. */
|
||||
if (n_sel >= 2 && !std::strcmp(e.plane[sel[0]].role, "scale")) {
|
||||
bool chain = true;
|
||||
for (int k = 0; k < n_sel && chain; ++k) {
|
||||
const RadEncPlane& p = e.plane[sel[k]];
|
||||
chain = p.kind == RAD_PLANE_TILED && rad_enc_role_in_chain(p.role, "scale") &&
|
||||
(k == 0 || std::strcmp(p.role, "scale") != 0);
|
||||
}
|
||||
if (chain) {
|
||||
const RadEncPlane& p0 = e.plane[sel[0]];
|
||||
const int64_t r = rows[0], c = cols[0];
|
||||
if (r * c != n)
|
||||
return refuse("its scales hold " + std::to_string(r * c) + " elements and the "
|
||||
"reader wants " + std::to_string(n));
|
||||
auto covers = [](int64_t b0, int64_t b) { return b <= 0 || (b0 > 0 && b % b0 == 0); };
|
||||
for (int k = 1; k < n_sel; ++k) {
|
||||
const RadEncPlane& p = e.plane[sel[k]];
|
||||
if (!covers(p0.block[0], p.block[0]) || !covers(p0.block[1], p.block[1]))
|
||||
return refuse(std::string("its '") + p.role + "' level does not cover whole '" +
|
||||
p0.role + "' blocks");
|
||||
}
|
||||
const int64_t rb0 = rad_enc_row_bytes(p0.dtype, c);
|
||||
for (int64_t i = 0; i < r; ++i)
|
||||
for (int64_t j = 0; j < c; ++j) {
|
||||
float v = rad_load_f32((const uint8_t*)data[0] + i * rb0, p0.dtype, j);
|
||||
for (int k = 1; k < n_sel; ++k) {
|
||||
const RadEncPlane& p = e.plane[sel[k]];
|
||||
const int64_t li = p.block[0] > 0 ? i * p0.block[0] / p.block[0] : 0;
|
||||
const int64_t lj = p.block[1] > 0 ? j * p0.block[1] / p.block[1] : 0;
|
||||
if (li >= rows[k] || lj >= cols[k])
|
||||
return refuse(std::string("its '") + p.role + "' level is " +
|
||||
std::to_string(rows[k]) + "x" +
|
||||
std::to_string(cols[k]) + " and does not reach scale " +
|
||||
std::to_string(i) + "," + std::to_string(j));
|
||||
v *= rad_load_f32((const uint8_t*)data[k] +
|
||||
li * rad_enc_row_bytes(p.dtype, cols[k]),
|
||||
p.dtype, lj);
|
||||
}
|
||||
rad_store_f32(out, dt, i * c + j, v);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
}
|
||||
if (n_sel != e.n_planes)
|
||||
return refuse("it takes " + std::to_string(n_sel) + " of its encoding's " +
|
||||
std::to_string(e.n_planes) + " planes, which decode to nothing on their own");
|
||||
|
||||
@@ -62,10 +62,11 @@ std::string enc_name(const RadEncoding& e);
|
||||
* `data[k]`, dense [rows[k], cols[k]] in its own elements -- as `n` elements of dtype `dt` at
|
||||
* `out`: the tensor a reference implementation reads where a kernel reads the stored form. One
|
||||
* plane is converted element by element (a bf16 scale plane into an f32 reference, codes as their
|
||||
* values); codes with the scalar codebook they index, each code as its table entry; the whole
|
||||
* encoding is decoded. RAD_OK, or RAD_E_SHAPE with `why` when the planes do not
|
||||
* make that tensor -- part of an encoding, which decodes to nothing on its own, or extents that
|
||||
* disagree with `n`; or the decoder's own refusal. */
|
||||
* values); codes with the scalar codebook they index, each code as its table entry; a scale with
|
||||
* the levels of its chain above it, each scale as their product; the whole encoding is decoded.
|
||||
* RAD_OK, or RAD_E_SHAPE with `why` when the planes do not make that tensor -- part of an
|
||||
* encoding, which decodes to nothing on its own, or extents that disagree with `n`; or the
|
||||
* decoder's own refusal. */
|
||||
int enc_selection_logical(const RadEncoding& e, const int* sel, int n_sel, const int64_t* rows,
|
||||
const int64_t* cols, const void* const* data, uint32_t dt, int64_t n,
|
||||
void* out, std::string* why);
|
||||
|
||||
+16
-2
@@ -38,7 +38,7 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
|
||||
struct VRect { int64_t r0, r1, c0, c1; };
|
||||
std::vector<VRect> view;
|
||||
const bool span = w.shard_hi > 0;
|
||||
const bool span = w.shard_hi > 0 || w.n_part_spans > 0;
|
||||
if (whole) {
|
||||
view.push_back({ 0, VR, 0, VC });
|
||||
} else {
|
||||
@@ -74,7 +74,21 @@ int weight_share(const WeightInfo& w, const RadEncoding& enc, uint32_t rank, con
|
||||
* a slice of EACH of them, not a contiguous slice of the stack. The parts are THIS
|
||||
* RANK'S rows, so a part is `world` times as many rows in the entry. */
|
||||
const int np = w.decl.n_row_parts > 1 ? w.decl.n_row_parts : 1;
|
||||
if (span) {
|
||||
if (w.n_part_spans > 0) {
|
||||
/* PER-PART SPANS: the plugin stated each stacked part's rows in the container
|
||||
* and this rank's [lo, hi) of it, so the parts need not be equal. */
|
||||
if (w.n_part_spans != np)
|
||||
return refuse(fmt("%d per-part spans for %d stacked parts", w.n_part_spans, np));
|
||||
int64_t sum = 0, soff = 0;
|
||||
for (int g = 0; g < np; ++g) sum += w.part_total[g];
|
||||
if (sum != VR)
|
||||
return refuse(fmt("the %d stacked parts' stated rows sum to %lld and the entry "
|
||||
"has %lld", np, (long long)sum, (long long)VR));
|
||||
for (int g = 0; g < np; ++g) {
|
||||
view.push_back({ soff + w.part_lo[g], soff + w.part_hi[g], 0, VC });
|
||||
soff += w.part_total[g];
|
||||
}
|
||||
} else if (span) {
|
||||
if (VR % np) return refuse(fmt("%lld rows do not divide into %d parts",
|
||||
(long long)VR, np));
|
||||
const int64_t cpart = VR / np;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
/* table_copy.cpp -- see table_copy.h. */
|
||||
#include "table_copy.h"
|
||||
|
||||
#include "../rad_internal.h"
|
||||
|
||||
#include <sys/mman.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
uint8_t* buf, std::string* why) {
|
||||
if (!why || !src || !buf || n <= 0) return RAD_E_INVAL;
|
||||
const int64_t huge = (int64_t)2 << 20;
|
||||
|
||||
/* A reader per hardware thread up to sixteen, each reading its own contiguous span in pieces of
|
||||
* 64 MiB: a drive serves sixteen queued reads at full rate, and the span keeps each reader's
|
||||
* reads sequential on the file. */
|
||||
const int nt = (int)std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
|
||||
const int64_t piece = (int64_t)64 << 20;
|
||||
const int64_t span = ((n + nt - 1) / nt + huge - 1) & ~(huge - 1);
|
||||
std::atomic<int> err{RAD_OK};
|
||||
std::vector<std::thread> rd;
|
||||
for (int i = 0; i < nt; ++i) {
|
||||
const int64_t lo = (int64_t)i * span, hi = std::min(n, lo + span);
|
||||
if (lo >= hi) break;
|
||||
rd.emplace_back([&, lo, hi] {
|
||||
for (int64_t o = lo; o < hi && err.load() == RAD_OK; o += piece) {
|
||||
const int64_t b = std::min(piece, hi - o);
|
||||
const int rc = file.read_at(buf + o, b, foff + o);
|
||||
if (rc < 0) { err.store(rc); return; }
|
||||
file.drop_range(foff + o, b);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (std::thread& t : rd) t.join();
|
||||
|
||||
if (err.load() != RAD_OK) {
|
||||
*why = fmt("reading the container failed (%s)", rad_strerror(err.load()));
|
||||
return RAD_E_IO;
|
||||
}
|
||||
const int64_t probe = std::min<int64_t>(n, 4096);
|
||||
bool same = std::memcmp(buf, src, (size_t)probe) == 0 &&
|
||||
std::memcmp(buf + n - probe, src + n - probe, (size_t)probe) == 0;
|
||||
for (int64_t o = 0; same && o + 4096 <= n; o += std::max<int64_t>(n / 64, 4096))
|
||||
same = std::memcmp(buf + o, src + o, 4096) == 0;
|
||||
if (!same) {
|
||||
*why = "the copy does not match the container's mapping";
|
||||
return RAD_E_IO;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
TableCopy* out, std::string* why) {
|
||||
if (!out || !why || !src || n <= 0) return RAD_E_INVAL;
|
||||
*out = TableCopy{};
|
||||
const size_t huge = (size_t)2 << 20;
|
||||
const size_t sz = ((size_t)n + huge - 1) & ~(huge - 1);
|
||||
void* m = ::mmap(nullptr, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
|
||||
-1, 0);
|
||||
if (m == MAP_FAILED) {
|
||||
*why = fmt("mmap of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
(void)::madvise(m, sz, MADV_HUGEPAGE);
|
||||
if (::mlock2(m, sz, MLOCK_ONFAULT) != 0) {
|
||||
*why = fmt("mlock2 of %s: %s", humanb((int64_t)sz).c_str(), std::strerror(errno));
|
||||
::munmap(m, sz);
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
const int rc = table_copy_fill(file, src, n, foff, static_cast<uint8_t*>(m), why);
|
||||
if (rc != RAD_OK) {
|
||||
::munlock(m, sz);
|
||||
::munmap(m, sz);
|
||||
return rc;
|
||||
}
|
||||
out->base = m;
|
||||
out->bytes = sz;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void table_copy_free(TableCopy* c) {
|
||||
if (!c || !c->base) return;
|
||||
::munlock(c->base, c->bytes);
|
||||
::munmap(c->base, c->bytes);
|
||||
*c = TableCopy{};
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,41 @@
|
||||
/* table_copy.h -- a container table copied into host memory (--ngram-placement ram): locked memory
|
||||
* for the host gather, made here, or pinned memory a card reads, which the caller allocates and
|
||||
* table_copy_fill fills. What follows is about the locked copy; the read and the check are both's.
|
||||
*
|
||||
* A COPY IN HUGE PAGES, NOT THE MAPPING LOCKED. Faulting a container's mapping in costs a fault every
|
||||
* 4 KiB page and leaves every row behind a 4 KiB translation, so a gather of scattered rows walks
|
||||
* the page tables on nearly every row; an anonymous MADV_HUGEPAGE region covers thousands of rows a
|
||||
* page. The region is locked as each page is first touched (MLOCK_ONFAULT), so nothing filled is
|
||||
* swapped out while the rest fills; it is read from the container by parallel positional reads, the
|
||||
* container's pages dropped behind them so the table is not held twice; and it is checked against
|
||||
* the mapping before anyone is handed it, because a wrong offset would serve every row from the
|
||||
* wrong place without an error. A host kernel reads an address no file backs as the memory it is
|
||||
* (libavx's table_file), so no plugin takes part. */
|
||||
#pragma once
|
||||
#include "radfile.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct TableCopy {
|
||||
void* base = nullptr;
|
||||
size_t bytes = 0; /* the mapping's length: the table rounded up to 2 MiB */
|
||||
};
|
||||
|
||||
/* Copies [src, src + n) of `file`'s mapping, which lies at file offset `foff`, into a new locked
|
||||
* region. RAD_OK with `out` filled, or a refusal with `why` saying what failed and nothing held. */
|
||||
int table_copy_make(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
TableCopy* out, std::string* why);
|
||||
|
||||
/* The read and the check table_copy_make makes, into [dst, dst + n) the caller allocated: pinned
|
||||
* memory a card reads in place, when a device kernel gathers the table (--ngram-placement ram). */
|
||||
int table_copy_fill(const RadFile& file, const uint8_t* src, int64_t n, int64_t foff,
|
||||
uint8_t* dst, std::string* why);
|
||||
|
||||
/* Unlocks and unmaps it; a copy never made is a no-op. */
|
||||
void table_copy_free(TableCopy* c);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,88 @@
|
||||
/* hostarena.cpp -- see hostarena.h. */
|
||||
#include "mem/hostarena.h"
|
||||
|
||||
#include "rad_internal.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
HostArena::~HostArena() { close(); }
|
||||
|
||||
int HostArena::open(int64_t slot_bytes, int64_t cap_bytes) {
|
||||
close();
|
||||
if (slot_bytes <= 0 || cap_bytes < slot_bytes) return RAD_E_INVAL;
|
||||
const int64_t n = cap_bytes / slot_bytes;
|
||||
/* PINNED, and the allocation is refused rather than downgraded. A pageable host buffer on
|
||||
* this path does not fail, it just collapses -- an async copy to pageable memory serialises
|
||||
* against the stream and the whole point of moving instead of dropping is gone. Better to
|
||||
* start without the store and say so than to run it at a tenth of the rate it was budgeted
|
||||
* at. */
|
||||
base_ = rad_dev_alloc(n * slot_bytes, RAD_MEM_HOST_PINNED);
|
||||
if (!base_) return RAD_E_NOMEM;
|
||||
slot_bytes_ = slot_bytes;
|
||||
used_ = 0;
|
||||
cap_slots_ = n;
|
||||
cursor_ = 0;
|
||||
bits_.assign((size_t)((n + 63) / 64), 0ull);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void HostArena::close() {
|
||||
if (base_) rad_dev_free(base_, RAD_MEM_HOST_PINNED);
|
||||
base_ = nullptr;
|
||||
slot_bytes_ = 0;
|
||||
used_ = 0;
|
||||
cap_slots_ = 0;
|
||||
cursor_ = 0;
|
||||
bits_.clear();
|
||||
}
|
||||
|
||||
int32_t HostArena::alloc() {
|
||||
int32_t got = 0;
|
||||
return alloc_run(1, &got);
|
||||
}
|
||||
|
||||
/* THE FIRST FREE RUN AT OR AFTER THE CURSOR, wrapping once. A whole word of used slots is skipped
|
||||
* in one compare, so a nearly full arena costs a scan of its bitmap -- a few thousand words at the
|
||||
* sizes an operator gives this -- and an arena with room costs nothing. The cursor makes
|
||||
* consecutive calls hand out consecutive slots, which is what lets a batch be one copy a run. */
|
||||
int32_t HostArena::alloc_run(int32_t want, int32_t* got) {
|
||||
*got = 0;
|
||||
if (want <= 0 || !base_ || full()) return -1;
|
||||
int64_t s = -1;
|
||||
for (int pass = 0; pass < 2 && s < 0; ++pass) {
|
||||
const int64_t lo = pass == 0 ? cursor_ : 0;
|
||||
const int64_t hi = pass == 0 ? cap_slots_ : cursor_;
|
||||
for (int64_t i = lo; i < hi;) {
|
||||
const uint64_t w = bits_[(size_t)(i >> 6)];
|
||||
if ((i & 63) == 0 && w == ~0ull) { i += 64; continue; }
|
||||
if (!is_used(i)) { s = i; break; }
|
||||
++i;
|
||||
}
|
||||
}
|
||||
if (s < 0) return -1;
|
||||
int64_t n = 0;
|
||||
while (n < want && s + n < cap_slots_ && !is_used(s + n)) {
|
||||
bits_[(size_t)((s + n) >> 6)] |= 1ull << ((s + n) & 63);
|
||||
++n;
|
||||
}
|
||||
used_ += n;
|
||||
cursor_ = s + n >= cap_slots_ ? 0 : s + n;
|
||||
*got = (int32_t)n;
|
||||
return (int32_t)s;
|
||||
}
|
||||
|
||||
void HostArena::free(int32_t slot) {
|
||||
if (slot < 0 || slot >= cap_slots_) return;
|
||||
/* A slot that is already free is refused rather than counted twice: the used count is what the
|
||||
* sessions view reports and what `full` answers, and a negative one hides the next leak. */
|
||||
if (!is_used(slot)) return;
|
||||
bits_[(size_t)(slot >> 6)] &= ~(1ull << (slot & 63));
|
||||
--used_;
|
||||
}
|
||||
|
||||
void* HostArena::at(int32_t slot) const {
|
||||
if (!base_ || slot < 0 || slot >= cap_slots_) return nullptr;
|
||||
return (char*)base_ + (int64_t)slot * slot_bytes_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,63 @@
|
||||
/* hostarena.h -- fixed-size slots of pinned host memory.
|
||||
*
|
||||
* Two stores are built from it: the KV tiers' block arena (core/mem/kvtier.h), where one slot is
|
||||
* one cache entry, and the linear-state snapshot store (KVManager::set_checkpoint_store), where
|
||||
* one slot is one snapshot. Under tensor parallelism a slot holds EVERY rank's shard of its
|
||||
* object, each rank at its own offset, so the disk store can read and write it as one payload.
|
||||
*
|
||||
* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
|
||||
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
|
||||
* synchronises. Slot-allocated at one fixed size rather than malloc'd per object: every object a
|
||||
* store holds is the same size for a given model, so a bitmap is the whole allocator.
|
||||
*
|
||||
* RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
|
||||
* thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
|
||||
* the call rate, not the link, is then what a restore costs. Slots taken together are given
|
||||
* consecutive ids wherever the arena has them, so a batch crosses the link as one strided copy
|
||||
* a run. */
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class HostArena {
|
||||
public:
|
||||
~HostArena();
|
||||
int open(int64_t slot_bytes, int64_t cap_bytes);
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
int64_t slot_bytes() const { return slot_bytes_; }
|
||||
/* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
|
||||
* HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
|
||||
int64_t capacity() const { return cap_slots_; }
|
||||
int64_t used_slots() const { return used_; }
|
||||
int64_t cap_bytes() const { return slot_bytes_ * capacity(); }
|
||||
int64_t free_slots() const { return cap_slots_ - used_; }
|
||||
|
||||
/* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
|
||||
* because the policy that would choose them lives with the store's owner and an allocator
|
||||
* that reached into it would give each object two owners. */
|
||||
bool full() const { return used_ >= cap_slots_; }
|
||||
int32_t alloc();
|
||||
/* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
|
||||
* many; the caller asks again for the rest. -1 when the arena is full. */
|
||||
int32_t alloc_run(int32_t want, int32_t* got);
|
||||
void free(int32_t slot);
|
||||
bool in_use(int32_t slot) const { return slot >= 0 && slot < cap_slots_ && is_used(slot); }
|
||||
void* at(int32_t slot) const;
|
||||
|
||||
private:
|
||||
bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; }
|
||||
void* base_ = nullptr;
|
||||
int64_t slot_bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
int64_t cap_slots_ = 0;
|
||||
int64_t cursor_ = 0;
|
||||
std::vector<uint64_t> bits_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+154
-251
@@ -100,7 +100,8 @@ int KVManager::configure(const std::vector<KVGroupInfo>& groups, const Config& c
|
||||
}
|
||||
|
||||
int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg) {
|
||||
/* The snapshot count is the operator's, through --checkpoint-slots. Nothing here derives it. */
|
||||
/* Only to say it is ignored on a model with no recurrent state: the slots are host memory and
|
||||
* the engine opens them (set_checkpoint_store). */
|
||||
const int64_t budget_ckpts = cfg.checkpoint_slots > 0 ? cfg.checkpoint_slots : 0;
|
||||
|
||||
forget();
|
||||
@@ -191,8 +192,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
* a change of read offset rather than a recompute (spec §10). The engine's
|
||||
* contract is that the kernel pair supports that; the manager's job is to make the
|
||||
* slot big enough for it. */
|
||||
p.conv_slots = (g.decl.conv_width > 0 ? g.decl.conv_width - 1 : 0)
|
||||
+ (cfg.n_spec > 0 ? cfg.n_spec : 0);
|
||||
p.conv_slots = conv_window_entries(g.decl, cfg.n_spec);
|
||||
if (p.conv_slots <= 0) {
|
||||
RAD_ERR("KV group '%s': conv_width %lld with n_spec %d gives 0 slots",
|
||||
p.name.c_str(), (long long)g.decl.conv_width, cfg.n_spec);
|
||||
@@ -231,6 +231,24 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
RAD_ERR("KV group '%s': per-sequence state computes to 0", p.name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* THE SLOT THE KERNELS INDEX, which is the slot this manager has to hand out. The
|
||||
* kernels lay slots out from the state tensor ([n_states, channels, conv_slots] or
|
||||
* [n_states, n_head_kv, state_dim]); this manager lays them out from bytes_per_state,
|
||||
* and clears, saves and restores slots in that layout. Two different sizes make every
|
||||
* one of those touch a neighbouring sequence's state. */
|
||||
const int64_t indexed =
|
||||
(p.kind == RAD_KV_CONV
|
||||
? p.conv_slots * g.decl.n_head_kv * g.decl.head_dim
|
||||
: g.decl.n_head_kv * g.decl.state_dim[0] * g.decl.state_dim[1])
|
||||
* elt * p.n_layers;
|
||||
if (p.bytes_per_state != indexed) {
|
||||
RAD_ERR("KV group '%s': %lld bytes a sequence are allocated, and the state the "
|
||||
"kernels index is %lld bytes over its %lld layers -- the slot this manager "
|
||||
"clears, checkpoints and restores would not be the slot the kernels read",
|
||||
p.name.c_str(), (long long)p.bytes_per_state, (long long)indexed,
|
||||
(long long)p.n_layers);
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
/* Exactly one slot per concurrent sequence, times whatever the kernel needs beside
|
||||
* it. Not a heuristic: a sequence owns exactly one recurrent state, so max_seqs is
|
||||
* the count of LOGICAL states, full stop. */
|
||||
@@ -239,6 +257,14 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
RAD_ERR("KV group '%s': unknown kind %d", p.name.c_str(), p.kind);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A ZERO GROUP COSTS THIS RANK NOTHING: declared for its position and its block count,
|
||||
* never carved, never read. The validation above still ran on the real sizes, so a zero
|
||||
* group is a real group on every other rank. */
|
||||
if (g.zero) {
|
||||
p.zero = true;
|
||||
p.bytes_per_block = 0;
|
||||
p.bytes_per_state = 0;
|
||||
}
|
||||
plans_.push_back(std::move(p));
|
||||
}
|
||||
bundling_ = compare_bundling(bundles);
|
||||
@@ -260,37 +286,12 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
int64_t fixed = 0;
|
||||
for (const auto& p : plans_)
|
||||
if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
|
||||
/* A SLOT IS ELASTIC ONLY WHEN A SNAPSHOT IS WORTH A GRANULE, and the stride follows from
|
||||
* that. Committing and releasing a slot on its own needs the stride to be a whole number of
|
||||
* granules: a commit rounds outward and a release rounds inward, so a straddling stride
|
||||
* would leave every slot's last partial granule backed for the life of the process and let
|
||||
* one slot's commit back part of its neighbour.
|
||||
*
|
||||
* That rounding is free on a linear-attention model, where a snapshot is a sizeable fraction
|
||||
* of a gigabyte. It is not free on a small one: a 16 KiB snapshot rounded to a 2 MiB granule
|
||||
* is 128x the address space to manage a charge that was never worth managing. Below a
|
||||
* granule the slots stay in the eagerly committed region, where they cost what they say
|
||||
* they cost and nothing reclaims them because there is nothing to reclaim. */
|
||||
const int64_t granule = Pool::granule();
|
||||
ck_elastic_ = granule > 0 && checkpoint_bytes_ >= granule;
|
||||
ck_stride_ = align_up(checkpoint_bytes_, ck_align());
|
||||
/* AND THE PAD IN FRONT OF THE REGION IS PART OF ITS COST. The slots are reserved LAST, after
|
||||
* every group, and on a ck_align() boundary -- so the region starts up to one alignment unit
|
||||
* past wherever the groups happened to end. Where that is cannot be known here, because the
|
||||
* paged split below is what decides it, so the whole unit is reserved rather than the exact
|
||||
* pad: it is at most one commit granule against a pool measured in gigabytes, and the
|
||||
* alternative is a budget the LAST slot falls off the end of -- a refusal at load on some
|
||||
* models and not others, depending on where the groups happened to end. */
|
||||
const int64_t ck_pad = budget_ckpts > 0 ? ck_align() : 0;
|
||||
const int64_t ck_total = budget_ckpts * ck_stride_ + ck_pad;
|
||||
fixed += ck_total;
|
||||
/* And one unit a paged group, for the same reason: a page size that is not a multiple of the
|
||||
* alignment pads too, and the carve below hands the groups everything that is left. */
|
||||
for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
|
||||
|
||||
fixed_ = fixed;
|
||||
ck_total_ = ck_total;
|
||||
ckpts_ = budget_ckpts;
|
||||
fixed_ = fixed;
|
||||
ckpts_ = budget_ckpts;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -336,58 +337,44 @@ void KVManager::forget() {
|
||||
chunk_blocks_.clear(); short_peak_.clear();
|
||||
pool_ = nullptr;
|
||||
clears_.clear();
|
||||
seqs_.clear(); pending_.clear(); ck_slot_base_.clear(); ck_free_.clear();
|
||||
ck_stride_ = ck_region_off_ = 0;
|
||||
ck_elastic_ = false;
|
||||
ck_high_water_ = 0;
|
||||
ck_backed_ = 0;
|
||||
seqs_.clear(); pending_.clear();
|
||||
configured_ = false;
|
||||
report_.clear();
|
||||
}
|
||||
|
||||
int KVManager::carve_into(Pool& kv_pool) {
|
||||
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
|
||||
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
const int64_t budget_bytes = kv_pool.avail();
|
||||
const int64_t budget_ckpts = ckpts_;
|
||||
const int64_t fixed = fixed_;
|
||||
const int64_t ck_total = ck_total_;
|
||||
pool_base_ = kv_pool.base();
|
||||
pool_ = &kv_pool;
|
||||
|
||||
if (fixed >= budget_bytes) {
|
||||
RAD_ERR("vram_kv does not fit its fixed costs:\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" checkpoints %10s (%lld x %s)\n"
|
||||
" ------------------------------\n"
|
||||
" fixed %10s\n"
|
||||
" --vram-kv-mib %10s\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --max-seqs or the checkpoint slot count, or raise --vram-kv-mib. "
|
||||
"The engine will not shrink one of them for you (spec §6).",
|
||||
humanb(fixed - ck_total).c_str(), (long long)max_seqs_,
|
||||
humanb(ck_total).c_str(), (long long)budget_ckpts,
|
||||
humanb(ck_stride_).c_str(),
|
||||
humanb(fixed).c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* blocks) const {
|
||||
/* Not a policy: size the groups to exhaust at the same total token count. Any other split
|
||||
* strands memory in whichever group outlasts the others, and a long-context server would then
|
||||
* run out of full-attention blocks with a window pool still half empty. */
|
||||
std::vector<int64_t> out(plans_.size(), 0);
|
||||
int64_t remaining = budget_bytes - fixed_;
|
||||
/* A ZERO GROUP COSTS THIS RANK NOTHING, so it takes no part in the split: it holds the
|
||||
* shared table's block count, which is what the costed groups settle on (here, or under the
|
||||
* cap, on the rank that does hold the cache). */
|
||||
std::vector<int32_t> open, zeros;
|
||||
for (const auto& p : plans_)
|
||||
if (p.paged()) (p.zero ? zeros : open).push_back(p.index);
|
||||
/* Every paged group zero: nothing on this rank limits the token count. The cap is what the
|
||||
* ranks that hold the cache carve, and without one there is no figure to report. */
|
||||
if (open.empty() && !zeros.empty()) {
|
||||
const int64_t tokens = tokens_cap_ > 0 ? tokens_cap_ : kUnboundedTokens;
|
||||
if (blocks) {
|
||||
for (int32_t i : zeros) out[i] = zero_blocks(plans_[i], tokens);
|
||||
*blocks = std::move(out);
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/* ---- the paged split. Not a policy: size the groups to exhaust at the same total token
|
||||
* count. Any other split strands memory in whichever group outlasts the others, and a
|
||||
* long-context server would then run out of full-attention blocks with a window pool still
|
||||
* half empty. ---- */
|
||||
int64_t remaining = budget_bytes - fixed;
|
||||
std::vector<int32_t> open;
|
||||
for (auto& p : plans_) if (p.paged()) open.push_back(p.index);
|
||||
|
||||
int64_t tokens = 0;
|
||||
while (!open.empty()) {
|
||||
while (!open.empty() && remaining > 0) {
|
||||
double cost = 0;
|
||||
for (int32_t i : open)
|
||||
cost += (double)plans_[i].bytes_per_block / (double)plans_[i].block_size;
|
||||
if (cost <= 0) break;
|
||||
tokens = (int64_t)((double)remaining / cost);
|
||||
/* ONE BLOCK TABLE SERVES EVERY RANK (Engine::serve checks it), so a rank with more pool
|
||||
* than its peers carves no more than the least of them. */
|
||||
if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_;
|
||||
|
||||
/* A windowed group cannot use more than window_blocks per sequence; anything past that
|
||||
* is memory nobody will ever address. Cap it and give the bytes back to the others. */
|
||||
@@ -398,18 +385,61 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; }
|
||||
}
|
||||
if (capped < 0) break;
|
||||
plans_[capped].n_blocks = max_seqs_ * plans_[capped].window_blocks;
|
||||
remaining -= plans_[capped].n_blocks * plans_[capped].bytes_per_block;
|
||||
out[capped] = max_seqs_ * plans_[capped].window_blocks;
|
||||
remaining -= out[capped] * plans_[capped].bytes_per_block;
|
||||
open.erase(std::find(open.begin(), open.end(), capped));
|
||||
}
|
||||
for (int32_t i : open) plans_[i].n_blocks = tokens / plans_[i].block_size;
|
||||
for (int32_t i : open) out[i] = remaining > 0 ? tokens / plans_[i].block_size : 0;
|
||||
for (int32_t i : zeros) out[i] = remaining > 0 ? zero_blocks(plans_[i], tokens) : 0;
|
||||
if (blocks) *blocks = std::move(out);
|
||||
return tokens;
|
||||
}
|
||||
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks;
|
||||
return b;
|
||||
}
|
||||
|
||||
int KVManager::carve_into(Pool& kv_pool) {
|
||||
/* The pool is whatever the operator stated or the resolver derived; nothing here re-decides
|
||||
* it. What this does decide is how the groups share it, which is arithmetic, not policy. */
|
||||
const int64_t budget_bytes = kv_pool.avail();
|
||||
const int64_t fixed = fixed_;
|
||||
pool_base_ = kv_pool.base();
|
||||
pool_ = &kv_pool;
|
||||
|
||||
if (fixed >= budget_bytes) {
|
||||
RAD_ERR("vram_kv does not fit its fixed costs:\n"
|
||||
" linear/conv state %10s (%lld sequences)\n"
|
||||
" --vram-kv-mib %10s\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --max-seqs or raise --vram-kv-mib. The engine will not shrink one of them "
|
||||
"for you (spec §6).",
|
||||
humanb(fixed).c_str(), (long long)max_seqs_, humanb(budget_bytes).c_str(),
|
||||
humanb(fixed - budget_bytes + 1).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
/* ---- the paged split (paged_split below): every rank's share of it is the same arithmetic,
|
||||
* and under a cap it is the least rank's. ---- */
|
||||
std::vector<int64_t> blocks;
|
||||
(void)paged_split(budget_bytes, &blocks);
|
||||
for (auto& p : plans_) if (p.paged()) p.n_blocks = blocks[p.index];
|
||||
|
||||
for (auto& p : plans_) {
|
||||
if (!p.paged()) continue;
|
||||
if (p.n_blocks <= 0 && p.zero) {
|
||||
RAD_ERR("KV group '%s' is zero on this rank and nothing set its block count: a zero "
|
||||
"group holds what the ranks keeping the cache carve, and no cap from them was "
|
||||
"given (cap_paged_tokens)", p.name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (p.n_blocks <= 0) {
|
||||
RAD_ERR("KV group '%s': a %s KV pool leaves 0 blocks (%s a page) after the fixed "
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib, lower --expert-vs-cache-ratio, "
|
||||
"or lower --max-seqs.",
|
||||
"linear/conv costs of %s. Raise --vram-kv-mib or --host-pool-mib, or lower "
|
||||
"--max-seqs.",
|
||||
p.name.c_str(), humanb(budget_bytes).c_str(),
|
||||
humanb(p.bytes_per_block).c_str(), humanb(fixed).c_str());
|
||||
return RAD_E_NOMEM;
|
||||
@@ -418,11 +448,18 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
|
||||
/* ---- carve. Every reservation comes from the KV pool and only from the KV pool: the mover
|
||||
* works inside the weight slab and cannot reach this (spec §6). ---- */
|
||||
int64_t paged_taken = 0;
|
||||
for (auto& p : plans_) {
|
||||
int64_t bytes = p.paged() ? p.n_blocks * p.bytes_per_block
|
||||
: p.n_states * p.bytes_per_state;
|
||||
if (p.paged()) paged_taken += bytes;
|
||||
if (p.zero) {
|
||||
p.base = nullptr;
|
||||
p.pool_offset = 0;
|
||||
p.pool_bytes = 0;
|
||||
RAD_INFO("KV group '%s': this rank keeps no cache for it (rad_kv_group_zero) -- %lld "
|
||||
"blocks of the shared table, nothing carved", p.name.c_str(),
|
||||
(long long)p.n_blocks);
|
||||
continue;
|
||||
}
|
||||
int64_t off = 0;
|
||||
void* ptr = kv_pool.reserve(p.name, bytes, RAD_ALIGN_UNIT, &off);
|
||||
if (!ptr && !kv_pool.accounting_only()) {
|
||||
@@ -434,30 +471,11 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
p.pool_offset = off;
|
||||
p.pool_bytes = bytes;
|
||||
}
|
||||
/* --checkpoint-slots on a model with no recurrent state buys nothing, and allocating zero-byte
|
||||
/* --checkpoint-slots on a model with no recurrent state buys nothing, and opening zero-byte
|
||||
* slots for it would leave the operator's flag looking honoured. Ignore it and say so. */
|
||||
if (budget_ckpts > 0 && checkpoint_bytes_ <= 0)
|
||||
if (ckpts_ > 0 && checkpoint_bytes_ <= 0)
|
||||
RAD_WARN("--checkpoint-slots %lld ignored: this model declares no linear-attention state, "
|
||||
"so there is nothing to snapshot", (long long)budget_ckpts);
|
||||
for (int64_t i = 0; checkpoint_bytes_ > 0 && i < budget_ckpts; ++i) {
|
||||
int64_t off = 0;
|
||||
if (!kv_pool.reserve("linear checkpoint", ck_stride_, ck_align(), &off)
|
||||
&& !kv_pool.accounting_only()) {
|
||||
/* The arithmetic that is supposed to make this impossible, printed next to the
|
||||
* failure: `fixed` reserved budget_ckpts * checkpoint_bytes_ up front, so a checkpoint
|
||||
* that does not fit means the paged carve above spent more than `remaining`. */
|
||||
RAD_ERR("linear checkpoint slot %lld (%lld B) did not fit the KV pool: %lld B of "
|
||||
"%lld B left after the paged groups took %lld B against a %lld B share",
|
||||
(long long)i, (long long)checkpoint_bytes_,
|
||||
(long long)kv_pool.avail(), (long long)budget_bytes,
|
||||
(long long)paged_taken, (long long)(budget_bytes - fixed));
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
if (i == 0) ck_region_off_ = off;
|
||||
ck_slot_base_.push_back(off);
|
||||
ck_free_.push_back((int32_t)i);
|
||||
}
|
||||
std::reverse(ck_free_.begin(), ck_free_.end()); /* pop_back hands out slot 0 first */
|
||||
"so there is nothing to snapshot", (long long)ckpts_);
|
||||
|
||||
/* ---- free lists ---- */
|
||||
free_blocks_.resize(plans_.size());
|
||||
@@ -495,36 +513,13 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
*
|
||||
* The fixed part -- recurrent state and conv slots -- is never released. It is sized per
|
||||
* sequence rather than per token, so there is no idle fraction of it to give back, and a
|
||||
* state slot cannot be re-created on demand the way a page can.
|
||||
*
|
||||
* CHECKPOINT SLOTS ARE NOT PART OF THAT. They are a CACHE -- the retention policy creates and
|
||||
* retires them all run, and a slot nobody has taken holds nothing that has to survive -- so
|
||||
* backing them all here would make --checkpoint-slots a standing VRAM charge whether or not a
|
||||
* snapshot exists. On a linear-attention model a slot is a sizeable fraction of a gigabyte,
|
||||
* and on a card whose experts do not fit that charge is decode step time. The region is left
|
||||
* unbacked and each slot is committed as it is handed out, which makes the flag a cap. */
|
||||
* state slot cannot be re-created on demand the way a page can. */
|
||||
if (pool_ && pool_->elastic()) {
|
||||
/* EVERYTHING EXCEPT THE CHECKPOINT REGION. The slots are reserved last, so the
|
||||
* second range is empty and this is a prefix -- written as a hole anyway, because
|
||||
* "commit everything below the slots" is the rule and "the slots are at the end" is a
|
||||
* detail of the carve above that nothing here should depend on. A prefix that stopped at
|
||||
* a region in the MIDDLE would leave every group past it addressable and unbacked, and
|
||||
* the paged groups are live from the first step: a fault at a valid-looking address on
|
||||
* the first write, which is the worst shape this class of bug has.
|
||||
*
|
||||
* Both edges are granule-aligned by construction (the slot reserve asks for ck_align()
|
||||
* and the stride is a whole number of granules), so neither commit rounds outward into
|
||||
* the region. That alignment is the whole reason it can be skipped at all. */
|
||||
const int64_t used = pool_->used();
|
||||
const int64_t hole_off = ck_elastic_ && !ck_slot_base_.empty() ? ck_region_off_ : used;
|
||||
const int64_t hole_end = ck_elastic_ && !ck_slot_base_.empty()
|
||||
? ck_slot_base_.back() + ck_stride_
|
||||
: used;
|
||||
int rc = pool_->commit(0, hole_off);
|
||||
if (rc >= 0 && used > hole_end) rc = pool_->commit(hole_end, used - hole_end);
|
||||
const int64_t used = pool_->used();
|
||||
const int rc = pool_->commit(0, used);
|
||||
if (rc < 0) {
|
||||
RAD_ERR("KV pool: the carve reserved %s of address space and the card would not back "
|
||||
"it", humanb(used - (hole_end - hole_off)).c_str());
|
||||
"it", humanb(used).c_str());
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
@@ -571,19 +566,12 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
}
|
||||
/* WHERE EACH GROUP STARTS, SO A FAULT ADDRESS CAN BE PLACED. A GPU memory fault names an
|
||||
* address and nothing else, and without this the only way to tell "kv_attn layer 7" from
|
||||
* "checkpoint slot 3" is to reconstruct the carve by hand from the sizes above. One line. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld, checkpoints at +%lld\n",
|
||||
* "kv_gdn_state slot 3" is to reconstruct the carve by hand from the sizes above. One line. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n",
|
||||
pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
|
||||
(long long)(plans_.size() > 1 ? plans_[1].pool_offset : 0),
|
||||
(long long)(plans_.empty() ? 0 : plans_.back().pool_offset +
|
||||
plans_.back().pool_bytes),
|
||||
(long long)(ck_slot_base_.empty() ? 0 : ck_slot_base_.front()));
|
||||
if (checkpoint_bytes_ > 0)
|
||||
report_ += fmt(
|
||||
" %-14s %-6s %lld slots x %s = %s%s\n", "checkpoints", "linear",
|
||||
(long long)ck_slot_base_.size(), humanb(ck_stride_).c_str(),
|
||||
humanb((int64_t)ck_slot_base_.size() * ck_stride_).c_str(),
|
||||
ck_elastic_ ? " (address space; backed as slots are taken)" : "");
|
||||
plans_.back().pool_bytes));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -734,73 +722,6 @@ int64_t KVManager::buffer_bytes() const {
|
||||
return b;
|
||||
}
|
||||
|
||||
int64_t KVManager::ck_reserve_bytes() const {
|
||||
if (!ck_elastic_ || ck_stride_ <= 0) return 0;
|
||||
/* Counted from what is BACKED and not from the free list, because a rank that is not the one
|
||||
* holding the free list still backs the slots it writes, and its reserve has to cover them. */
|
||||
const int64_t want = std::min(ckpts_, ck_high_water_ + 1);
|
||||
return want > ck_backed_ ? (want - ck_backed_) * ck_stride_ : 0;
|
||||
}
|
||||
|
||||
bool KVManager::ck_backed(int32_t slot) const {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return false;
|
||||
if (!ck_elastic_ || !pool_ || !pool_->elastic() || ck_stride_ <= 0) return true;
|
||||
return pool_->is_committed(ck_slot_base_[(size_t)slot], ck_stride_);
|
||||
}
|
||||
|
||||
int KVManager::ck_room(int32_t slot) const {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL;
|
||||
if (ck_backed(slot) || !ck_free_bytes_ || ck_keep_free_ <= 0) return RAD_OK;
|
||||
int64_t free_now = 0;
|
||||
RAD_TRY(ck_free_bytes_(&free_now));
|
||||
return free_now - ck_stride_ >= ck_keep_free_ ? RAD_OK : RAD_E_FULL;
|
||||
}
|
||||
|
||||
int KVManager::ck_commit(int32_t slot) {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return RAD_E_INVAL;
|
||||
if (ck_backed(slot)) return RAD_OK;
|
||||
if (pool_->commit(ck_slot_base_[(size_t)slot], ck_stride_) < 0) return RAD_E_FULL;
|
||||
if (++ck_backed_ > ck_high_water_) ck_high_water_ = ck_backed_;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int KVManager::back_checkpoint(int32_t slot) {
|
||||
RAD_TRY(ck_room(slot));
|
||||
return ck_commit(slot);
|
||||
}
|
||||
|
||||
/* EVERY CARD'S ANSWER BEFORE ANY CARD'S PAGES. Asking first means a slot one card refuses costs
|
||||
* the others nothing: on a driver that keeps what it maps, pages committed for a slot that is then
|
||||
* not handed out would be charged to that card for the life of the process. */
|
||||
int KVManager::ck_back_everywhere(int32_t slot) {
|
||||
RAD_TRY(ck_room(slot));
|
||||
for (KVManager* p : ck_peers_) RAD_TRY(p->ck_room(slot));
|
||||
RAD_TRY(ck_commit(slot));
|
||||
for (KVManager* p : ck_peers_) RAD_TRY(p->ck_commit(slot));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int KVManager::back_free_checkpoints(int64_t* withdrawn) {
|
||||
std::vector<int32_t> keep;
|
||||
keep.reserve(ck_free_.size());
|
||||
int64_t gone = 0;
|
||||
for (const int32_t s : ck_free_) {
|
||||
const int rc = ck_back_everywhere(s);
|
||||
if (rc == RAD_E_FULL) { ++gone; continue; }
|
||||
if (rc < 0) return rc;
|
||||
keep.push_back(s);
|
||||
}
|
||||
ck_free_.swap(keep);
|
||||
if (withdrawn) *withdrawn = gone;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t KVManager::ck_align() const {
|
||||
if (!ck_elastic_) return (int64_t)RAD_ALIGN_UNIT;
|
||||
const int64_t g = Pool::granule();
|
||||
return g > (int64_t)RAD_ALIGN_UNIT ? g : (int64_t)RAD_ALIGN_UNIT;
|
||||
}
|
||||
|
||||
/* WHAT THE GROUP CAN STILL HAND OUT, WHICH IS NOT WHAT IT HAS BELOW THE MARK. A lent block is
|
||||
* still carved, still addressed and still the operator's budget -- it is one recall away, and the
|
||||
* recall happens on the path that needs it. So every admission decision is made against this
|
||||
@@ -1400,47 +1321,27 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
|
||||
* caller sees RAD_E_FULL, which is the answer it already handles -- the retention policy runs and
|
||||
* the allocation is retried. Anything else would turn a card that is momentarily busy into a
|
||||
* failed request. */
|
||||
void KVManager::set_checkpoint_store(HostArena* store, int64_t rank_off) {
|
||||
ck_store_ = store && store->enabled() ? store : nullptr;
|
||||
ck_rank_off_ = rank_off;
|
||||
}
|
||||
|
||||
int KVManager::alloc_checkpoint(int32_t* slot_out) {
|
||||
if (ck_free_.empty()) return RAD_E_FULL;
|
||||
/* A SLOT EVERY CARD HAS BACKED ALREADY, WHERE ONE IS FREE: it costs no commit and no reading
|
||||
* of the card, and a card at its floor still has every slot it backed before. Otherwise the
|
||||
* top of the free list, backed on every card or not handed out at all. */
|
||||
size_t at = ck_free_.size() - 1;
|
||||
for (size_t i = ck_free_.size(); i-- > 0;) {
|
||||
const int32_t s = ck_free_[i];
|
||||
bool all = ck_backed(s);
|
||||
for (const KVManager* p : ck_peers_) all = all && p->ck_backed(s);
|
||||
if (all) { at = i; break; }
|
||||
}
|
||||
const int32_t slot = ck_free_[at];
|
||||
const int rc = ck_back_everywhere(slot);
|
||||
if (rc < 0) return rc;
|
||||
ck_free_.erase(ck_free_.begin() + (std::ptrdiff_t)at);
|
||||
if (!ck_store_ || checkpoint_bytes_ <= 0) return RAD_E_FULL;
|
||||
const int32_t slot = ck_store_->alloc();
|
||||
if (slot < 0) return RAD_E_FULL;
|
||||
*slot_out = slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void KVManager::free_checkpoint(int32_t slot) {
|
||||
if (slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return;
|
||||
for (int32_t f : ck_free_) if (f == slot) return; /* double free: refuse, do not corrupt */
|
||||
ck_free_.push_back(slot);
|
||||
/* AFTER the free list, so a release the driver refuses still leaves the slot allocatable: the
|
||||
* next commit of the same range is idempotent and the bytes are correct either way. */
|
||||
/* AND ONLY WHERE A RELEASE IS WORTH MAKING. See set_release_frees_card: on a driver that does
|
||||
* not return decommitted VRAM, unmapping these pages buys the card nothing and costs a commit
|
||||
* on the next allocation of the slot. It is not merely wasted work: the range is unmapped
|
||||
* while the slot id goes straight back on the free list, so anything still addressing it
|
||||
* reads a page that is no longer there. */
|
||||
if (ck_elastic_ && release_frees_card_ && pool_ && pool_->elastic() && ck_stride_ > 0) {
|
||||
const int64_t off = ck_slot_base_[(size_t)slot];
|
||||
if (pool_->is_committed(off, ck_stride_) && ck_backed_ > 0) --ck_backed_;
|
||||
(void)pool_->decommit(off, ck_stride_);
|
||||
}
|
||||
if (ck_store_) ck_store_->free(slot);
|
||||
}
|
||||
|
||||
void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
if (!pool_base_ || slot < 0 || slot >= (int32_t)ck_slot_base_.size()) return nullptr;
|
||||
return (char*)pool_base_ + ck_slot_base_[(size_t)slot];
|
||||
if (!ck_store_) return nullptr;
|
||||
char* p = (char*)ck_store_->at(slot);
|
||||
return p ? p + ck_rank_off_ : nullptr;
|
||||
}
|
||||
|
||||
/* One walk, both directions. Keeping save and restore as a single traversal is deliberate: the
|
||||
@@ -1449,14 +1350,16 @@ void* KVManager::checkpoint_ptr(int32_t slot) const {
|
||||
* functions that could stop agreeing. */
|
||||
int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot,
|
||||
bool save, RadStream s) {
|
||||
/* THIS RANK'S PAGES, BEFORE THIS RANK'S COPY. alloc_checkpoint backed the slot on every rank
|
||||
* before it handed the id out, so this finds it backed; a refusal here is a slot that did not
|
||||
* come from there. See KVManager::back_checkpoint. */
|
||||
RAD_TRY(back_checkpoint(ck_slot));
|
||||
/* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the
|
||||
* shared store rather than a list of its own. */
|
||||
if (!ck_store_ || !ck_store_->in_use(ck_slot)) return RAD_E_INVAL;
|
||||
char* ck = (char*)checkpoint_ptr(ck_slot);
|
||||
if (!ck) return RAD_E_INVAL;
|
||||
if (!state_slots || n_slots < (int)plans_.size()) return RAD_E_INVAL;
|
||||
|
||||
/* ONE PITCHED COPY A GROUP. Within a group the state of one sequence is a row a layer, one
|
||||
* layer_stride apart in the pool and packed end to end in the slot, so a group's whole share
|
||||
* crosses the link as one launch rather than a launch a layer. */
|
||||
int64_t off = 0;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
@@ -1464,19 +1367,19 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t
|
||||
const int32_t slot = state_slots[g];
|
||||
if (slot < 0) return RAD_E_STATE; /* no state to save, or none to restore into */
|
||||
const int64_t nbytes = p.layer_bytes_per_state();
|
||||
for (int64_t l = 0; l < p.n_layers; ++l) {
|
||||
void* st = state_ptr((int32_t)g, (int32_t)l, slot);
|
||||
if (!st) return RAD_E_STATE;
|
||||
if (off + nbytes > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes and this sequence's linear state "
|
||||
"needs more than that; configure() sized it from the same plans, so the "
|
||||
"two have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_async(ck + off, st, nbytes, s)
|
||||
: rad_memcpy_async(st, ck + off, nbytes, s));
|
||||
off += nbytes;
|
||||
void* st = state_ptr((int32_t)g, 0, slot);
|
||||
if (!st || p.n_layers <= 0) return RAD_E_STATE;
|
||||
if (off + nbytes * p.n_layers > checkpoint_bytes_) {
|
||||
RAD_ERR("checkpoint slot %d holds %lld bytes a rank and this sequence's linear state "
|
||||
"needs more than that; the store was sized from the same plans, so the two "
|
||||
"have gone out of step", (int)ck_slot, (long long)checkpoint_bytes_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
RAD_TRY(save ? rad_memcpy_2d_async(ck + off, nbytes, st, p.layer_stride(), nbytes,
|
||||
p.n_layers, s)
|
||||
: rad_memcpy_2d_async(st, p.layer_stride(), ck + off, nbytes, nbytes,
|
||||
p.n_layers, s));
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+52
-97
@@ -18,6 +18,7 @@
|
||||
* one of the two allocators keeps handing its state slot to the next request.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
#include "mem/pools.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
@@ -74,6 +75,10 @@ struct KVGroupPlan {
|
||||
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
|
||||
|
||||
int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */
|
||||
/* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position
|
||||
* and its block count (one block table serves every rank), its costs are zero and nothing is
|
||||
* carved; no op on this rank names it (issue refuses a group with no pool bound). */
|
||||
bool zero = false;
|
||||
int64_t n_states = 0; /* LINEAR/CONV: n_seq_states * state_copies */
|
||||
/* HOW MANY PHYSICAL SLOTS ONE LOGICAL STATE COSTS. One, normally: a sequence owns a state.
|
||||
* Under speculation a linear kernel needs somewhere to put what it cannot commit yet -- it
|
||||
@@ -151,11 +156,10 @@ public:
|
||||
* exhaust at the same total token count, and any other split strands memory in whichever
|
||||
* group outlasts the others.
|
||||
*
|
||||
* Both budgets come from the operator and neither is derived here: the byte budget is whatever
|
||||
* `kv_pool` still has (which is --vram-kv-mib), and the linear-snapshot count is
|
||||
* Config::checkpoint_slots (--checkpoint-slots). A checkpoint is ~96 MiB on a Qwen3-Next and
|
||||
* 64 of them is 6 GiB, so how many to retain is a budget decision and therefore not this
|
||||
* component's to make (spec §6, §7.3). */
|
||||
* The byte budget comes from the operator and is not derived here: it is whatever `kv_pool`
|
||||
* still has (which is --vram-kv-mib). The linear-state snapshots take none of it -- they live
|
||||
* in pinned host memory (set_checkpoint_store) -- so the pool is the live cache and nothing
|
||||
* else (spec §6, §7.3). */
|
||||
int configure(const std::vector<KVGroupInfo>& groups, const Config& cfg, Pool& kv_pool);
|
||||
|
||||
/* configure(), split at the seam the budget resolver needs. plan_groups() sizes every group
|
||||
@@ -166,8 +170,19 @@ public:
|
||||
int plan_groups(const std::vector<KVGroupInfo>& groups, const Config& cfg);
|
||||
int64_t ceiling(int64_t ctx) const;
|
||||
/* The part of every ceiling that is not context: recurrent and conv state for max_seqs
|
||||
* sequences, the checkpoint slots and the padding. Set by plan_groups(). */
|
||||
* sequences, and the padding. Set by plan_groups(). */
|
||||
int64_t fixed_bytes() const { return fixed_; }
|
||||
/* THE TOKEN COUNT THE PAGED GROUPS SETTLE ON for `budget_bytes` of pool -- carve()'s split
|
||||
* with nothing carved. One block table serves every rank, so every rank's paged groups must
|
||||
* hold the SAME number of blocks; under an uneven tensor-parallel split the ranks' pools are
|
||||
* not the same size (a rank with more delta-net heads holds more state and has less left for
|
||||
* pages, and a rank with no attention weights has more). The engine asks each rank this and
|
||||
* cap_paged_tokens() the least on all of them before carve(). 0 is no cap.
|
||||
* kUnboundedTokens when every paged group of this rank is zero (rad_kv_group_zero): its pages
|
||||
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
|
||||
static constexpr int64_t kUnboundedTokens = INT64_MAX;
|
||||
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
|
||||
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
|
||||
int carve(Pool& kv_pool);
|
||||
|
||||
const std::vector<KVGroupPlan>& plans() const { return plans_; }
|
||||
@@ -336,12 +351,6 @@ public:
|
||||
* recalled and the request is refused (RAD_E_FULL). */
|
||||
void set_reclaim(std::function<int(int64_t tokens)> f) { reclaim_ = std::move(f); }
|
||||
|
||||
/* WHETHER A DECOMMIT ACTUALLY GIVES THE CARD BACK, for the checkpoint region, which is the one
|
||||
* part of the pool still backed on demand. Measured once at bringup rather than assumed,
|
||||
* because it is a property of the driver: where it is false a freed checkpoint slot keeps its
|
||||
* pages, since unmapping them would cost driver calls and return nothing. */
|
||||
void set_release_frees_card(bool yes) { release_frees_card_ = yes; }
|
||||
|
||||
/* MATCH A LEADER'S LOAN, FOR A RANK THAT DOES NOT KNOW WHAT IT IS HOLDING.
|
||||
*
|
||||
* Block ids are SHARED ACROSS RANKS -- RadBatch carries one block table and every rank indexes
|
||||
@@ -355,59 +364,6 @@ public:
|
||||
int64_t live_blocks(int32_t group) const;
|
||||
int64_t committed_bytes() const;
|
||||
|
||||
/* HOW MUCH OF THE CHECKPOINT REGION MUST STAY AVAILABLE, in bytes, counting only what is not
|
||||
* committed already. The number is the HIGH WATER MARK PLUS ONE rather than the whole cap:
|
||||
* the cap is what the operator allows and the high water is what this workload takes, and
|
||||
* holding one slot past it means the allocation that would advance it always has room. */
|
||||
int64_t ck_reserve_bytes() const;
|
||||
|
||||
/* BACK THIS RANK'S COPY OF A SLOT, AND SAY SO IF THE CARD WILL NOT.
|
||||
*
|
||||
* A slot's LIFETIME is decided once: rank 0's PrefixCache owns the free list and every other
|
||||
* rank takes the id it is handed. Its BACKING is per rank, because every rank writes its own
|
||||
* shard of the snapshot into the same offset of its OWN pool. alloc_checkpoint backs the slot
|
||||
* on every rank before it hands the id out (set_checkpoint_peers), so on the paths that use a
|
||||
* slot this is a check that finds it backed. Called before EVERY access rather than once:
|
||||
* idempotence is what makes that safe, and a commit of a range already committed is a no-op.
|
||||
*
|
||||
* RAD_E_FULL when the commit would take the card under its floor (set_checkpoint_floor). */
|
||||
int back_checkpoint(int32_t slot);
|
||||
|
||||
/* THE CARD'S FLOOR FOR A CHECKPOINT SLOT'S PAGES: the card is read before a slot is backed,
|
||||
* and a slot that would leave it under `keep_free` bytes is refused as a full pool.
|
||||
*
|
||||
* The budget counts the whole checkpoint region as the cache's, but the region is backed as
|
||||
* slots are taken, and until then its bytes read as free. The allocations nobody sizes in
|
||||
* advance -- a kernel's code object and a spilling kernel's scratch, both made on the
|
||||
* kernel's first launch -- are made out of that same free memory. A slot that took the last
|
||||
* of it would leave the next first launch nothing, which is a fault inside the HIP runtime
|
||||
* and not an error. A refused slot is a snapshot fewer on the card, which the retention
|
||||
* policy answers and the host tier covers.
|
||||
*
|
||||
* `free_bytes` reads the card's free memory into its argument: the engine reads the device, a
|
||||
* test reads a simulated card, and no floor is set on a backend with no card. */
|
||||
using FreeBytes = std::function<int(int64_t*)>;
|
||||
void set_checkpoint_floor(FreeBytes free_bytes, int64_t keep_free) {
|
||||
ck_free_bytes_ = std::move(free_bytes);
|
||||
ck_keep_free_ = keep_free;
|
||||
}
|
||||
|
||||
/* THE OTHER RANKS' MANAGERS, given to the one whose free list hands the ids out. Every rank
|
||||
* writes its shard of a snapshot into the same slot of its own pool, so a slot is backed on
|
||||
* every card or handed out on none: a card that cannot back it is a full pool at allocation,
|
||||
* which the prefix cache answers by retiring a snapshot, rather than a failed copy after the
|
||||
* step that produced the state, which stops the engine. */
|
||||
void set_checkpoint_peers(std::vector<KVManager*> peers) { ck_peers_ = std::move(peers); }
|
||||
|
||||
/* BACK EVERY FREE SLOT NOW, ON EVERY RANK, and withdraw the ones the cards have no room for.
|
||||
* For a driver that never takes a mapping's pages back (set_release_frees_card(false)): a
|
||||
* slot backed later costs exactly what it costs now, and backing it now puts the region's
|
||||
* cost on the card before serving starts, where the startup reading shows it. A withdrawn
|
||||
* slot is never handed out. `withdrawn` counts them; RAD_E_FULL is not returned. */
|
||||
int back_free_checkpoints(int64_t* withdrawn);
|
||||
|
||||
int64_t checkpoint_stride() const { return ck_stride_; }
|
||||
|
||||
/* ---------------- preemption by recompute (spec §7.1, §17) ---------------- */
|
||||
/* Free the sequence's blocks and take it back to zero tokens. Its state slots are freed too: a
|
||||
* recurrent state that is not snapshotted cannot be resumed, so a preempted sequence replays
|
||||
@@ -458,10 +414,24 @@ public:
|
||||
const std::vector<uint64_t>& victims,
|
||||
std::vector<uint64_t>* preempted);
|
||||
|
||||
/* ---------------- linear-state checkpoints (spec §7.3) ---------------- */
|
||||
/* ---------------- linear-state checkpoints (spec §7.3) ----------------
|
||||
*
|
||||
* A SNAPSHOT LIVES IN PINNED HOST MEMORY, NOT ON THE CARD. It is a copy of a sequence's state
|
||||
* that no kernel reads -- the step reads the live state slots, and a snapshot only ever goes
|
||||
* back into one of those -- so it has no reason to hold VRAM. Saving it is one copy across the
|
||||
* link after the step that produced the state, restoring it one copy back before the step
|
||||
* that resumes from it, each a few milliseconds on a 50-100 MiB snapshot.
|
||||
*
|
||||
* THE STORE IS SHARED BY EVERY RANK and owned by the engine: a slot holds every rank's shard
|
||||
* of one snapshot, each at its own offset (`rank_off`), so the disk tier reads and writes a
|
||||
* slot as one payload. The slot ids are rank 0's -- its manager hands them out and the others
|
||||
* address the id they are given. Without a store no slot is ever handed out and a hybrid
|
||||
* model's prefix hits replay their linear layers from zero. `checkpoint_bytes()` is THIS
|
||||
* rank's shard. */
|
||||
void set_checkpoint_store(HostArena* store, int64_t rank_off);
|
||||
int64_t checkpoint_bytes() const { return checkpoint_bytes_; }
|
||||
int64_t checkpoint_slots() const { return (int64_t)ck_slot_base_.size(); }
|
||||
int64_t free_checkpoint_slots() const { return (int64_t)ck_free_.size(); }
|
||||
int64_t checkpoint_slots() const { return ck_store_ ? ck_store_->capacity() : 0; }
|
||||
int64_t free_checkpoint_slots() const { return ck_store_ ? ck_store_->free_slots() : 0; }
|
||||
int alloc_checkpoint(int32_t* slot_out);
|
||||
void free_checkpoint(int32_t slot);
|
||||
void* checkpoint_ptr(int32_t slot) const;
|
||||
@@ -483,7 +453,8 @@ public:
|
||||
*
|
||||
* Enqueued on `s`, not synchronous: the save has to follow the step that produced the state
|
||||
* and the restore has to precede the step that consumes it, and both are ordered by the
|
||||
* stream rather than by waiting. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
* stream rather than by waiting. One pitched copy a stateful group between the card and the
|
||||
* store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */
|
||||
int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s);
|
||||
|
||||
@@ -497,6 +468,13 @@ private:
|
||||
* through cannot leave plans_ answering guards for block state that was never sized. forget()
|
||||
* empties both together and is what plan_groups() starts from. */
|
||||
int carve_into(Pool& kv_pool);
|
||||
/* THE PAGED SPLIT, as arithmetic: the token count the paged groups exhaust at together for
|
||||
* `budget_bytes` of pool, under tokens_cap_, and each group's block count in `blocks` (by group
|
||||
* index; a windowed group capped at its window). carve_into() spends what this says. */
|
||||
int64_t paged_split(int64_t budget_bytes, std::vector<int64_t>* blocks) const;
|
||||
/* A zero group's share of `tokens`: the block count of the shared table, capped at the window
|
||||
* for a windowed group. 0 for kUnboundedTokens, which is not a count. */
|
||||
int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const;
|
||||
void forget();
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
@@ -536,8 +514,8 @@ private:
|
||||
std::unordered_map<uint64_t, Seq> seqs_;
|
||||
std::vector<BlockCopy> pending_;
|
||||
|
||||
std::vector<int64_t> ck_slot_base_; /* pool offsets of the checkpoint slots */
|
||||
std::vector<int32_t> ck_free_;
|
||||
HostArena* ck_store_ = nullptr; /* set_checkpoint_store */
|
||||
int64_t ck_rank_off_ = 0;
|
||||
int64_t checkpoint_bytes_ = 0;
|
||||
std::vector<StateClear> clears_; /* grabbed slots the engine must zero */
|
||||
void* pool_base_ = nullptr;
|
||||
@@ -547,32 +525,9 @@ private:
|
||||
int64_t max_ctx_ = 0;
|
||||
int64_t max_tok_ = 0; /* --max-num-batched-tokens; the buffer floor is one of these */
|
||||
/* plan_groups() computes these; carve() spends against them and ceiling() reports on them. */
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, checkpoints, padding */
|
||||
int64_t ck_total_ = 0; /* the checkpoint part of fixed_, named for the refusal message */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, as plan_groups() resolved it */
|
||||
/* THE SLOT STRIDE AND WHERE THE SLOTS BEGIN. The stride is checkpoint_bytes_ rounded up to a
|
||||
* whole number of commit granules, so a slot can be backed and released without touching a
|
||||
* neighbour; the offset is where the eager startup commit stops, because everything from
|
||||
* there up is backed as it is handed out. Zero on a model with no linear state. */
|
||||
bool release_frees_card_ = true;
|
||||
bool ck_elastic_ = false;
|
||||
int64_t ck_high_water_ = 0;
|
||||
int64_t ck_backed_ = 0;
|
||||
int64_t ck_stride_ = 0;
|
||||
int64_t ck_region_off_ = 0;
|
||||
FreeBytes ck_free_bytes_; /* set_checkpoint_floor */
|
||||
int64_t ck_keep_free_ = 0;
|
||||
std::vector<KVManager*> ck_peers_;
|
||||
/* RAD_OK when this rank has the slot backed or room above the floor to back it. */
|
||||
int ck_room(int32_t slot) const;
|
||||
bool ck_backed(int32_t slot) const;
|
||||
/* The commit itself, with no floor: callers have asked ck_room on every rank first. */
|
||||
int ck_commit(int32_t slot);
|
||||
/* ck_room on every rank, then ck_commit on every rank. */
|
||||
int ck_back_everywhere(int32_t slot);
|
||||
/* What a checkpoint slot is aligned and sized to. RAD_ALIGN_UNIT on a device with no virtual
|
||||
* memory management, where nothing is released and the stride is only padding. */
|
||||
int64_t ck_align() const;
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
|
||||
int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
|
||||
|
||||
/* ---- the loan. See the public block for what this is and why a block that anything holds
|
||||
* is never lent. ----
|
||||
|
||||
+226
-461
File diff suppressed because it is too large.
Load diff
+105
-161
@@ -78,6 +78,7 @@
|
||||
* such a transfer -- it reads host memory and nothing else -- and holds only the slots it reads.
|
||||
*/
|
||||
#pragma once
|
||||
#include "mem/hostarena.h"
|
||||
#include "mem/kv.h"
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
@@ -123,30 +124,23 @@ struct TierJob {
|
||||
|
||||
/* ---- the linear half, on a hybrid model ----
|
||||
*
|
||||
* A session's recurrent state lives in a CHECKPOINT SLOT rather than in blocks: one contiguous
|
||||
* KVManager::checkpoint_bytes() extent, which is why nothing here needs a gather. The snapshot
|
||||
* belonging to this entry moves with it, so a restored hybrid session gets its attention hit
|
||||
* AND its state back, instead of an attention hit and a full linear replay from token zero.
|
||||
* A session's recurrent state lives in a SNAPSHOT SLOT of the checkpoint store -- pinned host
|
||||
* memory, one contiguous KVManager::checkpoint_bytes() shard a rank -- rather than in blocks,
|
||||
* so it never crosses the link with them: a lookup restores it straight out of its slot. The
|
||||
* tiers only move it between that slot and the disk store, on the disk thread: a ToDisk job
|
||||
* reads `ck_slot`, a ToHost job writes it.
|
||||
*
|
||||
* `ck_dev` is the device slot: where the bytes are read from on the way out, and where the
|
||||
* engine put them on the way in -- it is an OUTPUT of a promotion, exactly as `blocks` is. */
|
||||
int32_t ck_dev = -1;
|
||||
int32_t ck_host = -1; /* a slot in the snapshot arena, not the block arena */
|
||||
* `ck_slot` is an INPUT to both. A read off disk is planned with `ck_want` and the engine
|
||||
* allocates the slot before the job leaves its hands (it holds the store's free list); a
|
||||
* write names the slot the snapshot is in. */
|
||||
int32_t ck_slot = -1;
|
||||
int64_t ck_pos = 0; /* the token position, which the disk store verifies on the way back */
|
||||
bool ck_want = false; /* a promotion should bring the snapshot back too */
|
||||
/* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves
|
||||
* fail for different reasons and are repaired differently: a snapshot that could not be copied
|
||||
* has not been damaged, it is still sitting correct and committed in its device slot and a
|
||||
* later pass reaches it again for free, so the blocks may as well carry on without it.
|
||||
*
|
||||
* A snapshot that is DROPPED is another matter, and it is worth being exact about the cost
|
||||
* because it is not what it looks like. On this build the scheduler clamps a hybrid session's
|
||||
* reuse to the last LINEAR CHECKPOINT it can reach, not to the attention hit -- RadBatch
|
||||
* carries one query length for every KV group, so the linear layers cannot be replayed over a
|
||||
* longer range than the attention ones (core/sched/scheduler.cpp, admit_one). A session whose
|
||||
* blocks came back and whose state did not therefore reuses NOTHING. The blocks are not a
|
||||
* partial win; they are unusable until some checkpoint under them survives. */
|
||||
bool ck_want = false; /* a read off disk should bring the snapshot in too */
|
||||
int64_t ck_bytes = 0;
|
||||
/* DID THE SNAPSHOT HALF SUCCEED. Separate from the job's own result because the two halves
|
||||
* fail for different reasons and are repaired differently: a snapshot whose disk write failed
|
||||
* is still correct in its slot, and one whose read failed costs the session a replay of its
|
||||
* linear layers, not its blocks. */
|
||||
bool ck_ok = true;
|
||||
/* A PROMOTION THAT WAS NEVER STARTED, as opposed to one that failed part of the way through.
|
||||
* A restore reserves every block before it moves a byte, and a chain that did not fit is cut
|
||||
@@ -157,54 +151,6 @@ struct TierJob {
|
||||
bool started = false;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the host arena */
|
||||
/* Pinned, because every byte of it is a PCIe transfer endpoint and a pageable one collapses: the
|
||||
* driver stages an async copy to pageable memory through its own buffer and, on some paths,
|
||||
* synchronises. Slot-allocated at one
|
||||
* fixed size rather than malloc'd per entry: every entry in a given model holds exactly one block
|
||||
* per cached group, so the size is a property of the geometry and a bitmap is the whole allocator.
|
||||
*
|
||||
* RUNS, BECAUSE A TRANSFER IS PER RUN. A 4-token block makes a 200K-token conversation fifty
|
||||
* thousand entries, and a copy per entry is fifty thousand driver calls on the engine thread --
|
||||
* the call rate, not the link, is then what a restore costs. Entries written together are given
|
||||
* consecutive slots wherever the arena has them, so a batch crosses the link as one strided copy
|
||||
* a run. */
|
||||
class HostArena {
|
||||
public:
|
||||
~HostArena();
|
||||
int open(int64_t slot_bytes, int64_t cap_bytes);
|
||||
void close();
|
||||
bool enabled() const { return base_ != nullptr; }
|
||||
|
||||
int64_t slot_bytes() const { return slot_bytes_; }
|
||||
/* Fixed when the arena is opened. Stored rather than counted from the bitmap, because an
|
||||
* HTTP thread reads it for the sessions view while the engine thread allocates and frees. */
|
||||
int64_t capacity() const { return cap_slots_; }
|
||||
int64_t used_slots() const { return used_; }
|
||||
int64_t cap_bytes() const { return slot_bytes_ * capacity(); }
|
||||
int64_t free_slots() const { return cap_slots_ - used_; }
|
||||
|
||||
/* -1 when the arena is full. The caller evicts and retries; this does not choose victims,
|
||||
* because the LRU that would choose them lives in IdleTiers and an allocator that reached
|
||||
* into it would give each record two owners. */
|
||||
bool full() const { return used_ >= cap_slots_; }
|
||||
int32_t alloc();
|
||||
/* UP TO `want` CONSECUTIVE SLOTS, the first free run at or after the cursor. `*got` is how
|
||||
* many; the caller asks again for the rest. -1 when the arena is full. */
|
||||
int32_t alloc_run(int32_t want, int32_t* got);
|
||||
void free(int32_t slot);
|
||||
void* at(int32_t slot) const;
|
||||
|
||||
private:
|
||||
bool is_used(int64_t s) const { return (bits_[(size_t)(s >> 6)] >> (s & 63)) & 1ull; }
|
||||
void* base_ = nullptr;
|
||||
int64_t slot_bytes_ = 0;
|
||||
int64_t used_ = 0;
|
||||
int64_t cap_slots_ = 0;
|
||||
int64_t cursor_ = 0;
|
||||
std::vector<uint64_t> bits_;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the policy */
|
||||
class IdleTiers {
|
||||
public:
|
||||
@@ -214,12 +160,11 @@ public:
|
||||
int64_t entry_bytes = 0; /* one entry: sum over cached groups of bytes_per_block */
|
||||
/* ---- the linear half ----
|
||||
* `ckpt_bytes` is ONE SNAPSHOT, every rank's shard of it, laid out exactly like
|
||||
* `entry_bytes`. `ckpt_cap_bytes` is carved out of the tier the operator sized rather than
|
||||
* added to it: a snapshot store is host memory like any other and a tier that quietly
|
||||
* allocated past its stated cap would be the one thing --prefix-cache-host-mib is for. Zero
|
||||
* for either means snapshots do not tier, and the blocks still do. */
|
||||
* `entry_bytes`. The snapshots live in the engine's checkpoint store, `ckpt_slots` deep,
|
||||
* which is reported here and not allocated: --prefix-cache-host-mib is the blocks' alone.
|
||||
* `ckpt_disk_slots` zero means snapshots never reach disk, and the blocks still do. */
|
||||
int64_t ckpt_bytes = 0;
|
||||
int64_t ckpt_cap_bytes = 0; /* host; part of host_cap_bytes, not additional to it */
|
||||
int64_t ckpt_slots = 0; /* the checkpoint store's capacity, for the report and view */
|
||||
int64_t ckpt_disk_slots = 0; /* how many the disk store was opened for */
|
||||
};
|
||||
|
||||
@@ -262,10 +207,7 @@ public:
|
||||
*
|
||||
* The records waiting for a host copy, up to `max_entries`, as WriteBack jobs with their host
|
||||
* slots already allocated. Oldest first, so a conversation that went idle before another is
|
||||
* copied before it. A record whose snapshot is still only on the device is included even when
|
||||
* its blocks already have their copy, with `blocks` empty -- the snapshot is the half a hybrid
|
||||
* session cannot resume without, and it becomes copyable later than the blocks (a checkpoint
|
||||
* is committed on its own clock).
|
||||
* copied before it. Blocks only: a snapshot is in host memory from the moment it is saved.
|
||||
*
|
||||
* Every record named by a returned job is `pending` until report() is called for it. An arena
|
||||
* too full to take the batch first gives up the host slots of the oldest entries the disk also
|
||||
@@ -286,32 +228,31 @@ public:
|
||||
bool droppable(const BlockHash& key) const;
|
||||
/* The cache released the blocks. The record is now a host record with its copy, on the host
|
||||
* tier's list like any other -- or a disk record, when its host slot was already given up.
|
||||
*
|
||||
* ITS SNAPSHOT STAYS WHERE IT IS. A snapshot's device slot is not memory anything else can
|
||||
* use -- the expert slab borrows blocks, never checkpoint slots -- so taking it off the device
|
||||
* along with the blocks would buy nothing and put the session's recurrent state at the mercy
|
||||
* of a host arena a few snapshots deep, shared by every conversation. The slot goes when the
|
||||
* checkpoint pool itself needs it (snapshot_backed). */
|
||||
* Its snapshot stays in its slot: the store is not the pool, and the blocks leaving frees
|
||||
* nothing there. */
|
||||
void drop_commit(const BlockHash& key);
|
||||
|
||||
/* ---------------- the snapshots' own pressure ----------------
|
||||
*
|
||||
* The checkpoint pool is --checkpoint-slots deep for the whole server, and when it is full the
|
||||
* cache retires the least recently used snapshot to make room. One whose bytes the tiers also
|
||||
* hold need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
|
||||
* stays, and the next restore of the session brings the state back with the blocks. True when
|
||||
* this key's device snapshot has a finished copy off the card that nothing is still writing. */
|
||||
* The checkpoint store is --checkpoint-slots deep for the whole server, and when it is full
|
||||
* the cache retires the least recently used snapshot to make room. One the disk also holds
|
||||
* need not be lost: the cache DETACHES it instead -- the slot goes back, the index entry
|
||||
* stays, and the next restore of the session reads the state back off disk (plan_fetch).
|
||||
* True when this key's snapshot is in a slot and has a finished disk copy that no write is
|
||||
* still producing. */
|
||||
bool snapshot_backed(const BlockHash& key) const;
|
||||
/* The cache gave the device slot back; the copy off the card is now the snapshot. */
|
||||
/* Is this key's snapshot in store slot `slot` by this object's record? */
|
||||
bool snapshot_in_slot(const BlockHash& key, int32_t slot) const;
|
||||
/* The cache gave the slot back; the disk copy is now the snapshot. */
|
||||
void snapshot_detached(const BlockHash& key);
|
||||
|
||||
/* ---------------- the slow half ----------------
|
||||
*
|
||||
* The host copies waiting for their disk copy, in the order they landed, as ToDisk jobs --
|
||||
* blocks and snapshot halves together where both are waiting. A ToDisk job does NOT make its
|
||||
* record pending: it only reads the host slots it names, which a restore may read at the same
|
||||
* time, and a slot the record gives up while the write is out is freed when the write reports
|
||||
* rather than under it. With no disk tier, the copies the arena refused since the last plan
|
||||
* blocks and snapshot halves together where both are waiting, and a resume point's snapshot
|
||||
* ahead of everything (note_snapshot). A ToDisk job does NOT make its record pending: it only
|
||||
* reads the host slots it names, which a restore may read at the same time, and a slot given
|
||||
* up while the write is out is freed when the write reports rather than under it. With no disk tier, the copies the arena refused since the last plan
|
||||
* are made room for by dropping that many of the oldest host-only entries. `budget` bounds
|
||||
* one plan so the IO a pass asks for is bounded too. */
|
||||
void plan(int budget, std::vector<TierJob>* out);
|
||||
@@ -340,12 +281,17 @@ public:
|
||||
* none of the chain is on disk, or none of what is can be given a slot -- a chain larger than
|
||||
* the arena comes back as far as the arena holds, and the rest is prefilled.
|
||||
*
|
||||
* The chain's deepest snapshot that is only on disk is read with it, into the snapshot arena,
|
||||
* because that is the state the hit resumes from (TierExec::issue_restore). Every record named
|
||||
* is `pending` until the read reports, and what a read brought in is not given up to make
|
||||
* room for anybody else until the request has had the step it needs to claim it. */
|
||||
* The chain's deepest snapshot, when it is only on disk, is read with it -- that is the state
|
||||
* the hit resumes from -- into the store slot `*ck_slot` the caller allocated after asking
|
||||
* snapshot_fetch_wanted. The slot is taken (and `*ck_slot` set to -1) only when the read is
|
||||
* planned; otherwise it is still the caller's to free. Every record named is `pending` until
|
||||
* the read reports, and what a read brought in is not given up to make room for anybody else
|
||||
* until the request has had the step it needs to claim it. */
|
||||
bool plan_fetch(const std::vector<BlockHash>& chain, std::vector<TierJob>* out,
|
||||
uint64_t now_ns);
|
||||
uint64_t now_ns, int32_t* ck_slot = nullptr);
|
||||
/* Would plan_fetch read this chain's deepest snapshot off disk -- is it there and nowhere
|
||||
* else? Asked first, because the slot it reads into is the store's, which the caller owns. */
|
||||
bool snapshot_fetch_wanted(const std::vector<BlockHash>& chain) const;
|
||||
|
||||
/* A promotion, asked for by a lookup that hit off-device. Returns false when the entry is not
|
||||
* in host memory -- a disk entry is read in by plan_fetch first -- or already has work
|
||||
@@ -382,38 +328,42 @@ public:
|
||||
*
|
||||
* Told by PrefixCache::commit_checkpoint, for the same reason note_used carries the block ids:
|
||||
* a copy has to know what to move and the cache's index is the only place it is written down.
|
||||
* `dev_slot` is a KVManager checkpoint slot and `pos` the token position the disk store
|
||||
* verifies a read against.
|
||||
* `slot` is a checkpoint store slot and `pos` the token position the disk store verifies a
|
||||
* read against.
|
||||
*
|
||||
* A record may hear this BEFORE it hears note_used -- a checkpoint is committed mid-request
|
||||
* and the chain is published when the request closes -- so this creates the record if it has
|
||||
* to. The snapshot is queued for a copy when the record is published, or at once when it
|
||||
* already was. */
|
||||
void note_snapshot(const BlockHash& key, int32_t dev_slot, int64_t pos);
|
||||
/* The cache is done with the snapshot at `key`: return whatever tier storage holds it. The
|
||||
* record's BLOCKS are untouched -- the two halves are retired by different policies on
|
||||
* different clocks, and a snapshot the retention policy drops says nothing about the prefix.
|
||||
* to. The snapshot is queued for its disk copy when the record is published, or at once when
|
||||
* it already was -- or AT ONCE AND AHEAD OF EVERYTHING when it is a resume point (`resume`):
|
||||
* the deepest checkpoint its prompt gets, which the next turn resumes from. Until it is on disk
|
||||
* the store can only retire it, and a burst of prefills churns the store through the whole
|
||||
* decode in between. */
|
||||
void note_snapshot(const BlockHash& key, int32_t slot, int64_t pos, bool resume = false);
|
||||
/* The cache is done with the snapshot at `key`, which is in store slot `slot`: return whatever
|
||||
* the tiers hold for it. The record's BLOCKS are untouched -- the two halves are retired by
|
||||
* different policies on different clocks, and a snapshot the retention policy drops says
|
||||
* nothing about the prefix.
|
||||
*
|
||||
* TRUE WHEN A COPY IS STILL READING THE DEVICE SLOT, and then the slot is NOT the caller's to
|
||||
* free: an asynchronous copy out of a slot the pool has decommitted reads a page that is no
|
||||
* longer there, which is a device fault rather than a stale byte. The tiers keep the slot and
|
||||
* hand it back through `take_checkpoint_frees` once the copy has reported. */
|
||||
bool release_snapshot(const BlockHash& key);
|
||||
/* Device checkpoint slots whose release waited on a copy, now safe to free. */
|
||||
* TRUE WHEN A DISK WRITE IS STILL READING THE SLOT, and then the slot is NOT the caller's to
|
||||
* free: a save into it would put half of another snapshot on disk under this key. The tiers
|
||||
* keep the slot and hand it back through `take_checkpoint_frees` once the write has reported.
|
||||
* Decided by the slot and not by the record, which may have gone while the write was out. */
|
||||
bool release_snapshot(const BlockHash& key, int32_t slot);
|
||||
/* Store slots whose release waited on a disk write, now safe to free. */
|
||||
void take_checkpoint_frees(std::vector<int32_t>* out);
|
||||
/* Is a copy reading this key's device snapshot right now? A save into that slot would tear it. */
|
||||
bool snapshot_reading(const BlockHash& key) const;
|
||||
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS. The snapshot store is far smaller than the
|
||||
* block store (a snapshot is thousands of blocks' worth of bytes) so it overflows first and on
|
||||
* its own, and the cache has to stop offering an index entry whose bytes nobody holds. Wired
|
||||
* to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an entry and
|
||||
* losing all of it are different events with different repairs. */
|
||||
/* Is a disk write reading store slot `slot` right now? A save into it would tear the write. */
|
||||
bool slot_reading(int32_t slot) const;
|
||||
/* THE TIERS LOST A SNAPSHOT BUT KEPT THE BLOCKS: its only copy was on disk and the disk store
|
||||
* no longer has it. The cache has to stop offering an index entry whose bytes nobody holds.
|
||||
* Wired to PrefixCache::drop_snapshot; separate from set_drop_sink because losing half an
|
||||
* entry and losing all of it are different events with different repairs. Never said of a
|
||||
* snapshot still in its slot: that one is the cache's. */
|
||||
void set_snapshot_drop_sink(std::function<void(const BlockHash&)> f) { on_ck_drop_ = std::move(f); }
|
||||
bool ckpt_on() const { return ck_arena_.enabled(); }
|
||||
/* Do snapshots reach disk at all? */
|
||||
bool ckpt_disk_on() const { return disk_on() && cfg_.ckpt_bytes > 0 && cfg_.ckpt_disk_slots > 0; }
|
||||
int64_t ckpt_bytes() const { return cfg_.ckpt_bytes; }
|
||||
HostArena& ckpt_arena() { return ck_arena_; }
|
||||
const HostArena& ckpt_arena() const { return ck_arena_; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
int64_t ckpt_disk_slots() const { return cfg_.ckpt_disk_slots; }
|
||||
int64_t ckpt_slots() const { return cfg_.ckpt_slots; }
|
||||
|
||||
/* ---------------- the session view ----------------
|
||||
*
|
||||
@@ -440,11 +390,11 @@ public:
|
||||
int64_t on_device = 0, on_host = 0, on_disk = 0; /* blocks, by tier */
|
||||
/* LINEAR STATE, on a hybrid model. Counted separately from blocks because it is a
|
||||
* different resource with a different scarcity: a snapshot is thousands of blocks' worth
|
||||
* of bytes and there are only --checkpoint-slots of them on the device. A session showing
|
||||
* of bytes and there are only --checkpoint-slots of them in host memory. A session showing
|
||||
* blocks on disk and no snapshot anywhere is one that will come back and re-run every
|
||||
* recurrent layer over its whole transcript, which is not what "restored" should mean. */
|
||||
int64_t snapshots = 0; /* this session holds, any tier */
|
||||
int64_t snap_device = 0, snap_host = 0, snap_disk = 0;
|
||||
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
|
||||
int64_t snap_bytes = 0;
|
||||
/* WHAT A RETURN REUSES: the token position of the deepest snapshot on the chain, in any
|
||||
* tier. On a hybrid model the scheduler clamps a hit to the last linear checkpoint it can
|
||||
@@ -500,9 +450,17 @@ public:
|
||||
int64_t fetched = 0, ck_fetched = 0;
|
||||
/* SNAPSHOTS MOVED, counted apart from blocks. A hybrid session can move its whole chain
|
||||
* off the device and still replay every linear layer from zero on the way back, and no
|
||||
* block counter can tell the two apart -- these are the numbers that can. */
|
||||
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
|
||||
* block counter can tell the two apart -- these are the numbers that can. `ck_drops` is
|
||||
* snapshots whose only copy was lost. */
|
||||
int64_t ck_to_disk = 0, ck_drops = 0;
|
||||
/* WHAT THE STEP THREAD SPENT ON THEM, under the scheduler's lock: restores issued at
|
||||
* admission, and copies landed synchronously because pressure could not wait for them.
|
||||
* Host time, not link time -- what every other request waits through. */
|
||||
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0;
|
||||
};
|
||||
/* The step thread's own time on the tiers (see Stats). */
|
||||
void note_restore(int64_t ns) { std::lock_guard lk(mu_); ++stats_.restores; stats_.restore_ns += ns; }
|
||||
void note_flush(int64_t ns) { std::lock_guard lk(mu_); ++stats_.flushes; stats_.flush_ns += ns; }
|
||||
/* A copy, taken under the lock: an HTTP thread reads these while the engine thread moves
|
||||
* records. */
|
||||
Stats stats() const;
|
||||
@@ -529,30 +487,19 @@ private:
|
||||
bool fetching = false; /* the pending job is a read off disk (plan_fetch) */
|
||||
bool doomed = false; /* forget() arrived while pending */
|
||||
bool queued = false; /* in wb_q_: waiting for a copy */
|
||||
bool resume_q = false; /* in resume_q_: a resume point waiting for its disk copy */
|
||||
bool clean_q = false; /* in clean_q_: a drop the cache has not been asked about */
|
||||
bool listed = false; /* on host_lru_ or disk_lru_; `it` is valid */
|
||||
std::vector<int32_t> blocks;
|
||||
/* ---- the linear half ----
|
||||
* `ck_dev` is the snapshot's device slot, `ck_host` its host copy and `ck_on_disk` the
|
||||
* disk store's. A clean device snapshot has both of the first two; a snapshot that has
|
||||
* left the device has no `ck_dev`. All clear when the record carries no snapshot, which is
|
||||
* the common case -- one block in every (interval / block_size) is a checkpoint position. */
|
||||
int32_t ck_dev = -1;
|
||||
int32_t ck_host = -1;
|
||||
* `ck_slot` is the snapshot's checkpoint store slot and `ck_on_disk` the disk store's
|
||||
* copy. A snapshot the store gave up has only the second. All clear when the record
|
||||
* carries no snapshot, which is the common case -- one block in every
|
||||
* (interval / block_size) is a checkpoint position. */
|
||||
int32_t ck_slot = -1;
|
||||
bool ck_on_disk = false;
|
||||
int64_t ck_pos = 0;
|
||||
/* A COPY IS READING `ck_dev` RIGHT NOW: set when a write-back takes the snapshot, cleared
|
||||
* when it reports. The one moment the device slot is not the cache's to free. */
|
||||
bool ck_reading = false;
|
||||
/* THIS SNAPSHOT WILL NOT BE COPIED AGAIN: its copy was refused for want of room, or taken
|
||||
* back to make room for another. The snapshot store is a few slots deep for the whole
|
||||
* server, and a snapshot still in its device slot re-queued the moment its copy was
|
||||
* evicted would evict the next one's, and so on -- every pass copying a hundred megabytes
|
||||
* a rank to throw another hundred away. Cleared when a new commit replaces the state. */
|
||||
bool ck_skip = false;
|
||||
/* A device slot the cache let go of while a copy was reading it. See release_snapshot. */
|
||||
int32_t ck_free_after = -1;
|
||||
/* The snapshot host slot a disk write is reading, as `disk_src` is for the blocks. */
|
||||
/* The store slot a disk write is reading, as `disk_src` is for the blocks. */
|
||||
int32_t ck_disk_src = -1;
|
||||
/* WHEN A READ OFF DISK BROUGHT THIS RECORD IN, 0 when none did or its restore has run.
|
||||
* Until the request that asked for it has been admitted the slots are its and not the
|
||||
@@ -566,24 +513,20 @@ private:
|
||||
std::list<BlockHash>::iterator it;
|
||||
};
|
||||
|
||||
/* Does this record want a copy it does not have yet? The blocks when they are in VRAM with no
|
||||
* copy off the card; the snapshot when it is in a device slot with no copy off the card and
|
||||
* the snapshot store exists at all. */
|
||||
/* Does this record want a host copy it does not have yet? Its blocks are in VRAM with none. */
|
||||
bool wants_copy(const Rec& r) const;
|
||||
/* The snapshot half of that on its own. */
|
||||
bool wants_ck_copy(const Rec& r) const;
|
||||
/* And a disk copy: a host copy of either half that the disk does not hold yet. */
|
||||
bool wants_disk(const Rec& r) const;
|
||||
bool wants_ck_disk(const Rec& r) const;
|
||||
void queue_copy(const BlockHash& key, Rec& r);
|
||||
void queue_clean(const BlockHash& key, Rec& r);
|
||||
void queue_disk(const BlockHash& key, Rec& r);
|
||||
/* GIVE UP A HOST SLOT, the record's or a finished job's. Every block-arena free goes through
|
||||
* `give_slot`, because a freed slot is what unblocks a write-back that found the arena full.
|
||||
* `free_host` / `free_ck_host` are the record's own: a slot a disk write is reading is left
|
||||
* `free_host` is the record's own: a slot a disk write is reading is left
|
||||
* for that write's report to free. */
|
||||
void give_slot(int32_t slot);
|
||||
void free_host(Rec& r);
|
||||
void free_ck_host(Rec& r);
|
||||
void set_on_disk(Rec& r, bool v);
|
||||
int64_t make_room_locked(int64_t n);
|
||||
/* May this record's host copies be given up to make room right now? Not while a read put
|
||||
@@ -594,12 +537,8 @@ private:
|
||||
void relist(const BlockHash& key, Rec& r);
|
||||
std::list<BlockHash>& list_for(KVTier t) { return t == KVTier::Host ? host_lru_ : disk_lru_; }
|
||||
void release_storage(const BlockHash& key, Rec& r);
|
||||
/* Take a snapshot arena slot from the record whose host copy is cheapest to lose, and tell the
|
||||
* cache if that was the snapshot's only copy. NO SECOND LIST: the records are walked, which
|
||||
* keeps the header's "one record, one tier, one list" rule intact. `lossless` takes only a
|
||||
* snapshot the disk also holds.
|
||||
* Returns -1 when there is none to take. */
|
||||
int32_t evict_snapshot_slot(bool lossless);
|
||||
/* The chain position of the deepest snapshot no job is out on, or chain.size(). */
|
||||
size_t deepest_snapshot(const std::vector<BlockHash>& chain) const;
|
||||
|
||||
struct Session {
|
||||
int64_t n_tokens = 0;
|
||||
@@ -655,16 +594,21 @@ private:
|
||||
Config cfg_;
|
||||
SSDTier* disk_ = nullptr;
|
||||
HostArena arena_;
|
||||
HostArena ck_arena_; /* snapshots; a different slot size, so a different arena */
|
||||
std::unordered_map<BlockHash, Rec, BlockHashHash> recs_;
|
||||
std::list<BlockHash> host_lru_, disk_lru_; /* front = oldest */
|
||||
/* THE WORK QUEUES, in the order the work arrived. Each holds a key at most once -- the Rec's
|
||||
* flag says whether it is in -- and a key whose record changed under it is skipped when it is
|
||||
* reached rather than searched for, so both stay a push and a pop. */
|
||||
std::deque<BlockHash> wb_q_; /* records wanting a host copy */
|
||||
std::deque<BlockHash> resume_q_; /* resume points wanting a disk copy, served first */
|
||||
std::deque<BlockHash> dk_q_; /* records wanting a disk copy, in the order they landed */
|
||||
std::vector<BlockHash> clean_q_; /* records whose VRAM copy may now go */
|
||||
std::vector<int32_t> ck_frees_; /* device checkpoint slots a finished copy released */
|
||||
/* STORE SLOTS A DISK WRITE IS READING, and those the cache let go of meanwhile. Kept by slot
|
||||
* and not on the record, because the record can be forgotten while the write is out and the
|
||||
* slot is the cache's either way. A few entries at most: one write batch is out at a time. */
|
||||
std::vector<int32_t> ck_reading_;
|
||||
std::vector<int32_t> ck_free_after_;
|
||||
std::vector<int32_t> ck_frees_; /* store slots a finished write released */
|
||||
/* COPIES THE ARENA REFUSED since the last maintenance plan, which is what that plan frees
|
||||
* room for. A count and not a list: any host-only entry makes room for any copy. */
|
||||
int64_t starved_ = 0;
|
||||
|
||||
+14
-7
@@ -43,6 +43,9 @@ MemAllocator& rad_malloc_allocator() { static MallocAllocator a; return a; }
|
||||
/* ------------------------------------------------------------------ Shortfall */
|
||||
|
||||
std::string Shortfall::str() const {
|
||||
if (!refused.empty())
|
||||
return fmt("%s: %s of %s refused: %s", pool.c_str(), what.c_str(),
|
||||
humanb(wanted).c_str(), refused.c_str());
|
||||
return fmt("%s: %s wanted %s, %s available -- short by %s",
|
||||
pool.c_str(), what.c_str(), humanb(wanted).c_str(),
|
||||
humanb(available).c_str(), humanb(missing()).c_str());
|
||||
@@ -81,8 +84,11 @@ int Pool::init(std::string_view nm, int64_t bytes, int kind, MemAllocator* a, bo
|
||||
base_ = a->alloc(bytes_, kind);
|
||||
if (!base_) {
|
||||
/* Refuse; do not retry smaller. An engine that quietly re-optimises the split is an
|
||||
* engine whose benchmarks do not reproduce (spec §6). */
|
||||
shortfalls_.push_back({name_, "backing allocation", bytes_, 0});
|
||||
* engine whose benchmarks do not reproduce (spec §6). The allocator's reason goes with
|
||||
* it: the device layer says what the driver answered. */
|
||||
const char* why = a == &rad_device_allocator() ? rad_dev_last_error() : nullptr;
|
||||
shortfalls_.push_back({name_, "backing allocation", bytes_, 0,
|
||||
why && *why ? why : "the allocator returned nothing"});
|
||||
bytes_ = 0;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -131,7 +137,9 @@ int Pool::init_elastic(std::string_view nm, int64_t bytes, int kind, MemAllocato
|
||||
/* Refuse; do not retry smaller. An address range is not memory -- a reservation that
|
||||
* fails on a 64-bit card is a bug and not a budget, and quietly halving it would hide the
|
||||
* bug behind a pool that cannot grow to what the operator asked for. */
|
||||
shortfalls_.push_back({ name_, "address reservation", bytes_, 0 });
|
||||
const char* why = rad_dev_last_error();
|
||||
shortfalls_.push_back({ name_, "address reservation", bytes_, 0,
|
||||
*why ? why : "the device layer gave no reason" });
|
||||
bytes_ = 0;
|
||||
return rc;
|
||||
}
|
||||
@@ -205,7 +213,7 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
if (cfg.vram_kv_mib <= 0) missing += " vram_kv resolved to 0 MiB\n";
|
||||
if (!missing.empty()) {
|
||||
fit_report_ = "VRAM pool budgets are empty -- state --vram-weights-mib / --vram-kv-mib, or "
|
||||
"let the card be split by --gpu-headroom-mib and --expert-vs-cache-ratio:\n"
|
||||
"let the card be split from --gpu-headroom-mib and --host-pool-mib:\n"
|
||||
+ missing;
|
||||
RAD_ERR("%s", fit_report_.c_str());
|
||||
return RAD_E_INVAL;
|
||||
@@ -222,9 +230,8 @@ int Pools::configure(const Config& cfg, int64_t vram_capacity,
|
||||
" total %10s\n"
|
||||
" card total %10s\n"
|
||||
" OVER BY %10s\n"
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or raise --gpu-headroom-mib and let "
|
||||
"--expert-vs-cache-ratio split what is left. The split is yours to make; the engine "
|
||||
"will not make it for you (spec §6).\n",
|
||||
"Lower --vram-weights-mib / --vram-kv-mib, or state neither and let the card be split "
|
||||
"from --gpu-headroom-mib and --host-pool-mib (spec §6).\n",
|
||||
humanb(w).c_str(), humanb(kv).c_str(),
|
||||
humanb(want).c_str(), humanb(vram_capacity).c_str(),
|
||||
humanb(want - vram_capacity).c_str());
|
||||
|
||||
@@ -54,6 +54,10 @@ struct Shortfall {
|
||||
std::string what; /* what was being reserved when it ran out */
|
||||
int64_t wanted = 0;
|
||||
int64_t available = 0;
|
||||
/* A backing allocation the allocator refused: there is no "available" to report, only the
|
||||
* allocator's own sentence for why, which is what tells an out-of-memory card from a pinned-
|
||||
* memory limit from a driver that would not map the range. */
|
||||
std::string refused;
|
||||
int64_t missing() const { return wanted - available; }
|
||||
std::string str() const;
|
||||
};
|
||||
|
||||
+251
-78
@@ -184,7 +184,7 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_
|
||||
|
||||
enabled_ = true;
|
||||
report_ = fmt("prefix cache: %zu paged group(s) at %lld-token blocks; linear checkpoints "
|
||||
"every %lld tokens (%s x %s), retention '%s'\n",
|
||||
"every %lld tokens (%s a rank x %s, pinned host memory), retention '%s'\n",
|
||||
groups_.size(), (long long)block_size_,
|
||||
(long long)(has_linear_ ? interval_ : 0),
|
||||
humanb(kv->checkpoint_bytes()).c_str(),
|
||||
@@ -224,7 +224,8 @@ void PrefixCache::touch(const BlockHash& h) const {
|
||||
|
||||
CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const {
|
||||
std::vector<std::vector<int32_t>>* blocks_out,
|
||||
const HitCap* cap) const {
|
||||
CacheHit hit;
|
||||
if (blocks_out) { blocks_out->assign(groups_.size(), {}); }
|
||||
if (!enabled_ || tokens.empty()) return hit;
|
||||
@@ -261,6 +262,43 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
* forward pass. */
|
||||
if (matched * block_size_ >= (int64_t)tokens.size() && matched > 0) --matched;
|
||||
|
||||
/* OVER THE SNAPSHOTS, NOT OVER THE POSITIONS. A checkpoint sits on the interval or at the
|
||||
* tail of a prompt (Scheduler::plan_chunk), which is any block boundary, so the deepest one
|
||||
* at or below `limit` is found by asking each snapshot whether this chain passes through it:
|
||||
* its key is the chained hash at its own position, which matches only on the same prefix. The
|
||||
* index holds a few hundred snapshots against tens of thousands of block positions. */
|
||||
auto deepest = [&](int64_t limit) {
|
||||
auto best = ck_by_prefix_.end();
|
||||
for (auto it = ck_by_prefix_.begin(); it != ck_by_prefix_.end(); ++it) {
|
||||
const Ckpt& c = it->second;
|
||||
if (!c.valid || c.detached || c.slot < 0 || c.pos <= 0 || c.pos > limit ||
|
||||
c.pos % block_size_ != 0)
|
||||
continue;
|
||||
if (best != ck_by_prefix_.end() && c.pos <= best->second.pos) continue;
|
||||
if (hs[(size_t)(c.pos / block_size_ - 1)] != it->first) continue;
|
||||
best = it;
|
||||
}
|
||||
return best;
|
||||
};
|
||||
/* What a hit of `m` blocks lets a sequence skip: all of it, or with recurrent state only up
|
||||
* to the deepest checkpoint under it (Scheduler::admit_one resumes there). */
|
||||
auto reusable = [&](int64_t m) -> int64_t {
|
||||
if (!has_linear_) return m * block_size_;
|
||||
const auto b = deepest(m * block_size_);
|
||||
return b == ck_by_prefix_.end() ? 0 : b->second.pos;
|
||||
};
|
||||
if (cap && matched > cap->tokens / block_size_) {
|
||||
const int64_t whole = reusable(matched);
|
||||
if (whole > cap->tokens) {
|
||||
const int64_t m = cap->tokens > 0 ? cap->tokens / block_size_ : 0;
|
||||
const int64_t lost = whole - reusable(m);
|
||||
if (lost <= cap->max_give_back) {
|
||||
matched = m;
|
||||
hit.given_back = (int32_t)lost;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (int64_t b = 0; b < matched; ++b) {
|
||||
touch(hs[(size_t)b]);
|
||||
if (!blocks_out) continue;
|
||||
@@ -279,26 +317,24 @@ CacheHit PrefixCache::lookup(const std::vector<int32_t>& tokens,
|
||||
|
||||
/* ---- the split: how far the LINEAR state can be reused ----
|
||||
* The attention blocks are reusable up to n_attn_tokens. The recurrent state is only reusable
|
||||
* at a checkpoint, so walk back to the last checkpoint boundary at or below n_attn_tokens and
|
||||
* look it up by the chained hash there. The gap between the two is replayed through the linear
|
||||
* layers only -- the attention layers for those tokens are already in the cache. */
|
||||
* at a checkpoint: the deepest snapshot at or below n_attn_tokens on this chain, in its store
|
||||
* slot. The scheduler resumes from there (Scheduler::admit_one) and recomputes the tokens
|
||||
* between the two. */
|
||||
if (!has_linear_) {
|
||||
/* No recurrent state means nothing to replay: the whole attention hit is directly usable. */
|
||||
hit.n_linear_tokens = hit.n_attn_tokens;
|
||||
return hit;
|
||||
}
|
||||
for (int64_t p = (hit.n_attn_tokens / interval_) * interval_; p > 0; p -= interval_) {
|
||||
const BlockHash& h = hs[(size_t)(p / block_size_ - 1)];
|
||||
auto it = ck_by_prefix_.find(h);
|
||||
if (it == ck_by_prefix_.end() || !it->second.valid) continue;
|
||||
hit.n_linear_tokens = (int32_t)p;
|
||||
hit.checkpoint_slot = it->second.slot;
|
||||
it->second.used = ++clock_;
|
||||
handed_.push_back(h);
|
||||
++stats_.ckpt_hits;
|
||||
const auto best = deepest(hit.n_attn_tokens);
|
||||
if (best == ck_by_prefix_.end()) {
|
||||
++stats_.ckpt_misses;
|
||||
return hit;
|
||||
}
|
||||
++stats_.ckpt_misses;
|
||||
hit.n_linear_tokens = (int32_t)best->second.pos;
|
||||
hit.checkpoint_slot = best->second.slot;
|
||||
best->second.used = ++clock_;
|
||||
handed_.push_back(best->first);
|
||||
++stats_.ckpt_hits;
|
||||
return hit;
|
||||
}
|
||||
|
||||
@@ -393,6 +429,27 @@ int PrefixCache::insert(uint64_t session,
|
||||
}
|
||||
tiers_->note_session(session, hs, n_tokens, now);
|
||||
}
|
||||
|
||||
/* A CONVERSATION'S SNAPSHOTS BELONG TO ITS LATEST TURN. The index keys a session by REQUEST
|
||||
* id, so each turn would otherwise keep its own tip forever: turn N-1's deepest snapshot stays
|
||||
* a "tip" after turn N has resumed from it and written deeper ones, and the retention policy
|
||||
* then guards a dozen dead tips across a long agent run while thinning the one conversation
|
||||
* that is live. Every snapshot on the chain this request just published is a prefix of it,
|
||||
* and is moved under this id, so the policy sees one session with one tip. */
|
||||
for (auto& kvp : ck_by_prefix_) {
|
||||
Ckpt& c = kvp.second;
|
||||
if (c.session == session || c.pos <= 0 || c.pos > n_full * block_size_ ||
|
||||
c.pos % block_size_ != 0 || hs[(size_t)(c.pos / block_size_ - 1)] != kvp.first)
|
||||
continue;
|
||||
auto old = ck_by_session_.find(c.session);
|
||||
if (old != ck_by_session_.end()) {
|
||||
old->second.erase(std::remove(old->second.begin(), old->second.end(), kvp.first),
|
||||
old->second.end());
|
||||
if (old->second.empty()) ck_by_session_.erase(old);
|
||||
}
|
||||
c.session = session;
|
||||
ck_by_session_[session].push_back(kvp.first);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -406,7 +463,10 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
if (chain) chain->clear();
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
const int64_t n_full = (int64_t)tokens.size() / block_size_;
|
||||
/* THE BLOCKS A HIT CAN USE: one token must remain to compute a logit from, so a prompt that
|
||||
* ends on a block boundary never reuses its last block (lookup backs off by one) and neither
|
||||
* restoring it nor bringing back a snapshot keyed there would be read. */
|
||||
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
|
||||
std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
|
||||
/* Walk exactly as lookup does, and keep walking past the point it stopped for as long as the
|
||||
@@ -447,10 +507,13 @@ void PrefixCache::drop_offdevice(const BlockHash& key) {
|
||||
if (it->second.in_lru) lru_.erase(it->second.lru);
|
||||
map_.erase(it);
|
||||
++stats_.evictions;
|
||||
/* AND THE SNAPSHOT KEYED BY THE SAME HASH. The tiers moved the two halves together, so they
|
||||
* lose them together; leaving the index entry behind would leave a snapshot marked off-device
|
||||
* whose bytes nobody holds, waiting to be promoted by something that no longer exists. */
|
||||
drop_snapshot(key);
|
||||
/* AND THE SNAPSHOT KEYED BY THE SAME HASH, when the disk was all it had: its record is gone,
|
||||
* and an index entry left behind would be a detached snapshot nobody can read back. One still
|
||||
* in its store slot stays -- no lookup reaches it past the missing block, the slot may be
|
||||
* under a disk write this sink cannot ask about, and the retention policy retires it through
|
||||
* the path that does ask (retire_ckpt). */
|
||||
auto ck = ck_by_prefix_.find(key);
|
||||
if (ck != ck_by_prefix_.end() && ck->second.detached) drop_snapshot(key);
|
||||
}
|
||||
|
||||
int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks) {
|
||||
@@ -474,18 +537,30 @@ int PrefixCache::rebind(const BlockHash& key, const std::vector<int32_t>& blocks
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool PrefixCache::shared_with_live(const Entry& e) const {
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
if (kv_->block_refcount(groups_[g], e.blocks[g]) > 1) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
int64_t done = 0;
|
||||
while (done < n && !lru_.empty()) {
|
||||
/* ONE PASS OVER WHAT WAS ON THE LIST WHEN THE CALL BEGAN. An entry a live sequence also holds
|
||||
* goes to the back rather than being evicted: releasing the cache's reference on it frees no
|
||||
* block, and an entry that had no host copy would be erased for nothing. It is in use, which is
|
||||
* what the back of the list means, and moving it is what keeps a caller that asks again from
|
||||
* walking the same shared run every time. */
|
||||
for (int64_t seen = (int64_t)lru_.size(); done < n && seen > 0 && !lru_.empty(); --seen) {
|
||||
const BlockHash h = lru_.front();
|
||||
lru_.pop_front();
|
||||
auto it = map_.find(h);
|
||||
if (it == map_.end()) continue;
|
||||
if (it == map_.end()) { lru_.pop_front(); continue; }
|
||||
Entry& e = it->second;
|
||||
if (shared_with_live(e)) {
|
||||
lru_.splice(lru_.end(), lru_, lru_.begin());
|
||||
continue;
|
||||
}
|
||||
lru_.pop_front();
|
||||
e.in_lru = false;
|
||||
/* Every entry on the list holds its blocks, whatever the tiers are doing with it: one on
|
||||
* its way to a host copy still holds the cache's references until the copy reports, and
|
||||
* the report finds it forgotten and keeps nothing. */
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
if (tiers_) {
|
||||
@@ -505,13 +580,51 @@ int64_t PrefixCache::evict_lru(int64_t n) {
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::trim(int64_t n_blocks) {
|
||||
/* TIERS ATTACHED AND OFF are no tiers: nothing becomes droppable, and waiting for a copy that
|
||||
* nobody will make would leave the reserve unkept for good. */
|
||||
const bool keep = tiers_ && tiers_->any_on();
|
||||
int64_t done = 0;
|
||||
auto it = lru_.begin();
|
||||
for (int64_t seen = (int64_t)lru_.size(); it != lru_.end() && done < n_blocks && seen > 0;
|
||||
--seen) {
|
||||
const BlockHash h = *it;
|
||||
auto m = map_.find(h);
|
||||
if (m == map_.end()) { it = lru_.erase(it); continue; }
|
||||
Entry& e = m->second;
|
||||
if (shared_with_live(e)) {
|
||||
/* In use: to the back, as evict_lru does, and the walk carries on from the next. */
|
||||
auto next = std::next(it);
|
||||
lru_.splice(lru_.end(), lru_, it);
|
||||
it = next;
|
||||
continue;
|
||||
}
|
||||
if (keep && !tiers_->droppable(h)) { ++it; continue; }
|
||||
it = lru_.erase(it);
|
||||
e.in_lru = false;
|
||||
for (size_t g = 0; g < groups_.size(); ++g)
|
||||
kv_->release_block(groups_[g], e.blocks[g]);
|
||||
if (keep) {
|
||||
tiers_->drop_commit(h);
|
||||
++stats_.drops;
|
||||
} else {
|
||||
if (tiers_) tiers_->forget(h);
|
||||
map_.erase(m);
|
||||
++stats_.evictions;
|
||||
}
|
||||
++done;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
int64_t PrefixCache::drop_clean() {
|
||||
if (!tiers_ || !kv_) return 0;
|
||||
drop_scratch_.clear();
|
||||
tiers_->take_clean(&drop_scratch_);
|
||||
const uint64_t frees = kv_->seq_frees();
|
||||
if (frees != frees_seen_) {
|
||||
if (frees != frees_seen_ || released_) {
|
||||
frees_seen_ = frees;
|
||||
released_ = false;
|
||||
drop_scratch_.insert(drop_scratch_.end(), drop_wait_.begin(), drop_wait_.end());
|
||||
drop_wait_.clear();
|
||||
}
|
||||
@@ -525,7 +638,7 @@ int64_t PrefixCache::drop_clean() {
|
||||
/* A BLOCK A RUNNING SEQUENCE ALSO HOLDS WOULD FREE NOTHING, and its entry would then be
|
||||
* off-device in the index while its bytes sat in VRAM under somebody else's table -- the
|
||||
* next lookup would restore a second copy beside them. */
|
||||
bool shared = false;
|
||||
bool shared = held_.count(h) > 0;
|
||||
for (size_t g = 0; g < groups_.size() && !shared; ++g)
|
||||
shared = kv_->block_refcount(groups_[g], e.blocks[g]) > 1;
|
||||
if (shared) {
|
||||
@@ -601,11 +714,11 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
auto it = ck_by_session_.find(session);
|
||||
if (it == ck_by_session_.end()) return 0;
|
||||
|
||||
/* DEVICE-RESIDENT SNAPSHOTS ONLY. This policy exists to spend a fixed number of --checkpoint-
|
||||
* slots well, and it runs when that pool is exhausted. A snapshot the idle tiers hold occupies
|
||||
* none of it, so retiring one would free nothing here and would cost a session the state it
|
||||
* was moved off the device precisely in order to keep. Tiered bytes are bounded by the tiers'
|
||||
* own caps, oldest first, which is the right policy for the resource they actually spend.
|
||||
/* SNAPSHOTS IN THE STORE ONLY. This policy exists to spend a fixed number of --checkpoint-
|
||||
* slots well, and it runs when the store is exhausted. A detached snapshot occupies none of
|
||||
* it, so retiring one would free nothing here and would cost a session the state it was
|
||||
* written to disk precisely in order to keep. The disk store bounds its own, oldest first,
|
||||
* which is the right policy for the resource it actually spends.
|
||||
*
|
||||
* It stays in `kept` rather than being skipped, or the session index would forget it. */
|
||||
std::vector<std::pair<int64_t, BlockHash>> all;
|
||||
@@ -613,7 +726,7 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto e = ck_by_prefix_.find(h);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
if (e->second.off_device) { kept.push_back(h); continue; }
|
||||
if (e->second.detached) { kept.push_back(h); continue; }
|
||||
all.push_back({e->second.pos, h});
|
||||
}
|
||||
std::sort(all.begin(), all.end(),
|
||||
@@ -628,11 +741,19 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
auto e = ck_by_prefix_.find(a.second);
|
||||
if (e != ck_by_prefix_.end()) {
|
||||
retire_ckpt(e);
|
||||
if (e == ck_by_prefix_.end()) continue;
|
||||
/* A SNAPSHOT THE DISK HOLDS LEAVES THE SLOT AND STAYS IN THE INDEX: the policy is about
|
||||
* the slots, and that copy costs none of them. */
|
||||
if (tiers_ && tiers_->snapshot_backed(a.second)) {
|
||||
(void)detach_snapshot(a.second);
|
||||
tiers_->snapshot_detached(a.second);
|
||||
kept.push_back(a.second);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
continue;
|
||||
}
|
||||
retire_ckpt(e);
|
||||
++freed;
|
||||
++stats_.ckpt_evictions;
|
||||
}
|
||||
/* ERASE THE SESSION WHEN NOTHING IS LEFT OF IT, and that is not tidiness. `session` is a
|
||||
* REQUEST id, so without an eraser this map gains an entry for every request that ever writes
|
||||
@@ -648,24 +769,27 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
int32_t* slot_out) {
|
||||
if (!enabled_ || !has_linear_) return RAD_E_UNSUPPORTED;
|
||||
if (!slot_out) return RAD_E_INVAL;
|
||||
if (interval_ <= 0 || pos <= 0 || pos % interval_ != 0) {
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token boundary; the scheduler splits chunks "
|
||||
"at the interval precisely so this cannot happen (spec §7.3)",
|
||||
(long long)pos, (long long)interval_);
|
||||
/* ON A BLOCK BOUNDARY, because the key is the chained hash of whole blocks. The scheduler
|
||||
* places checkpoints on the interval and at the tail of a prompt, both on its chunk quantum,
|
||||
* which is a multiple of the block. */
|
||||
if (interval_ <= 0 || pos <= 0 || pos % block_size_ != 0) {
|
||||
RAD_ERR("checkpoint at %lld is not on a %lld-token block boundary; the scheduler splits "
|
||||
"chunks on its quantum precisely so this cannot happen (spec §7.3)",
|
||||
(long long)pos, (long long)block_size_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
auto existing = ck_by_prefix_.find(prefix);
|
||||
if (existing != ck_by_prefix_.end()) {
|
||||
/* A SNAPSHOT THE TIERS HOLD IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot
|
||||
* would look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk
|
||||
* would silently stop checkpointing; handing back a slot that is not in the pool would be
|
||||
/* A DETACHED SNAPSHOT IS NOT ONE THIS CALL CAN HAND BACK. Returning its -1 slot would
|
||||
* look to the scheduler exactly like a refusal (it tests `cs >= 0`) and the chunk would
|
||||
* silently stop checkpointing; handing back a slot that is not in the store would be
|
||||
* worse. The state is about to be recomputed anyway -- that is what a reservation at this
|
||||
* prefix means -- so the tiered copy is retired and a fresh slot allocated below. */
|
||||
/* NOR ONE A COPY IS READING. The save that follows this reservation writes the slot on
|
||||
* the compute stream while the copy reads it on the transfer stream, and the host would
|
||||
* keep a snapshot that is half of each. A fresh slot costs one allocation. */
|
||||
if (!existing->second.off_device &&
|
||||
!(tiers_ && tiers_->snapshot_reading(prefix))) {
|
||||
* prefix means -- so the disk copy is retired and a fresh slot allocated below. */
|
||||
/* NOR ONE A DISK WRITE IS READING. The save that follows this reservation writes the slot
|
||||
* while the write reads it, and the disk would keep a snapshot that is half of each. A
|
||||
* fresh slot costs one allocation. */
|
||||
if (!existing->second.detached &&
|
||||
!(tiers_ && tiers_->slot_reading(existing->second.slot))) {
|
||||
*slot_out = existing->second.slot;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -710,10 +834,13 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
const Ckpt* victim = nullptr;
|
||||
const Ckpt* tip_victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
/* A TIERED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
|
||||
* Its device slot went back to the pool when the tiers took the bytes, so picking
|
||||
* it as the victim would retire a usable snapshot and then fail the retry anyway. */
|
||||
if (kvp.second.off_device) continue;
|
||||
/* A DETACHED SNAPSHOT IS NOT A CANDIDATE, because evicting it frees nothing HERE.
|
||||
* Its slot went back to the store when it was detached, so picking it as the
|
||||
* victim would retire a usable snapshot and then fail the retry anyway. */
|
||||
if (kvp.second.detached) continue;
|
||||
/* NOR ONE A DISK WRITE IS READING: its slot comes back only when the write
|
||||
* reports, so retiring it now loses the snapshot and frees nothing yet. */
|
||||
if (tiers_ && tiers_->slot_reading(kvp.second.slot)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
@@ -731,9 +858,9 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
if (!victim) return RAD_E_FULL;
|
||||
BlockHash vh = victim->prefix;
|
||||
uint64_t vs = victim->session;
|
||||
/* A VICTIM THE TIERS HOLD A COPY OF IS DETACHED, NOT LOST. The slot goes back all the
|
||||
* same; the index entry stays, and the session's next restore brings the state back
|
||||
* with its blocks instead of replaying every recurrent layer from an older point. */
|
||||
/* A VICTIM THE DISK HOLDS IS DETACHED, NOT LOST. The slot goes back all the same; the
|
||||
* index entry stays, and the session's next restore reads the state back instead of
|
||||
* replaying every recurrent layer from an older point. */
|
||||
if (tiers_ && tiers_->snapshot_backed(vh)) {
|
||||
(void)detach_snapshot(vh);
|
||||
tiers_->snapshot_detached(vh);
|
||||
@@ -766,15 +893,17 @@ int PrefixCache::reserve_checkpoint(uint64_t session, int64_t pos, const BlockHa
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
void PrefixCache::commit_checkpoint(const BlockHash& prefix, bool resume) {
|
||||
auto it = ck_by_prefix_.find(prefix);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* One that lost its slot between the reservation and now holds nothing to serve. */
|
||||
if (it->second.detached || it->second.slot < 0) return;
|
||||
it->second.valid = true;
|
||||
/* THE TIERS LEARN THE SNAPSHOT HERE, for the same reason note_used tells them the block ids:
|
||||
* a demotion has to know what to move and this index is the only place it is written down.
|
||||
* Before the commit there is nothing to move -- the slot still holds the previous tenant's
|
||||
* state -- so this is also the earliest moment at which telling them would be true. */
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos);
|
||||
if (tiers_) tiers_->note_snapshot(prefix, it->second.slot, it->second.pos, resume);
|
||||
}
|
||||
|
||||
|
||||
@@ -782,16 +911,16 @@ void PrefixCache::commit_checkpoint(const BlockHash& prefix) {
|
||||
|
||||
void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it) {
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
/* THE TIERS ARE ASKED FIRST, because they may be reading the slot: a copy to host memory in
|
||||
* flight out of a slot the pool then decommits reads a page that is no longer mapped. When
|
||||
* one is, the tiers keep the slot and hand it back once the copy has reported. */
|
||||
const bool held = tiers_ && tiers_->release_snapshot(it->first);
|
||||
/* THE TIERS ARE ASKED FIRST, because a disk write may be reading the slot: a save into it
|
||||
* before the write is done would put half of another snapshot on disk under this key. When
|
||||
* one is, the tiers keep the slot and hand it back once the write has reported. */
|
||||
const bool held = tiers_ && tiers_->release_snapshot(it->first, it->second.slot);
|
||||
if (it->second.slot >= 0 && !held) kv_->free_checkpoint(it->second.slot);
|
||||
/* TOLD EITHER WAY, AND NOT ONLY WHEN THE TIERS HOLD THE BYTES. They also remember a snapshot's
|
||||
* DEVICE slot -- note_snapshot records it at commit, because a demotion has to know what to
|
||||
* copy and this index is the only place it is written down. Freeing that slot here without
|
||||
* saying so leaves the tiers naming a slot the pool has since given to another session, and
|
||||
* the next demotion copies THAT session's recurrent state and restores it as this one's. The
|
||||
/* TOLD EITHER WAY, AND NOT ONLY WHEN THE DISK HOLDS THE BYTES. The tiers also remember a
|
||||
* snapshot's slot -- note_snapshot records it at commit, because a disk write has to know
|
||||
* what to read and this index is the only place it is written down. Freeing that slot here
|
||||
* without saying so leaves the tiers naming a slot the store has since given to another
|
||||
* session, and the next write puts THAT session's recurrent state on disk as this one's. The
|
||||
* text that comes back is fluent, deterministic and about the wrong conversation, which is
|
||||
* the exact failure the whole tier design is arranged to make impossible.
|
||||
*
|
||||
@@ -803,10 +932,11 @@ void PrefixCache::retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>
|
||||
int PrefixCache::detach_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (it->second.off_device) return RAD_OK; /* already theirs */
|
||||
if (it->second.detached) return RAD_OK; /* already only on disk */
|
||||
/* Only ever asked of a snapshot the tiers call backed, which no write is reading. */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
it->second.slot = -1;
|
||||
it->second.off_device = true;
|
||||
it->second.detached = true;
|
||||
/* NOT SERVABLE FROM HERE ON, which is the same state a reserved-but-unwritten snapshot is in
|
||||
* and is handled by the same branch in lookup(). A hit that reaches this position simply walks
|
||||
* back to an older checkpoint, or to none -- shorter, never wrong. */
|
||||
@@ -818,11 +948,15 @@ int PrefixCache::reattach_snapshot(const BlockHash& key, int32_t slot) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return RAD_E_NOTFOUND;
|
||||
if (slot < 0) return RAD_E_INVAL;
|
||||
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The promotion allocated it and filled it
|
||||
* from the tier copy of THIS key's state, so the identity that matters -- which prefix the
|
||||
/* AN ENTRY ALREADY IN A SLOT keeps it: taking the new one would leak the old. The caller gives
|
||||
* the new slot back. */
|
||||
if (!it->second.detached && it->second.slot >= 0) return it->second.slot == slot ? RAD_OK
|
||||
: RAD_E_STATE;
|
||||
/* A SLOT THIS ENTRY DID NOT ASK FOR IS STILL ITS OWN. The read allocated it and filled it
|
||||
* from the disk copy of THIS key's state, so the identity that matters -- which prefix the
|
||||
* bytes describe -- is carried by the key and not by the slot number it happened to get. */
|
||||
it->second.slot = slot;
|
||||
it->second.off_device = false;
|
||||
it->second.detached = false;
|
||||
it->second.valid = true;
|
||||
it->second.used = ++clock_;
|
||||
return RAD_OK;
|
||||
@@ -833,7 +967,7 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
const Ckpt* victim = nullptr;
|
||||
for (const auto& kvp : ck_by_prefix_) {
|
||||
const Ckpt& c = kvp.second;
|
||||
if (c.off_device || c.slot < 0 || !c.valid) continue;
|
||||
if (c.detached || c.slot < 0 || !c.valid) continue;
|
||||
if (victim && c.used >= victim->used) continue;
|
||||
if (std::find(handed_.begin(), handed_.end(), kvp.first) != handed_.end()) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
@@ -846,12 +980,51 @@ bool PrefixCache::free_checkpoint_for_restore() {
|
||||
return true;
|
||||
}
|
||||
|
||||
void PrefixCache::hold(uint64_t req, const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm) {
|
||||
if (!enabled_ || !tiers_ || tokens.empty() || holds_.count(req)) return;
|
||||
const int64_t n_full = ((int64_t)tokens.size() - 1) / block_size_;
|
||||
const std::vector<BlockHash> hs = chain_all(tokens, mm, n_full);
|
||||
std::vector<BlockHash>& mine = holds_[req];
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
auto it = map_.find(hs[(size_t)b]);
|
||||
if (it == map_.end()) break;
|
||||
const int32_t* src = tokens.data() + b * block_size_;
|
||||
if ((int64_t)it->second.tokens.size() != block_size_ ||
|
||||
std::memcmp(it->second.tokens.data(), src, (size_t)block_size_ * sizeof(int32_t)) != 0)
|
||||
break;
|
||||
mine.push_back(hs[(size_t)b]);
|
||||
++held_[hs[(size_t)b]];
|
||||
}
|
||||
}
|
||||
|
||||
size_t PrefixCache::resident_prefix(const std::vector<BlockHash>& chain) const {
|
||||
size_t n = 0;
|
||||
for (; n < chain.size(); ++n) {
|
||||
auto it = map_.find(chain[n]);
|
||||
if (it == map_.end() || !it->second.in_lru) break;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
void PrefixCache::release(uint64_t req) {
|
||||
auto it = holds_.find(req);
|
||||
if (it == holds_.end()) return;
|
||||
for (const BlockHash& h : it->second) {
|
||||
auto k = held_.find(h);
|
||||
if (k != held_.end() && --k->second <= 0) held_.erase(k);
|
||||
}
|
||||
holds_.erase(it);
|
||||
released_ = true;
|
||||
}
|
||||
|
||||
void PrefixCache::drop_snapshot(const BlockHash& key) {
|
||||
auto it = ck_by_prefix_.find(key);
|
||||
if (it == ck_by_prefix_.end()) return;
|
||||
const uint64_t session = it->second.session;
|
||||
/* No release_snapshot on this path: the tiers are the caller and the bytes are already gone.
|
||||
* Telling them to free what they just lost would double-free the arena slot. */
|
||||
/* No release_snapshot on this path: the tiers are the caller, holding their lock, and the
|
||||
* bytes are already gone. They say this only of a detached snapshot, so there is normally no
|
||||
* slot to give back. */
|
||||
if (it->second.slot >= 0) kv_->free_checkpoint(it->second.slot);
|
||||
ck_by_prefix_.erase(it);
|
||||
++stats_.ckpt_evictions;
|
||||
@@ -861,9 +1034,9 @@ void PrefixCache::drop_snapshot(const BlockHash& key) {
|
||||
if (sit->second.empty()) ck_by_session_.erase(sit);
|
||||
}
|
||||
|
||||
int64_t PrefixCache::snapshots_off_device() const {
|
||||
int64_t PrefixCache::snapshots_detached() const {
|
||||
int64_t n = 0;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.off_device) ++n;
|
||||
for (const auto& kvp : ck_by_prefix_) if (kvp.second.detached) ++n;
|
||||
return n;
|
||||
}
|
||||
} /* namespace rad */
|
||||
+86
-47
@@ -43,8 +43,8 @@
|
||||
* is unaffected either way; the only difference is whether the prefixes still exist when the next
|
||||
* turn asks for them, and that difference is one to two orders of magnitude of time to first
|
||||
* token. Size the cache so live sessions fit with room to spare -- a context of T tokens occupies
|
||||
* roughly 1.8 x T pool-tokens across the paged groups -- and keep --expert-vs-cache-ratio on the
|
||||
* safe side of that.
|
||||
* roughly 1.8 x T pool-tokens across the paged groups. The budget gives the cache everything the
|
||||
* experts can do without (core/mem/vram_budget.h); --host-pool-mib is what moves that.
|
||||
*
|
||||
* WHAT TO WATCH: `kv_util` (/stats, or vllm:kv_cache_usage_perc) is the predictor, and
|
||||
* `radiance:prefix_cache_evictions_total` is the event -- the hit rate is neither, because it only
|
||||
@@ -108,6 +108,18 @@ struct CacheHit {
|
||||
int32_t n_attn_tokens = 0; /* attention KV reused directly, always a whole block multiple */
|
||||
int32_t n_linear_tokens = 0; /* linear state reused; <= n_attn_tokens, a checkpoint multiple */
|
||||
int32_t checkpoint_slot = -1; /* the snapshot holding that state, -1 if none */
|
||||
int32_t given_back = 0; /* reusable tokens a HitCap took off the whole hit */
|
||||
};
|
||||
|
||||
/* A HIT ENDED EARLY ON PURPOSE. The hit ends no later than `tokens` -- at a block and, for a model
|
||||
* with recurrent state, at the deepest checkpoint at or below it -- unless that gives back more
|
||||
* than `max_give_back` of what the whole hit would reuse, in which case the whole hit stands. It
|
||||
* exists for a drafter whose own KV the cache does not hold (Scheduler::init, --draft-refill):
|
||||
* recomputing the prompt's tail gives it context, and a cap whose nearest checkpoint is far below
|
||||
* would recompute far more than that tail. */
|
||||
struct HitCap {
|
||||
int64_t tokens = 0;
|
||||
int64_t max_give_back = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ retention policy */
|
||||
@@ -181,10 +193,11 @@ public:
|
||||
*
|
||||
* NEVER returns the whole prompt: at least one token must remain for the step to compute a
|
||||
* logit from, so a full hit is backed off by one block. That is not a subtlety the caller
|
||||
* should have to know. */
|
||||
* should have to know. `cap`, when given, ends the hit early (HitCap). */
|
||||
CacheHit lookup(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr) const;
|
||||
std::vector<std::vector<int32_t>>* blocks_out = nullptr,
|
||||
const HitCap* cap = nullptr) const;
|
||||
|
||||
/* Publish the whole blocks a sequence just filled. `blocks[i]` is the block table of
|
||||
* cached_groups()[i]. Takes a KV reference on every newly indexed block. */
|
||||
@@ -203,6 +216,20 @@ public:
|
||||
* instead of forgetting it: the next turn restores it rather than re-prefilling it. Only an
|
||||
* entry with no host copy yet is lost. Either way the blocks go back to the pool. */
|
||||
int64_t evict_lru(int64_t n_entries);
|
||||
/* FREE UP TO `n_blocks` BLOCKS OF THE POOL for the reserve the scheduler keeps, losing nothing
|
||||
* a later turn could have reused. One walk of the LRU list, oldest first, that takes only what
|
||||
* gives the pool a block back without costing a conversation:
|
||||
*
|
||||
* - an entry a live sequence also holds is passed over. Releasing the cache's reference on
|
||||
* it frees nothing, and without a host copy it erases the entry -- which, right after a
|
||||
* publish, is the conversation that request just finished;
|
||||
* - with the idle tiers on, an entry whose host copy has not landed is passed over too. It
|
||||
* is the next turn's context with nowhere else to come from, and in a moment it is clean
|
||||
* and can leave VRAM for nothing.
|
||||
*
|
||||
* Pressure that cannot wait -- an admission or a step that needs the blocks now -- is
|
||||
* evict_lru's. Returns how many blocks went back. */
|
||||
int64_t trim(int64_t n_blocks);
|
||||
/* GIVE UP EVERY VRAM COPY THAT CAN GO FOR NOTHING: the entries whose host copy has landed and
|
||||
* that no running sequence is still reading. Called when the memory has a better use -- the
|
||||
* expert slab's loan -- and returns how many entries left VRAM. An entry a sequence still
|
||||
@@ -258,50 +285,53 @@ public:
|
||||
/* ---------------- the linear half of an idle session ----------------
|
||||
*
|
||||
* ON A HYBRID MODEL THE BLOCKS ARE ONLY HALF OF WHAT A SESSION NEEDS BACK. The other half is
|
||||
* the recurrent state, and it lives in a CHECKPOINT SLOT: a device-resident object of
|
||||
* KVManager::checkpoint_bytes(), of which there are --checkpoint-slots IN TOTAL for the whole
|
||||
* server. Eight by default, against the six or seven a single 200K session retains under
|
||||
* geometric backoff -- so a second session evicts the first's snapshots, tip included.
|
||||
*
|
||||
* Tiering the blocks and leaving the snapshot behind therefore gets the trade backwards: it
|
||||
* frees the plentiful resource and holds on to the scarce one. And what the session loses is
|
||||
* not part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a
|
||||
* hit can reach, because RadBatch carries one query length for every KV group and the linear
|
||||
* the recurrent state, and it lives in a CHECKPOINT SLOT: a slot of the engine's snapshot
|
||||
* store in pinned host memory, KVManager::checkpoint_bytes() a rank, of which there are
|
||||
* --checkpoint-slots IN TOTAL for the whole server. What the session loses without it is not
|
||||
* part of its hit, it is ALL of it -- the scheduler clamps reuse to the last checkpoint a hit
|
||||
* can reach, because RadBatch carries one query length for every KV group and the linear
|
||||
* layers cannot be replayed over a longer range than the attention ones (core/sched/
|
||||
* scheduler.cpp, admit_one). A restored session with no reachable snapshot reuses zero tokens
|
||||
* and re-prefills its whole transcript. The blocks without the state are not a partial win;
|
||||
* they are unusable.
|
||||
* and re-prefills its whole transcript.
|
||||
*
|
||||
* So a snapshot moves with the blocks whose hash it is keyed by, and these calls are the
|
||||
* cache's whole part in that. The bytes are the engine's to move. */
|
||||
* A snapshot never needs to follow its blocks: it is restored straight out of its slot into
|
||||
* the new sequence's state, wherever the blocks are. The only tier below the store is disk,
|
||||
* and a snapshot the disk holds can give its slot up and stay in the index (DETACHED) until a
|
||||
* read brings it back. */
|
||||
|
||||
/* Its bytes are on another tier now: give the device slot back and stop offering it. The index
|
||||
* entry STAYS, because that is what a promotion puts the snapshot back into, and an entry
|
||||
* whose state is not in the pool is exactly the `valid` flag's existing meaning -- lookup
|
||||
* already walks past one and falls back to an older position. */
|
||||
/* Its bytes are only on disk now: give the slot back and stop offering it. The index entry
|
||||
* STAYS, because that is what a read off disk puts the snapshot back into, and an entry whose
|
||||
* state is not in the store is exactly the `valid` flag's existing meaning -- lookup already
|
||||
* walks past one and falls back to an older position. */
|
||||
int detach_snapshot(const BlockHash& key);
|
||||
/* And back again, into a slot the caller has already filled. */
|
||||
int reattach_snapshot(const BlockHash& key, int32_t slot);
|
||||
/* A DEVICE CHECKPOINT SLOT FOR A RESTORE. The pool is --checkpoint-slots deep for the whole
|
||||
* server, and it is full whenever as many sessions have run since; a session restored then
|
||||
* would get its blocks back and replay every recurrent layer from an older point, because its
|
||||
* state has nowhere to land. One slot is freed by detaching the least recently used snapshot
|
||||
* the tiers hold a copy of -- which the next restore of THAT session brings back -- and never
|
||||
* one whose only copy is the slot, and never one a lookup has handed out since the step began:
|
||||
* that request reads the slot in this step's forward, and a restore writes it before the
|
||||
* forward runs. True when a slot was freed. */
|
||||
/* A STORE SLOT FOR A READ OFF DISK. The store is --checkpoint-slots deep for the whole server,
|
||||
* and it is full whenever as many sessions have run since; a session whose snapshot is only on
|
||||
* disk would then replay every recurrent layer from an older point, because its state has
|
||||
* nowhere to land. One slot is freed by detaching the least recently used snapshot the disk
|
||||
* also holds -- which the next restore of THAT session reads back -- and never one whose only
|
||||
* copy is the slot, and never one a lookup has handed out since the step began: that request's
|
||||
* restore reads the slot ahead of its step. True when a slot was freed. */
|
||||
bool free_checkpoint_for_restore();
|
||||
/* KEEP A WAITING REQUEST'S CHAIN ON THE CARD. An admission that restored a chain and was then
|
||||
* refused -- no free sequence, no room in the pool -- gives its hit back, and its entries are
|
||||
* clean: drop_clean would let them go at the next pass and the next attempt would restore the
|
||||
* same chain again, every step for as long as the request waits. A held entry is passed over
|
||||
* by drop_clean until release(); trim and evict_lru still take it under pressure, which costs
|
||||
* a restore and loses nothing. Idempotent per request. */
|
||||
void hold(uint64_t req, const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm);
|
||||
/* How many of `chain`'s leading entries are in VRAM: as far as a lookup's hit can reach. */
|
||||
size_t resident_prefix(const std::vector<BlockHash>& chain) const;
|
||||
void release(uint64_t req);
|
||||
/* A step's admissions begin. The snapshots the last step's lookups handed out have been read
|
||||
* by its forward, which committed before this step was planned. */
|
||||
void begin_step() { handed_.clear(); }
|
||||
/* The tiers lost it -- a capacity drop, a failed promotion, or an entry they were told to
|
||||
* forget. Erase the index entry; there is no device slot to give back. */
|
||||
/* The tiers lost it -- the disk store let it go, a failed read, or an entry they were told to
|
||||
* forget. Erase the index entry and give back the slot, if it still has one. */
|
||||
void drop_snapshot(const BlockHash& key);
|
||||
/* How many snapshots the index holds whose bytes the tiers have. Reported rather than derived
|
||||
* because it is the number that says whether hybrid tiering is doing anything at all: a
|
||||
* session can move its whole chain off the device and still be re-prefilling its linear
|
||||
* layers from zero on every hit, and nothing else distinguishes the two. */
|
||||
int64_t snapshots_off_device() const;
|
||||
/* How many snapshots the index holds whose bytes are only on disk. */
|
||||
int64_t snapshots_detached() const;
|
||||
/* ---------------- linear checkpoints ---------------- */
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
* checkpoint lands on a boundary (spec §7.1, §7.3). */
|
||||
@@ -313,8 +343,9 @@ public:
|
||||
int reserve_checkpoint(uint64_t session, int64_t pos, const BlockHash& prefix,
|
||||
int32_t* slot_out);
|
||||
/* The state named by `prefix` is now IN its slot. Until this is called the reservation is only
|
||||
* a promise and lookup() will not offer it -- see Ckpt::valid. */
|
||||
void commit_checkpoint(const BlockHash& prefix);
|
||||
* a promise and lookup() will not offer it -- see Ckpt::valid. A `resume` point is copied off
|
||||
* the card at once (IdleTiers::note_snapshot). */
|
||||
void commit_checkpoint(const BlockHash& prefix, bool resume = false);
|
||||
/* Every checkpoint of a session, ascending. */
|
||||
std::vector<int64_t> checkpoints(uint64_t session) const;
|
||||
/* Apply the retention policy to one session now. Returns how many snapshots were released.
|
||||
@@ -361,21 +392,24 @@ private:
|
||||
* lookup between those two points would hand out a slot holding the previous tenant's
|
||||
* history, which is the exact failure this whole mechanism exists to prevent. */
|
||||
bool valid = false;
|
||||
/* ARE THE BYTES STILL IN THE POOL. The idle tiers move a snapshot along with the blocks
|
||||
* it is keyed by, and `slot` is -1 for the whole time they hold it. Kept as its own flag
|
||||
* rather than inferred from the slot so that the two reasons a snapshot cannot be served
|
||||
* -- not written yet, and not here -- stay distinguishable in a debugger and in a report. */
|
||||
bool off_device = false;
|
||||
/* ARE THE BYTES ONLY ON DISK. A detached snapshot gave its store slot up because the disk
|
||||
* holds it, and `slot` is -1 until a read brings it back. Kept as its own flag rather than
|
||||
* inferred from the slot so that the two reasons a snapshot cannot be served -- not written
|
||||
* yet, and not here -- stay distinguishable in a debugger and in a report. */
|
||||
bool detached = false;
|
||||
};
|
||||
|
||||
std::vector<BlockHash> chain_all(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks) const;
|
||||
void touch(const BlockHash& h) const;
|
||||
/* Retire one snapshot whatever tier holds its bytes: a device slot goes back to the pool, and
|
||||
* tiered bytes go back to the tiers. One place, because three call sites that each remembered
|
||||
* to check `off_device` would be three places to forget. The session index is the caller's,
|
||||
* since every caller is already rebuilding or erasing it. */
|
||||
/* Does a live sequence hold any of this entry's blocks as well? Then releasing the cache's
|
||||
* reference frees nothing. */
|
||||
bool shared_with_live(const Entry& e) const;
|
||||
/* Retire one snapshot whatever tier holds its bytes: a slot goes back to the store, and a disk
|
||||
* copy goes back to the tiers. One place, because three call sites that each remembered to
|
||||
* check `detached` would be three places to forget. The session index is the caller's, since
|
||||
* every caller is already rebuilding or erasing it. */
|
||||
void retire_ckpt(std::unordered_map<BlockHash, Ckpt, BlockHashHash>::iterator it);
|
||||
|
||||
KVManager* kv_ = nullptr;
|
||||
@@ -394,6 +428,11 @@ private:
|
||||
std::vector<BlockHash> drop_wait_;
|
||||
std::vector<BlockHash> drop_scratch_;
|
||||
uint64_t frees_seen_ = 0;
|
||||
/* hold(): the keys each waiting request holds, and how many requests hold each key. A release
|
||||
* makes drop_wait_ worth looking at again, as a freed sequence does. */
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> holds_;
|
||||
std::unordered_map<BlockHash, int32_t, BlockHashHash> held_;
|
||||
bool released_ = false;
|
||||
mutable std::unordered_map<BlockHash, Ckpt, BlockHashHash> ck_by_prefix_;
|
||||
std::unordered_map<uint64_t, std::vector<BlockHash>> ck_by_session_;
|
||||
/* Snapshots lookup handed out since begin_step: not a restore's to take (free_checkpoint_for_restore). */
|
||||
|
||||
+100
-47
@@ -22,6 +22,13 @@ int64_t to_mib(int64_t bytes) { return bytes > 0 ? bytes / kMiB : 0; }
|
||||
* footprint to the byte, and there the rounding direction decides whether it loads. The MiB this
|
||||
* claims comes out of the headroom, which is what the headroom is for. */
|
||||
int64_t to_mib_up(int64_t bytes) { return bytes > 0 ? (bytes + kMiB - 1) / kMiB : 0; }
|
||||
|
||||
/* WHAT THE DRIVER'S OWN HOLDING MOVES BY AFTER IT IS READ. `already_held` is one reading, and on
|
||||
* ROCm 7.2 the same server started twice has read 4 MiB less than it later held (and once 30 MiB
|
||||
* more): a budget that split the difference away came up a few MiB short of the headroom the
|
||||
* first launches of kernels allocate from. Four times the drift seen, and charged before anything
|
||||
* is split. */
|
||||
constexpr int64_t kDriverDrift = 16 * kMiB;
|
||||
} /* namespace */
|
||||
|
||||
/* WHAT THE CACHE BACKS, counted on its PAGED part. The ceiling is the recurrent and conv state of
|
||||
@@ -33,7 +40,10 @@ static double paged_share(const VramBudget& b) {
|
||||
return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
|
||||
}
|
||||
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
|
||||
/* The resolver, with its log lines behind `log`: vram_budget_trial asks the same question
|
||||
* of a configuration it may not use, and a refusal printed for a split nobody takes reads as the
|
||||
* startup failing. */
|
||||
static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out, bool log) {
|
||||
VramBudget b;
|
||||
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
|
||||
|
||||
@@ -43,18 +53,28 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
b.capacity = per_rank[0].capacity;
|
||||
int64_t freeb = per_rank[0].free;
|
||||
int64_t layer_max = 0;
|
||||
int64_t layer_max = 0, kv_one = 0;
|
||||
for (const VramFacts& f : per_rank) {
|
||||
b.capacity = std::min(b.capacity, f.capacity);
|
||||
freeb = std::min(freeb, f.free);
|
||||
b.arena = std::max(b.arena, f.arena);
|
||||
b.staging = std::max(b.staging, f.staging);
|
||||
if ((int64_t)f.n_queues * f.queue_bytes > b.queues) {
|
||||
b.queues = (int64_t)f.n_queues * f.queue_bytes;
|
||||
b.n_queues = f.n_queues;
|
||||
b.queue_bytes = f.queue_bytes;
|
||||
}
|
||||
b.kv_ceiling = std::max(b.kv_ceiling, f.kv_ceiling);
|
||||
b.kv_fixed = std::max(b.kv_fixed, f.kv_fixed);
|
||||
b.statics = std::max(b.statics, f.statics);
|
||||
b.expert_ceiling = std::max(b.expert_ceiling, f.experts);
|
||||
layer_max = std::max(layer_max, f.expert_layer_max);
|
||||
/* THE RANK THAT NEEDS MOST ON THE CARD SETS THE FLOOR. */
|
||||
b.expert_floor = std::max(b.expert_floor, f.expert_floor);
|
||||
kv_one = std::max(kv_one, f.kv_one);
|
||||
}
|
||||
b.lends = true;
|
||||
for (const VramFacts& f : per_rank) b.lends = b.lends && f.lends;
|
||||
b.headroom = std::max<int64_t>(cfg.gpu_headroom_mib, 0) * kMiB;
|
||||
int64_t host_reserve = 0;
|
||||
for (const VramFacts& f : per_rank) host_reserve = std::max(host_reserve, f.host_reserve);
|
||||
@@ -83,7 +103,8 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
b.derived_kv = want_kv;
|
||||
|
||||
/* What is left after the terms nobody gets to spend. */
|
||||
int64_t fixed = b.already_held + b.headroom + b.arena + b.staging;
|
||||
b.drift = (want_w || want_kv) ? kDriverDrift : 0;
|
||||
int64_t fixed = b.already_held + b.drift + b.headroom + b.arena + b.staging + b.queues;
|
||||
if (!want_w) fixed += cfg.vram_weights_mib * kMiB; /* a stated pool is fixed too */
|
||||
if (!want_kv) fixed += cfg.vram_kv_mib * kMiB;
|
||||
b.claimable = b.capacity - fixed;
|
||||
@@ -93,22 +114,25 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
"VRAM does not cover the fixed costs before a single pool is sized:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s (driver context, code objects, anything else on the card)\n"
|
||||
" driver drift %10s (what that moves by after it is read)\n"
|
||||
" --gpu-headroom-mib %10s\n"
|
||||
" activation arena %10s (buffer plan + kernel scratch)\n"
|
||||
" step staging %10s (block tables + media staging)\n"
|
||||
" step staging %10s (block tables, media and KV tier staging)\n"
|
||||
" hardware queues %10s (%d at %s each, measured)\n"
|
||||
"%s%s"
|
||||
" ------------------------------\n"
|
||||
" SHORT BY %10s\n"
|
||||
"Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), "
|
||||
"or free the card.\n",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(),
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
want_w ? "" : fmt(" --vram-weights-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str()).c_str(),
|
||||
want_kv ? "" : fmt(" --vram-kv-mib %10s (stated)\n",
|
||||
humanb(cfg.vram_kv_mib * kMiB).c_str()).c_str(),
|
||||
humanb(-b.claimable).c_str());
|
||||
RAD_ERR("%s", b.report.c_str());
|
||||
if (log) RAD_ERR("%s", b.report.c_str());
|
||||
if (out) *out = b;
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -127,7 +151,7 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
/* Not fatal: the planner will demote what does not fit and the model still serves,
|
||||
* badly. Name it, because "why is this model 8x slower than it should be" has no other
|
||||
* answer at startup. */
|
||||
RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
if (log) RAD_WARN("the static (non-expert) weights alone want %s of the %s this card has to "
|
||||
"give. Every expert will stream from host memory and the KV cache has "
|
||||
"nothing left -- this model wants more VRAM, fewer ranks of it, or a smaller "
|
||||
"--max-num-batched-tokens.",
|
||||
@@ -137,39 +161,42 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
b.elastic = want_w ? b.claimable - b.statics : b.claimable;
|
||||
if (b.elastic < 0) b.elastic = 0;
|
||||
|
||||
/* ---- and only what is left is what the ratio divides ------------------------------------- */
|
||||
/* ---- and only what is left is divided --------------------------------------------------- */
|
||||
if (want_w && want_kv) {
|
||||
const double r = (cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0)
|
||||
? cfg.expert_cache_ratio : 0.75;
|
||||
int64_t kv = (int64_t)((double)b.elastic * (1.0 - r));
|
||||
int64_t exp = b.elastic - kv;
|
||||
|
||||
/* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, AND THE SLACK CROSSES OVER. A paged cache
|
||||
* cannot address past max_seqs x max_ctx tokens and an expert plane that is entirely
|
||||
* resident has no use for another byte -- so a share above either ceiling is memory
|
||||
* nothing will ever touch. Cap, then hand the remainder to whichever side is still short,
|
||||
* then stop: what neither can take is genuinely unusable and is reported as such rather
|
||||
* than allocated into a pool that reports itself three quarters empty. */
|
||||
if (b.kv_ceiling > 0 && kv > b.kv_ceiling) kv = b.kv_ceiling;
|
||||
/* ZERO EXPERTS IS A CEILING OF ZERO, NOT AN UNMEASURED ONE. weight_footprint() runs on
|
||||
* every rank before this call, so expert_ceiling is always known -- and guarding this cap
|
||||
* with `> 0` would read "dense" as "unlimited", handing a model with no experts at all a
|
||||
* large expert budget against nothing to put in it while its cache goes short.
|
||||
* kv_ceiling keeps its guard: that one IS genuinely unset when plan_groups fails. */
|
||||
if (exp > b.expert_ceiling) exp = b.expert_ceiling;
|
||||
int64_t spare = b.elastic - kv - exp;
|
||||
if (spare > 0 && b.expert_ceiling > exp) {
|
||||
const int64_t take = std::min(spare, b.expert_ceiling - exp);
|
||||
exp += take; spare -= take;
|
||||
}
|
||||
if (spare > 0 && b.kv_ceiling > kv) {
|
||||
const int64_t take = std::min(spare, b.kv_ceiling - kv);
|
||||
kv += take; spare -= take;
|
||||
/* An unset cache ceiling (plan_groups failed) bounds nothing; zero experts is a ceiling of
|
||||
* zero, which weight_footprint always measures. */
|
||||
const int64_t kv_cap = b.kv_ceiling > 0 ? b.kv_ceiling : b.elastic;
|
||||
int64_t kv = 0, exp = 0;
|
||||
if (kv_cap + b.expert_ceiling <= b.elastic) {
|
||||
/* BOTH FIT: nothing trades. */
|
||||
kv = kv_cap;
|
||||
exp = b.expert_ceiling;
|
||||
} else if (b.lends) {
|
||||
/* THE CACHE LENDS, so it is sized for what live requests could need and gives back
|
||||
* whatever they do not. The experts keep what the host pool cannot hold. */
|
||||
exp = std::min(b.expert_floor, b.elastic);
|
||||
kv = std::min(kv_cap, std::max(b.elastic - exp, kv_one));
|
||||
exp = std::min(std::max(b.expert_ceiling, b.expert_floor), b.elastic - kv);
|
||||
/* THE ONE SEQUENCE WINS, and the experts it pushes off the card have no tier: the
|
||||
* planner refuses them by name. Said here too, with what moves it. */
|
||||
if (log && exp < b.expert_floor)
|
||||
RAD_WARN("one --max-model-len sequence's cache (%s) leaves the experts %s, short of "
|
||||
"the %s the pinned host pool cannot hold: raise --host-pool-mib or lower "
|
||||
"--max-model-len",
|
||||
humanb(kv_one).c_str(), humanb(exp).c_str(),
|
||||
humanb(b.expert_floor).c_str());
|
||||
} else {
|
||||
/* NO LENDER: a block the cache does not use would sit empty, so the experts come
|
||||
* first and the cache keeps one --max-model-len sequence. */
|
||||
kv = std::min(kv_cap, std::max(b.elastic - b.expert_ceiling, kv_one));
|
||||
exp = std::min(b.expert_ceiling, b.elastic - kv);
|
||||
}
|
||||
if (kv > b.elastic) kv = b.elastic;
|
||||
if (exp < 0) exp = 0;
|
||||
b.experts = exp;
|
||||
b.kv = kv;
|
||||
b.weights = b.statics + exp;
|
||||
b.unusable = spare > 0 ? spare : 0;
|
||||
b.unusable = std::max<int64_t>(b.elastic - kv - exp, 0);
|
||||
} else if (want_kv) {
|
||||
b.kv = b.kv_ceiling > 0 ? std::min(b.claimable, b.kv_ceiling) : b.claimable;
|
||||
b.unusable = b.claimable - b.kv;
|
||||
@@ -204,7 +231,15 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
const double f = (double)(b.expert_ceiling - b.experts) / (double)b.expert_ceiling;
|
||||
const int64_t one = ((int64_t)std::ceil(f * (double)layer_max) + RAD_ALIGN_UNIT - 1) /
|
||||
RAD_ALIGN_UNIT * RAD_ALIGN_UNIT;
|
||||
if (2 * one < b.experts) {
|
||||
if (b.lends && want_kv) {
|
||||
/* A LENDING CACHE PAYS FOR IT: the experts are at their floor and a byte less would
|
||||
* leave one with no tier, while the region is lent to the slab whenever the steps are
|
||||
* small -- the same memory the cache would have lent. */
|
||||
if (b.kv - 2 * one >= kv_one) {
|
||||
b.stage = 2 * one;
|
||||
b.kv -= b.stage;
|
||||
}
|
||||
} else if (2 * one < b.experts) {
|
||||
b.stage = 2 * one;
|
||||
b.experts -= b.stage;
|
||||
b.weights = b.statics + b.experts;
|
||||
@@ -227,14 +262,15 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* because it is a real limit rather than a ratio, is that ONE max-length sequence fits: a
|
||||
* context no single request can complete is a configuration error however much slack the pool
|
||||
* has (core/engine_bringup.cpp, configure_kv). */
|
||||
if (b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
if (log && b.derived_kv && b.kv_ceiling > 0 && cfg.max_ctx > 0)
|
||||
RAD_INFO("kv: the pool backs %.0f%% of the worst case (%lld sequences all at %lld tokens), "
|
||||
"%.1f full-length sessions. That is concurrency at length before the scheduler "
|
||||
"preempts, not a bound on any one request. WITH PREFIX CACHING a finished "
|
||||
"sequence's blocks stay held so the next turn can reuse them, so the demand is "
|
||||
"live SESSIONS and not running requests -- when they do not all fit, the cache "
|
||||
"evicts prefixes the next turn wanted and that turn re-prefills its whole "
|
||||
"context. --expert-vs-cache-ratio moves it.",
|
||||
"context. --host-pool-mib moves it: the experts the host pool cannot hold are the "
|
||||
"part of the card the cache cannot have.",
|
||||
100.0 * paged_share(b),
|
||||
(long long)cfg.max_seqs, (long long)cfg.max_ctx,
|
||||
(double)cfg.max_seqs * paged_share(b));
|
||||
@@ -252,20 +288,24 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* line is not padding: to_mib truncates, and what it drops is real VRAM that ends up beside
|
||||
* the headroom. */
|
||||
const int64_t granted = cfg.vram_weights_mib * kMiB + cfg.vram_kv_mib * kMiB;
|
||||
const int64_t unclaimed = b.capacity - b.already_held - b.arena - b.staging - b.stage - granted;
|
||||
const int64_t unclaimed = b.capacity - b.already_held - b.drift - b.arena - b.staging - b.queues -
|
||||
b.stage - granted;
|
||||
const double ela = b.elastic > 0 ? (double)b.elastic : 1.0;
|
||||
b.report = fmt(
|
||||
"VRAM budget, per card:\n"
|
||||
" card total %10s\n"
|
||||
" already held %10s measured: driver context, code objects, anything else resident\n"
|
||||
" driver drift %10s what that moves by after it is read: kept free\n"
|
||||
" activation arena %10s computed from the buffer plan\n"
|
||||
" step staging %10s the step batch's block tables and media staging\n"
|
||||
" step staging %10s the step batch's block tables and media staging, and the\n"
|
||||
" KV tiers' copy staging\n"
|
||||
" hardware queues %10s %d a card at %s each, measured: the engine's streams\n"
|
||||
" %-18s %10s %s\n"
|
||||
" ------------------------------\n"
|
||||
" claimable %10s\n"
|
||||
" static weights %10s %s\n"
|
||||
" ------------------------------\n"
|
||||
" elastic %10s what --expert-vs-cache-ratio %.2f divides\n"
|
||||
" elastic %10s %s\n"
|
||||
" experts %10s %.0f%% of it%s\n"
|
||||
" kv cache %10s %.0f%% of it%s\n"
|
||||
"%s"
|
||||
@@ -275,8 +315,9 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
" vram_kv %10s %s\n"
|
||||
" unclaimed %10s the headroom, the unusable above, and what MiB rounding\n"
|
||||
" could not place\n",
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.arena).c_str(),
|
||||
humanb(b.staging).c_str(),
|
||||
humanb(b.capacity).c_str(), humanb(b.already_held).c_str(), humanb(b.drift).c_str(),
|
||||
humanb(b.arena).c_str(), humanb(b.staging).c_str(),
|
||||
humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(),
|
||||
shared ? "left to the host" : "--gpu-headroom-mib", humanb(b.headroom).c_str(),
|
||||
shared ? "integrated graphics: this memory is the host's; --vram-kv-mib states a pool "
|
||||
"outright"
|
||||
@@ -286,8 +327,10 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
b.derived_weights ? "off the top: every rank's own shard, and not a share of anything"
|
||||
: "(not charged here -- --vram-weights-mib was stated)",
|
||||
humanb(b.elastic).c_str(),
|
||||
(cfg.expert_cache_ratio > 0.0 && cfg.expert_cache_ratio < 1.0) ? cfg.expert_cache_ratio
|
||||
: 0.75,
|
||||
b.lends ? "the experts keep what the host pool cannot hold; the cache takes the rest\n"
|
||||
" and lends what no live request holds to the "
|
||||
"expert slab"
|
||||
: "no lender: the experts first, the cache at least one full-length sequence",
|
||||
humanb(b.experts).c_str(), 100.0 * (double)b.experts / ela,
|
||||
b.expert_ceiling == 0
|
||||
? " -- a dense model, so there is no expert plane for this share to fill and the\n"
|
||||
@@ -325,10 +368,11 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
"ceiling\n", humanb(b.unusable).c_str()).c_str()
|
||||
: "",
|
||||
b.stage > 0
|
||||
? fmt(" prefill staging %10s out of the experts: two buffers of one layer's "
|
||||
? fmt(" prefill staging %10s out of the %s: two buffers of one layer's "
|
||||
"non-resident experts,\n"
|
||||
" at the arena's top and lent back to the "
|
||||
"slab while steps are small\n", humanb(b.stage).c_str()).c_str()
|
||||
"slab while steps are small\n", humanb(b.stage).c_str(),
|
||||
b.lends ? "cache" : "experts").c_str()
|
||||
: "",
|
||||
humanb(cfg.vram_weights_mib * kMiB).c_str(),
|
||||
b.derived_weights ? "static + experts" : "stated by --vram-weights-mib",
|
||||
@@ -340,4 +384,13 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
|
||||
return resolve(cfg, per_rank, out, true);
|
||||
}
|
||||
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out) {
|
||||
Config c = cfg;
|
||||
return resolve(c, per_rank, out, false);
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+50
-16
@@ -24,22 +24,27 @@
|
||||
*
|
||||
* THE STATIC WEIGHTS COME OFF THE TOP. Everything that is not an expert -- the attention
|
||||
* projections, the norms, the embedding, the head -- has to be resident for the model to run at a
|
||||
* sensible speed at all, and under tensor parallel each rank already holds its own even share of
|
||||
* sensible speed at all (the one exception is a token embedding --embedding-placement puts in the
|
||||
* pinned host pool, which a lookup reads a few rows of in place; weight_footprint counts it out of
|
||||
* the statics then), and under tensor parallel each rank already holds its own even share of
|
||||
* them (declare runs per rank with every dimension divided, spec §9). They are a FLOOR, not a
|
||||
* share of anything: applying a ratio to the weights as a whole would let --expert-vs-cache-ratio
|
||||
* 0.3 demote the attention projections to host memory to make room for a cache nothing will fill.
|
||||
* If they do not fit, that is a refusal with the shortfall named.
|
||||
* share of anything: dividing the weights as a whole would let the cache's side demote the
|
||||
* attention projections to host memory to make room for blocks nothing will fill. If they do not
|
||||
* fit, that is a refusal with the shortfall named.
|
||||
*
|
||||
* ONLY WHAT IS LEFT AFTER THAT IS DIVIDED, and that is the division the flag is named for: the
|
||||
* expert plane against the KV cache, which is the one genuinely two-sided trade on this engine. A
|
||||
* long-context low-concurrency server and a short-context high-concurrency one want opposite
|
||||
* answers and neither is derivable.
|
||||
* ONLY WHAT IS LEFT AFTER THAT IS DIVIDED: the expert plane against the KV cache. Where the cache
|
||||
* lends its idle blocks to the expert slab, that division has nothing to guess. The experts keep
|
||||
* on the card exactly what the pinned host pool cannot hold -- they have nowhere else to be -- and
|
||||
* the cache takes the rest, up to what it could ever address; every block no live request holds
|
||||
* is lent back to the experts in place. So the cache is as large as the work needs at the moment
|
||||
* and the experts have everything else, for a long-context server and a high-concurrency one
|
||||
* alike. Without a lender the cache would hold that memory empty, so there the experts come first
|
||||
* and the cache keeps one --max-model-len sequence. The cache never gets less than that sequence.
|
||||
*
|
||||
* BOTH SIDES ARE THEN CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
|
||||
* BOTH SIDES ARE CAPPED AT WHAT THEY COULD USE, and whatever one side cannot take goes to the
|
||||
* other rather than nowhere. A cache cannot address past max_seqs x max_ctx tokens
|
||||
* (KVManager::ceiling), so a share larger than that ceiling is VRAM the cache can never fill and
|
||||
* the expert plane could have held. And an expert plane that fits entirely in VRAM has no use for
|
||||
* more; on a model that fits, the ratio stops meaning anything and that is correct.
|
||||
* (KVManager::ceiling), and an expert plane that fits entirely in VRAM has no use for more; when
|
||||
* both fit, both are whole.
|
||||
*
|
||||
* A stated --vram-weights-mib or --vram-kv-mib still wins outright and turns the whole of this
|
||||
* off for that pool. The point is that the DEFAULT is a full card rather than a guess: VRAM left
|
||||
@@ -60,14 +65,32 @@ struct VramFacts {
|
||||
int64_t capacity = 0; /* RadDeviceProps::vram_bytes -- totalGlobalMem */
|
||||
int64_t free = 0; /* RadDeviceProps::vram_free, measured now */
|
||||
int64_t arena = 0; /* arena_plan_bytes() for this rank's program, total incl. scratch */
|
||||
int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging */
|
||||
int64_t staging = 0; /* BatchBuilder::device_bytes(): the step slab and the media staging,
|
||||
* and TierExec::device_bytes() when a KV tier is configured */
|
||||
/* THE HARDWARE QUEUES this rank creates after `free` was read -- its compute stream, the expert
|
||||
* mover's, and the second compute lane where the program declares one -- at `queue_bytes`
|
||||
* each. MEASURED, by making one: a queue's kernel-argument ring is the engine's, and the
|
||||
* driver backs every queue with VRAM of its own beside it (33 MiB a queue on an R9700, eight
|
||||
* times the ring). */
|
||||
int n_queues = 0;
|
||||
int64_t queue_bytes = 0;
|
||||
int64_t kv_ceiling = 0; /* KVManager::ceiling(max_ctx) for this rank's declared groups */
|
||||
int64_t kv_fixed = 0; /* KVManager::fixed_bytes(): the part of the ceiling that is state */
|
||||
/* weight_footprint() for this rank, which under tensor parallel is already this card's even
|
||||
* share: declare runs per rank with every dimension already divided. */
|
||||
int64_t statics = 0; /* non-expert weights -- the floor, not a share of anything */
|
||||
int64_t experts = 0; /* the elastic plane the ratio divides against the KV cache */
|
||||
int64_t experts = 0; /* the expert plane: what trades against the KV cache */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes one routed layer holds */
|
||||
/* THE EXPERTS THE PINNED HOST POOL CANNOT HOLD on this rank, with the slab's spare slots
|
||||
* beside them: they have nowhere to be but the card, so this is the floor under the expert
|
||||
* slab when the cache lends (expert_vram_floor, core/place/planner.h). */
|
||||
int64_t expert_floor = 0;
|
||||
int64_t kv_one = 0; /* the cache for ONE --max-model-len sequence: the least it may get */
|
||||
/* WILL THE CACHE LEND ITS IDLE BLOCKS TO THE EXPERT SLAB: a placement that moves units
|
||||
* (expert_tiered, or auto), not --deterministic, on a device with virtual memory management.
|
||||
* Decides the split: a cache that lends gives back what it does not use, so it can be sized
|
||||
* for what live requests could need; one that does not would hold it empty. */
|
||||
bool lends = false;
|
||||
/* Integrated graphics: what of the host's memory the card leaves to the host. Its device
|
||||
* memory IS the host's, so an unclaimed MiB is the operating system's and every other
|
||||
* process's to run in, not slack. 0 on a discrete card. */
|
||||
@@ -78,9 +101,15 @@ struct VramFacts {
|
||||
* operator stated the budgets -- the placement report and the pool report both want the totals. */
|
||||
struct VramBudget {
|
||||
int64_t capacity = 0, already_held = 0, headroom = 0, arena = 0, staging = 0;
|
||||
int64_t drift = 0; /* kDriverDrift: what already_held moves by after it is read */
|
||||
int64_t queues = 0; /* n_queues * queue_bytes, from the rank that needs most */
|
||||
int n_queues = 0;
|
||||
int64_t queue_bytes = 0;
|
||||
int64_t claimable = 0; /* after the fixed terms above */
|
||||
int64_t statics = 0; /* off the top, before the ratio sees anything */
|
||||
int64_t elastic = 0; /* claimable - statics: what the ratio divides */
|
||||
int64_t statics = 0; /* off the top, before the split sees anything */
|
||||
int64_t elastic = 0; /* claimable - statics: what experts and cache share */
|
||||
int64_t expert_floor = 0; /* the experts the host pool cannot hold */
|
||||
bool lends = false; /* every rank's cache lends its idle blocks */
|
||||
int64_t kv_ceiling = 0, expert_ceiling = 0;
|
||||
int64_t kv_fixed = 0; /* the state part of kv_ceiling, which no context uses */
|
||||
int64_t experts = 0, kv = 0; /* the two shares, each capped at its ceiling */
|
||||
@@ -103,4 +132,9 @@ struct VramBudget {
|
||||
* Refuses, by name and by how much, when the fixed terms alone exceed the card. */
|
||||
int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* The same split worked out on a copy of `cfg`, written nowhere and printed nowhere: for a caller
|
||||
* deciding between two programs before it resolves the one it keeps (Engine::plan's table
|
||||
* placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -293,10 +293,10 @@ int Mover::init(const Program& prog, const Plan& plan, const MoverConfig& cfg, P
|
||||
*
|
||||
* A staging slot only ever receives a unit read from the container, so sizing it off every
|
||||
* class charges the host pool for classes that are never staged. The widest class is
|
||||
* typically the embedding table -- its own class, gigabytes wide, and resident in VRAM for
|
||||
* the whole run -- so sizing on it reserves several times that in pinned memory to receive
|
||||
* a weight that never arrives, and the file tier is then refused for want of memory it
|
||||
* did not need. */
|
||||
* typically the embedding table -- its own class, gigabytes wide, and never on the file
|
||||
* tier: in VRAM, or in the pinned host pool by --embedding-placement -- so sizing on it
|
||||
* reserves several times that in pinned memory to receive a weight that never arrives, and
|
||||
* the file tier is then refused for want of memory it did not need. */
|
||||
int64_t widest = 0;
|
||||
for (const MoveUnit& mu : plan.units) {
|
||||
if (mu.tier != Tier::SSD || mu.slab_class < 0) continue;
|
||||
|
||||
+227
-54
@@ -20,6 +20,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -37,6 +38,16 @@ const char* tier_name(Tier t) {
|
||||
return "?";
|
||||
}
|
||||
|
||||
const char* table_placement_name(TablePlacement p) {
|
||||
switch (p) {
|
||||
case TablePlacement::Auto: return "auto";
|
||||
case TablePlacement::Vram: return "vram";
|
||||
case TablePlacement::Ram: return "ram";
|
||||
case TablePlacement::Disk: return "disk";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
const char* site_name(Site s) {
|
||||
switch (s) {
|
||||
case Site::Device: return "device";
|
||||
@@ -91,24 +102,42 @@ int64_t weight_bytes(const WeightInfo& w) {
|
||||
/* See planner.h. Planner::resolve_sites, Planner::build_units and Planner::pin_mapped, run over
|
||||
* the same program without allocating a Plan -- the budget resolver calls this before a Planner
|
||||
* exists. Kept adjacent to the three so a change to any of them has this in the same diff. */
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out) {
|
||||
int64_t file_stage_reserve(int64_t widest, bool routed) {
|
||||
return (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest +
|
||||
(routed ? (int64_t)RAD_PLACE_FILE_WINDOWS * RAD_PLACE_FILE_WINDOW_BYTES : 0);
|
||||
}
|
||||
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
|
||||
if (wf.experts <= 0) return 0;
|
||||
const int64_t all = wf.experts + wf.expert_spare;
|
||||
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
if (!out) return;
|
||||
*out = WeightFootprint{};
|
||||
|
||||
/* resolve_sites: a weight every one of whose ops lacks a device band cannot be read on the
|
||||
* card, so it is never copied there whatever the budgets say. */
|
||||
std::vector<uint8_t> device_ok(prog.weights.size(), 1u);
|
||||
std::vector<uint8_t> device_ok(prog.weights.size(), 1u), host_ok(prog.weights.size(), 1u);
|
||||
for (const OpInfo& o : prog.ops) {
|
||||
bool dev = !o.bands.empty();
|
||||
for (const Band& b : o.bands) if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false;
|
||||
if (dev) continue;
|
||||
for (rad_weight w : o.weights)
|
||||
if (w != RAD_NULL_HANDLE && w < device_ok.size()) device_ok[w] = 0u;
|
||||
bool dev = !o.bands.empty(), host = !o.bands.empty();
|
||||
for (const Band& b : o.bands) {
|
||||
if (!b.dom[RAD_DOMAIN_DEVICE]) dev = false;
|
||||
if (!b.dom[RAD_DOMAIN_HOST]) host = false;
|
||||
}
|
||||
for (rad_weight w : o.weights) {
|
||||
if (w == RAD_NULL_HANDLE || w >= device_ok.size()) continue;
|
||||
if (!dev) device_ok[w] = 0u;
|
||||
if (!host) host_ok[w] = 0u;
|
||||
}
|
||||
}
|
||||
|
||||
/* build_units: a model-level weight is its own unit, everything else groups by the declared
|
||||
* (layer, expert). Ordered, for the same reason build_units is. */
|
||||
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false; };
|
||||
struct U { int32_t layer = -1, expert = -1; int64_t bytes = 0; bool mapped = false;
|
||||
bool emb = false, ngram = false, host = true; };
|
||||
std::map<std::pair<int32_t, int32_t>, size_t> by_group;
|
||||
std::vector<U> units;
|
||||
|
||||
@@ -137,20 +166,48 @@ void weight_footprint(const Program& prog, WeightFootprint* out) {
|
||||
mu.bytes = align_up(mu.bytes, a) + weight_bytes(wi);
|
||||
/* pin_mapped: THE WHOLE UNIT GOES, not the one weight. */
|
||||
if (w < device_ok.size() && !device_ok[w]) mu.mapped = true;
|
||||
if (w < host_ok.size() && !host_ok[w]) mu.host = false;
|
||||
/* The placement flags' tables: model-level, so the unit is this one weight. */
|
||||
if (layer < 0) {
|
||||
mu.emb = is_embedding_table(prog, w);
|
||||
mu.ngram = is_ngram_table(prog, w);
|
||||
}
|
||||
}
|
||||
|
||||
/* And one align_up a unit, because that is how Mover::init spends the slab: `us.static_off =
|
||||
* align_up(static_need, RAD_ALIGN_UNIT)` before every unit it places. A budget that summed raw
|
||||
* bytes would be short by one alignment per unit, which on a 512-expert MoE is real. */
|
||||
std::map<int32_t, int64_t> layer_experts;
|
||||
std::set<int64_t> expert_strides;
|
||||
bool ngram_host = true;
|
||||
for (const U& mu : units) if (mu.ngram && !mu.host) ngram_host = false;
|
||||
for (const U& mu : units) {
|
||||
const int64_t b = align_up(mu.bytes, RAD_ALIGN_UNIT);
|
||||
if (mu.mapped) out->mapped += b;
|
||||
else if (mu.expert >= 0) { out->experts += b; layer_experts[mu.layer] += b; }
|
||||
/* pin_embedding moves a table out of the statics only where nothing has mapped it. */
|
||||
if (mu.emb && !mu.mapped) out->embedding += b;
|
||||
if (mu.ngram) out->ngram += b;
|
||||
if (mu.ngram && !mu.mapped) out->ngram_device = true;
|
||||
/* pin_mapped: an n-gram table a device kernel reads stays off the card unless it was
|
||||
* placed in VRAM. */
|
||||
if (mu.mapped || (mu.ngram && ngram != TablePlacement::Vram)) out->mapped += b;
|
||||
else if (mu.emb && embedding == TablePlacement::Ram) out->hosted += b;
|
||||
else if (mu.expert >= 0) {
|
||||
out->experts += b;
|
||||
layer_experts[mu.layer] += b;
|
||||
out->expert_unit_max = std::max(out->expert_unit_max, b);
|
||||
expert_strides.insert(b);
|
||||
}
|
||||
else out->statics += b;
|
||||
if (mu.layer >= 0 && !mu.mapped) out->layer_unit_max = std::max(out->layer_unit_max, b);
|
||||
if (mu.expert >= 0 && mu.layer >= 0) out->routed = true;
|
||||
}
|
||||
/* build_classes: one expert slab class a stride. */
|
||||
for (int64_t s : expert_strides)
|
||||
out->expert_spare += (int64_t)(RAD_PLACE_SHADOW_SLOTS + RAD_PLACE_STAGE_RING) * s +
|
||||
RAD_ALIGN_UNIT;
|
||||
for (const auto& le : layer_experts)
|
||||
out->expert_layer_max = std::max(out->expert_layer_max, le.second);
|
||||
out->ngram_host = out->ngram > 0 && ngram_host;
|
||||
out->n_units = (int64_t)units.size();
|
||||
}
|
||||
std::string weight_class_key(const std::string& name) {
|
||||
@@ -185,9 +242,8 @@ std::string weight_class_key(const std::string& name) {
|
||||
*
|
||||
* Tracking host alone would rest on the argument that a missing device kernel is fatal at declare
|
||||
* and never reaches the planner. That is true only of an op with NO kernel in either domain: an op
|
||||
* such as `embed_lookup_q` resolves on the host and nowhere else -- deliberately, because its
|
||||
* table is far too large for the card and must not be copied there -- and declare reports that
|
||||
* device band as unserved without refusing the model. */
|
||||
* such as `embed_lookup_q` resolves on the host and nowhere else when no device kernel for it is
|
||||
* loaded, and declare reports that device band as unserved without refusing the model. */
|
||||
void Planner::resolve_sites(const Program& prog) {
|
||||
host_ok_.assign(prog.weights.size(), 1u);
|
||||
device_ok_.assign(prog.weights.size(), 1u);
|
||||
@@ -216,46 +272,75 @@ void Planner::resolve_sites(const Program& prog) {
|
||||
|
||||
/* ------------------------------------------------------------------ the mapped tier */
|
||||
/* A weight no device kernel can read is pinned to the container's mapping BEFORE any budget is
|
||||
* consulted, because it is not a budget question. The other three off-device tiers are what the
|
||||
* planner falls back to when VRAM runs out; this one is where the weight has to be whatever the
|
||||
* budgets say, and charging a pool for bytes that are never copied would make the operator size a
|
||||
* pool against a number that does not exist.
|
||||
* consulted, because it is not a budget question -- and so is an n-gram table --ngram-placement put
|
||||
* in RAM or on disk, whatever kernels could read it on a card. The other three off-device tiers are
|
||||
* what the planner falls back to when VRAM runs out; this one is where the weight has to be
|
||||
* whatever the budgets say, and charging a pool for bytes that are never copied would make the
|
||||
* operator size a pool against a number that does not exist.
|
||||
*
|
||||
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped
|
||||
* one has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY
|
||||
* weight operand of a host-only op, so the unit's other members are the same op's scale and
|
||||
* constants. What this does exclude is a plugin that groups a host-only weight with a device one:
|
||||
* that collapses the whole group onto the host, so the report names it. */
|
||||
* THE WHOLE UNIT GOES, not the one weight. A unit is the movement granularity and a half-mapped one
|
||||
* has no meaning -- and it costs nothing here, because `device_ok_` is cleared for EVERY weight
|
||||
* operand of a host-only op, so the unit's other members are the same op's scale and constants.
|
||||
* What this does exclude is a plugin that groups a host-only weight with a device one: that
|
||||
* collapses the whole group onto the host, so the report names it. */
|
||||
void Planner::pin_mapped(const Program& prog, Plan* p) {
|
||||
const TablePlacement ng = in_.config->ngram_resolved;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
bool mapped = false;
|
||||
bool host_only = false;
|
||||
for (rad_weight w : mu.weights)
|
||||
if (w < device_ok_.size() && !device_ok_[w]) mapped = true;
|
||||
if (!mapped) continue;
|
||||
if (w < device_ok_.size() && !device_ok_[w]) host_only = true;
|
||||
/* --ngram-placement keeps an n-gram table OFF THE CARD unless it says vram, whether or not
|
||||
* a device kernel could read it there: ram and disk are where the operator put it, and the
|
||||
* strategies below would otherwise spend the card on 48 GB of rows read sixteen a token. */
|
||||
const bool ngram = mu.layer < 0 && !mu.weights.empty() &&
|
||||
is_ngram_table(prog, mu.weights.front());
|
||||
if (!host_only && !(ngram && ng != TablePlacement::Vram)) continue;
|
||||
|
||||
mu.tier = Tier::Mapped;
|
||||
mu.site = Site::Host;
|
||||
mu.movable = false;
|
||||
mu.reason = "no device kernel for its op; read from the container's mapping";
|
||||
/* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping:
|
||||
* a weight its kernel rearranges at load, or a shard of one, has no place in the file
|
||||
* that already looks the way the kernel reads it (spec §5.1). */
|
||||
if (host_only) {
|
||||
mu.site = Site::Host;
|
||||
mu.reason = "no device kernel for its op; read from the container's mapping";
|
||||
} else if (ng == TablePlacement::Ram) {
|
||||
mu.site = Site::DeviceZeroCopy;
|
||||
mu.reason = "--ngram-placement ram: a pinned copy in RAM the card reads in place, made "
|
||||
"at load";
|
||||
} else {
|
||||
mu.site = Site::Host;
|
||||
mu.reason = "--ngram-placement disk: the host gather reads it from the container";
|
||||
for (rad_weight w : mu.weights)
|
||||
if (w < host_ok_.size() && !host_ok_[w])
|
||||
note_unfit(p, mu, "--ngram-placement disk needs a host kernel for its gather, "
|
||||
"and none was loaded");
|
||||
}
|
||||
/* --ngram-placement ram: the load phase copies an n-gram table out of the mapping and
|
||||
* publishes the copy -- locked memory the host kernel reads, or pinned memory the card
|
||||
* reads where a device kernel gathers. Every pool still sees the mapped tier; the report
|
||||
* shows what the copy costs. */
|
||||
if (ngram && ng == TablePlacement::Ram) {
|
||||
if (host_only) mu.reason = "--ngram-placement ram: a locked copy in RAM, made at load";
|
||||
else p->ngram_copy_card = true;
|
||||
p->ngram_copy_bytes += mu.bytes;
|
||||
}
|
||||
/* AND ONLY WHAT LIES IN THE CONTAINER AS THE KERNEL READS IT can be read from the mapping,
|
||||
* or copied out of it: a weight its kernel rearranges at load, or a shard of one, has no
|
||||
* place in the file that already looks the way the kernel reads it (spec §5.1). */
|
||||
if (!in_.container)
|
||||
note_unfit(p, mu, "only a host kernel reads it, so it must be read from a "
|
||||
"container's mapping -- and a checkpoint served directly has "
|
||||
"none; convert it to a container");
|
||||
note_unfit(p, mu, "it is read from a container's mapping or copied out of one -- and "
|
||||
"a checkpoint served directly has none; convert it to a container");
|
||||
else
|
||||
for (rad_weight w : mu.weights)
|
||||
if (w < prog.weights.size() &&
|
||||
!weight_file_direct(prog.weights[w], prog.ctx.world_size))
|
||||
note_unfit(p, mu, "only a host kernel reads it, so it must be read from the "
|
||||
"container's mapping -- and its stored form is not the "
|
||||
"container's (a relayout, a widening or a shard)");
|
||||
for (rad_weight w : mu.weights)
|
||||
if (w < device_ok_.size() && device_ok_[w])
|
||||
RAD_WARN("placement: '%s' is grouped with a weight only a host kernel can read, "
|
||||
"so the whole group stays in the container's mapping",
|
||||
prog.weights[w].name.c_str());
|
||||
note_unfit(p, mu, "it is read from the container's mapping or copied out of "
|
||||
"it -- and its stored form is not the container's (a "
|
||||
"relayout, a widening or a shard)");
|
||||
if (host_only)
|
||||
for (rad_weight w : mu.weights)
|
||||
if (w < device_ok_.size() && device_ok_[w])
|
||||
RAD_WARN("placement: '%s' is grouped with a weight only a host kernel can "
|
||||
"read, so the whole group stays in the container's mapping",
|
||||
prog.weights[w].name.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -514,9 +599,11 @@ struct HostFall {
|
||||
int Planner::assign_all_vram(Plan* p) {
|
||||
int64_t used = 0;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
/* A MAPPED UNIT IS ALREADY PLACED and no strategy may move it: there is no device kernel
|
||||
* that could read it anywhere else. Every assignment pass below begins with this line. */
|
||||
if (mu.tier == Tier::Mapped) continue;
|
||||
/* A PREPLACED UNIT IS ALREADY PLACED and no strategy may move it: a mapped one has no
|
||||
* device kernel that could read it anywhere else, and a token embedding
|
||||
* --embedding-placement put in the host pool is read there in place. Every assignment pass
|
||||
* below begins with this line. */
|
||||
if (mu.preplaced()) continue;
|
||||
mu.tier = Tier::VRAM;
|
||||
mu.site = Site::Device;
|
||||
mu.movable = false; /* the degenerate case: the mover never runs */
|
||||
@@ -546,12 +633,12 @@ int Planner::assign_all_vram(Plan* p) {
|
||||
*/
|
||||
int Planner::assign_layer_offload(Plan* p) {
|
||||
for (MoveUnit& mu : p->units) {
|
||||
if (mu.tier == Tier::Mapped) continue;
|
||||
if (mu.preplaced()) continue;
|
||||
mu.tier = Tier::VRAM; mu.site = Site::Device;
|
||||
}
|
||||
|
||||
int64_t total = 0;
|
||||
for (const MoveUnit& mu : p->units) total += mu.slot_bytes;
|
||||
for (const MoveUnit& mu : p->units) if (!mu.preplaced()) total += mu.slot_bytes;
|
||||
if (p->vram_budget <= 0 || total <= p->vram_budget) return RAD_OK;
|
||||
|
||||
/* Layers in EXECUTION order. The layer index is normally that order already, but the order
|
||||
@@ -617,7 +704,7 @@ int Planner::assign_layer_offload(Plan* p) {
|
||||
int rc = RAD_OK;
|
||||
for (size_t i = cut; i < layers.size(); ++i) {
|
||||
for (MoveUnit& mu : p->units) {
|
||||
if (mu.layer != layers[i] || mu.tier == Tier::Mapped) continue;
|
||||
if (mu.layer != layers[i] || mu.preplaced()) continue;
|
||||
bool host_kernel = true;
|
||||
for (rad_weight w : mu.weights) if (!host_ok_[w]) { host_kernel = false; break; }
|
||||
if (!fall.place(mu, host_kernel, &mu.reason)) {
|
||||
@@ -640,7 +727,7 @@ int Planner::assign_layer_offload(Plan* p) {
|
||||
int Planner::assign_expert_tiered(Plan* p) {
|
||||
int64_t fixed = 0;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
if (mu.tier == Tier::Mapped) continue;
|
||||
if (mu.preplaced()) continue;
|
||||
mu.tier = Tier::VRAM;
|
||||
mu.site = Site::Device;
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL) fixed += mu.slot_bytes;
|
||||
@@ -658,6 +745,15 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
for (const MoveUnit& mu : p->units)
|
||||
if (mu.access != RAD_ACCESS_CONDITIONAL && mu.tier == Tier::VRAM) fixed += mu.slot_bytes;
|
||||
}
|
||||
/* WHAT LAYER OFFLOAD ALREADY PUT IN THE HOST POOL: the dense units of the layers it spilled.
|
||||
* The routed experts below are placed again whatever it did with them, but the dense units
|
||||
* stay where it put them, so the expert fill spends the pool that is left and not the whole
|
||||
* of --host-pool-mib a second time. */
|
||||
int64_t host_spent = 0;
|
||||
for (const MoveUnit& mu : p->units)
|
||||
if (!mu.preplaced() && mu.access != RAD_ACCESS_CONDITIONAL &&
|
||||
(mu.tier == Tier::HostPinned || mu.tier == Tier::HostPageable))
|
||||
host_spent += mu.slot_bytes;
|
||||
|
||||
std::vector<int32_t> order;
|
||||
rank_units(p, &order);
|
||||
@@ -670,7 +766,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
* Two passes, and the second is enough: the reserve depends only on the first pass's slot
|
||||
* counts, and the first pass over-counts (it had more room), so the reserve it produces is an
|
||||
* upper bound. A third pass can only give slots back, never take more. */
|
||||
HostFall fall{0, p->host_budget, ssd_};
|
||||
HostFall fall{host_spent, p->host_budget, ssd_};
|
||||
int rc = RAD_OK;
|
||||
|
||||
/* ONE FILL: the conditional units in rank order, at most `cap` of them resident and the rest to
|
||||
@@ -688,7 +784,7 @@ int Planner::assign_expert_tiered(Plan* p) {
|
||||
}
|
||||
for (SlabClass& sc : p->classes) sc.n_shadow = 0;
|
||||
p->unfit.clear();
|
||||
fall = HostFall{0, p->host_budget, ssd_};
|
||||
fall = HostFall{host_spent, p->host_budget, ssd_};
|
||||
rc = RAD_OK;
|
||||
|
||||
for (int32_t ui : order) {
|
||||
@@ -960,10 +1056,75 @@ void Planner::finish(const Program& prog, Plan* p) {
|
||||
pl.reason = mu.reason;
|
||||
pl.bytes = weight_bytes(prog.weights[w]);
|
||||
p->totals.bytes[(int)mu.tier] += pl.bytes;
|
||||
if (mu.host_forced) p->embedding_host_used += pl.bytes;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the lookup tables */
|
||||
bool read_only_by(const Program& prog, rad_weight w, const char* op) {
|
||||
bool read = false;
|
||||
for (const OpInfo& o : prog.ops)
|
||||
for (rad_weight ow : o.weights)
|
||||
if (ow == w) {
|
||||
if (o.op != op) return false;
|
||||
read = true;
|
||||
}
|
||||
return read;
|
||||
}
|
||||
|
||||
/* --embedding-placement ram: THE TOKEN EMBEDDING goes to the pinned host pool before any strategy
|
||||
* runs, and stays there. The site is DeviceZeroCopy: the host pool is mapped (Pools::configure),
|
||||
* so the lookup kernel is handed the pool's device-side address and reads its M rows of n_embd
|
||||
* over the link in place -- a few KiB a decode step -- while the table, the largest model-level
|
||||
* weight a dense model has, gives its VRAM to the KV cache. Every strategy and every VRAM total
|
||||
* skips the unit through MoveUnit::preplaced(), as they skip the mapped tier, and weight_footprint
|
||||
* has already counted it out of the statics with the same test, so the budget the card was split
|
||||
* by is the one the planner spends. A layer unit is never one: is_embedding_table asks for a
|
||||
* model-level weight, and a layer belongs to the offload strategies. */
|
||||
int Planner::pin_embedding(const Program& prog, const Config& cfg, Plan* p) const {
|
||||
if (cfg.embedding_resolved != TablePlacement::Ram) return RAD_OK;
|
||||
int rc = RAD_OK, found = 0;
|
||||
for (MoveUnit& mu : p->units) {
|
||||
/* build_units gives a model-level weight a unit of its own: it is the unit's one weight. */
|
||||
if (mu.layer >= 0 || mu.weights.empty() || mu.tier == Tier::Mapped) continue;
|
||||
const rad_weight w = mu.weights.front();
|
||||
if (!is_embedding_table(prog, w)) continue;
|
||||
++found;
|
||||
const std::string& name = prog.weights[w].name;
|
||||
if (mu.slot_bytes > p->host_budget) {
|
||||
RAD_ERR("placement: --embedding-placement ram: '%s' needs %s of the pinned host pool "
|
||||
"and %s of --host-pool-mib is left%s", name.c_str(),
|
||||
humanb(mu.slot_bytes).c_str(), humanb(p->host_budget).c_str(),
|
||||
p->file_stage_reserve ? " after the file tier's staging" : "");
|
||||
p->notes.push_back(fmt("--embedding-placement ram: '%s' (%s) does not fit the host "
|
||||
"pool", name.c_str(), humanb(mu.slot_bytes).c_str()));
|
||||
rc = RAD_E_NOMEM;
|
||||
continue;
|
||||
}
|
||||
p->host_budget -= mu.slot_bytes;
|
||||
p->embedding_host_bytes += mu.slot_bytes;
|
||||
mu.tier = Tier::HostPinned;
|
||||
mu.site = Site::DeviceZeroCopy;
|
||||
mu.movable = false;
|
||||
mu.host_forced = true;
|
||||
mu.reason = "--embedding-placement ram; read over the link in place";
|
||||
RAD_INFO("placement: '%s' (%s) in the pinned host pool, read in place "
|
||||
"(--embedding-placement %s)", name.c_str(), humanb(mu.bytes).c_str(),
|
||||
cfg.embedding_placement == TablePlacement::Auto ? "auto" : "ram");
|
||||
}
|
||||
/* Engine::plan resolves Ram only where weight_footprint found a table with this same test,
|
||||
* so an empty pass is a plan built from a different program than the budget was: a wiring
|
||||
* fault, said by name rather than leaving the table on the card the budget split without it. */
|
||||
if (!found) {
|
||||
RAD_ERR("placement: --embedding-placement ram, and this rank's program has no model-level "
|
||||
"weight that only embed_lookup reads");
|
||||
p->notes.push_back("--embedding-placement ram: no token embedding table to place");
|
||||
rc = RAD_E_STATE;
|
||||
}
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ plan */
|
||||
int Planner::plan(Plan* out) {
|
||||
if (!out || !in_.program || !in_.config) return RAD_E_INVAL;
|
||||
@@ -1020,7 +1181,7 @@ int Planner::plan(Plan* out) {
|
||||
}
|
||||
const int64_t windows = routed ? (int64_t)RAD_PLACE_FILE_WINDOWS *
|
||||
RAD_PLACE_FILE_WINDOW_BYTES : 0;
|
||||
const int64_t need = (int64_t)RAD_PLACE_FILE_STAGE_SLOTS * widest + windows;
|
||||
const int64_t need = file_stage_reserve(widest, routed);
|
||||
if (need > 0) {
|
||||
if (need >= out->host_budget) {
|
||||
RAD_ERR("placement: the file tier needs %s of pinned staging (%d slots of %s%s) "
|
||||
@@ -1037,18 +1198,21 @@ int Planner::plan(Plan* out) {
|
||||
}
|
||||
}
|
||||
|
||||
/* NOT a RAD_TRY: a refusal still leaves `out` filled in far enough to print. */
|
||||
const int hrc = pin_embedding(prog, cfg, out);
|
||||
|
||||
int rc = assign(out);
|
||||
enforce_op_site_agreement(prog, out);
|
||||
schedule_prefetch(out);
|
||||
finish(prog, out);
|
||||
return rc;
|
||||
return hrc < 0 ? hrc : rc;
|
||||
}
|
||||
|
||||
int Planner::assign(Plan* p) {
|
||||
int64_t total = 0;
|
||||
bool has_conditional = false;
|
||||
for (const MoveUnit& mu : p->units) {
|
||||
total += mu.slot_bytes;
|
||||
if (!mu.preplaced()) total += mu.slot_bytes;
|
||||
if (mu.access == RAD_ACCESS_CONDITIONAL) has_conditional = true;
|
||||
}
|
||||
|
||||
@@ -1136,7 +1300,7 @@ std::string Plan::report(const Program& prog) const {
|
||||
humanb(totals.bytes[(int)Tier::VRAM]).c_str());
|
||||
s += fmt(" host pinned %12s %12s\n",
|
||||
host_budget > 0 ? humanb(host_budget).c_str() : "none",
|
||||
humanb(totals.bytes[(int)Tier::HostPinned]).c_str());
|
||||
humanb(totals.bytes[(int)Tier::HostPinned] - embedding_host_used).c_str());
|
||||
if (totals.bytes[(int)Tier::HostPageable])
|
||||
s += fmt(" host pageable %12s %12s\n", "-",
|
||||
humanb(totals.bytes[(int)Tier::HostPageable]).c_str());
|
||||
@@ -1156,6 +1320,15 @@ std::string Plan::report(const Program& prog) const {
|
||||
s += fmt(" file staging %12s %12s (%d slots%s, pinned)\n", "-",
|
||||
humanb(file_stage_reserve).c_str(), RAD_PLACE_FILE_STAGE_SLOTS,
|
||||
file_windows ? fmt(" and %d read windows", RAD_PLACE_FILE_WINDOWS).c_str() : "");
|
||||
/* The same, for --embedding-placement ram: out of --host-pool-mib before any strategy, read
|
||||
* in place. And the n-gram copy, which no pool holds: locked RAM the load phase fills. */
|
||||
if (embedding_host_bytes)
|
||||
s += fmt(" embedding %12s %12s (--embedding-placement ram, pinned, read in place)\n",
|
||||
"-", humanb(embedding_host_bytes).c_str());
|
||||
if (ngram_copy_bytes)
|
||||
s += fmt(" n-gram copy %12s %12s (--ngram-placement ram, %s, filled at load)\n",
|
||||
"-", humanb(ngram_copy_bytes).c_str(),
|
||||
ngram_copy_card ? "pinned RAM the card reads" : "locked RAM");
|
||||
/* Out of the VRAM weight budget, beside the residents and not among them: the two buffers a
|
||||
* routed layer's file-tier experts are read into, each sized to the layer that puts the most
|
||||
* there. */
|
||||
|
||||
+69
-4
@@ -95,6 +95,11 @@ struct MoveUnit {
|
||||
Site site = Site::Device;
|
||||
int32_t slab_slot = -1;
|
||||
bool movable = false; /* may the heat engine relocate it after load */
|
||||
bool host_forced = false; /* --embedding-placement ram put it in the pinned pool */
|
||||
|
||||
/* PLACED BEFORE ANY STRATEGY RAN, so every assignment pass skips it and no VRAM total counts
|
||||
* it: the mapped tier (no device kernel can read it) and --embedding-placement ram. */
|
||||
bool preplaced() const { return tier == Tier::Mapped || host_forced; }
|
||||
const char* reason = "fits in vram"; /* a fixed string, so the report never guesses */
|
||||
|
||||
/* The group's INTERNAL LAYOUT, computed once here so the mover never has to. `offset[i]` is
|
||||
@@ -239,6 +244,17 @@ public:
|
||||
int64_t vram_budget = 0, host_budget = 0;
|
||||
int64_t file_stage_reserve = 0;
|
||||
int64_t file_windows = 0; /* the read windows' part of it */
|
||||
/* --embedding-placement ram: the pool slots taken out of --host-pool-mib before any strategy
|
||||
* ran, like the file staging above, and reported beside it rather than among the pooled units.
|
||||
* `embedding_host_used` is the same tables' weight bytes, the unit the tier totals count in. */
|
||||
int64_t embedding_host_bytes = 0;
|
||||
int64_t embedding_host_used = 0;
|
||||
/* --ngram-placement ram: the n-gram tables the load phase copies into host memory. They stay
|
||||
* on the mapped tier as far as every pool is concerned; this is what the copy costs in RAM.
|
||||
* `ngram_copy_card` says which copy: pinned memory a device kernel reads in place over the
|
||||
* link, or locked memory the host gather reads. */
|
||||
int64_t ngram_copy_bytes = 0;
|
||||
bool ngram_copy_card = false;
|
||||
/* ROUTED EXPERTS ON THE FILE TIER have no address of their own: a routed layer's are read into
|
||||
* one of two VRAM buffers before the layer's first expert op and published there until the next
|
||||
* routed layer starts (place/stager.h, FileStager). `file_layer_max` is the most one layer's
|
||||
@@ -317,6 +333,7 @@ private:
|
||||
void resolve_sites(const Program& prog);
|
||||
void build_units(const Program& prog, Plan* p);
|
||||
void pin_mapped(const Program& prog, Plan* p);
|
||||
int pin_embedding(const Program& prog, const Config& cfg, Plan* p) const;
|
||||
void build_classes(Plan* p);
|
||||
void rank_units(Plan* p, std::vector<int32_t>* order) const;
|
||||
int assign(Plan* p);
|
||||
@@ -344,9 +361,8 @@ int64_t weight_bytes(const WeightInfo& w);
|
||||
* order: how much room is there, and only then what goes in it. And the split matters more than
|
||||
* the total. A model's static weights -- everything that is not an expert -- have to be resident
|
||||
* for the model to run at a sensible speed at all, so they come off the top; the expert plane is
|
||||
* the only thing that trades against the KV cache, and it is what --expert-vs-cache-ratio divides.
|
||||
* Applying a ratio to the two together would let a 0.3 setting demote the attention projections to
|
||||
* host memory to make room for a cache nothing will fill.
|
||||
* the only thing that trades against the KV cache. Dividing the two together would let the cache's
|
||||
* side demote the attention projections to host memory to make room for blocks nothing will fill.
|
||||
*
|
||||
* The three answers are per RANK, and under tensor parallel that is already the even split across
|
||||
* devices: declare runs once per rank with every dimension ALREADY DIVIDED (spec §9), so summing
|
||||
@@ -360,10 +376,59 @@ struct WeightFootprint {
|
||||
int64_t statics = 0; /* non-expert and device-readable -- the floor under any budget */
|
||||
int64_t experts = 0; /* the elastic plane: what streams from host when it does not fit */
|
||||
int64_t expert_layer_max = 0; /* the most expert bytes any one routed layer holds */
|
||||
int64_t expert_unit_max = 0; /* the largest expert unit's slot */
|
||||
/* THE SLAB'S SPARE SLOTS beside the residents of an expert-tiered plan, at their most: per
|
||||
* expert slab class, the shadow slots and the staging ring and the tail pad
|
||||
* (Planner::assign_expert_tiered). They come out of the same weight budget as the residents. */
|
||||
int64_t expert_spare = 0;
|
||||
int64_t layer_unit_max = 0; /* the widest per-layer unit's slot: the file tier's staging */
|
||||
bool routed = false; /* a layer has experts: the file tier's read windows */
|
||||
int64_t mapped = 0; /* no device kernel can read them; they never enter a pool at all */
|
||||
int64_t hosted = 0; /* --embedding-placement ram: in the pinned host pool, off the card */
|
||||
/* The tables the two placement flags move, wherever the buckets above count them: `embedding`
|
||||
* is inside statics or hosted, `ngram` inside statics when a device kernel reads it and it is
|
||||
* placed in VRAM, inside mapped otherwise. */
|
||||
int64_t embedding = 0;
|
||||
int64_t ngram = 0;
|
||||
/* A device kernel reads the n-gram table, so it can be on the card or read over the link from
|
||||
* pinned host memory; without one only the host gather reads it, from RAM or the container. */
|
||||
bool ngram_device = false;
|
||||
/* A host kernel gathers it, so it can stay in the container (--ngram-placement disk). */
|
||||
bool ngram_host = false;
|
||||
int64_t n_units = 0;
|
||||
};
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out);
|
||||
/* `embedding` is what the token embedding's placement resolved to; only Ram moves it out of the
|
||||
* statics. `ngram` is the n-gram table's; only Vram puts it among them, and only where a device
|
||||
* kernel reads it. Stated by every caller, so the budget and the planner cannot count it
|
||||
* differently. */
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram);
|
||||
|
||||
/* THE PINNED STAGING THE FILE TIER TAKES OUT OF --host-pool-mib before any unit is placed in it:
|
||||
* RAD_PLACE_FILE_STAGE_SLOTS of the widest per-layer unit, and the read windows when a routed
|
||||
* layer can stream from the container. Planner::plan spends it; the budget counts it the same. */
|
||||
int64_t file_stage_reserve(int64_t widest, bool routed);
|
||||
|
||||
/* THE EXPERT BYTES THE CARD MUST HOLD when `host_room` bytes of the pinned host pool are free for
|
||||
* experts: everything the pool cannot take, the slab's spare slots beside them, and one unit of
|
||||
* first-fit slack on each side -- the resident fill and the pool fill each skip a unit that does
|
||||
* not fit and can leave up to one unit's room unspent. At most every expert and the spare slots.
|
||||
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
|
||||
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
|
||||
|
||||
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
|
||||
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
|
||||
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
|
||||
* makes a tier below the card usable for it at all; a weight a GEMM also reads -- an output head
|
||||
* tied to the embedding -- would stream whole over the link every step, and is neither. One
|
||||
* definition, because the budget resolver and the planner must pick the same weights. */
|
||||
bool read_only_by(const Program& prog, rad_weight w, const char* op);
|
||||
inline bool is_embedding_table(const Program& prog, rad_weight w) {
|
||||
return read_only_by(prog, w, "embed_lookup");
|
||||
}
|
||||
inline bool is_ngram_table(const Program& prog, rad_weight w) {
|
||||
return read_only_by(prog, w, "embed_lookup_q");
|
||||
}
|
||||
|
||||
/* "blk.12.ffn_gate_exps.3.weight" -> "blk.*.ffn_gate_exps.*.weight". The report's grouping key:
|
||||
* one line per weight class rather than per weight (spec §16). */
|
||||
|
||||
@@ -181,6 +181,12 @@ public:
|
||||
* loads anything, once it has chosen its cards. */
|
||||
void set_code_device(int device) { code_device_ = device; }
|
||||
|
||||
/* WHAT THE ENGINE MEASURED ABOUT THE RANKS' DEVICES, for the constraints on "device." keys
|
||||
* (rad_types.h). Set before the first selection, by whoever chose the devices; a registry
|
||||
* nobody told anything has no facts, and a kernel constrained on one is not selected. */
|
||||
void set_device_fact(std::string_view key, long long v) { device_facts_.set_i(key, v); }
|
||||
const Geometry& device_facts() const { return device_facts_; }
|
||||
|
||||
void close(); /* fini instances, close hooks, dlclose, forget everything */
|
||||
|
||||
const std::vector<Plugin>& plugins() const { return plugins_; }
|
||||
@@ -327,6 +333,7 @@ private:
|
||||
};
|
||||
|
||||
int code_device_ = 0;
|
||||
Geometry device_facts_;
|
||||
TuneCache tune_;
|
||||
|
||||
int stage_(const std::string& path, Staged* out);
|
||||
|
||||
+13
-3
@@ -23,14 +23,24 @@ namespace {
|
||||
/* True when every constraint holds. Otherwise `why` names the FIRST one that did not and what it
|
||||
* wanted: "no kernel" on its own is not an answer anyone can act on, and the first failure is the
|
||||
* one a reader can fix -- listing all four of a row's unmet constraints buries it. */
|
||||
bool row_matches(const KernelRow& r, const Geometry& g, const std::vector<std::string>& skip,
|
||||
std::string* why) {
|
||||
bool row_matches(const KernelRow& r, const Geometry& g, const Geometry& facts,
|
||||
const std::vector<std::string>& skip, std::string* why) {
|
||||
static const size_t kFact = std::strlen(RAD_DEVICE_FACT_PREFIX);
|
||||
for (int i = 0; i < r.info->n_constraints; ++i) {
|
||||
const RadConstraint& c = r.info->constraints[i];
|
||||
/* A constraint on a RAD_DERIVED parameter the caller did not name is not a predicate on
|
||||
* the question -- it IS the answer, read back afterwards. Matching on it would make the
|
||||
* kernel unreachable by the only query anyone can ask (rad_abi.h, spec §7.2). */
|
||||
if (c.key && std::find(skip.begin(), skip.end(), c.key) != skip.end()) continue;
|
||||
/* A "device." key is a fact about the machine, read from what the engine measured. */
|
||||
if (c.key && std::strncmp(c.key, RAD_DEVICE_FACT_PREFIX, kFact) == 0) {
|
||||
if (constraint_holds(c, facts)) continue;
|
||||
if (why)
|
||||
*why = facts.has(c.key)
|
||||
? constraint_why(c, facts) + " -- this machine, measured at launch"
|
||||
: std::string(c.key) + " is not known: nothing measured this machine";
|
||||
return false;
|
||||
}
|
||||
if (!constraint_holds(c, g)) {
|
||||
if (why) *why = constraint_why(c, g);
|
||||
return false;
|
||||
@@ -111,7 +121,7 @@ const KernelRow* Registry::select(std::string_view op, const Geometry& g, int do
|
||||
}
|
||||
|
||||
std::string whynot;
|
||||
bool ok = row_matches(*r, g, derived_keys, &whynot);
|
||||
bool ok = row_matches(*r, g, device_facts_, derived_keys, &whynot);
|
||||
if (ok && accept && *accept) {
|
||||
whynot = (*accept)(*r, g);
|
||||
ok = whynot.empty();
|
||||
|
||||
@@ -103,6 +103,19 @@ static const RadOperandSpec kOpdNorm[] = {
|
||||
static const RadOperandSpec kOpdAttn[] = {
|
||||
{ "q", RAD_OPD_IN, 0 }, { "kv_cache", RAD_OPD_INOUT, 0 }, { "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
/* A grouped GEMM's operand list in miniature: one fixed weight, then four classes of experts as
|
||||
* table pairs -- codes, then scales -- with an activation operand between the first pair and the
|
||||
* rest, the way `moe_gemm_q_mod4` lays its classes out. It is here for the declaration's division
|
||||
* of one weight list over several table positions (tests/build_test.cpp). */
|
||||
static const RadOperandSpec kOpdMoe[] = {
|
||||
{ "a", RAD_OPD_IN, 0 }, { "g", RAD_OPD_WEIGHT, 0 },
|
||||
{ "w", RAD_OPD_WTAB, 0 }, { "w_scale", RAD_OPD_WTAB, 0 },
|
||||
{ "sorted", RAD_OPD_IN, 0 },
|
||||
{ "w_1", RAD_OPD_WTAB, 0 }, { "w_1_scale", RAD_OPD_WTAB, 0 },
|
||||
{ "w_2", RAD_OPD_WTAB, 0 }, { "w_2_scale", RAD_OPD_WTAB, 0 },
|
||||
{ "w_3", RAD_OPD_WTAB, 0 }, { "w_3_scale", RAD_OPD_WTAB, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ schemas */
|
||||
static const RadParamSpec kPGemm[] = {
|
||||
@@ -159,6 +172,11 @@ static const RadConstraint kCNorm4096[] = {
|
||||
static const RadConstraint kCTie[] = {
|
||||
RAD_CGE("M", 1),
|
||||
};
|
||||
/* A kernel that reaches another card's memory: a constraint on the machine, not the geometry. */
|
||||
static const RadConstraint kCPeer[] = {
|
||||
RAD_CGE("M", 1),
|
||||
RAD_CEQ(RAD_FACT_P2P, 1),
|
||||
};
|
||||
/* Constraint ORDER is the order the miss message reports in: the first unmet one is what a reader
|
||||
* is told, so the cheapest and most identifying predicate goes first. */
|
||||
static const RadConstraint kCAttn[] = {
|
||||
@@ -197,6 +215,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"a derived key its kernel does not pin" },
|
||||
{ "t_skinny", kPGemm, NELEM(kPGemm), kOpdGemm, NELEM(kOpdGemm), "a range with a hole in it" },
|
||||
{ "t_eq", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm), "an EQ band boundary" },
|
||||
{ "t_peer", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
|
||||
"a peer kernel with a fallback beneath it" },
|
||||
{ "t_peer_only", kPTie, NELEM(kPTie), kOpdNorm, NELEM(kOpdNorm),
|
||||
"a peer kernel and nothing else" },
|
||||
{ "t_moe", kPTie, NELEM(kPTie), kOpdMoe, NELEM(kOpdMoe),
|
||||
"one weight list over eight table operands" },
|
||||
};
|
||||
|
||||
static const RadKernelInfo kKernels[] = {
|
||||
@@ -236,6 +260,20 @@ static const RadKernelInfo kKernels[] = {
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_HOST, .priority = 10, .launch = t_launch },
|
||||
|
||||
/* Peer access is the machine's: the direct row needs it, the staged one does not. */
|
||||
{ .name = "t_peer_direct", .op = "t_peer", .family = "ar",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other",
|
||||
.dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 20,
|
||||
.constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch },
|
||||
{ .name = "t_peer_staged", .op = "t_peer", .family = "ar",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 1", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCTie, .n_constraints = NELEM(kCTie), .launch = t_launch },
|
||||
{ .name = "t_peer_only_direct", .op = "t_peer_only", .family = "ar",
|
||||
.computes = "nothing; a registry row", .shape = "M >= 1, cards reach each other",
|
||||
.dtypes = "any", .domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCPeer, .n_constraints = NELEM(kCPeer), .launch = t_launch },
|
||||
|
||||
/* Same op, same priority, same constraints. Ties break on declaration order, so t_tie_first
|
||||
* wins -- and if it ever does not, the tie rule has silently changed. */
|
||||
{ .name = "t_tie_first", .op = "t_tie", .family = "norm",
|
||||
@@ -275,6 +313,10 @@ static const RadKernelInfo kKernels[] = {
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10,
|
||||
.constraints = kCEqM32, .n_constraints = NELEM(kCEqM32),
|
||||
.init = t_init_fails, .launch = t_launch },
|
||||
|
||||
{ .name = "t_moe_any", .op = "t_moe", .family = "moe",
|
||||
.computes = "nothing; a registry row", .shape = "any", .dtypes = "any",
|
||||
.domain = RAD_DOMAIN_DEVICE, .priority = 10, .launch = t_launch },
|
||||
};
|
||||
|
||||
/* The name is a -D so that two of these can load side by side, and one of them can declare itself
|
||||
|
||||
+114
-6
@@ -109,10 +109,26 @@ struct Band {
|
||||
* beside the mapping that already holds one. A sparse Zipfian gather of a dozen rows out of
|
||||
* hundreds of millions is exactly what a page cache is good at.
|
||||
*
|
||||
* Only a HOST kernel can read one -- the bytes are pageable and at no device address -- so the
|
||||
* planner assigns this tier where, and only where, no device kernel for the op exists at all
|
||||
* (embed_lookup_q, libavx/avx_ngram.cpp, is the one such op in this tree). */
|
||||
* Only a HOST kernel can read the mapping -- the bytes are pageable and at no device address -- so
|
||||
* the planner assigns this tier where no device kernel for the op exists at all, and where
|
||||
* --ngram-placement keeps an n-gram table off the card (embed_lookup_q, libavx/avx_ngram.cpp).
|
||||
* Under `ram` the load phase publishes a copy in place of the mapping: locked memory for the host
|
||||
* gather, or pinned memory a device kernel reads over the link (the zero-copy site). */
|
||||
enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = 4 };
|
||||
|
||||
/* WHERE A LOOKUP TABLE LIVES: the token embedding (--embedding-placement) and an n-gram embedding
|
||||
* (--ngram-placement), each a model-level weight that only a row lookup reads, so a step touches M
|
||||
* of its rows and never the whole table. That is what makes every tier below the card usable for
|
||||
* it, and why the operator gets to choose.
|
||||
*
|
||||
* Vram resident on the card, a weight like any other.
|
||||
* Ram in host memory the card or a host kernel reads in place: the embedding in the pinned
|
||||
* host pool, read over the link; an n-gram table as a locked copy made at load.
|
||||
* Disk read from the container on demand.
|
||||
* Auto the fastest of the three that has room once every other weight is placed; Engine::plan
|
||||
* decides it and writes the answer into Config, so every rank plans from one choice. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
|
||||
|
||||
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
|
||||
@@ -130,6 +146,11 @@ struct WeightInfo {
|
||||
/* An uneven shard's slice of the split dimension (rad_weight_shard_span); hi 0 is the even
|
||||
* split. */
|
||||
int64_t shard_lo = 0, shard_hi = 0;
|
||||
/* rad_weight_shard_span_parts: a span per stacked part and each part's rows in the
|
||||
* container; n_part_spans 0 is shard_lo/hi (one span for every part) or the even share. */
|
||||
int n_part_spans = 0;
|
||||
int64_t part_lo[RAD_MAX_ROW_PARTS] = {0}, part_hi[RAD_MAX_ROW_PARTS] = {0};
|
||||
int64_t part_total[RAD_MAX_ROW_PARTS] = {0};
|
||||
|
||||
/* WHAT IT IS A VIEW OF (RadWeightDecl::source and ::planes, spec §4.3). `enc` is the source's
|
||||
* encoding as the model holds it -- or, with nothing behind the builder, plain in the declared
|
||||
@@ -185,6 +206,10 @@ struct WeightInfo {
|
||||
WeightInfo& operator=(const WeightInfo& o) {
|
||||
name = o.name; decl = o.decl; logical_bytes = o.logical_bytes;
|
||||
shard_lo = o.shard_lo; shard_hi = o.shard_hi;
|
||||
n_part_spans = o.n_part_spans;
|
||||
for (int i = 0; i < RAD_MAX_ROW_PARTS; ++i) {
|
||||
part_lo[i] = o.part_lo[i]; part_hi[i] = o.part_hi[i]; part_total[i] = o.part_total[i];
|
||||
}
|
||||
source = o.source; enc = o.enc; enc_known = o.enc_known; n_sel = o.n_sel;
|
||||
for (int i = 0; i < RAD_ENC_MAX_PLANES; ++i) {
|
||||
sel[i] = o.sel[i]; sel_rows[i] = o.sel_rows[i]; sel_cols[i] = o.sel_cols[i];
|
||||
@@ -267,8 +292,21 @@ struct KVGroupInfo {
|
||||
int64_t bytes_per_block = 0;
|
||||
int64_t bytes_per_state = 0; /* linear/conv: per sequence */
|
||||
std::vector<int> layers;
|
||||
bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */
|
||||
};
|
||||
|
||||
/* A RAD_KV_CONV GROUP'S WINDOW, IN ENTRIES: conv_width - 1 of history and one more for every
|
||||
* speculative position. It is the last extent of the state tensor the kernels index, and the
|
||||
* kernels take the layout from that extent -- a slot is `entries` consecutive entries a channel,
|
||||
* and libr4d's conv update derives the verify step's query length from it as
|
||||
* entries - (conv_width - 2). So the allocation's slot, the KV manager's view of a slot (its clear
|
||||
* when one is handed out, a checkpoint's save and restore) and the cursor conv_state_index derives
|
||||
* all take this one number. A slot sized larger on the manager's side than in the tensor puts
|
||||
* each of those views across the start of the next sequence's window. */
|
||||
inline int64_t conv_window_entries(const RadKVGroupDecl& d, int64_t n_spec) {
|
||||
return (d.conv_width > 0 ? d.conv_width - 1 : 0) + (n_spec > 0 ? n_spec : 0);
|
||||
}
|
||||
|
||||
/* Everything declare produced. The core owns it; the plugin only ever sees handles into it. */
|
||||
class Program {
|
||||
public:
|
||||
@@ -373,6 +411,50 @@ public:
|
||||
|
||||
enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled };
|
||||
|
||||
/* A CHAT REPLY'S REASONING BLOCK, AS TOKENS. The reply parser reads the block in text
|
||||
* (core/text/chatparse.h); this is the same block named by token id, so the engine can count it
|
||||
* and close it without detokenising. It exists only where both markers the reply needs are
|
||||
* single tokens -- `<think>` and `</think>` are, on every model this engine serves -- and
|
||||
* `close < 0` says it does not: such a reply's reasoning is still split out as text, but it is
|
||||
* not counted and no budget can be held on it.
|
||||
*
|
||||
* The block is read where the parser reads it: at the start of the reply. It is open from the
|
||||
* first token when the generation prompt opened it (`starts_open`), or opens on `open` as the
|
||||
* reply's first token, and the first `close` ends it. A reply that starts any other way has no
|
||||
* block. */
|
||||
struct ReasoningSpan {
|
||||
int32_t open = -1; /* the token a reply opens its own block with; -1 for none */
|
||||
int32_t close = -1; /* the token that ends the block; -1: no countable block */
|
||||
bool starts_open = false; /* the generation prompt left the reply inside the block */
|
||||
bool known() const { return close >= 0; }
|
||||
};
|
||||
|
||||
/* A reply's position relative to its ReasoningSpan, advanced one emitted token at a time. The
|
||||
* server counts with it and the sampler enforces a budget with it, and both must agree on where
|
||||
* the block ends, so there is one definition. */
|
||||
struct ReasoningCount {
|
||||
enum State : uint8_t { Lead, Think, Done };
|
||||
State st = Lead;
|
||||
int64_t tokens = 0; /* reasoning tokens: the markers the reply wrote, and the body */
|
||||
int64_t body = 0; /* the tokens between the markers, which a budget limits */
|
||||
|
||||
void start(const ReasoningSpan& s) {
|
||||
st = !s.known() ? Done : s.starts_open ? Think : Lead;
|
||||
tokens = body = 0;
|
||||
}
|
||||
void push(const ReasoningSpan& s, int32_t tok) {
|
||||
if (st == Lead) {
|
||||
if (s.open >= 0 && tok == s.open) { st = Think; ++tokens; }
|
||||
else st = Done;
|
||||
} else if (st == Think) {
|
||||
++tokens;
|
||||
if (tok == s.close) st = Done;
|
||||
else ++body;
|
||||
}
|
||||
}
|
||||
bool inside() const { return st == Think; }
|
||||
};
|
||||
|
||||
struct SamplingParams {
|
||||
float temp = 1.0f;
|
||||
int top_k = 0; /* 0 = off */
|
||||
@@ -394,6 +476,13 @@ struct SamplingParams {
|
||||
std::string grammar; /* GBNF, or "" */
|
||||
std::vector<std::string> dry_seq_breakers;
|
||||
|
||||
/* THE REPLY'S REASONING BLOCK, and how many tokens its body may run to. -1 is no limit. At
|
||||
* the limit the sampler masks every position still inside the block to `reasoning.close`, so
|
||||
* the block ends there and the answer follows -- vLLM's `thinking_token_budget`. A budget
|
||||
* needs a known span; the server refuses one it cannot hold. */
|
||||
ReasoningSpan reasoning;
|
||||
int32_t thinking_budget = -1;
|
||||
|
||||
/* A LAZY GRAMMAR CONSTRAINS NOTHING UNTIL A TRIGGER FIRES, and that is the only shape in
|
||||
* which a tool-calling chat template can be enforced: the reply is free prose until the
|
||||
* model starts writing a call, and grammar-shaped from there. Without this a request that
|
||||
@@ -494,6 +583,9 @@ struct Request {
|
||||
|
||||
/* ================================================================== engine config */
|
||||
|
||||
/* --p2p: whether the collectives use the cards' peer access. */
|
||||
enum { RAD_P2P_AUTO = 0, RAD_P2P_ON = 1, RAD_P2P_OFF = 2 };
|
||||
|
||||
struct Config {
|
||||
std::string model; /* path to the .rad */
|
||||
std::string radiance_home;
|
||||
@@ -520,6 +612,14 @@ struct Config {
|
||||
* floor that compresses everything which benefits while leaving single-sequence decode
|
||||
* exact. */
|
||||
int64_t tp_wire_min_kb = 128; /* --tp-wire-min-kb */
|
||||
/* HOW THE COLLECTIVES REACH THE OTHER CARDS. Auto asks the driver, for every ordered pair of
|
||||
* the ranks' cards, whether one can address the other's memory, and takes the P2P kernels only
|
||||
* if every pair can. A driver can answer yes on a board where peer traffic is broken or slower
|
||||
* than going through host memory, and that is what `off` is for: it takes the host-mailbox
|
||||
* collectives whatever the driver says. `on` takes the P2P kernels and stops startup naming
|
||||
* the pairs the driver refuses, rather than falling back -- a deployment that was measured on
|
||||
* P2P should not quietly serve on something else. */
|
||||
int p2p = RAD_P2P_AUTO; /* --p2p auto|on|off */
|
||||
int64_t max_tok = 8192; /* --max-num-batched-tokens */
|
||||
int64_t max_seqs = 256;
|
||||
int64_t max_ctx = 0; /* 0 = the model's training context */
|
||||
@@ -549,7 +649,6 @@ struct Config {
|
||||
* a third name for the second one, and a flag whose values are not all distinct is a flag
|
||||
* whose log line cannot be read back. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
double expert_cache_ratio = 0.75; /* --expert-vs-cache-ratio, weights vs KV of the remainder */
|
||||
/* SET BY THE RESOLVER, NOT BY A FLAG. vram_budget_resolve writes the two budgets above into
|
||||
* this config, which erases the only evidence of whether they were stated or derived -- and
|
||||
* Pools needs that to know whether unspent VRAM is a mis-stated budget worth warning about or
|
||||
@@ -565,6 +664,12 @@ struct Config {
|
||||
bool weights_disk_tier = false;
|
||||
|
||||
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
|
||||
/* --embedding-placement and --ngram-placement, as asked (TablePlacement says what each tier
|
||||
* is), and what Engine::plan resolved them to before any rank planned: never Auto. */
|
||||
TablePlacement embedding_placement = TablePlacement::Auto;
|
||||
TablePlacement ngram_placement = TablePlacement::Auto;
|
||||
TablePlacement embedding_resolved = TablePlacement::Vram;
|
||||
TablePlacement ngram_resolved = TablePlacement::Disk;
|
||||
bool deterministic = false;
|
||||
int64_t checkpoint_interval = 2048; /* linear-state checkpoints (spec §7.3) */
|
||||
/* HOW MANY LINEAR-STATE SNAPSHOTS THE SERVER MAY HOLD AT ONCE -- a CAP and not a charge.
|
||||
@@ -651,6 +756,8 @@ struct Config {
|
||||
/* The chat endpoint's default `reasoning_effort`, empty for the template's own default.
|
||||
* Passed through verbatim: the legal set belongs to the template, not to us. */
|
||||
std::string reasoning_effort;
|
||||
/* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */
|
||||
int64_t thinking_token_budget = -1;
|
||||
int port = 8000;
|
||||
/* --api-key: the bearer key every request but the probes and the dashboard page must carry.
|
||||
* Empty serves without one. */
|
||||
@@ -687,8 +794,9 @@ struct Config {
|
||||
sample_dry_penalty_last_n;
|
||||
std::optional<std::vector<std::string>> sample_dry_seq_breakers;
|
||||
|
||||
/* --default-max-tokens: what a request that names no max_tokens may generate. -1 is unset
|
||||
* (the server's 512), 0 is `auto` (whatever the context leaves after the prompt). */
|
||||
/* --default-max-tokens: what a request that names no max_tokens may generate. -1 is unset,
|
||||
* which is the server's default, `auto`; 0 is `auto` stated (whatever the context leaves after
|
||||
* the prompt). */
|
||||
int64_t default_max_tokens = -1;
|
||||
/* --max-tokens-cap: the most any request may generate. A larger max_tokens is clamped to it,
|
||||
* the way the context clamps one, and the reply ends with finish_reason "length". 0 is none. */
|
||||
|
||||
+28
-19
@@ -100,40 +100,46 @@ class Geometry {
|
||||
public:
|
||||
Geometry() = default;
|
||||
|
||||
/* The cached RadParam view holds char* into THIS object's own strings. An implicit copy would
|
||||
* carry those pointers into the copy along with dirty_ = false, so the copy would hand a
|
||||
* kernel pointers that dangle the moment the source dies -- and every Resolved holds a
|
||||
* Geometry while every Band holds two, so this type is copied constantly. A copy therefore
|
||||
* takes the storage and NOT the view, and rebuilds on first use.
|
||||
/* THE RadParam VIEW IS KEPT CURRENT BY EVERY WRITE, never built on first read. It holds char*
|
||||
* into this object's own strings, and a view rebuilt lazily from a const reader is a write
|
||||
* that two readers can make at once: the sizing declares of one rank all read the real
|
||||
* program's geometries side by side (Engine::probe_arena_levels), and one clearing the view
|
||||
* while another filled it is the heap corruption that crashed startup. So params() writes
|
||||
* nothing, and a Geometry nobody is writing can be read from any number of threads.
|
||||
*
|
||||
* The move is the same rule for a different reason: a moved-from vector's buffer may be
|
||||
* stolen, so the view's pointers stop meaning anything even though nothing was destroyed. */
|
||||
* A copy takes the storage and builds its own view, because the source's points into the
|
||||
* source. A move takes the view along with the storage: the vectors hand over their arrays,
|
||||
* so every string stays where it was and every pointer stays good. The moved-from object is
|
||||
* emptied, view included, so it is a valid empty geometry rather than one whose view names
|
||||
* strings it no longer owns. */
|
||||
Geometry(const Geometry& o)
|
||||
: keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {}
|
||||
: keys_(o.keys_), svals_(o.svals_), ivals_(o.ivals_), dvals_(o.dvals_), kinds_(o.kinds_) {
|
||||
rebuild();
|
||||
}
|
||||
|
||||
Geometry& operator=(const Geometry& o) {
|
||||
if (this != &o) {
|
||||
keys_ = o.keys_; svals_ = o.svals_; ivals_ = o.ivals_; dvals_ = o.dvals_;
|
||||
kinds_ = o.kinds_;
|
||||
view_.clear(); dirty_ = true;
|
||||
rebuild();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
Geometry(Geometry&& o) noexcept
|
||||
: keys_(std::move(o.keys_)), svals_(std::move(o.svals_)),
|
||||
ivals_(std::move(o.ivals_)), dvals_(std::move(o.dvals_)),
|
||||
kinds_(std::move(o.kinds_)) {
|
||||
o.view_.clear(); o.dirty_ = true;
|
||||
view_(std::move(o.view_)), ivals_(std::move(o.ivals_)),
|
||||
dvals_(std::move(o.dvals_)), kinds_(std::move(o.kinds_)) {
|
||||
o.clear();
|
||||
}
|
||||
|
||||
Geometry& operator=(Geometry&& o) noexcept {
|
||||
if (this != &o) {
|
||||
keys_ = std::move(o.keys_); svals_ = std::move(o.svals_);
|
||||
view_ = std::move(o.view_);
|
||||
ivals_ = std::move(o.ivals_); dvals_ = std::move(o.dvals_);
|
||||
kinds_ = std::move(o.kinds_);
|
||||
view_.clear(); dirty_ = true;
|
||||
o.view_.clear(); o.dirty_ = true;
|
||||
o.clear();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -149,17 +155,20 @@ public:
|
||||
const char* get_s(std::string_view k) const;
|
||||
bool has(std::string_view k) const;
|
||||
|
||||
/* A view suitable for RadArgs.p. Valid while this object lives. */
|
||||
const RadParam* params() const;
|
||||
int n_params() const;
|
||||
/* A view suitable for RadArgs.p. Valid while this object lives and is not written. */
|
||||
const RadParam* params() const { return view_.data(); }
|
||||
int n_params() const { return (int)view_.size(); }
|
||||
|
||||
std::string str() const; /* "M=64 N=8192 K=5120 dtype=w4a8", for diagnostics */
|
||||
|
||||
private:
|
||||
std::vector<std::string> keys_, svals_;
|
||||
std::vector<RadParam> view_;
|
||||
mutable bool dirty_ = true;
|
||||
void rebuild() const;
|
||||
void rebuild();
|
||||
void clear() noexcept {
|
||||
keys_.clear(); svals_.clear(); view_.clear(); ivals_.clear(); dvals_.clear();
|
||||
kinds_.clear();
|
||||
}
|
||||
std::vector<long long> ivals_;
|
||||
std::vector<double> dvals_;
|
||||
std::vector<int> kinds_;
|
||||
|
||||
+11
-9
@@ -760,10 +760,12 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
const uint32_t g = o.handle;
|
||||
if ((size_t)g >= kv_.size() || !kv_[g].base)
|
||||
return abort_step_msg(h, RAD_E_STATE,
|
||||
fmt("operand %d names KV group %u, which has no pool bound. "
|
||||
"The block manager allocates it at load and binds it "
|
||||
"into the Ctx; a group with none is a startup bug, not "
|
||||
"a runtime condition", i, g));
|
||||
fmt("operand %d names KV group %u, which has no pool bound on "
|
||||
"this rank. The block manager allocates it at load and "
|
||||
"binds it into the Ctx; a group with none is a startup "
|
||||
"bug -- or a group this rank declared with "
|
||||
"rad_kv_group_zero and then issued against, which the "
|
||||
"plugin must not do", i, g));
|
||||
const KVPoolBinding& b = kv_[g];
|
||||
/* A POSITION LOOKUP, not `o.offset - first_layer`. The subtraction is right only for a
|
||||
* group whose layers are contiguous, and they need not be: with 15 attention layers
|
||||
@@ -890,11 +892,11 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
* is the one place it stops being harmless: it runs NOW, on this thread, and reads and writes
|
||||
* the host arena NOW.
|
||||
*
|
||||
* A PLE gather is exactly that shape. `ngram_ids` writes the hashed row ids into a host-domain
|
||||
* buffer on the device, and `embed_lookup_q` reads them on the host. With no join the host
|
||||
* reads whatever the arena holds from an earlier step and gathers the rows of the wrong
|
||||
* n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text that
|
||||
* is a stable wrong answer rather than an intermittent one.
|
||||
* A PLE gather on the host is exactly that shape. `ngram_ids` writes the hashed row ids into a
|
||||
* host-domain buffer on the device, and `embed_lookup_q` reads them on the host. With no join
|
||||
* the host reads whatever the arena holds from an earlier step and gathers the rows of the
|
||||
* wrong n-gram -- valid ids, valid rows, every kernel agreeing with its oracle, and fluent text
|
||||
* that is a stable wrong answer rather than an intermittent one.
|
||||
*
|
||||
* WHAT THE JOIN WAITS FOR is the last device op on each lane that touched the host arena
|
||||
* (host_touch_ev_), not the whole stream. Every hazard a host op has is with such an op -- the
|
||||
|
||||
@@ -483,9 +483,12 @@ bool Ctx::oracle_unrelayout(rad_op h, const IssuePlan& hip, const IssuePlan& dip
|
||||
}
|
||||
RadOpdDesc d{};
|
||||
if (shape(dip.args.p, dip.args.n_p, i, &d) != RAD_OK || d.rank == 0) {
|
||||
/* A shape hook declines without a reason (RadShapeFn), so the geometry it declined is
|
||||
* printed, the dtype with it -- a description refuses a dtype it knows no grid for. */
|
||||
RAD_WARN("oracle #%lld op '%s': NOT CHECKED. nothing could describe the logical form "
|
||||
"of '%s' at this geometry, so there is nothing to invert its layout into.",
|
||||
(long long)seq, oi.op.c_str(), w.name.c_str());
|
||||
"of '%s' at this geometry {%s}, so there is nothing to invert its layout "
|
||||
"into.", (long long)seq, oi.op.c_str(), w.name.c_str(),
|
||||
oi.base.str().c_str());
|
||||
return false;
|
||||
}
|
||||
RadTensor lg{};
|
||||
|
||||
+112
-114
@@ -19,7 +19,7 @@ TierExec::~TierExec() { close(); }
|
||||
int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
|
||||
int64_t max_chain, bool leader, int device, int64_t slot_off,
|
||||
int64_t ck_slot_off, RadStream shared) {
|
||||
const HostArena* ck_store, RadStream shared) {
|
||||
close();
|
||||
if (!reg || !kv || !tiers || groups.empty() || max_batch <= 0 || max_copy <= 0 ||
|
||||
max_chain <= 0)
|
||||
@@ -28,9 +28,7 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
max_batch_ = max_batch; max_copy_ = max_copy; max_chain_ = max_chain;
|
||||
slot_off_ = slot_off;
|
||||
slot_bytes_ = tiers->entry_bytes();
|
||||
ck_bytes_ = kv->checkpoint_bytes();
|
||||
ck_slot_bytes_ = tiers->ckpt_bytes();
|
||||
ck_slot_off_ = ck_slot_off;
|
||||
ck_store_ = ck_store && ck_store->enabled() ? ck_store : nullptr;
|
||||
shared_ = shared;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
|
||||
@@ -46,6 +44,11 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
gi.n_blocks = p->n_blocks;
|
||||
gi.base = p->base;
|
||||
gi.off = off;
|
||||
if (p->zero) {
|
||||
gi.zero = true;
|
||||
gi_.push_back(gi);
|
||||
continue;
|
||||
}
|
||||
/* THE FRAGMENT WIDTH IS THE CONSTRAINT THE KERNEL IS PICKED ON. libr4d's byte-row pair
|
||||
* takes n as a multiple of 4; a geometry that does not satisfy it resolves to nothing
|
||||
* here rather than failing at launch inside a batch. */
|
||||
@@ -66,6 +69,15 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
gi_.push_back(gi);
|
||||
}
|
||||
if (gi_.empty()) return RAD_E_UNSUPPORTED;
|
||||
/* EVERY CACHED GROUP ZERO ON THIS RANK: it would hold nothing of any entry, and an empty
|
||||
* entry is a zero-width copy on every path below. Said, and the tiers are off -- one rank
|
||||
* that cannot take part takes them off for all. */
|
||||
if (off == 0) {
|
||||
RAD_WARN("kv tiers: this rank keeps no cache for any group the prefix cache holds "
|
||||
"(rad_kv_group_zero), so it has no part of an entry to move. The tiers are off.");
|
||||
close();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
entry_bytes_ = off;
|
||||
|
||||
/* NOTHING IS BUILT ON THE DEVICE HERE -- see device_init(). A tier that is configured but has
|
||||
@@ -77,15 +89,35 @@ int TierExec::configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier*
|
||||
char buf[320];
|
||||
std::snprintf(buf, sizeof buf,
|
||||
"kv tier transfer: %zu paged group(s), %s an entry, batches of %d through "
|
||||
"gather_rows/scatter_rows at u8%s%s",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(), max_batch_,
|
||||
ck_bytes_ > 0 ? "; linear state as one contiguous copy of " : "",
|
||||
ck_bytes_ > 0 ? humanb(ck_bytes_).c_str() : "");
|
||||
"gather_rows/scatter_rows at u8",
|
||||
gi_.size(), humanb(entry_bytes_).c_str(), max_batch_);
|
||||
report_ = buf;
|
||||
enabled_ = true;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
TierExec::Sizes TierExec::sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size) {
|
||||
Sizes s;
|
||||
if (entry_bytes <= 0) return s;
|
||||
/* 16 MiB of staging a rank, as entries, between 64 and 4096 of them: the reasons are at the
|
||||
* call in bringup. A copy out is four batches, and a restore is a whole chain, as long as the
|
||||
* longest context the server takes. */
|
||||
s.max_batch = (int)std::min<int64_t>(4096, std::max<int64_t>(64, (16ll << 20) / entry_bytes));
|
||||
s.max_copy = 4ll * s.max_batch;
|
||||
const int64_t bs = std::max<int64_t>(1, block_size);
|
||||
s.max_chain = (std::max<int64_t>(1, max_ctx) + bs - 1) / bs + 1;
|
||||
return s;
|
||||
}
|
||||
|
||||
/* What device_init() allocates, each allocation rounded to the pool granule the card hands VRAM
|
||||
* out in. */
|
||||
int64_t TierExec::device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s) {
|
||||
if (entry_bytes <= 0 || n_groups <= 0 || s.max_batch <= 0) return 0;
|
||||
const int64_t idx_n = (int64_t)n_groups * (s.max_copy + (int64_t)kRing * s.max_chain);
|
||||
return align_up((int64_t)s.max_batch * entry_bytes, (int64_t)RAD_ALIGN_POOL) +
|
||||
align_up(idx_n * (int64_t)sizeof(int32_t), (int64_t)RAD_ALIGN_POOL);
|
||||
}
|
||||
|
||||
void TierExec::close() {
|
||||
/* Nothing may still be reading the buffers about to be freed. */
|
||||
if (stream_) (void)rad_stream_sync(stream_);
|
||||
@@ -107,7 +139,7 @@ void TierExec::close() {
|
||||
order_.clear();
|
||||
verify_pending_.clear();
|
||||
entry_bytes_ = 0;
|
||||
ck_bytes_ = ck_slot_bytes_ = ck_slot_off_ = 0;
|
||||
ck_store_ = nullptr;
|
||||
enabled_ = false;
|
||||
leader_ = false;
|
||||
reg_ = nullptr; kv_ = nullptr; tiers_ = nullptr; disk_ = nullptr;
|
||||
@@ -233,22 +265,20 @@ static uint64_t tier_fnv(const void* p, int64_t n) {
|
||||
return h;
|
||||
}
|
||||
|
||||
void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
void TierExec::verify_note(const BlockHash& key, const void* p, int64_t n) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
(snapshot ? out_ck_ : out_sum_)[key] = tier_fnv(p, n);
|
||||
out_sum_[key] = tier_fnv(p, n);
|
||||
}
|
||||
|
||||
void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot) {
|
||||
void TierExec::verify_check(const BlockHash& key, const void* p, int64_t n) {
|
||||
if (!verify_ || !leader_ || !p || n <= 0) return;
|
||||
auto& m = snapshot ? out_ck_ : out_sum_;
|
||||
auto it = m.find(key);
|
||||
if (it == m.end()) return; /* never went out through this process */
|
||||
auto it = out_sum_.find(key);
|
||||
if (it == out_sum_.end()) return; /* never went out through this process */
|
||||
const uint64_t back = tier_fnv(p, n);
|
||||
if (back == it->second) return;
|
||||
RAD_ERR("kv tiers: the %s for %s came back DIFFERENT (%016llx out, %016llx in). The tier is "
|
||||
"moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
snapshot ? "linear-state snapshot" : "attention blocks", key.str().c_str(),
|
||||
(unsigned long long)it->second, (unsigned long long)back);
|
||||
RAD_ERR("kv tiers: the attention blocks for %s came back DIFFERENT (%016llx out, %016llx in). "
|
||||
"The tier is moving the wrong bytes, not the engine choosing differently downstream.",
|
||||
key.str().c_str(), (unsigned long long)it->second, (unsigned long long)back);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ helpers */
|
||||
@@ -273,7 +303,7 @@ bool TierExec::blocks_backed(const std::vector<int32_t>& blocks, const char* wha
|
||||
for (size_t k = 0; k < gi_.size(); ++k) {
|
||||
if (k >= blocks.size()) continue; /* an absent group is the gather's -1 row */
|
||||
const int32_t b = blocks[k];
|
||||
if (b < 0) continue;
|
||||
if (b < 0 || gi_[k].zero) continue;
|
||||
const int64_t live = kv_->live_blocks(gi_[k].g);
|
||||
if (b < live) continue;
|
||||
if (warned_unbacked_) return false;
|
||||
@@ -330,7 +360,7 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
if (!blocks_backed(j->blocks, "copy to host")) return RAD_E_STATE;
|
||||
|
||||
/* AFTER EVERYTHING THE COMPUTE STREAM HAS BEEN GIVEN, which includes the step that wrote these
|
||||
* blocks and the save that wrote the snapshots. A stream wait, not a host wait. */
|
||||
* blocks. A stream wait, not a host wait. */
|
||||
TIER_TRY(rad_event_record(ev_compute_, compute), "ordering the copy after the step");
|
||||
TIER_TRY(rad_event_wait(stream_, ev_compute_), "ordering the copy after the step");
|
||||
|
||||
@@ -347,7 +377,7 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
for (int64_t s = 0; s < n; s += max_batch_) {
|
||||
const int64_t c = std::min<int64_t>(max_batch_, n - s);
|
||||
for (size_t gidx = 0; gidx < gi_.size(); ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers; ++l)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && !gi_[gidx].zero; ++l)
|
||||
TIER_TRY(run_rows(gi_[gidx].gather, /*scatter=*/false, gi_[gidx], l, stage_,
|
||||
idx_dev_ + (int64_t)gidx * n + s, c),
|
||||
"the gather out of the pool");
|
||||
@@ -356,30 +386,13 @@ int TierExec::enqueue_copy(std::vector<TierJob>& jobs, RadStream compute) {
|
||||
st_.bytes_out += n * entry_bytes_;
|
||||
}
|
||||
|
||||
/* The linear half: one contiguous copy each, out of the device slot the snapshot sits in. */
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0 || j.ck_dev < 0 || ck_bytes_ <= 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const void* src = kv_->checkpoint_ptr(j.ck_dev);
|
||||
char* dst = (char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
const int st = rad_memcpy_async(dst + ck_slot_off_, src, ck_bytes_, stream_);
|
||||
if (st != RAD_OK) {
|
||||
warn_once("the snapshot copy to host memory", st);
|
||||
j.ck_ok = false;
|
||||
continue;
|
||||
}
|
||||
st_.bytes_out += ck_bytes_;
|
||||
}
|
||||
|
||||
TIER_TRY(rad_event_record(ev_copy_, stream_), "marking the copy");
|
||||
copy_out_ = true;
|
||||
++st_.passes;
|
||||
st_.jobs += (int64_t)jobs.size();
|
||||
if (verify_)
|
||||
for (const TierJob& j : jobs)
|
||||
verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot,
|
||||
j.ck_ok ? j.ck_host : -1});
|
||||
verify_pending_.push_back({j.key, j.blocks.empty() ? -1 : j.host_slot});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -393,10 +406,7 @@ int TierExec::copy_state() {
|
||||
for (const VerifyNote& v : verify_pending_) {
|
||||
if (v.host_slot >= 0)
|
||||
verify_note(v.key, (char*)tiers_->arena().at(v.host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
if (v.ck_host >= 0)
|
||||
verify_note(v.key, (char*)tiers_->ckpt_arena().at(v.ck_host) + ck_slot_off_,
|
||||
ck_bytes_, true);
|
||||
entry_bytes_);
|
||||
}
|
||||
}
|
||||
verify_pending_.clear();
|
||||
@@ -404,8 +414,22 @@ int TierExec::copy_state() {
|
||||
return q > 0 ? 1 : q;
|
||||
}
|
||||
|
||||
int TierExec::wait_copy() {
|
||||
if (!copy_out_) return 1;
|
||||
(void)rad_dev_set(device_);
|
||||
const int st = rad_event_sync(ev_copy_);
|
||||
if (st != RAD_OK) warn_once("waiting for the copy to host memory", st);
|
||||
return copy_state();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ restore */
|
||||
|
||||
void TierExec::quiesce() {
|
||||
if (!enabled_ || !stream_) return;
|
||||
if (rad_dev_set(device_) < 0) return;
|
||||
(void)rad_stream_sync(stream_);
|
||||
}
|
||||
|
||||
int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
std::vector<char>* ok) {
|
||||
ok->assign(jobs.size(), 0);
|
||||
@@ -464,7 +488,7 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
for (size_t i = 0; i < m; ++i) order_.push_back(&jobs[i]);
|
||||
for (size_t i = 0; i < m; ++i)
|
||||
verify_check(jobs[i].key, (char*)tiers_->arena().at(jobs[i].host_slot) + slot_off_,
|
||||
entry_bytes_, false);
|
||||
entry_bytes_);
|
||||
|
||||
/* FROM HERE ON A FAILURE LEAVES A MIXTURE, so every job about to be written is marked started
|
||||
* first -- report() drops a started job that failed rather than trusting its host copy to
|
||||
@@ -491,7 +515,7 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
const int64_t cc = std::min<int64_t>(max_batch_, c - b);
|
||||
if ((st = copy_runs(order_, s + (size_t)b, cc, /*out=*/false)) != RAD_OK) break;
|
||||
for (size_t gidx = 0; gidx < ng && st == RAD_OK; ++gidx)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK; ++l)
|
||||
for (int64_t l = 0; l < gi_[gidx].n_layers && st == RAD_OK && !gi_[gidx].zero; ++l)
|
||||
st = run_rows(gi_[gidx].scatter, /*scatter=*/true, gi_[gidx], l, stage_,
|
||||
d + (int64_t)gidx * c + b, cc);
|
||||
}
|
||||
@@ -501,45 +525,6 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
for (size_t i = 0; i < done; ++i) (*ok)[i] = 1;
|
||||
st_.bytes_in += (int64_t)done * entry_bytes_;
|
||||
|
||||
/* THE LINEAR HALF, into a slot the leader allocates. The same rule as the blocks: the id is
|
||||
* rank 0's to choose, and a follower takes the id it is handed and backs its own pages. A
|
||||
* snapshot that cannot be placed is not a failure of the restore -- the session keeps its
|
||||
* attention hit and replays its linear layers, which is what it would have done with no
|
||||
* tiers at all.
|
||||
*
|
||||
* THE DEEPEST ONE IS WORTH A SLOT SOMEBODY ELSE HAS. A hit resumes from the last checkpoint at
|
||||
* or below its attention hit, which on a restored chain is the chain's last snapshot; the
|
||||
* earlier ones take a slot only where one is free. A full pool is then made room in for that
|
||||
* one snapshot by detaching another session's, which that session's own next restore brings
|
||||
* back -- rather than for every snapshot on the chain, which would push out as many other
|
||||
* sessions' states as this one has checkpoints. */
|
||||
size_t deepest = done;
|
||||
for (size_t i = 0; i < done; ++i)
|
||||
if (jobs[i].ck_want && jobs[i].ck_ok && jobs[i].ck_host >= 0) deepest = i;
|
||||
for (size_t i = 0; i < done; ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!j.ck_want || !j.ck_ok || j.ck_host < 0 || ck_bytes_ <= 0) continue;
|
||||
if (leader_) {
|
||||
int32_t slot = -1;
|
||||
if (kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0) {
|
||||
slot = -1;
|
||||
if (i != deepest || !ck_room_ || !ck_room_() ||
|
||||
kv_->alloc_checkpoint(&slot) != RAD_OK || slot < 0)
|
||||
continue;
|
||||
}
|
||||
j.ck_dev = slot;
|
||||
}
|
||||
if (j.ck_dev < 0) continue;
|
||||
if (kv_->back_checkpoint(j.ck_dev) < 0) { j.ck_ok = false; continue; }
|
||||
const char* src = (const char*)tiers_->ckpt_arena().at(j.ck_host);
|
||||
void* dst = kv_->checkpoint_ptr(j.ck_dev);
|
||||
if (!src || !dst) { j.ck_ok = false; continue; }
|
||||
verify_check(j.key, src + ck_slot_off_, ck_bytes_, true);
|
||||
const int cs = rad_memcpy_async(dst, src + ck_slot_off_, ck_bytes_, stream_);
|
||||
if (cs != RAD_OK) { warn_once("the snapshot copy back into the pool", cs); j.ck_ok = false; continue; }
|
||||
st_.bytes_in += ck_bytes_;
|
||||
}
|
||||
|
||||
/* THE STEP THAT READS THESE WAITS FOR THEM, on the device. If even the marker cannot be
|
||||
* enqueued the only ordering left is the host's. */
|
||||
if (rad_event_record(ev_restore_, stream_) != RAD_OK ||
|
||||
@@ -551,13 +536,13 @@ int TierExec::issue_restore(std::vector<TierJob>& jobs, RadStream compute,
|
||||
return st;
|
||||
}
|
||||
|
||||
int TierExec::fence(RadEvent* out) {
|
||||
int TierExec::fence(RadEvent* out, RadStream on) {
|
||||
*out = nullptr;
|
||||
if (!enabled_ || !stream_) return RAD_OK;
|
||||
if (!enabled_ || (!on && !stream_)) return RAD_OK;
|
||||
RAD_TRY(rad_dev_set(device_));
|
||||
RadEvent e = nullptr;
|
||||
RAD_TRY(rad_event_create(&e));
|
||||
const int st = rad_event_record(e, stream_);
|
||||
const int st = rad_event_record(e, on ? on : stream_);
|
||||
if (st != RAD_OK) { rad_event_destroy(e); return st; }
|
||||
*out = e;
|
||||
return RAD_OK;
|
||||
@@ -580,12 +565,13 @@ bool TierExec::run_write(TierJob& j) {
|
||||
const void* src = tiers_->arena().at(j.host_slot);
|
||||
ok = disk_ && src && disk_->put_block(j.key, nullptr, 0, src, slot_bytes_) == RAD_OK;
|
||||
}
|
||||
if (j.ck_host >= 0) {
|
||||
const void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
if (j.ck_slot >= 0) {
|
||||
const void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr;
|
||||
/* A snapshot store that was never opened -- no room for one inside the disk cap -- refuses
|
||||
* this, which is the right answer and not an error: the host copy stays the only one, as
|
||||
* it was. */
|
||||
j.ck_ok = disk_ && cs && disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
* this, which is the right answer and not an error: the slot stays the only copy, as it
|
||||
* was. */
|
||||
j.ck_ok = disk_ && cs &&
|
||||
disk_->put_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK;
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
@@ -611,9 +597,10 @@ void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
st_.bytes_in += (int64_t)keys.size() * slot_bytes_;
|
||||
}
|
||||
for (TierJob& j : jobs) {
|
||||
if (j.ck_host < 0) continue;
|
||||
void* cs = tiers_->ckpt_arena().at(j.ck_host);
|
||||
j.ck_ok = disk_ && cs && disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_slot_bytes_) == RAD_OK;
|
||||
if (!j.ck_want || j.ck_slot < 0) continue;
|
||||
void* cs = ck_store_ ? ck_store_->at(j.ck_slot) : nullptr;
|
||||
j.ck_ok = disk_ && cs &&
|
||||
disk_->get_checkpoint(j.key, j.ck_pos, cs, ck_store_->slot_bytes()) == RAD_OK;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -622,28 +609,23 @@ void TierExec::run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok) {
|
||||
void TierExec::report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok,
|
||||
uint64_t now_ns) {
|
||||
if (!enabled_ || !leader_) return;
|
||||
bool quiet = false;
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
const bool good = i < ok.size() && ok[i];
|
||||
/* A SNAPSHOT IS RESTORED ONLY IF EVERY RANK RESTORED ITS SHARD, and the leader is the only
|
||||
* one that can act on that. It allocates the checkpoint slot and fills its own window
|
||||
* first, so a follower that then fails leaves the slot holding this rank's new state beside
|
||||
* another rank's stale state -- a checkpoint the cache would go on to serve, one card
|
||||
* resuming the conversation and the other resuming whatever it last held.
|
||||
*
|
||||
* A PROMOTION THAT FAILED AS A WHOLE gives back everything the leader took for it: report()
|
||||
* drops or keeps the record, and nothing will ever name these blocks or this slot again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && j.ck_dev >= 0 && (!j.ck_ok || !good)) {
|
||||
kv_->free_checkpoint(j.ck_dev);
|
||||
j.ck_dev = -1;
|
||||
}
|
||||
/* A PROMOTION THAT FAILED AS A WHOLE gives back the blocks the leader took for it, once
|
||||
* nothing queued against them can still land: report() drops or keeps the record, and
|
||||
* nothing will ever name these blocks again. */
|
||||
if (j.kind == TierJob::Kind::ToDevice && !good) {
|
||||
if (!quiet) { quiesce(); quiet = true; }
|
||||
for (size_t k = 0; k < gi_.size() && k < j.blocks.size(); ++k)
|
||||
if (j.blocks[k] >= 0) kv_->release_block(gi_[k].g, j.blocks[k]);
|
||||
j.blocks.clear();
|
||||
}
|
||||
tiers_->report(j, good, now_ns);
|
||||
}
|
||||
/* STORE SLOTS THE TIERS HAD BEEN KEEPING: a write that read one the cache let go of, or a
|
||||
* read nothing took. The disk thread is done with them -- these come only from reports. */
|
||||
std::vector<int32_t> frees;
|
||||
tiers_->take_checkpoint_frees(&frees);
|
||||
for (int32_t s : frees) kv_->free_checkpoint(s);
|
||||
@@ -681,11 +663,12 @@ void TierIO::stop() {
|
||||
fetch_done_.clear();
|
||||
}
|
||||
|
||||
bool TierIO::submit(std::vector<TierJob>&& jobs) {
|
||||
bool TierIO::submit(std::vector<TierJob>&& jobs, std::vector<RadEvent>&& fences) {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (has_work_ || has_done_ || !th_.joinable()) return false;
|
||||
work_ = std::move(jobs);
|
||||
work_fences_ = std::move(fences);
|
||||
ok_.assign(work_.size(), 1);
|
||||
work_at_ = 0;
|
||||
has_work_ = true;
|
||||
@@ -712,12 +695,15 @@ bool TierIO::take_fetch(Fetch* out) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool TierIO::take(std::vector<TierJob>* jobs, std::vector<char>* ok) {
|
||||
bool TierIO::take(std::vector<TierJob>* jobs, std::vector<char>* ok,
|
||||
std::vector<RadEvent>* fences) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!has_done_) return false;
|
||||
*jobs = std::move(done_);
|
||||
*ok = std::move(ok_);
|
||||
if (fences) *fences = std::move(done_fences_);
|
||||
done_.clear();
|
||||
done_fences_.clear();
|
||||
ok_.clear();
|
||||
has_done_ = false;
|
||||
return true;
|
||||
@@ -756,14 +742,26 @@ void TierIO::loop() {
|
||||
fetch_done_.push_back(std::move(f));
|
||||
continue;
|
||||
}
|
||||
/* One write at a time, so a read that arrives behind a long batch waits for one job. */
|
||||
const bool ok = i < work_.size() ? x_->run_write(work_[i]) : true;
|
||||
/* NOT A BYTE UNTIL THE COPIES THAT FILLED THE SLOTS HAVE LANDED, once a batch. A fence
|
||||
* that cannot be waited on fails the batch, and every record keeps what it had. */
|
||||
bool fenced = true;
|
||||
if (i == 0)
|
||||
for (RadEvent e : work_fences_) if (e && rad_event_sync(e) != RAD_OK) fenced = false;
|
||||
bool ok = false;
|
||||
if (fenced) ok = i < work_.size() ? x_->run_write(work_[i]) : true;
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (i < ok_.size()) ok_[i] = ok ? 1 : 0;
|
||||
work_at_ = i + 1;
|
||||
if (!fenced) {
|
||||
ok_.assign(work_.size(), 0);
|
||||
work_at_ = work_.size();
|
||||
} else {
|
||||
if (i < ok_.size()) ok_[i] = ok ? 1 : 0;
|
||||
work_at_ = i + 1;
|
||||
}
|
||||
if (work_at_ >= work_.size()) {
|
||||
done_ = std::move(work_);
|
||||
done_fences_ = std::move(work_fences_);
|
||||
work_.clear();
|
||||
work_fences_.clear();
|
||||
has_work_ = false;
|
||||
has_done_ = true;
|
||||
}
|
||||
|
||||
+49
-32
@@ -71,11 +71,19 @@ public:
|
||||
int configure(Registry* reg, KVManager* kv, IdleTiers* tiers, SSDTier* disk,
|
||||
const std::vector<int32_t>& groups, int max_batch, int64_t max_copy,
|
||||
int64_t max_chain, bool leader, int device, int64_t slot_off,
|
||||
int64_t ck_slot_off, RadStream shared);
|
||||
const HostArena* ck_store, RadStream shared);
|
||||
void close();
|
||||
bool enabled() const { return enabled_; }
|
||||
std::string report() const { return report_; }
|
||||
|
||||
/* THE SIZES A CONFIGURE IS GIVEN, from one entry's bytes on this rank, the longest context and
|
||||
* the block size, and the VRAM device_init() then takes for them. The VRAM budget reserves
|
||||
* device_bytes() before any of this exists and bringup configures with sizes(), so the two
|
||||
* cannot drift apart. */
|
||||
struct Sizes { int max_batch = 0; int64_t max_copy = 0, max_chain = 0; };
|
||||
static Sizes sizes(int64_t entry_bytes, int64_t max_ctx, int64_t block_size);
|
||||
static int64_t device_bytes(int64_t entry_bytes, int n_groups, const Sizes& s);
|
||||
|
||||
/* DECIDING AND DOING ARE SEPARATE, and under tensor parallelism that is the point. The policy
|
||||
* is one object describing CONVERSATIONS, which are not sharded; the transfer is per rank,
|
||||
* because each rank holds its own shard of every block. So the leader plans, every rank runs
|
||||
@@ -97,6 +105,13 @@ public:
|
||||
* the transfer stream reported an error. Taking the answer clears it. */
|
||||
int copy_state();
|
||||
bool copy_out() const { return copy_out_; }
|
||||
/* copy_state, after waiting for the batch to land. For a caller that cannot go on until the
|
||||
* copy has a host slot to show for it -- an eviction that would otherwise lose the entry. */
|
||||
int wait_copy();
|
||||
/* EVERYTHING THIS RANK ENQUEUED HAS LANDED. For a block given back on a failure path while a
|
||||
* copy into it may still be in flight: the pool would hand it to a sequence whose writes the
|
||||
* late copy then overwrites. */
|
||||
void quiesce();
|
||||
|
||||
/* ---------------- restore ----------------
|
||||
*
|
||||
@@ -107,36 +122,33 @@ public:
|
||||
* the jobs past the cut are left unstarted. `ok[i]` is whether job i was fully enqueued on
|
||||
* this rank. */
|
||||
int issue_restore(std::vector<TierJob>& jobs, RadStream compute, std::vector<char>* ok);
|
||||
|
||||
/* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far. A restore
|
||||
* reads host slots asynchronously, and a slot it is still reading may be given up and handed
|
||||
* to a read off disk the moment the restore has reported; the IO thread waits for this mark
|
||||
* before it writes into any slot it was handed. Null when nothing was ever enqueued here. The
|
||||
/* A MARK ON THIS RANK'S TRANSFER STREAM, after everything enqueued on it so far -- or on
|
||||
* `on`, the rank's compute stream, when it is given. A restore reads host slots
|
||||
* asynchronously, and a slot it is still reading may be given up and handed to a read off
|
||||
* disk the moment the restore has reported; the IO thread waits for this mark before it
|
||||
* writes into any slot it was handed. A snapshot's store slot is read and written by copies
|
||||
* on the compute stream (KVManager::checkpoint_save), so a disk write or read of one waits
|
||||
* for that stream's mark. Null when nothing was ever enqueued on the transfer stream. The
|
||||
* caller owns the event. */
|
||||
int fence(RadEvent* out);
|
||||
int fence(RadEvent* out, RadStream on = nullptr);
|
||||
|
||||
/* ---------------- the disk store (leader only; TierIO's thread) ---------------- */
|
||||
void run_disk(std::vector<TierJob>& jobs, std::vector<char>* ok);
|
||||
/* One ToDisk job; true when it was written. */
|
||||
bool run_write(TierJob& j);
|
||||
/* ToHost jobs: the blocks read in parallel into the host slots they were given, then the
|
||||
* snapshots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */
|
||||
* snapshots into their store slots. `ok[i]` is the blocks' result, `ck_ok` the snapshot's. */
|
||||
void run_fetch(std::vector<TierJob>& jobs, std::vector<char>* ok);
|
||||
|
||||
/* Leader only. Gives back what a failed job held -- a restore's blocks and checkpoint slot --
|
||||
* reports every job to the policy, and frees the device checkpoint slots a finished copy was
|
||||
* holding on the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */
|
||||
/* Leader only. Gives back what a failed job held -- a restore's blocks -- reports every job to
|
||||
* the policy, and frees the store slots a finished write or an unclaimed read was holding on
|
||||
* the cache's behalf. `now_ns` is when the pass ran: a promotion is a use. */
|
||||
void report_pass(std::vector<TierJob>& jobs, const std::vector<char>& ok, uint64_t now_ns);
|
||||
|
||||
/* A lookup hit off-device: the job that would bring it back, or false when the entry is not
|
||||
* off-device or already has work outstanding. */
|
||||
bool plan_promote(const BlockHash& key, TierJob* out); /* leader only */
|
||||
|
||||
/* Leader only: how a restore gets a device checkpoint slot when the pool is full. The cache
|
||||
* owns the policy for which snapshot gives its slot up (PrefixCache::free_checkpoint_for_restore);
|
||||
* this object only knows it needs one. True when a slot was freed. */
|
||||
void set_checkpoint_room(std::function<bool()> f) { ck_room_ = std::move(f); }
|
||||
|
||||
struct Stats { int64_t passes = 0, jobs = 0, bytes_out = 0, bytes_in = 0; };
|
||||
const Stats& stats() const { return st_; }
|
||||
|
||||
@@ -149,6 +161,10 @@ private:
|
||||
int64_t n_blocks = 0;
|
||||
void* base = nullptr;
|
||||
int64_t off = 0; /* this group's start inside one entry's staging bytes */
|
||||
/* rad_kv_group_zero: no shard on this rank. Kept in its place, because a job's block ids
|
||||
* are one per cached group in the same order on every rank; nothing is gathered or
|
||||
* scattered for it and it is no part of this rank's entry. */
|
||||
bool zero = false;
|
||||
Resolved gather, scatter;
|
||||
};
|
||||
|
||||
@@ -194,16 +210,13 @@ private:
|
||||
KVManager* kv_ = nullptr;
|
||||
IdleTiers* tiers_ = nullptr;
|
||||
SSDTier* disk_ = nullptr;
|
||||
std::function<bool()> ck_room_;
|
||||
std::vector<GroupInfo> gi_;
|
||||
int64_t entry_bytes_ = 0;
|
||||
/* ---- the linear half ----
|
||||
* `ck_bytes_` is THIS RANK's shard of one snapshot and `ck_slot_bytes_` the whole shared slot,
|
||||
* exactly as entry_bytes_ and slot_bytes_ are for blocks. Zero on a model with no recurrent
|
||||
* state, which is the whole of the "off" path here. */
|
||||
int64_t ck_bytes_ = 0;
|
||||
int64_t ck_slot_bytes_ = 0;
|
||||
int64_t ck_slot_off_ = 0;
|
||||
* The engine's snapshot store, whose slots the disk thread writes out and reads back whole --
|
||||
* every rank's shard of a snapshot together. Null on a model with no recurrent state, which
|
||||
* is the whole of the "off" path here. */
|
||||
const HostArena* ck_store_ = nullptr;
|
||||
int max_batch_ = 0;
|
||||
int64_t max_copy_ = 0;
|
||||
int64_t max_chain_ = 0;
|
||||
@@ -246,17 +259,17 @@ private:
|
||||
* the only question worth asking first: is the tier moving the wrong bytes, or is it moving
|
||||
* the right ones and something downstream is choosing differently?
|
||||
*
|
||||
* A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which for a snapshot is tens of
|
||||
* milliseconds an entry -- affordable when a run is being bisected and not otherwise. Off
|
||||
* A DIAGNOSTIC, NOT A GUARD. It hashes on the host, which is a cost on every entry --
|
||||
* affordable when a run is being bisected and not otherwise. Off
|
||||
* unless the variable is set, and leader-only, because the map is keyed by an object the
|
||||
* followers do not own. A copy out is hashed when it has LANDED, which is when copy_state
|
||||
* first sees it done. */
|
||||
bool verify_ = false;
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_, out_ck_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; int32_t ck_host = -1; };
|
||||
std::unordered_map<BlockHash, uint64_t, BlockHashHash> out_sum_;
|
||||
struct VerifyNote { BlockHash key; int32_t host_slot = -1; };
|
||||
std::vector<VerifyNote> verify_pending_;
|
||||
void verify_note(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
void verify_check(const BlockHash& key, const void* p, int64_t n, bool snapshot);
|
||||
void verify_note(const BlockHash& key, const void* p, int64_t n);
|
||||
void verify_check(const BlockHash& key, const void* p, int64_t n);
|
||||
|
||||
std::string report_;
|
||||
Stats st_;
|
||||
@@ -280,10 +293,13 @@ public:
|
||||
~TierIO();
|
||||
void start(TierExec* leader);
|
||||
void stop();
|
||||
/* False when a batch is already out. */
|
||||
bool submit(std::vector<TierJob>&& jobs);
|
||||
/* False when a batch is already out. `fences` are waited on before the first job is written --
|
||||
* a snapshot's store slot is filled by a copy on the compute stream (TierExec::fence) -- and
|
||||
* come back with the batch from take(), still the caller's to destroy. */
|
||||
bool submit(std::vector<TierJob>&& jobs, std::vector<RadEvent>&& fences = {});
|
||||
/* The finished batch, when there is one. */
|
||||
bool take(std::vector<TierJob>* jobs, std::vector<char>* ok);
|
||||
bool take(std::vector<TierJob>* jobs, std::vector<char>* ok,
|
||||
std::vector<RadEvent>* fences = nullptr);
|
||||
bool busy() const;
|
||||
|
||||
/* A read off disk. `tag` is the caller's (the request waiting on it); `fences` are waited on
|
||||
@@ -306,6 +322,7 @@ private:
|
||||
mutable std::mutex mu_;
|
||||
std::condition_variable cv_;
|
||||
std::vector<TierJob> work_, done_;
|
||||
std::vector<RadEvent> work_fences_, done_fences_;
|
||||
std::vector<char> ok_;
|
||||
size_t work_at_ = 0; /* the next write job; the thread's alone while has_work_ */
|
||||
bool has_work_ = false, has_done_ = false, stop_ = false;
|
||||
|
||||
@@ -2,12 +2,16 @@
|
||||
#include "wtab.h"
|
||||
|
||||
#include "device/device.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
int wtab_patch(const WtabPatch& p, RadStream s) {
|
||||
if (p.n == 0) return RAD_OK;
|
||||
/* After the stream's queued work, for the reason step_advance gives: a host stream is a queue
|
||||
* with a worker, and a write made ahead of it changes a table that work issued earlier reads. */
|
||||
if (device_is_host()) {
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
for (uint32_t i = 0; i < p.n; ++i) *p.dst[i] = p.val[i];
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@ struct WtabPatch {
|
||||
void* val[kWtabPatch] = {};
|
||||
};
|
||||
|
||||
/* Enqueue `p` on `s`. Under the host backend, whose streams run their work as it is issued and
|
||||
* whose device memory is host memory, the writes happen here. */
|
||||
/* Enqueue `p` on `s`. Under the host backend, whose device memory is host memory, the writes
|
||||
* happen here once `s` has run everything issued before them. */
|
||||
int wtab_patch(const WtabPatch& p, RadStream s);
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
+129
-42
@@ -83,9 +83,17 @@ std::pair<uint32_t, const char*> decode_utf8(const char* src) {
|
||||
|
||||
std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src,
|
||||
PartialUtf8 partial_start) {
|
||||
std::vector<uint32_t> cps;
|
||||
const PartialUtf8 p = decode_utf8(src, partial_start, &cps);
|
||||
return { std::move(cps), p };
|
||||
}
|
||||
|
||||
PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
|
||||
std::vector<uint32_t>* out) {
|
||||
static const int lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 2, 2, 3, 4 };
|
||||
const char* pos = src.c_str();
|
||||
std::vector<uint32_t> cps;
|
||||
std::vector<uint32_t>& cps = *out;
|
||||
cps.clear();
|
||||
cps.reserve(src.size() + 1);
|
||||
|
||||
uint32_t value = partial_start.value;
|
||||
@@ -95,7 +103,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
const uint8_t next_byte = (uint8_t)*pos;
|
||||
if ((next_byte >> 6) != 2) {
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ 0, -1 } };
|
||||
return PartialUtf8{ 0, -1 };
|
||||
}
|
||||
value = (value << 6) + (next_byte & 0x3F);
|
||||
++pos;
|
||||
@@ -110,7 +118,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
if (n_remain < 0) {
|
||||
cps.clear();
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ 0, n_remain } };
|
||||
return PartialUtf8{ 0, n_remain };
|
||||
}
|
||||
const uint8_t mask = (uint8_t)((1 << (7 - n_remain)) - 1);
|
||||
value = first_byte & mask;
|
||||
@@ -123,7 +131,7 @@ std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src
|
||||
if (n_remain == 0) cps.push_back(value);
|
||||
}
|
||||
cps.push_back(0);
|
||||
return { std::move(cps), PartialUtf8{ value, n_remain } };
|
||||
return PartialUtf8{ value, n_remain };
|
||||
}
|
||||
|
||||
} /* namespace gbnf */
|
||||
@@ -830,22 +838,73 @@ struct GbnfState {
|
||||
}
|
||||
};
|
||||
|
||||
/* A STATE AS fill_mask HOLDS IT, NOT COPIED: the stacks through pointers, in the order the key
|
||||
* sorts them into. It hashes and compares as the GbnfState it would become, so the cache is
|
||||
* probed without building a key -- a copy of every stack, per mask -- and one is built only for a
|
||||
* mask that is stored. */
|
||||
struct GbnfStateView {
|
||||
const std::vector<const GbnfStack*>* stacks;
|
||||
PartialUtf8 partial;
|
||||
bool allow_eog;
|
||||
int64_t words;
|
||||
};
|
||||
|
||||
struct GbnfStateHash {
|
||||
size_t operator()(const GbnfState& k) const {
|
||||
using is_transparent = void;
|
||||
|
||||
template <class Stacks, class Deref>
|
||||
static size_t hash(const Stacks& stacks, Deref deref, PartialUtf8 partial, bool allow_eog,
|
||||
int64_t words) {
|
||||
size_t h = 1469598103934665603ull;
|
||||
auto mix = [&h](size_t v) { h ^= v; h *= 1099511628211ull; };
|
||||
for (const GbnfStack& s : k.stacks) {
|
||||
for (const auto& x : stacks) {
|
||||
const GbnfStack& s = deref(x);
|
||||
mix(s.size());
|
||||
for (const GbnfElement* e : s) mix((size_t)e);
|
||||
}
|
||||
mix(k.partial.value);
|
||||
mix((size_t)(k.partial.n_remain + 1));
|
||||
mix(k.allow_eog ? 1u : 0u);
|
||||
mix((size_t)k.words);
|
||||
mix(partial.value);
|
||||
mix((size_t)(partial.n_remain + 1));
|
||||
mix(allow_eog ? 1u : 0u);
|
||||
mix((size_t)words);
|
||||
return h;
|
||||
}
|
||||
size_t operator()(const GbnfState& k) const {
|
||||
return hash(k.stacks, [](const GbnfStack& s) -> const GbnfStack& { return s; },
|
||||
k.partial, k.allow_eog, k.words);
|
||||
}
|
||||
size_t operator()(const GbnfStateView& k) const {
|
||||
return hash(*k.stacks, [](const GbnfStack* s) -> const GbnfStack& { return *s; },
|
||||
k.partial, k.allow_eog, k.words);
|
||||
}
|
||||
};
|
||||
|
||||
struct GbnfStateEq {
|
||||
using is_transparent = void;
|
||||
|
||||
bool operator()(const GbnfState& a, const GbnfState& b) const { return a == b; }
|
||||
bool operator()(const GbnfStateView& v, const GbnfState& k) const {
|
||||
if (k.allow_eog != v.allow_eog || k.words != v.words ||
|
||||
k.partial.value != v.partial.value || k.partial.n_remain != v.partial.n_remain ||
|
||||
k.stacks.size() != v.stacks->size())
|
||||
return false;
|
||||
for (size_t i = 0; i < k.stacks.size(); ++i)
|
||||
if (k.stacks[i] != *(*v.stacks)[i]) return false;
|
||||
return true;
|
||||
}
|
||||
bool operator()(const GbnfState& k, const GbnfStateView& v) const { return (*this)(v, k); }
|
||||
};
|
||||
|
||||
/* The key a view becomes, for storing. */
|
||||
static GbnfState state_of(const GbnfStateView& v) {
|
||||
GbnfState k;
|
||||
k.stacks.reserve(v.stacks->size());
|
||||
for (const GbnfStack* s : *v.stacks) k.stacks.push_back(*s);
|
||||
k.partial = v.partial;
|
||||
k.allow_eog = v.allow_eog;
|
||||
k.words = v.words;
|
||||
return k;
|
||||
}
|
||||
|
||||
struct GbnfProgram {
|
||||
GbnfRuleSet rules;
|
||||
GbnfStacks start; /* the root's alternates, advanced once */
|
||||
@@ -864,7 +923,7 @@ struct GbnfProgram {
|
||||
* speculative window revisiting a state the work again. */
|
||||
mutable std::mutex mu;
|
||||
struct Entry { std::vector<uint32_t> mask; uint64_t used = 0; };
|
||||
mutable std::unordered_map<GbnfState, Entry, GbnfStateHash> masks;
|
||||
mutable std::unordered_map<GbnfState, Entry, GbnfStateHash, GbnfStateEq> masks;
|
||||
mutable uint64_t clock = 0;
|
||||
|
||||
/* A tool-calling schema's working set is on the order of a hundred states; 512 is room for a
|
||||
@@ -873,7 +932,7 @@ struct GbnfProgram {
|
||||
* that was computed. */
|
||||
static constexpr size_t kMaxMasks = 512;
|
||||
|
||||
bool lookup(const GbnfState& k, uint32_t* dst, int64_t n_words) const {
|
||||
bool lookup(const GbnfStateView& k, uint32_t* dst, int64_t n_words) const {
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
auto it = masks.find(k);
|
||||
if (it == masks.end()) return false;
|
||||
@@ -1157,29 +1216,42 @@ int GbnfGrammar::accept_token_piece(int32_t token, const std::string& piece) {
|
||||
RAD_WARN("gbnf: token %d cannot be accepted: %s; the request cannot be continued",
|
||||
token, e.what());
|
||||
stacks_.clear();
|
||||
at_ = At{};
|
||||
return RAD_E_FULL;
|
||||
} catch (const std::bad_alloc&) {
|
||||
RAD_ERR("gbnf: out of memory accepting token %d; the request cannot be continued", token);
|
||||
stacks_.clear();
|
||||
at_ = At{};
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
}
|
||||
|
||||
int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece) {
|
||||
const auto decoded = decode_utf8(piece, partial_utf8_);
|
||||
const auto& cps = decoded.first;
|
||||
const PartialUtf8 partial = decode_utf8(piece, partial_utf8_, &cps_);
|
||||
const size_t n_cps = cps_.size() - 1; /* the terminating 0 is not a code point */
|
||||
|
||||
OpWork work;
|
||||
GbnfStacks new_stacks;
|
||||
SetBuild new_set(work);
|
||||
new_stacks.reserve(stacks_.size());
|
||||
|
||||
/* THE STACKS THAT MATCH CODE POINTS ARE ADVANCED TOGETHER, one code point at a time, as
|
||||
* accept_str does. Advancing each through the whole piece on its own gives the same set --
|
||||
* the union of the parts is the part of the union -- but when many stacks converge on one
|
||||
* continuation, as every alternative of a wide rule does once it matches, each of them
|
||||
* re-expands that continuation, and the token costs the square of the width. */
|
||||
GbnfStacks current;
|
||||
* re-expands that continuation, and the token costs the square of the width.
|
||||
*
|
||||
* AND THEY ARE ADVANCED THROUGH THE MASK PLAN'S AUTOMATON (plan_step), which holds each stack
|
||||
* set as a state with its successors memoised per interval of code points. The set is the
|
||||
* one accept_chr builds; what changes is that a state seen before -- the same free-text
|
||||
* value, token after token -- is a lookup per code point rather than every closure rebuilt,
|
||||
* allocated and de-duplicated again. The set comes back sorted, which nothing reads: the
|
||||
* mask cache sorts its key, and a mask is a union over the stacks.
|
||||
*
|
||||
* The new set is written over the one the previous token left (`spare_`) and the two are
|
||||
* swapped, so a set of the same shape, token after token, allocates nothing; and when the
|
||||
* automaton says the token left the set the state it was -- the steady state of a free-text
|
||||
* value -- the set is not touched at all. */
|
||||
current_.clear();
|
||||
for (const auto& stack : stacks_) {
|
||||
if (stack.empty()) continue;
|
||||
const GbnfElement* pos = stack.back();
|
||||
@@ -1190,19 +1262,37 @@ int GbnfGrammar::accept_token_piece_impl(int32_t token, const std::string& piece
|
||||
if (!is_end_of_sequence(pos + 1)) next.push_back(pos + 1);
|
||||
advance_stack(prog_->rules, next, new_stacks, new_set);
|
||||
} else {
|
||||
current.push_back(stack);
|
||||
current_.push_back(&stack);
|
||||
}
|
||||
}
|
||||
for (auto it = cps.begin(), end = cps.end() - 1; it != end && !current.empty(); ++it) {
|
||||
GbnfStacks next;
|
||||
SetBuild next_set(work);
|
||||
for (const auto& cs : current) accept_chr(prog_->rules, cs, *it, next, next_set);
|
||||
current = std::move(next);
|
||||
GbnfStacks& out = spare_;
|
||||
if (n_cps > 0 && !current_.empty()) {
|
||||
/* `at_` names a state only when every stack steps over code points, so with it known no
|
||||
* stack matched a token terminal above and the set is the stepped stacks alone. */
|
||||
gbnf::PlanState at{ at_.gen, at_.id };
|
||||
const bool same = gbnf::plan_step(*prog_->plan, current_, &at, cps_.data(), n_cps, &out,
|
||||
work);
|
||||
at_ = At{ at.gen, at.id };
|
||||
if (same) {
|
||||
partial_utf8_ = partial;
|
||||
return RAD_OK;
|
||||
}
|
||||
} else {
|
||||
out.resize(current_.size());
|
||||
for (size_t i = 0; i < current_.size(); ++i) out[i].assign(current_[i]->begin(),
|
||||
current_[i]->end());
|
||||
at_ = At{};
|
||||
}
|
||||
for (auto& s : current) new_set.insert(new_stacks, std::move(s));
|
||||
|
||||
stacks_ = std::move(new_stacks);
|
||||
partial_utf8_ = decoded.second;
|
||||
/* What a token terminal matched goes first, then the rest without the ones it already holds;
|
||||
* with nothing matched by token, `out` is the set as it stands -- a state of the automaton,
|
||||
* or a subset of the set before, and either way without duplicates. */
|
||||
if (!new_stacks.empty()) {
|
||||
for (auto& s : out) new_set.insert(new_stacks, std::move(s));
|
||||
out.swap(new_stacks);
|
||||
at_ = At{};
|
||||
}
|
||||
stacks_.swap(out);
|
||||
partial_utf8_ = partial;
|
||||
|
||||
if (stacks_.empty()) {
|
||||
/* NOT AN ERROR HERE, WHICH IS WHY IT LOGS AT DEBUG. This is reached as a matter of course
|
||||
@@ -1290,6 +1380,7 @@ int GbnfGrammar::accept_token(int32_t token) {
|
||||
int GbnfGrammar::accept_str(const std::string& piece) {
|
||||
const auto decoded = decode_utf8(piece, partial_utf8_);
|
||||
const auto& cps = decoded.first;
|
||||
at_ = At{};
|
||||
|
||||
try {
|
||||
OpWork work;
|
||||
@@ -1318,7 +1409,7 @@ int GbnfGrammar::accept_str(const std::string& piece) {
|
||||
|
||||
|
||||
void GbnfGrammar::push_state() {
|
||||
saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_ });
|
||||
saved_.push_back(Snapshot{ stacks_, partial_utf8_, awaiting_trigger_, scan_, recent_, at_ });
|
||||
}
|
||||
|
||||
int GbnfGrammar::rollback() {
|
||||
@@ -1332,21 +1423,11 @@ int GbnfGrammar::rollback() {
|
||||
awaiting_trigger_ = s.awaiting_trigger;
|
||||
scan_ = s.scan;
|
||||
recent_ = std::move(s.recent);
|
||||
at_ = s.at;
|
||||
saved_.pop_back();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The cache key for the state the machine is in right now. */
|
||||
GbnfState GbnfGrammar::state_key(bool allow_eog, int64_t n_words) const {
|
||||
GbnfState k;
|
||||
k.stacks = stacks_;
|
||||
k.partial = partial_utf8_;
|
||||
k.allow_eog = allow_eog;
|
||||
k.words = n_words;
|
||||
std::sort(k.stacks.begin(), k.stacks.end());
|
||||
return k;
|
||||
}
|
||||
|
||||
/* The mask for the current state, with no memo. */
|
||||
int GbnfGrammar::mask_compute(uint32_t* bitmask, int64_t n_words) const {
|
||||
std::fill(bitmask, bitmask + n_words, 0u);
|
||||
@@ -1391,8 +1472,14 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
* because a collision accepted on the hash alone would hand back a mask for a state the
|
||||
* sequence is not in and admit the wrong token set. The key sorts the stacks: two requests
|
||||
* that reach the same state by the same path produce the same order anyway, but the sort is
|
||||
* what makes that a guarantee rather than an observation. */
|
||||
const GbnfState key = state_key(complete(), n_words);
|
||||
* what makes that a guarantee rather than an observation. The probe sorts pointers to the
|
||||
* stacks, in storage of the calling thread's own, and copies them only to store. */
|
||||
thread_local std::vector<const GbnfStack*> sorted;
|
||||
sorted.clear();
|
||||
for (const GbnfStack& s : stacks_) sorted.push_back(&s);
|
||||
std::sort(sorted.begin(), sorted.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a < *b; });
|
||||
const GbnfStateView key{ &sorted, partial_utf8_, complete(), n_words };
|
||||
if (prog_->lookup(key, bitmask, n_words)) return RAD_OK;
|
||||
|
||||
prog_->computed.fetch_add(1, std::memory_order_relaxed);
|
||||
@@ -1400,7 +1487,7 @@ int GbnfGrammar::fill_mask(uint32_t* bitmask, int64_t n_words) const {
|
||||
if (st < 0) return st;
|
||||
|
||||
/* Store only a mask that stands: a dead state is not worth an entry and returns above. */
|
||||
prog_->store(key, bitmask, n_words);
|
||||
prog_->store(state_of(key), bitmask, n_words);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+24
-2
@@ -32,6 +32,11 @@
|
||||
* stacks that match code points are advanced together rather than one at a time, and a
|
||||
* large set is de-duplicated through an index. Each gives the same set as upstream; without
|
||||
* them, stacks that converge on one continuation re-expand it once each.
|
||||
* - Accepting a token steps the stacks that match code points through the mask plan's
|
||||
* stack-set automaton (gbnf_mask.cpp, plan_step) rather than through a closure per stack per
|
||||
* code point, and the grammar remembers which automaton state its stacks are. The set is the
|
||||
* one upstream's accept builds; the test oracle keeps upstream's accept and every accepted
|
||||
* token is held to it.
|
||||
* - The token mask is not upstream's candidate walk. It is served from a plan precomputed when
|
||||
* the grammar is compiled (gbnf_mask.cpp): per stack suffix, the tokens it admits whatever lies
|
||||
* below it, and a small trie of what depends on what does. Upstream's walk survives only as
|
||||
@@ -239,12 +244,23 @@ private:
|
||||
uint64_t start;
|
||||
};
|
||||
|
||||
/* The state of the mask plan's automaton `stacks_` is exactly, when it is one: which
|
||||
* automaton (`gen`) and which state in it, or an id of -1 when that is not known. It lets
|
||||
* accepting skip canonicalising the set, and skip rewriting it when a token leaves it where
|
||||
* it was. Everything that sets `stacks_` other than accepting through the automaton resets
|
||||
* it, or restores it with the stacks it describes. */
|
||||
struct At {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
};
|
||||
|
||||
struct Snapshot {
|
||||
GbnfStacks stacks;
|
||||
PartialUtf8 partial;
|
||||
bool awaiting_trigger = false;
|
||||
WordScanner::State scan;
|
||||
std::vector<Recent> recent;
|
||||
At at;
|
||||
};
|
||||
|
||||
const VocabView* vocab_ = nullptr;
|
||||
@@ -256,11 +272,10 @@ private:
|
||||
std::shared_ptr<const GbnfProgram> prog_;
|
||||
GbnfStacks stacks_;
|
||||
PartialUtf8 partial_utf8_{};
|
||||
At at_;
|
||||
|
||||
std::vector<Snapshot> saved_;
|
||||
|
||||
GbnfState state_key(bool allow_eog, int64_t n_words) const;
|
||||
|
||||
/* The mask itself, from the program's plan, with no memo. */
|
||||
int mask_compute(uint32_t* bitmask, int64_t n_words) const;
|
||||
|
||||
@@ -278,6 +293,13 @@ private:
|
||||
|
||||
int accept_token_piece(int32_t token, const std::string& piece);
|
||||
int accept_token_piece_impl(int32_t token, const std::string& piece);
|
||||
|
||||
/* Scratch for accepting, kept so a token in the steady state of a value allocates nothing:
|
||||
* the piece's code points, the stacks that step over them, and the set before the last one
|
||||
* accepted, whose storage the next one is written into. None of it is state. */
|
||||
std::vector<uint32_t> cps_;
|
||||
std::vector<const GbnfStack*> current_;
|
||||
GbnfStacks spare_;
|
||||
};
|
||||
|
||||
/* COMPILE A GRAMMAR, on the calling thread, into the program every GbnfGrammar::create for the
|
||||
|
||||
@@ -183,6 +183,10 @@ std::pair<uint32_t, const char*> decode_utf8(const char* src);
|
||||
std::pair<std::vector<uint32_t>, PartialUtf8> decode_utf8(const std::string& src,
|
||||
PartialUtf8 partial_start);
|
||||
|
||||
/* The same into `out`, whose capacity is reused; returns the carried state. */
|
||||
PartialUtf8 decode_utf8(const std::string& src, PartialUtf8 partial_start,
|
||||
std::vector<uint32_t>* out);
|
||||
|
||||
/* ============================================================ elements */
|
||||
|
||||
inline bool is_end_of_sequence(const GbnfElement* pos) {
|
||||
@@ -331,5 +335,30 @@ int plan_build(const GbnfRuleSet& rules, uint32_t root, const std::shared_ptr<co
|
||||
int plan_fill(const MaskPlan& plan, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
|
||||
uint32_t* bitmask, int64_t n_words);
|
||||
|
||||
/* STEP A STACK SET OVER CODE POINTS through the plan's automaton: `out` is the set accepting
|
||||
* cps[0..n) one at a time leaves -- what accept_chr over every stack, code point by code point,
|
||||
* builds -- sorted, without duplicates, written over what `out` held so its capacity is reused.
|
||||
* `stacks` need not be sorted and must not point into `out`.
|
||||
*
|
||||
* `at` IS THE STATE THE CALLER'S SET IS, when it knows: on entry, a state an earlier step on this
|
||||
* plan returned, which spares canonicalising the set, or an id of -1; on return, the state
|
||||
* reached, or an id of -1 when that state holds an empty stack or a token terminal on top -- a
|
||||
* set the caller does not step whole, so not one it can name next time. Valid only while the
|
||||
* automaton that issued it lives; `gen` says which one that was. Returns true when the state
|
||||
* reached is the one `at` named on entry: the caller's set already is it, and `out` is left
|
||||
* alone. That is the steady state of a free-text value.
|
||||
*
|
||||
* The automaton memoises each state's successor per
|
||||
* interval of code points, so a state seen before costs a lookup per code point where the stack
|
||||
* machinery would rebuild every closure; inside a free-text value the state is the same one
|
||||
* token after token. Throws GbnfLimit past the per-operation bounds. Thread-safe: it takes the
|
||||
* plan's lock. */
|
||||
struct PlanState {
|
||||
uint64_t gen = 0;
|
||||
int32_t id = -1;
|
||||
};
|
||||
bool plan_step(const MaskPlan& plan, const std::vector<const GbnfStack*>& stacks, PlanState* at,
|
||||
const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work);
|
||||
|
||||
} /* namespace gbnf */
|
||||
} /* namespace rad */
|
||||
+75
-11
@@ -909,6 +909,8 @@ struct MaskPlan {
|
||||
struct Group { int32_t key; std::vector<int32_t> ctx; };
|
||||
mutable std::vector<Group> groups;
|
||||
mutable GbnfStack ctx;
|
||||
mutable std::vector<const GbnfStack*> step_ptrs;
|
||||
mutable uint64_t dfa_gen = 0; /* which automaton `dfa` is; see plan_step */
|
||||
};
|
||||
|
||||
void MaskPlanDeleter::operator()(MaskPlan* p) const { delete p; }
|
||||
@@ -1841,23 +1843,85 @@ static void fill_resume(const MaskPlan& P, SetDfa& dfa, const GbnfStacks& stacks
|
||||
}
|
||||
}
|
||||
|
||||
/* The plan's automaton, for one operation charged to `work`. The caller holds P.mu.
|
||||
*
|
||||
* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused: every
|
||||
* state in it can be rediscovered, and a grammar whose stacks deepen with every token would
|
||||
* otherwise hold a new state per token for as long as it is cached. */
|
||||
static SetDfa& plan_dfa(const MaskPlan& P, OpWork& work) {
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; "
|
||||
"rebuilding it", P.dfa->n_states(), P.dfa->elems());
|
||||
P.dfa = std::make_unique<SetDfa>(P.rules);
|
||||
++P.dfa_gen;
|
||||
}
|
||||
P.dfa->begin(&work);
|
||||
return *P.dfa;
|
||||
}
|
||||
|
||||
bool plan_step(const MaskPlan& P, const std::vector<const GbnfStack*>& stacks, PlanState* at,
|
||||
const uint32_t* cps, size_t n, GbnfStacks* out, OpWork& work) {
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
/* The set as a state: the one the caller names, or canonicalised through pointers -- sorted,
|
||||
* without duplicates, and copied only if the automaton has not seen it. Charged as intern()
|
||||
* charges a sort. */
|
||||
const bool named = at->id >= 0 && at->gen == P.dfa_gen;
|
||||
int32_t s0;
|
||||
if (named) {
|
||||
s0 = at->id;
|
||||
work.add(stacks.size() + 1);
|
||||
} else {
|
||||
std::vector<const GbnfStack*>& ps = P.step_ptrs;
|
||||
ps.clear();
|
||||
size_t elems = 0;
|
||||
for (const GbnfStack* k : stacks) {
|
||||
ps.push_back(k);
|
||||
elems += k->size() + 1;
|
||||
}
|
||||
work.add(elems * (1 + (uint64_t)std::bit_width(ps.size())));
|
||||
std::sort(ps.begin(), ps.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a < *b; });
|
||||
ps.erase(std::unique(ps.begin(), ps.end(),
|
||||
[](const GbnfStack* a, const GbnfStack* b) { return *a == *b; }),
|
||||
ps.end());
|
||||
s0 = dfa.intern_ptrs(ps);
|
||||
}
|
||||
int32_t s = s0;
|
||||
|
||||
/* One successor per code point: the interval the code point falls in, then that interval's
|
||||
* successor, each built on first use and served from the memo after. */
|
||||
for (size_t k = 0; k < n && s >= 0; ++k) {
|
||||
const SetDfa::St& S = dfa.parted(s);
|
||||
const size_t i = (size_t)(std::upper_bound(S.lo.begin(), S.lo.end(), cps[k]) -
|
||||
S.lo.begin()) - 1;
|
||||
work.add(8);
|
||||
s = dfa.next(s, i);
|
||||
}
|
||||
if (named && s == s0) return true;
|
||||
at->gen = P.dfa_gen;
|
||||
if (s < 0) {
|
||||
at->id = -1;
|
||||
out->clear();
|
||||
return false;
|
||||
}
|
||||
const SetDfa::St& S = dfa.st(s);
|
||||
at->id = S.has_empty || !S.ttop.empty() ? -1 : s;
|
||||
out->resize(S.stacks.size());
|
||||
for (size_t i = 0; i < S.stacks.size(); ++i)
|
||||
(*out)[i].assign(S.stacks[i].begin(), S.stacks[i].end());
|
||||
return false;
|
||||
}
|
||||
|
||||
int plan_fill(const MaskPlan& P, const GbnfStacks& stacks, PartialUtf8 partial, bool allow_eog,
|
||||
uint32_t* bitmask, int64_t n_words) {
|
||||
std::lock_guard<std::mutex> lk(P.mu);
|
||||
std::fill(bitmask, bitmask + n_words, 0u);
|
||||
|
||||
OpWork work;
|
||||
/* The automaton is a memo, so past its bound it is dropped and rebuilt rather than refused:
|
||||
* every state in it can be rediscovered, and a grammar whose stacks deepen with every token
|
||||
* would otherwise hold a new state per token for as long as it is cached. */
|
||||
if (!P.dfa || P.dfa->elems() > kMaxDfaElems) {
|
||||
if (P.dfa)
|
||||
RAD_DEBUG("gbnf: the stack-set automaton holds %zu states, %zu stack elements; "
|
||||
"rebuilding it", P.dfa->n_states(), P.dfa->elems());
|
||||
P.dfa = std::make_unique<SetDfa>(P.rules);
|
||||
}
|
||||
SetDfa& dfa = *P.dfa;
|
||||
dfa.begin(&work);
|
||||
SetDfa& dfa = plan_dfa(P, work);
|
||||
|
||||
if (allow_eog)
|
||||
for (int32_t id : P.vx->eog) set_bit(bitmask, id);
|
||||
|
||||
+46
-1
@@ -382,7 +382,8 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(sp.typical_p < 1.0f, op_typical_, "sample_typical");
|
||||
if (!missing) missing = need(sp.xtc_probability > 0.0f, op_xtc_, "sample_xtc");
|
||||
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
|
||||
if (!missing) missing = need(!sp.grammar.empty(), op_mask_, "sample_mask");
|
||||
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
|
||||
"sample_mask");
|
||||
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
|
||||
if (missing) {
|
||||
if (why) *why = std::string("no kernel resolved for '") + missing + "'";
|
||||
@@ -456,6 +457,7 @@ int Sampler::begin_request(uint64_t req_id, const SamplingParams& sp, std::strin
|
||||
}
|
||||
}
|
||||
|
||||
st.think.start(sp.reasoning);
|
||||
seqs_[req_id] = std::move(st);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -591,8 +593,25 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
if (walk) gr->push_state();
|
||||
bool dead = false;
|
||||
|
||||
/* THE REASONING BUDGET, walked over the window as the grammar is. Position k is inside the
|
||||
* block or not according to the committed reply and drafts 0..k-1, which is the only
|
||||
* history under which its token is ever emitted; a draft that ends the block early is
|
||||
* accepted or rejected like any other. */
|
||||
const bool budget = st && sp.thinking_budget >= 0 && sp.reasoning.known();
|
||||
ReasoningCount think;
|
||||
if (budget) {
|
||||
if (st->think_seen > (size_t)n_out) {
|
||||
st->think.start(sp.reasoning);
|
||||
st->think_seen = 0;
|
||||
}
|
||||
for (; st->think_seen < (size_t)n_out; ++st->think_seen)
|
||||
st->think.push(sp.reasoning, r->output[st->think_seen]);
|
||||
think = st->think;
|
||||
}
|
||||
|
||||
for (int k = 0; k < n_pos; ++k) {
|
||||
if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true;
|
||||
if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]);
|
||||
const int64_t row = n_seq_++;
|
||||
|
||||
DeviceSampleParams& p = params_stage_[row];
|
||||
@@ -744,6 +763,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (budget && think.inside() && think.body >= sp.thinking_budget)
|
||||
force_close(p, row, sp.reasoning.close);
|
||||
}
|
||||
|
||||
/* Back to where the sequence actually is. The tokens it really accepted are applied by
|
||||
@@ -767,6 +789,29 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Sampler::force_close(DeviceSampleParams& p, int64_t row, int32_t close) {
|
||||
uint32_t* dst = mask_stage_ + row * mask_words_;
|
||||
const int64_t at = (int64_t)close - cfg_.vocab_off;
|
||||
const bool local = at >= 0 && at < cfg_.n_vocab_local;
|
||||
if (p.flags & RAD_SP_MASK) {
|
||||
/* The grammar's mask for this row. Under a split vocabulary the whole one is still in
|
||||
* mask_full_, and the close may be another rank's column. */
|
||||
const bool admitted =
|
||||
vocab_parallel()
|
||||
? close < (int64_t)mask_full_.size() * 32 &&
|
||||
(mask_full_[(size_t)(close >> 5)] >> (uint32_t)(close & 31)) & 1u
|
||||
: local && (dst[at >> 5] >> (uint32_t)(at & 31)) & 1u;
|
||||
if (!admitted) return;
|
||||
}
|
||||
/* ONE ADMISSIBLE TOKEN, on whichever rank holds its column. The others mask the whole row
|
||||
* out, which the candidate merge reads as no candidate from them (the grammar's own masks do
|
||||
* the same when the admissible set lives on one shard). */
|
||||
std::memset(dst, 0, (size_t)mask_words_ * 4);
|
||||
if (local) dst[at >> 5] |= 1u << (uint32_t)(at & 31);
|
||||
p.mask_row = (int32_t)row;
|
||||
p.flags |= RAD_SP_MASK;
|
||||
}
|
||||
|
||||
int Sampler::build_greedy(int64_t n) {
|
||||
if (!declared_) return RAD_E_STATE;
|
||||
if (n < 0) return RAD_E_INVAL;
|
||||
|
||||
@@ -218,8 +218,19 @@ private:
|
||||
struct SeqState {
|
||||
std::unique_ptr<GrammarBackend> grammar;
|
||||
DryBreakers dry;
|
||||
/* Where the reply stands against its reasoning block, over `output[0, think_seen)`.
|
||||
* Advanced by build_step over what each commit appended, so a step costs the tokens it
|
||||
* added and not the reply's length. Read only when the request carries a budget. */
|
||||
ReasoningCount think;
|
||||
size_t think_seen = 0;
|
||||
};
|
||||
|
||||
/* Mask staged row `row` to the reasoning block's close token: the budget is spent and the
|
||||
* sampled position is still inside the block. A grammar already masking the row keeps the
|
||||
* last word -- the close is forced only where the grammar admits it, and a row whose grammar
|
||||
* forbids it is left to the grammar and forced at a later position. */
|
||||
void force_close(DeviceSampleParams& p, int64_t row, int32_t close);
|
||||
|
||||
SamplerConfig cfg_{};
|
||||
const VocabView* vocab_ = nullptr;
|
||||
bool declared_ = false;
|
||||
|
||||
@@ -7,9 +7,13 @@ namespace rad {
|
||||
|
||||
int step_advance(const AdvanceArgs& a, RadStream s) {
|
||||
if (a.n_seq <= 0) return RAD_OK;
|
||||
/* THE HOST BACKEND RUNS A STREAM'S WORK AS IT IS ISSUED, and its device memory is host memory,
|
||||
* so the rows run here, now, in the order the stream would have run them. */
|
||||
/* THE HOST BACKEND'S STREAMS ARE QUEUES, each run by its own worker thread (device/host.cpp),
|
||||
* and its device memory is host memory. So the rows run here once the stream has finished
|
||||
* everything issued before this call, which is where the kernel would run in stream order.
|
||||
* Without the wait they can read a sampled token or a staged row whose copy is still queued,
|
||||
* and the next step then continues from the token before it. */
|
||||
if (device_is_host()) {
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -19,8 +19,9 @@
|
||||
* chunk, a history row for positions the host already knows -- with rows whose positions come from
|
||||
* the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded.
|
||||
*
|
||||
* The same code runs on the host backend, where device memory is host memory and a stream runs
|
||||
* its work as it is issued (advance_impl.h is shared by both builds).
|
||||
* The same code runs on the host backend, where device memory is host memory: the rows run on the
|
||||
* issuing thread once the stream has drained, which is their place in stream order
|
||||
* (advance_impl.h is shared by both builds).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
@@ -399,8 +399,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
if (max_ctx_ <= 0) max_ctx_ = cfg.max_tok;
|
||||
|
||||
/* The conv rolling window: width-1 entries of history plus room for the whole speculative
|
||||
* window, because a verify writes num_spec+1 conv outputs before anything is accepted, and a
|
||||
* rejection then reads back at the slot the last accepted token left (spec §10). */
|
||||
* window, and a rejection then reads back at the slot the last accepted token left (spec §10).
|
||||
* The state tensor's own extent (conv_window_entries), so the cursor derived from it stays
|
||||
* inside the slot the kernels index. */
|
||||
conv_window_.assign(prog.kv_groups.size(), 1);
|
||||
conv_group_ = -1;
|
||||
n_conv_ = 0;
|
||||
@@ -410,8 +411,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
++n_conv_;
|
||||
conv_group_ = n_conv_ == 1 ? (int32_t)i : -1; /* -1 once there is more than one */
|
||||
if (g.decl.conv_width > 0)
|
||||
conv_window_[i] = (int32_t)(g.decl.conv_width - 1 +
|
||||
(cfg.n_spec > 0 ? cfg.n_spec : 0) + 1);
|
||||
conv_window_[i] = (int32_t)conv_window_entries(g.decl, cfg.n_spec);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ derived buffers */
|
||||
|
||||
+56
-10
@@ -141,9 +141,16 @@ struct IPrefixCache {
|
||||
virtual Restore restore(const Request&) { return Restore::Done; }
|
||||
/* A step's admissions begin: what the last step's lookups handed out has been read. */
|
||||
virtual void begin_step() {}
|
||||
/* KEEP THIS WAITING REQUEST'S CHAIN WHERE IT IS until release(). Called when an admission is
|
||||
* refused after restore(): the request gives its hit back, and without the hold the chain it
|
||||
* just had restored would leave VRAM again before the next attempt restores it once more. */
|
||||
virtual void hold(const Request&) {}
|
||||
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
|
||||
virtual void release(const Request&) {}
|
||||
|
||||
virtual CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) const = 0;
|
||||
/* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
|
||||
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
|
||||
const HitCap* cap) const = 0;
|
||||
virtual const std::vector<int32_t>& cached_groups() const = 0;
|
||||
|
||||
/* PUBLISH what this sequence computed, so the next request sharing the prefix can adopt it.
|
||||
@@ -159,6 +166,11 @@ struct IPrefixCache {
|
||||
* blocks no live sequence needs, so this is what the scheduler tries BEFORE preempting a
|
||||
* running request: a cached prefix is a saving, a running request is work already done. */
|
||||
virtual int64_t evict(int64_t n_entries) = 0;
|
||||
/* FREE UP TO `n_blocks` FOR THE RESERVE, and nothing a later turn needs. Unlike evict(), which
|
||||
* answers a shortfall that cannot wait, this passes over an entry a live sequence still holds
|
||||
* (releasing it frees no block) and one whose only copy is in VRAM (it is the next turn's
|
||||
* context). Returns how many blocks went back to the pool. */
|
||||
virtual int64_t trim(int64_t n_blocks) = 0;
|
||||
|
||||
/* FORGET EVERYTHING, wherever it is. Not a loop over evict(): with idle tiers an eviction moves
|
||||
* an entry whose host copy has landed off the card and keeps it, so a reset built out of
|
||||
@@ -206,8 +218,9 @@ struct IPrefixCache {
|
||||
/* The state that reservation named is now IN its slot. A reservation is made when the chunk is
|
||||
* PLANNED and the state exists only after the step that computes it, so a lookup in between
|
||||
* would adopt a slot holding the previous tenant's history. Until this is called, the
|
||||
* reservation is a promise and lookup will not offer it. */
|
||||
virtual void commit_checkpoint(const Request& r, int64_t pos) = 0;
|
||||
* reservation is a promise and lookup will not offer it. `resume`: the deepest checkpoint this
|
||||
* prompt gets, the one its next turn resumes from (Scheduler::last_checkpoint). */
|
||||
virtual void commit_checkpoint(const Request& r, int64_t pos, bool resume) = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ block geometry */
|
||||
@@ -323,10 +336,10 @@ struct PCBinding final : IPrefixCache {
|
||||
mutable std::vector<MMContentKey> mm_;
|
||||
explicit PCBinding(PC* p) : m(p) {}
|
||||
|
||||
CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* out) const override {
|
||||
CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* out,
|
||||
const HitCap* cap) const override {
|
||||
media_keys(r, &mm_);
|
||||
return m->lookup(r.prompt, mm_, out);
|
||||
return m->lookup(r.prompt, mm_, out, cap);
|
||||
}
|
||||
|
||||
/* Installed by the engine when the idle tiers are on; empty otherwise. */
|
||||
@@ -335,6 +348,11 @@ struct PCBinding final : IPrefixCache {
|
||||
return restore_fn ? restore_fn(r) : Restore::Done;
|
||||
}
|
||||
void begin_step() override { m->begin_step(); }
|
||||
void hold(const Request& r) override {
|
||||
media_keys(r, &mm_);
|
||||
m->hold(r.id, r.prompt, mm_);
|
||||
}
|
||||
void release(const Request& r) override { m->release(r.id); }
|
||||
const std::vector<int32_t>& cached_groups() const override { return m->cached_groups(); }
|
||||
|
||||
/* prompt ++ output, for the same reason reserve_checkpoint chains both: the next turn of a
|
||||
@@ -352,7 +370,35 @@ struct PCBinding final : IPrefixCache {
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens);
|
||||
}
|
||||
int64_t evict(int64_t n) override { return m->evict_lru(n); }
|
||||
/* Installed by the engine when the idle tiers are on: lands every host copy that is waiting,
|
||||
* now, and says whether any landed. Called on the step thread under the scheduler's lock. */
|
||||
std::function<bool()> flush_fn;
|
||||
uint64_t lost_warned_ns_ = 0;
|
||||
/* PRESSURE TAKES WHAT CAN LEAVE VRAM AND STAY, FIRST. An entry whose host copy has landed is
|
||||
* dropped and kept (trim); a copy still on its way is landed and that entry dropped too; only
|
||||
* what the tiers then still cannot take -- an arena with no room and a disk that has not caught
|
||||
* up, or no tiers at all -- is erased, and an erase with the tiers on is said, because it is
|
||||
* a conversation a later turn will prefill again. */
|
||||
int64_t evict(int64_t n) override {
|
||||
int64_t k = m->trim(n);
|
||||
if (k < n && flush_fn && flush_fn()) k += m->trim(n - k);
|
||||
if (k >= n) return k;
|
||||
const int64_t before = m->stats().evictions;
|
||||
k += m->evict_lru(n - k);
|
||||
const int64_t lost = m->stats().evictions - before;
|
||||
if (lost > 0 && flush_fn) {
|
||||
const uint64_t now = rad_mono_ns();
|
||||
if (now - lost_warned_ns_ >= 60ull * 1000000000ull) {
|
||||
lost_warned_ns_ = now;
|
||||
RAD_WARN("prefix cache: %lld entries erased with no copy off the card -- the host "
|
||||
"tier had no room for them in time (--prefix-cache-host-mib, and the disk "
|
||||
"behind it); radiance:prefix_cache_evictions_total counts every one",
|
||||
(long long)lost);
|
||||
}
|
||||
}
|
||||
return k;
|
||||
}
|
||||
int64_t trim(int64_t n) override { return m->trim(n); }
|
||||
int64_t reset() override {
|
||||
const int64_t n = m->size();
|
||||
m->clear();
|
||||
@@ -378,8 +424,8 @@ struct PCBinding final : IPrefixCache {
|
||||
return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out);
|
||||
}
|
||||
|
||||
void commit_checkpoint(const Request& r, int64_t pos) override {
|
||||
m->commit_checkpoint(prefix_hash(r, pos));
|
||||
void commit_checkpoint(const Request& r, int64_t pos, bool resume) override {
|
||||
m->commit_checkpoint(prefix_hash(r, pos), resume);
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
@@ -75,6 +75,9 @@ struct SchedMetrics {
|
||||
/* Tokens one block covers, 0 for a stateful group. A pool measured in blocks cannot be
|
||||
* compared with a request measured in tokens, and every reader wants that comparison. */
|
||||
int64_t block_tokens = 0;
|
||||
/* A WINDOWED GROUP recycles its blocks below the window, so its carve says how far back a
|
||||
* sequence keeps context and nothing about how much context fits. */
|
||||
bool window = false;
|
||||
/* AND THE SAME GROUP IN BYTES, which is the measure that survives being added to the next
|
||||
* group's. Neither blocks nor tokens does: a stateful group has no token axis, and two
|
||||
* paged groups share one, so a token of context takes a slot in both and summing them
|
||||
@@ -120,6 +123,10 @@ struct SchedMetrics {
|
||||
/* Speculation (§10). */
|
||||
int64_t draft_tokens = 0;
|
||||
int64_t draft_accepted = 0;
|
||||
/* Prefix hits ended early so a windowed block drafter has context (Scheduler::draft_refill_),
|
||||
* and the reusable tokens they gave back to be recomputed. */
|
||||
int64_t draft_refills = 0;
|
||||
int64_t draft_refill_tokens = 0;
|
||||
float draft_acceptance = 0.0f;
|
||||
int draft_depth = 0; /* what the controller would choose right now */
|
||||
/* Per draft POSITION, so a cliff can be told from a decay: `reached` is how often every
|
||||
|
||||
+116
-29
@@ -87,6 +87,13 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
n_paged, pc->cached_groups().size(),
|
||||
hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole");
|
||||
}
|
||||
draft_refill_ = 0;
|
||||
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
|
||||
hit_holes_draft_) {
|
||||
draft_refill_ = prog.drafter.window;
|
||||
RAD_INFO("draft refill: a prefix hit ends %lld tokens before the prompt's end, so the "
|
||||
"drafter's window is recomputed", (long long)draft_refill_);
|
||||
}
|
||||
|
||||
DraftController::Params dp;
|
||||
dp.max_depth = cfg.n_spec;
|
||||
@@ -98,6 +105,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
ctx_limit_ = builder_.max_ctx();
|
||||
n_deferred_ = 0;
|
||||
closed_ = false;
|
||||
closed_status_ = RAD_E_STATE;
|
||||
|
||||
/* Everything the step path touches is reserved here. A vector that grows during a step is an
|
||||
* allocator call on the path this whole component exists to keep clear. */
|
||||
@@ -152,7 +160,7 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
* listening to -- and the refusal says why. */
|
||||
if (closed_) {
|
||||
RAD_WARN("request %llu refused: %s", (unsigned long long)r->id, closed_reason_);
|
||||
server::sink_fail(r->sink, RAD_E_STATE);
|
||||
server::sink_fail(r->sink, closed_status_, closed_reason_);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
@@ -256,7 +264,8 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
*
|
||||
* Appending to `Request::output` is not enough on its own: without a push the engine generates
|
||||
* correctly, step after step, while the HTTP thread waits in `Sink::wait()` until the client times
|
||||
* out. `sink_push`, `sink_finish` and `sink_prompt_stats` are called from here and nowhere else.
|
||||
* out. Every sink_* call -- push, finish, prompt stats, admission and drafts -- is made from this
|
||||
* file and nowhere else.
|
||||
*
|
||||
* A push returns false ONLY on overflow, and an overflowing sink has already failed the request --
|
||||
* a stream missing tokens in the middle is worse than one that stops and says so -- so the return
|
||||
@@ -278,7 +287,16 @@ static server::Finish finish_of(ReqState st, const std::string& reason) {
|
||||
* So a reserve is kept free. It is a fraction of the pool rather than a token count because the
|
||||
* thing being protected is the ability to admit ANY sequence, and how big that is depends on the
|
||||
* deployment. Trimming happens after a publish, off the step path, where the blocks were just
|
||||
* added -- not during admission, where the cost lands on a request that did nothing wrong. */
|
||||
* added -- not during admission, where the cost lands on a request that did nothing wrong.
|
||||
*
|
||||
* THE RESERVE IS NOT ALWAYS THE CACHE'S TO MEET. Live sequences count against it too, and once they
|
||||
* hold more than three quarters of the pool -- five or six agent sessions at 70K tokens each -- no
|
||||
* amount of trimming reaches it. Evicting in LRU order until it did would take everything on the
|
||||
* list: the entries running sequences share, which frees no block, and the conversation the
|
||||
* request being closed has just published, before its host copy can land -- so every agent's next
|
||||
* turn would re-prefill its whole context. The trim therefore asks the cache for the blocks it is
|
||||
* short and nothing more, and the cache gives only what frees a block without losing a
|
||||
* conversation (PrefixCache::trim). */
|
||||
|
||||
/* Drop every entry, in VRAM or off it -- IPrefixCache::reset, because an eviction does not
|
||||
* mean "forgotten" for an entry the idle tiers hold a copy of. */
|
||||
@@ -298,21 +316,16 @@ void Scheduler::trim_prefix_cache() {
|
||||
const int64_t total = kv_->total_blocks(g);
|
||||
if (total <= 0) return;
|
||||
const int64_t reserve = total / 4; /* a quarter of the pool stays free */
|
||||
for (int guard = 0; guard < 4096; ++guard) {
|
||||
/* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded
|
||||
* by the live mark, so a pool that has handed its unused top back reads as nearly full
|
||||
* however little anything holds -- and this loop would then drain the whole cache to
|
||||
* make room the pool can grow back into on demand. */
|
||||
if (total - kv_->held_blocks(g) >= reserve) return;
|
||||
if (pc_->evict(256) <= 0) return; /* nothing left to give back */
|
||||
}
|
||||
RAD_WARN("prefix cache: could not free %lld of %lld blocks in group %d after 4096 rounds; the "
|
||||
"pool is held by live sequences rather than by the cache",
|
||||
(long long)reserve, (long long)total, (int)g);
|
||||
/* FREE AGAINST THE CARVE, not free_blocks(). On an elastic pool free_blocks() is bounded by
|
||||
* the live mark, so a pool that has handed its unused top back reads as nearly full however
|
||||
* little anything holds -- and the trim would then drain the whole cache to make room the pool
|
||||
* can grow back into on demand. */
|
||||
const int64_t short_by = reserve - (total - kv_->held_blocks(g));
|
||||
if (short_by > 0) (void)pc_->trim(short_by);
|
||||
}
|
||||
|
||||
void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free,
|
||||
bool publish) {
|
||||
bool publish, int status, const char* why) {
|
||||
/* PUBLISH BEFORE FREEING. This is the only moment the sequence's whole prefix is both
|
||||
* computed and still owned, and it is what makes the cache a cache rather than a permanently
|
||||
* empty lookup: insert() takes its own KV references, so the blocks survive the free below.
|
||||
@@ -339,6 +352,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
s.pending_free = true;
|
||||
@@ -359,7 +374,8 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
/* Terminal, and idempotent on the sink's side: the first call wins, so a cancel racing a
|
||||
* natural stop does not produce two finish reasons. This is the last thing the producer does
|
||||
* to the sink, and the HTTP thread is waiting on exactly it. */
|
||||
server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason));
|
||||
if (st == ReqState::Failed && status < 0) server::sink_fail(s.req->sink, status, why);
|
||||
else server::sink_finish(s.req->sink, finish_of(st, s.req->finish_reason));
|
||||
}
|
||||
|
||||
int Scheduler::cancel(uint64_t id) {
|
||||
@@ -467,10 +483,11 @@ void Scheduler::release_deferred() {
|
||||
sweep_deferred();
|
||||
}
|
||||
|
||||
void Scheduler::shutdown(const char* reason) {
|
||||
void Scheduler::shutdown(const char* reason, int status) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
closed_ = true;
|
||||
closed_reason_ = reason ? reason : "the engine has stopped";
|
||||
closed_status_ = status < 0 ? status : RAD_E_STATE;
|
||||
/* Copied first: close_request erases from both queues. */
|
||||
std::vector<int32_t> live(running_);
|
||||
live.insert(live.end(), waiting_.begin(), waiting_.end());
|
||||
@@ -478,7 +495,7 @@ void Scheduler::shutdown(const char* reason) {
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req) continue;
|
||||
close_request(s, ReqState::Failed, closed_reason_, /*defer_free=*/false,
|
||||
/*publish=*/false);
|
||||
/*publish=*/false, closed_status_, closed_reason_);
|
||||
++m_.failed;
|
||||
completed_.push_back(s.req->id);
|
||||
}
|
||||
@@ -661,7 +678,22 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */
|
||||
if (n_computed + want > next) want = next - n_computed;
|
||||
if (n_computed + want == next && checkpoint_pos) *checkpoint_pos = next;
|
||||
if (n_computed + want == next) {
|
||||
if (checkpoint_pos) *checkpoint_pos = next;
|
||||
} else if (n_computed + want == n_target) {
|
||||
/* AND ONE AT THE TAIL OF THE PROMPT. The next turn of a conversation is this prompt
|
||||
* with more on the end, and it resumes from the deepest snapshot under its hit -- on
|
||||
* the interval alone that is up to an interval short of where this prompt ended, and
|
||||
* every one of those tokens is prefilled again on every turn. The last quantum
|
||||
* boundary is as far as a chunk may end short of the target, so the final chunk is
|
||||
* split there and the remainder, under a quantum, runs as the next step's chunk
|
||||
* (tail_checkpoint says where it is worth that step). */
|
||||
const int64_t tail = tail_checkpoint(n_target);
|
||||
if (tail > n_computed) {
|
||||
want = tail - n_computed;
|
||||
if (checkpoint_pos) *checkpoint_pos = tail;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (want < remaining) {
|
||||
@@ -684,6 +716,26 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg
|
||||
return want;
|
||||
}
|
||||
|
||||
/* THE DEEPEST CHECKPOINT A PROMPT OF `target` TOKENS GETS, asked of one at `pos`: no interval
|
||||
* boundary is left before the target and no tail checkpoint will follow (plan_chunk's rules). It
|
||||
* is the state the prompt's next turn resumes from. */
|
||||
bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const {
|
||||
if (!geo_.checkpoints()) return false;
|
||||
const int64_t I = geo_.checkpoint_interval;
|
||||
if ((pos / I + 1) * I <= target) return false;
|
||||
return tail_checkpoint(target) <= pos;
|
||||
}
|
||||
|
||||
/* THE TAIL CHECKPOINT OF A PROMPT OF `target` TOKENS, or -1: its last quantum boundary, past the
|
||||
* first interval -- a shorter prompt is cheap to prefill again -- and only where it buys a quarter
|
||||
* of an interval or more over the interval checkpoint below it, which is worth the extra step. */
|
||||
int64_t Scheduler::tail_checkpoint(int64_t target) const {
|
||||
const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum;
|
||||
if (I <= 0 || Q <= 0) return -1;
|
||||
const int64_t tail = target / Q * Q;
|
||||
return tail > I && tail - tail / I * I >= std::max<int64_t>(Q, I / 4) ? tail : -1;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ preemption */
|
||||
void Scheduler::preempt_back() {
|
||||
int32_t slot = running_.back();
|
||||
@@ -730,13 +782,29 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
s.hit_owed = true;
|
||||
}
|
||||
|
||||
/* WHAT NO HIT CAN CHANGE IS ASKED FIRST: a free sequence and a budget that can take a chunk.
|
||||
* A restore copies the whole context back, and an admission refused after it would give that
|
||||
* hit back and copy it again on the next attempt. */
|
||||
if (s.card < 0 && free_cards_.empty()) return RAD_E_FULL;
|
||||
if (budget < std::max<int64_t>(geo_.quantum, 1) && budget < s.seq_len() - r.n_computed)
|
||||
return RAD_E_FULL;
|
||||
|
||||
if (r.n_computed == 0 && cfg_.prefix_cache) {
|
||||
/* BEFORE the lookup, because the lookup stops at the first block the tiers hold -- an
|
||||
* honest shorter hit, but a shorter one. This is where a cold session gets its
|
||||
* context back instead of re-prefilling it: it costs a copy, and the alternative
|
||||
* costs a prefill. */
|
||||
if (pc_->restore(r) == IPrefixCache::Restore::Wait) return kAdmitWait;
|
||||
CacheHit h = pc_->lookup(r, &hit_blocks_);
|
||||
HitCap cap;
|
||||
if (draft_refill_ > 0) {
|
||||
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
|
||||
cap.max_give_back = 2 * draft_refill_;
|
||||
}
|
||||
const CacheHit h = pc_->lookup(r, &hit_blocks_, draft_refill_ > 0 ? &cap : nullptr);
|
||||
if (h.given_back > 0) {
|
||||
m_.draft_refill_tokens += h.given_back;
|
||||
++m_.draft_refills;
|
||||
}
|
||||
int32_t reuse = h.n_attn_tokens;
|
||||
if (geo_.checkpoints() && h.n_linear_tokens < reuse) {
|
||||
/* A hit landing between checkpoints reuses the attention blocks and must replay the
|
||||
@@ -766,9 +834,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
|
||||
/* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence
|
||||
* would skip computing those tokens and then attend to blocks it does not own. adopt()
|
||||
* takes a whole block multiple, which `reuse` is -- it is a multiple of the checkpoint
|
||||
* interval, which geometry.h made a multiple of the quantum, which is a multiple of the
|
||||
* block size. */
|
||||
* takes a whole block multiple, which `reuse` is -- a whole number of blocks, or a
|
||||
* checkpoint position, which is on the interval or on a quantum boundary at a prompt's tail
|
||||
* (plan_chunk), and geometry.h made both multiples of the block size. */
|
||||
if (reuse > 0) {
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
for (size_t i = 0; i < cg.size() && i < hit_blocks_.size(); ++i) {
|
||||
@@ -797,7 +865,17 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
else if (s.card < 0 && free_cards_.empty()) rc = RAD_E_FULL;
|
||||
else if (kv_->ensure(r.id, r.n_computed + want) < 0) rc = RAD_E_NOMEM;
|
||||
else {
|
||||
/* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running,
|
||||
* no other path would ever take blocks back from it, and the request would wait for good. */
|
||||
int rounds = 0;
|
||||
while (kv_->ensure(r.id, r.n_computed + want) < 0) {
|
||||
if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) {
|
||||
rc = RAD_E_NOMEM;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rc < 0) {
|
||||
/* A HIT THAT RESUMES FROM A SNAPSHOT IS NOT KEPT ACROSS A FAILED ATTEMPT. The slot is
|
||||
* named by id only, and until this request's first step restores from it nothing stops
|
||||
@@ -807,6 +885,8 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
* a lookup; the attention-only hit of a model with no recurrent state holds only
|
||||
* refcounted blocks and is kept. */
|
||||
if (s.ckpt_src >= 0) undo_hit(s);
|
||||
/* AND WHAT THE RESTORE BROUGHT BACK STAYS for the next attempt (IPrefixCache::hold). */
|
||||
if (cfg_.prefix_cache) pc_->hold(r);
|
||||
return rc;
|
||||
}
|
||||
|
||||
@@ -823,6 +903,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget) {
|
||||
if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); }
|
||||
r.state = ReqState::Running;
|
||||
s.running = true;
|
||||
server::sink_admitted(r.sink);
|
||||
s.sched_tokens = (int32_t)want;
|
||||
s.pending_ckpt = ckpt;
|
||||
++m_.admitted;
|
||||
@@ -944,7 +1025,8 @@ const RadBatch* Scheduler::step() {
|
||||
kv_->can_ever_fit(r.n_computed + want)
|
||||
? " and nothing lower-priority is left to preempt"
|
||||
: " at any occupancy");
|
||||
close_request(s, ReqState::Failed, "kv_exhausted");
|
||||
close_request(s, ReqState::Failed, "kv_exhausted", false, true, RAD_E_FULL,
|
||||
"the KV pool cannot hold it");
|
||||
++m_.failed;
|
||||
completed_.push_back(r.id);
|
||||
failed = true;
|
||||
@@ -1035,7 +1117,8 @@ const RadBatch* Scheduler::step() {
|
||||
RAD_WARN("request %llu failed: %lld tokens leave no room in a %lld-token context",
|
||||
(unsigned long long)s.req->id, (long long)s.seq_len(),
|
||||
(long long)ctx_limit_);
|
||||
close_request(s, ReqState::Failed, "context_length_exceeded");
|
||||
close_request(s, ReqState::Failed, "context_length_exceeded", false, true,
|
||||
RAD_E_FULL, "it leaves no room in the context");
|
||||
++m_.failed;
|
||||
completed_.push_back(s.req->id);
|
||||
continue;
|
||||
@@ -1406,8 +1489,10 @@ int Scheduler::commit(const StepResult& res) {
|
||||
* still holding the previous tenant's state. Stream ordering does the rest -- a later
|
||||
* restore is enqueued on the same stream behind this save, so validity does not have to
|
||||
* wait on the copy landing, only on it being issued. */
|
||||
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_)
|
||||
pc_->commit_checkpoint(r, (int64_t)e.ctx_len + e.ckpt_tok + 1);
|
||||
if (e.ckpt_slot >= 0 && e.ckpt_tok >= 0 && pc_) {
|
||||
const int64_t pos = (int64_t)e.ctx_len + e.ckpt_tok + 1;
|
||||
pc_->commit_checkpoint(r, pos, last_checkpoint(pos, s.seq_len()));
|
||||
}
|
||||
|
||||
if (e.is_prefill) {
|
||||
r.n_computed += e.n_tokens;
|
||||
@@ -1483,6 +1568,7 @@ int Scheduler::commit(const StepResult& res) {
|
||||
draft_.observe(e.n_spec, a);
|
||||
m_.draft_tokens += e.n_spec;
|
||||
m_.draft_accepted += a;
|
||||
server::sink_drafts(r.sink, e.n_spec, a);
|
||||
}
|
||||
}
|
||||
s.n_draft = 0;
|
||||
@@ -2081,7 +2167,7 @@ int32_t Scheduler::conv_window() const {
|
||||
int32_t W = 1;
|
||||
for (const KVGroupInfo& g : prog_->kv_groups)
|
||||
if (g.decl.kind == RAD_KV_CONV && g.decl.conv_width > 0)
|
||||
W = (int32_t)(g.decl.conv_width - 1 + (cfg_.n_spec > 0 ? cfg_.n_spec : 0) + 1);
|
||||
W = (int32_t)conv_window_entries(g.decl, cfg_.n_spec);
|
||||
return W;
|
||||
}
|
||||
|
||||
@@ -2164,6 +2250,7 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.kv[i].blocks_free = fr;
|
||||
m.kv[i].utilisation = tot > 0 ? (float)(1.0 - (double)fr / (double)tot) : 0.0f;
|
||||
m.kv[i].block_tokens = kv_->block_tokens(i);
|
||||
m.kv[i].window = gs[(size_t)i].decl.kind == RAD_KV_WINDOW;
|
||||
m.kv[i].bytes_total = kv_->pool_bytes(i);
|
||||
m.kv[i].bytes_used = kv_->pool_bytes_used(i);
|
||||
m.kv[i].bytes_carved = kv_->pool_bytes_carved(i);
|
||||
|
||||
+22
-4
@@ -238,8 +238,9 @@ public:
|
||||
|
||||
/* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is
|
||||
* failed with `reason` so its connection is answered rather than left waiting on a step that
|
||||
* will never come, and any request submitted afterwards is refused the same way. */
|
||||
void shutdown(const char* reason);
|
||||
* will never come, and any request submitted afterwards is refused the same way. `status` is
|
||||
* what stopped it, and what each of those requests reports. */
|
||||
void shutdown(const char* reason, int status = RAD_E_STATE);
|
||||
|
||||
/* The waiting queue in SERVICE order, by request id -- what the live view shows and what a
|
||||
* test asserts a preempted request re-entered at the front of. Returns how many were written. */
|
||||
@@ -444,6 +445,9 @@ public:
|
||||
|
||||
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
|
||||
* token budget, and the checkpoint position it will land on (-1 for none). */
|
||||
/* plan_chunk's checkpoint rules, asked after the fact (see the definitions). */
|
||||
bool last_checkpoint(int64_t pos, int64_t target) const;
|
||||
int64_t tail_checkpoint(int64_t target) const;
|
||||
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos) const;
|
||||
|
||||
@@ -468,6 +472,15 @@ private:
|
||||
* also skips on a block-size mismatch. A bound like this lives in exactly one place; a second
|
||||
* copy is free to drift out of step with the first. */
|
||||
bool hit_holes_draft_ = true;
|
||||
/* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is
|
||||
* declined until its window has slid past the hole, which on the follow-up turn of a chat --
|
||||
* the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window
|
||||
* before the end of the prompt (HitCap): the trunk recomputes that window, the drafter's
|
||||
* context pass covers it, and the sequence drafts from its first decode step. Output is
|
||||
* unchanged; only which tokens are recomputed moves. A hit whose nearest checkpoint below
|
||||
* that point would give back more than two windows is kept whole. The drafter's window, or 0
|
||||
* where no hit can leave such a hole. */
|
||||
int64_t draft_refill_ = 0;
|
||||
BatchBuilder builder_;
|
||||
DraftController draft_;
|
||||
|
||||
@@ -522,6 +535,7 @@ private:
|
||||
/* Set by shutdown(); add() refuses from then on. */
|
||||
bool closed_ = false;
|
||||
const char* closed_reason_ = "";
|
||||
int closed_status_ = RAD_E_STATE;
|
||||
|
||||
/* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch
|
||||
* builder sizes its block tables for it and the rotary tables are this long, so no position
|
||||
@@ -631,9 +645,13 @@ private:
|
||||
|
||||
/* lifecycle */
|
||||
/* `publish` is false only when the engine is shutting down: a sequence the device may have
|
||||
* left half-computed is not worth indexing, and nothing will ever hit it. */
|
||||
* left half-computed is not worth indexing, and nothing will ever hit it.
|
||||
*
|
||||
* A FAILED REQUEST SAYS WHAT FAILED: its sink is failed with `status` and `why`, which the
|
||||
* server puts in the error the client gets. RAD_OK leaves a sink that has failed already (an
|
||||
* overflow) as it is. */
|
||||
void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
|
||||
bool publish = true);
|
||||
bool publish = true, int status = RAD_OK, const char* why = nullptr);
|
||||
/* What reap() does once nothing points at the slot any more: give the blocks back, forget the
|
||||
* id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in
|
||||
* commit() for a request whose reap arrived while something still pointed at it. */
|
||||
|
||||
+18
-4
@@ -116,10 +116,11 @@ public:
|
||||
c.host_freed = s.host_freed; c.host_drops = s.host_drops; c.failures = s.failures;
|
||||
c.fetched = s.fetched; c.ck_fetched = s.ck_fetched;
|
||||
c.host_bytes = s.host_bytes; c.disk_bytes = s.disk_bytes;
|
||||
c.ck_to_host = s.ck_to_host; c.ck_to_disk = s.ck_to_disk; c.ck_promoted = s.ck_promoted;
|
||||
c.ck_drops = s.ck_drops; c.ck_starved = s.ck_starved;
|
||||
c.ck_to_disk = s.ck_to_disk; c.ck_drops = s.ck_drops;
|
||||
c.restores = s.restores; c.restore_ns = s.restore_ns;
|
||||
c.flushes = s.flushes; c.flush_ns = s.flush_ns;
|
||||
c.ck_bytes = tiers_->ckpt_bytes();
|
||||
c.ck_host_slots = tiers_->ckpt_arena().capacity();
|
||||
c.ck_host_slots = tiers_->ckpt_slots();
|
||||
c.ck_disk_slots = tiers_->ckpt_disk_slots();
|
||||
c.host_on = tiers_->host_on();
|
||||
c.disk_on = tiers_->disk_on();
|
||||
@@ -150,7 +151,6 @@ public:
|
||||
o.on_disk = s.on_disk;
|
||||
o.moving = s.moving;
|
||||
o.snapshots = s.snapshots;
|
||||
o.snap_device = s.snap_device;
|
||||
o.snap_host = s.snap_host;
|
||||
o.snap_disk = s.snap_disk;
|
||||
o.snap_bytes = s.snap_bytes;
|
||||
@@ -246,6 +246,9 @@ public:
|
||||
o.kv_bytes_total += m.kv[i].bytes_total;
|
||||
o.kv_bytes_used += m.kv[i].bytes_used;
|
||||
o.kv_bytes_carved += m.kv[i].bytes_carved;
|
||||
if (m.kv[i].block_tokens <= 0 || m.kv[i].window) continue;
|
||||
const int64_t t = m.kv[i].blocks_total * m.kv[i].block_tokens;
|
||||
if (o.kv_tokens_max == 0 || t < o.kv_tokens_max) o.kv_tokens_max = t;
|
||||
}
|
||||
|
||||
/* vLLM's gpu_prefix_cache_hit_rate is a single number and attention caching is what it
|
||||
@@ -265,6 +268,7 @@ public:
|
||||
o.draft_acceptance = m.draft_acceptance;
|
||||
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
|
||||
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
|
||||
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
|
||||
o.linear_hit_rate = m.linear_hit_rate;
|
||||
o.attn_cached_tokens = m.attn_cached_tokens;
|
||||
o.linear_cached_tokens = m.linear_cached_tokens;
|
||||
@@ -308,6 +312,7 @@ public:
|
||||
std::string push(int32_t t) override { return d_.push(t); }
|
||||
std::string flush() override { return d_.flush(); }
|
||||
bool stopped() const override { return d_.stopped(); }
|
||||
void defer_stops_until(const std::string& m) override { d_.defer_stops_until(m); }
|
||||
private:
|
||||
Detokenizer d_;
|
||||
};
|
||||
@@ -432,9 +437,14 @@ public:
|
||||
m.reasoning = r.reasoning;
|
||||
m.tool_calls.reserve(r.calls.size());
|
||||
for (const ReplyCall& c : r.calls) m.tool_calls.push_back({ std::string(), c.name, c.arguments });
|
||||
m.open_call = !r.calls.empty() && !r.calls.back().closed;
|
||||
return m;
|
||||
}
|
||||
|
||||
std::string content_with_open_call(std::string_view reply) const override {
|
||||
return s_->content_with_open_call(reply);
|
||||
}
|
||||
|
||||
private:
|
||||
void move_out(std::vector<ReplyDelta>* out) {
|
||||
if (!out) return;
|
||||
@@ -618,6 +628,10 @@ public:
|
||||
if (why) *why = perr;
|
||||
return ps;
|
||||
}
|
||||
const ReasoningMarkers rm = rp->reasoning();
|
||||
out->think_open = rm.open;
|
||||
out->think_close = rm.close;
|
||||
out->think_starts_open = rm.starts_open;
|
||||
out->parser = std::make_shared<ReplyParserBridge>(std::move(rp));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+25
-18
@@ -131,11 +131,12 @@ HttpResponse Server::handle_load(const HttpRequest&) {
|
||||
* finds out what this endpoint's token ids do to a subsequent /v1/completions. */
|
||||
HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
if (!deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"));
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"),
|
||||
req.peer);
|
||||
|
||||
json b;
|
||||
ApiError err;
|
||||
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err);
|
||||
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
|
||||
|
||||
const bool want_strs = get_bool_or(b, "return_token_strs", false);
|
||||
std::vector<int32_t> toks;
|
||||
@@ -143,15 +144,15 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
auto msgs = b.find("messages");
|
||||
auto prom = b.find("prompt");
|
||||
if (msgs != b.end() && prom != b.end())
|
||||
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"));
|
||||
return error_response(err_bad("prompt", "send `prompt` or `messages`, not both"), req.peer);
|
||||
|
||||
if (msgs != b.end()) {
|
||||
if (!deps_.chat)
|
||||
return error_response(err_not_implemented(
|
||||
"tokenising `messages` requires a chat template; this model was not loaded with "
|
||||
"one. Send `prompt` with the text you want tokenised"));
|
||||
"one. Send `prompt` with the text you want tokenised"), req.peer);
|
||||
if (!msgs->is_array() || msgs->empty())
|
||||
return error_response(err_bad("messages", "must be a non-empty array"));
|
||||
return error_response(err_bad("messages", "must be a non-empty array"), req.peer);
|
||||
|
||||
ChatRenderOptions opt;
|
||||
opt.add_generation_prompt = get_bool_or(b, "add_generation_prompt", true);
|
||||
@@ -170,16 +171,18 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
if (deps_.chat->apply(*msgs, tools, opt, &render, &why) < 0)
|
||||
return error_response(err_bad("messages", why.empty()
|
||||
? "the chat template could not render this request"
|
||||
: why));
|
||||
: why), req.peer);
|
||||
toks = deps_.tok->encode(render.prompt,
|
||||
get_bool_or(b, "add_special_tokens", false),
|
||||
/*parse_special=*/true);
|
||||
} else {
|
||||
if (prom == b.end() || !prom->is_string())
|
||||
return error_response(err_bad("prompt", "must be a string, or send `messages`"));
|
||||
return error_response(err_bad("prompt", "must be a string, or send `messages`"),
|
||||
req.peer);
|
||||
/* Encoded as /v1/completions encodes it, so the count is the count that endpoint sees. */
|
||||
toks = deps_.tok->encode(prom->get<std::string>(),
|
||||
get_bool_or(b, "add_special_tokens", true),
|
||||
/*parse_special=*/false);
|
||||
/*parse_special=*/true);
|
||||
}
|
||||
|
||||
json o;
|
||||
@@ -202,25 +205,26 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
* a token array would arrive as. The name is odd and it is the name clients read. */
|
||||
HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
if (!deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"));
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"),
|
||||
req.peer);
|
||||
|
||||
json b;
|
||||
ApiError err;
|
||||
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err);
|
||||
if (!parse_object(req.body, opt_.max_ctx, &b, &err)) return error_response(err, req.peer);
|
||||
|
||||
auto t = b.find("tokens");
|
||||
if (t == b.end() || !t->is_array())
|
||||
return error_response(err_bad("tokens", "must be an array of integers"));
|
||||
return error_response(err_bad("tokens", "must be an array of integers"), req.peer);
|
||||
|
||||
std::vector<int32_t> toks;
|
||||
toks.reserve(t->size());
|
||||
for (const auto& v : *t) {
|
||||
if (!v.is_number_integer())
|
||||
return error_response(err_bad("tokens", "must be an array of integers"));
|
||||
return error_response(err_bad("tokens", "must be an array of integers"), req.peer);
|
||||
int32_t id = 0;
|
||||
if (!token_id(v, &id))
|
||||
return error_response(err_bad("tokens", "a token id must be in [0, 2147483647], "
|
||||
"got " + v.dump()));
|
||||
"got " + v.dump()), req.peer);
|
||||
toks.push_back(id);
|
||||
}
|
||||
|
||||
@@ -235,9 +239,10 @@ HttpResponse Server::handle_detokenize(const HttpRequest& req) {
|
||||
* container carries a normalised vocabulary and not the JSON it was built from. So this answers
|
||||
* the questions that config is actually READ for -- how big is the vocabulary, which ids end a
|
||||
* generation, is a chat template available -- and says nothing it would have to invent. */
|
||||
HttpResponse Server::handle_tokenizer_info(const HttpRequest&) {
|
||||
HttpResponse Server::handle_tokenizer_info(const HttpRequest& req) {
|
||||
if (!deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"));
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"),
|
||||
req.peer);
|
||||
|
||||
const ITokenizer::VocabInfo v = deps_.tok->vocab_info();
|
||||
json o;
|
||||
@@ -320,6 +325,8 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
defs["max_tokens"] = srv["default_max_tokens"];
|
||||
defs["reasoning_effort"] = opt_.default_reasoning_effort.empty()
|
||||
? json(nullptr) : json(opt_.default_reasoning_effort);
|
||||
defs["thinking_token_budget"] = opt_.default_thinking_budget < 0
|
||||
? json(nullptr) : json(opt_.default_thinking_budget);
|
||||
json kw = json::object();
|
||||
for (const auto& [k, v] : opt_.default_template_kwargs) {
|
||||
json parsed = json::parse(v, nullptr, false);
|
||||
@@ -353,15 +360,15 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
/* 501 when there is no prefix cache to reset, and that is the point: vLLM answers 200 with an
|
||||
* empty body whether or not anything happened, so a benchmark that thinks it started cold has no
|
||||
* way to find out it did not. This says how many entries went. */
|
||||
HttpResponse Server::handle_reset_prefix_cache(const HttpRequest&) {
|
||||
HttpResponse Server::handle_reset_prefix_cache(const HttpRequest& req) {
|
||||
if (!deps_.sched)
|
||||
return error_response(err_not_implemented("the server has no engine attached"));
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
|
||||
const int64_t n = deps_.sched->reset_prefix_cache();
|
||||
if (n < 0)
|
||||
return error_response(err_not_implemented(
|
||||
"this engine has no prefix cache (started with --no-prefix-cache, or the model "
|
||||
"declares no cacheable KV group)"));
|
||||
"declares no cacheable KV group)"), req.peer);
|
||||
|
||||
json o;
|
||||
o["entries_dropped"] = n;
|
||||
|
||||
+25
-16
@@ -53,7 +53,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
if (deps_.sched) deps_.sched->sessions(&v, &occ);
|
||||
|
||||
int64_t dev = 0, host = 0, disk = 0, bytes = 0;
|
||||
int64_t sdev = 0, shost = 0, sdisk = 0;
|
||||
int64_t shost = 0, sdisk = 0;
|
||||
json a = json::array();
|
||||
for (const SessionStat& s : v) {
|
||||
json e;
|
||||
@@ -69,17 +69,16 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
e["moving"] = s.moving;
|
||||
/* THE RECURRENT HALF. On a hybrid model a session's attention blocks are only part of
|
||||
* what it needs back; the rest is its linear-state snapshots, which are a different size
|
||||
* of object in a different store. Counted where the BYTES are, so a snapshot that stayed
|
||||
* on the device while its blocks went to disk shows as exactly that. */
|
||||
* of object in a different store. Counted where the BYTES are: in the store in host
|
||||
* memory, or on disk alone. */
|
||||
e["snapshots"] = s.snapshots;
|
||||
e["snap_device"] = s.snap_device;
|
||||
e["snap_host"] = s.snap_host;
|
||||
e["snap_disk"] = s.snap_disk;
|
||||
e["snap_bytes"] = s.snap_bytes;
|
||||
e["resume_tokens"] = s.resume_tokens;
|
||||
a.push_back(std::move(e));
|
||||
dev += s.on_device; host += s.on_host; disk += s.on_disk;
|
||||
sdev += s.snap_device; shost += s.snap_host; sdisk += s.snap_disk;
|
||||
shost += s.snap_host; sdisk += s.snap_disk;
|
||||
bytes += s.bytes;
|
||||
}
|
||||
o["sessions"] = std::move(a);
|
||||
@@ -88,7 +87,7 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
* a server carrying long agent transcripts by more than an order of magnitude. The field
|
||||
* names say so rather than pretending the sums are totals. */
|
||||
o["blocks_sum_overlapping"] = { { "device", dev }, { "host", host }, { "disk", disk } };
|
||||
o["snapshots"] = { { "device", sdev }, { "host", shost }, { "disk", sdisk } };
|
||||
o["snapshots"] = { { "host", shost }, { "disk", sdisk } };
|
||||
o["bytes_sum_overlapping"] = bytes;
|
||||
const SchedMetrics sm = deps_.sched ? deps_.sched->metrics() : SchedMetrics{};
|
||||
/* AND THE ONE FIGURE THAT IS NOT A SUM, because a view about what the conversations cost has
|
||||
@@ -109,15 +108,14 @@ HttpResponse Server::handle_sessions(const HttpRequest&) {
|
||||
{ "fetched", c.fetched } };
|
||||
/* THE SNAPSHOT COUNTERS ARE NOT OPTIONAL ON A HYBRID MODEL, because a server that moves every
|
||||
* block it has and no snapshots at all looks identical in the block counters to one where
|
||||
* tiering works -- and the difference is a full linear replay on every restored session.
|
||||
* `starved` is the one to read when `to_host` stays at zero: it means the snapshot arena had
|
||||
* no room, which --prefix-cache-host-mib fixes. */
|
||||
o["snapshots_moved"] = { { "to_host", c.ck_to_host }, { "to_disk", c.ck_to_disk },
|
||||
{ "promoted", c.ck_promoted }, { "fetched", c.ck_fetched },
|
||||
{ "drops", c.ck_drops },
|
||||
{ "starved", c.ck_starved }, { "bytes_each", c.ck_bytes },
|
||||
* tiering works -- and the difference is a full linear replay on every restored session. */
|
||||
o["snapshots_moved"] = { { "to_disk", c.ck_to_disk }, { "fetched", c.ck_fetched },
|
||||
{ "drops", c.ck_drops }, { "bytes_each", c.ck_bytes },
|
||||
{ "host_slots", c.ck_host_slots },
|
||||
{ "disk_slots", c.ck_disk_slots } };
|
||||
/* THE STEP THREAD'S TIME ON THE TIERS: every request waits through it. */
|
||||
o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 },
|
||||
{ "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } };
|
||||
/* AND WHETHER ANY OF IT IS BEING READ. Moving a snapshot and restoring it proves the bytes
|
||||
* travelled; this is the number that says a lookup then SERVED one. A hybrid server can move
|
||||
* snapshots all day and still replay from token zero if the checkpoint the restore put back
|
||||
@@ -170,6 +168,7 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["kv_bytes_used"] = (double)m.kv_bytes_used;
|
||||
o["kv_bytes_total"] = (double)m.kv_bytes_total;
|
||||
o["kv_bytes_carved"] = (double)m.kv_bytes_carved;
|
||||
o["kv_tokens_max"] = m.kv_tokens_max;
|
||||
o["prefix_hit_rate"] = m.prefix_hit_rate;
|
||||
/* The leading indicator beside the lagging one: past ~75% kv utilisation the cache
|
||||
* begins dropping prefixes the next turn wants, and the hit rate only falls once
|
||||
@@ -361,10 +360,11 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
* This is the same walk (dump_graph_json shares every helper with the text one) served from the
|
||||
* process that is actually running, which is where the question is usually asked. Static after
|
||||
* declare, so it is rendered once and handed over. */
|
||||
HttpResponse Server::handle_graph(const HttpRequest&) {
|
||||
HttpResponse Server::handle_graph(const HttpRequest& req) {
|
||||
if (!opt_.graph_json)
|
||||
return error_response(err_not_implemented(
|
||||
"the server was not given a declared graph; this build has no engine attached"));
|
||||
"the server was not given a declared graph; this build has no engine attached"),
|
||||
req.peer);
|
||||
HttpResponse r;
|
||||
r.status = 200;
|
||||
r.body = opt_.graph_json();
|
||||
@@ -1483,6 +1483,10 @@ function meter(host, cls, title, idx, split) {
|
||||
const mKv = meter($("mem"), "meter", "KV cache", undefined, true);
|
||||
const mKvSub = el("div", "ksub");
|
||||
mKv.wrap.appendChild(mKvSub);
|
||||
/* AND HOW FAR IT CAN GROW: every block of the carve, the ones lent to the expert slab taken
|
||||
back -- which a request that needs them does, the same step. */
|
||||
const mKvMax = el("div", "ksub");
|
||||
mKv.wrap.appendChild(mKvMax);
|
||||
const mPc = meter($("mem"), "meter", "Prefix hits");
|
||||
/* `hot` is for a meter whose ceiling is a FAILURE -- KV utilisation near 100% preempts. A device
|
||||
* VRAM bar near 100% is the engine doing its job, so it passes false and stays neutral. */
|
||||
@@ -1728,7 +1732,8 @@ function update(s, dt) {
|
||||
of the pool is not among them: it is the bar in the memory panel, and repeating it here cost
|
||||
the line that says how much context the bytes are actually holding. */
|
||||
$("m-kvdet").textContent = s.kv_bytes_total > 0
|
||||
? "of " + hb(s.kv_bytes_total) + " · " + cnt3(s.kv_tokens_used) + " tok"
|
||||
? "of " + hb(s.kv_bytes_total) + " (max " + hb(s.kv_bytes_carved || 0) + ") · "
|
||||
+ cnt3(s.kv_tokens_used) + " tok"
|
||||
+ (kvGave > 0 ? " · " + hb(kvGave) + " lent to experts" : "")
|
||||
: "";
|
||||
setMetric("accept", 100 * s.draft_accept,
|
||||
@@ -1768,6 +1773,10 @@ function update(s, dt) {
|
||||
mKvSub.textContent = s.kv_tokens_used > 0
|
||||
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
|
||||
: "";
|
||||
mKvMax.textContent = s.kv_tokens_max > 0
|
||||
? "can grow to " + hb(s.kv_bytes_carved || 0) + " · " + cnt3(s.kv_tokens_max)
|
||||
+ " tok, with what the experts borrowed taken back"
|
||||
: "";
|
||||
mPc.v.textContent = pct(s.prefix_hit_rate); setBar(mPc.i, s.prefix_hit_rate, false);
|
||||
|
||||
/* ---- draft. The bar is the CONDITIONAL acceptance at that position; the reach row under the
|
||||
|
||||
@@ -367,6 +367,10 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
std::string got = hreq.get_header_value("Authorization");
|
||||
const std::string want = "Bearer " + api_key;
|
||||
if (got != want) {
|
||||
/* Said like every other refusal (Server::error_response), which this one never
|
||||
* reaches: the gate answers before the router does. */
|
||||
RAD_INFO("req refused from %s:%d -> 401 authentication_error: invalid api key",
|
||||
hreq.remote_addr.c_str(), hreq.remote_port);
|
||||
hres.status = 401;
|
||||
hres.set_content(error_body("authentication_error", "invalid api key"),
|
||||
"application/json");
|
||||
@@ -382,6 +386,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
req.method = hreq.method;
|
||||
req.path = hreq.path;
|
||||
req.body = std::move(body);
|
||||
req.peer = hreq.remote_addr + ":" + std::to_string(hreq.remote_port);
|
||||
for (auto& h : hreq.headers) req.headers[h.first] = h.second;
|
||||
for (auto& p : hreq.params) req.query[p.first] = p.second;
|
||||
req.closed = [&hreq] { return hreq.is_connection_closed(); };
|
||||
|
||||
@@ -31,6 +31,7 @@ struct HttpRequest {
|
||||
std::map<std::string, std::string, CiLess> headers;
|
||||
std::map<std::string, std::string> query;
|
||||
std::map<std::string, std::string> params; /* from a ":name" route segment */
|
||||
std::string peer; /* "addr:port"; empty in-process */
|
||||
|
||||
/* True once the peer is gone. The transport supplies it; in-process it is absent and the
|
||||
* waiting paths simply never see a drop. A dropped connection is a cancellation (spec §14),
|
||||
|
||||
+36
-11
@@ -67,6 +67,11 @@ struct SchedMetrics {
|
||||
int64_t kv_bytes_total = 0;
|
||||
/* What the pool was carved to address, which an elastic pool may not be holding. */
|
||||
int64_t kv_bytes_carved = 0;
|
||||
/* THE MOST CONTEXT THE CACHE CAN HOLD: every block of its carve, the ones lent to the expert
|
||||
* slab taken back. `kv_bytes_carved` is the same figure in bytes. The paged groups share one
|
||||
* token axis, so it is the smallest of theirs; a windowed group is left out, because its carve
|
||||
* bounds how far back a sequence keeps context rather than how much fits. */
|
||||
int64_t kv_tokens_max = 0;
|
||||
|
||||
double prefix_hit_rate = 0.0; /* 0..1 */
|
||||
/* Cumulative prefix-cache evictions. `prefix_hit_rate` falls only AFTER a prefix that
|
||||
@@ -97,6 +102,9 @@ struct SchedMetrics {
|
||||
/* The exact pair the ratio is computed from, for the same reason. */
|
||||
int64_t draft_tokens = 0;
|
||||
int64_t draft_accepted = 0;
|
||||
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
|
||||
int64_t draft_refills = 0;
|
||||
int64_t draft_refill_tokens = 0;
|
||||
/* THE PER-POSITION DRAFT HAZARD. `draft_acceptance` above is pooled over the whole window and
|
||||
* cannot distinguish a drafter that decays with depth from one whose later rounds are broken:
|
||||
* both read as one small number. These carry the conditional rate at each position -- of the
|
||||
@@ -157,7 +165,7 @@ struct SessionStat {
|
||||
* back and re-run every recurrent layer over its whole transcript -- which the hit rate will
|
||||
* report as a hit. Zero everywhere on a model that has no recurrent state. */
|
||||
int64_t snapshots = 0;
|
||||
int64_t snap_device = 0, snap_host = 0, snap_disk = 0;
|
||||
int64_t snap_host = 0, snap_disk = 0; /* in the store; only on disk */
|
||||
int64_t snap_bytes = 0;
|
||||
/* The prefix a return skips: the deepest snapshot's position (IdleTiers::SessionInfo). */
|
||||
int64_t resume_tokens = 0;
|
||||
@@ -264,11 +272,12 @@ public:
|
||||
int64_t fetched = 0, ck_fetched = 0;
|
||||
int64_t host_bytes = 0, disk_bytes = 0;
|
||||
/* THE LINEAR HALF, MOVED. Separate counters because a hybrid server can move every block
|
||||
* it has and no snapshots at all -- the arena too small, the device slots contended --
|
||||
* and no block counter can tell that apart from tiering working. */
|
||||
int64_t ck_to_host = 0, ck_to_disk = 0, ck_promoted = 0, ck_drops = 0, ck_starved = 0;
|
||||
* it has and no snapshots at all, and no block counter can tell that apart from tiering
|
||||
* working. `ck_drops` is snapshots whose only copy was lost. */
|
||||
int64_t ck_to_disk = 0, ck_drops = 0;
|
||||
int64_t ck_bytes = 0; /* one snapshot; 0 on a model with no recurrent state */
|
||||
int64_t ck_host_slots = 0, ck_disk_slots = 0;
|
||||
int64_t ck_host_slots = 0, ck_disk_slots = 0; /* the store's; the disk store's */
|
||||
int64_t restores = 0, restore_ns = 0, flushes = 0, flush_ns = 0; /* IdleTiers::Stats */
|
||||
/* WHETHER ANYTHING CAN MOVE AT ALL, which no counter above can answer: a tier that is on
|
||||
* and has had nothing to do reads the same as one that was never given a size, and the
|
||||
* two call for opposite responses from whoever is looking. */
|
||||
@@ -293,18 +302,21 @@ public:
|
||||
* search text that can no longer contain what it is searching for, and the generation would
|
||||
* run to max_tokens. Default false, for a decoder that leaves stop handling to us. */
|
||||
virtual bool stopped() const { return false; }
|
||||
/* Match the stop strings only after `marker` has been generated (core/text Detokenizer::
|
||||
* defer_stops_until): the reply starts inside its reasoning block. */
|
||||
virtual void defer_stops_until(const std::string& /*marker*/) {}
|
||||
};
|
||||
|
||||
class ITokenizer {
|
||||
public:
|
||||
virtual ~ITokenizer() = default;
|
||||
|
||||
/* `parse_special` is a security parameter, not a convenience one, and it is why this takes
|
||||
* three arguments rather than two. A rendered chat template contains control tokens that must
|
||||
* be recognised as themselves; raw user content must NOT be, because otherwise a user who
|
||||
* types "<|im_start|>system" reaches the system role. The server passes true for the one and
|
||||
* false for the other, and there is no default because a default is how the wrong one gets
|
||||
* picked silently. */
|
||||
/* `parse_special` decides whether a control token spelled out in the text is that token or
|
||||
* its characters, and there is no default because a default is how the wrong one gets picked
|
||||
* silently. Text the server is sent as a whole prompt is parsed: a rendered chat template
|
||||
* carries the control tokens that frame its turns, and a raw /v1/completions prompt is the
|
||||
* client's own rendering of the same, as vLLM and llama.cpp read it. Text that must reach the
|
||||
* model as characters is encoded with false. */
|
||||
virtual std::vector<int32_t> encode(const std::string& text, bool add_special,
|
||||
bool parse_special) const = 0;
|
||||
virtual std::string decode(const std::vector<int32_t>& toks) const = 0;
|
||||
@@ -391,6 +403,13 @@ struct ChatRender {
|
||||
|
||||
/* The tokens that parser must be able to SEE. See ITokenizer::detokenizer. */
|
||||
std::vector<std::string> preserved_tokens;
|
||||
|
||||
/* THE REASONING BLOCK THIS RENDER LEAVES THE REPLY FACING, as the parser reads it: the
|
||||
* markers with their optional whitespace trimmed, and whether the reply starts inside the
|
||||
* block. Empty `think_close` is a model with no reasoning block. The server turns these into
|
||||
* token ids (ReasoningSpan) to count the block and to hold a budget on it. */
|
||||
std::string think_open, think_close;
|
||||
bool think_starts_open = false;
|
||||
};
|
||||
|
||||
class IChatTemplate {
|
||||
@@ -423,6 +442,8 @@ struct ParsedMessage {
|
||||
std::string content;
|
||||
std::string reasoning; /* "" unless the template supports reasoning */
|
||||
std::vector<ToolCall> tool_calls;
|
||||
/* The reply ended inside its last call: that call never closed, and is no call to run. */
|
||||
bool open_call = false;
|
||||
};
|
||||
|
||||
/* One increment of a reply that is being read as it is generated. What has been delivered is
|
||||
@@ -451,6 +472,10 @@ public:
|
||||
virtual void finish(std::vector<ReplyDelta>* out) = 0;
|
||||
/* The whole reply, once finish() has run. */
|
||||
virtual ParsedMessage message() const = 0;
|
||||
/* Once finish() has run: the content with an open last call (ParsedMessage::open_call) read
|
||||
* as the text it was written as -- the content before the call, then the call's own bytes
|
||||
* from `reply`, the whole text fed. The content alone when no call is open. */
|
||||
virtual std::string content_with_open_call(std::string_view reply) const = 0;
|
||||
};
|
||||
|
||||
/* A request's reply format. Each choice opens its own reader, and a request that sent no tools
|
||||
|
||||
@@ -174,5 +174,63 @@ size_t json_stable_prefix(std::string_view s) {
|
||||
return n;
|
||||
}
|
||||
|
||||
bool json_quote_append(std::string& out, std::string_view s) {
|
||||
static const char kHex[] = "0123456789abcdef";
|
||||
const size_t mark = out.size();
|
||||
out.reserve(mark + s.size() + 2);
|
||||
out.push_back('"');
|
||||
const unsigned char* p = (const unsigned char*)s.data();
|
||||
const unsigned char* e = p + s.size();
|
||||
const unsigned char* run = p; /* [run, p) is verified and goes out as it is */
|
||||
while (p < e) {
|
||||
const unsigned char c = *p;
|
||||
if (c >= 0x80) {
|
||||
/* Length, and the range the SECOND byte is restricted to, which is what rejects
|
||||
* overlong forms, surrogates and anything past U+10FFFF without decoding. */
|
||||
size_t len;
|
||||
unsigned char lo = 0x80, hi = 0xBF;
|
||||
if (c >= 0xC2 && c <= 0xDF) len = 2;
|
||||
else if (c == 0xE0) { len = 3; lo = 0xA0; }
|
||||
else if (c >= 0xE1 && c <= 0xEC) len = 3;
|
||||
else if (c == 0xED) { len = 3; hi = 0x9F; }
|
||||
else if (c >= 0xEE && c <= 0xEF) len = 3;
|
||||
else if (c == 0xF0) { len = 4; lo = 0x90; }
|
||||
else if (c >= 0xF1 && c <= 0xF3) len = 4;
|
||||
else if (c == 0xF4) { len = 4; hi = 0x8F; }
|
||||
else len = 0;
|
||||
bool ok = len != 0 && (size_t)(e - p) >= len && p[1] >= lo && p[1] <= hi;
|
||||
for (size_t k = 2; ok && k < len; ++k) ok = p[k] >= 0x80 && p[k] <= 0xBF;
|
||||
if (!ok) {
|
||||
out.resize(mark);
|
||||
return false;
|
||||
}
|
||||
p += len;
|
||||
continue;
|
||||
}
|
||||
if (c >= 0x20 && c != '"' && c != '\\') {
|
||||
++p;
|
||||
continue;
|
||||
}
|
||||
out.append((const char*)run, (size_t)(p - run));
|
||||
switch (c) {
|
||||
case '"': out += "\\\""; break;
|
||||
case '\\': out += "\\\\"; break;
|
||||
case '\b': out += "\\b"; break;
|
||||
case '\t': out += "\\t"; break;
|
||||
case '\n': out += "\\n"; break;
|
||||
case '\f': out += "\\f"; break;
|
||||
case '\r': out += "\\r"; break;
|
||||
default: {
|
||||
const char u[6] = { '\\', 'u', '0', '0', kHex[c >> 4], kHex[c & 15] };
|
||||
out.append(u, 6);
|
||||
}
|
||||
}
|
||||
run = ++p;
|
||||
}
|
||||
out.append((const char*)run, (size_t)(p - run));
|
||||
out.push_back('"');
|
||||
return true;
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -12,11 +12,15 @@
|
||||
* boundary: cutting a multi-byte code point in half turns one delta into mojibake and the
|
||||
* next into a decode error.
|
||||
*
|
||||
* And one way to write it: `json_quote_append`, a string literal exactly as nlohmann writes one,
|
||||
* for the chunks that carry a delta.
|
||||
*
|
||||
* This is a scanner, not a parser: it allocates nothing and builds no DOM.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
|
||||
namespace rad {
|
||||
@@ -36,5 +40,15 @@ size_t utf8_trunc(std::string_view s);
|
||||
* escape, and the class of bug that produces is unbisectable from the server side. */
|
||||
size_t json_stable_prefix(std::string_view s);
|
||||
|
||||
/* Append `s` to `out` as a JSON string literal, quotes included, byte for byte as nlohmann's
|
||||
* dump() writes one: `\b \t \n \f \r \" \\` as two characters, every other control character
|
||||
* as `\u00xx` in lowercase hex, and everything else -- DEL and non-ASCII included -- as itself.
|
||||
* Returns false, with `out` as it was, when `s` is not well-formed UTF-8 (overlong forms,
|
||||
* surrogates and code points past U+10FFFF included), which nlohmann refuses rather than writes.
|
||||
*
|
||||
* A streamed chunk is written with this around a fixed frame instead of through a DOM: building
|
||||
* and dumping a tree per token cost more than every other part of the token's host work. */
|
||||
bool json_quote_append(std::string& out, std::string_view s);
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
@@ -130,6 +130,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
g_waiting_.set((double)m.waiting);
|
||||
g_preempted_.set((double)m.preempted);
|
||||
g_kv_util_.set(m.kv_util);
|
||||
g_kv_max_tokens_.set((double)m.kv_tokens_max);
|
||||
g_kv_max_bytes_.set((double)m.kv_bytes_carved);
|
||||
g_prefix_hit_.set(m.prefix_hit_rate);
|
||||
g_prefill_tps_.set(m.prefill_tps);
|
||||
g_decode_tps_.set(m.decode_tps);
|
||||
@@ -158,6 +160,9 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_decode_tokens_.inc(std::max(0.0, (double)m.decode_tokens - c_decode_tokens_.get()));
|
||||
c_draft_tokens_.inc(std::max(0.0, (double)m.draft_tokens - c_draft_tokens_.get()));
|
||||
c_draft_accepted_.inc(std::max(0.0, (double)m.draft_accepted - c_draft_accepted_.get()));
|
||||
c_draft_refills_.inc(std::max(0.0, (double)m.draft_refills - c_draft_refills_.get()));
|
||||
c_draft_refill_tokens_.inc(
|
||||
std::max(0.0, (double)m.draft_refill_tokens - c_draft_refill_tokens_.get()));
|
||||
c_attn_cached_.inc(std::max(0.0, (double)m.attn_cached_tokens - c_attn_cached_.get()));
|
||||
c_linear_cached_.inc(std::max(0.0, (double)m.linear_cached_tokens - c_linear_cached_.get()));
|
||||
c_checkpoints_.inc(std::max(0.0, (double)m.checkpoints_written - c_checkpoints_.get()));
|
||||
@@ -239,6 +244,12 @@ std::string Metrics::render() const {
|
||||
"GPU KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
|
||||
w.gauge("vllm:kv_cache_usage_perc",
|
||||
"KV-cache usage. 1 means 100 percent usage.", L, g_kv_util_.get());
|
||||
w.gauge("radiance:kv_cache_max_tokens",
|
||||
"Tokens of context the KV cache holds with every block it lends the experts taken "
|
||||
"back.", L, g_kv_max_tokens_.get());
|
||||
w.gauge("radiance:kv_cache_max_bytes",
|
||||
"VRAM the KV cache holds with every block it lends the experts taken back, one card.",
|
||||
L, g_kv_max_bytes_.get());
|
||||
w.gauge("vllm:gpu_prefix_cache_hit_rate",
|
||||
"GPU prefix cache block hit rate.", L, g_prefix_hit_.get());
|
||||
|
||||
@@ -337,6 +348,12 @@ std::string Metrics::render() const {
|
||||
w.counter("radiance:draft_accepted_total",
|
||||
"Speculative tokens accepted; the pair the acceptance ratio is computed from.",
|
||||
L, c_draft_accepted_.get());
|
||||
w.counter("radiance:draft_refills_total",
|
||||
"Prefix hits ended a drafter window early so a windowed block drafter has context.",
|
||||
L, c_draft_refills_.get());
|
||||
w.counter("radiance:draft_refill_tokens_total",
|
||||
"Cached prompt tokens those hits gave back to be recomputed.",
|
||||
L, c_draft_refill_tokens_.get());
|
||||
|
||||
/* PREFIX CACHING, DECOUPLED (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the ATTENTION one,
|
||||
* because that is what vLLM's single number has always meant. The linear side hits at a
|
||||
|
||||
@@ -112,6 +112,7 @@ private:
|
||||
std::string labels_; /* {model_name="...",engine="0"} */
|
||||
|
||||
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
|
||||
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
|
||||
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
|
||||
Gauge queue_depth_;
|
||||
/* The per-position draft hazard, kept as plain gauges because that is what it is: a
|
||||
@@ -143,6 +144,7 @@ private:
|
||||
* answers "how much between these two scrapes", and only the second survives a comparison
|
||||
* between two runs that settled into different mixes. */
|
||||
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
|
||||
Counter c_draft_refills_, c_draft_refill_tokens_;
|
||||
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
|
||||
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
|
||||
Gauge g_linear_hit_;
|
||||
|
||||
+228
-44
@@ -203,6 +203,7 @@ const char* kAcceptedChat[] = {
|
||||
"messages", "tools", "tool_choice", "response_format", "top_logprobs",
|
||||
"parallel_tool_calls", "add_generation_prompt", "max_completion_tokens",
|
||||
"chat_template_kwargs", "reasoning_effort", "enable_thinking", "preserve_thinking",
|
||||
"thinking_token_budget", "thinking_budget",
|
||||
};
|
||||
|
||||
const char* kAcceptedCompletion[] = { "prompt", "echo" };
|
||||
@@ -1157,6 +1158,74 @@ static int clamp_max_tokens(size_t n_prompt, const OaiLimits& lim, const char* f
|
||||
|
||||
/* ================================================================== chat */
|
||||
|
||||
/* THE REASONING BLOCK BY TOKEN ID, and the budget on it.
|
||||
*
|
||||
* The render names the block's markers as text; the engine counts and closes it by token, so
|
||||
* the markers are encoded here, once per request. A marker that is not one token leaves the span
|
||||
* unknown: the reply's reasoning is still split out, but it is not counted and cannot be closed
|
||||
* by forcing a token. The opener matters only to a reply that must open its own block.
|
||||
*
|
||||
* `thinking_token_budget` is vLLM's name for the field and `thinking_budget` Qwen's API's; both
|
||||
* are read, as max_tokens and max_completion_tokens are. A budget the span cannot hold is a 400
|
||||
* naming why -- accepting it and generating unbounded reasoning is the outcome this file's
|
||||
* header forbids. The deployment's default applies only where it can be held: a reply whose
|
||||
* block cannot be counted gets none, as it would on a model with no reasoning block at all. */
|
||||
static int parse_thinking_budget(const json& b, const OaiDeps& d, const OaiLimits& lim,
|
||||
const ChatRender& render, SamplingParams* sp, ApiError* err) {
|
||||
ReasoningSpan span;
|
||||
size_t n_close = 0, n_open = 0;
|
||||
if (!render.think_close.empty() && d.tok) {
|
||||
const std::vector<int32_t> c = d.tok->encode(render.think_close, false, true);
|
||||
std::vector<int32_t> o;
|
||||
if (!render.think_open.empty()) o = d.tok->encode(render.think_open, false, true);
|
||||
n_close = c.size();
|
||||
n_open = o.size();
|
||||
if (c.size() == 1 && (render.think_starts_open || o.size() == 1)) {
|
||||
span.close = c[0];
|
||||
span.open = o.size() == 1 ? o[0] : -1;
|
||||
span.starts_open = render.think_starts_open;
|
||||
}
|
||||
}
|
||||
sp->reasoning = span;
|
||||
|
||||
int64_t budget = -1;
|
||||
const char* named = nullptr;
|
||||
for (const char* k : { "thinking_token_budget", "thinking_budget" }) {
|
||||
auto it = b.find(k);
|
||||
if (it == b.end() || it->is_null()) continue;
|
||||
int64_t v = 0;
|
||||
if (!get_int(b, k, &v, err)) return RAD_E_INVAL;
|
||||
if (v < 0) { *err = err_bad(k, "must be >= 0"); return RAD_E_INVAL; }
|
||||
if (named && v != budget) {
|
||||
*err = err_bad(k, std::string("disagrees with ") + named + ", which is the same field");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
budget = v;
|
||||
named = k;
|
||||
}
|
||||
if (!named) {
|
||||
if (span.known()) sp->thinking_budget = (int32_t)lim.default_thinking_budget;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (!span.known()) {
|
||||
std::string why;
|
||||
if (render.think_close.empty())
|
||||
why = "this model's chat template has no reasoning block to hold a budget on";
|
||||
else if (n_close != 1)
|
||||
why = "this model's reasoning block ends in `" + render.think_close + "`, which is " +
|
||||
std::to_string(n_close) + " tokens, and a budget is held by forcing that end "
|
||||
"as one token";
|
||||
else
|
||||
why = "this reply has to open its own reasoning block, and the opener `" +
|
||||
render.think_open + "` is " + std::to_string(n_open) + " tokens, so the block "
|
||||
"cannot be found by token";
|
||||
*err = err_unsupported(named, why);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
sp->thinking_budget = (int32_t)budget;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimits& lim,
|
||||
OaiRequest* out, ApiError* err) {
|
||||
json b;
|
||||
@@ -1204,6 +1273,36 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
auto mit = b.find("messages");
|
||||
if (mit == b.end()) { *err = err_bad("messages", "is required"); return RAD_E_INVAL; }
|
||||
json messages = *mit;
|
||||
if (messages.is_array()) {
|
||||
out->n_messages = (int)messages.size();
|
||||
for (auto it = messages.rbegin(); it != messages.rend(); ++it) {
|
||||
if (!it->is_object() || !it->contains("role") || it->at("role") != "user") continue;
|
||||
const auto cit = it->find("content");
|
||||
if (cit == it->end()) break;
|
||||
/* At most 160 bytes are kept, so no more than that is copied out of a message that
|
||||
* may be a whole document, and the cut lands on a UTF-8 lead byte: a log line split
|
||||
* inside a character is not valid text. */
|
||||
constexpr size_t kKeep = 160;
|
||||
std::string t;
|
||||
auto take = [&t](const std::string& s) {
|
||||
if (t.size() <= kKeep) t.append(s, 0, kKeep + 1 - t.size());
|
||||
};
|
||||
if (cit->is_string()) take(cit->get_ref<const std::string&>());
|
||||
else if (cit->is_array())
|
||||
for (const auto& part : *cit)
|
||||
if (part.is_object() && part.value("type", "") == "text")
|
||||
take(part.value("text", ""));
|
||||
for (char& c : t) if (c == '\n' || c == '\r' || c == '\t') c = ' ';
|
||||
if (t.size() > kKeep) {
|
||||
size_t cut = kKeep - 3;
|
||||
while (cut > 0 && ((unsigned char)t[cut] & 0xC0) == 0x80) --cut;
|
||||
t.resize(cut);
|
||||
t += "...";
|
||||
}
|
||||
out->last_user = std::move(t);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* tools and tool_choice. */
|
||||
json tools = json::array();
|
||||
@@ -1221,6 +1320,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
}
|
||||
}
|
||||
tools = *tit;
|
||||
out->n_tools = (int)tools.size();
|
||||
}
|
||||
|
||||
/* FORCING A CALL IS REFUSED, and not because the grammar is out of reach -- the template
|
||||
@@ -1347,6 +1447,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
out->reply_parser = render.parser;
|
||||
out->preserved_tokens = render.preserved_tokens;
|
||||
out->parse_tools = out->tools_present && render.parser != nullptr;
|
||||
RAD_TRY(parse_thinking_budget(b, d, lim, render, &out->sp, err));
|
||||
|
||||
/* The format's own end-of-turn markers join the caller's stop strings rather than living in a
|
||||
* second list: both end the generation and both report `finish_reason: "stop"` (sink.cpp), so
|
||||
@@ -1355,6 +1456,12 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
if (std::find(out->stop.begin(), out->stop.end(), s) == out->stop.end())
|
||||
out->stop.push_back(s);
|
||||
|
||||
/* A reply that starts inside the reasoning block: its stop strings are the answer's, so they
|
||||
* apply only after the block's closer (Detokenizer::defer_stops_until). The chat format says
|
||||
* whether the rendered prompt leaves the block open and what closes it. */
|
||||
if (render.think_starts_open && !render.think_close.empty())
|
||||
out->stops_after = render.think_close;
|
||||
|
||||
/* Checked HERE, where the answer is still a 400. The grammar being validated may be the
|
||||
* caller's, or one the template produced for its own tool-call syntax; either way the first
|
||||
* moment it can fail is when the automaton is built, and building it on the step path would
|
||||
@@ -1444,10 +1551,15 @@ int parse_completion_request(const std::string& body, const OaiDeps& d, const Oa
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* A raw prompt is the client's whole input: no template wraps it and no role is the server's
|
||||
* to protect, so its control tokens are parsed, as vLLM and llama.cpp parse them. A client
|
||||
* that renders its own chat template sends "<|im_start|>" meaning the token; read as text it
|
||||
* reaches the model as six pieces of punctuation. Token ids could name any control token
|
||||
* already. */
|
||||
auto push_text = [&](const std::string& s) {
|
||||
PromptInput p;
|
||||
p.text = s;
|
||||
p.tokens = d.tok->encode(s, true, /*parse_special=*/false);
|
||||
p.tokens = d.tok->encode(s, true, /*parse_special=*/true);
|
||||
out->prompts.push_back(std::move(p));
|
||||
};
|
||||
auto push_ids = [&](const json& arr, ApiError* e) -> bool {
|
||||
@@ -1565,10 +1677,12 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
|
||||
return true;
|
||||
};
|
||||
|
||||
/* Parsed like a /v1/completions prompt, and for the same reason: the input is the client's
|
||||
* own text with no template around it. */
|
||||
if (it->is_string()) {
|
||||
PromptInput p;
|
||||
p.text = it->get<std::string>();
|
||||
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false);
|
||||
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
|
||||
out->prompts.push_back(std::move(p));
|
||||
} else if (it->is_array()) {
|
||||
if (it->empty()) { *err = err_bad("input", "must not be empty"); return RAD_E_INVAL; }
|
||||
@@ -1577,7 +1691,7 @@ int parse_embeddings_request(const std::string& body, const OaiDeps& d, const Oa
|
||||
if (!s.is_string()) { *err = err_bad("input", "expected all strings"); return RAD_E_INVAL; }
|
||||
PromptInput p;
|
||||
p.text = s.get<std::string>();
|
||||
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/false);
|
||||
p.tokens = d.tok->encode(p.text, true, /*parse_special=*/true);
|
||||
out->prompts.push_back(std::move(p));
|
||||
}
|
||||
} else if (it->front().is_number_integer()) {
|
||||
@@ -1632,6 +1746,39 @@ static json usage_json(const UsageOut& u) {
|
||||
o["completion_tokens"] = u.completion;
|
||||
o["total_tokens"] = u.prompt + u.completion;
|
||||
o["prompt_tokens_details"] = d;
|
||||
/* HOW MUCH OF completion_tokens THE CLIENT NEVER SEES AS CONTENT. Without it a reply cut at
|
||||
* max_tokens inside its reasoning reads as a model that answered nothing; with it the client
|
||||
* can tell the budget went to reasoning. */
|
||||
if (u.reasoning >= 0) {
|
||||
json c;
|
||||
c["reasoning_tokens"] = u.reasoning;
|
||||
o["completion_tokens_details"] = c;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
json timings_json(const TimingsOut& t) {
|
||||
auto per = [](int64_t n, double ms) -> json {
|
||||
return n > 0 && ms > 0.0 ? json(ms / (double)n) : json(nullptr);
|
||||
};
|
||||
auto rate = [](int64_t n, double ms) -> json {
|
||||
return n > 0 && ms > 0.0 ? json((double)n * 1000.0 / ms) : json(nullptr);
|
||||
};
|
||||
const json pms = t.prompt_ms >= 0.0 ? json(t.prompt_ms) : json(nullptr);
|
||||
json o;
|
||||
o["cache_n"] = t.cache_n;
|
||||
o["prompt_n"] = t.prompt_n;
|
||||
o["prompt_ms"] = pms;
|
||||
o["prompt_per_token_ms"] = per(t.prompt_n, t.prompt_ms);
|
||||
o["prompt_per_second"] = rate(t.prompt_n, t.prompt_ms);
|
||||
o["predicted_n"] = t.predicted_n;
|
||||
o["predicted_ms"] = t.predicted_ms;
|
||||
o["predicted_per_token_ms"] = per(t.decode_n, t.predicted_ms);
|
||||
o["predicted_per_second"] = rate(t.decode_n, t.predicted_ms);
|
||||
if (t.draft_n > 0) {
|
||||
o["draft_n"] = t.draft_n;
|
||||
o["draft_n_accepted"] = t.draft_n_accepted;
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
@@ -1643,7 +1790,8 @@ static json usage_json(const UsageOut& u) {
|
||||
*
|
||||
* One contract for both, OpenAI's: an empty choices array, sent after the last content chunk
|
||||
* and before [DONE]. Only the `object` differs, because it is a different endpoint's stream. */
|
||||
static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const char* object) {
|
||||
static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t,
|
||||
const char* object) {
|
||||
json o;
|
||||
o["id"] = r.id;
|
||||
o["object"] = object;
|
||||
@@ -1651,15 +1799,16 @@ static std::string usage_chunk(const OaiRequest& r, const UsageOut& u, const cha
|
||||
o["model"] = r.model;
|
||||
o["choices"] = json::array();
|
||||
o["usage"] = usage_json(u);
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u) {
|
||||
return usage_chunk(r, u, "text_completion");
|
||||
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) {
|
||||
return usage_chunk(r, u, t, "text_completion");
|
||||
}
|
||||
|
||||
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u) {
|
||||
return usage_chunk(r, u, "chat.completion.chunk");
|
||||
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u, const TimingsOut& t) {
|
||||
return usage_chunk(r, u, t, "chat.completion.chunk");
|
||||
}
|
||||
|
||||
static json chat_logprobs_json(const std::vector<LogprobEntry>& lp) {
|
||||
@@ -1680,7 +1829,7 @@ static json chat_logprobs_json(const std::vector<LogprobEntry>& lp) {
|
||||
}
|
||||
|
||||
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
|
||||
const UsageOut& u) {
|
||||
const UsageOut& u, const TimingsOut& t) {
|
||||
json arr = json::array();
|
||||
for (const auto& c : choices) {
|
||||
json m;
|
||||
@@ -1705,11 +1854,12 @@ std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
|
||||
o["model"] = r.model;
|
||||
o["choices"] = std::move(arr);
|
||||
o["usage"] = usage_json(u);
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
|
||||
const UsageOut& u) {
|
||||
const UsageOut& u, const TimingsOut& t) {
|
||||
json arr = json::array();
|
||||
for (const auto& c : choices) {
|
||||
json ch;
|
||||
@@ -1743,6 +1893,7 @@ std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOu
|
||||
o["model"] = r.model;
|
||||
o["choices"] = std::move(arr);
|
||||
o["usage"] = usage_json(u);
|
||||
if (t.valid) o["timings"] = timings_json(t);
|
||||
return o.dump();
|
||||
}
|
||||
|
||||
@@ -1801,7 +1952,7 @@ ChatDeltaStream::ChatDeltaStream(const OaiRequest& r, int index, const IReplyPar
|
||||
: reader_(parser ? parser->open() : nullptr), id_(r.id), model_(r.model),
|
||||
created_(r.created), index_(index) {}
|
||||
|
||||
std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) {
|
||||
std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const TimingsOut* t) {
|
||||
json ch;
|
||||
ch["index"] = index_;
|
||||
ch["delta"] = std::move(delta);
|
||||
@@ -1813,9 +1964,31 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason) {
|
||||
o["created"] = created_;
|
||||
o["model"] = model_;
|
||||
o["choices"] = json::array({ch});
|
||||
if (t && t->valid) o["timings"] = timings_json(*t);
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
void ChatDeltaStream::delta_open(std::string& out) {
|
||||
/* Built from nlohmann's own serialisation of each field, on first use rather than in the
|
||||
* constructor, so a field nlohmann refuses throws where chunk() would have. */
|
||||
if (head_.empty())
|
||||
head_ = "data: {\"id\":" + json(id_).dump() +
|
||||
",\"object\":\"chat.completion.chunk\",\"created\":" + json(created_).dump() +
|
||||
",\"model\":" + json(model_).dump() + ",\"choices\":[{\"index\":" +
|
||||
json(index_).dump() + ",\"delta\":";
|
||||
out += head_;
|
||||
}
|
||||
|
||||
void ChatDeltaStream::delta_close(std::string& out) const {
|
||||
out += ",\"finish_reason\":null}]}\n\n";
|
||||
}
|
||||
|
||||
/* Text that is not well-formed UTF-8 goes to nlohmann, which refuses it with the exception the
|
||||
* tree in chunk() raises for it. */
|
||||
void ChatDeltaStream::quote(std::string& out, std::string_view s) {
|
||||
if (!json_quote_append(out, s)) out += json(std::string(s)).dump();
|
||||
}
|
||||
|
||||
std::string ChatDeltaStream::first_chunk() {
|
||||
json d;
|
||||
d["role"] = "assistant";
|
||||
@@ -1830,49 +2003,53 @@ std::string ChatDeltaStream::first_chunk() {
|
||||
std::string ChatDeltaStream::emit(const std::vector<ReplyDelta>& ev) {
|
||||
std::string out;
|
||||
for (const ReplyDelta& d : ev) {
|
||||
json delta;
|
||||
switch (d.kind) {
|
||||
case ReplyDelta::Reasoning:
|
||||
if (d.text.empty()) continue;
|
||||
last_.reasoning += d.text;
|
||||
delta["reasoning_content"] = d.text;
|
||||
delta_open(out);
|
||||
out += "{\"reasoning_content\":";
|
||||
quote(out, d.text);
|
||||
out += '}';
|
||||
break;
|
||||
case ReplyDelta::Content:
|
||||
if (d.text.empty()) continue;
|
||||
last_.content += d.text;
|
||||
delta["content"] = d.text;
|
||||
delta_open(out);
|
||||
out += "{\"content\":";
|
||||
quote(out, d.text);
|
||||
out += '}';
|
||||
break;
|
||||
case ReplyDelta::CallBegin: {
|
||||
ToolCall tc;
|
||||
tc.id = random_id("call_");
|
||||
tc.name = d.text;
|
||||
last_.tool_calls.push_back(tc);
|
||||
json f;
|
||||
f["name"] = tc.name;
|
||||
f["arguments"] = "";
|
||||
json e;
|
||||
e["index"] = (int64_t)d.call;
|
||||
e["id"] = tc.id;
|
||||
e["type"] = "function";
|
||||
e["function"] = std::move(f);
|
||||
delta["tool_calls"] = json::array({e});
|
||||
delta_open(out);
|
||||
out += "{\"tool_calls\":[{\"index\":";
|
||||
out += std::to_string((int64_t)d.call);
|
||||
out += ",\"id\":";
|
||||
quote(out, tc.id);
|
||||
out += ",\"type\":\"function\",\"function\":{\"name\":";
|
||||
quote(out, tc.name);
|
||||
out += ",\"arguments\":\"\"}}]}";
|
||||
last_.tool_calls.push_back(std::move(tc));
|
||||
break;
|
||||
}
|
||||
case ReplyDelta::CallArgs: {
|
||||
if (d.text.empty() || d.call >= last_.tool_calls.size()) continue;
|
||||
last_.tool_calls[d.call].arguments += d.text;
|
||||
json f;
|
||||
f["arguments"] = d.text;
|
||||
json e;
|
||||
e["index"] = (int64_t)d.call;
|
||||
e["function"] = std::move(f);
|
||||
delta["tool_calls"] = json::array({e});
|
||||
delta_open(out);
|
||||
out += "{\"tool_calls\":[{\"index\":";
|
||||
out += std::to_string((int64_t)d.call);
|
||||
out += ",\"function\":{\"arguments\":";
|
||||
quote(out, d.text);
|
||||
out += "}}]}";
|
||||
break;
|
||||
}
|
||||
case ReplyDelta::CallEnd:
|
||||
continue;
|
||||
}
|
||||
out += chunk(std::move(delta), nullptr);
|
||||
delta_close(out);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1884,9 +2061,11 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
|
||||
/* Nothing to parse: the text is the answer, as it arrives. */
|
||||
if (!appended.empty()) {
|
||||
last_.content.append(appended);
|
||||
json d;
|
||||
d["content"] = std::string(appended);
|
||||
out = chunk(std::move(d), nullptr);
|
||||
delta_open(out);
|
||||
out += "{\"content\":";
|
||||
quote(out, appended);
|
||||
out += '}';
|
||||
delta_close(out);
|
||||
}
|
||||
finished_ = is_final;
|
||||
return out;
|
||||
@@ -1907,21 +2086,26 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
|
||||
return out;
|
||||
}
|
||||
|
||||
Finish ChatDeltaStream::adjusted_finish(Finish f) const {
|
||||
if (f != Finish::Stop && f != Finish::StopString) return f;
|
||||
if (last_.tool_calls.empty()) return f;
|
||||
/* Only claim tool_calls if every call's arguments actually parse. A truncated arguments
|
||||
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h). */
|
||||
for (const auto& tc : last_.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) return f;
|
||||
return Finish::ToolCalls;
|
||||
bool calls_complete(const ParsedMessage& m) {
|
||||
if (m.tool_calls.empty() || m.open_call) return false;
|
||||
for (const auto& tc : m.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
std::string ChatDeltaStream::final_chunk(Finish f) {
|
||||
Finish ChatDeltaStream::adjusted_finish(Finish f) const {
|
||||
if (f != Finish::Stop && f != Finish::StopString) return f;
|
||||
/* Only claim tool_calls if every call closed and its arguments parse. A truncated arguments
|
||||
* object reported as a tool call is a tool invoked with the wrong arguments (json_partial.h).
|
||||
* The deltas of an open call have gone out already; the finish reason says not to run it. */
|
||||
return calls_complete(last_) ? Finish::ToolCalls : f;
|
||||
}
|
||||
|
||||
std::string ChatDeltaStream::final_chunk(Finish f, const TimingsOut& t) {
|
||||
/* The generation is over, so whatever the reader was holding is resolved now. A caller that
|
||||
* already said so gets nothing twice. */
|
||||
std::string out = push(std::string_view(), true);
|
||||
out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)));
|
||||
out += chunk(json::object(), finish_reason_oai(adjusted_finish(f)), &t);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
+85
-10
@@ -77,6 +77,9 @@ struct OaiRequest {
|
||||
SamplingParams sp;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
/* The reasoning block's closer when the reply starts inside the block, else "": the stop
|
||||
* strings above then apply only after it (IDetokenizer::defer_stops_until). */
|
||||
std::string stops_after;
|
||||
/* Generate past end-of-text, to max_tokens. See Request::ignore_eos. */
|
||||
bool ignore_eos = false;
|
||||
int priority = 0;
|
||||
@@ -88,6 +91,14 @@ struct OaiRequest {
|
||||
bool want_logprobs = false;
|
||||
|
||||
bool tools_present = false;
|
||||
/* FOR THE REQUEST LOG, counted while the parse walks the body anyway: the messages and tools
|
||||
* a chat request carried, and the last user message's opening (one line, bounded) that the
|
||||
* debug level prints so a log line can be matched to what was typed. Completion requests
|
||||
* leave them at zero and empty. */
|
||||
int n_messages = 0;
|
||||
int n_tools = 0;
|
||||
std::string last_user;
|
||||
std::string peer; /* the handler sets it from the transport; "" in-process */
|
||||
bool parse_tools = false;
|
||||
/* The reply parser this request's render produced. Per request and not per server: it is the
|
||||
* model's format bound to the tools THIS call sent, so two concurrent requests against the
|
||||
@@ -109,8 +120,13 @@ struct OaiLimits {
|
||||
std::string model_id = "radiance";
|
||||
int64_t max_ctx = 0; /* 0 = unknown, no length check */
|
||||
/* What a request that names no max_tokens may generate. 0 is "whatever the context leaves",
|
||||
* resolved against the prompt in clamp_max_tokens. */
|
||||
int64_t default_max_tokens = 512;
|
||||
* resolved against the prompt in clamp_max_tokens, which needs max_ctx to resolve against.
|
||||
*
|
||||
* 0 BY DEFAULT, as vLLM's is: many clients send no max_tokens, and a reasoning model spends
|
||||
* the first thousands of tokens of an answer thinking. A fixed default of 512 ended those
|
||||
* answers inside the reasoning, with finish_reason "length" that a chat client does not show,
|
||||
* so they read as a model that stops at random. */
|
||||
int64_t default_max_tokens = 0;
|
||||
/* The most any request may generate; a larger max_tokens is clamped, not refused. 0 = none. */
|
||||
int64_t max_tokens_cap = 0;
|
||||
int max_n = 8;
|
||||
@@ -131,6 +147,13 @@ struct OaiLimits {
|
||||
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
|
||||
std::string default_reasoning_effort;
|
||||
|
||||
/* THE DEPLOYMENT'S DEFAULT `thinking_token_budget`, -1 for none. For the same reason the
|
||||
* effort default exists: an agent framework sizes max_tokens per turn and sends no budget, and
|
||||
* a reasoning block that spends the whole of max_tokens returns a turn with no answer in it.
|
||||
* Applied only to a request that names no budget, and only where the reply's reasoning block
|
||||
* can be counted. */
|
||||
int64_t default_thinking_budget = -1;
|
||||
|
||||
/* WHAT A REQUEST THAT SENDS NO SAMPLER FIELDS IS SERVED WITH, field by field.
|
||||
*
|
||||
* The struct's own defaults are an untruncated sampler -- temperature 1, top_k off, top_p 1
|
||||
@@ -215,12 +238,46 @@ struct UsageOut {
|
||||
int64_t prompt = 0;
|
||||
int64_t completion = 0;
|
||||
int64_t cached = 0;
|
||||
/* Of `completion`, the tokens inside the reply's reasoning block, its markers included: OpenAI's
|
||||
* completion_tokens_details.reasoning_tokens. -1 when the block cannot be counted, and the
|
||||
* breakdown is then left out. */
|
||||
int64_t reasoning = -1;
|
||||
};
|
||||
|
||||
/* WHERE ONE REQUEST'S TIME WENT, in llama.cpp's `timings` shape, which proxies and dashboards
|
||||
* built against llama-server already read (llama-swap's activity view is one). /metrics holds the
|
||||
* same quantities summed over every request, and two overlapping requests cannot be told apart
|
||||
* there; this is the per-request half.
|
||||
*
|
||||
* prompt_n prompt tokens computed, the prefix cache's excluded; cache_n is those
|
||||
* prompt_ms from the first step the scheduler gave the request to its first token -- the
|
||||
* prefill, without the time it waited for admission
|
||||
* predicted_n tokens generated: usage.completion_tokens
|
||||
* predicted_ms from the first token to the last
|
||||
* draft_n, draft_n_accepted
|
||||
* speculative tokens proposed for this request and accepted; present when any
|
||||
* were proposed, as llama.cpp does
|
||||
*
|
||||
* The rates divide the tokens by the time that produced them: prompt_n by prompt_ms, and the
|
||||
* predicted_n - 1 tokens after the first by predicted_ms, since the first token is the prompt
|
||||
* phase's product -- the same figure as /metrics' time per output token. A rate whose count or
|
||||
* time is zero is null. Over several choices the counts are summed and each time runs from the
|
||||
* earliest choice's start to the latest choice's end. */
|
||||
struct TimingsOut {
|
||||
bool valid = false; /* some choice produced a token; nothing is reported otherwise */
|
||||
int64_t prompt_n = 0, cache_n = 0;
|
||||
double prompt_ms = -1.0; /* < 0: the engine did not report the admission */
|
||||
int64_t predicted_n = 0;
|
||||
int64_t decode_n = 0; /* of predicted_n, the tokens after each choice's first */
|
||||
double predicted_ms = 0.0;
|
||||
int64_t draft_n = 0, draft_n_accepted = 0;
|
||||
};
|
||||
|
||||
/* `timings` is added at the top level when it is valid. */
|
||||
std::string chat_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
|
||||
const UsageOut& u);
|
||||
const UsageOut& u, const TimingsOut& t = TimingsOut());
|
||||
std::string text_completion_body(const OaiRequest& r, const std::vector<ChoiceOut>& choices,
|
||||
const UsageOut& u);
|
||||
const UsageOut& u, const TimingsOut& t = TimingsOut());
|
||||
std::string embeddings_body(const OaiRequest& r, const std::vector<std::vector<float>>& vecs,
|
||||
const UsageOut& u);
|
||||
std::string models_body(const std::string& model_id, int64_t created);
|
||||
@@ -229,8 +286,17 @@ std::string models_body(const std::string& model_id, int64_t created);
|
||||
* only payload is `usage`. Emitted when the request asked for stream_options.include_usage, ONCE
|
||||
* per stream and after every choice's final chunk -- `n` choices share one prompt and one total,
|
||||
* so a chunk per choice would count the prompt n times and interleave with the choices. */
|
||||
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u);
|
||||
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u);
|
||||
std::string text_usage_chunk(const OaiRequest& r, const UsageOut& u,
|
||||
const TimingsOut& t = TimingsOut());
|
||||
std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
|
||||
const TimingsOut& t = TimingsOut());
|
||||
/* The `timings` object, for a stream's final chunks. */
|
||||
json timings_json(const TimingsOut& t);
|
||||
|
||||
/* Whether a parsed reply's calls are all calls a client can run: none left open, each named,
|
||||
* each one's arguments one JSON value (json_partial.h). A reply is answered `tool_calls` by this
|
||||
* alone, streamed or not. */
|
||||
bool calls_complete(const ParsedMessage& m);
|
||||
|
||||
/* ================================================================== streaming
|
||||
*
|
||||
@@ -251,9 +317,10 @@ public:
|
||||
* `is_final` says the generation is over, which resolves whatever the reader was holding. */
|
||||
std::string push(std::string_view appended, bool is_final);
|
||||
|
||||
/* The terminating chunk carrying finish_reason. The usage chunk is the stream's, not the
|
||||
* choice's: chat_usage_chunk. */
|
||||
std::string final_chunk(Finish f);
|
||||
/* The terminating chunk carrying finish_reason, and this choice's `timings` when they are
|
||||
* valid -- on the final chunk whether or not the request asked for a usage chunk, as
|
||||
* llama.cpp sends them. The usage chunk is the stream's, not the choice's: chat_usage_chunk. */
|
||||
std::string final_chunk(Finish f, const TimingsOut& t = TimingsOut());
|
||||
|
||||
/* What the whole generation parsed to -- the non-streaming shape. Complete once push has
|
||||
* been called with is_final. */
|
||||
@@ -261,9 +328,17 @@ public:
|
||||
Finish adjusted_finish(Finish f) const;
|
||||
|
||||
private:
|
||||
std::string chunk(json delta, const char* finish_reason);
|
||||
std::string chunk(json delta, const char* finish_reason, const TimingsOut* t = nullptr);
|
||||
std::string emit(const std::vector<ReplyDelta>& ev);
|
||||
|
||||
/* A delta's chunk is written, not built: the frame around the delta object is the same in
|
||||
* every one, so it is serialised once, and the delta between is written with
|
||||
* json_quote_append. The bytes are the ones chunk() writes for the same delta. */
|
||||
void delta_open(std::string& out);
|
||||
void delta_close(std::string& out) const;
|
||||
static void quote(std::string& out, std::string_view s);
|
||||
std::string head_; /* `data: {...,"choices":[{"index":N,"delta":`, built on first use */
|
||||
|
||||
std::unique_ptr<IReplyReader> reader_;
|
||||
std::string id_, model_;
|
||||
int64_t created_;
|
||||
|
||||
+224
-49
@@ -1,4 +1,6 @@
|
||||
#include "server.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include "json_partial.h"
|
||||
#include "rad_internal.h"
|
||||
|
||||
@@ -22,9 +24,16 @@ struct Server::Generation {
|
||||
int prompt_index = 0;
|
||||
std::string text;
|
||||
std::vector<LogprobEntry> logprobs;
|
||||
/* The reply against its reasoning block, every token the sink delivers: what
|
||||
* completion_tokens_details.reasoning_tokens reports. */
|
||||
ReasoningCount think;
|
||||
Finish finish = Finish::None;
|
||||
bool closed = false; /* the server has decided this choice is over */
|
||||
size_t scanned = 0; /* how far the stop-string scan has reached */
|
||||
/* OaiRequest::stops_after: where in `text` the reasoning block's closer ends (npos until it
|
||||
* has been generated) and how far the search for it has reached. */
|
||||
size_t stops_floor = std::string::npos;
|
||||
size_t closer_scanned = 0;
|
||||
size_t stop_cut = std::string::npos;
|
||||
size_t emitted = 0; /* streaming: text already handed to the delta stream */
|
||||
bool retired = false; /* reap() has been said for this id, at most once */
|
||||
@@ -56,6 +65,7 @@ Server::Server(const Deps& d, const ServerOptions& o)
|
||||
lim_.allow_audio = opt_.allow_audio;
|
||||
lim_.supports_logprobs = opt_.supports_logprobs;
|
||||
lim_.default_reasoning_effort = opt_.default_reasoning_effort;
|
||||
lim_.default_thinking_budget = opt_.default_thinking_budget;
|
||||
lim_.default_sampling = opt_.default_sampling;
|
||||
lim_.default_dry_breakers_set = opt_.default_dry_breakers_set;
|
||||
lim_.default_template_kwargs = opt_.default_template_kwargs;
|
||||
@@ -193,6 +203,16 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor
|
||||
if (!l.default_reasoning_effort.empty()) render(l, effort_why);
|
||||
}
|
||||
|
||||
std::string Server::check_thinking_budget() const {
|
||||
if (!deps_.chat || lim_.default_thinking_budget < 0) return std::string();
|
||||
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
|
||||
R"("thinking_token_budget":)" +
|
||||
std::to_string(lim_.default_thinking_budget) + "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
return parse_chat_request(body, odeps_, lim_, &r, &e) < 0 ? e.message : std::string();
|
||||
}
|
||||
|
||||
void Server::stop() {
|
||||
stopping_.store(true);
|
||||
transport_.stop();
|
||||
@@ -234,13 +254,48 @@ void Server::sweep_abandoned() {
|
||||
|
||||
/* ------------------------------------------------------------------ errors */
|
||||
|
||||
HttpResponse Server::error_response(const ApiError& e) {
|
||||
/* " from <addr:port>" for the request log, or nothing in-process, where no transport names a
|
||||
* peer. */
|
||||
static std::string from_peer(const std::string& peer) {
|
||||
return peer.empty() ? std::string() : " from " + peer;
|
||||
}
|
||||
|
||||
HttpResponse Server::error_response(const ApiError& e, const std::string& peer) {
|
||||
metrics_.observe_http(e.status);
|
||||
/* A refusal is the line the operator is looking for when a client says "rejected": the
|
||||
* status, the type, the message, and who asked. 4xx is the client's doing and said at info;
|
||||
* 5xx is ours and said as a warning. */
|
||||
if (e.status >= 500)
|
||||
RAD_WARN("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
|
||||
e.message.c_str());
|
||||
else
|
||||
RAD_INFO("req refused%s -> %d %s: %s", from_peer(peer).c_str(), e.status, e.type.c_str(),
|
||||
e.message.c_str());
|
||||
HttpResponse r = HttpResponse::json_body(e.status, e.dump());
|
||||
if (e.status == 429) r.set_header("Retry-After", std::to_string(opt_.retry_after_s));
|
||||
return r;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the request log */
|
||||
|
||||
void Server::log_admitted(const OaiRequest& r) const {
|
||||
int64_t n_prompt = 0;
|
||||
for (const auto& p : r.prompts) n_prompt += (int64_t)p.tokens.size();
|
||||
const char* kind = r.endpoint == Endpoint::Chat ? "chat" : "completion";
|
||||
if (r.endpoint == Endpoint::Chat)
|
||||
RAD_INFO("req %s %s%s%s model=%s msgs=%d tools=%d prompt=%lld tok n=%d max_tokens=%lld",
|
||||
r.id.c_str(), kind, r.stream ? " stream" : "", from_peer(r.peer).c_str(),
|
||||
r.model.c_str(), r.n_messages, r.n_tools, (long long)n_prompt, r.n,
|
||||
(long long)r.max_tokens);
|
||||
else
|
||||
RAD_INFO("req %s %s%s%s model=%s prompts=%zu prompt=%lld tok n=%d max_tokens=%lld",
|
||||
r.id.c_str(), kind, r.stream ? " stream" : "", from_peer(r.peer).c_str(),
|
||||
r.model.c_str(), r.prompts.size(), (long long)n_prompt, r.n,
|
||||
(long long)r.max_tokens);
|
||||
if (!r.last_user.empty())
|
||||
RAD_DEBUG("req %s last user: %s", r.id.c_str(), r.last_user.c_str());
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ submission */
|
||||
|
||||
int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiError* err) {
|
||||
@@ -273,11 +328,13 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
g.prompt_index = (int)p;
|
||||
g.sink = std::make_shared<Sink>();
|
||||
g.sink->set_has_logprobs(opt_.supports_logprobs);
|
||||
g.think.start(r.sp.reasoning);
|
||||
g.detok = deps_.tok->detokenizer(r.stop, r.preserved_tokens);
|
||||
if (!g.detok) {
|
||||
*err = err_not_implemented("the tokenizer did not supply an incremental decoder");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (!r.stops_after.empty()) g.detok->defer_stops_until(r.stops_after);
|
||||
|
||||
Request rq;
|
||||
rq.prompt = r.prompts[p].tokens;
|
||||
@@ -286,7 +343,9 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
* Offsetting is enough: the sampler's stream is seeded, not chained. */
|
||||
rq.sp.seed = r.sp.seed + (uint64_t)k;
|
||||
rq.max_tokens = r.max_tokens;
|
||||
rq.stop = r.stop;
|
||||
/* With the stop strings deferred past the reasoning block, the scheduler -- which
|
||||
* cannot tell reasoning from answer -- gets none; the decoder and pump() cut. */
|
||||
rq.stop = r.stops_after.empty() ? r.stop : std::vector<std::string>{};
|
||||
rq.ignore_eos = r.ignore_eos;
|
||||
rq.priority = r.priority;
|
||||
rq.stream = r.stream;
|
||||
@@ -353,6 +412,7 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
while ((n = g.sink->read(buf, 128)) > 0) {
|
||||
progress = true;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
g.think.push(r.sp.reasoning, buf[i].token);
|
||||
std::string piece = g.detok->push(buf[i].token);
|
||||
if (!piece.empty()) g.text += piece;
|
||||
if (r.want_logprobs)
|
||||
@@ -376,8 +436,24 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
* string straddles token boundaries and only the detokenised text can be searched, so the
|
||||
* authoritative cut is made here. Scanning restarts (maxstop-1) bytes behind the previous
|
||||
* end so a match spanning two drains is still found. */
|
||||
if (maxstop && g.stop_cut == std::string::npos && !g.text.empty()) {
|
||||
/* Stop strings deferred past the reasoning block match only after its closer. The closer
|
||||
* is searched for incrementally, from (closer length - 1) bytes behind the previous end,
|
||||
* so a reply that thinks for a long time is not rescanned from its start every drain. */
|
||||
size_t floor = 0;
|
||||
if (!r.stops_after.empty()) {
|
||||
if (g.stops_floor == std::string::npos) {
|
||||
const size_t n = r.stops_after.size();
|
||||
const size_t from = g.closer_scanned >= n ? g.closer_scanned - n + 1 : 0;
|
||||
const size_t m = g.text.find(r.stops_after, from);
|
||||
g.closer_scanned = g.text.size();
|
||||
if (m != std::string::npos) g.stops_floor = m + n;
|
||||
}
|
||||
floor = g.stops_floor;
|
||||
}
|
||||
if (maxstop && floor != std::string::npos && g.stop_cut == std::string::npos &&
|
||||
!g.text.empty()) {
|
||||
size_t start = g.scanned >= maxstop ? g.scanned - maxstop + 1 : 0;
|
||||
if (start < floor) start = floor;
|
||||
for (const auto& s : r.stop) {
|
||||
if (s.empty()) continue;
|
||||
size_t at = g.text.find(s, start);
|
||||
@@ -410,8 +486,75 @@ bool Server::pump(std::vector<Generation>& gens, const OaiRequest& r) {
|
||||
return progress;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ usage */
|
||||
|
||||
/* THE REQUEST'S TOKENS, ONCE FOR BOTH PATHS. `n` choices share a prompt, so the prompt and its
|
||||
* cached part are counted once per prompt. Reasoning is reported only where the reply's block can
|
||||
* be counted by token (ReasoningSpan); a model without one reports no breakdown rather than a
|
||||
* zero that would claim there was no reasoning. */
|
||||
UsageOut Server::usage_of(const OaiRequest& r, const std::vector<Generation>& gens) {
|
||||
UsageOut u;
|
||||
for (const auto& p : r.prompts) u.prompt += (int64_t)p.tokens.size();
|
||||
if (r.sp.reasoning.known()) u.reasoning = 0;
|
||||
for (const auto& g : gens) {
|
||||
u.completion += g.sink->n_produced();
|
||||
if (g.prompt_index * r.n == g.index) u.cached += g.sink->n_cached();
|
||||
if (u.reasoning >= 0) u.reasoning += g.think.tokens;
|
||||
}
|
||||
return u;
|
||||
}
|
||||
|
||||
/* WHERE THE REQUEST'S TIME WENT, from its sinks: one for a choice's final chunk, all of them for
|
||||
* the request. Every time is moved onto one clock first -- each sink counts from its own
|
||||
* construction. See TimingsOut for what each field means. */
|
||||
TimingsOut Server::timings_of(const Sink* const* sinks, size_t n) {
|
||||
TimingsOut t;
|
||||
int64_t admit = INT64_MAX, first_lo = INT64_MAX, first_hi = INT64_MIN, last = INT64_MIN;
|
||||
bool admitted = true;
|
||||
for (size_t i = 0; i < n; ++i) {
|
||||
const Sink& s = *sinks[i];
|
||||
const int64_t produced = s.n_produced();
|
||||
t.predicted_n += produced;
|
||||
t.draft_n += s.n_drafted();
|
||||
t.draft_n_accepted += s.n_draft_accepted();
|
||||
const int64_t tf = s.t_first_token_ns();
|
||||
if (tf < 0) continue;
|
||||
t.valid = true;
|
||||
t.cache_n += s.n_cached();
|
||||
t.prompt_n += s.n_prompt() - s.n_cached();
|
||||
if (produced > 1) t.decode_n += produced - 1;
|
||||
const int64_t t0 = s.t_start_ns(), ta = s.t_admitted_ns();
|
||||
if (ta < 0) admitted = false;
|
||||
else admit = std::min(admit, t0 + ta);
|
||||
first_lo = std::min(first_lo, t0 + tf);
|
||||
first_hi = std::max(first_hi, t0 + tf);
|
||||
last = std::max(last, t0 + s.t_last_token_ns());
|
||||
}
|
||||
if (!t.valid) return t;
|
||||
if (admitted) t.prompt_ms = (double)(first_hi - admit) * 1e-6;
|
||||
t.predicted_ms = (double)(last - first_lo) * 1e-6;
|
||||
return t;
|
||||
}
|
||||
|
||||
TimingsOut Server::timings_of(const std::vector<Generation>& gens) {
|
||||
std::vector<const Sink*> v;
|
||||
v.reserve(gens.size());
|
||||
for (const auto& g : gens) v.push_back(g.sink.get());
|
||||
return timings_of(v.data(), v.size());
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ metrics bookkeeping */
|
||||
|
||||
/* WHAT FAILED, for the client: the sentence the failing component gave, and the status. A failed
|
||||
* request always carries a status -- an engine that stopped carries the one that stopped it -- so
|
||||
* this never reads "ok". */
|
||||
static std::string engine_failure(const Sink& s) {
|
||||
const int st = s.status() < 0 ? s.status() : RAD_E_STATE;
|
||||
const char* why = s.why();
|
||||
return why ? fmt("the engine failed this request: %s (%s)", why, rad_strerror(st))
|
||||
: fmt("the engine failed this request: %s", rad_strerror(st));
|
||||
}
|
||||
|
||||
static SuccessReason to_reason(Finish f) {
|
||||
switch (f) {
|
||||
case Finish::Length: return SuccessReason::Length;
|
||||
@@ -446,6 +589,23 @@ void Server::record(const OaiRequest& r, const std::vector<Generation>& gens, Fi
|
||||
}
|
||||
metrics_.observe_request(n_prompt, n_gen, ttft, tpot, e2e, decode,
|
||||
r.n, r.max_tokens, to_reason(overall));
|
||||
|
||||
/* THE OTHER HALF OF THE REQUEST LOG. The same figures /metrics aggregates, for this one
|
||||
* request: how it ended, what the prefix cache spared, the reasoning share when the parser
|
||||
* knows it, time to first token, the decode rate after it, and the whole. */
|
||||
const TimingsOut t = timings_of(gens);
|
||||
const UsageOut u = usage_of(r, gens);
|
||||
const double rate = (decode > 0.0 && n_gen > 1) ? (double)(n_gen - 1) / decode : -1.0;
|
||||
char reason[32] = "";
|
||||
if (u.reasoning >= 0) std::snprintf(reason, sizeof reason, " reason=%lld", (long long)u.reasoning);
|
||||
char ttft_s[32] = "ttft=-";
|
||||
if (ttft >= 0) std::snprintf(ttft_s, sizeof ttft_s, "ttft=%.2fs", ttft);
|
||||
char rate_s[32] = "";
|
||||
if (rate > 0) std::snprintf(rate_s, sizeof rate_s, " %.1f tok/s", rate);
|
||||
RAD_INFO("req %s done%s finish=%s prompt=%lld (cache %lld) gen=%lld%s %s%s %.2fs",
|
||||
r.id.c_str(), from_peer(r.peer).c_str(), finish_reason_oai(overall),
|
||||
(long long)n_prompt, (long long)(t.valid ? t.cache_n : 0), (long long)n_gen, reason,
|
||||
ttft_s, rate_s, e2e);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ non-streaming */
|
||||
@@ -456,7 +616,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
if (submit_all(r, &gens, &err) < 0) {
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err);
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
@@ -477,21 +637,18 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
cancel_all(gens, false);
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err_overloaded("the server is shutting down"));
|
||||
return error_response(err_overloaded("the server is shutting down"), req.peer);
|
||||
}
|
||||
/* Wait on whichever choice is still running. Bounded, so the peer check above runs. */
|
||||
for (auto& g : gens) if (!g.closed) { g.sink->wait(); break; }
|
||||
}
|
||||
|
||||
Finish overall = Finish::Stop;
|
||||
UsageOut usage;
|
||||
for (const auto& p : r.prompts) usage.prompt += (int64_t)p.tokens.size();
|
||||
const UsageOut usage = usage_of(r, gens);
|
||||
std::vector<ChoiceOut> choices;
|
||||
choices.reserve(gens.size());
|
||||
|
||||
for (auto& g : gens) {
|
||||
usage.completion += g.sink->n_produced();
|
||||
if (g.prompt_index * r.n == g.index) usage.cached += g.sink->n_cached();
|
||||
|
||||
ChoiceOut c;
|
||||
c.index = g.index;
|
||||
@@ -510,17 +667,20 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
rd->feed(g.text, nullptr);
|
||||
rd->finish(nullptr);
|
||||
c.msg = rd->message();
|
||||
/* Only claim a tool call when the arguments actually parse (json_partial.h). */
|
||||
bool complete = r.parse_tools && !c.msg.tool_calls.empty();
|
||||
for (const auto& tc : c.msg.tool_calls)
|
||||
if (tc.name.empty() || !json_complete(tc.arguments)) complete = false;
|
||||
/* Only claim a tool call when every call closed and its arguments parse
|
||||
* (json_partial.h) -- the streaming path's rule (calls_complete). */
|
||||
const bool complete = r.parse_tools && calls_complete(c.msg);
|
||||
if (complete && (c.finish == Finish::Stop || c.finish == Finish::StopString))
|
||||
c.finish = Finish::ToolCalls;
|
||||
else if (!c.msg.tool_calls.empty() && !complete) {
|
||||
/* A half-finished call is content, not a call. The client gets what the model
|
||||
* actually produced instead of a tool invocation with truncated arguments. */
|
||||
c.msg.tool_calls.clear();
|
||||
c.msg.content = g.text;
|
||||
if (c.msg.open_call) {
|
||||
/* A half-finished call is content, not a call: the client gets what the model
|
||||
* wrote instead of a tool invocation with truncated arguments. Only that call
|
||||
* -- the reply ended inside it, so it is the last -- and only its own text:
|
||||
* the reasoning stays reasoning, and the calls before it, which closed, stay
|
||||
* calls, as the stream announced them. The finish reason is the stream's. */
|
||||
c.msg.content = rd->content_with_open_call(g.text);
|
||||
c.msg.tool_calls.pop_back();
|
||||
c.msg.open_call = false;
|
||||
}
|
||||
} else {
|
||||
c.msg.content = g.text;
|
||||
@@ -529,22 +689,26 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
} else {
|
||||
c.text = r.echo ? r.prompts[g.prompt_index].text + g.text : g.text;
|
||||
}
|
||||
/* The request's outcome for record() and /metrics: a failure or a cancellation over
|
||||
* anything, else a tool call over a plain stop -- the same promotion the streaming path
|
||||
* makes, so a blocking tool call is not counted as "stop". */
|
||||
if (c.finish == Finish::Error || c.finish == Finish::Cancelled) overall = c.finish;
|
||||
else if (c.finish == Finish::ToolCalls && overall == Finish::Stop) overall = c.finish;
|
||||
choices.push_back(std::move(c));
|
||||
}
|
||||
|
||||
/* An engine-side failure is not a 200 with an empty answer. */
|
||||
for (auto& g : gens) {
|
||||
if (g.finish == Finish::Error) {
|
||||
int st = g.sink->status();
|
||||
const std::string why = engine_failure(*g.sink);
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
record(r, gens, Finish::Error);
|
||||
ApiError e;
|
||||
e.status = 500;
|
||||
e.type = "internal_server_error";
|
||||
e.message = std::string("the engine failed this request: ") + rad_strerror(st);
|
||||
return error_response(e);
|
||||
e.message = why;
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -552,9 +716,10 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
retire(gens);
|
||||
release(r.n_choices());
|
||||
|
||||
const TimingsOut timings = timings_of(gens);
|
||||
std::string body = r.endpoint == Endpoint::Chat
|
||||
? chat_completion_body(r, choices, usage)
|
||||
: text_completion_body(r, choices, usage);
|
||||
? chat_completion_body(r, choices, usage, timings)
|
||||
: text_completion_body(r, choices, usage, timings);
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, std::move(body));
|
||||
}
|
||||
@@ -562,7 +727,7 @@ HttpResponse Server::blocking_completion(const HttpRequest& req, OaiRequest& r)
|
||||
/* ------------------------------------------------------------------ streaming */
|
||||
|
||||
static std::string text_chunk(const OaiRequest& r, int index, const std::string& delta,
|
||||
const char* finish_reason) {
|
||||
const char* finish_reason, const TimingsOut* t = nullptr) {
|
||||
nlohmann::ordered_json ch;
|
||||
ch["text"] = delta;
|
||||
ch["index"] = index;
|
||||
@@ -574,6 +739,7 @@ static std::string text_chunk(const OaiRequest& r, int index, const std::string&
|
||||
o["created"] = r.created;
|
||||
o["model"] = r.model;
|
||||
o["choices"] = nlohmann::ordered_json::array({ch});
|
||||
if (t && t->valid) o["timings"] = timings_json(*t);
|
||||
return sse_event(o.dump());
|
||||
}
|
||||
|
||||
@@ -586,7 +752,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
if (submit_all(st->r, &st->gens, &err) < 0) {
|
||||
retire(st->gens);
|
||||
release(r.n_choices());
|
||||
return error_response(err);
|
||||
return error_response(err, req.peer);
|
||||
}
|
||||
if (st->r.endpoint == Endpoint::Chat)
|
||||
for (auto& g : st->gens)
|
||||
@@ -665,21 +831,20 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
}
|
||||
|
||||
if (self->all_done(st->gens)) {
|
||||
UsageOut u;
|
||||
for (const auto& p : st->r.prompts) u.prompt += (int64_t)p.tokens.size();
|
||||
for (auto& g : st->gens) {
|
||||
u.completion += g.sink->n_produced();
|
||||
if (g.prompt_index * st->r.n == g.index) u.cached += g.sink->n_cached();
|
||||
}
|
||||
const UsageOut u = usage_of(st->r, st->gens);
|
||||
Finish overall = Finish::Stop;
|
||||
for (auto& g : st->gens) {
|
||||
/* EACH CHOICE'S OWN TIMINGS ON ITS FINAL CHUNK, so a client that asked for no
|
||||
* usage chunk still has them, as llama.cpp sends them. */
|
||||
const Sink* one = g.sink.get();
|
||||
const TimingsOut gt = timings_of(&one, 1);
|
||||
if (st->r.endpoint == Endpoint::Chat) {
|
||||
out += g.delta->final_chunk(g.finish);
|
||||
out += g.delta->final_chunk(g.finish, gt);
|
||||
Finish adj = g.delta->adjusted_finish(g.finish);
|
||||
if (adj == Finish::Error || adj == Finish::Cancelled) overall = adj;
|
||||
else if (adj == Finish::ToolCalls) overall = adj;
|
||||
} else {
|
||||
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish));
|
||||
out += text_chunk(st->r, g.index, "", finish_reason_oai(g.finish), >);
|
||||
if (g.finish == Finish::Error) overall = Finish::Error;
|
||||
}
|
||||
/* A failed generation cannot become a non-200 -- the headers left long ago -- so
|
||||
@@ -689,8 +854,7 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
ApiError e;
|
||||
e.status = 500;
|
||||
e.type = "internal_server_error";
|
||||
e.message = std::string("the engine failed this request: ") +
|
||||
rad_strerror(g.sink->status());
|
||||
e.message = engine_failure(*g.sink);
|
||||
out += sse_error(e);
|
||||
}
|
||||
}
|
||||
@@ -702,9 +866,11 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
* it, and once for the request rather than once per choice: `n` completions share one
|
||||
* prompt and one total, so emitting it per generation would count the prompt n times
|
||||
* and interleave usage between the choices' final chunks. */
|
||||
if (st->r.include_usage)
|
||||
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u)
|
||||
: text_usage_chunk(st->r, u);
|
||||
if (st->r.include_usage) {
|
||||
const TimingsOut t = timings_of(st->gens);
|
||||
out += st->r.endpoint == Endpoint::Chat ? chat_usage_chunk(st->r, u, t)
|
||||
: text_usage_chunk(st->r, u, t);
|
||||
}
|
||||
|
||||
out += SSE_DONE;
|
||||
st->done_sent = true;
|
||||
@@ -743,50 +909,59 @@ HttpResponse Server::streaming_completion(const HttpRequest& req, OaiRequest& r)
|
||||
|
||||
HttpResponse Server::handle_chat(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"));
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
|
||||
if (parse_chat_request(req.body, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.peer = req.peer;
|
||||
|
||||
sweep_abandoned();
|
||||
if (!admit(r.n_choices())) {
|
||||
metrics_.observe_rejected();
|
||||
return error_response(err_overloaded(
|
||||
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
|
||||
"s. The server refuses rather than queueing without bound"));
|
||||
"s. The server refuses rather than queueing without bound"), req.peer);
|
||||
}
|
||||
log_admitted(r);
|
||||
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_completion(const HttpRequest& req) {
|
||||
if (!deps_.sched || !deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no engine attached"));
|
||||
return error_response(err_not_implemented("the server has no engine attached"), req.peer);
|
||||
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_completion_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
|
||||
if (parse_completion_request(req.body, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
r.peer = req.peer;
|
||||
|
||||
sweep_abandoned();
|
||||
if (!admit(r.n_choices())) {
|
||||
metrics_.observe_rejected();
|
||||
return error_response(err_overloaded(
|
||||
"the admission queue is full; retry after " + std::to_string(opt_.retry_after_s) +
|
||||
"s. The server refuses rather than queueing without bound"));
|
||||
"s. The server refuses rather than queueing without bound"), req.peer);
|
||||
}
|
||||
log_admitted(r);
|
||||
return r.stream ? streaming_completion(req, r) : blocking_completion(req, r);
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_embeddings(const HttpRequest& req) {
|
||||
if (!deps_.tok)
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"));
|
||||
return error_response(err_not_implemented("the server has no tokenizer attached"),
|
||||
req.peer);
|
||||
if (!deps_.embed)
|
||||
return error_response(err_not_implemented(
|
||||
"/v1/embeddings requires an embedding head; this model was not loaded with one"));
|
||||
"/v1/embeddings requires an embedding head; this model was not loaded with one"),
|
||||
req.peer);
|
||||
|
||||
OaiRequest r;
|
||||
ApiError err;
|
||||
if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0) return error_response(err);
|
||||
if (parse_embeddings_request(req.body, odeps_, lim_, &r, &err) < 0)
|
||||
return error_response(err, req.peer);
|
||||
|
||||
std::vector<std::vector<float>> vecs;
|
||||
UsageOut u;
|
||||
@@ -799,7 +974,7 @@ HttpResponse Server::handle_embeddings(const HttpRequest& req) {
|
||||
e.status = 500;
|
||||
e.type = "internal_server_error";
|
||||
e.message = std::string("the embedding pass failed: ") + rad_strerror(s);
|
||||
return error_response(e);
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
u.prompt += (int64_t)p.tokens.size();
|
||||
vecs.push_back(std::move(v));
|
||||
@@ -816,7 +991,7 @@ HttpResponse Server::handle_models(const HttpRequest& req) {
|
||||
e.type = "not_found_error";
|
||||
e.param = "model";
|
||||
e.message = "no such model: " + id;
|
||||
return error_response(e);
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, models_body(opt_.model_id, started_at_));
|
||||
|
||||
+17
-2
@@ -66,7 +66,7 @@ struct ServerOptions {
|
||||
int retry_after_s = 1;
|
||||
|
||||
int64_t max_ctx = 0;
|
||||
int64_t default_max_tokens = 512; /* 0: what the context leaves (OaiLimits) */
|
||||
int64_t default_max_tokens = 0; /* 0: what the context leaves (OaiLimits) */
|
||||
int64_t max_tokens_cap = 0; /* 0: none */
|
||||
int max_n = 8;
|
||||
int64_t max_stops = 64;
|
||||
@@ -76,6 +76,9 @@ struct ServerOptions {
|
||||
/* The deployment default for `reasoning_effort`, empty for the template's own. See
|
||||
* OaiLimits::default_reasoning_effort for why a server-side default is needed at all. */
|
||||
std::string default_reasoning_effort;
|
||||
/* The deployment default for `thinking_token_budget`, -1 for none. See
|
||||
* OaiLimits::default_thinking_budget. */
|
||||
int64_t default_thinking_budget = -1;
|
||||
/* What a request that sends no sampler fields is served with. See
|
||||
* OaiLimits::default_sampling; only the sampler knobs are read from it. */
|
||||
SamplingParams default_sampling;
|
||||
@@ -141,6 +144,10 @@ public:
|
||||
* A render that fails at the first step says nothing about the defaults and is not reported.
|
||||
* `kwargs_why` / `effort_why` are left empty, or hold the template's refusal at that step. */
|
||||
void check_template_defaults(std::string* kwargs_why, std::string* effort_why) const;
|
||||
/* THE DEPLOYMENT'S thinking_token_budget, asked for by a one-message chat the way a request
|
||||
* would ask for it. Empty when this model's reasoning block can hold one; otherwise the 400 a
|
||||
* request naming the budget would get, which says why. */
|
||||
std::string check_thinking_budget() const;
|
||||
void stop();
|
||||
int port() const { return transport_.port(); } /* 0 until run() is accepting */
|
||||
|
||||
@@ -150,6 +157,10 @@ private:
|
||||
struct Generation;
|
||||
struct StreamState;
|
||||
|
||||
static UsageOut usage_of(const OaiRequest& r, const std::vector<Generation>& gens);
|
||||
static TimingsOut timings_of(const Sink* const* sinks, size_t n);
|
||||
static TimingsOut timings_of(const std::vector<Generation>& gens);
|
||||
|
||||
void register_routes();
|
||||
|
||||
HttpResponse handle_chat(const HttpRequest& req);
|
||||
@@ -178,7 +189,11 @@ private:
|
||||
HttpResponse handle_stats(const HttpRequest& req);
|
||||
HttpResponse handle_graph(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e);
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer);
|
||||
/* THE REQUEST LOG. One line when a request is admitted and one from record() when it ends,
|
||||
* at the info level, so `docker logs` answers "who asked what, how long, how did it end"
|
||||
* without the engine's own levels. The debug level adds the last user message's opening. */
|
||||
void log_admitted(const OaiRequest& r) const;
|
||||
|
||||
/* Admission. Returns false when the queue is full; the caller answers 429. */
|
||||
bool admit(int64_t n);
|
||||
|
||||
+14
-1
@@ -89,8 +89,9 @@ void Sink::finish(Finish f) {
|
||||
}
|
||||
}
|
||||
|
||||
void Sink::fail(int rad_status) {
|
||||
void Sink::fail(int rad_status, const char* why) {
|
||||
status_.store(rad_status, std::memory_order_release);
|
||||
why_.store(why, std::memory_order_release);
|
||||
finish(Finish::Error);
|
||||
}
|
||||
|
||||
@@ -99,6 +100,18 @@ void Sink::set_prompt_stats(int32_t n_prompt, int32_t n_cached) {
|
||||
n_cached_.store(n_cached, std::memory_order_release);
|
||||
}
|
||||
|
||||
void Sink::mark_admitted() {
|
||||
if (t_admit_.load(std::memory_order_relaxed) < 0)
|
||||
t_admit_.store(now_ns() - t_start_ns_, std::memory_order_release);
|
||||
}
|
||||
|
||||
/* One producer, so a load and a store is the whole of the update. */
|
||||
void Sink::add_drafts(int32_t n, int32_t accepted) {
|
||||
n_draft_.store(n_draft_.load(std::memory_order_relaxed) + n, std::memory_order_release);
|
||||
n_draft_acc_.store(n_draft_acc_.load(std::memory_order_relaxed) + accepted,
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
size_t Sink::read(SinkToken* out, size_t max) {
|
||||
const uint64_t t = tail_.load(std::memory_order_relaxed);
|
||||
const uint64_t h = head_.load(std::memory_order_acquire);
|
||||
|
||||
+31
-3
@@ -79,7 +79,9 @@ public:
|
||||
/* Terminal. Idempotent -- the first call wins, so a cancel racing a natural stop does not
|
||||
* produce two finish reasons. */
|
||||
void finish(Finish f);
|
||||
void fail(int rad_status);
|
||||
/* `why` says what failed, in a sentence a client can read; a string that outlives the sink
|
||||
* (a literal), or null. */
|
||||
void fail(int rad_status, const char* why = nullptr);
|
||||
|
||||
/* The scheduler polls this to learn that the client hung up, and frees the blocks (spec §14).
|
||||
* It is also told by IScheduler::cancel(); this is the cheap path that needs no lookup. */
|
||||
@@ -88,6 +90,14 @@ public:
|
||||
/* Admission accounting, set once by the scheduler when the prompt is placed. */
|
||||
void set_prompt_stats(int32_t n_prompt, int32_t n_cached);
|
||||
|
||||
/* THE FIRST TIME THE SCHEDULER GIVES THIS REQUEST A STEP: where its prompt phase starts, so
|
||||
* the time it waited in the queue is not counted as prefill. A preempted request admitted
|
||||
* again keeps the first mark. */
|
||||
void mark_admitted();
|
||||
/* A verify step's speculation for this request: `n` tokens proposed, `accepted` of them
|
||||
* taken. Summed over the request, the per-request half of /metrics' draft counters. */
|
||||
void add_drafts(int32_t n, int32_t accepted);
|
||||
|
||||
/* ------------------------------------------------------------------ consumer: HTTP */
|
||||
|
||||
/* Copies up to `max` tokens out. Returns how many. Never blocks. */
|
||||
@@ -100,6 +110,7 @@ public:
|
||||
bool done() const { return finish_.load(std::memory_order_acquire) != (int)Finish::None; }
|
||||
Finish finish_reason() const { return (Finish)finish_.load(std::memory_order_acquire); }
|
||||
int status() const { return status_.load(std::memory_order_acquire); }
|
||||
const char* why() const { return why_.load(std::memory_order_acquire); }
|
||||
bool overflowed() const { return overflow_.load(std::memory_order_acquire); }
|
||||
|
||||
/* The HTTP thread calls this when the peer disappears. It does NOT free anything itself --
|
||||
@@ -109,7 +120,14 @@ public:
|
||||
/* Timings, in steady-clock nanoseconds since the sink was constructed. -1 until observed. */
|
||||
int64_t t_first_token_ns() const { return t_first_.load(std::memory_order_acquire); }
|
||||
int64_t t_last_token_ns() const { return t_last_.load(std::memory_order_acquire); }
|
||||
int64_t t_admitted_ns() const { return t_admit_.load(std::memory_order_acquire); }
|
||||
int64_t age_ns() const;
|
||||
/* The steady clock at construction, which the times above count from: what puts two sinks'
|
||||
* times on one axis. */
|
||||
int64_t t_start_ns() const { return t_start_ns_; }
|
||||
|
||||
int64_t n_drafted() const { return n_draft_.load(std::memory_order_acquire); }
|
||||
int64_t n_draft_accepted() const { return n_draft_acc_.load(std::memory_order_acquire); }
|
||||
|
||||
int64_t n_produced() const { return (int64_t)head_.load(std::memory_order_acquire); }
|
||||
int32_t n_prompt() const { return n_prompt_.load(std::memory_order_acquire); }
|
||||
@@ -135,12 +153,16 @@ private:
|
||||
|
||||
std::atomic<int> finish_{(int)Finish::None};
|
||||
std::atomic<int> status_{RAD_OK};
|
||||
std::atomic<const char*> why_{nullptr};
|
||||
std::atomic<bool> overflow_{false};
|
||||
std::atomic<bool> cancel_{false};
|
||||
std::atomic<bool> quiesced_{false}; /* the producer will not touch this object again */
|
||||
|
||||
std::atomic<int64_t> t_first_{-1};
|
||||
std::atomic<int64_t> t_last_{-1};
|
||||
std::atomic<int64_t> t_admit_{-1};
|
||||
std::atomic<int64_t> n_draft_{0};
|
||||
std::atomic<int64_t> n_draft_acc_{0};
|
||||
int64_t t_start_ns_ = 0;
|
||||
|
||||
std::atomic<int32_t> n_prompt_{0};
|
||||
@@ -159,8 +181,8 @@ inline bool sink_push(void* s, int32_t token, float logprob = 0.0f) {
|
||||
inline void sink_finish(void* s, Finish f) {
|
||||
if (s) static_cast<Sink*>(s)->finish(f);
|
||||
}
|
||||
inline void sink_fail(void* s, int rad_status) {
|
||||
if (s) static_cast<Sink*>(s)->fail(rad_status);
|
||||
inline void sink_fail(void* s, int rad_status, const char* why = nullptr) {
|
||||
if (s) static_cast<Sink*>(s)->fail(rad_status, why);
|
||||
}
|
||||
inline bool sink_cancelled(const void* s) {
|
||||
return s && static_cast<const Sink*>(s)->cancel_requested();
|
||||
@@ -168,6 +190,12 @@ inline bool sink_cancelled(const void* s) {
|
||||
inline void sink_prompt_stats(void* s, int32_t n_prompt, int32_t n_cached) {
|
||||
if (s) static_cast<Sink*>(s)->set_prompt_stats(n_prompt, n_cached);
|
||||
}
|
||||
inline void sink_admitted(void* s) {
|
||||
if (s) static_cast<Sink*>(s)->mark_admitted();
|
||||
}
|
||||
inline void sink_drafts(void* s, int32_t n, int32_t accepted) {
|
||||
if (s) static_cast<Sink*>(s)->add_drafts(n, accepted);
|
||||
}
|
||||
|
||||
} /* namespace server */
|
||||
} /* namespace rad */
|
||||
+2
-1
@@ -105,7 +105,8 @@ struct ChatFormat {
|
||||
ChatValue string_value = ChatValue::Cdata; /* a string-typed argument: Raw or Cdata */
|
||||
ChatValue other_value = ChatValue::Json; /* any other type: Json */
|
||||
/* One newline at each end of a value is punctuation: the template writes the value on its own
|
||||
* lines, and exactly the first and last newline belong to the tags. */
|
||||
* lines, and exactly the first and last newline belong to the tags. A tag that ends with its
|
||||
* newline (Qwen's `>\n`) has written the first one already, and the value starts after it. */
|
||||
bool value_newlines = true;
|
||||
|
||||
/* The literal words that start constrained decoding of a call. Empty means no lazy grammar:
|
||||
|
||||
+349
-86
@@ -135,7 +135,12 @@ private:
|
||||
* * no whitespace before the value, any whitespace after it and inside it;
|
||||
* * a number may not be followed by a character that could have continued it -- `01`, `1.`,
|
||||
* `1-` are not numbers -- while `true` and `null` may be followed by anything;
|
||||
* * a string may hold raw control characters, and any escape but the JSON ones fails it.
|
||||
* * a raw control character fails a string, as the schema's string rule refuses one and JSON
|
||||
* has none: a client's JSON parser rejects a raw newline in a string. Any escape but the
|
||||
* JSON ones fails it too.
|
||||
*
|
||||
* A value accepted here is still checked whole by a JSON parser before it is written as JSON
|
||||
* (json_value_done): the grammar admits a few spellings a client cannot read.
|
||||
*
|
||||
* push() answers More while the bytes are still a JSON value or its trailing whitespace, Fail at
|
||||
* the first byte that cannot be, and Done at the first byte after a complete value -- which is
|
||||
@@ -163,6 +168,7 @@ public:
|
||||
}
|
||||
if (c == '"') { st_ = key_ ? KeyAfter : After; return More; }
|
||||
if (c == '\\') { st_ = StrEsc; return More; }
|
||||
if (c < 0x20) return Fail;
|
||||
if (c < 0x80) return More;
|
||||
if (!(c & 0x40)) return Fail;
|
||||
if (!(c & 0x20)) { need_ = 1; return More; }
|
||||
@@ -410,8 +416,22 @@ std::string_view trim_trailing_ws(std::string_view v) {
|
||||
*
|
||||
* The bytes of one value as the delimiters bound it, turned into its JSON encoding in the
|
||||
* arguments object. Two encodings: a STRING (quoted, escaped) and RAW JSON text, which is either
|
||||
* a value that parsed as JSON or a non-string argument that did not and is passed through --
|
||||
* with a Python-style container's single quotes normalised to double ones.
|
||||
* a value that parsed as JSON or a non-string argument that did not.
|
||||
*
|
||||
* A NON-STRING ARGUMENT THAT DID NOT PARSE IS MADE JSON, never passed through: the arguments
|
||||
* object is the one thing a client parses, and a single bare token in it makes the whole call
|
||||
* unreadable -- the server then cannot report it as a call at all. The grammar admits text for a
|
||||
* typed argument, and what these models write there is Python: `True`, `False`, `None`, and
|
||||
* single-quoted containers. A scalar is held while it could still be a Python literal -- `True`
|
||||
* as true, `False`, `None` as null -- or a JSON number or literal, up to kScalar bytes, and is
|
||||
* then written as that; anything else, or anything longer, streams as a JSON string of its text.
|
||||
* An empty one is null. A CONTAINER -- its first byte after at most a few blanks is `[` or `{` --
|
||||
* is held whole, because whether it is JSON once its quotes are normalised to double ones and its
|
||||
* Python literals to JSON's is known only at its end: a trailing comma, a bare word, an escape
|
||||
* JSON has not or a missing bracket each leave it no JSON, and then it is a JSON string of its
|
||||
* text. A value the reply was cut off inside is written as it arrived: it has no end to read it
|
||||
* to, and the call it is in is not complete. A value the JSON reader ACCEPTED (json_value_done)
|
||||
* is written as it is.
|
||||
*
|
||||
* The transforms touch only the ends of a value -- one newline at each end, the CDATA opener and
|
||||
* closer -- so the middle streams straight through and only a short head and tail are held: the
|
||||
@@ -421,12 +441,17 @@ public:
|
||||
enum Mode : uint8_t { String, Raw };
|
||||
static constexpr size_t kHead = 16; /* a newline pair and the CDATA opener, and the tail */
|
||||
static constexpr size_t kTail = 5; /* a newline pair and the CDATA closer */
|
||||
/* The longest scalar held while it could still be a literal or a number: a few blanks and
|
||||
* a 64-bit integer, or a double in its shortest round-trip spelling. */
|
||||
static constexpr size_t kScalar = 28;
|
||||
|
||||
void begin(Mode m, bool cdata, bool newlines, std::string& out) {
|
||||
mode_ = m; cdata_ = cdata; newlines_ = newlines;
|
||||
/* `lead`, `trail`: a newline at that end is punctuation. `json`: the value already parsed as
|
||||
* JSON, so a Raw scalar is written as it is. */
|
||||
void begin(Mode m, bool cdata, bool lead, bool trail, std::string& out, bool json = false) {
|
||||
mode_ = m; cdata_ = cdata; lead_ = lead; trail_ = trail; json_ = json; str_ = false;
|
||||
buf_.clear(); head_ = false; opened_ = false;
|
||||
raw_started_ = false; container_ = false;
|
||||
in_single_ = in_double_ = bs_ = false;
|
||||
container_ = false;
|
||||
scalar_.clear(); cont_.clear();
|
||||
if (mode_ == String) out += '"';
|
||||
}
|
||||
|
||||
@@ -436,7 +461,7 @@ public:
|
||||
if (buf_.size() < kHead) return;
|
||||
std::string_view v(buf_);
|
||||
size_t drop = 0;
|
||||
if (newlines_) drop = v.size() - strip_leading_newline(v).size();
|
||||
if (lead_) drop = v.size() - strip_leading_newline(v).size();
|
||||
if (cdata_ && v.compare(drop, kCdOpen.size(), kCdOpen) == 0) {
|
||||
opened_ = true;
|
||||
drop += kCdOpen.size();
|
||||
@@ -454,10 +479,11 @@ public:
|
||||
void finish(bool partial, std::string& out) {
|
||||
std::string_view v(buf_);
|
||||
if (!head_) {
|
||||
if (newlines_) v = strip_trailing_newline(strip_leading_newline(v));
|
||||
if (lead_) v = strip_leading_newline(v);
|
||||
if (trail_) v = strip_trailing_newline(v);
|
||||
if (cdata_) unwrap_cdata(v, partial);
|
||||
} else {
|
||||
if (newlines_) v = strip_trailing_newline(v);
|
||||
if (trail_) v = strip_trailing_newline(v);
|
||||
if (opened_) {
|
||||
if (v.size() >= kCdClose.size() &&
|
||||
v.compare(v.size() - kCdClose.size(), kCdClose.size(), kCdClose) == 0) {
|
||||
@@ -472,61 +498,164 @@ public:
|
||||
}
|
||||
}
|
||||
emit(v.data(), v.size(), out);
|
||||
if (bs_) { out += '\\'; bs_ = false; }
|
||||
if (mode_ == Raw && !json_) {
|
||||
if (container_) container_out(partial, out);
|
||||
else if (str_) { if (!partial) out += '"'; }
|
||||
else if (partial) { out += scalar_; scalar_.clear(); } /* cut off: as it arrived */
|
||||
else scalar_out(out);
|
||||
}
|
||||
buf_.clear();
|
||||
}
|
||||
|
||||
size_t held() const { return buf_.size() + (bs_ ? 1 : 0); }
|
||||
/* Bytes held while the value's ends are decided, and a scalar while it could be a literal. */
|
||||
size_t held() const { return buf_.size() + scalar_.size(); }
|
||||
/* A container, held whole until its end. */
|
||||
size_t held_container() const { return cont_.size(); }
|
||||
|
||||
private:
|
||||
void emit(const char* p, size_t n, std::string& out) {
|
||||
if (n == 0) return;
|
||||
if (mode_ == String) { json_escape_into(out, p, n); return; }
|
||||
if (!raw_started_) {
|
||||
raw_started_ = true;
|
||||
container_ = p[0] == '[' || p[0] == '{';
|
||||
}
|
||||
if (!container_) { out.append(p, n); return; }
|
||||
for (size_t i = 0; i < n; ++i) normalise(p[i], out);
|
||||
}
|
||||
|
||||
/* Python-style quoting to JSON, one character at a time: a single-quoted string becomes a
|
||||
* double-quoted one, with the quotes inside it re-escaped to match. A backslash is held until
|
||||
* the character after it arrives, since the pair is read together. */
|
||||
void normalise(char c, std::string& out) {
|
||||
if (bs_) {
|
||||
bs_ = false;
|
||||
if (in_single_) {
|
||||
if (c == '\'') { out += '\''; return; }
|
||||
if (c == '"') { out += "\\\""; return; }
|
||||
out += '\\'; out += c; return;
|
||||
}
|
||||
if (in_double_) { out += '\\'; out += c; return; }
|
||||
out += '\\';
|
||||
/* Outside a string the backslash stands alone and the next character is read
|
||||
* normally. */
|
||||
} else if (c == '\\') {
|
||||
bs_ = true;
|
||||
if (json_) { out.append(p, n); return; }
|
||||
if (str_) { json_escape_into(out, p, n); return; }
|
||||
if (container_) { cont_.append(p, n); return; }
|
||||
scalar_.append(p, n);
|
||||
size_t ws = 0;
|
||||
while (ws < scalar_.size() && is_ws((unsigned char)scalar_[ws])) ++ws;
|
||||
if (ws <= 4 && ws < scalar_.size() && (scalar_[ws] == '[' || scalar_[ws] == '{')) {
|
||||
container_ = true;
|
||||
cont_.assign(scalar_, ws, std::string::npos);
|
||||
scalar_.clear();
|
||||
return;
|
||||
}
|
||||
if (c == '"') {
|
||||
if (in_single_) out += "\\\"";
|
||||
else { in_double_ = !in_double_; out += '"'; }
|
||||
} else if (c == '\'') {
|
||||
if (in_double_) out += '\'';
|
||||
else if (in_single_) { in_single_ = false; out += '"'; }
|
||||
else { in_single_ = true; out += '"'; }
|
||||
} else {
|
||||
out += c;
|
||||
if (scalar_.size() > kScalar || !scalar_prefix(scalar_)) {
|
||||
out += '"';
|
||||
json_escape_into(out, scalar_.data(), scalar_.size());
|
||||
scalar_.clear();
|
||||
str_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Could `v` still become a Python or JSON literal or a JSON number, after at most a few
|
||||
* bytes of blanks on either side? */
|
||||
static bool scalar_prefix(std::string_view v) {
|
||||
size_t ws = 0;
|
||||
while (ws < v.size() && is_ws((unsigned char)v[ws])) ++ws;
|
||||
if (ws > 4) return false;
|
||||
v.remove_prefix(ws);
|
||||
size_t tw = 0;
|
||||
while (tw < v.size() && is_ws((unsigned char)v[v.size() - 1 - tw])) ++tw;
|
||||
if (tw > 4) return false;
|
||||
if (tw > 0 && tw == v.size()) return true;
|
||||
v.remove_suffix(tw);
|
||||
if (v.empty()) return true;
|
||||
for (std::string_view l : { std::string_view("True"), std::string_view("False"),
|
||||
std::string_view("None"), std::string_view("true"),
|
||||
std::string_view("false"), std::string_view("null") })
|
||||
if (v.size() <= l.size() && l.compare(0, v.size(), v) == 0) return true;
|
||||
return number_prefix(v);
|
||||
}
|
||||
|
||||
/* A prefix of -?(0|[1-9][0-9]*)(.[0-9]+)?([eE][+-]?[0-9]+)? */
|
||||
static bool number_prefix(std::string_view v) {
|
||||
size_t i = 0;
|
||||
if (i < v.size() && v[i] == '-') ++i;
|
||||
if (i == v.size()) return true;
|
||||
if (v[i] == '0') ++i;
|
||||
else if (v[i] >= '1' && v[i] <= '9') while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
else return false;
|
||||
if (i < v.size() && v[i] == '.') {
|
||||
++i;
|
||||
while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
}
|
||||
if (i < v.size() && (v[i] == 'e' || v[i] == 'E')) {
|
||||
++i;
|
||||
if (i < v.size() && (v[i] == '+' || v[i] == '-')) ++i;
|
||||
while (i < v.size() && std::isdigit((unsigned char)v[i])) ++i;
|
||||
}
|
||||
return i == v.size();
|
||||
}
|
||||
|
||||
/* A Python literal is JSON's under another spelling; anything else is as written. */
|
||||
static const char* json_literal(std::string_view w) {
|
||||
if (w == "True") return "true";
|
||||
if (w == "False") return "false";
|
||||
if (w == "None") return "null";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void scalar_out(std::string& out) {
|
||||
std::string_view v = trim_trailing_ws(scalar_);
|
||||
while (!v.empty() && is_ws((unsigned char)v.front())) v.remove_prefix(1);
|
||||
if (v.empty()) out += "null";
|
||||
else if (const char* lit = json_literal(v)) out += lit;
|
||||
else if (nlohmann::json::accept(v)) out.append(v.data(), v.size());
|
||||
else out += json_quote(scalar_);
|
||||
scalar_.clear();
|
||||
}
|
||||
|
||||
/* The held container, normalised; JSON if that made it JSON, else a JSON string of its text.
|
||||
* One the reply was cut off inside is written normalised as far as it arrived. */
|
||||
void container_out(bool partial, std::string& out) {
|
||||
std::string j;
|
||||
j.reserve(cont_.size() + 8);
|
||||
normalise(cont_, j);
|
||||
if (partial || nlohmann::json::accept(j)) out += j;
|
||||
else out += json_quote(cont_);
|
||||
cont_.clear();
|
||||
}
|
||||
|
||||
/* Python-style quoting to JSON: a single-quoted string becomes a double-quoted one, with the
|
||||
* quotes inside it re-escaped to match and its raw control characters escaped, and a bare
|
||||
* Python literal outside every string is respelled as JSON's. Whatever is no JSON after that
|
||||
* is left as written, for the JSON parser to refuse. */
|
||||
static void normalise(std::string_view v, std::string& out) {
|
||||
bool in_single = false, in_double = false;
|
||||
for (size_t i = 0; i < v.size(); ++i) {
|
||||
const char c = v[i];
|
||||
if (in_single || in_double) {
|
||||
if (c == '\\' && i + 1 < v.size()) {
|
||||
const char d = v[++i];
|
||||
if (d == '\'') out += '\''; /* `\'` is a quote in either quoting */
|
||||
else if (in_single && d == '"') out += "\\\"";
|
||||
else { out += '\\'; out += d; }
|
||||
} else if (c == (in_single ? '\'' : '"')) {
|
||||
in_single = in_double = false;
|
||||
out += '"';
|
||||
} else if (c == '"') {
|
||||
out += "\\\"";
|
||||
} else if ((unsigned char)c < 0x20) {
|
||||
/* A raw line break or tab inside a string, which JSON spells as an escape. */
|
||||
json_escape_into(out, &c, 1);
|
||||
} else {
|
||||
out += c;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (std::isalnum((unsigned char)c) || c == '_') {
|
||||
size_t e = i + 1;
|
||||
while (e < v.size() && (std::isalnum((unsigned char)v[e]) || v[e] == '_')) ++e;
|
||||
const std::string_view w = v.substr(i, e - i);
|
||||
if (const char* lit = json_literal(w)) out += lit;
|
||||
else out.append(w.data(), w.size());
|
||||
i = e - 1;
|
||||
continue;
|
||||
}
|
||||
if (c == '\'') in_single = true;
|
||||
else if (c == '"') in_double = true;
|
||||
out += c == '\'' ? '"' : c;
|
||||
}
|
||||
}
|
||||
|
||||
Mode mode_ = String;
|
||||
bool cdata_ = true, newlines_ = true;
|
||||
bool cdata_ = true, lead_ = true, trail_ = true;
|
||||
std::string buf_;
|
||||
bool head_ = false, opened_ = false;
|
||||
bool raw_started_ = false, container_ = false;
|
||||
bool in_single_ = false, in_double_ = false, bs_ = false;
|
||||
bool container_ = false;
|
||||
std::string scalar_; /* a scalar while it could still be a Python literal */
|
||||
std::string cont_; /* a container, held whole */
|
||||
bool json_ = false; /* the value parsed as JSON: written as it is */
|
||||
bool str_ = false; /* the scalar is no literal and streams as a JSON string */
|
||||
};
|
||||
|
||||
/* ================================================================== the answer text
|
||||
@@ -562,19 +691,25 @@ public:
|
||||
/* The exact trim: trailing spaces and newlines, then the first terminator in the list that
|
||||
* ends what is left. */
|
||||
void finish(std::string& full) {
|
||||
while (!pend_.empty() && (pend_.back() == '\n' || pend_.back() == ' ')) pend_.pop_back();
|
||||
if (list_)
|
||||
for (const std::string& t : *list_)
|
||||
if (!t.empty() && pend_.size() >= t.size() &&
|
||||
pend_.compare(pend_.size() - t.size(), t.size(), t) == 0) {
|
||||
pend_.erase(pend_.size() - t.size());
|
||||
break;
|
||||
}
|
||||
trim(pend_);
|
||||
full += pend_;
|
||||
pend_.clear();
|
||||
}
|
||||
|
||||
size_t held_space() const { return std::min(ws_, pend_.size()); }
|
||||
/* What is held: the content after `full` so far, untrimmed. */
|
||||
const std::string& pending() const { return pend_; }
|
||||
/* The same trim, on a whole text. */
|
||||
void trim(std::string& s) const {
|
||||
while (!s.empty() && (s.back() == '\n' || s.back() == ' ')) s.pop_back();
|
||||
if (list_)
|
||||
for (const std::string& t : *list_)
|
||||
if (!t.empty() && s.size() >= t.size() &&
|
||||
s.compare(s.size() - t.size(), t.size(), t) == 0) {
|
||||
s.erase(s.size() - t.size());
|
||||
break;
|
||||
}
|
||||
}
|
||||
size_t held_other() const { return pend_.size() - held_space(); }
|
||||
|
||||
private:
|
||||
@@ -604,6 +739,9 @@ struct ReplyFormat::Impl {
|
||||
* model wrote it unconstrained, and its argument tags are read with the whitespace around
|
||||
* them optional -- as its name and its close are. */
|
||||
std::string name_end_core, value_core;
|
||||
/* call_close's core, when it can be told apart from what else may follow inside a call: a
|
||||
* wrapped call whose own close is missing is ended by its wrapper's. */
|
||||
std::string cc_core;
|
||||
Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose;
|
||||
size_t longest = 0; /* the longest delimiter */
|
||||
};
|
||||
@@ -651,7 +789,13 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr<const ReplyFormat>
|
||||
split_ws(f.arg_value_suffix, &m.value_core, &trail);
|
||||
m.arg_name_loose.build({ m.name_end_core });
|
||||
m.value_loose.build({ m.value_core });
|
||||
m.junk.build({ f.arg_prefix, m.end_core });
|
||||
split_ws(f.call_close, &m.cc_core, &trail);
|
||||
auto apart = [](const std::string& a, const std::string& b) {
|
||||
return a.find(b) == std::string::npos && b.find(a) == std::string::npos;
|
||||
};
|
||||
if (!apart(m.cc_core, f.arg_prefix) || !apart(m.cc_core, m.end_core)) m.cc_core.clear();
|
||||
if (m.cc_core.empty()) m.junk.build({ f.arg_prefix, m.end_core });
|
||||
else m.junk.build({ f.arg_prefix, m.end_core, m.cc_core });
|
||||
}
|
||||
const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open,
|
||||
&f.call_close, &f.name_prefix, &f.name_suffix,
|
||||
@@ -701,7 +845,22 @@ size_t ReplyParser::hold_bound() const {
|
||||
size_t term = 0;
|
||||
for (const std::string& t : impl_->terminators) term = std::max(term, t.size());
|
||||
return impl_->fmt->impl().longest + std::max(term, kFenceOpen.size()) + ValueOut::kHead + 1 +
|
||||
3 * 3;
|
||||
3 * 3 + ValueOut::kScalar;
|
||||
}
|
||||
|
||||
ReasoningMarkers ReplyParser::reasoning() const {
|
||||
const ReplyFormat::Impl& F = impl_->fmt->impl();
|
||||
ReasoningMarkers m;
|
||||
if (!F.f.has_reasoning()) return m;
|
||||
m.open = F.open_core;
|
||||
m.close = F.close_core;
|
||||
/* `tail` starts at the opener when the prompt holds one, and a prompt that also closed the
|
||||
* block -- thinking turned off -- leaves the reply after it. With no opener at all the stream
|
||||
* starts in the block (after_lead). */
|
||||
const std::string& t = impl_->tail;
|
||||
m.starts_open = F.open_core.empty() ||
|
||||
(!t.empty() && t.find(F.close_core, F.open_core.size()) == std::string::npos);
|
||||
return m;
|
||||
}
|
||||
|
||||
/* Read the tools the way the grammar generator reads them, so a name or a type means the same
|
||||
@@ -725,6 +884,9 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse
|
||||
info.resolve_refs(params);
|
||||
std::vector<std::string> optional;
|
||||
for (const auto& [pname, pschema] : properties.items()) {
|
||||
/* An optional argument no value satisfies has no arm in the grammar, which reads
|
||||
* it by the undeclared arm, as text (chatfmt.cpp); so does the parser. */
|
||||
if (!required.count(pname) && info.unsatisfiable(pschema)) continue;
|
||||
Param p;
|
||||
p.typed = F.f.other_value == ChatValue::Json && !info.resolves_to_string(pschema);
|
||||
t.has_props = true;
|
||||
@@ -904,9 +1066,16 @@ struct ReplyStream::Impl {
|
||||
size_t sent_r = 0, sent_c = 0, sent_a = 0;
|
||||
int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */
|
||||
|
||||
/* bytes to read again, ahead of the rest */
|
||||
struct Seg { const char* p; size_t n; };
|
||||
/* bytes to read again, ahead of the rest. Bytes read again are always the last ones read,
|
||||
* so each segment knows where its first byte is in the stream: the generation prompt's tail,
|
||||
* then the reply. */
|
||||
struct Seg { const char* p; size_t n; size_t at; };
|
||||
std::vector<Seg> stack;
|
||||
const char* seg_p = nullptr; /* the segment being read */
|
||||
size_t seg_at = 0; /* and where its first byte is in the stream */
|
||||
size_t fed = 0; /* the bytes the stream has been given */
|
||||
size_t att_at = 0; /* where the opener being tried begins */
|
||||
size_t here(const char* p) const { return seg_at + (size_t)(p - seg_p); }
|
||||
std::deque<std::string> owned;
|
||||
std::string refeed;
|
||||
|
||||
@@ -1090,6 +1259,7 @@ struct ReplyStream::Impl {
|
||||
st = origin;
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
lhold.clear();
|
||||
if (origin == St::Think) think_out(att.data(), 1);
|
||||
else text_out(att.data(), 1);
|
||||
read_again(std::string_view(att).substr(1));
|
||||
@@ -1105,6 +1275,9 @@ struct ReplyStream::Impl {
|
||||
0, name.size() - F.ns_core.size()));
|
||||
ReplyCall c;
|
||||
c.name.assign(nm);
|
||||
c.at = att_at >= P.tail.size() ? att_at - P.tail.size() : 0;
|
||||
c.content_at = msg.content.size();
|
||||
c.content_held = content.pending();
|
||||
msg.calls.push_back(std::move(c));
|
||||
sent_a = 0;
|
||||
cur = -1;
|
||||
@@ -1146,6 +1319,16 @@ struct ReplyStream::Impl {
|
||||
else after_loose_call();
|
||||
}
|
||||
|
||||
/* The wrapper's close inside a wrapped call, whose own close is missing: it ends the call
|
||||
* and the wrapper both. Read leniently -- the grammar requires call_end first -- but as the
|
||||
* close it is, or the next call's arguments would be read into this one. */
|
||||
void end_call_at_close() {
|
||||
lenient();
|
||||
end_call();
|
||||
if (loose) after_loose_call();
|
||||
else st = St::AfterCall;
|
||||
}
|
||||
|
||||
/* A loose call whose argument name runs into a tag was a call only as far as its arguments
|
||||
* before it: the call ends there, and the argument's opener and all after it are content. */
|
||||
void end_loose_call_at_arg(bool closed_name) {
|
||||
@@ -1174,21 +1357,40 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* The argument name is complete. */
|
||||
void begin_value() {
|
||||
const std::string_view nm = trim_arg_name(
|
||||
std::string_view nm = trim_arg_name(
|
||||
std::string_view(name).substr(0, name.size() - name_end().size()));
|
||||
param = nullptr;
|
||||
if (const Tool* t = cur_tool()) {
|
||||
auto it = t->params.find(std::string(nm));
|
||||
const bool exact = nm.size() + name_end().size() == name.size();
|
||||
/* The grammar binds a declared name to its own arm by the raw spelling; a name that
|
||||
* only trims to a declared one is read by the generic arm, as text. */
|
||||
if (it != t->params.end() && exact) {
|
||||
param = &it->second;
|
||||
} else if (it == t->params.end() && exact) {
|
||||
/* A name that repeats its own tag's opening, `<parameter=parameter=command>`: the
|
||||
* grammar's undeclared arm takes it, and the call would reach the tool without
|
||||
* the argument it names. Read as that declared argument, leniently. */
|
||||
const std::string_view rep = std::string_view(F.f.arg_prefix).substr(1);
|
||||
std::string_view rest = nm;
|
||||
while (!rep.empty() && rest.size() > rep.size() &&
|
||||
rest.compare(0, rep.size(), rep) == 0)
|
||||
rest.remove_prefix(rep.size());
|
||||
if (rest.size() < nm.size()) {
|
||||
auto jt = t->params.find(std::string(rest));
|
||||
if (jt != t->params.end()) {
|
||||
lenient();
|
||||
nm = rest;
|
||||
param = &jt->second;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
std::string key = argc > 0 ? "," : "";
|
||||
key += json_quote(nm);
|
||||
key += ':';
|
||||
args_out(key);
|
||||
++argc;
|
||||
param = nullptr;
|
||||
if (const Tool* t = cur_tool()) {
|
||||
auto it = t->params.find(std::string(nm));
|
||||
/* The grammar binds a declared name to its own arm by the raw spelling; a name that
|
||||
* only trims to a declared one is read by the generic arm, as text. */
|
||||
if (it != t->params.end() && nm.size() + name_end().size() == name.size())
|
||||
param = &it->second;
|
||||
}
|
||||
name.clear();
|
||||
if (param && param->typed) {
|
||||
js.reset();
|
||||
@@ -1207,9 +1409,21 @@ struct ReplyStream::Impl {
|
||||
/* A CDATA section is punctuation around any value the format lets carry one, typed or not. */
|
||||
bool cdata() const { return F.f.string_value == ChatValue::Cdata; }
|
||||
|
||||
/* The newline that opens a value is punctuation unless the tag before it has written it
|
||||
* already: Qwen's `<parameter=NAME>\n` ends with the newline the template puts before the
|
||||
* value, and a second one is the value's own. */
|
||||
bool lead_newline() const {
|
||||
const std::string& ne = name_end();
|
||||
return F.f.value_newlines && (ne.empty() || ne.back() != '\n');
|
||||
}
|
||||
|
||||
void begin_value_out(ValueOut::Mode m, bool json = false) {
|
||||
val.begin(m, cdata(), lead_newline(), F.f.value_newlines, scratch, json);
|
||||
}
|
||||
|
||||
void start_text_value(ValueOut::Mode m) {
|
||||
vmode = m;
|
||||
val.begin(m, cdata(), F.f.value_newlines, scratch);
|
||||
begin_value_out(m);
|
||||
flush_scratch();
|
||||
ds = 0;
|
||||
hold.clear();
|
||||
@@ -1217,9 +1431,19 @@ struct ReplyStream::Impl {
|
||||
}
|
||||
|
||||
/* A JSON-typed value that parsed and then met its suffix: the value is the JSON text and the
|
||||
* whitespace after it. */
|
||||
* whitespace after it. What a client's JSON parser takes is a little narrower than what
|
||||
* JsonScan reads as the grammar's JSON -- a number past a double's range (`1e400`), an
|
||||
* unpaired UTF-16 surrogate escape, a vertical tab or form feed after the value -- and such a
|
||||
* value is read by the grammar's other arm, as text, so the arguments stay JSON. */
|
||||
void json_value_done(std::string_view text) {
|
||||
val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch);
|
||||
if (!nlohmann::json::accept(text)) {
|
||||
begin_value_out(ValueOut::Raw);
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
return;
|
||||
}
|
||||
begin_value_out(ValueOut::Raw, /*json=*/true);
|
||||
val.add(text.data(), text.size(), scratch);
|
||||
val.finish(false, scratch);
|
||||
flush_scratch();
|
||||
@@ -1260,7 +1484,11 @@ struct ReplyStream::Impl {
|
||||
const Dfa& d = P.breaks ? F.think_breaks : F.think;
|
||||
p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); });
|
||||
if (hit == 0) { trail = 0; st = St::ThinkCloseWs; }
|
||||
else if (hit > 0) { att = d.pattern(hit); begin_attempt(St::Think); }
|
||||
else if (hit > 0) {
|
||||
att = d.pattern(hit);
|
||||
att_at = here(p) - att.size();
|
||||
begin_attempt(St::Think);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
@@ -1276,7 +1504,10 @@ struct ReplyStream::Impl {
|
||||
return e;
|
||||
}
|
||||
p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit >= 0) begin_text_attempt(hit);
|
||||
if (hit >= 0) {
|
||||
att_at = here(p) - F.openers[(size_t)hit].size();
|
||||
begin_text_attempt(hit);
|
||||
}
|
||||
return p;
|
||||
|
||||
case St::OpenCoTail:
|
||||
@@ -1407,9 +1638,12 @@ struct ReplyStream::Impl {
|
||||
const char c = *p;
|
||||
const std::string& ap = F.f.arg_prefix;
|
||||
const std::string& fc = F.end_core;
|
||||
const std::string& cc = F.cc_core;
|
||||
const bool a_ok = lpos < ap.size() && ap[lpos] == c && ap.compare(0, lpos, lhold) == 0;
|
||||
const bool f_ok = lpos < fc.size() && fc[lpos] == c && fc.compare(0, lpos, lhold) == 0;
|
||||
if (!a_ok && !f_ok) {
|
||||
const bool c_ok = wrapped && lpos < cc.size() && cc[lpos] == c &&
|
||||
cc.compare(0, lpos, lhold) == 0;
|
||||
if (!a_ok && !f_ok && !c_ok) {
|
||||
lenient();
|
||||
st = St::Junk;
|
||||
ds = 0;
|
||||
@@ -1423,6 +1657,7 @@ struct ReplyStream::Impl {
|
||||
++lpos;
|
||||
if (a_ok && lpos == ap.size()) { start_arg(); return p + 1; }
|
||||
if (f_ok && lpos == fc.size()) { finish_call_strictness(); end_core_done(); return p + 1; }
|
||||
if (c_ok && lpos == cc.size()) { end_call_at_close(); return p + 1; }
|
||||
return p + 1;
|
||||
}
|
||||
|
||||
@@ -1503,6 +1738,8 @@ struct ReplyStream::Impl {
|
||||
p = scan(F.junk, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); });
|
||||
if (hit == 0) start_arg();
|
||||
else if (hit == 1) end_core_done();
|
||||
else if (hit == 2 && wrapped) end_call_at_close();
|
||||
else if (hit == 2) text_out(F.cc_core.data(), F.cc_core.size());
|
||||
return p;
|
||||
|
||||
case St::AfterEnd:
|
||||
@@ -1658,20 +1895,25 @@ struct ReplyStream::Impl {
|
||||
|
||||
/* ------------------------------------------------------------ driving */
|
||||
|
||||
void run(std::string_view in) {
|
||||
stack.push_back({ in.data(), in.size() });
|
||||
/* Read `in`, whose first byte is at `at` in the stream. */
|
||||
void run(std::string_view in, size_t at) {
|
||||
stack.push_back({ in.data(), in.size(), at });
|
||||
while (!stack.empty()) {
|
||||
Seg s = stack.back();
|
||||
stack.pop_back();
|
||||
seg_p = s.p;
|
||||
seg_at = s.at;
|
||||
const char* p = s.p;
|
||||
const char* e = s.p + s.n;
|
||||
while (p < e) {
|
||||
p = step(p, e);
|
||||
if (!refeed.empty()) {
|
||||
if (p < e) stack.push_back({ p, (size_t)(e - p) });
|
||||
const size_t now = here(p);
|
||||
if (p < e) stack.push_back({ p, (size_t)(e - p), now });
|
||||
owned.push_back(std::move(refeed));
|
||||
refeed.clear();
|
||||
stack.push_back({ owned.back().data(), owned.back().size() });
|
||||
const size_t n = owned.back().size();
|
||||
stack.push_back({ owned.back().data(), n, now >= n ? now - n : 0 });
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -1682,7 +1924,13 @@ struct ReplyStream::Impl {
|
||||
void feed_tail() {
|
||||
if (fed_tail) return;
|
||||
fed_tail = true;
|
||||
if (!P.tail.empty()) run(P.tail);
|
||||
if (!P.tail.empty()) run(P.tail, 0);
|
||||
fed = P.tail.size();
|
||||
}
|
||||
|
||||
void feed(std::string_view bytes) {
|
||||
run(bytes, fed);
|
||||
fed += bytes.size();
|
||||
}
|
||||
|
||||
/* Would the grammar still be waiting for more, rather than have failed, on what an opener
|
||||
@@ -1718,7 +1966,7 @@ struct ReplyStream::Impl {
|
||||
fail_attempt();
|
||||
std::string again = std::move(refeed);
|
||||
refeed.clear();
|
||||
run(again);
|
||||
run(again, fed >= again.size() ? fed - again.size() : 0);
|
||||
}
|
||||
switch (st) {
|
||||
case St::OpenWs: case St::OpenPrefix: case St::OpenName: case St::OpenTail:
|
||||
@@ -1742,7 +1990,7 @@ struct ReplyStream::Impl {
|
||||
flush_scratch();
|
||||
break;
|
||||
case St::ValJson:
|
||||
val.begin(ValueOut::Raw, cdata(), F.f.value_newlines, scratch);
|
||||
begin_value_out(ValueOut::Raw);
|
||||
val.add(vheld.data(), vheld.size(), scratch);
|
||||
val.finish(true, scratch);
|
||||
flush_scratch();
|
||||
@@ -1778,7 +2026,7 @@ void ReplyStream::feed(std::string_view bytes, std::vector<ReplyEvent>* out) {
|
||||
if (m.finished) return;
|
||||
m.out = out;
|
||||
m.feed_tail();
|
||||
if (!bytes.empty()) m.run(bytes);
|
||||
if (!bytes.empty()) m.feed(bytes);
|
||||
if (m.cur >= 0) m.publish(m.cur, false);
|
||||
m.out = nullptr;
|
||||
}
|
||||
@@ -1794,16 +2042,31 @@ void ReplyStream::finish(std::vector<ReplyEvent>* out) {
|
||||
}
|
||||
|
||||
const ReplyMessage& ReplyStream::message() const { return impl_->msg; }
|
||||
|
||||
std::string ReplyStream::content_with_open_call(std::string_view reply) const {
|
||||
const Impl& m = *impl_;
|
||||
if (m.msg.calls.empty() || m.msg.calls.back().closed) return m.msg.content;
|
||||
const ReplyCall& c = m.msg.calls.back();
|
||||
std::string s(m.msg.content, 0, std::min(c.content_at, m.msg.content.size()));
|
||||
s += c.content_held;
|
||||
if (c.at < reply.size()) s.append(reply.substr(c.at));
|
||||
m.content.trim(s);
|
||||
return s;
|
||||
}
|
||||
|
||||
bool ReplyStream::strict() const { return impl_->strict; }
|
||||
|
||||
ReplyHeld ReplyStream::held() const {
|
||||
const Impl& m = *impl_;
|
||||
ReplyHeld h;
|
||||
h.delimiter = m.hold.size() + m.lhold.size() + m.val.held() + m.content.held_other() +
|
||||
/* A loose call's first argument name is read into lhold too, and is a tag name: its bytes
|
||||
* are in `att` already, counted as structure. */
|
||||
const size_t lhold = m.st == St::OpenPeekArg ? 0 : m.lhold.size();
|
||||
h.delimiter = m.hold.size() + lhold + m.val.held() + m.content.held_other() +
|
||||
(m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) +
|
||||
(m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a);
|
||||
h.space = m.content.held_space() + m.think_pend.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size();
|
||||
h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container();
|
||||
return h;
|
||||
}
|
||||
|
||||
|
||||
+25
-1
@@ -45,7 +45,9 @@
|
||||
* * a tag's own name while it is being read, since a name is only a name once it is closed;
|
||||
* * a JSON-typed argument value until its closing delimiter: `30` and `30 seconds` differ from
|
||||
* their first byte (a number, or the string "30 seconds"), so the value is emitted whole once
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there.
|
||||
* its type is known. A value that stops being JSON part-way is streamed as text from there,
|
||||
* except a container (`[`, `{`), which is held to its end: only there is it known whether
|
||||
* it is JSON once its Python quoting is normalised, or the JSON string of its text.
|
||||
*
|
||||
* Streaming emits in the reply's order; a call's arguments are streamed as they are parsed. */
|
||||
#pragma once
|
||||
@@ -81,6 +83,12 @@ struct ReplyCall {
|
||||
std::string name;
|
||||
std::string arguments; /* JSON text, as the OpenAI API carries it */
|
||||
bool closed = false;
|
||||
/* Where the call's text begins in the reply, and the content up to it: `content_at` bytes
|
||||
* of the message's content and the untrimmed whitespace held after them. What the content
|
||||
* is when the call is read as text (ReplyStream::content_with_open_call). */
|
||||
size_t at = 0;
|
||||
size_t content_at = 0;
|
||||
std::string content_held;
|
||||
};
|
||||
|
||||
/* A reply, taken apart. After finish() it is the whole reply; before, what has been emitted. */
|
||||
@@ -118,6 +126,14 @@ struct ReplyOptions {
|
||||
|
||||
class ReplyStream;
|
||||
|
||||
/* The reasoning block as one request's reply meets it: its markers with the optional whitespace
|
||||
* around them trimmed, and whether the reply starts inside it -- the generation prompt opened it,
|
||||
* or the format has no opener. Empty `close` is a format with no reasoning block. */
|
||||
struct ReasoningMarkers {
|
||||
std::string open, close;
|
||||
bool starts_open = false;
|
||||
};
|
||||
|
||||
/* A format compiled once: its automata and its delimiters. Shared by every request. */
|
||||
class ReplyFormat {
|
||||
public:
|
||||
@@ -150,6 +166,9 @@ public:
|
||||
* prefix in each place one can be pending at once, a value's undecided head, and an
|
||||
* unfinished UTF-8 sequence on each output. A constant of the format, not of the reply. */
|
||||
size_t hold_bound() const;
|
||||
/* Read from the generation prompt exactly as a stream's first bytes are, so a reply this
|
||||
* says starts in the block is one the stream reads as reasoning from its first byte. */
|
||||
ReasoningMarkers reasoning() const;
|
||||
|
||||
struct Impl;
|
||||
const Impl& impl() const { return *impl_; }
|
||||
@@ -168,6 +187,11 @@ public:
|
||||
void finish(std::vector<ReplyEvent>* out);
|
||||
|
||||
const ReplyMessage& message() const;
|
||||
/* After finish(): the content were the last call text, when the reply ended inside that call
|
||||
* -- the content before it, then the call as `reply` (every byte fed) spells it, trimmed at
|
||||
* the end as content is. A call that never closed cannot be reported as a call, and its text
|
||||
* is what the model wrote. The message's content when the last call closed, or there is none. */
|
||||
std::string content_with_open_call(std::string_view reply) const;
|
||||
/* False once the reply left the format's grammar and was read by a recovery rule. */
|
||||
bool strict() const;
|
||||
ReplyHeld held() const;
|
||||
|
||||
+66
-22
@@ -69,16 +69,28 @@ std::string byte_encode(std::string_view raw) {
|
||||
* user-defined token spelt in real text needs; it cannot be confused with a mapped one because
|
||||
* the mapped set is closed. */
|
||||
std::string byte_decode(const std::string& enc) {
|
||||
/* Unit by unit, a unit being what the lead byte says, cut short at the end. A unit is mapped
|
||||
* iff it is exactly some byte's spelling in the alphabet -- one ASCII byte, or a two-byte
|
||||
* sequence (lead C2..DF, a continuation byte) whose code point is below U+0144 -- so the
|
||||
* code point table answers what a lookup of the unit's bytes in `from` would, without
|
||||
* building a string per character. Anything else is passed through as its own bytes. */
|
||||
const ByteLevelAlphabet& a = alphabet();
|
||||
const uint8_t* p = (const uint8_t*)enc.data();
|
||||
const size_t n = enc.size();
|
||||
std::string out;
|
||||
out.reserve(enc.size());
|
||||
for (size_t i = 0; i < enc.size(); ) {
|
||||
const size_t n = std::min(unicode_len_utf8(enc[i]), enc.size() - i);
|
||||
const std::string one = enc.substr(i, n);
|
||||
auto it = a.from.find(one);
|
||||
if (it != a.from.end()) out += (char)it->second;
|
||||
else out += one;
|
||||
i += n;
|
||||
out.reserve(n);
|
||||
for (size_t i = 0; i < n; ) {
|
||||
const size_t len = std::min(unicode_len_utf8(enc[i]), n - i);
|
||||
int b = -1;
|
||||
if (len == 1 && p[i] < 0x80) {
|
||||
b = a.byte_of_cpt[p[i]];
|
||||
} else if (len == 2 && p[i] >= 0xC2 && (p[i + 1] & 0xC0) == 0x80) {
|
||||
const uint32_t c = ((uint32_t)(p[i] & 0x1F) << 6) | (p[i + 1] & 0x3F);
|
||||
if (c < 0x144) b = a.byte_of_cpt[c];
|
||||
}
|
||||
if (b >= 0) out += (char)b;
|
||||
else out.append(enc, i, len);
|
||||
i += len;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -1312,8 +1324,6 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
|
||||
if (!v_ || !v_->ready()) return RAD_E_STATE;
|
||||
const TokEncoder& e = *v_->enc_;
|
||||
|
||||
if (add_special && v_->add_bos() && v_->bos() >= 0) out.push_back(v_->bos());
|
||||
|
||||
/* Special-token partitioning. The text is cut into (raw, token, raw, token, ...) around any
|
||||
* declared special token that appears literally, before any other step touches it, because a
|
||||
* special token is not something the pre-tokeniser is allowed to split.
|
||||
@@ -1324,6 +1334,19 @@ int Tokenizer::encode(std::string_view text, std::vector<int32_t>& out,
|
||||
std::vector<SpecialFrag> frags;
|
||||
e.specials.split(text, parse_special, frags);
|
||||
|
||||
/* A text that already opens with BOS gets no second one. A client that renders its own chat
|
||||
* template writes the template's BOS into the prompt, and a doubled BOS is a sequence the
|
||||
* model never saw in training. */
|
||||
if (add_special && v_->add_bos() && v_->bos() >= 0) {
|
||||
int32_t first = -1;
|
||||
for (const SpecialFrag& f : frags) {
|
||||
if (f.id < 0 && f.len == 0) continue;
|
||||
first = f.id;
|
||||
break;
|
||||
}
|
||||
if (first != v_->bos()) out.push_back(v_->bos());
|
||||
}
|
||||
|
||||
EncodeScratch sc;
|
||||
WordCache words;
|
||||
for (const SpecialFrag& f : frags) {
|
||||
@@ -1557,14 +1580,15 @@ std::string utf8_sanitize(std::string_view s) {
|
||||
std::string Detokenizer::push(int32_t token) {
|
||||
if (!v_ || !v_->ready() || stopped_) return {};
|
||||
|
||||
Tokenizer t;
|
||||
/* Constructing a Tokenizer per push looks wasteful and is not: it holds a shared_ptr and
|
||||
* nothing else, and piece() is a pure function of the vocab. Keeping one as a member would
|
||||
* make Detokenizer non-copyable for no gain. */
|
||||
if (t.init(std::const_pointer_cast<Vocab>(std::const_pointer_cast<const Vocab>(v_))) < 0)
|
||||
return {};
|
||||
|
||||
std::string p = t.piece(token, render_special_ || preserved_.count(token) != 0);
|
||||
/* One Tokenizer for the stream, set up on the first push: it holds the vocab's shared_ptr
|
||||
* and nothing else, and piece() is a pure function of the vocab, so one built per push only
|
||||
* added a reference-count round trip to every token. */
|
||||
if (!tok_ready_) {
|
||||
if (tok_.init(v_) < 0) return {};
|
||||
tok_ready_ = true;
|
||||
}
|
||||
std::string p = tok_.piece(token, render_special_ ||
|
||||
(!preserved_.empty() && preserved_.count(token) != 0));
|
||||
|
||||
/* HuggingFace's decoders strip the leading space that Metaspace's prepend added. Only the
|
||||
* first piece of a stream can carry it, which is why this is a member flag and not a
|
||||
@@ -1582,13 +1606,32 @@ std::string Detokenizer::push(int32_t token) {
|
||||
all_ += p;
|
||||
pending_ += p;
|
||||
|
||||
/* Inside the reasoning block no stop string applies (defer_stops_until). The closer is
|
||||
* searched for incrementally in all_, from (closer length - 1) bytes behind the previous end.
|
||||
* Once it has been generated, matching starts in the text AFTER it: the closer may still be in
|
||||
* pending_, and nothing before its end may count. */
|
||||
size_t from = 0;
|
||||
if (!armed_) {
|
||||
const size_t n = arm_after_.size();
|
||||
const size_t start = arm_scanned_ >= n ? arm_scanned_ - n + 1 : 0;
|
||||
const size_t m = all_.find(arm_after_, start);
|
||||
arm_scanned_ = all_.size();
|
||||
if (m == std::string::npos) {
|
||||
from = std::string::npos;
|
||||
} else {
|
||||
armed_ = true;
|
||||
const size_t pending_at = all_.size() - pending_.size();
|
||||
from = m + n > pending_at ? m + n - pending_at : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* A complete stop string inside pending_ ends the stream. Everything before it is emitted;
|
||||
* the stop string and anything after it never is. */
|
||||
if (!stops_.empty()) {
|
||||
if (!stops_.empty() && from != std::string::npos) {
|
||||
size_t best = std::string::npos;
|
||||
const std::string* which = nullptr;
|
||||
for (const std::string& s : stops_) {
|
||||
const size_t m = pending_.find(s);
|
||||
const size_t m = pending_.find(s, from);
|
||||
if (m != std::string::npos && m < best) { best = m; which = &s; }
|
||||
}
|
||||
if (which) {
|
||||
@@ -1602,9 +1645,10 @@ std::string Detokenizer::push(int32_t token) {
|
||||
|
||||
const size_t cut = safe_prefix();
|
||||
if (cut == 0) return {};
|
||||
std::string out = pending_.substr(0, cut);
|
||||
/* Sanitised straight out of pending_, which keeps its storage for the next token. */
|
||||
std::string out = utf8_sanitize(std::string_view(pending_).substr(0, cut));
|
||||
pending_.erase(0, cut);
|
||||
return utf8_sanitize(out);
|
||||
return out;
|
||||
}
|
||||
|
||||
std::string Detokenizer::flush() {
|
||||
|
||||
@@ -247,6 +247,19 @@ public:
|
||||
bool stopped() const { return stopped_; }
|
||||
const std::string& stop_hit() const { return stop_hit_; }
|
||||
|
||||
/* STOP STRINGS ARE THE ANSWER'S, NOT THE REASONING'S. A generation that starts inside its
|
||||
* reasoning block is matched against its stop strings only after `marker` -- the block's
|
||||
* closer -- has been generated, and only in the text after it. Otherwise a stop string the
|
||||
* model happens to write while thinking ends the request with the reasoning cut short and no
|
||||
* answer at all: a few-shot harness that stops on "Q:" loses every reply whose reasoning
|
||||
* restates the question. "" = match from the first token, the behaviour of every request that
|
||||
* does not start in a block. */
|
||||
void defer_stops_until(std::string marker) {
|
||||
arm_after_ = std::move(marker);
|
||||
armed_ = arm_after_.empty();
|
||||
arm_scanned_ = 0;
|
||||
}
|
||||
|
||||
/* Everything pushed so far, stop string included. The scheduler wants this to decide whether
|
||||
* a request finished on a stop or on a length limit. */
|
||||
const std::string& text() const { return all_; }
|
||||
@@ -264,6 +277,11 @@ private:
|
||||
std::string stop_hit_;
|
||||
size_t max_stop_ = 0;
|
||||
bool first_ = true;
|
||||
std::string arm_after_; /* see defer_stops_until */
|
||||
bool armed_ = true;
|
||||
size_t arm_scanned_ = 0; /* how far into all_ the search for arm_after_ has reached */
|
||||
Tokenizer tok_; /* over v_, set up by the first push */
|
||||
bool tok_ready_ = false;
|
||||
|
||||
size_t safe_prefix() const; /* how much of pending_ can be released */
|
||||
};
|
||||
|
||||
+17
-20
@@ -156,35 +156,35 @@ std::vector<std::string_view> split_ws(std::string_view s) {
|
||||
* touches this at declare, not per step. A hash map here would be slower and less predictable. */
|
||||
void Geometry::set_i(std::string_view k, long long v) {
|
||||
for (size_t i = 0; i < keys_.size(); ++i)
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; dirty_ = true; return; }
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_INT; ivals_[i] = v; rebuild(); return; }
|
||||
keys_.emplace_back(k);
|
||||
svals_.emplace_back();
|
||||
ivals_.push_back(v);
|
||||
dvals_.push_back(0.0);
|
||||
kinds_.push_back(RAD_P_INT);
|
||||
dirty_ = true;
|
||||
rebuild();
|
||||
}
|
||||
|
||||
void Geometry::set_f(std::string_view k, double v) {
|
||||
for (size_t i = 0; i < keys_.size(); ++i)
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; dirty_ = true; return; }
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_F64; dvals_[i] = v; rebuild(); return; }
|
||||
keys_.emplace_back(k);
|
||||
svals_.emplace_back();
|
||||
ivals_.push_back(0);
|
||||
dvals_.push_back(v);
|
||||
kinds_.push_back(RAD_P_F64);
|
||||
dirty_ = true;
|
||||
rebuild();
|
||||
}
|
||||
|
||||
void Geometry::set_s(std::string_view k, std::string_view v) {
|
||||
for (size_t i = 0; i < keys_.size(); ++i)
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); dirty_ = true; return; }
|
||||
if (keys_[i] == k) { kinds_[i] = RAD_P_STR; svals_[i] = std::string(v); rebuild(); return; }
|
||||
keys_.emplace_back(k);
|
||||
svals_.emplace_back(v);
|
||||
ivals_.push_back(0);
|
||||
dvals_.push_back(0.0);
|
||||
kinds_.push_back(RAD_P_STR);
|
||||
dirty_ = true;
|
||||
rebuild();
|
||||
}
|
||||
|
||||
bool Geometry::get_i(std::string_view k, long long* out) const {
|
||||
@@ -210,10 +210,12 @@ bool Geometry::has(std::string_view k) const {
|
||||
return false;
|
||||
}
|
||||
|
||||
void Geometry::rebuild() const {
|
||||
auto* self = const_cast<Geometry*>(this);
|
||||
self->view_.clear();
|
||||
self->view_.reserve(keys_.size());
|
||||
/* Every key and every string value may have moved: an append can reallocate keys_ and svals_, and
|
||||
* a short string lives inside its element. So the whole view is redone, which is the same handful
|
||||
* of entries the setter's scan already walked. */
|
||||
void Geometry::rebuild() {
|
||||
view_.clear();
|
||||
view_.reserve(keys_.size());
|
||||
for (size_t i = 0; i < keys_.size(); ++i) {
|
||||
RadParam p{};
|
||||
p.key = keys_[i].c_str();
|
||||
@@ -221,14 +223,10 @@ void Geometry::rebuild() const {
|
||||
p.ival = ivals_[i];
|
||||
p.dval = dvals_[i];
|
||||
p.sval = kinds_[i] == RAD_P_STR ? svals_[i].c_str() : nullptr;
|
||||
self->view_.push_back(p);
|
||||
view_.push_back(p);
|
||||
}
|
||||
dirty_ = false;
|
||||
}
|
||||
|
||||
const RadParam* Geometry::params() const { if (dirty_) rebuild(); return view_.data(); }
|
||||
int Geometry::n_params() const { if (dirty_) rebuild(); return (int)view_.size(); }
|
||||
|
||||
std::string Geometry::str() const {
|
||||
std::string s;
|
||||
for (size_t i = 0; i < keys_.size(); ++i) {
|
||||
@@ -243,11 +241,10 @@ std::string Geometry::str() const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ constraint matching */
|
||||
/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule and the
|
||||
* reason its two-shot all-reduce rows have to precede the one-shot ones: a query that omits `hops`
|
||||
* fails the row that needs it, so the more constrained row can never be reached unless it is
|
||||
* asked for. Making the absence a failure is what makes "ask for hops=2 to be handed the two-shot"
|
||||
* mean something. */
|
||||
/* A constraint whose key the geometry does not carry does NOT hold. That is libr4d's rule: a row
|
||||
* that constrains an optional parameter serves only a caller that states it, so the more
|
||||
* constrained of two rows is reached only when it is asked for, and a caller that leaves the
|
||||
* parameter out is handed the row that does not need it. */
|
||||
bool constraint_holds(const RadConstraint& c, const Geometry& g) {
|
||||
if (c.op == RAD_C_IN) {
|
||||
const char* v = g.get_s(c.key);
|
||||
|
||||
@@ -12,7 +12,7 @@ services:
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 2 --tp-wire wht6 --max-num-seqs 8 --max-model-len 200000
|
||||
--placement expert_tiered --host-pool-mib 12288 --gpu-headroom-mib 96
|
||||
--expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8
|
||||
--kv-cache-dtype fp8
|
||||
--prefix-cache-host-mib 4096 --prefix-cache-dir /data/kvcache/flashnext
|
||||
--prefix-cache-disk-mib 131072
|
||||
--num-speculative-tokens 3 --max-num-batched-tokens 2048
|
||||
Loaded 100 of 198 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user