sched: a bound on the preempted-prefill gate's wait

This commit is contained in:
baKon authored and StillDeadcode committed 2026-10-30 10:21:57 +01:00
1 parent 0792d86375
commit 33108e488b
16 files changed
+1522 -150

No files matched your search

+81 -9
View File
@@ -39,7 +39,7 @@ static const std::string g_draft_window_help =
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
" --num-speculative-tokens every step; adaptive makes that\n"
" the ceiling and follows each sequence's acceptance and the\n"
" measured step cost (a serial draft head only). Default ") +
" measured step cost (a draft head, or prompt lookup alone). Default ") +
draft_window_name(kDraftWindowDefault);
static const Flag g_flags[] = {
@@ -73,6 +73,10 @@ static const Flag g_flags[] = {
{ "--prefill-interleave", "N", "decode-only steps after each prefill chunk while other\n"
"sequences decode, at most 64; 0 (default) lets every step\n"
"carry a chunk" },
{ "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n"
"recompute gate before reclaiming cache blocks and\n"
"preempting the lowest-priority running request; 0\n"
"(default 5000) falls back on the next step" },
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
@@ -117,6 +121,16 @@ static const Flag g_flags[] = {
{ "--weights-disk-tier", nullptr, "read weights that fit neither VRAM nor the host pool from the\n"
" container on disk (O_DIRECT); a routed expert is read a layer\n"
" at a time, so a step is paced by the drive" },
{ "--row-prefetch", "MODE", "on (default) | off -- a host gather from a table read through\n"
" the container's mapping (--ngram-placement disk) asks for the\n"
" pages its rows cover before its kernel runs, or beside it when\n"
" they are already resident; off leaves every row to the\n"
" kernel's own page faults. The output is the same either way" },
{ "--mapped-rewarm", "MODE", "on (default) | off -- at startup, ask the page cache again for\n"
" the pages of a table read through the container's mapping\n"
" that an earlier run left cached and the load's own\n"
" allocations pushed out, at most half of the available memory,\n"
" so the first requests do not read them from the drive" },
{ "--prefix-cache-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n"
" so their VRAM can go to experts and a return restores\n"
" instead of re-prefilling. A full tier drops its least\n"
@@ -181,6 +195,15 @@ static const Flag g_flags[] = {
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
" own operating point, which the plugin states. A container\n"
" with no draft head is unaffected -- auto resolves to 0." },
{ "--spec-ngram", "K", "speculate by prompt lookup alone: up to K drafts a step\n"
" copied from what followed the latest earlier occurrence of\n"
" the sequence's last n tokens (no weights, no draft pass).\n"
" Sets the window to K; a draft head the container carries is\n"
" not loaded. A proposal is verified only when its record\n"
" says it pays at the measured step cost. 0 (default) off" },
{ "--spec-ngram-min", "N", "shortest pattern prompt lookup matches (default 2)" },
{ "--spec-ngram-max", "N", "longest pattern prompt lookup matches, tried first\n"
"(default 4, at most 15)" },
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
"from N decoding sequences on (0 never): the long block pays\n"
@@ -298,6 +321,13 @@ static const Flag g_flags[] = {
{ "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" },
{ "--debug-selection", nullptr, "print the selection table" },
{ "--debug-placement", nullptr, "print the placement plan" },
{ "--debug-tape-dump", nullptr, "list the dispatches of the first recorded pass of each kind\n"
" on stderr (TAPEDUMP lines, every rank) and which of them\n"
" start unordered behind the one before" },
{ "--debug-draft-oracle", "FILE", "a verify-path test, not a drafter: with --spec-ngram, prompt\n"
" lookup proposes from the token ids in FILE (a plain greedy\n"
" run's continuation of the one prompt the test sends), 30% of\n"
" the drafts corrupted; the text must stay the plain run's" },
{ "--debug-accept-reference-kernels", nullptr,
"serve even when ops resolve only to a reference library. NOT a production configuration: the reference\n"
" implementation is an oracle and a last resort, and falling back\n"
@@ -518,6 +548,7 @@ int config_parse(int argc, char** argv, Config* c) {
else if (!parse_int(a.c_str(), v, 1, INT64_MAX, &c->busy_prefill_chunk)) return RAD_E_INVAL;
}
else if (S("--prefill-interleave")) { if (!num(0, 64, &c->prefill_interleave)) return RAD_E_INVAL; }
else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; }
else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; }
else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; }
else if (S("--rope-scaling")) {
@@ -617,6 +648,24 @@ int config_parse(int argc, char** argv, Config* c) {
c->tower_placement = p;
}
else if (S("--weights-disk-tier")) { c->weights_disk_tier = true; }
else if (S("--row-prefetch")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "on")) c->row_prefetch = true;
else if (!std::strcmp(v, "off")) c->row_prefetch = false;
else {
RAD_ERR("--row-prefetch takes on or off, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--mapped-rewarm")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "on")) c->mapped_rewarm = true;
else if (!std::strcmp(v, "off")) c->mapped_rewarm = false;
else {
RAD_ERR("--mapped-rewarm takes on or off, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--prefix-cache-mib")) { if (!num(0, INT32_MAX, &c->prefix_cache_mib)) return RAD_E_INVAL; }
else if (S("--prefix-cache-ttl")) { if (!num(0, INT32_MAX, &c->prefix_cache_ttl)) return RAD_E_INVAL; }
else if (S("--lora")) {
@@ -732,6 +781,9 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
c->n_spec = (int)n;
}
else if (S("--spec-ngram")) { if (!num(0, 64, &c->spec_ngram)) return RAD_E_INVAL; }
else if (S("--spec-ngram-min")) { if (!num(1, 15, &c->spec_ngram_min)) return RAD_E_INVAL; }
else if (S("--spec-ngram-max")) { if (!num(1, 15, &c->spec_ngram_max)) return RAD_E_INVAL; }
else if (S("--draft-window")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
@@ -769,14 +821,7 @@ int config_parse(int argc, char** argv, Config* c) {
}
else if (S("--host")) { if (!(v = need(i))) return RAD_E_INVAL; c->host = v; }
else if (S("--port")) { if (!num(0, 65535, &c->port)) return RAD_E_INVAL; }
else if (S("--api-key")) {
if (!(v = need(i))) return RAD_E_INVAL;
/* An empty key is no key: --api-key "" or --api-key "$UNSET_VAR" must not start a
* server that looks guarded and answers everything keyless. */
if (!*v) { RAD_ERR("--api-key takes a non-empty key; an empty value guards nothing");
return RAD_E_INVAL; }
c->api_key = v;
}
else if (S("--api-key")) { if (!(v = need(i))) return RAD_E_INVAL; c->api_key = v; }
else if (S("--served-model-name")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!*v) { RAD_ERR("--served-model-name takes a non-empty name"); return RAD_E_INVAL; }
@@ -962,6 +1007,8 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; }
else if (S("--debug-selection")) c->debug_selection = true;
else if (S("--debug-placement")) c->debug_placement = true;
else if (S("--debug-tape-dump")) c->debug_tape_dump = true;
else if (S("--debug-draft-oracle")) { if (!(v = need(i))) return RAD_E_INVAL; c->debug_draft_oracle = v; }
else if (S("--debug-accept-reference-kernels")) c->accept_reference_kernels = true;
else if (S("--profile-ops")) c->profile_ops = true;
else if (S("--expert-stats")) { if (!(v = need(i))) return RAD_E_INVAL; c->expert_stats = v; }
@@ -1021,6 +1068,22 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
/* Prompt lookup alone: the window is its K, stated once. */
if (c->spec_ngram_min > c->spec_ngram_max) {
RAD_ERR("--spec-ngram-min %d is longer than --spec-ngram-max %d", c->spec_ngram_min,
c->spec_ngram_max);
return RAD_E_INVAL;
}
if (c->spec_ngram > 0) {
if (c->given.count("--num-speculative-tokens") && c->n_spec != c->spec_ngram) {
RAD_ERR("--spec-ngram %d sets the speculative window to %d, and "
"--num-speculative-tokens asks for %s; give one", c->spec_ngram,
c->spec_ngram, c->n_spec < 0 ? "auto" : std::to_string(c->n_spec).c_str());
return RAD_E_INVAL;
}
c->n_spec = c->spec_ngram;
}
/* KL mode: exactly one direction, each with the inputs it reads. */
if (!c->kld_record.empty() && !c->kld_ref.empty()) {
RAD_ERR("--kld-record writes a reference and --kld-ref scores against one; give one");
@@ -1177,6 +1240,7 @@ const ShowRow kShow[] = {
: c.busy_prefill_chunk == 0 ? std::string("off") : num(c.busy_prefill_chunk); } },
{ "--prefill-interleave", [](const Config& c) {
return c.prefill_interleave > 0 ? num(c.prefill_interleave) : std::string("off"); } },
{ "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } },
{ "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } },
{ "--max-model-len", [](const Config& c) {
return c.max_ctx ? num(c.max_ctx) : std::string("0 (the model's training context)"); } },
@@ -1196,6 +1260,8 @@ const ShowRow kShow[] = {
return c.ngram_share_dir.empty() ? v : v + "=" + c.ngram_share_dir; } },
{ "--vision-tower-placement", [](const Config& c) { return std::string(table_placement_name(c.tower_placement)); } },
{ "--weights-disk-tier", [](const Config& c) { return onoff(c.weights_disk_tier); } },
{ "--row-prefetch", [](const Config& c) { return onoff(c.row_prefetch); } },
{ "--mapped-rewarm", [](const Config& c) { return onoff(c.mapped_rewarm); } },
{ "--prefix-cache-mib", [](const Config& c) {
return c.prefix_cache_mib ? num(c.prefix_cache_mib) : std::string("0 (off)"); } },
{ "--prefix-cache-ttl", [](const Config& c) {
@@ -1227,6 +1293,10 @@ const ShowRow kShow[] = {
return std::string(c.prefix_exact ? "exact" : "nearest"); } },
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
{ "--spec-ngram", [](const Config& c) {
return c.spec_ngram > 0 ? num(c.spec_ngram) : std::string("0 (off)"); } },
{ "--spec-ngram-min", [](const Config& c) { return num(c.spec_ngram_min); } },
{ "--spec-ngram-max", [](const Config& c) { return num(c.spec_ngram_max); } },
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
{ "--draft-short-from", [](const Config& c) {
return c.draft_short_from < 0 ? std::string("auto")
@@ -1309,6 +1379,8 @@ const ShowRow kShow[] = {
{ "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } },
{ "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } },
{ "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } },
{ "--debug-tape-dump", [](const Config& c) { return onoff(c.debug_tape_dump); } },
{ "--debug-draft-oracle", [](const Config& c) { return or_none(c.debug_draft_oracle, "none"); } },
{ "--debug-accept-reference-kernels", [](const Config& c) { return onoff(c.accept_reference_kernels); } },
{ "--profile-ops", [](const Config& c) { return onoff(c.profile_ops); } },
{ "--expert-stats", [](const Config& c) { return or_none(c.expert_stats, "off"); } },
+60
View File
@@ -59,6 +59,9 @@ struct KernelRow {
bool reference = false;
/* rad_kernel_chain: its launches can wait in the kernel instead of behind the barrier bit. */
bool chain = false;
/* rad_kernel_fetches_rows: it reads a mapped table's rows itself, so the engine does not read
* them ahead through the page cache (runtime/rowprefetch.h). */
bool fetches_rows = false;
};
/* A kernel bound to one geometry, one domain and one variant, with init() already run. */
@@ -214,6 +217,9 @@ struct WeightInfo {
void* ptr = nullptr;
void* host_ptr = nullptr;
uint64_t file_offset = 0;
/* Each selected plane's offset in the container (file_offset is plane_offset[0]), for a
* file-tier weight the loader relayouts on every read (weight_file_relaid). */
uint64_t file_plane_offset[RAD_ENC_MAX_PLANES] = {0};
/* First and last op index that read the weight. Prefetch runs off these, so layer offload is
* scheduling rather than prediction (spec §5). */
@@ -532,6 +538,30 @@ public:
};
/* The kernel whose layout hook settled `w`'s stored form, or null when it is stored as is or
* widened. */
inline const RadKernelInfo* weight_layout_kernel(const Program& prog, const WeightInfo& w) {
if (w.identity || w.widen || w.lay_op < 0 || (size_t)w.lay_op >= prog.ops.size()) return nullptr;
const OpInfo& op = prog.ops[(size_t)w.lay_op];
if (w.lay_band < 0 || (size_t)w.lay_band >= op.bands.size() || w.lay_dom < 0 ||
w.lay_dom >= RAD_N_DOMAINS)
return nullptr;
const KernelRow* row = op.bands[(size_t)w.lay_band].dom[w.lay_dom].row;
return row ? row->info : nullptr;
}
/* Whether the file tier can serve `w` by relayouting it on every read, as the loader does once
* for a resident weight: whole planes (no shard at a world above one, so each plane is one range
* of the container), not widened, and a kernel that relayouts. The selected planes are read from
* the container and the kernel's relayout writes the stored form into the pinned stage the copy
* to the card reads. The mapped tier cannot do this: it hands kernels the container's bytes. */
inline bool weight_file_relaid(const Program& prog, const WeightInfo& w, int world_size) {
if (w.identity || w.widen) return false;
if (w.decl.shard != RAD_SHARD_NONE && world_size > 1) return false;
const RadKernelInfo* ki = weight_layout_kernel(prog, w);
return ki && ki->relayout;
}
/* ================================================================== requests */
enum class ReqState { Waiting, Running, Preempted, Finished, Failed, Cancelled };
@@ -814,6 +844,10 @@ struct Config {
* the chunk at N tokens on such a step. See Scheduler::step, docs/GUIDE.md. */
int64_t busy_prefill_chunk = -1;
int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks */
/* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate
* before the scheduler evicts cache blocks and preempts a lower-priority running request to
* make room for it. 0 = fall back on the next step; default 5000 ms. */
int64_t preempt_wait_ms = 5000;
int64_t max_seqs = 256;
int64_t max_ctx = 0; /* 0 = the model's training context */
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
@@ -859,6 +893,14 @@ struct Config {
* exact prefetch, a routed expert a routed layer at a time). Off by default because disk
* paces the step, so an accidental spill makes the server orders of magnitude slower. */
bool weights_disk_tier = false;
/* --row-prefetch on|off: a host gather's rows on the mapped tier (a table on disk, read
* through the container's mapping) are asked for ahead of its kernel (runtime/rowprefetch.h,
* CtxDesc::row_prefetch). Output-neutral; on is the default. */
bool row_prefetch = true;
/* --mapped-rewarm on|off: at startup, the mapped tier's pages an earlier run left in the page
* cache and the load's allocations reclaimed are asked for again, at most half of
* MemAvailable (RadFile::rewarm). Output-neutral; on is the default. */
bool mapped_rewarm = true;
std::string placement = "auto"; /* all_vram | layer_offload | expert_tiered | auto */
/* --embedding-placement and --ngram-placement as given (see TablePlacement), and their
@@ -958,6 +1000,18 @@ struct Config {
* and rad-tune read the same operating point; defaulting to off would pay for the head in
* VRAM and still decode one token a step. */
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
/* --spec-ngram K: speculate by prompt lookup alone, K drafts a step (core/sched/ngram.h), each
* proposal verified only when it pays for its verify rows (core/sched/lookup.h).
* Sets the window to K and tells the plugin to declare no draft head
* (RadBuildCtx::draft_head_off), so a head the container carries costs no memory. 0 (the
* default) is off: a deployment that speculates still uses prompt lookup for any sequence its
* head declines, and a container without a head speculates by prompt lookup at
* --num-speculative-tokens N. */
int spec_ngram = 0;
/* The pattern lengths prompt lookup tries, longest first (--spec-ngram-min/--spec-ngram-max),
* wherever it runs. */
int spec_ngram_min = 2;
int spec_ngram_max = 4;
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
/* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in
* the step just run; 0 never. -1, auto: never for a chain, and from two for a tree
@@ -1092,6 +1146,12 @@ struct Config {
bool debug_graph = false;
bool debug_selection = false;
bool debug_placement = false;
/* --debug-tape-dump: each rank lists the dispatches of the first recorded pass of each kind
* (CtxDesc::tape_dump). */
bool debug_tape_dump = false;
/* --debug-draft-oracle FILE: prompt lookup proposes from these token ids, 30% of its drafts
* corrupted -- the verify path's test harness (Scheduler::draft_ngram). Empty is off. */
std::string debug_draft_oracle;
bool profile_ops = false;
/* --expert-stats FILE: count the routed experts every layer selects, by step kind, and write
* the counts to FILE as JSON every 30 s and at shutdown (place/xstats.h). Empty is off. */
+145
View File
@@ -0,0 +1,145 @@
/* lookup.cpp -- the prompt-lookup verify gate. See lookup.h. */
#include "lookup.h"
#include <cmath>
namespace rad {
void LookupGate::configure(int max_depth) {
max_depth_ = max_depth < 0 ? 0 : (max_depth > RAD_SCHED_MAX_SPEC ? RAD_SCHED_MAX_SPEC : max_depth);
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
for (int k = 0; k < kCostKeys; ++k) { cost_r_[k] = 0.0; cost_ms_[k] = 0.0; cost_n_[k] = 0; }
proposed_ = held_ = held_drafts_ = held_hits_ = 0;
}
/* ------------------------------------------------------------------ one sequence */
void LookupGate::start(LookupSeq& q) const {
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) {
q.s[0][j] = (float)kPriorShort;
q.s[1][j] = (float)kPriorLong;
}
q.n[0] = q.n[1] = 0;
q.pend_pos = -1;
q.pend_len = q.pend_done = q.pend_cls = 0;
q.pend_held = q.last_taken = false;
q.proposed = q.held = q.held_drafts = q.held_hits = 0;
q.started = true;
}
double LookupGate::expect(LookupSeq& q, int cls, int k) const {
if (!q.started) start(q);
if (cls < 0 || cls > 1) cls = 0;
if (k > RAD_SCHED_MAX_SPEC) k = RAD_SCHED_MAX_SPEC;
double e = 0.0;
for (int j = 0; j < k; ++j) e += (double)q.s[cls][j];
return e;
}
void LookupGate::offer(LookupSeq& q, int64_t pos, const int32_t* prop, int n, int match) const {
if (!q.started) start(q);
if (n <= 0 || !prop) return;
++q.proposed;
++proposed_;
q.last_taken = false;
if (q.pend_pos >= 0) return; /* one at a time: it resolves within n tokens, usually one */
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
q.pend_pos = pos;
q.pend_len = n;
q.pend_done = 0;
q.pend_cls = class_of(match);
q.pend_held = false;
q.last_taken = true;
for (int j = 0; j < n; ++j) q.pend[j] = prop[j];
}
void LookupGate::held(LookupSeq& q, int n) const {
if (n <= 0) return;
++q.held;
q.held_drafts += n;
++held_;
held_drafts_ += n;
if (q.last_taken) q.pend_held = true;
}
void LookupGate::fold(LookupSeq& q, int cls, int len, int hits) const {
/* Position j came true iff j < hits: the survival estimate S_j sees every evaluated
* proposal, not only those that reached j. */
const double w = std::fmax(alpha_, 1.0 / ((double)q.n[cls] + kPriorWeight + 1.0));
for (int j = 0; j < len; ++j) {
const double x = j < hits ? 1.0 : 0.0;
q.s[cls][j] = (float)((double)q.s[cls][j] + w * (x - (double)q.s[cls][j]));
}
if (q.n[cls] < UINT16_MAX) ++q.n[cls];
}
void LookupGate::advance(LookupSeq& q, const TokenSeq& seq) const {
if (!q.started || q.pend_pos < 0) return;
const int64_t len = seq.size();
while (q.pend_done < q.pend_len && q.pend_pos + q.pend_done < len) {
if (seq[q.pend_pos + q.pend_done] != q.pend[q.pend_done]) break;
++q.pend_done;
}
const bool missed = q.pend_done < q.pend_len && q.pend_pos + q.pend_done < len;
if (!missed && q.pend_done < q.pend_len) return; /* agrees so far; more tokens to come */
fold(q, q.pend_cls, q.pend_len, q.pend_done);
if (q.pend_held) {
q.held_hits += q.pend_done;
held_hits_ += q.pend_done;
}
q.pend_pos = -1;
}
/* ------------------------------------------------------------------ the step */
bool LookupGate::pays(double gain, int k, int64_t rows, double tokens) const {
if (k <= 0 || !(gain > 0.0)) return false;
if (rows < 1) rows = 1;
if (tokens < 1.0) tokens = 1.0;
const double t0 = step_cost(rows);
const double t1 = step_cost(rows + k);
/* (tokens + gain) / t1 > tokens / t0 */
return gain * t0 > tokens * (t1 - t0);
}
int LookupGate::cost_key(int64_t rows) {
if (rows < 1) rows = 1;
if (rows <= kCostExact) return (int)(rows - 1);
const int64_t k = kCostExact + (rows - kCostExact - 1) / kCostBand;
return (int)(k < kCostKeys ? k : kCostKeys - 1);
}
void LookupGate::step_time(int64_t rows, double ms) {
if (rows < 1 || !(ms > 0.0) || !std::isfinite(ms)) return;
const int k = cost_key(rows);
double& m = cost_ms_[k];
double& r = cost_r_[k];
int64_t& n = cost_n_[k];
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
m = n ? m + w * (ms - m) : ms;
r = n ? r + w * ((double)rows - r) : (double)rows;
++n;
}
int64_t LookupGate::cost_samples(int64_t rows) const { return cost_n_[cost_key(rows)]; }
double LookupGate::step_cost(int64_t rows) const {
if (rows < 1) rows = 1;
const double R = (double)rows;
/* The timed keys either side, by the mean rows of their samples (monotone in the key). */
int lo = -1, hi = -1;
for (int k = 0; k < kCostKeys; ++k) {
if (cost_n_[k] <= 0) continue;
if (cost_r_[k] <= R) lo = k;
if (cost_r_[k] >= R && hi < 0) hi = k;
}
if (lo >= 0 && hi >= 0) {
const double r0 = cost_r_[lo], r1 = cost_r_[hi];
if (lo == hi || r1 <= r0) return cost_ms_[lo];
return cost_ms_[lo] + (cost_ms_[hi] - cost_ms_[lo]) * (R - r0) / (r1 - r0);
}
if (lo >= 0) return cost_ms_[lo] * prior(R) / prior(cost_r_[lo]);
if (hi >= 0) return cost_ms_[hi] * prior(R) / prior(cost_r_[hi]);
return prior(R);
}
} /* namespace rad */
+152
View File
@@ -0,0 +1,152 @@
/* lookup.h -- whether a prompt-lookup proposal is worth its verify rows.
*
* A verify row is not free. On a MoE every row reads its own routed experts, so verifying five
* drafts on one sequence costs a few plain steps (DeepSeek-V4.1 at TP4: 32 ms against 13.5 ms),
* and prompt lookup proposes on novel text too: any bigram it has seen before is a pattern. On
* prose those proposals are wrong four times in five and the verifies make decoding slower than
* not speculating; on code edits and quoted text they are right most of the time and it is twice
* as fast. So each proposal is verified only when it is expected to pay:
*
* verify k drafts iff E[accepted] * T(R) > tokens * (T(R + k) - T(R))
*
* where T(R) is the measured wall time of a decode step of R query rows, R the rows the step
* already carries and `tokens` what it already expects to emit. For one sequence that is
* 1 + E[accepted] > T(1 + k) / T(1).
*
* E[accepted] = sum_{j<k} S_j, with S_j the sequence's estimate of P(the proposal's first j + 1
* tokens all come true). The estimate is fed by every proposal, verified or not: a proposal held
* back is compared with the tokens the sequence goes on to emit, and its accepted count is their
* common prefix. That is exactly what a verify would have accepted, at any temperature, because
* a verify accepts a draft iff it equals the token the target emits at that position and the
* target's draw there does not depend on the draft (core/sample/accept.h). So a held sequence
* keeps learning at no cost, and resumes drafting as soon as its text turns repetitive.
*
* Estimates are kept per class of proposal: one whose match runs at least kLongMatch tokens back
* (the sequence is copying a stretch it has seen) and one whose match is shorter (a recurring
* bigram or trigram). They differ by far more than either varies within a reply, and a new
* sequence starts each from its own prior: a long match is drafted at once, a short one waits for
* evidence.
*
* T is measured online over pure decode steps, keyed by rows (StepCost). Before a row count is
* timed, its cost is the nearest timed count's scaled by the prior shape 1 + kRowCost (R - 1),
* which is optimistic on purpose: the first verify it lets through times the real cost.
*
* Only which proposals are verified changes, never what is emitted: output is the same as with
* speculation off.
*/
#pragma once
#include <cstdint>
#include "draft.h"
#include "ngram.h"
namespace rad {
/* One sequence's record: its estimates and the proposal being compared with its text. Kept in the
* scheduler's per-request state; it describes the text, so preemption keeps it and a new request
* starts it over. */
struct LookupSeq {
bool started = false;
float s[2][RAD_SCHED_MAX_SPEC] = {}; /* by class: P(first j + 1 drafts all come true) */
uint16_t n[2] = {}; /* proposals evaluated in each class, saturating */
/* The proposal under evaluation: its first token is the sequence's token `pend_pos`; -1 none.
* `pend_done` of its `pend_len` tokens have been compared, all equal so far. */
int64_t pend_pos = -1;
int32_t pend_len = 0;
int32_t pend_done = 0;
int32_t pend_cls = 0;
bool pend_held = false; /* it was held back rather than verified */
bool last_taken = false; /* the last offer became the pending one */
int32_t pend[RAD_SCHED_MAX_SPEC] = {};
/* For the request's log line. */
int64_t proposed = 0, held = 0, held_drafts = 0, held_hits = 0;
};
class LookupGate {
public:
/* ---------------------------------------------------------- the policy's constants
* Fixed; none is a property of a deployment. The deployment's one property, what a verify
* row costs, is measured (step_time). Chosen on 24 real replies (an essay, a code edit and 22
* varied prompts, DeepSeek-V4.1 greedy, 256 tokens) replayed through the engine's lookup rule
* at per-row costs of 0.06 to 0.6 of a plain step: over the prose replies, 0.999 to 1.014x
* the speed of not speculating (geometric mean) and 0.988x at worst, where verifying every
* proposal gives 0.85 to 1.015x and 0.73x at worst; on the code edit within 2.1% of verifying
* every proposal at the costs where that pays, and 11% ahead of it at 0.6. */
/* A proposal whose match runs this many tokens back is the long class. */
static constexpr int kLongMatch = 8;
/* Where each class starts: P(each draft comes true), the same at every position. A long match
* drafts at once at any row cost under 0.8 of a step; a short one waits until its own record
* says it pays. */
static constexpr double kPriorShort = 0.0;
static constexpr double kPriorLong = 0.8;
/* The prior weighs as much as two proposals: the third evaluated in a class moves its
* estimate by a third. */
static constexpr double kPriorWeight = 2.0;
/* Then a moving average with a half-life of 8 proposals, short enough to follow a reply from
* prose into a quoted block and out again within a few lines. */
static constexpr double kHalfLife = 8.0;
/* The shape an untimed row count is priced on: each query row adds 6% to a step. */
static constexpr double kRowCost = 0.06;
/* Step times: a running mean for the first samples, then a moving average with a half-life of
* 32 steps; once a key has 4 samples one step counts for at most 4x its mean (a step that
* waited on a recording or a host stall says nothing about its row count). As draft.cpp. */
static constexpr double kCostHalfLife = 32.0;
static constexpr double kCostOutlier = 4.0;
static constexpr int64_t kCostClipAfter = 4;
/* Row counts are kept exactly up to 128, then in bands of 32. */
enum { kCostExact = 128, kCostBand = 32, kCostKeys = 160 };
void configure(int max_depth);
int max_depth() const { return max_depth_; }
/* ---------------------------------------------------------- one sequence */
/* The class of a proposal whose match runs `match` tokens back. */
static int class_of(int match) { return match >= kLongMatch ? 1 : 0; }
/* Expected drafts accepted if the first `k` of a class-`cls` proposal are verified. Starts the
* estimate if needed. */
double expect(LookupSeq& q, int cls, int k) const;
/* A proposal of `n` tokens whose first is the sequence's token `pos`: taken for evaluation
* when none is pending. Counted as proposed either way. */
void offer(LookupSeq& q, int64_t pos, const int32_t* prop, int n, int match) const;
/* The proposal offered last was not verified: `n` drafts held back. Counters only. */
void held(LookupSeq& q, int n) const;
/* After a commit: compares the pending proposal with the tokens `seq` now holds, and folds it
* into its class once a token differs or every token has come true. */
void advance(LookupSeq& q, const TokenSeq& seq) const;
/* ---------------------------------------------------------- the step */
/* Whether `k` drafts expected to yield `gain` accepted tokens pay, in a step that so far
* carries `rows` query rows and expects `tokens` tokens. */
bool pays(double gain, int k, int64_t rows, double tokens) const;
/* A pure decode step of `rows` query rows took `ms`, from the end of the step before. */
void step_time(int64_t rows, double ms);
/* The expected wall time of a decode step of `rows` rows: ms once anything is timed, else the
* unitless prior. Only ratios are used. */
double step_cost(int64_t rows) const;
int64_t cost_samples(int64_t rows) const;
/* Across all sequences, for metrics: proposals offered; proposals held back and their drafts;
* and of the held proposals scored (one at a time per sequence), the drafts that came true:
* what verifying them would have accepted. Updated by the per-sequence calls above, which are
* const on the policy, hence mutable. */
int64_t proposed() const { return proposed_; }
int64_t held_count() const { return held_; }
int64_t held_drafts() const { return held_drafts_; }
int64_t held_hits() const { return held_hits_; }
private:
int max_depth_ = 0;
double alpha_ = 0.0;
double cost_r_[kCostKeys] = {}; /* mean rows of the samples in each key */
double cost_ms_[kCostKeys] = {};
int64_t cost_n_[kCostKeys] = {};
mutable int64_t proposed_ = 0, held_ = 0, held_drafts_ = 0, held_hits_ = 0;
static int cost_key(int64_t rows);
static double prior(double rows) { return 1.0 + kRowCost * (rows - 1.0); }
void start(LookupSeq& q) const;
void fold(LookupSeq& q, int cls, int len, int hits) const;
};
} /* namespace rad */
+11
View File
@@ -24,6 +24,9 @@ struct SchedMetrics {
int64_t failed = 0;
int64_t cancelled = 0;
int64_t preemptions = 0;
/* --preempt-wait-ms fallback: waits that ended by evicting cache blocks and forcing a running
* victim, not just by the pool freeing itself. */
int64_t preempt_forced = 0;
int64_t steps = 0;
/* Steps by shape. `steps_mixed` counts steps carrying both a prefill chunk and decode rows.
@@ -148,6 +151,14 @@ struct SchedMetrics {
bool draft_adaptive = false;
float draft_depth_adaptive = 0.0f;
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
/* Prompt lookup's verify gate (sched/lookup.h), when lookup is the only drafter: proposals
* made, proposals held back unverified and their drafts, and of the held proposals scored
* against the text that followed, the drafts that came true (what a verify would have
* accepted). */
int64_t lookup_proposals = 0;
int64_t lookup_held = 0;
int64_t lookup_held_drafts = 0;
int64_t lookup_held_hits = 0;
};
+119
View File
@@ -0,0 +1,119 @@
/* ngram.cpp -- the prompt-lookup drafter's index. See ngram.h. */
#include "ngram.h"
#include <algorithm>
namespace rad {
void NgramIndex::reset(uint64_t owner) {
std::vector<uint32_t>().swap(tab_);
mask_ = 0;
filled_ = 0;
entries_ = 0;
owner_ = owner;
nmin_ = nmax_ = 0;
}
uint64_t NgramIndex::hash(const TokenSeq& s, int64_t end, int n) {
uint64_t h = 0x9E3779B97F4A7C15ull * (uint64_t)(n + 1);
for (int64_t i = end - n + 1; i <= end; ++i) {
h ^= (uint64_t)(uint32_t)s[i];
h *= 0xff51afd7ed558ccdull;
h ^= h >> 32;
}
h *= 0xc4ceb9fe1a85ec53ull;
return h ^ (h >> 29);
}
bool NgramIndex::same(const TokenSeq& s, int64_t e1, int64_t e2, int n) {
for (int k = 0; k < n; ++k)
if (s[e1 - k] != s[e2 - k]) return false;
return true;
}
/* Ends arrive in increasing order, so an n-gram already present is overwritten by a later
* occurrence: the entry is always the latest. */
void NgramIndex::insert(const TokenSeq& s, int64_t end, int n) {
const uint32_t v = ((uint32_t)(end + 1) << 4) | (uint32_t)n;
for (uint64_t i = hash(s, end, n) & mask_;; i = (i + 1) & mask_) {
const uint32_t t = tab_[(size_t)i];
if (t == 0) {
tab_[(size_t)i] = v;
++entries_;
return;
}
if ((int)(t & 15u) == n && same(s, (int64_t)(t >> 4) - 1, end, n)) {
tab_[(size_t)i] = v;
return;
}
}
}
/* At most half full, so a probe ends within a few slots. Doubling rehashes from the sequence's
* own tokens; amortised over the tokens that filled it, a constant per token. */
void NgramIndex::grow(const TokenSeq& s, int64_t want_entries) {
uint64_t cap = 1024;
while ((int64_t)cap < 2 * want_entries) cap <<= 1;
if (cap <= (uint64_t)tab_.size()) return;
std::vector<uint32_t> old;
old.swap(tab_);
tab_.assign((size_t)cap, 0u);
mask_ = cap - 1;
entries_ = 0;
for (const uint32_t t : old)
if (t) insert(s, (int64_t)(t >> 4) - 1, (int)(t & 15u));
}
void NgramIndex::index_to(const TokenSeq& s, int64_t upto) {
if (upto <= filled_) return;
const int nn = nmax_ - nmin_ + 1;
grow(s, entries_ + (upto - filled_) * nn);
for (int64_t e = filled_; e < upto; ++e)
for (int n = nmin_; n <= nmax_ && n <= e + 1; ++n) insert(s, e, n);
filled_ = upto;
}
int64_t NgramIndex::find_suffix(const TokenSeq& s, int n) const {
const int64_t end = s.size() - 1;
if (tab_.empty() || n < 1 || n > end) return -1;
for (uint64_t i = hash(s, end, n) & mask_;; i = (i + 1) & mask_) {
const uint32_t t = tab_[(size_t)i];
if (t == 0) return -1;
const int64_t e = (int64_t)(t >> 4) - 1;
if ((int)(t & 15u) == n && e < end && same(s, e, end, n)) return e;
}
}
int NgramIndex::propose(const TokenSeq& seq, int nmin, int nmax, int depth, int32_t* out,
int* match, int match_cap) {
const int64_t len = seq.size();
if (depth <= 0 || len < 2) return 0;
nmin = std::max(1, std::min(nmin, (int)kMaxN));
nmax = std::max(nmin, std::min(nmax, (int)kMaxN));
/* Only n-grams with a token after them are indexed: the last one is the pattern sought. */
const int64_t upto = std::min(len - 1, kMaxLen);
if (nmin != nmin_ || nmax != nmax_ || filled_ > upto) {
const uint64_t own = owner_;
reset(own);
nmin_ = nmin;
nmax_ = nmax;
}
index_to(seq, upto);
for (int n = (int)std::min<int64_t>(nmax, len - 1); n >= nmin; --n) {
const int64_t e = find_suffix(seq, n);
if (e < 0) continue;
for (int d = 0; d < depth; ++d) {
const int64_t i = e + 1 + d;
out[d] = i < len ? seq[i] : out[i - len];
}
if (match) {
int m = n;
while (m < match_cap && e - m >= 0 && seq[e - m] == seq[len - 1 - m]) ++m;
*match = m;
}
return depth;
}
return 0;
}
} /* namespace rad */
+86
View File
@@ -0,0 +1,86 @@
/* ngram.h -- the prompt-lookup drafter's index: where each n-gram of a sequence last occurred.
*
* Prompt lookup (Scheduler::draft_ngram) proposes, for a sequence of L tokens, what followed the
* most recent earlier occurrence of its last n tokens, for n from the longest pattern down to the
* shortest. Scanning the sequence for that occurrence costs O(L) a step on a miss, which at a
* 400k-token context is a millisecond of host time per sequence per step. This index answers it in
* O(n) and is updated incrementally: each token committed adds the n-grams ending at the token
* before it, so a sequence is indexed once over its lifetime, prompt included.
*
* The table is open-addressed and stores no keys. An entry is the end position of the n-gram's
* latest occurrence and its length n, and its tokens are the sequence's own, compared on every
* probe, so the index is exact: a hit is a true earlier occurrence, a miss means there is none.
* One table holds every length; it doubles past half full, so memory is about 8 bytes per token
* per pattern length (16 MiB for 400k tokens and lengths 2..4), allocated as the sequence grows.
*
* The proposal itself is a guess like any drafter's: the verify step emits the target's own
* tokens whatever it proposes (core/sample/accept.h), so the index changes speed, never text.
*/
#pragma once
#include <cstdint>
#include <vector>
namespace rad {
/* A sequence as prompt ++ output, the two vectors a Request keeps, without copying either. */
struct TokenSeq {
const int32_t* a = nullptr;
int64_t na = 0;
const int32_t* b = nullptr;
int64_t nb = 0;
int64_t size() const { return na + nb; }
int32_t operator[](int64_t i) const { return i < na ? a[i] : b[i - na]; }
};
class NgramIndex {
public:
/* The longest pattern an entry can name (4 bits), and the longest sequence it indexes: past
* 2^27 tokens the index stops growing and only earlier occurrences are found. */
enum { kMaxN = 15 };
static constexpr int64_t kMaxLen = ((int64_t)1 << 27) - 1;
/* Empties the index and releases its table. `owner` names the sequence it is built for (a
* request id); a lookup for any other owner starts over. */
void reset(uint64_t owner = 0);
uint64_t owner() const { return owner_; }
/* Proposes up to `depth` tokens into `out` for the sequence `seq`, indexing what it added
* since the last call. For n = nmax down to nmin: if the last n tokens occurred earlier, the
* tokens after their latest earlier occurrence; past the sequence's end the proposal goes on
* with its own tokens, so a pattern that repeats with a period shorter than `depth` is
* proposed whole. Returns how many were proposed, 0 when no pattern of those lengths recurs.
*
* The sequence must only grow between calls under one owner; a shorter one (or other pattern
* lengths) rebuilds the index. 1 <= nmin <= nmax <= kMaxN.
*
* `match`, if given, receives how far the match behind the proposal runs back: the number of
* tokens before the end that equal those before the occurrence, at least the pattern's n and
* at most `match_cap` (counted only that far). The verify gate (lookup.h) prices a long match
* apart from a recurring bigram. */
int propose(const TokenSeq& seq, int nmin, int nmax, int depth, int32_t* out,
int* match = nullptr, int match_cap = 0);
/* The latest end position e < seq.size() - 1 of an earlier occurrence of the sequence's last
* `n` tokens, or -1. Visible for tests; propose() calls it after indexing. */
int64_t find_suffix(const TokenSeq& seq, int n) const;
int64_t indexed() const { return filled_; } /* n-grams ending before this are in */
int64_t entries() const { return entries_; }
size_t bytes() const { return tab_.capacity() * sizeof(uint32_t); }
private:
std::vector<uint32_t> tab_; /* 0 empty, else (end + 1) << 4 | n */
uint64_t mask_ = 0;
int64_t filled_ = 0; /* every n-gram ending at e < filled_ is indexed */
int64_t entries_ = 0;
uint64_t owner_ = 0;
int nmin_ = 0, nmax_ = 0;
static uint64_t hash(const TokenSeq& s, int64_t end, int n);
static bool same(const TokenSeq& s, int64_t e1, int64_t e2, int n);
void insert(const TokenSeq& s, int64_t end, int n);
void grow(const TokenSeq& s, int64_t want_entries);
void index_to(const TokenSeq& s, int64_t upto);
};
} /* namespace rad */
+199 -43
View File
@@ -11,6 +11,7 @@
#include <cstdio>
#include <cstdlib>
#include <numeric>
#include <string>
namespace rad {
@@ -164,17 +165,47 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
* 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
* policy with fixed rounds: each sequence verifies the first min(D, its stop) of the block.
* Prompt lookup runs no pass and keeps the fixed window; the outcome is logged either way. */
* Prompt lookup as the only drafter runs no pass either, and takes the policy the same way:
* its drafts feed each sequence's estimate and its proposal is cut to the sequence's window.
* As a fallback beside a head it keeps the step's window and stays out of the head's
* estimate. The outcome is logged either way. */
lookup_adapt_ = false;
/* The verify-path harness (scheduler.h): --debug-draft-oracle names a file of token ids,
* whitespace or comma separated, a plain greedy run's continuation of the one prompt the test
* sends; kDebugMiss of the drafts are corrupted. The text must stay the plain run's whatever is
* accepted. */
debug_oracle_.clear();
if (const char* f = cfg.debug_draft_oracle.c_str(); *f && cfg.n_spec > 0) {
if (FILE* fp = std::fopen(f, "r")) {
std::string text;
char buf[4096];
for (size_t k; (k = std::fread(buf, 1, sizeof buf, fp)) > 0;) text.append(buf, k);
std::fclose(fp);
for (char& ch : text)
if ((ch < '0' || ch > '9') && ch != '-') ch = ' ';
const char* q = text.c_str();
for (char* e = nullptr;; q = e) {
const long long v = std::strtoll(q, &e, 10);
if (e == q) break;
if (v >= 0 && v < prog.meta.n_vocab) debug_oracle_.push_back((int32_t)v);
}
}
RAD_WARN("--debug-draft-oracle: prompt lookup proposes from %zu fixed ids in %s, "
"%.0f%% of drafts corrupted -- a verify-path test, not a drafter",
debug_oracle_.size(), f, 100.0 * kDebugMiss);
}
if (cfg.draft_window == DraftWindow::Adaptive) {
const RadDrafterDecl& dd = prog.drafter;
if (cfg.n_spec <= 0)
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
else if ((dd.kind != RAD_DRAFT_SERIAL && dd.kind != RAD_DRAFT_BLOCK) || dd.depth <= 0)
RAD_WARN("--draft-window adaptive: the window is fixed at %d with prompt lookup only "
"-- the adaptive window prices draft passes and verify rows, and prompt "
"lookup runs no pass", cfg.n_spec);
else {
else if ((dd.kind != RAD_DRAFT_SERIAL && dd.kind != RAD_DRAFT_BLOCK) || dd.depth <= 0) {
dp.adapt = true;
lookup_adapt_ = true;
RAD_INFO("--draft-window adaptive with prompt lookup only: each sequence verifies its "
"lookup's first min(D, its stop) drafts, %d at most, priced like a head's",
cfg.n_spec);
} else {
dp.adapt = true;
if (dd.kind == RAD_DRAFT_BLOCK)
RAD_INFO("--draft-window adaptive with a block drafter: the block of %d is "
@@ -183,6 +214,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
}
}
RAD_TRY(draft_.configure(dp));
/* Prompt lookup as the deployment's only drafter verifies a proposal only when it pays
* (lookup.h). Not configurable: the one deployment property it needs, the cost of a verify
* row, is measured. */
{
const RadDrafterDecl& dd = prog.drafter;
const bool head =
(dd.kind == RAD_DRAFT_SERIAL || dd.kind == RAD_DRAFT_BLOCK) && dd.depth > 0;
lookup_gate_on_ = cfg.n_spec > 0 && !head;
lookup_.configure(lookup_gate_on_ ? cfg.n_spec : 0);
if (lookup_gate_on_)
RAD_INFO("prompt lookup: a proposal is verified when its sequence's record says it "
"pays for its verify rows at the measured step cost; one held back is still "
"scored against the text that follows");
}
draft_est_.clear();
draft_est_.reserve((size_t)cfg.max_seqs);
@@ -263,17 +308,6 @@ 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;
/* 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) —
* the whole engine would die for one bad number. Same bound as the scored-prompt check below.
*/
for (int32_t t : r->prompt)
if (t < 0 || t >= prog_->meta.n_vocab) {
RAD_WARN("request %llu refused: prompt token id %d is outside the vocabulary [0, %lld)",
(unsigned long long)r->id, t, (long long)prog_->meta.n_vocab);
return RAD_E_INVAL;
}
/* Nor could a prompt the KV pool cannot hold even alone: admission takes only what the pool
* holds, so it would wait at the head of the queue, and everything behind it, forever. The
* prompt is the least a request needs: its first token comes from the prefill's last row.
@@ -314,6 +348,7 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
s.arrival = ++arrival_;
s.arrived_us = mono_us();
s.first_tok_us = 0;
s.preempted_us = 0;
s.slot = slot;
s.card = -1;
s.running = false;
@@ -321,6 +356,7 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
/* A new request's text, so a new estimate. */
s.adapt.depth = 0;
s.adapt.held = 0;
s.look.started = false;
s.sched_tokens = 0;
s.entry = -1;
s.entry_next = -1;
@@ -555,6 +591,16 @@ 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();
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",
(unsigned long long)s.req->id, (long long)s.look.proposed,
(long long)s.look.held, (long long)s.look.held_drafts,
(long long)s.look.held_hits, lookup_.max_depth(),
lookup_.step_cost(1 + lookup_.max_depth()) / lookup_.step_cost(1));
s.look.started = false;
/* Fold what the draft head did on this text into the next text's starting estimate, once:
* marking it unstarted makes a second close add nothing. */
if (draft_.adaptive()) {
@@ -846,28 +892,40 @@ int Scheduler::requests_locked(ReqStat* out, int max) const {
*
* Longest pattern and most recent occurrence first: a longer match predicts better, and falling
* back to shorter ones only on a miss keeps common bigrams from dragging acceptance down. A
* declared draft head calls set_draft() before step(), so this only fills an empty proposal. */
int Scheduler::draft_ngram(SchedReq& s, int depth) const {
* declared draft head calls set_draft() before step(), so this only fills an empty proposal.
*
* The occurrence comes from the sequence's own index (ngram.h): O(pattern) a lookup, plus the
* n-grams the last commit added, rather than a scan of the context. */
int Scheduler::draft_ngram(SchedReq& s, int depth, int* match) const {
if (match) *match = -1;
if (depth <= 0 || !s.req) return 0;
const Request& r = *s.req;
const int64_t np = (int64_t)r.prompt.size(), no = (int64_t)r.output.size();
const int64_t n = np + no;
if (n < 2) return 0;
auto at = [&](int64_t i) -> int32_t {
return i < np ? r.prompt[(size_t)i] : r.output[(size_t)(i - np)];
};
for (int k = kNgramMax; k >= kNgramMin; --k) {
if (n < (int64_t)k + 1) continue;
for (int64_t j = n - k - 1; j >= 0; --j) {
bool hit = true;
for (int t = 0; t < k && hit; ++t) hit = (at(j + t) == at(n - k + t));
if (!hit) continue;
int d = 0;
while (d < depth && j + k + d < n) { s.draft[d] = at(j + k + d); ++d; }
return d;
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();
if (seq.size() < 2) return 0;
if (depth > RAD_SCHED_MAX_SPEC) depth = RAD_SCHED_MAX_SPEC;
if (!debug_oracle_.empty()) {
/* The harness: ids n.. of the plain run's continuation, each replaced by its neighbour id
* where a hash of (n, position) falls under the miss rate. */
const int64_t n = seq.nb;
int d = 0;
for (; d < depth && n + d < (int64_t)debug_oracle_.size(); ++d) {
uint64_t h = (uint64_t)(n * RAD_SCHED_MAX_SPEC + d + 1) * 0x9E3779B97F4A7C15ull;
h ^= h >> 31;
h *= 0xbf58476d1ce4e5b9ull;
h ^= h >> 29;
const bool miss = (double)(h >> 11) * 0x1.0p-53 < kDebugMiss;
const int32_t t = debug_oracle_[(size_t)(n + d)];
s.draft[d] = miss ? (int32_t)((t + 1) % (int32_t)prog_->meta.n_vocab) : t;
}
return d;
}
return 0;
if (s.ngram_ix.owner() != r.id) s.ngram_ix.reset(r.id);
return s.ngram_ix.propose(seq, cfg_.spec_ngram_min, cfg_.spec_ngram_max, depth, s.draft, match,
LookupGate::kLongMatch);
}
/* ------------------------------------------------------------------ chunking */
@@ -1145,6 +1203,7 @@ void Scheduler::preempt_back() {
r.n_cached = 0;
r.n_accepted = 0;
r.state = ReqState::Preempted;
s.preempted_us = mono_us();
s.drafter_reset();
/* Also clear the request's own window. The sampler stages 1 + Request::n_draft rows
* (Sampler::build_step), and a drafter may have set it for the step this preemption removed;
@@ -1419,6 +1478,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
if (s.card < 0) { s.card = free_cards_.back(); free_cards_.pop_back(); }
r.state = ReqState::Running;
s.preempted_us = 0;
s.running = true;
server::sink_admitted(r.sink);
server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(), r.n_cached);
@@ -1475,6 +1535,15 @@ bool Scheduler::preempted_can_prefill(const SchedReq& s) const {
return true;
}
bool Scheduler::preempt_wait_overdue(const SchedReq& s) const {
if (!s.req || s.req->state != ReqState::Preempted) return false;
/* 0 means fall back on the next step; a timed request must have been preempted before. */
if (s.preempted_us <= 0) return false;
if (cfg_.preempt_wait_ms == 0) return true;
const int64_t waited_ms = (mono_us() - s.preempted_us) / 1000;
return waited_ms >= cfg_.preempt_wait_ms;
}
/* ------------------------------------------------------------------ the step */
const RadBatch* Scheduler::step() {
std::lock_guard<std::mutex> lk(mu_);
@@ -1494,6 +1563,45 @@ const RadBatch* Scheduler::step() {
step_prefill_tok_ = 0;
step_decode_tok_ = 0;
/* 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
* still cannot fit after one victim must not leave the rest of the queue waiting forever.
* Reclaim cache blocks once, then preempt the lowest-priority running request until one
* overdue request can prefill or nothing is left running. The admission pass below sees the
* reclaimed blocks; nothing is planned for a victim this step. */
bool overdue = false;
for (int32_t slot : waiting_) {
const SchedReq& s = *reqs_[(size_t)slot];
if (s.req && s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) {
overdue = true;
break;
}
}
if (overdue) {
bool evicted = false;
while (!running_.empty()) {
SchedReq* fit = nullptr;
for (int32_t slot : waiting_) {
SchedReq& s = *reqs_[(size_t)slot];
if (!s.req || s.req->state != ReqState::Preempted || !preempt_wait_overdue(s))
continue;
if (preempted_can_prefill(s)) { fit = &s; break; }
}
if (fit) break;
if (!evicted && pc_ && cfg_.prefix_cache) {
(void)pc_->evict(kEvictBlocks);
evicted = true;
continue;
}
const SchedReq& victim = *reqs_[(size_t)running_.back()];
RAD_DEBUG("step: preempted prefill overdue; preempting the lowest-priority running "
"request %llu",
victim.req ? (unsigned long long)victim.req->id : 0ull);
++m_.preempt_forced;
preempt_back();
}
}
int64_t budget = cfg_.max_tok;
bool preempted_here = false;
/* --prefill-interleave: after a step that carried a chunk beside decoding sequences, with the
@@ -1578,6 +1686,19 @@ const RadBatch* Scheduler::step() {
int32_t capped_at = -1;
int64_t capped_full = 0;
/* The verify gate's view of the step: every decoding sequence's own row, before any drafts. */
if (lookup_gate_on_) {
gate_rows_ = 0;
for (int32_t slot : running_) {
const SchedReq& g = *reqs_[(size_t)slot];
if (!g.req) continue;
const Request& gr = *g.req;
if (gr.n_computed >= (int64_t)gr.prompt.size() && gr.n_computed + 1 >= g.seq_len())
++gate_rows_;
}
gate_tokens_ = (double)gate_rows_;
}
/* ---------------------------------------------------------- running requests first */
/* Continuous batching: requests already holding blocks are served before new ones are
* admitted, so new work never preempts work half done. */
@@ -1630,8 +1751,29 @@ const RadBatch* Scheduler::step() {
bool ngram = false;
if (!r.may_speculate) s.n_draft = 0;
else if (s.n_draft == 0) {
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
/* As the only drafter under the adaptive window, the lookup is the head: its
* proposal is cut to the sequence's own window. */
int match = -1;
s.n_draft = (int32_t)draft_ngram(s, lookup_adapt_ ? cap : draft_.step_window(),
&match);
ngram = s.n_draft > 0;
/* The verify gate (lookup.h). Every proposal is offered, so a held one is still
* scored against the text; the --debug-draft-oracle harness (match < 0) is a
* verify-path test and always verified. */
if (ngram && lookup_gate_on_ && match >= 0) {
const int64_t pos = (int64_t)r.prompt.size() + (int64_t)r.output.size();
lookup_.offer(s.look, pos, s.draft, s.n_draft, match);
const double gain =
lookup_.expect(s.look, LookupGate::class_of(match), s.n_draft);
if (lookup_.pays(gain, s.n_draft, gate_rows_, gate_tokens_)) {
gate_rows_ += s.n_draft;
gate_tokens_ += gain;
} else {
lookup_.held(s.look, s.n_draft);
s.n_draft = 0;
ngram = false;
}
}
}
if (!ngram && s.n_draft > cap) s.n_draft = cap;
s.draft_ngram = ngram;
@@ -2103,12 +2245,6 @@ 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;
/* 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
* prefill. Scored rows only -- every other decode keeps the step of overlap it had. */
if (r.token_scores && r.max_tokens > 0 &&
(int64_t)r.output.size() + 1 >= r.max_tokens) return nullptr;
/* The furthest context the row can reach: every position this step verifies committed,
* counted from the last commit rather than this step's own bound (which would add a
@@ -2352,6 +2488,15 @@ int Scheduler::commit(StepResult& res) {
}
if (res.token) emit(res.token[i], a);
r.n_computed = valid;
/* The gate's pending proposal against what this step emitted (lookup.h). */
if (lookup_gate_on_ && s.look.started) {
TokenSeq ts;
ts.a = r.prompt.data();
ts.na = (int64_t)r.prompt.size();
ts.b = r.output.data();
ts.nb = (int64_t)r.output.size();
lookup_.advance(s.look, ts);
}
step_decode_tok_ += 1 + a;
if (e.n_spec > 0) {
@@ -2359,7 +2504,7 @@ int Scheduler::commit(StepResult& res) {
/* And this sequence's own estimate under the adaptive window, only when the head
* drafted: a prompt-lookup proposal is accepted on different text by a different
* rule. A move takes effect at the next draft; this step's drafter already ran. */
if (draft_.adaptive() && !e.ngram) {
if (draft_.adaptive() && (!e.ngram || lookup_adapt_)) {
const int was = s.adapt.depth;
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
@@ -2496,6 +2641,13 @@ void Scheduler::step_finished() {
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
}
/* The step's cost by query rows, for the prompt-lookup gate (lookup.h): every pure decode
* step, drafting or not, since the plain step is what a verify is weighed against. */
if (lookup_gate_on_ && plan_.phase == RAD_PHASE_DECODE && wall > 0) {
int64_t rows = 0;
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
@@ -3130,6 +3282,10 @@ SchedMetrics Scheduler::metrics_locked() const {
m.draft_pos_reached [j] = draft_.reached(j);
m.draft_pos_accepted[j] = draft_.hits(j);
}
m.lookup_proposals = lookup_.proposed();
m.lookup_held = lookup_.held_count();
m.lookup_held_drafts = lookup_.held_drafts();
m.lookup_held_hits = lookup_.held_hits();
if (draft_.adaptive()) {
m.draft_adaptive = true;
/* Over the running sequences whose estimate has started; one that has not drafted yet
+40 -6
View File
@@ -14,7 +14,9 @@
#pragma once
#include "batch.h"
#include "draft.h"
#include "lookup.h"
#include "metrics.h"
#include "ngram.h"
#include <chrono>
#include <memory>
@@ -40,6 +42,8 @@ struct SchedReq {
/* Wall clock, for the live request table; `arrival` is a counter and cannot measure time. */
int64_t arrived_us = 0;
int64_t first_tok_us = 0; /* 0 until the first output token: this request's TTFT */
int64_t preempted_us = 0; /* when this state became Preempted; 0 otherwise. Bounds the
* whole-recompute admission wait (--preempt-wait-ms). */
/* The drafter's proposal for the next step, and the conv-window read cursor a rejection
* moves rather than rolls back (§10). */
@@ -81,6 +85,13 @@ struct SchedReq {
DraftAdapt adapt;
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
bool draft_ngram = false;
/* Prompt lookup's index over prompt ++ output (ngram.h), built at the sequence's first lookup
* and extended by each later one. It depends on the tokens alone, so preemption keeps it; it
* is keyed by request id, so a recycled slot starts over, and a closed request frees it. */
NgramIndex ngram_ix;
/* Prompt lookup's record on this text for the verify gate (lookup.h): it describes the text,
* so preemption keeps it; a new request starts it over. */
LookupSeq look;
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
@@ -425,6 +436,7 @@ public:
const StepPlan& plan() const { return plan_; }
const ChunkGeometry& geometry() const { return geo_; }
DraftController& draft() { return draft_; }
LookupGate& lookup_gate() { return lookup_; }
SchedMetrics metrics() const;
/* The observers' copy. Dashboards, scrapers and admin calls read what the engine thread last
@@ -566,11 +578,30 @@ private:
std::vector<DraftAdapt*> draft_est_;
void draft_cycle();
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
* lengths it tries, longest first. */
int draft_ngram(SchedReq& s, int depth) const;
enum { kNgramMin = 2, kNgramMax = 4 };
/* The built-in prompt-lookup drafter (scheduler.cpp, ngram.h). Fills s.draft and returns how
* many tokens it proposed; 0 when the sequence has no repeated pattern to extend. It tries
* --spec-ngram-max down to --spec-ngram-min tokens, longest first. `match`, if given, gets how
* far the match behind the proposal runs back (NgramIndex::propose), -1 when the proposal did
* not come from the index (--debug-draft-oracle). */
int draft_ngram(SchedReq& s, int depth, int* match = nullptr) const;
/* Prompt lookup is the deployment's only drafter and --draft-window adaptive is on: its
* proposals feed each sequence's estimate and are capped by its window, as a head's are. */
bool lookup_adapt_ = false;
/* Prompt lookup is the deployment's only drafter: each proposal is verified only when its
* sequence's record says it pays for its verify rows at the measured step cost (lookup.h).
* Beside a draft head the lookup only fills in for a sequence the head declines, and is
* left to the head's window. */
bool lookup_gate_on_ = false;
LookupGate lookup_;
/* Decode rows and expected tokens of the step being planned, for the gate: a decode row
* counts once up front, and each verified proposal adds its drafts and expected yield. */
int64_t gate_rows_ = 0;
double gate_tokens_ = 0.0;
/* --debug-draft-oracle (draft_ngram): a fixed continuation the lookup proposes from instead,
* with kDebugMiss of the drafts corrupted, so a verify accepts and rejects at every depth on
* any model. A test harness; empty when not given. */
std::vector<int32_t> debug_oracle_;
static constexpr double kDebugMiss = 0.3;
mutable std::mutex mu_;
@@ -766,8 +797,11 @@ private:
void preempt_back();
/* A preempted request waits until the pool can hold its WHOLE remaining recompute plus one
* block of headroom for every running sequence; otherwise admitting it now just gets it
* preempted again next step and the prefill loops. */
* preempted again next step and the prefill loops. `preempt_wait_overdue` bounds that wait
* for every overdue preempted request: after --preempt-wait-ms the scheduler reclaims cache
* blocks and preempts lowest-priority running requests until one of them can prefill. */
bool preempted_can_prefill(const SchedReq& s) const;
bool preempt_wait_overdue(const SchedReq& s) const;
/* Give blocks back from the prefix cache until the pool has headroom again. */
void trim_prefix_cache();
/* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind
+3
View File
@@ -122,6 +122,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
o.prefill_tokens = m.prefill_tokens; o.decode_tokens = m.decode_tokens;
o.draft_tokens = m.draft_tokens; o.draft_accepted = m.draft_accepted;
o.draft_refills = m.draft_refills; o.draft_refill_tokens = m.draft_refill_tokens;
o.lookup_proposals = m.lookup_proposals; o.lookup_held = m.lookup_held;
o.lookup_held_drafts = m.lookup_held_drafts; o.lookup_held_hits = m.lookup_held_hits;
o.linear_hit_rate = m.linear_hit_rate;
o.attn_cached_tokens = m.attn_cached_tokens;
o.linear_cached_tokens = m.linear_cached_tokens;
@@ -139,6 +141,7 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) {
d < std::size(m.draft_verify_depth) && d < std::size(o.draft_verify_depth); ++d)
o.draft_verify_depth[d] = m.draft_verify_depth[d];
o.preemptions = m.preemptions;
o.preempt_forced = m.preempt_forced;
o.total_requests = m.admitted;
o.steps = m.steps;
o.steps_prefill = m.steps_prefill; o.steps_mixed = m.steps_mixed;
+7
View File
@@ -104,6 +104,12 @@ struct SchedMetrics {
/* Prefix hits ended early for a windowed block drafter, and the tokens they gave back. */
int64_t draft_refills = 0;
int64_t draft_refill_tokens = 0;
/* Prompt lookup's verify gate, lookup the only drafter (sched/lookup.h): proposals made,
* held back and their drafts, and of the held ones scored, the drafts that came true. */
int64_t lookup_proposals = 0;
int64_t lookup_held = 0;
int64_t lookup_held_drafts = 0;
int64_t lookup_held_hits = 0;
/* Per-position draft acceptance. The pooled `draft_acceptance` cannot tell a drafter that
* decays with depth from one whose later rounds are broken. Per position j: verifies that
* reached j (every earlier position accepted) and how many of those took j. */
@@ -117,6 +123,7 @@ struct SchedMetrics {
double draft_depth_adaptive = 0.0;
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
int64_t preemptions = 0;
int64_t preempt_forced = 0; /* --preempt-wait-ms fallback victims */
int64_t total_requests = 0;
/* Engine steps: one forward pass plus any draft rounds after it. With speculation a step
* emits more than one token, so step time cannot be derived from tokens per second. */
+20
View File
@@ -166,6 +166,7 @@ void Metrics::sample(const SchedMetrics& m) {
draft_adapt_on_.store(true, std::memory_order_release);
}
c_preemptions_.advance_to(m.preemptions);
c_preempt_forced_.advance_to(m.preempt_forced);
c_steps_.advance_to(m.steps);
c_steps_prefill_.advance_to(m.steps_prefill);
c_steps_mixed_.advance_to(m.steps_mixed);
@@ -182,6 +183,10 @@ void Metrics::sample(const SchedMetrics& m) {
c_draft_accepted_.advance_to(m.draft_accepted);
c_draft_refills_.advance_to(m.draft_refills);
c_draft_refill_tokens_.advance_to(m.draft_refill_tokens);
c_lookup_proposals_.advance_to(m.lookup_proposals);
c_lookup_held_.advance_to(m.lookup_held);
c_lookup_held_drafts_.advance_to(m.lookup_held_drafts);
c_lookup_held_hits_.advance_to(m.lookup_held_hits);
c_attn_cached_.advance_to(m.attn_cached_tokens);
c_linear_cached_.advance_to(m.linear_cached_tokens);
c_checkpoints_.advance_to(m.checkpoints_written);
@@ -308,6 +313,9 @@ std::string Metrics::render() const {
"Number of generation tokens processed.", L, c_generation_tokens_.get());
w.counter("vllm:num_preemptions_total",
"Cumulative number of preemptions from the engine.", L, c_preemptions_.get());
w.counter("radiance:preempt_forced_total",
"Preempted prefill waits that ended by reclaiming cache blocks and forcing a "
"lowest-priority running victim (--preempt-wait-ms).", L, c_preempt_forced_.get());
w.help("vllm:request_success_total",
"Count of successfully processed requests.", "counter");
@@ -416,6 +424,18 @@ std::string Metrics::render() const {
w.counter("radiance:draft_refill_tokens_total",
"Cached prompt tokens those hits gave back to be recomputed.",
L, c_draft_refill_tokens_.get());
w.counter("radiance:lookup_proposals_total",
"Prompt-lookup proposals made, with prompt lookup the only drafter.",
L, c_lookup_proposals_.get());
w.counter("radiance:lookup_held_total",
"Prompt-lookup proposals held back unverified: not expected to pay for their "
"verify rows at the measured step cost.", L, c_lookup_held_.get());
w.counter("radiance:lookup_held_drafts_total",
"Drafts in the held-back proposals.", L, c_lookup_held_drafts_.get());
w.counter("radiance:lookup_held_hits_total",
"Of the held-back proposals scored against the text that followed, the drafts "
"that came true: what verifying them would have accepted.",
L, c_lookup_held_hits_.get());
/* Decoupled prefix caching (spec §7.3). vllm:gpu_prefix_cache_hit_rate is the attention hit
* rate, as in vLLM. The linear side hits at a different granularity (whole checkpoints, not
+2 -1
View File
@@ -136,7 +136,7 @@ private:
* difference). Concurrent scrapes would both add the same difference, so they are serialised. */
std::mutex sample_mu_;
Counter c_prompt_tokens_, c_generation_tokens_, c_preemptions_;
Counter c_prompt_tokens_, c_generation_tokens_, c_preemptions_, c_preempt_forced_;
/* Engine steps. With speculation a step emits 1 + the accepted drafts, so tokens/s does not
* give step time; two scrapes of this counter and a clock do. */
Counter c_steps_;
@@ -150,6 +150,7 @@ private:
/* Exact totals behind the rate gauges; see render(). */
Counter c_prefill_tokens_, c_decode_tokens_, c_draft_tokens_, c_draft_accepted_;
Counter c_draft_refills_, c_draft_refill_tokens_;
Counter c_lookup_proposals_, c_lookup_held_, c_lookup_held_drafts_, c_lookup_held_hits_;
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
Counter c_prefix_expired_, c_prefix_ckpt_expired_;