Archived
radiance 2.0.0
Radiance becomes a multi-model engine: one process serves several models behind one port, loads each when a request names it, parks it in host memory or restores it from its container, and shares the cards between them (docs/MULTIMODEL.md). The configuration is one YAML file; the command line flags are gone (`radiance --config FILE`, hot reload on SIGHUP). Formats. IQ8R (rotated int8) and IQR-V4 replace FP8 and MXFP4 as whole-model formats, with an int8 KV cache (`kv-cache-dtype: i8`) in place of the fp8 one. Containers whose weights are block FP8, MXFP4, M2XFP4, NVFP4 or ParoQuant are refused at startup by the name of the first such weight. Not served until they have int8 containers: GLM-5.3-Flash, Ornith-1.5, Sage-A1.5, Nemotron-3.5-Bolt-74B, Ling-3.0-flash, drama-3 and Anima's FP8 container; Nemotron-3.5-Bolt-E4B, the Gemma 4 31B DFlash containers and MiniCPM5-2B bf16 serve without their drafter. 1.17.0 serves all of them. Speed. Chained launches for Qwen3.8-27B, Gemma 4, Gemma 3 and the small bf16 models, a new Qwen3.8-Flash-Next container (IQR-V4 experts, int8 trunk) with its decode step and prefill reworked, and a reworked adaptive draft window. Deployment. deploy/compose has two fleet files, tp1.yaml and tp2.yaml, each with its configuration beside it, in place of the per-model files. `host-pool-mib` is a model's host pool in all, split among its ranks. The dashboard is rebuilt: an hour of history kept by the server, each accelerator's memory by model, model states over time. Merged since 1.17.0: Nemotron-3.5-Bolt-74B-A9B by keptn42 (#339); GLM-5.3-Flash on four cards by AnimusNull (#397); chained launches for Flash-Next's decode step (#396) and preempted requests keeping their prefix and place (#405) by mici81; --prefill-interleave auto by Code000 (#410); eight more libr3d kernels and the w4a4 reference by RikshaDriver (#403, #407, #408); libr3d large-BAR and E4M3 decode fixes by neuromanMD (#438, #439); int4/int5 decode tiles by Kezi (#426); attention for Nanbeige 4.3 33B by everplays (#417); expert_stats_report.py by baKon (#431). Fixed: #398, #402, #419, #437 (dschmitz's patch); added the metrics of #392, and multi-model serving as asked for in #367 and #109. Plugin ABI 39: out-of-tree plugins need to be rebuilt. Thanks to @keptn42, @AnimusNull, @mici81, @Code000, @RikshaDriver, @neuromanMD, @Kezi, @everplays, @baKon and @dschmitz.
This commit is contained in:
1 parent
b4c04b6042
commit
ddcb9c69bb
696 files changed
+120770
-56596
No files matched your search
+6
-47
@@ -8,6 +8,7 @@
|
||||
#include <cstdlib>
|
||||
|
||||
#include "advance_impl.h"
|
||||
#include "device/chain_kernel.h"
|
||||
#include "rad_abi.h"
|
||||
|
||||
extern "C" int rad_dev_chain_enabled(void); /* core/device/device.h */
|
||||
@@ -21,42 +22,12 @@ __global__ __launch_bounds__(kThreads) void rad_step_advance(rad::AdvanceArgs a)
|
||||
if (i < a.n_seq) rad::adv_row(a, i);
|
||||
}
|
||||
|
||||
/* The chained form (RadKernelChainFn, abi/rad_abi.h): the backend gives a kernel named r4dchain*
|
||||
* a record at RAD_CHAIN_KARG_OFF and drops its barrier bit behind another chained kernel. Before
|
||||
* the first read one lane waits for the queue's counter to reach the record's target; after the
|
||||
* last write the block releases and adds 1. A record that does not check out means: run plain. */
|
||||
struct ChainRec {
|
||||
unsigned long long magic, target;
|
||||
unsigned long long* ctr;
|
||||
unsigned long long check;
|
||||
};
|
||||
__device__ __forceinline__ const ChainRec* chain_rec() {
|
||||
const ChainRec* r = (const ChainRec*)((const char*)__builtin_amdgcn_kernarg_segment_ptr() +
|
||||
RAD_CHAIN_KARG_OFF);
|
||||
const unsigned long long magic = r->magic, target = r->target, check = r->check;
|
||||
if (magic != RAD_CHAIN_MAGIC ||
|
||||
check != (magic ^ target ^ (unsigned long long)(uintptr_t)r->ctr ^ RAD_CHAIN_CHECK))
|
||||
return nullptr;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The chained forms (chain_kernel.h), launched where launches chain. */
|
||||
__global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceArgs a) {
|
||||
const ChainRec* r = chain_rec();
|
||||
if (r) {
|
||||
if (threadIdx.x == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
rad_chain_wait();
|
||||
const int i = (int)(blockIdx.x * kThreads + threadIdx.x);
|
||||
if (i < a.n_seq) rad::adv_row(a, i);
|
||||
if (r) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
rad_chain_done();
|
||||
}
|
||||
|
||||
/* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads
|
||||
@@ -72,21 +43,9 @@ __global__ __launch_bounds__(kCompactThreads) void rad_step_compact(rad::Advance
|
||||
step_compact_body(a);
|
||||
}
|
||||
__global__ __launch_bounds__(kCompactThreads) void r4dchain_step_compact(rad::AdvanceArgs a) {
|
||||
const ChainRec* r = chain_rec();
|
||||
if (r) {
|
||||
if (threadIdx.x == 0)
|
||||
while (__hip_atomic_load(r->ctr, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) < r->target)
|
||||
__builtin_amdgcn_s_sleep(1);
|
||||
__syncthreads();
|
||||
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "agent");
|
||||
}
|
||||
rad_chain_wait();
|
||||
step_compact_body(a);
|
||||
if (r) {
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "agent");
|
||||
__syncthreads();
|
||||
if (threadIdx.x == 0)
|
||||
__hip_atomic_fetch_add(r->ctr, 1ull, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
|
||||
}
|
||||
rad_chain_done();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
+52
-28
@@ -5,6 +5,7 @@
|
||||
#include "derive.h"
|
||||
#include "device/device.h"
|
||||
#include "kvstream/bind.h"
|
||||
#include "util/simd.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
@@ -691,9 +692,9 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
};
|
||||
|
||||
/* Reset every group's row: a sequence with no state in a group must read -1, not a stale slot
|
||||
* from the previous step. */
|
||||
* from the previous step. -1 is all-ones, so the reset is a memset. */
|
||||
for (int64_t gi = 0; gi < (int64_t)kvgeom_.g.size(); ++gi)
|
||||
for (int64_t i = 0; i < n_seq; ++i) s.h_convslot[gi * max_seqs_ + i] = -1;
|
||||
std::memset(s.h_convslot + gi * max_seqs_, 0xff, (size_t)n_seq * sizeof(int32_t));
|
||||
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
Group& g = s.groups[gi];
|
||||
@@ -717,17 +718,20 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
|
||||
int64_t first = 0;
|
||||
SeqWindow win;
|
||||
bool has_win = false;
|
||||
/* One lookup of the sequence for everything below (IKVManager::seq_group); the
|
||||
* change mark is taken with it, for a paged group only, as take_table_changes was. */
|
||||
SeqGroupView gv;
|
||||
kv.seq_group(e.seq, (int32_t)gi, L.paged, &gv);
|
||||
/* A state group's row starts at 0 and carries no window, as before the view: only a
|
||||
* paged group was ever asked. */
|
||||
int64_t first = L.paged ? gv.first : 0;
|
||||
const SeqWindow& win = gv.win;
|
||||
const bool has_win = L.paged && gv.has_win;
|
||||
int64_t bt_len = 0; /* the sequence's block table, in blocks */
|
||||
int64_t table_end = 0; /* the table's last position, for a runtime window's used */
|
||||
if (L.paged) {
|
||||
/* The manager's block table, by sequence id; Request::blocks is not the source
|
||||
* of truth (see IKVManager). */
|
||||
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
|
||||
if (has_win) {
|
||||
/* The ring size sets the group header's geometry, so every sequence in the
|
||||
* group must report the same one. */
|
||||
@@ -738,36 +742,47 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
}
|
||||
ring_blocks = (int32_t)win.ring_blocks;
|
||||
}
|
||||
bt_len = (int64_t)bt.size();
|
||||
bt_len = (int64_t)gv.bt_n;
|
||||
table_end = bt_len * L.block_size;
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) {
|
||||
const int64_t pos = (int64_t)e.ctx_len + j;
|
||||
g.h_slot[t + j] = has_win
|
||||
? kvgeom_.slot_ring((int)gi, bt, first, pos, win)
|
||||
: kvgeom_.slot((int)gi, bt, first, pos);
|
||||
}
|
||||
/* Consecutive positions: the segment walk (KVGeom::slots) stages the same
|
||||
* slots slot()/slot_ring() would, one division a block instead of two a token. */
|
||||
if (has_win)
|
||||
kvgeom_.slots_ring((int)gi, gv.bt, gv.bt_n, first, (int64_t)e.ctx_len,
|
||||
e.n_tokens, win, g.h_slot + t);
|
||||
else
|
||||
kvgeom_.slots((int)gi, gv.bt, gv.bt_n, first, (int64_t)e.ctx_len,
|
||||
e.n_tokens, g.h_slot + t);
|
||||
/* Restage relative to what the card holds (BtMirror). The same sequence in the
|
||||
* same row keeps entries below the first changed one and below the end of both
|
||||
* old and new tables, so a decode step stages nothing or one appended block. A
|
||||
* new or moved sequence restages the whole row, and its copies in other rows go
|
||||
* unknown. Change marks are taken for every row. */
|
||||
const int64_t nb = std::min<int64_t>((int64_t)bt.size(), pitch);
|
||||
const int64_t chg = kv.take_table_changes(e.seq, (int32_t)gi);
|
||||
const int64_t nb = std::min<int64_t>((int64_t)gv.bt_n, pitch);
|
||||
const int64_t chg = gv.changed_from;
|
||||
int64_t lo = 0, hi = pitch;
|
||||
if (m.len[(size_t)i] >= 0 && m.seq[(size_t)i] == e.seq) {
|
||||
lo = std::min(std::min(chg, m.len[(size_t)i]), nb);
|
||||
hi = std::max(nb, m.len[(size_t)i]);
|
||||
} else {
|
||||
for (int64_t k = 0; k < max_seqs_; ++k)
|
||||
if (m.seq[(size_t)k] == e.seq) m.len[(size_t)k] = -1;
|
||||
/* Invalidate this sequence's copies in other rows. Ids compare bitwise, so
|
||||
* the uint64 row array is searched as int64 (simd::find_eq_i64). */
|
||||
const int64_t* rows = (const int64_t*)m.seq.data();
|
||||
int64_t k = simd::find_eq_i64(rows, (size_t)max_seqs_, (int64_t)e.seq);
|
||||
while (k >= 0) {
|
||||
m.len[(size_t)k] = -1;
|
||||
if (k + 1 >= max_seqs_) break;
|
||||
const int64_t nx = simd::find_eq_i64(
|
||||
rows + k + 1, (size_t)(max_seqs_ - k - 1), (int64_t)e.seq);
|
||||
k = nx < 0 ? -1 : k + 1 + nx;
|
||||
}
|
||||
}
|
||||
if (lo < hi) {
|
||||
int32_t* w = pay + np;
|
||||
const int64_t nc = nb > lo ? nb - lo : 0;
|
||||
/* Guarded: an empty table's data() may be null, and memcpy's source must
|
||||
* not be, even for zero bytes. */
|
||||
if (nc > 0) std::memcpy(w, bt.data() + lo, (size_t)nc * sizeof(int32_t));
|
||||
std::fill(w + nc, w + (hi - lo), -1);
|
||||
if (nc > 0) std::memcpy(w, gv.bt + lo, (size_t)nc * sizeof(int32_t));
|
||||
std::memset(w + nc, 0xff, (size_t)(hi - lo - nc) * sizeof(int32_t));
|
||||
stage(g.bt_fix + i * pitch + lo, np, hi - lo);
|
||||
np += hi - lo;
|
||||
}
|
||||
@@ -777,8 +792,17 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
/* A linear or conv group has one state slot per sequence; every token maps to it
|
||||
* and the block-table row is that slot, so table-reading kernels need no second
|
||||
* path. */
|
||||
int32_t st = kv.state_slot(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) g.h_slot[t + j] = st;
|
||||
const int32_t st = gv.state;
|
||||
/* A kernel reads -1 as "no state" and carries on, so a sequence without its slot
|
||||
* would compute fluent, wrong text. A drafter's pass may still name a finished
|
||||
* sequence's rows; the trunk's may not. */
|
||||
if (st < 0 && plan.draft_pass == 0 && e.n_tokens > 0 &&
|
||||
(L.kind == RAD_KV_CONV || L.kind == RAD_KV_LINEAR)) {
|
||||
RAD_ERR("step plan row %lld: sequence %llu holds no state slot in KV group %d",
|
||||
(long long)i, (unsigned long long)e.seq, (int)gi);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
std::fill(g.h_slot + t, g.h_slot + t + e.n_tokens, st);
|
||||
pay[np + i] = st;
|
||||
/* Every conv group, at its own row. Feeds only DeriveInput::conv_slot; conv
|
||||
* kernels read RadKVGroupBatch::state_index (see conv_window_ in batch.h). */
|
||||
@@ -812,16 +836,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
if (used < 0) used = 0;
|
||||
g.h_used[i] = (int32_t)used;
|
||||
if (L.paged) {
|
||||
for (int64_t j = 0; j < g.sidx_pitch; ++j) g.h_sidx[i * g.sidx_pitch + j] = -1;
|
||||
std::memset(g.h_sidx + i * g.sidx_pitch, 0xff,
|
||||
(size_t)g.sidx_pitch * sizeof(int32_t));
|
||||
} else {
|
||||
kv.state_index_row(e.seq, (int32_t)gi, g.h_sidx + i * g.sidx_pitch,
|
||||
(int)g.sidx_pitch);
|
||||
}
|
||||
}
|
||||
int32_t group_used = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i)
|
||||
group_used = std::max(group_used, g.h_used[i]);
|
||||
o.kv_used_max_h[gi] = group_used;
|
||||
/* As the loop it replaces: the rows' maximum, floored at 0 (n_seq may be 0 and a row's
|
||||
* used is clamped non-negative above, so the floor only binds then). */
|
||||
o.kv_used_max_h[gi] = std::max<int32_t>(0, simd::max_i32(g.h_used, (size_t)n_seq));
|
||||
/* A state group's rows are one slot per sequence: n_seq words, restaged whole. */
|
||||
if (!L.paged) {
|
||||
stage(g.bt_fix, np, n_seq);
|
||||
|
||||
+17
-65
@@ -11,22 +11,6 @@ namespace rad {
|
||||
|
||||
namespace {
|
||||
|
||||
/* Step-cost prior, a shape rather than a measurement: each draft adds 6% to a step (one serial
|
||||
* head round plus one verify row on a weight-bound step). Once anything is measured only its
|
||||
* ratios are used: an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
|
||||
constexpr double kCostSlope = 0.06;
|
||||
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
|
||||
|
||||
/* A step-time mean is a running mean for the first steps, then a moving average with a half-life
|
||||
* of 32 steps: long enough to average out one-off costs (a tier copy, a recording, a prefix-cache
|
||||
* trim), short enough to follow a context growing by a few thousand tokens over a reply. */
|
||||
constexpr double kCostHalfLife = 32.0;
|
||||
/* Once a key has 4 samples, one step counts for at most 4x its mean. A step that waited on
|
||||
* something else (a first recording, an allocation, a host stall) says nothing about its depth's
|
||||
* cost. Below 4 samples the mean is not a trustworthy reference to clip against. */
|
||||
constexpr double kCostOutlier = 4.0;
|
||||
constexpr int64_t kCostClipAfter = 4;
|
||||
|
||||
/* The prior weighs as much as this many verifies. The (n+1)-th verify moves an estimate by
|
||||
* 1 / (n + k + 1), a running mean over prior and evidence, until that falls below the half-life's
|
||||
* step and the moving average takes over. Without it a sequence would spend its first ~16
|
||||
@@ -59,10 +43,8 @@ int DraftController::configure(const Params& p) {
|
||||
step_held_ = 0;
|
||||
prior_n_ = 0;
|
||||
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
|
||||
by_depth_[d] = 0;
|
||||
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
|
||||
}
|
||||
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) by_depth_[d] = 0;
|
||||
cost_.reset(kRowCost);
|
||||
if (adapt_)
|
||||
RAD_INFO("draft depth: adaptive, %d..%d; a sequence stops at the first draft emitted less "
|
||||
"than %.0f%% of the time, and the depth moves at +%.0f%% at most every %d steps",
|
||||
@@ -91,51 +73,16 @@ void DraftController::observe(int drafted, int accepted) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the step's cost */
|
||||
int DraftController::cost_class(int n_rows) {
|
||||
int c = 0;
|
||||
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
|
||||
return c;
|
||||
void DraftController::step_time(int q_rows, double ms) {
|
||||
if (!adapt_) return;
|
||||
cost_.sample(q_rows, ms);
|
||||
}
|
||||
|
||||
void DraftController::step_time(int depth, int n_rows, double ms) {
|
||||
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
|
||||
!std::isfinite(ms))
|
||||
return;
|
||||
const int c = cost_class(n_rows);
|
||||
double& m = cost_ms_[depth][c];
|
||||
int64_t& n = cost_n_[depth][c];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = settle_weight(kCostHalfLife, n);
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
++n;
|
||||
int64_t DraftController::cost_samples(int q_rows) const {
|
||||
return q_rows >= 1 ? cost_.samples(q_rows) : 0;
|
||||
}
|
||||
|
||||
int64_t DraftController::cost_samples(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
|
||||
return cost_n_[depth][cost_class(n_rows)];
|
||||
}
|
||||
|
||||
double DraftController::step_cost(int depth, int n_rows) const {
|
||||
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
|
||||
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
|
||||
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
|
||||
/* Nearest measured key: this class first (nearest depth, shallower on a tie), then the
|
||||
* nearest class. Only its ratio to the prior is borrowed, so D's comparison across depths in
|
||||
* one class follows the prior's shape until those depths are measured. */
|
||||
for (int dc = 0; dc < kCostClasses; ++dc) {
|
||||
for (int sgn = 0; sgn < 2; ++sgn) {
|
||||
const int k = sgn ? c + dc : c - dc;
|
||||
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
|
||||
int best = -1;
|
||||
for (int d = 1; d <= p_.max_depth; ++d) {
|
||||
if (cost_n_[d][k] <= 0) continue;
|
||||
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
|
||||
}
|
||||
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
|
||||
}
|
||||
}
|
||||
return cost_prior(depth);
|
||||
}
|
||||
double DraftController::step_cost(int q_rows) const { return cost_.cost(q_rows); }
|
||||
|
||||
/* ------------------------------------------------------------------ one sequence */
|
||||
int DraftController::stop_of(const float* a) const {
|
||||
@@ -236,9 +183,11 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
if (n_rows < n_seq) n_rows = n_seq;
|
||||
const int M = p_.max_depth;
|
||||
|
||||
/* Expected tokens at each head depth: sum_i E_i(min(D, stop_i)), plus one per non-drafting
|
||||
* row. Candidates end at the deepest stop, since a deeper D changes nothing. */
|
||||
/* Expected tokens at each head depth, sum_i E_i(min(D, stop_i)) plus one per non-drafting
|
||||
* row, and the drafts the step would then verify, sum_i min(D, stop_i). Candidates end at the
|
||||
* deepest stop, since a deeper D changes nothing. */
|
||||
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int drafts[RAD_SCHED_MAX_SPEC + 1] = {};
|
||||
int top = kMinDepth;
|
||||
for (int i = 0; i < n_seq; ++i) {
|
||||
DraftAdapt& s = *seq[i];
|
||||
@@ -248,15 +197,18 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
for (int d = 1; d <= M; ++d) {
|
||||
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
|
||||
tok[d] += e;
|
||||
drafts[d] += d <= s.depth ? d : s.depth;
|
||||
}
|
||||
}
|
||||
const double plain = (double)(n_rows - n_seq);
|
||||
if (top > M) top = M;
|
||||
|
||||
/* A step's query rows at depth d: a row a decode sequence and its drafts. */
|
||||
auto gain = [&](int d) { return (tok[d] + plain) / step_cost(n_rows + drafts[d]); };
|
||||
int best = kMinDepth;
|
||||
double best_g = -1.0;
|
||||
for (int d = kMinDepth; d <= top; ++d) {
|
||||
const double g = (tok[d] + plain) / step_cost(d, n_rows);
|
||||
const double g = gain(d);
|
||||
if (g > best_g) { best_g = g; best = d; }
|
||||
}
|
||||
|
||||
@@ -268,7 +220,7 @@ int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
|
||||
} else {
|
||||
if (step_held_ < INT32_MAX) ++step_held_;
|
||||
const int cur = step_d_ < top ? step_d_ : top;
|
||||
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
|
||||
const double cur_g = gain(cur);
|
||||
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
|
||||
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
|
||||
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
|
||||
|
||||
+25
-24
@@ -17,9 +17,10 @@
|
||||
* chance of being emitted still pays for its verify row (kDraftMinChance).
|
||||
*
|
||||
* Per step (plan_step): the head depth D. A serial head runs as many rounds as the deepest
|
||||
* window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(D, n), with
|
||||
* E(d) = 1 + sum_k prod_{j<=k} a_j and T measured online (step_time). Each sequence then
|
||||
* drafts min(D, stop_i).
|
||||
* window in the step, so D maximises sum_i E_i(min(D, stop_i)) / T(R(D)), with
|
||||
* E(d) = 1 + sum_k prod_{j<=k} a_j, R(D) the query rows the step would then carry (a row a
|
||||
* sequence plus sum_i min(D, stop_i)) and T measured online by row count (step_time,
|
||||
* step_cost.h). Each sequence then drafts min(D, stop_i).
|
||||
*
|
||||
* Both move only past a hold, and D also past a hysteresis, because a new window is a new pass
|
||||
* shape that must be recorded before it plays (runtime/ctx.h). `max_depth` stays the ceiling and
|
||||
@@ -35,6 +36,7 @@
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_core.h"
|
||||
#include "step_cost.h"
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -96,15 +98,16 @@ public:
|
||||
static constexpr int kMinDepth = 1;
|
||||
/* A sequence stops at the first draft whose chance of being emitted, prod_{j<=d} a_j, is
|
||||
* under 1 in 10. Once the head runs D rounds for the deepest neighbour, a sequence's only
|
||||
* added cost is its verify row. At one sequence the step-cost prior (1 + 0.06 d) breaks even
|
||||
* near this chance (a draft pays while p_d / E exceeds the ~6% it adds, with E around 2), and
|
||||
* a row alone costs less than a round plus a row, so this is never stricter than D's own
|
||||
* trade. A constant because a row's share cannot be separated from the head's rounds in step
|
||||
* times keyed by depth. */
|
||||
* added cost is its verify row, and a draft pays while p_d / E exceeds the share of the step
|
||||
* that row adds. That share is a few percent at any load and E is two to three tokens a
|
||||
* sequence, so this is never stricter than D's own trade; it only keeps a sequence that
|
||||
* accepts little from riding its neighbours' rounds with rows that are almost never emitted. */
|
||||
static constexpr double kDraftMinChance = 0.1;
|
||||
/* Step times are kept per running-row class: 1, 2-3, 4-7, 8-15, 16+. Cost moves with how many
|
||||
* rows share the weight reads; power-of-two classes keep every key fed. */
|
||||
static constexpr int kCostClasses = 5;
|
||||
/* The shape an untimed row count is priced on (StepCost): each query row adds 12% of a
|
||||
* one-row step, a verify row of streamed experts and its share of a head round. Qwen3.8
|
||||
* Flash-Next on two R9700s, ms a step at 3 / 4 / 5 rows of one sequence: 11.2 / 12.3 / 13.6.
|
||||
* Only ratios are used, and a timed row count replaces it. */
|
||||
static constexpr double kRowCost = 0.12;
|
||||
|
||||
int configure(const Params& p);
|
||||
const Params& params() const { return p_; }
|
||||
@@ -145,15 +148,15 @@ public:
|
||||
* the head (prompt lookup) are held to it, so they add no deeper pass shape. */
|
||||
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
|
||||
|
||||
/* T(depth, n): a decode step with deepest window `depth` and `n_rows` decode rows took `ms`
|
||||
* since the end of the previous step. Fed by Scheduler::step_finished; adaptive policy only. */
|
||||
void step_time(int depth, int n_rows, double ms);
|
||||
/* Expected cost of a step at `depth` with `n_rows` rows: the key's mean (ms) if it has
|
||||
* samples; else the nearest measured key scaled by the prior's ratio (1 + 0.06 d); else the
|
||||
* unitless prior itself. */
|
||||
double step_cost(int depth, int n_rows) const;
|
||||
/* Samples behind a key: for tests and logs. */
|
||||
int64_t cost_samples(int depth, int n_rows) const;
|
||||
/* T(R): a drafting decode step of `q_rows` query rows (every sequence's verified token and
|
||||
* its drafts) took `ms` since the end of the previous step, the head's rounds included. Fed
|
||||
* by Scheduler::step_finished; adaptive policy only. */
|
||||
void step_time(int q_rows, double ms);
|
||||
/* Expected cost of a step of `q_rows` query rows (StepCost::cost): ms once anything is timed,
|
||||
* else the unitless prior. */
|
||||
double step_cost(int q_rows) const;
|
||||
/* Samples behind a row count: for tests and logs. */
|
||||
int64_t cost_samples(int q_rows) const;
|
||||
|
||||
/* E(d) for `s`'s current estimate: expected tokens emitted by a verify of d drafts, the
|
||||
* verified token included. For tests and logs. */
|
||||
@@ -205,15 +208,13 @@ private:
|
||||
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
|
||||
float prior_[RAD_SCHED_MAX_SPEC] = {};
|
||||
int64_t prior_n_ = 0;
|
||||
/* T(d, class): the mean step time of each key, and the steps behind it. */
|
||||
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
|
||||
/* T(R): drafting steps' times by query rows. */
|
||||
StepCost cost_{kRowCost};
|
||||
|
||||
/* Fill a sequence's estimate from the prior and set its first stop. */
|
||||
void start(DraftAdapt& s) const;
|
||||
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
|
||||
int stop_of(const float* a) const;
|
||||
static int cost_class(int n_rows);
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
+4
-40
@@ -8,7 +8,7 @@ namespace rad {
|
||||
void LookupGate::configure(int max_depth) {
|
||||
max_depth_ = max_depth < 0 ? 0 : (max_depth > RAD_SCHED_MAX_SPEC ? RAD_SCHED_MAX_SPEC : max_depth);
|
||||
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
|
||||
for (int k = 0; k < kCostKeys; ++k) { cost_r_[k] = 0.0; cost_ms_[k] = 0.0; cost_n_[k] = 0; }
|
||||
cost_.reset(kRowCost);
|
||||
proposed_ = held_ = held_drafts_ = held_hits_ = 0;
|
||||
}
|
||||
|
||||
@@ -100,46 +100,10 @@ bool LookupGate::pays(double gain, int k, int64_t rows, double tokens) const {
|
||||
return gain * t0 > tokens * (t1 - t0);
|
||||
}
|
||||
|
||||
int LookupGate::cost_key(int64_t rows) {
|
||||
if (rows < 1) rows = 1;
|
||||
if (rows <= kCostExact) return (int)(rows - 1);
|
||||
const int64_t k = kCostExact + (rows - kCostExact - 1) / kCostBand;
|
||||
return (int)(k < kCostKeys ? k : kCostKeys - 1);
|
||||
}
|
||||
void LookupGate::step_time(int64_t rows, double ms) { cost_.sample(rows, ms); }
|
||||
|
||||
void LookupGate::step_time(int64_t rows, double ms) {
|
||||
if (rows < 1 || !(ms > 0.0) || !std::isfinite(ms)) return;
|
||||
const int k = cost_key(rows);
|
||||
double& m = cost_ms_[k];
|
||||
double& r = cost_r_[k];
|
||||
int64_t& n = cost_n_[k];
|
||||
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
r = n ? r + w * ((double)rows - r) : (double)rows;
|
||||
++n;
|
||||
}
|
||||
int64_t LookupGate::cost_samples(int64_t rows) const { return cost_.samples(rows); }
|
||||
|
||||
int64_t LookupGate::cost_samples(int64_t rows) const { return cost_n_[cost_key(rows)]; }
|
||||
|
||||
double LookupGate::step_cost(int64_t rows) const {
|
||||
if (rows < 1) rows = 1;
|
||||
const double R = (double)rows;
|
||||
/* The timed keys either side, by the mean rows of their samples (monotone in the key). */
|
||||
int lo = -1, hi = -1;
|
||||
for (int k = 0; k < kCostKeys; ++k) {
|
||||
if (cost_n_[k] <= 0) continue;
|
||||
if (cost_r_[k] <= R) lo = k;
|
||||
if (cost_r_[k] >= R && hi < 0) hi = k;
|
||||
}
|
||||
if (lo >= 0 && hi >= 0) {
|
||||
const double r0 = cost_r_[lo], r1 = cost_r_[hi];
|
||||
if (lo == hi || r1 <= r0) return cost_ms_[lo];
|
||||
return cost_ms_[lo] + (cost_ms_[hi] - cost_ms_[lo]) * (R - r0) / (r1 - r0);
|
||||
}
|
||||
if (lo >= 0) return cost_ms_[lo] * prior(R) / prior(cost_r_[lo]);
|
||||
if (hi >= 0) return cost_ms_[hi] * prior(R) / prior(cost_r_[hi]);
|
||||
return prior(R);
|
||||
}
|
||||
double LookupGate::step_cost(int64_t rows) const { return cost_.cost(rows); }
|
||||
|
||||
} /* namespace rad */
|
||||
+6
-16
@@ -27,9 +27,10 @@
|
||||
* sequence starts each from its own prior: a long match is drafted at once, a short one waits for
|
||||
* evidence.
|
||||
*
|
||||
* T is measured online over pure decode steps, keyed by rows (StepCost). Before a row count is
|
||||
* timed, its cost is the nearest timed count's scaled by the prior shape 1 + kRowCost (R - 1),
|
||||
* which is optimistic on purpose: the first verify it lets through times the real cost.
|
||||
* T is measured online over pure decode steps, keyed by rows (StepCost, step_cost.h). Before a
|
||||
* row count is timed, its cost is the nearest timed count's scaled by the prior shape
|
||||
* 1 + kRowCost (R - 1), which is optimistic on purpose: the first verify it lets through times
|
||||
* the real cost.
|
||||
*
|
||||
* Only which proposals are verified changes, never what is emitted: output is the same as with
|
||||
* speculation off.
|
||||
@@ -38,6 +39,7 @@
|
||||
#include <cstdint>
|
||||
|
||||
#include "draft.h"
|
||||
#include "step_cost.h"
|
||||
#include "ngram.h"
|
||||
|
||||
namespace rad {
|
||||
@@ -88,14 +90,6 @@ public:
|
||||
static constexpr double kHalfLife = 8.0;
|
||||
/* The shape an untimed row count is priced on: each query row adds 6% to a step. */
|
||||
static constexpr double kRowCost = 0.06;
|
||||
/* Step times: a running mean for the first samples, then a moving average with a half-life of
|
||||
* 32 steps; once a key has 4 samples one step counts for at most 4x its mean (a step that
|
||||
* waited on a recording or a host stall says nothing about its row count). As draft.cpp. */
|
||||
static constexpr double kCostHalfLife = 32.0;
|
||||
static constexpr double kCostOutlier = 4.0;
|
||||
static constexpr int64_t kCostClipAfter = 4;
|
||||
/* Row counts are kept exactly up to 128, then in bands of 32. */
|
||||
enum { kCostExact = 128, kCostBand = 32, kCostKeys = 160 };
|
||||
|
||||
void configure(int max_depth);
|
||||
int max_depth() const { return max_depth_; }
|
||||
@@ -138,13 +132,9 @@ public:
|
||||
private:
|
||||
int max_depth_ = 0;
|
||||
double alpha_ = 0.0;
|
||||
double cost_r_[kCostKeys] = {}; /* mean rows of the samples in each key */
|
||||
double cost_ms_[kCostKeys] = {};
|
||||
int64_t cost_n_[kCostKeys] = {};
|
||||
StepCost cost_{kRowCost};
|
||||
mutable int64_t proposed_ = 0, held_ = 0, held_drafts_ = 0, held_hits_ = 0;
|
||||
|
||||
static int cost_key(int64_t rows);
|
||||
static double prior(double rows) { return 1.0 + kRowCost * (rows - 1.0); }
|
||||
void start(LookupSeq& q) const;
|
||||
void fold(LookupSeq& q, int cls, int len, int hits) const;
|
||||
};
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
#pragma once
|
||||
#include <functional>
|
||||
#include "mem/prefix.h"
|
||||
#include "mem/seqwindow.h"
|
||||
#include "rad_core.h"
|
||||
#include "mm/processor.h"
|
||||
|
||||
@@ -153,6 +154,22 @@ struct IKVManager {
|
||||
* changed tail, must be the only caller. 0 is always correct (restage the whole table). */
|
||||
virtual int64_t take_table_changes(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* The batch builder's reads about (seq, group) in one call (SeqGroupView, mem/seqwindow.h).
|
||||
* The default composes the accessors above, so a manager that does not override it answers
|
||||
* identically; the concrete manager overrides it to find the sequence once. `take_changes`
|
||||
* additionally performs take_table_changes (batch build only, as there). */
|
||||
virtual void seq_group(uint64_t seq, int32_t group, bool take_changes,
|
||||
SeqGroupView* out) const {
|
||||
const std::vector<int32_t>& bt = block_table(seq, group);
|
||||
out->bt = bt.data();
|
||||
out->bt_n = bt.size();
|
||||
out->first = first_block_pos(seq, group);
|
||||
out->has_win = runtime_window(seq, group, &out->win);
|
||||
if (!out->has_win) out->win = SeqWindow{};
|
||||
out->state = state_slot(seq, group);
|
||||
out->changed_from = take_changes ? take_table_changes(seq, group) : 0;
|
||||
}
|
||||
|
||||
/* Whether the snapshot store still holds `slot`. The scheduler checks before building a
|
||||
* restore step, since a released slot may hold another session's state. */
|
||||
virtual bool checkpoint_held(int32_t slot) const = 0;
|
||||
@@ -320,6 +337,78 @@ struct KVGeom {
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
|
||||
/* Steps until trunc(x / bs) next changes as x increases: the run over which a quotient (and
|
||||
* the matching C++ remainder, x - trunc(x/bs)*bs) stays affine. Truncation toward zero makes
|
||||
* the negative side differ from floor: the quotient of a negative x next changes one past a
|
||||
* multiple, not at it. */
|
||||
static int64_t trunc_steps(int64_t x, int64_t bs) {
|
||||
const int64_t q = x / bs;
|
||||
return (q >= 0 ? (q + 1) * bs : q * bs + 1) - x;
|
||||
}
|
||||
|
||||
/* slot() at n consecutive positions pos0, pos0+1, ..., identical values with one division a
|
||||
* segment instead of two a token. A segment ends where the block index or the in-block
|
||||
* offset would change rule (trunc_steps of (pos - first_pos) and of pos); inside it the slot
|
||||
* is (block base + off + k), or -1 throughout when the block index is outside the table.
|
||||
* bt is the table's data and length where slot() takes the vector. */
|
||||
void slots(int gi, const int32_t* bt, size_t bt_n, int64_t first_pos, int64_t pos0,
|
||||
int64_t n, int32_t* out) const {
|
||||
const int64_t bs = g[(size_t)gi].block_size;
|
||||
int64_t done = 0;
|
||||
while (done < n) {
|
||||
const int64_t pos = pos0 + done;
|
||||
const int64_t rel = pos - first_pos;
|
||||
const int64_t bi = rel / bs;
|
||||
int64_t len = trunc_steps(rel, bs);
|
||||
const int64_t lo = trunc_steps(pos, bs);
|
||||
if (lo < len) len = lo;
|
||||
if (len > n - done) len = n - done;
|
||||
if (bi < 0 || (size_t)bi >= bt_n) {
|
||||
for (int64_t k = 0; k < len; ++k) out[done + k] = -1;
|
||||
} else {
|
||||
const int64_t base = (int64_t)bt[(size_t)bi] * bs + pos % bs;
|
||||
for (int64_t k = 0; k < len; ++k) out[done + k] = (int32_t)(base + k);
|
||||
}
|
||||
done += len;
|
||||
}
|
||||
}
|
||||
|
||||
/* slot_ring() at n consecutive positions, the same treatment. Positions before ring_pos go
|
||||
* through slots(); in the ring the block index advances where (pos - ring_pos) crosses a
|
||||
* block multiple, wrapping modulo ring_blocks at those same points. A window with no ring
|
||||
* blocks cannot be armed (KVManager::set_window clamps the ring to at least one block and
|
||||
* slot_ring's modulo would be by zero), so it takes the plain mapping. */
|
||||
void slots_ring(int gi, const int32_t* bt, size_t bt_n, int64_t first_pos, int64_t pos0,
|
||||
int64_t n, const SeqWindow& w, int32_t* out) const {
|
||||
if (!w.set || w.ring_blocks <= 0) {
|
||||
slots(gi, bt, bt_n, first_pos, pos0, n, out);
|
||||
return;
|
||||
}
|
||||
const int64_t bs = g[(size_t)gi].block_size;
|
||||
int64_t done = 0;
|
||||
if (pos0 < w.ring_pos) {
|
||||
done = w.ring_pos - pos0 < n ? w.ring_pos - pos0 : n;
|
||||
slots(gi, bt, bt_n, first_pos, pos0, done, out);
|
||||
}
|
||||
const int64_t ring_bi0 = w.ring_pos / bs;
|
||||
while (done < n) {
|
||||
const int64_t pos = pos0 + done;
|
||||
const int64_t rp = pos - w.ring_pos;
|
||||
const int64_t bi = ring_bi0 + (rp / bs) % w.ring_blocks;
|
||||
int64_t len = trunc_steps(rp, bs);
|
||||
const int64_t lo = trunc_steps(pos, bs);
|
||||
if (lo < len) len = lo;
|
||||
if (len > n - done) len = n - done;
|
||||
if (bi < 0 || (size_t)bi >= bt_n) {
|
||||
for (int64_t k = 0; k < len; ++k) out[done + k] = -1;
|
||||
} else {
|
||||
const int64_t base = (int64_t)bt[(size_t)bi] * bs + pos % bs;
|
||||
for (int64_t k = 0; k < len; ++k) out[done + k] = (int32_t)(base + k);
|
||||
}
|
||||
done += len;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ binding the concrete classes */
|
||||
@@ -387,6 +476,9 @@ struct KVBinding final : IKVManager {
|
||||
int64_t take_table_changes(uint64_t s, int32_t g) const override {
|
||||
return m->take_table_changes(s, g);
|
||||
}
|
||||
void seq_group(uint64_t s, int32_t g, bool take, SeqGroupView* o) const override {
|
||||
m->seq_group(s, g, take, o);
|
||||
}
|
||||
bool checkpoint_held(int32_t slot) const override { return m->checkpoint_held(slot); }
|
||||
};
|
||||
|
||||
|
||||
+86
-20
@@ -296,16 +296,42 @@ void Scheduler::fini() {
|
||||
|
||||
/* ------------------------------------------------------------------ arrival */
|
||||
int Scheduler::add(std::unique_ptr<Request> r) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
return add_locked(std::move(r));
|
||||
int rc;
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
rc = add_locked(std::move(r));
|
||||
}
|
||||
wake();
|
||||
return rc;
|
||||
}
|
||||
|
||||
/* One lock for all of them, so the step that admits the first finds them all waiting. Otherwise a
|
||||
* step could start between two adds and admit a timing-dependent subset, and the batch (and its
|
||||
* tie-level rounding) would vary between identical runs. */
|
||||
void Scheduler::add_all(std::unique_ptr<Request>* rs, size_t n, int* rc) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i]));
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
for (size_t i = 0; i < n; ++i) rc[i] = add_locked(std::move(rs[i]));
|
||||
}
|
||||
wake();
|
||||
}
|
||||
|
||||
uint64_t Scheduler::wake_seq() {
|
||||
std::lock_guard<std::mutex> lk(wake_mu_);
|
||||
return wake_n_;
|
||||
}
|
||||
|
||||
void Scheduler::wait_idle(uint64_t seen, std::chrono::microseconds max) {
|
||||
std::unique_lock<std::mutex> lk(wake_mu_);
|
||||
wake_cv_.wait_for(lk, max, [&] { return wake_n_ != seen; });
|
||||
}
|
||||
|
||||
void Scheduler::wake() {
|
||||
{
|
||||
std::lock_guard<std::mutex> lk(wake_mu_);
|
||||
++wake_n_;
|
||||
}
|
||||
wake_cv_.notify_all();
|
||||
}
|
||||
|
||||
int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
@@ -535,6 +561,35 @@ int64_t Scheduler::reset_prefix_cache() {
|
||||
return dropped;
|
||||
}
|
||||
|
||||
int64_t Scheduler::evict_prefix_until(const std::function<bool()>& enough) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!pc_ || !cfg_.prefix_cache) return 0;
|
||||
int64_t total = 0;
|
||||
/* Doubling, since the blocks that free the top of the pool may be anywhere in the LRU order. */
|
||||
for (int64_t n = 64; !enough(); n *= 2) {
|
||||
const int64_t done = pc_->trim(n);
|
||||
if (done <= 0) break;
|
||||
total += done;
|
||||
}
|
||||
/* What is left has no host copy to fall back on, or one still on its way. */
|
||||
if (!enough()) {
|
||||
const int64_t dropped = pc_->reset();
|
||||
RAD_INFO("prefix cache: reset for room, %lld entries dropped", (long long)dropped);
|
||||
total += dropped;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
int Scheduler::preempt_until(const std::function<bool()>& enough) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
int n = 0;
|
||||
while (!running_.empty() && !enough()) {
|
||||
preempt_back();
|
||||
++n;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
int Scheduler::release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
|
||||
SessionRelease* out) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
@@ -748,6 +803,8 @@ int Scheduler::cancel(uint64_t id) {
|
||||
* the request; then commit or sweep_deferred releases them (SchedReq::pending_free). */
|
||||
const bool in_flight = in_step(s) || block_holds(id);
|
||||
close_request(s, ReqState::Cancelled, "cancelled", in_flight);
|
||||
/* The idle loop drains what a cancel releases. */
|
||||
wake();
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1357,12 +1414,14 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
++rounds;
|
||||
/* Nothing else is running, so a missing state slot will not come back by waiting.
|
||||
* Put leaked slots back, then admit. A recompute the empty pool cannot hold is
|
||||
* failed below (spec §17) rather than left in kAdmitWait, which parks the engine. */
|
||||
if (!preempted_can_prefill(s) && running_.empty())
|
||||
* failed below (spec §17) rather than left in kAdmitWait, which parks the engine.
|
||||
* A request this pass has just admitted is not in running_ yet, and it runs. */
|
||||
if (!preempted_can_prefill(s) && running_.empty() && took_.empty())
|
||||
(void)kv_->release_idle_states();
|
||||
}
|
||||
if (!preempted_can_prefill(s)) {
|
||||
if (!(running_.empty() && preempt_wait_overdue(s) && kv_->can_ever_fit(s.seq_len())))
|
||||
if (!(running_.empty() && took_.empty() && preempt_wait_overdue(s) &&
|
||||
kv_->can_ever_fit(s.seq_len())))
|
||||
return kAdmitWait;
|
||||
}
|
||||
}
|
||||
@@ -2021,8 +2080,13 @@ const RadBatch* Scheduler::step() {
|
||||
preempted_here = true;
|
||||
if (last) { yielded = true; break; }
|
||||
}
|
||||
/* close_request or preempt_back removed it from running_; i now indexes the next. */
|
||||
if (failed || yielded) continue;
|
||||
/* close_request or preempt_back removed it from running_; i now indexes the next. A chunk
|
||||
* marked as held back has no entry after all, and the mark would name whichever comes next
|
||||
* or none. */
|
||||
if (failed || yielded) {
|
||||
if (capped_at == (int32_t)plan_.e.size()) capped_at = -1;
|
||||
continue;
|
||||
}
|
||||
|
||||
StepEntry e;
|
||||
e.req = &r;
|
||||
@@ -2128,8 +2192,9 @@ const RadBatch* Scheduler::step() {
|
||||
* the refusal is a restore waiting a step for deferred releases: both clear by the
|
||||
* next step, and failing them lost two of ten preempted requests under KV pressure
|
||||
* once their prompts were published at the preemption (1. 11. 2026). */
|
||||
if (as < 0 && running_.empty() && plan_.e.empty() && !admit_next_step_ && s.req &&
|
||||
s.req->state == ReqState::Preempted && preempt_wait_overdue(s)) {
|
||||
if (as < 0 && running_.empty() && took_.empty() && plan_.e.empty() &&
|
||||
!admit_next_step_ && s.req && s.req->state == ReqState::Preempted &&
|
||||
preempt_wait_overdue(s)) {
|
||||
RAD_WARN("request %llu failed: overdue preempted prefill could not be admitted "
|
||||
"with nothing running (%s)",
|
||||
(unsigned long long)s.req->id, rad_strerror(as));
|
||||
@@ -2578,6 +2643,8 @@ void Scheduler::promote_next() {
|
||||
int Scheduler::commit(StepResult& res) {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (!step_open_) return RAD_E_STATE;
|
||||
/* The step's tokens are pushed at one time (Sink::push). */
|
||||
const int64_t pushed_ns = server::sink_now_ns();
|
||||
/* StepResult's counts describe this step only. */
|
||||
step_finished_ = 0;
|
||||
last_prefill_ids_.clear();
|
||||
@@ -2660,7 +2727,7 @@ int Scheduler::commit(StepResult& res) {
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i]] : nullptr;
|
||||
if (lp && lp->token < 0) lp_failed = true;
|
||||
else overflowed = !server::sink_push(r.sink, res.token[i], lp);
|
||||
else overflowed = !server::sink_push(r.sink, res.token[i], lp, pushed_ns);
|
||||
/* The conv window absorbed this chunk; the cursor advances one committed
|
||||
* position, as in decode. */
|
||||
s.conv_cursor = (int32_t)((s.conv_cursor + 1) % (W ? W : 1));
|
||||
@@ -2719,7 +2786,7 @@ int Scheduler::commit(StepResult& res) {
|
||||
res.lp && res.first_row[i] >= 0 && r.sp.n_probs >= 0
|
||||
? &res.lp[res.first_row[i] + j] : nullptr;
|
||||
if (lp_failed || (lp && lp->token < 0)) { lp_failed = true; return; }
|
||||
if (!server::sink_push(r.sink, t, lp)) overflowed = true;
|
||||
if (!server::sink_push(r.sink, t, lp, pushed_ns)) overflowed = true;
|
||||
};
|
||||
/* On a tree step the accepted drafts are the path's nodes, in path order. */
|
||||
const int32_t* path = res.path ? res.path + (size_t)i * RAD_SCHED_MAX_SPEC : nullptr;
|
||||
@@ -2892,14 +2959,13 @@ void Scheduler::step_finished() {
|
||||
for (const StepEntry& e : plan_.e) rows += e.is_prefill ? 0 : e.n_tokens;
|
||||
if (rows > 0) lookup_.step_time(rows, wall * 1e3);
|
||||
}
|
||||
/* The step's cost at its depth, for the adaptive window (draft.h): the same wall time,
|
||||
* including the draft rounds after it, with a step issued ahead counted once. Decode steps
|
||||
* only. Keyed by the deepest window the step verified, which is the head depth it ran at
|
||||
* whenever D held from the step before. */
|
||||
/* The step's cost by query rows, for the adaptive window (draft.h): the same wall time,
|
||||
* including the draft rounds after it, with a step issued ahead counted once. Drafting decode
|
||||
* steps only: a step that verified nothing ran no head round. */
|
||||
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
|
||||
int rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
|
||||
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
|
||||
int64_t rows = 0;
|
||||
for (const StepEntry& e : plan_.e) rows += e.is_prefill ? 0 : e.n_tokens;
|
||||
if (rows > 0) draft_.step_time((int)rows, wall * 1e3);
|
||||
}
|
||||
last_step_at_ = step_end;
|
||||
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
#include "ngram.h"
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#ifdef RAD_ENABLE_KV_ROLLBACK_TEST_HOOK
|
||||
#include <functional>
|
||||
#endif
|
||||
@@ -201,6 +202,12 @@ public:
|
||||
/* `n` requests under one hold of the queue lock, each accepted or refused as add() would, with
|
||||
* its result in rc[i]. For the sequences of one API request, which must reach the same step. */
|
||||
void add_all(std::unique_ptr<Request>* rs, size_t n, int* rc);
|
||||
/* The step loop's idle wait. wake_seq() before a step() that finds nothing, then
|
||||
* wait_idle(seen, max): it returns at once if anything woke the loop since `seen` (a request
|
||||
* added or cancelled, or wake()), else after `max` at the latest. */
|
||||
uint64_t wake_seq();
|
||||
void wait_idle(uint64_t seen, std::chrono::microseconds max);
|
||||
void wake();
|
||||
/* Frees blocks immediately rather than at completion (spec §14); otherwise the pool shrinks
|
||||
* under exactly the load that cancels. */
|
||||
int cancel(uint64_t id);
|
||||
@@ -309,6 +316,16 @@ public:
|
||||
* cache. Takes the step lock because the step path inserts into the map (live sequences hold
|
||||
* their own block references). See IScheduler::reset_prefix_cache. */
|
||||
int64_t reset_prefix_cache();
|
||||
/* Least recently used entries leave VRAM until `enough()` (called under the step lock) holds
|
||||
* or the whole cache has gone; an entry with a host copy stays restorable as long as that
|
||||
* gives enough room. Returns how many went.
|
||||
* The step lock, with nothing in flight reading the blocks. */
|
||||
int64_t evict_prefix_until(const std::function<bool()>& enough);
|
||||
/* Running requests go back to the queue by recompute, youngest first, their blocks freed,
|
||||
* until `enough()` (called under the step lock) holds or none runs: the fleet takes a
|
||||
* lower-priority model's cache while it is busy (docs/MULTIMODEL.md §6.4). Between steps
|
||||
* only, with nothing in flight. Returns how many went back. */
|
||||
int preempt_until(const std::function<bool()>& enough);
|
||||
/* The end-of-generation ids the card's acceptance reads, for ends_every_request. Set once at
|
||||
* start; without them only max_tokens ends are predicted. */
|
||||
void set_eog(std::vector<int32_t> ids);
|
||||
@@ -639,6 +656,14 @@ private:
|
||||
|
||||
mutable std::mutex mu_;
|
||||
|
||||
/* wake_seq/wait_idle/wake. */
|
||||
|
||||
std::mutex wake_mu_;
|
||||
|
||||
std::condition_variable wake_cv_;
|
||||
|
||||
uint64_t wake_n_ = 0;
|
||||
|
||||
SchedMetrics metrics_locked() const;
|
||||
int requests_locked(ReqStat* out, int max) const;
|
||||
/* The published copy and its lock (publish()). The scratch pair is the engine thread's, filled
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
/* step_cost.h -- a decode step's wall time as a function of its query rows, measured online.
|
||||
*
|
||||
* A decode step's cost moves with the rows it carries (each sequence's verified token and its
|
||||
* drafts): the routed experts and every other weight read per row. Both speculation policies
|
||||
* weigh a draft's expected yield against that cost (lookup.h, draft.h), and both need the cost of
|
||||
* row counts they have not run yet. So step times are kept by row count: a timed count is its
|
||||
* mean; one between two timed counts lies on the line between them; one outside them is the
|
||||
* nearest timed count scaled by a prior shape, 1 + row_cost (R - 1); with nothing timed it is
|
||||
* that shape itself, unitless. Only ratios of costs are used.
|
||||
*
|
||||
* Row counts move by themselves as sequences come and go, so a policy holding one window still
|
||||
* times its neighbours' row counts without ever trying them.
|
||||
*/
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
|
||||
namespace rad {
|
||||
|
||||
class StepCost {
|
||||
public:
|
||||
/* A running mean for the first samples, then a moving average with a half-life of 32 steps:
|
||||
* long enough to average out one-off costs (a tier copy, a recording, a prefix-cache trim),
|
||||
* short enough to follow a context growing by a few thousand tokens over a reply. */
|
||||
static constexpr double kHalfLife = 32.0;
|
||||
/* Once a key has 4 samples one step counts for at most 4x its mean: a step that waited on a
|
||||
* recording or a host stall says nothing about its row count. Below 4 samples the mean is not
|
||||
* a trustworthy reference to clip against. */
|
||||
static constexpr double kOutlier = 4.0;
|
||||
static constexpr int64_t kClipAfter = 4;
|
||||
/* Row counts are kept exactly up to 128, then in bands of 32. */
|
||||
enum { kExact = 128, kBand = 32, kKeys = 160 };
|
||||
|
||||
/* `row_cost` is the prior shape's slope: the share of a one-row step each further row adds. */
|
||||
explicit StepCost(double row_cost = 0.0) : row_cost_(row_cost) {}
|
||||
|
||||
/* Forgets every sample and takes a slope. */
|
||||
void reset(double row_cost) {
|
||||
row_cost_ = row_cost;
|
||||
for (int k = 0; k < kKeys; ++k) { r_[k] = 0.0; ms_[k] = 0.0; n_[k] = 0; }
|
||||
}
|
||||
|
||||
/* A step of `rows` query rows took `ms`. Nonsense is not a sample. */
|
||||
void sample(int64_t rows, double ms) {
|
||||
if (rows < 1 || !(ms > 0.0) || !std::isfinite(ms)) return;
|
||||
const int k = key(rows);
|
||||
double& m = ms_[k];
|
||||
double& r = r_[k];
|
||||
int64_t& n = n_[k];
|
||||
if (n >= kClipAfter && ms > kOutlier * m) ms = kOutlier * m;
|
||||
const double w = std::fmax(1.0 - std::exp2(-1.0 / kHalfLife), 1.0 / (double)(n + 1));
|
||||
m = n ? m + w * (ms - m) : ms;
|
||||
r = n ? r + w * ((double)rows - r) : (double)rows;
|
||||
++n;
|
||||
}
|
||||
|
||||
/* The expected wall time of a step of `rows` rows: ms once anything is timed, else the
|
||||
* unitless prior. */
|
||||
double cost(int64_t rows) const {
|
||||
if (rows < 1) rows = 1;
|
||||
const double R = (double)rows;
|
||||
/* The timed keys either side, by the mean rows of their samples (monotone in the key). */
|
||||
int lo = -1, hi = -1;
|
||||
for (int k = 0; k < kKeys; ++k) {
|
||||
if (n_[k] <= 0) continue;
|
||||
if (r_[k] <= R) lo = k;
|
||||
if (r_[k] >= R && hi < 0) hi = k;
|
||||
}
|
||||
if (lo >= 0 && hi >= 0) {
|
||||
const double r0 = r_[lo], r1 = r_[hi];
|
||||
if (lo == hi || r1 <= r0) return ms_[lo];
|
||||
return ms_[lo] + (ms_[hi] - ms_[lo]) * (R - r0) / (r1 - r0);
|
||||
}
|
||||
if (lo >= 0) return ms_[lo] * prior(R) / prior(r_[lo]);
|
||||
if (hi >= 0) return ms_[hi] * prior(R) / prior(r_[hi]);
|
||||
return prior(R);
|
||||
}
|
||||
|
||||
/* Samples behind a row count's key: for tests and logs. */
|
||||
int64_t samples(int64_t rows) const { return n_[key(rows)]; }
|
||||
|
||||
private:
|
||||
double row_cost_ = 0.0;
|
||||
double r_[kKeys] = {}; /* mean rows of the samples in each key */
|
||||
double ms_[kKeys] = {};
|
||||
int64_t n_[kKeys] = {};
|
||||
|
||||
static int key(int64_t rows) {
|
||||
if (rows < 1) rows = 1;
|
||||
if (rows <= kExact) return (int)(rows - 1);
|
||||
const int64_t k = kExact + (rows - kExact - 1) / kBand;
|
||||
return (int)(k < kKeys ? k : kKeys - 1);
|
||||
}
|
||||
double prior(double rows) const { return 1.0 + row_cost_ * (rows - 1.0); }
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
Reference in new issue
Block a user