Merge upstream main (v1.12 -> v1.15.1, 408 commits) into the SYCL port

Conflicts from the old m2xfp branch take upstream's version. Two libxe2 fixes the merge needs:
- rad_plugin_abi_layout: the plugin now exports the ABI layout hash the loader checks.
- gemm_nt_q_w4a16: upstream 492d33c sends bf16 activations to the w4a16 GEMM (the separate cast
  is gone); the fast kernel took only f16, so every call fell back to the exact path (decode
  ~2.5 tok/s). A bf16 activation is narrowed to f16 (round to nearest even) into a workspace first,
  the dropped cast bit for bit; decode back to ~57 tok/s on one request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
claudeandClaude Opus 5.5 committed 2026-11-02 00:25:57 +01:00
commit 7580ec3d17
937 files changed
+285776 -8914

No files matched your search

+20
View File
@@ -25,4 +25,24 @@ int step_advance(const AdvanceArgs& a, RadStream s) {
#endif
}
int step_compact(const AdvanceArgs& a, RadStream s) {
if (a.n_seq <= 0 || a.n_pool <= 0) return RAD_OK;
if (device_is_host()) {
RAD_TRY(rad_stream_sync(s));
const int items = adv_compact_items(a);
for (int i = 0; i < a.n_seq; ++i)
for (int w = 0; w < items; ++w) {
int p = 0, l = 0, h = 0;
if (adv_compact_item(a, w, &p, &l, &h)) adv_compact(a, i, p, l, h, 0, 1);
}
return RAD_OK;
}
#if defined(RAD_HAVE_HIP) && RAD_HAVE_HIP
return rad_step_compact_launch(&a, (void*)s) == 0 ? RAD_OK : RAD_E_DEVICE;
#else
(void)s;
return RAD_E_UNSUPPORTED;
#endif
}
} /* namespace rad */
+53 -1
View File
@@ -35,7 +35,20 @@ struct StepSlot {
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];
/* A tree drafter's proposal (rad_drafter_tree): par[j] is the parent of node j + 1, a node
* index in [0, j], where node 0 is the bonus token tok[0] and node j + 1 is tok[j + 1].
* `ntree` is the number of nodes it describes, written by ADV_BTAKE from the drafter's
* parents plane; 0 means tok[1..] is a chain. */
int32_t par[RAD_SCHED_MAX_SPEC];
int32_t ntree;
/* The last verify's accepted root path: path[t] is the node committed (t + 1)-th, so the
* committed tokens are tok[path[0]], tok[path[1]], ... and the step's anchor sits at
* ctx - 1 - npath. ADV_COMPACT moves those nodes' K and V from where the verify stored them
* (its row index) to where they belong (their depth), and ADV_CTXTREE positions the
* drafter's context rows by it. 0 after a chain verify, which needs neither. */
int32_t npath;
int32_t path[RAD_SCHED_MAX_SPEC];
int32_t pad[2];
};
enum AdvMode : int32_t {
@@ -47,6 +60,26 @@ enum AdvMode : int32_t {
/* A block drafter (RAD_DRAFT_BLOCK) on the card: */
ADV_BLOCK = 6, /* before the query pass: the anchor at the committed end, then the masks */
ADV_BTAKE = 7, /* after it: its `round` proposals into the state, behind the bonus token */
/* A tree drafter (rad_drafter_tree), whose verify rows are a tree rather than a chain: */
ADV_CTXTREE = 8, /* before the context pass: the accepted path's rows at their depth, the
* rejected rows stored nowhere */
};
/* The most paged KV groups one ADV_COMPACT moves (the trunk's sliding and global groups and a
* drafter's own, with room). */
enum { kAdvMaxPools = 6 };
/* One paged group's cache on one rank, as ADV_COMPACT addresses it: `n_layers` caches of
* [n_blocks, n_head, block_size, row_bytes] bytes, `layer_stride` apart from `base`
* (core/runtime/kvbind.cpp composes that shape). `grp` indexes the batch's AdvGroup array, whose
* block table maps a position to a block. */
struct AdvPool {
char* base;
int64_t layer_stride;
int32_t n_layers;
int32_t n_head;
int32_t row_bytes;
int32_t grp;
};
/* One KV group, as the builder stages it for this build. Offsets are bytes into the rank's slab,
@@ -112,12 +145,31 @@ struct AdvanceArgs {
* position of those rows, 0 or 1 past the committed position. Zero for every other head. */
int32_t shared_kv = 0;
int32_t rot_shift = 0;
/* A tree drafter (rad_drafter_tree). ADV_BTAKE: the proposal's parents plane, row i's from
* i * src_pitch as the tokens are; null for a chain drafter. */
const int32_t* par = nullptr;
/* ADV_TRUNK: RadBatch::spec_parent [n_tok] in the slab, or -1 when the build stages none.
* A tree row's entry is its parent's row within the sequence's block (-1 for the bonus
* token); every other row's is -2, an ordinary causal row. */
int64_t parent_off = -1;
/* ADV_COMPACT: every paged group's cache on this rank. */
AdvPool pool[kAdvMaxPools] = {};
int32_t n_pool = 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);
/* ADV_COMPACT, after ADV_ACCEPT on a tree verify and before anything reads the trunk's cache: for
* every row whose StepSlot holds an accepted path, move the K and V each path node's verify row
* stored (at the anchor's position + its row index) to its committed position (+ its depth), in
* every pool of `a`, every layer and every head. A separate kernel from the advance because it
* moves bytes across the whole cache rather than patching a row's few integers. */
int step_compact(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);
/* And ADV_COMPACT's. */
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream);
+43
View File
@@ -59,8 +59,51 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr
}
}
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
* split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every
* block waiting for the kernels before it and counting itself in after its moves. */
constexpr int kCompactThreads = 64;
__device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) {
int p = 0, l = 0, h = 0;
if (!rad::adv_compact_item(a, (int)blockIdx.x, &p, &l, &h)) return;
rad::adv_compact(a, (int)blockIdx.y, p, l, h, (int)threadIdx.x, kCompactThreads);
}
__global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::AdvanceArgs a) {
step_compact_body(a);
}
__global__ __launch_bounds__(kCompactThreads) void r4dchain_step_compact(rad::AdvanceArgs a) {
const ChainRec* r = chain_rec();
if (r) {
if (threadIdx.x == 0)
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
__builtin_amdgcn_s_sleep(1);
__syncthreads();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
}
step_compact_body(a);
if (r) {
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
__syncthreads();
if (threadIdx.x == 0)
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
}
} // namespace
extern "C" int rad_step_compact_launch(const rad::AdvanceArgs* args, void* stream) {
if (!args || args->n_seq <= 0) return 0;
const int items = rad::adv_compact_items(*args);
if (items <= 0) return 0;
if (!rad_dev_chain_enabled())
hipLaunchKernelGGL(rad_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
else
hipLaunchKernelGGL(r4dchain_step_compact, dim3((unsigned)items, (unsigned)args->n_seq),
dim3(kCompactThreads), 0, (hipStream_t)stream, *args);
return hipGetLastError() == hipSuccess ? 0 : -1;
}
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);
+184 -15
View File
@@ -28,6 +28,20 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
return lo < a.n_eog && a.eog[lo] == t;
}
/* Group `e`'s slot for position `p` of batch row `i`, or -1 past its block table. A runtime
* window's position at or past ring_pos is in its ring (see adv_groups). */
RAD_ADV_FN int32_t adv_slot(const AdvanceArgs& a, const AdvGroup& e, int i, int32_t p) {
const int32_t first = adv_i32(a, e.first_off)[i];
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t bi = (p - first) / e.block_size;
if (e.ring && e.ring_blocks > 0 && adv_i32(a, e.tlen_off)[i] > 0) {
const int32_t rpos = adv_i32(a, e.rpos_off)[i];
if (p >= rpos) bi = rpos / e.block_size + ((p - rpos) / e.block_size) % e.ring_blocks;
}
return (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
}
/* Every group's slots for the row's `n` positions (from the positions just written) and its
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
* tables for the furthest reachable position, so only a row whose output is unused hits this.
@@ -40,38 +54,46 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
* reads the -1 padding the builder fills and faults the card on a negative block;
* - a position at or past ring_pos lives in the ring, at block
* ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs
* off the table once the ring wraps. */
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
* off the table once the ring wraps.
*
* `len`, when given, is the length's count from `base` in place of `n` (ADV_HIST: rows that
* repeat a position must not lengthen the context). `at`, when given, is where each row stores its
* K and V instead of its position: a tree verify's rows rotate at their depth but store at their
* row index, since siblings share a depth (ADV_TRUNK), and a context row the tree rejected stores
* nowhere (-1, ADV_CTXTREE). */
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n,
int32_t len = -1, const int32_t* at = nullptr) {
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];
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
const bool ring = e.ring && tlen > 0;
int64_t used = (int64_t)base + n - first;
int64_t used = (int64_t)base + (len >= 0 ? len : n) - first;
if (ring) {
const int64_t span = (int64_t)tlen * e.block_size;
if (used > span) used = span;
}
adv_i32(a, e.used_off)[i] = (int32_t)used;
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];
int32_t bi = (p - first) / e.block_size;
if (ring && p >= rpos && e.ring_blocks > 0)
bi = rpos / e.block_size +
((p - rpos) / e.block_size) % e.ring_blocks;
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
const int32_t p = at ? at[j] : pos[k + j];
slot[k + j] = p >= 0 ? adv_slot(a, e, i, p) : -1;
}
}
}
/* A tree's node depths from its parents: node 0 (the bonus token) at 0, node j + 1 one below
* par[j]. A parent outside [0, j] is a drafter bug; it is read as the previous node, so the row
* still stores and rotates somewhere sane, and the verify rejects whatever it proposed. */
RAD_ADV_FN int32_t adv_parent(const StepSlot& S, int32_t j) {
const int32_t p = S.par[j - 1];
return (p < 0 || p >= j) ? j - 1 : p;
}
/* Writes a row's position and moves its rotary components by the same amount. A row whose
* position does not change keeps the host's components. */
RAD_ADV_FN void adv_pos(const AdvanceArgs& a, int32_t* pos, int32_t row, int32_t p) {
@@ -104,10 +126,39 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
switch (a.mode) {
case ADV_ACCEPT: {
const int32_t* y = a.src + rout;
/* A tree verify, which the trunk's spec_parent row says (its first entry is -1, the root,
* whoever staged it: ADV_TRUNK for a card row, the builder for a host row): accept_tree's
* rule. From the bonus token, follow the first child (lowest node index) whose token is
* the target's pick at its parent's row, as long as one is; then the same
* end-of-generation cut over the tokens that walk emits. */
const int32_t* tp = a.parent_off >= 0 ? adv_i32(a, a.parent_off) + rtok : nullptr;
if (tp && aux > 0 && tp[0] == -1) {
const int32_t* d = tok + rtok; /* node j's token is d[j], 1 <= j <= aux */
const int32_t a0 = rtok - k; /* parents count rows from the sequence's first */
int32_t cur = 0, acc = 0;
for (;;) {
int32_t nxt = -1;
for (int32_t j = cur + 1; j <= aux; ++j)
if (tp[j] - a0 == cur && d[j] == y[cur]) { nxt = j; break; }
if (nxt < 0) break;
S.path[acc++] = nxt;
cur = nxt;
}
for (int32_t t = 0; t <= acc; ++t)
if (adv_is_eog(a, y[t == 0 ? 0 : S.path[t - 1]])) { acc = t; 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 == 0 ? 0 : S.path[acc - 1]];
S.npath = acc;
return;
}
/* accept_greedy's rule, then collect_step's end-of-generation cut: a draft is accepted
* while it equals the target's pick at its position, and the run stops at an
* end-of-generation token, not after it. */
const int32_t* y = a.src + rout;
const int32_t* d = tok + rtok + 1;
int32_t acc = 0;
while (acc < aux && d[acc] == y[acc]) ++acc;
@@ -119,16 +170,64 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
S.ctx = head + 1;
S.n_acc = acc + 1;
S.tok[0] = y[acc];
S.npath = 0;
return;
}
case ADV_TRUNK: {
const int32_t base = S.ctx;
if (a.parent_off >= 0) {
int32_t* par = adv_i32(a, a.parent_off);
/* A row verifying fewer nodes than the drafter proposed (a window cut it) verifies
* their prefix, which is a tree too: every parent precedes its child. */
if (n > 1 && S.ntree >= n - 1) {
/* A tree: node j stores its K and V at base + j (siblings share a depth, so the
* position cannot address them) and rotates at base + its depth, the position the
* token would have if its path were committed. Attention reads spec_parent to see
* only a row's own ancestors inside the block. */
int32_t dep[1 + RAD_SCHED_MAX_SPEC], at[1 + RAD_SCHED_MAX_SPEC];
for (int32_t j = 0; j < n; ++j) {
const int32_t p = j == 0 ? -1 : adv_parent(S, j);
dep[j] = j == 0 ? 0 : dep[p] + 1;
tok[k + j] = S.tok[j];
par[k + j] = p;
adv_pos(a, pos, k + j, base + dep[j]);
at[j] = base + j;
}
ctx[i] = base;
adv_i32(a, a.acc_off)[i] = S.n_acc;
adv_groups(a, i, k, base, n, -1, at);
return;
}
for (int32_t j = 0; j < n; ++j) par[k + j] = -2;
}
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_CTXTREE: {
/* The drafter's context pass over a tree verify's rows (one per node, in node order, as
* the trunk tapped them), a card row only where the host marked the step's entry as one.
* Only the accepted path is context: path node t's row writes at the anchor + t + 1,
* rotated there, which is where its token now sits, and every rejected node's row stores
* nowhere. Run after ADV_ACCEPT, which wrote the path, and before ADV_BTAKE. A chain
* verify's path is its first `acc` rows (npath 0). */
const int32_t base = S.head - S.acc;
int32_t at[1 + RAD_SCHED_MAX_SPEC];
at[0] = base;
adv_pos(a, pos, k, base);
for (int32_t j = 1; j < n; ++j) { at[j] = -1; adv_pos(a, pos, k + j, base); }
for (int32_t t = 0; t < S.acc; ++t) {
const int32_t r = t < S.npath ? S.path[t] : t + 1;
if (r < 1 || r >= n) continue;
at[r] = base + t + 1;
adv_pos(a, pos, k + r, base + t + 1);
}
ctx[i] = base;
adv_groups(a, i, k, base, n, -1, at);
return;
}
case ADV_HIST: {
if (a.shared_kv) {
/* A head that reads the trunk's cache and keeps none (rad_drafter_shared_kv). With no
@@ -162,7 +261,14 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
out[k + j] = row0 + jj;
}
ctx[i] = base;
adv_groups(a, i, k, base, n);
/* The context ends at the last committed position, not at the run's end. Attention places
* row j of a q_len-row run at seqused - q_len + j and reads keys up to there (attn_paged's
* contract). With the run's whole length the last row, the only one whose output is used,
* would also read the n_spec - acc positions after it, which the head has not written for
* this sequence (stale rounds, or another request's K and V). Earlier rows then count
* lower than their positions, but nothing reads their output, and every row's K and V
* still store at its own position's slot. */
adv_groups(a, i, k, base, n, last + 1);
return;
}
case ADV_ROUND: {
@@ -194,13 +300,76 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
return;
}
case ADV_BTAKE:
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. */
/* Row i is the query pass's i-th block, which is the i-th drafting sequence. A tree
* drafter's parents come with the tokens, at the same pitch. */
for (int32_t j = 0; j < a.round; ++j)
S.tok[1 + j] = a.src[(int64_t)i * a.src_pitch + j];
if (a.par) {
for (int32_t j = 0; j < a.round; ++j) S.par[j] = a.par[(int64_t)i * a.src_pitch + j];
S.ntree = a.round;
} else {
S.ntree = 0;
}
return;
default:
return;
}
}
/* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at
* base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its
* child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads:
* a destination base + t + 1 is either the node's own place or a place a node already moved out
* of. Each caller keeps one chunk set across every t, so its reads and writes stay in order. */
RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, int c0, int cstep) {
/* Only a row that sampled in this step: ADV_ACCEPT just wrote its slot. Any other row's slot
* may hold a path from an earlier request that used the same slot. */
const int32_t* rows = adv_i32(a, a.row_off);
if (rows[2 * a.row_pitch + i] < 0) return;
const StepSlot& S = a.st[adv_i32(a, a.sid_off)[i]];
const int32_t np = S.npath < S.acc ? S.npath : S.acc;
if (np <= 0) return;
const AdvPool& P = a.pool[p];
if (!P.base || l >= P.n_layers || h >= P.n_head) return;
const AdvGroup& e = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off)[P.grp];
if (!e.paged) return;
const int32_t base = S.head - S.acc;
const int32_t bs = e.block_size;
char* lay = P.base + (int64_t)l * P.layer_stride;
const int32_t chunks = P.row_bytes / 16;
for (int32_t t = 0; t < np; ++t) {
const int32_t src = base + S.path[t], dst = base + t + 1;
if (src == dst) continue;
const int32_t ss = adv_slot(a, e, i, src), ds = adv_slot(a, e, i, dst);
if (ss < 0 || ds < 0) continue;
const uint32_t* from = reinterpret_cast<const uint32_t*>(
lay + (((int64_t)(ss / bs) * P.n_head + h) * bs + ss % bs) * P.row_bytes);
uint32_t* to = reinterpret_cast<uint32_t*>(
lay + (((int64_t)(ds / bs) * P.n_head + h) * bs + ds % bs) * P.row_bytes);
for (int32_t c = c0; c < chunks; c += cstep) {
const uint32_t v0 = from[4 * c], v1 = from[4 * c + 1], v2 = from[4 * c + 2],
v3 = from[4 * c + 3];
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
}
}
}
/* The (pool, layer, head) of ADV_COMPACT's work item `w`, counting every pool's layers x heads in
* order; false past the last. */
RAD_ADV_FN bool adv_compact_item(const AdvanceArgs& a, int w, int* p, int* l, int* h) {
for (int q = 0; q < a.n_pool; ++q) {
const int n = a.pool[q].n_layers * a.pool[q].n_head;
if (w < n) { *p = q; *l = w / a.pool[q].n_head; *h = w % a.pool[q].n_head; return true; }
w -= n;
}
return false;
}
RAD_ADV_FN int adv_compact_items(const AdvanceArgs& a) {
int n = 0;
for (int q = 0; q < a.n_pool; ++q) n += a.pool[q].n_layers * a.pool[q].n_head;
return n;
}
} /* namespace rad */
+112 -18
View File
@@ -4,6 +4,7 @@
#include "mm/processor.h"
#include "derive.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include <algorithm>
#include <cassert>
@@ -12,6 +13,13 @@
namespace rad {
/* Steps of the following prompt a prefill batch carries for the PLE read-ahead queue
* (RadBatch::n_ahead), whose rows the arch's reader thread prefetches off the step path. Two: the
* reader needs to run one chunk ahead of the gather, and libavx hands it at most a quarter of its
* row cache (avx_ngram.cpp, kAheadRows), two chunks of 4096 tokens at 16 rows each. Keep in step
* with rad_block_ple.h's kAheadChunks, which clamps to the buffer it declared. */
static constexpr int64_t k_ahead_chunks = 2;
/* Alignment of each staging array carved from a set's slab. One slab per set means a couple of
* allocations at init instead of two dozen, with every array sharing one mapping. */
static const int64_t k_carve_align = 256;
@@ -97,9 +105,8 @@ void BatchBuilder::carve(Set& s, char* h) {
*ph = ::rad::carve<int32_t>(h, oh, n);
*pd = ::rad::carve<int32_t>(d, od, n);
};
/* Twice the step: its own tokens, then up to a step of the following prompt
* (RadBatch::n_ahead). */
pair(&s.h_tok, &s.d_tok, 2 * T);
/* The step's tokens, then k_ahead_chunks steps of the following prompt (RadBatch::n_ahead). */
pair(&s.h_tok, &s.d_tok, (1 + k_ahead_chunks) * T);
pair(&s.h_pos, &s.d_pos, T);
pair(&s.h_parent, &s.d_parent, T);
pair(&s.h_cu, &s.d_cu, S + 1);
@@ -131,6 +138,9 @@ void BatchBuilder::carve(Set& s, char* h) {
/* Each row's adapter slot, carved only when the engine serves adapters, so an engine without
* them lays the slab out as if the array did not exist. */
pair(&s.h_lora, &s.d_lora, lora_on_ ? T : 0);
/* Each sequence's words for the plugin, carved only when the program declared a bound. */
pair(&s.h_pw, &s.d_pw, pw_cap_ ? S * pw_cap_ : 0);
pair(&s.h_pwcu, &s.d_pwcu, pw_cap_ ? S + 1 : 0);
/* Host-only (derived metadata is copied into the planned arena), but carved on both sides to
* keep device offsets equal to host offsets. */
{
@@ -233,7 +243,11 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
for (Out& o : out_) {
o.kv.assign(ranks_.size(), std::vector<RadKVGroupBatch>(s.groups.size()));
o.stream.assign(ranks_.size(), std::vector<RadKVStream>(s.groups.size()));
o.batch.assign(ranks_.size(), RadBatch{});
o.seqs.clear();
o.seqs.reserve((size_t)max_seqs_); /* a build fills it without allocating */
o.has_seqs = false;
}
pitch_.assign(s.groups.size(), 1);
bt_mirror_.assign(s.groups.size(), BtMirror{});
@@ -467,6 +481,7 @@ int BatchBuilder::layout(Program& prog, const Config& cfg) {
mm_on_ = prog.encoder.modalities != 0 || prog.audio_encoder.modalities != 0;
lora_on_ = cfg.lora.enabled();
pw_cap_ = prog.plugin_words;
return RAD_OK;
}
@@ -821,6 +836,8 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
a.tlen_off = (const char*)s.d_tlen - d0;
}
/* Each rank's own view of the group's ring and mirror (kvstream_step_view). */
const RadKVStream* sv = kv.stream_view((int32_t)gi);
for (size_t r = 0; r < ranks_.size(); ++r) {
void* base = s.dev[r];
RadKVGroupBatch& b = o.kv[r][gi];
@@ -833,6 +850,10 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
b.state_index_pitch = g.sidx_pitch;
b.block_size = L.block_size;
b.max_blocks = pitch;
b.stream = kvstream_step_view(&o.stream[r][gi],
ranks_[r].kv_streams ? ranks_[r].kv_streams[gi] : sv,
ranks_[r].kv_streams != nullptr,
ranks_[0].kv_base, ranks_[r].kv_base);
/* The group's arrays are uploaded with the rest of the slab in build(). */
}
@@ -850,14 +871,6 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(long long)max_seqs_, (long long)max_tok_);
return nullptr;
}
if (plan.spec_is_tree) {
/* spec_parent is in the ABI and allocated, but no drafter emits a tree, so tree parents
* and positions are not written. Filling in the linear-chain answer would verify a tree
* against the wrong causal mask. */
RAD_ERR("tree-layout speculation was requested but is not implemented in this build");
return nullptr;
}
Set& s = set_;
const int64_t n_seq = (int64_t)plan.e.size();
@@ -905,6 +918,9 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
RAD_TRY_NULL(reserve(need, &off));
carve(s, ring_.host + off);
Out& o = out_[out_next_];
o.has_seqs = true;
o.seqs.clear();
for (const StepEntry& e : plan.e) o.seqs.push_back(e.seq);
const int64_t n_tok = plan.n_tok;
@@ -919,6 +935,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
int64_t n_mm = 0;
bool lora_rows = false;
int32_t cvec_rows = 0;
int64_t n_pw = 0;
if (pw_cap_) s.h_pwcu[0] = 0;
s.h_cu[0] = 0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
@@ -945,6 +963,29 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
s.h_tok[k + j] = token_at(e, (int64_t)e.ctx_len + j + shift);
s.h_pos[k + j] = e.ctx_len + j;
}
/* A tree verify (RadBatch::spec_parent): every verify block of a tree step is staged as
* a tree, a chain proposal (prompt lookup) as the tree whose node j hangs off j - 1, so
* the card's acceptance and the host's agree on every row. Node j stores its K and V at
* its row's position (the slots below are unchanged) and rotates at the anchor + its
* depth. A parent is named by its row within the sequence's rows (from cu_seqlens), the
* index an attention kernel has. A card row is restaged by ADV_TRUNK from its StepSlot. */
if (plan.spec_is_tree) {
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_parent[k + j] = -2;
if (e.produces_token && !e.is_prefill && e.n_spec > 0 &&
e.n_spec < e.n_tokens && e.n_spec <= RAD_SCHED_MAX_SPEC) {
const int32_t a0 = e.n_tokens - 1 - e.n_spec; /* the anchor's row */
int32_t dep[1 + RAD_SCHED_MAX_SPEC];
dep[0] = 0;
s.h_parent[k + a0] = -1;
for (int32_t j = 1; j <= e.n_spec; ++j) {
int32_t p = e.draft_parent ? e.draft_parent[j - 1] : j - 1;
if (p < 0 || p >= j) p = j - 1;
dep[j] = dep[p] + 1;
s.h_parent[k + a0 + j] = a0 + p;
s.h_pos[k + a0 + j] = e.ctx_len + a0 + dep[j];
}
}
}
/* Every row of a sequence runs with its request's adapter (RadBatch::lora_slot), fixed at
* admission; a placeholder row with no request is a base row. */
if (lora_on_) {
@@ -961,7 +1002,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
(e.req && e.req->media && !e.req->media->rope.empty()) ? &e.req->media->rope : nullptr;
for (int32_t j = 0; j < e.n_tokens; ++j) {
int32_t v[3];
const int64_t p = (int64_t)e.ctx_len + j;
/* h_pos, not ctx_len + j: a tree verify's rows rotate at their depth. */
const int64_t p = (int64_t)s.h_pos[k + j];
if (rl) rl->at(p, v);
else v[0] = v[1] = v[2] = (int32_t)p;
s.h_rope[k + j] = v[0];
@@ -995,9 +1037,25 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
const int32_t nr = e.hidden_n > 0 ? e.hidden_n : e.n_tokens;
for (int32_t j = 0; j < nr; ++j) s.h_out[n_out++] = e.hidden_row + j;
} else if (e.produces_token) {
/* The request's words for the plugin ride the trunk step that samples its prompt's
* first token (RadBatch::plugin_words); word 0 is that row's index in `out_ids`. */
if (pw_cap_ && e.is_prefill && plan.draft_pass == 0 && e.req &&
!e.req->plugin_words.empty()) {
const std::vector<int32_t>& w = e.req->plugin_words;
if ((int64_t)w.size() > pw_cap_) {
RAD_ERR("step batch: sequence %llu carries %zu words for the plugin, past the "
"%lld it declared", (unsigned long long)e.seq, w.size(),
(long long)pw_cap_);
return nullptr;
}
std::memcpy(s.h_pw + n_pw, w.data(), w.size() * sizeof(int32_t));
s.h_pw[n_pw] = (int32_t)n_out;
n_pw += (int64_t)w.size();
}
const int32_t first = (int32_t)(k + e.n_tokens) - 1 - e.n_spec;
for (int32_t j = 0; j <= e.n_spec; ++j) s.h_out[n_out++] = first + j;
}
if (pw_cap_) s.h_pwcu[i + 1] = (int32_t)n_pw;
if (e.draft_out) s.h_dout[n_dout++] = (int32_t)(k + e.n_tokens - 1);
/* RADIANCE_DFLASH_TRACE logs each drafter pass's kind, positions and token ids. A wrong
* anchor, mask id or position base shows only as near-zero acceptance with correct
@@ -1044,17 +1102,18 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
}
}
/* Up to a step of the last sequence's following tokens, after this step's own
* (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by
* the tokens the request has; like token_at, a re-prefill after preemption continues into its
* own output. */
/* Up to k_ahead_chunks steps of the last sequence's following tokens, after this step's own
* (RadBatch::n_ahead). Only on a trunk pass whose last entry is a prefill chunk, bounded by the
* tokens the request has; like token_at, a re-prefill after preemption continues into its own
* output. The arch clamps to the rows it declared. */
int64_t n_ahead = 0;
if (n_seq > 0 && plan.draft_pass == 0 && plan.tok_shift == 0) {
const StepEntry& e = plan.e[(size_t)(n_seq - 1)];
if (e.req && e.is_prefill) {
const int64_t next = (int64_t)e.ctx_len + e.n_tokens;
const int64_t have = (int64_t)e.req->prompt.size() + (int64_t)e.req->output.size();
n_ahead = std::min<int64_t>(std::max<int64_t>(have - next, 0), max_tok_);
n_ahead = std::min<int64_t>(std::max<int64_t>(have - next, 0),
k_ahead_chunks * max_tok_);
for (int64_t j = 0; j < n_ahead; ++j) s.h_tok[n_tok + j] = token_at(e, next + j);
}
}
@@ -1120,6 +1179,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
mm_ev_live_ = true;
}
/* A scored step (RadBatch::score_only): every sampled row is a scored request's first row, on
* one rank, in a program that told the core where its hidden rows and head table are. Each
* such entry gives one row, so the step is scored only when they account for all n_out: a
* mid-prefill chunk's KLD rows or an entry's own hidden rows still need the lm_head. */
int32_t score_only = 0;
if (n_out > 0 && n_dout == 0 && !plan.draft_pass && ranks_.size() == 1 &&
prog_->score_hidden != RAD_NULL_HANDLE && prog_->score_table != RAD_NULL_HANDLE) {
int64_t scored = 0;
for (const StepEntry& e : plan.e)
if (e.produces_token && e.hidden_row < 0 && e.req && e.req->token_scores &&
e.req->output.empty() && e.n_spec == 0)
++scored;
score_only = scored == n_out;
}
/* ---------------------------------------------------------- the batch, one per rank */
for (size_t r = 0; r < ranks_.size(); ++r) {
void* const base = s.dev[r];
@@ -1135,6 +1209,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.seq_ids = on_rank(base, b0, s.d_sid);
B.n_out = n_out;
B.out_ids = n_out ? on_rank(base, b0, s.d_out) : nullptr;
B.score_only = score_only;
B.n_draft_out = n_dout;
B.draft_out_ids = n_dout ? on_rank(base, b0, s.d_dout) : nullptr;
B.q_lens = on_rank(base, b0, s.d_q);
@@ -1153,7 +1228,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
* without drafts may follow one that had drafts, and the linear kernels need its accepted
* count instead of their absent-operand default of 1. */
B.num_accepted = cfg_.n_spec > 0 ? on_rank(base, b0, s.d_acc) : nullptr;
B.spec_parent = nullptr; /* a linear chain; the tree case is refused above */
/* Staged above on a tree step: each row's parent row, -2 for an ordinary causal one. */
B.spec_parent = plan.spec_is_tree ? on_rank(base, b0, s.d_parent) : nullptr;
B.rope_pos = mm_on_ ? on_rank(base, b0, s.d_rope) : nullptr;
B.rope_mixed = rope_mixed;
B.n_mm_rows = n_mm;
@@ -1163,6 +1239,11 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
* runs the same pass as an engine serving no adapters. */
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
B.control_vector = cvec_rows;
B.n_plugin_words = n_pw;
B.plugin_words = n_pw ? on_rank(base, b0, s.d_pw) : nullptr;
B.plugin_cu = n_pw ? on_rank(base, b0, s.d_pwcu) : nullptr;
B.plugin_words_h = n_pw ? s.h_pw : nullptr;
B.plugin_cu_h = n_pw ? s.h_pwcu : nullptr;
B.enc = 0;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
@@ -1192,12 +1273,21 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
++ring_.live;
last_n_seq_ = n_seq;
last_n_tok_ = n_tok;
last_tree_ = plan.spec_is_tree;
ring_.head = off + used;
out_last_ = out_next_;
out_next_ = (out_next_ + 1) % kOut;
return &o.batch[0];
}
const std::vector<uint64_t>* BatchBuilder::step_seqs(const RadBatch* b) const {
if (!b) return nullptr;
for (const Out& o : out_)
for (const RadBatch& rb : o.batch)
if (&rb == b) return o.has_seqs ? &o.seqs : nullptr;
return nullptr;
}
const RadBatch* BatchBuilder::batch_for(int rank) const {
if (out_last_ < 0) return nullptr;
const Out& o = out_[out_last_];
@@ -1223,6 +1313,7 @@ AdvanceArgs BatchBuilder::advance_args(int rank) const {
a.cu_off = off(s.d_cu);
a.q_off = off(s.d_q);
a.row_off = off(s.d_rows);
a.parent_off = last_tree_ ? off(s.d_parent) : -1;
a.row_pitch = (int32_t)max_seqs_;
a.grp_off = off(s.d_grp);
if (mm_on_) {
@@ -1298,6 +1389,9 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
}
}
Out& o = out_[out_next_];
/* An encoder pass runs no sequence's KV. */
o.has_seqs = false;
o.seqs.clear();
for (size_t r = 0; r < ranks_.size(); ++r) {
RadBatch& B = o.batch[r];
B = RadBatch{};
+28
View File
@@ -41,6 +41,10 @@ struct StepEntry {
int32_t ckpt_restore = -1;
const int32_t* draft = nullptr; /* the drafter's proposal, appended after the committed tail */
int32_t n_draft = 0;
/* A tree drafter's proposal (rad_drafter_tree): draft_parent[j] is the parent of draft[j] as a
* node index (0 the anchor, j + 1 draft[j]). Null for a chain. Read only on a tree step
* (StepPlan::spec_is_tree), where a null one is staged as the chain. */
const int32_t* draft_parent = nullptr;
/* First logits row, written into `out_ids`, that this entry reads, or -1 for the default
* rule. The MTP history pass uses it to gather the 1 + n_spec trunk rows of a verifying
* sequence; the DFlash2 query pass uses it to name the mask rows of its own block. Which
@@ -105,6 +109,13 @@ public:
int device = 0;
RadStream stream = nullptr;
Program* prog = nullptr;
/* This rank's KV pool base, for rebasing rank 0's map pointers when no per-rank views are
* given (kvstream_step_view). */
void* kv_base = nullptr;
/* Per group, this rank's stream view or null, owned by the engine. Each rank's view names its
* own maps and its own mirror. Pointers rather than the manager, so a test that drives the
* builder without a device does not link the manager. */
const RadKVStream* const* kv_streams = nullptr;
};
/* `prog` is non-const because derived buffers are written into its arena, whose pointer lands
@@ -129,6 +140,11 @@ public:
* round, slot state and inputs (advance.h). */
AdvanceArgs advance_args(int rank) const;
/* The sequences of `b`, a batch build() returned that is still valid (any rank's), in row
* order; null for another batch (an encoder pass). What a streamed group's prefill stage
* copies is read from their tables (kvstream/stage.h, "Volume"). */
const std::vector<uint64_t>* step_seqs(const RadBatch* b) const;
/* Longest sequence a batch can describe, in tokens, as sized into the block-table rows at
* init. A position at or past it cannot be addressed. */
int64_t max_ctx() const { return max_ctx_; }
@@ -213,6 +229,10 @@ private:
/* [n_tok] each row's runtime LoRA adapter slot (RadBatch::lora_slot): carved only when the
* engine serves adapters, empty otherwise. */
int32_t *h_lora = nullptr, *d_lora = nullptr;
/* [max_seqs * plugin_words] and [max_seqs + 1]: each sequence's words for the plugin
* (RadBatch::plugin_words), carved only when the program declared a bound. */
int32_t *h_pw = nullptr, *d_pw = nullptr;
int32_t *h_pwcu = nullptr, *d_pwcu = nullptr;
/* [n_kv_groups][max_seqs]: every conv group's state slot per sequence (see init()). */
int32_t* h_convslot = nullptr;
@@ -242,7 +262,12 @@ private:
static constexpr int kOut = RAD_SCHED_MAX_SPEC + 4;
struct Out {
std::vector<std::vector<RadKVGroupBatch>> kv;
/* Per rank and group, the RadKVStream a batch names: each rank's own copy, outside the slab. */
std::vector<std::vector<RadKVStream>> stream;
std::vector<RadBatch> batch;
/* The build's sequences in row order (step_seqs); none for an encoder pass. */
std::vector<uint64_t> seqs;
bool has_seqs = false;
};
struct Derived {
@@ -306,6 +331,7 @@ private:
int64_t pay_words_ = 0; /* payload build_groups wrote, in int32 words */
void forget_tables();
int64_t last_n_seq_ = 0;
bool last_tree_ = false; /* the last build staged spec_parent (advance_args' parent_off) */
int64_t derived_bytes_ = 0;
std::vector<Derived> derived_;
@@ -320,6 +346,8 @@ private:
bool mm_on_ = false;
/* The engine serves runtime LoRA adapters (Config::lora): the batch carries each row's slot. */
bool lora_on_ = false;
/* Program::plugin_words: the words a sequence may carry, 0 for none. */
int64_t pw_cap_ = 0;
int64_t n_embd_ = 0;
std::vector<void*> mm_dev_;
uint16_t* mm_host_ = nullptr;
+80 -22
View File
@@ -38,6 +38,30 @@ int64_t prefill_shared_tok(const Config& cfg) {
return std::max(std::min(cfg.max_tok, I), cfg.max_tok - (cfg.prefill_span - 1) * I);
}
/* What a prefix hit restores beside the cached blocks: linear state, or a trunk's sliding window.
* Only the trunk's window makes a model take window snapshots; a block drafter's rides in them
* where they exist (KVManager::set_drafter_window_snapshot) and is recomputed by draft refill
* where they do not. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt length, which no
* slot could describe, so it is sized for the context plus a ring and is never checkpointed. */
static void restored_state(const Program& prog, bool* linear, bool* window) {
*linear = *window = false;
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind != RAD_KV_FULL && kg.decl.kind != RAD_KV_WINDOW &&
kg.decl.kind != RAD_KV_RING)
*linear = true;
else if (kg.decl.kind == RAD_KV_WINDOW && kg.block_size > 0 && !kg.layers.empty() &&
!kg.drafter)
*window = true;
}
}
bool window_snapshots(const Program& prog, const Config& cfg) {
bool linear = false, window = false;
restored_state(prog, &linear, &window);
return !linear && window && cfg.prefix_cache && cfg.checkpoint_interval > 0;
}
int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry* out) {
if (!out) return RAD_E_INVAL;
ChunkGeometry g;
@@ -46,22 +70,12 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
/* lcm across every paged group. libr4d uses 16 for all of them, but a sliding-window group
* served by a different kernel may differ (§7.2). */
bool has_linear = false, has_window = false;
restored_state(prog, &has_linear, &has_window);
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) {
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());
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
* length, which no slot could describe, so it is sized for the context plus a ring
* and is never checkpointed. */
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
has_window = true;
}
} else {
has_linear = true;
if ((kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) && 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());
}
}
@@ -126,14 +140,15 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
* retention.
*
* Without linear state there are no checkpoints, except for a trunk window under a prefix
* cache, which snapshots the window behind a prompt's tail (window_ckpt) without splitting
* chunks. */
* cache, which snapshots the window at interval boundaries and the prompt's tail
* (window_ckpt). */
if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0)
g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum);
else
g.checkpoint_interval = 0;
g.window_ckpt = !has_linear && g.checkpoint_interval > 0;
/* A window snapshot splits no chunk (plan_chunk), so there is no interval grid to span. */
g.window_periodic = g.window_ckpt && cfg.checkpoint_policy != "tip-only";
/* Window checkpoints do not support skipping snapshots inside a prefill span. */
g.span = (g.checkpoint_interval > 0 && !g.window_ckpt && cfg.prefill_span > 1)
? cfg.prefill_span : 1;
g.shared_tok = prefill_shared_tok(cfg);
@@ -142,20 +157,56 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
* checkpoints land wherever a step ends (§7.3). */
g.min_max_tok = g.quantum;
*out = g;
if (cfg.max_tok < g.min_max_tok) {
*out = g;
RAD_ERR("--max-num-batched-tokens is %lld but this model's chunk geometry needs at least "
"%lld, so a chunk can end on a linear-state boundary: %s",
(long long)cfg.max_tok, (long long)g.min_max_tok, g.why.c_str());
return RAD_E_INVAL;
}
/* The resume grid (--prefix-resume exact): where an idle server's prefill chunks start. A
* prefill alone in its step takes the budget, rounded down to the quantum. Where chunks split
* at the interval (linear state, or periodic window snapshots) it stops at every interval
* boundary it reaches, and a span carries h intervals from the second one on. An interval past
* the budget must be a multiple of the budget's chunk, or the chunk after a checkpoint would
* start off the cold run's grid; it is rounded up, as the quantum rounds it, since a longer
* interval costs only retention. */
const int64_t I0 = g.checkpoint_interval;
const bool splits = I0 > 0 && (!g.window_ckpt || g.window_periodic);
const int64_t budget_chunk = cfg.max_tok / g.quantum * g.quantum;
g.exact = cfg.prefix_exact && cfg.prefix_cache;
if (g.exact && splits && I0 > budget_chunk && I0 % budget_chunk != 0) {
g.checkpoint_interval = align_up(I0, budget_chunk);
RAD_WARN("--checkpoint-interval %lld resolves to %lld: --prefix-resume exact needs it a "
"multiple of the %lld-token prefill chunk (--max-num-batched-tokens %lld) so "
"every checkpoint is where a cold prefill's chunk ends; give a multiple of %lld, "
"or --prefix-resume nearest to keep %lld", (long long)cfg.checkpoint_interval,
(long long)g.checkpoint_interval, (long long)budget_chunk, (long long)cfg.max_tok,
(long long)budget_chunk, (long long)I0);
}
if (g.exact) {
const int64_t I = g.checkpoint_interval;
if (splits && I <= budget_chunk) {
const int64_t h = g.span > 1 ? std::max<int64_t>(1, std::min(g.span, cfg.max_tok / I))
: 1;
g.grid = h * I;
g.grid_origin = h > 1 ? I : 0;
} else {
g.grid = budget_chunk;
g.grid_origin = 0;
}
}
*out = g;
/* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so
* when the interval is below --max-num-batched-tokens, raising the budget does not change the
* chunk; the log line makes that visible. A window snapshot splits nothing. */
* chunk; the log line makes that visible. tip-only window snapshots do not
* split at the interval, so their chunk is bounded by the token budget. */
const int64_t span_tok = g.checkpoint_interval * g.span;
const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && span_tok < cfg.max_tok)
const bool periodic = !g.window_ckpt || g.window_periodic;
const int64_t eff = (g.checkpoint_interval > 0 && periodic && span_tok < cfg.max_tok)
? span_tok : cfg.max_tok;
RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint "
"interval %lld, max_tok %lld -> prefill chunks of at most %lld%s",
@@ -164,6 +215,13 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
eff >= cfg.max_tok ? ""
: g.span > 1 ? " (the checkpoint interval times the span, not the budget)"
: " (the checkpoint interval, not the budget)");
if (g.exact)
RAD_INFO("prefix resume: exact -- a hit resumes only where an idle server's cold prefill "
"of the same prompt starts a chunk (every %lld tokens%s) and a prompt's tail "
"snapshot is taken where its last chunk starts, so the hit recomputes the cold "
"run's own chunks and answers bit-identically; a turn re-prefills up to one chunk "
"more than --prefix-resume nearest", (long long)g.grid,
g.grid_origin > 0 ? fmt(" from %lld", (long long)g.grid_origin).c_str() : "");
if (cfg.prefill_span > 1) {
/* What the span does here, said once: the intervals the budget holds can be fewer than
* the flag asks for, and a model without an interval grid spans nothing. */
+34 -4
View File
@@ -51,13 +51,38 @@ struct ChunkGeometry {
/* Every contributor by name, for the startup line and the refusal. */
std::string why;
/* No linear state but a sliding window: the checkpoint snapshots only the window behind a
* prompt's tail (KVManager::has_window_snapshot). Chunks are not split at the interval, since
* a mid-prompt window snapshot gains nothing; the interval is only the shortest prompt worth
* a snapshot. */
/* No linear state but a sliding window: checkpoints snapshot the window behind an
* interval boundary or the prompt's tail (KVManager::has_window_snapshot). Intermediate
* snapshots let an edited prompt resume below its divergence instead of from zero.
* tip-only skips interval snapshots and keeps the original tail-only chunking. */
bool window_ckpt = false;
/* Window checkpoints at interval boundaries too, not only at the tail: every policy but
* tip-only, which keeps the tail alone and so splits no chunk at the interval. */
bool window_periodic = false;
/* --prefix-resume exact (Config::prefix_exact): a prefix hit resumes only where a cold prefill
* of the same prompt starts a chunk, so the tokens it recomputes are cut into the cold run's
* chunks. A kernel may round a row differently at another chunk length (a split-K count chosen
* from M, a small-M path); in the same chunks, on an idle server, the hit's output is the cold
* run's bit for bit. The grid is where an idle server's prefill chunks start: 0, then
* grid_origin + k * grid. Where chunks split at the interval and it fits the budget, `grid` is
* the interval times the span the budget holds, from grid_origin = the interval when that span
* is over 1. Otherwise `grid` is --max-num-batched-tokens rounded down to the quantum, and the
* interval is rounded up to a multiple of it. Zero when not exact. */
bool exact = false;
int64_t grid = 0;
int64_t grid_origin = 0;
bool checkpoints() const { return checkpoint_interval > 0; }
/* The deepest grid position at or below `pos`; `pos` itself when not exact. */
int64_t grid_floor(int64_t pos) const {
if (pos <= 0) return 0;
if (!exact || grid <= 0) return pos;
if (pos < grid_origin) return 0;
return grid_origin + (pos - grid_origin) / grid * grid;
}
bool on_grid(int64_t pos) const { return grid_floor(pos) == pos; }
};
/* The budget of a step a span does not take (ChunkGeometry::shared_tok), from the configuration
@@ -66,6 +91,11 @@ struct ChunkGeometry {
* (RadBuildCtx::max_mixed_tok) and the scheduler plans by it, so the two agree. */
int64_t prefill_shared_tok(const Config& cfg);
/* ChunkGeometry::window_ckpt from the program and the configuration alone, without resolving or
* reporting the geometry: a trunk's sliding window, no linear state, a prefix cache and an
* interval. Bring-up asks it before the geometry is resolved (Engine::drafter_window_snap). */
bool window_snapshots(const Program& prog, const Config& cfg);
/* Resolve the geometry from the declared program and the operator's budgets.
*
* Returns RAD_E_INVAL when cfg.max_tok is too small (the required number is in
+145
View File
@@ -0,0 +1,145 @@
/* lookup.cpp -- the prompt-lookup verify gate. See lookup.h. */
#include "lookup.h"
#include <cmath>
namespace rad {
void LookupGate::configure(int max_depth) {
max_depth_ = max_depth < 0 ? 0 : (max_depth > RAD_SCHED_MAX_SPEC ? RAD_SCHED_MAX_SPEC : max_depth);
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
for (int k = 0; k < kCostKeys; ++k) { cost_r_[k] = 0.0; cost_ms_[k] = 0.0; cost_n_[k] = 0; }
proposed_ = held_ = held_drafts_ = held_hits_ = 0;
}
/* ------------------------------------------------------------------ one sequence */
void LookupGate::start(LookupSeq& q) const {
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) {
q.s[0][j] = (float)kPriorShort;
q.s[1][j] = (float)kPriorLong;
}
q.n[0] = q.n[1] = 0;
q.pend_pos = -1;
q.pend_len = q.pend_done = q.pend_cls = 0;
q.pend_held = q.last_taken = false;
q.proposed = q.held = q.held_drafts = q.held_hits = 0;
q.started = true;
}
double LookupGate::expect(LookupSeq& q, int cls, int k) const {
if (!q.started) start(q);
if (cls < 0 || cls > 1) cls = 0;
if (k > RAD_SCHED_MAX_SPEC) k = RAD_SCHED_MAX_SPEC;
double e = 0.0;
for (int j = 0; j < k; ++j) e += (double)q.s[cls][j];
return e;
}
void LookupGate::offer(LookupSeq& q, int64_t pos, const int32_t* prop, int n, int match) const {
if (!q.started) start(q);
if (n <= 0 || !prop) return;
++q.proposed;
++proposed_;
q.last_taken = false;
if (q.pend_pos >= 0) return; /* one at a time: it resolves within n tokens, usually one */
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
q.pend_pos = pos;
q.pend_len = n;
q.pend_done = 0;
q.pend_cls = class_of(match);
q.pend_held = false;
q.last_taken = true;
for (int j = 0; j < n; ++j) q.pend[j] = prop[j];
}
void LookupGate::held(LookupSeq& q, int n) const {
if (n <= 0) return;
++q.held;
q.held_drafts += n;
++held_;
held_drafts_ += n;
if (q.last_taken) q.pend_held = true;
}
void LookupGate::fold(LookupSeq& q, int cls, int len, int hits) const {
/* Position j came true iff j < hits: the survival estimate S_j sees every evaluated
* proposal, not only those that reached j. */
const double w = std::fmax(alpha_, 1.0 / ((double)q.n[cls] + kPriorWeight + 1.0));
for (int j = 0; j < len; ++j) {
const double x = j < hits ? 1.0 : 0.0;
q.s[cls][j] = (float)((double)q.s[cls][j] + w * (x - (double)q.s[cls][j]));
}
if (q.n[cls] < UINT16_MAX) ++q.n[cls];
}
void LookupGate::advance(LookupSeq& q, const TokenSeq& seq) const {
if (!q.started || q.pend_pos < 0) return;
const int64_t len = seq.size();
while (q.pend_done < q.pend_len && q.pend_pos + q.pend_done < len) {
if (seq[q.pend_pos + q.pend_done] != q.pend[q.pend_done]) break;
++q.pend_done;
}
const bool missed = q.pend_done < q.pend_len && q.pend_pos + q.pend_done < len;
if (!missed && q.pend_done < q.pend_len) return; /* agrees so far; more tokens to come */
fold(q, q.pend_cls, q.pend_len, q.pend_done);
if (q.pend_held) {
q.held_hits += q.pend_done;
held_hits_ += q.pend_done;
}
q.pend_pos = -1;
}
/* ------------------------------------------------------------------ the step */
bool LookupGate::pays(double gain, int k, int64_t rows, double tokens) const {
if (k <= 0 || !(gain > 0.0)) return false;
if (rows < 1) rows = 1;
if (tokens < 1.0) tokens = 1.0;
const double t0 = step_cost(rows);
const double t1 = step_cost(rows + k);
/* (tokens + gain) / t1 > tokens / t0 */
return gain * t0 > tokens * (t1 - t0);
}
int LookupGate::cost_key(int64_t rows) {
if (rows < 1) rows = 1;
if (rows <= kCostExact) return (int)(rows - 1);
const int64_t k = kCostExact + (rows - kCostExact - 1) / kCostBand;
return (int)(k < kCostKeys ? k : kCostKeys - 1);
}
void LookupGate::step_time(int64_t rows, double ms) {
if (rows < 1 || !(ms > 0.0) || !std::isfinite(ms)) return;
const int k = cost_key(rows);
double& m = cost_ms_[k];
double& r = cost_r_[k];
int64_t& n = cost_n_[k];
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
m = n ? m + w * (ms - m) : ms;
r = n ? r + w * ((double)rows - r) : (double)rows;
++n;
}
int64_t LookupGate::cost_samples(int64_t rows) const { return cost_n_[cost_key(rows)]; }
double LookupGate::step_cost(int64_t rows) const {
if (rows < 1) rows = 1;
const double R = (double)rows;
/* The timed keys either side, by the mean rows of their samples (monotone in the key). */
int lo = -1, hi = -1;
for (int k = 0; k < kCostKeys; ++k) {
if (cost_n_[k] <= 0) continue;
if (cost_r_[k] <= R) lo = k;
if (cost_r_[k] >= R && hi < 0) hi = k;
}
if (lo >= 0 && hi >= 0) {
const double r0 = cost_r_[lo], r1 = cost_r_[hi];
if (lo == hi || r1 <= r0) return cost_ms_[lo];
return cost_ms_[lo] + (cost_ms_[hi] - cost_ms_[lo]) * (R - r0) / (r1 - r0);
}
if (lo >= 0) return cost_ms_[lo] * prior(R) / prior(cost_r_[lo]);
if (hi >= 0) return cost_ms_[hi] * prior(R) / prior(cost_r_[hi]);
return prior(R);
}
} /* namespace rad */
+152
View File
@@ -0,0 +1,152 @@
/* lookup.h -- whether a prompt-lookup proposal is worth its verify rows.
*
* A verify row is not free. On a MoE every row reads its own routed experts, so verifying five
* drafts on one sequence costs a few plain steps (DeepSeek-V4.1 at TP4: 32 ms against 13.5 ms),
* and prompt lookup proposes on novel text too: any bigram it has seen before is a pattern. On
* prose those proposals are wrong four times in five and the verifies make decoding slower than
* not speculating; on code edits and quoted text they are right most of the time and it is twice
* as fast. So each proposal is verified only when it is expected to pay:
*
* verify k drafts iff E[accepted] * T(R) > tokens * (T(R + k) - T(R))
*
* where T(R) is the measured wall time of a decode step of R query rows, R the rows the step
* already carries and `tokens` what it already expects to emit. For one sequence that is
* 1 + E[accepted] > T(1 + k) / T(1).
*
* E[accepted] = sum_{j<k} S_j, with S_j the sequence's estimate of P(the proposal's first j + 1
* tokens all come true). The estimate is fed by every proposal, verified or not: a proposal held
* back is compared with the tokens the sequence goes on to emit, and its accepted count is their
* common prefix. That is exactly what a verify would have accepted, at any temperature, because
* a verify accepts a draft iff it equals the token the target emits at that position and the
* target's draw there does not depend on the draft (core/sample/accept.h). So a held sequence
* keeps learning at no cost, and resumes drafting as soon as its text turns repetitive.
*
* Estimates are kept per class of proposal: one whose match runs at least kLongMatch tokens back
* (the sequence is copying a stretch it has seen) and one whose match is shorter (a recurring
* bigram or trigram). They differ by far more than either varies within a reply, and a new
* sequence starts each from its own prior: a long match is drafted at once, a short one waits for
* evidence.
*
* T is measured online over pure decode steps, keyed by rows (StepCost). Before a row count is
* timed, its cost is the nearest timed count's scaled by the prior shape 1 + kRowCost (R - 1),
* which is optimistic on purpose: the first verify it lets through times the real cost.
*
* Only which proposals are verified changes, never what is emitted: output is the same as with
* speculation off.
*/
#pragma once
#include <cstdint>
#include "draft.h"
#include "ngram.h"
namespace rad {
/* One sequence's record: its estimates and the proposal being compared with its text. Kept in the
* scheduler's per-request state; it describes the text, so preemption keeps it and a new request
* starts it over. */
struct LookupSeq {
bool started = false;
float s[2][RAD_SCHED_MAX_SPEC] = {}; /* by class: P(first j + 1 drafts all come true) */
uint16_t n[2] = {}; /* proposals evaluated in each class, saturating */
/* The proposal under evaluation: its first token is the sequence's token `pend_pos`; -1 none.
* `pend_done` of its `pend_len` tokens have been compared, all equal so far. */
int64_t pend_pos = -1;
int32_t pend_len = 0;
int32_t pend_done = 0;
int32_t pend_cls = 0;
bool pend_held = false; /* it was held back rather than verified */
bool last_taken = false; /* the last offer became the pending one */
int32_t pend[RAD_SCHED_MAX_SPEC] = {};
/* For the request's log line. */
int64_t proposed = 0, held = 0, held_drafts = 0, held_hits = 0;
};
class LookupGate {
public:
/* ---------------------------------------------------------- the policy's constants
* Fixed; none is a property of a deployment. The deployment's one property, what a verify
* row costs, is measured (step_time). Chosen on 24 real replies (an essay, a code edit and 22
* varied prompts, DeepSeek-V4.1 greedy, 256 tokens) replayed through the engine's lookup rule
* at per-row costs of 0.06 to 0.6 of a plain step: over the prose replies, 0.999 to 1.014x
* the speed of not speculating (geometric mean) and 0.988x at worst, where verifying every
* proposal gives 0.85 to 1.015x and 0.73x at worst; on the code edit within 2.1% of verifying
* every proposal at the costs where that pays, and 11% ahead of it at 0.6. */
/* A proposal whose match runs this many tokens back is the long class. */
static constexpr int kLongMatch = 8;
/* Where each class starts: P(each draft comes true), the same at every position. A long match
* drafts at once at any row cost under 0.8 of a step; a short one waits until its own record
* says it pays. */
static constexpr double kPriorShort = 0.0;
static constexpr double kPriorLong = 0.8;
/* The prior weighs as much as two proposals: the third evaluated in a class moves its
* estimate by a third. */
static constexpr double kPriorWeight = 2.0;
/* Then a moving average with a half-life of 8 proposals, short enough to follow a reply from
* prose into a quoted block and out again within a few lines. */
static constexpr double kHalfLife = 8.0;
/* The shape an untimed row count is priced on: each query row adds 6% to a step. */
static constexpr double kRowCost = 0.06;
/* Step times: a running mean for the first samples, then a moving average with a half-life of
* 32 steps; once a key has 4 samples one step counts for at most 4x its mean (a step that
* waited on a recording or a host stall says nothing about its row count). As draft.cpp. */
static constexpr double kCostHalfLife = 32.0;
static constexpr double kCostOutlier = 4.0;
static constexpr int64_t kCostClipAfter = 4;
/* Row counts are kept exactly up to 128, then in bands of 32. */
enum { kCostExact = 128, kCostBand = 32, kCostKeys = 160 };
void configure(int max_depth);
int max_depth() const { return max_depth_; }
/* ---------------------------------------------------------- one sequence */
/* The class of a proposal whose match runs `match` tokens back. */
static int class_of(int match) { return match >= kLongMatch ? 1 : 0; }
/* Expected drafts accepted if the first `k` of a class-`cls` proposal are verified. Starts the
* estimate if needed. */
double expect(LookupSeq& q, int cls, int k) const;
/* A proposal of `n` tokens whose first is the sequence's token `pos`: taken for evaluation
* when none is pending. Counted as proposed either way. */
void offer(LookupSeq& q, int64_t pos, const int32_t* prop, int n, int match) const;
/* The proposal offered last was not verified: `n` drafts held back. Counters only. */
void held(LookupSeq& q, int n) const;
/* After a commit: compares the pending proposal with the tokens `seq` now holds, and folds it
* into its class once a token differs or every token has come true. */
void advance(LookupSeq& q, const TokenSeq& seq) const;
/* ---------------------------------------------------------- the step */
/* Whether `k` drafts expected to yield `gain` accepted tokens pay, in a step that so far
* carries `rows` query rows and expects `tokens` tokens. */
bool pays(double gain, int k, int64_t rows, double tokens) const;
/* A pure decode step of `rows` query rows took `ms`, from the end of the step before. */
void step_time(int64_t rows, double ms);
/* The expected wall time of a decode step of `rows` rows: ms once anything is timed, else the
* unitless prior. Only ratios are used. */
double step_cost(int64_t rows) const;
int64_t cost_samples(int64_t rows) const;
/* Across all sequences, for metrics: proposals offered; proposals held back and their drafts;
* and of the held proposals scored (one at a time per sequence), the drafts that came true:
* what verifying them would have accepted. Updated by the per-sequence calls above, which are
* const on the policy, hence mutable. */
int64_t proposed() const { return proposed_; }
int64_t held_count() const { return held_; }
int64_t held_drafts() const { return held_drafts_; }
int64_t held_hits() const { return held_hits_; }
private:
int max_depth_ = 0;
double alpha_ = 0.0;
double cost_r_[kCostKeys] = {}; /* mean rows of the samples in each key */
double cost_ms_[kCostKeys] = {};
int64_t cost_n_[kCostKeys] = {};
mutable int64_t proposed_ = 0, held_ = 0, held_drafts_ = 0, held_hits_ = 0;
static int cost_key(int64_t rows);
static double prior(double rows) { return 1.0 + kRowCost * (rows - 1.0); }
void start(LookupSeq& q) const;
void fold(LookupSeq& q, int cls, int len, int hits) const;
};
} /* namespace rad */
+68 -4
View File
@@ -79,6 +79,19 @@ struct IKVManager {
* instead of deadlocking the engine (spec §17). */
virtual bool can_ever_fit(int64_t n_tokens) const = 0;
/* Whether `seq` can be grown to `n_tokens` without taking blocks from another sequence.
* A sequence the manager does not know is not a refusal: the caller adds it first. */
virtual bool can_grow(uint64_t seq, int64_t n_tokens) const = 0;
/* Return state slots no running sequence holds, and any slot neither free nor held.
* The caller guarantees nothing is running. A slot held by a zeroed or forgotten sequence
* would otherwise keep an overdue preempted prefill waiting forever (spec §17). Returns
* how many slots were put back. A manager with no state leaves this as a no-op. */
virtual int release_idle_states() { return 0; }
/* How many blocks a paged group can still hand out, including those lent to the expert slab
* and recallable on demand. */
virtual int64_t available_blocks(int32_t group) 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;
@@ -94,6 +107,8 @@ struct IKVManager {
/* Blocks held by anything, as opposed to free_blocks (what can be handed out now). On an
* elastic pool they differ by what the cache released (KVManager::held_blocks). */
virtual int64_t held_blocks(int32_t group) const = 0;
/* KVManager::held_top_blocks; a manager that cannot answer says the whole row. */
virtual int64_t held_top_blocks(int32_t group) const { (void)group; return INT64_MAX; }
/* The pool in bytes, the only unit that sums across groups. Asked of the manager because its
* plan knows whether a group counts blocks or states. */
@@ -102,8 +117,20 @@ struct IKVManager {
/* What the carve gave the group; an elastic pool may have released part of it. */
virtual int64_t pool_bytes_carved(int32_t group) const = 0;
/* A streamed group's RadKVStream for the step batch, or null for a resident group; its addresses
* are fixed from bring-up. */
virtual const RadKVStream* stream_view(int32_t group) const { (void)group; return nullptr; }
/* The resolve's cumulative traffic and the rings' depth, for the metrics; zero without
* streaming. */
virtual int64_t stream_misses() const { return 0; }
virtual int64_t stream_bytes_in() const { return 0; }
virtual int64_t stream_resident_blocks() const { return 0; }
/* Tokens one block covers, or 0 for a stateful group. */
virtual int64_t block_tokens(int32_t group) const = 0;
/* A checkpoint slot carries this group's window (KVGroupPlan::win_snap): a prefix hit, which
* resumes from such a slot, restores it whole. */
virtual bool window_snapshot(int32_t group) const { (void)group; return false; }
/* Speculative rejection rollback (spec §10). A verify writes KV for 1 + n_spec positions and
* the sampler accepts a prefix; this shrinks the sequence to `n_tokens` and frees blocks past
@@ -158,10 +185,14 @@ struct IPrefixCache {
/* Longest cached prefix, plus the checkpoint covering the linear state for a prefix of it.
* `blocks_out` receives block ids per cached group, in cached_groups() order, for
* IKVManager::adopt. `cap`, when not null, ends the hit early (HitCap, core/mem/prefix.h). */
* IKVManager::adopt: n_attn_tokens over the group's own block size of them. `cap`, when not
* null, ends the hit early (HitCap, core/mem/prefix.h). */
virtual CacheHit lookup(const Request& r, std::vector<std::vector<int32_t>>* blocks_out,
const HitCap* cap) const = 0;
virtual const std::vector<int32_t>& cached_groups() const = 0;
/* The drafter's refill window (Scheduler::init): retention keeps a snapshot that deep below a
* session's tip, so a refill-capped hit has one to end on (PrefixCache::set_drafter_floor). */
virtual void set_drafter_floor(int64_t) {}
/* Publish what this sequence computed so a later request sharing the prefix can adopt it.
* `blocks[i]` is the block table of cached_groups()[i]; `n_tokens` is how many tokens are
@@ -173,10 +204,12 @@ struct IPrefixCache {
/* Release the least recently used entries and their KV references. The scheduler tries this
* before preempting a running request. */
virtual int64_t evict(int64_t n_entries) = 0;
/* Free up to `n_blocks` for the reserve without losing anything a later turn needs. Unlike
/* Free up to `n_entries` for the reserve without losing anything a later turn needs. Unlike
* evict(), it skips entries a live sequence still holds (no block would be freed) and entries
* whose only copy is in VRAM. Returns the number of blocks freed. */
virtual int64_t trim(int64_t n_blocks) = 0;
* whose only copy is in VRAM. An entry is one block in each cached group, or more in a group
* whose blocks are shorter than the entry (PrefixCache::blocks_per_entry). Returns the number
* of entries freed. */
virtual int64_t trim(int64_t n_entries) = 0;
/* Drop every entry in every tier. Implementations with idle tiers must override this: there,
* evict() keeps an entry whose host copy has landed. Returns the number of entries dropped. */
@@ -202,6 +235,16 @@ struct IPrefixCache {
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
virtual int64_t expired() const { return 0; }
virtual int64_t ckpt_expired() const { return 0; }
/* Entries and snapshots a client released on purpose (release_session). */
virtual int64_t released() const { return 0; }
virtual int64_t ckpt_released() const { return 0; }
/* Forget one stored conversation now, by the client's label or the engine's session id
* (PrefixCache::release_session). RAD_E_UNSUPPORTED from a cache without a session table. */
virtual int release_session(const std::string& /*label*/, uint64_t /*id*/,
int64_t /*keep_tokens*/, SessionRelease* /*out*/) {
return RAD_E_UNSUPPORTED;
}
/* Tokens of context held only by the cache right now. Blocks a running sequence also reads
* are excluded. Separates a working cache from a leak in the pool figures. */
@@ -305,6 +348,8 @@ struct KVBinding final : IKVManager {
}
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); }
bool can_grow(uint64_t s, int64_t n) const override { return m->can_grow(s, n); }
int release_idle_states() override { return m->release_idle_states(); }
const std::vector<int32_t>& block_table(uint64_t s, int32_t g) const override {
return m->block_table(s, g);
}
@@ -314,15 +359,27 @@ struct KVBinding final : IKVManager {
}
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 available_blocks(int32_t g) const override { return m->available_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 held_top_blocks(int32_t g) const override { return m->held_top_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); }
const RadKVStream* stream_view(int32_t g) const override { return m->stream_view(g); }
int64_t stream_misses() const override { return (int64_t)m->stream_stats().misses; }
int64_t stream_bytes_in() const override { return (int64_t)m->stream_stats().bytes_in; }
int64_t stream_resident_blocks() const override {
return m->stream_stats().resident_blocks;
}
int64_t block_tokens(int32_t g) const override {
const KVGroupPlan* p = m->plan(g);
return p && p->paged() ? p->block_size : 0;
}
bool window_snapshot(int32_t g) const override {
const KVGroupPlan* p = m->plan(g);
return p && p->win_snap;
}
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);
@@ -435,6 +492,7 @@ struct PCBinding final : IPrefixCache {
}
void release(const Request& r) override { m->release(r.id); }
const std::vector<int32_t>& cached_groups() const override { return m->cached_groups(); }
void set_drafter_floor(int64_t tokens) override { m->set_drafter_floor(tokens); }
/* Indexes prompt ++ output: the next turn sends the reply back in its prompt, so indexing the
* prompt alone would stop hitting at the first assistant token. */
@@ -488,6 +546,12 @@ struct PCBinding final : IPrefixCache {
}
int64_t expired() const override { return m->stats().expired; }
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
int64_t released() const override { return m->stats().released; }
int64_t ckpt_released() const override { return m->stats().ckpt_released; }
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) override {
return m->release_session(label, id, keep_tokens, out);
}
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); }
+17
View File
@@ -24,6 +24,9 @@ struct SchedMetrics {
int64_t failed = 0;
int64_t cancelled = 0;
int64_t preemptions = 0;
/* --preempt-wait-ms fallback: waits that ended by evicting cache blocks and forcing a running
* victim, not just by the pool freeing itself. */
int64_t preempt_forced = 0;
int64_t steps = 0;
/* Steps by shape. `steps_mixed` counts steps carrying both a prefill chunk and decode rows.
@@ -77,6 +80,11 @@ struct SchedMetrics {
* difference is the VRAM the elastic pool released behind unheld blocks. */
int64_t bytes_carved = 0;
} kv[RAD_SCHED_MAX_KV_GROUPS];
/* KV streaming: the rings' depth over every streamed group, and the resolve's cumulative misses
* and bytes copied in from the host mirrors. Zero when nothing streams. */
int64_t kv_resident_blocks = 0;
int64_t kv_stream_misses = 0;
int64_t kv_stream_bytes_in = 0;
/* Prefix caching (§7.3). Attention and linear are reported separately because they hit at
* different granularities. */
@@ -92,6 +100,7 @@ struct SchedMetrics {
* and reservations that went without a snapshot. */
int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0;
int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */
int64_t prefix_released = 0, prefix_ckpt_released = 0; /* DELETE /sessions */
/* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
* state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
* that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a
@@ -142,6 +151,14 @@ struct SchedMetrics {
bool draft_adaptive = false;
float draft_depth_adaptive = 0.0f;
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
/* Prompt lookup's verify gate (sched/lookup.h), when lookup is the only drafter: proposals
* made, proposals held back unverified and their drafts, and of the held proposals scored
* against the text that followed, the drafts that came true (what a verify would have
* accepted). */
int64_t lookup_proposals = 0;
int64_t lookup_held = 0;
int64_t lookup_held_drafts = 0;
int64_t lookup_held_hits = 0;
};
+72
View File
@@ -0,0 +1,72 @@
/* mtp_couple_bind.h -- the engine's post-commit binding step for a serial drafting row.
*
* Engine::finish_serial_drafter calls this after the commit, once the card's proposal states are
* read back. It decides:
*
* - the position the next build stages the row at: the request's committed output length after
* this commit. It is not rebuilt from the draw's pre-commit base plus the accepted count, which
* differ when a max_tokens or context cut emits fewer tokens than the card accepted;
* - whether the row binds at all: a sequence that is gone from the commit or no longer Running
* will not sample again.
*
* Both come from Scheduler::committed_seq(), filled by commit under the scheduler lock, never from
* the plan's StepEntry::req, which reap() may have freed by now. A header of its own so the rule
* can be tested against a real commit without an Engine (tests/sched_test.cpp).
*/
#pragma once
#include "advance.h"
#include "rad_spechub.h"
#include <cstring>
#include <string>
namespace rad {
/* Where the next build will sample this sequence, after the current step's commit. */
struct MtpCoupleBindPoint {
bool found = false; /* the committed step carried the sequence */
bool live = false; /* and its request was still Running (not finished/cancelled/failed) */
uint64_t n_out = 0; /* its committed output length: what the next build reads as n_out */
};
/* Bind `done` rounds of this row's draw to the positions the next build samples. `rb` is round 1
* of this row in the engine's readback (stride `rb_stride` states), `tok[rd]` the card's token for
* round rd, `S` the card's slot. Fills `out[0, done)` and sets `*n_bound = done`; a sequence that
* is not live binds nothing (`*n_bound = 0`, RAD_OK) and leaves `out` untouched. RAD_E_STATE with
* `why` for a readback that is not this draw's, or is not a state the proposer could have written.
* A sampled round the proposer marked status -1 (a shortlist it could not turn into Q) kept the
* greedy proposal; it is bound as is, the sampler does not couple it, and `*n_malformed` counts it.
* `base` is never read here: it is the draft's coordinate, not the verify's. */
inline int mtp_couple_bind_rounds(const MtpCoupleBindPoint& p, const RadMtpCoupleDraw& d,
const RadMtpCoupleState* rb, int rb_stride, int done,
const StepSlot& S, int64_t vocab, RadMtpCoupleState* out,
int* n_bound, std::string* why, int* n_malformed = nullptr) {
*n_bound = 0;
if (n_malformed) *n_malformed = 0;
if (!p.live) return RAD_OK;
const bool sampled = d.mode == 1;
for (int rd = 1; rd <= done; ++rd) {
const RadMtpCoupleState& st = rb[(size_t)(rd - 1) * (size_t)rb_stride];
const bool malformed = sampled && st.status == -1;
if (std::memcmp(&st.draw, &d, sizeof d) || st.round != rd || st.x != S.tok[rd] ||
(st.status != (sampled ? 1 : 0) && !malformed) ||
(sampled && !malformed && !rad_mtp_couple_state_valid(st, vocab))) {
*why = "MTP coupled: sequence " + std::to_string(d.seq) + " round " +
std::to_string(rd) + " returned status " + std::to_string(st.status) +
" round " + std::to_string(st.round) + " x " + std::to_string(st.x) +
" for card token " + std::to_string(S.tok[rd]) + " (draw " +
(std::memcmp(&st.draw, &d, sizeof d) ? "stale" : "current") +
"); refusing the step";
return RAD_E_STATE;
}
if (malformed && n_malformed) ++*n_malformed;
RadMtpCoupleState b = st;
b.pos = rad_mtp_couple_verify_pos(p.n_out, rd);
out[rd - 1] = b;
}
*n_bound = done;
return RAD_OK;
}
} // namespace rad
+54
View File
@@ -0,0 +1,54 @@
/* mtp_couple_plan.h -- which draw the engine stages for each drafting row (serial or block).
*
* Engine::stage_couple_draws (core/engine_draft.cpp) reads the draw of every sequence on its card
* from the step plan and, for each drafting row, the plan entry naming the row's sequence on the
* row's card. Pure host bookkeeping, so it is tested without a card.
*
* `by_card` has one entry per card slot, indexed by StepEntry::card in [0, max_seqs), the range of
* the StepSlots the advance reads.
*/
#pragma once
#include "batch.h"
#include "scheduler.h" /* Scheduler::SerialRow */
#include "rad_spechub.h"
#include <cstdint>
#include <string>
#include <vector>
namespace rad {
/* Fills `by_card[0, n_card)` from the plan and writes one draw per drafting row to `stage[0, n)`.
* RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting
* row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the
* staged draw, so it is refused here where the row can be named). */
template <class Row> /* Scheduler::SerialRow or Scheduler::BlockRow: a sequence and its card */
inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Row* rows,
int n, std::vector<RadMtpCoupleDraw>* by_card,
RadMtpCoupleDraw* stage, std::string* why) {
if (!by_card || !stage || !why) return RAD_E_INVAL;
if ((int)by_card->size() < n_card) {
*why = "the draw plane holds " + std::to_string(by_card->size()) +
" card slot(s), the step can use " + std::to_string(n_card);
return RAD_E_STATE;
}
for (int c = 0; c < n_card; ++c) (*by_card)[(size_t)c] = RadMtpCoupleDraw{};
for (const StepEntry& e : plan.e)
if (e.req && e.card >= 0 && e.card < n_card)
(*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq,
e.card, e.req->sp.greedy() ? 0u : 1u };
for (int i = 0; i < n; ++i) {
const Row& row = rows[i];
if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) {
*why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) +
", card " + std::to_string(row.card) + ") has no plan entry on its card";
return RAD_E_STATE;
}
stage[i] = (*by_card)[(size_t)row.card];
}
return RAD_OK;
}
} // namespace rad
+119
View File
@@ -0,0 +1,119 @@
/* ngram.cpp -- the prompt-lookup drafter's index. See ngram.h. */
#include "ngram.h"
#include <algorithm>
namespace rad {
void NgramIndex::reset(uint64_t owner) {
std::vector<uint32_t>().swap(tab_);
mask_ = 0;
filled_ = 0;
entries_ = 0;
owner_ = owner;
nmin_ = nmax_ = 0;
}
uint64_t NgramIndex::hash(const TokenSeq& s, int64_t end, int n) {
uint64_t h = 0x9E3779B97F4A7C15ull * (uint64_t)(n + 1);
for (int64_t i = end - n + 1; i <= end; ++i) {
h ^= (uint64_t)(uint32_t)s[i];
h *= 0xff51afd7ed558ccdull;
h ^= h >> 32;
}
h *= 0xc4ceb9fe1a85ec53ull;
return h ^ (h >> 29);
}
bool NgramIndex::same(const TokenSeq& s, int64_t e1, int64_t e2, int n) {
for (int k = 0; k < n; ++k)
if (s[e1 - k] != s[e2 - k]) return false;
return true;
}
/* Ends arrive in increasing order, so an n-gram already present is overwritten by a later
* occurrence: the entry is always the latest. */
void NgramIndex::insert(const TokenSeq& s, int64_t end, int n) {
const uint32_t v = ((uint32_t)(end + 1) << 4) | (uint32_t)n;
for (uint64_t i = hash(s, end, n) & mask_;; i = (i + 1) & mask_) {
const uint32_t t = tab_[(size_t)i];
if (t == 0) {
tab_[(size_t)i] = v;
++entries_;
return;
}
if ((int)(t & 15u) == n && same(s, (int64_t)(t >> 4) - 1, end, n)) {
tab_[(size_t)i] = v;
return;
}
}
}
/* At most half full, so a probe ends within a few slots. Doubling rehashes from the sequence's
* own tokens; amortised over the tokens that filled it, a constant per token. */
void NgramIndex::grow(const TokenSeq& s, int64_t want_entries) {
uint64_t cap = 1024;
while ((int64_t)cap < 2 * want_entries) cap <<= 1;
if (cap <= (uint64_t)tab_.size()) return;
std::vector<uint32_t> old;
old.swap(tab_);
tab_.assign((size_t)cap, 0u);
mask_ = cap - 1;
entries_ = 0;
for (const uint32_t t : old)
if (t) insert(s, (int64_t)(t >> 4) - 1, (int)(t & 15u));
}
void NgramIndex::index_to(const TokenSeq& s, int64_t upto) {
if (upto <= filled_) return;
const int nn = nmax_ - nmin_ + 1;
grow(s, entries_ + (upto - filled_) * nn);
for (int64_t e = filled_; e < upto; ++e)
for (int n = nmin_; n <= nmax_ && n <= e + 1; ++n) insert(s, e, n);
filled_ = upto;
}
int64_t NgramIndex::find_suffix(const TokenSeq& s, int n) const {
const int64_t end = s.size() - 1;
if (tab_.empty() || n < 1 || n > end) return -1;
for (uint64_t i = hash(s, end, n) & mask_;; i = (i + 1) & mask_) {
const uint32_t t = tab_[(size_t)i];
if (t == 0) return -1;
const int64_t e = (int64_t)(t >> 4) - 1;
if ((int)(t & 15u) == n && e < end && same(s, e, end, n)) return e;
}
}
int NgramIndex::propose(const TokenSeq& seq, int nmin, int nmax, int depth, int32_t* out,
int* match, int match_cap) {
const int64_t len = seq.size();
if (depth <= 0 || len < 2) return 0;
nmin = std::max(1, std::min(nmin, (int)kMaxN));
nmax = std::max(nmin, std::min(nmax, (int)kMaxN));
/* Only n-grams with a token after them are indexed: the last one is the pattern sought. */
const int64_t upto = std::min(len - 1, kMaxLen);
if (nmin != nmin_ || nmax != nmax_ || filled_ > upto) {
const uint64_t own = owner_;
reset(own);
nmin_ = nmin;
nmax_ = nmax;
}
index_to(seq, upto);
for (int n = (int)std::min<int64_t>(nmax, len - 1); n >= nmin; --n) {
const int64_t e = find_suffix(seq, n);
if (e < 0) continue;
for (int d = 0; d < depth; ++d) {
const int64_t i = e + 1 + d;
out[d] = i < len ? seq[i] : out[i - len];
}
if (match) {
int m = n;
while (m < match_cap && e - m >= 0 && seq[e - m] == seq[len - 1 - m]) ++m;
*match = m;
}
return depth;
}
return 0;
}
} /* namespace rad */
+86
View File
@@ -0,0 +1,86 @@
/* ngram.h -- the prompt-lookup drafter's index: where each n-gram of a sequence last occurred.
*
* Prompt lookup (Scheduler::draft_ngram) proposes, for a sequence of L tokens, what followed the
* most recent earlier occurrence of its last n tokens, for n from the longest pattern down to the
* shortest. Scanning the sequence for that occurrence costs O(L) a step on a miss, which at a
* 400k-token context is a millisecond of host time per sequence per step. This index answers it in
* O(n) and is updated incrementally: each token committed adds the n-grams ending at the token
* before it, so a sequence is indexed once over its lifetime, prompt included.
*
* The table is open-addressed and stores no keys. An entry is the end position of the n-gram's
* latest occurrence and its length n, and its tokens are the sequence's own, compared on every
* probe, so the index is exact: a hit is a true earlier occurrence, a miss means there is none.
* One table holds every length; it doubles past half full, so memory is about 8 bytes per token
* per pattern length (16 MiB for 400k tokens and lengths 2..4), allocated as the sequence grows.
*
* The proposal itself is a guess like any drafter's: the verify step emits the target's own
* tokens whatever it proposes (core/sample/accept.h), so the index changes speed, never text.
*/
#pragma once
#include <cstdint>
#include <vector>
namespace rad {
/* A sequence as prompt ++ output, the two vectors a Request keeps, without copying either. */
struct TokenSeq {
const int32_t* a = nullptr;
int64_t na = 0;
const int32_t* b = nullptr;
int64_t nb = 0;
int64_t size() const { return na + nb; }
int32_t operator[](int64_t i) const { return i < na ? a[i] : b[i - na]; }
};
class NgramIndex {
public:
/* The longest pattern an entry can name (4 bits), and the longest sequence it indexes: past
* 2^27 tokens the index stops growing and only earlier occurrences are found. */
enum { kMaxN = 15 };
static constexpr int64_t kMaxLen = ((int64_t)1 << 27) - 1;
/* Empties the index and releases its table. `owner` names the sequence it is built for (a
* request id); a lookup for any other owner starts over. */
void reset(uint64_t owner = 0);
uint64_t owner() const { return owner_; }
/* Proposes up to `depth` tokens into `out` for the sequence `seq`, indexing what it added
* since the last call. For n = nmax down to nmin: if the last n tokens occurred earlier, the
* tokens after their latest earlier occurrence; past the sequence's end the proposal goes on
* with its own tokens, so a pattern that repeats with a period shorter than `depth` is
* proposed whole. Returns how many were proposed, 0 when no pattern of those lengths recurs.
*
* The sequence must only grow between calls under one owner; a shorter one (or other pattern
* lengths) rebuilds the index. 1 <= nmin <= nmax <= kMaxN.
*
* `match`, if given, receives how far the match behind the proposal runs back: the number of
* tokens before the end that equal those before the occurrence, at least the pattern's n and
* at most `match_cap` (counted only that far). The verify gate (lookup.h) prices a long match
* apart from a recurring bigram. */
int propose(const TokenSeq& seq, int nmin, int nmax, int depth, int32_t* out,
int* match = nullptr, int match_cap = 0);
/* The latest end position e < seq.size() - 1 of an earlier occurrence of the sequence's last
* `n` tokens, or -1. Visible for tests; propose() calls it after indexing. */
int64_t find_suffix(const TokenSeq& seq, int n) const;
int64_t indexed() const { return filled_; } /* n-grams ending before this are in */
int64_t entries() const { return entries_; }
size_t bytes() const { return tab_.capacity() * sizeof(uint32_t); }
private:
std::vector<uint32_t> tab_; /* 0 empty, else (end + 1) << 4 | n */
uint64_t mask_ = 0;
int64_t filled_ = 0; /* every n-gram ending at e < filled_ is indexed */
int64_t entries_ = 0;
uint64_t owner_ = 0;
int nmin_ = 0, nmax_ = 0;
static uint64_t hash(const TokenSeq& s, int64_t end, int n);
static bool same(const TokenSeq& s, int64_t e1, int64_t e2, int n);
void insert(const TokenSeq& s, int64_t end, int n);
void grow(const TokenSeq& s, int64_t want_entries);
void index_to(const TokenSeq& s, int64_t upto);
};
} /* namespace rad */
+768 -87
View File
File diff suppressed because it is too large. Load diff
+145 -17
View File
@@ -14,7 +14,9 @@
#pragma once
#include "batch.h"
#include "draft.h"
#include "lookup.h"
#include "metrics.h"
#include "ngram.h"
#include <chrono>
#include <memory>
@@ -40,12 +42,18 @@ struct SchedReq {
/* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
int64_t arrived_us = 0;
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
int64_t preempted_us = 0; /* when this state became Preempted; 0 otherwise. Bounds the
* whole-recompute admission wait (--preempt-wait-ms). */
/* 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;
/* A tree drafter's parents for `draft` (StepEntry::draft_parent), valid while `draft_tree`;
* a chain proposal (prompt lookup, or a chain drafter) clears it. */
int32_t draft_par[RAD_SCHED_MAX_SPEC] = {};
bool draft_tree = false;
/* A serial drafter's valid history: positions [0, draft_filled) of the head's own layer hold
* K and V for the sequence's real tokens. Only the head writes that layer, so before drafting
@@ -77,6 +85,13 @@ struct SchedReq {
DraftAdapt adapt;
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
bool draft_ngram = false;
/* Prompt lookup's index over prompt ++ output (ngram.h), built at the sequence's first lookup
* and extended by each later one. It depends on the tokens alone, so preemption keeps it; it
* is keyed by request id, so a recycled slot starts over, and a closed request frees it. */
NgramIndex ngram_ix;
/* Prompt lookup's record on this text for the verify gate (lookup.h): it describes the text,
* so preemption keeps it; a new request starts it over. */
LookupSeq look;
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 */
@@ -127,16 +142,31 @@ struct SchedReq {
class Scheduler {
public:
/* What the sampler hands back after a step: per sequence, how many drafts survived, the token
* sampled at the accepted position, and whether the sequence ended. No logits. */
* sampled at the accepted position, and whether the sequence ended. No logits. commit() fills
* in the two counts. */
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 */
int n_prefill_done = 0; /* prompts this step fully placed */
int n_finished = 0; /* requests that ended during this step */
/* Logprobs, null on a step where no request asked: entry i's j-th emitted token (its
* accepted drafts first, then the sampled token) is lp[first_row[i] + j]. */
const TokenLogprobs* lp = nullptr;
const int32_t* first_row = nullptr; /* [n_seq] */
/* A tree step's accepted nodes, [n_seq][RAD_SCHED_MAX_SPEC]: entry i's t-th accepted
* draft is draft[path[i][t] - 1]. Null on a chain step, where it is draft[t]. */
const int32_t* path = nullptr;
};
/* What commit left a sequence at: its committed length and whether it is still Running.
* Copied under the lock in commit because reap() may free the Request before the serial bind
* reads it. */
struct CommittedSeq {
uint64_t seq = 0;
uint64_t n_out = 0;
bool live = false;
};
/* `geo` is the already-resolved chunk geometry. The engine resolves it once because
@@ -148,6 +178,8 @@ public:
/* 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); }
/* See BatchBuilder::step_seqs. */
const std::vector<uint64_t>* step_seqs(const RadBatch* b) const { return builder_.step_seqs(b); }
/* The advance's view of that build on one rank; see BatchBuilder::advance_args. Also carries
* the serial head's shape, which only the draft passes' modes read. */
AdvanceArgs advance_args(int rank) const {
@@ -167,6 +199,15 @@ public:
* under exactly the load that cancels. */
int cancel(uint64_t id);
Request* find(uint64_t id);
/* Fail every request prefilling in the step just committed, with `why` for the client: a streamed
* group's resolve latched overflow, so their selection tables no longer address the pool
* (docs/KV-STREAMING.md §3.4). */
int fail_prefilling(const char* why);
/* Whether the request is still admitted and Running, read under the lock. */
bool running(uint64_t id) const;
/* What the step just committed left for `seq`, copied by commit under the lock. False when
* that step carried no such sequence. */
bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const;
/* Requests that reached a terminal state since the last call, oldest first, swapped into
* `out` under the lock (old contents discarded). Only the engine consumes it, to drop
@@ -241,7 +282,8 @@ public:
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
int set_draft(uint64_t id, const int32_t* tokens, int n);
/* `parents`: a tree drafter's (rad_drafter_tree), node j + 1's parent node, null for a chain. */
int set_draft(uint64_t id, const int32_t* tokens, int n, const int32_t* parents = nullptr);
/* ---------------------------------------------------------- media the encoder owes
* A request carrying media is admitted only once every item is encoded; until then it keeps
@@ -260,6 +302,16 @@ public:
* cache. Takes the step lock because the step path inserts into the map (live sequences hold
* their own block references). See IScheduler::reset_prefix_cache. */
int64_t reset_prefix_cache();
/* The end-of-generation ids the card's acceptance reads, for ends_every_request. Set once at
* start; without them only max_tokens ends are predicted. */
void set_eog(std::vector<int32_t> ids);
/* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens`
* (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that
* conversation is queued or running: its blocks would be skipped as live and its close
* would publish the chain again, so the release would be half done and undone at once.
* Takes the step lock like reset_prefix_cache. */
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out);
/* ---------------------------------------------------------- the step path */
/* One decision, one batch. Null when there is nothing to run, which is not an error. */
@@ -286,10 +338,14 @@ public:
void expect_draft(uint64_t id, int n);
const RadBatch* step_next();
const RadBatch* step_next_locked();
/* Whether the step just issued likely ends every request it carries; step_next_locked then
* issues nothing behind it. */
bool ends_every_request() const;
void promote_next();
/* 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);
* finished requests, feed the draft controller, and fill `r`'s report counts
* (n_prefill_done, n_finished). */
int commit(StepResult& r);
/* Ends the step for timing; call once per loop iteration that ran a step, after the drafter,
* so the draft rounds are charged to the step (see the definition). Without it the counters
* stay correct but there is no timing. */
@@ -361,6 +417,20 @@ public:
* in the order block_query() emits them. */
int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max,
bool on_card = false);
/* How many running sequences the step just run decoded (produced a token for), the load a
* block drafter's block length is chosen by. Read before block_begin(). */
int decoded_seqs() const;
/* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it
* ran it last step and this step's decoded_seqs(): on from `from`, and off again two below or
* at one sequence below `from`, where the long block pays. Two below keeps a load wavering at
* a threshold of 3 or more from switching the pass shape every step. From 2 there is no such
* margin: a load between one and two sequences switches every step (block_shape reads it per
* step), and the one sequence left after an overlap runs the long block again. */
static bool short_block_on(bool was_on, int64_t decoded, int64_t from) {
if (decoded >= from) return true;
if (decoded <= 1 || decoded + 2 <= from) return false;
return was_on;
}
const RadBatch* block_context(int step);
const RadBatch* block_query(int step);
void block_end();
@@ -368,6 +438,7 @@ public:
const StepPlan& plan() const { return plan_; }
const ChunkGeometry& geometry() const { return geo_; }
DraftController& draft() { return draft_; }
LookupGate& lookup_gate() { return lookup_; }
SchedMetrics metrics() const;
/* The observers' copy. Dashboards, scrapers and admin calls read what the engine thread last
@@ -379,8 +450,15 @@ public:
SchedMetrics observed_metrics() const;
int observed_requests(ReqStat* out, int max) const;
/* plan_chunk's tail-checkpoint rule (see the definition). */
/* plan_chunk's tail-checkpoint rule for each --prefix-resume mode (see the definition). */
int64_t tail_checkpoint(int64_t target) const;
/* The least recompute a snapshot at a shared head (CacheHit::branch_at) must save each later
* request for the chunk split that takes it. */
static constexpr int64_t kSharedHeadMin = 256;
/* The lowest position tail_checkpoint takes a window snapshot at (ChunkGeometry::window_ckpt),
* or the interval where that is lower. A prompt reaches it at kWindowSnapshotMin +
* max(quantum, 16) tokens: 528 at a quantum of 16. */
static constexpr int64_t kWindowSnapshotMin = 512;
/* 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). `keep_at` is the
* request's own checkpoint (Request::checkpoint_at), 0 for none. */
@@ -433,16 +511,25 @@ private:
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 windowed groups, so a windowed drafter has K and V
* only from the hit position and must wait for its window to slide past it. A full-attention
* drafter's group is cached like the trunk's and its floor is 0; treating it as windowed
* would stop drafting for good, since it has no window to slide. Read off
* IPrefixCache::cached_groups() so prefix.cpp's rule lives in one place. */
* is neither prefix-cached nor restored from the window snapshot. prefix.cpp skips windowed
* groups, so a windowed drafter the snapshot does not carry has K and V only from the hit
* position and must wait for its window to slide past it. A full-attention drafter's group is
* cached like the trunk's and its floor is 0; treating it as windowed would stop drafting for
* good, since it has no window to slide. Read off IPrefixCache::cached_groups() and
* IKVManager::window_snapshot() so prefix.cpp's and the KV manager's rules live in one
* place. */
bool hit_holes_draft_ = true;
/* Does a hit leave a hole in the trunk: a paged group with a trunk layer (bound below
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index and
* no checkpoint slot carries? Unlike a drafter hole, recomputing the tail cannot repair it;
* every hit is refused (admit_one). */
bool hit_holes_trunk_ = false;
/* The end-of-generation ids, sorted and unique (set_eog), and a lookup in them. */
std::vector<int32_t> eog_;
bool is_eog(int32_t id) const;
/* A windowed trunk group, which the cache does not index: a hit stands only where it resumes
* at a window snapshot (IKVManager::has_window_snapshot), which restores the window. */
bool hit_needs_window_ = false;
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
* not declare one, in which case admission and commit are exactly as before. A sequence with
@@ -462,6 +549,8 @@ private:
* at the committed position (advance.h). False and 0 for every other drafter. */
bool serial_shared_ = false;
int32_t serial_rot_shift_ = 0;
/* A tree drafter (rad_drafter_tree): every trunk plan is StepPlan::spec_is_tree. */
bool tree_ = false;
BatchBuilder builder_;
DraftController draft_;
@@ -491,11 +580,30 @@ private:
std::vector<DraftAdapt*> draft_est_;
void draft_cycle();
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
* lengths it tries, longest first. */
int draft_ngram(SchedReq& s, int depth) const;
enum { kNgramMin = 2, kNgramMax = 4 };
/* The built-in prompt-lookup drafter (scheduler.cpp, ngram.h). Fills s.draft and returns how
* many tokens it proposed; 0 when the sequence has no repeated pattern to extend. It tries
* --spec-ngram-max down to --spec-ngram-min tokens, longest first. `match`, if given, gets how
* far the match behind the proposal runs back (NgramIndex::propose), -1 when the proposal did
* not come from the index (--debug-draft-oracle). */
int draft_ngram(SchedReq& s, int depth, int* match = nullptr) const;
/* Prompt lookup is the deployment's only drafter and --draft-window adaptive is on: its
* proposals feed each sequence's estimate and are capped by its window, as a head's are. */
bool lookup_adapt_ = false;
/* Prompt lookup is the deployment's only drafter: each proposal is verified only when its
* sequence's record says it pays for its verify rows at the measured step cost (lookup.h).
* Beside a draft head the lookup only fills in for a sequence the head declines, and is
* left to the head's window. */
bool lookup_gate_on_ = false;
LookupGate lookup_;
/* Decode rows and expected tokens of the step being planned, for the gate: a decode row
* counts once up front, and each verified proposal adds its drafts and expected yield. */
int64_t gate_rows_ = 0;
double gate_tokens_ = 0.0;
/* --debug-draft-oracle (draft_ngram): a fixed continuation the lookup proposes from instead,
* with kDebugMiss of the drafts corrupted, so a verify accepts and rejects at every depth on
* any model. A test harness; empty when not given. */
std::vector<int32_t> debug_oracle_;
static constexpr double kDebugMiss = 0.3;
mutable std::mutex mu_;
@@ -521,6 +629,10 @@ private:
std::vector<int32_t> running_;
std::vector<int32_t> waiting_;
std::vector<uint64_t> completed_;
/* StepResult's counts for the step being committed: the ids whose prompt it completed, and the
* requests it ended. Reset at every commit. */
std::vector<uint64_t> last_prefill_ids_;
int step_finished_ = 0;
/* Requests whose release waits on something that still refers to them (a deferred reap or a
* deferred free). A count, so the sweeps cost nothing on the steps where there are none. */
@@ -545,6 +657,8 @@ private:
* lives here). See add_locked. */
int64_t pool_tokens_ = -1;
std::string pool_refusal_;
/* fail_prefilling()'s message; a sink keeps the pointer until the HTTP thread writes it. */
std::string stream_why_;
/* 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. */
@@ -598,6 +712,7 @@ private:
int32_t card = -1;
int32_t ctx_len = 0;
int32_t n_tokens = 0;
int32_t n_spec = 0; /* the trunk entry's drafts: a tree verify when > 0 */
int64_t base_pos = 0; /* the anchor's position: the sequence's next one */
bool can_draft = false;
/* On the card: the anchor's position is the card's, and `base_pos` the furthest it can
@@ -637,6 +752,8 @@ private:
* 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;
/* The step just committed: its sequences' committed length and liveness, in plan order. */
std::vector<CommittedSeq> committed_;
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
DecodeFloor decode_floor_;
@@ -680,12 +797,23 @@ private:
/* 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();
/* A preempted request waits until the pool can hold its WHOLE remaining recompute, the rest
* of every running prefill, and one block of headroom per runner. Admitting it against only
* the next token steals the blocks a running prefill still needs and preempt_back() resets
* that prefill to zero — the loop. `preempt_wait_overdue` bounds the wait for every overdue
* preempted request: after --preempt-wait-ms the scheduler reclaims cache blocks and preempts
* a decoding runner until one of them can prefill. A runner still prefilling is not a victim. */
bool preempted_can_prefill(const SchedReq& s) const;
bool preempt_wait_overdue(const SchedReq& s) const;
/* Give blocks back from the prefix cache until the pool has headroom again. */
void trim_prefix_cache();
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
* it. `reserve`: tokens of the step to leave for the requests queued behind this one
* (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0);
/* Positive sentinel from admit_one: the request waits (its context is still being read off
* disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */
static constexpr int kAdmitWait = 1;
/* The queue positions one step's admission took, kept to reuse the allocation. */
std::vector<size_t> took_;
/* A step's prefill entries while step() moves its decode entries first; reserved at init,