Merge upstream main (v1.17.0 -> v2.1.0) into the SYCL port

102 upstream commits. Nine conflicts resolved. Fork side of the merge:
- libxe2: declare the givens_dense_quant schema (upstream 2.0 dropped it
  from libavx and libref; the device libraries now each carry it).
- plain_norm becomes an ABI 42 append to RadBuildCtx; abi layout table
  regenerated, kTableAbi = 42.

Known before the PR: arch_test (MTP lint and pinned graph hashes for
qwen35_fp8, qwen35moe_fp8, qwen4exp with MTP).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
aneinanderandClaude Opus 5.5 committed 2026-11-18 15:06:17 +01:00
commit 4b70a96378
850 files changed
+157819 -58519

No files matched your search

+7 -48
View File
@@ -8,6 +8,7 @@
#include <cstdlib>
#include "advance_impl.h"
#include "device/chain_kernel.h"
#include "rad_abi.h"
extern "C" int rad_dev_chain_enabled(void); /* core/device/device.h */
@@ -21,46 +22,16 @@ __global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a)
if (i < a.n_seq) rad::adv_row(a, i);
}
/* The chained form (RadKernelChainFn, abi/rad_abi.h): the backend gives a kernel named r4dchain*
* a record at RAD_CHAIN_KARG_OFF and drops its barrier bit behind another chained kernel. Before
* the first read one lane waits for the queue's counter to reach the record's target; after the
* last write the block releases and adds 1. A record that does not check out means: run plain. */
struct ChainRec {
unsigned long long magic, target;
unsigned long long* ctr;
unsigned long long check;
};
__device__ __forceinline__ const ChainRec* chain_rec() {
const ChainRec* r = (const ChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
RAD_CHAIN_KARG_OFF);
const unsigned long long magic = r->magic, target = r->target, check = r->check;
if (magic != RAD_CHAIN_MAGIC ||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
return nullptr;
return r;
}
/* The chained forms (chain_kernel.h), launched where launches chain. */
__global__ __launch_bounds__(kThreads) void r4dchain_step_advance(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");
}
rad_chain_wait();
const int i = (int)(blockIdx.x * kThreads + threadIdx.x);
if (i < a.n_seq) rad::adv_row(a, i);
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);
}
rad_chain_done();
}
/* 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
* split the K|V row into 16-byte chunks and its last words. 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) {
@@ -72,21 +43,9 @@ __global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::Advance
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");
}
rad_chain_wait();
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);
}
rad_chain_done();
}
} // namespace
+7 -2
View File
@@ -320,7 +320,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) {
}
/* 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
* for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. A row is whole 32-bit words; the
* words past its last whole chunk (an int8 cache's two f16 scales) go with the caller whose chunk
* set the next chunk would be in. 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
@@ -340,7 +342,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in
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;
const int32_t chunks = P.row_bytes / 16, tail = P.row_bytes % 16 / 4;
const bool tails = tail > 0 && chunks % cstep == c0;
for (int32_t t = 0; t < np; ++t) {
const int32_t src = base + S.path[t], dst = base + t + 1;
if (src == dst) continue;
@@ -355,6 +358,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in
v3 = from[4 * c + 3];
to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3;
}
if (tails)
for (int32_t j = 0; j < tail; ++j) to[4 * chunks + j] = from[4 * chunks + j];
}
}
+91 -32
View File
@@ -5,8 +5,10 @@
#include "derive.h"
#include "device/device.h"
#include "kvstream/bind.h"
#include "util/simd.h"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <cstring>
#include <cstdlib>
@@ -212,13 +214,17 @@ int BatchBuilder::alloc_set(Set& s, const std::vector<KVGroupInfo>& groups) {
}
RAD_TRY(rad_dev_set(ranks_[0].device));
/* The ring holds three worst-case builds before a long-context prefill waits on an upload two
* builds back. A decode build's span is far smaller, so hundreds fit. */
/* The ring holds kRingBuilds worst-case builds. A speculative step takes four or more builds
* (history pass, draft rounds, the next verify), and reserve() must not wait on an upload of
* the step being issued (that would hold step_next back until the card ran this step's draft
* uploads): two steps of builds fit with room over. A decode build's span is far smaller than
* the worst case, so many more fit; this is pinned host memory only, the device slab stays
* one build. */
int64_t worst_pay = 0;
for (const Group& g : s.groups) worst_pay += max_seqs_ * g.max_blocks * (int64_t)sizeof(int32_t);
const int64_t worst_ranges = worst_pay / k_range_max + max_seqs_ * (int64_t)s.groups.size() + 1;
ranges_.reserve((size_t)worst_ranges);
ring_.bytes = 3 * (s.host_bytes + worst_ranges * (int64_t)sizeof(RadCopyRange) + k_carve_align);
ring_.bytes = kRingBuilds * (s.host_bytes + worst_ranges * (int64_t)sizeof(RadCopyRange) + k_carve_align);
ring_.host = static_cast<char*>(rad_dev_alloc(ring_.bytes, RAD_MEM_HOST_PINNED));
if (!ring_.host) {
RAD_ERR("step batch staging: could not reserve %s of pinned host staging",
@@ -691,9 +697,9 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
};
/* Reset every group's row: a sequence with no state in a group must read -1, not a stale slot
* from the previous step. */
* from the previous step. -1 is all-ones, so the reset is a memset. */
for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi)
for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1;
std::memset(s.h_convslot + gi * max_seqs_, 0xff, (size_t)n_seq * sizeof(int32_t));
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
Group& g = s.groups[gi];
@@ -717,17 +723,20 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
int64_t first = 0;
SeqWindow win;
bool has_win = false;
/* One lookup of the sequence for everything below (IKVManager::seq_group); the
* change mark is taken with it, for a paged group only, as take_table_changes was. */
SeqGroupView gv;
kv.seq_group(e.seq, (int32_t)gi, L.paged, &gv);
/* A state group's row starts at 0 and carries no window, as before the view: only a
* paged group was ever asked. */
int64_t first = L.paged ? gv.first : 0;
const SeqWindow& win = gv.win;
const bool has_win = L.paged && gv.has_win;
int64_t bt_len = 0; /* the sequence's block table, in blocks */
int64_t table_end = 0; /* the table's last position, for a runtime window's used */
if (L.paged) {
/* The manager's block table, by sequence id; Request::blocks is not the source
* of truth (see IKVManager). */
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
first = kv.first_block_pos(e.seq, (int32_t)gi);
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
if (has_win) {
/* The ring size sets the group header's geometry, so every sequence in the
* group must report the same one. */
@@ -738,36 +747,47 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
}
ring_blocks = (int32_t)win.ring_blocks;
}
bt_len = (int64_t)bt.size();
bt_len = (int64_t)gv.bt_n;
table_end = bt_len * L.block_size;
for (int32_t j = 0; j < e.n_tokens; ++j) {
const int64_t pos = (int64_t)e.ctx_len + j;
g.h_slot[t + j] = has_win
? kvgeom_.slot_ring((int)gi, bt, first, pos, win)
: kvgeom_.slot((int)gi, bt, first, pos);
}
/* Consecutive positions: the segment walk (KVGeom::slots) stages the same
* slots slot()/slot_ring() would, one division a block instead of two a token. */
if (has_win)
kvgeom_.slots_ring((int)gi, gv.bt, gv.bt_n, first, (int64_t)e.ctx_len,
e.n_tokens, win, g.h_slot + t);
else
kvgeom_.slots((int)gi, gv.bt, gv.bt_n, first, (int64_t)e.ctx_len,
e.n_tokens, g.h_slot + t);
/* Restage relative to what the card holds (BtMirror). The same sequence in the
* same row keeps entries below the first changed one and below the end of both
* old and new tables, so a decode step stages nothing or one appended block. A
* new or moved sequence restages the whole row, and its copies in other rows go
* unknown. Change marks are taken for every row. */
const int64_t nb = std::min<int64_t>((int64_t)bt.size(), pitch);
const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi);
const int64_t nb = std::min<int64_t>((int64_t)gv.bt_n, pitch);
const int64_t chg = gv.changed_from;
int64_t lo = 0, hi = pitch;
if (m.len[(size_t)i] >= 0 && m.seq[(size_t)i] == e.seq) {
lo = std::min(std::min(chg, m.len[(size_t)i]), nb);
hi = std::max(nb, m.len[(size_t)i]);
} else {
for (int64_t k = 0; k < max_seqs_; ++k)
if (m.seq[(size_t)k] == e.seq) m.len[(size_t)k] = -1;
/* Invalidate this sequence's copies in other rows. Ids compare bitwise, so
* the uint64 row array is searched as int64 (simd::find_eq_i64). */
const int64_t* rows = (const int64_t*)m.seq.data();
int64_t k = simd::find_eq_i64(rows, (size_t)max_seqs_, (int64_t)e.seq);
while (k >= 0) {
m.len[(size_t)k] = -1;
if (k + 1 >= max_seqs_) break;
const int64_t nx = simd::find_eq_i64(
rows + k + 1, (size_t)(max_seqs_ - k - 1), (int64_t)e.seq);
k = nx < 0 ? -1 : k + 1 + nx;
}
}
if (lo < hi) {
int32_t* w = pay + np;
const int64_t nc = nb > lo ? nb - lo : 0;
/* Guarded: an empty table's data() may be null, and memcpy's source must
* not be, even for zero bytes. */
if (nc > 0) std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
std::fill(w + nc, w + (hi - lo), -1);
if (nc > 0) std::memcpy(w, gv.bt + lo, (size_t)nc * sizeof(int32_t));
std::memset(w + nc, 0xff, (size_t)(hi - lo - nc) * sizeof(int32_t));
stage(g.bt_fix + i * pitch + lo, np, hi - lo);
np += hi - lo;
}
@@ -777,8 +797,17 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
/* A linear or conv group has one state slot per sequence; every token maps to it
* and the block-table row is that slot, so table-reading kernels need no second
* path. */
int32_t st = kv.state_slot(e.seq, (int32_t)gi);
for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st;
const int32_t st = gv.state;
/* A kernel reads -1 as "no state" and carries on, so a sequence without its slot
* would compute fluent, wrong text. A drafter's pass may still name a finished
* sequence's rows; the trunk's may not. */
if (st < 0 && plan.draft_pass == 0 && e.n_tokens > 0 &&
(L.kind == RAD_KV_CONV || L.kind == RAD_KV_LINEAR)) {
RAD_ERR("step plan row %lld: sequence %llu holds no state slot in KV group %d",
(long long)i, (unsigned long long)e.seq, (int)gi);
return RAD_E_STATE;
}
std::fill(g.h_slot + t, g.h_slot + t + e.n_tokens, st);
pay[np + i] = st;
/* Every conv group, at its own row. Feeds only DeriveInput::conv_slot; conv
* kernels read RadKVGroupBatch::state_index (see conv_window_ in batch.h). */
@@ -812,16 +841,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
if (used < 0) used = 0;
g.h_used[i] = (int32_t)used;
if (L.paged) {
for (int64_t j = 0; j < g.sidx_pitch; ++j) g.h_sidx[i * g.sidx_pitch + j] = -1;
std::memset(g.h_sidx + i * g.sidx_pitch, 0xff,
(size_t)g.sidx_pitch * sizeof(int32_t));
} else {
kv.state_index_row(e.seq, (int32_t)gi, g.h_sidx + i * g.sidx_pitch,
(int)g.sidx_pitch);
}
}
int32_t group_used = 0;
for (int64_t i = 0; i < n_seq; ++i)
group_used = std::max(group_used, g.h_used[i]);
o.kv_used_max_h[gi] = group_used;
/* As the loop it replaces: the rows' maximum, floored at 0 (n_seq may be 0 and a row's
* used is clamped non-negative above, so the floor only binds then). */
o.kv_used_max_h[gi] = std::max<int32_t>(0, simd::max_i32(g.h_used, (size_t)n_seq));
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
if (!L.paged) {
stage(g.bt_fix, np, n_seq);
@@ -1044,10 +1073,35 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
if (bidi_on_ && plan.draft_pass == 0 && shift == 0 && e.req && e.req->media) {
const mm::PromptMedia& pm = *e.req->media;
const int64_t c0 = e.ctx_len, c1 = c0 + e.n_tokens, T = max_tok_;
/* RopeLayout::runs is documented ascending and pairwise disjoint, and the slice
* bound (h_bidi is 4*max_tok_ wide, one slot per token this step can carry) leans
* on exactly that: overlapping runs would count one token twice. The layout is now
* fed from request-side placement, so the promise is checked here rather than
* trusted -- an overlapping run drops its media rows' bidirectionality, which the
* acceptance path treats as an ordinary miss, where a slot overrun is a fault. */
int64_t prev_b = c0;
for (const mm::RopeLayout::Run& run : pm.rope.runs) {
const int64_t a = std::max<int64_t>(run.tok, c0);
const int64_t b = std::min<int64_t>((int64_t)run.tok + run.n, c1);
if (a >= b || pm.items[(size_t)run.item].item->kind == mm::Kind::Audio) continue;
if (a < prev_b) {
static std::atomic<bool> said{false};
if (log_once(said))
RAD_WARN("step batch: a rope layout overlaps at token %lld; that run is "
"not staged bidirectionally (first of possibly many)",
(long long)a);
continue;
}
prev_b = b;
if (n_bidi >= T) {
/* Belt: the disjoint check makes this unreachable; the slice says so
* rather than letting an overrun reach the card. */
static std::atomic<bool> said2{false};
if (log_once(said2))
RAD_WARN("step batch: bidi runs overflowed the %lld-token plane "
"(first of possibly many)", (long long)T);
break;
}
s.h_bidi[n_bidi] = (int32_t)b;
s.h_bidi[T + n_bidi] = (int32_t)(k + a - c0);
s.h_bidi[2 * T + n_bidi] = (int32_t)(b - a);
@@ -1108,7 +1162,12 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
s.h_q[i] = e.n_tokens;
s.h_ctx[i] = e.ctx_len;
s.h_acc[i] = e.n_accepted;
s.h_arow[i] = -1;
/* Row 0, not -1: the query pass gathers the context state by these values, and the
* gather's index plane is validated in shape only -- a row that reaches the correlator
* without having advanced would gather one row BEFORE the context buffer (device OOB).
* Row 0 is always in range; a row that skipped its advance reads a wrong anchor, which
* the acceptance path discards, instead of faulting or reading a neighbour's state. */
s.h_arow[i] = 0;
if (e.is_prefill) { if (e.n_tokens > max_q_pf) max_q_pf = e.n_tokens; }
else { if (e.n_tokens > max_q_dec) max_q_dec = e.n_tokens; }
}
+10
View File
@@ -62,6 +62,10 @@ struct StepEntry {
* acceptance but not the adaptive window's estimate of the draft head (DraftController,
* draft.h). */
bool ngram = false;
/* The drafts are a SuffixDecoding proposal (--draft-suffix, suffix.h): a chain of the
* sequence's own history, verified with no coupled row (Request::draft_suffix). Implies
* `ngram`. */
bool suffix = false;
/* Device row: the card overwrites its tokens, positions, rollback count and slots from the
* StepSlot before the pass runs (advance.h); `ctx_len` is then only an upper bound for the
* host-side ceilings. dev_tok/dev_out/dev_aux are advance.h's row descriptor: the verify
@@ -135,6 +139,10 @@ public:
/* The last build's batch for one rank: build()'s result with that rank's slab pointers. */
const RadBatch* batch_for(int rank) const;
/* Program::plugin_words as declared: the most words one request may carry. Admission checks
* it -- the build stage refuses an over-cap sequence, and a refused build restages forever,
* so a request admitted past the cap stalls every queue behind it. */
int64_t plugin_words_cap() const { return pw_cap_; }
/* The last build's slab and offsets on one rank, for the advance. The caller supplies mode,
* round, slot state and inputs (advance.h). */
@@ -255,6 +263,8 @@ private:
int ev = -1; /* row of ev_ holding one event per rank */
};
static constexpr int kFlights = 64;
/* Worst-case builds the staging ring holds (see alloc_set). Must stay below kFlights. */
static constexpr int kRingBuilds = 16;
struct Ring {
char* host = nullptr;
int64_t bytes = 0;
+19 -67
View File
@@ -11,22 +11,6 @@ namespace rad {
namespace {
/* Step-cost prior, a shape rather than a measurement: each draft adds 6% to a step (one serial
* head round plus one verify row on a weight-bound step). Once anything is measured only its
* ratios are used: an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
constexpr double kCostSlope = 0.06;
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
/* A step-time mean is a running mean for the first steps, then a moving average with a half-life
* of 32 steps: long enough to average out one-off costs (a tier copy, a recording, a prefix-cache
* trim), short enough to follow a context growing by a few thousand tokens over a reply. */
constexpr double kCostHalfLife = 32.0;
/* Once a key has 4 samples, one step counts for at most 4x its mean. A step that waited on
* something else (a first recording, an allocation, a host stall) says nothing about its depth's
* cost. Below 4 samples the mean is not a trustworthy reference to clip against. */
constexpr double kCostOutlier = 4.0;
constexpr int64_t kCostClipAfter = 4;
/* The prior weighs as much as this many verifies. The (n+1)-th verify moves an estimate by
* 1 / (n + k + 1), a running mean over prior and evidence, until that falls below the half-life's
* step and the moving average takes over. Without it a sequence would spend its first ~16
@@ -59,10 +43,8 @@ int DraftController::configure(const Params& p) {
step_held_ = 0;
prior_n_ = 0;
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
by_depth_[d] = 0;
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
}
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) by_depth_[d] = 0;
cost_.reset(kRowCost);
if (adapt_)
RAD_INFO("draft depth: adaptive, %d..%d; a sequence stops at the first draft emitted less "
"than %.0f%% of the time, and the depth moves at +%.0f%% at most every %d steps",
@@ -91,51 +73,16 @@ void DraftController::observe(int drafted, int accepted) {
}
/* ------------------------------------------------------------------ the step's cost */
int DraftController::cost_class(int n_rows) {
int c = 0;
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
return c;
void DraftController::step_time(int q_rows, double ms) {
if (!adapt_) return;
cost_.sample(q_rows, ms);
}
void DraftController::step_time(int depth, int n_rows, double ms) {
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
!std::isfinite(ms))
return;
const int c = cost_class(n_rows);
double& m = cost_ms_[depth][c];
int64_t& n = cost_n_[depth][c];
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
const double w = settle_weight(kCostHalfLife, n);
m = n ? m + w * (ms - m) : ms;
++n;
int64_t DraftController::cost_samples(int q_rows) const {
return q_rows >= 1 ? cost_.samples(q_rows) : 0;
}
int64_t DraftController::cost_samples(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
return cost_n_[depth][cost_class(n_rows)];
}
double DraftController::step_cost(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
/* Nearest measured key: this class first (nearest depth, shallower on a tie), then the
* nearest class. Only its ratio to the prior is borrowed, so D's comparison across depths in
* one class follows the prior's shape until those depths are measured. */
for (int dc = 0; dc < kCostClasses; ++dc) {
for (int sgn = 0; sgn < 2; ++sgn) {
const int k = sgn ? c + dc : c - dc;
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
int best = -1;
for (int d = 1; d <= p_.max_depth; ++d) {
if (cost_n_[d][k] <= 0) continue;
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
}
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
}
}
return cost_prior(depth);
}
double DraftController::step_cost(int q_rows) const { return cost_.cost(q_rows); }
/* ------------------------------------------------------------------ one sequence */
int DraftController::stop_of(const float* a) const {
@@ -181,14 +128,14 @@ double DraftController::yield(const DraftAdapt& s, int d) const {
}
int DraftController::window_of(const DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (!adapt_) return next_depth();
if (s.depth <= 0) return 0;
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
return s.depth < D ? s.depth : D;
}
int DraftController::window_for(DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (!adapt_) return next_depth();
if (s.depth <= 0) start(s);
return window_of(s);
}
@@ -236,9 +183,11 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
if (n_rows < n_seq) n_rows = n_seq;
const int M = p_.max_depth;
/* Expected tokens at each head depth: sum_i E_i(min(D, stop_i)), plus one per non-drafting
* row. Candidates end at the deepest stop, since a deeper D changes nothing. */
/* Expected tokens at each head depth, sum_i E_i(min(D, stop_i)) plus one per non-drafting
* row, and the drafts the step would then verify, sum_i min(D, stop_i). Candidates end at the
* deepest stop, since a deeper D changes nothing. */
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
int drafts[RAD_SCHED_MAX_SPEC + 1] = {};
int top = kMinDepth;
for (int i = 0; i < n_seq; ++i) {
DraftAdapt& s = *seq[i];
@@ -248,15 +197,18 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
for (int d = 1; d <= M; ++d) {
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
tok[d] += e;
drafts[d] += d <= s.depth ? d : s.depth;
}
}
const double plain = (double)(n_rows - n_seq);
if (top > M) top = M;
/* A step's query rows at depth d: a row a decode sequence and its drafts. */
auto gain = [&](int d) { return (tok[d] + plain) / step_cost(n_rows + drafts[d]); };
int best = kMinDepth;
double best_g = -1.0;
for (int d = kMinDepth; d <= top; ++d) {
const double g = (tok[d] + plain) / step_cost(d, n_rows);
const double g = gain(d);
if (g > best_g) { best_g = g; best = d; }
}
@@ -268,7 +220,7 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
} else {
if (step_held_ < INT32_MAX) ++step_held_;
const int cur = step_d_ < top ? step_d_ : top;
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
const double cur_g = gain(cur);
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
+30 -26
View File
@@ -17,9 +17,10 @@
* chance of being emitted still pays for its verify row (kDraftMinChance).
*
* Per step (plan_step): the head depth D. A serial head runs as many rounds as the deepest
* window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(D, n), with
* E(d) = 1 + sum_k prod_{j<=k} a_j and T measured online (step_time). Each sequence then
* drafts min(D, stop_i).
* window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(R(D)), with
* E(d) = 1 + sum_k prod_{j<=k} a_j, R(D) the query rows the step would then carry (a row a
* sequence plus sum_i min(D, stop_i)) and T measured online by row count (step_time,
* step_cost.h). Each sequence then drafts min(D, stop_i).
*
* Both move only past a hold, and D also past a hysteresis, because a new window is a new pass
* shape that must be recorded before it plays (runtime/ctx.h). `max_depth` stays the ceiling and
@@ -35,6 +36,7 @@
*/
#pragma once
#include "rad_core.h"
#include "step_cost.h"
namespace rad {
@@ -58,6 +60,9 @@ class DraftController {
public:
struct Params {
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
/* The head's own rounds when the window is wider than they are (--draft-suffix: a suffix
* step verifies more rows than the head drafts); 0 = max_depth. */
int head_depth = 0;
/* The adaptive policy: `--draft-window adaptive` with a serial drafter, decided by
* Scheduler::init. Off, the depth is max_depth. */
bool adapt = false;
@@ -96,22 +101,23 @@ public:
static constexpr int kMinDepth = 1;
/* A sequence stops at the first draft whose chance of being emitted, prod_{j<=d} a_j, is
* under 1 in 10. Once the head runs D rounds for the deepest neighbour, a sequence's only
* added cost is its verify row. At one sequence the step-cost prior (1 + 0.06 d) breaks even
* near this chance (a draft pays while p_d / E exceeds the ~6% it adds, with E around 2), and
* a row alone costs less than a round plus a row, so this is never stricter than D's own
* trade. A constant because a row's share cannot be separated from the head's rounds in step
* times keyed by depth. */
* added cost is its verify row, and a draft pays while p_d / E exceeds the share of the step
* that row adds. That share is a few percent at any load and E is two to three tokens a
* sequence, so this is never stricter than D's own trade; it only keeps a sequence that
* accepts little from riding its neighbours' rounds with rows that are almost never emitted. */
static constexpr double kDraftMinChance = 0.1;
/* Step times are kept per running-row class: 1, 2-3, 4-7, 8-15, 16+. Cost moves with how many
* rows share the weight reads; power-of-two classes keep every key fed. */
static constexpr int kCostClasses = 5;
/* The shape an untimed row count is priced on (StepCost): each query row adds 12% of a
* one-row step, a verify row of streamed experts and its share of a head round. Qwen3.8
* Flash-Next on two R9700s, ms a step at 3 / 4 / 5 rows of one sequence: 11.2 / 12.3 / 13.6.
* Only ratios are used, and a timed row count replaces it. */
static constexpr double kRowCost = 0.12;
int configure(const Params& p);
const Params& params() const { return p_; }
/* The draft depth for the next step; 0 means do not speculate. Constant: under the adaptive
* policy it is the ceiling, and window_for() is the window. */
int next_depth() const { return p_.max_depth; }
int next_depth() const { return p_.head_depth > 0 ? p_.head_depth : p_.max_depth; }
/* ---------------------------------------------------------- the adaptive policy */
bool adaptive() const { return adapt_; }
@@ -143,17 +149,17 @@ public:
/* The deepest window a step at depth D carries: D capped at the deepest stop it was chosen
* over; the ceiling before the first choice or with the policy off. Proposals from outside
* the head (prompt lookup) are held to it, so they add no deeper pass shape. */
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : next_depth(); }
/* T(depth, n): a decode step with deepest window `depth` and `n_rows` decode rows took `ms`
* since the end of the previous step. Fed by Scheduler::step_finished; adaptive policy only. */
void step_time(int depth, int n_rows, double ms);
/* Expected cost of a step at `depth` with `n_rows` rows: the key's mean (ms) if it has
* samples; else the nearest measured key scaled by the prior's ratio (1 + 0.06 d); else the
* unitless prior itself. */
double step_cost(int depth, int n_rows) const;
/* Samples behind a key: for tests and logs. */
int64_t cost_samples(int depth, int n_rows) const;
/* T(R): a drafting decode step of `q_rows` query rows (every sequence's verified token and
* its drafts) took `ms` since the end of the previous step, the head's rounds included. Fed
* by Scheduler::step_finished; adaptive policy only. */
void step_time(int q_rows, double ms);
/* Expected cost of a step of `q_rows` query rows (StepCost::cost): ms once anything is timed,
* else the unitless prior. */
double step_cost(int q_rows) const;
/* Samples behind a row count: for tests and logs. */
int64_t cost_samples(int q_rows) const;
/* E(d) for `s`'s current estimate: expected tokens emitted by a verify of d drafts, the
* verified token included. For tests and logs. */
@@ -205,15 +211,13 @@ private:
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
float prior_[RAD_SCHED_MAX_SPEC] = {};
int64_t prior_n_ = 0;
/* T(d, class): the mean step time of each key, and the steps behind it. */
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
/* T(R): drafting steps' times by query rows. */
StepCost cost_{kRowCost};
/* Fill a sequence's estimate from the prior and set its first stop. */
void start(DraftAdapt& s) const;
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
int stop_of(const float* a) const;
static int cost_class(int n_rows);
};
} /* namespace rad */
+131
View File
@@ -0,0 +1,131 @@
/* draft_depth.h -- same-step adaptive depth of a coupled serial draft chain (--draft-depth adaptive).
*
* A fixed chain drafts N tokens every step and its verify pays for N + 1 rows whatever the head
* thought of them. Here the chain of a step stops as soon as the head's own laws say the next draft
* is unlikely to be accepted: round j (j >= 2) runs only while the chain's confidence stays at or
* above the threshold,
*
* round j runs iff j <= max and ( j <= min or conf(j - 1 - lag) >= stop ),
* conf(m) = prod_{i = 1..m} s_i, conf(m <= 0) = 1,
*
* where s_i is read from round i's coupled state (abi/rad_spechub.h): the largest mass of the law
* Q_i the round drew from (`top`), or the mass of the token it drew (`path`, the probability of
* the drafted path). The first round that does not run ends the chain; its depth D is the number
* of rounds that ran, and the next verify carries D drafts (D + 1 rows).
*
* `lag` is how many rounds the decision trails the chain: with lag 0 round j is decided by every
* round before it, so the card waits for the host between two rounds; with lag 1 round j is decided
* when round j - 2 has finished, while round j - 1 runs, so the host's decision (a readback of one
* state row, then the next round's or the next verify's issue) hides behind a running round.
*
* Why this keeps the verify exact. The decision "x_j is drafted" reads Q_1 .. Q_{j-1-lag} and, for
* `path`, x_1 .. x_{j-1-lag}: draft-side quantities of the chain's ANCESTORS of x_j only, never a
* target output and never x_j itself. For a row-wise verify any such stopping time is exact (each
* verified position is exact on its own). For the traversal walk (abi/rad_mtp_traversal.h) the step
* of its induction at a node v needs v's number of children to be independent of the tokens drawn
* AT v; the shape of a child's subtree may depend on the child's own token, because the induction
* hypothesis is applied per child value. Here node v (the prefix x_1 .. x_{j-1}) has a child iff
* the rule above holds, a function of v's own path. A rule that read x_j's own mass to admit x_j
* would not be exact (tests/mtp_rrs_test.cpp shows the statistic that catches it, and one that
* peeks at the target).
*
* Plain code, no engine types beyond the wire row: the engine's driver, the scheduler's tests and
* the exactness test share it.
*/
#pragma once
#include <cstdint>
#include "rad_spechub.h"
namespace rad {
enum DraftDepthStat : int32_t {
DRAFT_DEPTH_TOP = 0, /* s_i = max_x Q_i(x) */
DRAFT_DEPTH_PATH = 1, /* s_i = Q_i(x_i), the drawn token's mass */
};
struct DraftDepthCfg {
bool on = false;
int max = 0; /* the deepest chain: rounds 1 .. max (the head's declared depth caps it) */
int min = 1; /* rounds that always run */
int lag = 1; /* rounds the decision trails the chain, 0 or more */
int stat = DRAFT_DEPTH_TOP;
double stop = 0.85; /* the chain goes on while conf >= stop */
int lawless = 3; /* the depth of a row with no law (a greedy request, a malformed round) */
};
/* One drafting row's chain while its step is drafted. */
struct DraftDepthRow {
double conf = 1.0; /* conf(seen) */
int seen = 0; /* rounds whose state went into conf */
int depth = 1; /* rounds decided to run so far (round 1 always does) */
bool done = false; /* a round was refused: depth is final */
bool lawless = false; /* no law: the fixed fallback depth */
};
/* Round `round`'s statistic from its state, or a negative number when the state carries no law
* (status != 1: a greedy row or a shortlist the proposer could not turn into Q). */
inline double draft_depth_stat(const RadMtpCoupleState& s, int round, int stat) {
if (s.status != 1 || s.round != round || s.count < 1 || s.count > 8) return -1.0;
double top = 0.0, own = -1.0;
for (int i = 0; i < s.count; ++i) {
const double q = s.q[i];
if (!(q > 0.0) || q > 1.0) return -1.0;
if (q > top) top = q;
if (s.ids[i] == s.x) own = q;
}
return stat == DRAFT_DEPTH_PATH ? own : top;
}
/* The round whose statistic decides round `j` (>= 2); <= 0 when nothing does (conf = 1). */
inline int draft_depth_need(const DraftDepthCfg& c, int j) { return j - 1 - (c.lag > 0 ? c.lag : 0); }
/* The start of a step's chain for one row. `lawless`: the row draws nothing (a greedy request). */
inline void draft_depth_begin(const DraftDepthCfg& c, DraftDepthRow* r, bool lawless) {
*r = DraftDepthRow{};
r->lawless = lawless;
(void)c;
}
/* Feed round `round`'s statistic (rounds in order, each once). A negative one makes the row lawless. */
inline void draft_depth_observe(DraftDepthRow* r, int round, double s) {
if (round != r->seen + 1) return;
r->seen = round;
if (s < 0.0) { r->lawless = true; return; }
r->conf *= s;
}
/* Whether round `j` (>= 2) runs for this row, given every statistic up to round
* draft_depth_need(c, j) was observed. Rounds are asked in order; once one is refused the chain has
* ended. Records the answer in r->depth / r->done. */
inline bool draft_depth_go(const DraftDepthCfg& c, DraftDepthRow* r, int j) {
if (r->done || j != r->depth + 1) return false;
bool go;
if (j > c.max) go = false;
else if (r->lawless) go = j <= (c.lawless > 0 ? c.lawless : 1);
else if (j <= c.min) go = true;
else {
/* conf(need): the row has seen exactly `need` rounds when asked in order with lag >= 0, or
* more when the caller observed ahead; recompute is not possible, so the caller observes
* no further than draft_depth_need before asking (the driver does). */
go = r->conf >= c.stop;
}
if (go) r->depth = j; else r->done = true;
return go;
}
/* The whole rule at once, for a chain whose statistics are all known (tests, offline): s[i] is
* round i + 1's, n of them (n >= max - 1 - lag is enough). Returns the depth D in [1, max]. */
inline int draft_depth_of(const DraftDepthCfg& c, const double* s, int n) {
DraftDepthRow r;
draft_depth_begin(c, &r, false);
for (int j = 2; j <= c.max; ++j) {
const int need = draft_depth_need(c, j);
while (r.seen < need && r.seen < n) draft_depth_observe(&r, r.seen + 1, s[r.seen]);
if (!draft_depth_go(c, &r, j)) break;
}
return r.depth < 1 ? 1 : r.depth;
}
} /* namespace rad */
+4 -40
View File
@@ -8,7 +8,7 @@ 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; }
cost_.reset(kRowCost);
proposed_ = held_ = held_drafts_ = held_hits_ = 0;
}
@@ -100,46 +100,10 @@ bool LookupGate::pays(double gain, int k, int64_t rows, double tokens) const {
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) { cost_.sample(rows, ms); }
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_.samples(rows); }
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);
}
double LookupGate::step_cost(int64_t rows) const { return cost_.cost(rows); }
} /* namespace rad */
+6 -16
View File
@@ -27,9 +27,10 @@
* 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.
* T is measured online over pure decode steps, keyed by rows (StepCost, step_cost.h). 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.
@@ -38,6 +39,7 @@
#include <cstdint>
#include "draft.h"
#include "step_cost.h"
#include "ngram.h"
namespace rad {
@@ -88,14 +90,6 @@ public:
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_; }
@@ -138,13 +132,9 @@ public:
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] = {};
StepCost cost_{kRowCost};
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;
};
+92
View File
@@ -13,6 +13,7 @@
#pragma once
#include <functional>
#include "mem/prefix.h"
#include "mem/seqwindow.h"
#include "rad_core.h"
#include "mm/processor.h"
@@ -153,6 +154,22 @@ struct IKVManager {
* changed tail, must be the only caller. 0 is always correct (restage the whole table). */
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
/* The batch builder's reads about (seq, group) in one call (SeqGroupView, mem/seqwindow.h).
* The default composes the accessors above, so a manager that does not override it answers
* identically; the concrete manager overrides it to find the sequence once. `take_changes`
* additionally performs take_table_changes (batch build only, as there). */
virtual void seq_group(uint64_t seq, int32_t group, bool take_changes,
SeqGroupView* out) const {
const std::vector<int32_t>& bt = block_table(seq, group);
out->bt = bt.data();
out->bt_n = bt.size();
out->first = first_block_pos(seq, group);
out->has_win = runtime_window(seq, group, &out->win);
if (!out->has_win) out->win = SeqWindow{};
out->state = state_slot(seq, group);
out->changed_from = take_changes ? take_table_changes(seq, group) : 0;
}
/* Whether the snapshot store still holds `slot`. The scheduler checks before building a
* restore step, since a released slot may hold another session's state. */
virtual bool checkpoint_held(int32_t slot) const = 0;
@@ -320,6 +337,78 @@ struct KVGeom {
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
}
/* Steps until trunc(x / bs) next changes as x increases: the run over which a quotient (and
* the matching C++ remainder, x - trunc(x/bs)*bs) stays affine. Truncation toward zero makes
* the negative side differ from floor: the quotient of a negative x next changes one past a
* multiple, not at it. */
static int64_t trunc_steps(int64_t x, int64_t bs) {
const int64_t q = x / bs;
return (q >= 0 ? (q + 1) * bs : q * bs + 1) - x;
}
/* slot() at n consecutive positions pos0, pos0+1, ..., identical values with one division a
* segment instead of two a token. A segment ends where the block index or the in-block
* offset would change rule (trunc_steps of (pos - first_pos) and of pos); inside it the slot
* is (block base + off + k), or -1 throughout when the block index is outside the table.
* bt is the table's data and length where slot() takes the vector. */
void slots(int gi, const int32_t* bt, size_t bt_n, int64_t first_pos, int64_t pos0,
int64_t n, int32_t* out) const {
const int64_t bs = g[(size_t)gi].block_size;
int64_t done = 0;
while (done < n) {
const int64_t pos = pos0 + done;
const int64_t rel = pos - first_pos;
const int64_t bi = rel / bs;
int64_t len = trunc_steps(rel, bs);
const int64_t lo = trunc_steps(pos, bs);
if (lo < len) len = lo;
if (len > n - done) len = n - done;
if (bi < 0 || (size_t)bi >= bt_n) {
for (int64_t k = 0; k < len; ++k) out[done + k] = -1;
} else {
const int64_t base = (int64_t)bt[(size_t)bi] * bs + pos % bs;
for (int64_t k = 0; k < len; ++k) out[done + k] = (int32_t)(base + k);
}
done += len;
}
}
/* slot_ring() at n consecutive positions, the same treatment. Positions before ring_pos go
* through slots(); in the ring the block index advances where (pos - ring_pos) crosses a
* block multiple, wrapping modulo ring_blocks at those same points. A window with no ring
* blocks cannot be armed (KVManager::set_window clamps the ring to at least one block and
* slot_ring's modulo would be by zero), so it takes the plain mapping. */
void slots_ring(int gi, const int32_t* bt, size_t bt_n, int64_t first_pos, int64_t pos0,
int64_t n, const SeqWindow& w, int32_t* out) const {
if (!w.set || w.ring_blocks <= 0) {
slots(gi, bt, bt_n, first_pos, pos0, n, out);
return;
}
const int64_t bs = g[(size_t)gi].block_size;
int64_t done = 0;
if (pos0 < w.ring_pos) {
done = w.ring_pos - pos0 < n ? w.ring_pos - pos0 : n;
slots(gi, bt, bt_n, first_pos, pos0, done, out);
}
const int64_t ring_bi0 = w.ring_pos / bs;
while (done < n) {
const int64_t pos = pos0 + done;
const int64_t rp = pos - w.ring_pos;
const int64_t bi = ring_bi0 + (rp / bs) % w.ring_blocks;
int64_t len = trunc_steps(rp, bs);
const int64_t lo = trunc_steps(pos, bs);
if (lo < len) len = lo;
if (len > n - done) len = n - done;
if (bi < 0 || (size_t)bi >= bt_n) {
for (int64_t k = 0; k < len; ++k) out[done + k] = -1;
} else {
const int64_t base = (int64_t)bt[(size_t)bi] * bs + pos % bs;
for (int64_t k = 0; k < len; ++k) out[done + k] = (int32_t)(base + k);
}
done += len;
}
}
};
/* ------------------------------------------------------------------ binding the concrete classes */
@@ -387,6 +476,9 @@ struct KVBinding final : IKVManager {
int64_t take_table_changes(uint64_t s, int32_t g) const override {
return m->take_table_changes(s, g);
}
void seq_group(uint64_t s, int32_t g, bool take, SeqGroupView* o) const override {
m->seq_group(s, g, take, o);
}
bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
};
+95 -2
View File
@@ -43,9 +43,14 @@ struct SchedMetrics {
* (Scheduler::step_next). Every other step leaves the card idle during the host's commit and
* staging. */
int64_t steps_ahead = 0;
/* Prefill chunks capped to leave room for decode rows or a waiting admission in the same
* step (--busy-prefill-chunk). Zero under `off`. */
/* Prefill chunks capped to leave room for other work in the same step, by the fixed busy
* policy or the adaptive mixed-step target. */
int64_t prefill_chunks_capped = 0;
/* --mixed-step-target-ms: mixed steps observed, those over their target, and the current
* seeded or learned aggregate prefill-row cap (0 when the policy is disabled). */
int64_t mixed_step_target_steps = 0;
int64_t mixed_step_target_misses = 0;
int64_t mixed_step_target_prefill_cap = 0;
/* Cumulative nanoseconds spent inside steps, total and for decode steps only. Wall time over
* a step count is not a step time: it charges idle gaps between requests to steps and mixes
@@ -159,6 +164,13 @@ struct SchedMetrics {
int64_t lookup_held = 0;
int64_t lookup_held_drafts = 0;
int64_t lookup_held_hits = 0;
/* --draft-suffix (suffix.h): verifies that carried a suffix chain, the rows they carried and the
* drafts accepted; decode steps not issued ahead because the sequence was in a recurring
* pattern (where the lookup could run after the commit instead). */
int64_t suffix_steps = 0;
int64_t suffix_rows = 0;
int64_t suffix_accepted = 0;
int64_t suffix_held_ahead = 0;
};
@@ -213,4 +225,85 @@ private:
double mean_ = 0.0; /* the rejection reference */
};
/* Feedback controller for --mixed-step-target-ms. Completed mixed-step service time includes the
* forward and drafter work, but not queueing or HTTP transport. Scale rows by target/observed when the
* target is missed; grow only after three representative steps below 95% of the target and by at
* most a quarter of the measured headroom. A one-quantum probe lets a conservative cap recover
* when fixed decode cost makes proportional scaling alone predict no larger legal chunk.
*
* The controller is deliberately model-agnostic. It may take a cap below an expert stager's
* throughput floor: satisfying an explicitly requested latency target while decoders are active
* is the point of the flag. With the flag off no caller consults it. */
struct MixedStepTarget {
void reset() { cap_ = 0; good_ = 0; }
/* A new server has no mixed-step timing yet. Begin at a conservative fraction of that
* model's declared mixed-step capacity instead of allowing one unbounded calibration miss;
* subsequent observations replace or grow this seed exactly like any learned cap. */
void seed(int64_t rows, int64_t quantum, int64_t max_rows) {
if (rows <= 0 || max_rows <= 0) return;
const int64_t q = quantum > 0 ? quantum : 1;
max_rows = std::max<int64_t>(q, max_rows / q * q);
rows = std::max<int64_t>(q, rows / q * q);
cap_ = std::min(rows, max_rows);
good_ = 0;
}
void observe(int64_t rows, int64_t ns, int64_t target_ns, int64_t quantum,
int64_t max_rows, bool representative = true) {
if (rows <= 0 || ns <= 0 || target_ns <= 0 || max_rows <= 0) return;
const int64_t q = quantum > 0 ? quantum : 1;
max_rows = max_rows / q * q;
if (max_rows < q) max_rows = q;
long double scaled = (long double)rows * (long double)target_ns / (long double)ns;
int64_t want = scaled >= (long double)max_rows ? max_rows : (int64_t)scaled;
want = want / q * q;
if (want < q) want = q;
if (cap_ == 0) {
cap_ = want;
good_ = 0;
return;
}
if (ns > target_ns) {
good_ = 0;
/* A prompt tail did not exercise a reusable limit. A checkpoint, fixed busy cap or
* other policy boundary still leaves the prompt unfinished and is representative:
* reducing this controller below that boundary can shorten the next mixed step. */
if (!representative) return;
/* A representative miss corrects immediately. */
if (want < cap_) cap_ = want;
return;
}
/* A short tail did not exercise the cap and cannot justify growing it. Near-target steps
* reset the recovery streak; three clearly fast full-cap samples earn one probe. */
if (!representative || ns * 20 >= target_ns * 19 || cap_ >= max_rows) {
good_ = 0;
return;
}
if (++good_ < 3) return;
good_ = 0;
const int64_t goal = std::max<int64_t>(want, std::min(max_rows, cap_ + q));
int64_t grow = (goal - cap_) / 4;
if (grow < q) grow = q;
cap_ = cap_ + grow;
cap_ = cap_ / q * q;
if (cap_ > goal) cap_ = goal;
if (cap_ > max_rows) cap_ = max_rows;
}
int64_t cap() const { return cap_; }
int64_t limit(int64_t budget, int64_t quantum) const {
if (cap_ <= 0 || budget <= 0) return budget;
const int64_t q = quantum > 0 ? quantum : 1;
const int64_t c = cap_ / q * q;
return c > 0 && c < budget ? c : budget;
}
private:
int64_t cap_ = 0;
int good_ = 0;
};
} /* namespace rad */
+383 -60
View File
@@ -57,6 +57,15 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
cfg_ = cfg;
kv_ = kv;
pc_ = pc;
/* THE STEP RECORD EXISTS ONLY FOR --diagnose. Sized here, once, and never on the serving
* path: 64 Ki steps is minutes of decode at any step rate this engine reaches and 2.5 MiB, and
* a record a step is work a serving process has no reader for. A reader that falls further
* behind is told how many it lost, not handed the wrong ones. The recorder is chosen here so
* the step path calls one instead of testing the mode on every step. */
if (cfg_.diagnose_mode()) {
step_ring_.reset(1u << 16);
record_step_ = &Scheduler::record_step;
}
/* The engine resolves the geometry once, because the prefix cache needs its checkpoint
* interval first; a caller without one (tests) resolves its own from prog and cfg. Both
@@ -143,10 +152,48 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
"prompt unfinished while other sequences decode, decode-only steps follow for up "
"to %.2f of the chunk step's measured time (at most %lld steps)",
cfg.prefill_interleave_share, (long long)kInterleaveAutoMax);
mixed_target_.reset();
m_.mixed_step_target_prefill_cap = 0;
if (cfg.mixed_step_target_ms > 0) {
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
/* A mixed step never receives a span's wide lone-prefill budget. Validate the same
* shared budget step() will use, or a spanned deployment can start even though no legal
* prefill quantum fits beside a decoder. */
const int64_t mixed_budget = geo_.shared_tok;
const int64_t draft_rows = 1 + std::max<int64_t>(cfg.n_spec, 0);
const int64_t mixed_floor = cfg.max_seqs > 1 ? Q + draft_rows : 0;
if ((cfg.busy_prefill_chunk > 0 && cfg.busy_prefill_chunk < Q) ||
(mixed_floor > 0 && mixed_budget < mixed_floor)) {
RAD_ERR("--mixed-step-target-ms needs room for one legal prefill quantum and "
"the active decode rows: quantum=%lld, max_seqs=%lld, draft_rows=%lld, "
"mixed_step_budget=%lld, max_num_batched_tokens=%lld, busy_prefill_chunk=%lld",
(long long)Q, (long long)cfg.max_seqs, (long long)draft_rows,
(long long)mixed_budget,
(long long)cfg.max_tok, (long long)cfg.busy_prefill_chunk);
return RAD_E_INVAL;
}
const int64_t max_prefill_quanta = mixed_budget > draft_rows
? (mixed_budget - draft_rows) / Q : 0;
if (cfg.max_seqs > 1 && cfg.max_seqs - 1 > max_prefill_quanta)
RAD_WARN("--mixed-step-target-ms: this batch budget can carry at most %lld legal "
"prefill quantum(s) beside a speculative decode row; with more simultaneous "
"prefills, priority and arrival order continue across later steps",
(long long)max_prefill_quanta);
mixed_target_.seed(std::max<int64_t>(Q, geo_.shared_tok / 4), Q, geo_.shared_tok);
m_.mixed_step_target_prefill_cap = mixed_target_.cap();
RAD_INFO("scheduler: --mixed-step-target-ms %lld: completed mixed steps teach an adaptive "
"aggregate prefill-row cap; while another sequence decodes the cap starts at "
"%lld rows and aims for a full mixed-step duration near %lld ms (a soft target)",
(long long)cfg.mixed_step_target_ms, (long long)mixed_target_.cap(),
(long long)cfg.mixed_step_target_ms);
}
interleave_left_ = 0;
ema_chunk_s_ = 0.0;
ema_decode_s_ = 0.0;
held_prefill_ = 0;
mixed_target_active_ = false;
mixed_target_prefill_planned_ = 0;
mixed_target_prefill_continues_ = false;
draft_refill_ = 0;
if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 &&
hit_holes_draft_) {
@@ -168,6 +215,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
DraftController::Params dp;
dp.max_depth = cfg.n_spec;
dp.head_depth = cfg.n_spec_head > 0 && cfg.n_spec_head < cfg.n_spec ? cfg.n_spec_head : 0;
/* The adaptive window (draft.h) prices a draft by the measured cost of the step it adds to.
* A block drafter proposes its block in one pass, but each verified draft is still a verify
* row, which is not free on a MoE that reads each row's routed experts. So it takes the same
@@ -296,16 +344,42 @@ void Scheduler::fini() {
/* ------------------------------------------------------------------ arrival */
int Scheduler::add(std::unique_ptr<Request> r) {
std::lock_guard<std::mutex> lk(mu_);
return add_locked(std::move(r));
int rc;
{
std::lock_guard<std::mutex> lk(mu_);
rc = add_locked(std::move(r));
}
wake();
return rc;
}
/* One lock for all of them, so the step that admits the first finds them all waiting. Otherwise a
* step could start between two adds and admit a timing-dependent subset, and the batch (and its
* tie-level rounding) would vary between identical runs. */
void Scheduler::add_all(std::unique_ptr<Request>* rs, size_t n, int* rc) {
std::lock_guard<std::mutex> lk(mu_);
for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i]));
{
std::lock_guard<std::mutex> lk(mu_);
for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i]));
}
wake();
}
uint64_t Scheduler::wake_seq() {
std::lock_guard<std::mutex> lk(wake_mu_);
return wake_n_;
}
void Scheduler::wait_idle(uint64_t seen, std::chrono::microseconds max) {
std::unique_lock<std::mutex> lk(wake_mu_);
wake_cv_.wait_for(lk, max, [&] { return wake_n_ != seen; });
}
void Scheduler::wake() {
{
std::lock_guard<std::mutex> lk(wake_mu_);
++wake_n_;
}
wake_cv_.notify_all();
}
int Scheduler::add_locked(std::unique_ptr<Request> r) {
@@ -315,6 +389,13 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
/* An embedding input runs in one step or not at all (Request::embed); one longer than a step
* could never be admitted. */
if (r->embed && (int64_t)r->prompt.size() > cfg_.max_tok) return RAD_E_INVAL;
/* The words a request hands the plugin are bounded by the plugin's declaration. The batch
* stage refuses a sequence past it, and a refused build restages the step forever -- an
* over-cap request admitted here would stall every queue behind it. The server-side route
* caps its own words; this is the promise no future route can miss. */
if (!r->plugin_words.empty() &&
(int64_t)r->plugin_words.size() > builder_.plugin_words_cap())
return RAD_E_INVAL;
/* Every prompt id, tokenised or client-supplied, names a real vocabulary row: an id past the
* embedding table is refused at admission, never staged into a pass. Raw id arrays reach here
* straight from the request body, and an op failing mid-step is a device fault (spec §17) --
@@ -535,6 +616,35 @@ int64_t Scheduler::reset_prefix_cache() {
return dropped;
}
int64_t Scheduler::evict_prefix_until(const std::function<bool()>& enough) {
std::lock_guard<std::mutex> lk(mu_);
if (!pc_ || !cfg_.prefix_cache) return 0;
int64_t total = 0;
/* Doubling, since the blocks that free the top of the pool may be anywhere in the LRU order. */
for (int64_t n = 64; !enough(); n *= 2) {
const int64_t done = pc_->trim(n);
if (done <= 0) break;
total += done;
}
/* What is left has no host copy to fall back on, or one still on its way. */
if (!enough()) {
const int64_t dropped = pc_->reset();
RAD_INFO("prefix cache: reset for room, %lld entries dropped", (long long)dropped);
total += dropped;
}
return total;
}
int Scheduler::preempt_until(const std::function<bool()>& enough) {
std::lock_guard<std::mutex> lk(mu_);
int n = 0;
while (!running_.empty() && !enough()) {
preempt_back();
++n;
}
return n;
}
int Scheduler::release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
SessionRelease* out) {
std::lock_guard<std::mutex> lk(mu_);
@@ -640,6 +750,7 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
/* Prompt lookup's index is this text's alone. */
s.ngram_ix.reset();
s.suffix_ix.reset();
if (lookup_gate_on_ && s.look.started && s.look.proposed > 0)
RAD_DEBUG("prompt lookup: request %llu made %lld proposals, held back %lld (%lld drafts, "
"%lld of those scored came true); a %d-draft verify costs %.2f plain steps",
@@ -748,6 +859,8 @@ int Scheduler::cancel(uint64_t id) {
* the request; then commit or sweep_deferred releases them (SchedReq::pending_free). */
const bool in_flight = in_step(s) || block_holds(id);
close_request(s, ReqState::Cancelled, "cancelled", in_flight);
/* The idle loop drains what a cancel releases. */
wake();
return RAD_OK;
}
@@ -977,6 +1090,24 @@ int Scheduler::draft_ngram(SchedReq& s, int depth, int* match) const {
LookupGate::kLongMatch);
}
/* --draft-suffix: SuffixDecoding's chain for the sequence's committed history (suffix.h). */
int Scheduler::suffix_propose(SchedReq& s, int32_t* out, int* match) {
if (match) *match = -1;
if (!s.req) return 0;
const Request& r = *s.req;
TokenSeq seq;
seq.a = r.prompt.data();
seq.na = (int64_t)r.prompt.size();
seq.b = r.output.data();
seq.nb = (int64_t)r.output.size();
const SuffixIndex::Out o =
s.suffix_ix.propose(seq, r.id, cfg_.draft_suffix_min_match,
std::min(cfg_.draft_suffix_max, (int)RAD_SCHED_MAX_SPEC),
cfg_.draft_suffix_min_score, out);
if (match && o.n > 0) *match = o.match;
return o.n;
}
/* ------------------------------------------------------------------ chunking */
int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target;
@@ -1241,23 +1372,24 @@ void Scheduler::set_stage_rows(int64_t rows) {
* about the size of the reserve, as the next step's whole chunk. When that would be under the
* floor, the interval is split into two chunks at or above the floor instead. */
int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget,
int64_t reserve, bool shared, bool rows_only) const {
int64_t reserve, bool shared, bool rows_only,
int64_t mixed_target_shares, int64_t mixed_target_decode_reserve) const {
const int64_t mode = cfg_.busy_prefill_chunk;
if (mode == 0 || budget <= 0) return budget;
if (budget <= 0 || (mode == 0 && !mixed_target_active_)) return budget;
/* Auto holds a chunk back only for work that would otherwise get nothing this step: rows
* behind it, or a request waiting to start. Rows planned ahead of it are in the step anyway.
* An explicit N trades prefill speed for every other row's latency, so it applies whenever
* the chunk shares the step. */
if (reserve <= 0 && !(mode > 0 && shared)) return budget;
if (reserve <= 0 && !(mode > 0 && shared) && !(mixed_target_active_ && shared)) return budget;
reserve = std::max<int64_t>(reserve, 0);
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
int64_t cap = budget - reserve;
int64_t cap = mode == 0 ? budget : budget - reserve;
if (mode > 0) {
/* The operator's number, with no floor; set_stage_rows warns when it is under the
* stager's step. */
cap = std::min(cap, mode);
} else {
} else if (mode < 0) {
const int64_t floor = std::max(Q, stage_rows_ / Q * Q);
cap = std::max(cap, floor);
const int64_t remaining = n_target - n_computed;
@@ -1274,6 +1406,25 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget
if (!rows_only && cap < span && span - cap < floor && span - floor >= floor)
cap = span - floor;
}
/* Apply the decoder reservation after the auto staging floor. Otherwise the floor can raise
* a reduced cap back to the whole budget, exclude the decoder, and prevent feedback. */
if (mixed_target_active_ && mixed_target_decode_reserve > 0)
cap = std::min(cap, budget - mixed_target_decode_reserve);
if (mixed_target_active_ && mixed_target_.cap() > 0) {
mixed_target_shares = std::max<int64_t>(0, mixed_target_shares);
/* Share the aggregate allowance evenly among this prefill and those expected later in
* the step. Stable queue order must not let the first request consume the cap while the
* others receive only a minimum quantum on every step. If the learned cap cannot hold
* one quantum apiece, the effective allowance grows just enough to make progress; this
* may miss an impossible target, but it cannot silently starve a queued prompt. */
const int64_t floor = mixed_target_prefill_planned_ + (mixed_target_shares + 1) * Q;
const int64_t allowance = std::max(mixed_target_.cap(), floor);
const int64_t left = std::max<int64_t>(0, allowance - mixed_target_prefill_planned_);
const int64_t participants = mixed_target_shares + 1;
const int64_t fair = left / participants / Q * Q;
if (fair < Q || cap < Q) return 0;
cap = std::min(cap, fair);
}
return std::min(std::max(cap, Q), budget);
}
@@ -1340,7 +1491,8 @@ bool Scheduler::preempt_back() {
/* ------------------------------------------------------------------ admission */
/* Admission checks the KV budget before a request enters running; a request admitted without the
* blocks to run would be preempted on its first step, a full recompute for nothing. */
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve,
int64_t mixed_target_shares) {
Request& r = *s.req;
/* A REQUEST THAT WAS PREEMPTED WAITS FOR ROOM FOR THE WHOLE RECOMPUTE, plus one block of
@@ -1357,12 +1509,14 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
++rounds;
/* Nothing else is running, so a missing state slot will not come back by waiting.
* Put leaked slots back, then admit. A recompute the empty pool cannot hold is
* failed below (spec §17) rather than left in kAdmitWait, which parks the engine. */
if (!preempted_can_prefill(s) && running_.empty())
* failed below (spec §17) rather than left in kAdmitWait, which parks the engine.
* A request this pass has just admitted is not in running_ yet, and it runs. */
if (!preempted_can_prefill(s) && running_.empty() && took_.empty())
(void)kv_->release_idle_states();
}
if (!preempted_can_prefill(s)) {
if (!(running_.empty() && preempt_wait_overdue(s) && kv_->can_ever_fit(s.seq_len())))
if (!(running_.empty() && took_.empty() && preempt_wait_overdue(s) &&
kv_->can_ever_fit(s.seq_len())))
return kAdmitWait;
}
}
@@ -1563,11 +1717,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
/* An admission shares the step the same way: otherwise a cold prompt with requests
* queued behind it takes every token left. The hit is known by now, so the cap applies
* to what really has to run. */
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
false, mixed_target_shares, 0);
const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
if (want <= 0 && cap < budget && prog_->encoder.bidirectional &&
(!mixed_target_active_ || r.media))
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
else if (cap < budget && want > 0)
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at, &r);
@@ -1651,31 +1807,58 @@ void Scheduler::undo_hit(SchedReq& s) {
bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
const Request& r = *s.req;
const int64_t target = s.seq_len();
/* What the recompute adopts from the cache (its own prefix, published at the preemption) needs
* no new block. */
const int64_t hit = (cfg_.prefix_cache && pc_) ? pc_->lookup(r, nullptr, nullptr).n_attn_tokens : 0;
for (size_t g = 0; g < kvgeom_.g.size(); ++g) {
const KVGeom::G& gg = kvgeom_.g[g];
/* A group the manager gives no blocks (the sentinel at index 0) asks nothing. Counting it
* wanted the whole prompt from a pool of none and kept a preempted request out for good. */
if (!gg.paged || kv_->total_blocks((int32_t)g) <= 0) continue;
int64_t need = (target + gg.block_size - 1) / gg.block_size -
(int64_t)kv_->block_table(r.id, (int32_t)g).size() - hit / gg.block_size;
if (need < 0) need = 0;
for (int32_t slot : running_) {
const SchedReq& rs = *reqs_[(size_t)slot];
if (!rs.req) continue;
const Request& rr = *rs.req;
int64_t goal = rr.n_computed + 1;
if (rr.n_computed < (int64_t)rr.prompt.size())
goal = std::max(goal, (int64_t)rr.prompt.size());
const int64_t rows = (goal + gg.block_size - 1) / gg.block_size;
const int64_t held = (int64_t)kv_->block_table(rr.id, (int32_t)g).size();
if (rows > held) need += rows - held;
need += 1; /* one block past that, so the next step is not the victim */
/* Whether the pools hold the recompute plus every runner's remaining need, given `hit` tokens
* of prefix the recompute adopts without new blocks. */
auto enough = [&](int64_t hit) {
for (size_t g = 0; g < kvgeom_.g.size(); ++g) {
const KVGeom::G& gg = kvgeom_.g[g];
/* A group the manager gives no blocks (the sentinel at index 0) asks nothing. Counting
* it wanted the whole prompt from a pool of none and kept a preempted request out for
* good. */
if (!gg.paged || kv_->total_blocks((int32_t)g) <= 0) continue;
int64_t need = (target + gg.block_size - 1) / gg.block_size -
(int64_t)kv_->block_table(r.id, (int32_t)g).size() - hit / gg.block_size;
if (need < 0) need = 0;
for (int32_t slot : running_) {
const SchedReq& rs = *reqs_[(size_t)slot];
if (!rs.req) continue;
const Request& rr = *rs.req;
int64_t goal = rr.n_computed + 1;
if (rr.n_computed < (int64_t)rr.prompt.size())
goal = std::max(goal, (int64_t)rr.prompt.size());
const int64_t rows = (goal + gg.block_size - 1) / gg.block_size;
const int64_t held = (int64_t)kv_->block_table(rr.id, (int32_t)g).size();
if (rows > held) need += rows - held;
need += 1; /* one block past that, so the next step is not the victim */
}
if (need > kv_->available_blocks((int32_t)g)) return false;
}
if (need > kv_->available_blocks((int32_t)g)) return false;
return true;
};
/* The hash-chain lookup costs the request's length in CPU, and this gate runs per waiting
* slot per scheduling round, under mu_. The zero-credit count answers "yes" without it
* whenever the pools plainly hold the recompute; the lookup is consulted only when the
* credit decides, which is precisely when the gate is about to deny anyway. */
if (!enough(0)) {
if (!cfg_.prefix_cache || !pc_) return false;
/* Credit what the recompute ADOPTS, not the raw attention hit: admit_one clamps the
* attention hit to the linear hit under checkpoints -- the linear layers replay from the
* checkpoint regardless of how deep the attention matched -- and never adopts the whole
* prompt, one token staying for the logits. Crediting deeper than admission adopts
* subtracts blocks the recompute will really need: the preempted request is admitted
* against a loan it cannot repay, the next ensure preempts it again, and that is the
* loop this gate exists to stop. The exact-mode grid floor is folded in as a bound too
* -- crediting less than admission adopts only delays a re-admission by one round,
* crediting more reopens the loop. */
const CacheHit h = pc_->lookup(r, nullptr, nullptr);
int64_t hit = h.n_attn_tokens;
if (geo_.checkpoints() && h.n_linear_tokens < hit) hit = h.n_linear_tokens;
if (geo_.exact && hit > 0) hit = geo_.grid_floor(hit);
const int64_t last = target - 1;
if (hit > last) hit = last;
if (hit < 0) hit = 0;
if (!enough(hit)) return false;
}
/* Stateful groups: the recompute needs its state slots back, and every running sequence must
@@ -1716,6 +1899,8 @@ const RadBatch* Scheduler::step() {
plan_.spec_is_tree = tree_;
step_prefill_tok_ = 0;
step_decode_tok_ = 0;
mixed_target_prefill_planned_ = 0;
mixed_target_prefill_continues_ = false;
/* A preempted prefill waits for the whole-recompute gate so it cannot loop. That wait is
* bounded here, for every overdue preempted request, not only the queue head: a head that
@@ -1806,7 +1991,7 @@ const RadBatch* Scheduler::step() {
bool any_decoding = false;
bool hold_prefill = false;
held_prefill_ = 0;
if (cfg_.prefill_interleave != 0) {
if (cfg_.prefill_interleave != 0 || cfg_.mixed_step_target_ms > 0) {
for (int32_t slot : running_) {
const SchedReq& s = *reqs_[(size_t)slot];
if (!s.req || !s.running) continue;
@@ -1816,8 +2001,9 @@ const RadBatch* Scheduler::step() {
break;
}
if (!any_decoding) interleave_left_ = 0;
hold_prefill = interleave_left_ > 0;
hold_prefill = cfg_.prefill_interleave != 0 && interleave_left_ > 0;
}
mixed_target_active_ = cfg_.mixed_step_target_ms > 0 && any_decoding;
/* A span is for a prefill alone in its step (ChunkGeometry::span). A spanned step takes as
* long as the intervals it carries, so a decode row riding along would wait that long for its
@@ -1861,11 +2047,12 @@ const RadBatch* Scheduler::step() {
* to be walked needs 1 + the deepest window it can take, each prefill row a share, plus one
* share when a request waits and a slot is free. Counted down as the loop walks, so a row's
* reserve is what is behind it. */
const bool share_step = cfg_.busy_prefill_chunk != 0;
const bool share_step = cfg_.busy_prefill_chunk != 0 || mixed_target_active_;
const int64_t Q = std::max<int64_t>(geo_.quantum, 1);
/* An eighth of this step's budget, which under a span is shared_tok for a shared step. */
const int64_t share_tok = std::max<int64_t>(Q, budget / 8 / Q * Q);
const int64_t dec_row_tok = 1 + std::max<int64_t>(depth, draft_.step_window());
const int64_t dec_row_tok = 1 + std::max<int64_t>({ (int64_t)depth, (int64_t)draft_.step_window(),
cfg_.draft_suffix ? (int64_t)cfg_.draft_suffix_max : 0 });
int64_t behind_dec = 0, behind_pf = 0;
if (share_step) {
for (int32_t slot : running_) {
@@ -1875,6 +2062,10 @@ const RadBatch* Scheduler::step() {
if (pf) ++behind_pf; else behind_dec += dec_row_tok;
}
}
const int64_t admit_room = std::min<int64_t>(
(int64_t)free_cards_.size(), cfg_.max_seqs - (int64_t)running_.size());
const int64_t mixed_target_waits = mixed_target_active_
? std::min<int64_t>((int64_t)waiting_.size(), std::max<int64_t>(0, admit_room)) : 0;
const bool admit_waits = share_step && !waiting_.empty() && !free_cards_.empty() &&
(int64_t)running_.size() < cfg_.max_seqs;
/* The first prefill chunk held back this step (its index in plan_.e before the sort) and what
@@ -1918,13 +2109,15 @@ const RadBatch* Scheduler::step() {
if (prefill && hold_prefill) { ++held_prefill_; ++i; continue; }
if (prefill) {
const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0;
const int64_t mixed_target_shares = mixed_target_active_ ? behind_pf + mixed_target_waits : 0;
const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
/*rows_only=*/shares == 0);
/*rows_only=*/shares == 0, mixed_target_shares, behind_dec);
const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r);
/* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */
if (want <= 0 && cap < budget && prog_->encoder.bidirectional)
if (want <= 0 && cap < budget && prog_->encoder.bidirectional &&
(!mixed_target_active_ || r.media))
want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r);
else if (cap < budget && want > 0 && capped_at < 0) {
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
@@ -1948,7 +2141,24 @@ const RadBatch* Scheduler::step() {
* drafts this step and no deeper. */
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
bool ngram = false;
if (!r.may_speculate) s.n_draft = 0;
bool suffix = false;
/* --draft-suffix: a sequence whose own history ends in a recurring pattern verifies that
* pattern's earlier continuation in place of the head's draft (the head still drafted
* behind the step before, so a miss costs nothing but that draft). A function of the
* committed text alone, so the choice never reads a draw; the rows it verifies carry no
* coupled state (Request::draft_suffix below), so each is the target's plain draw. */
if (cfg_.draft_suffix && r.may_speculate) {
int32_t buf[RAD_SCHED_MAX_SPEC];
const int np = suffix_propose(s, buf);
if (np > 0) {
std::copy(buf, buf + np, s.draft);
s.n_draft = np;
s.draft_tree = false;
suffix = true;
}
}
if (suffix) ngram = true;
else if (!r.may_speculate) s.n_draft = 0;
else if (s.n_draft == 0) {
/* As the only drafter under the adaptive window, the lookup is the head: its
* proposal is cut to the sequence's own window. */
@@ -1976,6 +2186,7 @@ const RadBatch* Scheduler::step() {
}
if (!ngram && s.n_draft > cap) s.n_draft = cap;
s.draft_ngram = ngram;
s.draft_suffix = suffix;
/* No verified position at or past the context end: nothing past ctx_limit_ - 1 has a
* rotary row or block-table column. commit() finishes a sequence before it reaches
* the limit, so the one token itself always fits. */
@@ -2021,8 +2232,13 @@ const RadBatch* Scheduler::step() {
preempted_here = true;
if (last) { yielded = true; break; }
}
/* close_request or preempt_back removed it from running_; i now indexes the next. */
if (failed || yielded) continue;
/* close_request or preempt_back removed it from running_; i now indexes the next. A chunk
* marked as held back has no entry after all, and the mark would name whichever comes next
* or none. */
if (failed || yielded) {
if (capped_at == (int32_t)plan_.e.size()) capped_at = -1;
continue;
}
StepEntry e;
e.req = &r;
@@ -2050,6 +2266,11 @@ const RadBatch* Scheduler::step() {
e.n_draft = s.n_draft;
e.is_prefill = prefill;
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
e.suffix = e.ngram && s.draft_suffix;
/* A suffix chain has no model node: the coupled sampler binds no state to any row of it
* (core/sample/sampler.cpp), whatever stale state the head's own draft for these positions
* left. */
r.draft_suffix = e.suffix;
/* A tree drafter's parents, unless prompt lookup replaced its proposal with a chain. */
e.draft_parent = (!prefill && s.draft_tree && !e.ngram) ? s.draft_par : nullptr;
r.draft_parent = e.n_spec ? e.draft_parent : nullptr;
@@ -2065,6 +2286,9 @@ const RadBatch* Scheduler::step() {
s.sched_tokens = (int32_t)want;
plan_.e.push_back(e);
plan_.n_tok += want;
if (prefill && mixed_target_active_) {
mixed_target_prefill_planned_ += want;
}
if (!prefill && s.n_draft > plan_.n_spec) plan_.n_spec = s.n_draft;
budget -= want;
++i;
@@ -2109,7 +2333,15 @@ const RadBatch* Scheduler::step() {
? share_tok : 0;
admit_full_ = 0;
admit_next_step_ = false;
const int as = admit_one(s, budget, areserve);
const int64_t mixed_target_shares = mixed_target_active_
? std::min<int64_t>(
(int64_t)waiting_.size() - (int64_t)at - 1,
std::min<int64_t>(
cfg_.max_seqs - (int64_t)plan_.e.size() - 1,
(int64_t)free_cards_.size() - 1))
: 0;
const int as = admit_one(s, budget, areserve,
std::max<int64_t>(0, mixed_target_shares));
/* A preempted request waiting for its whole-recompute gate lets the next one be asked;
* an overdue one does not. The room the overdue path made this step is for it, and a
* request queued behind it would take that room back: a victim just forced off for it,
@@ -2128,8 +2360,9 @@ const RadBatch* Scheduler::step() {
* the refusal is a restore waiting a step for deferred releases: both clear by the
* next step, and failing them lost two of ten preempted requests under KV pressure
* once their prompts were published at the preemption (1. 11. 2026). */
if (as < 0 && running_.empty() && plan_.e.empty() && !admit_next_step_ && s.req &&
s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) {
if (as < 0 && running_.empty() && took_.empty() && plan_.e.empty() &&
!admit_next_step_ && s.req && s.req->state == ReqState::Preempted &&
preempt_wait_overdue(s)) {
RAD_WARN("request %llu failed: overdue preempted prefill could not be admitted "
"with nothing running (%s)",
(unsigned long long)s.req->id, rad_strerror(as));
@@ -2172,6 +2405,9 @@ const RadBatch* Scheduler::step() {
s.entry = (int32_t)plan_.e.size();
plan_.e.push_back(e);
plan_.n_tok += s.sched_tokens;
if (mixed_target_active_) {
mixed_target_prefill_planned_ += s.sched_tokens;
}
budget -= s.sched_tokens;
took_.push_back(at);
++at;
@@ -2201,6 +2437,11 @@ const RadBatch* Scheduler::step() {
* to it at most. */
int64_t limit = std::min(capped_full, had + budget);
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
if (mixed_target_active_ && mixed_target_.cap() > 0) {
const int64_t other = std::max<int64_t>(0, mixed_target_prefill_planned_ - had);
const int64_t left = std::max<int64_t>(0, mixed_target_.cap() - other);
limit = std::min(limit, std::max(had, left));
}
int64_t ckpt = -1;
const int64_t grown = e.ckpt_slot < 0 && limit > had
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at, &r)
@@ -2211,6 +2452,7 @@ const RadBatch* Scheduler::step() {
if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1));
s.sched_tokens = (int32_t)grown;
plan_.n_tok += grown - had;
if (mixed_target_active_) mixed_target_prefill_planned_ += grown - had;
budget -= grown - had;
}
if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped;
@@ -2248,6 +2490,11 @@ const RadBatch* Scheduler::step() {
plan_.phase = any_pf && n_dec ? RAD_PHASE_MIXED
: any_pf ? RAD_PHASE_PREFILL
: RAD_PHASE_DECODE;
if (mixed_target_active_) {
mixed_target_prefill_continues_ = false;
for (const StepEntry& e : plan_.e)
if (e.is_prefill && !e.produces_token) mixed_target_prefill_continues_ = true;
}
/* Step-shape counters. `steps_mixed` / `steps` shows how often a step carries both kinds of
* row. `decode_rows_unspeculated` counts every decode row that took no draft, whatever the
@@ -2473,6 +2720,10 @@ const RadBatch* Scheduler::step_next_locked() {
* that cannot rewind decides at commit whether the next step may speculate; one that can,
* or no grammar, keeps its answer. */
if (!e.produces_token || !r.speculation_fixed) return nullptr;
/* --draft-suffix: a sequence whose history ended in a recurring pattern at the last commit
* is likely to continue it; its next step is built after the commit, where the lookup can
* read the committed end (a step issued ahead is made on the card from the head's drafts). */
if (cfg_.draft_suffix && s.suffix_hot) { ++m_.suffix_held_ahead; return nullptr; }
/* A SCORED row (Request::token_scores, a /v1/systemone question) that the step in flight
* brings to max_tokens gets no step issued ahead: it would run a whole forward pass for a
* request that finishes at the commit, and max_tokens=1 pays a decode step after its
@@ -2578,6 +2829,8 @@ void Scheduler::promote_next() {
int Scheduler::commit(StepResult& res) {
std::lock_guard<std::mutex> lk(mu_);
if (!step_open_) return RAD_E_STATE;
/* The step's tokens are pushed at one time (Sink::push). */
const int64_t pushed_ns = server::sink_now_ns();
/* StepResult's counts describe this step only. */
step_finished_ = 0;
last_prefill_ids_.clear();
@@ -2660,7 +2913,7 @@ int Scheduler::commit(StepResult& res) {
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
? &res.lp[res.first_row[i]] : nullptr;
if (lp && lp->token < 0) lp_failed = true;
else overflowed = !server::sink_push(r.sink, res.token[i], lp);
else overflowed = !server::sink_push(r.sink, res.token[i], lp, pushed_ns);
/* The conv window absorbed this chunk; the cursor advances one committed
* position, as in decode. */
s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
@@ -2719,7 +2972,7 @@ int Scheduler::commit(StepResult& res) {
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
? &res.lp[res.first_row[i] + j] : nullptr;
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
if (!server::sink_push(r.sink, t, lp, pushed_ns)) overflowed = true;
};
/* On a tree step the accepted drafts are the path's nodes, in path order. */
const int32_t* path = res.path ? res.path + (size_t)i * RAD_SCHED_MAX_SPEC : nullptr;
@@ -2761,6 +3014,11 @@ int Scheduler::commit(StepResult& res) {
draft_.yield(s.adapt, now), est);
}
}
if (e.suffix) {
++m_.suffix_steps;
m_.suffix_rows += e.n_spec;
m_.suffix_accepted += a;
}
m_.draft_tokens += e.n_spec;
m_.draft_accepted += a;
server::sink_drafts(r.sink, e.n_spec, a);
@@ -2768,7 +3026,16 @@ int Scheduler::commit(StepResult& res) {
}
s.n_draft = 0;
r.n_draft = 0;
s.draft_suffix = false;
r.draft_suffix = false;
s.entry = -1;
/* --draft-suffix: does the history now end in a pattern that recurred? (step_next_locked) */
if (cfg_.draft_suffix && e.produces_token && r.state == ReqState::Running) {
int32_t buf[RAD_SCHED_MAX_SPEC];
s.suffix_hot = r.may_speculate && suffix_propose(s, buf) > 0;
} else {
s.suffix_hot = false;
}
/* A request the next step carries finishes now but keeps its blocks, which that step
* writes; its commit finds the request not running and returns them. */
@@ -2840,6 +3107,18 @@ int Scheduler::commit(StepResult& res) {
*
* Host timing, always available. Per-op device timing adds synchronisations that change the
* mover's slot supply, so profiled runs are not comparable (spec §16). */
void Scheduler::record_step(int64_t ns, int64_t end_ns) {
diag::StepRecord r;
r.step = m_.steps;
r.phase = plan_.phase;
r.n_seq = (int32_t)plan_.e.size();
r.prefill_tok = (int32_t)step_prefill_tok_;
r.decode_tok = (int32_t)step_decode_tok_;
r.ns = ns;
r.end_ns = end_ns;
step_ring_.push(r);
}
void Scheduler::step_finished() {
std::lock_guard<std::mutex> lk(mu_);
if (step_start_.time_since_epoch().count() == 0) return; /* no step has run */
@@ -2848,6 +3127,9 @@ void Scheduler::step_finished() {
const int64_t ns =
std::chrono::duration_cast<std::chrono::nanoseconds>(step_end - step_start_).count();
m_.step_ns += ns;
mixed_target_observe_locked(ns);
(this->*record_step_)(ns, std::chrono::duration_cast<std::chrono::nanoseconds>(
step_end.time_since_epoch()).count());
if (plan_.phase == RAD_PHASE_DECODE) {
m_.step_ns_decode += ns;
/* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step
@@ -2892,20 +3174,61 @@ void Scheduler::step_finished() {
for (const StepEntry& e : plan_.e) rows += e.is_prefill ? 0 : e.n_tokens;
if (rows > 0) lookup_.step_time(rows, wall * 1e3);
}
/* The step's cost at its depth, for the adaptive window (draft.h): the same wall time,
* including the draft rounds after it, with a step issued ahead counted once. Decode steps
* only. Keyed by the deepest window the step verified, which is the head depth it ran at
* whenever D held from the step before. */
/* The step's cost by query rows, for the adaptive window (draft.h): the same wall time,
* including the draft rounds after it, with a step issued ahead counted once. Drafting decode
* steps only: a step that verified nothing ran no head round. */
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
int rows = 0;
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
int64_t rows = 0;
for (const StepEntry& e : plan_.e) rows += e.is_prefill ? 0 : e.n_tokens;
if (rows > 0) draft_.step_time((int)rows, wall * 1e3);
}
last_step_at_ = step_end;
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
step_start_ = {};
}
/* The mixed-step target's one timing entry point. `step_finished` supplies the live bracket;
* note_mixed_step_cost supplies a deterministic bracket to scheduler tests and host simulations. */
void Scheduler::mixed_target_observe_locked(int64_t ns) {
int64_t rows = 0;
for (const StepEntry& e : plan_.e) if (e.is_prefill) rows += e.n_tokens;
if (cfg_.mixed_step_target_ms <= 0 || plan_.phase != RAD_PHASE_MIXED ||
rows <= 0 || plan_.n_seq_decode <= 0 || ns <= 0) return;
const int64_t target_ns = cfg_.mixed_step_target_ms * 1000000ll;
++m_.mixed_step_target_steps;
if (ns > target_ns) ++m_.mixed_step_target_misses;
const int64_t before = mixed_target_.cap();
mixed_target_.observe(rows, ns, target_ns, std::max<int64_t>(geo_.quantum, 1),
geo_.shared_tok, mixed_target_prefill_continues_);
m_.mixed_step_target_prefill_cap = mixed_target_.cap();
if (mixed_target_.cap() != before && (int)log_level() >= (int)Log::Debug)
RAD_DEBUG("scheduler: mixed-step target observed %.2f ms over %lld prefill token(s); "
"adaptive mixed-prefill cap %lld -> %lld for a %lld ms target",
(double)ns / 1e6, (long long)rows, (long long)before,
(long long)mixed_target_.cap(), (long long)cfg_.mixed_step_target_ms);
}
void Scheduler::note_mixed_step_cost(int64_t ns) {
std::lock_guard<std::mutex> lk(mu_);
mixed_target_observe_locked(ns);
}
uint64_t Scheduler::step_record_count() const {
std::lock_guard<std::mutex> lk(mu_);
return step_ring_.count();
}
size_t Scheduler::step_record_capacity() const {
std::lock_guard<std::mutex> lk(mu_);
return step_ring_.capacity();
}
uint64_t Scheduler::step_records(uint64_t from, std::vector<diag::StepRecord>* out) const {
std::lock_guard<std::mutex> lk(mu_);
return step_ring_.copy_since(from, out);
}
/* ------------------------------------------------------------------ the serial drafter */
/* Which sequences may take a serial draft after the step just run, and what each needs. Called
* while plan() still describes that step, since everything here indexes into it: the head reads
+75 -2
View File
@@ -17,8 +17,11 @@
#include "lookup.h"
#include "metrics.h"
#include "ngram.h"
#include "suffix.h"
#include "diag/diagnose.h"
#include <chrono>
#include <condition_variable>
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
#include <functional>
#endif
@@ -80,6 +83,8 @@ struct SchedReq {
void drafter_reset() {
n_draft = 0;
draft_next = 0;
draft_suffix = false;
suffix_hot = false;
conv_cursor = 0;
draft_filled = 0;
draft_lo = 0;
@@ -91,6 +96,13 @@ struct SchedReq {
DraftAdapt adapt;
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
bool draft_ngram = false;
/* --draft-suffix (suffix.h): the proposal the step being planned carries is a suffix chain
* (StepEntry::suffix); and whether the last commit left the sequence's history ending in a
* recurring pattern, which keeps the next step from being issued ahead (it is built after the
* commit, where the lookup can run). */
bool draft_suffix = false;
bool suffix_hot = false;
SuffixIndex suffix_ix;
/* 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. */
@@ -201,6 +213,12 @@ public:
/* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with
* its result in rc[i]. For the sequences of one API request, which must reach the same step. */
void add_all(std::unique_ptr<Request>* rs, size_t n, int* rc);
/* The step loop's idle wait. wake_seq() before a step() that finds nothing, then
* wait_idle(seen, max): it returns at once if anything woke the loop since `seen` (a request
* added or cancelled, or wake()), else after `max` at the latest. */
uint64_t wake_seq();
void wait_idle(uint64_t seen, std::chrono::microseconds max);
void wake();
/* Frees blocks immediately rather than at completion (spec §14); otherwise the pool shrinks
* under exactly the load that cancels. */
int cancel(uint64_t id);
@@ -223,6 +241,17 @@ public:
void take_completed(std::vector<uint64_t>* out);
int reap(uint64_t id);
/* ---------------------------------------------------------- the step record (--diagnose)
*
* One diag::StepRecord per committed step, in a ring sized at init and only with --diagnose: a
* serving process keeps no ring and records nothing. A reader takes every step a phase ran --
* its shape and its time -- without a second clock. Both calls take the lock; `step_records`
* appends what came after `from` and returns how many of those the ring overwrote before they
* were read (diag/diagnose.h). */
uint64_t step_record_count() const;
size_t step_record_capacity() const; /* 0 without --diagnose */
uint64_t step_records(uint64_t from, std::vector<diag::StepRecord>* out) const;
/* ---------------------------------------------------------- the lock, for the engine
*
* Every mutation of the KV manager and the prefix cache happens under this lock; neither has
@@ -309,6 +338,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();
/* Least recently used entries leave VRAM until `enough()` (called under the step lock) holds
* or the whole cache has gone; an entry with a host copy stays restorable as long as that
* gives enough room. Returns how many went.
* The step lock, with nothing in flight reading the blocks. */
int64_t evict_prefix_until(const std::function<bool()>& enough);
/* Running requests go back to the queue by recompute, youngest first, their blocks freed,
* until `enough()` (called under the step lock) holds or none runs: the fleet takes a
* lower-priority model's cache while it is busy (docs/MULTIMODEL.md §6.4). Between steps
* only, with nothing in flight. Returns how many went back. */
int preempt_until(const std::function<bool()>& enough);
/* 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);
@@ -357,6 +396,9 @@ public:
* so the draft rounds are charged to the step (see the definition). Without it the counters
* stay correct but there is no timing. */
void step_finished();
/* Feed the open mixed step a completed service time, as step_finished does. Visible for
* deterministic scheduler tests and timed host simulations. */
void note_mixed_step_cost(int64_t ns);
/* ---------------------------------------------------- the serial drafter (spec §10)
*
@@ -497,7 +539,8 @@ public:
* and `shared` says rows are already planned ahead of it. Returns `budget` when
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
bool shared = false, bool rows_only = false) const;
bool shared = false, bool rows_only = false,
int64_t mixed_target_shares = 0, int64_t mixed_target_decode_reserve = 0) const;
/* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime
* window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a
* recompute replays runs one token a step: the ring rewrites its slots in place, so a
@@ -618,6 +661,9 @@ private:
* 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;
/* --draft-suffix: the suffix proposal for `s`'s next step, over its committed history, into
* `out` (RAD_SCHED_MAX_SPEC entries). Returns its length, 0 for none. */
int suffix_propose(SchedReq& s, int32_t* out, int* match = nullptr);
/* 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;
@@ -639,6 +685,14 @@ private:
mutable std::mutex mu_;
/* wake_seq/wait_idle/wake. */
std::mutex wake_mu_;
std::condition_variable wake_cv_;
uint64_t wake_n_ = 0;
SchedMetrics metrics_locked() const;
int requests_locked(ReqStat* out, int max) const;
/* The published copy and its lock (publish()). The scratch pair is the engine thread's, filled
@@ -775,6 +829,13 @@ private:
* throughput window; metrics() decays what it reports by this. */
std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now();
int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0;
/* The step record, picked once at init: with --diagnose the ring is sized and record_step is
* written into it, without it step_finished calls a no-op. One indirect call a step, no test
* of the mode and no ring on the serving path. Callers of step_finished hold mu_. */
void record_step(int64_t ns, int64_t end_ns);
void record_no_step(int64_t, int64_t) {}
void (Scheduler::*record_step_)(int64_t, int64_t) = &Scheduler::record_no_step;
diag::StepRing step_ring_;
/* --prefill-interleave: decode-only steps still owed before the next chunk, and how many
* prefilling requests the last step() held back. step_next_locked stops issuing ahead once
* the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */
@@ -787,6 +848,17 @@ private:
static constexpr int64_t kInterleaveAutoMax = 64;
double ema_chunk_s_ = 0.0, ema_decode_s_ = 0.0;
void step_cost_locked(bool chunk, double seconds);
/* --mixed-step-target-ms: learned mixed-step cap and whether this planning pass has a decoder
* whose output latency the cap protects. */
MixedStepTarget mixed_target_;
bool mixed_target_active_ = false;
/* Aggregate prefill rows already admitted to this mixed step. The learned cap is a budget
* for the step, not a per-request allowance. */
int64_t mixed_target_prefill_planned_ = 0;
/* At least one prefill in the issued mixed step has work beyond this chunk. Unlike a true
* prompt tail, a policy or checkpoint-limited chunk is representative feedback. */
bool mixed_target_prefill_continues_ = false;
void mixed_target_observe_locked(int64_t ns);
/* The throughput window (step_finished): each kind's tokens and the wall time the steps
* covered, both decayed with the same time constant, so their ratio is tokens over time. */
double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0;
@@ -850,7 +922,8 @@ private:
/* 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);
int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0,
int64_t mixed_target_shares = 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;
+97
View File
@@ -0,0 +1,97 @@
/* step_cost.h -- a decode step's wall time as a function of its query rows, measured online.
*
* A decode step's cost moves with the rows it carries (each sequence's verified token and its
* drafts): the routed experts and every other weight read per row. Both speculation policies
* weigh a draft's expected yield against that cost (lookup.h, draft.h), and both need the cost of
* row counts they have not run yet. So step times are kept by row count: a timed count is its
* mean; one between two timed counts lies on the line between them; one outside them is the
* nearest timed count scaled by a prior shape, 1 + row_cost (R - 1); with nothing timed it is
* that shape itself, unitless. Only ratios of costs are used.
*
* Row counts move by themselves as sequences come and go, so a policy holding one window still
* times its neighbours' row counts without ever trying them.
*/
#pragma once
#include <cmath>
#include <cstdint>
namespace rad {
class StepCost {
public:
/* A running mean for the first samples, then a moving average with a half-life of 32 steps:
* long enough to average out one-off costs (a tier copy, a recording, a prefix-cache trim),
* short enough to follow a context growing by a few thousand tokens over a reply. */
static constexpr double kHalfLife = 32.0;
/* 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. Below 4 samples the mean is not
* a trustworthy reference to clip against. */
static constexpr double kOutlier = 4.0;
static constexpr int64_t kClipAfter = 4;
/* Row counts are kept exactly up to 128, then in bands of 32. */
enum { kExact = 128, kBand = 32, kKeys = 160 };
/* `row_cost` is the prior shape's slope: the share of a one-row step each further row adds. */
explicit StepCost(double row_cost = 0.0) : row_cost_(row_cost) {}
/* Forgets every sample and takes a slope. */
void reset(double row_cost) {
row_cost_ = row_cost;
for (int k = 0; k < kKeys; ++k) { r_[k] = 0.0; ms_[k] = 0.0; n_[k] = 0; }
}
/* A step of `rows` query rows took `ms`. Nonsense is not a sample. */
void sample(int64_t rows, double ms) {
if (rows < 1 || !(ms > 0.0) || !std::isfinite(ms)) return;
const int k = key(rows);
double& m = ms_[k];
double& r = r_[k];
int64_t& n = n_[k];
if (n >= kClipAfter && ms > kOutlier * m) ms = kOutlier * m;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kHalfLife), 1.0 / (double)(n + 1));
m = n ? m + w * (ms - m) : ms;
r = n ? r + w * ((double)rows - r) : (double)rows;
++n;
}
/* The expected wall time of a step of `rows` rows: ms once anything is timed, else the
* unitless prior. */
double 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 < kKeys; ++k) {
if (n_[k] <= 0) continue;
if (r_[k] <= R) lo = k;
if (r_[k] >= R && hi < 0) hi = k;
}
if (lo >= 0 && hi >= 0) {
const double r0 = r_[lo], r1 = r_[hi];
if (lo == hi || r1 <= r0) return ms_[lo];
return ms_[lo] + (ms_[hi] - ms_[lo]) * (R - r0) / (r1 - r0);
}
if (lo >= 0) return ms_[lo] * prior(R) / prior(r_[lo]);
if (hi >= 0) return ms_[hi] * prior(R) / prior(r_[hi]);
return prior(R);
}
/* Samples behind a row count's key: for tests and logs. */
int64_t samples(int64_t rows) const { return n_[key(rows)]; }
private:
double row_cost_ = 0.0;
double r_[kKeys] = {}; /* mean rows of the samples in each key */
double ms_[kKeys] = {};
int64_t n_[kKeys] = {};
static int key(int64_t rows) {
if (rows < 1) rows = 1;
if (rows <= kExact) return (int)(rows - 1);
const int64_t k = kExact + (rows - kExact - 1) / kBand;
return (int)(k < kKeys ? k : kKeys - 1);
}
double prior(double rows) const { return 1.0 + row_cost_ * (rows - 1.0); }
};
} /* namespace rad */
+172
View File
@@ -0,0 +1,172 @@
/* suffix.h -- SuffixDecoding's proposal for a hybrid step selector (--draft-suffix, DESIGN-suffix.md).
*
* SuffixDecoding (Oliaro et al., arXiv 2411.04975) drafts from a suffix tree of earlier text: for
* the longest suffix of the current context that occurred before, it expands the tokens that
* followed, each node scored by the product of its followers' frequencies (D, the expected number of
* accepted tokens along its path). Here the tree is the per-request one (prompt ++ output of THIS
* request; an offline study found a cross-request tree adds nothing on this workload), reduced to what
* a chain needs:
*
* - the earlier occurrence comes from the existing NgramIndex (the --spec-ngram matcher): the
* latest earlier occurrence of the longest recurring suffix of `min_match..min_match+3` tokens;
* - the frequency rule comes from two count tables over `min_match`-token contexts: how often a
* context was followed by anything, and by each token. A proposal token at depth j has
* C_j = count(context_j + token_j) / count(context_j) with context_j the last `min_match`
* tokens of the sequence extended by the proposal so far, and the chain is cut where its path
* score D_j = prod C_i falls under `min_score`.
*
* It is a heuristic and only that: every proposed token is verified (the sampler's own draw must
* equal it), so a collision in the tables, a stale count or a wrong match changes how many tokens a
* step lands, never which tokens come out. The tables key on 64-bit hashes and store 32 bits of the
* key; a clash merges two contexts' counts.
*
* The index is incremental: each call indexes the tokens committed since the last one, prompt
* included at the first, so a sequence is indexed once over its lifetime. Memory is about 8 bytes a
* token per table and per NgramIndex pattern length (4 lengths).
*/
#pragma once
#include "ngram.h"
#include <cstdint>
#include <vector>
namespace rad {
class SuffixIndex {
public:
/* NgramIndex tries pattern lengths min_match .. min_match + kExtra, longest first: the proposal
* follows the latest occurrence of the longest recurring suffix in that range. */
enum { kExtra = 3, kMaxK = 12 };
/* Forget the sequence; `owner` is the request id the next lookups are for. */
void reset(uint64_t owner = 0) {
ix_.reset(owner);
followed_.clear();
follow_.clear();
filled_ = 0;
k_ = 0;
}
uint64_t owner() const { return ix_.owner(); }
struct Out {
int n = 0; /* tokens proposed */
int match = 0; /* how far the match behind the proposal runs back (>= min_match) */
float score = 0.0f; /* D of the last proposed node: the chance the whole chain is taken */
float expect = 0.0f; /* sum of D along the chain: expected accepted tokens */
};
/* The proposal for `seq`: at most `max_rows` tokens into `out` (the index is brought up to the
* sequence first). n == 0 when the last `min_match` tokens did not occur before, or the first
* token's own score is under `min_score`. 1 <= min_match <= kMaxK. */
Out propose(const TokenSeq& seq, uint64_t owner, int min_match, int max_rows, float min_score,
int32_t* out) {
Out r;
if (min_match < 1 || min_match > kMaxK || max_rows < 1 || seq.size() <= min_match) return r;
if (ix_.owner() != owner || k_ != min_match) { reset(owner); k_ = min_match; }
const int64_t L = seq.size();
if (L < filled_) { reset(owner); k_ = min_match; }
index_to(seq, L);
int match = 0;
const int n = ix_.propose(seq, min_match, min_match + kExtra, max_rows, out, &match, 64);
if (n <= 0) return r;
/* Score the chain: the context moves forward over the proposal's own tokens. */
int32_t win[kMaxK];
for (int i = 0; i < k_; ++i) win[i] = seq[L - k_ + i];
float d = 1.0f, sum = 0.0f;
int m = 0;
for (; m < n; ++m) {
const uint64_t h = hash_ctx(win, k_);
const uint32_t a = followed_.get(h);
const uint32_t b = follow_.get(mix(h, (uint64_t)(uint32_t)out[m]));
if (a == 0 || b == 0) break; /* a path the history never took */
const float c = (float)b / (float)a;
if (d * c < min_score) break;
d *= c;
sum += d;
for (int i = 0; i + 1 < k_; ++i) win[i] = win[i + 1];
win[k_ - 1] = out[m];
}
r.n = m;
r.match = match;
r.score = m > 0 ? d : 0.0f;
r.expect = sum;
return r;
}
int64_t indexed() const { return filled_; }
size_t bytes() const { return ix_.bytes() + (followed_.t.capacity() + follow_.t.capacity()) * 8; }
private:
/* Open addressing; an entry is key (the high 32 bits of a 64-bit hash, never 0) << 32 | count.
* The probe starts from the stored key, so a rehash needs nothing else. */
struct Table {
std::vector<uint64_t> t;
uint64_t mask = 0;
int64_t n = 0;
void clear() { t.clear(); t.shrink_to_fit(); mask = 0; n = 0; }
static uint32_t key_of(uint64_t h) { return (uint32_t)(h >> 32) | 1u; }
static uint64_t start(uint32_t key) { return ((uint64_t)key * 0x9e3779b97f4a7c15ull) >> 29; }
uint32_t get(uint64_t h) const {
if (t.empty()) return 0;
const uint32_t key = key_of(h);
for (uint64_t i = start(key) & mask;; i = (i + 1) & mask) {
const uint64_t e = t[i];
if (e == 0) return 0;
if ((uint32_t)(e >> 32) == key) return (uint32_t)e;
}
}
void bump(uint64_t h) {
if (t.empty() || (uint64_t)(n + 1) * 2 > mask + 1) grow();
const uint32_t key = key_of(h);
for (uint64_t i = start(key) & mask;; i = (i + 1) & mask) {
uint64_t& e = t[i];
if (e == 0) { e = (uint64_t)key << 32 | 1u; ++n; return; }
if ((uint32_t)(e >> 32) == key) { if ((uint32_t)e != 0xffffffffu) ++e; return; }
}
}
void grow() {
std::vector<uint64_t> old;
old.swap(t);
const uint64_t cap = old.empty() ? 1024 : (mask + 1) * 2;
t.assign(cap, 0);
mask = cap - 1;
for (uint64_t e : old) {
if (!e) continue;
for (uint64_t i = start((uint32_t)(e >> 32)) & mask;; i = (i + 1) & mask)
if (t[i] == 0) { t[i] = e; break; }
}
}
};
NgramIndex ix_;
Table followed_; /* a k-token context -> how many times anything followed it */
Table follow_; /* a k-token context and a token -> how many times that token did */
int64_t filled_ = 0; /* positions < filled_ are counted */
int k_ = 0;
static uint64_t mix(uint64_t h, uint64_t v) {
h ^= v + 0x9e3779b97f4a7c15ull + (h << 6) + (h >> 2);
h *= 0xff51afd7ed558ccdull;
h ^= h >> 32;
return h;
}
static uint64_t hash_ctx(const int32_t* t, int k) {
uint64_t h = 0x84222325cbf29ce4ull;
for (int i = 0; i < k; ++i) h = mix(h, (uint64_t)(uint32_t)t[i]);
return h;
}
/* Count, for every position e in [filled_, upto) with k tokens before it, the context
* seq[e-k..e-1] followed by seq[e]. */
void index_to(const TokenSeq& seq, int64_t upto) {
int32_t win[kMaxK];
for (int64_t e = filled_ < k_ ? k_ : filled_; e < upto; ++e) {
for (int i = 0; i < k_; ++i) win[i] = seq[e - k_ + i];
const uint64_t h = hash_ctx(win, k_);
followed_.bump(h);
follow_.bump(mix(h, (uint64_t)(uint32_t)seq[e]));
}
filled_ = upto;
}
};
} /* namespace rad */