radiance 1.11.0

New models:
- GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget),
  with decode kernels for a few rows and the DSA indexer split over the ranks
- Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter
- Unlimited-OCR (bf16)
- Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces
  are fused with the junctions, overlapped with the compute and sent compressed
- Ornith-1.5-35B-A3B w4a8 compose files

Speed:
- Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued
  ahead
- The four-rank all-reduce is faster for every --tp 4 model
- qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly
- --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20%
  prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default

Features:
- Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch,
  and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE)
- Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance
- Cards with a small PCI BAR run, with kernel arguments kept in host memory
- Dashboard: live acceptance figures; statsdump rotates its file at a size cap
- KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot

Fixes:
- Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore
  makes room as memory pressure does and waits a step for the previous turn's release (two
  conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now)
- Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory
  management is turned off there, with a warning
- Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output
- The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start
- GLM-5.3: every refusal names the setting and the reason; its template keeps string content
- Several pictures in one request no longer refuse processors that take one image at a time

Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
Deadcode committed 2026-10-23 11:57:52 +02:00
210 files changed
+14363 -2138

No files matched your search

+10
View File
@@ -60,6 +60,16 @@ struct AdvGroup {
int64_t used_off; /* [n_seq] seqused */
int64_t bt_off; /* [n_seq][pitch] block table */
int64_t first_off; /* [n_seq] the position each row's block table starts at */
/* The runtime window (KVManager::set_window / SeqWindow), so the card computes the same
* `used` and slots the host builder staged: a ring sequence keeps its reference and rewrites
* a fixed ring of blocks, so its held span stops at its own table and a position past its
* ring_pos maps modulo ring_blocks. Without it (ring 0) the advance is the linear mapping, as
* before. ring_pos and the table length are per sequence (each prompt has its own floor and
* table), ring_blocks is the same for the group (one W). */
int32_t ring; /* 1: the group carries runtime windows */
int32_t ring_blocks; /* whole blocks the ring holds */
int64_t rpos_off; /* [n_seq] the sequence's block-aligned first ring position, 0 if none */
int64_t tlen_off; /* [n_seq] the sequence's block-table length in blocks, 0 if none */
};
/* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the
+26 -4
View File
@@ -30,21 +30,43 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
/* Every group's slots for the row's `n` positions (from the positions just written) and its
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
* tables for the furthest reachable position, so only a row whose output is unused hits this. */
* tables for the furthest reachable position, so only a row whose output is unused hits this.
*
* A runtime window (e.ring, KVManager::set_window) must be computed exactly as the host builder
* staged it (BatchBuilder::build_groups), because this runs after the build and overwrites what it
* wrote:
* - `used` stops at the table: the ring reuses its blocks, so the sequence's held span is the
* table's, not the context's. Without this the decode walks bt[(used-1)/block] past the end,
* reads the -1 padding the builder fills and faults the card on a negative block;
* - a position at or past ring_pos lives in the ring, at block
* ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs
* off the table once the ring wraps. */
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
const int32_t* pos = adv_i32(a, a.pos_off);
for (int g = 0; g < a.n_groups; ++g) {
const AdvGroup& e = G[g];
const int32_t first = adv_i32(a, e.first_off)[i];
adv_i32(a, e.used_off)[i] = base + n - first;
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
const bool ring = e.ring && tlen > 0;
int64_t used = (int64_t)base + n - first;
if (ring) {
const int64_t span = (int64_t)tlen * e.block_size;
if (used > span) used = span;
}
adv_i32(a, e.used_off)[i] = (int32_t)used;
if (!e.paged) continue;
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
int32_t* slot = adv_i32(a, e.slot_off);
for (int32_t j = 0; j < n; ++j) {
const int32_t p = pos[k + j];
const int32_t bi = (p - first) / e.block_size;
slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0)
int32_t bi = (p - first) / e.block_size;
if (ring && p >= rpos && e.ring_blocks > 0)
bi = rpos / e.block_size +
((p - rpos) / e.block_size) % e.ring_blocks;
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
? bt[bi] * e.block_size + p % e.block_size : -1;
}
}
+61 -3
View File
@@ -6,6 +6,7 @@
#include "device/device.h"
#include <algorithm>
#include <cassert>
#include <cstring>
#include <cstdlib>
@@ -112,6 +113,9 @@ void BatchBuilder::carve(Set& s, char* h) {
pair(&s.h_dout, &s.d_dout, S);
pair(&s.h_rows, &s.d_rows, 4 * S);
pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size());
/* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */
pair(&s.h_rpos, &s.d_rpos, S);
pair(&s.h_tlen, &s.d_tlen, S);
s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size());
s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size());
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
@@ -686,17 +690,37 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
}
int64_t t = 0;
/* The group's ring block count, read off the first armed sequence: declare_runtime_window
* fixes one W per group, so every armed sequence computes the same count. Collected here,
* with the table walk that already opens each window, so the group header below needs no
* second pass over the plan. */
int32_t ring_blocks = 0;
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;
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);
for (int32_t j = 0; j < e.n_tokens; ++j)
g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
if (has_win) {
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
ring_blocks = (int32_t)win.ring_blocks;
}
bt_len = (int64_t)bt.size();
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);
}
/* 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
@@ -737,6 +761,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
}
s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
/* The advance recomputes this row's used and slots after the build (advance_impl.h),
* so it needs the same per-sequence ring data this build staged: the row's floor and
* its table's length, 0 when the sequence has no runtime window. */
s.h_rpos[i] = has_win ? (int32_t)win.ring_pos : 0;
s.h_tlen[i] = has_win ? (int32_t)bt_len : 0;
t += e.n_tokens;
/* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
@@ -745,8 +774,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
* unwritten slots at the end of the table, read as the newest context; a non-causal
* window group would attend to them. Do not clamp to `window` either: the held span
* may exceed it by under a block, and clamping would drop the newest tokens. Attending
* a few extra old positions is the cost of paging a window (vLLM does the same). */
* a few extra old positions is the cost of paging a window (vLLM does the same).
*
* A runtime window (R-SWA) has reused its ring's slots once the sequence is past the
* ring's span, so the held span is the table's, not the context's: every slot of the
* reference and of the ring holds live KV, and the ring's blocks are what a non-causal
* decode reads. Before the ring is full the shorter of the two is the written count. */
int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
if (has_win) {
used = std::min<int64_t>(used, table_end);
}
if (used < 0) used = 0;
g.h_used[i] = (int32_t)used;
if (L.paged) {
@@ -773,6 +810,15 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
a.used_off = (const char*)g.d_used - d0;
a.bt_off = (const char*)g.d_bt - d0;
a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0;
/* The runtime window (KVManager::set_window): the advance runs after this build and
* overwrites `used` and the slots, so it must reproduce the ring's mapping rather
* than the linear one (advance_impl.h). The floor and table length are per sequence
* (s.h_rpos / s.h_tlen), the ring's block count is the group's W, collected with the
* table walk above. */
a.ring = ring_blocks ? 1 : 0;
a.ring_blocks = ring_blocks;
a.rpos_off = (const char*)s.d_rpos - d0;
a.tlen_off = (const char*)s.d_tlen - d0;
}
for (size_t r = 0; r < ranks_.size(); ++r) {
@@ -872,6 +918,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
int32_t rope_mixed = 0;
int64_t n_mm = 0;
bool lora_rows = false;
int32_t cvec_rows = 0;
s.h_cu[0] = 0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
@@ -905,6 +952,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls;
if (ls >= 0 && e.n_tokens > 0) lora_rows = true;
}
/* The same rows derive.cpp's projection_on_rows sets (RadBatch::control_vector). */
if (e.req && e.req->sp.use_control_vector && e.n_tokens > 0) cvec_rows = 1;
/* Rotary position of each row at its own position (draft-head rows rotate at the index
* they write, not the token they embed). Three planes of n_tok. */
if (mm_on_) {
@@ -1113,6 +1162,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
* runs the same pass as an engine serving no adapters. */
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
B.control_vector = cvec_rows;
B.enc = 0;
B.enc_n_patch = 0;
B.enc_pixels = nullptr;
@@ -1120,6 +1170,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
B.enc_n_seg = 0;
B.enc_cu = nullptr;
B.enc_max_seg = 0;
B.enc_seg_h = nullptr;
B.enc_seg_w = nullptr;
B.n_checkpoints = n_ck;
B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr;
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
@@ -1188,6 +1240,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
enc_cu_host_[0] = 0;
enc_seg_h_host_.clear();
enc_seg_w_host_.clear();
for (const EncoderPart& p : parts) {
const mm::Item& it = *p.item;
if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) {
@@ -1210,6 +1264,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) {
const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q);
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
enc_seg_h_host_.push_back(it.seg_h(q));
enc_seg_w_host_.push_back(it.seg_w(q));
++n_seg;
if (seg_p > max_seg) max_seg = seg_p;
}
@@ -1256,6 +1312,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
B.enc_n_seg = n_seg;
B.enc_cu = static_cast<const int32_t*>(enc_cu_dev_[r]);
B.enc_max_seg = (int32_t)max_seg;
B.enc_seg_h = enc_seg_h_host_.data();
B.enc_seg_w = enc_seg_w_host_.data();
}
out_last_ = out_next_;
out_next_ = (out_next_ + 1) % kOut;
+8
View File
@@ -199,6 +199,11 @@ private:
int32_t *h_rows = nullptr, *d_rows = nullptr;
int32_t *h_first = nullptr, *d_first = nullptr;
AdvGroup *h_grp = nullptr, *d_grp = nullptr;
/* [max_seqs] per-sequence runtime-window data for the advance: the block-aligned first
* ring position and the block table's length in blocks, 0 when the sequence has no
* runtime window (advance.h). Per sequence because each prompt has its own floor. */
int32_t *h_rpos = nullptr, *d_rpos = nullptr;
int32_t *h_tlen = nullptr, *d_tlen = nullptr;
char* h_derived = nullptr; /* derivation staging, byte-addressed */
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
@@ -328,6 +333,9 @@ private:
int32_t* enc_coord_host_ = nullptr;
int32_t* enc_cu_host_ = nullptr;
std::vector<int32_t> enc_coord_tmp_; /* one item's coordinates; kept for its capacity */
/* The pass's per-segment grid, host side (RadBatch::enc_seg_h/w). Filled by build_encoder and
* valid until the next build, like the staged coordinates. */
std::vector<int32_t> enc_seg_h_host_, enc_seg_w_host_;
int64_t last_n_tok_ = 0;
struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */
+6 -2
View File
@@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
* served by a different kernel may differ (§7.2). */
bool has_linear = false, has_window = false;
for (const KVGroupInfo& kg : prog.kv_groups) {
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
kg.decl.kind == RAD_KV_RING) {
if (kg.block_size > 0) {
g.attn_block = lcm64(g.attn_block, kg.block_size);
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
* snapshot for a prefix hit to resume. */
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
* length, which no slot could describe, so it is sized for the context plus a ring
* and is never checkpointed. */
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
has_window = true;
}
+79 -15
View File
@@ -44,6 +44,24 @@ struct IKVManager {
/* After a committed step, a window group frees what no later query can read
* (KVManager::trim_window). */
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
/* R-SWA (KVManager::declare_runtime_window): the W this group arms a sequence with, 0 when it
* carries no runtime windows. The scheduler arms every sequence it admits with
* set_window(seq, prompt length, W); a manager with no runtime window refuses it and the
* scheduler never asks. */
virtual int64_t runtime_window_tokens(int32_t group) const { (void)group; return 0; }
virtual int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens) {
(void)seq; (void)visible_lo; (void)window_tokens;
return RAD_E_UNSUPPORTED;
}
/* The sequence's runtime window in `group`, if it has one (KVManager::runtime_window). A
* sequence with one is excluded from prefix publish, checkpoint snapshots and speculation:
* the window is runtime data and the ring rewrites its slots in place. */
virtual bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const {
(void)seq; (void)group; (void)out;
return false;
}
virtual bool has_runtime_window(uint64_t seq) const { (void)seq; return false; }
/* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
* defaults mean no hit on a windowed trunk is ever resumed. */
virtual bool has_window_snapshot() const { return false; }
@@ -95,7 +113,11 @@ struct IKVManager {
/* Absolute token position that block_table(seq, group)[0] covers: zero for a full group,
* non-zero for a window group once blocks below the window are recycled. The step batch maps
* a slot as `(pos - first_block_pos) / block_size`. */
* a slot as `(pos - first_block_pos) / block_size`.
*
* A sequence with a runtime window (runtime_window) keeps first_block_pos 0 even once the ring
* recycles: its table is [reference][ring] from position 0 and the ring's positions map
* modulo ring_blocks (SeqWindow), so only the slot index recycles, never the table. */
virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0;
/* Index of the first entry of block_table(seq, group) changed since the previous call;
@@ -110,13 +132,22 @@ struct IKVManager {
};
/* ------------------------------------------------------------------ the prefix cache */
/* What IPrefixCache::restore did: brought back every entry the tiers hold for the prompt (or there
* were none), brought back part of them because the pool could not hold the chain, or, asked for
* the whole chain only, left it on the host. */
enum class RestoreResult : uint8_t { Whole, Cut, Declined };
struct IPrefixCache {
virtual ~IPrefixCache() = default;
/* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine
* performs it (it allocates blocks and runs a device scatter). A failure only leaves a
* shorter prefix, which is always safe. */
virtual void restore(const Request&) {}
* shorter prefix, which is always safe. With `whole_only`, a chain the pool cannot be made to
* hold whole is left on the host (RestoreResult::Declined). */
virtual RestoreResult restore(const Request&, bool whole_only) {
(void)whole_only;
return RestoreResult::Whole;
}
/* A step's admissions begin; the last step's lookup results have been consumed. */
virtual void begin_step() {}
/* Keep this waiting request's chain in VRAM until release(). Called when admission is refused
@@ -170,8 +201,6 @@ struct IPrefixCache {
virtual CkptCounts ckpt_counts() const { return {}; }
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
virtual int64_t expired() const { return 0; }
/* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */
virtual int64_t restore_cuts() const { return 0; }
virtual int64_t ckpt_expired() const { return 0; }
/* Tokens of context held only by the cache right now. Blocks a running sequence also reads
@@ -215,7 +244,7 @@ struct KVGeom {
for (const KVGroupInfo& gi : groups) {
G e;
e.kind = gi.decl.kind;
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW);
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW || e.kind == RAD_KV_RING);
e.block_size = gi.block_size > 0 ? gi.block_size : 1;
e.window = gi.decl.window;
k.g.push_back(e);
@@ -231,6 +260,23 @@ 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));
}
/* The same slot for a runtime window (SeqWindow): the reference maps linearly (first_pos is
* 0 there), and a position at or past the ring's start lives in block
* ring_pos/block + ((pos - ring_pos)/block) % ring_blocks, which is what rewrites the ring's
* slots in place. ring_pos is block-aligned, so `pos % block` stays the in-block offset. */
int32_t slot_ring(int gi, const std::vector<int32_t>& bt, int64_t first_pos, int64_t pos,
const SeqWindow& w) const {
const G& e = g[(size_t)gi];
int64_t bi;
if (w.set && pos >= w.ring_pos) {
bi = w.ring_pos / e.block_size + ((pos - w.ring_pos) / e.block_size) % w.ring_blocks;
} else {
bi = (pos - first_pos) / e.block_size;
}
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
}
};
/* ------------------------------------------------------------------ binding the concrete classes */
@@ -246,6 +292,12 @@ struct KVBinding final : IKVManager {
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); }
void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); }
int64_t runtime_window_tokens(int32_t g) const override { return m->runtime_window_tokens(g); }
int set_window(uint64_t s, int64_t lo, int64_t w) override { return m->set_window(s, lo, w); }
bool runtime_window(uint64_t s, int32_t g, SeqWindow* o) const override {
return m->runtime_window(s, g, o);
}
bool has_runtime_window(uint64_t s) const override { return m->has_runtime_window(s); }
bool has_window_snapshot() const override { return m->has_window_snapshot(); }
int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); }
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
@@ -344,16 +396,20 @@ struct PCBinding final : IPrefixCache {
}
/* Installed by the engine when the idle tiers are on; empty otherwise. */
std::function<void(const Request&)> restore_fn;
void restore(const Request& r) override {
if (restore_fn) restore_fn(r);
std::function<RestoreResult(const Request&, bool whole_only)> restore_fn;
RestoreResult restore(const Request& r, bool whole_only) override {
return restore_fn ? restore_fn(r, whole_only) : RestoreResult::Whole;
}
/* The entries restore_fn brings back, in chain order: the whole chain if the pool can be made
* to hold it, otherwise cut (PrefixCache::restorable_from). Room is made as evict() makes it,
* dropping entries with a landed host copy, then landing pending copies and dropping those, but
* never erasing one: a restore is worth no lost conversation. The pool's free quarter can go
* to it; the reserve's trim after the next publish frees it again. */
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt) {
* dropping entries with a landed host copy, then landing pending copies and dropping those,
* but never erasing one, so no other conversation is lost to a restore. The pool's free
* quarter can go to it; the reserve's trim after the next publish frees it again. `*res`
* says whether the chain was cut; with `whole_only`, a chain that would be cut comes back
* empty and Declined, and the room made stays for the next attempt. */
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt, bool whole_only = false,
RestoreResult* res = nullptr) {
if (res) *res = RestoreResult::Whole;
media_keys(r, &mm_, salt);
std::vector<BlockHash> want = m->restorable_from(r.prompt, mm_);
const int64_t need = (int64_t)want.size() - m->restore_room();
@@ -361,7 +417,16 @@ struct PCBinding final : IPrefixCache {
const int64_t k = m->trim_for(r.prompt, mm_, need);
if (k < need && flush_fn && flush_fn()) (void)m->trim_for(r.prompt, mm_, need - k);
/* Landing copies may have moved records; take the chain again against the room made. */
return m->restorable_from(r.prompt, mm_, m->restore_room());
if (whole_only) {
want = m->restorable_from(r.prompt, mm_);
if ((int64_t)want.size() <= m->restore_room()) return want;
if (res) *res = RestoreResult::Declined;
return {};
}
bool cut = false;
want = m->restorable_from(r.prompt, mm_, m->restore_room(), &cut);
if (cut && res) *res = RestoreResult::Cut;
return want;
}
void begin_step() override { m->begin_step(); }
void hold(const Request& r) override {
@@ -422,7 +487,6 @@ struct PCBinding final : IPrefixCache {
return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused };
}
int64_t expired() const override { return m->stats().expired; }
int64_t restore_cuts() const override { return m->stats().restore_cuts; }
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
int64_t held_tokens() const override { return m->unshared_tokens(); }
+6 -5
View File
@@ -95,15 +95,16 @@ struct SchedMetrics {
/* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
* state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
* that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a
* snapshot more than one checkpoint interval below the hit: the retention ladder had
* nothing nearer, or the restore brought back only part of the chain. `hit_cut_tokens` is
* the checkpoint shortfall: prompt tokens the attention cache held and the admission
* computed again, because the hit resumed at a snapshot below it or was cut to nothing. */
* snapshot more than one checkpoint interval below the hit: the previous reply was longer
* than an interval (decode writes no snapshot), the retention policy kept nothing nearer, or
* a restore was cut (prefix_restore_cuts). `hit_cut_tokens` is the checkpoint shortfall:
* prompt tokens the attention cache held and the admission computed again, because the hit
* resumed at a snapshot below it or was cut to nothing. */
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
int64_t hit_cut_resumed_below = 0;
int64_t hit_cut_tokens = 0;
/* Restores from the host tier the pool could not hold whole, even after giving up the VRAM
* copies of other conversations (PrefixCache::Stats::restore_cuts). */
* copies of other conversations, counted once per admission (RestoreResult::Cut). */
int64_t prefix_restore_cuts = 0;
/* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks
* shared with a running sequence. Same token axis as the paged groups, so comparable with
+81 -13
View File
@@ -70,6 +70,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
has_linear_state_ = false;
for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true;
/* R-SWA: which groups carry runtime per-sequence windows, and the W they arm a sequence
* with. Empty unless the engine declared one (KVManager::declare_runtime_window), so a model
* with a fixed window (gemma4) takes none of the runtime-window paths. */
rswa_windows_.clear();
for (size_t i = 1; i < kvgeom_.g.size(); ++i) {
const int64_t w = kv->runtime_window_tokens((int32_t)i);
if (w > 0) rswa_windows_.push_back({(int32_t)i, w});
}
if (!rswa_windows_.empty())
RAD_INFO("R-SWA: %zu KV group(s) with a runtime window; a sequence keeps its prompt as the "
"reference and decodes into a ring of %lld token(s) after it, and is excluded from "
"the prefix cache, checkpoints and speculation",
rswa_windows_.size(), (long long)rswa_windows_[0].tokens);
/* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached
* (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is
* true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */
@@ -282,6 +296,10 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
s.ckpt_src = -1;
s.hit_attn = 0;
s.hit_owed = false;
/* Slots are reused: a request that inherited `restore_waited` would never wait for a deferred
* release and its restore would be cut. */
s.restore_waited = false;
s.restore_cut = false;
s.req->state = ReqState::Waiting;
/* The step path appends to `output`, so its capacity is settled here, on the arrival thread.
@@ -407,7 +425,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
* and failed requests are published too; their prompts were computed, and a client that hangs
* up mid-answer is likely to ask for that prefix again. */
if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
s.req->n_computed > 0) {
s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) {
/* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its
* table is a reference plus a ring rather than a prefix from position 0, and the window
* length is runtime data that no cache key carries; a hit would adopt blocks for a window
* this sequence does not have. prefix.cpp already skips a windowed group -- this makes the
* policy explicit, rather than a consequence of the kind declared at build time. */
const std::vector<int32_t>& cg = pc_->cached_groups();
pub_blocks_.assign(cg.size(), {});
bool ok = !cg.empty();
@@ -466,6 +489,11 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
* refusal leaves the entry without one. */
void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) {
int32_t cs = -1;
/* R-SWA: a sequence with a runtime window is never checkpointed. The window is runtime data
* (the prompt's own length), so a slot would describe a window the sequence does not have, and
* the ring is not the [lo, pos) block list a restore seeds. The prefix cache can never reuse
* it either, so the copy would be dead weight. */
if (kv_->has_runtime_window(r.id)) return;
if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return;
e.ckpt_tok = tok;
e.ckpt_slot = cs;
@@ -700,6 +728,12 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const {
}
/* ------------------------------------------------------------------ chunking */
int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target;
const int64_t prompt = (int64_t)r.prompt.size();
return std::min(n_target, r.n_computed < prompt ? prompt : r.n_computed + 1);
}
/* A prefill chunk splits at the linear-state checkpoint interval so a checkpoint is always
* written (spec §7.3; see scheduler.h).
*
@@ -918,6 +952,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
/* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The
* floor is this sequence's own prompt length (image tokens included, they are prompt rows),
* and it is armed here rather than at the prefill's end so no checkpoint is reserved for the
* sequence: a snapshot would describe a window the sequence no longer has (set_window). */
for (const RswaWindow& w : rswa_windows_) {
const int rc = kv_->set_window(r.id, (int64_t)r.prompt.size(), w.tokens);
if (rc < 0) {
RAD_WARN("request %llu: runtime window of %lld tokens over a %zu-token prompt: %s",
(unsigned long long)r.id, (long long)w.tokens, r.prompt.size(),
rad_strerror(rc));
return rc;
}
}
/* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier
* attempt's hit (n_computed > 0) keeps what it found. */
if (r.n_computed == 0) {
@@ -937,8 +985,21 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
if (r.n_computed == 0 && cfg_.prefix_cache) {
/* Restore before the lookup, which stops at the first block the tiers hold. This is
* where a cold session gets its context back for the cost of a copy instead of a
* prefill. */
pc_->restore(r);
* prefill.
*
* A sequence closed while a step issued ahead still read its blocks keeps them until the
* next commit, and the room a restore makes cannot include them yet: a request right
* behind another conversation's last turn would come back cut and prefill the rest. Such
* a restore waits one step, once, instead of being cut. */
const bool whole_only = n_deferred_ > 0 && !s.restore_waited;
const RestoreResult rr = pc_->restore(r, whole_only);
if (rr == RestoreResult::Declined) {
s.restore_waited = true;
RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)",
(unsigned long long)r.id, n_deferred_);
return RAD_E_FULL;
}
s.restore_cut = rr == RestoreResult::Cut;
HitCap cap;
if (draft_refill_ > 0) {
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
@@ -974,8 +1035,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
"below it", (unsigned long long)r.id, (long long)h.n_attn_tokens);
} else if (reuse < h.n_attn_tokens) {
/* Within an interval of the hit is the ordinary case: a turn's tail past its last
* checkpoint. Further down, the snapshots in between are gone, or the attention
* blocks reach past what the tiers could restore of the chain. */
* checkpoint. Further down, the previous reply was longer than an interval (decode
* writes no snapshot), the retention policy kept nothing nearer, or the attention
* blocks reach past the snapshot a cut restore stopped at. */
if (geo_.checkpoints() && h.n_attn_tokens - reuse > geo_.checkpoint_interval)
s.hit_cut = SchedReq::HitCut::ResumedBelow;
RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld",
@@ -1056,9 +1118,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
* queued behind it takes every token left. The hit is known by now, so the cap applies
* to what really has to run. */
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
if (cap < budget && want > 0)
admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at);
}
int rc = RAD_OK;
if (want <= 0) rc = RAD_E_FULL;
@@ -1093,6 +1156,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
m_.attn_cached_tokens += s.hit_attn;
m_.linear_cached_tokens += r.n_cached;
if (s.hit_attn > r.n_cached) m_.hit_cut_tokens += s.hit_attn - r.n_cached;
if (s.restore_cut) ++m_.prefix_restore_cuts;
switch (s.hit_cut) {
case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break;
case SchedReq::HitCut::Window: ++m_.hit_cut_window; break;
@@ -1254,9 +1318,10 @@ const RadBatch* Scheduler::step() {
const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
/*rows_only=*/shares == 0);
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
const int64_t end = chunk_end(r, target);
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
if (cap < budget && want > 0 && capped_at < 0) {
const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr,
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
r.checkpoint_at);
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
}
@@ -1476,7 +1541,8 @@ const RadBatch* Scheduler::step() {
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
int64_t ckpt = -1;
const int64_t grown = e.ckpt_slot < 0 && limit > had
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had;
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at)
: had;
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
e.n_tokens = (int32_t)grown;
e.produces_token = (r.n_computed + grown >= s.seq_len());
@@ -1607,7 +1673,7 @@ bool Scheduler::prefill_continues() const {
std::lock_guard<std::mutex> lk(mu_);
/* Only the step being released has a plan to read. Between a commit and the next step (an
* encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no
* longer holds: a cancel and reap may have released one (#127). */
* longer holds: a cancel and reap may have released one. */
if (stage_rows_ <= 0 || !step_open_) return false;
/* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
* would be dropped by that step. */
@@ -2125,7 +2191,10 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
* so the host bounds it by all of them. A mid-prompt chunk verified nothing. */
const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec;
const int64_t head_max = vstart + e.n_spec;
bool can_draft = may_draft && e.produces_token;
/* A runtime-window (R-SWA) sequence is never drafted for: its rollback refuses (the ring
* rewrites slots KVManager::rollback cannot unwind), so a rejected draft would only warn
* and waste the draft compute. This is the gate kv.cpp's rollback comment states. */
bool can_draft = may_draft && e.produces_token && !kv_->has_runtime_window(r.id);
/* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end,
* so blocks must exist up to the furthest head acceptance could leave. The next verify
@@ -2631,7 +2700,6 @@ SchedMetrics Scheduler::metrics_locked() const {
m.prefix_ckpt_refused = cc.refused;
m.prefix_expired = pc_->expired();
m.prefix_ckpt_expired = pc_->ckpt_expired();
m.prefix_restore_cuts = pc_->restore_cuts();
m.prefix_held_tokens = pc_->held_tokens(); }
m.attn_hit_rate = m.prompt_tokens
? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f;
+31 -10
View File
@@ -111,6 +111,12 @@ struct SchedReq {
* snapshot more than an interval below it. */
enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow };
HitCut hit_cut = HitCut::None;
/* Admission waited a step for a sequence's deferred release before cutting its restore
* (Scheduler::admit_one); it waits once. */
bool restore_waited = false;
/* That attempt's restore came back cut (SchedMetrics::prefix_restore_cuts, counted once the
* admission happens). */
bool restore_cut = false;
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
int64_t seq_len() const {
@@ -322,25 +328,27 @@ public:
* A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
* one pass, so there are no rounds; instead it runs two passes of different shapes.
*
* block_begin right after commit(), while plan() still describes the step just run.
* Reserves the draft KV block the query pass writes, and returns which
* sequences may draft.
* block_begin right after the step is issued, before commit(), while plan() still
* describes it. Reserves the draft KV block the query pass writes, and
* returns which sequences may draft.
* block_context the context pass, draft_pass -1. Its entries mirror the trunk step's
* row for row (BlockSeq).
* block_query the query pass, draft_pass +1. One entry per drafting sequence: the
* anchor at its next position, then `block - 1` masks; `out_ids` names the
* last `depth` rows.
* block_end moves the filled range over what actually ran.
* block_end after commit(): moves the filled range over what actually ran.
*
* The drafter writes its proposal to its declared proposal buffer, not through the sampler,
* and the engine publishes it through set_draft().
*
* On the card (`on_card`), block_begin runs before commit() instead, right after the step is
* issued, so both passes queue behind it with no readback in between. The context pass is
* unchanged: it mirrors the trunk step, whose positions the host knows. The query pass's
* anchor depends on acceptance, so its rows are device rows (advance.h, ADV_BLOCK) staged at
* the furthest position acceptance could leave, and the reservation covers that far.
* block_end still runs after commit().
* Both passes queue behind the step with no readback in between. The context pass mirrors the
* trunk step, whose positions the host knows. The query pass's anchor depends on acceptance,
* so its rows are device rows (advance.h, ADV_BLOCK) staged at the furthest position
* acceptance could leave, and the reservation covers that far.
*
* With `on_card` false, block_begin runs after commit() instead and stages the query pass
* from the committed sequence. The engine does not use it; it is the reference the
* scheduler's tests hold the card's staging to.
*/
struct BlockRow {
uint64_t seq = 0;
@@ -397,6 +405,12 @@ public:
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
bool shared = false, bool rows_only = false) const;
/* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime
* window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a
* recompute replays runs one token a step: the ring rewrites its slots in place, so a
* multi-token chunk past the floor would overwrite keys its own earlier rows still read, while
* one token a step attends as its decode step did. Otherwise `n_target`. */
int64_t chunk_end(const Request& r, int64_t n_target) const;
private:
Program* prog_ = nullptr;
@@ -429,6 +443,13 @@ private:
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
bool hit_holes_trunk_ = false;
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
* not declare one, in which case admission and commit are exactly as before. A sequence with
* one keeps its prompt as a reference and decodes into a ring after it; it is excluded from
* prefix publish, checkpoints and speculation (the window is runtime data). */
struct RswaWindow { int32_t group = -1; int64_t tokens = 0; };
std::vector<RswaWindow> rswa_windows_;
/* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
* drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
* which on a chat's follow-up turn is most of the reply, so the hit ends one window before the