Archived
radiance 1.0.0
This commit is contained in:
commit
ae74a8aebf
616 files changed
+338692
No files matched your search
@@ -0,0 +1,24 @@
|
||||
/* advance.cpp -- issuing an advance. See advance.h. */
|
||||
#include "advance_impl.h"
|
||||
|
||||
#include "device/device.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
int step_advance(const AdvanceArgs& a, RadStream s) {
|
||||
if (a.n_seq <= 0) return RAD_OK;
|
||||
/* THE HOST BACKEND RUNS A STREAM'S WORK AS IT IS ISSUED, and its device memory is host memory,
|
||||
* so the rows run here, now, in the order the stream would have run them. */
|
||||
if (device_is_host()) {
|
||||
for (int i = 0; i < a.n_seq; ++i) adv_row(a, i);
|
||||
return RAD_OK;
|
||||
}
|
||||
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
|
||||
return rad_step_advance_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
#else
|
||||
(void)s;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
#endif
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,104 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* The same code runs on the host backend, where device memory is host memory and a stream runs
|
||||
* its work as it is issued (advance_impl.h is shared by both builds).
|
||||
*/
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
|
||||
#include "rad_device.h"
|
||||
#include "draft.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One sequence slot's state between passes. The accept step writes it; every later pass reads it. */
|
||||
struct StepSlot {
|
||||
int32_t ctx; /* the next verify step's first position: tokens committed so far */
|
||||
int32_t n_acc; /* its one-based num_accepted: tokens the last verify step committed */
|
||||
int32_t head; /* the last committed index, which the draft head's first round extends */
|
||||
int32_t acc; /* drafts the last verify step accepted */
|
||||
/* The next verify step's input tokens: the bonus token, then the draft head's proposals. */
|
||||
int32_t tok[1 + RAD_SCHED_MAX_SPEC];
|
||||
int32_t pad[3];
|
||||
};
|
||||
|
||||
enum AdvMode : int32_t {
|
||||
ADV_ACCEPT = 1, /* after a verify step's sampler: acceptance, and the state it leaves */
|
||||
ADV_TRUNK = 2, /* before a verify step: its tokens, positions and rollback count */
|
||||
ADV_HIST = 3, /* before the draft head's history pass: the verified positions */
|
||||
ADV_ROUND = 4, /* before draft round `round` >= 2: the next position, the last proposal */
|
||||
ADV_TAKE = 5, /* after the last round: its proposal into the state */
|
||||
};
|
||||
|
||||
/* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab,
|
||||
* which every rank carves identically. */
|
||||
struct AdvGroup {
|
||||
int32_t block_size;
|
||||
int32_t paged; /* 0: a state group, whose slots do not depend on the position */
|
||||
int32_t pitch; /* this build's block-table pitch */
|
||||
int32_t pad;
|
||||
int64_t slot_off; /* [n_tok] slot_mapping */
|
||||
int64_t used_off; /* [n_seq] seqused */
|
||||
int64_t bt_off; /* [n_seq][pitch] block table */
|
||||
int64_t first_off; /* [n_seq] the position each row's block table starts at */
|
||||
};
|
||||
|
||||
/* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the
|
||||
* kernel's argument. */
|
||||
struct AdvanceArgs {
|
||||
int32_t mode = 0;
|
||||
int32_t round = 0; /* ADV_ROUND: the draft round, from 2; ADV_TAKE: the last, from 1 */
|
||||
int32_t n_seq = 0;
|
||||
int32_t n_groups = 0;
|
||||
char* slab = nullptr; /* this rank's device slab */
|
||||
int64_t tok_off = 0, pos_off = 0, ctx_off = 0, acc_off = 0, out_off = 0;
|
||||
int64_t sid_off = 0, cu_off = 0, q_off = 0;
|
||||
/* [4][row_pitch] int32: device-row flag; the verify step's token row of the row's first
|
||||
* verified position; its first sampled row, or -1 for a row that sampled nothing; and one
|
||||
* number the mode reads -- ADV_ACCEPT the row's draft count, ADV_HIST how many of the row's
|
||||
* positions come before the verified ones, whose tokens the host staged. */
|
||||
int64_t row_off = 0;
|
||||
int32_t row_pitch = 0;
|
||||
int64_t grp_off = 0; /* [n_groups] AdvGroup */
|
||||
StepSlot* st = nullptr; /* [max_seqs], by scheduler slot */
|
||||
/* ADV_ACCEPT and ADV_HIST: the verify step's sampled tokens, one a row. ADV_ROUND and
|
||||
* ADV_TAKE: the last round's proposals, row i at i * src_pitch. */
|
||||
const int32_t* src = nullptr;
|
||||
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. */
|
||||
int64_t rope_off = -1;
|
||||
int32_t rope_pitch = 0;
|
||||
};
|
||||
|
||||
/* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */
|
||||
int step_advance(const AdvanceArgs& a, RadStream s);
|
||||
|
||||
} /* namespace rad */
|
||||
|
||||
/* The launcher in advance.hip: one kernel onto `stream` through hipLaunchKernel. */
|
||||
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream);
|
||||
@@ -0,0 +1,27 @@
|
||||
/* advance.hip -- the advance kernel: one thread a 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.
|
||||
*/
|
||||
#include <hip/hip_runtime.h>
|
||||
|
||||
#include "advance_impl.h"
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kThreads = 64;
|
||||
|
||||
__global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a) {
|
||||
const int i = (int)(blockIdx.x * kThreads + threadIdx.x);
|
||||
if (i < a.n_seq) rad::adv_row(a, i);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int rad_step_advance_launch(const rad::AdvanceArgs* args, void* stream) {
|
||||
if (!args || args->n_seq <= 0) return 0;
|
||||
const unsigned blocks = (unsigned)((args->n_seq + kThreads - 1) / kThreads);
|
||||
hipLaunchKernelGGL(rad_step_advance, dim3(blocks), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
*args);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -1;
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "advance.h"
|
||||
|
||||
#if defined(__HIPCC__)
|
||||
#define RAD_ADV_FN __host__ __device__ inline
|
||||
#else
|
||||
#define RAD_ADV_FN inline
|
||||
#endif
|
||||
|
||||
namespace rad {
|
||||
|
||||
RAD_ADV_FN int32_t* adv_i32(const AdvanceArgs& a, int64_t off) {
|
||||
return reinterpret_cast<int32_t*>(a.slab + off);
|
||||
}
|
||||
|
||||
RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
int32_t lo = 0, hi = a.n_eog;
|
||||
while (lo < hi) {
|
||||
const int32_t mid = (lo + hi) / 2;
|
||||
if (a.eog[mid] < t) lo = mid + 1; else hi = mid;
|
||||
}
|
||||
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. */
|
||||
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);
|
||||
for (int g = 0; g < a.n_groups; ++g) {
|
||||
const AdvGroup& e = G[g];
|
||||
const int32_t first = adv_i32(a, e.first_off)[i];
|
||||
adv_i32(a, e.used_off)[i] = base + n - first;
|
||||
if (!e.paged) continue;
|
||||
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
|
||||
int32_t* slot = adv_i32(a, e.slot_off);
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t p = pos[k + j];
|
||||
const int32_t bi = (p - first) / e.block_size;
|
||||
slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0)
|
||||
? bt[bi] * e.block_size + p % e.block_size : -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
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;
|
||||
if (a.rope_off < 0 || was == p) return;
|
||||
int32_t* r = adv_i32(a, a.rope_off);
|
||||
const int32_t shift = r[row] - was;
|
||||
r[row] = p + shift;
|
||||
r[a.rope_pitch + row] = p + shift;
|
||||
r[2 * a.rope_pitch + row] = p + shift;
|
||||
}
|
||||
|
||||
RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
|
||||
const int32_t* rows = adv_i32(a, a.row_off);
|
||||
const int32_t rtok = rows[a.row_pitch + i];
|
||||
const int32_t rout = rows[2 * a.row_pitch + i];
|
||||
const int32_t aux = rows[3 * a.row_pitch + i];
|
||||
/* Acceptance runs over every row that sampled, whoever staged it; every other mode over the
|
||||
* rows the card owns. */
|
||||
if (a.mode == ADV_ACCEPT ? rout < 0 : !rows[i]) return;
|
||||
|
||||
int32_t* tok = adv_i32(a, a.tok_off);
|
||||
int32_t* pos = adv_i32(a, a.pos_off);
|
||||
int32_t* ctx = adv_i32(a, a.ctx_off);
|
||||
const int32_t slot = adv_i32(a, a.sid_off)[i];
|
||||
const int32_t k = adv_i32(a, a.cu_off)[i];
|
||||
const int32_t n = adv_i32(a, a.q_off)[i];
|
||||
StepSlot& S = a.st[slot];
|
||||
|
||||
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. */
|
||||
const int32_t* y = a.src + rout;
|
||||
const int32_t* d = tok + rtok + 1;
|
||||
int32_t acc = 0;
|
||||
while (acc < aux && d[acc] == y[acc]) ++acc;
|
||||
for (int32_t j = 0; j <= acc; ++j)
|
||||
if (adv_is_eog(a, y[j])) { acc = j; break; }
|
||||
const int32_t head = ctx[i] + (rtok - k) + acc;
|
||||
S.acc = acc;
|
||||
S.head = head;
|
||||
S.ctx = head + 1;
|
||||
S.n_acc = acc + 1;
|
||||
S.tok[0] = y[acc];
|
||||
return;
|
||||
}
|
||||
case ADV_TRUNK: {
|
||||
const int32_t base = S.ctx;
|
||||
for (int32_t j = 0; j < n; ++j) { tok[k + j] = S.tok[j]; adv_pos(a, pos, k + j, base + j); }
|
||||
ctx[i] = base;
|
||||
adv_i32(a, a.acc_off)[i] = S.n_acc;
|
||||
adv_groups(a, i, k, base, n);
|
||||
return;
|
||||
}
|
||||
case ADV_HIST: {
|
||||
/* `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). */
|
||||
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);
|
||||
const int32_t row0 = out[k];
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t jj = j < last ? j : last;
|
||||
if (jj >= aux) tok[k + j] = a.src[rout + jj - aux];
|
||||
adv_pos(a, pos, k + j, base + jj);
|
||||
out[k + j] = row0 + jj;
|
||||
}
|
||||
ctx[i] = base;
|
||||
adv_groups(a, i, k, base, n);
|
||||
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. */
|
||||
const int32_t base = S.head + a.round - 1;
|
||||
const int32_t t = a.src[(int64_t)i * a.src_pitch];
|
||||
S.tok[a.round - 1] = t;
|
||||
tok[k] = t;
|
||||
adv_pos(a, pos, k, base);
|
||||
ctx[i] = base;
|
||||
adv_groups(a, i, k, base, 1);
|
||||
return;
|
||||
}
|
||||
case ADV_TAKE:
|
||||
S.tok[a.round] = a.src[(int64_t)i * a.src_pitch];
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,385 @@
|
||||
/* batch.h -- the step batch, built ONCE PER STEP BY THE CORE and shared by every layer and every
|
||||
* KV group (spec §8).
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "advance.h"
|
||||
#include "device/device.h"
|
||||
#include "geometry.h"
|
||||
#include "mem_iface.h"
|
||||
#include "metrics.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
/* One sequence's participation in one step. The scheduler fills these; the builder turns them
|
||||
* into device arrays and touches nothing else. */
|
||||
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 */
|
||||
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 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 --
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
bool draft_out = false;
|
||||
bool is_prefill = false;
|
||||
bool produces_token = false; /* this entry's last token is the sequence's last */
|
||||
/* 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. */
|
||||
bool dev = false;
|
||||
int32_t dev_tok = 0;
|
||||
int32_t dev_out = -1;
|
||||
int32_t dev_aux = 0;
|
||||
};
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t n_seq_decode = 0;
|
||||
int64_t n_tok_decode = 0;
|
||||
int32_t max_q_len = 0;
|
||||
int32_t max_ctx_len = 0;
|
||||
|
||||
void reset() {
|
||||
e.clear();
|
||||
n_tok = 0; phase = RAD_PHASE_DECODE; draft_pass = 0; tok_shift = 0; n_spec = 0;
|
||||
spec_is_tree = false; max_q_len = 0; max_ctx_len = 0; n_seq_decode = 0; n_tok_decode = 0;
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
struct RankIO {
|
||||
int device = 0;
|
||||
RadStream stream = nullptr;
|
||||
Program* prog = nullptr;
|
||||
};
|
||||
|
||||
int init(Program& prog, const Config& cfg, const ChunkGeometry& geo,
|
||||
const KVGeom& kvg, const std::vector<RankIO>& ranks);
|
||||
void fini();
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
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). */
|
||||
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. */
|
||||
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. */
|
||||
struct EncoderPart {
|
||||
const mm::Item* item = nullptr;
|
||||
int32_t seg0 = 0, n_seg = 0;
|
||||
};
|
||||
const RadBatch* build_encoder(const std::vector<EncoderPart>& parts, int step);
|
||||
bool has_encoder() const { return mm_on_; }
|
||||
int64_t encoder_patches() const { return enc_patches_; }
|
||||
|
||||
|
||||
private:
|
||||
struct Group {
|
||||
rad_kvgroup g = 0;
|
||||
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. */
|
||||
int64_t bt_fix = 0;
|
||||
int32_t* d_bt = nullptr;
|
||||
int32_t* h_used = nullptr; int32_t* d_used = nullptr;
|
||||
int32_t* h_sidx = nullptr; int32_t* d_sidx = nullptr;
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
std::vector<void*> dev;
|
||||
|
||||
int32_t *h_tok = nullptr, *h_pos = nullptr, *h_cu = nullptr, *h_sid = nullptr;
|
||||
int32_t *h_q = nullptr, *h_ctx = nullptr, *h_acc = nullptr, *h_parent = nullptr;
|
||||
int32_t *h_cktok = nullptr, *h_ckslot = nullptr;
|
||||
int32_t *h_out = nullptr; /* [n_out] which of this step's tokens want logits */
|
||||
int32_t *h_dout = nullptr; /* [n_draft_out] a history pass's round-1 rows */
|
||||
int32_t *d_tok = nullptr, *d_pos = nullptr, *d_cu = nullptr, *d_sid = nullptr;
|
||||
int32_t *d_q = nullptr, *d_ctx = nullptr, *d_acc = nullptr, *d_parent = nullptr;
|
||||
int32_t *d_cktok = nullptr, *d_ckslot = nullptr;
|
||||
int32_t *d_out = nullptr;
|
||||
int32_t *d_dout = nullptr;
|
||||
/* The advance's inputs (advance.h): [4][max_seqs] row descriptors, [groups][max_seqs]
|
||||
* first positions, and one AdvGroup a group. */
|
||||
int32_t *h_rows = nullptr, *d_rows = nullptr;
|
||||
int32_t *h_first = nullptr, *d_first = nullptr;
|
||||
AdvGroup *h_grp = nullptr, *d_grp = nullptr;
|
||||
|
||||
char* h_derived = nullptr; /* derivation staging, byte-addressed */
|
||||
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
|
||||
* 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(). */
|
||||
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. */
|
||||
struct Flight {
|
||||
int64_t begin = 0, end = 0;
|
||||
int ev = -1; /* row of ev_ holding one event per rank */
|
||||
};
|
||||
static constexpr int kFlights = 64;
|
||||
struct Ring {
|
||||
char* host = nullptr;
|
||||
int64_t bytes = 0;
|
||||
int64_t head = 0; /* where the next span starts */
|
||||
Flight fifo[kFlights]; /* live flights, oldest at `first`, `live` of them */
|
||||
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. */
|
||||
static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4;
|
||||
struct Out {
|
||||
std::vector<std::vector<RadKVGroupBatch>> kv;
|
||||
std::vector<RadBatch> batch;
|
||||
};
|
||||
|
||||
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. */
|
||||
int32_t conv_grp = -1;
|
||||
const char* name = nullptr;
|
||||
int fn_index = -1;
|
||||
int64_t off = 0; /* byte offset into a set's derived region */
|
||||
int64_t capacity = 0; /* elements */
|
||||
int64_t produced = 0;
|
||||
BufferInfo* buf = nullptr;
|
||||
};
|
||||
|
||||
Program* prog_ = nullptr;
|
||||
Config cfg_{};
|
||||
ChunkGeometry geo_{};
|
||||
KVGeom kvgeom_{};
|
||||
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. */
|
||||
std::vector<int32_t> conv_window_;
|
||||
int32_t conv_group_ = -1; /* the ONLY conv group, when there is exactly one; else -1 */
|
||||
int32_t n_conv_ = 0;
|
||||
|
||||
Set set_;
|
||||
Ring ring_;
|
||||
/* [flight][rank]: the events a flight records behind its uploads, reused as flights retire. */
|
||||
std::vector<std::vector<RadEvent>> ev_;
|
||||
std::vector<int> ev_free_;
|
||||
Out out_[kOut];
|
||||
int out_next_ = 0;
|
||||
int out_last_ = -1; /* the Out build() just filled */
|
||||
/* 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.
|
||||
*
|
||||
* 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. */
|
||||
struct BtMirror {
|
||||
int64_t pitch = -1;
|
||||
std::vector<uint64_t> seq;
|
||||
std::vector<int64_t> len;
|
||||
};
|
||||
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 */
|
||||
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_).
|
||||
*
|
||||
* 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. */
|
||||
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 encoder's inputs: patches, their coordinates and the segment boundaries, the
|
||||
* largest pass the plugin declared. One copy a rank, since each runs the tower itself. */
|
||||
int64_t enc_patches_ = 0, enc_dim_ = 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;
|
||||
int64_t last_n_tok_ = 0;
|
||||
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. */
|
||||
int64_t stage_mm_rows(const StepEntry& e, int64_t k, int64_t shift, int64_t n_rows,
|
||||
int32_t* rows);
|
||||
|
||||
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. */
|
||||
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);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,117 @@
|
||||
/* derive.cpp -- the derivation table. One row per name; adding one is adding a row.
|
||||
*/
|
||||
#include "derive.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
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. */
|
||||
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;
|
||||
std::memcpy(out, in.cu_seqlens, (size_t)n * sizeof(int32_t));
|
||||
*n_out = n;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ conv_state_index */
|
||||
/* [n_seq] -- the entry of the conv state cache 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. */
|
||||
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;
|
||||
const int32_t W = in.conv_window > 0 ? in.conv_window : 1;
|
||||
for (int64_t i = 0; i < in.n_seq; ++i) {
|
||||
const StepEntry& e = in.plan->e[(size_t)i];
|
||||
int32_t slot = in.conv_slot[i];
|
||||
out[i] = slot < 0 ? -1 : (int32_t)(slot * W + (e.conv_cursor % W));
|
||||
}
|
||||
*n_out = in.n_seq;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- 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. */
|
||||
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;
|
||||
int64_t k = 0;
|
||||
|
||||
if (!WantSeq) {
|
||||
if (cap < 1) return RAD_E_FULL;
|
||||
out[k++] = 0;
|
||||
}
|
||||
for (int64_t i = 0; i < in.n_seq; ++i) {
|
||||
int64_t b = in.cu_seqlens[i], e = in.cu_seqlens[i + 1];
|
||||
if (e <= b) continue;
|
||||
int64_t p0 = in.positions[b];
|
||||
/* First interior boundary: the next absolute multiple of C strictly after p0. */
|
||||
int64_t next = ((p0 / C) + 1) * C;
|
||||
for (int64_t abs = next; abs < p0 + (e - b); abs += C) {
|
||||
if (k >= cap) return RAD_E_FULL;
|
||||
out[k++] = WantSeq ? (int32_t)i : (int32_t)(b + (abs - p0));
|
||||
}
|
||||
if (k >= cap) return RAD_E_FULL;
|
||||
out[k++] = WantSeq ? (int32_t)i : (int32_t)e;
|
||||
}
|
||||
*n_out = k;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* [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. */
|
||||
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. */
|
||||
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);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the table */
|
||||
static const DeriveRow g_rows[] = {
|
||||
{ "seq_start_index", d_seq_start_index,
|
||||
"[n_seq+1] first token index of each sequence in this step, and the total" },
|
||||
{ "conv_state_index", d_conv_state_index,
|
||||
"[n_seq] conv rolling-window entry to read, base slot * window + accepted cursor" },
|
||||
{ "state_chunk_bounds", d_state_chunk_bounds,
|
||||
"[n_chunks+1] token indices bounding each linear-state chunk; never crosses a sequence" },
|
||||
{ "state_chunk_seq", d_state_chunk_seq,
|
||||
"[n_chunks] the sequence each chunk belongs to" },
|
||||
};
|
||||
|
||||
int derive_index(const char* name) {
|
||||
if (!name) return -1;
|
||||
for (int i = 0; i < (int)(sizeof g_rows / sizeof g_rows[0]); ++i)
|
||||
if (std::strcmp(g_rows[i].name, name) == 0) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
const DeriveRow* derive_row(int i) {
|
||||
return (i >= 0 && i < (int)(sizeof g_rows / sizeof g_rows[0])) ? &g_rows[i] : nullptr;
|
||||
}
|
||||
|
||||
int derive_count() { return (int)(sizeof g_rows / sizeof g_rows[0]); }
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,51 @@
|
||||
/* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#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. */
|
||||
struct DeriveInput {
|
||||
const StepPlan* plan = nullptr;
|
||||
const int32_t* cu_seqlens = nullptr; /* [n_seq+1] */
|
||||
const int32_t* positions = nullptr; /* [n_tok] absolute position per token */
|
||||
const int32_t* conv_slot = nullptr; /* [n_seq] the conv group's state slot, -1 if none */
|
||||
int64_t n_tok = 0;
|
||||
int64_t n_seq = 0;
|
||||
int64_t state_chunk = 1; /* the resolved linear-state chunk length */
|
||||
int32_t conv_window = 1; /* conv_width - 1 + max_spec */
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
typedef int (*DeriveFn)(const DeriveInput& in, int32_t* out, int64_t cap, int64_t* n_out);
|
||||
|
||||
struct DeriveRow {
|
||||
const char* name;
|
||||
DeriveFn fn;
|
||||
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). */
|
||||
int derive_index(const char* name);
|
||||
const DeriveRow* derive_row(int index);
|
||||
int derive_count();
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,39 @@
|
||||
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
|
||||
*/
|
||||
#include "draft.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
int DraftController::configure(const Params& p) {
|
||||
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
|
||||
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
|
||||
p.max_depth, RAD_SCHED_MAX_SPEC, RAD_SCHED_MAX_SPEC);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
p_ = p;
|
||||
tot_drafted_ = tot_accepted_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
|
||||
seen_ = 0;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void DraftController::observe(int drafted, int accepted) {
|
||||
if (drafted <= 0) return;
|
||||
if (drafted > RAD_SCHED_MAX_SPEC) drafted = RAD_SCHED_MAX_SPEC;
|
||||
if (accepted < 0) accepted = 0;
|
||||
if (accepted > drafted) accepted = drafted;
|
||||
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. */
|
||||
const int last = accepted < drafted ? accepted : drafted - 1;
|
||||
for (int j = 0; j <= last; ++j) {
|
||||
++reach_[j];
|
||||
if (j < accepted) ++hit_[j];
|
||||
}
|
||||
if (drafted > seen_) seen_ = drafted;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,81 @@
|
||||
/* draft.h -- the speculative draft-depth controller.
|
||||
*
|
||||
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
|
||||
*
|
||||
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#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. */
|
||||
enum { RAD_SCHED_MAX_SPEC = 64 };
|
||||
|
||||
class DraftController {
|
||||
public:
|
||||
struct Params {
|
||||
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
|
||||
};
|
||||
|
||||
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. */
|
||||
int next_depth() const { return p_.max_depth; }
|
||||
|
||||
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
|
||||
* taken. Feeds the reported metrics and nothing else. */
|
||||
void observe(int drafted, int accepted);
|
||||
|
||||
/* Metrics (spec §14). Cumulative and exact. */
|
||||
int64_t drafted() const { return tot_drafted_; }
|
||||
int64_t accepted() const { return tot_accepted_; }
|
||||
float acceptance() const {
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
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. */
|
||||
int depth_seen() const { return seen_; }
|
||||
|
||||
private:
|
||||
Params p_;
|
||||
int64_t tot_drafted_ = 0, tot_accepted_ = 0;
|
||||
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
|
||||
int seen_ = 0;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,164 @@
|
||||
/* geometry.cpp -- reconciling the linear-state chunk geometry with the attention block size.
|
||||
* See geometry.h for why this is computed and not configured.
|
||||
*/
|
||||
#include "geometry.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
/* 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. */
|
||||
static const char* chunk_key_of(const RadOpSchema* s) {
|
||||
if (!s) return nullptr;
|
||||
for (int i = 0; i < s->n_params; ++i)
|
||||
if (s->params[i].role == RAD_PROLE_SEQ_CHUNK) return s->params[i].key;
|
||||
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. */
|
||||
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);
|
||||
}
|
||||
|
||||
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. */
|
||||
bool has_linear = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
|
||||
if (kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
}
|
||||
} else {
|
||||
has_linear = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- 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. */
|
||||
for (const OpInfo& op : prog.ops) {
|
||||
const char* ckey = chunk_key_of(op.schema);
|
||||
if (!ckey) continue;
|
||||
for (const Band& b : op.bands) {
|
||||
for (int d = 0; d < RAD_N_DOMAINS; ++d) {
|
||||
const Resolved& r = b.dom[d];
|
||||
if (!r) continue;
|
||||
|
||||
long long v = 0;
|
||||
if (r.geom.get_i(ckey, &v) && v > 0) {
|
||||
g.state_chunk = lcm64(g.state_chunk, (int64_t)v);
|
||||
note(g.why, ckey, v, op.op.c_str());
|
||||
}
|
||||
|
||||
const RadKernelInfo* ki = r.row ? r.row->info : nullptr;
|
||||
if (!ki) continue;
|
||||
for (int i = 0; i < ki->n_constraints; ++i) {
|
||||
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. */
|
||||
case RAD_C_DIV:
|
||||
case RAD_C_EQ:
|
||||
case RAD_C_GE:
|
||||
g.state_chunk = lcm64(g.state_chunk, (int64_t)c.ival);
|
||||
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)
|
||||
: (int64_t)c.ival;
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- reconcile */
|
||||
g.quantum = lcm64(g.attn_block, g.state_chunk);
|
||||
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. */
|
||||
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;
|
||||
out->min_max_tok = g.quantum;
|
||||
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.
|
||||
*
|
||||
* 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. */
|
||||
if (has_linear && cfg.checkpoint_interval > 0)
|
||||
g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
|
||||
else
|
||||
g.checkpoint_interval = 0;
|
||||
|
||||
/* 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. */
|
||||
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.");
|
||||
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. */
|
||||
const int64_t eff = (g.checkpoint_interval > 0 && g.checkpoint_interval < cfg.max_tok)
|
||||
? g.checkpoint_interval : 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)" : "");
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,62 @@
|
||||
/* geometry.h -- the chunk geometry, COMPUTED from the resolved kernels rather than documented as
|
||||
* a minimum an operator has to know.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t checkpoint_interval = 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. */
|
||||
int64_t max_chunk = 0;
|
||||
|
||||
/* Every contributor by name, for the startup line and for the refusal. Built once. */
|
||||
std::string why;
|
||||
|
||||
bool checkpoints() const { return checkpoint_interval > 0; }
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out);
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,410 @@
|
||||
/* 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:
|
||||
*
|
||||
* - 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.
|
||||
*
|
||||
* `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.
|
||||
*/
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include "mem/prefix.h"
|
||||
#include "rad_core.h"
|
||||
#include "mm/processor.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
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. */
|
||||
struct IKVManager {
|
||||
virtual ~IKVManager() = default;
|
||||
|
||||
virtual int add_sequence(uint64_t seq) = 0;
|
||||
virtual bool has_sequence(uint64_t seq) const = 0;
|
||||
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. */
|
||||
virtual int ensure(uint64_t seq, int64_t n_tokens) = 0;
|
||||
|
||||
/* 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. */
|
||||
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). */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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`. */
|
||||
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. */
|
||||
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
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. `Wait` when part of it is still being read off disk: the request is not
|
||||
* admitted this step -- the ones behind it may be -- and is asked again on the next. Admitting
|
||||
* it anyway would stop its hit at the first entry not yet read, and the hit length is what
|
||||
* its prefill is chunked against, so the same prompt would run different shapes depending on
|
||||
* how far a read had got.
|
||||
*
|
||||
* 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. */
|
||||
enum class Restore { Done, Wait };
|
||||
virtual Restore restore(const Request&) { return Restore::Done; }
|
||||
/* A step's admissions begin: what the last step's lookups handed out has been read. */
|
||||
virtual void begin_step() {}
|
||||
|
||||
virtual CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* blocks_out) 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. */
|
||||
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. */
|
||||
virtual int64_t evict(int64_t n_entries) = 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. */
|
||||
virtual int64_t reset() {
|
||||
int64_t dropped = 0;
|
||||
for (int guard = 0; guard < 65536; ++guard) {
|
||||
const int64_t n = evict(1024);
|
||||
if (n <= 0) break;
|
||||
dropped += n;
|
||||
}
|
||||
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. */
|
||||
virtual int64_t evictions() const = 0;
|
||||
virtual int64_t ckpt_evictions() const = 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t sidx_width = 1;
|
||||
};
|
||||
std::vector<G> g;
|
||||
|
||||
static KVGeom of(const std::vector<KVGroupInfo>& groups) {
|
||||
KVGeom k;
|
||||
k.g.reserve(groups.size());
|
||||
for (const KVGroupInfo& gi : groups) {
|
||||
G e;
|
||||
e.kind = gi.decl.kind;
|
||||
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW);
|
||||
e.block_size = gi.block_size > 0 ? gi.block_size : 1;
|
||||
e.window = gi.decl.window;
|
||||
k.g.push_back(e);
|
||||
}
|
||||
return k;
|
||||
}
|
||||
|
||||
/* Flat KV slot for absolute token position `pos`, given the sequence's block table for this
|
||||
* group and the position its first block covers. */
|
||||
int32_t slot(int gi, const std::vector<int32_t>& bt, int64_t first_pos, int64_t pos) const {
|
||||
const G& e = g[(size_t)gi];
|
||||
int64_t bi = (pos - first_pos) / e.block_size;
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ 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. */
|
||||
template <class KV>
|
||||
struct KVBinding final : IKVManager {
|
||||
KV* m;
|
||||
explicit KVBinding(KV* k) : m(k) {}
|
||||
|
||||
int add_sequence(uint64_t s) override { return m->add_sequence(s); }
|
||||
bool has_sequence(uint64_t s) const override { return m->has_sequence(s); }
|
||||
void free_sequence(uint64_t s) override { m->free_sequence(s); }
|
||||
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
|
||||
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
|
||||
return m->adopt(s, g, b, n);
|
||||
}
|
||||
int preempt(uint64_t s) override { return m->preempt(s); }
|
||||
bool can_ever_fit(int64_t n) const override { return m->can_ever_fit(n); }
|
||||
const std::vector<int32_t>& block_table(uint64_t s, int32_t g) const override {
|
||||
return m->block_table(s, g);
|
||||
}
|
||||
int32_t state_slot(uint64_t s, int32_t g) const override { return m->state_slot(s, g); }
|
||||
int state_index_row(uint64_t s, int32_t g, int32_t* o, int n) const override {
|
||||
return m->state_index_row(s, g, o, n);
|
||||
}
|
||||
int64_t state_index_width(int32_t g) const override { return m->state_index_width(g); }
|
||||
int64_t free_blocks(int32_t g) const override { return m->free_blocks(g); }
|
||||
int64_t total_blocks(int32_t g) const override { return m->total_blocks(g); }
|
||||
int64_t held_blocks(int32_t g) const override { return m->held_blocks(g); }
|
||||
int64_t pool_bytes(int32_t g) const override { return m->pool_bytes(g); }
|
||||
int64_t pool_bytes_used(int32_t g) const override { return m->pool_bytes_used(g); }
|
||||
int64_t pool_bytes_carved(int32_t g) const override { return m->pool_bytes_carved(g); }
|
||||
int64_t block_tokens(int32_t g) const override {
|
||||
const KVGroupPlan* p = m->plan(g);
|
||||
return p && p->paged() ? p->block_size : 0;
|
||||
}
|
||||
int rollback(uint64_t s, int64_t n) override { return m->rollback(s, n); }
|
||||
int64_t first_block_pos(uint64_t s, int32_t g) const override {
|
||||
return m->first_block_pos(s, g);
|
||||
}
|
||||
int64_t take_table_changes(uint64_t s, int32_t g) const override {
|
||||
return m->take_table_changes(s, g);
|
||||
}
|
||||
};
|
||||
|
||||
/* 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. */
|
||||
inline void media_keys(const Request& r, std::vector<MMContentKey>* out) {
|
||||
out->clear();
|
||||
if (!r.media) return;
|
||||
const mm::PromptMedia& pm = *r.media;
|
||||
for (const mm::RopeLayout::Run& run : pm.rope.runs) {
|
||||
const mm::Item& it = *pm.items[(size_t)run.item].item;
|
||||
MMContentKey k;
|
||||
k.tok_begin = run.tok;
|
||||
k.tok_end = run.tok + run.n;
|
||||
k.hash = it.key_hi ^ (it.key_lo * 0x9e3779b97f4a7c15ull) ^
|
||||
((uint64_t)(uint32_t)run.row0 * 0xc2b2ae3d27d4eb4full);
|
||||
out->push_back(k);
|
||||
}
|
||||
}
|
||||
|
||||
template <class PC>
|
||||
struct PCBinding final : IPrefixCache {
|
||||
PC* m;
|
||||
/* Scratch for a request's media keys, reused so a text request's lookup allocates nothing. */
|
||||
mutable std::vector<MMContentKey> mm_;
|
||||
explicit PCBinding(PC* p) : m(p) {}
|
||||
|
||||
CacheHit lookup(const Request& r,
|
||||
std::vector<std::vector<int32_t>>* out) const override {
|
||||
media_keys(r, &mm_);
|
||||
return m->lookup(r.prompt, mm_, out);
|
||||
}
|
||||
|
||||
/* Installed by the engine when the idle tiers are on; empty otherwise. */
|
||||
std::function<Restore(const Request&)> restore_fn;
|
||||
Restore restore(const Request& r) override {
|
||||
return restore_fn ? restore_fn(r) : Restore::Done;
|
||||
}
|
||||
void begin_step() override { m->begin_step(); }
|
||||
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. */
|
||||
int insert(const Request& r, const std::vector<std::vector<int32_t>>& blocks,
|
||||
int64_t n_tokens) override {
|
||||
std::vector<int32_t> toks;
|
||||
toks.reserve(r.prompt.size() + r.output.size());
|
||||
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. */
|
||||
media_keys(r, &mm_);
|
||||
return m->insert(r.id, toks, mm_, blocks, n_tokens);
|
||||
}
|
||||
int64_t evict(int64_t n) override { return m->evict_lru(n); }
|
||||
int64_t reset() override {
|
||||
const int64_t n = m->size();
|
||||
m->clear();
|
||||
return n;
|
||||
}
|
||||
int64_t evictions() const override { return m->stats().evictions; }
|
||||
int64_t ckpt_evictions() const override { return m->stats().ckpt_evictions; }
|
||||
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. */
|
||||
return m->reserve_checkpoint(r.id, pos, prefix_hash(r, pos), slot_out);
|
||||
}
|
||||
|
||||
void commit_checkpoint(const Request& r, int64_t pos) override {
|
||||
m->commit_checkpoint(prefix_hash(r, pos));
|
||||
}
|
||||
|
||||
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. */
|
||||
BlockHash prefix_hash(const Request& r, int64_t pos) const {
|
||||
media_keys(r, &mm_);
|
||||
const int64_t bs = m->block_size();
|
||||
BlockHash h{};
|
||||
if (bs <= 0) return h;
|
||||
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);
|
||||
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)];
|
||||
}
|
||||
h = chain_block_hash(h, blk.data(), (int32_t)bs, mm_.data(), (int32_t)mm_.size(), base);
|
||||
}
|
||||
return h;
|
||||
}
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -0,0 +1,135 @@
|
||||
/* 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.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
enum { RAD_SCHED_MAX_KV_GROUPS = 16 };
|
||||
|
||||
struct SchedMetrics {
|
||||
int64_t step = 0;
|
||||
|
||||
/* Queue state, instantaneous. */
|
||||
int64_t queue_depth = 0; /* requests waiting, including preempted ones */
|
||||
int64_t running = 0;
|
||||
int64_t preempted_waiting = 0; /* of queue_depth, how many are awaiting recompute */
|
||||
|
||||
/* Cumulative counters. Monotonic, so a scraper can rate() them. */
|
||||
int64_t admitted = 0;
|
||||
int64_t finished = 0;
|
||||
int64_t failed = 0;
|
||||
int64_t cancelled = 0;
|
||||
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. */
|
||||
int64_t steps_prefill = 0;
|
||||
int64_t steps_mixed = 0;
|
||||
int64_t steps_decode = 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. */
|
||||
int64_t steps_ahead = 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). */
|
||||
int64_t step_ns = 0;
|
||||
int64_t step_ns_decode = 0;
|
||||
|
||||
/* Per KV group. `name` points into the Program, which outlives any scrape. */
|
||||
int n_kv_groups = 0;
|
||||
struct Group {
|
||||
const char* name = "";
|
||||
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. */
|
||||
int64_t block_tokens = 0;
|
||||
/* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int64_t prefix_evictions = 0;
|
||||
int64_t prefix_ckpt_evictions = 0;
|
||||
/* 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. */
|
||||
int64_t prefix_held_tokens = 0;
|
||||
float linear_hit_rate = 0.0f;
|
||||
int64_t checkpoints_written = 0;
|
||||
|
||||
/* Throughput: tokens over wall time in a 1-second decaying window (Scheduler::step_finished);
|
||||
* the counters beside them are exact. */
|
||||
int64_t prefill_tokens = 0;
|
||||
int64_t decode_tokens = 0;
|
||||
float prefill_tps = 0.0f;
|
||||
float decode_tps = 0.0f;
|
||||
|
||||
/* Speculation (§10). */
|
||||
int64_t draft_tokens = 0;
|
||||
int64_t draft_accepted = 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. */
|
||||
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] = {};
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,676 @@
|
||||
/* scheduler.h -- continuous batching, chunked prefill, a priority queue, 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.
|
||||
*
|
||||
* 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).
|
||||
*/
|
||||
#pragma once
|
||||
#include "batch.h"
|
||||
#include "draft.h"
|
||||
#include "metrics.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <unordered_map>
|
||||
|
||||
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. */
|
||||
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 */
|
||||
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. */
|
||||
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. */
|
||||
int64_t arrived_us = 0;
|
||||
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
|
||||
|
||||
/* The drafter's proposal for the next step, and the conv-window read cursor a rejection
|
||||
* moves rather than rolls back (§10). */
|
||||
int32_t draft[RAD_SCHED_MAX_SPEC] = {};
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
void drafter_reset() {
|
||||
n_draft = 0;
|
||||
draft_next = 0;
|
||||
conv_cursor = 0;
|
||||
draft_filled = 0;
|
||||
draft_lo = 0;
|
||||
draft_hi = 0;
|
||||
}
|
||||
|
||||
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
|
||||
* 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. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
int32_t hit_attn = 0;
|
||||
bool hit_owed = false;
|
||||
|
||||
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
|
||||
int64_t seq_len() const {
|
||||
return (int64_t)req->prompt.size() + (int64_t)req->output.size();
|
||||
}
|
||||
};
|
||||
|
||||
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. */
|
||||
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 */
|
||||
};
|
||||
|
||||
/* `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. */
|
||||
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. */
|
||||
AdvanceArgs advance_args(int rank) const { return builder_.advance_args(rank); }
|
||||
void fini();
|
||||
|
||||
/* ---------------------------------------------------------- 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. */
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
*
|
||||
* NOTHING RUN UNDER IT MAY CALL BACK INTO THE SCHEDULER: the mutex is not recursive, and
|
||||
* every public method here takes it. */
|
||||
template <class Fn> auto locked(Fn&& fn) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return fn();
|
||||
}
|
||||
/* The same lock, held for the rest of the caller's scope. */
|
||||
[[nodiscard]] std::unique_lock<std::mutex> hold() { return std::unique_lock<std::mutex>(mu_); }
|
||||
|
||||
/* ---------------------------------------------------------- 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. */
|
||||
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. */
|
||||
void shutdown(const char* reason);
|
||||
|
||||
/* 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. */
|
||||
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. */
|
||||
struct ReqStat {
|
||||
uint64_t id = 0;
|
||||
int state = 0; /* ReqState, as an int -- the caller has the enum */
|
||||
bool running = false;
|
||||
int64_t prompt_tokens = 0;
|
||||
int64_t computed_tokens = 0; /* of the prompt, how much is in the KV: prefill progress */
|
||||
int64_t cached_tokens = 0; /* of those, how many came from the prefix cache */
|
||||
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. */
|
||||
int64_t kv_blocks = 0;
|
||||
int64_t kv_tokens = 0;
|
||||
int32_t n_draft = 0; /* the proposal standing for the next step */
|
||||
int32_t slot = -1;
|
||||
double age_s = 0;
|
||||
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. */
|
||||
int requests(ReqStat* out, int max) const;
|
||||
|
||||
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
|
||||
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. */
|
||||
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. */
|
||||
const RadBatch* build_encoder(const std::vector<BatchBuilder::EncoderPart>& parts, int step) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return builder_.build_encoder(parts, step);
|
||||
}
|
||||
int64_t encoder_patches() const { return builder_.encoder_patches(); }
|
||||
|
||||
/* 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. */
|
||||
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
|
||||
*
|
||||
* 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.
|
||||
*
|
||||
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
|
||||
* which is how many the next step verifies.
|
||||
* 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.
|
||||
* 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. */
|
||||
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. */
|
||||
void step_finished();
|
||||
|
||||
/* ---------------------------------------------------- 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
struct SerialRow {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
int32_t card = -1;
|
||||
};
|
||||
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. */
|
||||
void serial_end(int rounds_done);
|
||||
|
||||
/* ----------------------------------------------------- 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.
|
||||
*
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
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. */
|
||||
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);
|
||||
void block_end();
|
||||
|
||||
const StepPlan& plan() const { return plan_; }
|
||||
const ChunkGeometry& geometry() const { return geo_; }
|
||||
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. */
|
||||
void publish(bool idle);
|
||||
SchedMetrics observed_metrics() const;
|
||||
int observed_requests(ReqStat* out, int max) const;
|
||||
|
||||
/* Visible for tests: the chunk the scheduler would give a request at `n_computed` under a
|
||||
* token budget, and the checkpoint position it will land on (-1 for none). */
|
||||
int64_t plan_chunk(int64_t n_computed, int64_t n_target, int64_t budget,
|
||||
int64_t* checkpoint_pos) const;
|
||||
|
||||
private:
|
||||
Program* prog_ = nullptr;
|
||||
Config cfg_{};
|
||||
ChunkGeometry geo_{};
|
||||
KVGeom kvgeom_{};
|
||||
/* Does this model carry recurrent state a prefix hit would have to restore? See admit_one. */
|
||||
bool has_linear_state_ = false;
|
||||
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. */
|
||||
bool hit_holes_draft_ = true;
|
||||
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. */
|
||||
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 built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
|
||||
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
|
||||
* lengths it tries, longest first. */
|
||||
int draft_ngram(SchedReq& s, int depth) const;
|
||||
enum { kNgramMin = 2, kNgramMax = 4 };
|
||||
|
||||
mutable std::mutex mu_;
|
||||
|
||||
SchedMetrics metrics_locked() const;
|
||||
int requests_locked(ReqStat* out, int max) const;
|
||||
/* The published copy and its lock (publish()). The scratch pair is the engine thread's, filled
|
||||
* under mu_ and then swapped with the published pair, so a publication allocates nothing once
|
||||
* the vectors have grown to the request count. */
|
||||
mutable std::mutex pub_mu_;
|
||||
SchedMetrics pub_m_;
|
||||
std::vector<ReqStat> pub_reqs_;
|
||||
SchedMetrics scratch_m_;
|
||||
std::vector<ReqStat> scratch_reqs_;
|
||||
int64_t pub_at_us_ = 0;
|
||||
|
||||
std::vector<std::unique_ptr<SchedReq>> reqs_; /* by slot */
|
||||
std::vector<int32_t> free_slots_;
|
||||
std::vector<int32_t> free_cards_; /* card indices not held by any sequence; see SchedReq::card */
|
||||
std::unordered_map<uint64_t, int32_t> by_id_;
|
||||
|
||||
/* Both kept sorted by (priority desc, arrival asc). running_ is sorted so the preemption
|
||||
* victim is the back; waiting_ so admission takes the front. */
|
||||
std::vector<int32_t> running_;
|
||||
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. */
|
||||
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. */
|
||||
bool media_ready(SchedReq& s);
|
||||
|
||||
/* Set by shutdown(); add() refuses from then on. */
|
||||
bool closed_ = false;
|
||||
const char* closed_reason_ = "";
|
||||
|
||||
/* 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. */
|
||||
int64_t ctx_limit_ = 0;
|
||||
|
||||
/* 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. */
|
||||
std::vector<std::vector<int32_t>> hit_blocks_;
|
||||
/* Scratch for publishing a finished sequence into the prefix cache. Reused so close_request
|
||||
* does not allocate per completion. */
|
||||
std::vector<std::vector<int32_t>> pub_blocks_;
|
||||
|
||||
StepPlan plan_;
|
||||
StepPlan plan_next_;
|
||||
bool next_open_ = false;
|
||||
/* Is a step the card may still be running holding this request? */
|
||||
bool in_step(const SchedReq& s) const {
|
||||
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. */
|
||||
struct SerialSeq {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
int32_t card = -1;
|
||||
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):
|
||||
* 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. */
|
||||
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
|
||||
* 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. */
|
||||
struct BlockSeq {
|
||||
uint64_t seq = 0;
|
||||
int32_t slot = -1;
|
||||
int32_t card = -1;
|
||||
int32_t ctx_len = 0;
|
||||
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). */
|
||||
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(). */
|
||||
};
|
||||
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. */
|
||||
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. */
|
||||
std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
|
||||
int64_t step_prefill_tok_ = 0, step_decode_tok_ = 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;
|
||||
bool step_open_ = false;
|
||||
|
||||
/* arrival; mu_ held */
|
||||
int add_locked(std::unique_ptr<Request> r);
|
||||
|
||||
/* ordering */
|
||||
bool ahead_of(int32_t a, int32_t b) const;
|
||||
void queue_insert(std::vector<int32_t>& q, int32_t slot);
|
||||
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. */
|
||||
void close_request(SchedReq& s, ReqState st, const char* reason, bool defer_free = false,
|
||||
bool publish = true);
|
||||
/* What reap() does once nothing points at the slot any more: give the blocks back, forget the
|
||||
* id, destroy the Request and return the slot. Called by reap() directly, or by the sweep in
|
||||
* commit() for a request whose reap arrived while something still pointed at it. */
|
||||
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. */
|
||||
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. */
|
||||
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. */
|
||||
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.
|
||||
* The next attempt looks the prompt up again. */
|
||||
void undo_hit(SchedReq& s);
|
||||
/* The live Request behind a snapshot row, or null if it went away. */
|
||||
const Request* block_req(const BlockSeq& d) const;
|
||||
const Request* serial_req(const SerialSeq& m) const;
|
||||
/* Both snapshots resolve the same way; the two wrappers exist because the row types differ. */
|
||||
const Request* live_req(int32_t slot, uint64_t id) const;
|
||||
void preempt_back();
|
||||
/* Give blocks back from the prefix cache until the pool has headroom again. */
|
||||
void trim_prefix_cache();
|
||||
/* RAD_OK, a negative status when the request cannot be admitted now -- nothing behind it is
|
||||
* either -- or kAdmitWait when its context is still being read off disk and the next request
|
||||
* may go ahead of it. */
|
||||
int admit_one(SchedReq& s, int64_t budget);
|
||||
static constexpr int kAdmitWait = 1;
|
||||
/* The queue positions one step's admission took, kept to reuse the allocation. */
|
||||
std::vector<size_t> took_;
|
||||
|
||||
/* The conv rolling window, width-1 + num_spec + 1 entries (spec §10). */
|
||||
int32_t conv_window() const;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user