Archived
radiance 1.7.0
- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves every shipped container - Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime - /v1/messages works with Claude Code as it ships (gearwave00001) - a long agent conversation keeps its cached history when the client rewrites its last turn (manueloverride) - a stream's first event goes out with the first token, so llama-benchy measures prefill right - opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42) - four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b) - NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA adapters (baKon) - many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool arguments and the CPU's vision and audio encoders - plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
@@ -7,11 +7,9 @@ namespace rad {
|
||||
|
||||
int step_advance(const AdvanceArgs& a, RadStream s) {
|
||||
if (a.n_seq <= 0) return RAD_OK;
|
||||
/* THE HOST BACKEND'S STREAMS ARE QUEUES, each run by its own worker thread (device/host.cpp),
|
||||
* and its device memory is host memory. So the rows run here once the stream has finished
|
||||
* everything issued before this call, which is where the kernel would run in stream order.
|
||||
* Without the wait they can read a sampled token or a staged row whose copy is still queued,
|
||||
* and the next step then continues from the token before it. */
|
||||
/* Host backend streams are queues run by worker threads (device/host.cpp), and device memory
|
||||
* is host memory. Drain the stream first so the rows run where the kernel would in stream
|
||||
* order; otherwise they can read a sampled token or staged row whose copy is still queued. */
|
||||
if (device_is_host()) {
|
||||
RAD_TRY(rad_stream_sync(s));
|
||||
for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
|
||||
|
||||
+23
-28
@@ -1,27 +1,23 @@
|
||||
/* advance.h -- the card's own bookkeeping between passes: which drafts a verify step accepted, and
|
||||
* the inputs of every pass that follows from it.
|
||||
*
|
||||
* WHY THE CARD DOES THIS AND NOT THE HOST. A speculative step is a verify pass and the draft passes
|
||||
* behind it, and every pass after the verify depends on how many drafts it accepted: the draft
|
||||
* head continues from the accepted position, and the next verify starts after it. Deciding that on
|
||||
* the host means reading the sampled tokens back, waiting for them, and only then staging the next
|
||||
* pass -- a synchronisation per step during which the card has nothing queued. Deciding it here
|
||||
* lets the host stage and issue every pass of a step, and the next step, before any of them has
|
||||
* run: the rule is a compare of a few integers a sequence, and the card already holds all of them.
|
||||
* Why on the card: every pass after a verify depends on how many drafts it accepted (the draft
|
||||
* head continues from the accepted position, the next verify starts after it). Deciding that on
|
||||
* the host costs a readback and a sync per step with the card idle. On the card it is a compare
|
||||
* of a few integers per sequence, so the host can stage and issue every pass of a step, and the
|
||||
* next step, before any of them runs.
|
||||
*
|
||||
* THE STATE IS PER SEQUENCE SLOT (StepSlot), in device memory on every rank, and it carries exactly
|
||||
* what a pass needs that the host cannot know in advance: where the next verify starts, what it
|
||||
* rolls back, which tokens it verifies, and where the draft head continues from. Every rank keeps
|
||||
* its own copy and computes the same numbers from the same sampled tokens, so no rank ever reads
|
||||
* another's memory.
|
||||
* State: one StepSlot per sequence slot, in device memory on every rank. It holds what the host
|
||||
* cannot know in advance: where the next verify starts, what it rolls back, which tokens it
|
||||
* verifies and where the draft head continues. Each rank computes the same numbers from the same
|
||||
* sampled tokens, so no rank reads another's memory.
|
||||
*
|
||||
* A PASS NAMES ITS DEVICE ROWS. A batch can mix rows whose inputs the host staged -- a prefill
|
||||
* chunk, a history row for positions the host already knows -- with rows whose positions come from
|
||||
* the card; `rows[0][i]` says which, and the advance leaves a host row exactly as it was uploaded.
|
||||
* Device rows: a batch can mix host-staged rows (a prefill chunk, a history row at known
|
||||
* positions) with rows whose positions come from the card. `rows[0][i]` says which; the advance
|
||||
* leaves a host row as uploaded.
|
||||
*
|
||||
* The same code runs on the host backend, where device memory is host memory: the rows run on the
|
||||
* issuing thread once the stream has drained, which is their place in stream order
|
||||
* (advance_impl.h is shared by both builds).
|
||||
* On the host backend, device memory is host memory and the rows run on the issuing thread once
|
||||
* the stream has drained (advance_impl.h is shared by both builds).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
@@ -87,18 +83,17 @@ struct AdvanceArgs {
|
||||
int64_t src_pitch = 1;
|
||||
const int32_t* eog = nullptr; /* end-of-generation ids, sorted */
|
||||
int32_t n_eog = 0;
|
||||
/* THE ROTARY PLANES (RadBatch::rope_pos), [3][rope_pitch] at rope_off, or rope_off -1 when the
|
||||
* build carries none. A row whose position the card moves carries its rotary position along
|
||||
* by the offset the host staged for it: the rows the card owns are decode and draft rows, all
|
||||
* text, and text rotates at its index plus one per-sequence shift. A row the card leaves at
|
||||
* the host's position keeps the host's three components, which is what a media token needs. */
|
||||
/* Rotary planes (RadBatch::rope_pos), [3][rope_pitch] at rope_off; rope_off -1 when the build
|
||||
* has none. A row the card moves keeps the host-staged offset between its position and its
|
||||
* rotary position: card-owned rows are decode and draft rows, all text, which rotate at their
|
||||
* index plus a per-sequence shift. A row left at the host's position keeps the host's three
|
||||
* components, as a media token needs. */
|
||||
int64_t rope_off = -1;
|
||||
int32_t rope_pitch = 0;
|
||||
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), read by ADV_HIST and
|
||||
* ADV_ROUND alone: its history pass is one row a sequence at the committed position, and every
|
||||
* round sits there too, its context ending at that position. `rot_shift` is where those rows
|
||||
* sit for the rotary, 0 or 1 past the committed position. Zero for every other head, whose
|
||||
* passes advance exactly as they always did. */
|
||||
/* A serial head with no cache of its own (rad_drafter_shared_kv), read by ADV_HIST and
|
||||
* ADV_ROUND only: its history pass is one row per sequence at the committed position, and
|
||||
* every round sits there too, with context ending at that position. `rot_shift` is the rotary
|
||||
* position of those rows, 0 or 1 past the committed position. Zero for every other head. */
|
||||
int32_t shared_kv = 0;
|
||||
int32_t rot_shift = 0;
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* advance.hip -- the advance kernel: one thread a row of the batch it patches. See advance.h.
|
||||
/* advance.hip -- the advance kernel: one thread per row of the batch it patches. See advance.h.
|
||||
*
|
||||
* Launched through hipLaunchKernel like any kernel library's, which the AQL backend intercepts, so
|
||||
* it is one dispatch on the rank's own queue in stream order with the pass it belongs to.
|
||||
* Launched through hipLaunchKernel, which the AQL backend intercepts, so it is one dispatch on the
|
||||
* rank's own queue, in stream order with its pass.
|
||||
*/
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
|
||||
+26
-31
@@ -1,8 +1,8 @@
|
||||
/* advance_impl.h -- one row of an advance, shared by the kernel (advance.hip) and the host backend
|
||||
* (advance.cpp). See advance.h for what the modes are and why the card computes them.
|
||||
* (advance.cpp). See advance.h for the modes.
|
||||
*
|
||||
* Every row is independent: it reads its own slot's state and writes only its own positions,
|
||||
* tokens and slots, so the kernel runs one thread a row and the host a loop.
|
||||
* Rows are independent: each reads its own slot's state and writes only its own positions, tokens
|
||||
* and slots, so the kernel runs one thread per row and the host a loop.
|
||||
*/
|
||||
#pragma once
|
||||
#include "advance.h"
|
||||
@@ -28,10 +28,9 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
return lo < a.n_eog && a.eog[lo] == t;
|
||||
}
|
||||
|
||||
/* Every group's slots for the row's `n` positions, read from the positions just written, and its
|
||||
* length from `base`. A position its block table does not reach gets slot -1, which the kernels
|
||||
* read as "no slot" -- the builder sized the tables for the furthest position a pass can reach,
|
||||
* so it only happens to a row that is being computed for nothing. */
|
||||
/* Every group's slots for the row's `n` positions (from the positions just written) and its
|
||||
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this. */
|
||||
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
|
||||
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
|
||||
const int32_t* pos = adv_i32(a, a.pos_off);
|
||||
@@ -51,8 +50,8 @@ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base,
|
||||
}
|
||||
}
|
||||
|
||||
/* A row's position, written, with its rotary components moved by the same amount -- only when it
|
||||
* moved, so a row the host placed exactly keeps whatever components the host gave it. */
|
||||
/* Writes a row's position and moves its rotary components by the same amount. A row whose
|
||||
* position does not change keeps the host's components. */
|
||||
RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
|
||||
const int32_t was = pos[row];
|
||||
pos[row] = p;
|
||||
@@ -83,9 +82,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
|
||||
switch (a.mode) {
|
||||
case ADV_ACCEPT: {
|
||||
/* THE RULE accept_greedy states, and then the end-of-generation cut collect_step applies:
|
||||
* a draft is accepted while it equals the target's own pick at its position, and the run
|
||||
* stops AT an end-of-generation token rather than after it. */
|
||||
/* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
|
||||
* while it equals the target's pick at its position, and the run stops at an
|
||||
* end-of-generation token, not after it. */
|
||||
const int32_t* y = a.src + rout;
|
||||
const int32_t* d = tok + rtok + 1;
|
||||
int32_t acc = 0;
|
||||
@@ -110,13 +109,12 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
}
|
||||
case ADV_HIST: {
|
||||
if (a.shared_kv) {
|
||||
/* A HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_drafter_shared_kv). There is
|
||||
* no history to fill, so the pass is round 1 alone and its one row is the last one of
|
||||
* the run below: the committed position, the trunk's row there, the token the trunk
|
||||
* chose after it. Its context is the committed positions and NOT the verify step's
|
||||
* whole run -- the cache past the committed position holds the K and V of the drafts
|
||||
* this verify rejected. The host staged the run's first trunk row; the card adds the
|
||||
* drafts it accepted. */
|
||||
/* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
|
||||
* history to fill, the pass is round 1 alone: one row at the committed position, with
|
||||
* the trunk's row there and the token chosen after it. Its context ends at the
|
||||
* committed position, not the verify step's whole run, because the cache past it
|
||||
* holds K/V of rejected drafts. The host staged the run's first trunk row; the card
|
||||
* adds the accepted drafts. */
|
||||
int32_t* out = adv_i32(a, a.out_off);
|
||||
tok[k] = a.src[rout + S.acc];
|
||||
adv_pos(a, pos, k, S.head + a.rot_shift);
|
||||
@@ -125,14 +123,12 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
adv_groups(a, i, k, S.head, 1);
|
||||
return;
|
||||
}
|
||||
/* `aux` positions the host already knew the tokens of, then the verify step's own
|
||||
* positions up to the last one it committed, each with the token committed after it --
|
||||
* the sampler's pick there, since the drafts before it agreed with it. The pass has a
|
||||
* row for every position the step COULD have committed, and the ones past the last
|
||||
* committed repeat it: a position past it would take a rejected draft's hidden state
|
||||
* into the head's cache. The repeat is also what makes the run's LAST row draft round
|
||||
* 1's -- the committed position, its hidden state and the token after it -- whatever
|
||||
* the acceptance was (RadBatch::draft_out_ids). */
|
||||
/* `aux` host-known positions, then the verify step's positions up to the last committed
|
||||
* one, each with the token committed after it (the sampler's pick there). The pass has a
|
||||
* row for every position the step could have committed; rows past the last committed
|
||||
* repeat it, so no rejected draft's hidden state enters the head's cache. The repeat also
|
||||
* makes the run's last row draft round 1's input whatever the acceptance was
|
||||
* (RadBatch::draft_out_ids). */
|
||||
const int32_t base = S.head - S.acc - aux;
|
||||
const int32_t last = aux + S.acc;
|
||||
int32_t* out = adv_i32(a, a.out_off);
|
||||
@@ -148,10 +144,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
return;
|
||||
}
|
||||
case ADV_ROUND: {
|
||||
/* Round 2 onward: round 1 is the history pass's last row (ADV_HIST above), so every
|
||||
* round embeds the proposal of the round before it. A head with no cache of its own does
|
||||
* not step forward: it stays at the committed position over the committed context, and
|
||||
* what it proposed reaches the next round through its own hidden state. */
|
||||
/* Round 2 onward (round 1 is the history pass's last row); each round embeds the previous
|
||||
* round's proposal. A head with no cache of its own stays at the committed position over
|
||||
* the committed context; its proposal reaches the next round through its hidden state. */
|
||||
const int32_t base = a.shared_kv ? S.head : S.head + a.round - 1;
|
||||
const int32_t t = a.src[(int64_t)i * a.src_pitch];
|
||||
S.tok[a.round - 1] = t;
|
||||
|
||||
+188
-304
@@ -1,4 +1,4 @@
|
||||
/* batch.cpp -- building the step batch once. See batch.h for why.
|
||||
/* batch.cpp -- builds the step batch once per step. See batch.h.
|
||||
*/
|
||||
#include "batch.h"
|
||||
#include "mm/processor.h"
|
||||
@@ -11,35 +11,27 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Staging arrays are carved out of one slab per set rather than allocated one by one: the copies
|
||||
* are still per array (each carries only the prefix this step used, and those lengths differ by an
|
||||
* order of magnitude between a decode step and a prefill chunk), but the allocator is called twice
|
||||
* at init instead of two dozen times and every array in a set shares one mapping. */
|
||||
/* Alignment of each staging array carved from a set's slab. One slab per set means a couple of
|
||||
* allocations at init instead of two dozen, with every array sharing one mapping. */
|
||||
static const int64_t k_carve_align = 256;
|
||||
|
||||
/* The longest range a build's upload names: one round of the workgroup that copies it, whose loads
|
||||
* are all in flight before its first store (rad_memcpy_ranges_async). */
|
||||
/* Longest range in a build's upload: one round of the copying workgroup, which issues all its
|
||||
* loads before its first store (rad_memcpy_ranges_async). */
|
||||
static const int64_t k_range_max = 16384;
|
||||
|
||||
/* A HOST-SIDE BOUND, ROUNDED UP ONTO A COARSE GRID: to a multiple of `min_q`, and above 64 of
|
||||
* 1/32 to 1/64 of the value's power of two if that is coarser -- so ~3% over at a long context and
|
||||
* at most `min_q` over at a short one.
|
||||
/* Rounds a host-side bound up to a multiple of `min_q`, or above 64 to 1/32..1/64 of the value's
|
||||
* power of two if that is coarser: ~3% slack at long context, at most `min_q` at short.
|
||||
*
|
||||
* `max_ctx_len` and the block-table pitch are ceilings -- a kernel reads each row's own length off
|
||||
* the card -- and they are the only arguments of a decode pass that move while a request runs:
|
||||
* attention and the QSA indexer size their grids by them. Exact, they change the pass's arguments
|
||||
* every step or two; rounded, a pass is the same dispatches with the same arguments for many steps
|
||||
* at a time, which is what lets a recorded pass be played instead of issued (see Ctx::run_step).
|
||||
* The price is grid slack that exits on its first compare, and at a short context, where the
|
||||
* floor is most of the bound, the whole attention term is small. */
|
||||
/* THE FLOOR IS 1024 TOKENS. Every crossing re-records each kind of pass a step runs, twice -- the
|
||||
* recording and the audit before its first play -- at a few hundred microseconds of a rank thread
|
||||
* each, and at a 256-token floor a short-context decode crosses often enough to spend a tenth of
|
||||
* its rank threads recording. It is not higher because a block may choose its PATH by this bound
|
||||
* and not only its grid: rad_block_attn_gated_fp8.h keeps the cheaper dense attention while the
|
||||
* bound says every sequence is inside the indexer's budget, and a floor at that budget takes the
|
||||
* dense path away from every short context -- a verify step's attention at eight sequences takes
|
||||
* 48 us a layer at 2048 instead of 15. */
|
||||
* `max_ctx_len` and the block-table pitch are ceilings (kernels read each row's length from the
|
||||
* card) and the only decode-pass arguments that move as a request runs. Rounded, a pass keeps the
|
||||
* same arguments for many steps, so a recorded pass can be replayed (Ctx::run_step); the cost is
|
||||
* grid slack that exits on its first compare.
|
||||
*
|
||||
* Floor of 1024 tokens: every crossing re-records each pass kind twice (recording plus audit), a
|
||||
* few hundred microseconds of rank thread each, which a 256 floor makes frequent at short context.
|
||||
* Not higher, because a block may pick its path by this bound: rad_block_attn_gated_fp8.h keeps
|
||||
* dense attention while every sequence is inside the indexer's budget; with a 2048 floor, a
|
||||
* verify step's attention at eight sequences costs 48 us a layer instead of 15. */
|
||||
static const int64_t k_bound_tokens = 1024;
|
||||
|
||||
static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
|
||||
@@ -52,8 +44,8 @@ static inline int64_t bound_bucket(int64_t v, int64_t min_q) {
|
||||
return (v + q - 1) / q * q;
|
||||
}
|
||||
|
||||
/* A negative device status inside build() aborts the step; there is nothing to fall back to and a
|
||||
* partially staged batch is worse than no batch. */
|
||||
/* A negative device status inside build() aborts the step: there is no fallback, and a partially
|
||||
* staged batch is worse than none. */
|
||||
#define RAD_TRY_NULL(expr) \
|
||||
do { int _s = (expr); \
|
||||
if (_s < 0) { RAD_ERR("step batch: %s -> %s", #expr, rad_strerror(_s)); \
|
||||
@@ -67,14 +59,11 @@ static T* carve(char* base, int64_t& off, int64_t n) {
|
||||
return base ? reinterpret_cast<T*>(base + o) : nullptr;
|
||||
}
|
||||
|
||||
/* The full token sequence of a request is prompt ++ output ++ draft, and n_computed indexes into
|
||||
* it. One accessor for all three keeps prefill, decode, recompute-after-preemption and speculative
|
||||
* verify on the same path: a preempted request re-prefills its own generated output because that
|
||||
* is simply the tail of the same sequence, and a verify reads past the committed end into the
|
||||
* drafter's proposal. No special case anywhere. */
|
||||
/* Token i of prompt ++ output ++ draft, the sequence n_computed indexes. One accessor keeps
|
||||
* prefill, decode, recompute after preemption and speculative verify on one path. */
|
||||
static inline int32_t token_at(const StepEntry& e, int64_t i) {
|
||||
/* A placeholder entry -- a drafter context row whose request has already gone -- has no
|
||||
* tokens, and the pass it belongs to reads none. */
|
||||
/* A placeholder entry (a drafter context row whose request is gone) has no tokens, and its
|
||||
* pass reads none. */
|
||||
if (!e.req) return 0;
|
||||
const Request& r = *e.req;
|
||||
int64_t np = (int64_t)r.prompt.size();
|
||||
@@ -87,23 +76,19 @@ static inline int32_t token_at(const StepEntry& e, int64_t i) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ set layout */
|
||||
/* Walked with null bases to measure and with real ones to assign. Keeping both in one function is
|
||||
* what stops them drifting, which is the classic way a hand-carved slab ends up with two arrays
|
||||
* sharing bytes. Every array is carved in PAIRS, host and device at the same offset, including the
|
||||
* host-only ones: that is what lets one copy of a prefix move a whole build, and it puts the
|
||||
* block tables -- the only part whose size moves from build to build -- last. */
|
||||
/* Called with null bases to measure and with real ones to assign, so the two cannot drift. Every
|
||||
* array is carved as a host/device pair at the same offset, host-only ones included, so one copy
|
||||
* of a prefix moves a whole build. The block tables, whose size varies per build, go last. */
|
||||
void BatchBuilder::carve(Set& s, char* h) {
|
||||
char* const d = s.dev.empty() ? nullptr : static_cast<char*>(s.dev[0]);
|
||||
const int64_t T = max_tok_, S = max_seqs_;
|
||||
/* The most logit rows one step can want: one per sequence, or one per verified draft position
|
||||
* per sequence at a speculative step. It is what bounds Geom::max_logit_rows on the plugin
|
||||
* side, and the two have to agree or the plugin gathers into a buffer smaller than out_ids. */
|
||||
/* ...or one row a TOKEN, which an MTP history pass is: it gathers the trunk`s hidden state
|
||||
* for every position the step just computed, and names those rows through the same array. */
|
||||
/* Most logit rows one step can want: one per verified position per sequence, or one per
|
||||
* token for an MTP history pass. Must agree with Geom::max_logit_rows on the plugin side, or
|
||||
* the plugin gathers into a buffer smaller than out_ids. */
|
||||
int64_t O = S * (1 + (cfg_.n_spec > 0 ? (int64_t)cfg_.n_spec : 0));
|
||||
if (O < T) O = T;
|
||||
/* ...and in the KL mode a row at every token as well, after the sampled ones
|
||||
* (Request::score). RadBuildCtx::max_out_rows says the same number to the plugin. */
|
||||
/* KL mode adds a row at every token after the sampled ones (Request::score); keep in sync
|
||||
* with RadBuildCtx::max_out_rows. */
|
||||
if (cfg_.kld()) O = T + S;
|
||||
|
||||
int64_t oh = 0, od = 0;
|
||||
@@ -111,7 +96,7 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
*ph = ::rad::carve<int32_t>(h, oh, n);
|
||||
*pd = ::rad::carve<int32_t>(d, od, n);
|
||||
};
|
||||
/* Twice the step: its own tokens, then up to a step of the prompt that follows
|
||||
/* Twice the step: its own tokens, then up to a step of the following prompt
|
||||
* (RadBatch::n_ahead). */
|
||||
pair(&s.h_tok, &s.d_tok, 2 * T);
|
||||
pair(&s.h_pos, &s.d_pos, T);
|
||||
@@ -135,14 +120,12 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
pair(&g.h_used, &g.d_used, S);
|
||||
pair(&g.h_sidx, &g.d_sidx, S * g.sidx_pitch);
|
||||
}
|
||||
/* THE ROTARY PLANES AND THE ENCODER-ROW TARGETS, only for a program with an encoder: nothing
|
||||
* else can move a rotary position off the token index, and a text-only deployment should not
|
||||
* upload twelve bytes a token of copies of `positions` every step. */
|
||||
/* Rotary planes and encoder-row targets, only for a program with an encoder; nothing else
|
||||
* moves a rotary position off the token index. */
|
||||
pair(&s.h_rope, &s.d_rope, mm_on_ ? 3 * T : 0);
|
||||
pair(&s.h_mmrow, &s.d_mmrow, mm_on_ ? T : 0);
|
||||
/* Host-only: derived metadata is copied into the arena the buffer plan already placed. Carved
|
||||
* in the pair anyway, so the device offsets stay the host's -- a few kilobytes of slab nobody
|
||||
* reads. */
|
||||
/* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
|
||||
* keep device offsets equal to host offsets. */
|
||||
{
|
||||
int32_t* unused = nullptr;
|
||||
char* hd = ::rad::carve<char>(h, oh, derived_bytes_);
|
||||
@@ -150,18 +133,14 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
s.h_derived = hd;
|
||||
pair(&s.h_convslot, &unused, S * (int64_t)kvgeom_.g.size());
|
||||
}
|
||||
/* ---- the block tables, LAST ------------------------------------------------------------
|
||||
/* ---- the block tables, last ------------------------------------------------------------
|
||||
*
|
||||
* A group's table is carved for the worst step -- max_seqs rows of max_ctx/block_size entries
|
||||
* -- because the slab has to hold one. At a long context and a small block that is over a
|
||||
* megabyte per paged group, and a model may declare several: the tables are nearly the whole
|
||||
* slab. A build fills n_seq rows of `pitch`, THIS step's longest table, and the device reads
|
||||
* them at that pitch (block_table_pitch below).
|
||||
*
|
||||
* ON THE CARD each group's rows have a FIXED place in this region, so the rows a build leaves
|
||||
* alone are still there for the next one (BtMirror). IN THE HOST SPAN the region is the
|
||||
* build's payload and range list instead, sized by what changed: the carve's host half only
|
||||
* says where the payload starts. */
|
||||
* Each group's table is carved for the worst step (max_seqs rows of max_ctx/block_size
|
||||
* entries), nearly the whole slab at long context. A build fills n_seq rows at `pitch`, this
|
||||
* step's longest table, and the device reads them at that pitch (block_table_pitch below).
|
||||
* On the card each group's rows have a fixed place, so rows a build leaves alone persist
|
||||
* (BtMirror). In the host span this region holds the payload and range list, sized by what
|
||||
* changed; the host half of the carve only marks where the payload starts. */
|
||||
{
|
||||
int64_t bt_n = 0;
|
||||
s.bt_base = od;
|
||||
@@ -185,9 +164,8 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
s.groups[gi].block_size = e.block_size;
|
||||
int64_t mb = 1;
|
||||
if (e.paged) {
|
||||
/* A WINDOW row holds the window behind the step's first query AND the step's own
|
||||
* tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the
|
||||
* window -- plus the speculative lookahead, which a verify row carries on top. */
|
||||
/* A window row holds the window behind the step's first query plus the step's own
|
||||
* tokens (KVManager::ensure keeps both), plus a verify row's speculative lookahead. */
|
||||
const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1);
|
||||
int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_)
|
||||
? wspan : max_ctx_;
|
||||
@@ -202,8 +180,7 @@ void BatchBuilder::size_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
size_set(s, groups);
|
||||
|
||||
/* ONE SLAB PER RANK, on that rank's card. rad_dev_alloc has no device argument and uses the
|
||||
* current one, so the bind is part of the allocation. */
|
||||
/* One slab per rank, on its card. rad_dev_alloc uses the current device, hence the bind. */
|
||||
s.dev.assign(ranks_.size(), nullptr);
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RAD_TRY(rad_dev_set(ranks_[r].device));
|
||||
@@ -216,9 +193,8 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
}
|
||||
RAD_TRY(rad_dev_set(ranks_[0].device));
|
||||
|
||||
/* THE RING HOLDS THREE WORST-CASE BUILDS, which is the most a host running ahead of the card
|
||||
* can have in flight before a long-context prefill has to wait for its own upload two builds
|
||||
* back; a decode build's span is its fixed prefix and a few rows of tables, so hundreds fit. */
|
||||
/* The ring holds three worst-case builds before a long-context prefill waits on an upload two
|
||||
* builds back. A decode build's span is far smaller, so hundreds fit. */
|
||||
int64_t worst_pay = 0;
|
||||
for (const Group& g : s.groups) worst_pay += max_seqs_ * g.max_blocks * (int64_t)sizeof(int32_t);
|
||||
const int64_t worst_ranges = worst_pay / k_range_max + max_seqs_ * (int64_t)s.groups.size() + 1;
|
||||
@@ -234,8 +210,7 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
|
||||
ring_.first = 0;
|
||||
ring_.live = 0;
|
||||
|
||||
/* Local: the host waits on these only to know an upload has READ its span, which a card-wide
|
||||
* release says as well as a system-wide one. */
|
||||
/* Local events suffice: the host waits on them only to know an upload has read its span. */
|
||||
ev_.assign(kFlights, std::vector<RadEvent>(ranks_.size(), nullptr));
|
||||
ev_free_.clear();
|
||||
ev_free_.reserve(kFlights);
|
||||
@@ -291,10 +266,9 @@ void BatchBuilder::free_set(Set& s) {
|
||||
for (Out& o : out_) { o.kv.clear(); o.batch.clear(); }
|
||||
}
|
||||
|
||||
/* A SPAN OF THE RING, contiguous, of `need` bytes. A span that would run past the end starts over
|
||||
* at zero. Every flight overlapping the span is retired first -- its uploads have run, on every
|
||||
* rank -- oldest first, which is the order they were issued in and so the order the card
|
||||
* finishes them. */
|
||||
/* A contiguous span of `need` bytes, wrapping to zero if it would run past the end. Every flight
|
||||
* overlapping it is retired first (its uploads have run on every rank), oldest first, which is
|
||||
* issue order and so completion order. */
|
||||
int BatchBuilder::reserve(int64_t need, int64_t* off) {
|
||||
if (need > ring_.bytes) {
|
||||
RAD_ERR("step batch staging: a build of %s does not fit the %s ring",
|
||||
@@ -320,15 +294,14 @@ int BatchBuilder::reserve(int64_t need, int64_t* off) {
|
||||
if (!clash) break;
|
||||
RAD_TRY(retire_oldest());
|
||||
}
|
||||
/* And a flight needs an event row: out of rows is out of flights. */
|
||||
/* A flight also needs a free event row. */
|
||||
while (ev_free_.empty() || ring_.live == kFlights) RAD_TRY(retire_oldest());
|
||||
*off = at;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* THE SAME ARRAY ON ANOTHER RANK'S SLAB. Every slab is carved by the same walk() from the same
|
||||
* sizes, so an array's offset is rank-independent: the byte offset off rank 0's base, re-applied
|
||||
* to rank r's. */
|
||||
/* The same array on another rank's slab. Every slab has the same carve, so the byte offset from
|
||||
* rank 0's base applies to rank r's. */
|
||||
template <class T>
|
||||
static inline T* on_rank(void* base_r, void* base_0, T* p0) {
|
||||
return p0 ? (T*)((char*)base_r + ((char*)p0 - (char*)base_0)) : nullptr;
|
||||
@@ -343,8 +316,8 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
|
||||
kvgeom_ = kvg;
|
||||
ranks_ = ranks;
|
||||
if (ranks_.empty()) return RAD_E_INVAL;
|
||||
/* A null stream is the default stream and is legal; a null Program is not -- a derived
|
||||
* buffer would have no arena to land in. */
|
||||
/* A null stream (the default stream) is legal; a null Program is not, since derived buffers
|
||||
* need its arena. */
|
||||
for (const RankIO& r : ranks_)
|
||||
if (!r.prog) return RAD_E_INVAL;
|
||||
RAD_TRY(layout(prog, cfg));
|
||||
@@ -353,25 +326,20 @@ int BatchBuilder::init(Program& prog, const Config& cfg, const ChunkGeometry& ge
|
||||
out_last_ = -1;
|
||||
if (mm_on_) RAD_TRY(alloc_media());
|
||||
|
||||
/* THE RESERVATION AND WHAT ACTUALLY CROSSES ARE DIFFERENT NUMBERS, so the line says both.
|
||||
* Nearly all of the slab is block-table rectangles carved for the worst step, and a step
|
||||
* copies only the rows it filled -- an operator reading the reservation alone would price
|
||||
* the per-step cost far above what it is. */
|
||||
RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank, %d KV group(s), "
|
||||
"%d derived buffer(s); of the slab, %s is block tables carved for the worst step "
|
||||
"and only the filled rows cross",
|
||||
/* Report both the reservation and the block-table share of it: tables are carved for the
|
||||
* worst step, but a step uploads only the rows it filled. */
|
||||
RAD_INFO("step batch: %s pinned staging ring + %s device slab a rank (%s of it block "
|
||||
"tables), %d KV group(s), %d derived buffer(s)",
|
||||
humanb(ring_.bytes).c_str(), humanb(set_.dev_bytes).c_str(),
|
||||
(int)prog.kv_groups.size(), (int)derived_.size(),
|
||||
humanb(set_.dev_bytes - set_.bt_base).c_str());
|
||||
humanb(set_.dev_bytes - set_.bt_base).c_str(), (int)prog.kv_groups.size(),
|
||||
(int)derived_.size());
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* WHAT init() WILL ALLOCATE ON EVERY RANK'S CARD, before any of it exists: the VRAM budget is
|
||||
* resolved before the builder is, and a reservation it does not charge comes out of
|
||||
* --gpu-headroom-mib -- the room a kernel's first launch allocates from, where running out is a
|
||||
* fault inside the HIP runtime rather than an error. The slab's block tables grow with
|
||||
* --max-num-seqs and the media staging with --max-num-batched-tokens, so neither is small enough
|
||||
* to leave to the headroom. The same layout() and carve walk as init(), so the two cannot drift. */
|
||||
/* What init() will allocate on every rank's card, for the VRAM budget, which is resolved before
|
||||
* the builder. An uncharged reservation would eat --gpu-headroom-mib, where running out faults
|
||||
* inside the HIP runtime; the block tables grow with --max-num-seqs and the media staging with
|
||||
* --max-num-batched-tokens. Uses the same layout() and carve as init(). */
|
||||
int64_t BatchBuilder::device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg) {
|
||||
BatchBuilder b;
|
||||
b.prog_ = &prog;
|
||||
@@ -395,17 +363,14 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
}
|
||||
if (kvgeom_.g.size() != prog.kv_groups.size()) return RAD_E_INVAL;
|
||||
|
||||
/* The block-table staging rectangle. A sequence never holds more blocks than its context (or
|
||||
* its window, which is the whole point of declaring one: a 4K-window layer in a 128K context
|
||||
* needs a row 32x shorter). The +1 is because a window's blocks are not aligned to the
|
||||
* window's start, so it can straddle one extra block. */
|
||||
/* Block-table rows are sized by context, or by window for a window group (size_set). The +1
|
||||
* block there is because a window is not block-aligned and can straddle one extra block. */
|
||||
max_ctx_ = cfg.max_ctx > 0 ? cfg.max_ctx : prog.meta.n_ctx_train;
|
||||
if (max_ctx_ <= 0) max_ctx_ = cfg.max_tok;
|
||||
|
||||
/* The conv rolling window: width-1 entries of history plus room for the whole speculative
|
||||
* window, and a rejection then reads back at the slot the last accepted token left (spec §10).
|
||||
* The state tensor's own extent (conv_window_entries), so the cursor derived from it stays
|
||||
* inside the slot the kernels index. */
|
||||
/* Conv rolling window: width-1 entries of history plus the whole speculative window, so a
|
||||
* rejection reads back at the slot the last accepted token left (spec §10). Taken from the
|
||||
* state tensor's extent (conv_window_entries) so the derived cursor stays inside the slot. */
|
||||
conv_window_.assign(prog.kv_groups.size(), 1);
|
||||
conv_group_ = -1;
|
||||
n_conv_ = 0;
|
||||
@@ -458,11 +423,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
d.buf = &b;
|
||||
d.off = derived_bytes_;
|
||||
|
||||
/* WHICH CONV GROUP THIS ONE IS ABOUT. `conv_state_index` is the derivation that reads a
|
||||
* rolling window, and a model may declare several of different depths -- so the buffer
|
||||
* names its group and 0 means "the only one of its kind". With more than one conv group
|
||||
* and no name the answer is a guess between two windows, and the wrong depth produces a
|
||||
* plausible cursor pointing at history the kernel never wrote. Refused instead. */
|
||||
/* `conv_state_index` reads a rolling window, and conv groups may differ in depth, so the
|
||||
* buffer names its group; 0 means the only conv group. With several conv groups and no
|
||||
* name, refuse: the wrong depth yields a cursor into history never written. */
|
||||
if (std::strcmp(d.name, "conv_state_index") == 0) {
|
||||
if (b.decl.kv != 0) {
|
||||
if (b.decl.kv >= prog.kv_groups.size() ||
|
||||
@@ -475,10 +438,9 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
} else if (n_conv_ == 1) {
|
||||
d.conv_grp = conv_group_;
|
||||
} else {
|
||||
RAD_ERR("derived buffer '%s' runs 'conv_state_index' and names no KV group, but "
|
||||
"%d RAD_KV_CONV groups are declared. Set RadBufDecl::kv -- a cursor "
|
||||
"computed against the wrong window's depth points at history that was "
|
||||
"never written.", b.name.c_str(), n_conv_);
|
||||
RAD_ERR("derived buffer '%s' runs 'conv_state_index' with %d RAD_KV_CONV "
|
||||
"groups declared; set RadBufDecl::kv to the one it reads",
|
||||
b.name.c_str(), n_conv_);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
@@ -486,13 +448,10 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
derived_bytes_ = align_up(derived_bytes_ + n * (int64_t)sizeof(int32_t), k_carve_align);
|
||||
}
|
||||
|
||||
/* Two layers declaring the same derivation get two BufferInfos and two arena slots -- that is
|
||||
* what the buffer plan produced -- but they share ONE computation: run_derivations computes
|
||||
* each distinct derivation once per step and copies the result to every destination. The cost
|
||||
* §8 is about is the recomputation, not the bytes.
|
||||
*
|
||||
* SORTED BY (derivation, GROUP), because two buffers running one derivation over different
|
||||
* conv groups are different answers and the sharing rule below is "same as the previous". */
|
||||
/* Buffers declaring the same derivation keep separate arena slots but share one computation
|
||||
* per step (run_derivations copies the result; §8). Sorted by (derivation, group), since
|
||||
* run_derivations shares a result only with the previous entry and different conv groups
|
||||
* give different answers. */
|
||||
std::sort(derived_.begin(), derived_.end(),
|
||||
[](const Derived& a, const Derived& b) {
|
||||
return a.fn_index != b.fn_index ? a.fn_index < b.fn_index
|
||||
@@ -505,8 +464,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
|
||||
|
||||
/* ------------------------------------------------------------------ media staging */
|
||||
BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
/* The larger of the two encoders' passes, field by field: they run one at a time. Both write
|
||||
* rows of the model's embedding width. */
|
||||
/* The larger of the two encoders' passes, field by field, since they run one at a time. */
|
||||
enc_patches_ = enc_pix_elems_ = enc_segs_ = 0;
|
||||
n_embd_ = 0;
|
||||
for (const RadEncoderDecl* e : { &prog_->encoder, &prog_->audio_encoder }) {
|
||||
@@ -514,7 +472,7 @@ BatchBuilder::MediaBytes BatchBuilder::media_bytes() {
|
||||
n_embd_ = std::max<int64_t>(n_embd_, e->n_embd);
|
||||
enc_patches_ = std::max<int64_t>(enc_patches_, e->max_patches);
|
||||
enc_pix_elems_ = std::max<int64_t>(enc_pix_elems_, e->max_patches * e->patch_dim);
|
||||
/* The most segments one pass can hold: a segment is at least one output row. */
|
||||
/* Most segments one pass can hold; a segment is at least one output row. */
|
||||
enc_segs_ = std::max<int64_t>(enc_segs_, e->max_patches / (e->merge > 0 ? e->merge : 1) + 1);
|
||||
}
|
||||
MediaBytes m;
|
||||
@@ -580,10 +538,9 @@ void BatchBuilder::free_media() {
|
||||
mm_ev_live_ = false;
|
||||
}
|
||||
|
||||
/* THE ENCODER ROWS OF ONE ENTRY. A row reads its embedding at token `ctx_len + j + shift` -- the
|
||||
* draft head's history pass shifts its tokens one ahead, and its embeddings with them -- and the
|
||||
* rows that land in a media run take that run's encoder row instead. Consecutive tokens of one run
|
||||
* are consecutive rows of its item, so a run is one copy. */
|
||||
/* Row j reads its embedding at token `ctx_len + j + shift` (the draft head's history pass shifts
|
||||
* by one); rows inside a media run take that run's encoder row instead. Consecutive tokens of a
|
||||
* run are consecutive rows of its item, so each run is one copy. */
|
||||
int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
|
||||
int32_t* rows) {
|
||||
const mm::PromptMedia& pm = *e.req->media;
|
||||
@@ -600,7 +557,7 @@ int64_t BatchBuilder::stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift
|
||||
(unsigned long long)e.seq);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
/* The rest of this run inside this entry, and inside the prompt. */
|
||||
/* The rest of this run within this entry and the prompt. */
|
||||
int64_t take = std::min<int64_t>((int64_t)run->tok + run->n - ti, e.n_tokens - j);
|
||||
take = std::min<int64_t>(take, prompt - ti);
|
||||
const int64_t row = (int64_t)run->row0 + (ti - run->tok);
|
||||
@@ -631,20 +588,16 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
in.n_seq = (int64_t)plan.e.size();
|
||||
in.state_chunk = geo_.state_chunk;
|
||||
|
||||
/* derived_ is sorted by derivation, so "the same one as the previous entry" is the whole
|
||||
* sharing rule and it needs no map. IT IS A PAIR NOW: two buffers running the same derivation
|
||||
* over DIFFERENT KV GROUPS are different answers, and sharing them would give one group the
|
||||
* other's cursors. */
|
||||
/* derived_ is sorted by (derivation, group), so an entry matching the previous one on both
|
||||
* reuses its result. Different groups never share. */
|
||||
int last_fn = -1;
|
||||
int32_t last_grp = -1;
|
||||
const Derived* last = nullptr;
|
||||
for (Derived& d : derived_) {
|
||||
int32_t* host = (int32_t*)(s.h_derived + d.off);
|
||||
|
||||
/* THE GROUP'S OWN SLOTS AND ITS OWN WINDOW. `conv_state_index` computes a cursor inside a
|
||||
* rolling window, so the depth has to be that group's: one number shared across groups
|
||||
* fits only one of them, and the wrong depth produces a plausible cursor pointing at
|
||||
* history the kernel never wrote. */
|
||||
/* The group's own slots and window depth; `conv_state_index` computes a cursor inside
|
||||
* that group's rolling window. */
|
||||
const int32_t grp = d.conv_grp;
|
||||
in.conv_slot = (grp >= 0) ? s.h_convslot + (int64_t)grp * max_seqs_ : nullptr;
|
||||
in.conv_window = (grp >= 0 && grp < (int32_t)conv_window_.size()) ? conv_window_[grp] : 1;
|
||||
@@ -667,9 +620,7 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
last = &d;
|
||||
}
|
||||
|
||||
/* INTO EVERY RANK'S ARENA, on that rank's stream. A derived buffer is an ordinary
|
||||
* transient the core fills, so it lives in the per-rank arena the buffer plan placed --
|
||||
* copying only into rank 0's leaves every other rank reading whatever its arena held. */
|
||||
/* Copy into every rank's arena on that rank's stream; each rank has its own slot. */
|
||||
for (const RankIO& io : ranks_) {
|
||||
if (d.handle >= io.prog->buffers.size()) return RAD_E_STATE;
|
||||
void* dst = io.prog->buffers[d.handle].ptr;
|
||||
@@ -685,16 +636,15 @@ int BatchBuilder::run_derivations(const StepPlan& plan, Set& s) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
/* ------------------------------------------------------------------ per-group fill */
|
||||
int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o) {
|
||||
const int64_t n_seq = (int64_t)plan.e.size();
|
||||
int32_t* const pay = s.bt_h0; /* the payload: the table entries this build restages */
|
||||
int32_t* const pay = s.bt_h0; /* payload: the table entries this build restages */
|
||||
int64_t np = 0;
|
||||
ranges_.clear();
|
||||
/* `n` entries of the payload from word `src` to word `dst` of the card's table region, as
|
||||
* ranges of at most k_range_max bytes. A run that continues the last range extends it, which
|
||||
* is what makes a whole restage of consecutive rows a handful of ranges and not one a row. */
|
||||
/* Stage `n` payload words from word `src` to word `dst` of the card's table region, as ranges
|
||||
* of at most k_range_max bytes. A run continuing the last range extends it, so consecutive
|
||||
* whole rows become a few ranges instead of one per row. */
|
||||
auto stage = [&](int64_t dst, int64_t src, int64_t n) {
|
||||
int64_t db = s.bt_base + dst * (int64_t)sizeof(int32_t);
|
||||
int64_t sb = s.bt_base + src * (int64_t)sizeof(int32_t);
|
||||
@@ -713,8 +663,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
}
|
||||
};
|
||||
|
||||
/* Every group's row, not just the first: a sequence with no state in a group must read -1
|
||||
* there, and a stale slot from the previous step is the worst possible value. */
|
||||
/* Reset every group's row: a sequence with no state in a group must read -1, not a stale slot
|
||||
* from the previous step. */
|
||||
for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi)
|
||||
for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1;
|
||||
|
||||
@@ -722,9 +672,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
Group& g = s.groups[gi];
|
||||
const KVGeom::G& L = kvgeom_.g[gi];
|
||||
|
||||
/* THIS STEP's pitch, which build() measured before it sized the span. RadKVGroupBatch
|
||||
* carries it, so the device reads the rows at the width they were staged. A new pitch
|
||||
* moves every row, so nothing the card holds is where this build reads it. */
|
||||
/* This step's pitch, set by build() before it sized the span and passed in
|
||||
* RadKVGroupBatch. A new pitch moves every row, invalidating the mirror. */
|
||||
const int64_t pitch = pitch_[gi];
|
||||
BtMirror& m = bt_mirror_[gi];
|
||||
if (L.paged && m.pitch != pitch) {
|
||||
@@ -738,19 +687,17 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
|
||||
int64_t first = 0;
|
||||
if (L.paged) {
|
||||
/* The block table is the MANAGER's, read by sequence id. Request::blocks is not
|
||||
* the source of truth: two allocators disagreeing about what a sequence owns is
|
||||
* the bug where a freed sequence's blocks are handed out from under it. */
|
||||
/* The manager's block table, by sequence id; Request::blocks is not the source
|
||||
* of truth (see IKVManager). */
|
||||
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j)
|
||||
g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
|
||||
/* THE ROW, FROM WHAT THE CARD ALREADY HOLDS OF IT. The same sequence in the same
|
||||
* row keeps every entry below the lowest one the manager changed and below the end
|
||||
* of both the old and the new table; a decode step's row is then nothing, or the
|
||||
* one block it appended. Anything else -- a new sequence, one that moved rows -- is
|
||||
* the whole row, and its copies in other rows stop being current, since its marks
|
||||
* are taken here. The marks are taken for every row either way. */
|
||||
/* Restage relative to what the card holds (BtMirror). The same sequence in the
|
||||
* same row keeps entries below the first changed one and below the end of both
|
||||
* old and new tables, so a decode step stages nothing or one appended block. A
|
||||
* new or moved sequence restages the whole row, and its copies in other rows go
|
||||
* unknown. Change marks are taken for every row. */
|
||||
const int64_t nb = std::min<int64_t>((int64_t)bt.size(), pitch);
|
||||
const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi);
|
||||
int64_t lo = 0, hi = pitch;
|
||||
@@ -764,7 +711,9 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
if (lo < hi) {
|
||||
int32_t* w = pay + np;
|
||||
const int64_t nc = nb > lo ? nb - lo : 0;
|
||||
std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
|
||||
/* Guarded: an empty table's data() may be null, and memcpy's source must
|
||||
* not be, even for zero bytes. */
|
||||
if (nc > 0) std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
|
||||
std::fill(w + nc, w + (hi - lo), -1);
|
||||
stage(g.bt_fix + i * pitch + lo, np, hi - lo);
|
||||
np += hi - lo;
|
||||
@@ -772,43 +721,27 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
m.seq[(size_t)i] = e.seq;
|
||||
m.len[(size_t)i] = nb;
|
||||
} else {
|
||||
/* A linear or conv group owns one state instance per sequence, so every token of
|
||||
* the sequence maps to it and the "block table" row is that slot -- a kernel that
|
||||
* only reads block tables then needs no second path. */
|
||||
/* A linear or conv group has one state slot per sequence; every token maps to it
|
||||
* and the block-table row is that slot, so table-reading kernels need no second
|
||||
* path. */
|
||||
int32_t st = kv.state_slot(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st;
|
||||
pay[np + i] = st;
|
||||
/* EVERY conv group, at its own row. This array feeds `DeriveInput::conv_slot`
|
||||
* and NOTHING ELSE -- a conv KERNEL reads its slot from
|
||||
* RadKVGroupBatch::state_index, which is filled per group a few lines below and
|
||||
* always has been. See the note at conv_window_ in init(). */
|
||||
/* Every conv group, at its own row. Feeds only DeriveInput::conv_slot; conv
|
||||
* kernels read RadKVGroupBatch::state_index (see conv_window_ in batch.h). */
|
||||
if (kvgeom_.g[gi].kind == RAD_KV_CONV)
|
||||
s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
|
||||
}
|
||||
s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
|
||||
t += e.n_tokens;
|
||||
|
||||
/* THE TOKENS THIS SEQUENCE ACTUALLY HOLDS, WHICH IS NOT min(length, window).
|
||||
*
|
||||
* `seqused` is a count from index 0 of the BLOCK TABLE, and the table of a windowed
|
||||
* group is REBASED at `first_block_pos` once the window slides -- kvgeom_.slot() above
|
||||
* subtracts exactly that. So the count the kernel needs is the held span, and the held
|
||||
* span is a whole number of BLOCKS: recycling leaves `window_blocks` of them, whose
|
||||
* last one is partially filled by however far past a block boundary the sequence has
|
||||
* got. `min(length, window)` reports the full window every time and therefore claims
|
||||
* up to block_size - 1 positions that were never written this pass -- and they are the
|
||||
* ones at the END of the table, which every attention kernel reads as the NEWEST
|
||||
* context. Their bytes are whatever the recycled block held.
|
||||
*
|
||||
* A NON-CAUSAL windowed group is where this bites: every query row attends to those
|
||||
* stale slots at full weight, and acceptance falls off a cliff at exactly the context
|
||||
* where the window first slides. A causal group hides the same defect, because a stale
|
||||
* slot past the query is masked anyway.
|
||||
*
|
||||
* No clamp to `window` any more: block granularity means the held span can exceed the
|
||||
* window by less than a block, and dropping that from the FRONT of the count would
|
||||
* drop the NEWEST tokens rather than the oldest. Attending to a few extra old
|
||||
* positions is what paging a sliding window costs, and it is what vLLM does too. */
|
||||
/* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
|
||||
* from index 0 of the block table, which a window group rebases at `first_block_pos`
|
||||
* (as slot() does above). min(length, window) would claim up to block_size - 1
|
||||
* unwritten slots at the end of the table, read as the newest context; a non-causal
|
||||
* window group would attend to them. Do not clamp to `window` either: the held span
|
||||
* may exceed it by under a block, and clamping would drop the newest tokens. Attending
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same). */
|
||||
int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
|
||||
if (used < 0) used = 0;
|
||||
g.h_used[i] = (int32_t)used;
|
||||
@@ -819,8 +752,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
(int)g.sidx_pitch);
|
||||
}
|
||||
}
|
||||
/* A state group's rows are one slot a sequence: restaged whole, since they are n_seq
|
||||
* words and one range. */
|
||||
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
|
||||
if (!L.paged) {
|
||||
stage(g.bt_fix, np, n_seq);
|
||||
np += n_seq;
|
||||
@@ -852,8 +784,7 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
b.block_size = L.block_size;
|
||||
b.max_blocks = pitch;
|
||||
|
||||
/* The bytes cross in build()'s one slab copy: a group's arrays are carved out of
|
||||
* the same slab as everything else and there is nothing group-shaped about them. */
|
||||
/* The group's arrays are uploaded with the rest of the slab in build(). */
|
||||
}
|
||||
}
|
||||
pay_words_ = np;
|
||||
@@ -870,10 +801,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
if (plan.spec_is_tree) {
|
||||
/* spec_parent is in the ABI and its pool is allocated, but no drafter in v1 emits a tree,
|
||||
* so the parent chain and the positions a tree implies are not written. Saying so beats
|
||||
* filling the array with the linear-chain answer, which would verify a tree against the
|
||||
* wrong causal mask and produce fluent wrong text. */
|
||||
/* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
|
||||
* and positions are not written. Filling in the linear-chain answer would verify a tree
|
||||
* against the wrong causal mask. */
|
||||
RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
|
||||
return nullptr;
|
||||
}
|
||||
@@ -881,7 +811,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
Set& s = set_;
|
||||
const int64_t n_seq = (int64_t)plan.e.size();
|
||||
|
||||
/* THE CONTEXT BOUND, rounded (see bound_bucket), before anything that derives from it. */
|
||||
/* The context bound, rounded (see bound_bucket), before anything that derives from it. */
|
||||
int32_t max_ctx = 0, max_q = 0;
|
||||
for (const StepEntry& e : plan.e) {
|
||||
if (e.ctx_len > max_ctx) max_ctx = e.ctx_len;
|
||||
@@ -889,20 +819,15 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
const int64_t ctx_bound = std::min<int64_t>(bound_bucket(max_ctx, k_bound_tokens), max_ctx_);
|
||||
|
||||
/* THE BLOCK-TABLE PITCH OF EVERY GROUP FIRST, because it sizes the build's span of the ring:
|
||||
* the span is the fixed prefix and exactly the rows build_groups will pack. The pitch is a
|
||||
* property of THIS STEP, not of the deployment -- a rectangle wide enough for max_ctx would be
|
||||
* megabytes staged and copied on every decode step to carry a few hundred live entries.
|
||||
/* Every group's block-table pitch comes first because it sizes the ring span. The pitch is
|
||||
* per step, not max_ctx wide, so decode does not stage megabytes of empty rows.
|
||||
*
|
||||
* IT IS A FUNCTION OF THE CONTEXT BOUND, so the two move on the same step. Both are in a
|
||||
* recorded pass's key, and rounded separately they cross their buckets on different steps --
|
||||
* every crossing of either is a pass recorded again, so twice the recordings for nothing. A
|
||||
* row holds the sequence's context plus this step's tokens plus the scheduler's draft
|
||||
* lookahead, which is at most two speculative windows, and the pitch is that rounded up to
|
||||
* the bound's own grid. A table longer than that (none is, today) takes its own rounded
|
||||
* length, which is correct and only costs the alignment. */
|
||||
* It derives from the context bound so both cross their buckets on the same step (both key a
|
||||
* recorded pass; separate rounding would double the re-recordings). A row holds context plus
|
||||
* this step's tokens plus at most two speculative windows of draft lookahead, rounded up to
|
||||
* the bound's grid. A longer table takes its own rounded length. */
|
||||
const int64_t reach = ctx_bound + max_q + 2 * ((int64_t)std::max(plan.n_spec, 0) + 1);
|
||||
int64_t pay_need = 0; /* the payload if every row were restaged whole */
|
||||
int64_t pay_need = 0; /* payload if every row were restaged whole */
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
int64_t pitch = 1;
|
||||
if (kvgeom_.g[gi].paged) {
|
||||
@@ -920,9 +845,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
pitch_[gi] = pitch;
|
||||
pay_need += n_seq * pitch * (int64_t)sizeof(int32_t);
|
||||
}
|
||||
/* THE SPAN: the fixed prefix, the payload, and the range list behind it, each at its bound --
|
||||
* a range a row or state group plus one a k_range_max of payload. What the build turns out to
|
||||
* use is usually far less, and only that is held once it is known. */
|
||||
/* The span: fixed prefix, payload and range list, each at its bound (one range per row or
|
||||
* state group plus one per k_range_max of payload). Only what the build uses is held once
|
||||
* known. */
|
||||
const int64_t max_ranges = pay_need / k_range_max + n_seq * (int64_t)s.groups.size() + 1;
|
||||
int64_t off = 0;
|
||||
const int64_t need = align_up(s.bt_base + align_up(pay_need, 16) +
|
||||
@@ -935,8 +860,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
|
||||
/* ---------------------------------------------------------- tokens, positions, boundaries */
|
||||
int64_t k = 0;
|
||||
/* PER HALF as well as overall: a mixed step`s max_q is its prefill chunk, and a block that
|
||||
* issues the decode rows separately must not select their kernel band with it. */
|
||||
/* Also per half: a mixed step's max_q is its prefill chunk, which must not select the kernel
|
||||
* band for separately issued decode rows. */
|
||||
int32_t max_q_dec = 0, max_q_pf = 0;
|
||||
int n_ck = 0;
|
||||
int64_t n_out = 0, n_dout = 0;
|
||||
@@ -952,26 +877,24 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
/* The advance indexes the card's StepSlots by this, and there are max_seqs of them. */
|
||||
/* The advance indexes the card's max_seqs StepSlots by this. */
|
||||
if (e.card < 0 || e.card >= max_seqs_) {
|
||||
RAD_ERR("step plan row %lld: sequence %llu has card index %d, outside the %lld step "
|
||||
"slots", (long long)i, (unsigned long long)e.seq, (int)e.card,
|
||||
(long long)max_seqs_);
|
||||
return nullptr;
|
||||
}
|
||||
/* THE MTP HEAD READS ONE POSITION AHEAD. Its index i pairs the trunk`s hidden state at i
|
||||
* with the EMBEDDING OF THE TOKEN AT i + 1, and predicts i + 2 (rad_block_mtp_fp8.h). The
|
||||
* shift is applied once, here, so that no kernel and no plugin carries it -- and
|
||||
* token_at() reaches the drafter`s own earlier rounds through `draft` exactly as a verify
|
||||
* step reaches its proposal. StepPlan::tok_shift says how far, because it is the HEAD's
|
||||
* indexing and not the draft round's: DFlash2 is a draft pass that shifts by nothing. */
|
||||
/* Token shift (StepPlan::tok_shift): the MTP head pairs hidden state i with the token
|
||||
* at i + 1 and predicts i + 2 (rad_block_mtp_fp8.h). Applied only here, so no kernel or
|
||||
* plugin carries it; token_at() reaches earlier draft rounds through `draft`. DFlash2
|
||||
* passes use 0. */
|
||||
const int64_t shift = plan.tok_shift;
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) {
|
||||
s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
|
||||
s.h_pos[k + j] = e.ctx_len + j;
|
||||
}
|
||||
/* THE ROTARY POSITION OF EACH ROW, at the row's own position -- the draft head's rows
|
||||
* rotate at the index they write, not at the token they embed. Planes of n_tok. */
|
||||
/* Rotary position of each row at its own position (draft-head rows rotate at the index
|
||||
* they write, not the token they embed). Three planes of n_tok. */
|
||||
if (mm_on_) {
|
||||
const mm::RopeLayout* rl =
|
||||
(e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
|
||||
@@ -986,7 +909,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
if (v[1] != v[0] || v[2] != v[0]) rope_mixed = 1;
|
||||
}
|
||||
if (e.req && e.req->media && !e.req->media->items.empty()) {
|
||||
/* The staging is the last upload's until that upload has run. */
|
||||
/* Wait until the last upload from the staging has run. */
|
||||
if (mm_ev_live_) {
|
||||
if (rad_event_sync(mm_ev_) < 0) return nullptr;
|
||||
mm_ev_live_ = false;
|
||||
@@ -997,23 +920,16 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
if (e.ckpt_tok >= 0 && e.ckpt_slot >= 0) {
|
||||
/* checkpoint_tok indexes THIS STEP's tokens, so it is the sequence's base plus the
|
||||
* offset the scheduler chose -- which the chunk split guarantees is the last token of
|
||||
* a checkpoint interval (§7.3). */
|
||||
/* checkpoint_tok indexes this step's tokens: the sequence's base plus the offset the
|
||||
* scheduler chose, the last token of a checkpoint interval (§7.3). */
|
||||
s.h_cktok[n_ck] = (int32_t)(k + e.ckpt_tok);
|
||||
s.h_ckslot[n_ck] = e.ckpt_slot;
|
||||
++n_ck;
|
||||
}
|
||||
/* Which of this step's tokens the sampler wants logits for. `produces_token` is the
|
||||
* scheduler's answer to "is this entry's last token the sequence's last" -- false for the
|
||||
* middle chunk of a long prefill, which therefore contributes no row and does not touch
|
||||
* the lm_head at all. At a speculative verify every drafted position needs a distribution
|
||||
* to accept against, so the entry contributes 1 + n_spec rows and not one. */
|
||||
/* AN MTP PASS NAMES ITS OWN ROWS, and they are rows of the PREVIOUS step: the head
|
||||
* gathers the trunk`s hidden state for the positions it continues from, and which those
|
||||
* are is not a function of this batch at all. One per token of the pass, consecutive from
|
||||
* `hidden_row` -- which is a single row for a draft round and a whole chunk for a history
|
||||
* pass. See StepEntry::hidden_row. */
|
||||
/* Rows the sampler wants logits for. An entry with `hidden_row` names its own rows
|
||||
* (StepEntry::hidden_row), consecutive from it. Otherwise a `produces_token` entry gives
|
||||
* 1 + n_spec rows (every drafted position needs a distribution), and a mid-prefill chunk
|
||||
* gives none. */
|
||||
if (e.hidden_row >= 0) {
|
||||
const int32_t nr = e.hidden_n > 0 ? e.hidden_n : e.n_tokens;
|
||||
for (int32_t j = 0; j < nr; ++j) s.h_out[n_out++] = e.hidden_row + j;
|
||||
@@ -1022,13 +938,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
for (int32_t j = 0; j <= e.n_spec; ++j) s.h_out[n_out++] = first + j;
|
||||
}
|
||||
if (e.draft_out) s.h_dout[n_dout++] = (int32_t)(k + e.n_tokens - 1);
|
||||
/* RADIANCE_DFLASH_TRACE prints what a drafter pass actually consumes -- the pass kind, the
|
||||
* absolute positions, and the token ids at them. A block-diffusion drafter reads an ANCHOR
|
||||
* the target has already chosen followed by mask ids, and every way of getting that wrong
|
||||
* (an anchor one token stale, a mask id that is an ordinary token, a position base that
|
||||
* disagrees with the KV the context pass wrote) produces the same symptom from outside:
|
||||
* acceptance near zero and output still exactly correct. So it is printed rather than
|
||||
* reasoned about. */
|
||||
/* RADIANCE_DFLASH_TRACE logs each drafter pass's kind, positions and token ids. A wrong
|
||||
* anchor, mask id or position base shows only as near-zero acceptance with correct
|
||||
* output. */
|
||||
static const bool trace = std::getenv("RADIANCE_DFLASH_TRACE") != nullptr;
|
||||
if (trace && plan.draft_pass != 0) {
|
||||
std::string ln = fmt("df %s seq %d pos %d..%d tok",
|
||||
@@ -1053,11 +965,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* THE SCORED ROWS (Request::score), after every row the sampler reads: a row at each token of
|
||||
* a scoring entry's prefill chunk, in entry order, which is the order Engine::score_rows walks
|
||||
* to map them back to a request and a position. They come after so that nothing indexing the
|
||||
* sampled rows -- the sampler, the card's acceptance (dev_out) -- sees them at all. A trunk
|
||||
* pass only: a draft pass's rows are the head's, not the model's. */
|
||||
/* Scored rows (Request::score): one per token of a scoring entry's prefill chunk, in entry
|
||||
* order (the order Engine::score_rows maps back). Appended after the sampled rows so the
|
||||
* sampler and the card's acceptance (dev_out) never see them. Trunk passes only. */
|
||||
if (cfg_.kld() && plan.draft_pass == 0 && plan.tok_shift == 0) {
|
||||
int64_t at = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
@@ -1073,11 +983,10 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* THE PROMPT THAT FOLLOWS: the last sequence's next tokens, up to a step of them, after this
|
||||
* step's own (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk with
|
||||
* more of its sequence still to run -- a draft pass's tokens are shifted and it reads no such
|
||||
* data -- and bounded by the tokens the request has, so a re-prefill after preemption reads
|
||||
* its own output as the prompt's continuation, as token_at does. */
|
||||
/* Up to a step of the last sequence's following tokens, after this step's own
|
||||
* (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by
|
||||
* the tokens the request has; like token_at, a re-prefill after preemption continues into its
|
||||
* own output. */
|
||||
int64_t n_ahead = 0;
|
||||
if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) {
|
||||
const StepEntry& e = plan.e[(size_t)(n_seq - 1)];
|
||||
@@ -1089,8 +998,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* From here the manager's change marks are taken, so a build that stops before its upload
|
||||
* is issued on every rank leaves the card's tables unknown to the next one. */
|
||||
/* build_groups consumes the manager's change marks, so any failure before every rank's
|
||||
* upload is issued must forget_tables(). */
|
||||
if (int st = build_groups(plan, kv, s, o); st < 0) {
|
||||
forget_tables();
|
||||
RAD_ERR("step batch: build_groups -> %s", rad_strerror(st));
|
||||
@@ -1105,41 +1014,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return nullptr;
|
||||
}
|
||||
RadCopyRange* const rng = reinterpret_cast<RadCopyRange*>(ring_.host + off + rng_at);
|
||||
std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
|
||||
if (n_rng > 0) std::memcpy(rng, ranges_.data(), (size_t)n_rng * sizeof(RadCopyRange));
|
||||
const int64_t used = align_up(rng_at + n_rng * (int64_t)sizeof(RadCopyRange), k_carve_align);
|
||||
|
||||
/* ---------------------------------------------------------- ONE COPY PER RANK
|
||||
/* ---------------------------------------------------------- one copy per rank
|
||||
*
|
||||
* carve() lays out the host span and every rank's device slab in the same order, at the same
|
||||
* sizes, aligning the OFFSET and not the pointer. So below bt_base the device slab is a
|
||||
* byte-for-byte mirror of the host span, and a whole step's staging -- the token and position
|
||||
* arrays, the per-sequence arrays, and every KV group's slot map, seqused and state index --
|
||||
* crosses in one transfer, with the block-table entries that changed riding the same dispatch
|
||||
* as ranges.
|
||||
* Below bt_base the device slab mirrors the host span byte for byte (carve() aligns offsets,
|
||||
* not pointers), so a step's whole staging crosses in one transfer, with changed block-table
|
||||
* entries as ranges in the same dispatch. Copying per array would move fewer bytes, but a
|
||||
* decode step has about 2 KB live across dozens of arrays, where per-transfer dispatch cost
|
||||
* dominates; the unused tail costs a few microseconds of DMA. Since everything crosses every
|
||||
* step, `num_accepted` needs no gate.
|
||||
*
|
||||
* One copy per ARRAY would carry only the prefix the step used, which is the right trade when
|
||||
* the arrays are full and the wrong one when they are not. A decode step has about two
|
||||
* kilobytes of live staging spread over dozens of arrays -- one per array, per KV group, per
|
||||
* rank -- and at that size the bytes are the smallest part of the cost: each transfer costs a
|
||||
* dispatch plus the dependent gap behind it, which together dominate the DMA.
|
||||
*
|
||||
* The over-copy is the unused tail of the arrays sized by max_num_batched_tokens. At a full
|
||||
* prefill chunk it is nothing at all -- the same bytes cross either way and only the launch
|
||||
* count differs -- and at decode a few microseconds of DMA buys back dozens of dispatches.
|
||||
*
|
||||
* It also removes the need for a gate on `num_accepted`: the kernels read that operand
|
||||
* whenever the DEPLOYMENT speculates, not only when the step drafted, so copying it
|
||||
* conditionally leaves them reading the arena on exactly the step that had something to roll
|
||||
* back. Everything in the slab crosses on every step.
|
||||
*
|
||||
* AND IT STAYS ON THE COMPUTE STREAM, which is not an oversight. Moving it to a third,
|
||||
* staging stream -- so that a producer on the second lane could see its batch without
|
||||
* queueing behind compute -- is substantially SLOWER at every concurrency, byte-identical.
|
||||
* Sharing the queue is load-bearing: the split has to pay for two orderings the queue gives
|
||||
* away, and the one that hurts is the copy waiting on the event that says the step which last
|
||||
* read this slab is done -- it cannot start until the previous step has drained, where riding
|
||||
* the compute stream lets it issue in line. That is three cross-stream round-trips a step a
|
||||
* rank against a prize of a few percent. Do not rebuild the staging stream. */
|
||||
* The copy stays on the compute stream. A separate staging stream is slower at every
|
||||
* concurrency: the copy must wait on an event for the step that last read the slab, adding
|
||||
* cross-stream round-trips, while on the compute stream it issues in line. Do not move it. */
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
const int st = rad_memcpy_ranges_async(s.dev[r], ring_.host + off, s.bt_base, rng, n_rng,
|
||||
ranks_[r].stream);
|
||||
@@ -1150,13 +1039,12 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
}
|
||||
}
|
||||
|
||||
/* Derived metadata reads the host staging, so it runs after the fills and before the event. */
|
||||
/* Derivations read the host staging: after the fills, before the event. */
|
||||
RAD_TRY_NULL(run_derivations(plan, s));
|
||||
|
||||
/* ---------------------------------------------------------- encoder rows
|
||||
* Behind the slab on every rank's stream, so the rows are on the card before any kernel of the
|
||||
* pass reads them: rank 0 takes the staged rows, every other rank the zeros that make the
|
||||
* vocabulary reduction count each row once. */
|
||||
* Behind the slab on every rank's stream. Rank 0 gets the staged rows, the others zeros, so the
|
||||
* vocabulary reduction counts each row once. */
|
||||
if (n_mm > 0) {
|
||||
const int64_t bytes = n_mm * n_embd_ * (int64_t)sizeof(uint16_t);
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -1200,11 +1088,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.kv = o.kv[r].data();
|
||||
B.draft_pass = plan.draft_pass;
|
||||
B.n_spec = plan.n_spec;
|
||||
/* PASSED WHENEVER THE DEPLOYMENT SPECULATES, not only on the steps that drafted. A step that
|
||||
* declines to draft still FOLLOWS one that did, and the linear kernels need to know how much
|
||||
* of that step survived before they can start. Gating this on the step's own draft count
|
||||
* makes the kernels fall back to their absent-operand default of 1 on exactly the step that
|
||||
* had something to roll back. */
|
||||
/* Passed whenever the deployment speculates, not only on steps that drafted: a step
|
||||
* without drafts may follow one that had drafts, and the linear kernels need its accepted
|
||||
* count instead of their absent-operand default of 1. */
|
||||
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
|
||||
B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */
|
||||
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
|
||||
@@ -1224,8 +1110,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
|
||||
B.n_ahead = n_ahead;
|
||||
}
|
||||
/* THE FLIGHT, behind everything that reads this span: the upload, and the derivation copies
|
||||
* run_derivations issued above. */
|
||||
/* Record the flight behind everything reading this span: the upload and the derivation
|
||||
* copies. */
|
||||
const int ev = ev_free_.back();
|
||||
ev_free_.pop_back();
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -1245,8 +1131,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
return &o.batch[0];
|
||||
}
|
||||
|
||||
/* The batch the last build produced for one rank. Same numbers as build()'s return; different
|
||||
* device pointers, because each rank reads its own slab. */
|
||||
const RadBatch* BatchBuilder::batch_for(int rank) const {
|
||||
if (out_last_ < 0) return nullptr;
|
||||
const Out& o = out_[out_last_];
|
||||
@@ -1315,9 +1199,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
if (seg_p > max_seg) max_seg = seg_p;
|
||||
}
|
||||
}
|
||||
/* Coordinates in planes of n_patch, which is what makes planes 0 and 1 a dense [2, n_patch]. */
|
||||
/* Coordinates in planes of n_patch, so planes 0 and 1 form a dense [2, n_patch]. */
|
||||
{
|
||||
std::vector<int32_t> tmp;
|
||||
std::vector<int32_t>& tmp = enc_coord_tmp_;
|
||||
int64_t at = 0;
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
|
||||
+119
-172
@@ -1,20 +1,11 @@
|
||||
/* batch.h -- the step batch, built ONCE PER STEP BY THE CORE and shared by every layer and every
|
||||
* KV group (spec §8).
|
||||
/* batch.h -- the step batch, built once per step by the core and shared by every layer and every
|
||||
* KV group (spec §8). Unlike vLLM, which rebuilds the metadata per KV-cache group, there is one
|
||||
* build and every consumer reads the same buffers.
|
||||
*
|
||||
* vLLM builds this per KV-cache group, per layer, in Python, and that shape is what this file
|
||||
* exists to avoid: a model whose linear-attention layers fall into several KV-cache groups runs
|
||||
* the metadata builder once per group, and every run after the first produces values identical to
|
||||
* it -- dozens of tiny dispatches a step for numbers already computed, and host time on the step
|
||||
* path is time the GPU spends idle.
|
||||
*
|
||||
* So: one build, one owner, every consumer reads the same buffers.
|
||||
*
|
||||
* Everything here comes out of pools sized at max_tok / max_seqs at init. Nothing on this path
|
||||
* allocates. Staging is PINNED HOST memory crossing in one async copy a rank, out of a RING so
|
||||
* that a build is never written while an earlier build's copy is still reading it -- the cost of
|
||||
* getting that wrong is a torn block table, which shows up as a sequence reading another
|
||||
* sequence's KV and reads as a model quality problem -- and so that the host can stage several
|
||||
* passes ahead of the card without waiting for any of them.
|
||||
* Everything comes from pools sized at max_tok / max_seqs at init; nothing on this path
|
||||
* allocates. Staging is pinned host memory, uploaded in one async copy per rank, carved from a
|
||||
* ring so that a build never overwrites staging an earlier upload is still reading (that would
|
||||
* tear a block table) and the host can stage several passes ahead of the card.
|
||||
*/
|
||||
#pragma once
|
||||
#include "advance.h"
|
||||
@@ -26,63 +17,52 @@
|
||||
namespace rad {
|
||||
|
||||
/* One sequence's participation in one step. The scheduler fills these; the builder turns them
|
||||
* into device arrays and touches nothing else. */
|
||||
* into device arrays. */
|
||||
struct StepEntry {
|
||||
const Request* req = nullptr;
|
||||
uint64_t seq = 0; /* the KV manager's key -- the request id */
|
||||
int32_t slot = -1; /* scheduler slot: where the scheduler keeps the request */
|
||||
uint64_t seq = 0; /* the KV manager's key (the request id) */
|
||||
int32_t slot = -1; /* the scheduler's slot for the request */
|
||||
int32_t card = -1; /* the card's StepSlot index, [0, max_seqs): the sequence
|
||||
* identity in this batch (SchedReq::card) */
|
||||
int32_t n_tokens = 0; /* query length this step */
|
||||
int32_t ctx_len = 0; /* computed tokens BEFORE this step -- the first token's position */
|
||||
int32_t ctx_len = 0; /* tokens computed before this step: the first token's position */
|
||||
int32_t n_spec = 0; /* draft tokens included in n_tokens (decode only) */
|
||||
/* HOW MANY TOKENS THE PREVIOUS STEP COMMITTED, and it is ONE-BASED: the token that step was
|
||||
* given plus however many of its drafts survived. Both linear kernels read it that way --
|
||||
/* Tokens the previous step committed, one-based: its input token plus its accepted drafts.
|
||||
* gdn_conv_update reads its rolling window at `num_accepted - 1` and gdn_recurrent_update
|
||||
* takes the state the (num_accepted)th token left -- so 1 is the ordinary decode step that
|
||||
* drafted nothing, which is exactly what they assume when the operand is absent. Zero is not
|
||||
* a value either of them can read; the scheduler's own `SchedReq::n_accepted` counts DRAFTS,
|
||||
* which is one less. */
|
||||
* takes the state the (num_accepted)th token left, so 1 is a plain decode step (also their
|
||||
* default when the operand is absent) and 0 is invalid. SchedReq::n_accepted counts drafts
|
||||
* only, one less. */
|
||||
int32_t n_accepted = 1;
|
||||
int32_t conv_cursor = 0; /* read offset inside the rolling conv window (§10) */
|
||||
int32_t ckpt_tok = -1; /* token index WITHIN this entry to snapshot at, or -1 */
|
||||
int32_t ckpt_slot = -1;
|
||||
/* THE SNAPSHOT THIS ENTRY RESUMES FROM, or -1. Set on the first step after a prefix hit and
|
||||
* never again: the recurrent half of a hit is carried by this and by nothing else, because
|
||||
* the adopted blocks describe the attention layers only. */
|
||||
/* Snapshot this entry resumes from, or -1. Set only on the first step after a prefix hit; the
|
||||
* adopted blocks cover attention only, so this is the sole carrier of the recurrent state. */
|
||||
int32_t ckpt_restore = -1;
|
||||
const int32_t* draft = nullptr; /* the drafter's proposal, appended after the committed tail */
|
||||
int32_t n_draft = 0;
|
||||
/* WHICH LOGITS ROW OF THE STEP JUST RUN holds the hidden state this entry continues from,
|
||||
* or -1 for the ordinary rule. It exists for the MTP drafter's history pass: the trunk step
|
||||
* produced 1 + n_spec rows for a verifying sequence, and the head gathers the run of them
|
||||
* starting here. Filled into `out_ids`, so the head's gather picks them out of the same
|
||||
* buffer.
|
||||
*
|
||||
* A pass that gathers its OWN output names rows of itself through the same field -- the
|
||||
* DFlash2 query pass does, because the rows it wants logits for are the mask positions of the
|
||||
* block it just ran. Which buffer out_ids indexes is the architecture block's business; this
|
||||
* is only the list. */
|
||||
/* First logits row, written into `out_ids`, that this entry reads, or -1 for the default
|
||||
* rule. The MTP history pass uses it to gather the 1 + n_spec trunk rows of a verifying
|
||||
* sequence; the DFlash2 query pass uses it to name the mask rows of its own block. Which
|
||||
* buffer out_ids indexes is up to the architecture block. */
|
||||
int32_t hidden_row = -1;
|
||||
/* HOW MANY ROWS FROM `hidden_row`, or 0 for the rule that predates it: one a token. The MTP
|
||||
* history pass wants exactly its n_tokens and says 0; the DFlash2 query pass runs `block`
|
||||
* tokens and wants the block-1 mask rows, so it says block-1 and starts one row in. */
|
||||
/* Rows from `hidden_row`, or 0 for one per token. The MTP history pass uses 0; the DFlash2
|
||||
* query pass runs `block` tokens and uses block-1, starting one row in. */
|
||||
int32_t hidden_n = 0;
|
||||
/* THIS ENTRY'S LAST ROW IS DRAFT ROUND 1 (RadBatch::draft_out_ids): set on a history-pass
|
||||
* entry whose sequence drafts, whose rows end with the position round 1 continues from. */
|
||||
/* This entry's last row is where draft round 1 continues from (RadBatch::draft_out_ids).
|
||||
* Set on a history-pass entry whose sequence drafts. */
|
||||
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). */
|
||||
/* The drafts came from prompt lookup, not the declared drafter. They count toward reported
|
||||
* acceptance but not the adaptive window's estimate of 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
|
||||
* are advance.h's row descriptor: the verify step's token row of the row's first verified
|
||||
* position, its first sampled row (-1 for none), and the mode's own number. A verify step's
|
||||
* entries always carry them, for its acceptance. */
|
||||
/* Device row: the card overwrites its tokens, positions, rollback count and slots from the
|
||||
* StepSlot before the pass runs (advance.h); `ctx_len` is then only an upper bound for the
|
||||
* host-side ceilings. dev_tok/dev_out/dev_aux are advance.h's row descriptor: the verify
|
||||
* step's token row of the first verified position, the first sampled row (-1 for none), and
|
||||
* the mode's own number. A verify step's entries always carry them. */
|
||||
bool dev = false;
|
||||
int32_t dev_tok = 0;
|
||||
int32_t dev_out = -1;
|
||||
@@ -93,20 +73,17 @@ struct StepPlan {
|
||||
std::vector<StepEntry> e;
|
||||
int64_t n_tok = 0;
|
||||
int phase = RAD_PHASE_DECODE;
|
||||
/* THE DRAFT PASS, straight through to RadBatch::draft_pass. 0 is a trunk step; r > 0 runs
|
||||
* only the draft head, r < 0 is a history pass. */
|
||||
/* Passed to RadBatch::draft_pass. 0 is a trunk step, r > 0 runs only the draft head, r < 0
|
||||
* is a history pass. */
|
||||
int draft_pass = 0;
|
||||
/* HOW FAR AHEAD OF ITS POSITION A ROW READS ITS TOKEN. The MTP head pairs the trunk's hidden
|
||||
* state at index i with the embedding of the token at i + 1 (rad_block_mtp_fp8.h), so its
|
||||
* passes say 1 and the shift is applied once, here, rather than in a kernel. It is NOT a
|
||||
* property of "being a draft pass": DFlash2's query block embeds the token at its own
|
||||
* position -- the anchor at the row that holds it and a mask everywhere after -- and says 0.
|
||||
* Deriving it from `draft_pass` instead feeds such a drafter the token one past its anchor. */
|
||||
/* How far past its position a row reads its token. The MTP head pairs hidden state i with
|
||||
* the token at i + 1 (rad_block_mtp_fp8.h), so its passes use 1. Do not derive this from
|
||||
* `draft_pass`: DFlash2's query block embeds the token at its own position and uses 0. */
|
||||
int tok_shift = 0;
|
||||
int n_spec = 0; /* the batch-wide speculative window */
|
||||
bool spec_is_tree = false; /* a tree drafter fills spec_parent; a chain leaves it null */
|
||||
/* THE SPLIT, for a block that issues over each half separately. Sorted above, so the decode
|
||||
* rows are sequences [0, n_seq_decode) and the prefill chunks are the rest. */
|
||||
/* Decode/prefill split, for a block that issues each half separately. Entries are sorted so
|
||||
* decode rows are sequences [0, n_seq_decode) and prefill chunks follow. */
|
||||
int64_t n_seq_decode = 0;
|
||||
int64_t n_tok_decode = 0;
|
||||
int32_t max_q_len = 0;
|
||||
@@ -122,58 +99,52 @@ struct StepPlan {
|
||||
/* ------------------------------------------------------------------ the builder */
|
||||
class BatchBuilder {
|
||||
public:
|
||||
/* `prog` is non-const because derived buffers are written into the arena, and the arena
|
||||
* pointer lands in BufferInfo::ptr after the buffer plan runs. */
|
||||
/* What the builder needs about one rank: which card its slab lives on, which stream its
|
||||
* upload rides, and which Program holds the arena a derived buffer is copied into. */
|
||||
/* One rank: the card its slab lives on, the stream its upload runs on, and the Program whose
|
||||
* arena derived buffers are copied into. */
|
||||
struct RankIO {
|
||||
int device = 0;
|
||||
RadStream stream = nullptr;
|
||||
Program* prog = nullptr;
|
||||
};
|
||||
|
||||
/* `prog` is non-const because derived buffers are written into its arena, whose pointer lands
|
||||
* in BufferInfo::ptr after the buffer plan runs. */
|
||||
int init(Program& prog, const Config& cfg, const ChunkGeometry& geo,
|
||||
const KVGeom& kvg, const std::vector<RankIO>& ranks);
|
||||
void fini();
|
||||
|
||||
/* The bytes init() allocates on each rank's card -- the step slab and, with an encoder, the
|
||||
* media staging -- computed without allocating, for the VRAM budget. -1 when the program is
|
||||
* one init() would refuse. */
|
||||
/* Bytes init() allocates on each rank's card (the step slab and, with an encoder, the media
|
||||
* regions), computed without allocating, for the VRAM budget. -1 if init() would refuse. */
|
||||
static int64_t device_bytes(Program& prog, const Config& cfg, const KVGeom& kvg);
|
||||
|
||||
/* Build the batch for this step. The returned pointer is stable until the kOut-th next call
|
||||
* and is the pointer the rank threads share -- because the ranks share an address space, the
|
||||
* batch is shared by pointer rather than broadcast (spec §1). Null on a device failure, which
|
||||
* is fatal for the step. */
|
||||
/* Build the batch for this step. The returned pointer stays valid for the next kOut - 1
|
||||
* calls and is shared by pointer across rank threads (spec §1). Null on a device failure,
|
||||
* which is fatal for the step. */
|
||||
const RadBatch* build(const StepPlan& plan, const IKVManager& kv, int step);
|
||||
|
||||
/* The batch the LAST build produced for one rank. Same contents as build()'s return
|
||||
* except for the device pointers, which name that rank's staging slab. */
|
||||
/* The last build's batch for one rank: build()'s result with that rank's slab pointers. */
|
||||
const RadBatch* batch_for(int rank) const;
|
||||
|
||||
/* THE ADVANCE'S VIEW OF THE LAST BUILD on one rank: the slab and every offset in it. The mode,
|
||||
* the round, the slot state and the inputs are the caller's (advance.h). */
|
||||
/* The last build's slab and offsets on one rank, for the advance. The caller supplies mode,
|
||||
* round, slot state and inputs (advance.h). */
|
||||
AdvanceArgs advance_args(int rank) const;
|
||||
|
||||
/* THE LONGEST SEQUENCE A BATCH CAN DESCRIBE, in tokens: what the block-table rows were sized
|
||||
* for at init. A position at or past it has no column to be addressed through. */
|
||||
/* Longest sequence a batch can describe, in tokens, as sized into the block-table rows at
|
||||
* init. A position at or past it cannot be addressed. */
|
||||
int64_t max_ctx() const { return max_ctx_; }
|
||||
|
||||
/* AN ENCODER PASS (RadBatch::enc): the patches of whole segments of one or more media items,
|
||||
* staged into every rank's encoder input -- each rank runs the tower on its own card, so none
|
||||
* waits on another's output. Returns rank 0's batch like build(); batch_for() serves the rest.
|
||||
* The caller synchronises every rank's stream before the next encoder build, which it has to
|
||||
* anyway to read the pass's rows back. */
|
||||
/* An encoder pass (RadBatch::enc): patches of whole segments of one or more media items,
|
||||
* staged into every rank's encoder input, since each rank runs the tower itself. Returns rank
|
||||
* 0's batch like build(); batch_for() serves the rest. The caller must synchronise every
|
||||
* rank's stream before the next encoder build. */
|
||||
struct EncoderPart {
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
/* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts,
|
||||
* and its modalities are RadBatch::enc. */
|
||||
/* `enc` is the encoder the pass runs: its patch width, pass size and merge bound the parts;
|
||||
* its modalities become RadBatch::enc. */
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step,
|
||||
const RadEncoderDecl& enc);
|
||||
bool has_encoder() const { return mm_on_; }
|
||||
|
||||
|
||||
private:
|
||||
struct Group {
|
||||
@@ -181,9 +152,8 @@ private:
|
||||
int64_t block_size = 0;
|
||||
int64_t max_blocks = 0;
|
||||
int32_t* h_slot = nullptr; int32_t* d_slot = nullptr;
|
||||
/* The group's block tables on the card: a fixed place in the table region, `bt_fix`
|
||||
* int32 past its start, max_seqs rows of this build's pitch. They have no host twin -- a
|
||||
* build stages only what changed. */
|
||||
/* The group's block tables on the card: max_seqs rows of this build's pitch, `bt_fix`
|
||||
* int32 into the table region. No host twin; a build stages only what changed. */
|
||||
int64_t bt_fix = 0;
|
||||
int32_t* d_bt = nullptr;
|
||||
int32_t* h_used = nullptr; int32_t* d_used = nullptr;
|
||||
@@ -191,38 +161,27 @@ private:
|
||||
int64_t sidx_pitch = 1; /* columns per sequence in h_sidx/d_sidx */
|
||||
};
|
||||
|
||||
/* THE LAYOUT OF A BUILD: every array's place on the card and in host staging, at the same
|
||||
* offset in both, so that one copy moves a whole build.
|
||||
/* Layout of a build: every array at the same offset on the card and in host staging, so one
|
||||
* copy moves a whole build.
|
||||
*
|
||||
* THE DEVICE SLAB IS ONE PER RANK AND IS NEVER DOUBLE BUFFERED. A build's upload and every
|
||||
* kernel that reads it are on that rank's compute stream, so the next build's upload is
|
||||
* ordered behind the kernels of the last one by the queue itself: nothing on the card can
|
||||
* read a slab another build is writing. What does need more than one copy is the HOST side,
|
||||
* which the upload reads when the stream reaches it and not when it is issued -- and the host
|
||||
* may be several passes ahead of the card. That staging is carved out of a ring (see Ring),
|
||||
* so any number of builds can be in flight and a build only waits when the ring is full.
|
||||
*
|
||||
* `h_*` are re-carved for every build at its place in the ring; `d_*` are rank 0's slab and
|
||||
* never move. */
|
||||
* The device slab is one per rank and never double buffered: uploads and the kernels reading
|
||||
* them share the rank's compute stream, so stream order protects it. The host side is read
|
||||
* when the stream reaches the upload, possibly several passes later, so it comes from a ring
|
||||
* (see Ring). `h_*` are re-carved for every build at its ring position; `d_*` are rank 0's
|
||||
* slab and never move. */
|
||||
struct Set {
|
||||
int64_t host_bytes = 0, dev_bytes = 0;
|
||||
/* THE BLOCK TABLES ARE NOT PART OF THE FIXED LAYOUT'S COPY. `bt_base` is where they
|
||||
* start, and everything below it crosses whole every build. On the card the region past
|
||||
* it is every group's tables at a fixed place; in the host span it is the build's
|
||||
* PAYLOAD -- the table entries that changed, packed -- followed by the list of ranges
|
||||
* saying where each run of it lands (see BtMirror). `dev_bytes` is the ALLOCATION, which
|
||||
* holds every group's worst table. */
|
||||
/* Everything below `bt_base` is uploaded whole every build. Past it, the card holds every
|
||||
* group's block tables at fixed places, while the host span holds the payload (changed
|
||||
* table entries, packed) followed by the ranges saying where each run lands (see
|
||||
* BtMirror). `dev_bytes` is the allocation, sized for every group's largest table. */
|
||||
int32_t* bt_h0 = nullptr; int32_t* bt_d0 = nullptr;
|
||||
int64_t bt_base = 0;
|
||||
/* ONE DEVICE SLAB PER RANK, and this is not an optimisation.
|
||||
*
|
||||
* The batch is built once and shared BY POINTER (spec §1), which is right for the host
|
||||
* side and wrong for the device side. A single slab on rank 0's card, filled by async
|
||||
* copies on rank 0's stream and read by every rank's kernels off its own stream, has
|
||||
* nothing ordering the other ranks' reads after rank 0's copies. A slab per rank makes
|
||||
* each rank's upload an ordinary same-stream dependency and puts the metadata on the card
|
||||
* that reads it, instead of behind PCIe. The carve is identical on every rank, so d_*
|
||||
* below are rank 0's pointers AND the offset basis for the rest. */
|
||||
/* One device slab per rank, required for correctness: a single slab on rank 0 would leave
|
||||
* other ranks' reads unordered against rank 0's copies. Per rank, each upload is a
|
||||
* same-stream dependency and the metadata sits on the card that reads it. The carve is
|
||||
* identical on every rank, so d_* below are rank 0's pointers and the offset basis for
|
||||
* the rest. */
|
||||
std::vector<void*> dev;
|
||||
|
||||
int32_t *h_tok = nullptr, *h_pos = nullptr, *h_cu = nullptr, *h_sid = nullptr;
|
||||
@@ -246,18 +205,16 @@ private:
|
||||
* mm_rows): carved only when the program declared an encoder, empty otherwise. */
|
||||
int32_t *h_rope = nullptr, *d_rope = nullptr;
|
||||
int32_t *h_mmrow = nullptr, *d_mmrow = nullptr;
|
||||
/* [n_kv_groups][max_seqs]: EVERY conv group's state slot per sequence, not just one, since
|
||||
* a model may have more than one conv group -- see init(). */
|
||||
/* [n_kv_groups][max_seqs]: every conv group's state slot per sequence (see init()). */
|
||||
int32_t* h_convslot = nullptr;
|
||||
|
||||
std::vector<Group> groups;
|
||||
};
|
||||
|
||||
/* THE HOST STAGING RING. A build takes the bytes it will upload -- the fixed prefix and the
|
||||
* block-table rows it fills -- as one contiguous span, fills it, and records an event per rank
|
||||
* behind the upload. A span is reusable once every rank's upload of it has run, which is what
|
||||
* `reserve` waits for when the ring is full; at steady state it never is, because a decode
|
||||
* build's span is a small fraction of the ring. */
|
||||
/* Host staging ring. A build takes one contiguous span for what it uploads (the fixed prefix
|
||||
* and its block-table payload), fills it, and records an event per rank behind the upload. A
|
||||
* span is reusable once every rank's upload has run; `reserve` waits for that only when the
|
||||
* ring is full. */
|
||||
struct Flight {
|
||||
int64_t begin = 0, end = 0;
|
||||
int ev = -1; /* row of ev_ holding one event per rank */
|
||||
@@ -271,9 +228,9 @@ private:
|
||||
int first = 0, live = 0;
|
||||
};
|
||||
|
||||
/* What a build hands the ranks: the ABI views and the batch, ONE PER RANK, since they differ
|
||||
* only in the device pointers. kOut of them so a batch stays valid while later ones are
|
||||
* built: a step's own batch is read after its draft passes and the next step's batch are. */
|
||||
/* A build's ABI views and batch, one per rank (they differ only in device pointers). kOut of
|
||||
* them, because a step's batch is still read after its draft passes and the next step have
|
||||
* been built. */
|
||||
static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4;
|
||||
struct Out {
|
||||
std::vector<std::vector<RadKVGroupBatch>> kv;
|
||||
@@ -282,8 +239,8 @@ private:
|
||||
|
||||
struct Derived {
|
||||
rad_buf handle = 0;
|
||||
/* WHICH conv group this derivation is about, or -1 for none. From RadBufDecl::kv, or the
|
||||
* only conv group when the plugin left that 0 and there IS only one. */
|
||||
/* Conv group this derivation is about, or -1. From RadBufDecl::kv, or the only conv
|
||||
* group when the plugin left it 0 and there is exactly one. */
|
||||
int32_t conv_grp = -1;
|
||||
const char* name = nullptr;
|
||||
int fn_index = -1;
|
||||
@@ -300,16 +257,12 @@ private:
|
||||
std::vector<RankIO> ranks_;
|
||||
|
||||
int64_t max_tok_ = 0, max_seqs_ = 0, max_ctx_ = 0;
|
||||
/* Per KV GROUP, indexed by group, and 0 for a group that is not RAD_KV_CONV.
|
||||
*
|
||||
* THIS AND `h_convslot` FEED `DeriveInput` AND NOTHING ELSE. A conv KERNEL reads its slot from
|
||||
* RadKVGroupBatch::state_index, which is per group. What reads these two is the
|
||||
* `conv_state_index` DERIVATION, which no architecture plugin currently calls --
|
||||
* rad_block_gdn_fp8.h takes `cv->state_index` straight off the group batch. Keeping them per
|
||||
* group is what makes the derivation correct, and usable, for a model with a second conv
|
||||
* group. */
|
||||
/* Per KV group, 0 for a non-conv group. This and `h_convslot` only feed DeriveInput for the
|
||||
* `conv_state_index` derivation, which no plugin calls at present; conv kernels read
|
||||
* RadKVGroupBatch::state_index instead. Kept per group so the derivation is correct with more
|
||||
* than one conv group. */
|
||||
std::vector<int32_t> conv_window_;
|
||||
int32_t conv_group_ = -1; /* the ONLY conv group, when there is exactly one; else -1 */
|
||||
int32_t conv_group_ = -1; /* the conv group when there is exactly one, else -1 */
|
||||
int32_t n_conv_ = 0;
|
||||
|
||||
Set set_;
|
||||
@@ -323,22 +276,17 @@ private:
|
||||
/* Per group, this build's block-table pitch: sized before the span is reserved. */
|
||||
std::vector<int64_t> pitch_;
|
||||
|
||||
/* WHAT EVERY RANK'S SLAB HOLDS IN ITS BLOCK-TABLE REGION, so a build stages only what changed.
|
||||
/* What every rank's slab holds in its block-table region, so a build stages only what changed.
|
||||
* At long context a table is thousands of entries per group, too many to restage every build.
|
||||
* The slab outlives the build and uploads land in build order, so it holds the last build's
|
||||
* rows. A row still holding the same sequence at the same pitch is restaged from the first
|
||||
* entry the manager changed (take_table_changes) to the end of what it or the card holds; any
|
||||
* other row is restaged whole.
|
||||
*
|
||||
* A sequence's table is its whole context in blocks, thousands of entries a group at long
|
||||
* context, and restaging every row whole every build cost the scheduler time in proportion
|
||||
* to context times sequences times the several builds of a speculative step -- and the card
|
||||
* as much in upload. But the slab is one per rank and outlives the build, the uploads reach it
|
||||
* in the order the builds were made, and a group's tables have a fixed place in it, so it
|
||||
* already holds the last build's rows. A row that still holds the same sequence at the same
|
||||
* pitch is restaged from the lowest entry the manager changed (take_table_changes) to the end
|
||||
* of what it or the card holds; any other row is restaged whole.
|
||||
*
|
||||
* `len[i]` is how many entries of row i are the table of `seq[i]`, and the rest of the row is
|
||||
* -1, which is what a whole restage leaves; -1 in `len` is "unknown". A sequence is current in
|
||||
* at most one row: its change marks are consumed where it is written, so a copy of it left
|
||||
* in another row goes unknown. A layout change -- the group's pitch -- and a build that fails
|
||||
* after taking marks make every row unknown. */
|
||||
* `len[i]` is how many entries of row i are the table of `seq[i]`; the rest of the row is -1.
|
||||
* -1 in `len` means unknown. A sequence is current in at most one row, because its change marks
|
||||
* are consumed where it is written; a copy left in another row becomes unknown. A pitch change,
|
||||
* or a build that fails after taking marks, makes every row unknown. */
|
||||
struct BtMirror {
|
||||
int64_t pitch = -1;
|
||||
std::vector<uint64_t> seq;
|
||||
@@ -347,54 +295,53 @@ private:
|
||||
std::vector<BtMirror> bt_mirror_;
|
||||
/* This build's upload ranges, host-side, until build() writes them behind the payload. */
|
||||
std::vector<RadCopyRange> ranges_;
|
||||
int64_t pay_words_ = 0; /* the payload build_groups wrote, in int32 */
|
||||
int64_t pay_words_ = 0; /* payload build_groups wrote, in int32 words */
|
||||
void forget_tables();
|
||||
int64_t last_n_seq_ = 0;
|
||||
|
||||
int64_t derived_bytes_ = 0;
|
||||
std::vector<Derived> derived_;
|
||||
|
||||
/* THE MEDIA STAGING, allocated only when the program declared an encoder (mm_on_).
|
||||
/* Media staging, allocated only when the program declares an encoder (mm_on_).
|
||||
*
|
||||
* The encoder rows a pass overwrites its embeddings with are NOT in the slab: the slab's
|
||||
* prefix crosses whole on every build, and max_tok rows of an embedding are megabytes a decode
|
||||
* step would copy for nothing. They have a device region of their own on every rank, filled
|
||||
* only by a build that carries them -- rank 0 from pinned staging, every other rank with zeros
|
||||
* (RadBatch::mm_embd says why). The staging is refilled only once the last upload out of it
|
||||
* has run, which `mm_ev_` records. */
|
||||
* Encoder rows are kept out of the slab, whose prefix is uploaded every build; max_tok
|
||||
* embedding rows would be megabytes per decode step. Each rank has its own device region,
|
||||
* filled only by a build that carries rows: rank 0 from pinned staging, the others with zeros
|
||||
* (see RadBatch::mm_embd). The staging is refilled only after its last upload has run
|
||||
* (`mm_ev_`). */
|
||||
bool mm_on_ = false;
|
||||
int64_t n_embd_ = 0;
|
||||
std::vector<void*> mm_dev_;
|
||||
uint16_t* mm_host_ = nullptr;
|
||||
RadEvent mm_ev_ = nullptr;
|
||||
bool mm_ev_live_ = false;
|
||||
/* ...and the encoders' inputs: patches, their coordinates and the segment boundaries, sized
|
||||
* for the larger of the passes the plugin declared (a vision tower's and an audio encoder's
|
||||
* run one at a time and share it). One copy a rank, since each runs the tower itself. */
|
||||
/* Encoder inputs: patches, their coordinates and segment boundaries, sized for the largest
|
||||
* declared pass (encoder passes run one at a time and share it). One copy per rank. */
|
||||
int64_t enc_patches_ = 0, enc_pix_elems_ = 0, enc_segs_ = 0;
|
||||
std::vector<void*> enc_pix_dev_, enc_coord_dev_, enc_cu_dev_;
|
||||
uint16_t* enc_pix_host_ = nullptr;
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
int32_t* enc_cu_host_ = nullptr;
|
||||
std::vector<int32_t> enc_coord_tmp_; /* one item's coordinates; kept for its capacity */
|
||||
int64_t last_n_tok_ = 0;
|
||||
struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
|
||||
MediaBytes media_bytes(); /* the four device regions alloc_media reserves, per rank */
|
||||
MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */
|
||||
int alloc_media();
|
||||
void free_media();
|
||||
/* The encoder rows of one entry: the media tokens among its positions, their rows copied into
|
||||
* the staging from `n_rows` on. Returns how many it added, or negative. */
|
||||
/* Stage the encoder rows of one entry's media tokens, starting at row `n_rows`. Returns how
|
||||
* many it added, or negative on error. */
|
||||
int64_t stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
|
||||
int32_t* rows);
|
||||
|
||||
/* The members init() derives from the program and the config, allocating nothing. */
|
||||
/* Derive the members init() needs from the program and config, without allocating. */
|
||||
int layout(Program& prog, const Config& cfg);
|
||||
/* The set's groups and its carve with no base: dev_bytes and host_bytes, nothing reserved. */
|
||||
/* Fill the set's groups and sizes (dev_bytes, host_bytes) without reserving anything. */
|
||||
void size_set(Set& s, const std::vector<KVGroupInfo>& groups);
|
||||
int alloc_set(Set& s, const std::vector<KVGroupInfo>& groups);
|
||||
void free_set(Set& s);
|
||||
/* Point every h_* at host staging based at `base`, and every d_* at rank 0's slab. */
|
||||
void carve(Set& s, char* base);
|
||||
/* A span of `need` bytes of the ring, waiting for old uploads when it is full. */
|
||||
/* Reserve `need` bytes of the ring, waiting for old uploads when it is full. */
|
||||
int reserve(int64_t need, int64_t* off);
|
||||
int run_derivations(const StepPlan& plan, Set& s);
|
||||
int build_groups(const StepPlan& plan, const IKVManager& kv, Set& s, Out& o);
|
||||
|
||||
+15
-23
@@ -1,4 +1,4 @@
|
||||
/* derive.cpp -- the derivation table. One row per name; adding one is adding a row.
|
||||
/* derive.cpp -- the derivation table, one row per name.
|
||||
*/
|
||||
#include "derive.h"
|
||||
|
||||
@@ -8,9 +8,7 @@ namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ seq_start_index */
|
||||
/* [n_seq+1] -- where each sequence's tokens begin in this step's flat token array, and the total.
|
||||
* This is cu_seqlens, exposed as a declared buffer so a plugin can name it as an operand instead
|
||||
* of reaching into RadBatch. It costs a copy of n_seq+1 int32 and it means an op's operand list
|
||||
* says what it reads. */
|
||||
* A copy of cu_seqlens, so a plugin can name it as an operand instead of reaching into RadBatch. */
|
||||
static int d_seq_start_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
int64_t n = in.n_seq + 1;
|
||||
if (n > cap) return RAD_E_FULL;
|
||||
@@ -20,13 +18,12 @@ static int d_seq_start_index(const DeriveInput& in, int32_t* out, int64_t cap, i
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv_state_index */
|
||||
/* [n_seq] -- the entry of the conv state cache this sequence's update reads from.
|
||||
/* [n_seq] -- the conv state cache entry this sequence's update reads from.
|
||||
*
|
||||
* libr4d treats the conv state as a rolling window of `width-1 + num_spec` entries and reads at
|
||||
* the slot the last accepted token left, so a speculative rejection is a change of READ OFFSET
|
||||
* rather than a recompute (spec §10). The window base is the sequence's state slot; the offset is
|
||||
* the cursor the scheduler advances by 1 + num_accepted per verify. Both numbers live in the
|
||||
* request's bookkeeping, which is why this is a scheduler-side derivation and not a kernel one. */
|
||||
* The conv state is a rolling window of `width-1 + num_spec` entries read at the slot the last
|
||||
* accepted token left, so a speculative rejection moves the read offset instead of recomputing
|
||||
* (spec §10). Base is the sequence's state slot; offset is the cursor the scheduler advances by
|
||||
* 1 + num_accepted per verify. Both live in request bookkeeping, hence a scheduler derivation. */
|
||||
static int d_conv_state_index(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
if (in.n_seq > cap) return RAD_E_FULL;
|
||||
if (!in.conv_slot) return RAD_E_STATE;
|
||||
@@ -41,15 +38,11 @@ static int d_conv_state_index(const DeriveInput& in, int32_t* out, int64_t cap,
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- the linear-state chunk walk */
|
||||
/* The chunked linear-attention kernels tile a sequence in fixed chunks measured from the
|
||||
* sequence's own origin, not from the start of the step's token array. In a varlen batch those two
|
||||
* disagree, so the boundaries have to be derived: a chunk may never cross a sequence boundary, and
|
||||
* a chunk boundary must land on an absolute multiple of the chunk length or the recurrent state
|
||||
* carried into the next chunk is the state of a partial tile.
|
||||
*
|
||||
* The scheduler already guarantees a prefill chunk ends on a multiple of the quantum (geometry.h),
|
||||
* so in a pure prefill step the interior boundaries are exactly the multiples; the walk still runs
|
||||
* because a mixed step's decode rows start at arbitrary positions. */
|
||||
/* Chunked linear-attention kernels tile each sequence in fixed chunks from the sequence's own
|
||||
* origin, not the step's token array. A chunk never crosses a sequence boundary, and interior
|
||||
* boundaries land on absolute multiples of the chunk length, or the carried recurrent state would
|
||||
* be that of a partial tile. Prefill chunks already end on the quantum (geometry.h); the walk is
|
||||
* still needed because a mixed step's decode rows start at arbitrary positions. */
|
||||
template <bool WantSeq>
|
||||
static int chunk_walk(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
const int64_t C = in.state_chunk > 0 ? in.state_chunk : 1;
|
||||
@@ -77,14 +70,13 @@ static int chunk_walk(const DeriveInput& in, int32_t* out, int64_t cap, int64_t*
|
||||
}
|
||||
|
||||
/* [n_chunks+1] token indices: chunk c covers [out[c], out[c+1]). out[0] is 0 and the last entry is
|
||||
* n_tok, so the array reads exactly like cu_seqlens does. */
|
||||
* n_tok, like cu_seqlens. */
|
||||
static int d_state_chunk_bounds(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
return chunk_walk<false>(in, out, cap, n_out);
|
||||
}
|
||||
|
||||
/* [n_chunks] -- which sequence each chunk belongs to. Recoverable from the bounds by a search
|
||||
* against cu_seqlens, but the search is per chunk in every layer that wants it, and this is one
|
||||
* pass shared by all of them. */
|
||||
/* [n_chunks] -- which sequence each chunk belongs to. Derivable from the bounds, but one shared
|
||||
* pass here saves a per-chunk search in every layer. */
|
||||
static int d_state_chunk_seq(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out) {
|
||||
return chunk_walk<true>(in, out, cap, n_out);
|
||||
}
|
||||
|
||||
+11
-18
@@ -1,25 +1,19 @@
|
||||
/* derive.h -- per-step metadata the core computes ONCE, by name, into the arena.
|
||||
/* derive.h -- per-step metadata the core computes once, by name, into the arena.
|
||||
*
|
||||
* An architecture plugin that needs linear-state chunk boundaries or conv-state indices declares
|
||||
* them at build time as a RAD_BUF_DERIVED buffer and names the derivation. The core computes it
|
||||
* once per step; it is NOT recomputed per layer, and layers that share a geometry share the buffer.
|
||||
* A plugin that needs linear-state chunk boundaries or conv-state indices declares a
|
||||
* RAD_BUF_DERIVED buffer naming the derivation. The core fills it once per step, not per layer,
|
||||
* and layers that share a geometry share the buffer. The step batch is the natural owner of
|
||||
* "once per step"; vLLM has no such object and keys it off a module-level counter.
|
||||
*
|
||||
* Sharing like this is what vLLM has no natural place for: it has to establish "same step" through
|
||||
* a module-level counter, because nothing there is an object that belongs to a step, and a marker
|
||||
* held per metadata-builder instead removes nothing -- every KV-cache group is still the first one
|
||||
* its own builder sees. Here the step batch IS that place.
|
||||
*
|
||||
* Adding a derivation is a row in the table in derive.cpp. The core is not the thing you edit to
|
||||
* add a kernel; it is the thing you edit to add a shape of per-step metadata, and that list is
|
||||
* short and shared.
|
||||
* Adding a derivation is a row in the table in derive.cpp.
|
||||
*/
|
||||
#pragma once
|
||||
#include "batch.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* Everything a derivation may read. All host memory, already staged for this step: a derivation
|
||||
* that needed a device read would be a synchronisation on the step path. */
|
||||
/* Everything a derivation may read. All host memory, already staged for this step, so no
|
||||
* derivation adds a device sync to the step path. */
|
||||
struct DeriveInput {
|
||||
const StepPlan* plan = nullptr;
|
||||
const int32_t* cu_seqlens = nullptr; /* [n_seq+1] */
|
||||
@@ -32,8 +26,7 @@ struct DeriveInput {
|
||||
};
|
||||
|
||||
/* Writes at most `cap` int32 elements to `out` and reports how many. Returns RAD_OK or negative;
|
||||
* negative aborts the step, because a plugin issuing an op against a half-filled derived buffer is
|
||||
* the silent-wrong-output failure this engine exists to remove. */
|
||||
* negative aborts the step rather than let an op read a half-filled buffer. */
|
||||
typedef int (*DeriveFn)(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out);
|
||||
|
||||
struct DeriveRow {
|
||||
@@ -42,8 +35,8 @@ struct DeriveRow {
|
||||
const char* doc;
|
||||
};
|
||||
|
||||
/* -1 if the name is not a derivation the core knows. Reported at declare, by name, with the known
|
||||
* list -- the same treatment a misspelled op gets (spec §2.3). */
|
||||
/* -1 for an unknown name. Reported at declare with the known list, like a misspelled op
|
||||
* (spec §2.3). */
|
||||
int derive_index(const char* name);
|
||||
const DeriveRow* derive_row(int index);
|
||||
int derive_count();
|
||||
|
||||
+42
-51
@@ -1,5 +1,5 @@
|
||||
/* 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.
|
||||
/* draft.cpp -- the static draft-depth policy and the adaptive one (`--draft-window adaptive`).
|
||||
* See draft.h.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
@@ -11,33 +11,33 @@ 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'). */
|
||||
/* Step-cost prior, a shape rather than a measurement: each draft adds 6% to a step (one serial
|
||||
* head round plus one verify row on a weight-bound step). Once anything is measured only its
|
||||
* ratios are used: 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. */
|
||||
/* A step-time mean is a running mean for the first steps, then a moving average with a half-life
|
||||
* of 32 steps: long enough to average out one-off costs (a tier copy, a recording, a prefix-cache
|
||||
* trim), short enough to follow a context growing 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. */
|
||||
/* Once a key has 4 samples, one step counts for at most 4x its mean. A step that waited on
|
||||
* something else (a first recording, an allocation, a host stall) says nothing about its depth's
|
||||
* cost. Below 4 samples the mean is not a trustworthy reference to clip against. */
|
||||
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. */
|
||||
/* The prior weighs as much as this many verifies. The (n+1)-th verify moves an estimate by
|
||||
* 1 / (n + k + 1), a running mean over prior and evidence, until that falls below the half-life's
|
||||
* step and the moving average takes over. Without it a sequence would spend its first ~16
|
||||
* verifies at the prior's window, most of a short answer. */
|
||||
constexpr double kPriorWeight = 4.0;
|
||||
|
||||
/* The weight of the (n+1)-th sample in an estimate that is a running mean until 1 / (n + 1)
|
||||
* falls below a moving average's step at half-life `h` samples, and that average after. */
|
||||
double settle_weight(double h, int64_t n) {
|
||||
return std::fmax(1.0 - std::exp2(-1.0 / h), 1.0 / (double)(n + 1));
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
@@ -64,10 +64,8 @@ int DraftController::configure(const Params& p) {
|
||||
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",
|
||||
RAD_INFO("draft depth: adaptive, %d..%d; a sequence stops at the first draft emitted less "
|
||||
"than %.0f%% of the time, and the depth moves at +%.0f%% at most every %d steps",
|
||||
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -80,9 +78,9 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
tot_drafted_ += drafted;
|
||||
tot_accepted_ += accepted;
|
||||
|
||||
/* Position j was EVALUATED only if every position before it was accepted, so this verify
|
||||
* produces exactly: 0..accepted-1 evaluated and accepted, and -- when the prefix was not the
|
||||
* whole draft -- position `accepted` evaluated and rejected. Nothing past that was reached. */
|
||||
/* Position j is evaluated only if every earlier position was accepted: 0..accepted-1 are
|
||||
* evaluated and accepted, position `accepted` (if drafted) evaluated and rejected, and nothing
|
||||
* past it is reached. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
++reach_[j];
|
||||
@@ -107,7 +105,7 @@ void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
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));
|
||||
const double w = settle_weight(kCostHalfLife, n);
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
}
|
||||
@@ -121,10 +119,9 @@ 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. */
|
||||
/* Nearest measured key: this class first (nearest depth, shallower on a tie), then the
|
||||
* nearest class. Only its ratio to the prior is borrowed, so D's comparison across depths in
|
||||
* one class follows the prior's shape until those 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;
|
||||
@@ -158,8 +155,7 @@ double DraftController::prior_at(int j) const {
|
||||
}
|
||||
|
||||
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). */
|
||||
/* From finished sequences once there are enough (adapt_retire), else the fixed kPrior. */
|
||||
for (int j = 0; j < p_.max_depth; ++j) {
|
||||
s.a[j] = (float)prior_at(j);
|
||||
s.n[j] = 0;
|
||||
@@ -170,8 +166,7 @@ void DraftController::start(DraftAdapt& s) const {
|
||||
|
||||
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));
|
||||
const double w = settle_weight(kPriorHalfLifeSeqs, prior_n_);
|
||||
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];
|
||||
@@ -207,9 +202,8 @@ int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) con
|
||||
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. */
|
||||
/* The positions this verify evaluated, by observe()'s rule. Positions past the first
|
||||
* rejection were never evaluated and are not updated here. */
|
||||
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));
|
||||
@@ -217,17 +211,15 @@ int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) con
|
||||
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. */
|
||||
/* Positions past the window drift toward its deepest one. Otherwise a sequence held shallow
|
||||
* by prose that turns into code would keep its stale deep estimates and never draft deep
|
||||
* enough to update them. Assumes acceptance decays smoothly with position; when wrong it costs
|
||||
* a move out and 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. */
|
||||
/* 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);
|
||||
@@ -244,9 +236,8 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
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. */
|
||||
/* Expected tokens at each head depth: sum_i E_i(min(D, stop_i)), plus one per non-drafting
|
||||
* row. Candidates end at the deepest stop, since a deeper D changes nothing. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
@@ -269,8 +260,8 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int 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. */
|
||||
/* Move only after kHold steps and only for kHyst more yield than the current depth. The
|
||||
* first drafting step takes the best outright. */
|
||||
if (step_d_ <= 0) {
|
||||
step_d_ = best;
|
||||
step_held_ = 0;
|
||||
|
||||
+98
-146
@@ -1,74 +1,52 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
* Static by default: the depth is `--num-speculative-tokens`. A dynamic policy that gates on the
|
||||
* drafter's own top-1 confidences cannot work here, because the scheduler picks the depth before
|
||||
* the drafter runs; measured acceptance arrives a step late and pooled across sequences. With a
|
||||
* draft head whose cost is nearly flat in depth (one extra verify row on a weight-bound step), the
|
||||
* best depth is a property of the model pair and is known up front, so it is a flag. The
|
||||
* controller still keeps acceptance accounting, a reported metric (spec §14).
|
||||
*
|
||||
* 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
|
||||
* decides the depth BEFORE the drafter runs and cannot see them; the only substitute available
|
||||
* here is measured acceptance, which is the right quantity in expectation but arrives one step
|
||||
* late and pooled across sequences. Against a draft head whose cost is nearly flat in depth (one
|
||||
* extra verify row on a step that is weight-bound, not compute-bound) that estimate has nothing to
|
||||
* buy: the best depth is a property of the model pair, it is known before the serve starts, and it
|
||||
* is a flag. A controller that can only pick a worse depth than the constant contributes only the
|
||||
* risk that it picks one.
|
||||
* `--draft-window adaptive` is for when that premise fails: with streamed weights (a MoE reading
|
||||
* experts per verify row, a serial head running one pass per round) each draft costs a head round
|
||||
* and a verify row, and the best depth depends on the text (deep on code and JSON, shallow on
|
||||
* prose). The adaptive policy has two halves:
|
||||
*
|
||||
* 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.
|
||||
* Per sequence (DraftAdapt): a smoothed estimate of each draft position's conditional
|
||||
* acceptance, fed by the verify outcomes, and the sequence's stop -- the deepest draft whose
|
||||
* chance of being emitted still pays for its verify row (kDraftMinChance).
|
||||
*
|
||||
* 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.
|
||||
* Per step (plan_step): the head depth D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(D, n), with
|
||||
* E(d) = 1 + sum_k prod_{j<=k} a_j and T measured online (step_time). Each sequence then
|
||||
* drafts min(D, stop_i).
|
||||
*
|
||||
* So the adaptive window is a policy on the host, in two halves:
|
||||
* Both move only past a hold, and D also past a hysteresis, because a new window is a new pass
|
||||
* shape that must be recorded before it plays (runtime/ctx.h). `max_depth` stays the ceiling and
|
||||
* everything is sized for it.
|
||||
*
|
||||
* 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).
|
||||
* The policy is for serial drafters only (Scheduler::init): a block drafter proposes its block in
|
||||
* one pass and prompt lookup runs none, so neither pays per-round cost.
|
||||
*
|
||||
* 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).
|
||||
* It changes only how many drafts a step verifies. Acceptance follows core/sample/accept.h, so
|
||||
* every emitted token is the target's own; at temperature 0 the text matches a plain run as far
|
||||
* as the logits do, and a verify row's logits are computed at an M that moves with the window
|
||||
* (see accept.h).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* libr4d's decode kernel serves up to 64 query rows precisely because a verify step falls in that
|
||||
* band (spec §10), so 64 is the largest window any batch can carry. */
|
||||
/* libr4d's decode kernel serves up to 64 query rows, the verify-step 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.
|
||||
/* One sequence's half of the adaptive policy: the drafter's record on this sequence's text and the
|
||||
* resulting stop. Stored in the scheduler's per-request state; the controller does the arithmetic.
|
||||
*
|
||||
* `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. */
|
||||
* `depth` 0 means not started: the first ask fills the estimate from the prior and sets the stop.
|
||||
* It belongs to the request, not its cache: preemption keeps it, a recycled slot resets it. */
|
||||
struct DraftAdapt {
|
||||
int32_t depth = 0; /* the sequence's stop; 0 = not started */
|
||||
int32_t held = 0; /* verifies since `depth` last moved */
|
||||
@@ -80,132 +58,112 @@ class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
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. */
|
||||
/* The adaptive policy: `--draft-window adaptive` with a serial drafter, decided by
|
||||
* Scheduler::init. Off, the depth is max_depth. */
|
||||
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). */
|
||||
* Not configurable: each is a property of the policy, not of a deployment. The one
|
||||
* deployment property, step cost, 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. */
|
||||
/* A window moves only for 2% more yield. One draft more or less moves E/T by several percent,
|
||||
* while a smoothed estimate wobbles about 1% per verify; a lower threshold would flip D
|
||||
* between 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. */
|
||||
/* And not within 8 verifies (steps, for D) of the last move. A pass shape is recorded on its
|
||||
* second sighting and played from the third (runtime/ctx.h), so a shape held 8 steps mostly
|
||||
* plays from the recording; 8 verifies at kHalfLife move an estimate about a third of the way
|
||||
* to a new rate, 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. */
|
||||
/* Each position's estimate has a half-life of 16 verifies that evaluate it (about 50 tokens of
|
||||
* text): short enough to follow a reply from prose into code and back, long enough that one
|
||||
* rejection moves an estimate by about 4%. */
|
||||
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. */
|
||||
/* An unmeasured position starts at 0.8, optimistic on purpose: a window that starts deep
|
||||
* learns every position, one that starts shallow never learns the deep ones. 0.8 lies between
|
||||
* typical first-position acceptance on prose and on code, so a wrong start corrects 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. */
|
||||
/* Once 4 sequences have finished, new ones start from the mean of their final estimates
|
||||
* (adapt_retire): a running mean, then a moving average with a half-life of 32 sequences, so
|
||||
* the prior follows a change of traffic within a few dozen requests. A sequence counts only
|
||||
* after kHalfLife verifies; before that its estimate is mostly the prior 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. */
|
||||
/* Never fewer than one draft: at zero no position is evaluated, so the estimate could never
|
||||
* recover. */
|
||||
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. */
|
||||
/* A sequence stops at the first draft whose chance of being emitted, prod_{j<=d} a_j, is
|
||||
* under 1 in 10. Once the head runs D rounds for the deepest neighbour, a sequence's only
|
||||
* added cost is its verify row. At one sequence the step-cost prior (1 + 0.06 d) breaks even
|
||||
* near this chance (a draft pays while p_d / E exceeds the ~6% it adds, with E around 2), and
|
||||
* a row alone costs less than a round plus a row, so this is never stricter than D's own
|
||||
* trade. A constant because a row's share cannot be separated from the head's rounds in step
|
||||
* times keyed by depth. */
|
||||
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. */
|
||||
/* Step times are kept per running-row class: 1, 2-3, 4-7, 8-15, 16+. Cost moves with how many
|
||||
* rows share the weight reads; power-of-two classes keep every key fed. */
|
||||
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:
|
||||
* under the adaptive policy it is the CEILING, and window_for() is the window. */
|
||||
/* The draft depth for the next step; 0 means do not speculate. Constant: 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. */
|
||||
* first ask; max_depth when the policy is off. Before any step chooses 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. */
|
||||
/* As window_for() but never starts an estimate; 0 if not started. 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. */
|
||||
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Updates the
|
||||
* estimate, and the stop once past the hold. Returns the stop. */
|
||||
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.
|
||||
/* A finished sequence: its estimate joins the prior that new 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. */
|
||||
* Per sequence, not per verify. Under this policy, pooled accepted(j) / reached(j) is biased:
|
||||
* only well-predicted texts get windows deep enough to measure deep positions. Here each
|
||||
* finished sequence counts once at every position, using its edge extrapolation where it never
|
||||
* reached (adapt_observe), so shallow texts pull deep positions down as much as deep ones hold
|
||||
* 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. */
|
||||
/* D for the step being opened. `seq` holds the estimates of the `n_seq` drafting sequences
|
||||
* (started here if needed), `n_rows` all decode rows (the rest emit one token and draft
|
||||
* nothing). Moves D past the hold and hysteresis; with nothing 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. */
|
||||
/* The deepest window a step at depth D carries: D capped at the deepest stop it was chosen
|
||||
* over; the ceiling before the first choice or with the policy off. Proposals from outside
|
||||
* the head (prompt lookup) are held to it, so they add no deeper pass shape. */
|
||||
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. */
|
||||
/* T(depth, n): a decode step with deepest window `depth` and `n_rows` decode rows took `ms`
|
||||
* since the end of the previous step. Fed by Scheduler::step_finished; adaptive policy only. */
|
||||
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. */
|
||||
/* Expected cost of a step at `depth` with `n_rows` rows: the key's mean (ms) if it has
|
||||
* samples; else the nearest measured key scaled by the prior's ratio (1 + 0.06 d); else the
|
||||
* unitless prior itself. */
|
||||
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. */
|
||||
/* E(d) for `s`'s current estimate: expected tokens emitted by a verify of d drafts, 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. */
|
||||
/* Histogram of verifies by window, counted only under the adaptive policy. */
|
||||
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. */
|
||||
/* One verify's outcome: `drafted` proposed, a prefix of `accepted` taken. Metrics only. */
|
||||
void observe(int drafted, int accepted);
|
||||
|
||||
/* Metrics (spec §14). Cumulative and exact. */
|
||||
@@ -215,25 +173,19 @@ public:
|
||||
return tot_drafted_ ? (float)((double)tot_accepted_ / (double)tot_drafted_) : 0.0f;
|
||||
}
|
||||
|
||||
/* PER-POSITION ACCEPTANCE, and it is a diagnostic rather than a policy input.
|
||||
/* Per-position acceptance, a diagnostic rather than a policy input. The pooled ratio cannot
|
||||
* tell a drafter that decays gradually from one that fails at a specific position.
|
||||
*
|
||||
* The pooled ratio above cannot tell a drafter that decays from one that falls off a cliff,
|
||||
* and the difference is the difference between "this is what the head is worth" and "round
|
||||
* three is broken". A drafter whose accepted-tokens-per-step stops rising past some depth has
|
||||
* a hazard that goes to zero there; pooled over the whole window that reads as a uniformly
|
||||
* mediocre drafter, which is a different diagnosis and a different fix.
|
||||
*
|
||||
* `reached` is "every earlier position was accepted, so this one was evaluated"; `hits` is
|
||||
* "and it was accepted too". Their ratio is the conditional hazard. A position the draft
|
||||
* never reached is charged nothing, which is why a rejection at position 0 does not libel
|
||||
* every position behind it. */
|
||||
* `reached`: every earlier position was accepted, so this one was evaluated. `hits`: and it
|
||||
* was accepted. Their ratio is the conditional acceptance. Unreached positions are not
|
||||
* charged, so a rejection at position 0 does not count against later positions. */
|
||||
int64_t reached(int j) const {
|
||||
return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? reach_[j] : 0;
|
||||
}
|
||||
int64_t hits(int j) const {
|
||||
return (j >= 0 && j < RAD_SCHED_MAX_SPEC) ? hit_[j] : 0;
|
||||
}
|
||||
/* The deepest position any draft has ever reached; how much of the two arrays is meaningful. */
|
||||
/* The deepest position any draft has reached; bounds the meaningful part of both arrays. */
|
||||
int depth_seen() const { return seen_; }
|
||||
|
||||
private:
|
||||
|
||||
+73
-55
@@ -1,29 +1,24 @@
|
||||
/* geometry.cpp -- reconciling the linear-state chunk geometry with the attention block size.
|
||||
* See geometry.h for why this is computed and not configured.
|
||||
/* geometry.cpp -- reconciles the linear-state chunk length with the attention block size.
|
||||
* See geometry.h.
|
||||
*/
|
||||
#include "geometry.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <numeric>
|
||||
|
||||
namespace rad {
|
||||
|
||||
static int64_t gcd64(int64_t a, int64_t b) {
|
||||
while (b) { int64_t t = a % b; a = b; b = t; }
|
||||
return a < 0 ? -a : a;
|
||||
}
|
||||
/* lcm, with a non-positive side meaning "no constraint yet". */
|
||||
static int64_t lcm64(int64_t a, int64_t b) {
|
||||
if (a <= 0) return b;
|
||||
if (b <= 0) return a;
|
||||
return a / gcd64(a, b) * b;
|
||||
return std::lcm(a, b);
|
||||
}
|
||||
|
||||
/* WHICH PARAMETER OF THIS OP IS ITS SEQUENCE-CHUNK LENGTH, asked of the op's own schema. The
|
||||
* scheduler must cut its steps on a multiple of it or a linear-state chunk straddles a sequence
|
||||
* boundary, so this is the one parameter the core reads by MEANING rather than carrying opaquely.
|
||||
*
|
||||
* The schema names it (RAD_PROLE_SEQ_CHUNK), so the core holds no vocabulary of its own. Matching
|
||||
* a list of likely parameter spellings here instead would silently miss any op that spells it
|
||||
* differently, and a missed contributor is a quantum that does not divide the kernel's tile. */
|
||||
/* The op's sequence-chunk parameter, found by role (RAD_PROLE_SEQ_CHUNK) in its schema. Steps
|
||||
* must be cut on a multiple of it or a linear-state chunk straddles a step boundary. Matching
|
||||
* parameter names instead would silently miss an op that spells it differently. */
|
||||
static const char* chunk_key_of(const RadOpSchema* s) {
|
||||
if (!s) return nullptr;
|
||||
for (int i = 0; i < s->n_params; ++i)
|
||||
@@ -31,22 +26,25 @@ static const char* chunk_key_of(const RadOpSchema* s) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/* One contributor, appended to the explanation. Kept to a line each so the refusal prints as a
|
||||
* short list and not a wall. */
|
||||
/* Appends one contributor to the explanation. */
|
||||
static void note(std::string& why, const char* what, int64_t v, const char* from) {
|
||||
if (!why.empty()) why += "; ";
|
||||
why += fmt("%s=%lld from %s", what, (long long)v, from);
|
||||
}
|
||||
|
||||
int64_t prefill_shared_tok(const Config& cfg) {
|
||||
if (cfg.prefill_span <= 1 || cfg.checkpoint_interval <= 0) return cfg.max_tok;
|
||||
const int64_t I = cfg.checkpoint_interval;
|
||||
return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
|
||||
}
|
||||
|
||||
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
ChunkGeometry g;
|
||||
|
||||
/* ---------------------------------------------------------------- attention block size */
|
||||
/* One lcm across every paged group. In practice every paged group on a given kernel set has
|
||||
* the same block size -- libr4d's is 16 for all of them -- but a hybrid model with a
|
||||
* sliding-window group served by a different kernel is exactly the case §7.2 is written for,
|
||||
* and lcm is the answer that is right for both. */
|
||||
/* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
|
||||
* served by a different kernel may differ (§7.2). */
|
||||
bool has_linear = false, has_window = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
|
||||
@@ -64,9 +62,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- linear-state chunk */
|
||||
/* Two sources, both already resolved: what the plugin declared the op with, and what the
|
||||
* kernel that won selection constrains. The first is the model's statement, the second is the
|
||||
* kernel's, and a chunk that is a multiple of both satisfies both. */
|
||||
/* Two sources: the geometry the plugin declared the op with, and the constraints of the
|
||||
* kernel selected for it. The lcm satisfies both. */
|
||||
for (const OpInfo& op : prog.ops) {
|
||||
const char* ckey = chunk_key_of(op.schema);
|
||||
if (!ckey) continue;
|
||||
@@ -87,9 +84,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
const RadConstraint& c = ki->constraints[i];
|
||||
if (!c.key || std::strcmp(c.key, ckey) != 0 || c.ival <= 0) continue;
|
||||
switch (c.op) {
|
||||
/* DIV and EQ are both "a legal chunk is a multiple of this". GE is folded
|
||||
* in the same way rather than as a separate floor: a multiple of N is
|
||||
* >= N, so one number carries both facts and the arithmetic stays lcm. */
|
||||
/* DIV and EQ mean "a legal chunk is a multiple of this". GE folds in the
|
||||
* same way, since a multiple of N is >= N. */
|
||||
case RAD_C_DIV:
|
||||
case RAD_C_EQ:
|
||||
case RAD_C_GE:
|
||||
@@ -97,8 +93,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
note(g.why, c.key, c.ival, ki->name);
|
||||
break;
|
||||
case RAD_C_LE:
|
||||
g.max_chunk = g.max_chunk ? (g.max_chunk < c.ival ? g.max_chunk
|
||||
: (int64_t)c.ival)
|
||||
g.max_chunk = g.max_chunk ? std::min<int64_t>(g.max_chunk, c.ival)
|
||||
: (int64_t)c.ival;
|
||||
break;
|
||||
default: break;
|
||||
@@ -113,8 +108,8 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
if (g.quantum < 1) g.quantum = 1;
|
||||
|
||||
if (g.max_chunk > 0 && g.quantum > g.max_chunk) {
|
||||
/* Two kernels that cannot both be fed. Naming it is the whole value: the alternative is a
|
||||
* chunk that is legal for one of them and silently wrong for the other. */
|
||||
/* No chunk length satisfies both kernels; report it instead of serving a chunk that is
|
||||
* wrong for one of them. */
|
||||
out->why = fmt("chunk quantum %lld exceeds the %lld a resolved kernel accepts (%s)",
|
||||
(long long)g.quantum, (long long)g.max_chunk, g.why.c_str());
|
||||
out->quantum = g.quantum;
|
||||
@@ -122,51 +117,74 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
/* The checkpoint interval is the operator's number rounded up to a legal chunk length, so that
|
||||
* "split at the interval" is always also "split at a quantum". Rounding UP rather than down
|
||||
* because down can reach zero and because a longer interval costs retention, not correctness.
|
||||
/* Round the operator's interval up to a multiple of the quantum, so a split at the interval
|
||||
* is a legal chunk split. Up, not down: down can reach zero, and a longer interval costs only
|
||||
* retention.
|
||||
*
|
||||
* No linear state means no checkpoints: the interval is a property of a state kind that this
|
||||
* model does not have, and pretending otherwise would split chunks for nothing. The one
|
||||
* exception is a trunk window under a prefix cache, which snapshots the window behind a
|
||||
* prompt's tail (window_ckpt) and does not split chunks for it. */
|
||||
* Without linear state there are no checkpoints, except for a trunk window under a prefix
|
||||
* cache, which snapshots the window behind a prompt's tail (window_ckpt) without splitting
|
||||
* chunks. */
|
||||
if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0)
|
||||
g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
|
||||
else
|
||||
g.checkpoint_interval = 0;
|
||||
g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
|
||||
/* A window snapshot splits no chunk (plan_chunk), so there is no interval grid to span. */
|
||||
g.span = (g.checkpoint_interval > 0 && !g.window_ckpt && cfg.prefill_span > 1)
|
||||
? cfg.prefill_span : 1;
|
||||
g.shared_tok = prefill_shared_tok(cfg);
|
||||
|
||||
/* One full quantum has to fit in one step. Below that, every chunk is short, no chunk ever
|
||||
* ends on a boundary, and the checkpoint lands wherever the step happened to end -- which is
|
||||
* precisely the vLLM failure §7.3 exists to remove. Refusing is the honest response. */
|
||||
/* One full quantum must fit in one step; otherwise no chunk ends on a boundary and
|
||||
* checkpoints land wherever a step ends (§7.3). */
|
||||
g.min_max_tok = g.quantum;
|
||||
|
||||
*out = g;
|
||||
|
||||
if (cfg.max_tok < g.min_max_tok) {
|
||||
RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least "
|
||||
"%lld: %s", (long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
|
||||
RAD_ERR("a smaller budget cannot end a chunk on a linear-state boundary, so every "
|
||||
"checkpoint would land in request-unique tokens and the linear prefix hit rate "
|
||||
"would be zero. Refusing rather than serving that.");
|
||||
"%lld, so a chunk can end on a linear-state boundary: %s",
|
||||
(long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* AND THE CHUNK AN OPERATOR ACTUALLY GETS, which is not --max-num-batched-tokens whenever the
|
||||
* checkpoint interval is smaller: `plan_chunk` splits at the interval so a checkpoint is
|
||||
* always written, and that clamp comes FIRST. Printing only the budget would hide it -- every
|
||||
* budget above the interval runs the same chunk length, so a sweep over them reads as
|
||||
* "prefill is flat against the chunk" when nothing about the chunk changed. The clamp itself
|
||||
* is correct; a budget that silently does nothing is what has to be visible. A window
|
||||
* snapshot is taken at the prompt's tail and splits nothing. */
|
||||
const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt &&
|
||||
g.checkpoint_interval < cfg.max_tok)
|
||||
? g.checkpoint_interval : cfg.max_tok;
|
||||
/* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
|
||||
* when the interval is below --max-num-batched-tokens, raising the budget does not change the
|
||||
* chunk; the log line makes that visible. A window snapshot splits nothing. */
|
||||
const int64_t span_tok = g.checkpoint_interval * g.span;
|
||||
const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && span_tok < cfg.max_tok)
|
||||
? span_tok : cfg.max_tok;
|
||||
RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint "
|
||||
"interval %lld, max_tok %lld -> prefill chunks of at most %lld%s",
|
||||
(long long)g.quantum, (long long)g.attn_block, (long long)g.state_chunk,
|
||||
(long long)g.checkpoint_interval, (long long)cfg.max_tok, (long long)eff,
|
||||
eff < cfg.max_tok ? " (the checkpoint interval, not the budget)" : "");
|
||||
eff >= cfg.max_tok ? ""
|
||||
: g.span > 1 ? " (the checkpoint interval times the span, not the budget)"
|
||||
: " (the checkpoint interval, not the budget)");
|
||||
if (cfg.prefill_span > 1) {
|
||||
/* What the span does here, said once: the intervals the budget holds can be fewer than
|
||||
* the flag asks for, and a model without an interval grid spans nothing. */
|
||||
const int64_t held = g.span > 1 ? std::min(g.span, cfg.max_tok / g.checkpoint_interval) : 0;
|
||||
if (g.span <= 1)
|
||||
RAD_WARN("--prefill-span %lld: this model has no checkpoint interval grid (%s), so no "
|
||||
"chunk spans; a prefill alone in its step may still take the whole budget, "
|
||||
"and every other step is planned at %lld tokens", (long long)cfg.prefill_span,
|
||||
g.checkpoint_interval > 0 ? "its snapshots are taken at a prompt's end"
|
||||
: "it keeps no linear state",
|
||||
(long long)g.shared_tok);
|
||||
else if (held < 2)
|
||||
RAD_WARN("--prefill-span %lld does nothing: --max-num-batched-tokens %lld holds one "
|
||||
"checkpoint interval of %lld tokens, and a span of %lld needs %lld",
|
||||
(long long)cfg.prefill_span, (long long)cfg.max_tok,
|
||||
(long long)g.checkpoint_interval, (long long)cfg.prefill_span,
|
||||
(long long)(cfg.prefill_span * g.checkpoint_interval));
|
||||
else
|
||||
RAD_INFO("chunk geometry: a prefill alone in its step spans up to %lld intervals%s "
|
||||
"from its second interval on; every other step is planned at %lld tokens",
|
||||
(long long)held,
|
||||
held < g.span ? fmt(" (all the budget holds of the %lld asked)",
|
||||
(long long)g.span).c_str() : "",
|
||||
(long long)g.shared_tok);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
+43
-35
@@ -1,17 +1,11 @@
|
||||
/* geometry.h -- the chunk geometry, COMPUTED from the resolved kernels rather than documented as
|
||||
* a minimum an operator has to know.
|
||||
/* geometry.h -- the prefill chunk geometry, computed from the resolved kernels.
|
||||
*
|
||||
* vLLM makes a hybrid model's operator pass a minimum `--max-num-batched-tokens` by hand, because
|
||||
* it inflates the attention block size until it matches the mamba page and then asserts the batch
|
||||
* budget covers it. The constraint is real; the fact that a human has to carry the number is not.
|
||||
* Here declare has already resolved every kernel, so the constraints that produce it are in hand:
|
||||
* the attention block size comes off the resolved attention kernel (§7.2) and the linear-state
|
||||
* chunk length off whichever resolved kernels mark a parameter RAD_PROLE_SEQ_CHUNK, and the
|
||||
* reconciliation is arithmetic.
|
||||
*
|
||||
* If the resolved geometry needs more tokens than the operator budgeted, that is said at startup
|
||||
* with the number and the engine refuses -- rather than running something subtly wrong, which here
|
||||
* means chunks that never land on a checkpoint boundary and a linear prefix hit rate of zero.
|
||||
* The attention block size comes from the resolved attention kernel (§7.2) and the linear-state
|
||||
* chunk length from every resolved kernel that marks a parameter RAD_PROLE_SEQ_CHUNK, so the
|
||||
* operator never has to supply a minimum --max-num-batched-tokens by hand (as vLLM requires for
|
||||
* hybrid models). If the budget is below what the geometry needs, startup prints the number and
|
||||
* refuses: a smaller budget means chunks never land on a checkpoint boundary and the linear
|
||||
* prefix hit rate is zero.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -19,50 +13,64 @@
|
||||
namespace rad {
|
||||
|
||||
struct ChunkGeometry {
|
||||
/* The attention block size, reconciled across every paged KV group. Taken from the resolved
|
||||
* kernel; libr4d's paged attention is compiled for 16 and rejects anything else. */
|
||||
/* Attention block size, the lcm across every paged KV group. libr4d's paged attention is
|
||||
* compiled for 16 only. */
|
||||
int64_t attn_block = 1;
|
||||
|
||||
/* The length a linear-state scan tiles at -- libr4d's gated delta net is the one that has
|
||||
* one, at 64. Scanned off the constraints of every op whose schema marks a parameter
|
||||
* RAD_PROLE_SEQ_CHUNK, and off the geometry the architecture plugin declared them with. */
|
||||
/* Tile length of a linear-state scan (64 for libr4d's gated delta net). Taken from the
|
||||
* declared geometry and kernel constraints of every op whose schema marks a parameter
|
||||
* RAD_PROLE_SEQ_CHUNK. */
|
||||
int64_t state_chunk = 1;
|
||||
|
||||
/* What a NON-FINAL prefill chunk must be a multiple of: lcm(attn_block, state_chunk). A chunk
|
||||
* that ends here ends on an attention block boundary and on a linear chunk boundary at once,
|
||||
* so neither kernel is handed a partial tile it has to special-case. */
|
||||
/* lcm(attn_block, state_chunk); every non-final prefill chunk is a multiple of it, so no
|
||||
* kernel is handed a partial tile. */
|
||||
int64_t quantum = 1;
|
||||
|
||||
/* The linear-state checkpoint interval (§7.3), rounded UP from the operator's request to a
|
||||
* multiple of `quantum`, so splitting at an interval is automatically a legal chunk split.
|
||||
* Zero when the model has no linear state and checkpointing means nothing. */
|
||||
/* Linear-state checkpoint interval (§7.3): the operator's request rounded up to a multiple
|
||||
* of `quantum`, so a split at the interval is a legal chunk split. Zero without linear state
|
||||
* (see window_ckpt for the exception). */
|
||||
int64_t checkpoint_interval = 0;
|
||||
|
||||
/* How many intervals one prefill chunk may carry from an interval boundary past the first
|
||||
* (Config::prefill_span); 1 without an interval grid. plan_chunk is where it acts. */
|
||||
int64_t span = 1;
|
||||
|
||||
/* The budget of every step a span does not take (prefill_shared_tok). A span is for a prefill
|
||||
* alone in its step (Scheduler::step); a step carrying anything else is planned at this
|
||||
* budget as a deployment without a span plans it, so the span's extra rows never lengthen a
|
||||
* step other requests wait on. */
|
||||
int64_t shared_tok = 0;
|
||||
|
||||
/* The smallest --max-num-batched-tokens this geometry can be served with. */
|
||||
int64_t min_max_tok = 1;
|
||||
|
||||
/* An upper bound some kernel placed on the chunk length, or 0. Used only to detect a
|
||||
* contradiction, which is a kernel-set bug worth naming rather than clamping around. */
|
||||
/* Smallest upper bound a kernel places on the chunk length, or 0. Used only to report a
|
||||
* contradiction with `quantum`, never to clamp. */
|
||||
int64_t max_chunk = 0;
|
||||
|
||||
/* Every contributor by name, for the startup line and for the refusal. Built once. */
|
||||
/* Every contributor by name, for the startup line and the refusal. */
|
||||
std::string why;
|
||||
|
||||
/* NO LINEAR STATE, A SLIDING WINDOW: the checkpoint snapshots the window behind a prompt's
|
||||
* tail (KVManager::has_window_snapshot) and nothing else. Chunks are not split at the
|
||||
* interval -- a window snapshot in the middle of a prompt buys a later hit nothing its tail
|
||||
* does not -- and the interval is only the shortest prompt worth a snapshot. */
|
||||
/* No linear state but a sliding window: the checkpoint snapshots only the window behind a
|
||||
* prompt's tail (KVManager::has_window_snapshot). Chunks are not split at the interval, since
|
||||
* a mid-prompt window snapshot gains nothing; the interval is only the shortest prompt worth
|
||||
* a snapshot. */
|
||||
bool window_ckpt = false;
|
||||
|
||||
bool checkpoints() const { return checkpoint_interval > 0; }
|
||||
};
|
||||
|
||||
/* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration
|
||||
* alone: --max-num-batched-tokens less the span's extra intervals, at least one interval, and the
|
||||
* whole budget without a span. The engine states it to the plugin before declare
|
||||
* (RadBuildCtx::max_mixed_tok) and the scheduler plans by it, so the two agree. */
|
||||
int64_t prefill_shared_tok(const Config& cfg);
|
||||
|
||||
/* Resolve the geometry from the declared program and the operator's budgets.
|
||||
*
|
||||
* Returns RAD_OK, or RAD_E_INVAL when cfg.max_tok cannot serve the geometry -- in which case the
|
||||
* required number is in out->min_max_tok and the reason in out->why, and the caller is expected to
|
||||
* print both and stop. Returns RAD_E_SHAPE when two kernels' constraints cannot be satisfied at
|
||||
* once, which is a kernel-set bug and not an operator one. */
|
||||
* Returns RAD_E_INVAL when cfg.max_tok is too small (the required number is in
|
||||
* out->min_max_tok, the reason in out->why; the caller stops), and RAD_E_SHAPE when two kernels'
|
||||
* constraints contradict each other, which is a kernel-set bug. */
|
||||
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out);
|
||||
|
||||
} /* namespace rad */
|
||||
+115
-174
@@ -1,24 +1,14 @@
|
||||
/* mem_iface.h -- the seam between core/sched and core/mem.
|
||||
*
|
||||
* core/mem owns the concrete `KVManager` and `PrefixCache`. The scheduler binds to the pure-virtual
|
||||
* mirrors below rather than to those classes directly, for two reasons and neither is abstraction
|
||||
* for its own sake:
|
||||
* The scheduler binds to pure-virtual mirrors of core/mem's `KVManager` (kv.h) and `PrefixCache`
|
||||
* (prefix.h) instead of the classes themselves:
|
||||
*
|
||||
* - it lets tests/sched_test.cpp drive the scheduler against a block pool it can make
|
||||
* arbitrarily small, which is the only way to test admission refusal and preemption at all;
|
||||
* - it costs one indirect call per SEQUENCE per step (at most max_seqs, a few hundred), not one
|
||||
* per token, so it is off the part of the step path that is actually hot.
|
||||
* - tests/sched_test.cpp can drive the scheduler against an arbitrarily small block pool, the
|
||||
* only way to test admission refusal and preemption;
|
||||
* - the cost is one indirect call per sequence per step, not per token.
|
||||
*
|
||||
* `KVBinding` / `PCBinding` at the bottom adapt the concrete classes and require no change on
|
||||
* their side. They are templates so that they are only type-checked where the engine instantiates
|
||||
* them -- so a method core/mem does not provide is a compile error at exactly one line rather
|
||||
* than a comment nobody reads.
|
||||
*
|
||||
* The interface below mirrors core/mem/kv.h and core/mem/prefix.h.
|
||||
*
|
||||
* `CacheHit` comes from core/mem/prefix.h and is NOT redefined here. Two identical definitions of
|
||||
* a struct that crosses a component boundary is an ODR violation that costs nothing today and
|
||||
* becomes a silent layout mismatch the first time one side adds a field.
|
||||
* `KVBinding` / `PCBinding` at the bottom adapt the concrete classes. `CacheHit` comes from
|
||||
* core/mem/prefix.h; do not redefine it here (ODR).
|
||||
*/
|
||||
#pragma once
|
||||
#include <functional>
|
||||
@@ -31,10 +21,9 @@
|
||||
namespace rad {
|
||||
|
||||
/* ------------------------------------------------------------------ the KV manager */
|
||||
/* Keyed by SEQUENCE ID, which is the request id. The manager owns the block tables; Request::blocks
|
||||
* is not the source of truth and the scheduler does not read it. Two allocators disagreeing about
|
||||
* what a sequence owns is not a leak, it is the bug where a freed sequence's state slot is handed
|
||||
* to the next request while the first still reads it. */
|
||||
/* Keyed by sequence id (the request id). The manager owns the block tables; the scheduler does
|
||||
* not read Request::blocks, so there is one owner and a freed state slot cannot be handed out
|
||||
* while its previous sequence still reads it. */
|
||||
struct IKVManager {
|
||||
virtual ~IKVManager() = default;
|
||||
|
||||
@@ -43,98 +32,80 @@ struct IKVManager {
|
||||
virtual void free_sequence(uint64_t seq) = 0;
|
||||
|
||||
/* Grow the sequence's mapping to cover `n_tokens` in every group. RAD_E_FULL when a group's
|
||||
* free list is empty, which is a scheduling signal and not an error: the caller preempts a
|
||||
* victim and retries. */
|
||||
* free list is empty; the caller preempts a victim and retries. */
|
||||
virtual int ensure(uint64_t seq, int64_t n_tokens) = 0;
|
||||
/* The same, for a step whose first query sits at `keep_from` (the request's n_computed): a
|
||||
* WINDOW group then keeps every block that query can still read, however long the step is.
|
||||
* See KVManager::ensure. The default is for a manager with no windowed group. */
|
||||
/* As ensure(), for a step whose first query is at `keep_from` (the request's n_computed): a
|
||||
* window group keeps every block that query can still read (KVManager::ensure). The default
|
||||
* suits a manager with no windowed group. */
|
||||
virtual int ensure_from(uint64_t seq, int64_t n_tokens, int64_t keep_from) {
|
||||
(void)keep_from;
|
||||
return ensure(seq, n_tokens);
|
||||
}
|
||||
/* A committed step: a WINDOW group gives back what no later query can read. A no-op for a
|
||||
* manager with no windowed group. See KVManager::trim_window. */
|
||||
/* After a committed step, a window group frees what no later query can read
|
||||
* (KVManager::trim_window). */
|
||||
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
|
||||
/* The window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
|
||||
* defaults are a manager with none: no hit on a windowed trunk is ever resumed. */
|
||||
/* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
|
||||
* defaults mean no hit on a windowed trunk is ever resumed. */
|
||||
virtual bool has_window_snapshot() const { return false; }
|
||||
virtual int seed_window(uint64_t seq, int64_t pos) { (void)seq; (void)pos; return -1; }
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size -- a partial block is never shared, because the next token written into it would
|
||||
* corrupt the cache entry. */
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a multiple of the group's block
|
||||
* size; a shared partial block would be corrupted by the next token written into it. */
|
||||
virtual int adopt(uint64_t seq, int32_t group, const std::vector<int32_t>& blocks,
|
||||
int64_t n_tokens) = 0;
|
||||
|
||||
/* Free the blocks and mark the sequence for re-prefill. */
|
||||
virtual int preempt(uint64_t seq) = 0;
|
||||
|
||||
/* Could a sequence of this length EVER fit, in an empty pool? If not, preempting the whole
|
||||
* server would not help and the request is failed immediately rather than the engine
|
||||
* deadlocking on it (spec §17). */
|
||||
/* Whether a sequence of this length fits an empty pool. If not, the request fails at once
|
||||
* instead of deadlocking the engine (spec §17). */
|
||||
virtual bool can_ever_fit(int64_t n_tokens) const = 0;
|
||||
|
||||
virtual const std::vector<int32_t>& block_table(uint64_t seq, int32_t group) const = 0;
|
||||
virtual int32_t state_slot(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* THE WHOLE state_index ROW FOR A SEQUENCE, and how wide it is. One entry, normally: the
|
||||
* sequence's state. A group whose kernel asked for scratch beside the state names that too,
|
||||
* and the manager owns the mapping from column to physical slot because it owns the pool --
|
||||
* the scheduler stages the row and does not read it. Returns the width written, 0 for a
|
||||
* paged group. `max` bounds the write. */
|
||||
/* The sequence's state_index row: normally one entry (its state slot), plus any scratch
|
||||
* slots the group's kernel asked for. The manager owns the column-to-slot mapping; the
|
||||
* scheduler stages the row without reading it. Returns the width written (0 for a paged
|
||||
* group), at most `max`. */
|
||||
virtual int state_index_row(uint64_t seq, int32_t group, int32_t* out, int max) const = 0;
|
||||
virtual int64_t state_index_width(int32_t group) const = 0;
|
||||
|
||||
virtual int64_t free_blocks(int32_t group) const = 0;
|
||||
virtual int64_t total_blocks(int32_t group) const = 0;
|
||||
/* What anything is HOLDING, as against what may be handed out right now. See
|
||||
* KVManager::held_blocks: on an elastic pool the two differ by whatever the cache has
|
||||
* released, and an occupancy figure built from the second reads an idle server as full. */
|
||||
/* Blocks held by anything, as opposed to free_blocks (what can be handed out now). On an
|
||||
* elastic pool they differ by what the cache released (KVManager::held_blocks). */
|
||||
virtual int64_t held_blocks(int32_t group) const = 0;
|
||||
|
||||
/* THE SAME POOL IN BYTES. Blocks and tokens are both un-summable across groups -- a stateful
|
||||
* group has neither, and two paged groups share one token axis -- so bytes are the only
|
||||
* measure a reader can add up to "how much of the card is the KV cache holding". Asked of the
|
||||
* manager rather than derived here, because the manager owns the plan that knows whether a
|
||||
* group is counted in blocks or in states. */
|
||||
/* The pool in bytes, the only unit that sums across groups. Asked of the manager because its
|
||||
* plan knows whether a group counts blocks or states. */
|
||||
virtual int64_t pool_bytes(int32_t group) const = 0;
|
||||
virtual int64_t pool_bytes_used(int32_t group) const = 0;
|
||||
/* What the carve gave the group, which an elastic pool may have released part of. */
|
||||
/* What the carve gave the group; an elastic pool may have released part of it. */
|
||||
virtual int64_t pool_bytes_carved(int32_t group) const = 0;
|
||||
|
||||
/* HOW MANY TOKENS ONE BLOCK OF THIS GROUP COVERS, or 0 for a stateful group. The pool's
|
||||
* capacity in blocks is already here; the live request table wants it in TOKENS, because that
|
||||
* is the unit a request is measured in and the only one the two can be compared in. */
|
||||
/* Tokens one block covers, or 0 for a stateful group. */
|
||||
virtual int64_t block_tokens(int32_t group) const = 0;
|
||||
|
||||
/* SPECULATIVE REJECTION ROLLBACK (spec §10). A verify writes KV for 1 + n_spec
|
||||
* positions and the sampler accepts a prefix of them; the sequence's length must come back to
|
||||
* the accepted position and the blocks past it must go to the free list. `ensure` is monotone
|
||||
* and cannot express it.
|
||||
*
|
||||
* It is a slot-table edit and nothing else -- crucially it does NOT touch the linear or conv
|
||||
* groups, whose rollback is a change of read offset the kernels perform themselves. Without
|
||||
* this the pool leaks one block per rejected block-crossing, which is a slow leak and
|
||||
* therefore the worst kind. */
|
||||
/* Speculative rejection rollback (spec §10). A verify writes KV for 1 + n_spec positions and
|
||||
* the sampler accepts a prefix; this shrinks the sequence to `n_tokens` and frees blocks past
|
||||
* it, which the monotone ensure() cannot. Only the slot table changes: linear and conv groups
|
||||
* roll back by read offset inside their kernels. */
|
||||
virtual int rollback(uint64_t seq, int64_t n_tokens) = 0;
|
||||
|
||||
/* THE ABSOLUTE TOKEN POSITION that block_table(seq, group)[0] covers. Zero for a
|
||||
* FULL group and non-zero for a WINDOW group, whose blocks below the window are recycled: the
|
||||
* step batch's slot mapping is `(pos - first_block_pos) / block_size`, and with the offset
|
||||
* missing every sliding-window sequence writes its KV to the wrong slot the moment it passes
|
||||
* its window. KVManager::Seq already tracks this privately as `first_block_pos`. */
|
||||
/* Absolute token position that block_table(seq, group)[0] covers: zero for a full group,
|
||||
* non-zero for a window group once blocks below the window are recycled. The step batch maps
|
||||
* a slot as `(pos - first_block_pos) / block_size`. */
|
||||
virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* THE ENTRIES OF block_table(seq, group) THAT CHANGED since the previous call: everything
|
||||
* below the returned index is unchanged, and INT64_MAX says nothing changed. Reading clears
|
||||
* 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. */
|
||||
/* Index of the first entry of block_table(seq, group) changed since the previous call;
|
||||
* INT64_MAX if none.
|
||||
* Reading clears it, so the batch builder, which keeps the device copy and stages only the
|
||||
* changed tail, must be the only caller. 0 is always correct (restage 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. */
|
||||
/* Whether the snapshot store still holds `slot`. The scheduler checks before building a
|
||||
* restore step, since a released slot may hold another session's state. */
|
||||
virtual bool checkpoint_held(int32_t slot) const = 0;
|
||||
};
|
||||
|
||||
@@ -142,53 +113,42 @@ struct IKVManager {
|
||||
struct IPrefixCache {
|
||||
virtual ~IPrefixCache() = default;
|
||||
|
||||
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
|
||||
* `blocks_out` receives the block ids per cached group, in cached_groups() order, ready for
|
||||
* IKVManager::adopt. */
|
||||
/* GIVE BACK WHATEVER THE TIERS HOLD FOR THIS PROMPT, before the lookup that would otherwise
|
||||
* stop at it.
|
||||
*
|
||||
* The scheduler calls it and must not know what a tier is: a restore allocates blocks and
|
||||
* runs a device scatter, so it is the engine's to perform and is installed as a callable
|
||||
* rather than reached through this header. A failure is not an error here -- it leaves a
|
||||
* shorter prefix, and a shorter prefix is always safe. */
|
||||
/* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine
|
||||
* performs it (it allocates blocks and runs a device scatter). A failure only leaves a
|
||||
* shorter prefix, which is always safe. */
|
||||
virtual void restore(const Request&) {}
|
||||
/* A step's admissions begin: what the last step's lookups handed out has been read. */
|
||||
/* A step's admissions begin; the last step's lookup results have been consumed. */
|
||||
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. */
|
||||
/* Keep this waiting request's chain in VRAM until release(). Called when admission is refused
|
||||
* after restore(), so the restored chain is not moved out again before the next attempt. */
|
||||
virtual void hold(const Request&) {}
|
||||
/* The request is gone -- finished, failed or cancelled -- and holds nothing any more. */
|
||||
/* The request finished, failed or was cancelled and holds nothing any more. */
|
||||
virtual void release(const Request&) {}
|
||||
|
||||
/* `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
|
||||
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
|
||||
* `blocks_out` receives block ids per cached group, in cached_groups() order, for
|
||||
* IKVManager::adopt. `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.
|
||||
* Without this the cache is only ever read: every lookup misses, `cached_tokens` is always
|
||||
* zero, and a chat client re-prefills its whole history on every turn, which for a long
|
||||
* conversation is seconds a message. `blocks[i]` is the block table of cached_groups()[i], and
|
||||
* `n_tokens` how many of them are backed. Takes a KV reference on every newly indexed block,
|
||||
* so it must be called BEFORE the sequence's own blocks are released. */
|
||||
/* Publish what this sequence computed so a later request sharing the prefix can adopt it.
|
||||
* `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
|
||||
* backed. Takes a KV reference on every newly indexed block, so call it before the sequence's
|
||||
* own blocks are released. */
|
||||
virtual int insert(const Request& r, const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) = 0;
|
||||
|
||||
/* Release the least recently used entries, and with them their KV references. The cache holds
|
||||
* 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. */
|
||||
/* Release the least recently used entries and their KV references. The scheduler tries this
|
||||
* before preempting a running request. */
|
||||
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. */
|
||||
/* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike
|
||||
* evict(), it skips entries a live sequence still holds (no block would be freed) and entries
|
||||
* whose only copy is in VRAM. Returns the number of blocks freed. */
|
||||
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
|
||||
* evictions would leave every such conversation behind. Returns how many entries went. */
|
||||
/* Drop every entry in every tier. Implementations with idle tiers must override this: there,
|
||||
* evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */
|
||||
virtual int64_t reset() {
|
||||
int64_t dropped = 0;
|
||||
for (int guard = 0; guard < 65536; ++guard) {
|
||||
@@ -199,60 +159,50 @@ struct IPrefixCache {
|
||||
return dropped;
|
||||
}
|
||||
|
||||
/* HOW MANY ENTRIES THE CACHE HAS THROWN AWAY, which is the leading indicator of the failure
|
||||
* mode that matters operationally: once the pool is utilised past the reserve the scheduler
|
||||
* keeps free (a quarter of it), the cache begins evicting prefixes that are about to be
|
||||
* reused, and an agent's next turn re-prefills its whole context -- turning a cached turn of
|
||||
* a few seconds into a full prefill of a very long prompt. `prefix_hit_rate` only falls AFTER
|
||||
* that has happened; this count rises first. */
|
||||
/* Entries evicted, cumulative. Once the pool fills past the scheduler's reserve (a quarter of
|
||||
* it), the cache evicts prefixes about to be reused; this count rises before the hit rate
|
||||
* falls. */
|
||||
virtual int64_t evictions() const = 0;
|
||||
virtual int64_t ckpt_evictions() const = 0;
|
||||
/* And what --prefix-cache-ttl took: not memory pressure, so not evictions. */
|
||||
/* ckpt_evictions by reason, and reservations that found nothing to give up
|
||||
* (PrefixCache::Stats). */
|
||||
struct CkptCounts { int64_t retired = 0, lru = 0, refused = 0; };
|
||||
virtual CkptCounts ckpt_counts() const { return {}; }
|
||||
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
|
||||
virtual int64_t expired() const { return 0; }
|
||||
virtual int64_t ckpt_expired() const { return 0; }
|
||||
|
||||
/* WHAT IT IS HOLDING ON ITS OWN RIGHT NOW, in tokens of context, as against the counters
|
||||
* above which are cumulative. A finished turn's blocks stay held so the next turn can reuse
|
||||
* them, so on any server serving conversations MOST of a full KV pool is this rather than the
|
||||
* live sequences -- and with one number for the pool there is no way to see that, which makes
|
||||
* a working cache indistinguishable from a leak.
|
||||
*
|
||||
* ON ITS OWN is the whole of it. A cached block a running sequence is also reading is not
|
||||
* memory the cache is keeping back from anybody, and counting those would make a single 200K
|
||||
* request look like a cache refusing to release 200K. */
|
||||
/* Tokens of context held only by the cache right now. Blocks a running sequence also reads
|
||||
* are excluded. Separates a working cache from a leak in the pool figures. */
|
||||
virtual int64_t held_tokens() const = 0;
|
||||
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
* checkpoint lands on a boundary. */
|
||||
virtual int64_t next_checkpoint_after(int64_t pos) const = 0;
|
||||
|
||||
/* Reserve the snapshot slot the scheduler is about to WRITE. Retention is budgeted (§7.3:
|
||||
* ~96 MiB a snapshot, so 64 of them is 6 GiB), which makes RAD_E_FULL an ordinary condition
|
||||
* and not a failure -- the scheduler simply does not write a checkpoint at that boundary and
|
||||
* the next hit replays from the previous one. */
|
||||
/* Reserve the snapshot slot the scheduler is about to write. Retention is budgeted (§7.3: on
|
||||
* Qwen3.5-27B a snapshot is 144 MiB, and a 128K session at the default interval is 64 of them,
|
||||
* about 9 GiB), so RAD_E_FULL is ordinary: no checkpoint is written at that boundary and a
|
||||
* later hit replays from the previous one. */
|
||||
virtual int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) = 0;
|
||||
|
||||
/* 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. */
|
||||
/* The reserved state is now in its slot. Reservation happens at planning, before the step
|
||||
* computes the state, so lookup does not offer the slot until this is called. */
|
||||
virtual void commit_checkpoint(const Request& r, int64_t pos) = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ block geometry */
|
||||
/* Everything the step batch needs to turn a token position into a KV slot, read off the declared
|
||||
* program rather than off the manager: block size is KVGroupInfo::block_size, which the build
|
||||
* component already took from the resolved attention kernel's constraints (§7.2). Duplicating it
|
||||
* through a second interface would be a second place for it to be wrong. */
|
||||
/* What the step batch needs to turn a token position into a KV slot, read from the declared
|
||||
* program: KVGroupInfo::block_size comes from the resolved attention kernel's constraints
|
||||
* (§7.2). */
|
||||
struct KVGeom {
|
||||
struct G {
|
||||
int kind = RAD_KV_FULL;
|
||||
int64_t block_size = 1;
|
||||
int64_t window = 0;
|
||||
bool paged = true;
|
||||
/* Columns in this group's state_index row. The MANAGER decides it -- it depends on what
|
||||
* the group's kernel wants beside the state -- so KVGeom::of leaves it at 1 and the
|
||||
* scheduler fills it in from the configured pool. */
|
||||
/* Columns in this group's state_index row. The manager decides it, so KVGeom::of leaves
|
||||
* it at 1 and the scheduler fills it in from the configured pool. */
|
||||
int64_t sidx_width = 1;
|
||||
};
|
||||
std::vector<G> g;
|
||||
@@ -282,8 +232,7 @@ struct KVGeom {
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ binding the concrete classes */
|
||||
/* Templates, so nothing here is type-checked until the engine instantiates it against the real
|
||||
* classes. That instantiation is where a mismatch with core/mem is reported. */
|
||||
/* Templates, so a mismatch with core/mem is reported where the engine instantiates them. */
|
||||
template <class KV>
|
||||
struct KVBinding final : IKVManager {
|
||||
KV* m;
|
||||
@@ -330,11 +279,9 @@ struct KVBinding final : IKVManager {
|
||||
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
|
||||
* Request, because the placeholder ids inside a media run are identical for every picture: hashing
|
||||
* the ids alone would serve one request another's image. Each run is keyed by its item's content
|
||||
* key (core/mm, taken over the processed patches) and its segment, so the same picture at the same
|
||||
* place hits -- and skips the encoder along with the prefill -- and two pictures never alias. */
|
||||
/* Content keys for a request's media runs. Placeholder ids are identical for every picture, so
|
||||
* the prefix cache also hashes each run's item content key (core/mm, over the processed patches)
|
||||
* and segment: the same picture at the same place hits, two pictures never alias. */
|
||||
inline void media_keys(const Request& r, std::vector<MMContentKey>* out) {
|
||||
out->clear();
|
||||
if (!r.media) return;
|
||||
@@ -376,9 +323,8 @@ struct PCBinding final : IPrefixCache {
|
||||
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
|
||||
* conversation sends the reply back as part of its prompt, so a cache that indexed only the
|
||||
* prompt would stop hitting at the first assistant token and re-prefill everything after it. */
|
||||
/* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
|
||||
* prompt alone would stop hitting at the first assistant token. */
|
||||
int insert(const Request& r, const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) override {
|
||||
std::vector<int32_t> toks;
|
||||
@@ -386,20 +332,16 @@ struct PCBinding final : IPrefixCache {
|
||||
toks.insert(toks.end(), r.prompt.begin(), r.prompt.end());
|
||||
toks.insert(toks.end(), r.output.begin(), r.output.end());
|
||||
if (n_tokens > (int64_t)toks.size()) n_tokens = (int64_t)toks.size();
|
||||
/* r.id is the session, and it is the SAME id reserve_checkpoint keys its snapshots by --
|
||||
* so the tiers' session view and the checkpoint index are talking about one thing. */
|
||||
/* r.id is the session, the same id reserve_checkpoint keys its snapshots by. */
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens, r.session_label);
|
||||
}
|
||||
/* 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. */
|
||||
/* Installed by the engine when the idle tiers are on: lands every pending host copy now and
|
||||
* returns whether any landed. Runs 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, 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. */
|
||||
/* Under pressure, first drop entries whose host copy has landed (trim), then land pending
|
||||
* copies and trim again. Only the rest is erased; with tiers on, an erase is warned about,
|
||||
* since a later turn will prefill that conversation 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);
|
||||
@@ -427,23 +369,20 @@ struct PCBinding final : IPrefixCache {
|
||||
}
|
||||
int64_t evictions() const override { return m->stats().evictions; }
|
||||
int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; }
|
||||
CkptCounts ckpt_counts() const override {
|
||||
const auto& st = m->stats();
|
||||
return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused };
|
||||
}
|
||||
int64_t expired() const override { return m->stats().expired; }
|
||||
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
|
||||
int64_t held_tokens() const override { return m->unshared_tokens(); }
|
||||
|
||||
int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); }
|
||||
int reserve_checkpoint(const Request& r, int64_t pos, int32_t* slot_out) override {
|
||||
/* The cache keys a snapshot by the CHAINED HASH of the prefix it covers, and the chain is
|
||||
* built here rather than inside the cache because the cache does not hold the tokens --
|
||||
* that is the whole reason this interface passes a Request. It must be the SAME chain
|
||||
* lookup() walks, or a checkpoint reserved at `pos` and a later hit at `pos` name two
|
||||
* different entries and the linear cache silently never hits.
|
||||
*
|
||||
* The prefix is prompt ++ output: a checkpoint written during decode covers tokens the
|
||||
* request has generated, and keying it on the prompt alone would alias every continuation
|
||||
* of the same prompt onto one snapshot -- which is one session's recurrent state served to
|
||||
* another. Whole blocks only; a partial block is never keyed, because the next token
|
||||
* written into it would change what the key stands for. */
|
||||
/* A snapshot is keyed by the chained hash of the prefix it covers, built here because the
|
||||
* cache does not hold the tokens. It must match the chain lookup() walks, or the linear
|
||||
* cache never hits. The prefix is prompt ++ output, so continuations of one prompt do not
|
||||
* share a snapshot; whole blocks only, since a partial block's key would change. */
|
||||
return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out);
|
||||
}
|
||||
|
||||
@@ -452,9 +391,11 @@ struct PCBinding final : IPrefixCache {
|
||||
}
|
||||
|
||||
private:
|
||||
/* The chain reserve_checkpoint keys on, factored out so commit cannot drift from it: two
|
||||
* copies of this walk that agreed when written would be two copies that could stop agreeing,
|
||||
* and the symptom would be a checkpoint that is written and never found. */
|
||||
uint64_t lost_warned_ns_ = 0;
|
||||
mutable std::vector<int32_t> blk_; /* prefix_hash's block of tokens, kept for its capacity */
|
||||
|
||||
/* The chain reserve_checkpoint and commit_checkpoint both key on; shared so they cannot
|
||||
* drift apart. */
|
||||
BlockHash prefix_hash(const Request& r, int64_t pos) const {
|
||||
media_keys(r, &mm_);
|
||||
const int64_t bs = m->block_size();
|
||||
@@ -463,14 +404,14 @@ private:
|
||||
const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size();
|
||||
const int64_t have = np + no;
|
||||
const int64_t n_blocks = (pos < have ? pos : have) / bs;
|
||||
std::vector<int32_t> blk((size_t)bs);
|
||||
blk_.resize((size_t)bs);
|
||||
for (int64_t b = 0; b < n_blocks; ++b) {
|
||||
const int64_t base = b * bs;
|
||||
for (int64_t j = 0; j < bs; ++j) {
|
||||
const int64_t k = base + j;
|
||||
blk[(size_t)j] = k < np ? r.prompt[(size_t)k] : r.output[(size_t)(k - np)];
|
||||
blk_[(size_t)j] = k < np ? r.prompt[(size_t)k] : r.output[(size_t)(k - np)];
|
||||
}
|
||||
h = chain_block_hash(h, blk.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base);
|
||||
h = chain_block_hash(h, blk_.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
+47
-68
@@ -1,9 +1,7 @@
|
||||
/* metrics.h -- the scheduler's snapshot, for the server's /metrics endpoint (spec §14).
|
||||
/* metrics.h -- the scheduler's snapshot for the server's /metrics endpoint (spec §14).
|
||||
*
|
||||
* A plain struct of numbers with no strings built and nothing formatted. Formatting belongs to
|
||||
* whoever is exporting -- Prometheus wants vLLM-compatible names, the live view wants a terminal
|
||||
* line, and a scheduler that rendered either would have to be edited to add the other. Fixed
|
||||
* arrays, so a scrape allocates nothing and cannot contend with the step path for the allocator.
|
||||
* Plain numbers only; each exporter (Prometheus, the live view) does its own formatting. Fixed
|
||||
* arrays, so a scrape allocates nothing and never contends with the step path for the allocator.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
@@ -28,45 +26,28 @@ struct SchedMetrics {
|
||||
int64_t preemptions = 0;
|
||||
int64_t steps = 0;
|
||||
|
||||
/* STEPS BY SHAPE, AND WHAT SPECULATION DID NOT REACH. `steps_mixed` over `steps` says how
|
||||
* often the load produces a step carrying both a prefill chunk and decode rows; an agentic
|
||||
* load produces them often enough to be worth measuring.
|
||||
*
|
||||
* `decode_rows_unspeculated` counts every decode row that took no draft, whatever the reason
|
||||
* -- depth 0, a request that may not speculate, a drafter with nothing to propose. Counting
|
||||
* ROWS rather than any one reason keeps it the answer to "how much of my decode is running
|
||||
* unspeculated" as the set of reasons changes. Without it the loss is invisible: throughput
|
||||
* falls and every explanation fits. */
|
||||
/* Steps by shape. `steps_mixed` counts steps carrying both a prefill chunk and decode rows.
|
||||
* `decode_rows_unspeculated` counts every decode row that took no draft, for any reason
|
||||
* (depth 0, a request that may not speculate, a drafter with nothing to propose). */
|
||||
int64_t steps_prefill = 0;
|
||||
int64_t steps_mixed = 0;
|
||||
int64_t steps_decode = 0;
|
||||
/* --prefill-interleave: decode-only steps the hold inserted, issued ahead or not; each kept a
|
||||
* ready chunk out. */
|
||||
int64_t steps_held = 0;
|
||||
int64_t decode_rows_unspeculated = 0;
|
||||
/* STEPS ISSUED AHEAD: a step whose forward pass went onto the card behind the step before it,
|
||||
* before that step committed (Scheduler::step_next). Every other step waits for the host's
|
||||
* commit and staging with the card idle, so steps_ahead against steps is how much of the run
|
||||
* kept the card fed through the host's part of it. */
|
||||
/* Steps whose forward pass was enqueued behind the previous step before it committed
|
||||
* (Scheduler::step_next). Every other step leaves the card idle during the host's commit and
|
||||
* staging. */
|
||||
int64_t steps_ahead = 0;
|
||||
/* PREFILL CHUNKS HELD BACK for other work in the same step (--busy-prefill-chunk): each is a
|
||||
* chunk that would have taken more of the step and left decode rows behind it, or a request
|
||||
* waiting to be admitted, with nothing. Zero under `off`, and on a load that never overlaps a
|
||||
* prefill with anything else. */
|
||||
/* Prefill chunks capped to leave room for decode rows or a waiting admission in the same
|
||||
* step (--busy-prefill-chunk). Zero under `off`. */
|
||||
int64_t prefill_chunks_capped = 0;
|
||||
|
||||
/* HOW LONG THE ENGINE SPENT INSIDE A STEP, cumulative nanoseconds, and the decode half of it
|
||||
* separately. Neither is a derived rate -- they are counters, and that is the point.
|
||||
*
|
||||
* A STEP TIME IS NOT WALL TIME OVER A STEP COUNT, and a gauge that computes it that way is
|
||||
* wrong in two directions at once. An engine that idles between requests -- which is every
|
||||
* agent, every chat client, every tool loop -- charges the idle gap to the steps around it,
|
||||
* inflating the step time by however long nothing was running. And a prefill chunk costs an
|
||||
* order of magnitude more than a decode step, so a load that mixes them averages two
|
||||
* populations and calls the result the step time. Both faults are invisible without an
|
||||
* instrument: the number is plausible, it moves with load, and nothing contradicts it.
|
||||
*
|
||||
* With these, `step_ns_decode / steps_decode` is a decode step time that needs no window, no
|
||||
* saturation assumption and no second endpoint. Charged from the scheduler's own
|
||||
* `step_start_`, which is the same clock `decode_tps` already uses -- so this adds no
|
||||
* synchronisation and no timing mode (spec §16). */
|
||||
/* Cumulative nanoseconds spent inside steps, total and for decode steps only. Wall time over
|
||||
* a step count is not a step time: it charges idle gaps between requests to steps and mixes
|
||||
* prefill with decode. `step_ns_decode / steps_decode` is the decode step time. Measured from
|
||||
* `step_start_`, the clock `decode_tps` uses, so no extra synchronisation (spec §16). */
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
|
||||
@@ -77,44 +58,44 @@ struct SchedMetrics {
|
||||
int64_t blocks_total = 0;
|
||||
int64_t blocks_free = 0;
|
||||
float utilisation = 0.0f; /* 1 - free/total */
|
||||
/* 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. */
|
||||
/* Tokens one block covers, 0 for a stateful group. */
|
||||
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. */
|
||||
/* A windowed group recycles blocks below the window, so its size bounds how far back a
|
||||
* sequence sees, not 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
|
||||
* reports a pool the card does not have. */
|
||||
/* The group in bytes, the only unit that sums across groups: a stateful group has no
|
||||
* token axis, and paged groups share one, so summed tokens overcount. */
|
||||
int64_t bytes_total = 0;
|
||||
int64_t bytes_used = 0;
|
||||
/* WHAT IT WAS CARVED TO ADDRESS, as against bytes_total, which is what the card is
|
||||
* actually holding for it. The two differ by what the elastic pool has released: the
|
||||
* cache releases the VRAM behind blocks nothing holds, and the difference between these
|
||||
* two numbers is exactly what it gave back. Equal otherwise. */
|
||||
/* Bytes the group was carved to address. bytes_total is what the card holds now; the
|
||||
* difference is the VRAM the elastic pool released behind unheld blocks. */
|
||||
int64_t bytes_carved = 0;
|
||||
} kv[RAD_SCHED_MAX_KV_GROUPS];
|
||||
|
||||
/* Prefix caching (§7.3). Attention and linear are reported separately because they hit at
|
||||
* different granularities and a single number would hide exactly the effect the decoupling
|
||||
* was for. */
|
||||
* different granularities. */
|
||||
int64_t prompt_tokens = 0;
|
||||
int64_t attn_cached_tokens = 0;
|
||||
int64_t linear_cached_tokens = 0;
|
||||
float attn_hit_rate = 0.0f;
|
||||
/* Cumulative, from the prefix cache itself. Rising evictions under a steady workload
|
||||
* mean the pool cannot hold the working set and turn-2 latency is about to collapse. */
|
||||
/* Cumulative, from the prefix cache. Rising evictions under a steady workload mean the pool
|
||||
* cannot hold the working set. */
|
||||
int64_t prefix_evictions = 0;
|
||||
int64_t prefix_ckpt_evictions = 0;
|
||||
/* prefix_ckpt_evictions by reason (retention policy, least recently used of a full store),
|
||||
* and reservations that went without a snapshot. */
|
||||
int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
|
||||
int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */
|
||||
/* WHAT THE CACHE IS HOLDING ON ITS OWN NOW, in tokens of context: the part of the pool that
|
||||
* an eviction would actually free, because no live sequence is reading it. The pool figure
|
||||
* above counts a held block whoever holds it, and on a server serving conversations most of
|
||||
* it is this rather than the running requests -- so without it a working cache and a leak are
|
||||
* the same picture. Blocks shared with a running sequence are NOT in it; counting them would
|
||||
* make one long request read as a cache that would not release its context. Same token axis
|
||||
* as the paged groups, so it is comparable with kv_tokens_used. */
|
||||
/* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
|
||||
* state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
|
||||
* that could not be adopted. `hit_cut_tokens` is the checkpoint shortfall: prompt tokens the
|
||||
* attention cache held and the admission computed again, because the hit resumed at a
|
||||
* snapshot below it or was cut to nothing. */
|
||||
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
|
||||
int64_t hit_cut_tokens = 0;
|
||||
/* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks
|
||||
* shared with a running sequence. Same token axis as the paged groups, so comparable with
|
||||
* kv_tokens_used. */
|
||||
int64_t prefix_held_tokens = 0;
|
||||
float linear_hit_rate = 0.0f;
|
||||
int64_t checkpoints_written = 0;
|
||||
@@ -135,18 +116,16 @@ struct SchedMetrics {
|
||||
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
|
||||
* earlier position was accepted and this one was therefore evaluated, `accepted` how often it
|
||||
* was then taken. Their ratio is the conditional hazard, which is the number that says what a
|
||||
* deeper draft would actually buy. `draft_depth_seen` bounds how much of the arrays is real. */
|
||||
/* Per draft position: `reached` counts verifies where every earlier position was accepted,
|
||||
* `accepted` how often this one was then taken. Their ratio is the conditional acceptance,
|
||||
* which says what a deeper draft would buy. `draft_depth_seen` bounds the valid entries. */
|
||||
enum { RAD_METRICS_MAX_SPEC = 64 };
|
||||
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. */
|
||||
/* Adaptive window (--draft-window adaptive, draft.h); all zero while off. The gauge is the
|
||||
* mean window over running sequences; the cumulative histogram counts verifies by window,
|
||||
* index = drafts verified. */
|
||||
bool draft_adaptive = false;
|
||||
float draft_depth_adaptive = 0.0f;
|
||||
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
|
||||
|
||||
+743
-900
File diff suppressed because it is too large.
Load diff
+245
-354
@@ -1,21 +1,15 @@
|
||||
/* scheduler.h -- continuous batching, chunked prefill, a priority queue, preemption by recompute.
|
||||
* ONE scheduler decision per step, producing ONE RadBatch (spec §7.1).
|
||||
/* scheduler.h -- continuous batching, chunked prefill, a priority queue and preemption by
|
||||
* recompute. One scheduler decision per step, producing one RadBatch (spec §7.1).
|
||||
*
|
||||
* Host time spent here is time the GPU spends idle, so this component is written to be cheap and
|
||||
* to build things once. Everything on the step path comes out of a pool sized at max_tok /
|
||||
* max_seqs; the only allocation the scheduler performs is on arrival and completion, which are
|
||||
* the HTTP thread's problem and not the step's.
|
||||
* Host time spent here is GPU idle time. The step path allocates nothing: its storage is sized at
|
||||
* max_tok / max_seqs, and allocation happens only on arrival and completion (HTTP threads).
|
||||
*
|
||||
* Two things it owns that vLLM's does not:
|
||||
*
|
||||
* - CHUNK BOUNDARIES, and it uses that. A prefill chunk splits at a linear-state checkpoint
|
||||
* interval, so a checkpoint is always WRITTEN rather than landing wherever a step happened to
|
||||
* end. vLLM writes one only when a step's end coincides with a boundary, which is why a
|
||||
* checkpoint landing in request-unique tokens silently drops linear caching to zero. The cost
|
||||
* of doing it this way is an occasional short chunk; the benefit is that hit rate is a
|
||||
* property of the workload rather than of scheduling luck (§7.3).
|
||||
*
|
||||
* - DRAFT DEPTH, controlled against measured acceptance (draft.h, §10).
|
||||
* Unlike vLLM's scheduler it also owns:
|
||||
* - Chunk boundaries. A prefill chunk splits at a linear-state checkpoint interval, so a
|
||||
* checkpoint is always written instead of only when a step happens to end on a boundary.
|
||||
* The cost is an occasional short chunk; the hit rate then depends on the workload, not on
|
||||
* scheduling luck (§7.3).
|
||||
* - Draft depth, controlled against measured acceptance (draft.h, §10).
|
||||
*/
|
||||
#pragma once
|
||||
#include "batch.h"
|
||||
@@ -30,26 +24,20 @@
|
||||
namespace rad {
|
||||
|
||||
/* The scheduler's own per-request state. Request (rad_core.h) is shared across components and
|
||||
* frozen; anything only the scheduler needs lives here, so adding a scheduling concept never
|
||||
* touches a struct three other components read. */
|
||||
* frozen; state only the scheduler needs lives here. */
|
||||
struct SchedReq {
|
||||
std::unique_ptr<Request> req;
|
||||
uint64_t arrival = 0; /* monotonic; the tiebreak below priority, and what makes a
|
||||
* preempted request re-enter AHEAD of everything admitted after
|
||||
* it rather than at the back of the queue */
|
||||
uint64_t arrival = 0; /* monotonic; the tiebreak below priority. A preempted request
|
||||
* keeps it, so it re-enters ahead of later arrivals */
|
||||
int32_t slot = -1;
|
||||
/* THE CARD'S INDEX FOR THIS SEQUENCE: which StepSlot the advance reads and writes (advance.h),
|
||||
* and so the sequence identity a batch carries. It is NOT `slot`. A slot is taken on arrival,
|
||||
* so a queue behind the admission limit -- or a burst arriving while the last one's requests
|
||||
* are still held for their final commit -- numbers slots past max_seqs, and the card has
|
||||
* max_seqs StepSlots. The card index is taken on admission from a pool of exactly that many
|
||||
* and given back with the sequence's KV (free_kv, preempt_back), so it lives as long as any
|
||||
* step in flight can still name it and never longer. */
|
||||
/* The card's index for this sequence: the StepSlot the advance reads and writes (advance.h),
|
||||
* and the sequence identity a batch carries. Not `slot`, which is taken on arrival and can
|
||||
* exceed the card's max_seqs StepSlots. Taken on admission from a pool of max_seqs and
|
||||
* returned with the sequence's KV (free_kv, preempt_back). */
|
||||
int32_t card = -1;
|
||||
bool running = false;
|
||||
|
||||
/* WALL CLOCK, for the live request table. `arrival` above is a monotonic COUNTER -- it
|
||||
* orders the queue and cannot say how long anything has been in it. */
|
||||
/* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
|
||||
int64_t arrived_us = 0;
|
||||
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
|
||||
|
||||
@@ -59,47 +47,22 @@ struct SchedReq {
|
||||
int32_t n_draft = 0;
|
||||
int32_t conv_cursor = 0;
|
||||
|
||||
/* HOW MUCH OF A SERIAL DRAFTER`S OWN ATTENTION HISTORY IS VALID: positions [0, draft_filled)
|
||||
* of the head`s layer hold K and V computed from the tokens the sequence actually has. The
|
||||
* head attends to its own layer and nothing else in the engine writes it -- a prefill fills
|
||||
* the trunk`s layers and leaves the head`s untouched -- so the drafter runs a history pass
|
||||
* over whatever the last step added before it drafts. Zero on admission and on preemption,
|
||||
* which is what makes a recomputed sequence refill it rather than trust a stale watermark. */
|
||||
/* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
|
||||
* K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
|
||||
* it runs a history pass over what the last step added. */
|
||||
int64_t draft_filled = 0;
|
||||
|
||||
/* THE RANGE OF A BLOCK DRAFTER'S OWN KV CACHE THAT HOLDS REAL K AND V, as [draft_lo,
|
||||
* draft_hi). Two numbers rather than a serial head's one because the low end CAN move: such a
|
||||
* drafter has a KV group of its own, and whether a hit leaves that group short depends on
|
||||
* whether prefix.cpp caches it -- see hit_holes_draft_. A WINDOWED drafter's group is skipped
|
||||
* (a hit's blocks do not describe a cache whose floor moves), so a sequence that hits at
|
||||
* position P has trunk K and V from 0 and draft K and V only from P, and drafting waits until
|
||||
* the drafter's window has slid past P rather than attending to blocks nobody wrote.
|
||||
*
|
||||
* A FULL-ATTENTION DRAFTER'S GROUP IS CACHED LIKE THE TRUNK'S and the floor stays 0. Treating
|
||||
* one as windowed disables drafting outright: a windowless drafter has no window to slide, so
|
||||
* "wait until the window has passed P" is a condition that can never come true, and a workload
|
||||
* that hits the prefix cache on every turn would then never draft again.
|
||||
* Both zero on admission and on preemption, which is what makes a recomputed sequence refill
|
||||
* rather than trust a stale watermark. */
|
||||
/* The range [draft_lo, draft_hi) of a block drafter's own KV cache that holds real K and V.
|
||||
* The low end is non-zero when a prefix hit left the drafter's group uncached
|
||||
* (hit_holes_draft_); drafting then waits until the window has slid past it. */
|
||||
int64_t draft_lo = 0;
|
||||
int64_t draft_hi = 0;
|
||||
|
||||
/* EVERY PIECE OF DRAFTER STATE THAT DESCRIBES THE SEQUENCE IN THIS SLOT, cleared together.
|
||||
*
|
||||
* A slot is RECYCLED: add() takes one off `free_slots_` and the SchedReq in it is the last
|
||||
* request's object, so anything not reset here is inherited by a sequence that has nothing to
|
||||
* do with it. Both watermarks above say "zero on admission and on preemption", and a list of
|
||||
* fields spelled out at each call site is what lets one of them go unreset; hence one function,
|
||||
* called from both.
|
||||
*
|
||||
* WHAT A SURVIVING WATERMARK COSTS. `draft_filled` carried into the next request at the
|
||||
* previous one's total length makes its prefill compute `hs = max(draft_filled, ctx_len)` =
|
||||
* the stale watermark, `he` clamps up to meet it, and the history pass comes out EMPTY -- so
|
||||
* the MTP head's layer of the attention cache is never written for the whole prompt and the
|
||||
* head drafts against whatever the pool last held. The drafts are then wrong, so acceptance
|
||||
* moves, so the committed lengths move, so the arithmetic of every later step moves: the same
|
||||
* greedy prompt yields a different completion per request, reproducible request-for-request
|
||||
* across processes, and only ever with speculation on. */
|
||||
/* Clears all drafter state for the sequence in this slot, on admission and on preemption.
|
||||
* Slots are recycled, so anything not reset here leaks into an unrelated sequence: a stale
|
||||
* `draft_filled`, for one, empties the next prefill's history pass (hs = max(draft_filled,
|
||||
* ctx_len)), and the MTP head drafts against stale pool contents, making greedy output vary
|
||||
* per request with speculation on. */
|
||||
void drafter_reset() {
|
||||
n_draft = 0;
|
||||
draft_next = 0;
|
||||
@@ -109,56 +72,44 @@ 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. */
|
||||
/* The adaptive draft window's estimate (--draft-window adaptive, draft.h). Not reset by
|
||||
* drafter_reset(): it describes the text, which preemption does not change. */
|
||||
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
|
||||
/* Its index in the next step, already issued while this one runs (step_next), or -1; and the
|
||||
* drafts the drafter issued for it, which that step verifies. */
|
||||
int32_t entry_next = -1;
|
||||
int32_t draft_next = 0;
|
||||
|
||||
/* Cancelled while its tokens were in the step the device is still running, or while a
|
||||
* drafter's snapshot still names it. Its blocks are released at commit rather than now,
|
||||
* because handing a block to another sequence while a kernel is still writing it is a data
|
||||
* race whose symptom is one sequence's KV appearing in another's attention -- and it would
|
||||
* present as a model quality problem. A drafter pass built after the free would be worse
|
||||
* still: its block-table row is all -1 with a non-zero length, and attention reads block -1,
|
||||
* which is below the layer's region of the pool. */
|
||||
/* Cancelled while a step in flight or a drafter snapshot still names it; its blocks are
|
||||
* released once nothing does. Freed earlier, a kernel still writing a block would put one
|
||||
* sequence's KV in another's attention, and a drafter pass built after the free would carry
|
||||
* an all -1 block-table row with a non-zero length, reading block -1 below the pool. */
|
||||
bool pending_free = false;
|
||||
/* REAPED WHILE ITS TOKENS WERE IN THE STEP THE DEVICE IS STILL RUNNING, which is the same
|
||||
* window `pending_free` covers and a strictly worse thing to get wrong. The server reaps a
|
||||
* generation as soon as its sink is finished, and cancelling a request finishes the sink
|
||||
* immediately -- so a client that disconnects mid-decode has its Request destroyed and its
|
||||
* slot handed back while commit() still holds a StepEntry pointing at that slot. commit() then
|
||||
* dereferences a null `req`, or worse, finds the slot re-admitted and commits one client's
|
||||
* tokens into another's output. The release is deferred to commit instead. */
|
||||
/* Reaped in the same window. A disconnect finishes the sink and the server reaps at once;
|
||||
* destroying the Request then would leave commit() reading a null `req`, or committing one
|
||||
* client's tokens into a re-admitted slot. */
|
||||
bool reap_pending = false;
|
||||
int64_t pending_ckpt = -1; /* absolute position this step's chunk checkpoints at */
|
||||
|
||||
/* The checkpoint the linear state should be SEEDED from on admission. Neither Request nor
|
||||
* KVManager::ensure carries it, so the scheduler holds the answer here and hands it to the
|
||||
* sequence's first entry as StepEntry::ckpt_restore.
|
||||
*
|
||||
* NEVER HELD ACROSS A STEP. A checkpoint slot is only the cache's until the cache retires it,
|
||||
* and between two steps the retention policy, another admission's reservation or an idle
|
||||
* tier can retire it, reallocate it and save a different sequence into it -- nothing pins it.
|
||||
* So an admission that fails after the lookup gives the hit back (admit_one) and the next
|
||||
* attempt looks it up again, rather than restoring whatever the slot holds by then. */
|
||||
/* The checkpoint the linear state is seeded from on admission, handed to the sequence's first
|
||||
* entry as StepEntry::ckpt_restore. Never held across a step: nothing pins a checkpoint slot,
|
||||
* so a failed admission gives the hit back (admit_one) and the next attempt looks it up
|
||||
* again. */
|
||||
int32_t ckpt_src = -1;
|
||||
|
||||
/* The prefix hit this admission attempt found, in tokens, and whether its accounting is still
|
||||
* owed. Counted once, when the admission SUCCEEDS: a request at the head of the queue that
|
||||
* does not fit is retried every step, and counting each attempt would inflate the prompt and
|
||||
* hit totals by however long it waited. */
|
||||
* owed. Counted once, when admission succeeds; counting each retry of a request that does not
|
||||
* fit would inflate the prompt and hit totals. */
|
||||
int32_t hit_attn = 0;
|
||||
bool hit_owed = false;
|
||||
/* Why that hit was cut to nothing, for the counters (SchedMetrics::hit_cut_*). */
|
||||
enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt };
|
||||
HitCut hit_cut = HitCut::None;
|
||||
|
||||
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
|
||||
int64_t seq_len() const {
|
||||
@@ -168,31 +119,30 @@ struct SchedReq {
|
||||
|
||||
class Scheduler {
|
||||
public:
|
||||
/* What the sampler hands back after a step. The scheduler needs three numbers per sequence and
|
||||
* no logits: how many drafted tokens survived, the token sampled at the accepted position, and
|
||||
* whether the sequence ended. Everything else is the sampler's business. */
|
||||
/* What the sampler hands back after a step: per sequence, how many drafts survived, the token
|
||||
* sampled at the accepted position, and whether the sequence ended. No logits. */
|
||||
struct StepResult {
|
||||
int n_seq = 0;
|
||||
const int32_t* n_accepted = nullptr; /* [n_seq] drafted tokens accepted, 0..n_spec */
|
||||
const int32_t* token = nullptr; /* [n_seq] token sampled at the accepted position */
|
||||
const uint8_t* eos = nullptr; /* [n_seq] 1 when the sequence ended */
|
||||
/* LOGPROBS, null on a step where no request asked: entry i's j-th emitted token (its
|
||||
/* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its
|
||||
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
|
||||
const TokenLogprobs* lp = nullptr;
|
||||
const int32_t* first_row = nullptr; /* [n_seq] */
|
||||
};
|
||||
|
||||
/* `geo` is the already-resolved chunk geometry. The engine resolves it once and passes it,
|
||||
* because PrefixCache::configure needs the checkpoint interval out of it and runs first;
|
||||
* pass nullptr to resolve one here instead. */
|
||||
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
|
||||
* PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to
|
||||
* resolve one here. */
|
||||
int init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCache* pc,
|
||||
const std::vector<BatchBuilder::RankIO>& ranks,
|
||||
const ChunkGeometry* geo = nullptr);
|
||||
|
||||
/* The batch the last build produced for one rank; see BatchBuilder::batch_for. */
|
||||
const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); }
|
||||
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. It carries
|
||||
* the serial head's shape as well, which only the draft passes' modes read. */
|
||||
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. Also carries
|
||||
* the serial head's shape, which only the draft passes' modes read. */
|
||||
AdvanceArgs advance_args(int rank) const {
|
||||
AdvanceArgs a = builder_.advance_args(rank);
|
||||
a.shared_kv = serial_shared_ ? 1 : 0;
|
||||
@@ -204,39 +154,30 @@ public:
|
||||
/* ---------------------------------------------------------- off the step path */
|
||||
int add(std::unique_ptr<Request> r);
|
||||
/* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with
|
||||
* its result in rc[i]. For the sequences of one API request, which have to reach the same
|
||||
* step. */
|
||||
* its result in rc[i]. For the sequences of one API request, which must reach the same step. */
|
||||
void add_all(std::unique_ptr<Request>* rs, size_t n, int* rc);
|
||||
/* Cancellation propagates to the scheduler and frees blocks IMMEDIATELY rather than at
|
||||
* completion (spec §14). A cancelled request holding its blocks until the step that would
|
||||
* have finished it is a pool that shrinks under exactly the load that cancels. */
|
||||
/* Frees blocks immediately rather than at completion (spec §14); otherwise the pool shrinks
|
||||
* under exactly the load that cancels. */
|
||||
int cancel(uint64_t id);
|
||||
Request* find(uint64_t id);
|
||||
|
||||
/* Requests that reached a terminal state since the last call, oldest first, SWAPPED OUT under
|
||||
* the lock into `out` (whose old contents are discarded). The engine drains this to drop its
|
||||
* per-request sampler state; it is the only consumer. The server does not read it -- it
|
||||
* learns of a terminal request through the sink and calls reap(), which is what finally
|
||||
* releases the Request object.
|
||||
*
|
||||
* A swap rather than a reference: an HTTP thread's cancel() appends to this list under the
|
||||
* lock, and a caller walking a reference to it without the lock walks a vector another thread
|
||||
* may be reallocating. Handing the same vector back and forth also keeps both capacities, so
|
||||
* a steady state allocates nothing. */
|
||||
/* Requests that reached a terminal state since the last call, oldest first, swapped into
|
||||
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
|
||||
* per-request sampler state; the server learns through the sink and calls reap(). A swap
|
||||
* because cancel() appends from HTTP threads; swapping the same vectors keeps both
|
||||
* capacities, so steady state allocates nothing. */
|
||||
void take_completed(std::vector<uint64_t>* out);
|
||||
int reap(uint64_t id);
|
||||
|
||||
/* ---------------------------------------------------------- the lock, for the engine
|
||||
*
|
||||
* EVERY MUTATION OF THE KV MANAGER AND THE PREFIX CACHE HAPPENS UNDER THIS LOCK. Neither has
|
||||
* a lock of its own, and both are reached from two kinds of thread: the step path, and HTTP
|
||||
* threads running cancel(), reap() and reset_prefix_cache(), which publish into the cache,
|
||||
* evict from it and free sequences. The engine's own passes between steps -- the idle tiers,
|
||||
* the elastic rebalance, the checkpoint copies -- mutate the same structures, so they run
|
||||
* inside this too. Taken once per pass that has work, never per sequence.
|
||||
* Every mutation of the KV manager and the prefix cache happens under this lock; neither has
|
||||
* its own, and both are reached from the step path, from HTTP threads (cancel(), reap(),
|
||||
* reset_prefix_cache()) and from the engine's passes between steps (idle tiers, elastic
|
||||
* rebalance, checkpoint copies). Taken once per pass that has work, never per sequence.
|
||||
*
|
||||
* NOTHING RUN UNDER IT MAY CALL BACK INTO THE SCHEDULER: the mutex is not recursive, and
|
||||
* every public method here takes it. */
|
||||
* Nothing run under it may call back into the scheduler: the mutex is not recursive and every
|
||||
* public method takes it. */
|
||||
template <class Fn> auto locked(Fn&& fn) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return fn();
|
||||
@@ -247,32 +188,25 @@ public:
|
||||
/* ---------------------------------------------------------- work the device still owes
|
||||
*
|
||||
* A request cancelled while a drafter pass was being built keeps its blocks until the passes
|
||||
* that name them are done (see SchedReq::pending_free). commit() releases them once nothing
|
||||
* refers to them; an engine that has gone idle runs no commit, so it drains its streams and
|
||||
* calls release_deferred() instead. has_deferred() is the cheap test for whether that is
|
||||
* needed at all. */
|
||||
* that name them are done (SchedReq::pending_free). commit() releases them; an idle engine
|
||||
* runs no commit, so it drains its streams and calls release_deferred() instead.
|
||||
* has_deferred() is the cheap test for whether that is needed. */
|
||||
bool has_deferred() const;
|
||||
void release_deferred();
|
||||
|
||||
/* THE ENGINE HAS STOPPED AND WILL RUN NO MORE STEPS. Every request still queued or running is
|
||||
* failed with `reason` so its connection is answered rather than left waiting on a step that
|
||||
* will never come, and any request submitted afterwards is refused the same way. `status` is
|
||||
* what stopped it, and what each of those requests reports. */
|
||||
/* The engine has stopped and will run no more steps. Every queued or running request is
|
||||
* failed with `reason` so its connection gets an answer, and later submissions are refused the
|
||||
* same way. `status` is the cause, and what each of those requests reports. */
|
||||
void shutdown(const char* reason, int status = RAD_E_STATE);
|
||||
|
||||
/* The waiting queue in SERVICE order, by request id -- what the live view shows and what a
|
||||
* test asserts a preempted request re-entered at the front of. Returns how many were written. */
|
||||
/* The waiting queue's request ids in service order, for the live view and for tests (a
|
||||
* preempted request re-enters at the front). Returns how many were written. */
|
||||
int queue_snapshot(uint64_t* out, int max) const;
|
||||
|
||||
/* ---------------------------------------------------------- who is in flight
|
||||
*
|
||||
* WHAT EVERY REQUEST IS DOING RIGHT NOW, for the dashboard and for anyone debugging a stall.
|
||||
* The aggregate metrics answer "is the engine busy"; they cannot answer "which of these eight
|
||||
* is stuck", and a request that has been in `Waiting` for forty seconds because its prompt
|
||||
* does not fit is invisible in every number above.
|
||||
*
|
||||
* A snapshot under the step lock, copied out: holding a pointer into the scheduler's storage
|
||||
* across a step is holding a pointer to a request that may be reaped. */
|
||||
* Per-request state for the dashboard and for debugging a stall. Copied out under the step
|
||||
* lock, since a pointer into scheduler storage could outlive a reaped request. */
|
||||
struct ReqStat {
|
||||
uint64_t id = 0;
|
||||
int state = 0; /* ReqState, as an int -- the caller has the enum */
|
||||
@@ -283,9 +217,9 @@ public:
|
||||
int64_t output_tokens = 0;
|
||||
int64_t max_tokens = 0;
|
||||
int64_t ctx_tokens = 0; /* prompt ++ output */
|
||||
/* THIS REQUEST'S SHARE OF THE PAGED POOLS, summed over every paged group: the blocks it
|
||||
* holds and the tokens they cover. `ctx_tokens` is what it is USING; this is what it has
|
||||
* TAKEN, and they differ by a partial block and by whatever a rejected draft left. */
|
||||
/* This request's share of the paged pools: the blocks it holds and the tokens they cover.
|
||||
* It differs from `ctx_tokens` (what it uses) by a partial block and by whatever a
|
||||
* rejected draft left. */
|
||||
int64_t kv_blocks = 0;
|
||||
int64_t kv_tokens = 0;
|
||||
int32_t n_draft = 0; /* the proposal standing for the next step */
|
||||
@@ -294,8 +228,8 @@ public:
|
||||
double ttft_s = -1; /* negative until the first token */
|
||||
double decode_tps = 0; /* this request's own, since its first token */
|
||||
};
|
||||
/* Newest first is wrong here: a dashboard wants the oldest at the top, because the oldest is
|
||||
* the one that is stuck. Returns how many were written. */
|
||||
/* Oldest first, since the oldest is the one most likely 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 sequence's window
|
||||
@@ -303,11 +237,9 @@ public:
|
||||
int set_draft(uint64_t id, const int32_t* tokens, int n);
|
||||
|
||||
/* ---------------------------------------------------------- media the encoder owes
|
||||
* A REQUEST CARRYING MEDIA IS ADMITTED ONLY ONCE EVERY ITEM IS ENCODED. Until then it keeps
|
||||
* its place in the queue, the requests behind it are admitted around it, and its items wait
|
||||
* here for the engine, which runs the encoder between steps and marks them done (take_encodes).
|
||||
* Encoding before admission rather than chunk by chunk keeps the encoder off the step path:
|
||||
* a step never waits for a tower, and the batch builder only ever copies rows that exist. */
|
||||
* A request carrying media is admitted only once every item is encoded; until then it keeps
|
||||
* its queue position and later requests are admitted around it. The engine takes the items
|
||||
* (take_encodes) and encodes them between steps, which keeps the encoder off the step path. */
|
||||
bool encodes_pending() const;
|
||||
void take_encodes(std::vector<std::shared_ptr<mm::Item>>* out);
|
||||
/* An encoder pass over whole segments; see BatchBuilder::build_encoder. */
|
||||
@@ -317,79 +249,61 @@ public:
|
||||
return builder_.build_encoder(parts, step, enc);
|
||||
}
|
||||
|
||||
/* Drop every prefix-cache entry, returning how many were dropped, or RAD_E_UNSUPPORTED when
|
||||
* this engine has no prefix cache. Under the step lock: releasing the cache's references is
|
||||
* safe against a running step -- a block a live sequence holds stays allocated because the
|
||||
* sequence holds its own reference -- but the map itself is not, and the step path inserts
|
||||
* into it. See IScheduler::reset_prefix_cache for why the endpoint exists. */
|
||||
/* Drop every prefix-cache entry; returns how many, or RAD_E_UNSUPPORTED without a prefix
|
||||
* cache. Takes the step lock because the step path inserts into the map (live sequences hold
|
||||
* their own block references). See IScheduler::reset_prefix_cache. */
|
||||
int64_t reset_prefix_cache();
|
||||
|
||||
/* ---------------------------------------------------------- the step path */
|
||||
/* One decision, one batch. Null when there is nothing to run, which is not an error. */
|
||||
const RadBatch* step();
|
||||
|
||||
/* ---------------------------------------------------- THE NEXT STEP, BEFORE THIS ONE COMMITS
|
||||
/* ---------------------------------------------------- the next step, before this one commits
|
||||
*
|
||||
* A decode step's successor does not need anything the host learns from the step: every row
|
||||
* continues where the card's acceptance leaves it (sched/advance.h), with the drafts the
|
||||
* drafter proposed on the card, and the host can bound how far that is. So the engine issues
|
||||
* the next step's forward pass while this one is still running, and the card goes straight
|
||||
* from one to the other.
|
||||
* A decode step's successor needs nothing the host learns from it: every row continues where
|
||||
* the card's acceptance leaves it (sched/advance.h), with drafts proposed on the card, and the
|
||||
* host can bound how far that is. So the next forward pass is issued while this one runs.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* 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.
|
||||
* expect_draft after the drafter is issued: how many drafts the next step verifies for a
|
||||
* sequence, capped at its window (under the adaptive policy possibly 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
|
||||
* committed state can make: a request waiting for admission, a prefill chunk
|
||||
* to continue, a grammar, the context's end, or a pool that cannot grow.
|
||||
* the furthest context it can reach. Null (step() runs after the commit
|
||||
* instead) when only committed state can decide: a request awaiting admission,
|
||||
* a prefill chunk to continue, a grammar, the context's end, or a pool that
|
||||
* cannot grow.
|
||||
* promote_next once this step has committed: the next step becomes the open one.
|
||||
*
|
||||
* While the next step is open, commit() leaves each continuing request's blocks where they
|
||||
* are -- the next step is writing past the committed end -- and a request that finishes keeps
|
||||
* them until the next step has run. */
|
||||
* While the next step is open, commit() leaves continuing requests' blocks in place, and a
|
||||
* finished request keeps them until that step has run. */
|
||||
void expect_draft(uint64_t id, int n);
|
||||
const RadBatch* step_next();
|
||||
const RadBatch* step_next_locked();
|
||||
void promote_next();
|
||||
bool next_open() const { return next_open_; }
|
||||
/* Fold the step's outcome back in: append tokens, roll back rejected speculation, retire
|
||||
* finished requests, feed the draft controller. */
|
||||
int commit(const StepResult& r);
|
||||
/* THE ENGINE'S LOOP IS ROUND, AND THE STEP ENDS HERE -- after the drafter, not at commit.
|
||||
* A serial draft head runs as extra steps AFTER the trunk step that fed it (see below), so
|
||||
* closing the step at commit would leave those rounds in no step at all: their time is charged
|
||||
* to nothing, `decode_tps` reads high and the reported step time reads short. The definition in
|
||||
* scheduler.cpp is the argument. Call it once per loop iteration that ran a step; a caller that
|
||||
* does not is left with correct counters and no timing. */
|
||||
/* Ends the step for timing; call once per loop iteration that ran a step, after the drafter,
|
||||
* so the draft rounds are charged to the step (see the definition). Without it the counters
|
||||
* stay correct but there is no timing. */
|
||||
void step_finished();
|
||||
|
||||
/* ---------------------------------------------------- the SERIAL drafter (spec §10)
|
||||
/* ---------------------------------------------------- the serial drafter (spec §10)
|
||||
*
|
||||
* A serial draft head (RAD_DRAFT_SERIAL) runs as EXTRA STEPS of its own, after the
|
||||
* trunk step that fed it. It cannot run inside that step: round 1 consumes the token the
|
||||
* sampler chose and the hidden state of the position that token came from, and which position
|
||||
* that is depends on how many drafts the verify accepted -- neither is known until the trunk
|
||||
* step has been sampled and committed.
|
||||
* A serial draft head (RAD_DRAFT_SERIAL) runs as extra steps after the trunk step that fed it,
|
||||
* because round 1 needs the sampled token and its position, which depends on how many drafts
|
||||
* the verify accepted. The engine drives it through:
|
||||
*
|
||||
* So the engine drives it, and these three calls are the scheduler's half:
|
||||
*
|
||||
* serial_begin BEFORE commit(), right after the step is issued, while plan() describes it.
|
||||
* Says which sequences may draft, reserves the lookahead KV they may write
|
||||
* into -- for the furthest position acceptance could reach, since how far it
|
||||
* reached is the card's to decide -- and clamps `rounds` to the controller's
|
||||
* current depth.
|
||||
* serial_batch one batch per pass: 0 the history, which also carries round 1 for the
|
||||
* rows that draft (RadBatch::draft_out_ids), then the rounds from 2. Every row
|
||||
* that continues a sampled verify is a DEVICE row (advance.h): the card fills
|
||||
* its positions from the acceptance it computed, and its tokens from the sampled
|
||||
* ids and each round's proposal, so no pass waits on the host.
|
||||
* serial_end AFTER commit(), with the rounds that ran: moves the history watermark to
|
||||
* the last position the committed acceptance says the history pass wrote.
|
||||
* set_draft the engine publishes each row's tokens through the ordinary door, so a head's
|
||||
* draft and a prompt-lookup draft are the same thing to the next step. A row
|
||||
* the head declined leaves n_draft at 0 and the n-gram drafter fills in.
|
||||
* serial_begin before commit(), right after the step is issued, while plan() describes it.
|
||||
* Says which sequences may draft, reserves lookahead KV up to the furthest
|
||||
* position acceptance could reach, and clamps `rounds` to the current depth.
|
||||
* serial_batch one batch per pass: 0 is the history, which also carries round 1 for the
|
||||
* drafting rows (RadBatch::draft_out_ids), then rounds from 2. Rows continuing
|
||||
* a sampled verify are device rows (advance.h): the card fills their positions
|
||||
* and tokens, so no pass waits on the host.
|
||||
* serial_end after commit(), with the rounds that ran: moves the history watermark.
|
||||
* set_draft publishes each row's tokens like any other draft. A row the head declined
|
||||
* keeps n_draft 0 and the n-gram drafter fills in.
|
||||
*/
|
||||
struct SerialRow {
|
||||
uint64_t seq = 0;
|
||||
@@ -398,48 +312,37 @@ public:
|
||||
};
|
||||
int serial_begin(int* rounds, SerialRow* out, int max);
|
||||
const RadBatch* serial_batch(int round, int step);
|
||||
/* Round 0 is the HISTORY pass -- null when no row needs one -- and round 1 is always null,
|
||||
* because round 0 carries it. Call serial_end() once the step has committed so the watermark
|
||||
* moves. */
|
||||
/* Round 0 is the history pass (null when no row needs one); round 1 is always null, because
|
||||
* round 0 carries it. Call serial_end() once the step has committed. */
|
||||
void serial_end(int rounds_done);
|
||||
|
||||
/* ----------------------------------------------------- the BLOCK drafter (spec §10)
|
||||
/* ----------------------------------------------------- the block drafter (spec §10)
|
||||
*
|
||||
* A block-diffusion drafter (RAD_DRAFT_BLOCK), and the shape is the whole point: ONE pass
|
||||
* over a block of `block` positions proposes all of them, so depth costs nothing and there is
|
||||
* no chain of rounds. What replaces it is TWO passes with different shapes, and the scheduler's
|
||||
* half is telling each of them which rows it runs over.
|
||||
* A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
|
||||
* one pass, so there are no rounds; instead it runs two passes of different shapes.
|
||||
*
|
||||
* block_begin right after commit(), while plan() still describes the step just run.
|
||||
* Reserves the block of draft KV the query pass will write, and answers
|
||||
* which sequences may draft.
|
||||
* block_context the CONTEXT pass, draft_pass -1. Its entries MIRROR that trunk step's --
|
||||
* same sequence, same ctx_len, same n_tokens -- because the drafter reads
|
||||
* the trunk's tapped hidden states positionally out of a buffer of its own,
|
||||
* and a mirror is what makes row i of the batch row i of it. No gather,
|
||||
* no offset, and no special case for a rejected suffix: those positions are
|
||||
* inside the block the query pass is about to overwrite.
|
||||
* block_query the QUERY pass, draft_pass +1. One entry a drafting sequence, `block`
|
||||
* tokens: the anchor at the sequence's own next position and a mask at each
|
||||
* of the `block - 1` after it. `out_ids` names THE LAST `depth` ROWS, which
|
||||
* is the one rule both trained conventions reduce to: at block = depth + 1
|
||||
* the anchor row predicts nothing and each mask row predicts the token at
|
||||
* ITS OWN position, and at block = depth every row predicts the token AFTER
|
||||
* it and the anchor is not wasted. rad_builder.h argues the pair.
|
||||
* Reserves the draft KV block the query pass writes, and returns which
|
||||
* sequences may draft.
|
||||
* block_context the context pass, draft_pass -1. Its entries mirror the trunk step's
|
||||
* row for row (BlockSeq).
|
||||
* block_query the query pass, draft_pass +1. One entry per drafting sequence: the
|
||||
* anchor at its next position, then `block - 1` masks; `out_ids` names the
|
||||
* last `depth` rows.
|
||||
* block_end moves the filled range over what actually ran.
|
||||
*
|
||||
* The proposal does not come back through the sampler: the drafter writes it to the buffer it
|
||||
* declared as its proposal, and the engine publishes it through set_draft() like any other.
|
||||
* The drafter writes its proposal to its declared proposal buffer, not through the sampler,
|
||||
* and the engine publishes it through set_draft().
|
||||
*/
|
||||
struct BlockRow {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
int32_t card = -1;
|
||||
};
|
||||
/* `block` is the drafter's trained block in ROWS and `depth` how many tokens it proposes out
|
||||
* of them -- the head takes the last `depth` -- and `window` is its attention window (0 for
|
||||
* none); `mask` is the token id its masked query slots embed. Returns how many sequences may
|
||||
* draft, and fills `out` with those -- in the order block_query() will emit them. */
|
||||
/* `block` is the drafter's trained block in rows, `depth` how many tokens it proposes (the
|
||||
* last `depth` rows), `window` its attention window (0 for none) and `mask` the token id its
|
||||
* masked query slots embed. Returns how many sequences may draft and fills `out` with them,
|
||||
* in the order block_query() emits them. */
|
||||
int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max);
|
||||
const RadBatch* block_context(int step);
|
||||
const RadBatch* block_query(int step);
|
||||
@@ -450,15 +353,11 @@ public:
|
||||
DraftController& draft() { return draft_; }
|
||||
SchedMetrics metrics() const;
|
||||
|
||||
/* THE OBSERVERS' COPY. A dashboard, a scraper or an admin call reads what the engine thread
|
||||
* last published and never the scheduler's own state, because that state is behind the lock
|
||||
* every step takes: a reader holding it for as long as its own work takes delays the step by
|
||||
* exactly that long, and an observer must not be able to slow what it observes.
|
||||
*
|
||||
* publish() is the engine thread's, once a step and at most every 20 ms while idle. It builds
|
||||
* the copy under the scheduler's lock -- the engine thread's own lock, so nothing waits -- and
|
||||
* swaps it in only if no reader is copying out at that moment; a swap it skips is made at the
|
||||
* next call. The readers take only the copy's lock, which the engine thread never waits on. */
|
||||
/* The observers' copy. Dashboards, scrapers and admin calls read what the engine thread last
|
||||
* published, never the scheduler's state behind the step lock, so an observer cannot slow
|
||||
* the step. publish() runs on the engine thread once a step (at most every 20 ms while idle),
|
||||
* builds the copy under mu_ and swaps it in only if no reader holds the copy's lock; a
|
||||
* skipped swap happens at the next call. */
|
||||
void publish(bool idle);
|
||||
SchedMetrics observed_metrics() const;
|
||||
int observed_requests(ReqStat* out, int max) const;
|
||||
@@ -471,10 +370,15 @@ public:
|
||||
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos, int64_t keep_at = 0) const;
|
||||
|
||||
/* THE SMALLEST STEP THE PREFILL STAGER OVERLAPS, in tokens (0 = no stager), set once by the
|
||||
* engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it; see
|
||||
* busy_cap. Also where the resolved policy is stated at startup. */
|
||||
/* The smallest step the prefill stager overlaps, in tokens (0 = no stager), set once by the
|
||||
* engine after init. --busy-prefill-chunk keeps a held-back chunk at or above it (busy_cap).
|
||||
* Also logs the resolved policy at startup. */
|
||||
void set_stage_rows(int64_t rows);
|
||||
/* The shortest prefill that spans, in tokens (0: every one alone in its step), set once by
|
||||
* the engine after init. Where routed experts are read from host memory, the arena a spanned
|
||||
* step takes is room the experts lose for it, which on a short prompt costs more than the span
|
||||
* saves (Engine::serve). */
|
||||
void set_span_min(int64_t tokens);
|
||||
/* Whether the step just planned leaves a prompt with at least the stager's smallest pass still
|
||||
* to prefill, so the next step most likely carries a chunk the stager arms for. */
|
||||
bool prefill_continues() const;
|
||||
@@ -494,76 +398,63 @@ private:
|
||||
bool has_linear_state_ = false;
|
||||
/* set_stage_rows: the prefill stager's smallest pass, 0 when it is not armed. */
|
||||
int64_t stage_rows_ = 0;
|
||||
/* set_span_min: the shortest prefill a span is taken for, 0 for any. */
|
||||
int64_t span_min_ = 0;
|
||||
/* Set by admit_one when it held the admitted chunk back: what it would have taken. */
|
||||
int64_t admit_full_ = 0;
|
||||
/* Whether this step's prefill may span (ChunkGeometry::span): set by step() for the step it
|
||||
* plans, true only for a prefill alone in its step, and read by plan_chunk. True outside a
|
||||
* step, so plan_chunk called directly answers for a span. */
|
||||
bool span_now_ = true;
|
||||
IKVManager* kv_ = nullptr;
|
||||
IPrefixCache* pc_ = nullptr;
|
||||
|
||||
/* DOES A PREFIX-CACHE HIT LEAVE A HOLE IN A BLOCK DRAFTER'S OWN KV? Only if some PAGED group
|
||||
* is not prefix-cached. prefix.cpp skips a WINDOWED group -- "a hit's blocks do not describe
|
||||
* a cache whose floor moves" -- so a windowed drafter really does start at the hit position
|
||||
* and really must wait for its window to slide past it. A FULL-attention drafter's group is
|
||||
* cached exactly like the trunk's: the hit hands over blocks the PREVIOUS sequence's own
|
||||
* context pass wrote, so the content is there and the floor is 0.
|
||||
*
|
||||
* Read off IPrefixCache::cached_groups() rather than re-deriving prefix.cpp's rule, which
|
||||
* 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. */
|
||||
/* Does a prefix-cache hit leave a hole in a block drafter's own KV? Only if some paged group
|
||||
* is not prefix-cached. prefix.cpp skips windowed groups, so a windowed drafter has K and V
|
||||
* only from the hit position and must wait for its window to slide past it. A full-attention
|
||||
* drafter's group is cached like the trunk's and its floor is 0; treating it as windowed
|
||||
* would stop drafting for good, since it has no window to slide. Read off
|
||||
* IPrefixCache::cached_groups() so prefix.cpp's rule lives in one place. */
|
||||
bool hit_holes_draft_ = true;
|
||||
/* DOES A HIT HOLE THE TRUNK ITSELF? hit_holes_draft_ is the drafter's guard, and draft_refill_
|
||||
* repairs a drafter hole by recomputing the prompt's TAIL. A TRUNK group the cache does not
|
||||
* index admits no such repair: the adopted blocks cover the cached groups only, while the
|
||||
* windowed trunk layers read the positions below ctx_len this sequence never wrote — the KV of
|
||||
* whoever held these blocks last. So a trunk hole refuses the hit outright.
|
||||
*
|
||||
* THE TRUNK IS WHICH GROUPS? The one a drafter borrows is bound at `base_layer` and above —
|
||||
* the drafter's layers run after the trunk's (rad_bind_layer_kv at the drafter declare), so a
|
||||
* group with a bound layer below meta.n_layers belongs to the trunk and a hit must cover it;
|
||||
* a drafter's own group is the refill's business, not this clamp's. Read off the Program,
|
||||
* which carries both the bindings and the trunk's layer count. */
|
||||
/* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
|
||||
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
|
||||
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
|
||||
bool hit_holes_trunk_ = false;
|
||||
/* 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. */
|
||||
/* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
|
||||
* drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
|
||||
* which on a chat's follow-up turn is most of the reply, so the hit ends one window before the
|
||||
* prompt's end (HitCap) and the recompute fills the drafter's window too. Output is unchanged.
|
||||
* A hit whose nearest checkpoint below that point gives back more than two windows is kept
|
||||
* whole. */
|
||||
int64_t draft_refill_ = 0;
|
||||
/* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), off the Program at init. It
|
||||
* owes no history, so serial_begin gives it one row a drafting sequence and none to a sequence
|
||||
* that does not draft, and its rounds stay at the committed position (advance.h). False and 0
|
||||
* for every other drafter, whose passes are staged exactly as before. */
|
||||
/* A serial head with no cache of its own (rad_drafter_shared_kv). It owes no history, so
|
||||
* serial_begin gives it one row per drafting sequence and none otherwise, and its rounds stay
|
||||
* at the committed position (advance.h). False and 0 for every other drafter. */
|
||||
bool serial_shared_ = false;
|
||||
int32_t serial_rot_shift_ = 0;
|
||||
BatchBuilder builder_;
|
||||
DraftController draft_;
|
||||
|
||||
/* Where this sequence's block-drafter cache begins, as the guard in block_begin reads it
|
||||
* and block_end records it. One rule, one place. */
|
||||
/* Where this sequence's block-drafter cache begins; block_begin's guard reads it and
|
||||
* block_end records it. */
|
||||
int64_t draft_floor(const SchedReq& s, int64_t ctx_len) const {
|
||||
if (s.draft_hi != 0 || s.draft_lo != 0) return s.draft_lo;
|
||||
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. */
|
||||
/* 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 first use).
|
||||
* Every site that caps a proposal applies it: step(), set_draft(), expect_draft() and the
|
||||
* rounds in serial_begin(). With the policy off it is next_depth(). */
|
||||
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.
|
||||
/* The step's head depth D is chosen once per cycle by draft_cycle(), the first thing step()
|
||||
* and promote_next() do. A proposal passes four sites that must agree on it: the verifying
|
||||
* plan, the drafting rounds, expect_draft() and set_draft(). A commit or a disconnect changes
|
||||
* the running set mid-cycle, so a D read live could move between them; held, 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. */
|
||||
@@ -601,14 +492,13 @@ private:
|
||||
std::vector<int32_t> waiting_;
|
||||
std::vector<uint64_t> completed_;
|
||||
|
||||
/* Requests whose release is waiting on something that still refers to them -- a deferred
|
||||
* reap or a deferred free. A count, so the sweeps that look for them cost nothing on the
|
||||
* steps where there are none, which is nearly all of them. */
|
||||
/* Requests whose release waits on something that still refers to them (a deferred reap or a
|
||||
* deferred free). A count, so the sweeps cost nothing on the steps where there are none. */
|
||||
int n_deferred_ = 0;
|
||||
/* Items a waiting request needs encoded, in the order its requests reached the queue's head;
|
||||
* each at most once (Item::queued). mu_ held. */
|
||||
std::vector<std::shared_ptr<mm::Item>> enc_want_;
|
||||
/* Are all of this request's items encoded; the ones that are not are queued for the encoder. */
|
||||
/* Are all of this request's items encoded? The ones that are not are queued for the encoder. */
|
||||
bool media_ready(SchedReq& s);
|
||||
|
||||
/* Set by shutdown(); add() refuses from then on. */
|
||||
@@ -616,10 +506,15 @@ private:
|
||||
const char* closed_reason_ = "";
|
||||
int closed_status_ = RAD_E_STATE;
|
||||
|
||||
/* THE LONGEST SEQUENCE THIS DEPLOYMENT CAN ADDRESS, prompt and output together. The batch
|
||||
* builder sizes its block tables for it and the rotary tables are this long, so no position
|
||||
* at or past it may be scheduled -- whatever max_tokens a request carries, including none. */
|
||||
/* The longest sequence (prompt plus output) this deployment can address. The batch builder's
|
||||
* block tables and the rotary tables are sized for it, so no position at or past it may be
|
||||
* scheduled, whatever max_tokens a request carries. */
|
||||
int64_t ctx_limit_ = 0;
|
||||
/* The longest sequence the KV pool can ever hold alone, when that is less than ctx_limit_,
|
||||
* else -1; and the refusal a longer prompt gets, naming it (a sink keeps the pointer, so it
|
||||
* lives here). See add_locked. */
|
||||
int64_t pool_tokens_ = -1;
|
||||
std::string pool_refusal_;
|
||||
|
||||
/* Scratch for a prefix-cache hit's block ids, one row per cached group. Reserved at init so
|
||||
* an admission does not reach the allocator. */
|
||||
@@ -636,9 +531,7 @@ private:
|
||||
return (step_open_ && s.entry >= 0) || (next_open_ && s.entry_next >= 0);
|
||||
}
|
||||
|
||||
/* The serial drafter's rows, valid between serial_begin() and serial_end(). `base_pos`
|
||||
* is the position round 1 writes at: the emitted token's own position, which is exactly the
|
||||
* committed length because that token has not been fed to the model yet. */
|
||||
/* The serial drafter's rows, valid between serial_begin() and serial_end(). */
|
||||
struct SerialSeq {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
@@ -646,32 +539,29 @@ private:
|
||||
int32_t hist_row = -1; /* the trunk row the history pass starts at */
|
||||
int32_t hist_n = 0; /* how many positions it has to fill, 0 for none */
|
||||
int64_t hist_pos = 0; /* the head index that first row is */
|
||||
/* THE VERIFY STEP THIS ROW CONTINUES FROM, as the card's advance reads it (advance.h):
|
||||
/* The verify step this row continues from, as the card's advance reads it (advance.h):
|
||||
* whether it sampled, the token row of its first verified position, its first sampled
|
||||
* row, and how many history positions come before the verified ones. */
|
||||
bool dev = false;
|
||||
int32_t dev_tok = 0;
|
||||
int32_t dev_out = -1;
|
||||
int32_t lead = 0;
|
||||
/* ITS INDEX AMONG THE DRAFTING ROWS, or -1 for a row that only owes history. A sequence
|
||||
* in the middle of a long prompt has hidden states worth turning into the head`s K and V
|
||||
* and no token to draft from yet, and so does every sequence when a prefill is queued
|
||||
* behind this step -- so the two sets are not the same set. */
|
||||
/* Its index among the drafting rows, or -1 for a row that only owes history (e.g. a
|
||||
* sequence mid-prompt, with hidden states but no token to draft from). */
|
||||
int32_t draft_idx = -1;
|
||||
/* NO Request* HERE, for the reason BlockSeq gives: serial_ is taken under the lock in
|
||||
* serial_begin and read again by serial_batch, once a round, after the lock has been
|
||||
* released and retaken -- and a client can disconnect in any of those windows. */
|
||||
/* THE FURTHEST POSITION ROUND 1 CAN WRITE AT: the verify step's last position, reached
|
||||
/* No Request* here, as for BlockSeq: serial_batch reads serial_ after the lock was
|
||||
* released and retaken. */
|
||||
/* The furthest position round 1 can write at: the verify step's last position, reached
|
||||
* when every draft is accepted. The card knows the real one; this bounds it. */
|
||||
int64_t base_pos = 0;
|
||||
};
|
||||
std::vector<SerialSeq> serial_;
|
||||
StepPlan serial_plan_;
|
||||
|
||||
/* The block drafter's rows, valid between block_begin() and block_end(). One entry for EVERY
|
||||
* entry of the trunk step just run, in its order; `can_draft` says whether it also gets a
|
||||
* query pass. `ctx_len`/`n_tokens` mirror that step's entry, which is the whole contract with
|
||||
* the drafter's own source buffer. */
|
||||
/* The block drafter's rows, valid between block_begin() and block_end(): one per entry of the
|
||||
* trunk step just run, in order, with `ctx_len`/`n_tokens` mirroring it. The drafter reads
|
||||
* the trunk's tapped hidden states positionally from its own buffer, so row i must be the
|
||||
* trunk's row i. `can_draft` says whether the row also gets a query pass. */
|
||||
struct BlockSeq {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
@@ -680,35 +570,36 @@ private:
|
||||
int32_t n_tokens = 0;
|
||||
int64_t base_pos = 0; /* the anchor's position: the sequence's next one */
|
||||
bool can_draft = false;
|
||||
/* A ROW KEPT ONLY TO HOLD ITS PLACE. The trunk step finished this sequence -- it ended,
|
||||
* failed or was cancelled at commit -- so its KV is gone and it drafts nothing. It is
|
||||
* still a row of the context pass, because the drafter reads the trunk's hidden states
|
||||
* positionally: dropping it would slide every later sequence onto its neighbour's rows.
|
||||
* With no blocks behind it the pass stores nothing for it (a negative slot is padding). */
|
||||
/* A placeholder: the trunk step finished this sequence, so it has no KV and drafts
|
||||
* nothing, but keeps its row so later rows stay aligned with the trunk's. The pass stores
|
||||
* nothing for it (a negative slot is padding). */
|
||||
bool mirror = false;
|
||||
/* NO Request* HERE, DELIBERATELY. block_ is taken under the lock in block_begin and read
|
||||
* again in block_context, block_query and block_end, and the lock is RELEASED between
|
||||
* them -- so a client that disconnects in that window can have its Request destroyed
|
||||
* under the second pass, leaving BatchBuilder::build reading tokens off freed memory.
|
||||
* The snapshot is a WEAK reference: `slot` plus `seq`, resolved through block_req(). */
|
||||
/* No Request* here: block_ is read by later passes with the lock released in between,
|
||||
* and a disconnect could free the Request. Rows hold `slot` plus `seq`, resolved through
|
||||
* block_req(). */
|
||||
};
|
||||
std::vector<BlockSeq> block_;
|
||||
StepPlan block_plan_;
|
||||
int32_t block_len_ = 0;
|
||||
int32_t block_depth_ = 0; /* tokens proposed; the head takes the LAST this many */
|
||||
/* `block` - 1 copies of the drafter's mask token, which is what a query entry's `draft` array
|
||||
* points at: token_at() walks prompt ++ output ++ draft, so the mask positions fall straight
|
||||
* out of the accessor every other pass already uses. */
|
||||
int32_t block_depth_ = 0; /* tokens proposed; the head takes the last this many */
|
||||
/* `block` - 1 copies of the drafter's mask token, which a query entry's `draft` points at:
|
||||
* token_at() walks prompt ++ output ++ draft, so the mask positions come from the accessor
|
||||
* every other pass uses. */
|
||||
std::vector<int32_t> block_mask_;
|
||||
int step_ = 0;
|
||||
uint64_t arrival_ = 0;
|
||||
|
||||
SchedMetrics m_{};
|
||||
std::chrono::steady_clock::time_point step_start_{};
|
||||
/* When the last step ended. An idle engine runs no steps, so the throughput window has
|
||||
* nothing adding time to it, and metrics() decays what it reports by this. */
|
||||
/* When the last step ended. An idle engine runs no steps, so nothing adds time to the
|
||||
* throughput window; metrics() decays what it reports by this. */
|
||||
std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
|
||||
int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0;
|
||||
/* --prefill-interleave: decode-only steps still owed before the next chunk, and how many
|
||||
* prefilling requests the last step() held back. step_next_locked stops issuing ahead once
|
||||
* the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
|
||||
int64_t interleave_left_ = 0;
|
||||
int64_t held_prefill_ = 0;
|
||||
/* The throughput window (step_finished): each kind's tokens and the wall time the steps
|
||||
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
|
||||
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
|
||||
@@ -723,28 +614,26 @@ private:
|
||||
static void queue_erase(std::vector<int32_t>& q, int32_t slot);
|
||||
|
||||
/* lifecycle */
|
||||
/* `publish` is false only when the engine is shutting down: a sequence the device may have
|
||||
* left half-computed is not worth indexing, and nothing will ever hit it.
|
||||
*
|
||||
* A FAILED REQUEST SAYS WHAT FAILED: its sink is failed with `status` and `why`, which the
|
||||
* server puts in the error the client gets. RAD_OK leaves a sink that has failed already (an
|
||||
* overflow) as it is. */
|
||||
/* Ends a request: counts it by `st` and queues its id for take_completed. `publish` is
|
||||
* false only at shutdown, where a possibly half-computed sequence is not worth indexing. A
|
||||
* failed request's sink is failed with `status` and `why`, which reach the client's error;
|
||||
* RAD_OK leaves an already-failed sink (an overflow) as it is. */
|
||||
void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
|
||||
bool publish = true, int status = RAD_OK, const char* why = nullptr);
|
||||
/* What reap() does once nothing points at the slot any more: give the blocks back, forget the
|
||||
* id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in
|
||||
void reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok);
|
||||
/* What reap() does once nothing points at the slot: give the blocks back, forget the id,
|
||||
* destroy the Request and return the slot. Called by reap() directly, or by the sweep in
|
||||
* commit() for a request whose reap arrived while something still pointed at it. */
|
||||
void release_locked(SchedReq& s);
|
||||
/* The sequence's KV back to the manager and its card index back to the pool, together:
|
||||
* both are what a step in flight still addresses, so both wait for the same moment. */
|
||||
/* The sequence's KV back to the manager and its card index back to the pool, together: a step
|
||||
* in flight still addresses both, so both wait for the same moment. */
|
||||
void free_kv(SchedReq& s);
|
||||
void drop_card(SchedReq& s);
|
||||
/* Is this request still referenced by a drafter's snapshot? block_ and serial_ outlive the
|
||||
* lock. */
|
||||
/* Is this request still named by a drafter snapshot? block_ and serial_ outlive the lock. */
|
||||
bool block_holds(uint64_t id) const;
|
||||
/* Release every deferred reap and every deferred free whose request nothing refers to any
|
||||
* more. At most one step late: the reference that blocked it is either the step just
|
||||
* committed or a drafter snapshot that block_end() / serial_end() has since cleared. */
|
||||
/* Release every deferred reap and free whose request nothing refers to any more. At most one
|
||||
* step late: what blocked it is either the step just committed or a drafter snapshot that
|
||||
* block_end() / serial_end() has since cleared. */
|
||||
void sweep_deferred();
|
||||
/* Give back a prefix hit an admission attempt took and then could not use: the adopted
|
||||
* blocks, the checkpoint it would have restored, and the position it would have resumed at.
|
||||
@@ -758,13 +647,15 @@ private:
|
||||
void preempt_back();
|
||||
/* Give blocks back from the prefix cache until the pool has headroom again. */
|
||||
void trim_prefix_cache();
|
||||
/* RAD_OK, or a negative status when the request cannot be admitted now -- nothing behind it is
|
||||
* either. */
|
||||
/* `reserve`: tokens of the step to leave for the requests queued behind this one
|
||||
* (--busy-prefill-chunk; busy_cap). 0 plans the chunk on the whole budget, as before. */
|
||||
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
|
||||
* it. `reserve`: tokens of the step to leave for the requests queued behind this one
|
||||
* (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
|
||||
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
|
||||
/* The queue positions one step's admission took, kept to reuse the allocation. */
|
||||
std::vector<size_t> took_;
|
||||
/* A step's prefill entries while step() moves its decode entries first; reserved at init,
|
||||
* since std::stable_partition would take a temporary buffer from the allocator every step. */
|
||||
std::vector<StepEntry> part_;
|
||||
|
||||
/* The conv rolling window, width-1 + num_spec + 1 entries (spec §10). */
|
||||
int32_t conv_window() const;
|
||||
|
||||
Reference in new issue
Block a user