Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ac79f4dc8a | ||
|
|
6fa7707dff | ||
|
|
ee5fcf1024 | ||
|
|
432b50d7dd | ||
|
|
32cdaa5cc7 | ||
|
|
d579bd7d45 | ||
|
|
1e27172c14 | ||
|
|
76727fa050 | ||
|
|
82da8eab69 | ||
|
|
73691a1189 | ||
|
|
92eb44619b | ||
|
|
e31be583a9 | ||
|
|
33778b2b8c | ||
|
|
6fd7421f79 | ||
|
|
59d36ae928 | ||
|
|
2af7fa4022 | ||
|
|
d23c3e0d17 | ||
|
|
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 |
No files matched your search
+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.13 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.2.2 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
@@ -2,12 +2,17 @@ radiance
|
||||
Copyright 2026 Deadcode and the radiance contributors
|
||||
|
||||
Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce kernels), ggz14
|
||||
(the MXFP4 GEMM and the GDN kernels' overflow guards), goodman-b (four-rank tensor parallelism
|
||||
(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 and the Grafana dashboard),
|
||||
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 and the request
|
||||
log).
|
||||
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, the
|
||||
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
|
||||
decode kernel), 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), baKon (three-rank tensor parallelism,
|
||||
serving any world size from the shipped container, the request log, an uneven world's per-rank
|
||||
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
|
||||
|
||||
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` |
|
||||
@@ -81,18 +82,17 @@ 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, four ranks | `--tp 4 --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, three ranks (the checkpoint padded first, [`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 --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
|
||||
@@ -107,8 +107,8 @@ tiering flags are the tp2 recipe carried over. Above two ranks each rank still o
|
||||
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 `--expert-vs-cache-ratio` and
|
||||
`--host-pool-mib` before trusting them. **`--host-pool-mib` is pinned on every card**, so the row
|
||||
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).
|
||||
@@ -156,7 +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) | padding a checkpoint, exactly, to a world its head counts do not divide; three ranks |
|
||||
| [`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 |
|
||||
|
||||
|
||||
+24
-1
@@ -39,6 +39,10 @@ typedef struct RadModelMeta {
|
||||
|
||||
float rms_eps;
|
||||
float rope_theta;
|
||||
/* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope --
|
||||
* and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with
|
||||
* text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses
|
||||
* by name. A bare factor here would read every scheme as a linear position divide. */
|
||||
float rope_scale;
|
||||
|
||||
/* Free-form key/value from the container header, for anything the struct above does not
|
||||
@@ -364,6 +368,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 +688,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
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
#ifndef RAD_YARN_H
|
||||
#define RAD_YARN_H
|
||||
|
||||
/* Static YaRN coefficients. The architecture resolves the correction bounds using
|
||||
* the ORIGINAL training length, never the deployment/table length. Kernels share
|
||||
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
|
||||
#include "rad_plugin.h"
|
||||
#include <cmath>
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_YARN_HD __host__ __device__
|
||||
#else
|
||||
#define RAD_YARN_HD
|
||||
#endif
|
||||
|
||||
struct RadYarn {
|
||||
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
|
||||
float low = 0.0f;
|
||||
float high = 0.0f;
|
||||
float magnitude = 1.0f;
|
||||
|
||||
RAD_YARN_HD float frequency(float inv, int i) const {
|
||||
if (factor == 0.0f) return inv;
|
||||
const float width = high == low ? 0.001f : high - low;
|
||||
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
|
||||
/* Keep the blend order used by the reference YaRN implementation. */
|
||||
const float mask = 1.0f - ramp;
|
||||
return (inv / factor) * (1.0f - mask) + inv * mask;
|
||||
}
|
||||
};
|
||||
|
||||
inline RadYarn rad_yarn_args(const RadArgs* a) {
|
||||
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
|
||||
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
|
||||
if (factor == 0.0f) return {};
|
||||
return { factor,
|
||||
(float)rad_args_getf_or(a, "yarn_low", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_high", 0.0),
|
||||
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
|
||||
}
|
||||
|
||||
inline bool rad_yarn_valid(const RadYarn& y) {
|
||||
return std::isfinite(y.factor) && (y.factor == 0.0f ||
|
||||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
|
||||
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
|
||||
}
|
||||
|
||||
#undef RAD_YARN_HD
|
||||
#endif
|
||||
+190
-12
@@ -16,6 +16,7 @@
|
||||
#include "rad_builder.h"
|
||||
#include "rad_device.h"
|
||||
#include "rad_runtime.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
#include <cstdarg>
|
||||
#include <cstdio>
|
||||
@@ -576,6 +577,18 @@ struct Geom {
|
||||
* 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;
|
||||
@@ -614,6 +627,7 @@ struct Geom {
|
||||
float wadd_qk = 0.0f;
|
||||
float theta = 1e6f;
|
||||
float rope_scale = 1.0f;
|
||||
RadYarn yarn;
|
||||
/* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several
|
||||
* position components declares `rope` with `rope_mode` and these sections and hands it
|
||||
* RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here
|
||||
@@ -717,13 +731,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, bool arch_splits_ff = false) {
|
||||
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
|
||||
@@ -755,7 +791,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
g.dtype = dtype;
|
||||
g.act_dtype = act_dtype;
|
||||
{
|
||||
@@ -786,7 +822,23 @@ 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;
|
||||
/* 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
|
||||
@@ -805,19 +857,24 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
*
|
||||
* 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 (g.world > g.n_head_kv_all) {
|
||||
if (g.world % g.n_head_kv_all != 0) {
|
||||
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",
|
||||
g.world, (long long)g.n_head_kv_all);
|
||||
aw, (long long)g.n_head_kv_all);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.n_head_kv = 1; /* world / n_head_kv_all ranks share each KV head */
|
||||
g.kv_off = (g.rank / (g.world / g.n_head_kv_all)) * g.head_dim;
|
||||
} else if ((s = divide_or_fail(g.n_head_kv_all, g.world, "n_head_kv", &g.n_head_kv)) < 0) {
|
||||
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 {
|
||||
g.kv_off = 0; /* a split rank reads the rows the plain row-shard already gives it */
|
||||
/* 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) */
|
||||
@@ -968,19 +1025,140 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
|
||||
* cannot rotate. */
|
||||
inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
|
||||
|
||||
/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
|
||||
* exactly the parameters it was given, so its op identities and tune keys are unchanged. */
|
||||
inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_F64("yarn_factor", g.yarn.factor));
|
||||
p.push_back(RAD_F64("yarn_low", g.yarn.low));
|
||||
p.push_back(RAD_F64("yarn_high", g.yarn.high));
|
||||
p.push_back(RAD_F64("yarn_magnitude", g.yarn.magnitude));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
|
||||
* target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
|
||||
* `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
|
||||
* factor without its type would be a linear position divide for a scheme that is not one.
|
||||
*
|
||||
* The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
|
||||
* `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
|
||||
* `draft.rope_scaling.`) that names a type in `rope_type` or `type`; a multimodal target's
|
||||
* text_config is authoritative. core/format/rope_override.h writes --rope-scaling into the same
|
||||
* object, found in the same order.
|
||||
*
|
||||
* default, mrope no scaling (`mrope` is the legacy Qwen2-VL spelling of default + sections)
|
||||
* linear positions divided by `factor`
|
||||
* yarn static YaRN: frequencies blended over the correction range that `factor`,
|
||||
* `original_max_position_embeddings`, `beta_fast`/`beta_slow` and `truncate`
|
||||
* give, cos/sin scaled by `attention_factor` (default 1 + 0.1 ln factor). The
|
||||
* factor is the config's, read as vLLM and transformers read it.
|
||||
*
|
||||
* Anything else -- llama3, longrope, dynamic -- is refused by name, as is YaRN's `mscale` form. A
|
||||
* refusal leaves the geometry as it was. */
|
||||
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
|
||||
const std::string root(prefix);
|
||||
const char* who = root.empty() ? "target" : "draft";
|
||||
const std::vector<std::string> homes = root.empty()
|
||||
? std::vector<std::string>{"text_config.rope_parameters.", "rope_parameters.",
|
||||
"text_config.rope_scaling.", "rope_scaling."}
|
||||
: std::vector<std::string>{root + "rope_parameters.", root + "rope_scaling."};
|
||||
std::string home, type_key;
|
||||
const char* type = nullptr;
|
||||
for (const auto& h : homes) {
|
||||
for (const char* t : {"rope_type", "type"})
|
||||
if ((type = rad_meta_gets(meta, (h + t).c_str(), nullptr))) { type_key = h + t; break; }
|
||||
if (type) { home = h; break; }
|
||||
}
|
||||
if (!type || !std::strcmp(type, "default") || !std::strcmp(type, "mrope")) {
|
||||
g.yarn = {};
|
||||
g.rope_scale = 1.0f;
|
||||
return RAD_OK;
|
||||
}
|
||||
auto get = [&](const char* key, double fallback) {
|
||||
const char* text = rad_meta_gets(meta, (home + key).c_str(), nullptr);
|
||||
if (!text) return fallback;
|
||||
char* end = nullptr;
|
||||
const double value = std::strtod(text, &end);
|
||||
if (end == text) return (double)NAN;
|
||||
while (*end == ' ' || *end == '\t' || *end == '\n') ++end;
|
||||
return *end ? (double)NAN : value;
|
||||
};
|
||||
if (!std::strcmp(type, "linear")) {
|
||||
const double factor = get("factor", 0.0);
|
||||
const float scale = (float)factor;
|
||||
if (!std::isfinite(factor) || factor <= 0.0 || !std::isfinite(scale) || scale <= 0.0f) {
|
||||
fprintf(stderr, "radiance: %s linear rotary scaling (%s) needs a finite factor > 0\n",
|
||||
who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = {};
|
||||
g.rope_scale = scale;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (std::strcmp(type, "yarn")) {
|
||||
fprintf(stderr, "radiance: %s rotary type '%s' (%s) is not implemented; default, linear "
|
||||
"and yarn are\n", who, type, type_key.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
|
||||
* out are the same answer. */
|
||||
double truncate = 1.0;
|
||||
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
|
||||
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
|
||||
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
|
||||
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
|
||||
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
|
||||
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
|
||||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
|
||||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
|
||||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
|
||||
rot < 2 || (rot & 1)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) needs a finite factor >= 1, an integral "
|
||||
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
|
||||
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* mscale variants are a different contract; never silently ignore them. */
|
||||
for (const char* k : {"mscale", "mscale_all_dim"})
|
||||
if (rad_meta_gets(meta, (home + k).c_str(), nullptr)) {
|
||||
fprintf(stderr, "radiance: %s YaRN %s%s is not implemented; attention_factor is\n",
|
||||
who, home.c_str(), k);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto correction = [&](double beta) {
|
||||
return rot * std::log(original / (beta * 2.0 * 3.14159265358979323846)) /
|
||||
(2.0 * std::log((double)g.theta));
|
||||
};
|
||||
double low = correction(fast), high = correction(slow);
|
||||
if (truncate != 0.0) { low = std::floor(low); high = std::ceil(high); }
|
||||
const RadYarn y = {(float)factor, (float)std::max(0.0, low),
|
||||
(float)std::min((double)rot - 1, high), (float)magnitude};
|
||||
if (!rad_yarn_valid(y)) {
|
||||
fprintf(stderr, "radiance: %s YaRN (%s) resolves to an empty correction range\n", who,
|
||||
home.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
g.yarn = y;
|
||||
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
|
||||
* `mode` otherwise. */
|
||||
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
|
||||
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
|
||||
if (g.rope_mc)
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_NOWEIGHTS);
|
||||
return RAD_OP(b, "rope",
|
||||
return decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
|
||||
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -121,7 +121,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
|
||||
0, { q_dim, kv_dim, kv_dim }));
|
||||
|
||||
op_rope = rw(b, RAD_OP(b, "rope",
|
||||
op_rope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -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
|
||||
@@ -192,9 +193,19 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
* 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. */
|
||||
const bool kv_spanned = g.world > g.n_head_kv_all;
|
||||
/* 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",
|
||||
@@ -234,8 +245,26 @@ 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,
|
||||
0, {}, kv_span_lo, kv_span_hi));
|
||||
@@ -417,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",
|
||||
@@ -448,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);
|
||||
|
||||
@@ -538,7 +538,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
|
||||
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
|
||||
* serves every layer. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -712,14 +712,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
RAD_WEIGHTS(w_fcb[i])),
|
||||
{w.h, w.coef}, {w.h2});
|
||||
}
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -508,7 +508,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
|
||||
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
|
||||
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
|
||||
op_crope = rw(b, RAD_OP(b, "rope",
|
||||
op_crope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
@@ -667,14 +667,14 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
|
||||
{w.ffn.q, w.ffn.s}, {w.h.x});
|
||||
}
|
||||
|
||||
op_qrope = rw(b, RAD_OP(b, "rope",
|
||||
op_qrope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("mode", "neox")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_krope = rw(b, RAD_OP(b, "rope",
|
||||
op_krope = rw(b, decl_rotary(b, g, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -76,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.
|
||||
@@ -362,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;
|
||||
@@ -452,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) {
|
||||
@@ -495,6 +506,31 @@ inline int MoeFP8::format_of(const RadEncoding& e) {
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
/* WHETHER A CHECKPOINT SHIPS ONE LAYER'S EXPERTS STACKED OR ONE BY ONE, as the Src it fills.
|
||||
* Recent releases stack them -- `<prefix>.gate_up_proj` and `<prefix>.down_proj` -- and a
|
||||
* quantised export (AutoRound's) writes each expert on its own, `<prefix>.<e>.{gate,up,down}_proj`.
|
||||
* Each form is asked of the checkpoint through a probe name mapped to its first expert, which the
|
||||
* checkpoint answers or does not. Stacked is the answer when neither is found: a container is
|
||||
* read by declared name, the same under both maps, so it asks nothing here. `tag` keeps one
|
||||
* caller's probe name apart from another's for the same layer. */
|
||||
inline int moe_expert_sources(RadBuilder* b, Names& nm, const char* tag, const char* prefix,
|
||||
MoeFP8::Src* src) {
|
||||
const char* gu = nm.ckpt("%s.gate_up_proj", prefix);
|
||||
const char* probe = nm.f("probe.%s.%s.0", tag, prefix);
|
||||
RadEncoding e{};
|
||||
RAD_ARCH_TRY(map_concat(b, probe, { nm.ckpt("%s.0.gate_proj.weight", prefix),
|
||||
nm.ckpt("%s.0.up_proj.weight", prefix) }));
|
||||
if (weight_enc(b, probe, &e)) {
|
||||
src->experts = nm.ckpt("%s", prefix);
|
||||
src->experts_gate_up = src->experts_down = nullptr;
|
||||
} else {
|
||||
src->experts = nullptr;
|
||||
src->experts_gate_up = gu;
|
||||
src->experts_down = nm.ckpt("%s.down_proj", prefix);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The gate_up and down name maps of one expert: a dim-0 slice of the stacked tensors, or the
|
||||
* checkpoint's per-expert gate and up joined along rows. `gate_up` false maps down alone. */
|
||||
inline int moe_map_expert(RadBuilder* b, Names& nm, const MoeFP8::Src& src, const char* guw,
|
||||
@@ -572,6 +608,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.
|
||||
*
|
||||
@@ -1335,6 +1374,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. */
|
||||
@@ -1367,6 +1407,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),
|
||||
@@ -1399,7 +1486,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);
|
||||
@@ -1431,11 +1521,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);
|
||||
@@ -1482,7 +1586,7 @@ 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)
|
||||
|
||||
@@ -664,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;
|
||||
@@ -676,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;
|
||||
@@ -722,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
|
||||
@@ -751,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;
|
||||
@@ -891,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. */
|
||||
@@ -928,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;
|
||||
@@ -988,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);
|
||||
|
||||
@@ -269,7 +269,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
|
||||
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
|
||||
op_bkey = g.rope_mc
|
||||
? RAD_OP(b, "qsa_block_key",
|
||||
? decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
@@ -278,7 +278,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
|
||||
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
|
||||
RAD_STR("sections", g.rope_sections)),
|
||||
RAD_WEIGHTS(w_kn))
|
||||
: RAD_OP(b, "qsa_block_key",
|
||||
: decl_rotary(b, g, "qsa_block_key",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
|
||||
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
|
||||
RAD_INT("block_size", c.ratio),
|
||||
|
||||
@@ -185,7 +185,6 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
|
||||
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
|
||||
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
|
||||
@@ -201,6 +200,7 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
|
||||
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
int s;
|
||||
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
|
||||
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
|
||||
@@ -431,6 +431,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the KV cache. One group: every layer is full attention. */
|
||||
RadKVGroupDecl fd{};
|
||||
|
||||
@@ -237,6 +237,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
|
||||
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
|
||||
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
|
||||
|
||||
@@ -339,7 +339,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
|
||||
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
|
||||
rad_meta_getf(meta, "draft.rope_theta", 0.0));
|
||||
dg.rope_scale = 1.0f;
|
||||
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
|
||||
/* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
|
||||
* the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
|
||||
* conventions in one process, which is exactly why this is a second Geom and not a flag. */
|
||||
@@ -635,6 +635,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
GdnFP8::Config& gc = m.gcfg;
|
||||
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
|
||||
"linear_num_key_heads", 0);
|
||||
@@ -952,7 +953,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
|
||||
* band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
|
||||
* prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
|
||||
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
|
||||
RAD_STR("dtype", "f32")),
|
||||
|
||||
@@ -320,8 +320,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* 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. */
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16, /*arch_splits_ff=*/true));
|
||||
* 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
|
||||
@@ -361,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
/* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
|
||||
* for the target device, the answer is a converter flag that writes a NAMED partial container
|
||||
* -- not an environment variable that makes a full one silently mean something else. A slice
|
||||
@@ -406,9 +410,38 @@ 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.
|
||||
@@ -488,8 +521,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
? (int64_t)g.rank * (mc.n_expert / g.world) : 0;
|
||||
{
|
||||
MoeFP8::Src ps{};
|
||||
ps.experts_gate_up = nm.ckpt("model.language_model.layers.0.mlp.experts.gate_up_proj");
|
||||
ps.experts_down = nm.ckpt("model.language_model.layers.0.mlp.experts.down_proj");
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "format",
|
||||
"model.language_model.layers.0.mlp.experts", &ps));
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, 0, ps, &mc));
|
||||
}
|
||||
/* A CHECKPOINT SERVED AS IT SHIPS IS bf16 THROUGHOUT. Plain experts mean a container
|
||||
@@ -576,7 +609,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* 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. */
|
||||
/* 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);
|
||||
@@ -961,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* one step; the symptom is fluent output with one arm of the model reading the other's
|
||||
* leftovers, which nothing downstream flags.
|
||||
*/
|
||||
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
|
||||
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
|
||||
RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta),
|
||||
RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")),
|
||||
@@ -1104,6 +1144,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));
|
||||
@@ -1161,8 +1206,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
MoeFP8::Src ms{};
|
||||
ms.cfg = m.moecfg;
|
||||
ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l);
|
||||
ms.experts_gate_up = nm.ckpt("%s.%lld.mlp.experts.gate_up_proj", pre, (long long)l);
|
||||
ms.experts_down = nm.ckpt("%s.%lld.mlp.experts.down_proj", pre, (long long)l);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "layer",
|
||||
nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l), &ms));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l);
|
||||
ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l);
|
||||
@@ -1323,8 +1368,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
ts.mlp.cfg = m.moecfg;
|
||||
ts.mlp.router = nm.ckpt("%s.layers.0.mlp.gate.weight", mpre);
|
||||
ts.mlp.experts_gate_up = nm.ckpt("%s.layers.0.mlp.experts.gate_up_proj", mpre);
|
||||
ts.mlp.experts_down = nm.ckpt("%s.layers.0.mlp.experts.down_proj", mpre);
|
||||
RAD_ARCH_TRY(moe_expert_sources(b, nm, "mtp", nm.ckpt("%s.layers.0.mlp.experts", mpre),
|
||||
&ts.mlp));
|
||||
if (m.moecfg.n_ff_shared > 0) {
|
||||
ts.mlp.shared = nm.ckpt("%s.layers.0.mlp.shared_expert", mpre);
|
||||
ts.mlp.shared_gate = nm.ckpt("%s.layers.0.mlp.shared_expert_gate.weight", mpre);
|
||||
|
||||
@@ -97,6 +97,22 @@ function(rad_add_plugin name kind)
|
||||
"because the language a project compiles in is the project's own decision.")
|
||||
endif()
|
||||
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
|
||||
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
|
||||
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
|
||||
# input path, the output path and the command line, so one source built in two directories --
|
||||
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
|
||||
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
|
||||
# object's read-only data and with it every PC-relative address .text forms into it: the same
|
||||
# instructions, different bytes. Named from what identifies the unit and nothing about where it
|
||||
# was built, the ID is the same wherever the plugin is built and still differs between any two
|
||||
# sources, which is the property clang needs of it.
|
||||
foreach(src ${P_HIP_SOURCES})
|
||||
get_filename_component(_rad_abs "${src}" ABSOLUTE)
|
||||
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
|
||||
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
|
||||
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
|
||||
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
|
||||
endforeach()
|
||||
list(APPEND srcs ${P_HIP_SOURCES})
|
||||
endif()
|
||||
add_library(${name} MODULE ${srcs})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -892,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; }
|
||||
@@ -1615,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);
|
||||
|
||||
+30
-1
@@ -129,7 +129,7 @@ static std::vector<std::string> home_subdirs(const std::string& home, const char
|
||||
|
||||
int rad_tools_load_plugins(const std::string& home, const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id, const std::string& quant,
|
||||
LoadedPlugins* out) {
|
||||
LoadedPlugins* out, bool imported) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = LoadedPlugins{};
|
||||
|
||||
@@ -188,6 +188,35 @@ int rad_tools_load_plugins(const std::string& home, const std::vector<std::strin
|
||||
}
|
||||
}
|
||||
|
||||
/* AN IMPORTED QUANTISATION is served by the family's quantised plugin (startup.h). */
|
||||
if (imported && !arch_id.empty() && out->arch_plugin.empty()) {
|
||||
std::vector<const Plugin*> fam, quantised;
|
||||
for (const Plugin& p : r.plugins())
|
||||
if (p.kind == RAD_PLUGIN_ARCH && p.arch_id == arch_id) {
|
||||
fam.push_back(&p);
|
||||
if (!p.arch_quant.empty()) quantised.push_back(&p);
|
||||
}
|
||||
const Plugin* pick = quantised.size() == 1 ? quantised[0]
|
||||
: quantised.empty() && fam.size() == 1 ? fam[0] : nullptr;
|
||||
if (!pick && quantised.size() > 1) {
|
||||
std::string names;
|
||||
for (const Plugin* p : quantised) names += (names.empty() ? "" : ", ") + p->arch_quant;
|
||||
RAD_ERR("'%s' is quantised by %s and imported weight by weight, and '%s' has more than "
|
||||
"one quantised plugin (%s) to serve it; none is chosen for it",
|
||||
arch_id.c_str(), quant.c_str(), arch_id.c_str(), names.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
if (pick) {
|
||||
out->arch_plugin = pick->name;
|
||||
out->arch_version = pick->version;
|
||||
out->arch_id = pick->arch_id;
|
||||
out->arch_quant = pick->arch_quant;
|
||||
RAD_INFO("quantisation '%s' is imported weight by weight; '%s' serves it as %s",
|
||||
quant.c_str(), pick->name.c_str(),
|
||||
pick->arch_quant.empty() ? "(unquantised)" : pick->arch_quant.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
if (out->kernels.empty()) {
|
||||
RAD_ERR("no kernel plugin loaded from %s/kernels. Every weight's layout comes from the "
|
||||
"kernel that will read it, so there is nothing to lay a container out for.",
|
||||
|
||||
@@ -66,11 +66,19 @@ std::string rad_home_file(const std::string& home, const std::string& rel);
|
||||
* has one plugin per weight format and they all answer the same architecture id. `quant` is the
|
||||
* container's own descriptor -- RadModelMeta::quant, RadFileHeader::quant -- and "" is the
|
||||
* unquantised case, which matches a plugin that says "" and nothing else. */
|
||||
/*
|
||||
* `imported` is a checkpoint whose quantisation is imported weight by weight
|
||||
* (Checkpoint::imports): its descriptor names the tool that made it and no plugin claims it, so
|
||||
* the plugin is the architecture's QUANTISED one -- the one plugin of the family claiming a
|
||||
* descriptor, or the family's only plugin when that claims none. Two quantised plugins are a
|
||||
* choice this cannot make, and are refused by name. `out->arch_quant` is the descriptor chosen,
|
||||
* which is what a container converted from it records. */
|
||||
int rad_tools_load_plugins(const std::string& radiance_home,
|
||||
const std::vector<std::string>& hierarchy,
|
||||
const std::string& arch_id,
|
||||
const std::string& quant,
|
||||
LoadedPlugins* out);
|
||||
LoadedPlugins* out,
|
||||
bool imported = false);
|
||||
|
||||
/* `also` declares into the SAME builder after the architecture plugin has. That is what puts the
|
||||
* sampler chain in the same Program: its ops resolve through the same hierarchy at the same
|
||||
|
||||
+70
-22
@@ -6,6 +6,7 @@
|
||||
* (spec §6).
|
||||
*/
|
||||
#include "rad_core.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "sample/host_ref.h"
|
||||
#include "server/oai.h"
|
||||
|
||||
@@ -28,6 +29,15 @@ struct Flag {
|
||||
const char* help;
|
||||
};
|
||||
|
||||
/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
|
||||
* that points at it: the two are initialised in this order. */
|
||||
static const std::string g_draft_window_help =
|
||||
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
|
||||
" --num-speculative-tokens every step; adaptive makes that\n"
|
||||
" the ceiling and follows each sequence's acceptance and the\n"
|
||||
" measured step cost (a serial draft head only). Default ") +
|
||||
draft_window_name(kDraftWindowDefault);
|
||||
|
||||
static const Flag g_flags[] = {
|
||||
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
|
||||
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
|
||||
@@ -39,20 +49,16 @@ static const Flag g_flags[] = {
|
||||
"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" },
|
||||
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
|
||||
"keys, no reconvert (docs/YARN.md); none: off" },
|
||||
|
||||
{ "--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" },
|
||||
@@ -89,13 +95,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" },
|
||||
@@ -103,6 +110,7 @@ static const Flag g_flags[] = {
|
||||
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
@@ -128,6 +136,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" },
|
||||
{ "--reasoning-effort-map", "MAP", "FROM=TO[,FROM=TO...]: a `reasoning_effort` a request sends, replaced before\n"
|
||||
" the chat template sees it -- high=xhigh lets a client that always sends\n"
|
||||
" OpenAI's top level reach Qwen3.8's. TO is checked against the template at\n"
|
||||
" startup; none and minimal turn thinking off. Repeatable" },
|
||||
{ "--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"
|
||||
@@ -370,10 +382,29 @@ 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); }
|
||||
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
|
||||
else if (S("--rope-scaling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
/* Checked here, so a typo is a refusal at the command line and not a model served
|
||||
* with its trained rotary at a length it cannot reach. */
|
||||
RopeSpec rs;
|
||||
if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
|
||||
RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
|
||||
"length, or none -- got '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->rope_scaling = v;
|
||||
}
|
||||
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
|
||||
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
|
||||
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
|
||||
@@ -389,16 +420,6 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
}
|
||||
else if (S("--expert-vs-cache-ratio")) {
|
||||
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);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
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");
|
||||
@@ -447,6 +468,15 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-window")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
|
||||
else if (!std::strcmp(v, "adaptive")) c->draft_window = DraftWindow::Adaptive;
|
||||
else {
|
||||
RAD_ERR("--draft-window takes fixed or adaptive, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
|
||||
* own drafter -- or none -- would hand the caller a server that is not the one they
|
||||
@@ -488,6 +518,24 @@ 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("--reasoning-effort-map")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
const std::string all = v;
|
||||
size_t at = 0;
|
||||
while (at <= all.size()) {
|
||||
const size_t end = std::min(all.find(',', at), all.size());
|
||||
const std::string pair = all.substr(at, end - at);
|
||||
const size_t eq = pair.find('=');
|
||||
if (eq == std::string::npos || eq == 0 || eq + 1 == pair.size() ||
|
||||
pair.find('=', eq + 1) != std::string::npos) {
|
||||
RAD_ERR("--reasoning-effort-map takes FROM=TO pairs separated by commas, "
|
||||
"not '%s'", pair.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->reasoning_effort_map[pair.substr(0, eq)] = pair.substr(eq + 1);
|
||||
at = end + 1;
|
||||
}
|
||||
}
|
||||
else if (S("--thinking-token-budget")) { if (!(v = need(i)) ||
|
||||
!parse_int(a.c_str(), v, 0, INT32_MAX,
|
||||
&c->thinking_token_budget))
|
||||
|
||||
+86
-11
@@ -1023,10 +1023,15 @@ 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"): base ->
|
||||
* length, ordered so an inner address finds its range. */
|
||||
/* 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, int64_t> g_pinned;
|
||||
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;
|
||||
@@ -1034,9 +1039,9 @@ bool pinned_range(const void* p, uintptr_t* lo, int64_t* len) {
|
||||
auto it = g_pinned.upper_bound(a);
|
||||
if (it == g_pinned.begin()) return false;
|
||||
--it;
|
||||
if (a - it->first >= (uintptr_t)it->second) return false;
|
||||
if (a - it->first >= (uintptr_t)it->second.len) return false;
|
||||
if (lo) *lo = it->first;
|
||||
if (len) *len = it->second;
|
||||
if (len) *len = it->second.len;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -2040,6 +2045,20 @@ int a_vmem_decommit(void* addr, int64_t bytes) {
|
||||
* 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
|
||||
@@ -2093,7 +2112,56 @@ const char* hsa_why(hsa_status_t st) {
|
||||
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
|
||||
@@ -2113,8 +2181,6 @@ void* pin_pieces(int64_t bytes) {
|
||||
prefer_numa_node(p, len, current_card_numa_node());
|
||||
if (len >= ((int64_t)2 << 20)) ::madvise(p, (size_t)len, MADV_HUGEPAGE);
|
||||
|
||||
std::vector<hsa_agent_t> cards;
|
||||
for (const Dev& d : G().dev) cards.push_back(d.agent);
|
||||
const int pieces = (int)((len + kPinPiece - 1) / kPinPiece);
|
||||
int done = 0;
|
||||
for (; done < pieces; ++done) {
|
||||
@@ -2133,7 +2199,9 @@ void* pin_pieces(int64_t bytes) {
|
||||
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",
|
||||
"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;
|
||||
}
|
||||
@@ -2144,12 +2212,12 @@ void* pin_pieces(int64_t bytes) {
|
||||
return nullptr;
|
||||
}
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
g_pinned.emplace((uintptr_t)p, len);
|
||||
g_pinned.emplace((uintptr_t)p, Pinned{len, nullptr});
|
||||
return p;
|
||||
}
|
||||
|
||||
void unpin_pieces(void* p) {
|
||||
int64_t len = 0;
|
||||
Pinned r;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(g_pinned_mu);
|
||||
auto it = g_pinned.find((uintptr_t)p);
|
||||
@@ -2158,9 +2226,16 @@ void unpin_pieces(void* p) {
|
||||
"leaked rather than unpinned", p);
|
||||
return;
|
||||
}
|
||||
len = it->second;
|
||||
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)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
+208
-81
@@ -534,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();
|
||||
|
||||
@@ -646,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) {
|
||||
@@ -660,21 +665,17 @@ int Engine::step_loop() {
|
||||
for (const StepEntry& e : plan.e) {
|
||||
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. */
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& rk = ranks_[ri];
|
||||
/* 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(),
|
||||
e.ckpt_restore, rk->ctx.stream());
|
||||
if (s < 0) {
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d: %s",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore,
|
||||
rad_strerror(s));
|
||||
RAD_ERR("could not restore sequence %llu from checkpoint slot %d on "
|
||||
"rank %d: %s", (unsigned long long)e.seq,
|
||||
(int)e.ckpt_restore, (int)ri, rad_strerror(s));
|
||||
if (ranks_.size() > 1) (void)rad_dev_set(ranks_[0]->device);
|
||||
return s;
|
||||
}
|
||||
@@ -754,8 +755,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. */
|
||||
@@ -768,8 +770,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(),
|
||||
@@ -1142,15 +1142,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
|
||||
@@ -1291,14 +1284,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());
|
||||
}
|
||||
}
|
||||
@@ -1307,7 +1306,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);
|
||||
}
|
||||
@@ -1329,6 +1330,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
|
||||
@@ -1338,7 +1355,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);
|
||||
@@ -1348,6 +1383,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
|
||||
@@ -1357,25 +1460,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;
|
||||
@@ -1403,11 +1501,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();
|
||||
@@ -1447,12 +1546,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())
|
||||
@@ -1463,13 +1559,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
|
||||
@@ -1508,22 +1618,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
|
||||
@@ -1534,10 +1642,6 @@ int Engine::serve() {
|
||||
for (auto& rk : ranks_)
|
||||
rio.push_back({ rk->device, rk->ctx.stream(), &rk->program });
|
||||
RAD_TRY(sched_.init(ranks_[0]->program, cfg_, kv_iface_.get(), pc_iface_.get(), rio, &geo_));
|
||||
/* The step staging the budget kept room for exists now, so a checkpoint slot backed from here
|
||||
* on leaves the headroom and only what is still to be built on first use. */
|
||||
set_checkpoint_floors(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20) +
|
||||
late_lazy_bytes_);
|
||||
|
||||
for (auto& r : ranks_) r->sampler.attach_vocab(vocab_view_.get());
|
||||
|
||||
@@ -2046,6 +2150,7 @@ 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.reasoning_effort_map = cfg_.reasoning_effort_map;
|
||||
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();
|
||||
@@ -2172,6 +2277,28 @@ 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());
|
||||
}
|
||||
/* THE EFFORTS THE TEMPLATE TAKES, said once: a client sending another gets this set back in
|
||||
* its 400 and can read it off /server_info beforehand. A map whose target the template
|
||||
* refuses would refuse every request it maps, so it stops startup. */
|
||||
if (d.chat) {
|
||||
const std::vector<std::string> efforts = srv.probe_reasoning_efforts();
|
||||
std::string mapped;
|
||||
for (const auto& [from, to] : cfg_.reasoning_effort_map)
|
||||
mapped += fmt("%s%s -> %s", mapped.empty() ? "" : ", ", from.c_str(), to.c_str());
|
||||
if (!efforts.empty()) {
|
||||
std::string list;
|
||||
for (const std::string& e : efforts) list += (list.empty() ? "" : ", ") + e;
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
} else if (!mapped.empty()) {
|
||||
RAD_INFO("chat: reasoning_effort mapped: %s", mapped.c_str());
|
||||
}
|
||||
if (const std::string why = srv.check_reasoning_effort_map(); !why.empty()) {
|
||||
RAD_ERR("--reasoning-effort-map %s", why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
/* 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()) {
|
||||
|
||||
+30
-10
@@ -22,6 +22,7 @@
|
||||
#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"
|
||||
@@ -92,6 +93,15 @@ private:
|
||||
std::vector<std::thread> rank_threads_;
|
||||
|
||||
Config cfg_;
|
||||
/* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
|
||||
* token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
|
||||
* whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
|
||||
* count and the difference in its weights pool. Engine::plan fills it, and every reader of the
|
||||
* resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
|
||||
* cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
|
||||
* plan and weights pool disagree. */
|
||||
std::vector<Config> rank_cfg_;
|
||||
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
|
||||
|
||||
/* The model's source, one of the two. A container stays mapped for the life of the engine:
|
||||
* the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
|
||||
@@ -116,12 +126,16 @@ private:
|
||||
int load_plugins();
|
||||
int read_metadata();
|
||||
int read_checkpoint_metadata();
|
||||
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
|
||||
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
|
||||
int apply_rope_scaling();
|
||||
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, int64_t kv_floor,
|
||||
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
|
||||
@@ -306,6 +320,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
|
||||
@@ -327,19 +350,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 checkpoint
|
||||
* slots backed at the end of bringup leave both free, and the bringup's closing reading is
|
||||
* checked against both. */
|
||||
* 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;
|
||||
/* Every rank's checkpoint floor: a slot is backed only while the card keeps `keep` free. */
|
||||
void set_checkpoint_floors(int64_t keep);
|
||||
/* 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_`.
|
||||
|
||||
+491
-182
@@ -14,6 +14,7 @@
|
||||
#include "device/device.h"
|
||||
#include "device/directio.h"
|
||||
#include "format/radfile.h"
|
||||
#include "format/rope_override.h"
|
||||
#include "format/share.h"
|
||||
#include "format/table_copy.h"
|
||||
#include "rad_plugin.h"
|
||||
@@ -231,15 +232,22 @@ static void report_pool_refusal(int rank, int device, const Pools& pools, const
|
||||
}
|
||||
}
|
||||
}
|
||||
/* A refusal with room under both is not a capacity one, and advice to shrink the pool
|
||||
* would send the reader after the wrong cause: the device's reason above is the answer. */
|
||||
const int64_t want = (int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024 + pinned + mapped;
|
||||
const bool fits = cap > 0 && avail >= 0 && want <= cap && want <= avail;
|
||||
RAD_ERR("host: --host-pool-mib %lld is pinned once per rank, so %d rank(s) pin %s; this "
|
||||
"process had taken %s of pinned host memory before rank %d's pool. The amdgpu "
|
||||
"driver caps pinned memory system-wide at %s (ttm.pages_limit, half of RAM unless "
|
||||
"raised), and %s of RAM is available. Lower --host-pool-mib, or raise the cap",
|
||||
"raised), and %s of RAM is available. %s",
|
||||
(long long)cfg.host_pool_mib, cfg.tp,
|
||||
humanb((int64_t)cfg.tp * cfg.host_pool_mib * 1024 * 1024).c_str(),
|
||||
humanb(pinned + mapped).c_str(), rank,
|
||||
cap > 0 ? humanb(cap).c_str() : "an unreadable limit",
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount");
|
||||
avail >= 0 ? humanb(avail).c_str() : "an unknown amount",
|
||||
fits ? "The pools fit under both, so the refusal is not one of size; the reason "
|
||||
"the device gave is above"
|
||||
: "Lower --host-pool-mib, or raise the cap");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -438,7 +446,8 @@ bool Engine::ngram_gather_to_host() {
|
||||
* RAM's is lockable_room's -- the memory and every cgroup after the pools still to be allocated,
|
||||
* and the memlock limit for a locked copy. */
|
||||
int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
const std::vector<int64_t>& emb_bytes, int64_t kv_floor,
|
||||
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) {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
int64_t emb_max = 0;
|
||||
@@ -501,9 +510,13 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
auto card_holds = [&](std::string* why) {
|
||||
std::vector<VramFacts> with = facts;
|
||||
int64_t fixed = 0;
|
||||
for (VramFacts& f : with) {
|
||||
for (size_t i = 0; i < with.size(); ++i) {
|
||||
VramFacts& f = with[i];
|
||||
f.statics += ngram_bytes;
|
||||
if (emb == TablePlacement::Ram) f.statics -= emb_max;
|
||||
if (emb == TablePlacement::Ram) {
|
||||
f.statics -= emb_max;
|
||||
f.expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
fixed = std::max(fixed, f.statics);
|
||||
}
|
||||
/* `fixed` and not the trial's own statics: the split clamps those to what the card can give
|
||||
@@ -511,12 +524,21 @@ int Engine::resolve_table_placement(const std::vector<VramFacts>& facts,
|
||||
VramBudget tb;
|
||||
const int st = vram_budget_trial(cfg_, with, &tb);
|
||||
const bool over = st == RAD_OK && fixed >= tb.claimable;
|
||||
if (st == RAD_OK && !over && (!tb.derived_kv || tb.kv >= kv_floor)) return true;
|
||||
/* AND THE EXPERTS KEEP A TIER: where the cache lends, those the host pool cannot hold have
|
||||
* only the card, and a table that took their room would leave them nowhere. */
|
||||
const bool starved = st == RAD_OK && tb.lends && tb.expert_ceiling > 0 &&
|
||||
tb.experts < tb.expert_floor;
|
||||
if (st == RAD_OK && !over && !starved && (!tb.derived_kv || tb.kv >= kv_floor))
|
||||
return true;
|
||||
if (st != RAD_OK)
|
||||
*why = "the card cannot hold the other weights with it";
|
||||
else if (over)
|
||||
*why = fmt("with it the fixed weights want %s of a card that has %s to give",
|
||||
humanb(fixed).c_str(), humanb(tb.claimable).c_str());
|
||||
else if (starved)
|
||||
*why = fmt("with it on the card the experts get %s, short of the %s the pinned host "
|
||||
"pool cannot hold", humanb(tb.experts).c_str(),
|
||||
humanb(tb.expert_floor).c_str());
|
||||
else
|
||||
*why = fmt("with it on the card the KV pool is %s, short of the %s one "
|
||||
"--max-model-len sequence needs", humanb(tb.kv).c_str(),
|
||||
@@ -662,7 +684,9 @@ int Engine::read_metadata() {
|
||||
meta_.n_expert_shared = geti("n_expert_shared", 0);
|
||||
meta_.rms_eps = getf("rms_eps", 1e-6);
|
||||
meta_.rope_theta = getf("rope_theta", 10000.0);
|
||||
meta_.rope_scale = getf("rope_scale", 1.0);
|
||||
/* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
|
||||
* An older container's `rope_scale` key holds the factor alone and is not read. */
|
||||
meta_.rope_scale = 1.0f;
|
||||
|
||||
/* A container that says nothing about its own shape is refused HERE, by name, rather than at
|
||||
* declare as an "invalid argument" from a plugin that was handed zeros. */
|
||||
@@ -686,6 +710,7 @@ int Engine::read_metadata() {
|
||||
default: meta_kv_v_.push_back(file_->str(kv.v.s)); break;
|
||||
}
|
||||
}
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str());
|
||||
for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str());
|
||||
@@ -720,6 +745,7 @@ int Engine::read_checkpoint_metadata() {
|
||||
}
|
||||
meta_kv_k_ = mo.keys;
|
||||
meta_kv_v_ = mo.vals;
|
||||
RAD_TRY(apply_rope_scaling());
|
||||
meta_kv_kp_.clear(); meta_kv_vp_.clear();
|
||||
for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str());
|
||||
for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str());
|
||||
@@ -733,10 +759,61 @@ int Engine::read_checkpoint_metadata() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
|
||||
* load, where the architecture's reader takes them, so an existing container serves past its
|
||||
* trained context with no reconvert -- and is checked by the same reader a converted one is. The
|
||||
* drafter, when there is one, gets the same factor over its own trained length. Then one line says
|
||||
* what the rotary is, and a context past what it covers is named. */
|
||||
int Engine::apply_rope_scaling() {
|
||||
RopeSpec spec;
|
||||
if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
|
||||
RAD_ERR("--rope-scaling '%s': yarn:FACTOR (above 1) with an optional :ORIG, or none",
|
||||
cfg_.rope_scaling.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (spec.kind != RopeSpec::Keep) {
|
||||
std::string why;
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "", meta_.n_ctx_train, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RopeKeys kv{ meta_kv_k_, meta_kv_v_ };
|
||||
if (kv.any_prefix("draft.")) {
|
||||
int64_t dtrain = meta_.n_ctx_train;
|
||||
if (const std::string* t = kv.get("draft.max_position_embeddings"))
|
||||
dtrain = std::atoll(t->c_str());
|
||||
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "draft.", dtrain, &why)) {
|
||||
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const RopeResolved r = rope_resolve(meta_kv_k_, meta_kv_v_, "");
|
||||
const long long want = cfg_.max_ctx > 0 ? (long long)cfg_.max_ctx : (long long)meta_.n_ctx_train;
|
||||
if (r.type == "yarn" && r.factor > 1.0) {
|
||||
const long long reach = (long long)(r.orig * r.factor);
|
||||
RAD_INFO("rope: YaRN factor %g over %lld trained positions -- the rotary reaches %lld; "
|
||||
"--max-model-len %lld%s", r.factor, (long long)r.orig, reach, want,
|
||||
spec.kind == RopeSpec::Yarn ? " (--rope-scaling)" : " (the container's own)");
|
||||
if (want > reach)
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions YaRN factor %g covers; "
|
||||
"positions beyond them are extrapolated", want, reach, r.factor);
|
||||
} else if (meta_.n_ctx_train > 0 && want > meta_.n_ctx_train &&
|
||||
!(r.type == "linear" && r.factor > 1.0)) {
|
||||
RAD_WARN("--max-model-len %lld is past the %lld positions the model was trained on and "
|
||||
"nothing scales its rotary, so positions beyond them are extrapolated; a model "
|
||||
"card's YaRN extension is --rope-scaling yarn:FACTOR (docs/YARN.md)", want,
|
||||
(long long)meta_.n_ctx_train);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ================================================================== 3 + 4. plugins, declare */
|
||||
int Engine::load_plugins() {
|
||||
int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy,
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_);
|
||||
meta_.arch_id, meta_.quant ? meta_.quant : "", &plugins_,
|
||||
ckpt_ && ckpt_->imports() != Checkpoint::Import::None);
|
||||
if (s < 0) {
|
||||
/* rad_tools_load_plugins has said why -- a plugin refused, or no architecture plugin for
|
||||
* this model -- each by name. What it does not know is that this was the engine's start. */
|
||||
@@ -1064,6 +1141,7 @@ int Engine::plan() {
|
||||
/* The placement flags' tables, per rank where they are sharded (the embedding) and once
|
||||
* where they are not (the n-gram table every rank reads from the one mapping). */
|
||||
std::vector<int64_t> emb_bytes;
|
||||
std::vector<WeightFootprint> wfs;
|
||||
int64_t ngram_bytes = 0, kv_floor = 0;
|
||||
bool ngram_device = false, ngram_host = false;
|
||||
const int64_t ctx = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
@@ -1106,6 +1184,12 @@ int Engine::plan() {
|
||||
weight_footprint(r->program, &wf, TablePlacement::Vram, TablePlacement::Disk);
|
||||
f.statics = wf.statics;
|
||||
f.experts = wf.experts;
|
||||
/* The expert floor waits for the tables' placement: the embedding may take its share
|
||||
* of the host pool first. */
|
||||
wfs.push_back(wf);
|
||||
/* THE CACHE LENDS where units move and the pool can give its blocks back in place. */
|
||||
f.lends = VMem::supported() && !cfg_.deterministic &&
|
||||
(cfg_.placement == "auto" || cfg_.placement == "expert_tiered");
|
||||
emb_bytes.push_back(wf.embedding);
|
||||
ngram_bytes = std::max(ngram_bytes, wf.ngram);
|
||||
ngram_device = ngram_device || wf.ngram_device;
|
||||
@@ -1118,8 +1202,10 @@ int Engine::plan() {
|
||||
Config one = cfg_;
|
||||
one.max_seqs = 1;
|
||||
KVManager single;
|
||||
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK)
|
||||
if (single.plan_groups(r->program.kv_groups, one) == RAD_OK) {
|
||||
kv_floor = std::max(kv_floor, single.ceiling(ctx));
|
||||
f.kv_one = single.ceiling(ctx);
|
||||
}
|
||||
}
|
||||
/* THE STAGING REGION IS SIZED ONLY WHERE THE ARENA LENDS ITS TOP: with no smaller level
|
||||
* nothing gives the region back to the slab at decode, and a deterministic plan moves
|
||||
@@ -1167,13 +1253,28 @@ int Engine::plan() {
|
||||
late_lazy_bytes_ = std::max(late_lazy_bytes_, lazy);
|
||||
facts.push_back(f);
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, kv_floor, ngram_bytes, ngram_device,
|
||||
ngram_host));
|
||||
/* THE PINNED HOST POOL IS THE EXPERTS' OTHER HOME, less what Planner::plan takes out of it
|
||||
* before any expert: the embedding when it is placed there, and the file tier's staging.
|
||||
* Both floors are known before the tables are placed, so placing them can ask whether the
|
||||
* experts would still have a tier. */
|
||||
std::vector<int64_t> floor_emb_ram(facts.size(), 0);
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
int64_t room = cfg_.host_pool_mib * ((int64_t)1 << 20);
|
||||
if (cfg_.weights_disk_tier)
|
||||
room -= file_stage_reserve(wfs[i].layer_unit_max, wfs[i].routed);
|
||||
facts[i].expert_floor = expert_vram_floor(wfs[i], std::max<int64_t>(room, 0));
|
||||
floor_emb_ram[i] = expert_vram_floor(wfs[i], std::max<int64_t>(room - emb_bytes[i], 0));
|
||||
}
|
||||
RAD_TRY(resolve_table_placement(facts, emb_bytes, floor_emb_ram, kv_floor, ngram_bytes,
|
||||
ngram_device, ngram_host));
|
||||
/* The n-gram table was counted off the card; on it, it is every rank's whole table. */
|
||||
if (cfg_.ngram_resolved == TablePlacement::Vram)
|
||||
for (VramFacts& f : facts) f.statics += ngram_bytes;
|
||||
if (cfg_.embedding_resolved == TablePlacement::Ram)
|
||||
for (size_t i = 0; i < facts.size(); ++i) facts[i].statics -= emb_bytes[i];
|
||||
for (size_t i = 0; i < facts.size(); ++i) {
|
||||
facts[i].statics -= emb_bytes[i];
|
||||
facts[i].expert_floor = floor_emb_ram[i];
|
||||
}
|
||||
VramBudget vb;
|
||||
RAD_TRY(vram_budget_resolve(cfg_, facts, &vb));
|
||||
if (!vb.report.empty()) RAD_INFO("%s", vb.report.c_str());
|
||||
@@ -1187,9 +1288,111 @@ int Engine::plan() {
|
||||
r->program.arena_stage_bytes = vb.stage;
|
||||
r->program.arena_bytes = r->program.arena_stage_off + vb.stage;
|
||||
}
|
||||
|
||||
/* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
|
||||
*
|
||||
* The split above is the dearest rank's, applied to every card, and one block table serves
|
||||
* every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
|
||||
* costs less per token (an attention-zero rank keeps no attention cache, only what its
|
||||
* other groups cost) would reserve the common KV pool and page a fraction of it, while its
|
||||
* experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
|
||||
* KV pool that pages exactly the common token count and the difference in its weights
|
||||
* pool, up to every one of its weights resident. The token count, the carve, the loan and
|
||||
* the dearest ranks' pools are what they were.
|
||||
*
|
||||
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
|
||||
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
|
||||
* its weights would choose all_vram while its peers spill -- one strategy per world is the
|
||||
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
|
||||
* does not lend (--deterministic, or a device without virtual memory management) is
|
||||
* re-split all the same: the bytes it would never page are bytes its experts can hold, and
|
||||
* without virtual memory management they are allocated whole.
|
||||
* Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
|
||||
* on every rank, field for field. A rank that qualifies and is not re-split is named with
|
||||
* the reason, once. */
|
||||
rank_cfg_.assign(ranks_.size(), cfg_);
|
||||
kv_planned_tokens_ = 0;
|
||||
constexpr int64_t kMiB = (int64_t)1 << 20;
|
||||
int64_t kv_max = 0;
|
||||
for (const VramFacts& f : facts) kv_max = std::max(kv_max, f.kv_ceiling);
|
||||
std::vector<size_t> cheaper;
|
||||
for (size_t i = 0; i < facts.size() && i < ranks_.size(); ++i)
|
||||
if (facts[i].kv_ceiling < kv_max) cheaper.push_back(i);
|
||||
/* Why no cheaper rank is re-split, where the reason holds for the whole world. */
|
||||
std::string kept;
|
||||
std::vector<std::unique_ptr<KVManager>> probes(ranks_.size());
|
||||
int64_t T = -1;
|
||||
if (cheaper.empty()) {
|
||||
/* Every rank's cache costs the same per token: there is nothing to re-split. */
|
||||
} else if (!vb.derived_kv || !vb.derived_weights) {
|
||||
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
|
||||
} else if (cfg_.placement != "expert_tiered") {
|
||||
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
|
||||
cfg_.placement.c_str());
|
||||
} else {
|
||||
/* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
|
||||
* pool, the least of them. Asked of the same plan configure_kv makes, against the same
|
||||
* bytes: nothing reserves from a KV pool before its carve. */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
const int64_t t = probes[i]->paged_tokens(cfg_.vram_kv_mib * kMiB);
|
||||
if (t == KVManager::kUnboundedTokens) continue;
|
||||
if (T < 0 || t < T) T = t;
|
||||
}
|
||||
if (kept.empty() && T <= 0)
|
||||
kept = "no rank's cache pages a bounded token count in the common pool";
|
||||
}
|
||||
for (size_t i : cheaper) {
|
||||
const std::string costs =
|
||||
fmt("kv: rank %d's cache costs %s at the worst case where its dearest peer's costs "
|
||||
"%s", ranks_[i]->index, humanb(facts[i].kv_ceiling).c_str(),
|
||||
humanb(kv_max).c_str());
|
||||
if (!kept.empty()) {
|
||||
RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
|
||||
continue;
|
||||
}
|
||||
/* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
|
||||
* pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
|
||||
* a pool whose budget is exactly this many MiB. The pool's own alignment is already
|
||||
* among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
|
||||
const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
|
||||
if (need < 0) {
|
||||
RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
|
||||
"tokens in the common %lld MiB", costs.c_str(), (long long)T,
|
||||
(long long)cfg_.vram_kv_mib);
|
||||
continue;
|
||||
}
|
||||
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
|
||||
const RankSplit rs =
|
||||
vram_budget_rank_split(cfg_.vram_weights_mib, cfg_.vram_kv_mib, need, cap);
|
||||
if (!rs.resplit) {
|
||||
RAD_INFO("%s; its pools stay the common split: it needs all %lld MiB of the common "
|
||||
"pool to page the common %lld tokens", costs.c_str(),
|
||||
(long long)cfg_.vram_kv_mib, (long long)T);
|
||||
continue;
|
||||
}
|
||||
rank_cfg_[i].vram_kv_mib = rs.kv_mib;
|
||||
rank_cfg_[i].vram_weights_mib = rs.weights_mib;
|
||||
kv_planned_tokens_ = T;
|
||||
RAD_INFO("%s, so its KV pool pages the common %lld tokens in %lld MiB instead of %lld; "
|
||||
"its weights pool grows %lld -> %lld MiB (every weight resident wants %s)%s",
|
||||
costs.c_str(), (long long)T, (long long)rs.kv_mib, (long long)cfg_.vram_kv_mib,
|
||||
(long long)cfg_.vram_weights_mib, (long long)rs.weights_mib,
|
||||
humanb(cap).c_str(),
|
||||
rs.unusable_mib > 0
|
||||
? fmt(", and %lld MiB stay unclaimed", (long long)rs.unusable_mib).c_str()
|
||||
: "");
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
/* This rank's own split: cfg_ field for field unless the block above re-split it. */
|
||||
const Config& rc = rank_cfg_[ri];
|
||||
LogRank lr(r->index);
|
||||
/* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
|
||||
* reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
|
||||
@@ -1203,18 +1406,18 @@ int Engine::plan() {
|
||||
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
|
||||
* inference about what the workload will be (spec §6). Pools refuses by name and by how
|
||||
* much rather than shrinking anything. */
|
||||
int s = r->pools.configure(cfg_, props.vram_bytes);
|
||||
int s = r->pools.configure(rc, props.vram_bytes);
|
||||
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
|
||||
if (s < 0) {
|
||||
report_pool_refusal(r->index, r->device, r->pools, cfg_);
|
||||
report_pool_refusal(r->index, r->device, r->pools, rc);
|
||||
return s;
|
||||
}
|
||||
|
||||
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
|
||||
* against its own card's budget (spec §5.3). */
|
||||
* against its own card's budget (spec §5.3) -- the same split its pools were given. */
|
||||
PlannerInput in{};
|
||||
in.program = &r->program;
|
||||
in.config = &cfg_;
|
||||
in.config = &rc;
|
||||
in.rank = r->index;
|
||||
in.world_size = cfg_.tp;
|
||||
if (file_ && file_->header().prof_count) {
|
||||
@@ -1227,6 +1430,16 @@ int Engine::plan() {
|
||||
if (cfg_.debug_placement || s < 0)
|
||||
fputs(r->plan.report(r->program).c_str(), stderr);
|
||||
if (s < 0) return s;
|
||||
/* The slab the planner filled is the pool the mover will fill: one split, read twice. */
|
||||
RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
|
||||
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
|
||||
* re-split rank whose grown weights pool took every weight still holds it. Said, because
|
||||
* the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
|
||||
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
|
||||
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
|
||||
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
|
||||
"holds no weights; its %lld MiB (--host-pool-mib) stay allocated, as on every "
|
||||
"rank", r->index, (long long)cfg_.host_pool_mib);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -1388,6 +1601,27 @@ public:
|
||||
rad_stream_destroy(uplinks_[(size_t)d].st);
|
||||
uplinks_[(size_t)d].st = nullptr;
|
||||
}
|
||||
/* EVERY STAGED WEIGHT MUST HAVE BEEN DELIVERED. One nothing arrived for was never laid out
|
||||
* and its slot holds whatever the card had there: zeros on a card whose freed memory the
|
||||
* driver wipes, which is how such a slot serves for months unnoticed, and garbage on one
|
||||
* that has just been through a reset. Refusing here is what makes the hole visible. */
|
||||
if (status_ == RAD_OK && !audited_) {
|
||||
audited_ = true;
|
||||
int64_t undelivered = 0;
|
||||
for (const StagedWeight& s : items_)
|
||||
if (s.remaining > 0) {
|
||||
if (undelivered < 4)
|
||||
RAD_ERR("load: '%s' was staged and nothing delivered its %s: its slot was "
|
||||
"never written", s.prog->weights[s.wi].name.c_str(),
|
||||
humanb(s.remaining).c_str());
|
||||
++undelivered;
|
||||
}
|
||||
if (undelivered) {
|
||||
RAD_ERR("load: %lld staged weight(s) were never delivered; the model cannot run",
|
||||
(long long)undelivered);
|
||||
status_ = RAD_E_STATE;
|
||||
}
|
||||
}
|
||||
return status_;
|
||||
}
|
||||
|
||||
@@ -1664,6 +1898,7 @@ private:
|
||||
std::vector<int> out_; /* copies outstanding out of each sweep window */
|
||||
int64_t budget_ = 0, held_ = 0, pending_ = 0, peak_ = 0;
|
||||
bool done_ = false;
|
||||
bool audited_ = false; /* finish() runs its delivery audit once; the destructor calls it again */
|
||||
std::atomic<bool> failed_{false};
|
||||
int status_ = RAD_OK;
|
||||
};
|
||||
@@ -1979,11 +2214,11 @@ static int fill_from_checkpoint(const CkptWeight& cw, const std::vector<PlaneSha
|
||||
std::string why;
|
||||
for (size_t k = 0; k < shares.size(); ++k) {
|
||||
const PlaneShare& sh = shares[k];
|
||||
uint8_t* at = in + offs[k];
|
||||
const RadEncPlane& p = cw.enc.plane[sel[k]];
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&p, cw.rows, cw.cols, &pr, &pc);
|
||||
const int64_t crb = rad_enc_row_bytes(p.dtype, pc);
|
||||
uint8_t* at = in + offs[k];
|
||||
for (const PlaneShare::Rect& q : sh.rects) {
|
||||
if (q.byte0 == 0 && q.bytes == sh.row_bytes) {
|
||||
const int64_t off = q.row0 * sh.row_bytes, n = q.rows * sh.row_bytes;
|
||||
@@ -2484,21 +2719,93 @@ int Engine::configure_kv() {
|
||||
/* Resolved once, for the cache below and for Scheduler::init later. Resolving it separately in
|
||||
* each is how the two come to disagree, and the interval is the field where that shows. */
|
||||
RAD_TRY(chunk_geometry_resolve(ranks_[0]->program, cfg_, &geo_));
|
||||
/* ONE BLOCK TABLE SERVES EVERY RANK (serve() checks it), so every rank carves the SAME number
|
||||
* of paged blocks. The ranks' pools are not the same size under an uneven tensor-parallel
|
||||
* split -- a rank with more delta-net heads holds more recurrent state, a rank with zero
|
||||
* attention weights has more pool -- so each is planned first, asked what it could carve, and
|
||||
* every rank is capped at the least before any carves. At an even split the cap is what
|
||||
* every rank would have carved anyway. */
|
||||
int64_t least = -1;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
|
||||
* construction: its pool is the least whole MiB whose paged split reaches it, asked of the
|
||||
* same plan against the same bytes. Short of it, this rank would set every rank's count
|
||||
* under what its dearest peer pages -- a broken construction, refused by name. */
|
||||
if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
|
||||
RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
|
||||
"and pages %lld: the pool and the plan that sized it disagree", r->index,
|
||||
(long long)rank_cfg_[i].vram_kv_mib, (long long)kv_planned_tokens_,
|
||||
(long long)t);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
|
||||
if (least < 0 || t < least) least = t;
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(rad_dev_set(r->device)); /* allocates on the CURRENT device; see plan() */
|
||||
RAD_TRY(r->kv.configure(r->program.kv_groups, cfg_, r->pools.kv()));
|
||||
if (ranks_.size() > 1) {
|
||||
const int64_t own = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
if (own > least && own != KVManager::kUnboundedTokens)
|
||||
RAD_INFO("kv: rank %d could page %lld tokens and carves %lld, the least rank's, so "
|
||||
"that one block table serves every rank", r->index, (long long)own,
|
||||
(long long)least);
|
||||
r->kv.cap_paged_tokens(least);
|
||||
}
|
||||
RAD_TRY(r->kv.carve(r->pools.kv()));
|
||||
/* THE ONE CASE WHERE THE CACHE CANNOT GIVE ANYTHING BACK, said once and named. Every
|
||||
* caller is written against the elastic contract and runs unchanged here -- the pool
|
||||
* simply holds its whole carve -- so nothing fails, and the only symptom is an expert
|
||||
* plane that never grows and a split that stays where --expert-vs-cache-ratio put it.
|
||||
* plane that never grows and a split that stays where the budget put it.
|
||||
* That is worth a line, because it is indistinguishable from a working run in every
|
||||
* counter this engine reports. */
|
||||
if (r->index == 0 && !r->pools.kv().elastic())
|
||||
RAD_WARN("this device has no virtual memory management, so the KV cache holds its "
|
||||
"whole carve and the expert slab has nothing to grow into. The split stays "
|
||||
"where --expert-vs-cache-ratio put it.");
|
||||
"whole carve and the expert slab has nothing to grow into. The experts were "
|
||||
"given the card first and the cache one full-length sequence.");
|
||||
if (cfg_.debug_placement) fputs(r->kv.report().c_str(), stderr);
|
||||
}
|
||||
|
||||
/* ---------------- the linear-state snapshot store ---------------- */
|
||||
/* PINNED HOST MEMORY, NOT THE CARD. A snapshot is a copy of a sequence's recurrent state that
|
||||
* no kernel reads: a save copies the state out after the step that produced it and a hit
|
||||
* copies it back before the step that resumes from it, each a few milliseconds across the
|
||||
* link. Holding it in VRAM would charge the KV pool for memory the live cache could use.
|
||||
*
|
||||
* One slot holds every rank's shard, each at its own offset, so the disk tier moves a slot as
|
||||
* one payload; rank 0's manager hands the ids out. Opened only where there is something to
|
||||
* snapshot and a cache to serve it. */
|
||||
{
|
||||
/* THE SHARDS NEED NOT BE EQUAL: a rank's state holds its own heads of each group, and a
|
||||
* world the heads do not divide gives the ranks different shares. A slot is the sum of
|
||||
* the ranks' shards and a rank's starts where the ranks before it end. */
|
||||
std::vector<int64_t> shard_off(ranks_.size(), 0);
|
||||
int64_t slot = 0;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
shard_off[i] = slot;
|
||||
slot += ranks_[i]->kv.checkpoint_bytes();
|
||||
}
|
||||
const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0;
|
||||
if (slot > 0 && n > 0 && cfg_.prefix_cache) {
|
||||
if (ck_store_.open(slot, slot * n) != RAD_OK) {
|
||||
RAD_WARN("checkpoint slots: no pinned host memory for %lld snapshot(s) of %s; a "
|
||||
"hybrid session's prefix hits replay their linear layers from zero. "
|
||||
"Lower --checkpoint-slots.", (long long)n, humanb(slot).c_str());
|
||||
} else {
|
||||
RAD_INFO("checkpoint slots: %lld linear-state snapshot(s) of %s in pinned host "
|
||||
"memory (%s), none of it on the card", (long long)n,
|
||||
humanb(slot).c_str(), humanb(ck_store_.cap_bytes()).c_str());
|
||||
}
|
||||
}
|
||||
for (auto& r : ranks_)
|
||||
r->kv.set_checkpoint_store(&ck_store_, shard_off[(size_t)(&r - &ranks_[0])]);
|
||||
}
|
||||
for (auto& r : ranks_) {
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(r->prefix.configure(cfg_, &r->kv, geo_.checkpoint_interval));
|
||||
}
|
||||
|
||||
@@ -2516,17 +2823,29 @@ int Engine::configure_kv() {
|
||||
{
|
||||
const bool tier_asked = cfg_.prefix_cache_host_mib > 0 || cfg_.prefix_cache_disk_mib > 0;
|
||||
const std::vector<int32_t>& cg = ranks_[0]->prefix.cached_groups();
|
||||
int64_t entry_bytes = 0;
|
||||
for (int32_t g : cg) {
|
||||
const KVGroupPlan* p = ranks_[0]->kv.plan(g);
|
||||
if (p && p->paged()) entry_bytes += p->bytes_per_block;
|
||||
}
|
||||
/* ONE SLOT HOLDS EVERY RANK'S SHARD. An entry under tensor parallelism is n_ranks
|
||||
* pieces of KV that are not interchangeable, so the unit the tiers store and budget
|
||||
* in is the whole thing; each rank writes only its own window of it. */
|
||||
const int64_t slot_bytes = entry_bytes * (int64_t)ranks_.size();
|
||||
* in is the whole thing; each rank writes only its own window of it. THE SHARDS NEED
|
||||
* NOT BE EQUAL -- a rank's block holds its own heads of a group, and a world the heads
|
||||
* do not divide gives the ranks different shares, or none (rad_kv_group_zero) -- so a
|
||||
* slot is the SUM of the ranks' entries and a rank's window starts where the ranks
|
||||
* before it end. Where every rank's share is the same this is n_ranks times one entry
|
||||
* at offsets of one entry, as it always was. The sizing below (TierExec::sizes) takes
|
||||
* the largest rank's entry: the staging ring is a rank's own, and the ring that fits
|
||||
* the largest fits every one. */
|
||||
std::vector<int64_t> rank_entry(ranks_.size(), 0), entry_off(ranks_.size(), 0);
|
||||
int64_t entry_bytes = 0, slot_bytes = 0;
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
for (int32_t g : cg) {
|
||||
const KVGroupPlan* p = ranks_[i]->kv.plan(g);
|
||||
if (p && p->paged()) rank_entry[i] += p->bytes_per_block;
|
||||
}
|
||||
entry_off[i] = slot_bytes;
|
||||
slot_bytes += rank_entry[i];
|
||||
entry_bytes = std::max(entry_bytes, rank_entry[i]);
|
||||
}
|
||||
|
||||
/* ---- how the tier is split between the two halves of a session ----
|
||||
/* ---- how the disk tier is split between the two halves of a session ----
|
||||
*
|
||||
* ON THIS BUILD A RESTORED HYBRID SESSION WITH NO SNAPSHOT REUSES NOTHING AT ALL. The
|
||||
* scheduler clamps its reuse to the last reachable checkpoint and says why: RadBatch
|
||||
@@ -2551,9 +2870,12 @@ int Engine::configure_kv() {
|
||||
*
|
||||
* Two thirds is the ceiling. Not because the arithmetic asks for one, but because the
|
||||
* clamp above is a property of THIS build rather than of the design, and a tier with
|
||||
* almost no room for blocks would be badly sized the day it is lifted. */
|
||||
const int64_t ck_slot_bytes = ranks_[0]->kv.checkpoint_bytes() * (int64_t)ranks_.size();
|
||||
int64_t ck_host_cap = 0, ck_disk_slots = 0;
|
||||
* almost no room for blocks would be badly sized the day it is lifted.
|
||||
*
|
||||
* THE HOST TIER IS NOT SPLIT: snapshots live in the checkpoint store, which
|
||||
* --checkpoint-slots sizes, and --prefix-cache-host-mib is the blocks' alone. */
|
||||
const int64_t ck_slot_bytes = ck_store_.enabled() ? ck_store_.slot_bytes() : 0;
|
||||
int64_t ck_disk_slots = 0;
|
||||
if (ck_slot_bytes > 0) {
|
||||
const int64_t bs = ranks_[0]->prefix.block_size();
|
||||
const int64_t iv = ranks_[0]->prefix.checkpoint_interval();
|
||||
@@ -2566,19 +2888,13 @@ int Engine::configure_kv() {
|
||||
const int64_t sess_blocks = bs > 0 ? (mlen / bs) * slot_bytes : slot_bytes;
|
||||
const int64_t sess_snaps = retained * ck_slot_bytes;
|
||||
const int64_t denom = sess_blocks + sess_snaps;
|
||||
const int64_t host_cap = cfg_.prefix_cache_host_mib << 20;
|
||||
const int64_t disk_cap = cfg_.prefix_cache_disk_mib << 20;
|
||||
const int64_t host_ck = std::min(host_cap * 2 / 3, denom > 0 ? host_cap / denom * sess_snaps
|
||||
+ host_cap % denom * sess_snaps / denom
|
||||
: 0);
|
||||
const int64_t disk_ck = std::min(disk_cap * 2 / 3, denom > 0 ? disk_cap / denom * sess_snaps
|
||||
+ disk_cap % denom * sess_snaps / denom
|
||||
: 0);
|
||||
ck_host_cap = (host_ck / ck_slot_bytes) * ck_slot_bytes;
|
||||
ck_disk_slots = disk_ck / ck_slot_bytes;
|
||||
/* One of each where there is room for one at all: a tier that holds a session's blocks
|
||||
* and not one snapshot holds nothing usable. */
|
||||
if (ck_host_cap == 0 && host_cap >= ck_slot_bytes * 2) ck_host_cap = ck_slot_bytes;
|
||||
/* One where there is room for one at all: a tier that holds a session's blocks and not
|
||||
* one snapshot holds nothing usable. */
|
||||
if (ck_disk_slots == 0 && disk_cap >= ck_slot_bytes * 2) ck_disk_slots = 1;
|
||||
}
|
||||
if (cg.empty() || entry_bytes <= 0) {
|
||||
@@ -2601,16 +2917,20 @@ int Engine::configure_kv() {
|
||||
sc.n_ckpt_slots = ck_disk_slots;
|
||||
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
|
||||
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only
|
||||
* meaningful under the container and layout that produced it; read back under
|
||||
* another, it is a lossless function of somebody else's weights. */
|
||||
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
|
||||
* everything a cached block's bytes actually depend on. Read back under a
|
||||
* different container, layout or KV width, a block is a lossless function of
|
||||
* somebody else's weights -- fluent, confident and wrong. There is no cheaper
|
||||
* check than refusing the whole store, because a block carries no evidence of
|
||||
* what produced it beyond the tokens it was keyed by. */
|
||||
* different container, layout, KV width or rotary, a block is a lossless
|
||||
* function of somebody else's weights -- fluent, confident and wrong. There is
|
||||
* no cheaper check than refusing the whole store, because a block carries no
|
||||
* evidence of what produced it beyond the tokens it was keyed by.
|
||||
*
|
||||
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
|
||||
* (rope_identity): a YaRN container converted from the same checkpoint has the
|
||||
* same name and shapes as the stock one, and every cached key and QSA block key
|
||||
* is rotated differently under it. */
|
||||
{
|
||||
char theta[32];
|
||||
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
|
||||
const std::string id =
|
||||
std::string(meta_.name ? meta_.name : "") + "|" +
|
||||
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
|
||||
@@ -2618,7 +2938,8 @@ int Engine::configure_kv() {
|
||||
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
|
||||
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
|
||||
cfg_.kv_cache_dtype + "|" +
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION;
|
||||
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
|
||||
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
|
||||
uint64_t h = 1469598103934665603ull;
|
||||
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
|
||||
sc.fingerprint = h;
|
||||
@@ -2638,7 +2959,7 @@ int Engine::configure_kv() {
|
||||
tc.disk_cap_bytes = kv_disk_ ? (cfg_.prefix_cache_disk_mib << 20) : 0;
|
||||
tc.entry_bytes = slot_bytes;
|
||||
tc.ckpt_bytes = ck_slot_bytes;
|
||||
tc.ckpt_cap_bytes = ck_host_cap;
|
||||
tc.ckpt_slots = ck_store_.capacity();
|
||||
tc.ckpt_disk_slots = kv_disk_ ? ck_disk_slots : 0;
|
||||
|
||||
/* THE POLICY IS RANK 0'S AND THE TRANSFER IS EVERY RANK'S. A session is not sharded --
|
||||
@@ -2690,8 +3011,8 @@ int Engine::configure_kv() {
|
||||
max_batch, max_copy, max_chain,
|
||||
/*leader=*/&r == &ranks_[0],
|
||||
r->device,
|
||||
(int64_t)(&r - &ranks_[0]) * entry_bytes,
|
||||
(int64_t)(&r - &ranks_[0]) * ranks_[0]->kv.checkpoint_bytes(),
|
||||
entry_off[(size_t)(&r - &ranks_[0])],
|
||||
&ck_store_,
|
||||
/*shared=*/r->mover.transfer_stream())
|
||||
!= RAD_OK) {
|
||||
all = false;
|
||||
@@ -2707,7 +3028,7 @@ int Engine::configure_kv() {
|
||||
T.close();
|
||||
kv_disk_.reset();
|
||||
tc.host_cap_bytes = tc.disk_cap_bytes = 0;
|
||||
tc.ckpt_cap_bytes = tc.ckpt_disk_slots = 0;
|
||||
tc.ckpt_disk_slots = 0;
|
||||
RAD_TRY(T.configure(tc, nullptr));
|
||||
} else {
|
||||
/* The tiers can lose an entry without the cache asking: a capacity drop, or a
|
||||
@@ -2716,10 +3037,10 @@ int Engine::configure_kv() {
|
||||
T.set_drop_sink([this](const BlockHash& h) {
|
||||
ranks_[0]->prefix.drop_offdevice(h);
|
||||
});
|
||||
/* And the linear half on its own. The snapshot store is far smaller than the
|
||||
* block store, so it overflows first and by itself; an index entry left
|
||||
* behind would be a checkpoint the cache goes on offering whose bytes nobody
|
||||
* holds, which is the recurrent-state form of the same corruption. */
|
||||
/* And the linear half on its own: a snapshot whose only copy was on disk and
|
||||
* that the disk store let go of. An index entry left behind would be a
|
||||
* checkpoint the cache goes on offering whose bytes nobody holds, which is the
|
||||
* recurrent-state form of the same corruption. */
|
||||
T.set_snapshot_drop_sink([this](const BlockHash& h) {
|
||||
ranks_[0]->prefix.drop_snapshot(h);
|
||||
});
|
||||
@@ -2784,9 +3105,10 @@ int Engine::configure_kv() {
|
||||
* that request is accepted by the API and can never complete, whatever the load. */
|
||||
RAD_WARN("kv group '%s' holds %lld tokens but the context limit is %lld: ONE request "
|
||||
"longer than %lld tokens is accepted by the API and then refused as too "
|
||||
"large to ever fit -- this is a hard limit, not a backing ratio. Raise "
|
||||
"--expert-vs-cache-ratio toward the cache (about %lld MiB more for the whole "
|
||||
"context), halve the cost a token with --kv-cache-dtype fp8, or lower "
|
||||
"large to ever fit -- this is a hard limit, not a backing ratio. Give the "
|
||||
"cache more (about %lld MiB for the whole context: a larger --host-pool-mib "
|
||||
"takes experts off the card), halve the cost a token with --kv-cache-dtype fp8, "
|
||||
"or lower "
|
||||
"--max-model-len to %lld.",
|
||||
p->name.c_str(), (long long)cap, (long long)want, (long long)cap,
|
||||
(long long)(((want - cap) / p->block_size * p->bytes_per_block) >> 20),
|
||||
@@ -2855,18 +3177,6 @@ static void bind_kv_pools(const Program& p, const KVManager& kv, std::vector<KVP
|
||||
}
|
||||
|
||||
/* ================================================================== start */
|
||||
void Engine::set_checkpoint_floors(int64_t keep) {
|
||||
for (auto& r : ranks_) {
|
||||
const int dev = r->device;
|
||||
r->kv.set_checkpoint_floor([dev](int64_t* free_now) -> int {
|
||||
RadDeviceProps p{};
|
||||
RAD_TRY(rad_dev_props(dev, &p));
|
||||
*free_now = p.vram_free;
|
||||
return RAD_OK;
|
||||
}, keep);
|
||||
}
|
||||
}
|
||||
|
||||
int Engine::start() {
|
||||
std::vector<int> devs;
|
||||
std::string inventory;
|
||||
@@ -2903,9 +3213,11 @@ int Engine::start() {
|
||||
/* PEER ACCESS, MEASURED BEFORE ANYTHING IS SELECTED. A kernel that reads or writes another
|
||||
* card's memory says so with a constraint on device.p2p (rad_types.h), and the selector reads
|
||||
* it from here: on a machine where some pair of the ranks' cards cannot reach each other such a
|
||||
* kernel is not selected, and declare names the constraint instead of the all-reduce faulting
|
||||
* or hanging on its first message. Every ordered pair, because access is granted one way at a
|
||||
* time. */
|
||||
* kernel is not selected, and one that exchanges through host memory takes the op instead (or
|
||||
* declare names the constraint) rather than the all-reduce faulting or hanging on its first
|
||||
* message. Every ordered pair, because access is granted one way at a time. --p2p overrides the
|
||||
* answer in one direction each way (Config::p2p): off turns it down whatever the driver says,
|
||||
* on refuses to start without it. */
|
||||
{
|
||||
long long p2p = 1;
|
||||
std::string blocked;
|
||||
@@ -2923,14 +3235,27 @@ int Engine::start() {
|
||||
blocked += fmt("%s%d->%d", blocked.empty() ? "" : ", ", devs[i], devs[j]);
|
||||
}
|
||||
}
|
||||
if (cfg_.tp > 1 && cfg_.p2p == RAD_P2P_ON && !p2p) {
|
||||
RAD_ERR("device: --p2p on, but the driver reports no peer-to-peer access between cards "
|
||||
"%s. IOMMU settings and the PCIe topology decide this, not radiance; --p2p auto "
|
||||
"serves through host memory instead", blocked.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const bool forced_off = cfg_.p2p == RAD_P2P_OFF;
|
||||
if (forced_off) p2p = 0;
|
||||
rad_tools_registry().set_device_fact(RAD_FACT_P2P, p2p);
|
||||
if (cfg_.tp > 1) {
|
||||
if (p2p) RAD_INFO("device: the %d cards reach each other's memory directly (peer to "
|
||||
"peer)", cfg_.tp);
|
||||
else RAD_WARN("device: no peer-to-peer access between cards %s. A kernel that needs "
|
||||
"it (device.p2p == 1) is not selected; if nothing else implements its "
|
||||
"op, startup stops below naming it. IOMMU settings and the PCIe "
|
||||
"topology decide this, not radiance", blocked.c_str());
|
||||
else if (forced_off)
|
||||
RAD_INFO("device: --p2p off: the collectives exchange through pinned host memory%s",
|
||||
blocked.empty() ? " although the driver reports peer-to-peer access"
|
||||
: "");
|
||||
else RAD_WARN("device: no peer-to-peer access between cards %s. The collectives "
|
||||
"exchange through pinned host memory instead, and a kernel that needs "
|
||||
"peer access (device.p2p == 1) is not selected; if nothing else "
|
||||
"implements its op, startup stops below naming it. IOMMU settings and "
|
||||
"the PCIe topology decide this, not radiance", blocked.c_str());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3067,6 +3392,35 @@ int Engine::start() {
|
||||
}
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
|
||||
/* THE MOST THE CACHE CAN HOLD, said once in one line: the whole carve, with every block it lends
|
||||
* the experts taken back -- which a request that needs them does, the same step. Tokens are the
|
||||
* paged groups' shared axis, so the smallest of theirs; a windowed group bounds how far back a
|
||||
* sequence keeps context, not how much fits, and is left out. The /stats and /metrics figures
|
||||
* (kv_tokens_max, radiance:kv_cache_max_tokens) are the same numbers. */
|
||||
{
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
int64_t bytes = 0, state = 0, tokens = 0;
|
||||
for (const KVGroupPlan& p : kv.plans()) {
|
||||
bytes += kv.pool_bytes_carved(p.index);
|
||||
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
|
||||
if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue;
|
||||
const int64_t t = p.n_blocks * p.block_size;
|
||||
if (tokens == 0 || t < tokens) tokens = t;
|
||||
}
|
||||
const int64_t mlen = cfg_.max_ctx > 0 ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
const int64_t lent = lending_ ? ranks_[0]->mover.flex_capacity() : 0;
|
||||
if (bytes > 0)
|
||||
RAD_INFO("kv: the cache can grow to %s a card -- %lld tokens of context, %.1f sessions at "
|
||||
"%lld -- with every block it lends the experts taken back; %s of that is "
|
||||
"per-sequence state, and %s",
|
||||
humanb(bytes).c_str(), (long long)tokens,
|
||||
mlen > 0 ? (double)tokens / (double)mlen : 0.0, (long long)mlen,
|
||||
humanb(state).c_str(),
|
||||
lent > 0 ? fmt("up to %s is lent to the experts while no request holds it",
|
||||
humanb(lent).c_str()).c_str()
|
||||
: "nothing is lent: it is all the cache's");
|
||||
}
|
||||
|
||||
/* ---- AND THE TOP OF THE ACTIVATION ARENA, lent while the steps are small ----------------
|
||||
*
|
||||
* One stretch a rank: from the end of the full plan's transients down to the end of the
|
||||
@@ -3163,131 +3517,86 @@ int Engine::start() {
|
||||
*
|
||||
* Everything above this line allocated: the two pools, the activation arena, the step batch
|
||||
* staging, the weight tables a grouped GEMM walks. What is left on the card should now be
|
||||
* --gpu-headroom-mib and nothing else, and this is the only place that can say whether it is.
|
||||
* --gpu-headroom-mib plus what the budget kept for later, and this is the only place that can
|
||||
* say whether it is.
|
||||
*
|
||||
* Both directions are worth a line. TOO LITTLE means the terms the resolver could not compute
|
||||
* -- anything still allocated lazily, and whatever the driver took after the reading -- ate
|
||||
* into the memory the operator asked to keep, and the next thing to allocate on this card is
|
||||
* whatever fails. TOO MUCH means the budget left VRAM on the floor, which on a model whose
|
||||
* experts do not fit is milliseconds of decode step for every unspent GiB -- the exact
|
||||
* failure this resolver exists to remove.
|
||||
* TOO LITTLE is memory taken after the budget read the card that the budget did not count:
|
||||
* another process on the card (a desktop, a second server), or a driver allocation made
|
||||
* after the reading. It comes out of the room a kernel's first launch allocates its code
|
||||
* object and scratch from, and running out of that is a fault inside the HIP runtime.
|
||||
*
|
||||
* A slack of one arena is tolerated silently: MiB rounding and a kernel plugin's own
|
||||
* workspaces live in there, and naming a number this close to right would be noise. */
|
||||
/* DOES A DECOMMIT GIVE THE CARD BACK? The checkpoint slots are the one part of the KV pool
|
||||
* backed on demand, and releasing a freed slot's pages is only worth a driver call where the
|
||||
* card actually gets them back. That is a claim about the driver rather than about the API,
|
||||
* so it is measured here, once, on a range nothing else owns: commit it, read the card,
|
||||
* decommit it, read again. tools/vmemprobe.cpp asks the same question in more detail, and on
|
||||
* ROCm 7.2 / gfx1201 the answer is no -- hipMemUnmap returns nothing, and a reservation is
|
||||
* charged for its high-water commit until hipMemAddressFree.
|
||||
* THE WARNING IS ON THE ROOM, NOT ON THE FLAG. Raising --gpu-headroom-mib raises what is left
|
||||
* here and what this compares it with by the same amount, so a check of free memory against
|
||||
* the flag can never be satisfied by the flag: the gap is whatever was taken after the
|
||||
* reading, and it is there at every value. The room a first launch has -- what is free less
|
||||
* what the budget kept for later -- is what the flag actually moves, and it is held against
|
||||
* this engine's own allowance for its first launches (the flag's default). A card short of
|
||||
* that is warned with the value that clears it; one that kept the allowance but lost part of
|
||||
* a larger stated headroom says so on its INFO line.
|
||||
*
|
||||
* The expert slab does not depend on the answer. It borrows the cache's idle blocks at the
|
||||
* addresses the cache already owns, so no page ever changes hands (Engine::loan_tick). */
|
||||
if (!ranks_.empty() && VMem::supported()) {
|
||||
VMem v;
|
||||
const int64_t g = VMem::granularity();
|
||||
const int64_t n = std::max<int64_t>(64ll << 20, g > 0 ? g * 16 : 0);
|
||||
RadDeviceProps a{}, b{};
|
||||
release_frees_card_ = false;
|
||||
if (rad_dev_set(ranks_[0]->device) >= 0 && v.reserve(n) >= 0 && v.commit(0, n) >= 0 &&
|
||||
rad_dev_props(ranks_[0]->device, &a) >= 0 && v.decommit(0, n) >= 0 &&
|
||||
rad_dev_props(ranks_[0]->device, &b) >= 0)
|
||||
release_frees_card_ = (b.vram_free - a.vram_free) > n / 2;
|
||||
for (auto& r : ranks_) r->kv.set_release_frees_card(release_frees_card_);
|
||||
if (!release_frees_card_)
|
||||
RAD_INFO("this driver does not return decommitted VRAM to the card (%s unmapped, the "
|
||||
"free counter did not move), so a freed checkpoint slot keeps its pages. The "
|
||||
"expert slab is unaffected: it borrows the cache's idle blocks in place.",
|
||||
humanb(n).c_str());
|
||||
}
|
||||
|
||||
/* A CHECKPOINT SLOT IS BACKED ON EVERY CARD BEFORE ITS ID IS HANDED OUT, AND NEVER INTO THE
|
||||
* HEADROOM. Rank 0's free list hands the ids out and every rank writes its shard of a snapshot
|
||||
* into the same slot of its own pool; backing a slot on one card and meeting a refusal on the
|
||||
* other at the snapshot copy would stop the engine mid-serve. See
|
||||
* KVManager::set_checkpoint_floor for why the floor is the headroom.
|
||||
*
|
||||
* AND NOT INTO WHAT THE BUDGET KEPT FOR LATER either: the step staging serve() allocates, and
|
||||
* what is built on first use. serve() lowers the floor once the staging exists. */
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * (1ll << 20);
|
||||
const int64_t keep_now = headroom + late_step_bytes_ + late_lazy_bytes_;
|
||||
if (!ranks_.empty()) {
|
||||
set_checkpoint_floors(keep_now);
|
||||
std::vector<KVManager*> peers;
|
||||
for (size_t i = 1; i < ranks_.size(); ++i) peers.push_back(&ranks_[i]->kv);
|
||||
ranks_[0]->kv.set_checkpoint_peers(std::move(peers));
|
||||
}
|
||||
/* AND ON A DRIVER THAT KEEPS WHAT IT MAPS, BACKED NOW. A slot backed later would cost the card
|
||||
* exactly what it costs now and could never be given back, so waiting would only move the
|
||||
* region's cost out of the reading below and into the middle of serving -- where the budget's
|
||||
* misses (allocations made after it was resolved) may already have taken part of it. Backed
|
||||
* here, the reading includes the slots, and a slot the cards have no room for is withdrawn
|
||||
* here and said so. */
|
||||
if (!release_frees_card_ && !ranks_.empty() && ranks_[0]->kv.free_checkpoint_slots() > 0) {
|
||||
KVManager& lead = ranks_[0]->kv;
|
||||
const int64_t asked = lead.free_checkpoint_slots();
|
||||
int64_t gone = 0;
|
||||
RAD_TRY(lead.back_free_checkpoints(&gone));
|
||||
if (gone > 0) {
|
||||
const int64_t stride = lead.checkpoint_stride();
|
||||
int64_t short_by = 0;
|
||||
for (auto& r : ranks_) {
|
||||
RadDeviceProps p{};
|
||||
if (rad_dev_props(r->device, &p) < 0) continue;
|
||||
short_by = std::max(short_by, gone * stride - (p.vram_free - keep_now));
|
||||
}
|
||||
RAD_WARN("checkpoint slots: %lld of %lld backed (%s each), %lld withdrawn -- one more "
|
||||
"would take a card under the %s it has to keep free: the %s "
|
||||
"--gpu-headroom-mib, the room a kernel's first launch allocates from, and %s "
|
||||
"the budget kept for the step staging and for what is built on first use. "
|
||||
"The prefix cache holds %lld linear-state snapshots on the card and its "
|
||||
"retention policy decides which. The budget counted all %lld; the card is %s "
|
||||
"short of them, which is allocations made after the budget was resolved.",
|
||||
(long long)(asked - gone), (long long)asked, humanb(stride).c_str(),
|
||||
(long long)gone, humanb(keep_now).c_str(), humanb(headroom).c_str(),
|
||||
humanb(late_step_bytes_ + late_lazy_bytes_).c_str(), (long long)(asked - gone),
|
||||
(long long)asked, humanb(short_by).c_str());
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& r : ranks_) {
|
||||
* TOO MUCH means the budget left VRAM on the floor, which on a model whose experts do not
|
||||
* fit is milliseconds of decode step for every unspent GiB. A slack of 256 MiB is tolerated
|
||||
* silently: MiB rounding and a kernel plugin's own workspaces live in there. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
|
||||
const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
|
||||
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
|
||||
auto& r = ranks_[ri];
|
||||
LogRank lr(r->index);
|
||||
RadDeviceProps props{};
|
||||
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
|
||||
|
||||
/* AGAINST THE HEADROOM AND WHAT THE BUDGET KEPT FOR LATER, because both are still free
|
||||
* here: the step staging is allocated by serve(), and the KV tiers' staging and a second
|
||||
* compute lane are built on first use. A card at exactly the headroom now would be under
|
||||
* it once those exist. */
|
||||
const int64_t MiB = 1024 * 1024;
|
||||
* compute lane are built on first use. */
|
||||
const int64_t late = late_step_bytes_ + late_lazy_bytes_;
|
||||
const int64_t want = headroom + late;
|
||||
const int64_t got = props.vram_free;
|
||||
const int64_t room = got - late;
|
||||
const std::string asked =
|
||||
late > 0 ? fmt("%s (the %s --gpu-headroom-mib and %s kept for the step staging and "
|
||||
"for what is built on first use)", humanb(want).c_str(),
|
||||
humanb(headroom).c_str(), humanb(late).c_str())
|
||||
: fmt("%s --gpu-headroom-mib", humanb(want).c_str());
|
||||
if (got < want) {
|
||||
/* WHAT THIS SHORTFALL THREATENS is whatever allocates after startup: a kernel's code
|
||||
* object, loaded on its FIRST launch, and a spilling kernel's scratch, sized on its
|
||||
* first launch by the whole grid. Neither is knowable when the budget is resolved, and
|
||||
* running out for either is a fault inside the HIP runtime rather than an error. */
|
||||
RAD_WARN("card %d settled at %s free against %s. The difference is allocations "
|
||||
"made after the budget was resolved, and it comes out of the room a kernel's "
|
||||
"first launch allocates from. Raise --gpu-headroom-mib by at least %s so the "
|
||||
"budget is resolved against the right number.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str());
|
||||
}
|
||||
else if (got > want + 256 * MiB) {
|
||||
if (room < allowance) {
|
||||
const int64_t raise_mib = (allowance - room + MiB - 1) / MiB;
|
||||
RAD_WARN("card %d settled at %s free against %s, which leaves %s for a kernel's first "
|
||||
"launch to load its code object and size its scratch in -- under the %s this "
|
||||
"engine allows for its own. %s Set --gpu-headroom-mib to at least %lld: what "
|
||||
"is left here rises with it one for one.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(),
|
||||
humanb(std::max<int64_t>(room, 0)).c_str(), humanb(allowance).c_str(),
|
||||
got < want
|
||||
? fmt("%s of the headroom was taken after the budget read the card, by "
|
||||
"another process on it or an allocation the budget does not "
|
||||
"count.", humanb(want - got).c_str()).c_str()
|
||||
: "",
|
||||
(long long)(std::max<int64_t>(cfg_.gpu_headroom_mib, 0) + raise_mib));
|
||||
} else if (got < want) {
|
||||
RAD_INFO("card %d settled at %s free against %s: %s of the headroom was taken after "
|
||||
"the budget read the card, by another process on it or an allocation the "
|
||||
"budget does not count, and %s is left for first launches",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), humanb(want - got).c_str(),
|
||||
humanb(room).c_str());
|
||||
} else if (got > want + 256 * MiB) {
|
||||
/* AND "TOO MUCH" IS ONLY A FAULT WHERE SOMEBODY STATED THE BUDGET. Where the resolver
|
||||
* made the split, what is left is left because neither pool could address another
|
||||
* byte -- a small dense model already at the largest context its cache can hold
|
||||
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
|
||||
* Warning here would contradict that receipt and send the reader looking for a flag
|
||||
* to set. */
|
||||
if (cfg_.vram_budget_derived)
|
||||
* to set. A rank plan() re-split for the common token count also leaves what its
|
||||
* weights could not use, and the `kv: rank N ...` line said how much. */
|
||||
const int64_t unclaimed_mib =
|
||||
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
|
||||
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
|
||||
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
|
||||
"MiB are what rank %d's weights could not use of what its KV pool did not "
|
||||
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
|
||||
"line of the VRAM budget.",
|
||||
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
|
||||
r->index, r->index);
|
||||
else if (cfg_.vram_budget_derived)
|
||||
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
|
||||
"neither pool could address another byte, which is the `unusable` line of "
|
||||
"the VRAM budget above.",
|
||||
|
||||
+332
-11
@@ -253,7 +253,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
|
||||
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
|
||||
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
|
||||
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
|
||||
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
|
||||
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
|
||||
* be a linear position divide for llama3, longrope or YaRN. */
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
|
||||
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
|
||||
@@ -300,7 +303,48 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
|
||||
m.n_expert_shared= gi("expert_shared_count", 0);
|
||||
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
|
||||
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
|
||||
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
|
||||
m.rope_scale = 1.0f;
|
||||
|
||||
/* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
|
||||
* those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
|
||||
* a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
|
||||
* attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
|
||||
* has no spelling for, so a file that sets one to anything but its neutral value is refused
|
||||
* here rather than served as plain YaRN. */
|
||||
{
|
||||
/* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
|
||||
* the older rope.scale_linear, and 0 or 1 is no scaling. */
|
||||
std::string type = "linear";
|
||||
g.get_str(a + ".rope.scaling.type", &type);
|
||||
const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
|
||||
const bool none = type == "none" || (type == "linear" && (factor == 0.0 || factor == 1.0));
|
||||
if (!none) {
|
||||
const struct { const char* key; double neutral; } kOff[] = {
|
||||
{ "rope.scaling.attn_factor", 1.0 }, { "rope.scaling.yarn_attn_factor", 1.0 },
|
||||
{ "rope.scaling.yarn_log_multiplier", 0.0 } };
|
||||
for (const auto& k : kOff)
|
||||
if (gf(k.key, k.neutral) != k.neutral) {
|
||||
RAD_ERR("the GGUF sets %s.%s = %g; that modifier of the rotary's scaling is "
|
||||
"not implemented", a.c_str(), k.key, gf(k.key, k.neutral));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double ext = gf("rope.scaling.yarn_ext_factor", -1.0);
|
||||
if (ext >= 0.0 && ext != 1.0) {
|
||||
RAD_ERR("the GGUF sets %s.rope.scaling.yarn_ext_factor = %g; YaRN is implemented "
|
||||
"at extrapolation factor 1", a.c_str(), ext);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
out->kv("rope_scaling.type", type);
|
||||
if (factor != 0.0) out->kv("rope_scaling.factor", fmt("%.17g", factor));
|
||||
const int64_t orig = gi("rope.scaling.original_context_length", 0);
|
||||
if (orig > 0) out->kv("rope_scaling.original_max_position_embeddings",
|
||||
fmt("%lld", (long long)orig));
|
||||
for (const char* beta : { "beta_fast", "beta_slow" }) {
|
||||
const double v = gf((std::string("rope.scaling.yarn_") + beta).c_str(), 0.0);
|
||||
if (v != 0.0) out->kv(std::string("rope_scaling.") + beta, fmt("%.17g", v));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<std::string> toks;
|
||||
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
|
||||
@@ -432,10 +476,169 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
fp8_bc_ = c;
|
||||
}
|
||||
}
|
||||
detect_import();
|
||||
meta_.finish();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHICH PUBLISHED QUANTISATION THIS IS, from quantization_config alone: the tensors are checked
|
||||
* one by one when a weight is resolved (import_piece), so a file that says one thing and holds
|
||||
* another is refused at the weight that differs. */
|
||||
void Checkpoint::detect_import() {
|
||||
auto qc = [&](const std::string& k) {
|
||||
const char* v = meta_.get("quantization_config." + k);
|
||||
return v ? std::string(v) : std::string();
|
||||
};
|
||||
auto any_under = [&](const std::string& prefix) {
|
||||
for (const std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config." + prefix, 0) == 0) return true;
|
||||
return false;
|
||||
};
|
||||
const std::string qm = qc("quant_method");
|
||||
if (qm == "auto-round") {
|
||||
/* AutoRound's GPTQ-compatible export; its own `auto_round` packing is another layout. */
|
||||
const std::string pf = qc("packing_format");
|
||||
if (pf == "auto_round:auto_gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "AutoRound's packing_format '" + pf + "' is not one this reads; its "
|
||||
"auto_round:auto_gptq export is";
|
||||
} else if (qm == "gptq") {
|
||||
/* v1, the format auto_gptq writes: the zero point stored less one. gptq_v2 stores it as
|
||||
* it is, and reading it as v1 would shift every code by one. */
|
||||
const std::string cf = qc("checkpoint_format");
|
||||
if (cf.empty() || cf == "gptq") import_ = Import::Gptq;
|
||||
else import_why_ = "GPTQ's checkpoint_format '" + cf + "' is not one this reads; 'gptq' is";
|
||||
} else if (qm == "quark") {
|
||||
const std::string w = "global_quant_config.weight.";
|
||||
if (qc(w + "dtype") == "fp4" && qc(w + "qscheme") == "per_group" &&
|
||||
qc(w + "group_size") == "32" && qc(w + "scale_format") == "e8m0" &&
|
||||
!any_under("layer_quant_config.") && !any_under("layer_type_quant_config."))
|
||||
import_ = Import::QuarkMx;
|
||||
else
|
||||
import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) "
|
||||
"throughout, which is the one this reads";
|
||||
}
|
||||
/* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as
|
||||
* the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an
|
||||
* imported checkpoint's says how a tool made it instead: every weight states its own
|
||||
* encoding. Renamed, it still travels into the container as provenance. */
|
||||
if (import_ != Import::None)
|
||||
for (std::string& k : meta_.keys)
|
||||
if (k.rfind("quantization_config.", 0) == 0) k = "imported_" + k;
|
||||
}
|
||||
|
||||
int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes,
|
||||
const SrcTensor** scale, std::string* why) {
|
||||
auto refuse = [&](int rc, std::string m) {
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (import_ == Import::None) return RAD_E_NOTFOUND;
|
||||
if (auto hit = imported_.find(name); hit != imported_.end()) {
|
||||
*codes = hit->second.first;
|
||||
*scale = hit->second.second;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
if (import_ == Import::QuarkMx) {
|
||||
/* QUARK'S MXFP4 IS THE ENCODING AS IT STANDS: two codes a byte, element 2j in the low
|
||||
* nibble, and one biased exponent a 32 of K -- `fp4_e2m1*e8m0[1x32]`. A view renames the
|
||||
* dtypes and the logical width; no byte moves. Its excluded layers are plain tensors. */
|
||||
const SrcTensor* w = find(name);
|
||||
const SrcTensor* e = w ? find(name + "_scale") : nullptr;
|
||||
if (!w || !e || w->rad_dtype != RAD_U8) return RAD_E_NOTFOUND;
|
||||
if (e->rad_dtype != RAD_U8 || w->shape.size() != 2 || e->shape.size() != 2 ||
|
||||
e->shape[0] != w->shape[0] || e->shape[1] * 32 != w->shape[1] * 2)
|
||||
return refuse(RAD_E_SHAPE, "'" + e->name + "' is not the [N, K/32] exponent plane of '" +
|
||||
w->name + "'");
|
||||
SrcTensor c = *w;
|
||||
c.rad_dtype = RAD_FP4E2M1;
|
||||
c.shape = { w->shape[0], w->shape[1] * 2 };
|
||||
SrcTensor x = *e;
|
||||
x.rad_dtype = RAD_E8M0;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
sliced_.push_back(std::move(x));
|
||||
*scale = &sliced_.back();
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally,
|
||||
* X.g_idx. The width is read off the tensors rather than quantization_config, because a
|
||||
* release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */
|
||||
const std::string suffix = ".weight";
|
||||
if (name.size() <= suffix.size() ||
|
||||
name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0)
|
||||
return RAD_E_NOTFOUND;
|
||||
const std::string base = name.substr(0, name.size() - suffix.size());
|
||||
const SrcTensor* qw = find(base + ".qweight");
|
||||
if (!qw) return RAD_E_NOTFOUND;
|
||||
const SrcTensor* sc = find(base + ".scales");
|
||||
const SrcTensor* qz = find(base + ".qzeros");
|
||||
const SrcTensor* gi = find(base + ".g_idx");
|
||||
const std::string what = "'" + qw->name + "'";
|
||||
if (qw->rad_dtype != RAD_I32 || qw->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " is not an int32 [K*bits/32, N] matrix");
|
||||
if (!sc || sc->shape.size() != 2 ||
|
||||
(sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32))
|
||||
return refuse(RAD_E_FORMAT, what + " has no float [groups, N] '" + base + ".scales' beside it");
|
||||
if (!qz || qz->rad_dtype != RAD_I32 || qz->shape.size() != 2)
|
||||
return refuse(RAD_E_FORMAT, what + " has no int32 '" + base + ".qzeros' beside it");
|
||||
const int64_t N = qw->shape[1];
|
||||
const int64_t bits = N > 0 && (qz->shape[1] * 32) % N == 0 ? qz->shape[1] * 32 / N : 0;
|
||||
if (bits != 4 && bits != 8)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " packs " + std::to_string(bits) + "-bit codes "
|
||||
"(from its qzeros' width); 4 and 8 are read");
|
||||
const int64_t K = qw->shape[0] * 32 / bits;
|
||||
const int64_t G = sc->shape[0];
|
||||
if (sc->shape[1] != N || G <= 0 || K % G)
|
||||
return refuse(RAD_E_SHAPE, "'" + sc->name + "' is not a [groups, " + std::to_string(N) +
|
||||
"] scale tensor for " + std::to_string(K) + " columns");
|
||||
const int64_t group = K / G;
|
||||
/* THE SERVED SCALE COVERS 128 OF K, so a group of 128 is one scale each and a wider one --
|
||||
* per channel included -- repeats; a narrower group has no form the kernels read. */
|
||||
if (K % 128 || group % 128)
|
||||
return refuse(RAD_E_UNSUPPORTED, what + " has groups of " + std::to_string(group) +
|
||||
" columns; the imported form scales a 128 of K, so the "
|
||||
"group must be a multiple of 128");
|
||||
if (qz->shape[0] != G)
|
||||
return refuse(RAD_E_SHAPE, "'" + qz->name + "' has " + std::to_string(qz->shape[0]) +
|
||||
" rows for " + std::to_string(G) + " groups");
|
||||
/* SYMMETRIC, OR NOT READ: every zero point the v1 2^(bits-1) - 1, which is what makes a code
|
||||
* the signed value it offsets to. An asymmetric weight would need a zero plane. */
|
||||
const uint32_t zero = bits == 4 ? 0x77777777u : 0x7f7f7f7fu;
|
||||
for (int64_t i = 0; i < qz->numel(); ++i) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)qz->data + i * 4, 4);
|
||||
if (v != zero)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + qz->name + "' holds a zero point other than "
|
||||
"the symmetric one; an asymmetric weight is not read");
|
||||
}
|
||||
/* AND IN ORDER: act-order (desc_act) permutes the columns' groups, which a [1x128] scale
|
||||
* cannot follow. The identity, or none, is the only g_idx read. */
|
||||
if (gi) {
|
||||
if (gi->rad_dtype != RAD_I32 || gi->numel() != K)
|
||||
return refuse(RAD_E_FORMAT, "'" + gi->name + "' is not an int32 [K] group index");
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
int32_t v;
|
||||
std::memcpy(&v, (const uint8_t*)gi->data + k * 4, 4);
|
||||
if (v != k / group)
|
||||
return refuse(RAD_E_UNSUPPORTED, "'" + gi->name + "' reorders the columns' groups "
|
||||
"(act-order); only an in-order index is read");
|
||||
}
|
||||
}
|
||||
SrcTensor c = *qw;
|
||||
c.rad_dtype = bits == 4 ? RAD_I4 : RAD_I8;
|
||||
c.shape = { N, K };
|
||||
c.gptq_bits = (int32_t)bits;
|
||||
c.gptq_group = group;
|
||||
sliced_.push_back(std::move(c));
|
||||
*codes = &sliced_.back();
|
||||
*scale = sc;
|
||||
imported_[name] = { *codes, *scale };
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Checkpoint::open(const std::string& path) {
|
||||
path_ = path;
|
||||
const bool gguf = path.size() > 5 && path.compare(path.size() - 5, 5, ".gguf") == 0;
|
||||
@@ -577,6 +780,22 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
for (const Src1& s1 : srcs) {
|
||||
const SrcTensor* st = ck.find(s1.name);
|
||||
const SrcTensor* sc = st ? ck.find(scale_name(s1.name)) : nullptr;
|
||||
/* A WEIGHT THE CHECKPOINT SHIPS IN AN IMPORTED FORM is read through that form's views. */
|
||||
{
|
||||
const SrcTensor *ic = nullptr, *is = nullptr;
|
||||
std::string iw;
|
||||
const int ir = ck.import_piece(s1.name, &ic, &is, &iw);
|
||||
if (ir == RAD_OK) {
|
||||
if (s1.index >= 0)
|
||||
return refuse(RAD_E_UNSUPPORTED, "it is a slice of '" + std::string(s1.name) +
|
||||
"', which the checkpoint ships quantised; an "
|
||||
"imported tensor is read whole");
|
||||
st = ic;
|
||||
sc = is;
|
||||
} else if (ir != RAD_E_NOTFOUND) {
|
||||
return refuse(ir, iw);
|
||||
}
|
||||
}
|
||||
/* A SUB-TENSOR INDEX IS TAKEN, never ignored: ignoring it gives every expert a copy of
|
||||
* the whole stack, in a model that loads and answers. Its scale plane is stacked the same
|
||||
* way and sliced at the same index. */
|
||||
@@ -636,6 +855,40 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b
|
||||
(gguf_dtype(p0.ggml) ? gguf_dtype(p0.ggml)->name : "block") + " tensor";
|
||||
} else if (!same) {
|
||||
out->why = "its pieces are stored in different dtypes";
|
||||
} else if (p0.gptq_bits) {
|
||||
/* GPTQ-PACKED, IMPORTED: one width and one group throughout, joined only along rows --
|
||||
* a column join would put two pieces' groups in one scale block. */
|
||||
out->imported = true;
|
||||
for (size_t k = 1; k < out->pieces.size() && out->imported; ++k)
|
||||
if (out->pieces[k]->gptq_bits != p0.gptq_bits ||
|
||||
out->pieces[k]->gptq_group != p0.gptq_group) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces differ in width or group";
|
||||
}
|
||||
if (out->imported && d != 0 && out->pieces.size() > 1) {
|
||||
out->imported = false;
|
||||
out->why = "its GPTQ-packed pieces are joined along a column, across their groups";
|
||||
}
|
||||
if (out->imported) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", dt, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_BF16, 1, 128);
|
||||
out->why = "it is GPTQ-packed int" + std::to_string(p0.gptq_bits) + ", which "
|
||||
"rad-convert imports with its scales rounded to bf16 -- serve the "
|
||||
"container it writes";
|
||||
}
|
||||
} else if (dt == RAD_FP4E2M1 && scaled) {
|
||||
/* QUARK'S MXFP4, byte for byte: the codes and exponents are the planes of
|
||||
* `fp4_e2m1*e8m0[1x32]`. Joined only along rows, which is how gate and up become one. */
|
||||
out->trivial = d == 0 || out->pieces.size() == 1;
|
||||
if (!out->trivial) out->why = "its MXFP4 pieces are joined along a column";
|
||||
if (out->trivial) {
|
||||
rad_enc_clear(&out->enc);
|
||||
rad_enc_copy_str(out->enc.scheme, "affine");
|
||||
rad_enc_add_plane(&out->enc, "codes", RAD_FP4E2M1, 1, 1);
|
||||
rad_enc_add_plane(&out->enc, "scale", RAD_E8M0, 1, 32);
|
||||
}
|
||||
} else if ((dt == RAD_F8E4M3 || dt == RAD_F8E5M2) && scaled) {
|
||||
/* BLOCK-SCALED FP8, byte for byte: the codes and the scale plane are the planes of
|
||||
* `fp8_e4m3*bf16[128x128]` (whatever the scale's own dtype). Joined only along rows, and
|
||||
@@ -785,6 +1038,21 @@ struct Joined {
|
||||
|
||||
/* `n` elements of a stored-dtype piece from element `e`, as f32. */
|
||||
int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
if (t.gptq_bits) {
|
||||
/* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits)
|
||||
* of word [k / (32/bits), row], less its zero point */
|
||||
const int64_t N = t.shape[0], K = t.shape[1];
|
||||
const int64_t per = 32 / t.gptq_bits;
|
||||
const uint32_t mask = (1u << t.gptq_bits) - 1u;
|
||||
const int zp = 1 << (t.gptq_bits - 1);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t row = (e + i) / K, k = (e + i) % K;
|
||||
uint32_t w;
|
||||
std::memcpy(&w, (const uint8_t*)t.data + ((k / per) * N + row) * 4, 4);
|
||||
out[i] = (float)((int)((w >> ((k % per) * t.gptq_bits)) & mask) - zp);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (t.rad_dtype == RAD_DT_INVALID) {
|
||||
/* a GGUF block type: whole rows only, and a row is whole blocks */
|
||||
const int64_t cols = t.shape.back();
|
||||
@@ -807,7 +1075,7 @@ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2:
|
||||
case RAD_F16: case RAD_F8E4M3: case RAD_F8E5M2: case RAD_FP4E2M1:
|
||||
case RAD_I8: case RAD_U8: case RAD_I16: case RAD_I32: case RAD_U32: case RAD_U16:
|
||||
for (int64_t i = 0; i < n; ++i) out[i] = rad_load_f32(p, t.rad_dtype, e + i);
|
||||
return RAD_OK;
|
||||
@@ -841,8 +1109,25 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std::
|
||||
: "?")
|
||||
: std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) +
|
||||
")");
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE: the pieces are joined along rows, so logical row
|
||||
* r is in the piece whose rows cover it, and its scales are that piece's. */
|
||||
/* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is
|
||||
* [groups, N], so row r's scales are a column of it. */
|
||||
if (w.imported) {
|
||||
int64_t base = 0;
|
||||
for (size_t k = 0; k < w.pieces.size(); ++k) {
|
||||
const SrcTensor& pk = *w.pieces[k];
|
||||
const SrcTensor& sk = *w.scales[k];
|
||||
const int64_t pr = pk.shape[0];
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r)
|
||||
for (int64_t c = 0; c < w.cols; ++c)
|
||||
out[(r - r0) * w.cols + c] *=
|
||||
rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base));
|
||||
base += pr;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* FP8 IS ITS CODE TIMES ITS BLOCK'S SCALE (and MXFP4 its code times its exponent): the pieces
|
||||
* are joined along rows, so logical row r is in the piece whose rows cover it, and its scales
|
||||
* are that piece's. */
|
||||
if (!w.scales.empty() && w.scales[0]) {
|
||||
const int64_t br = w.enc.n_planes > 1 ? w.enc.plane[1].block[0] : 128;
|
||||
const int64_t bc = w.enc.n_planes > 1 ? w.enc.plane[1].block[1] : 128;
|
||||
@@ -869,8 +1154,8 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
if (why) *why = std::move(m);
|
||||
return rc;
|
||||
};
|
||||
if (!w.trivial || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial encoding");
|
||||
if (!(w.trivial || w.imported) || k < 0 || k >= w.enc.n_planes)
|
||||
return refuse(RAD_E_STATE, "not a plane of a trivial or imported encoding");
|
||||
const std::vector<const SrcTensor*>& src = k == 0 ? w.pieces : w.scales;
|
||||
int64_t pr = 0, pc = 0;
|
||||
rad_enc_plane_dims(&w.enc.plane[k], w.rows, w.cols, &pr, &pc);
|
||||
@@ -878,14 +1163,50 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds
|
||||
const uint32_t dt = w.enc.plane[k].dtype;
|
||||
const int64_t eb = rad_dtype_bits(dt) / 8;
|
||||
uint8_t* o = (uint8_t*)dst;
|
||||
if (w.imported) {
|
||||
/* GPTQ-PACKED, RE-LAID: a row of codes is a column of the qweight, its words' bytes in
|
||||
* order -- two codes a byte for int4, low nibble first, as the encoding packs them -- each
|
||||
* offset to signed by flipping the top bit of every field; a row of scales is a column of
|
||||
* the scale tensor, one a 128 of K, rounded to bf16. */
|
||||
int64_t base = 0;
|
||||
for (size_t p = 0; p < w.pieces.size(); ++p) {
|
||||
const SrcTensor& c = *w.pieces[p];
|
||||
const SrcTensor& s = *w.scales[p];
|
||||
const int64_t N = c.shape[0], K = c.shape[1];
|
||||
const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80;
|
||||
for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) {
|
||||
const int64_t n = r - base;
|
||||
if (k == 0) {
|
||||
const uint8_t* q = (const uint8_t*)c.data;
|
||||
for (int64_t wi = 0; wi < K * c.gptq_bits / 32; ++wi) {
|
||||
uint32_t v;
|
||||
std::memcpy(&v, q + (wi * N + n) * 4, 4);
|
||||
for (int b = 0; b < 4; ++b) *o++ = (uint8_t)(v >> (8 * b)) ^ flip;
|
||||
}
|
||||
} else {
|
||||
for (int64_t g = 0; g < K / 128; ++g) {
|
||||
const uint16_t h = rad_f32_to_bf16(
|
||||
rad_load_f32(s.data, s.rad_dtype, ((g * 128) / c.gptq_group) * N + n));
|
||||
std::memcpy(o, &h, 2);
|
||||
o += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
base += N;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (k == 0) {
|
||||
/* the codes: the pieces joined, bytes as they are */
|
||||
/* the codes: the pieces joined, bytes as they are. A sub-byte code (MXFP4) joins along
|
||||
* rows of even width, so every run starts and ends on a byte. */
|
||||
const int64_t bits = rad_dtype_bits(dt);
|
||||
Joined j;
|
||||
j.init(src, w.concat_dim);
|
||||
return j.walk(r0 * pc, (r0 + nr) * pc, [&](int p, int64_t e, int64_t n) {
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * eb, (size_t)(n * eb));
|
||||
o += n * eb;
|
||||
return RAD_OK;
|
||||
if ((e * bits) % 8 || (n * bits) % 8) return (int)RAD_E_SHAPE;
|
||||
std::memcpy(o, (const uint8_t*)src[(size_t)p]->data + e * bits / 8, (size_t)(n * bits / 8));
|
||||
o += n * bits / 8;
|
||||
return (int)RAD_OK;
|
||||
});
|
||||
}
|
||||
/* an FP8 scale plane: the pieces' scale rows one after another */
|
||||
|
||||
@@ -10,9 +10,16 @@
|
||||
* resolves it to -- concatenations, alternatives and expert slices included -- with the
|
||||
* encoding they already are when that encoding is trivial, and the rows of it on demand.
|
||||
*
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), and block-scaled
|
||||
* FP8, where `X.weight_scale_inv` is the scale plane of `X.weight`. Anything else is a weight
|
||||
* whose served form needs quantisation work, which a recipe does ahead of time.
|
||||
* Trivial is the set spec §4.3 names: plain f32, f16 and bf16 (GGUF's too), block-scaled FP8,
|
||||
* where `X.weight_scale_inv` is the scale plane of `X.weight`, and MXFP4 as AMD Quark ships it
|
||||
* (`X.weight` U8 codes, `X.weight_scale` U8 exponents), which is `fp4_e2m1*e8m0[1x32]` byte for
|
||||
* byte. Anything else is a weight whose served form needs quantisation work, which a recipe does
|
||||
* ahead of time -- or, for a published GPTQ-packed release (AutoRound, GPTQ), an IMPORT: the
|
||||
* shipped integer codes and group scales re-laid as an encoding the kernels read, at convert time.
|
||||
*
|
||||
* AN IMPORTED QUANTISATION IS STATED WEIGHT BY WEIGHT. The checkpoint's quantisation descriptor
|
||||
* (`auto-round`, `gptq`, `quark`) names the tool that made it, not a served form, so no
|
||||
* architecture plugin claims it; the plugin is chosen as Checkpoint::imports() describes.
|
||||
*/
|
||||
#pragma once
|
||||
#include "../rad_internal.h"
|
||||
@@ -42,6 +49,13 @@ struct SrcTensor {
|
||||
std::vector<int64_t> shape; /* row-major */
|
||||
const void* data = nullptr;
|
||||
int64_t bytes = 0;
|
||||
/* GPTQ-PACKED (auto_gptq's layout, which AutoRound's `auto_round:auto_gptq` export shares):
|
||||
* `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along
|
||||
* K from the low bits up, stored unsigned with the zero point 2^(bits-1). The tensor this
|
||||
* describes is the logical [N, K] code matrix, `rad_dtype` RAD_I4 or RAD_I8; `gptq_group` is
|
||||
* the K columns one row of its scale tensor covers. 0 for any other tensor. */
|
||||
int32_t gptq_bits = 0;
|
||||
int64_t gptq_group = 0;
|
||||
|
||||
int64_t numel() const {
|
||||
int64_t n = 1;
|
||||
@@ -109,10 +123,29 @@ public:
|
||||
int64_t fp8_block_rows() const { return fp8_br_; }
|
||||
int64_t fp8_block_cols() const { return fp8_bc_; }
|
||||
|
||||
/* THE CHECKPOINT'S QUANTISATION, IMPORTED WEIGHT BY WEIGHT, or None. Read from
|
||||
* quantization_config at open: AutoRound's `auto_round:auto_gptq` export and GPTQ's own (v1,
|
||||
* the zero point stored less one) are Gptq; Quark's MXFP4 (fp4 weights, per_group 32, e8m0
|
||||
* scales, no per-layer overrides) is QuarkMx. A quantisation of one of those tools in a form
|
||||
* this does not read stays None, with the reason in import_refusal(). */
|
||||
/* Its quantization_config keys are then renamed `imported_quantization_config.*`: they
|
||||
* describe the tool, not a served format, and a plugin reads the latter there. */
|
||||
enum class Import { None, Gptq, QuarkMx };
|
||||
Import imports() const { return import_; }
|
||||
const std::string& import_refusal() const { return import_why_; }
|
||||
|
||||
/* The pieces an imported weight is read from, as views owned here: for `name` (a `.weight`)
|
||||
* the GPTQ-packed codes and their scale tensor, or Quark's codes and exponents as their RAD
|
||||
* dtypes. RAD_E_NOTFOUND when the checkpoint ships `name` as an ordinary tensor or not at
|
||||
* all; another error, with `why`, when it ships an imported form this cannot read. */
|
||||
int import_piece(const std::string& name, const SrcTensor** codes, const SrcTensor** scale,
|
||||
std::string* why);
|
||||
|
||||
private:
|
||||
int add_shard(const std::string& p, const std::string& prefix = "");
|
||||
int open_safetensors(const std::string& path);
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
|
||||
enum Kind { None, Gguf, SafeT } kind_ = None;
|
||||
std::string path_, dir_;
|
||||
@@ -123,6 +156,10 @@ private:
|
||||
std::unordered_map<std::string, size_t> index_;
|
||||
std::deque<SrcTensor> sliced_; /* views; a deque never moves what it holds */
|
||||
int64_t fp8_br_ = 128, fp8_bc_ = 128;
|
||||
Import import_ = Import::None;
|
||||
std::string import_why_;
|
||||
/* import_piece's answers by name, so a weight resolved twice reads one pair of views. */
|
||||
std::unordered_map<std::string, std::pair<const SrcTensor*, const SrcTensor*>> imported_;
|
||||
};
|
||||
|
||||
/* ================================================================== logical weights */
|
||||
@@ -138,6 +175,11 @@ struct CkptWeight {
|
||||
int64_t rows = 0, cols = 0; /* its [rows, cols] view (rad_enc_view) */
|
||||
/* The encoding the pieces ARE, when it is trivial; `why` says what is not when it is not. */
|
||||
bool trivial = false;
|
||||
/* GPTQ-PACKED PIECES, read into `enc` (`i4` or `i8` codes, bf16 scales a 128 of K) by
|
||||
* ckpt_plane_rows: the codes transposed and offset to signed, the f16 scales rounded to bf16.
|
||||
* Not trivial -- the rounding means the numbers are not served as shipped -- so the loader
|
||||
* refuses one and rad-convert keeps it in `enc`, as it keeps a trivial weight. */
|
||||
bool imported = false;
|
||||
RadEncoding enc{};
|
||||
std::string why;
|
||||
};
|
||||
@@ -161,8 +203,8 @@ bool ckpt_reads_any(const CkptWeight& w, const std::unordered_set<std::string>&
|
||||
* 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);
|
||||
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL `w`, in the plane's own elements, dense into
|
||||
* `dst`: the bytes a container entry holds for it. */
|
||||
/* Rows [r0, r0 + nr) of plane `k` of a TRIVIAL or IMPORTED `w`, in the plane's own elements, dense
|
||||
* into `dst`: the bytes a container entry holds for it. */
|
||||
int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst,
|
||||
std::string* why);
|
||||
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
/* --rope-scaling, over a container's free-form metadata.
|
||||
*
|
||||
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
|
||||
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
|
||||
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
|
||||
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
|
||||
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
|
||||
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
|
||||
* it would a converted container, so there is one reader and one set of checks.
|
||||
*
|
||||
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
|
||||
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
|
||||
* sit behind that and never be read.
|
||||
*
|
||||
* Pure functions over two parallel string vectors, so they are tested without an engine
|
||||
* (tests/yarn_test.cpp holds them to yarn_from). */
|
||||
#pragma once
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct RopeSpec {
|
||||
enum Kind { Keep, None, Yarn } kind = Keep;
|
||||
double factor = 0.0;
|
||||
int64_t orig = 0; /* 0: the container's own trained length */
|
||||
};
|
||||
|
||||
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
|
||||
* else, so a typo is refused where it was typed. */
|
||||
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
|
||||
RopeSpec r;
|
||||
if (!s || !*s) { *out = r; return true; }
|
||||
if (!std::strcmp(s, "none")) { r.kind = RopeSpec::None; *out = r; return true; }
|
||||
if (std::strncmp(s, "yarn:", 5)) return false;
|
||||
char* e = nullptr;
|
||||
r.factor = std::strtod(s + 5, &e);
|
||||
if (e == s + 5 || !(r.factor > 1.0) || r.factor > 1e6) return false;
|
||||
if (*e == ':') {
|
||||
char* e2 = nullptr;
|
||||
const long long o = std::strtoll(e + 1, &e2, 10);
|
||||
if (e2 == e + 1 || *e2 || o <= 0) return false;
|
||||
r.orig = o;
|
||||
} else if (*e) {
|
||||
return false;
|
||||
}
|
||||
r.kind = RopeSpec::Yarn;
|
||||
*out = r;
|
||||
return true;
|
||||
}
|
||||
|
||||
struct RopeKeys {
|
||||
std::vector<std::string>& k;
|
||||
std::vector<std::string>& v;
|
||||
|
||||
int find(const std::string& key) const {
|
||||
for (size_t i = 0; i < k.size(); ++i)
|
||||
if (k[i] == key) return (int)i;
|
||||
return -1;
|
||||
}
|
||||
const std::string* get(const std::string& key) const {
|
||||
const int i = find(key);
|
||||
return i < 0 ? nullptr : &v[(size_t)i];
|
||||
}
|
||||
void set(const std::string& key, const std::string& val) {
|
||||
const int i = find(key);
|
||||
if (i >= 0) { v[(size_t)i] = val; return; }
|
||||
k.push_back(key);
|
||||
v.push_back(val);
|
||||
}
|
||||
void erase(const std::string& key) {
|
||||
const int i = find(key);
|
||||
if (i < 0) return;
|
||||
k.erase(k.begin() + i);
|
||||
v.erase(v.begin() + i);
|
||||
}
|
||||
bool any_prefix(const char* pre) const {
|
||||
const size_t n = std::strlen(pre);
|
||||
for (const auto& s : k)
|
||||
if (!s.compare(0, n, pre)) return true;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
/* The reader's order -- yarn_from's, kept in step with it. */
|
||||
inline std::vector<std::string> rope_homes(const char* group) {
|
||||
if (!*group)
|
||||
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
|
||||
"rope_scaling." };
|
||||
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
|
||||
}
|
||||
|
||||
/* The object the reader takes and the key that names its type, or empty strings when no object
|
||||
* names one (the model's rotary is then the default). */
|
||||
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
|
||||
std::string* type_key) {
|
||||
home->clear();
|
||||
type_key->clear();
|
||||
for (const auto& h : rope_homes(group))
|
||||
for (const char* t : { "rope_type", "type" })
|
||||
if (kv.get(h + t)) { *home = h; *type_key = h + t; return; }
|
||||
}
|
||||
|
||||
struct RopeResolved {
|
||||
std::string type; /* "" when nothing names one */
|
||||
double factor = 1.0;
|
||||
double orig = 0.0;
|
||||
};
|
||||
|
||||
inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const char* group) {
|
||||
RopeKeys kv{ k, v };
|
||||
RopeResolved r;
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
if (home.empty()) return r;
|
||||
r.type = *kv.get(tk);
|
||||
if (const std::string* f = kv.get(home + "factor")) r.factor = std::strtod(f->c_str(), nullptr);
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
r.orig = std::strtod(o->c_str(), nullptr);
|
||||
return r;
|
||||
}
|
||||
|
||||
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
|
||||
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
|
||||
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
|
||||
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
|
||||
const RopeSpec& spec, const char* group, int64_t trained,
|
||||
std::string* why) {
|
||||
if (spec.kind == RopeSpec::Keep) return true;
|
||||
RopeKeys kv{ k, v };
|
||||
std::string home, tk;
|
||||
rope_authoritative(kv, group, &home, &tk);
|
||||
const std::string type = home.empty() ? std::string() : *kv.get(tk);
|
||||
if (spec.kind == RopeSpec::None) {
|
||||
if (type == "yarn") kv.set(tk, "default");
|
||||
return true;
|
||||
}
|
||||
/* `mrope` is the legacy Qwen2-VL spelling of default with sections. */
|
||||
if (!type.empty() && type != "default" && type != "mrope" && type != "yarn") {
|
||||
*why = "the " + std::string(*group ? "drafter's" : "model's") + " rotary is '" + type +
|
||||
"' (" + tk + "); YaRN over it is not --rope-scaling's to decide";
|
||||
return false;
|
||||
}
|
||||
if (home.empty()) {
|
||||
home = *group ? std::string(group) + "rope_parameters."
|
||||
: kv.any_prefix("text_config.") ? "text_config.rope_parameters."
|
||||
: "rope_parameters.";
|
||||
tk = home + "rope_type";
|
||||
}
|
||||
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
|
||||
* tied to its old factor goes, so the reader derives it for the new one. */
|
||||
int64_t orig = spec.orig;
|
||||
if (!orig && type == "yarn")
|
||||
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
|
||||
orig = std::atoll(o->c_str());
|
||||
if (!orig) orig = trained;
|
||||
if (orig <= 0) {
|
||||
*why = "no trained length to scale from; give one: yarn:FACTOR:ORIG";
|
||||
return false;
|
||||
}
|
||||
char buf[64];
|
||||
kv.set(tk, "yarn");
|
||||
std::snprintf(buf, sizeof buf, "%.17g", spec.factor);
|
||||
kv.set(home + "factor", buf);
|
||||
std::snprintf(buf, sizeof buf, "%lld", (long long)orig);
|
||||
kv.set(home + "original_max_position_embeddings", buf);
|
||||
for (const char* stale : { "attention_factor", "mscale", "mscale_all_dim" })
|
||||
kv.erase(home + stale);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
|
||||
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
|
||||
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
|
||||
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
|
||||
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
|
||||
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
|
||||
* angles. Key order and unrelated keys do not change it. */
|
||||
inline std::string rope_identity(const std::vector<std::string>& k,
|
||||
const std::vector<std::string>& v) {
|
||||
auto names_rotary = [](const std::string& key) {
|
||||
size_t s = 0;
|
||||
while (s <= key.size()) {
|
||||
size_t e = key.find('.', s);
|
||||
if (e == std::string::npos) e = key.size();
|
||||
const std::string part = key.substr(s, e - s);
|
||||
if (part.find("rope") != std::string::npos || part.find("rotary") != std::string::npos)
|
||||
return true;
|
||||
s = e + 1;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
std::vector<std::string> rows;
|
||||
for (size_t i = 0; i < k.size() && i < v.size(); ++i)
|
||||
if (names_rotary(k[i])) rows.push_back(k[i] + "=" + v[i]);
|
||||
std::sort(rows.begin(), rows.end());
|
||||
std::string out;
|
||||
for (const auto& r : rows) { out += r; out += ';'; }
|
||||
return out;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+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,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 */
|
||||
+196
-253
@@ -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();
|
||||
@@ -256,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);
|
||||
@@ -277,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;
|
||||
}
|
||||
|
||||
@@ -353,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. */
|
||||
@@ -415,18 +385,82 @@ 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::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
const int64_t MiB = (int64_t)1 << 20;
|
||||
if (max_mib <= 0) return -1;
|
||||
const auto reaches = [&](int64_t mib) {
|
||||
/* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
|
||||
* whose only paged group is zero still has to hold them. */
|
||||
if (mib * MiB < fixed_) return false;
|
||||
const int64_t t = paged_split(mib * MiB, nullptr);
|
||||
return t == kUnboundedTokens || t >= tokens;
|
||||
};
|
||||
if (!reaches(max_mib)) return -1;
|
||||
/* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
|
||||
int64_t lo = 0, hi = max_mib;
|
||||
if (reaches(lo)) return 0;
|
||||
while (hi - lo > 1) {
|
||||
const int64_t mid = lo + (hi - lo) / 2;
|
||||
if (reaches(mid)) hi = mid; else lo = mid;
|
||||
}
|
||||
return hi;
|
||||
}
|
||||
|
||||
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;
|
||||
@@ -435,11 +469,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()) {
|
||||
@@ -451,30 +492,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());
|
||||
@@ -512,36 +534,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;
|
||||
}
|
||||
}
|
||||
@@ -588,19 +587,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;
|
||||
}
|
||||
|
||||
@@ -751,73 +743,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
|
||||
@@ -1417,47 +1342,31 @@ 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);
|
||||
}
|
||||
|
||||
bool KVManager::checkpoint_held(int32_t slot) const {
|
||||
return ck_store_ && ck_store_->in_use(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
|
||||
@@ -1466,34 +1375,68 @@ 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. Each refusal says which check it is: a slot the
|
||||
* store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */
|
||||
const char* dir = save ? "save into" : "restore from";
|
||||
if (!ck_store_) {
|
||||
RAD_ERR("checkpoint %s slot %d: this rank has no snapshot store", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!ck_store_->in_use(ck_slot)) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store does not hold that slot (%lld of %lld in use) -- "
|
||||
"it was given back after its id was handed out", dir, (int)ck_slot,
|
||||
(long long)ck_store_->used_slots(), (long long)ck_store_->capacity());
|
||||
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;
|
||||
if (!ck) {
|
||||
RAD_ERR("checkpoint %s slot %d: the store has no address for it", dir, (int)ck_slot);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!state_slots || n_slots < (int)plans_.size()) {
|
||||
RAD_ERR("checkpoint %s slot %d: %d state slot(s) named for %d group(s)", dir, (int)ck_slot,
|
||||
state_slots ? n_slots : 0, (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];
|
||||
if (!p.stateful()) continue;
|
||||
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;
|
||||
if (slot < 0) { /* no state to save, or none to restore into */
|
||||
RAD_ERR("checkpoint %s slot %d: the sequence holds no state slot in group %d", dir,
|
||||
(int)ck_slot, (int)g);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t nbytes = p.layer_bytes_per_state();
|
||||
void* st = state_ptr((int32_t)g, 0, slot);
|
||||
if (!st || p.n_layers <= 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: group %d has no address for state slot %d", dir,
|
||||
(int)ck_slot, (int)g, (int)slot);
|
||||
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;
|
||||
}
|
||||
const int cs = 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);
|
||||
if (cs < 0) {
|
||||
RAD_ERR("checkpoint %s slot %d: the device refused the copy of group %d (%lld rows of "
|
||||
"%lld bytes): %s", dir, (int)ck_slot, (int)g, (long long)p.n_layers,
|
||||
(long long)nbytes, rad_strerror(cs));
|
||||
return cs;
|
||||
}
|
||||
off += nbytes * p.n_layers;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+59
-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,24 @@ 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); }
|
||||
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
|
||||
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
|
||||
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
|
||||
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
|
||||
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
|
||||
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 +356,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 +369,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,13 +419,29 @@ 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;
|
||||
/* The store holds `slot`: it was allocated and not given back since. */
|
||||
bool checkpoint_held(int32_t slot) const;
|
||||
|
||||
/* SNAPSHOT AND RESUME A SEQUENCE'S WHOLE LINEAR STATE. This is what makes a prefix hit legal
|
||||
* on a hybrid model: the attention half of a hit is carried by the adopted blocks, and the
|
||||
@@ -483,7 +460,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 +475,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 +521,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 +532,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;
|
||||
|
||||
+3
-4
@@ -213,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;
|
||||
@@ -230,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());
|
||||
|
||||
+261
-79
@@ -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(),
|
||||
@@ -627,12 +740,23 @@ int64_t PrefixCache::retain(uint64_t session) {
|
||||
int64_t freed = 0;
|
||||
for (const auto& a : all) {
|
||||
if (std::binary_search(keep.begin(), keep.end(), a.first)) { kept.push_back(a.second); continue; }
|
||||
/* NOR ONE HANDED OUT THIS STEP, whatever the policy says of its position: the admission it
|
||||
* was handed to restores from the slot ahead of the step, and that is after this runs. */
|
||||
if (handed(a.second)) { 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,27 +772,33 @@ 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;
|
||||
}
|
||||
/* ONE HANDED OUT THIS STEP IS NOT RETIRED either: an admission restores from it ahead of
|
||||
* the step. This chunk goes without a checkpoint, which costs a later hit some replay. */
|
||||
if (handed(prefix)) return RAD_E_FULL;
|
||||
const uint64_t vs = existing->second.session;
|
||||
retire_ckpt(existing);
|
||||
auto sit = ck_by_session_.find(vs);
|
||||
@@ -710,10 +840,16 @@ 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;
|
||||
/* NOR ONE A LOOKUP HANDED OUT THIS STEP: its admission restores from the slot
|
||||
* ahead of the step, and a slot freed under it restores nothing. */
|
||||
if (handed(kvp.first)) continue;
|
||||
auto sit = ck_by_session_.find(kvp.second.session);
|
||||
bool is_tip = false;
|
||||
if (sit != ck_by_session_.end()) {
|
||||
@@ -731,9 +867,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 +902,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 +920,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 +941,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 +957,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,9 +976,9 @@ 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 (handed(kvp.first)) continue;
|
||||
if (!tiers_->snapshot_backed(kvp.first)) continue;
|
||||
victim = &c;
|
||||
}
|
||||
@@ -846,12 +989,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 +1043,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 */
|
||||
+98
-50
@@ -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
|
||||
@@ -54,6 +54,7 @@
|
||||
#include "mem/kv.h"
|
||||
#include "rad_core.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
@@ -108,6 +109,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 +194,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 +217,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 +286,55 @@ 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. */
|
||||
* by its forward, which committed before this step was planned. Until then a handed snapshot
|
||||
* keeps its slot through every path that would give one up: retention, the eviction in
|
||||
* reserve_checkpoint, and free_checkpoint_for_restore. */
|
||||
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). */
|
||||
@@ -309,12 +342,16 @@ public:
|
||||
bool is_checkpoint(int64_t pos) const { return interval_ > 0 && pos > 0 && pos % interval_ == 0; }
|
||||
|
||||
/* Reserve a snapshot slot for `session` at `pos`. Applies the retention policy when the slot
|
||||
* pool is exhausted, never evicting a session tip. RAD_E_FULL when even that is not enough. */
|
||||
* pool is exhausted, then evicts the least recently used snapshot, a session's tip last. A
|
||||
* snapshot a lookup handed out this step is never given up: the admission it was handed to
|
||||
* restores from the slot ahead of the step, after this reservation was made. RAD_E_FULL when
|
||||
* nothing else can be given up. */
|
||||
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 +398,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,10 +434,18 @@ 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). */
|
||||
/* Snapshots lookup handed out since begin_step: kept in their slots until then (begin_step). */
|
||||
mutable std::vector<BlockHash> handed_;
|
||||
bool handed(const BlockHash& h) const {
|
||||
return std::find(handed_.begin(), handed_.end(), h) != handed_.end();
|
||||
}
|
||||
mutable uint64_t clock_ = 0;
|
||||
std::unique_ptr<CheckpointPolicy> policy_;
|
||||
mutable Stats stats_;
|
||||
|
||||
+95
-45
@@ -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,20 +40,21 @@ static double paged_share(const VramBudget& b) {
|
||||
return ctx > 0 ? std::max(0.0, (double)(b.kv - b.kv_fixed)) / ctx : 0.0;
|
||||
}
|
||||
|
||||
/* The resolver, with its three log lines behind `log`: vram_budget_trial asks the same question
|
||||
/* 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; }
|
||||
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks
|
||||
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
|
||||
* of one deployment normally hold the same shard shapes and the same program, so these folds
|
||||
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
|
||||
* overcommitting the smaller one on the first allocation. */
|
||||
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
|
||||
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
|
||||
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);
|
||||
@@ -62,7 +70,12 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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);
|
||||
@@ -91,7 +104,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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.queues;
|
||||
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;
|
||||
@@ -101,6 +115,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"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 and KV tier staging)\n"
|
||||
@@ -110,7 +125,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" 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",
|
||||
@@ -147,39 +162,42 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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;
|
||||
@@ -214,7 +232,15 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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;
|
||||
@@ -244,7 +270,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"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));
|
||||
@@ -262,13 +289,14 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
* 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.queues - 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, and the\n"
|
||||
" KV tiers' copy staging\n"
|
||||
@@ -278,7 +306,7 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" 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"
|
||||
@@ -288,8 +316,8 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
" 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 "
|
||||
@@ -300,8 +328,10 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
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"
|
||||
@@ -339,10 +369,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
|
||||
"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",
|
||||
@@ -363,4 +394,23 @@ int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank,
|
||||
return resolve(c, per_rank, out, false);
|
||||
}
|
||||
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes) {
|
||||
RankSplit s;
|
||||
s.weights_mib = common_weights_mib;
|
||||
s.kv_mib = common_kv_mib;
|
||||
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
|
||||
const int64_t saved = common_kv_mib - need_kv_mib;
|
||||
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
|
||||
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
|
||||
* rather than allocated empty. */
|
||||
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
|
||||
const int64_t grown = std::min(common_weights_mib + saved, cap);
|
||||
s.kv_mib = need_kv_mib;
|
||||
s.weights_mib = grown;
|
||||
s.unusable_mib = saved - (grown - common_weights_mib);
|
||||
s.resplit = true;
|
||||
return s;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+48
-15
@@ -28,20 +28,23 @@
|
||||
* 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
|
||||
@@ -76,8 +79,18 @@ struct VramFacts {
|
||||
/* 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. */
|
||||
@@ -88,12 +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 */
|
||||
@@ -109,7 +125,8 @@ struct VramBudget {
|
||||
};
|
||||
|
||||
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree.
|
||||
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
|
||||
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
|
||||
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
|
||||
* fit on every card it is applied to.
|
||||
*
|
||||
@@ -121,4 +138,20 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
|
||||
* placement). */
|
||||
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
|
||||
|
||||
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
|
||||
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
|
||||
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
|
||||
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
|
||||
* every one of its weights would take resident (statics + all experts + their spare slots), this
|
||||
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
|
||||
* unclaimed. Nothing changes when the need is not below the common pool. */
|
||||
struct RankSplit {
|
||||
int64_t weights_mib = 0;
|
||||
int64_t kv_mib = 0;
|
||||
int64_t unusable_mib = 0; /* saved from the KV pool but past the weights cap: never allocated */
|
||||
bool resplit = false;
|
||||
};
|
||||
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
|
||||
int64_t need_kv_mib, int64_t weights_cap_bytes);
|
||||
|
||||
} /* namespace rad */
|
||||
+35
-2
@@ -20,6 +20,7 @@
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -101,6 +102,26 @@ 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. */
|
||||
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));
|
||||
}
|
||||
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
|
||||
if (p.vram_budget == pool_bytes) return RAD_OK;
|
||||
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
|
||||
"pool holds %s (%lld bytes): the planner and the pool were given different splits",
|
||||
p.rank, humanb(p.vram_budget).c_str(), (long long)p.vram_budget,
|
||||
humanb(pool_bytes).c_str(), (long long)pool_bytes);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
|
||||
TablePlacement ngram) {
|
||||
if (!out) return;
|
||||
@@ -166,6 +187,7 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
* 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) {
|
||||
@@ -178,9 +200,20 @@ void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement
|
||||
* 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; }
|
||||
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;
|
||||
@@ -1157,7 +1190,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) "
|
||||
|
||||
+28
-3
@@ -361,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
|
||||
@@ -377,6 +376,13 @@ 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`
|
||||
@@ -398,6 +404,25 @@ struct WeightFootprint {
|
||||
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 PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
|
||||
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
|
||||
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
|
||||
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
|
||||
* the rank and both sizes, when they differ. */
|
||||
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
|
||||
|
||||
/* 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
|
||||
|
||||
+56
-4
@@ -129,6 +129,27 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* 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);
|
||||
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; each step's head depth and each sequence's stop follow the
|
||||
* measured acceptance and the measured step cost. A serial drafter's policy only.
|
||||
* The default is kDraftWindowDefault, and the help text and the startup line read it from there.
|
||||
*
|
||||
* FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
|
||||
* two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
|
||||
*
|
||||
* concurrent sequences 1 2 4 8
|
||||
* adaptive, ceiling 3 +0.4% -0.1% +1.7% -0.3%
|
||||
* adaptive, ceiling 5 +7.1% -2.3% +7.4% -11.9%
|
||||
*
|
||||
* At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
|
||||
* 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
|
||||
* not yet timed at a load is priced on the prior. */
|
||||
enum class DraftWindow { Fixed = 0, Adaptive = 1 };
|
||||
constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
|
||||
inline const char* draft_window_name(DraftWindow w) {
|
||||
return w == DraftWindow::Adaptive ? "adaptive" : "fixed";
|
||||
}
|
||||
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
|
||||
@@ -146,6 +167,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
|
||||
@@ -201,6 +227,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];
|
||||
@@ -283,6 +313,7 @@ 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
|
||||
@@ -573,6 +604,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;
|
||||
@@ -599,9 +633,21 @@ 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 */
|
||||
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
|
||||
* model card's extension past its trained context, no reconvert); "none" takes a checkpoint's
|
||||
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
|
||||
std::string rope_scaling;
|
||||
|
||||
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
|
||||
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
|
||||
@@ -613,7 +659,10 @@ struct Config {
|
||||
* what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
|
||||
* that sum and writes the answer back into the two fields below, so every consumer downstream
|
||||
* -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
|
||||
* second place for them to disagree.
|
||||
* second place for them to disagree. Engine::plan derives each rank's own copy from it
|
||||
* (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
|
||||
* still one number per card, and the same number on every card whose cache costs as much per
|
||||
* token as the dearest rank's.
|
||||
*
|
||||
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
|
||||
int64_t vram_weights_mib = 0;
|
||||
@@ -628,7 +677,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
|
||||
@@ -701,8 +749,8 @@ struct Config {
|
||||
* code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
|
||||
* faults inside the HIP runtime rather than returning an error when there is no room. */
|
||||
|
||||
/* The speculative window, and the whole of the draft policy: the depth is constant and this
|
||||
* is it. See core/sched/draft.h. */
|
||||
/* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
|
||||
* core/sched/draft.h. */
|
||||
/* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
|
||||
* trained at, and a container with no draft head resolves to 0 with a line saying so.
|
||||
*
|
||||
@@ -712,6 +760,7 @@ struct Config {
|
||||
* paying for it again in VRAM, and then running at one token a step -- a small fraction of
|
||||
* the throughput the same container gives at its declared depth. */
|
||||
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
|
||||
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
|
||||
|
||||
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
|
||||
*
|
||||
@@ -736,6 +785,9 @@ 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;
|
||||
/* --reasoning-effort-map FROM=TO,...: an effort a request sends, replaced before the template
|
||||
* sees it. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
/* --thinking-token-budget: the chat endpoint's default `thinking_token_budget`, -1 for none. */
|
||||
int64_t thinking_token_budget = -1;
|
||||
int port = 8000;
|
||||
|
||||
@@ -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
|
||||
|
||||
+90
-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,10 +89,8 @@ 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;
|
||||
@@ -129,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;
|
||||
@@ -255,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 */
|
||||
@@ -295,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;
|
||||
@@ -352,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");
|
||||
|
||||
@@ -369,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");
|
||||
@@ -378,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;
|
||||
}
|
||||
|
||||
@@ -415,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();
|
||||
@@ -426,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);
|
||||
@@ -486,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
|
||||
@@ -513,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);
|
||||
}
|
||||
@@ -523,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 ||
|
||||
@@ -573,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;
|
||||
@@ -602,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;
|
||||
}
|
||||
@@ -633,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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -644,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);
|
||||
@@ -703,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;
|
||||
@@ -734,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;
|
||||
@@ -778,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;
|
||||
}
|
||||
|
||||
+41
-32
@@ -71,7 +71,7 @@ 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_; }
|
||||
@@ -105,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 ----------------
|
||||
*
|
||||
@@ -115,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_; }
|
||||
|
||||
@@ -157,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;
|
||||
};
|
||||
|
||||
@@ -202,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;
|
||||
@@ -254,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_;
|
||||
@@ -288,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
|
||||
@@ -314,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;
|
||||
|
||||
+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);
|
||||
|
||||
@@ -73,6 +73,10 @@ struct StepEntry {
|
||||
bool draft_out = false;
|
||||
bool is_prefill = false;
|
||||
bool produces_token = false; /* this entry's last token is the sequence's last */
|
||||
/* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
|
||||
* in the reported acceptance like any other, and kept out of the adaptive window's estimate,
|
||||
* which describes the draft head (DraftController, draft.h). */
|
||||
bool ngram = false;
|
||||
/* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
|
||||
* StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
|
||||
* `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
|
||||
|
||||
+255
-1
@@ -1,9 +1,46 @@
|
||||
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
|
||||
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
|
||||
* on. See draft.h for why the first is the default and what the second changes.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
|
||||
namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
|
||||
* one round of a serial head and one more verify row against a weight-bound step. It prices a
|
||||
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
|
||||
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
|
||||
constexpr double kCostSlope = 0.06;
|
||||
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
|
||||
|
||||
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
|
||||
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
|
||||
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
|
||||
* grows by a few thousand tokens over a reply. */
|
||||
constexpr double kCostHalfLife = 32.0;
|
||||
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
|
||||
* step that waited on something other than its own work -- a first recording, an allocation, a
|
||||
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
|
||||
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
|
||||
* against: its first step may itself be the odd one. */
|
||||
constexpr double kCostOutlier = 4.0;
|
||||
constexpr int64_t kCostClipAfter = 4;
|
||||
|
||||
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
|
||||
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
|
||||
* the half-life's, and from then on it is the moving average it is meant to be. Without it a
|
||||
* sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
|
||||
* a short answer. */
|
||||
constexpr double kPriorWeight = 4.0;
|
||||
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int DraftController::configure(const Params& p) {
|
||||
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
|
||||
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
|
||||
@@ -14,6 +51,24 @@ int DraftController::configure(const Params& p) {
|
||||
tot_drafted_ = tot_accepted_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
|
||||
seen_ = 0;
|
||||
|
||||
adapt_ = p.adapt && p.max_depth > 0;
|
||||
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
|
||||
step_d_ = 0;
|
||||
step_w_ = 0;
|
||||
step_held_ = 0;
|
||||
prior_n_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
|
||||
by_depth_[d] = 0;
|
||||
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
|
||||
}
|
||||
if (adapt_)
|
||||
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
|
||||
"maximises the tokens its sequences are expected to emit over the step's measured "
|
||||
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
|
||||
"time; moves at +%.0f%% and at most every %d steps",
|
||||
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -34,6 +89,205 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
if (j < accepted) ++hit_[j];
|
||||
}
|
||||
if (drafted > seen_) seen_ = drafted;
|
||||
if (adapt_) ++by_depth_[drafted];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's cost */
|
||||
int DraftController::cost_class(int n_rows) {
|
||||
int c = 0;
|
||||
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
|
||||
return c;
|
||||
}
|
||||
|
||||
void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
|
||||
!std::isfinite(ms))
|
||||
return;
|
||||
const int c = cost_class(n_rows);
|
||||
double& m = cost_ms_[depth][c];
|
||||
int64_t& n = cost_n_[depth][c];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
}
|
||||
|
||||
int64_t DraftController::cost_samples(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
|
||||
return cost_n_[depth][cost_class(n_rows)];
|
||||
}
|
||||
|
||||
double DraftController::step_cost(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
|
||||
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
|
||||
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
|
||||
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
|
||||
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
|
||||
* ONE class -- reads the prior's shape until its own depths are measured. */
|
||||
for (int dc = 0; dc < kCostClasses; ++dc) {
|
||||
for (int sgn = 0; sgn < 2; ++sgn) {
|
||||
const int k = sgn ? c + dc : c - dc;
|
||||
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
|
||||
int best = -1;
|
||||
for (int d = 1; d <= p_.max_depth; ++d) {
|
||||
if (cost_n_[d][k] <= 0) continue;
|
||||
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
|
||||
}
|
||||
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
|
||||
}
|
||||
}
|
||||
return cost_prior(depth);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one sequence */
|
||||
int DraftController::stop_of(const float* a) const {
|
||||
double p = 1.0;
|
||||
int d = 0;
|
||||
while (d < p_.max_depth) {
|
||||
p *= (double)a[d];
|
||||
if (p < kDraftMinChance) break;
|
||||
++d;
|
||||
}
|
||||
return d < kMinDepth ? kMinDepth : d;
|
||||
}
|
||||
|
||||
double DraftController::prior_at(int j) const {
|
||||
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
|
||||
}
|
||||
|
||||
void DraftController::start(DraftAdapt& s) const {
|
||||
/* Each position from the sequences that finished before it once there are enough of them
|
||||
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
|
||||
for (int j = 0; j < p_.max_depth; ++j) {
|
||||
s.a[j] = (float)prior_at(j);
|
||||
s.n[j] = 0;
|
||||
}
|
||||
s.depth = stop_of(s.a);
|
||||
s.held = 0;
|
||||
}
|
||||
|
||||
void DraftController::adapt_retire(const DraftAdapt& s) {
|
||||
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
|
||||
1.0 / (double)(prior_n_ + 1));
|
||||
for (int j = 0; j < p_.max_depth; ++j)
|
||||
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
|
||||
: s.a[j];
|
||||
++prior_n_;
|
||||
}
|
||||
|
||||
double DraftController::yield(const DraftAdapt& s, int d) const {
|
||||
if (d > p_.max_depth) d = p_.max_depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
|
||||
return e;
|
||||
}
|
||||
|
||||
int DraftController::window_of(const DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) return 0;
|
||||
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
|
||||
return s.depth < D ? s.depth : D;
|
||||
}
|
||||
|
||||
int DraftController::window_for(DraftAdapt& s) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
return window_of(s);
|
||||
}
|
||||
|
||||
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
|
||||
if (!adapt_) return p_.max_depth;
|
||||
if (s.depth <= 0) start(s);
|
||||
if (drafted <= 0) return s.depth;
|
||||
const int D = p_.max_depth;
|
||||
if (drafted > D) drafted = D;
|
||||
if (accepted < 0) accepted = 0;
|
||||
if (accepted > drafted) accepted = drafted;
|
||||
|
||||
/* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
|
||||
* rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
|
||||
* and never looked at, and says nothing either way. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
|
||||
const double x = j < accepted ? 1.0 : 0.0;
|
||||
s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
|
||||
if (s.n[j] < UINT16_MAX) ++s.n[j];
|
||||
}
|
||||
/* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
|
||||
* learned about them while the window is shorter -- and a sequence held at three by prose that
|
||||
* turns into code would otherwise keep pricing positions four and up at whatever they read
|
||||
* before, and never draft deep enough to find out. The guess is that acceptance decays with
|
||||
* position rather than falling off a cliff, so the window's edge stands in for what lies past
|
||||
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
|
||||
const double edge = (double)s.a[drafted - 1];
|
||||
for (int j = drafted; j < D; ++j)
|
||||
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
|
||||
|
||||
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
|
||||
if (s.held < INT32_MAX) ++s.held;
|
||||
if (s.held < kHold) return s.depth;
|
||||
const int d = stop_of(s.a);
|
||||
if (d != s.depth) {
|
||||
s.depth = d;
|
||||
s.held = 0;
|
||||
}
|
||||
return s.depth;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
if (!adapt_ || n_seq <= 0) return step_d_;
|
||||
if (n_rows < n_seq) n_rows = n_seq;
|
||||
const int M = p_.max_depth;
|
||||
|
||||
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
|
||||
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
|
||||
* sequence drafts further and the head runs no further -- so the candidates end there. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
DraftAdapt& s = *seq[i];
|
||||
if (s.depth <= 0) start(s);
|
||||
if (s.depth > top) top = s.depth;
|
||||
double e = 1.0, run = 1.0;
|
||||
for (int d = 1; d <= M; ++d) {
|
||||
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
|
||||
tok[d] += e;
|
||||
}
|
||||
}
|
||||
const double plain = (double)(n_rows - n_seq);
|
||||
if (top > M) top = M;
|
||||
|
||||
int best = kMinDepth;
|
||||
double best_g = -1.0;
|
||||
for (int d = kMinDepth; d <= top; ++d) {
|
||||
const double g = (tok[d] + plain) / step_cost(d, n_rows);
|
||||
if (g > best_g) { best_g = g; best = d; }
|
||||
}
|
||||
|
||||
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
|
||||
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
|
||||
if (step_d_ <= 0) {
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
} else {
|
||||
if (step_held_ < INT32_MAX) ++step_held_;
|
||||
const int cur = step_d_ < top ? step_d_ : top;
|
||||
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
|
||||
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
|
||||
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
|
||||
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
|
||||
best_g);
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
}
|
||||
}
|
||||
step_w_ = step_d_ < top ? step_d_ : top;
|
||||
return step_d_;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
+190
-4
@@ -1,8 +1,8 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
*
|
||||
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
|
||||
* No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
|
||||
* dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
|
||||
* decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
|
||||
* DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
|
||||
@@ -16,6 +16,42 @@
|
||||
*
|
||||
* What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
|
||||
* and because a verify that accepts nothing has to be visible.
|
||||
*
|
||||
* UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
|
||||
* weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
|
||||
* round -- a step is NOT flat in depth: each draft is one more round of the head and one more
|
||||
* verify row. And the best depth is not a property of the model pair but of the TEXT:
|
||||
* per-position acceptance stays high deep into the window on code and JSON and falls off after a
|
||||
* position or two on prose and summaries. No constant is right for all of them, and the one that
|
||||
* is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
|
||||
*
|
||||
* So the adaptive window is a policy on the host, in two halves:
|
||||
*
|
||||
* PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
|
||||
* acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
|
||||
* deepest draft whose chance of being emitted still pays for the verify row it adds
|
||||
* (kDraftMinChance).
|
||||
*
|
||||
* PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so depth is a property of the step and not of one sequence: D maximises
|
||||
* the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
|
||||
* at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
|
||||
* and T measured online (step_time). Every sequence then drafts min(D, stop_i).
|
||||
*
|
||||
* Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
|
||||
* a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
|
||||
* and everything sized for it stays sized for it.
|
||||
*
|
||||
* IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
|
||||
* prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
|
||||
* turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
|
||||
*
|
||||
* IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
|
||||
* core/sample/accept.h, so what a step emits is the target's own token at every position whatever
|
||||
* window it verified. At temperature 0 that is the same text at every window, to exactly the
|
||||
* degree a speculative run matches a plain one at all: exact given the same logits, and a verify
|
||||
* row's logits are computed at an M that now moves with the window (accept.h says what that does
|
||||
* and does not change).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -26,18 +62,148 @@ namespace rad {
|
||||
* band (spec §10), so 64 is the largest window any batch can carry. */
|
||||
enum { RAD_SCHED_MAX_SPEC = 64 };
|
||||
|
||||
/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
|
||||
* text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
|
||||
* and the controller does the arithmetic, so neither has to look the other up.
|
||||
*
|
||||
* `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
|
||||
* It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
|
||||
* it describes is still the text the request is writing -- and a recycled slot starts it over. */
|
||||
struct DraftAdapt {
|
||||
int32_t depth = 0; /* the sequence's stop; 0 = not started */
|
||||
int32_t held = 0; /* verifies since `depth` last moved */
|
||||
float a[RAD_SCHED_MAX_SPEC] = {}; /* conditional acceptance at each draft position */
|
||||
uint16_t n[RAD_SCHED_MAX_SPEC] = {}; /* verifies that evaluated each one, saturating */
|
||||
};
|
||||
|
||||
class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
/* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
|
||||
* drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
|
||||
bool adapt = false;
|
||||
};
|
||||
|
||||
/* ---------------------------------------------------------- the policy's constants
|
||||
* Named rather than configurable: each is a property of how the policy works, not of a
|
||||
* deployment, and the one property that IS a deployment's -- what a step costs -- is
|
||||
* measured (step_time). */
|
||||
|
||||
/* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
|
||||
* percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
|
||||
* a percent verify to verify; below two percent a move would flip D between two near-equal
|
||||
* neighbours and pay a recording each time. */
|
||||
static constexpr double kHyst = 0.02;
|
||||
/* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
|
||||
* second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
|
||||
* eight steps plays from the tape for most of them; and eight verifies at the half-life below
|
||||
* move an estimate by about a third of the way to a new rate, which is a trend rather than
|
||||
* one rejection. */
|
||||
static constexpr int kHold = 8;
|
||||
/* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
|
||||
* tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
|
||||
* into a code block and back, long enough that a single rejection moves an estimate by four
|
||||
* percent rather than resetting it. */
|
||||
static constexpr double kHalfLife = 16.0;
|
||||
/* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
|
||||
* deep evaluates every position and learns all of them, one that starts shallow learns nothing
|
||||
* about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
|
||||
* and on code at the first positions, so a wrong start is corrected within a hold. */
|
||||
static constexpr double kPrior = 0.8;
|
||||
/* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
|
||||
* the mean of their estimates, a running mean and then a moving average with a half-life of 32
|
||||
* sequences, so a deployment that moves from one kind of traffic to another follows it within
|
||||
* a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
|
||||
* once it has had a half-life of verifies: before that its estimate is mostly the prior it
|
||||
* started from, and folding it back would feed the prior to itself. */
|
||||
static constexpr int kPriorMinSeqs = 4;
|
||||
static constexpr double kPriorHalfLifeSeqs = 32.0;
|
||||
/* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
|
||||
* ever move its estimate off zero again. */
|
||||
static constexpr int kMinDepth = 1;
|
||||
/* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
|
||||
* and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
|
||||
* the step whatever D is, and that row is the only cost a sequence adds once the head runs D
|
||||
* rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
|
||||
* breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
|
||||
* it adds to the step, with E around two -- and a verify row alone costs less than a round
|
||||
* plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
|
||||
* measurement: a row's share of the step is not separable from the head's rounds in step
|
||||
* times keyed by depth, and the measured T(D, n) already prices the rounds. */
|
||||
static constexpr double kDraftMinChance = 0.1;
|
||||
/* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
|
||||
* step's cost moves with how many rows share its weight reads, and a class a power of two
|
||||
* wide keeps every key fed often enough to mean something. */
|
||||
static constexpr int kCostClasses = 5;
|
||||
|
||||
int configure(const Params& p);
|
||||
const Params& params() const { return p_; }
|
||||
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */
|
||||
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
|
||||
* under the adaptive policy it is the CEILING, and window_for() is the window. */
|
||||
int next_depth() const { return p_.max_depth; }
|
||||
|
||||
/* ---------------------------------------------------------- the adaptive policy */
|
||||
bool adaptive() const { return adapt_; }
|
||||
/* The window this sequence may draft into: min(D, its stop), starting its estimate on the
|
||||
* first ask; max_depth when the policy is off. Before any step has chosen D, D is the
|
||||
* ceiling. */
|
||||
int window_for(DraftAdapt& s) const;
|
||||
/* The same for a sequence whose estimate has started, without starting one: 0 when it has
|
||||
* not. For reporting. */
|
||||
int window_of(const DraftAdapt& s) const;
|
||||
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
|
||||
* estimate, and its stop past the hold. Returns the stop after. */
|
||||
int adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
|
||||
/* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
|
||||
*
|
||||
* PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
|
||||
* every verify -- are what a fixed window would want, and under this policy they are biased:
|
||||
* only a sequence whose drafts keep being accepted is given a window that reaches the deep
|
||||
* positions, so those positions are measured almost only on the texts that predict well, and
|
||||
* a new sequence would start as if every text did. Each finished sequence counts once here, at
|
||||
* every position, and at a position it never reached its estimate is the extrapolation from
|
||||
* its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
|
||||
* much as a deep one holds them up. */
|
||||
void adapt_retire(const DraftAdapt& s);
|
||||
/* The prior a sequence starting now is given at position `j`. For tests and logs. */
|
||||
double prior_at(int j) const;
|
||||
|
||||
/* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
|
||||
* draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
|
||||
* draft nothing). Started here if they have not been. Moves D past the hold and the
|
||||
* hysteresis; with no sequence to draft, D stays. Returns D. */
|
||||
int plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
|
||||
/* The step depth in force: 0 before the first step chose one. */
|
||||
int step_depth() const { return step_d_; }
|
||||
/* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
|
||||
* was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
|
||||
* any step chose one, and with the policy off. What a proposal from outside the head (prompt
|
||||
* lookup) is held to, so it adds no deeper pass shape than the head's own. */
|
||||
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
|
||||
|
||||
/* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
|
||||
* took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
|
||||
* adaptive policy reads it. */
|
||||
void step_time(int depth, int n_rows, double ms);
|
||||
/* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
|
||||
* been measured: the key's own mean when it has samples; the nearest measured key scaled by
|
||||
* the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
|
||||
* measured. */
|
||||
double step_cost(int depth, int n_rows) const;
|
||||
/* Samples behind a key: for tests and logs. */
|
||||
int64_t cost_samples(int depth, int n_rows) const;
|
||||
|
||||
/* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
|
||||
* the verified token included. For tests and logs. */
|
||||
double yield(const DraftAdapt& s, int d) const;
|
||||
/* Verifies by the window they carried, counted only under the policy: the histogram of the
|
||||
* depths it actually chose, which the mean gauge on its own cannot show. */
|
||||
int64_t verified_at(int d) const {
|
||||
return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
|
||||
}
|
||||
|
||||
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
|
||||
* taken. Feeds the reported metrics and nothing else. */
|
||||
void observe(int drafted, int accepted);
|
||||
@@ -76,6 +242,26 @@ private:
|
||||
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
|
||||
int seen_ = 0;
|
||||
|
||||
/* The adaptive policy as configure() resolved it. */
|
||||
bool adapt_ = false;
|
||||
double alpha_ = 0.0; /* the smoothing step from kHalfLife */
|
||||
int64_t by_depth_[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int32_t step_d_ = 0; /* D; 0 until a step chose one */
|
||||
int32_t step_w_ = 0; /* min(D, the deepest stop it saw) */
|
||||
int32_t step_held_ = 0; /* steps since D last moved */
|
||||
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
|
||||
float prior_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t prior_n_ = 0;
|
||||
/* T(d, class): the mean step time of each key, and the steps behind it. */
|
||||
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
|
||||
/* Fill a sequence's estimate from the prior and set its first stop. */
|
||||
void start(DraftAdapt& s) const;
|
||||
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
|
||||
int stop_of(const float* a) const;
|
||||
static int cost_class(int n_rows);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+62
-10
@@ -117,6 +117,11 @@ struct IKVManager {
|
||||
* it, so the batch builder is its one caller: it keeps the device's copy of a table and
|
||||
* stages only what moved. 0 is always a correct answer -- it restages the whole table. */
|
||||
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* THE SNAPSHOT STORE STILL HOLDS `slot`: it was allocated and not given back since. A step
|
||||
* that restores from a slot the store gave back would read another session's state or
|
||||
* nothing, so the scheduler asks before it builds one. */
|
||||
virtual bool checkpoint_held(int32_t slot) const = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
@@ -141,9 +146,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 +171,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 +223,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 */
|
||||
@@ -294,6 +312,7 @@ struct KVBinding final : IKVManager {
|
||||
int64_t take_table_changes(uint64_t s, int32_t g) const override {
|
||||
return m->take_table_changes(s, g);
|
||||
}
|
||||
bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
|
||||
};
|
||||
|
||||
/* The prefix cache's own lookup takes tokens and content-hashed multimodal keys rather than a
|
||||
@@ -323,10 +342,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 +354,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 +376,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 +430,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
|
||||
@@ -130,6 +137,13 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
|
||||
int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
|
||||
/* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
|
||||
* window it gives the sequences running now -- at one sequence, that sequence's window -- and
|
||||
* the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
|
||||
* where the policy stands, the histogram where it has been. */
|
||||
bool draft_adaptive = false;
|
||||
float draft_depth_adaptive = 0.0f;
|
||||
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+274
-27
@@ -87,10 +87,39 @@ 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;
|
||||
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
|
||||
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
|
||||
* pass at all, so for either the window stays fixed -- decided here, once, before any step
|
||||
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
|
||||
* like a flag that made no difference. */
|
||||
if (cfg.draft_window == DraftWindow::Adaptive) {
|
||||
const RadDrafterDecl& dd = prog.drafter;
|
||||
if (cfg.n_spec <= 0)
|
||||
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
|
||||
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
|
||||
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
|
||||
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
|
||||
"window prices the rounds of a serial draft head, which this deployment does "
|
||||
"not run", cfg.n_spec,
|
||||
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
|
||||
"pass"
|
||||
: "prompt lookup only");
|
||||
else
|
||||
dp.adapt = true;
|
||||
}
|
||||
RAD_TRY(draft_.configure(dp));
|
||||
draft_est_.clear();
|
||||
draft_est_.reserve((size_t)cfg.max_seqs);
|
||||
|
||||
RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
|
||||
/* The builder's bound and not a second derivation of it: it is what the block tables were
|
||||
@@ -171,6 +200,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.card = -1;
|
||||
s.running = false;
|
||||
s.drafter_reset();
|
||||
/* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
|
||||
s.adapt.depth = 0;
|
||||
s.adapt.held = 0;
|
||||
s.sched_tokens = 0;
|
||||
s.entry = -1;
|
||||
s.entry_next = -1;
|
||||
@@ -214,8 +246,15 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
|
||||
/* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
|
||||
* the card already put the tokens in its batch; the host copy is what that step's commit
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped. */
|
||||
* emits the accepted ones from, so it takes exactly those, unclamped.
|
||||
*
|
||||
* UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
|
||||
* and expect_draft() already cut this one's count to its own window -- the card verifies the
|
||||
* FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
|
||||
* count here, against the number the step was planned with: the window itself may have moved
|
||||
* at the commit in between, and the planned step is what these tokens are for. */
|
||||
if (next_open_ && s.entry_next >= 0) {
|
||||
if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
|
||||
if (n != s.draft_next) {
|
||||
RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d",
|
||||
(unsigned long long)id, n, s.draft_next);
|
||||
@@ -237,7 +276,7 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int cap = draft_.next_depth();
|
||||
int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
|
||||
for (int i = 0; i < n; ++i) s.draft[i] = tokens[i];
|
||||
@@ -280,7 +319,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. */
|
||||
@@ -300,17 +348,12 @@ 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,
|
||||
@@ -341,6 +384,14 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
}
|
||||
}
|
||||
|
||||
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
|
||||
/* What the draft head did on this text is now part of what the next text starts from --
|
||||
* once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
|
||||
if (draft_.adaptive()) {
|
||||
draft_.adapt_retire(s.adapt);
|
||||
s.adapt.depth = 0;
|
||||
}
|
||||
|
||||
if (defer_free) {
|
||||
if (!s.pending_free) ++n_deferred_;
|
||||
s.pending_free = true;
|
||||
@@ -665,7 +716,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) {
|
||||
@@ -688,6 +754,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();
|
||||
@@ -734,13 +820,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
|
||||
@@ -770,9 +872,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) {
|
||||
@@ -801,7 +903,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
|
||||
@@ -811,6 +923,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;
|
||||
}
|
||||
|
||||
@@ -848,6 +962,8 @@ void Scheduler::undo_hit(SchedReq& s) {
|
||||
/* ------------------------------------------------------------------ the step */
|
||||
const RadBatch* Scheduler::step() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
|
||||
draft_cycle();
|
||||
|
||||
/* The drafter's snapshots describe the step before this one and nothing reads them from here
|
||||
* on. block_end() and serial_end() clear them already; this covers a drafter that stopped
|
||||
@@ -903,10 +1019,22 @@ const RadBatch* Scheduler::step() {
|
||||
/* THE LAST GATE, and it has to be here rather than only at set_draft, because the
|
||||
* n-gram fallback below fills any proposal a drafter left empty -- so refusing a
|
||||
* draft upstream and stopping there hands the request a different draft instead of
|
||||
* none. Request::may_speculate says why a request can be ineligible. */
|
||||
* none. Request::may_speculate says why a request can be ineligible.
|
||||
*
|
||||
* AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
|
||||
* policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
|
||||
* for. The n-gram fallback is not the head and that estimate says nothing about it, so
|
||||
* it is held to the step's window instead: as deep as the head drafts this step and no
|
||||
* deeper, which adds no pass shape the head's own windows do not. */
|
||||
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
|
||||
bool ngram = false;
|
||||
if (!r.may_speculate) s.n_draft = 0;
|
||||
else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth);
|
||||
if (s.n_draft > depth) s.n_draft = depth;
|
||||
else if (s.n_draft == 0) {
|
||||
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
|
||||
ngram = s.n_draft > 0;
|
||||
}
|
||||
if (!ngram && s.n_draft > cap) s.n_draft = cap;
|
||||
s.draft_ngram = ngram;
|
||||
/* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
|
||||
* .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
|
||||
* block-table column. commit() finishes a sequence before its length reaches the
|
||||
@@ -993,6 +1121,7 @@ const RadBatch* Scheduler::step() {
|
||||
e.draft = s.draft;
|
||||
e.n_draft = s.n_draft;
|
||||
e.is_prefill = prefill;
|
||||
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
|
||||
e.produces_token = (r.n_computed + want >= target);
|
||||
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
|
||||
* sequence after this, and restoring it again on a later chunk would rewind it. */
|
||||
@@ -1187,8 +1316,23 @@ const RadBatch* Scheduler::step() {
|
||||
}();
|
||||
if (force_mixed && plan_.phase == RAD_PHASE_DECODE) plan_.phase = RAD_PHASE_MIXED;
|
||||
|
||||
/* EVERY SNAPSHOT THIS STEP RESTORES FROM IS STILL IN THE STORE. The prefix cache keeps a
|
||||
* handed-out snapshot's slot until the next step begins (PrefixCache::begin_step), so this
|
||||
* holds by construction; it is checked because a restore from a slot the store gave back
|
||||
* reads another session's state or nothing, and the engine can only stop on it. A step that
|
||||
* finds one is abandoned like a failed staging, below: the request gives its hit back and is
|
||||
* prefilled again, and the rest re-schedule unchanged. */
|
||||
bool lost_restore = false;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (e.ckpt_restore < 0 || kv_->checkpoint_held(e.ckpt_restore)) continue;
|
||||
RAD_ERR("sequence %llu was to resume from checkpoint slot %d, which the store no longer "
|
||||
"holds; its hit is given back and its prompt prefilled again",
|
||||
(unsigned long long)e.seq, (int)e.ckpt_restore);
|
||||
lost_restore = true;
|
||||
}
|
||||
|
||||
step_start_ = std::chrono::steady_clock::now();
|
||||
const RadBatch* b = builder_.build(plan_, *kv_, step_);
|
||||
const RadBatch* b = lost_restore ? nullptr : builder_.build(plan_, *kv_, step_);
|
||||
if (!b) {
|
||||
/* Staging failed. Nothing was computed, so nothing is committed and n_computed did not
|
||||
* advance: the next step re-schedules the same chunks and the KV allocations already made
|
||||
@@ -1244,12 +1388,39 @@ void Scheduler::take_encodes(std::vector<std::shared_ptr<mm::Item>>* out) {
|
||||
out->swap(enc_want_);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's head depth */
|
||||
void Scheduler::draft_cycle() {
|
||||
if (!draft_.adaptive()) return;
|
||||
/* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
|
||||
* may speculate draft, and their estimates choose D; the rest emit one token each, which is
|
||||
* part of what the step yields and of what it costs. A sequence still prefilling is neither. */
|
||||
draft_est_.clear();
|
||||
int n_rows = 0;
|
||||
for (int32_t slot : running_) {
|
||||
SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (!s.req || !s.running) continue;
|
||||
const Request& r = *s.req;
|
||||
if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
|
||||
++n_rows;
|
||||
if (r.may_speculate) draft_est_.push_back(&s.adapt);
|
||||
}
|
||||
(void)draft_.plan_step(draft_est_.data(), (int)draft_est_.size(), n_rows);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the next step */
|
||||
void Scheduler::expect_draft(uint64_t id, int n) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
auto it = by_id_.find(id);
|
||||
if (it == by_id_.end()) return;
|
||||
reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0;
|
||||
SchedReq& s = *reqs_[(size_t)it->second];
|
||||
/* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
|
||||
* first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
|
||||
* since: nothing commits between the two, and D is the cycle's (draft_cycle). */
|
||||
if (draft_.adaptive() && n > 0) {
|
||||
const int cap = draft_cap(s);
|
||||
if (n > cap) n = cap;
|
||||
}
|
||||
s.draft_next = n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
const RadBatch* Scheduler::step_next() {
|
||||
@@ -1333,6 +1504,10 @@ const RadBatch* Scheduler::step_next_locked() {
|
||||
void Scheduler::promote_next() {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!next_open_) return;
|
||||
/* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
|
||||
* called. Its proposals were counted under the last cycle's D; the next ones are drafted
|
||||
* under this one. */
|
||||
draft_cycle();
|
||||
std::swap(plan_, plan_next_);
|
||||
plan_next_.reset();
|
||||
step_prefill_tok_ = 0;
|
||||
@@ -1413,8 +1588,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;
|
||||
@@ -1488,6 +1665,28 @@ int Scheduler::commit(const StepResult& res) {
|
||||
|
||||
if (e.n_spec > 0) {
|
||||
draft_.observe(e.n_spec, a);
|
||||
/* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
|
||||
* window -- when the head drafted it. A prompt-lookup proposal is accepted on
|
||||
* different text by a different rule, and folding it in would price the head's
|
||||
* next window on what the lookup found. A move takes effect at the next draft:
|
||||
* this step's drafter has already run, sized from the estimate as it stood before
|
||||
* this commit. */
|
||||
if (draft_.adaptive() && !e.ngram) {
|
||||
const int was = s.adapt.depth;
|
||||
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
|
||||
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
|
||||
char est[8 * RAD_SCHED_MAX_SPEC];
|
||||
int o = 0;
|
||||
for (int j = 0; j < draft_.next_depth() && o < (int)sizeof est - 8; ++j)
|
||||
o += std::snprintf(est + o, sizeof est - (size_t)o, "%s%.2f",
|
||||
j ? " " : "", (double)s.adapt.a[j]);
|
||||
est[o] = 0;
|
||||
RAD_DEBUG("draft window: request %llu stops at %d, was %d (expected "
|
||||
"tokens a verify %.3f -> %.3f; acceptance by position %s)",
|
||||
(unsigned long long)r.id, now, was, draft_.yield(s.adapt, was),
|
||||
draft_.yield(s.adapt, now), est);
|
||||
}
|
||||
}
|
||||
m_.draft_tokens += e.n_spec;
|
||||
m_.draft_accepted += a;
|
||||
server::sink_drafts(r.sink, e.n_spec, a);
|
||||
@@ -1614,6 +1813,16 @@ void Scheduler::step_finished() {
|
||||
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
|
||||
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
|
||||
}
|
||||
/* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
|
||||
* which is the step's share of the loop -- the draft rounds that followed it included, and a
|
||||
* step issued ahead counted from the end of the one before rather than twice. A decode step
|
||||
* only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
|
||||
* the step verified, which is the head depth it ran at whenever D held from the step before. */
|
||||
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
|
||||
int rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
|
||||
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
|
||||
}
|
||||
last_step_at_ = step_end;
|
||||
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
|
||||
step_start_ = {};
|
||||
@@ -1647,6 +1856,27 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
if (depth > 0 && *rounds > depth) *rounds = depth;
|
||||
if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
|
||||
|
||||
/* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
|
||||
* pass of the head over every drafting row, so the step runs as many as its deepest window,
|
||||
* and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
|
||||
* round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
|
||||
* draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
|
||||
* is the history pass, and that still has to run. The reservation below is then made for the
|
||||
* rounds that will actually run, which is what it is for. */
|
||||
if (may_draft && draft_.adaptive()) {
|
||||
int want = 0;
|
||||
for (const StepEntry& e : plan_.e) {
|
||||
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
|
||||
SchedReq& s = *reqs_[(size_t)e.slot];
|
||||
if (!s.req || s.req->state != ReqState::Running || !s.running ||
|
||||
!s.req->may_speculate)
|
||||
continue;
|
||||
const int c = draft_cap(s);
|
||||
if (c > want) want = c;
|
||||
}
|
||||
if (want > 0 && *rounds > want) *rounds = want;
|
||||
}
|
||||
|
||||
int n_draft_rows = 0;
|
||||
int64_t cu = 0; /* this entry's first token in the step just run */
|
||||
for (size_t i = 0; i < plan_.e.size(); ++i) {
|
||||
@@ -2172,6 +2402,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);
|
||||
@@ -2199,6 +2430,22 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.draft_pos_reached [j] = draft_.reached(j);
|
||||
m.draft_pos_accepted[j] = draft_.hits(j);
|
||||
}
|
||||
if (draft_.adaptive()) {
|
||||
m.draft_adaptive = true;
|
||||
/* Over the running sequences whose estimate has started; one that has not drafted yet
|
||||
* has no window to report. */
|
||||
int64_t sum = 0, n = 0;
|
||||
for (int32_t slot : running_) {
|
||||
const SchedReq& s = *reqs_[(size_t)slot];
|
||||
if (s.adapt.depth <= 0) continue;
|
||||
/* The window it drafts into: its stop under the step's head depth. */
|
||||
sum += draft_.window_of(s.adapt);
|
||||
++n;
|
||||
}
|
||||
m.draft_depth_adaptive = n ? (float)((double)sum / (double)n) : 0.0f;
|
||||
const int kDepth = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
for (int d = 0; d < kDepth; ++d) m.draft_verify_depth[d] = draft_.verified_at(d);
|
||||
}
|
||||
return m;
|
||||
}
|
||||
|
||||
|
||||
+47
-2
@@ -109,6 +109,14 @@ struct SchedReq {
|
||||
draft_hi = 0;
|
||||
}
|
||||
|
||||
/* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
|
||||
* deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
|
||||
* preemption does not change, rather than any cache the request holds. A recycled slot starts
|
||||
* it over in add_locked. Untouched while the policy is off. */
|
||||
DraftAdapt adapt;
|
||||
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
|
||||
bool draft_ngram = false;
|
||||
|
||||
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
|
||||
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
|
||||
/* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
|
||||
@@ -280,7 +288,8 @@ public:
|
||||
* the one that is stuck. Returns how many were written. */
|
||||
int requests(ReqStat* out, int max) const;
|
||||
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
|
||||
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
|
||||
int set_draft(uint64_t id, const int32_t* tokens, int n);
|
||||
|
||||
/* ---------------------------------------------------------- media the encoder owes
|
||||
@@ -318,7 +327,8 @@ public:
|
||||
* from one to the other.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* which is how many the next step verifies.
|
||||
* which is how many the next step verifies -- capped at the sequence's window,
|
||||
* which under the adaptive policy can be fewer than the rounds that ran.
|
||||
* step_next plans and builds that step: every row of this one, as a device row, at
|
||||
* the furthest context it can reach. Null -- and the engine plans with step()
|
||||
* after this one commits -- whenever the step needs a decision only a
|
||||
@@ -445,6 +455,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;
|
||||
|
||||
@@ -469,6 +482,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_;
|
||||
|
||||
@@ -479,6 +501,29 @@ private:
|
||||
return hit_holes_draft_ ? ctx_len : 0;
|
||||
}
|
||||
|
||||
/* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
|
||||
* min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
|
||||
* It is the rule every site that caps a proposal applies -- step(), set_draft(),
|
||||
* expect_draft() and the rounds in serial_begin() -- and with the policy off it is
|
||||
* next_depth(), exactly as before. */
|
||||
int draft_cap(SchedReq& s) const {
|
||||
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
|
||||
}
|
||||
|
||||
/* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
|
||||
* first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
|
||||
* A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
|
||||
* draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
|
||||
* to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
|
||||
* different one. A D read live could move between them, because a commit or a client hanging
|
||||
* up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
|
||||
* proposal drafted under one D and planned under the next is only ever cut shorter.
|
||||
*
|
||||
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
|
||||
* allocate. */
|
||||
std::vector<DraftAdapt*> draft_est_;
|
||||
void draft_cycle();
|
||||
|
||||
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
|
||||
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
|
||||
* lengths it tries, longest first. */
|
||||
|
||||
+24
-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;
|
||||
@@ -276,6 +280,13 @@ public:
|
||||
o.draft_pos_reached [j] = m.draft_pos_reached [j];
|
||||
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
|
||||
}
|
||||
o.draft_adaptive = m.draft_adaptive;
|
||||
o.draft_depth_adaptive = m.draft_depth_adaptive;
|
||||
{
|
||||
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
|
||||
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
|
||||
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
|
||||
}
|
||||
o.preemptions = m.preemptions;
|
||||
o.total_requests = m.admitted;
|
||||
o.steps = m.steps;
|
||||
@@ -308,6 +319,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 +444,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;
|
||||
@@ -545,6 +562,7 @@ public:
|
||||
o.grammar = opt.grammar;
|
||||
o.json_schema = opt.json_schema;
|
||||
o.template_kwargs = opt.template_kwargs;
|
||||
o.quiet = opt.quiet;
|
||||
|
||||
ChatPrompt p;
|
||||
const int st = t_.apply(messages, tools, o, &p);
|
||||
@@ -587,6 +605,8 @@ public:
|
||||
gq.generation_prompt = p.generation_prompt;
|
||||
gq.parallel_tool_calls = opt.parallel_tool_calls;
|
||||
gq.extract_reasoning = opt.reasoning_format != "none";
|
||||
gq.require_call = calls && opt.tool_choice == "required";
|
||||
gq.only_tool = opt.tool_name;
|
||||
ChatGrammar g;
|
||||
std::string gerr;
|
||||
if (chat_format_grammar(f, gq, &g, &gerr) < 0) {
|
||||
|
||||
+15
-4
@@ -161,6 +161,7 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
if (kw != b.end() && kw->is_object())
|
||||
for (auto it = kw->begin(); it != kw->end(); ++it)
|
||||
opt.template_kwargs[it.key()] = json_dump(it.value());
|
||||
map_reasoning_effort(lim_, &opt);
|
||||
|
||||
json tools = json::array();
|
||||
auto t = b.find("tools");
|
||||
@@ -168,10 +169,8 @@ HttpResponse Server::handle_tokenize(const HttpRequest& req) {
|
||||
|
||||
ChatRender render;
|
||||
std::string why;
|
||||
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), req.peer);
|
||||
if (const int rs = deps_.chat->apply(*msgs, tools, opt, &render, &why); rs < 0)
|
||||
return error_response(template_refusal(opt, lim_, rs, why), req.peer);
|
||||
toks = deps_.tok->encode(render.prompt,
|
||||
get_bool_or(b, "add_special_tokens", false),
|
||||
/*parse_special=*/true);
|
||||
@@ -299,6 +298,15 @@ HttpResponse Server::handle_server_info(const HttpRequest&) {
|
||||
caps["video"] = deps_.mm && deps_.mm->accepts(MediaKind::Video);
|
||||
caps["audio"] = deps_.mm && deps_.mm->accepts(MediaKind::Audio);
|
||||
caps["logprobs"] = opt_.supports_logprobs;
|
||||
/* THE EFFORTS A CHAT REQUEST MAY SEND, as probed from the template at startup: null when it
|
||||
* takes any word. "none" and "minimal" are this server's, and turn thinking off. */
|
||||
if (lim_.reasoning_efforts.empty()) {
|
||||
caps["reasoning_efforts"] = nullptr;
|
||||
} else {
|
||||
std::vector<std::string> e = { "none", "minimal" };
|
||||
e.insert(e.end(), lim_.reasoning_efforts.begin(), lim_.reasoning_efforts.end());
|
||||
caps["reasoning_efforts"] = e;
|
||||
}
|
||||
|
||||
/* WHAT A REQUEST THAT LEAVES A FIELD OUT GETS, under the request's own spelling of each
|
||||
* field, so a client can read off exactly what leaving one out means on this deployment. */
|
||||
@@ -325,6 +333,9 @@ 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);
|
||||
json emap = json::object();
|
||||
for (const auto& [from, to] : lim_.reasoning_effort_map) emap[from] = to;
|
||||
defs["reasoning_effort_map"] = std::move(emap);
|
||||
defs["thinking_token_budget"] = opt_.default_thinking_budget < 0
|
||||
? json(nullptr) : json(opt_.default_thinking_budget);
|
||||
json kw = json::object();
|
||||
|
||||
+22
-14
@@ -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
|
||||
@@ -1484,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. */
|
||||
@@ -1729,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,
|
||||
@@ -1769,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
|
||||
|
||||
+32
-5
@@ -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
|
||||
@@ -106,6 +114,11 @@ struct SchedMetrics {
|
||||
int draft_depth_seen = 0;
|
||||
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
|
||||
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
|
||||
* of the running sequences, and the verifies by the window they carried (index = drafts). */
|
||||
bool draft_adaptive = false;
|
||||
double draft_depth_adaptive = 0.0;
|
||||
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
|
||||
int64_t preemptions = 0;
|
||||
int64_t total_requests = 0;
|
||||
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
|
||||
@@ -157,7 +170,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 +277,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,6 +307,9 @@ 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 {
|
||||
@@ -361,10 +378,14 @@ struct ChatRenderOptions {
|
||||
bool enable_thinking = true;
|
||||
bool parallel_tool_calls = true;
|
||||
std::string tool_choice = "auto"; /* auto | none | required */
|
||||
std::string tool_name; /* a named tool_choice's function, or "" */
|
||||
std::string grammar; /* the caller's GBNF, or "" */
|
||||
std::string json_schema; /* a response_format schema, as JSON text, or "" */
|
||||
std::string reasoning_format = "auto";
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
/* A render whose refusal is an answer and not an error -- the startup probes of what the
|
||||
* template takes -- so the template's refusal is not logged. */
|
||||
bool quiet = false;
|
||||
};
|
||||
|
||||
/* What it gives back. A STRING IS NOT ENOUGH, and that is the whole reason this struct exists: a
|
||||
@@ -430,6 +451,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
|
||||
@@ -458,6 +481,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 */
|
||||
+55
-1
@@ -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);
|
||||
@@ -138,11 +140,23 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
for (int j = 0; j < seen; ++j) {
|
||||
const int64_t r = m.draft_pos_reached[j];
|
||||
g_draft_pos_reached_[j].set((double)r);
|
||||
g_draft_pos_accepted_[j].set((double)m.draft_pos_accepted[j]);
|
||||
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
|
||||
}
|
||||
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
|
||||
* gauge has not been written yet. */
|
||||
draft_pos_seen_.store(seen, std::memory_order_release);
|
||||
if (m.draft_adaptive) {
|
||||
g_draft_depth_adapt_.set(m.draft_depth_adaptive);
|
||||
int top = 0;
|
||||
for (int d = 1; d <= (int)MAX_DRAFT_POS; ++d) {
|
||||
g_draft_vdepth_[d].set((double)m.draft_verify_depth[d]);
|
||||
if (m.draft_verify_depth[d] > 0) top = d;
|
||||
}
|
||||
/* After the gauges, for the reason above. */
|
||||
draft_vdepth_top_.store(top, std::memory_order_release);
|
||||
draft_adapt_on_.store(true, std::memory_order_release);
|
||||
}
|
||||
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
|
||||
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
|
||||
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
|
||||
@@ -158,6 +172,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 +256,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 +360,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
|
||||
@@ -365,7 +394,9 @@ std::string Metrics::render() const {
|
||||
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
|
||||
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
|
||||
* drafter that decays from one whose later rounds are broken; these can, and the companion
|
||||
* `_reached_total` says how much evidence each position carries. */
|
||||
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
|
||||
* same ratio over any window: at a fixed depth the next position's reach would do, but an
|
||||
* adaptive window can end at j with j taken. */
|
||||
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
|
||||
if (seen > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
@@ -380,6 +411,29 @@ std::string Metrics::render() const {
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
|
||||
w.help("radiance:draft_position_accepted_total",
|
||||
"Verifies that accepted each draft position.", "counter");
|
||||
for (int j = 0; j < seen; ++j)
|
||||
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
|
||||
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
|
||||
}
|
||||
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
|
||||
* at one sequence, that sequence's window -- and where it has been, as verifies by the
|
||||
* number of drafts they carried. */
|
||||
if (draft_adapt_on_.load(std::memory_order_acquire)) {
|
||||
w.gauge("radiance:draft_depth_adaptive",
|
||||
"Mean draft window the adaptive policy gives the running sequences.",
|
||||
L, g_draft_depth_adapt_.get());
|
||||
const int top = draft_vdepth_top_.load(std::memory_order_acquire);
|
||||
if (top > 0) {
|
||||
const std::string base = L.substr(0, L.size() - 1);
|
||||
w.help("radiance:draft_verify_depth_total",
|
||||
"Verifies by the number of drafts they carried, under the adaptive window.",
|
||||
"counter");
|
||||
for (int d = 1; d <= top; ++d)
|
||||
w.out += "radiance:draft_verify_depth_total" + base + ",depth=\"" +
|
||||
std::to_string(d) + "\"} " + num(g_draft_vdepth_[d].get()) + '\n';
|
||||
}
|
||||
}
|
||||
w.gauge("radiance:num_requests_preempted",
|
||||
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
|
||||
|
||||
@@ -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
|
||||
@@ -120,7 +121,15 @@ private:
|
||||
enum { MAX_DRAFT_POS = 64 };
|
||||
Gauge g_draft_pos_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
|
||||
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
|
||||
std::atomic<int> draft_pos_seen_{0};
|
||||
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
|
||||
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
|
||||
* is on, so a deployment without it exposes exactly what it always did. */
|
||||
Gauge g_draft_depth_adapt_;
|
||||
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
|
||||
std::atomic<bool> draft_adapt_on_{false};
|
||||
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
|
||||
|
||||
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
|
||||
* counter and adding the difference. Two scrapes doing that at once both read the old value
|
||||
@@ -143,6 +152,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_;
|
||||
|
||||
+143
-53
@@ -142,6 +142,7 @@ std::string ApiError::dump() const {
|
||||
e["type"] = type;
|
||||
if (param.empty()) e["param"] = nullptr; else e["param"] = param;
|
||||
if (code.empty()) e["code"] = nullptr; else e["code"] = code;
|
||||
if (!supported.empty()) e["supported"] = supported;
|
||||
json o;
|
||||
o["error"] = e;
|
||||
return o.dump();
|
||||
@@ -652,6 +653,53 @@ void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOpti
|
||||
opt->reasoning_format = lim.reasoning_format;
|
||||
}
|
||||
|
||||
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt) {
|
||||
if (lim.reasoning_effort_map.empty()) return;
|
||||
auto it = opt->template_kwargs.find("reasoning_effort");
|
||||
if (it == opt->template_kwargs.end()) return;
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
if (!v.is_string()) return;
|
||||
auto m = lim.reasoning_effort_map.find(v.get<std::string>());
|
||||
if (m == lim.reasoning_effort_map.end()) return;
|
||||
if (m->second == "none" || m->second == "minimal") {
|
||||
opt->enable_thinking = false;
|
||||
opt->template_kwargs.erase(it);
|
||||
} else {
|
||||
it->second = json(m->second).dump();
|
||||
}
|
||||
}
|
||||
|
||||
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
|
||||
const std::string& why) {
|
||||
/* AN EFFORT OUTSIDE THE SET IS THE REASON, when the set is known and the word is not in it:
|
||||
* the render that refused carried no other variable the template was probed for. The
|
||||
* template's own sentence is a traceback through its source, which says nothing a client can
|
||||
* act on that the set does not. */
|
||||
auto it = opt.template_kwargs.find("reasoning_effort");
|
||||
if (it != opt.template_kwargs.end() && !lim.reasoning_efforts.empty()) {
|
||||
const json v = json::parse(it->second, nullptr, false);
|
||||
const std::vector<std::string>& set = lim.reasoning_efforts;
|
||||
if (v.is_string() && std::find(set.begin(), set.end(), v.get<std::string>()) == set.end()) {
|
||||
std::string list;
|
||||
for (size_t i = 0; i < set.size(); ++i)
|
||||
list += (i ? (i + 1 == set.size() ? " and " : ", ") : "") + ("'" + set[i] + "'");
|
||||
ApiError e = err_bad("reasoning_effort",
|
||||
"'" + v.get<std::string>() + "' is not a level this model's chat "
|
||||
"template takes. It takes " + list + "; 'none' and 'minimal' "
|
||||
"turn thinking off");
|
||||
e.code = "unsupported_value";
|
||||
e.supported = { "none", "minimal" };
|
||||
e.supported.insert(e.supported.end(), set.begin(), set.end());
|
||||
return e;
|
||||
}
|
||||
}
|
||||
return rs == RAD_E_UNSUPPORTED
|
||||
? err_unsupported("messages", why.empty() ? "the chat template refused this request"
|
||||
: why)
|
||||
: err_bad("messages", why.empty() ? "the chat template could not render this "
|
||||
"request" : why);
|
||||
}
|
||||
|
||||
static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions* opt,
|
||||
ApiError* err) {
|
||||
auto kw = b.find("chat_template_kwargs");
|
||||
@@ -677,6 +725,7 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
|
||||
}
|
||||
}
|
||||
}
|
||||
map_reasoning_effort(lim, opt);
|
||||
|
||||
bool think = opt->enable_thinking;
|
||||
if (!get_bool(b, "enable_thinking", &think, err)) return RAD_E_INVAL;
|
||||
@@ -713,6 +762,10 @@ static int parse_thinking(const json& b, const OaiLimits& lim, ChatRenderOptions
|
||||
* An explicit chat_template_kwargs entry still wins: emplace does not overwrite. */
|
||||
std::string effort;
|
||||
if (!get_str(b, "reasoning_effort", &effort, err)) return RAD_E_INVAL;
|
||||
/* --reasoning-effort-map, before "none" and "minimal" are read, so a map can name either. */
|
||||
if (auto m = lim.reasoning_effort_map.find(effort);
|
||||
!effort.empty() && m != lim.reasoning_effort_map.end())
|
||||
effort = m->second;
|
||||
/* The deployment's default, where the request did not say. Last, so every explicit spelling
|
||||
* above it wins; emplace, so a chat_template_kwargs entry that already set the key stands.
|
||||
* "none" and "minimal" are an enable_thinking default, so any word about thinking drops them;
|
||||
@@ -1323,14 +1376,10 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
out->n_tools = (int)tools.size();
|
||||
}
|
||||
|
||||
/* FORCING A CALL IS REFUSED, and not because the grammar is out of reach -- the template
|
||||
* returns one. It is that the grammar it returns for a forced choice does not force anything:
|
||||
* it admits leading prose (the template invites "optional reasoning BEFORE the function
|
||||
* call") and then an unbounded run of calls with no terminating state, so the reply is prose
|
||||
* followed by invented calls and `finish_reason: "length"`. Serving that would be worse than
|
||||
* refusing it: the caller asked for exactly one call and would get a request that never stops.
|
||||
* `parallel_tool_calls: false` IS honoured -- that one narrows the grammar's repetition rule,
|
||||
* which is a change the generator actually makes. */
|
||||
/* A forced choice -- "required", or an object naming one function -- makes the call grammar
|
||||
* the whole reply instead of a lazy one: the reasoning block, then the calls (one when
|
||||
* `parallel_tool_calls` is false), then nothing, so the reply ends at the last call. A named
|
||||
* function narrows the calls to that one. */
|
||||
std::string tool_choice = "auto", named;
|
||||
auto tcit = b.find("tool_choice");
|
||||
if (tcit != b.end() && !tcit->is_null()) {
|
||||
@@ -1355,17 +1404,22 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
if (tool_choice == "none") {
|
||||
tools = json::array();
|
||||
} else if (tool_choice == "required") {
|
||||
*err = err_unsupported(
|
||||
"tool_choice",
|
||||
named.empty()
|
||||
? "\"auto\" and \"none\" are implemented. \"required\" is not: the grammar this "
|
||||
"model's template produces for it admits prose before the call and an unbounded "
|
||||
"run of calls after it, so it does not force one call -- it produces a reply "
|
||||
"that runs to max_tokens. Send \"auto\" and check the response for a call."
|
||||
: "a named function is not implemented, for the same reason \"required\" is not: "
|
||||
"the template's forced-call grammar does not terminate. Send \"auto\" with only "
|
||||
"that function in `tools`.");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (tools.empty()) {
|
||||
*err = err_bad("tool_choice", "a tool call is required, but `tools` is empty");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!named.empty() &&
|
||||
std::none_of(tools.begin(), tools.end(), [&](const json& t) {
|
||||
return t.at("function").at("name") == named;
|
||||
})) {
|
||||
*err = err_bad("tool_choice", "names \"" + named + "\", which is not in `tools`");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!schema_json.empty() || !out->sp.grammar.empty()) {
|
||||
*err = err_bad("tool_choice", "a forced tool call is the whole reply, so it cannot be "
|
||||
"combined with `response_format` or `grammar`");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (tool_choice != "auto") {
|
||||
*err = err_bad("tool_choice", "must be \"none\", \"auto\", \"required\", or an object");
|
||||
return RAD_E_INVAL;
|
||||
@@ -1392,7 +1446,9 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
out->tools_present = !tools.empty();
|
||||
|
||||
ChatRenderOptions opt;
|
||||
opt.quiet = lim.probe;
|
||||
opt.tool_choice = tool_choice;
|
||||
opt.tool_name = named;
|
||||
opt.parallel_tool_calls = parallel;
|
||||
if (!get_bool(b, "add_generation_prompt", &opt.add_generation_prompt, err)) return RAD_E_INVAL;
|
||||
|
||||
@@ -1412,11 +1468,7 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
std::string why;
|
||||
const int rs = d.chat->apply(messages, tools, opt, &render, &why);
|
||||
if (rs < 0) {
|
||||
*err = rs == RAD_E_UNSUPPORTED
|
||||
? err_unsupported("messages", why.empty() ? "the chat template refused this "
|
||||
"request" : why)
|
||||
: err_bad("messages", why.empty() ? "the chat template could not render this "
|
||||
"request" : why);
|
||||
*err = template_refusal(opt, lim, rs, why);
|
||||
return rs;
|
||||
}
|
||||
if (render.prompt.empty()) {
|
||||
@@ -1456,6 +1508,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
|
||||
@@ -1962,6 +2020,27 @@ std::string ChatDeltaStream::chunk(json delta, const char* finish_reason, const
|
||||
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";
|
||||
@@ -1976,49 +2055,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;
|
||||
}
|
||||
@@ -2030,9 +2113,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;
|
||||
@@ -2053,14 +2138,19 @@ std::string ChatDeltaStream::push(std::string_view appended, bool is_final) {
|
||||
return out;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
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;
|
||||
/* 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) {
|
||||
|
||||
@@ -37,6 +37,9 @@ struct ApiError {
|
||||
std::string message;
|
||||
std::string param; /* "" when the error is not about one field */
|
||||
std::string code; /* "" when there is nothing more specific to say */
|
||||
/* The values `param` takes, when the error is a value outside a known set: `supported` in the
|
||||
* envelope, so a client can retry with one rather than parse the sentence. */
|
||||
std::vector<std::string> supported;
|
||||
|
||||
std::string dump() const; /* the OpenAI error envelope, as a JSON string */
|
||||
};
|
||||
@@ -77,6 +80,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;
|
||||
@@ -144,6 +150,22 @@ struct OaiLimits {
|
||||
* dial at all. Seeded only when the request says nothing, so a caller always wins. */
|
||||
std::string default_reasoning_effort;
|
||||
|
||||
/* THE WORDS THE CHAT TEMPLATE TAKES AS `reasoning_effort`, found at startup by rendering each
|
||||
* word this server knows of (Server::probe_reasoning_efforts). Empty when the template takes
|
||||
* any word -- it does not read the variable, or reads it without refusing one -- and when
|
||||
* nothing was probed. A request whose effort the template refuses is answered with this set
|
||||
* rather than with the template's traceback (template_refusal). */
|
||||
std::vector<std::string> reasoning_efforts;
|
||||
|
||||
/* --reasoning-effort-map: an effort a request sends, replaced by the deployment's word before
|
||||
* the template sees it. For a client that always sends a word of OpenAI's ladder ("high")
|
||||
* to a model whose template has its own ("xhigh"). */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
|
||||
/* A STARTUP PROBE, NOT A REQUEST: what the template refuses is the answer being asked for, so
|
||||
* its refusal is not logged (ChatRenderOptions::quiet). */
|
||||
bool probe = false;
|
||||
|
||||
/* 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.
|
||||
@@ -193,6 +215,19 @@ RequestThinking request_thinking(const json& b);
|
||||
* prompt served by the other. */
|
||||
void apply_template_defaults(const json& b, const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* --reasoning-effort-map, on the effort chat_template_kwargs put in the render options: a mapped
|
||||
* word replaces it, and a word mapped to "none" or "minimal" turns thinking off instead. The chat
|
||||
* endpoint maps the top-level `reasoning_effort` itself, before it reads "none" and "minimal";
|
||||
* this is the kwargs spelling, for it and for /tokenize. */
|
||||
void map_reasoning_effort(const OaiLimits& lim, ChatRenderOptions* opt);
|
||||
|
||||
/* THE 400 FOR A TEMPLATE THAT REFUSED A RENDER. An effort outside the template's known set
|
||||
* (OaiLimits::reasoning_efforts) is named as `reasoning_effort` with the set in `supported`, the
|
||||
* way OpenAI answers an unsupported value; anything else is `messages` with the template's own
|
||||
* sentence. */
|
||||
ApiError template_refusal(const ChatRenderOptions& opt, const OaiLimits& lim, int rs,
|
||||
const std::string& why);
|
||||
|
||||
/* True when `v` is a legal value of the sampler field a request spells `field`; otherwise `why`
|
||||
* says what the legal set is, in the words a 400 carries. The same table checks a request and the
|
||||
* command-line flag that sets the field's default, so a default the command line accepts is one
|
||||
@@ -290,6 +325,11 @@ std::string chat_usage_chunk(const OaiRequest& r, const UsageOut& u,
|
||||
/* 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
|
||||
*
|
||||
* One of these per choice. It feeds the generated text to the choice's reply reader as it grows
|
||||
@@ -323,6 +363,14 @@ private:
|
||||
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_;
|
||||
|
||||
+83
-11
@@ -30,6 +30,10 @@ struct Server::Generation {
|
||||
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 */
|
||||
@@ -65,6 +69,7 @@ Server::Server(const Deps& d, const ServerOptions& o)
|
||||
lim_.default_sampling = opt_.default_sampling;
|
||||
lim_.default_dry_breakers_set = opt_.default_dry_breakers_set;
|
||||
lim_.default_template_kwargs = opt_.default_template_kwargs;
|
||||
lim_.reasoning_effort_map = opt_.reasoning_effort_map;
|
||||
lim_.reasoning_format = opt_.reasoning_format;
|
||||
|
||||
odeps_.tok = deps_.tok;
|
||||
@@ -192,6 +197,7 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.probe = true;
|
||||
if (!render(l, nullptr)) return;
|
||||
l.default_template_kwargs = lim_.default_template_kwargs;
|
||||
if (!l.default_template_kwargs.empty() && !render(l, kwargs_why)) return;
|
||||
@@ -199,6 +205,50 @@ void Server::check_template_defaults(std::string* kwargs_why, std::string* effor
|
||||
if (!l.default_reasoning_effort.empty()) render(l, effort_why);
|
||||
}
|
||||
|
||||
std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
lim_.reasoning_efforts.clear();
|
||||
if (!deps_.chat) return {};
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
auto takes = [&](const std::string& effort) {
|
||||
std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1)";
|
||||
if (!effort.empty()) body += R"(,"reasoning_effort":)" + json(effort).dump();
|
||||
body += "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
return parse_chat_request(body, odeps_, l, &r, &e) >= 0;
|
||||
};
|
||||
/* A render that fails with no effort at all says nothing about efforts, and one that takes a
|
||||
* word no ladder has takes every word. */
|
||||
if (!takes("") || takes("radiance-probe-not-a-level")) return {};
|
||||
std::vector<std::string> set;
|
||||
for (const char* w : { "low", "medium", "high", "xhigh", "max" })
|
||||
if (takes(w)) set.push_back(w);
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
}
|
||||
|
||||
std::string Server::check_reasoning_effort_map() const {
|
||||
if (!deps_.chat) return std::string();
|
||||
OaiLimits l = lim_;
|
||||
l.default_template_kwargs.clear();
|
||||
l.default_reasoning_effort.clear();
|
||||
l.reasoning_effort_map.clear();
|
||||
l.probe = true;
|
||||
for (const auto& [from, to] : lim_.reasoning_effort_map) {
|
||||
const std::string body = R"({"messages":[{"role":"user","content":"Hello"}],"max_tokens":1,)"
|
||||
R"("reasoning_effort":)" + json(to).dump() + "}";
|
||||
OaiRequest r;
|
||||
ApiError e;
|
||||
if (parse_chat_request(body, odeps_, l, &r, &e) < 0)
|
||||
return from + "=" + to + ": the chat template refuses '" + to + "': " + e.message;
|
||||
}
|
||||
return std::string();
|
||||
}
|
||||
|
||||
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,)"
|
||||
@@ -330,6 +380,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
*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;
|
||||
@@ -338,7 +389,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;
|
||||
@@ -429,8 +482,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);
|
||||
@@ -644,17 +713,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;
|
||||
|
||||
@@ -85,6 +85,8 @@ struct ServerOptions {
|
||||
bool default_dry_breakers_set = false;
|
||||
/* The deployment's chat template variables and reply format. See OaiLimits. */
|
||||
std::map<std::string, std::string> default_template_kwargs;
|
||||
/* --reasoning-effort-map. See OaiLimits::reasoning_effort_map. */
|
||||
std::map<std::string, std::string> reasoning_effort_map;
|
||||
std::string reasoning_format = "auto";
|
||||
bool allow_image = false;
|
||||
bool allow_video = false;
|
||||
@@ -148,6 +150,15 @@ public:
|
||||
* 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;
|
||||
/* THE EFFORTS THE CHAT TEMPLATE TAKES, found by parsing a one-message chat with each word this
|
||||
* server knows of (low, medium, high, xhigh, max) the way a request would send it, with no
|
||||
* deployment defaults. A template that takes a word nobody uses takes any word, and the answer
|
||||
* is empty. Kept for the refusal of a word outside the set and for /server_info; called once,
|
||||
* before run(). */
|
||||
std::vector<std::string> probe_reasoning_efforts();
|
||||
/* --reasoning-effort-map's targets, each rendered as a request's effort would be. Empty when
|
||||
* the template takes every one; otherwise the first refusal, naming the target. */
|
||||
std::string check_reasoning_effort_map() const;
|
||||
void stop();
|
||||
int port() const { return transport_.port(); } /* 0 until run() is accepting */
|
||||
|
||||
|
||||
+1
-1
@@ -198,7 +198,7 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt
|
||||
try {
|
||||
p = common_chat_templates_apply(impl_->tmpls.get(), in);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
if (!opt.quiet) RAD_ERR("chat: template refused the request: %s", e.what());
|
||||
out->error = e.what();
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ struct ChatOptions {
|
||||
bool add_bos = false;
|
||||
bool add_eos = false;
|
||||
std::map<std::string, std::string> template_kwargs;
|
||||
bool quiet = false; /* a refusal is not logged: a startup probe */
|
||||
};
|
||||
|
||||
/* Everything the scheduler and the sampler need for one request, produced in one pass. */
|
||||
|
||||
+32
-8
@@ -577,6 +577,13 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
const ojson& tools = req.tools ? *req.tools : none;
|
||||
const bool has_tools = f.has_tools() && tools.is_array() && !tools.empty();
|
||||
const bool has_rf = req.json_schema && req.json_schema->is_object() && !req.json_schema->empty();
|
||||
if (req.require_call && (has_rf || !has_tools)) {
|
||||
if (why)
|
||||
*why = has_rf ? "a required tool call and a response format cannot both be the "
|
||||
"whole reply"
|
||||
: "a tool call is required, but there are no tools this format can call";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!has_rf && !(has_tools && !f.triggers.empty())) return RAD_OK;
|
||||
|
||||
const std::string opener = f.call_open.empty() ? f.name_prefix : f.call_open;
|
||||
@@ -598,12 +605,9 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.resolve_refs(schema);
|
||||
}
|
||||
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
/* A grammar that is the whole reply starts where the generation prompt does, so the
|
||||
* prompt's assistant prefix and the reasoning block come first. */
|
||||
auto whole_reply = [&]() {
|
||||
std::string gp = req.generation_prompt;
|
||||
if (f.has_reasoning() && !f.reasoning_open.empty()) {
|
||||
const size_t at = gp.find(f.reasoning_open);
|
||||
@@ -612,6 +616,15 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
std::vector<G> root{ gp.empty() ? eps() : lit(gp), space() };
|
||||
if (f.has_reasoning() && req.extract_reasoning) root.push_back(reasoning_expr(f, breaks));
|
||||
root.push_back(space());
|
||||
return root;
|
||||
};
|
||||
if (has_rf) {
|
||||
/* The whole reply: what follows the generation prompt, the reasoning block, and
|
||||
* the document, fenced or not. */
|
||||
b.add_rule("response-format", b.add_schema("response-format-schema",
|
||||
*req.json_schema));
|
||||
add_json_rules(b);
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(alt({ seq({ lit("```json"), space(), rule_ref("response-format"), space(),
|
||||
lit("```") }),
|
||||
rule_ref("response-format") }));
|
||||
@@ -630,6 +643,7 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
continue;
|
||||
const auto& fn = tool.at("function");
|
||||
const std::string name = fn.at("name");
|
||||
if (!req.only_tool.empty() && name != req.only_tool) continue;
|
||||
auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object();
|
||||
const auto properties = params.contains("properties") ? params.at("properties")
|
||||
: ojson::object();
|
||||
@@ -687,6 +701,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
b.add_rule(rule_name("tool-" + name), render(func));
|
||||
choices.push_back(rule_ref(rule_name("tool-" + name)));
|
||||
}
|
||||
if (choices.empty() && !req.only_tool.empty())
|
||||
throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call");
|
||||
if (typed) add_json_rules(b);
|
||||
if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix }));
|
||||
|
||||
@@ -704,13 +720,21 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat
|
||||
: seq({ lit(""), space(), choice, space(), lit("") });
|
||||
}
|
||||
b.add_rule("tool-call", render(calls));
|
||||
b.add_rule("root", "tool-call");
|
||||
if (req.require_call) {
|
||||
/* The calls and nothing after them: a complete grammar admits only the end of
|
||||
* the turn, so the reply stops at the last call's closer. */
|
||||
std::vector<G> root = whole_reply();
|
||||
root.push_back(rule_ref("tool-call"));
|
||||
b.add_rule("root", render(seq(std::move(root))));
|
||||
} else {
|
||||
b.add_rule("root", "tool-call");
|
||||
}
|
||||
});
|
||||
} catch (const std::exception& e) {
|
||||
if (why) *why = e.what();
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
out->lazy = !has_rf;
|
||||
out->lazy = !has_rf && !req.require_call;
|
||||
if (out->lazy) out->trigger_words = f.triggers;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
+10
-3
@@ -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:
|
||||
@@ -145,14 +146,20 @@ std::string chat_format_describe(const ChatFormat& f);
|
||||
* The GBNF that constrains a reply to the format, generated from the description. For a tool
|
||||
* request it is LAZY: the reply is free until one of `triggers` appears, and from there the
|
||||
* grammar admits the call syntax with each argument constrained by its schema. For a response
|
||||
* format it is the whole reply. Rule names and structure follow the vendored generator so the
|
||||
* two produce the same grammar for a template-analysed format. */
|
||||
* format, and for a request that requires a call, it is the whole reply. Rule names and structure
|
||||
* follow the vendored generator so the two produce the same grammar for a template-analysed
|
||||
* format. */
|
||||
struct ChatGrammarRequest {
|
||||
const nlohmann::ordered_json* tools = nullptr; /* the request's tools, or null */
|
||||
const nlohmann::ordered_json* json_schema = nullptr; /* a response format's schema, or null */
|
||||
std::string generation_prompt;
|
||||
bool parallel_tool_calls = true;
|
||||
bool extract_reasoning = true; /* reasoning_format != "none" */
|
||||
/* tool_choice "required" or a named function: the grammar is the whole reply rather than lazy,
|
||||
* the reasoning block and then the calls with nothing after them, and `only_tool` (when set)
|
||||
* narrows the calls to that one function. */
|
||||
bool require_call = false;
|
||||
std::string only_tool;
|
||||
};
|
||||
|
||||
struct ChatGrammar {
|
||||
|
||||
+334
-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,7 @@ 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 {
|
||||
@@ -740,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;
|
||||
@@ -919,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;
|
||||
|
||||
@@ -1105,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));
|
||||
@@ -1120,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;
|
||||
@@ -1161,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) {
|
||||
@@ -1189,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();
|
||||
@@ -1222,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();
|
||||
@@ -1232,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();
|
||||
@@ -1275,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;
|
||||
}
|
||||
|
||||
@@ -1291,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:
|
||||
@@ -1422,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;
|
||||
@@ -1438,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;
|
||||
}
|
||||
|
||||
@@ -1518,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:
|
||||
@@ -1673,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;
|
||||
}
|
||||
}
|
||||
@@ -1697,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
|
||||
@@ -1733,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:
|
||||
@@ -1757,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();
|
||||
@@ -1793,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;
|
||||
}
|
||||
@@ -1809,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;
|
||||
}
|
||||
|
||||
|
||||
+14
-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. */
|
||||
@@ -179,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;
|
||||
|
||||
+53
-20
@@ -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;
|
||||
}
|
||||
@@ -1568,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
|
||||
@@ -1593,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) {
|
||||
@@ -1613,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 */
|
||||
};
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# q38-27b-quark-mxfp4-df2.recipe -- AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter.
|
||||
#
|
||||
# rad-convert <amd/Qwen3.8-27B-Quark-AWQ-MXFP4> --draft-model <z-lab/Qwen3.8-27B-DFlash2> \
|
||||
# --recipe q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
|
||||
#
|
||||
# Quark's MXFP4 linears are read as `fp4_e2m1*e8m0[1x32]`, byte for byte, so no rule names them:
|
||||
# the trunk is served at the 4-bit weights Quark shipped, against E4M3 activations. The checkpoint
|
||||
# is served by the family's quantised plugin (qwen35_fp8). The delta net's a/b projection is
|
||||
# declared bf16, and every MXFP4 value is exact in bf16, so `cast` keeps Quark's values that way.
|
||||
# The rest is as in q38-27b-fp8-df2.recipe: the head at block fp8, the drafter's linears at block
|
||||
# fp8, and its 2-bit copy of the target's head.
|
||||
|
||||
blk.*.ssm_ab.weight cast dtype=bf16
|
||||
|
||||
output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
|
||||
dflash.fc.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_q.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_k.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_v.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.attn_output.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_gate_up.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
dflash.blk.*.ffn_down.weight rtn codes=fp8_e4m3 block=128x128 scale=bf16
|
||||
@@ -0,0 +1,38 @@
|
||||
# qwen4exp-autoround-i8-hc8m.recipe -- a Qwen3.8-Flash-Next released as AutoRound int4
|
||||
# (`auto_round:auto_gptq`, symmetric, group 128), such as
|
||||
# ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound, arranged as the production container is
|
||||
# around its experts.
|
||||
#
|
||||
# rad-convert <AutoRound checkpoint> --recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe \
|
||||
# -o swift-autoround.rad
|
||||
#
|
||||
# The routed experts are named by no rule: rad-convert imports the release's int4 codes and group
|
||||
# scales as `i4*bf16[1x128]` (the scales rounded from f16 to bf16), served on the four-bit expert
|
||||
# GEMM. The release ships its block linears in int4 as well, which the trunk's W8A8 GEMMs do not
|
||||
# read, so they are made int8 from the int4 values the release holds -- a 128 of K each, as their
|
||||
# groups are. Everything the release keeps in bf16 is quantised as qwen4exp-w4nl64-i8-hc8m.recipe
|
||||
# quantises it, the MTP layer's experts rounded to the experts' own format.
|
||||
|
||||
# The MTP layer's experts, bf16 in the release (blk.48 is the MTP layer).
|
||||
blk.48.ffn_*_exps.*.weight rtn codes=i4 group=128 scale=bf16
|
||||
|
||||
# The connections' mixing matrices and the MTP head's fc matrices, as in production.
|
||||
*_hc_down.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
*_hc_up.weight rtn codes=fp8_e4m3 group=80 scale=f32
|
||||
mtp.fc_hidden.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
mtp.fc_embedding.weight rtn codes=fp8_e4m3 group=128 scale=f32
|
||||
|
||||
# The trunk's block linears as int8, a scale per 128 columns searched for least error.
|
||||
blk.*.attn_qg.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_k.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_v.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.attn_output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_inz.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ssm_out.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
|
||||
|
||||
# The n-gram table at one fixed E4M3 scale, and the MTP head's 2-bit draft head.
|
||||
blk.*.ple_ngram.weight rtn codes=fp8_e4m3 block=*x* scale=bf16 rule=fixed scale_value=1.99317932128906e-4
|
||||
mtp.draft_head.weight rtn codes=u2 zero=u8 group=128 scale=f16
|
||||
@@ -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
|
||||
@@ -0,0 +1,12 @@
|
||||
# Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk (4-bit weights, E4M3 activations) and its DFlash2
|
||||
# block-diffusion drafter merged into the container; the speculation depth is the drafter's own
|
||||
# operating point.
|
||||
name: radiance-qwen3.8-27b-mxfp4
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-qwen3.8-27b-mxfp4
|
||||
command: >
|
||||
--model /models/qwen3.8-27b-mxfp4.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 2 --max-num-seqs 32 --max-model-len 200000 --kv-cache-dtype fp8
|
||||
@@ -28,11 +28,10 @@ Window values are counter ratios with the definitions of the since-start gauges:
|
||||
| prompt from attention cache | `attn_cached_tokens` / `prompt_tokens` | `vllm:gpu_prefix_cache_hit_rate` |
|
||||
| prompt from linear checkpoint | `linear_cached_tokens` / (`linear_cached_tokens` + `prefill_tokens`) | `radiance:linear_prefix_cache_hit_rate` |
|
||||
| draft acceptance | `draft_accepted` / `draft_tokens` | `radiance:draft_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_reached`(j+1) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
| conditional acceptance at j | `draft_position_accepted`(j) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
|
||||
|
||||
Position j+1 is evaluated only when j was accepted, so its reach counts j's acceptances. The last
|
||||
position's acceptances are the total accepted minus every later reach. Draft blocks per decode step is
|
||||
the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
Draft blocks per decode step is the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
|
||||
The adaptive draft window and verifies by draft depth have data only under `--draft-window adaptive`.
|
||||
|
||||
Prometheus extrapolates `rate()` inside the window and VictoriaMetrics does not, so short windows at
|
||||
the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's time
|
||||
|
||||
+143
-33
@@ -1252,7 +1252,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well. Position j+1 is reached only when j was accepted, so this is reached(j+1) / reached(j); the last position is the total accepted minus every later reach. A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"description": "In the window: of the verifies that reached position j, the fraction that took j as well, accepted(j) / reached(j). A late position that collapses while the pooled rate looks fine shows here first.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
@@ -1265,7 +1265,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 0",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
@@ -1276,7 +1276,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 1",
|
||||
"refId": "B",
|
||||
"range": true,
|
||||
@@ -1287,7 +1287,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 2",
|
||||
"refId": "C",
|
||||
"range": true,
|
||||
@@ -1298,7 +1298,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 3",
|
||||
"refId": "D",
|
||||
"range": true,
|
||||
@@ -1309,7 +1309,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 4",
|
||||
"refId": "E",
|
||||
"range": true,
|
||||
@@ -1320,7 +1320,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 5",
|
||||
"refId": "F",
|
||||
"range": true,
|
||||
@@ -1331,7 +1331,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 6",
|
||||
"refId": "G",
|
||||
"range": true,
|
||||
@@ -1342,7 +1342,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 7",
|
||||
"refId": "H",
|
||||
"range": true,
|
||||
@@ -1353,7 +1353,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 8",
|
||||
"refId": "I",
|
||||
"range": true,
|
||||
@@ -1364,7 +1364,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 9",
|
||||
"refId": "J",
|
||||
"range": true,
|
||||
@@ -1375,7 +1375,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 10",
|
||||
"refId": "K",
|
||||
"range": true,
|
||||
@@ -1386,7 +1386,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 11",
|
||||
"refId": "L",
|
||||
"range": true,
|
||||
@@ -1397,7 +1397,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 12",
|
||||
"refId": "M",
|
||||
"range": true,
|
||||
@@ -1408,7 +1408,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 13",
|
||||
"refId": "N",
|
||||
"range": true,
|
||||
@@ -1419,7 +1419,7 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 14",
|
||||
"refId": "O",
|
||||
"range": true,
|
||||
@@ -1430,8 +1430,8 @@
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "(sum(rate(radiance:draft_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])) - sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position!=\"0\"}[$__rate_interval]))) / min(sum by (position) (rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])))",
|
||||
"legendFormat": "last position",
|
||||
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval]))",
|
||||
"legendFormat": "position 15",
|
||||
"refId": "P",
|
||||
"range": true,
|
||||
"instant": false
|
||||
@@ -1743,6 +1743,116 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Adaptive draft window",
|
||||
"id": 42,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Mean draft window the adaptive policy gives the running sequences; a gap while none runs. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "max by (instance) (radiance:draft_depth_adaptive{instance=~\"$instance\", model_name=~\"$model_name\"}) > 0",
|
||||
"legendFormat": "{{instance}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 5,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "none",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "timeseries",
|
||||
"title": "Verifies by draft depth",
|
||||
"id": 43,
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"description": "Share of verifies by the number of drafts they carried, under the adaptive window. Only under --draft-window adaptive; no data otherwise.",
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 43
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "${datasource}"
|
||||
},
|
||||
"expr": "sum by (depth) (rate(radiance:draft_verify_depth_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval]))",
|
||||
"legendFormat": "depth {{depth}}",
|
||||
"refId": "A",
|
||||
"range": true,
|
||||
"instant": false
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit",
|
||||
"custom": {
|
||||
"lineWidth": 1,
|
||||
"fillOpacity": 40,
|
||||
"showPoints": "never",
|
||||
"stacking": {
|
||||
"mode": "percent",
|
||||
"group": "A"
|
||||
}
|
||||
}
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"legend": {
|
||||
"displayMode": "list",
|
||||
"placement": "bottom",
|
||||
"showLegend": true
|
||||
},
|
||||
"tooltip": {
|
||||
"mode": "multi",
|
||||
"sort": "desc"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "row",
|
||||
"title": "Scheduler",
|
||||
@@ -1753,7 +1863,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 43
|
||||
"y": 51
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1769,7 +1879,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1846,7 +1956,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1912,7 +2022,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 44
|
||||
"y": 52
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -1977,7 +2087,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 52
|
||||
"y": 60
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -1993,7 +2103,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2070,7 +2180,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2147,7 +2257,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 53
|
||||
"y": 61
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2221,7 +2331,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 61
|
||||
"y": 69
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2237,7 +2347,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 0,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2294,7 +2404,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 8,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2362,7 +2472,7 @@
|
||||
"h": 8,
|
||||
"w": 8,
|
||||
"x": 16,
|
||||
"y": 62
|
||||
"y": 70
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2447,7 +2557,7 @@
|
||||
"h": 1,
|
||||
"w": 24,
|
||||
"x": 0,
|
||||
"y": 70
|
||||
"y": 78
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -2463,7 +2573,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
@@ -2518,7 +2628,7 @@
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 71
|
||||
"y": 79
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
|
||||
@@ -123,6 +123,7 @@ the cards the engine runs on.
|
||||
| `flashnext-bf16.yaml` | `qwen3.8-flash-next-bf16.rad` | Qwen3.8-Flash-Next in bf16, streamed from the disk tier. A reference, not a production server |
|
||||
| `qwen3.6-35b-a3b.yaml` | `qwen3.6-35b-a3b-fp8.rad` | Qwen3.6-35B-A3B, FP8 |
|
||||
| `qwen3.8-27b-fp8.yaml` | `qwen3.8-27b-fp8.rad` | Qwen3.8-27B FP8 with its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-mxfp4.yaml` | `qwen3.8-27b-mxfp4.rad` | Qwen3.8-27B with AMD's Quark AWQ-MXFP4 trunk, its DFlash2 drafter and vision tower |
|
||||
| `qwen3.8-27b-bf16.yaml` | `qwen3.8-27b-bf16.rad` | Qwen3.8-27B in bf16 |
|
||||
| `minicpm5-2b.yaml` | `minicpm5-2b-fp8.rad` | MiniCPM5-2B FP8 with its DSpark drafter |
|
||||
| `minicpm5-2b-bf16.yaml` | `minicpm5-2b-bf16.rad` | MiniCPM5-2B in bf16 with its DSpark drafter |
|
||||
|
||||
+185
-70
@@ -191,8 +191,8 @@ code is built for every family's generic target besides, whatever is named here.
|
||||
## 2. Five things to know before you start
|
||||
|
||||
**1. A model is a checkpoint served as it stands, or a `.rad` container.** A checkpoint whose
|
||||
weights are bf16, f16, f32 or block-scaled fp8 is served at that precision straight from its
|
||||
directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a
|
||||
weights are bf16, f16, f32, block-scaled fp8 or Quark's MXFP4 is served at that precision straight
|
||||
from its directory. Anything that needs quantising is quantised once, by `rad-convert` and a recipe, into a
|
||||
container. A container holds each weight as the planes of its *encoding* — codes, scales, zero
|
||||
points, a rotation — in one canonical arrangement, plus the tokeniser, the chat template, the
|
||||
metadata, the recipe it was quantised with and optionally a draft head. No kernel library is named
|
||||
@@ -208,7 +208,7 @@ Three ship with the tree:
|
||||
|
||||
| library | |
|
||||
|---|---|
|
||||
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, P2P all-reduce, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
|
||||
| `libr4d` | the device library: AMD RDNA4 (`gfx12xx`). Paged and dense attention, gated delta net, all-reduce over P2P or a host-memory mailbox, skinny and tiled quantised GEMM, rotate-and-quantise fusions. Built when ROCm is present and the build targets a `gfx12` card |
|
||||
| `libref` | every op naively and generically. The last-resort fallback **and** the correctness oracle `rad-kbench` measures against |
|
||||
| `libavx` | the host library: the same vocabulary in hand-written x86 SIMD, dispatched by CPU feature at load. Serves every op placed on the host, the n-gram embedding's gather among them. Built on x86-64 |
|
||||
|
||||
@@ -311,6 +311,33 @@ rad-convert $SRC -o new.rad --recipe new.recipe --reuse old.rad
|
||||
The conversions of record live in `scripts/convfn.sh` and `scripts/convdspark.sh`, with their
|
||||
recipes in `data/recipes/`.
|
||||
|
||||
**A release someone else already quantised is read as it ships.** Two forms are imported weight
|
||||
by weight, so their quantised linears need no recipe rule:
|
||||
|
||||
| `quantization_config` | read as | |
|
||||
|---|---|---|
|
||||
| `quark`, MXFP4 weights (fp4, per_group 32, e8m0) | `fp4_e2m1*e8m0[1x32]` | byte for byte: the same codes and exponents. A checkpoint of this form is also served as it stands (§3.4) |
|
||||
| `auto-round` with `packing_format: auto_round:auto_gptq`, and `gptq` (v1) | `i4*bf16[1x128]` or `i8*bf16[1x128]` | the GPTQ-packed codes transposed and made signed, the f16 scales rounded to bf16. Symmetric, group 128 or a multiple of it (per channel included), no act-order. Convert-time only, because the scales are not served as shipped |
|
||||
|
||||
The width is read per tensor, so a release mixing int4 experts with int8 projections imports both.
|
||||
What an import cannot read — an asymmetric zero point, an act-order index, a group under 128 — is
|
||||
refused by name at the weight. The release's `quantization_config` names the tool, not a served
|
||||
form, so it is kept in the container as `imported_quantization_config.*`, and the model is served by
|
||||
its family's quantised plugin (`qwen35_fp8` for Qwen3.8-27B; `qwen4exp_fp8` for Flash-Next).
|
||||
|
||||
A weight the architecture declares in another form than the release holds still takes a rule: the
|
||||
recipe dequantises the import exactly and quantises from that. The two recipes of record:
|
||||
|
||||
```sh
|
||||
# AMD's Quark AWQ-MXFP4 Qwen3.8-27B with the DFlash2 drafter
|
||||
rad-convert ~/models/amd/Qwen3.8-27B-Quark-AWQ-MXFP4 --draft-model ~/models/z-lab/Qwen3.8-27B-DFlash2 \
|
||||
--recipe data/recipes/q38-27b-quark-mxfp4-df2.recipe -o q38-27b-quark-mxfp4-df2.rad
|
||||
|
||||
# An AutoRound int4 Qwen3.8-Flash-Next: its experts imported, its int4 projections made int8
|
||||
rad-convert ~/models/ukisai/Swift-1.5-Qwen3.8-Flash-Next-W4A16-AutoRound \
|
||||
--recipe data/recipes/qwen4exp-autoround-i8-hc8m.recipe -o swift-autoround.rad
|
||||
```
|
||||
|
||||
### 3.3 Look at what you built
|
||||
|
||||
```sh
|
||||
@@ -409,39 +436,52 @@ outright:
|
||||
radiance --model m.rad --vram-weights-mib 24000 --vram-kv-mib 6000
|
||||
```
|
||||
|
||||
or let the engine derive it from the card and tell it only the ratio:
|
||||
or leave both unset and let the engine derive it from the card. The non-expert weights come off
|
||||
the top of what is claimed. The rest — the `elastic` line of the startup receipt — is shared by
|
||||
the expert slab and the KV cache, and no flag divides it:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --expert-vs-cache-ratio 0.82
|
||||
```
|
||||
- **The cache lends** under `--placement auto` or `expert_tiered`, without `--deterministic`, on a
|
||||
device with virtual memory management. The experts keep on the card exactly what the pinned host
|
||||
pool (`--host-pool-mib`) cannot hold, plus one expert unit of packing slack; they have nowhere
|
||||
else to be. The cache takes everything else, up to what it could ever address
|
||||
(`--max-num-seqs` x `--max-model-len`), and every block no live request holds is lent back to the
|
||||
expert slab in place. The prefill staging region comes out of the cache's side.
|
||||
- **Without a lender** — `--deterministic`, a stated `--placement all_vram` or `layer_offload`, or
|
||||
no virtual memory management — a block the cache does not use would sit empty, so the experts
|
||||
come first and the cache keeps one `--max-model-len` sequence.
|
||||
|
||||
`--expert-vs-cache-ratio` is the **weights** share of what is claimed. 0.75 (the default) gives
|
||||
three quarters to weights and a quarter to KV.
|
||||
The cache never gets less than one `--max-model-len` sequence, and when both sides fit, both are
|
||||
whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
|
||||
off the card and gives the cache more.
|
||||
|
||||
**This flag decides whether multi-turn works, which is more than the split it names.** The KV side
|
||||
is not only concurrency: prefix caching holds a finished sequence's blocks so the next turn can
|
||||
reuse them. 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.
|
||||
**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
|
||||
whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
|
||||
token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
|
||||
`expert_tiered` with both pools derived, a KV pool that pages exactly the common token count and the
|
||||
difference in its weights pool, up to every one of its weights resident; the startup log names the
|
||||
rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
|
||||
under `--deterministic`, or on a device without virtual memory management, the bytes that rank
|
||||
would never page go to its experts all the same. A stated `--vram-kv-mib` or `--vram-weights-mib`
|
||||
is applied to every card unchanged, and a rank whose cache costs as much per token as the dearest
|
||||
rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
|
||||
keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
|
||||
allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
|
||||
and that rank's log says its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
|
||||
|
||||
Measured on Qwen3.8-Flash-Next at a 200K context, two ~184K-token sessions, byte-identical text:
|
||||
|
||||
| ratio | turn 1 | turn 2 | prefix hit |
|
||||
|---|---|---|---|
|
||||
| 0.87 | 207.4 s | 173.0 s | 0.0% |
|
||||
| 0.82 | 227.7 s | **3.0 s** | 99.0% |
|
||||
|
||||
Same model, same prompts. The only difference is whether the pool could hold both sessions. 57x on
|
||||
the second turn, paid for with ~10% on the cold first turn and ~1.4% of the decode step — experts
|
||||
lose 5% of the elastic pool and the MoE GEMM is residency-bound.
|
||||
|
||||
The cliff is sharp and it is worth knowing where: at this shape 0.84 is **not** enough (49.7% hit,
|
||||
one of the two sessions), and watching `kv_util` finds it — between 0.75 and 0.81 of the pool the
|
||||
hit rate falls from 80.7% to 49.4%.
|
||||
**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix
|
||||
caching holds a finished sequence's blocks so the next turn can reuse them. 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.
|
||||
Measured on Qwen3.8-Flash-Next at a 200K context with two ~184K-token sessions and byte-identical
|
||||
text, the second turn took 173.0 s at a 0.0% prefix hit with a pool that could not hold both
|
||||
sessions, and 3.0 s at 99.0% with one that could. The fall-off is sharp, and `kv_util` shows a
|
||||
pool approaching it.
|
||||
|
||||
To size it yourself: work out what a token of context costs across **all** paged groups for your
|
||||
model (the startup log prints this), multiply by the context you actually serve, multiply by the
|
||||
sessions you want live at once, and give the KV side at least that.
|
||||
sessions you want live at once, and compare that with the cache the receipt reports. The cache
|
||||
already has everything the experts can do without; a larger `--host-pool-mib` (RAM permitting) or
|
||||
`--kv-cache-dtype fp8` gives it more.
|
||||
|
||||
Worked, on Qwen3.8-Flash-Next: two paged groups share one token axis — `kv_attn` at 26.00 KiB and
|
||||
`kv_qsa_bkey` at 3.25 KiB per 4-token block — so a token of context costs **7.32 KiB**, and a
|
||||
@@ -544,16 +584,18 @@ run to pay for cache nobody is using.
|
||||
|
||||
What it leans on is `--gpu-headroom-mib`. That reserve is what the card keeps for allocations
|
||||
this engine does not make — chief among them a kernel's code object, which HIP loads on the
|
||||
kernel's *first launch*, not at startup. A deployment whose budget settles *below* its stated
|
||||
headroom has already spent it, and the slab growing into what is left collides with the first
|
||||
kernel that has never run: a draft head's, a sampler chain's, whatever the early requests did not
|
||||
reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in a
|
||||
kernel that is correct, on a server that had been serving fine.
|
||||
kernel's *first launch*, not at startup. A card with too little of it left collides with the
|
||||
first kernel that has never run: a draft head's, a sampler chain's, whatever the early requests
|
||||
did not reach. It fails its load and faults inside the HIP runtime, which arrives as a segfault in
|
||||
a kernel that is correct, on a server that had been serving fine.
|
||||
|
||||
Startup measures that shortfall and holds it back on top of the reserve, so a run that did not
|
||||
quite keep its headroom is safe rather than fatal — but it is costing you the VRAM twice. Raise
|
||||
`--gpu-headroom-mib` past the number startup names, so the budget resolver sees it and the expert
|
||||
plane is sized against it instead of trimmed afterwards.
|
||||
Startup checks what is left once everything is allocated (`card N settled at ... free`). Memory
|
||||
taken after the budget read the card — another process on it, such as a desktop, or a driver
|
||||
allocation — comes out of the headroom, and the line says how much. It warns only when the room
|
||||
left for first launches is under the 96 MiB the engine allows for its own, and then names the
|
||||
`--gpu-headroom-mib` value that clears it: what is left rises one for one with the flag, so that
|
||||
value is a fixed point. A larger headroom that lost part of itself to another process is reported
|
||||
on the INFO line and not warned.
|
||||
|
||||
What the engine itself allocates after the card is read is charged before the split, so it never
|
||||
comes out of the headroom: the step staging, the KV tiers' copy staging, and its hardware queues.
|
||||
@@ -564,8 +606,7 @@ holds at that price.
|
||||
### 4.4 Long context
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 \
|
||||
--expert-vs-cache-ratio 0.82 --max-num-seqs 8
|
||||
radiance --model m.rad --max-model-len 200000 --kv-cache-dtype fp8 --max-num-seqs 8
|
||||
```
|
||||
|
||||
`--max-model-len` does not reserve anything per request — it sets the worst case the pool is sized
|
||||
@@ -584,11 +625,10 @@ per sequence whether it is used or not:
|
||||
|
||||
- **Recurrent state.** On a hybrid model every sequence owns its delta-net state, and with
|
||||
speculation two copies of it. Qwen3.8-Flash-Next keeps 54 MiB a copy on each card, so 32
|
||||
sequences take 3.4 GiB of the cache share before a single token is cached. At
|
||||
`--expert-vs-cache-ratio 0.82` the attention cache then holds about 116K tokens, less than one
|
||||
200K request, and startup warns that a longer one would be refused; 0.78 brings it back, and the
|
||||
experts it moves off the card cost single-stream decode about 15%. The 27B in bf16 lands at
|
||||
117K the same way. The 27B in FP8 holds 2.8 full-length sessions at 32, the 35B-A3B ten.
|
||||
sequences take 3.4 GiB of the cache share before a single token is cached. The 27B in bf16,
|
||||
with no experts to give way, then holds about 117K tokens of attention cache, less than one 200K
|
||||
request, and startup warns that a longer one would be refused. The 27B in FP8 holds 2.8
|
||||
full-length sessions at 32, the 35B-A3B ten.
|
||||
- **Block tables.** The step batch's tables are carved for every sequence at the full context.
|
||||
They are charged to the VRAM budget (`step staging` in the startup receipt), so they come out of
|
||||
the cache share and not out of `--gpu-headroom-mib`.
|
||||
@@ -700,6 +740,42 @@ error that says so rather than being quietly ignored.
|
||||
|
||||
When you measure speculation, **measure step time, not tokens per second.**
|
||||
|
||||
A drafter with a sliding window over its own cache (DFlash2) keeps that cache outside the prefix
|
||||
cache, so a prefix hit leaves it with nothing to attend to for the cached part of the prompt, and
|
||||
it cannot draft until its window has slid past the hit. On the follow-up turn of a chat that is
|
||||
most of the reply. Such a hit is therefore ended one drafter window before the end of the prompt,
|
||||
at a checkpoint: the window is recomputed, which costs that much prefill, and the drafter drafts
|
||||
from the first token. The reply is the same either way. A hit whose nearest checkpoint below that
|
||||
point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
|
||||
the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
|
||||
|
||||
**One depth for every request is a compromise; `--draft-window adaptive` lets the text decide.**
|
||||
Acceptance depends on the text: code and JSON keep accepting deep into the window, prose and
|
||||
summaries fall off after a position or two. With the adaptive window, `--num-speculative-tokens` is
|
||||
the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --num-speculative-tokens 6 --draft-window adaptive
|
||||
```
|
||||
|
||||
A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen
|
||||
for the step, not for one sequence: each step's head depth is the one that maximises the tokens all
|
||||
its sequences are expected to emit over what such a step costs. The cost is measured as the server
|
||||
runs — the time of every decode step, by its depth and by how many sequences it carried — so there
|
||||
is nothing to enter; a depth not yet measured is priced from the nearest one that was. Under that
|
||||
depth each sequence stops at the first draft that would be emitted — it and every draft before it
|
||||
accepted — less than one time in ten, so a prose reply beside a code reply does not pay verify rows
|
||||
for drafts nobody takes. The depth moves only after eight steps and for a two-percent gain, because
|
||||
every new window is a new pass shape and a new recording. A new sequence starts from what the
|
||||
sequences before it finished on, each counted once.
|
||||
|
||||
The adaptive window is the serial draft head's policy. With a block drafter, with prompt lookup
|
||||
alone, or with speculation off the window stays fixed, and the server says so at startup. Prompt
|
||||
lookup proposals made when the head declines are counted in the acceptance metrics but do not move
|
||||
the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree
|
||||
with each other; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and
|
||||
`radiance:draft_verify_depth_total` (§6.3) show where the windows stand. The default is `fixed`.
|
||||
|
||||
### 4.7 Two cards
|
||||
|
||||
```sh
|
||||
@@ -732,13 +808,25 @@ the decode and verify steps — up to `--max-num-seqs` × (1 + `--num-speculativ
|
||||
prefill chunk, and a message that goes out on the tiered-int8 wire, runs the unfused chain, where
|
||||
the all-reduce's own size choice between one-shot and two-shot applies.
|
||||
|
||||
**The cards must reach each other's memory directly** (peer to peer, P2P). The all-reduce
|
||||
kernels push into the other card's memory. At launch radiance asks the driver, for every pair of
|
||||
the cards it will use, whether that works, and logs the answer. When some pair cannot, those
|
||||
kernels are not selected, and startup stops naming `device.p2p` instead of the first all-reduce
|
||||
faulting or hanging. Whether P2P works is decided by the platform: the IOMMU setting, the PCIe
|
||||
topology, and whether the cards sit behind a switch that allows peer traffic. The startup line
|
||||
names the pairs that failed.
|
||||
**Cards that cannot reach each other's memory still serve.** The all-reduce kernels normally push
|
||||
into the other card's memory directly (peer to peer, P2P). At launch radiance asks the driver,
|
||||
for every pair of the cards it will use, whether that works, and logs the answer. Whether it does
|
||||
is decided by the platform: the IOMMU setting, the PCIe topology, and whether the cards sit behind
|
||||
a switch that allows peer traffic. When some pair cannot, the same kernels run with their
|
||||
exchange buffers in pinned host memory instead: every card writes its share to host RAM over its
|
||||
own link and reads the others' back the same way, and no card touches another card's VRAM. The
|
||||
startup line names the pairs that failed, and the selection report names the `_host` rows that
|
||||
took the collectives. The results are the same bytes either way; the cost is a message crossing
|
||||
two links instead of one. On two R9700s on PCIe 4.0 that cost is within run-to-run noise for
|
||||
decode, at one stream and at four, and 2–10% on a 23.6K-token prefill, because there the peer
|
||||
link is no faster than the host link. A machine whose cards reach host memory over a narrower
|
||||
link than they reach each other pays more.
|
||||
|
||||
`--p2p` overrides the driver's answer. `off` takes the host-memory path even where the driver
|
||||
reports peer access, for a board where peer traffic is broken or slow while the driver still says
|
||||
it works. `on` takes the peer-to-peer kernels and stops at startup, naming the pairs, if the driver
|
||||
refuses any of them, so a deployment measured on P2P never quietly serves on host memory. `auto`,
|
||||
the default, trusts the driver.
|
||||
|
||||
### 4.8 Finished conversations: copied to host, VRAM given up on demand
|
||||
|
||||
@@ -763,18 +851,21 @@ radiance --model m.rad \
|
||||
--prefix-cache-disk-mib 65536 --prefix-cache-dir /var/cache/radiance
|
||||
```
|
||||
|
||||
- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. Part of
|
||||
it goes to linear-state snapshots on a hybrid model; startup says how many. Size it for the
|
||||
conversations you expect to come back: one that does not fit comes back from disk instead.
|
||||
- `--prefix-cache-host-mib N` — **this is the switch.** Without a size, nothing is copied. It holds
|
||||
attention blocks only; a hybrid model's linear-state snapshots are in host memory already, in the
|
||||
`--checkpoint-slots` store. Size it for the conversations you expect to come back: one that does
|
||||
not fit comes back from disk instead.
|
||||
- `--prefix-cache-disk-mib N` — the disk tier's size. Everything that reaches host memory is
|
||||
written here too, so it sees the same bytes the host tier does.
|
||||
written here too, snapshots included, so a full snapshot store detaches its least recently used
|
||||
snapshot instead of losing it.
|
||||
- `--prefix-cache-dir DIR` — where the disk tier lives. **Not `--weights-disk-tier`**, which is about
|
||||
*weights*. The disk tier holds conversation content unencrypted.
|
||||
- Recovering a 200K-token turn costs a copy over PCIe; recomputing it costs minutes.
|
||||
|
||||
On a hybrid model this includes the recurrent state, not just the attention blocks — restoring the
|
||||
On a hybrid model the recurrent state matters as much as the attention blocks — restoring the
|
||||
blocks alone leaves the session re-running every linear layer over its whole transcript, which
|
||||
every hit-rate counter reports as a hit. `/sessions` shows what is stored, where, and whether the
|
||||
every hit-rate counter reports as a hit. The snapshots never take VRAM: each is copied to host
|
||||
memory after the step that produced it and back before the step that resumes from it. `/sessions` shows what is stored, where, and whether the
|
||||
linear half is being served.
|
||||
|
||||
### 4.9 What a request that leaves a field out gets
|
||||
@@ -853,6 +944,24 @@ refuses is a warning at startup: requests that send their own effort still work.
|
||||
radiance --model m.rad --reasoning-effort medium
|
||||
```
|
||||
|
||||
**The template's set is probed at startup** by rendering each of `low`, `medium`, `high`, `xhigh`
|
||||
and `max`, and startup names the ones it takes. `/server_info` publishes them as
|
||||
`capabilities.reasoning_efforts` (with `none` and `minimal`, which are the server's own; `null`
|
||||
when the template takes any word). A request outside the set gets a 400 with `param:
|
||||
"reasoning_effort"`, `code: "unsupported_value"` and the set in `error.supported`, rather than the
|
||||
template's traceback.
|
||||
|
||||
**`--reasoning-effort-map FROM=TO,...`** rewrites a request's effort before the template sees it,
|
||||
for a client that always sends a word of OpenAI's ladder. Qwen3.8 has no `high`, so:
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --reasoning-effort-map high=xhigh
|
||||
```
|
||||
|
||||
It applies to both spellings (`reasoning_effort` and `chat_template_kwargs.reasoning_effort`), and
|
||||
before `none` and `minimal` are read, so `minimal=low` keeps thinking on. A `TO` the template
|
||||
refuses stops startup.
|
||||
|
||||
**`--thinking-token-budget N`** caps the reasoning instead of its depth. At N tokens inside the
|
||||
reasoning block the block is closed, by masking the next position to its end token
|
||||
(`</think>`), and the answer follows. This makes a client's `max_tokens` buy an answer, where
|
||||
@@ -885,13 +994,13 @@ one line naming each one the command line moved.
|
||||
| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
|
||||
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
|
||||
| `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
|
||||
| `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
|
||||
|
||||
**Memory**
|
||||
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
|
||||
| `--expert-vs-cache-ratio R` | 0.75 | weights share of what is claimed |
|
||||
| `--vram-weights-mib N` | derive | the resident weight slab |
|
||||
| `--vram-kv-mib N` | derive | the paged KV pool |
|
||||
| `--kv-cache-dtype T` | bf16 | `bf16` or `fp8` |
|
||||
@@ -915,7 +1024,7 @@ one line naming each one the command line moved.
|
||||
| `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` |
|
||||
| `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine |
|
||||
| `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens |
|
||||
| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. A cap, not a charge: slots are backed as they are taken, so unused ones cost no VRAM. Raising it trades addressable context, since the range comes out of the KV pool |
|
||||
| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. With a disk tier a full store detaches its least recently used snapshot to disk instead of losing it |
|
||||
| `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` |
|
||||
| `--no-prefix-cache` | — | disable prefix caching |
|
||||
|
||||
@@ -926,12 +1035,14 @@ one line naming each one the command line moved.
|
||||
| `--tp N` | 1 | tensor-parallel ranks |
|
||||
| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
|
||||
| `--tp-wire-min-kb N` | 128 | smallest all-reduce the lossy wire is used for |
|
||||
| `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
|
||||
|
||||
**Speculation**
|
||||
|
||||
| flag | default | |
|
||||
|---|---|---|
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables |
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
|
||||
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
|
||||
| `--draft-model PATH` | — | **not implemented** — merge at convert time |
|
||||
|
||||
**Server**
|
||||
@@ -972,6 +1083,7 @@ that names the field wins.
|
||||
| `--max-stop-strings N`, `--max-stop-bytes N` | 64, 4096 | how many stop strings a request may send, and how long each may be |
|
||||
| `--chat-template-kwargs JSON` | — | variables for the chat template on every chat request; a JSON object or `@FILE`, repeatable |
|
||||
| `--reasoning-effort S` | template's own | default `reasoning_effort` for chat |
|
||||
| `--reasoning-effort-map MAP` | — | `FROM=TO,...`: a request's `reasoning_effort` rewritten before the template sees it; `TO` is checked at startup |
|
||||
| `--thinking-token-budget N` | none | default `thinking_token_budget` for chat: the reasoning block is closed at N tokens |
|
||||
| `--reasoning-format MODE` | auto | `auto` returns reasoning as `reasoning_content`; `none` leaves it inline in `content` |
|
||||
|
||||
@@ -1214,9 +1326,9 @@ curl -s http://localhost:8000/detokenize -H 'Content-Type: application/json' \
|
||||
| `ignore_eos` | generate to `max_tokens` whatever the model emits |
|
||||
| `stream`, `stream_options.include_usage` | |
|
||||
| `logprobs`, `top_logprobs` | **not implemented** — refused, not returned as nulls. `/server_info` reports `logprobs: false` |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
|
||||
| `add_generation_prompt`, `chat_template_kwargs` | chat only |
|
||||
| `reasoning_effort`, `enable_thinking` | chat only |
|
||||
| `reasoning_effort`, `enable_thinking` | chat only. The levels are the template's (`capabilities.reasoning_efforts` on `/server_info`); `none` and `minimal` turn thinking off |
|
||||
| `thinking_token_budget`, `thinking_budget` | chat only. ≥ 0: the reasoning tokens after which the block is closed — see §5.2. Default `--thinking-token-budget`, else none |
|
||||
| `preserve_thinking` | chat only. The chat template variable of that name, as llama.cpp maps it; Qwen3.6 and later keep earlier turns' reasoning in the prompt with it |
|
||||
| `response_format` | chat only. Mutually exclusive with `grammar` |
|
||||
@@ -1376,8 +1488,9 @@ the startup log too — but a startup log is on a machine, in a file, from a pro
|
||||
been restarted since.
|
||||
|
||||
Its `request_defaults` object says what a request that leaves a field out is served with: every
|
||||
sampler field, `max_tokens`, `reasoning_effort`, `chat_template_kwargs` and `reasoning_format`,
|
||||
under the request's own spelling of each. `server.default_max_tokens` is `null` for `auto`, and
|
||||
sampler field, `max_tokens`, `reasoning_effort`, `reasoning_effort_map`, `chat_template_kwargs` and
|
||||
`reasoning_format`, under the request's own spelling of each. `capabilities.reasoning_efforts`
|
||||
lists the efforts the chat template takes, or is `null` when it takes any. `server.default_max_tokens` is `null` for `auto`, and
|
||||
`server.max_tokens_cap` is `null` when there is none.
|
||||
|
||||
### 6.3 Metrics
|
||||
@@ -1399,8 +1512,10 @@ under the request's own spelling of each. `server.default_max_tokens` is `null`
|
||||
| `decode_tokens_total`, `prefill_tokens_total` | |
|
||||
| `decode_tokens_per_second`, `prefill_tokens_per_second` | |
|
||||
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
|
||||
| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position, since start |
|
||||
| `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
|
||||
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
|
||||
| `decode_rows_unspeculated_total` | rows that never drafted at all |
|
||||
| `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
|
||||
| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
|
||||
| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
|
||||
| `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | |
|
||||
@@ -1480,15 +1595,15 @@ released until it does.
|
||||
| What you see | What it means | What to do |
|
||||
|---|---|---|
|
||||
| `N declared op(s) resolve to libref` and the engine exits | No kernel library covers those ops on this card. Serving from the reference implementation would be orders of magnitude slow with nothing to say so | Install a library that covers them, or accept the cost with `--debug-accept-reference-kernels`. The named ops are exactly what a new library must implement |
|
||||
| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: **raise** `--expert-vs-cache-ratio`, lower `--max-model-len` or `--max-num-seqs`, or add `--host-pool-mib`. If a **KV group** did not fit: lower the ratio, or `--kv-cache-dtype fp8`. The plan report names which, by class, with the shortfall |
|
||||
| `did not fit` at load, naming a weight class or a KV group | The split left one side too little. A routed expert cannot be served from the file tier, so it has nowhere else to go | If **weights** did not fit: add or raise `--host-pool-mib`, or lower `--max-model-len` or `--max-num-seqs`. If a **KV group** did not fit: `--kv-cache-dtype fp8`, or a larger `--host-pool-mib` (RAM permitting), which takes experts off the card. The plan report names which, by class, with the shortfall |
|
||||
| `chat is 501` in the startup line | The container carries no chat template | Re-convert with `--tokenizer`, and check that a `chat_template.jinja` sits beside `tokenizer_config.json` in the checkpoint. Meanwhile use `/v1/completions` |
|
||||
| `does not read '<weight>' encoded <encoding>` at startup | No loaded kernel takes that weight's encoding for the op that reads it | Convert with a recipe that writes an encoding a loaded kernel reads, or load the library that reads it |
|
||||
| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | Lower `--expert-vs-cache-ratio` (more to KV), or `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 |
|
||||
| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card that never met `--gpu-headroom-mib` — see §4.3. Raise the headroom past the shortfall startup names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
|
||||
| Prefix hit rate 0% and every turn re-prefills | The KV pool cannot hold the live sessions, so the cache evicts what the next turn wanted | The cache already has everything the experts can do without: a larger `--host-pool-mib` (RAM permitting), `--kv-cache-dtype fp8`, or fewer/shorter sessions. See §4.3 |
|
||||
| The server dies with no log line, on a request it had been serving fine | A kernel whose code object had never been loaded could not be: the card has no room left. HIP faults inside the launch rather than returning an error, so there is nothing to print | A card left with too little room for a first launch — see §4.3. Set `--gpu-headroom-mib` to the value the startup warning names. `coredumpctl info` names the kernel; `AMD_LOG_LEVEL=1` prints `HSA_STATUS_ERROR_OUT_OF_RESOURCES` just above the fault |
|
||||
| KV in VRAM stays high with one session and nothing moves | The idle tiers are **off** — they are sized, and with no size nothing is copied | Pass `--prefix-cache-host-mib N` |
|
||||
| `out of memory` / `the carve reserved N of address space and the card would not back it` | Something else is holding VRAM | Check with `rocm-smi`; stop the other process. The budget is stated before allocation, so the log says what it asked for |
|
||||
| `pool allocation refused` with `backing allocation of … refused` on the second card, after the first card's pools succeeded | The VRAM budget is measured before any rank allocates. A card that refuses its weights pool lost that memory to another process in between (the line below the refusal says how much is free now). A refused `host_pool` is pinned memory: **every rank pins its own `--host-pool-mib`**, so `--tp 2` pins it twice, and the amdgpu driver caps pinned memory system-wide at `ttm.pages_limit`, half of RAM by default | Stop the other process (`rocm-smi --showpids`). For the host pool, keep `--tp` × `--host-pool-mib` under the cap the refusal names, or raise it with the kernel parameter `ttm.pages_limit` |
|
||||
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, and every multi-rank kernel requires it. Report the kernel version, the IOMMU mode and the refusal line |
|
||||
| `host_pool: backing allocation of … refused: rad_dev_alloc(…): locking piece K of N`, and `failed to pin userptr` in `journalctl -k` | The IOMMU would not DMA-map one piece of the pinned host pool. Pinned host memory is locked in pieces of at most 1 GiB because an Intel VT-d host in scalable mode was seen to refuse any single pin above about 2.5 GiB; a piece failing means this machine refuses smaller pins still, or a total its IOMMU will not map | Keep IOMMU translation on: `iommu=pt` lets every pin through but on that host also removed peer access between the cards, which moves every all-reduce onto the slower host-memory path. Report the kernel version, the IOMMU mode and the refusal line |
|
||||
| `--draft-model is not implemented` | This engine loads its drafter from the container | `rad-convert --draft-model DIR` at conversion time |
|
||||
| `context_length_exceeded` on a request | The **prompt alone** does not fit the context. `max_tokens` is clamped rather than refused, so this fires only when there is no room left to generate at all | Shorten the prompt by the number of tokens the message names, or raise `--max-model-len` if the model allows it |
|
||||
| `unknown option '--foo'` and the engine exits | Deliberate. A typo in a budget flag is the difference between the plan you asked for and one the planner invented | Check `radiance --help` |
|
||||
|
||||
+1
-1
@@ -232,7 +232,7 @@ not.
|
||||
| `ple_gate` | | device | host |
|
||||
| `qk_norm_rope` | | - | host |
|
||||
| `qk_norm_rope_gate` | | device | - |
|
||||
| `qsa_block_key` | | device | - |
|
||||
| `qsa_block_key` | | device | host |
|
||||
| `qsa_score` | | device | - |
|
||||
| `qsa_select` | | device | - |
|
||||
| `qsa_tail_store` | | device | - |
|
||||
|
||||
+4
-5
@@ -66,9 +66,8 @@ LDS lookup a byte), more protected bf16 experts (+4% bytes for 7% less error), a
|
||||
(13% less error energy for +13-18% on the expert GEMMs).
|
||||
|
||||
**Further quality levers**, in order: five bits on both projections of layers
|
||||
16-31 (the same +8% as the down projections, ~0.066 expected); fewer layers at five bits for a
|
||||
smaller prefill cost; and `--expert-vs-cache-ratio`, which buys the residency back with KV
|
||||
capacity. The formats, the kernel and a layer's own choice of form are all in the tree.
|
||||
16-31 (the same +8% as the down projections, ~0.066 expected), and fewer layers at five bits for a
|
||||
smaller prefill cost. The formats, the kernel and a layer's own choice of form are all in the tree.
|
||||
|
||||
## The stored plane
|
||||
|
||||
@@ -244,8 +243,8 @@ its Hessians in the model's own domain; a rotated recipe's GPTQ reads them rotat
|
||||
Whole experts per rank, which a calibration run wants anyway. A step reads about 100 GiB a rank from
|
||||
the drive and grows only slowly with what it carries -- 50 s at ~32K tokens, 59 s at ~55K -- so
|
||||
drive it with large prefill steps: `--max-num-batched-tokens 65536 --max-num-seqs 64`, about 96
|
||||
requests in flight, and `--expert-vs-cache-ratio 0.5` so the cache share holds 64 sequences'
|
||||
recurrent state. That records ~930 tokens a second, ten million tokens in three hours.
|
||||
requests in flight, with a KV pool that holds 64 sequences' recurrent state (`--vram-kv-mib`
|
||||
states it outright). That records ~930 tokens a second, ten million tokens in three hours.
|
||||
|
||||
**The corpus is what the Hessian is of, so it has to look like the traffic.** A few thousand
|
||||
tokens of one repeated sentence gives a Gram whose energy sits in a handful of directions, and GPTQ
|
||||
|
||||
+38
-5
@@ -173,6 +173,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th
|
||||
| `softmax` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `silu` | `M` `n` `dtype` | `x` → `y` |
|
||||
| `fill` | `M`(range) `n` `dtype` `value`:f64/opt | → `y` |
|
||||
|
||||
`gelu` and `silu` are two ops with one schema, and `silu` carries a row of its own because a row
|
||||
names one op.
|
||||
@@ -217,6 +218,12 @@ it. Every other elementwise op keeps the strict same-shape rule.
|
||||
`sigmoid`, with a broadcast-capable `mul`, is what a gated shared expert needs
|
||||
(`ffn_gate_inp_shexp`). Without it the shared expert runs ungated, which is a different model.
|
||||
|
||||
`fill` has no input: `y = value` over the extent, `value` 0 when absent. It is the op a rank issues
|
||||
where it computes nothing and a reader downstream still expects a defined buffer -- an
|
||||
attention-zero rank's block (`docs/TP3.md`) is one `fill` of its output wire before the all-reduce.
|
||||
A wire shared across layers cannot be zeroed once a step, and a memset knows neither the row pitch
|
||||
nor the dtype; this does.
|
||||
|
||||
## Quantisation and rotation
|
||||
|
||||
| op | params | operands |
|
||||
@@ -364,8 +371,8 @@ that folds dequantisation into its epilogue still receives them.
|
||||
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
|
||||
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
|
||||
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` | `positions` → `cos_sin` |
|
||||
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` |
|
||||
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` |
|
||||
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
|
||||
|
||||
`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at
|
||||
@@ -479,6 +486,7 @@ and adding 0.0f is exact, so a block sum over 8 wave partials and over 32 are th
|
||||
| `router_topk` | `M`(range) `n_expert` `top_k` `norm` `dtype` | `logits` → `expert_ids`, `expert_w` |
|
||||
| `moe_scatter` | `M`(range) `n_expert` `top_k` `expert_base`/opt `protect`:str/opt | `expert_ids` → `sorted_tok`, `expert_offset`, `expert_count` |
|
||||
| `router_topk_scatter` | `M`(range) `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `logits` → `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count` |
|
||||
| `router_gemm_topk_scatter` | `M`(range) `K` `n_expert` `n_local`/opt `top_k` `norm` `dtype` `expert_base`/opt `protect`:str/opt | `a`, `b`w, `gate_b`w? → `logits`, `expert_ids`, `expert_w`, `sorted_tok`, `expert_offset`, `expert_count`, `gate`? |
|
||||
| `moe_gemm` | `M`(range) `N` `K` `n_expert` `top_k` `a_order` `dtype` | `a`, `w`wt, `sorted_tok`, `expert_offset` → `y` |
|
||||
| `moe_gather` | `M`(range) `n` `top_k` `dtype` `act`:str/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`? → `y` |
|
||||
| `row_topk` | `M`(range) `N` `R` `vocab_off`/opt `dtype` | `x` → `idx`, `val`, `pairs`? |
|
||||
@@ -531,6 +539,25 @@ sequences at depth 3 and top_k 10 is 320 slots — and a prefill chunk is past i
|
||||
where the pair is amortised over real work and a fusion would buy nothing. A caller past the bound
|
||||
gets a refusal, not a silent change of cost.
|
||||
|
||||
**`router_gemm_topk_scatter` puts the router's GEMM in front of that pair**, in the same launch:
|
||||
`gemm_nt` of `a` [M, K] against the router `b` [n_expert, K] into `logits`, then exactly
|
||||
`router_topk_scatter` over those logits. With `gate_b` [1, K] and `gate` [M, 1] present it is
|
||||
also the shared expert's one-column `gemm_nt` over the same `a`; the two come together or not at
|
||||
all. The selection needs every logit of a row, so it runs in the workgroup that finishes the GEMM
|
||||
last (an arrival counter, self-resetting, one an op instance: libr4d takes it in the row's `init`,
|
||||
so it is in the VRAM budget, and refuses a launch without one). It is byte-identical to the
|
||||
launches it stands in for: an element of the skinny bf16 GEMM depends only on its split-K count,
|
||||
which this op takes from the same law at the same N, and the selection and sort are the same code.
|
||||
Decode only, `M <= 64` -- past that the router is the tiled GEMM -- and bounded like the pair. The
|
||||
logits stay an output.
|
||||
|
||||
**The router GEMM inside it is NOTUNE.** It always takes the split the untuned law picks, which is
|
||||
what makes it byte-identical to the unfused GEMM as an untuned install runs it. A tune-cache entry
|
||||
for the unfused router's `gemm_nt` does not reach this op, so on a tuned install the two forms may
|
||||
differ in the last bit; no shipped configuration tunes these GEMMs. An architecture asks for this op
|
||||
wherever it declares the pair and issues the router and the pair itself where it does not resolve
|
||||
or a pass is past its rows.
|
||||
|
||||
`moe_scatter`'s output is what `rad_route_report` hands the heat engine. The histogram is read
|
||||
back asynchronously and consumed on the next step; nothing here blocks the compute stream
|
||||
(`spec.md` §5.5).
|
||||
@@ -1134,11 +1161,11 @@ stages of its sorting network when the runs are a power of two long and fill the
|
||||
over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that
|
||||
hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
## Sparse attention (QSA) — device-only
|
||||
## Sparse attention (QSA)
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt | `k`, `w`w, `page`?, `pos`? → `out` |
|
||||
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` |
|
||||
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
|
||||
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
|
||||
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
|
||||
@@ -1146,7 +1173,8 @@ hands it unsorted runs gets a wrong order, not a slow one.
|
||||
|
||||
Five ops decompose one thing: an indexer that scores blocks of key history against the query and
|
||||
hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five.
|
||||
schemas, and `arch/common/rad_qsa.h` issues all five. **`qsa_block_key` has a host kernel in libref
|
||||
and libavx** -- the oracle for libr4d's, YaRN included -- and the other four are **device-only**.
|
||||
|
||||
`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which
|
||||
is what the indexer's block scores are taken against.
|
||||
@@ -1155,6 +1183,11 @@ is what the indexer's block scores are taken against.
|
||||
out[b] = rope( rmsnorm( mean over j<ratio of k[b*ratio + j] ), at position pos0 + b*ratio )
|
||||
```
|
||||
|
||||
The rotation is `rope`'s NeoX ladder over the first `rotary_dim` lanes, with `rope`'s YaRN
|
||||
coefficients (`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude`) when given -- the
|
||||
attention's own rotary, so a compressed key and the keys it summarises are rotated alike. With
|
||||
YaRN, `scale` must be 1.
|
||||
|
||||
**`M` is BLOCKS and `k` is `ratio` times taller.** Every other op in this document has one output
|
||||
row per input row. A caller that sized `k` at the block count would have every block pool three
|
||||
rows of the next one — plausible numbers and a different model — so libr4d's entry point checks it.
|
||||
|
||||
+3
-1
@@ -103,7 +103,9 @@ op's parameters. `RAD_CEQ(RAD_FACT_P2P, 1)` (`device.p2p`) is how a kernel says
|
||||
another card's memory. On a machine where some pair of the ranks' cards cannot reach each other,
|
||||
such a kernel is not selected. The next row that does not need it takes the op. With no such row,
|
||||
startup stops and the selection table names the fact (`device.p2p == 1, have 0 -- this machine,
|
||||
measured at launch`). Every collective in libr4d carries it. A machine fact is in no geometry, so
|
||||
measured at launch`). Every collective in libr4d carries it, and each has a `_host` twin that
|
||||
requires `device.p2p == 0` and exchanges through pinned host memory, so exactly one of the pair
|
||||
matches any machine. A machine fact is in no geometry, so
|
||||
it changes no tuning key. A tool that selects without an engine has measured nothing, and such a
|
||||
kernel is not selected there either.
|
||||
|
||||
|
||||
+3
-3
@@ -534,19 +534,19 @@ deliberately disconnects clients from it, which is not the same promise.
|
||||
| | knobs |
|
||||
|---|---|
|
||||
| `mcserve.sh` | MiniCPM5-2B + DSpark drafter (`minicpm5-2b-dspark.v2.rad`), left running. `P` `TP` `MLEN` `SEQS` `M` `KVD` `HR` `MNBT` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `RATIO` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnserve.sh` | Qwen3.8-Flash-Next, the production container `w4nl64-i8lm.rad`, same contract. `P` `TP` `MLEN` `SEQS` `M` `NS` `HOSTPOOL` `KVD` `HR` `MNBT` `WIRE` `KVHOST` `KVDIR` `KVDISK` `EXTRA` `EXTRA_ENV` |
|
||||
| `fnstop.sh` | stops whichever is running and **waits for the process to go** |
|
||||
| `convdspark.sh`, `convfn.sh` | rebuild the containers those two serve. The conversions of record. `convfn.sh` needs `CALIB=<dir>`: the production recipe's expert rule runs GPTQ against the calibration Grams there |
|
||||
| `hfget.sh` | fetch a checkpoint from Hugging Face with `curl` and `jq`. Resumable |
|
||||
|
||||
```sh
|
||||
scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx, ratio 0.82
|
||||
scripts/fnserve.sh # defaults: port 8100, tp 2, 200K ctx
|
||||
P=8100 MLEN=131072 SEQS=4 scripts/fnserve.sh # override
|
||||
scripts/fnstop.sh
|
||||
```
|
||||
|
||||
Both print the endpoints and exit with the server still up. Read their headers — `fnserve.sh` in
|
||||
particular carries the whole `--expert-vs-cache-ratio` argument with the measurements behind it.
|
||||
particular records why each production flag is what it is.
|
||||
|
||||
### Measuring a server that is already up
|
||||
|
||||
|
||||
+134
-100
@@ -1,124 +1,158 @@
|
||||
# Three ranks: padding a checkpoint to a world its geometry does not divide
|
||||
# Any world size: the attention world, uneven delta-net heads, and nothing padded
|
||||
|
||||
Radiance shards by dividing: `n_head`, `n_head_kv`, the GDN head counts and the vocabulary each
|
||||
split evenly across the world, and a count that does not divide is **refused at declare, by name**
|
||||
(`share.cpp`, `rad_arch.h`). Four ranks got through for Qwen3.8-Flash-Next by replicating the two
|
||||
KV heads in rank pairs (1.0.7). Three ranks cannot: 24 query heads, 2 KV heads, 16 GDN K heads and
|
||||
48 GDN V heads have no even share in 3, and replication needs a world that is a multiple of the
|
||||
head count. The engine is right to refuse. What this document describes is how to **change the
|
||||
checkpoint** so there is nothing to refuse, exactly, and what the engine gained so that the padded
|
||||
checkpoint then serves at three ranks.
|
||||
Radiance shards by dividing: `n_head`, `n_head_kv`, the delta-net head counts and the vocabulary
|
||||
each split across the world, and a count that does not divide is **refused at declare, by name**
|
||||
(`share.cpp`, `rad_arch.h`). Four ranks get through for Qwen3.8-Flash-Next by replicating the two
|
||||
KV heads in rank pairs; three did not: 24 query heads, 2 KV heads, 16 GDN K heads and 48 GDN V
|
||||
heads have no even share in 3, and replication needs a world that is a multiple of the head count.
|
||||
Padding the checkpoint offline (`tools/pad_tp.py`: zero heads appended so that 36 / 3 / 18 / 54
|
||||
divide) served three ranks exactly, at the cost of a second 115 GiB container for every model and
|
||||
a third of the attention and 2 of 18 delta-net heads computing zeros.
|
||||
|
||||
The regime is tcclaviger's `vllm/config/tp_padding.py`, which pads the same model to the same
|
||||
shape at load time inside vLLM. Radiance has no load-time pad -- a container is served as it was
|
||||
converted -- so the pad is done once, offline, before `rad-convert`.
|
||||
This document describes what replaced it: **the shipped container serves at any world size**, with
|
||||
no tool and no second file. Two rules, both built from machinery the engine already had.
|
||||
|
||||
## 1. What is padded, and why it is exact
|
||||
## 1. The attention world
|
||||
|
||||
Every padded weight gains **zeros**, placed where a zero contributes nothing to the forward pass:
|
||||
`rad_arch.h` `geom_from` handles a world *above* the KV head count by replication, when the world
|
||||
is a multiple of the count. For a plugin that asks for it (`attn_world_ok`; qwen4exp does) it also
|
||||
handles a world that is **neither a divisor nor a multiple** of it:
|
||||
|
||||
| block | tensor | gains | exact because |
|
||||
|---|---|---|---|
|
||||
| attention | `k_proj`, `v_proj` | zero **rows** (new KV heads) | a zero KV head stores zeros and is read only by zero query heads |
|
||||
| attention | `q_proj` (fused q+gate on Flash-Next: 512-row head blocks) | zero rows so every KV group has the new ratio | a zero query head attends uniformly, and its `o_proj` column is zero, so its output is 0 |
|
||||
| attention | `o_proj` | zero **columns** in the same head order | the zero heads' outputs are multiplied by zero |
|
||||
| GDN | `in_proj_qkvz`, `in_proj_ba` | zero rows per the fused layout (new K and V heads) | a zero head carries a zero state |
|
||||
| GDN | `conv1d` | zero channels | zero input, zero output |
|
||||
| GDN | `A_log`, `dt_bias` | zero heads | a zero head decays nothing |
|
||||
| GDN | `out_proj` | zero columns | the zero heads are multiplied by zero |
|
||||
> attention is served on the largest multiple of the KV head count under the world -- the
|
||||
> **attention world** -- and the ranks past it are **attention-zero**.
|
||||
|
||||
Norms, embeddings, the lm_head, the router and the experts are untouched: their only width is
|
||||
`n_embd`. The experts stay at the model's own 640 and the plugin slices them by parity across the
|
||||
ranks (1.0.8: at three ranks the five 128-wide blocks go 2, 2, 1), so the +20 % expert bytes of a
|
||||
640 → 768 pad are not paid.
|
||||
Three ranks over two KV heads: the attention world is 2. Ranks 0 and 1 split the heads exactly as
|
||||
the two-rank serve does -- 12 query heads, one KV head, gqa 12, the same kernels -- and rank 2
|
||||
**computes no attention**: `rad_block_attn_gated_fp8.h` declares no projections, no attention and
|
||||
no cache store on it, and writes the block's output wire to zero with one `fill` (`docs/OPS.md`).
|
||||
The all-reduce and the residual after it see what they always saw, and the zero adds exactly
|
||||
nothing to the reduce. Five ranks over two: attention world 4 (two replicated pairs), rank 4
|
||||
attention-zero. Six: three pairs, no zero rank. A plugin that does not ask is refused at a world
|
||||
like these, by name, as before.
|
||||
|
||||
For Qwen3.8-Flash-Next the pad is **24 → 36 query heads, 2 → 3 KV heads, GDN 16 → 18 K heads and
|
||||
48 → 54 V heads** -- head_dim 256 for attention and 128 for GDN are unchanged, so every rank at
|
||||
three declares 12 query heads, 1 KV head and gqa 12: **the same per-rank attention geometry the
|
||||
two-rank serve declares**, and the same kernels resolve. Dummies go **last**, as the vLLM pad does,
|
||||
so rank 2 carries them.
|
||||
**The KV groups stay in the same order on every rank.** The scheduler sees one program
|
||||
(`core/sched/batch.cpp` indexes `kv_groups[i]` by position) and one block table serves every rank,
|
||||
so an attention-zero rank declares its attention group like its peers and marks it
|
||||
`rad_kv_group_zero`: it carves nothing for it, holds the shared table's block count, lends none of
|
||||
it, and the tiers skip it when they move an entry. Every rank carves the same block count -- each
|
||||
is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
|
||||
zero limits nobody) and capped at the least before any carves.
|
||||
|
||||
The cost is the dummies' arithmetic: 12 of 36 query heads and 2 of 18 GDN heads are zeros on the
|
||||
last rank, so three ranks do 1.5× the attention work of two for 1.5× the cards.
|
||||
**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
|
||||
card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
|
||||
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
|
||||
attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
|
||||
such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
|
||||
the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
|
||||
because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
|
||||
difference into its weights pool, no further than every one of its weights resident. Both readers
|
||||
of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
|
||||
grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
|
||||
whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
|
||||
loan and the attention ranks' pools are unchanged; a stated `--vram-kv-mib` / `--vram-weights-mib`
|
||||
keeps meaning "this many on every card", and `auto` keeps the common split (a fully resident rank
|
||||
would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
|
||||
management re-split like any other: the cache does not lend there, and the bytes the rank never
|
||||
pages are as much its experts' as they are under a lending cache. The condition is the cost, not
|
||||
the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
|
||||
which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names the reason on
|
||||
its `kv: rank N's cache costs ...` line. The pinned host pool is not re-split: every rank allocates
|
||||
its whole `--host-pool-mib`, and a re-split rank whose weights all fit on the card says so
|
||||
(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
|
||||
|
||||
## 2. The tool
|
||||
|
||||
`tools/pad_tp.py` (Python, numpy only; no torch) rewrites a Hugging Face safetensors checkpoint:
|
||||
|
||||
```sh
|
||||
tools/pad_tp.py SRC DST --heads 36 --kv-heads 3 --gdn-k 18 --gdn-v 54 --sparse
|
||||
tools/pad_verify.py SRC DST
|
||||
```
|
||||
kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
|
||||
I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
|
||||
```
|
||||
|
||||
It streams one tensor at a time (a 336 GiB checkpoint pads in a few GB of RAM), reads bf16 as raw
|
||||
u16 (no arithmetic happens), rewrites `config.json` with the new counts and an explicit `head_dim`,
|
||||
and handles the fused layouts: the Flash-Next `q_proj` that carries the attention gate beside each
|
||||
query head, and the GDN `in_proj_qkvz` / `in_proj_ba` row order.
|
||||
The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
|
||||
than at the budget's `unusable` line alone.
|
||||
|
||||
`--sparse` is for checkpoints larger than the free disk. Instead of copying, it **reflinks** every
|
||||
original shard (btrfs, XFS; `cp --reflink`) and writes only the padded tensors into new shards named
|
||||
`model-00000-of-NNNNN-tp3pad-*.safetensors`. Radiance's reader lists the index's shards sorted by
|
||||
name and keeps the **first** tensor of a name (`checkpoint.cpp`, `emplace`), so the new shards
|
||||
shadow the originals by sorting first. Flash-Next: 340 tensors, 6.6 GB of new bytes, the 131
|
||||
original shards shared.
|
||||
Under a smaller attention world the plain even shard over `world` is the wrong cut for every
|
||||
attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
|
||||
call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
|
||||
+n_head)` heads, k/v rows at `kv_off`. When the attention world is the world -- every TP2 and TP4
|
||||
deployment -- no span is declared and the block declares as it always did.
|
||||
|
||||
`tools/pad_verify.py` reads both checkpoints back and checks every tensor: an untouched tensor is
|
||||
byte-identical, a padded one is the source in its place and zeros everywhere else. Run it before
|
||||
`rad-convert`; a pad that passes it cannot change what the model computes.
|
||||
## 2. Uneven delta-net heads
|
||||
|
||||
Padding proved on Llama-3.2-3B (24/8 heads, gqa 3 → 36/9, gqa 4): a 28-layer numpy forward on the
|
||||
padded weights gives the same argmax as the original with max |Δlogit| 2.1e-5 (fp32 summation
|
||||
order), and on the engine TP1 on the padded checkpoint produces the same text as TP1 on the
|
||||
original at temperature 0.
|
||||
The delta net has no KV-head constraint: its kernels are bound on head *widths* (`head_k`,
|
||||
`head_v`, the chunk) and take any head count. So 16 K heads over three ranks are **5, 5 and 6**,
|
||||
each rank's V heads the same multiple of its K heads (48 / 16 = 3: 15, 15, 18), every rank real
|
||||
heads, nothing padded. The extra head goes to the rank without attention (`remainder_place` in
|
||||
`rad_arch.h`): it has the time, and the rank that would otherwise hold the extra head AND attention
|
||||
is the step's slowest. The experts' extra block stays on the parity rotation (`qwen4exp_fp8.cpp`
|
||||
says why). `qwen4exp` computes the split and `rad_block_gdn_fp8.h` declares it as spans of the
|
||||
container's rows. Each rank's recurrent state is its own size, so a fresh slot is cleared, a
|
||||
snapshot taken and a tier entry laid out by each rank's own plan: a slot of the snapshot store or
|
||||
the tiers is the sum of the ranks' shares, each rank's where the ones before it end.
|
||||
|
||||
## 3. What the engine gained for three ranks
|
||||
That needed one thing the span call could not say. `in_proj_qkv|z` is four projections stacked
|
||||
along dim 0 -- q 2048, k 2048, v 6144, z 6144 rows -- and `rad_weight_shard_span` takes one
|
||||
`[lo, hi)` applied to every stacked part, which assumes the parts are equal.
|
||||
**`rad_weight_shard_span_parts`** (an additive export) takes a span per part together with each
|
||||
part's whole extent in the container; `share.cpp` cuts every part by its own rows. The conv
|
||||
channels `[q|k|v]`, the `[a|b]` projections, `A_log`, `dt_bias` and the output projection's
|
||||
columns take the same rank's heads. The even split, when the counts divide, is untouched.
|
||||
|
||||
- **libr4d: `all_reduce` and `all_gather` at world 3.** `ar_oneshot_3rank_exact` is the wide
|
||||
one-shot family's template at 3; `ar_gather_3rank` the same for the gather the vocab-parallel
|
||||
sampler declares. Both share the wide family's instance (scratch, `[block][source]` flags, seq
|
||||
counters). There is no two-shot at 3: it shards the message `world` ways and a residual width
|
||||
such as 2560 does not divide by 3. `wht6` is a two-rank wire; three ranks take the exact one, as
|
||||
four do. Selftest: `--case ar_oneshot_3rank_exact` and `--case ar_gather_3rank`, bit-exact against
|
||||
the host sum / concatenation on three gfx1201 cards, with the two-rank controls unchanged.
|
||||
- **The vocabulary at a world that does not divide it.** 248 320 rows do not divide by 3 and
|
||||
`share.cpp` refuses a row shard without a declared span. `qwen4exp` now declares the rank's span
|
||||
for `token_embd` and `output`, and the split rule (`rad_arch.h` `shard_extent` / `shard_begin`,
|
||||
restated in `core/engine.cpp`) keeps the even share whenever the world divides the vocabulary and
|
||||
otherwise rounds the per-rank count up to a **128-row block** -- a block-scaled fp8 head refuses a
|
||||
cut inside a tile. At three the ranks take 82 816, 82 816 and 82 688; two and four ranks divide
|
||||
248 320 evenly and are untouched.
|
||||
- Everything else three ranks need was already there by 1.0.8: the width split of the experts at
|
||||
any world up to the block count, the uneven tile share of the plain bf16 (protected) experts, the
|
||||
N-rank gather's placement.
|
||||
## 3. What this is built from
|
||||
|
||||
- `rad_weight_shard_span_parts(b, w, lo, hi, total, n)` -- a span per stacked part.
|
||||
- `rad_kv_group_zero(b, g)` -- this rank keeps no cache for a paged group.
|
||||
- the `fill` op -- libr4d's `fill_bf16`, libref's `ref_fill`.
|
||||
- `Geom::attn_world / attn_rank / attn_zero`, set by `geom_from` under `attn_world_ok`;
|
||||
`GdnFP8::Config::k_first / v_first`, set by the plugin.
|
||||
- The exports are additive: `RAD_ABI_VERSION` does not move, and a plugin that does not call them
|
||||
declares as before. `tests/share_test.cpp` holds the per-part cut, `tests/arch_test.cpp` the
|
||||
three-rank declaration, `tests/mem_test.cpp` the capped carve, the zero group and a tier entry
|
||||
moved across ranks with unequal shares.
|
||||
|
||||
**A load check that came with it.** The relayout pool refuses to finish when any staged weight was
|
||||
never delivered: a slot nothing wrote holds whatever the card had there -- zeros on a card whose
|
||||
freed memory the driver wipes, garbage after a reset ("VRAM is lost"). The instrument that shows
|
||||
such a read on any card:
|
||||
|
||||
RADIANCE_DEBUG_POISON_ALLOC=255 radiance --model stock.rad --tp 3 ...
|
||||
|
||||
fills every fresh device allocation with 0xFF (NaN in every float width) before it is handed out;
|
||||
the serve must answer exactly as without it. `RADIANCE_DEBUG_POISON_RANGE=lo:hi` narrows the fill
|
||||
to a thread's allocation ordinals for a bisect (`core/device/dispatch.cpp`).
|
||||
|
||||
## 4. Serving
|
||||
|
||||
```sh
|
||||
tools/pad_tp.py ~/models/Qwen3.8-Flash-Next ~/models/Qwen3.8-Flash-Next-tp3pad \
|
||||
--heads 36 --kv-heads 3 --gdn-k 18 --gdn-v 54 --sparse
|
||||
tools/pad_verify.py ~/models/Qwen3.8-Flash-Next ~/models/Qwen3.8-Flash-Next-tp3pad
|
||||
build/bin/rad-convert ~/models/Qwen3.8-Flash-Next-tp3pad -o qfn-tp3pad.rad \
|
||||
--recipe data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe
|
||||
radiance --model qfn-tp3pad.rad --tp 3 --tp-wire exact --max-num-seqs 8 --max-model-len 200000 \
|
||||
--placement expert_tiered --host-pool-mib 8192 --gpu-headroom-mib 96 \
|
||||
--expert-vs-cache-ratio 0.82 --kv-cache-dtype fp8 --num-speculative-tokens 3 \
|
||||
--max-num-batched-tokens 2048
|
||||
radiance --model qwen3.8-next-flash-fp8-iq4r-moe.rad --tp 3 --tp-wire exact --max-num-seqs 8 \
|
||||
--max-model-len 262144 --placement expert_tiered --host-pool-mib 8192 \
|
||||
--gpu-headroom-mib 96 --kv-cache-dtype fp8 \
|
||||
--num-speculative-tokens 3 --max-num-batched-tokens 2048
|
||||
```
|
||||
|
||||
Measured on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16, Threadripper PRO 9955WX), the
|
||||
uncensored Flash-Next fine-tune padded as above and converted with the shipped recipe
|
||||
(`qwen4exp-w4nl64-i8-hc8m`, here without Hessians: nearest into the codebook), on 1.0.8 with
|
||||
the changes above; the two-rank column is the shipped `qwen3.8-next-flash-fp8-iq4r-moe.rad` on the same box:
|
||||
The log says what the geometry did:
|
||||
|
||||
| | three ranks, padded | two ranks, shipped container |
|
||||
|---|---|---|
|
||||
| READY from cold | 45 s | 35 s |
|
||||
| 1 / 4 / 8 streams, aggregate t/s | 173.5 / 332.2 / 410.9 | 156 / 320 / 404 |
|
||||
| 4 streams at 100 K context, per stream | 41.8 | 41.2 |
|
||||
| warm-prefix TTFT, 60 K prompt, second time | 0.3 s (cold 8.2 s) | — |
|
||||
| HumanEval / GSM8K | 0.854 / 0.915 | 0.854 / 0.940 |
|
||||
```
|
||||
radiance: world_size = 3 over n_head_kv = 2: attention on 2 rank(s), rank(s) 2..2 carry no attention and take the delta net's remainder first
|
||||
radiance: qwen4exp: rank 0 takes delta-net K heads [6, 11) of 16 and V heads [18, 33) of 48
|
||||
radiance: qwen4exp: rank 1 takes delta-net K heads [11, 16) of 16 and V heads [33, 48) of 48
|
||||
radiance: qwen4exp: rank 2 takes delta-net K heads [0, 6) of 16 and V heads [0, 18) of 48
|
||||
```
|
||||
|
||||
The GSM8K gap is the Hessians the shipped container was quantised against and this one was not;
|
||||
the GPTQ'd conversion of the same padded checkpoint is the comparison that closes it. Hi-vocab
|
||||
tokens (CJK, Cyrillic -- rank 2's lm_head shard, the three-rank gather) decode correctly; no engine
|
||||
warnings; every band the run issued resolved to a device kernel.
|
||||
Measured by the contributor on three Radeon AI PRO R9700 (gfx1201, PCIe Gen5 x16) at an earlier
|
||||
state of this design -- the attention-zero rank then ran its projections on zero weights, and the
|
||||
extra delta-net head sat on rank 0 -- with the uncensored Flash-Next fine-tune. Hot = 1 / 4 / 8
|
||||
streams, 8 K prompt, 1 K generated, aggregate tok/s; crowd = 4 streams at 100 K context, per
|
||||
stream; HumanEval 164 and a 200-question GSM8K subset at temperature 0:
|
||||
|
||||
| container | `--tp` | hot c1 / c4 / c8 | crowd | HE | GSM8K |
|
||||
|---|---|---|---|---|---|
|
||||
| unpadded | 3 | 191 / 309 / 353 | 42.7 | 0.878 | 0.925 |
|
||||
| unpadded, the same file | 2 | 177 / 308 / 377 | 33.8 | 0.884 | 0.915 |
|
||||
| padded offline | 3 | 182 / 288 / 395 | 43.5 | 0.848 | 0.935 |
|
||||
|
||||
Three ranks buy the single stream and the long-context crowd, not the eight-stream aggregate. The
|
||||
quality rows are within a rerun of each other (HumanEval moves by about 3 of 164 between runs of one
|
||||
container); unpadded and padded at three ranks gave the same answers on 40 prompts at temperature
|
||||
0, bit-identical on one -- the head regroup changes the order the all-reduce sums in, and near-ties
|
||||
flip.
|
||||
|
||||
`tools/pad_tp.py` and `tools/pad_verify.py` remain in the tree: they are how a checkpoint is padded
|
||||
for an engine that has no attention world, and how a pad is verified, and nothing here needs them.
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# Static YaRN
|
||||
|
||||
Increasing `--max-model-len` reserves a larger serving window; it does not change
|
||||
the model's rotary embeddings. A checkpoint trained at 262144 positions can
|
||||
explicitly request static YaRN for a 524288-token deployment. Whether that extension
|
||||
preserves useful accuracy must be measured on the model and workload.
|
||||
|
||||
One reader takes every architecture's rotary scaling (`yarn_from`,
|
||||
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
|
||||
then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
|
||||
in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
|
||||
A drafter (DFlash2, DSpark) reads its own `draft.rope_parameters` /
|
||||
`draft.rope_scaling`; it does not inherit the target's scaling. The vision tower keeps
|
||||
its original axial rotations. A GGUF's `rope.scaling.*` keys are carried in as the
|
||||
same `rope_scaling` keys when it is read.
|
||||
|
||||
**The factor convention is the config's**, as vLLM and transformers read it:
|
||||
`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
|
||||
|
||||
Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
|
||||
variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
|
||||
`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
|
||||
same keys and declare the same ops; YaRN there has had no model run.
|
||||
|
||||
## Metadata
|
||||
|
||||
| Key within the rotary object | Meaning |
|
||||
| --- | --- |
|
||||
| `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
|
||||
| `factor` | finite number >= 1, required for YaRN |
|
||||
| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
|
||||
| `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
|
||||
| `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
|
||||
| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
|
||||
|
||||
Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
|
||||
as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
|
||||
GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
|
||||
anything but its neutral value is refused when read. Rotary width (including
|
||||
partial rotary), theta and M-RoPE section selection are unchanged.
|
||||
|
||||
## Convert a separate container
|
||||
|
||||
Use the original target and drafter checkpoints, the same quantization recipe,
|
||||
and a **new output path**. `--reuse` is valid only for the same source weights and
|
||||
recipe; it is not a way to mix weights from different model revisions.
|
||||
|
||||
```sh
|
||||
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
|
||||
--draft-model /checkpoints/Qwen3.8-27B-DFlash2 \
|
||||
--recipe data/recipes/q38-27b-fp8-df2.recipe \
|
||||
--reuse /models/qwen3.8-27b-fp8.rad \
|
||||
--set text_config.rope_parameters.rope_type=yarn \
|
||||
--set text_config.rope_parameters.factor=2 \
|
||||
--set text_config.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--set draft.rope_parameters.rope_type=yarn \
|
||||
--set draft.rope_parameters.factor=2 \
|
||||
--set draft.rope_parameters.original_max_position_embeddings=262144 \
|
||||
--max-ctx 524288 --kv-cache-dtype bf16 \
|
||||
-o /models/qwen3.8-27b-fp8-yarn2.rad
|
||||
```
|
||||
|
||||
Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
|
||||
replacement for the explicit YaRN metadata or the server's `--max-model-len`.
|
||||
The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
|
||||
Check both target and draft settings with `rad-info --meta` after conversion.
|
||||
|
||||
Serve on enough memory for the requested window:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
|
||||
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
|
||||
```
|
||||
|
||||
That cache flag controls **both** target and drafter KV. Startup capacity and
|
||||
successful actual long requests must be checked; the command is not a promise
|
||||
of concurrency or accuracy. Keep the unmodified model and serving setup until
|
||||
long-context quality and speed meet the deployment's requirements.
|
||||
|
||||
## Serve an existing container: `--rope-scaling`
|
||||
|
||||
The same metadata can be written when the container is loaded instead of converted in:
|
||||
|
||||
```sh
|
||||
radiance --model /models/qwen3.8-next-flash-fp8.rad \
|
||||
--rope-scaling yarn:2 --max-model-len 409600
|
||||
```
|
||||
|
||||
`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
|
||||
(`ORIG`, default the container's own trained length) in the rotary object the reader above
|
||||
takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
|
||||
`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
|
||||
drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
|
||||
the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
|
||||
`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
|
||||
`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
|
||||
than stacked over. The result is resolved and checked exactly as a converted container's is
|
||||
(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
|
||||
|
||||
Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
|
||||
reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
|
||||
at all, past the trained length. A persisted prefix cache (`--prefix-cache-dir`) is fingerprinted
|
||||
with the resolved rotary of the target and the drafter, so a store written under a different
|
||||
one -- another `--rope-scaling`, or a container converted with YaRN -- is not reused: every cached
|
||||
key was rotated differently.
|
||||
|
||||
The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
|
||||
a deployment that settles on one can convert it in as above and drop the flag.
|
||||
|
||||
## Kernel and test contract
|
||||
|
||||
`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
|
||||
`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
|
||||
is the original path, with the original op identities. With YaRN, `scale` must be 1:
|
||||
inverse frequencies are blended rather than all positions being divided. Axial
|
||||
rotary with YaRN is refused. Rebuild the bundled plugins together because their
|
||||
shared op schemas must match.
|
||||
|
||||
The math follows the static YaRN formulation (Peng et al.) as vLLM's
|
||||
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
|
||||
correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
|
||||
256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
|
||||
`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
|
||||
same formula at positions through 524287, within 8 ulp of each angle -- tight where
|
||||
the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
|
||||
places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
|
||||
fused versus unfused HIP rotation is checked byte-for-byte separately.
|
||||
+118
-1
@@ -54,6 +54,7 @@
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
#include "rad_yarn.h"
|
||||
|
||||
using namespace avx;
|
||||
|
||||
@@ -836,6 +837,12 @@ AVX_KERNEL(rope) {
|
||||
}
|
||||
}
|
||||
const int pair_mode = mode == ROPE_GPTJ ? ROPE_GPTJ : ROPE_NEOX;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f) {
|
||||
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
}
|
||||
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN)
|
||||
@@ -851,6 +858,8 @@ AVX_KERNEL(rope) {
|
||||
} else {
|
||||
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
|
||||
}
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
|
||||
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
|
||||
* this op takes the fused qkv rather than two tensors. */
|
||||
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
|
||||
@@ -953,7 +962,11 @@ AVX_KERNEL(rope_table) {
|
||||
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
|
||||
const int64_t rows = numel(cs) / rot;
|
||||
const int64_t half = rot / 2;
|
||||
const float* invf = inv_freqs(half, rot, theta);
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
@@ -962,6 +975,8 @@ AVX_KERNEL(rope_table) {
|
||||
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
|
||||
float* buf = scratch_f32((size_t)rot);
|
||||
angles(buf, invf, half, p);
|
||||
if (yarn.factor != 0.0f)
|
||||
for (int64_t i = 0; i < rot; ++i) buf[i] *= yarn.magnitude;
|
||||
/* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
|
||||
* libref does unconditionally. The dense case is one row store. */
|
||||
if (rad_tensor_is_contiguous(cs)) {
|
||||
@@ -972,3 +987,105 @@ AVX_KERNEL(rope_table) {
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ qsa_block_key */
|
||||
/* QSA's compressed key (docs/OPS.md): a block's `ratio` rows of k averaged in f32 and rounded to
|
||||
* k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at the block's
|
||||
* position, YaRN included. libref's arithmetic in libref's order; what differs is that the angles
|
||||
* of a block come from one `angles` table, and the inverse frequencies are built once a launch. */
|
||||
AVX_KERNEL(qsa_block_key) {
|
||||
const RadTensor* k = rad_arg_in(a, 0);
|
||||
const RadTensor* w = rad_arg_in(a, 1);
|
||||
const RadTensor* page = rad_arg_in(a, 2);
|
||||
const RadTensor* pos = rad_arg_in(a, 3);
|
||||
const RadTensor* out = rad_arg_in(a, 4);
|
||||
if (!k || !w || !out) return RAD_E_INVAL;
|
||||
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
|
||||
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
|
||||
if (n <= 0 || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
|
||||
if (rot < 0 || rot > n || (rot & 1) || rot / 2 > 512) return RAD_E_SHAPE;
|
||||
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
|
||||
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
|
||||
const int64_t M = page ? numel(page) : out->shape[0];
|
||||
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
|
||||
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
|
||||
const bool pos2 = pos && pos->rank == 2;
|
||||
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
|
||||
|
||||
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
|
||||
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
|
||||
static const char* kModes[] = { "neox", "mrope", "imrope" };
|
||||
const int mi = p_enum(a, "mode", kModes, 3, 0);
|
||||
if (mi < 0) return RAD_E_UNSUPPORTED;
|
||||
int64_t sec[3] = {};
|
||||
int n_sec = 0;
|
||||
for (const char* v = p_str(a, "sections", nullptr); v && *v;) {
|
||||
char* e = nullptr;
|
||||
const long long x = std::strtoll(v, &e, 10);
|
||||
if (e == v) break;
|
||||
if (x <= 0 || n_sec >= 3) return RAD_E_SHAPE;
|
||||
sec[n_sec++] = x;
|
||||
v = e;
|
||||
}
|
||||
/* Several components only with a mode, its sections and three columns of `pos`. */
|
||||
const bool mc = mi != 0 && n_sec > 0 && pos2 && pos->shape[1] >= 3;
|
||||
const RadYarn yarn = rad_yarn_args(a);
|
||||
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
|
||||
return RAD_E_INVAL;
|
||||
const int64_t half = rot / 2;
|
||||
float* invf = inv_freqs(half, rot, theta);
|
||||
int comp[512] = {};
|
||||
if (mc) {
|
||||
int64_t total = 0;
|
||||
for (int c = 0; c < n_sec; ++c) total += sec[c];
|
||||
if (mi == 1 && total != half) return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
int c = 0;
|
||||
if (mi == 1) {
|
||||
int64_t start = 0;
|
||||
while (c + 1 < n_sec && i >= start + sec[c]) { start += sec[c]; ++c; }
|
||||
} else if (n_sec >= 3) {
|
||||
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
|
||||
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
|
||||
}
|
||||
comp[i] = c;
|
||||
}
|
||||
}
|
||||
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
|
||||
float* gain = (float*)scratch_f32_c((size_t)n);
|
||||
for (int64_t t = 0; t < n; ++t) gain[t] = wadd + ldt(w, offlin(w, t));
|
||||
|
||||
AVX_PARALLEL_FOR_IF(M * ratio * n >= AVX_PAR_MIN)
|
||||
for (int64_t b = 0; b < M; ++b) {
|
||||
const int64_t orow = page ? ldi(page, offlin(page, b)) : b;
|
||||
if (orow < 0) continue;
|
||||
float* y = scratch_f32((size_t)n);
|
||||
float* cs = scratch_f32_b((size_t)(rot > 0 ? rot : 1));
|
||||
double ss = 0.0;
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
|
||||
uint64_t tmp = 0;
|
||||
st_elem(&tmp, k->dtype, 0, acc / (float)ratio);
|
||||
y[t] = ld_elem(&tmp, k->dtype, 0);
|
||||
ss += (double)y[t] * y[t];
|
||||
}
|
||||
const float s = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
|
||||
for (int64_t t = 0; t < n; ++t) y[t] = y[t] * s * gain[t];
|
||||
const float div = rscale != 0.0f ? rscale : 1.0f;
|
||||
float pc[3] = {};
|
||||
for (int c = 0; c < (mc ? 3 : 1); ++c)
|
||||
pc[c] = (float)(!pos ? pos0 + b * ratio
|
||||
: ldi(pos, offlin(pos, pos2 ? b * pos->shape[1] + c : b))) / div;
|
||||
if (mc) angles_multi(cs, invf, comp, half, pc);
|
||||
else angles(cs, invf, half, pc[0]);
|
||||
for (int64_t i = 0; i < half; ++i) {
|
||||
const float c = cs[i] * yarn.magnitude, sn = cs[half + i] * yarn.magnitude;
|
||||
const float x0 = y[i], x1 = y[half + i];
|
||||
y[i] = x0 * c - x1 * sn;
|
||||
y[half + i] = x0 * sn + x1 * c;
|
||||
}
|
||||
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -54,6 +54,8 @@ std::vector<Case> build_cases() {
|
||||
add("gelu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("silu", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
|
||||
add("sigmoid", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("fill", { HI("M", 6), HI("n", 645), HS("dtype", dt), HF("value", 1.3) },
|
||||
EB(6, 645, w, 1));
|
||||
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
|
||||
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
|
||||
@@ -204,6 +206,36 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
|
||||
HS("dtype", "f32") });
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
for (const char* mode : { "neox", "gptj", "imrope" })
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 1e7), HF("scale", 1), HS("mode", mode),
|
||||
HI("rotary_dim", 64), HS("sections", "11 11 10"), HS("dtype", dt),
|
||||
HF("yarn_factor", 2), HF("yarn_low", 14), HF("yarn_high", 22),
|
||||
HF("yarn_magnitude", 1.069314718) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
|
||||
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
|
||||
}
|
||||
for (double magnitude : {2.0, (double)NAN}) {
|
||||
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
|
||||
HF("theta", 1e7), HF("scale", 1), HS("mode", "neox"),
|
||||
HI("rotary_dim", 64), HS("dtype", "bf16"), HF("yarn_factor", 0),
|
||||
HF("yarn_magnitude", magnitude) });
|
||||
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
|
||||
HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) });
|
||||
}
|
||||
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and
|
||||
* with YaRN, positions drawn up to the block count times the ratio. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1),
|
||||
HS("dtype", dt) });
|
||||
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
|
||||
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0),
|
||||
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
|
||||
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
|
||||
}
|
||||
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
|
||||
* tower's 2-D axial rotary over a whole 72-wide head. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
|
||||
@@ -261,6 +261,25 @@ AVX_KERNEL(gelu) { return unary<UN_GELU>(a); }
|
||||
AVX_KERNEL(silu) { return unary<UN_SILU>(a); }
|
||||
AVX_KERNEL(sigmoid) { return unary<UN_SIGMOID>(a); }
|
||||
|
||||
/* ------------------------------------------------------------------ fill */
|
||||
/* y = value over [M, n] at y's own row pitch, the value rounded once by the store. Nothing to
|
||||
* vectorise that the store does not already do: it is a write of one number. */
|
||||
AVX_KERNEL(fill) {
|
||||
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
|
||||
const RadTensor* y = &a->t[0];
|
||||
const int64_t n = p_int(a, "n", y->rank >= 1 ? y->shape[y->rank - 1] : 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
const int64_t M = rows_of(y, n);
|
||||
if (M <= 0) return RAD_E_SHAPE;
|
||||
const float v = p_f32(a, "value", 0.0f);
|
||||
AVX_PARALLEL_FOR_IF(M * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < M; ++r) {
|
||||
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
|
||||
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gather_rows */
|
||||
/* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup
|
||||
* follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An
|
||||
|
||||
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user