unlimitedocr: the DeepEncoder tower, R-SWA ring KV and the n-gram ban

DeepEncoder (arch/common/rad_block_sam.h): the checkpoint's SAM ViT-B/16,
neck and CLIP ViT-L/14 producing its 16x17+1 row layout, with a new
`sam_attn` op for the windowed, zero-padded SAM attention and its
decomposed relative-position bias (libref oracle, libavx kernel, libr4d
kernel and selftest). The plugin declares the tower when the container
records `radiance.encoder`, and splices its rows over the placeholders
after embed_lookup.

BOS: the chat path adds BOS when the rendered template does not already
start with it. This checkpoint's template is a bare concatenation and its
tokenizer states add_bos_token, so without it every position was off by
one and the det boxes came out wrong. A media run's placeholders shift
with it.

R-SWA: RAD_KV_RING, paged like a window group but with a per-sequence
floor armed at admission. adv_groups now computes the same clamped
seqused and modulo ring slots the builder stages; the mismatch read the
block table's -1 padding and faulted the card. Prefill stays causal;
prefix cache, checkpoints and speculation are off for the group.

Sampling: sample_ngram_ban in libref/libavx/libr4d and the host chain,
the request knobs, and the container's generation config (35 over 128).

Processor: the checkpoint's grid/mode selection, its tall-last tie order,
Pillow's bicubic pass order, and goldens generated from its own code.

Tools: --mm-max-patches auto-detection accepts a tower stated as per-width
tables under vision_config.image_size, and rad-convert records
radiance.encoder.

Verified: tower stages match the checkpoint's code (rows cos 0.9998), the
device sam_attn selftest is within tolerance, the R-SWA device repro
returns text, a GPU e2e reproduces the reference's first det block, and
the host suite is 88/89 (known webp decode baseline).
This commit is contained in:
Juup committed 2026-10-20 07:04:01 +00:00
1 parent 543cba7416
commit fad4ba7f1a
63 files changed
+6162 -169

No files matched your search

+10
View File
@@ -57,6 +57,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
+27 -4
View File
@@ -30,21 +30,44 @@ 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 (the P4a
* regression);
* - 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;
}
}
+47 -3
View File
@@ -112,6 +112,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) {
@@ -690,13 +693,24 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
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);
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 +751,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 +764,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 +800,23 @@ 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. */
a.ring = 0;
a.ring_blocks = 0;
a.rpos_off = (const char*)s.d_rpos - d0;
a.tlen_off = (const char*)s.d_tlen - d0;
for (int64_t i = 0; i < n_seq; ++i) {
const StepEntry& e = plan.e[(size_t)i];
SeqWindow w;
if (kv.runtime_window(e.seq, (int32_t)gi, &w)) {
a.ring = 1;
a.ring_blocks = (int32_t)w.ring_blocks;
break;
}
}
}
for (size_t r = 0; r < ranks_.size(); ++r) {
+5
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,
+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;
}
+47 -2
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;
@@ -213,7 +235,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);
@@ -229,6 +251,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 */
@@ -244,6 +283,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 {
+39 -1
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. */
@@ -407,7 +421,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 +485,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;
@@ -918,6 +942,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) {
+7
View File
@@ -420,6 +420,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