radiance 1.2.2

- Static YaRN for the Qwen rotary paths (#37): a container whose config names YaRN gets it in
  attention, the QSA index keys and a DFlash2 drafter; one reader for every rotary type, and a
  LLaMA container whose type is not served (llama3, longrope, dynamic) is refused by name.
- --rope-scaling yarn:FACTOR[:ORIG] (#38) writes YaRN over a container's own rotary keys at load,
  no reconvert; the persisted prefix cache's fingerprint carries the resolved rotary.
- An uneven world's cheaper rank (#36) pages the common token count and gives the rest of its
  VRAM to its experts; a plan and pool that disagree refuse to start.
- MoE prefill (#35): wide gather, parallel scan and run-map prefix, 256-column down tile, early
  weight loads -- by rule, bit-identical.
- MoE decode (#34): the sorted operand's own down kernel, its column tiles by routed rows.
- --draft-window fixed|adaptive (#24): a per-sequence draft window priced by measured step time,
  one head depth per step over the batch; fixed stays the default. New metric
  radiance:draft_position_accepted_total and Grafana panels.
- Out-of-tree plugin builds compile to the tree's device code from any build directory.
This commit is contained in:
Deadcode committed 2026-10-07 12:37:53 +02:00
1 parent 6fa7707dff
commit ac79f4dc8a
63 files changed
+2744 -8759

No files matched your search

+189 -197
View File
@@ -1,23 +1,35 @@
/* draft.cpp -- the static draft-depth policy, and the adaptive one RADIANCE_DRAFT_ADAPT turns on.
* See draft.h for why the first is the default and what the second changes.
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
* on. See draft.h for why the first is the default and what the second changes.
*/
#include "draft.h"
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>
namespace rad {
namespace {
/* THE COST MODEL WHEN NO TABLE IS GIVEN: every draft adds six percent to a step -- one round of
* the head (about 0.4 ms profiled on QFN at tp4) and one more verify row, against a step of about
* 12 ms. A guess at a shape, not a measurement of any deployment: one that has measured its own
* steps by depth gives them as RADIANCE_DRAFT_COST. */
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
* one round of a serial head and one more verify row against a weight-bound step. It prices a
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
constexpr double kCostSlope = 0.06;
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
* grows by a few thousand tokens over a reply. */
constexpr double kCostHalfLife = 32.0;
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
* step that waited on something other than its own work -- a first recording, an allocation, a
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
* against: its first step may itself be the odd one. */
constexpr double kCostOutlier = 4.0;
constexpr int64_t kCostClipAfter = 4;
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
@@ -26,169 +38,37 @@ constexpr double kCostSlope = 0.06;
* a short answer. */
constexpr double kPriorWeight = 4.0;
/* A POSITION THE DEPLOYMENT HAS EVALUATED FEWER TIMES THAN THIS starts a new sequence from the
* fixed prior rather than from the global count: a rate over a handful of verifies is noise, and a
* position nobody has drafted to is no rate at all. */
constexpr int64_t kGlobalMinReach = 64;
/* RADIANCE_DRAFT_COST="1:10.6,2:11.3,3:12.0": depth:cost pairs, comma separated. Returns how many
* it read, or -1 when the string is not that. */
int parse_cost(const char* s, float* cost) {
int n = 0;
const char* p = s;
for (;;) {
while (*p == ' ') ++p;
if (!*p) return n;
char* end = nullptr;
const long d = std::strtol(p, &end, 10);
if (end == p || *end != ':') return -1;
p = end + 1;
const double v = std::strtod(p, &end);
if (end == p) return -1;
if (d < 1 || d > RAD_SCHED_MAX_SPEC || !std::isfinite(v) || !(v > 0.0)) return -1;
cost[d] = (float)v;
++n;
p = end;
while (*p == ' ') ++p;
if (*p == ',') ++p;
else if (*p) return -1;
}
}
/* One knob, or the default with a warning when it does not parse. A knob that is silently not
* read is the one that gets reported as "made no difference". */
void env_real(const char* name, double lo, double hi, float* out) {
const char* v = std::getenv(name);
if (!v || !*v) return;
char* end = nullptr;
const double x = std::strtod(v, &end);
if (end == v || *end || !(x >= lo && x <= hi)) {
RAD_WARN("%s=%s is not a number in [%g, %g]; keeping %g", name, v, lo, hi, (double)*out);
return;
}
*out = (float)x;
}
void env_int(const char* name, long lo, long hi, int* out) {
const char* v = std::getenv(name);
if (!v || !*v) return;
char* end = nullptr;
const long x = std::strtol(v, &end, 10);
if (end == v || *end || x < lo || x > hi) {
RAD_WARN("%s=%s is not an integer in [%ld, %ld]; keeping %d", name, v, lo, hi, *out);
return;
}
*out = (int)x;
}
} /* namespace */
void DraftController::from_env(Params* p) {
static const Params env = [] {
Params e;
const char* on = std::getenv("RADIANCE_DRAFT_ADAPT");
e.adapt = on && *on && *on != '0';
if (const char* c = std::getenv("RADIANCE_DRAFT_COST"); c && *c) {
const int n = parse_cost(c, e.cost);
if (n < 2) {
RAD_WARN("RADIANCE_DRAFT_COST=\"%s\" %s; the adaptive draft depth prices a step at "
"1 + %.2f per draft instead", c,
n < 0 ? "is not a list of depth:cost pairs"
: "has fewer than two depth:cost pairs", kCostSlope);
std::memset(e.cost, 0, sizeof e.cost);
}
}
env_real("RADIANCE_DRAFT_ADAPT_HYST", 0.0, 10.0, &e.hyst);
env_int ("RADIANCE_DRAFT_ADAPT_HOLD", 0, 1000000, &e.hold);
env_real("RADIANCE_DRAFT_ADAPT_HALFLIFE", 0.5, 1e6, &e.half_life);
env_real("RADIANCE_DRAFT_ADAPT_PRIOR", 0.0, 1.0, &e.prior);
env_int ("RADIANCE_DRAFT_ADAPT_MIN", 1, RAD_SCHED_MAX_SPEC, &e.min_depth);
env_int ("RADIANCE_DRAFT_ADAPT_BUSY", 0, 1000000, &e.busy);
env_int ("RADIANCE_DRAFT_ADAPT_BUSY_DEPTH", 1, RAD_SCHED_MAX_SPEC, &e.busy_depth);
return e;
}();
p->adapt = env.adapt;
std::memcpy(p->cost, env.cost, sizeof p->cost);
p->hyst = env.hyst;
p->hold = env.hold;
p->half_life = env.half_life;
p->prior = env.prior;
p->min_depth = env.min_depth;
p->busy = env.busy;
p->busy_depth = env.busy_depth;
}
int DraftController::configure(const Params& p) {
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
p.max_depth, RAD_SCHED_MAX_SPEC, RAD_SCHED_MAX_SPEC);
return RAD_E_INVAL;
}
if (p.adapt && (!(p.hyst >= 0.0f) || p.hold < 0 || !(p.half_life > 0.0f) ||
!(p.prior >= 0.0f && p.prior <= 1.0f) || p.min_depth < 1 || p.busy < 0 ||
p.busy_depth < 1)) {
RAD_ERR("adaptive draft depth: hysteresis %g, hold %d, half-life %g, prior %g, minimum %d, "
"busy %d, busy depth %d -- they want >= 0, >= 0, > 0, 0..1, >= 1, >= 0 and >= 1",
(double)p.hyst, p.hold, (double)p.half_life, (double)p.prior, p.min_depth, p.busy,
p.busy_depth);
return RAD_E_INVAL;
}
p_ = p;
tot_drafted_ = tot_accepted_ = 0;
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
seen_ = 0;
adapt_ = p.adapt && p.max_depth > 0;
alpha_ = 0.0;
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) { cost_[d] = 0.0; by_depth_[d] = 0; }
/* SAID, because a switch that does nothing reads exactly like a switch that made no
* difference. */
if (p.adapt && !adapt_)
RAD_WARN("RADIANCE_DRAFT_ADAPT is set and this deployment does not speculate "
"(--num-speculative-tokens 0): there is no window to adapt");
if (!adapt_) return RAD_OK;
if (p_.min_depth > p_.max_depth) p_.min_depth = p_.max_depth;
alpha_ = 1.0 - std::exp2(-1.0 / (double)p_.half_life);
/* THE COST TABLE, resolved for every window the policy may choose. A point that was measured
* is taken as it is; between two points the line between them; past the ends the line through
* the nearest two -- a table for depths 1..6 still prices depth 8 the way its own last two
* steps say. A table that extrapolates to a cost at or below zero is a table with the wrong
* sign in it, and the default is the better guess. */
int pd[RAD_SCHED_MAX_SPEC];
double pv[RAD_SCHED_MAX_SPEC];
int np = 0;
for (int d = 1; d <= RAD_SCHED_MAX_SPEC; ++d)
if (std::isfinite(p.cost[d]) && p.cost[d] > 0.0f) {
pd[np] = d;
pv[np] = (double)p.cost[d];
++np;
}
bool table = np >= 2;
for (int d = 1; table && d <= p_.max_depth; ++d) {
int i = 0;
while (i + 2 < np && pd[i + 1] < d) ++i;
const double t = (double)(d - pd[i]) / (double)(pd[i + 1] - pd[i]);
cost_[d] = pv[i] + t * (pv[i + 1] - pv[i]);
if (!(cost_[d] > 0.0)) {
RAD_WARN("adaptive draft depth: the cost table extrapolates to %g at depth %d; pricing "
"a step at 1 + %.2f per draft instead", cost_[d], d, kCostSlope);
table = false;
}
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
step_d_ = 0;
step_w_ = 0;
step_held_ = 0;
prior_n_ = 0;
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
by_depth_[d] = 0;
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
}
if (!table)
for (int d = 1; d <= p_.max_depth; ++d) cost_[d] = 1.0 + kCostSlope * (double)d;
std::string t;
for (int d = 1; d <= p_.max_depth; ++d) t += fmt("%s%d:%.3g", d > 1 ? " " : "", d, cost_[d]);
RAD_INFO("draft depth: ADAPTIVE per sequence (RADIANCE_DRAFT_ADAPT), %d..%d -- the window "
"maximising E(d)/T(d) for T = [%s]%s; moves at +%.1f%% and at most every %d verifies; "
"acceptance half-life %.1f verifies, prior %.2f",
p_.min_depth, p_.max_depth, t.c_str(), table ? "" : " (the default model)",
100.0 * (double)p_.hyst, p_.hold, (double)p_.half_life, (double)p_.prior);
if (p_.busy > 0)
RAD_INFO("draft depth: above %d running sequences every window is capped at %d "
"(RADIANCE_DRAFT_ADAPT_BUSY)", p_.busy, p_.busy_depth);
if (adapt_)
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
"maximises the tokens its sequences are expected to emit over the step's measured "
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
"time; moves at +%.0f%% and at most every %d steps",
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
return RAD_OK;
}
@@ -212,49 +92,115 @@ void DraftController::observe(int drafted, int accepted) {
if (adapt_) ++by_depth_[drafted];
}
/* ------------------------------------------------------------------ the adaptive policy */
int DraftController::best_depth(const float* a, int at, double* best, double* at_gain) const {
double e = 1.0, run = 1.0, bg = -1.0, ag = 0.0;
int arg = p_.min_depth;
for (int d = 1; d <= p_.max_depth; ++d) {
run *= (double)a[d - 1];
e += run;
const double g = e / cost_[d];
if (d == at) ag = g;
if (d >= p_.min_depth && g > bg) { bg = g; arg = d; }
/* ------------------------------------------------------------------ the step's cost */
int DraftController::cost_class(int n_rows) {
int c = 0;
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
return c;
}
void DraftController::step_time(int depth, int n_rows, double ms) {
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
!std::isfinite(ms))
return;
const int c = cost_class(n_rows);
double& m = cost_ms_[depth][c];
int64_t& n = cost_n_[depth][c];
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
m = n ? m + w * (ms - m) : ms;
++n;
}
int64_t DraftController::cost_samples(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
return cost_n_[depth][cost_class(n_rows)];
}
double DraftController::step_cost(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
* ONE class -- reads the prior's shape until its own depths are measured. */
for (int dc = 0; dc < kCostClasses; ++dc) {
for (int sgn = 0; sgn < 2; ++sgn) {
const int k = sgn ? c + dc : c - dc;
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
int best = -1;
for (int d = 1; d <= p_.max_depth; ++d) {
if (cost_n_[d][k] <= 0) continue;
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
}
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
}
}
if (best) *best = bg;
if (at_gain) *at_gain = ag;
return arg;
return cost_prior(depth);
}
double DraftController::gain(const DraftAdapt& s, int d) const {
if (!adapt_ || d < 1 || d > p_.max_depth) return 0.0;
double e = 1.0, run = 1.0;
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
return e / cost_[d];
/* ------------------------------------------------------------------ one sequence */
int DraftController::stop_of(const float* a) const {
double p = 1.0;
int d = 0;
while (d < p_.max_depth) {
p *= (double)a[d];
if (p < kDraftMinChance) break;
++d;
}
return d < kMinDepth ? kMinDepth : d;
}
int DraftController::depth_for(DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (s.depth > 0) return s.depth;
/* NOT STARTED. Each position from what the deployment has measured there, where it has
* measured enough; otherwise from the fixed prior, which is optimistic on purpose: a window
* that starts deep evaluates every position and learns all of them, and one that starts
* shallow learns nothing about the positions it never drafts to. */
double DraftController::prior_at(int j) const {
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
}
void DraftController::start(DraftAdapt& s) const {
/* Each position from the sequences that finished before it once there are enough of them
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
for (int j = 0; j < p_.max_depth; ++j) {
s.a[j] = reach_[j] >= kGlobalMinReach ? (float)((double)hit_[j] / (double)reach_[j])
: p_.prior;
s.a[j] = (float)prior_at(j);
s.n[j] = 0;
}
s.depth = best_depth(s.a, 0, nullptr, nullptr);
s.depth = stop_of(s.a);
s.held = 0;
return s.depth;
}
void DraftController::adapt_retire(const DraftAdapt& s) {
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
1.0 / (double)(prior_n_ + 1));
for (int j = 0; j < p_.max_depth; ++j)
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
: s.a[j];
++prior_n_;
}
double DraftController::yield(const DraftAdapt& s, int d) const {
if (d > p_.max_depth) d = p_.max_depth;
double e = 1.0, run = 1.0;
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
return e;
}
int DraftController::window_of(const DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) return 0;
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
return s.depth < D ? s.depth : D;
}
int DraftController::window_for(DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) start(s);
return window_of(s);
}
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) (void)depth_for(s);
if (s.depth <= 0) start(s);
if (drafted <= 0) return s.depth;
const int D = p_.max_depth;
if (drafted > D) drafted = D;
@@ -275,27 +221,73 @@ int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) con
* learned about them while the window is shorter -- and a sequence held at three by prose that
* turns into code would otherwise keep pricing positions four and up at whatever they read
* before, and never draft deep enough to find out. The guess is that acceptance decays with
* position rather than falling off a cliff, which is what QFN's head measured, so the window's
* edge stands in for what lies past it. Where that is wrong it costs a move out, the verifies
* that refute it, and a move back. */
* position rather than falling off a cliff, so the window's edge stands in for what lies past
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
const double edge = (double)s.a[drafted - 1];
for (int j = drafted; j < D; ++j)
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
/* THE MOVE, rate-limited twice. A window changes the shape of the verify pass and of the
* head's history pass, and a shape is a new recording before it plays (runtime/ctx.h); a
* window that follows every flicker of the estimate pays that for nothing. So it moves only
* when the window it would take is worth `hyst` more than the one it has, and not again within
* `hold` verifies of the last move. */
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
if (s.held < INT32_MAX) ++s.held;
if (s.held < p_.hold) return s.depth;
double best = 0.0, cur = 0.0;
const int d = best_depth(s.a, s.depth, &best, &cur);
if (d != s.depth && best > cur * (1.0 + (double)p_.hyst)) {
if (s.held < kHold) return s.depth;
const int d = stop_of(s.a);
if (d != s.depth) {
s.depth = d;
s.held = 0;
}
return s.depth;
}
/* ------------------------------------------------------------------ the step */
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
if (!adapt_ || n_seq <= 0) return step_d_;
if (n_rows < n_seq) n_rows = n_seq;
const int M = p_.max_depth;
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
* sequence drafts further and the head runs no further -- so the candidates end there. */
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
int top = kMinDepth;
for (int i = 0; i < n_seq; ++i) {
DraftAdapt& s = *seq[i];
if (s.depth <= 0) start(s);
if (s.depth > top) top = s.depth;
double e = 1.0, run = 1.0;
for (int d = 1; d <= M; ++d) {
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
tok[d] += e;
}
}
const double plain = (double)(n_rows - n_seq);
if (top > M) top = M;
int best = kMinDepth;
double best_g = -1.0;
for (int d = kMinDepth; d <= top; ++d) {
const double g = (tok[d] + plain) / step_cost(d, n_rows);
if (g > best_g) { best_g = g; best = d; }
}
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
if (step_d_ <= 0) {
step_d_ = best;
step_held_ = 0;
} else {
if (step_held_ < INT32_MAX) ++step_held_;
const int cur = step_d_ < top ? step_d_ : top;
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
best_g);
step_d_ = best;
step_held_ = 0;
}
}
step_w_ = step_d_ < top ? step_d_ : top;
return step_d_;
}
} /* namespace rad */