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_;
+72 -15
View File
@@ -825,7 +825,14 @@ radiance --model qwen3.8-27b-fp8.rad --tp 1 --vision-tower-placement ram
*An n-gram table* (Qwen3.8-Flash-Next's is 47.7 GiB) is read a few rows a token. `disk` reads rows
from the container through a row cache with direct reads on the host; about half of a step's rows
are first-seen, so steps wait on the drive. `ram` copies the table into host memory at load (12 to
are first-seen, so steps wait on the drive. (That is libavx's `embed_lookup_q`. A host gather
without a row source of its own, such as libref's `embed_lookup_planes` over a GGUF table's planes,
reads through the mapping; the engine then asks for every page a step's rows cover before the
gather runs, so the drive answers them together rather than one fault at a time. A long gather
(a prefill chunk's) whose sampled rows are already resident is asked for beside the gather
instead, so a warm chunk does not wait for the asking: ~0.5 us a page, ~240 ms a rank for an
8192-token Engram chunk.
`--row-prefetch off` turns that off.) `ram` copies the table into host memory at load (12 to
40 s more startup, depending on the page cache) and the card's gather kernel reads the pinned copy,
so a step has no host work. `vram` puts all of it on every card. `ram` needs the table's size free
after the pinned host pools and the prefix cache's host tier, with `--host-headroom-mib` to spare
@@ -1326,6 +1333,50 @@ more than two windows is kept whole. The startup line `draft floor` says which a
`radiance:draft_refills_total` counts the hits ended early and `radiance:draft_refill_tokens_total`
the tokens recomputed.
**Prompt lookup.** The engine also drafts with no model at all: for each sequence it finds the
latest earlier occurrence of the sequence's last n tokens (prompt and output alike, n from
`--spec-ngram-max` down to `--spec-ngram-min`, 4 and 2 by default, the longest first) and proposes
the tokens that followed it, continuing past the end with its own proposal when the pattern repeats
within the window. There is no draft pass, and no proposal when nothing recurs, so such a step is an
ordinary decode. It pays where the reply copies its context -- code edits, rewrites, diffs, JSON,
quoting -- and costs a verify row per wrong draft elsewhere. Each sequence keeps an index of where
its n-grams last occurred (about 8 bytes a token per pattern length, 16 MiB at 400k tokens and the
default range), extended by each commit, so a lookup does not scan the context.
A verify row is not free: on a MoE each row reads its own routed experts, and five drafts can cost
a couple of plain steps. So when prompt lookup is the only drafter, a proposal is verified only when
it is expected to pay: K drafts are verified when E[accepted] * T(R) > tokens * (T(R + K) - T(R)),
with T(R) the measured time of a decode step of R query rows (timed online over every pure decode
step) and `tokens` what the step already expects to emit -- for one sequence, 1 + E[accepted] >
T(1 + K) / T(1). E[accepted] is the sequence's own record, kept apart for a match that runs at least
8 tokens back (the reply is copying a stretch; drafted at once) and a shorter one (a recurring
bigram; drafted once its record says so). A proposal held back is still scored against the tokens
the sequence goes on to emit, which is exactly what a verify would have accepted, so a sequence that
stops drafting on prose keeps learning and drafts again as soon as it starts copying. There is
nothing to configure; the constants are in `core/sched/lookup.h`. Only which proposals are verified
changes, never the text. `radiance:lookup_held_total` counts the held proposals.
```sh
radiance --model m.rad --spec-ngram 5 # prompt lookup alone, up to 5 drafts
radiance --model m.rad --spec-ngram 5 --draft-window adaptive # each sequence's window follows its acceptance
radiance --model m.rad --num-speculative-tokens 4 # a head drafts; lookup fills in where it declines
```
`--spec-ngram K` sets the window to K (a different `--num-speculative-tokens` is refused) and asks
the plugin to leave out any draft head the container carries (`RadBuildCtx::draft_head_off`), so
the head's weights take no memory: the choice for a model whose head does not fit, or does not pay.
A plugin that declares its head regardless is refused at startup. Without the flag, prompt lookup
still drafts for every sequence a declared head declines, and is the only drafter when speculation
is on (`--num-speculative-tokens N`) and the container has no head. Startup says which
(`speculation: prompt lookup only (--spec-ngram K)`), and the drafts count in `draft_n` /
`draft_n_accepted` and the `radiance:draft_*` metrics like a head's. Prompt lookup reads the
committed sequence, so a step is not issued ahead of the previous one's readback.
A lookup draft is a single token, a point mass, and the verify accepts it when the target's own draw
at that position equals it: with probability p(x), and otherwise the emitted token is the target's
draw conditioned on not being x. That is the speculative-sampling rule for a deterministic proposal,
so output is distribution-exact at any temperature and greedy text matches decoding without it.
**Adaptive window.** Code and JSON keep accepting deep into the window; prose falls off after a
position or two. With `--draft-window adaptive`, `--num-speculative-tokens` is the ceiling and the
engine keeps a smoothed acceptance per draft position for every sequence:
@@ -1342,9 +1393,11 @@ being emitted is under one in ten. The depth moves only after eight steps and fo
each new window is a new pass shape and a new recording. A new sequence starts from what earlier
sequences finished on.
The adaptive window needs a serial draft head; with a block drafter, prompt lookup alone, or
speculation off, the window stays fixed and startup says so. Prompt-lookup proposals made when the
head declines count in the acceptance metrics but do not move the window. At temperature 0 the text
A block drafter proposes its whole block in one pass and each sequence verifies the first min(D,
its stop) of it; prompt lookup as the only drafter is measured the same way, its drafts feeding each
sequence's estimate. With speculation off the window has nothing to adapt and startup says so.
Prompt-lookup proposals made when a head declines count in the acceptance metrics but do not move
the head's window. At temperature 0 the text
is that of a fixed depth wherever fixed depths agree; above 0 it is distribution-exact.
`radiance:draft_depth_adaptive` and `radiance:draft_verify_depth_total` (§6.3) show the windows.
@@ -1992,6 +2045,7 @@ by 0.002-0.003 nats.
|---|---|---|
| `--max-num-batched-tokens N` | 2048 | largest token count one step may carry |
| `--prefill-interleave N` | 0 (off) | decode-only steps after each prefill chunk while other sequences decode (§4.5), at most 64 |
| `--preempt-wait-ms N` | 5000 | how long a preempted prefill may wait for its whole-recompute gate before reclaiming cache blocks and preempting lowest-priority running requests until one overdue request can prefill; `0` falls back on the next step |
| `--busy-prefill-chunk MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens |
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
| `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
@@ -2012,6 +2066,8 @@ by 0.002-0.003 nats.
| `--ngram-placement WHERE` | auto | `auto`, `vram`, `ram` or `disk`: an n-gram table on the card, as a copy in RAM made at load and read by the card, or read from the container (§4.3) |
| `--vision-tower-placement WHERE` | vram | `vram` or `ram`: the encoder towers (vision, and audio where a model has one) on the card, or pinned in host memory beside `--host-pool-mib` and read in place once an image (§4.3) |
| `--weights-disk-tier` | off | read weights that fit neither VRAM nor the host pool from the container (O_DIRECT); routed experts a layer at a time |
| `--row-prefetch MODE` | on | `on` or `off`: a host gather from a table read through the container's mapping (`--ngram-placement disk`) asks for its rows' pages before its kernel, or beside it when they are resident (§4.3); the output is the same either way |
| `--mapped-rewarm MODE` | on | `on` or `off`: at startup, the pages of such a table an earlier run left in the page cache, and the load's own allocations pushed out, are asked for again (at most half of the available memory), so the first requests after a restart do not read them from the drive |
**LoRA adapters** (§4.9.1)
@@ -2059,9 +2115,11 @@ by 0.002-0.003 nats.
| flag | default | |
|---|---|---|
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
| `--spec-ngram K` | 0 | prompt lookup alone: up to K drafts a step from the sequence's own n-grams, each proposal verified when it pays at the measured step cost; no draft head declared; sets the window to K (§4.6) |
| `--spec-ngram-min N`, `--spec-ngram-max N` | 2, 4 | the pattern lengths prompt lookup tries, longest first (at most 15), wherever it drafts |
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, for a serial draft head or prompt lookup alone (§4.6) |
| `--draft-short-from N` | auto | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below or at one sequence; 0 never; auto never for a chain and 2 for a tree drafter, which then verifies the short block's nodes (§4.6) |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature 0.6 (where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged. A DFlash2 drafter (Qwen3.5/3.8) couples its candidate walk instead: each position is sampled from the softmax of the walk's own scores over its best eight candidates, at temperature `RADIANCE_DFLASH_Q_TEMP` (default 0.6, where acceptance peaked); on Qwen3.8-27B MXFP4 TP2 at 2x R9700 and request temperature 1, tokens per verify step +8% on held-out prompts at c4 (3.53 to 3.82) and decode +2..8% per stream at c1/c4. Any other drafter is refused at startup |
| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
**Server**
@@ -2070,7 +2128,7 @@ by 0.002-0.003 nats.
|---|---|---|
| `--host ADDR` | 0.0.0.0 | listen address |
| `--port N` | 8000 | listen port |
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6); the key must be non-empty |
| `--api-key KEY` | none | require `Authorization: Bearer KEY` or `X-Api-Key: KEY` on every request but `/health`, `/v1/health`, `/ping` and the dashboard page (§6.6) |
| `--served-model-name NAME` | container's name | the model id `/v1/models` lists, the metrics carry and a response names when its request named none. A request may name any model; the loaded one serves it |
| `--mm-max-patches N` | auto | patches one vision-encoder pass carries, and so the largest image (a patch is 16x16 pixels, 14x14 on GLM-5.3). `auto` is 16384 when the container carries a vision tower; 0 serves text only and keeps the tower off the card. A pass is not one tower invocation: inside it the tower batches at most 8 tiles per weight read, and the pass size may reduce that (4 tiles at the 64-pixel grid with the default 16384 patches); a picture contributes a separate pass per grid. See the concurrency notes for Unlimited-OCR (§5.17) |
| `--override-chat-template PATH` | container's | a Jinja chat template file served in place of the container's. The reply format (reasoning markers, tool calls) is derived from it too, unless the architecture plugin declares one. An unreadable or empty file stops startup |
@@ -2138,6 +2196,8 @@ flags are refused on it, and so are the pixel bands.
| `--debug-graph` | print the declared graph and the selection table, and exit |
| `--debug-selection` | print the selection table |
| `--debug-placement` | print the placement plan |
| `--debug-draft-oracle FILE` | a verify-path test, not a drafter: with `--spec-ngram`, prompt lookup proposes from the token ids in `FILE` (a plain greedy run's continuation of the one prompt the test sends) with 30% of the drafts corrupted, so verifies accept and reject at every depth; the text must stay the plain run's |
| `--debug-tape-dump` | list the dispatches of the first recorded pass of each kind (`TAPEDUMP` lines on stderr, every rank) and which of them start unordered behind the one before |
| `--debug-accept-reference-kernels` | serve even when ops resolve to `libref`. Not a production configuration |
| `--profile-ops` | per-op device timing |
| `--expert-stats FILE` | count the routed experts every layer selects, apart for prefill, decode, mixed steps and draft-head passes, and write them to `FILE` as JSON every 30 s and at shutdown (written through a temporary and a rename). Counted on the host from the routing histograms the core already copies back for the heat engine, so it adds no device work and no synchronisation; under expert parallelism each rank's slice is mapped to the model's expert ids through the container's directory |
@@ -3531,6 +3591,7 @@ there is none.
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
| `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
| `lookup_proposals_total`, `lookup_held_total`, `lookup_held_drafts_total`, `lookup_held_hits_total` | prompt lookup as the only drafter: proposals made, proposals held back as not paying for their verify rows and their drafts, and of the held ones scored against the text that followed, the drafts that came true (§4.6) |
| `decode_rows_unspeculated_total` | rows that never drafted |
| `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
| `engine_prefill_chunks_capped_total` | prefill chunks held back to share a step (§4.5) |
@@ -3543,7 +3604,8 @@ there is none.
| `prefix_restore_cuts_total` | restores from the host tier the pool could not hold whole, even after giving up other conversations' VRAM copies (§4.8); `RADIANCE_LOG=debug` logs where each was cut |
| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` removed (§4.8) |
| `prefix_cache_released_total{what}` | entries and snapshots clients forgot through `DELETE /sessions` (§4.8) |
| `num_requests_preempted` | |
| `num_requests_preempted` | |
| `preempt_forced_total` | preempted prefill waits that ended by reclaiming cache blocks and forcing a lowest-priority running victim (`--preempt-wait-ms`) |
| `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | |
| `client_disconnect_total`, `stream_overflow_total` | |
@@ -3594,16 +3656,11 @@ With a key, every request must carry `Authorization: Bearer KEY` (or Anthropic's
or it is answered 401, `/tokenize` and `/server_info` included. Exempt are `/health`, `/v1/health` and
`/ping`, because load balancers cannot send a bearer token, and the dashboard page (`/`,
`/dashboard`), which holds no data: on a 401 it asks for the key, keeps it in the browser's storage
and sends it on every data fetch. The exemption follows those paths' methods -- reads, plus the
`POST /ping` of the health-check convention -- so it cannot follow a method no route answers.
An empty `--api-key` value is a startup error: it would guard nothing.
and sends it on every data fetch.
Without a key, `/diagnostics` answers only loopback clients (others get 403), because it describes
the host: kernel, boot parameters, PCI layout, memory limits. Read it on the machine, or start the
server with `--api-key`. The same loopback-only rule covers the control-vector default and runtime
LoRA loads, and a browser page on another origin does not qualify as a loopback client even when
its own machine serves the port: that is how a hostile web page would reach these routes through a
victim's browser, and a request that says `Origin: http://evil` is refused the way a remote one is.
server with `--api-key`.
The key is not encrypted in transit. On a network you do not control, bind to localhost behind a
TLS-terminating reverse proxy:
+39 -1
View File
@@ -440,6 +440,7 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--tp-attn-split", { "rows" } }, { "--weight-prefetch", { "off" } },
{ "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } },
{ "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } },
{ "--preempt-wait-ms", { "5000" } },
{ "--max-num-seqs", { "4" } },
{ "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } },
{ "--gpu-headroom-mib", { "128" } }, { "--kv-cache-dtype", { "fp8" } },
@@ -448,12 +449,16 @@ const std::map<std::string, std::vector<std::string>>& legal_values() {
{ "--host-pool-mib", { "1024" } }, { "--host-headroom-mib", { "2048" } },
{ "--embedding-placement", { "vram" } },
{ "--vision-tower-placement", { "ram" } }, { "--ngram-placement", { "disk" } },
{ "--row-prefetch", { "off" } }, { "--mapped-rewarm", { "off" } },
{ "--debug-draft-oracle", { "/o.txt", "--spec-ngram", "4" } },
{ "--prefix-cache-mib", { "256" } }, { "--prefix-cache-ttl", { "60" } },
{ "--placement", { "all_vram" } }, { "--checkpoint-interval", { "256" } },
{ "--prefill-span", { "2" } },
{ "--checkpoint-slots", { "4" } }, { "--checkpoint-policy", { "tip-only" } },
{ "--prefix-resume", { "nearest" } },
{ "--num-speculative-tokens", { "2" } }, { "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } },
{ "--num-speculative-tokens", { "2" } }, { "--spec-ngram", { "4" } },
{ "--spec-ngram-min", { "1" } }, { "--spec-ngram-max", { "6" } },
{ "--draft-window", { "fixed" } }, { "--draft-short-from", { "4" } },
{ "--draft-coupling", { "on" } },
{ "--host", { "127.0.0.1" } }, { "--port", { "8001" } }, { "--api-key", { "k" } },
{ "--served-model-name", { "m" } }, { "--mm-max-patches", { "1024" } },
@@ -1263,6 +1268,39 @@ TEST(auto_speculation_is_negative_one_and_not_zero) {
CHECK_EQ(d.n_spec, -1); /* auto is also the default */
}
/* --spec-ngram K is prompt lookup alone at window K: it sets the window, agrees with a matching
* --num-speculative-tokens and refuses another; the pattern range must be a range. Off by
* default, at the lengths 2..4. */
TEST(spec_ngram_sets_the_window_and_refuses_another) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK_EQ(d.spec_ngram, 0);
CHECK_EQ(d.spec_ngram_min, 2);
CHECK_EQ(d.spec_ngram_max, 4);
Config c;
CHECK_EQ(parse({ "--spec-ngram", "5" }, &c), RAD_OK);
CHECK_EQ(c.spec_ngram, 5);
CHECK_EQ(c.n_spec, 5);
Config e;
CHECK_EQ(parse({ "--spec-ngram", "5", "--num-speculative-tokens", "5" }, &e), RAD_OK);
CHECK_EQ(e.n_spec, 5);
Config f;
{
LogGuard lg;
CHECK_EQ(parse({ "--spec-ngram", "5", "--num-speculative-tokens", "3" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--spec-ngram", "5", "--num-speculative-tokens", "auto" }, &f),
RAD_E_INVAL);
CHECK_EQ(parse({ "--spec-ngram-min", "5", "--spec-ngram-max", "3" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--spec-ngram-max", "16" }, &f), RAD_E_INVAL);
CHECK_EQ(parse({ "--spec-ngram", "65" }, &f), RAD_E_INVAL);
}
Config g;
CHECK_EQ(parse({ "--spec-ngram-min", "1", "--spec-ngram-max", "8" }, &g), RAD_OK);
CHECK_EQ(g.spec_ngram_min, 1);
CHECK_EQ(g.spec_ngram_max, 8);
CHECK_EQ(g.n_spec, -1); /* the range alone changes no window */
}
/* --gpu-headroom is an alias for --gpu-headroom-mib; both set the same field. */
TEST(gpu_headroom_parses_under_both_spellings) {
Config a, b, d;
+486 -75
View File
@@ -11,7 +11,7 @@
#include "server/sink.h"
#include <algorithm>
#include <cstdint>
#include <chrono>
#include <cstdlib>
#include <cstring>
#include <new>
@@ -98,9 +98,7 @@ struct Fixture {
g_gdn_row = KernelRow{ &g_gdn_ki, "fake", 0, 0 };
prog.meta.n_ctx_train = 4096;
/* Above the 1000 + i the requests below spell: admission refuses ids past the
* vocabulary, and these prompts must be admissible. */
prog.meta.n_vocab = 65536;
prog.meta.n_vocab = 512;
/* index 0 is the sentinel every handle table in Program carries */
prog.ops.emplace_back();
@@ -1283,30 +1281,6 @@ TEST(a_scored_request_names_real_vocabulary_rows) {
CHECK(!kept->may_speculate);
}
/* The prompt itself names real vocabulary rows too: raw id arrays arrive verbatim from the
* request body, and an id past the embedding table must die at admission, never staged into a
* pass — the embedding gather would fail the step, a failed step is a device fault, and a
* device fault stops the engine (spec §17). One bad number must not be a server kill. */
TEST(a_prompt_names_real_vocabulary_rows) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
const int32_t n_vocab = (int32_t)f.prog.meta.n_vocab;
std::unique_ptr<Request> rs[5];
const std::vector<std::vector<int32_t>> ids = { { 1, 2, n_vocab - 1 }, { n_vocab }, { -1 },
{ 7, INT32_MAX }, { 0, 1, 2, n_vocab + 9 } };
int rc[5] = { -1, -1, -1, -1, -1 };
for (int i = 0; i < 5; ++i) {
rs[i] = std::make_unique<Request>();
rs[i]->id = f.next_id++;
rs[i]->max_tokens = 1;
rs[i]->prompt = ids[(size_t)i];
}
f.sch.add_all(rs, 5, rc);
CHECK_EQ(rc[0], RAD_OK);
for (int i = 1; i < 5; ++i) CHECK_EQ(rc[i], RAD_E_INVAL);
}
TEST(a_prefix_hit_starts_the_request_at_the_last_usable_checkpoint) {
Fixture f;
f.build();
@@ -1704,6 +1678,7 @@ TEST(preemption_takes_the_lowest_priority_victim_and_requeues_it_to_the_front) {
TEST(a_preempted_prefill_waits_for_the_whole_prompt_and_running_headroom) {
Fixture f;
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
f.cfg.preempt_wait_ms = 60000; /* old gate test: no fallback in its 80 steps */
CHECK_OK(f.start());
uint64_t a = f.submit(287, 64, /*priority=*/5);
@@ -1750,6 +1725,63 @@ TEST(a_preempted_prefill_waits_for_the_whole_prompt_and_running_headroom) {
f.commit_plain();
}
/* The gate's wait is bounded: after --preempt-wait-ms an overdue preempted prefill gets room by
* preempting the lowest-priority running request before the step is planned, so it cannot queue
* forever behind a long decode (the 710 s stall in the daily's log). */
TEST(a_preempted_prefill_falls_back_to_a_running_victim_after_the_wait) {
Fixture f;
f.build(/*blocks=*/26, /*states=*/64); /* 26 x 16 = 416 tokens */
f.cfg.preempt_wait_ms = 0; /* fallback on the next step */
CHECK_OK(f.start());
uint64_t a = f.submit(287, 64, /*priority=*/5);
uint64_t b = f.submit(128, 64, /*priority=*/0);
/* A and B fill the pool; B's next token needs a block and B is the victim. */
CHECK(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().e.size(), 2);
f.commit_plain();
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Preempted);
f.commit_plain();
/* B's blocks are back in the pool; the old gate wants B's whole prompt plus one block of
* headroom beside A's next token, so it cannot admit B without a victim. */
CHECK(f.sch.step() != nullptr);
CHECK_EQ((int)f.sch.find(b)->state, (int)ReqState::Running);
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Running);
CHECK_EQ(f.sch.metrics().preemptions, 2);
CHECK_EQ(f.sch.metrics().preempted_waiting, 0);
f.commit_plain();
}
/* Several overdue preempted prefills: reclaiming for the head alone is not enough. Keep forcing
* the lowest-priority runner until one overdue request can prefill, so the rest of the queue
* cannot sit in Preempted behind a head that still does not fit. */
TEST(overdue_preempted_prefills_keep_forcing_until_one_fits) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64); /* 20 x 16 = 320 tokens */
f.cfg.preempt_wait_ms = 0;
f.cfg.max_seqs = 3;
CHECK_OK(f.start());
uint64_t a = f.submit(160, 16, /*priority=*/5);
uint64_t b = f.submit(80, 16, /*priority=*/3);
uint64_t c = f.submit(48, 16, /*priority=*/0);
CHECK(f.sch.step() != nullptr);
f.commit_plain();
/* Fill until the pool refuses someone. Then the overdue path must not leave every preempted
* request waiting while a runner keeps the blocks. */
for (int i = 0; i < 8; ++i) {
if (!f.sch.step()) break;
f.commit_plain();
}
CHECK(f.sch.metrics().preempted_waiting == 0 || f.sch.metrics().preempt_forced > 0);
CHECK(f.sch.metrics().running + f.sch.metrics().preempted_waiting > 0);
(void)a; (void)b; (void)c;
}
TEST(a_mixed_step_has_the_right_boundaries_and_slot_mapping) {
Fixture f;
f.build();
@@ -3340,9 +3372,9 @@ TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) {
CHECK_EQ(h.plan_step(hone, 0, 3), 2);
}
/* The flag, for a drafting head (serial or block). --draft-window adaptive with prompt lookup
* alone, or with no speculation, keeps the configured depth and says so at startup; the proposal
* then reaches the step uncut. The default is the fixed window. */
/* The flag, for a drafting head (serial or block) or prompt lookup alone. --draft-window adaptive
* with no speculation keeps the configured depth and says so at startup. The default is the fixed
* window. */
TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_none) {
{
Fixture f;
@@ -3395,6 +3427,8 @@ TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_no
CHECK(f.sch.metrics().draft_verify_depth[4] > 0);
CHECK(f.sch.metrics().draft_verify_depth[1] > 0);
}
/* Prompt lookup as the only drafter takes the policy as a block drafter does: each of its
* drafts is a verify row (prompt_lookup_alone_follows_its_own_acceptance). */
{
Fixture f;
adaptive_fixture(f, 4);
@@ -3403,9 +3437,9 @@ TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_no
int st = RAD_E_STATE;
const std::string log = info_of([&] { st = f.start(); });
CHECK_OK(st);
CHECK(!f.sch.draft().adaptive());
CHECK(log.find("--draft-window adaptive: the window is fixed at 4") != std::string::npos);
CHECK(log.find("prompt lookup only") != std::string::npos);
CHECK(f.sch.draft().adaptive());
CHECK(log.find("--draft-window adaptive with prompt lookup only") != std::string::npos);
CHECK(log.find("the window is fixed") == std::string::npos);
const uint64_t a = f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
@@ -3413,7 +3447,7 @@ TEST(the_adaptive_window_is_a_flag_for_a_drafting_head_and_said_when_there_is_no
int32_t draft[4] = { 21, 22, 23, 24 };
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_EQ(f.sch.find(a)->n_draft, 4);
CHECK(!f.sch.metrics().draft_adaptive);
CHECK(f.sch.metrics().draft_adaptive);
}
{
Fixture f;
@@ -3613,6 +3647,423 @@ TEST(the_adaptive_window_is_not_fed_by_prompt_lookup) {
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6);
}
/* With prompt lookup the only drafter, its drafts are what the adaptive window measures: refused
* lookups bring each sequence's window, and the lookup's proposals, down to one draft. */
TEST(prompt_lookup_alone_follows_its_own_acceptance) {
Fixture f;
adaptive_fixture(f, 4);
f.prog.drafter.kind = RAD_DRAFT_NONE;
f.prog.drafter.depth = 0;
CHECK_OK(f.start());
REQUIRE(f.sch.draft().adaptive());
auto r = std::make_unique<Request>();
r->id = f.next_id++;
r->max_tokens = 2000;
r->prompt.resize(160);
for (int i = 0; i < 160; ++i) r->prompt[(size_t)i] = 100 + i % 8;
CHECK_OK(f.sch.add(std::move(r)));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(100);
int first = 0, last = 0, lookups = 0;
for (int t = 0; t < 6 * DraftController::kHold; ++t) {
REQUIRE(f.sch.step() != nullptr);
const StepEntry& e = f.sch.plan().e[0];
if (e.n_spec > 0) {
CHECK(e.ngram);
/* What the pattern says comes next, the period continued. */
CHECK_EQ(e.draft[0], 100 + (t + 1) % 8);
if (!first) first = e.n_spec;
last = e.n_spec;
++lookups;
}
f.commit_plain(100 + (t + 1) % 8); /* every lookup refused */
}
CHECK_EQ(lookups, 6 * DraftController::kHold);
CHECK_EQ(first, 4);
CHECK_EQ(last, 1);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6);
}
/* ------------------------------------------------------------------ prompt lookup's verify gate */
/* A held proposal is scored against the text that follows, as a verify would have scored it: its
* accepted count is the common prefix. One proposal at a time; the next is taken once it ends. */
TEST(the_lookup_gate_scores_a_held_proposal_against_the_text_that_follows) {
LookupGate g;
g.configure(4);
LookupSeq q;
/* The priors: a short match waits, a long one drafts. */
CHECK_NEAR(g.expect(q, 0, 4), 4 * LookupGate::kPriorShort, 1e-6);
CHECK_NEAR(g.expect(q, 1, 4), 4 * LookupGate::kPriorLong, 1e-6);
CHECK_EQ(LookupGate::class_of(LookupGate::kLongMatch - 1), 0);
CHECK_EQ(LookupGate::class_of(LookupGate::kLongMatch), 1);
std::vector<int32_t> text(10, 1); /* the sequence so far: 10 tokens */
TokenSeq ts;
auto view = [&]() {
ts.a = text.data();
ts.na = (int64_t)text.size();
};
const int32_t prop[4] = { 5, 6, 7, 8 };
g.offer(q, 10, prop, 4, 2);
g.held(q, 4);
const int32_t other[4] = { 40, 41, 42, 43 };
g.offer(q, 10, other, 4, 9); /* pending already: counted, not taken */
CHECK_EQ(q.proposed, (int64_t)2);
CHECK_EQ(q.pend_cls, 0);
text.push_back(5); /* the first came true; no verdict yet */
view();
g.advance(q, ts);
CHECK(q.pend_pos >= 0);
CHECK_NEAR(q.s[0][0], 0.0, 1e-6);
text.push_back(6);
text.push_back(9); /* two came true, the third did not */
view();
g.advance(q, ts);
CHECK(q.pend_pos < 0);
/* The prior weighs two proposals: the first evaluated moves each position a third. */
const double w = 1.0 / (LookupGate::kPriorWeight + 1.0);
CHECK_NEAR(q.s[0][0], w, 1e-6);
CHECK_NEAR(q.s[0][1], w, 1e-6);
CHECK_NEAR(q.s[0][2], 0.0, 1e-6);
CHECK_NEAR(q.s[0][3], 0.0, 1e-6);
CHECK_NEAR(q.s[1][0], LookupGate::kPriorLong, 1e-6); /* the other class untouched */
CHECK_EQ(q.held_hits, (int64_t)2);
CHECK_EQ(g.held_hits(), (int64_t)2);
CHECK_EQ(g.held_count(), (int64_t)1);
CHECK_EQ(g.held_drafts(), (int64_t)4);
/* A proposal that comes true whole ends at its last token; a verified one counts no held
* hits but feeds the estimate the same way. */
const int64_t at = (int64_t)text.size();
const int32_t whole[4] = { 11, 12, 13, 14 };
g.offer(q, at, whole, 4, 3);
for (int32_t t : whole) text.push_back(t);
view();
g.advance(q, ts);
CHECK(q.pend_pos < 0);
CHECK(q.s[0][3] > 0.0f);
CHECK_EQ(q.held_hits, (int64_t)2);
/* Evidence is what moves a short match into drafting: a run of proposals that come true. */
LookupGate g2;
g2.configure(4);
LookupSeq r;
CHECK(!g2.pays(g2.expect(r, 0, 4), 4, 1, 1.0));
std::vector<int32_t> s2(4, 1);
for (int i = 0; i < 6; ++i) {
const int32_t p2[4] = { 2, 3, 4, 5 };
g2.offer(r, (int64_t)s2.size(), p2, 4, 2);
for (int32_t t : p2) s2.push_back(t);
TokenSeq t2;
t2.a = s2.data();
t2.na = (int64_t)s2.size();
g2.advance(r, t2);
}
CHECK(g2.expect(r, 0, 4) > 2.9); /* 6 / (6 + 2) a position */
CHECK(g2.pays(g2.expect(r, 0, 4), 4, 1, 1.0));
}
/* What a verify costs: the measured step time at the step's rows with the drafts against without
* them; between timed row counts a line, outside them the nearest scaled by the prior's shape. */
TEST(the_lookup_gate_prices_a_verify_by_measured_step_times) {
LookupGate g;
g.configure(4);
/* Untimed: the prior shape, 6% a row, so a whole window pays at a quarter of a token. */
CHECK_NEAR(g.step_cost(5) / g.step_cost(1), 1.0 + 4 * LookupGate::kRowCost, 1e-9);
CHECK(g.pays(0.3, 4, 1, 1.0));
CHECK(!g.pays(0.2, 4, 1, 1.0));
CHECK(!g.pays(0.0, 4, 1, 1.0));
/* One row timed: a verify is priced off it on the prior's shape. */
for (int i = 0; i < 8; ++i) g.step_time(1, 10.0);
CHECK_EQ(g.cost_samples(1), (int64_t)8);
CHECK_NEAR(g.step_cost(5), 10.0 * (1.0 + 4 * LookupGate::kRowCost), 1e-9);
/* Both timed: 2.5x for four drafts (a MoE reading each row's experts). 1 + E must beat it. */
for (int i = 0; i < 8; ++i) g.step_time(5, 25.0);
CHECK_NEAR(g.step_cost(5), 25.0, 1e-9);
CHECK_NEAR(g.step_cost(3), 17.5, 1e-9); /* between: the line */
CHECK(!g.pays(1.4, 4, 1, 1.0));
CHECK(g.pays(1.6, 4, 1, 1.0));
/* Past the last timed count: the prior's shape from there. */
CHECK_NEAR(g.step_cost(9), 25.0 * (1.0 + 8 * LookupGate::kRowCost) /
(1.0 + 4 * LookupGate::kRowCost), 1e-9);
/* In a step of eight rows already expecting eight tokens, the same drafts weigh against the
* whole step: marginal cost over the step's rate. */
for (int i = 0; i < 8; ++i) g.step_time(8, 30.0);
for (int i = 0; i < 8; ++i) g.step_time(12, 36.0);
CHECK(!g.pays(1.5, 4, 8, 8.0)); /* 1.5 / 8 < 36 / 30 - 1 */
CHECK(g.pays(1.7, 4, 8, 8.0));
/* A step that waited on something else counts as at most four times the mean. */
g.step_time(1, 1000.0);
CHECK(g.step_cost(1) < 10.0 + 40.0 / 8.0);
/* Junk is ignored. */
g.step_time(0, 5.0);
g.step_time(2, -1.0);
CHECK_EQ(g.cost_samples(2), (int64_t)0);
/* Wide steps share keys in bands of 32 rows past 128. */
g.step_time(200, 80.0);
g.step_time(210, 90.0);
CHECK_EQ(g.cost_samples(205), (int64_t)2);
}
/* The index says how far the match behind a proposal runs back, up to the cap. */
TEST(prompt_lookup_reports_how_far_its_match_runs_back) {
NgramIndex ix;
/* 1 2 3 4 5 6 7 8 9 | 30 31 | 5 6 7 8 9: the last four match 5 6 7 8 9 at its first place,
* which runs five back; 30 31 then follows. */
std::vector<int32_t> s = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 30, 31, 5, 6, 7, 8, 9 };
TokenSeq ts;
ts.a = s.data();
ts.na = (int64_t)s.size();
int32_t out[4];
int m = -1;
CHECK_EQ(ix.propose(ts, 2, 4, 4, out, &m, 8), 4);
CHECK_EQ(out[0], 30);
CHECK_EQ(m, 5);
/* A copy that runs back further is cut at the cap. */
std::vector<int32_t> c;
for (int i = 0; i < 20; ++i) c.push_back(100 + i);
for (int i = 0; i < 12; ++i) c.push_back(100 + i);
TokenSeq tc;
tc.a = c.data();
tc.na = (int64_t)c.size();
NgramIndex ic;
CHECK_EQ(ic.propose(tc, 2, 4, 4, out, &m, 8), 4);
CHECK_EQ(out[0], 112);
CHECK_EQ(m, 8);
/* Without the out-parameter nothing changes. */
NgramIndex id;
CHECK_EQ(id.propose(tc, 2, 4, 4, out), 4);
}
namespace {
/* A lookup-only deployment (no draft head) at window `depth`, the fixed window (the default). */
void lookup_fixture(Fixture& f, int depth) {
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = depth;
f.prog.drafter.kind = RAD_DRAFT_NONE;
f.prog.drafter.depth = 0;
}
} /* namespace */
/* Prompt lookup alone, the gate on by default. Text that copies a stretch it has seen drafts at
* once and keeps drafting while its drafts come true; text that only repeats bigrams it has seen,
* whose proposals do not come true, is never verified, yet every proposal is still scored; and a
* reply that turns from the second kind into the first drafts as soon as it does. The text is
* the same either way: the emitted token is the fixture's, whatever was verified. */
TEST(prompt_lookup_alone_holds_back_proposals_that_do_not_pay) {
Fixture f;
lookup_fixture(f, 4);
std::string log = info_of([&]() { CHECK_OK(f.start()); });
CHECK(log.find("prompt lookup: a proposal is verified when") != std::string::npos);
CHECK(!f.sch.draft().adaptive());
/* A copy: an 8-token period, 160 tokens of it; the reply goes on with it. */
auto r = std::make_unique<Request>();
r->id = f.next_id++;
r->max_tokens = 2000;
r->prompt.resize(160);
for (int i = 0; i < 160; ++i) r->prompt[(size_t)i] = 100 + i % 8;
CHECK_OK(f.sch.add(std::move(r)));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(100);
f.sch.step_finished(); /* a prefill step: not a sample */
for (int64_t rows = 1; rows <= 5; ++rows)
CHECK_EQ(f.sch.lookup_gate().cost_samples(rows), (int64_t)0);
int64_t pos = 161; /* the next token's place in the period */
auto truth = [&](int64_t p) { return (int32_t)(100 + p % 8); };
int verified = 0;
for (int t = 0; t < 24; ++t) {
REQUIRE(f.sch.step() != nullptr);
const StepEntry& e = f.sch.plan().e[0];
int32_t a = 0;
if (e.n_spec > 0) {
CHECK(e.ngram);
++verified;
while (a < e.n_spec && e.draft[a] == truth(pos + a)) ++a;
}
CHECK_OK(f.commit(truth(pos + a), 0, [a](const StepEntry&) { return a; }));
f.sch.step_finished(); /* a decode step of 1 + 4 rows, timed */
pos += a + 1;
}
CHECK_EQ(verified, 24);
CHECK_EQ(f.sch.lookup_gate().cost_samples(5), (int64_t)24);
SchedMetrics m = f.sch.metrics();
CHECK_EQ(m.lookup_held, (int64_t)0);
CHECK_EQ(m.lookup_proposals, (int64_t)24);
CHECK_EQ(m.draft_accepted, m.draft_tokens);
/* Recurring bigrams: the prompt holds every pair of the reply 200, 201, 202, ... followed by
* a 50, so after each token the lookup proposes 50 on a two-token match, and it never comes
* true. */
Fixture g;
lookup_fixture(g, 4);
CHECK_OK(g.start());
auto q = std::make_unique<Request>();
q->id = g.next_id++;
q->max_tokens = 2000;
for (int i = 0; i < 60; ++i) {
q->prompt.push_back(200 + i);
q->prompt.push_back(201 + i);
q->prompt.push_back(50);
}
q->prompt.push_back(199);
CHECK_OK(g.sch.add(std::move(q)));
REQUIRE(g.sch.step() != nullptr);
g.commit_plain(200);
int proposals = 0;
for (int t = 0; t < 40; ++t) {
REQUIRE(g.sch.step() != nullptr);
CHECK_EQ(g.sch.plan().e[0].n_spec, 0); /* held, every one */
g.commit_plain(201 + t);
++proposals;
}
m = g.sch.metrics();
CHECK_EQ(m.draft_tokens, (int64_t)0);
CHECK(m.lookup_proposals >= proposals - 1);
CHECK_EQ(m.lookup_held, m.lookup_proposals);
CHECK_EQ(m.lookup_held_drafts, 4 * m.lookup_held);
CHECK_EQ(m.lookup_held_hits, (int64_t)0);
/* The reply now copies its own stretch 201.. from the start: a long match, drafted at once. */
std::vector<int32_t> copy;
for (int i = 0; i < 40; ++i) copy.push_back(200 + i);
size_t k = 0;
int drafted_steps = 0, steps = 0;
while (k < copy.size() && steps < 40) {
REQUIRE(g.sch.step() != nullptr);
const StepEntry& e = g.sch.plan().e[0];
int32_t a = 0;
if (e.n_spec > 0) {
++drafted_steps;
while (a < e.n_spec && k + (size_t)a < copy.size() &&
e.draft[a] == copy[k + (size_t)a])
++a;
}
CHECK_OK(g.commit(copy[std::min(k + (size_t)a, copy.size() - 1)], 0,
[a](const StepEntry&) { return a; }));
k += (size_t)a + 1;
++steps;
}
CHECK(drafted_steps > 0);
CHECK(g.sch.metrics().draft_accepted > 0);
}
namespace {
/* Prompt lookup by scanning: the longest pattern first, its latest earlier occurrence, the
* proposal continued past the end with its own tokens. The index must answer exactly this. */
int scan_propose(const std::vector<int32_t>& s, int nmin, int nmax, int depth, int32_t* out) {
const int64_t L = (int64_t)s.size();
if (L < 2) return 0;
for (int n = (int)std::min<int64_t>(nmax, L - 1); n >= nmin; --n)
for (int64_t e = L - 2; e >= n - 1; --e) {
bool ok = true;
for (int k = 0; k < n && ok; ++k) ok = s[(size_t)(e - k)] == s[(size_t)(L - 1 - k)];
if (!ok) continue;
for (int d = 0; d < depth; ++d) {
const int64_t i = e + 1 + d;
out[d] = i < L ? s[(size_t)i] : out[i - L];
}
return depth;
}
return 0;
}
} /* namespace */
/* The index against the scan, over sequences grown a few tokens at a time across the prompt /
* output seam, on alphabets small enough to repeat often and large enough to miss, at several
* pattern ranges; then a change of range and a shorter sequence, which rebuild it. */
TEST(prompt_lookup_index_answers_what_a_scan_answers) {
uint32_t rng = 12345;
auto next = [&](uint32_t mod) { rng = rng * 1664525u + 1013904223u; return (rng >> 8) % mod; };
const int kRanges[][2] = { { 1, 1 }, { 1, 4 }, { 2, 4 }, { 3, 7 }, { 15, 15 } };
int64_t hits = 0, misses = 0;
for (const uint32_t alphabet : { 2u, 5u, 40u, 3000u }) {
for (const auto& rg : kRanges) {
std::vector<int32_t> seq;
const int64_t np = 50 + next(200);
NgramIndex ix;
ix.reset(7);
while (seq.size() < 1500) {
const int add = 1 + (int)next(6);
for (int k = 0; k < add; ++k) {
/* Runs and copies as well as noise, so long patterns recur. */
if (seq.size() > 20 && next(4) == 0) {
const size_t from = next((uint32_t)seq.size() - 10);
for (int c = 0; c < 6; ++c) seq.push_back(seq[from + (size_t)c]);
} else {
seq.push_back((int32_t)next(alphabet));
}
}
TokenSeq ts;
ts.a = seq.data();
ts.na = std::min<int64_t>(np, (int64_t)seq.size());
ts.b = seq.data() + ts.na;
ts.nb = (int64_t)seq.size() - ts.na;
int32_t want[8] = {}, got[8] = {};
const int depth = 1 + (int)next(8);
const int w = scan_propose(seq, rg[0], rg[1], depth, want);
const int g = ix.propose(ts, rg[0], rg[1], depth, got);
CHECK_EQ(g, w);
if (g == w) CHECK(std::memcmp(got, want, sizeof(int32_t) * (size_t)w) == 0);
(w ? hits : misses) += 1;
}
CHECK_EQ(ix.indexed(), (int64_t)seq.size() - 1);
CHECK(ix.bytes() <= (size_t)(16 * (rg[1] - rg[0] + 1)) * seq.size() + 8192);
}
}
CHECK(hits > 100);
CHECK(misses > 100);
/* Another range, then a shorter sequence (another request in the slot): both rebuild. */
std::vector<int32_t> a = { 1, 2, 3, 9, 1, 2, 3 };
TokenSeq ta{ a.data(), (int64_t)a.size(), nullptr, 0 };
NgramIndex ix;
int32_t out[4] = {};
CHECK_EQ(ix.propose(ta, 2, 4, 2, out), 2);
CHECK_EQ(out[0], 9);
CHECK_EQ(out[1], 1);
CHECK_EQ(ix.propose(ta, 4, 4, 2, out), 0); /* no 4-gram recurs */
std::vector<int32_t> b = { 5, 6, 5 };
TokenSeq tb{ b.data(), (int64_t)b.size(), nullptr, 0 };
CHECK_EQ(ix.propose(tb, 1, 4, 3, out), 3); /* period 2, continued: 6 5 6 */
CHECK_EQ(out[0], 6);
CHECK_EQ(out[1], 5);
CHECK_EQ(out[2], 6);
}
/* A lookup costs the n-grams the last commit added, not a pass over the context: over a 400k-token
* prompt that never repeats a 2-gram, the first lookup indexes it once and the next thousand
* lookups, a token apart, together take a small fraction of that. */
TEST(prompt_lookup_does_not_scan_the_context) {
std::vector<int32_t> seq;
seq.reserve(401000);
for (int i = 0; i < 400000; ++i) seq.push_back(i); /* every token distinct: always a miss */
NgramIndex ix;
int32_t out[8];
TokenSeq ts{ seq.data(), (int64_t)seq.size(), nullptr, 0 };
const auto t0 = std::chrono::steady_clock::now();
CHECK_EQ(ix.propose(ts, 2, 4, 8, out), 0);
const auto t1 = std::chrono::steady_clock::now();
for (int i = 0; i < 1000; ++i) {
seq.push_back(1000000 + i);
TokenSeq t2{ seq.data(), (int64_t)seq.size(), nullptr, 0 };
CHECK_EQ(ix.propose(t2, 2, 4, 8, out), 0);
}
const auto t2 = std::chrono::steady_clock::now();
const double build = std::chrono::duration<double, std::milli>(t1 - t0).count();
const double steps = std::chrono::duration<double, std::milli>(t2 - t1).count();
fprintf(stderr, " index 400k tokens: %.1f ms; 1000 lookups after: %.3f ms (%.1f MiB)\n", build,
steps, (double)ix.bytes() / 1048576.0);
CHECK(steps < build);
CHECK_EQ(ix.indexed(), (int64_t)seq.size() - 1);
}
/* The scheduler's half of the cost: a decode step that verified drafts is timed at its deepest
* window and row count, and the next cycle's head depth reads it. Measured dear past one round at
* two rows, both windows (and the rounds) come down to one. */
@@ -5843,46 +6294,6 @@ TEST(a_request_finishing_under_a_step_issued_ahead_keeps_its_blocks_for_that_ste
CHECK_EQ((int)f.sch.find(a)->output.size(), 2); /* the step ahead emitted nothing */
}
/* A SCORED row (Request::token_scores) the step in flight brings to max_tokens gets no step issued
* ahead: it would be a forward pass for a request that finishes at the commit. The step after the
* commit is planned as usual, and a decode that is not scored keeps its step of overlap. */
TEST(no_step_is_issued_ahead_for_a_scored_request_the_step_in_flight_finishes) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
const int64_t before = f.kv.free_blocks(0);
auto r = f.request(40, /*max_tokens=*/2);
r->speculation_fixed = true;
r->token_scores = std::make_shared<TokenScores>();
r->token_scores->tokens = { 1, 2 };
const uint64_t a = f.add(std::move(r));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain();
REQUIRE(f.sch.step() != nullptr);
CHECK(f.sch.step_next() == nullptr);
f.commit_plain(); /* the second token: finished */
CHECK_EQ((int)f.sch.find(a)->state, (int)ReqState::Finished);
CHECK_EQ(f.kv.free_blocks(0), before);
CHECK_EQ((int)f.sch.find(a)->output.size(), 2);
CHECK(f.sch.step() == nullptr);
}
/* The same row without token_scores is an ordinary decode: the step ahead is issued, as upstream. */
TEST(a_non_scored_row_keeps_the_step_issued_ahead) {
Fixture f;
f.build(/*blocks=*/20, /*states=*/64);
CHECK_OK(f.start());
auto r = f.request(40, /*max_tokens=*/2);
r->speculation_fixed = true;
const uint64_t a = f.add(std::move(r));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain();
REQUIRE(f.sch.step() != nullptr);
CHECK(f.sch.step_next() != nullptr);
f.commit_plain();
CHECK_EQ((int)f.sch.find(a)->output.size(), 2);
}
/* ================================================================== terminal paths */
/* A lone request that outgrows the whole pool fails with the reason the client sees and gives its
* blocks back; nothing is preempted, since there is nobody to preempt and preempting itself would