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

+6 -3
View File
@@ -87,6 +87,7 @@ const char* bld_kv_kind_name(int k) {
case RAD_KV_WINDOW: return "window";
case RAD_KV_LINEAR: return "linear";
case RAD_KV_CONV: return "conv";
case RAD_KV_RING: return "ring";
default: return "?";
}
}
@@ -336,7 +337,7 @@ rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) {
rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) {
if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : "");
if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration");
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV)
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING)
return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind);
std::string n = scoped(name);
@@ -923,7 +924,7 @@ int Builder::kv_group_zero(rad_kvgroup h) {
* state is saved and cleared on every rank, so a zero-sized one would mismatch those
* copies. */
const int kind = prog_.kv_groups[h].decl.kind;
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW && kind != RAD_KV_RING) {
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
prog_.kv_groups[h].name.c_str());
return RAD_E_INVAL;
@@ -1964,7 +1965,8 @@ void Builder::finish_kv_groups() {
KVGroupInfo& gi = prog_.kv_groups[g];
const RadKVGroupDecl& d = gi.decl;
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) {
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW || d.kind == RAD_KV_RING) &&
gi.block_size == 0) {
/* The plugin may never have asked; the manifest still needs the answer. */
kv_block_size((rad_kvgroup)g);
}
@@ -1977,6 +1979,7 @@ void Builder::finish_kv_groups() {
switch (d.kind) {
case RAD_KV_FULL:
case RAD_KV_WINDOW:
case RAD_KV_RING:
/* One block holds K and V for block_size tokens, the block manager's unit. */
gi.bytes_per_block =
rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound;
+48 -9
View File
@@ -1037,7 +1037,10 @@ int Engine::declare() {
* area, which would need 16x the activation memory on every card. */
if (cfg_.mm_max_patches < 0) {
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0;
/* A checkpoint's vision_config states a tower as a flat patch_size, or (Unlimited-OCR's
* DeepEncoder) only the per-width tables under a `vision_config.image_size`. */
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 ||
rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0;
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
/* Whole output rows a pass: the plugin's merge, when it states one. */
RadArchProbe pb{};
@@ -1295,6 +1298,21 @@ void Engine::probe_arena_levels() {
}
/* ================================================================== 5. plan */
/* R-SWA: a RAD_KV_RING group names its ring's W in the declaration (`window`). Tell the manager
* before it plans, so the group is planned for per-sequence windows: sized for the whole context
* plus one ring a sequence (the ring in the fixed costs), never capped at the declare-time
* window, never snapshotted. Every plan (each sizing probe and the real manager) goes through
* here, so they all plan the same bytes. */
static int declare_ring_windows(KVManager& kv, const Program& prog) {
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
const RadKVGroupDecl& d = prog.kv_groups[g].decl;
if (d.kind != RAD_KV_RING) continue;
RAD_TRY(kv.declare_runtime_window((int32_t)g, d.window));
}
return RAD_OK;
}
int Engine::plan() {
/* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve
* folds the smallest capacity with the largest program so one split fits every card, and
@@ -1373,6 +1391,19 @@ int Engine::plan() {
ngram_bytes = std::max(ngram_bytes, wf.ngram);
ngram_device = ngram_device || wf.ngram_device;
ngram_host = ngram_host || wf.ngram_host;
/* One --max-model-len sequence's cache: the least a KV pool can hold and still serve
* every acceptable request (configure_kv warns below it). --ngram-placement auto puts
* the table on the card only if the pool stays above it. */
{
Config one = cfg_;
one.max_seqs = 1;
KVManager single;
if (declare_ring_windows(single, r->program) == RAD_OK &&
single.plan_groups(r->program.kv_groups, one) == RAD_OK) {
kv_floor = std::max(kv_floor, single.ceiling(ctx));
f.kv_one = single.ceiling(ctx);
}
}
/* The staging region is sized only where the arena lends its top: without smaller
* levels nothing returns it to the slab at decode, and a deterministic plan moves
* nothing. */
@@ -1381,7 +1412,8 @@ int Engine::plan() {
* memory, and the real pool does not exist yet. */
KVManager probe;
host_arenas += arena_host_bytes(r->program);
if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
if (declare_ring_windows(probe, r->program) == RAD_OK &&
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
ck_slot += probe.checkpoint_bytes();
f.kv_ceiling = probe.ceiling(ctx);
f.kv_fixed = probe.fixed_bytes();
@@ -1512,7 +1544,8 @@ int Engine::plan() {
* its carve). */
for (size_t i = 0; i < ranks_.size(); ++i) {
probes[i] = std::make_unique<KVManager>();
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
break;
}
@@ -2850,6 +2883,7 @@ int Engine::configure_kv() {
for (size_t i = 0; i < ranks_.size(); ++i) {
auto& r = ranks_[i];
LogRank lr(r->index);
RAD_TRY(declare_ring_windows(r->kv, r->program));
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
/* A rank plan() re-sized for the common token count must page at least that count (same
@@ -3074,13 +3108,16 @@ int Engine::configure_kv() {
/* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated
* flags; otherwise such a request is accepted and then refused at admission with a message
* about blocks. Only full paged groups apply: a window group costs the window, and a linear
* group is O(1) in context. */
* group is O(1) in context. A runtime-window (RAD_KV_RING) group is not checked here either:
* it is sized for the whole context plus one ring a sequence and its tokens are a per-sequence
* reference rather than the pool's capacity, so the comparison would be about the wrong
* number. */
{
const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
const KVManager& kv = ranks_[0]->kv;
for (int32_t g = 0; g < kv.n_groups(); ++g) {
const KVGroupPlan* p = kv.plan(g);
if (!p || !p->paged() || p->window_blocks > 0) continue;
if (!p || !p->paged() || p->window_blocks > 0 || p->runtime_win) continue;
const int64_t cap = p->n_blocks * p->block_size;
if (cap >= want) continue;
/* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the
@@ -3368,16 +3405,18 @@ int Engine::start() {
(void)rad_dev_set(ranks_[0]->device);
/* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them
* in the same step). Tokens are the smallest over the full paged groups; a windowed group
* bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max,
* radiance:kv_cache_max_tokens). */
* in the same step). Tokens are the smallest over the full paged groups; a fixed-window group
* bounds history, not capacity. A runtime-window (RAD_KV_RING) group does hold its sequences'
* references, so it counts like a full group. /stats and /metrics report the same numbers
* (kv_tokens_max, radiance:kv_cache_max_tokens). */
{
const KVManager& kv = ranks_[0]->kv;
int64_t bytes = 0, state = 0, tokens = 0;
for (const KVGroupPlan& p : kv.plans()) {
bytes += kv.pool_bytes_carved(p.index);
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue;
if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0)
continue;
const int64_t t = p.n_blocks * p.block_size;
if (tokens == 0 || t < tokens) tokens = t;
}
+74
View File
@@ -20,6 +20,8 @@
#include <chrono>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <string>
namespace rad {
@@ -47,10 +49,53 @@ int Engine::run_encodes() {
Rank& r0 = *ranks_[0];
const Program& prog = r0.program;
/* Diagnostic: RADIANCE_DEBUG_MM_BUFFERS names encoder buffers (comma separated, with an
* optional `:rows` cap) and each pass writes them, as raw bytes, to `<dump dir>/buf.<name>`.
* The pass has finished and been read back, so the copy sees each buffer's last writer; the
* tower's per-stage intermediates are tapped inside the pass instead (rad_block_sam.h). */
struct DumpBuf { std::string name; int64_t rows; };
std::vector<DumpBuf> dump_bufs;
static const char* const dump_list = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
if (dump_dir && *dump_dir && dump_list) {
for (const char* s = dump_list; *s; ) {
const char* e = s;
while (*e && *e != ',') ++e;
std::string want(s, (size_t)(e - s));
s = *e ? e + 1 : e;
int64_t rows = 0;
if (const size_t colon = want.find(':'); colon != std::string::npos) {
rows = std::strtoll(want.c_str() + colon + 1, nullptr, 10);
want.resize(colon);
}
if (!want.empty()) dump_bufs.push_back({ want, rows });
}
}
auto answers_to = [](const std::string& name, const std::string& want) {
if (name.size() < want.size() ||
name.compare(name.size() - want.size(), want.size(), want) != 0) return false;
return name.size() == want.size() || name[name.size() - want.size() - 1] == '.';
};
for (auto& ip : items) {
if (ip->encoded) continue;
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0);
/* Diagnostic: RADIANCE_DEBUG_MM_ROWS=<raw bf16 file> substitutes a reference encoder's
* rows for the tower's, to tell a tower difference from a language-model one. */
if (const char* rp = std::getenv("RADIANCE_DEBUG_MM_ROWS")) {
if (FILE* rf = std::fopen(rp, "rb")) {
const size_t want = ip->embd.size() * sizeof(uint16_t);
const size_t got = std::fread(ip->embd.data(), 1, want, rf);
std::fclose(rf);
if (got == want) {
ip->encoded = true;
RAD_INFO("encoder: %zu row(s) taken from %s instead of the tower",
(size_t)ip->n_rows(), rp);
continue;
}
RAD_ERR("encoder: %s holds %zu bytes, wanted %zu", rp, got, want);
}
}
if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size());
}
@@ -132,6 +177,35 @@ int Engine::run_encodes() {
}
/* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
if (dump_dir && *dump_dir && !dump_bufs.empty()) {
for (const DumpBuf& d : dump_bufs) {
for (size_t bi = 1; bi < prog.buffers.size(); ++bi) {
const BufferInfo& info = prog.buffers[bi];
if (!answers_to(info.name, d.name) || info.bytes <= 0) continue;
const int64_t nrow = info.decl.rank >= 1 ? info.decl.shape[0] : 1;
const int64_t rowb = nrow > 0 ? info.bytes / nrow : info.bytes;
const int64_t rows = d.rows > 0 ? std::min<int64_t>(d.rows, nrow) : nrow;
void* ptr = r0.ctx.buf_ptr((rad_buf)bi);
std::vector<char> raw((size_t)(rows * rowb));
if (!ptr || rad_memcpy_async(raw.data(), ptr, raw.size(),
r0.ctx.stream()) < 0)
continue;
rad_stream_sync(r0.ctx.stream());
char path[512];
std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_buf.%s.raw",
dump_dir, (unsigned long long)parts.front().item->key_hi,
(unsigned long long)parts.front().item->key_lo,
info.name.c_str());
if (FILE* f = std::fopen(path, "wb")) {
std::fwrite(raw.data(), 1, raw.size(), f);
std::fclose(f);
RAD_INFO("encoder: wrote %s (%lld rows of %lld bytes)", path,
(long long)rows, (long long)rowb);
}
}
}
}
}
}
+41 -3
View File
@@ -22,6 +22,13 @@ void take(const char* what, const char* src, double v, double lo, double hi, boo
src, what, v, lo_open ? "(" : "[", lo, hi);
}
/* An integer field (a token count), same contract. */
void take_i(const char* what, const char* src, int64_t v, int64_t lo, int64_t hi, int* dst) {
if (v >= lo && v <= hi) { *dst = (int)v; return; }
RAD_WARN("%s states %s %lld, which is outside [%lld, %lld]; ignoring it",
src, what, (long long)v, (long long)lo, (long long)hi);
}
} /* namespace */
SamplingParams GenSampling::onto(SamplingParams base) const {
@@ -29,16 +36,29 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
if (top_p >= 0.0f) base.top_p = top_p;
if (min_p >= 0.0f) base.min_p = min_p;
if (top_k >= 0) base.top_k = top_k;
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
if (ngram_window >= 0) base.ngram_window = ngram_window;
return base;
}
std::string GenSampling::describe(const SamplingParams& sp) {
char buf[200];
char buf[320];
std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f",
(double)sp.temp, sp.top_k,
sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "",
(double)sp.top_p, (double)sp.min_p);
return buf;
std::string s(buf);
if (sp.ngram_ban_n > 0) {
char ban[96];
if (sp.ngram_window > 0)
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the last %d tokens",
sp.ngram_ban_n, sp.ngram_window);
else
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence",
sp.ngram_ban_n);
s += ban;
}
return s;
}
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
@@ -88,6 +108,22 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v);
else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v);
}
/* The windowed no-repeat-n-gram ban. Its checkpoint name in transformers is
* no_repeat_ngram_size / no_repeat_ngram_window_size (Unlimited-OCR ships 35 over the last
* 128); this sampler's own names are taken too. The reference's negative window means the
* whole sequence, which this sampler spells 0. */
it = j.find("no_repeat_ngram_size");
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_ban_n");
if (it != j.end() && it->is_number_integer())
take_i("no_repeat_ngram_size", src, it->get<int64_t>(), 0, 256, &out->ngram_ban_n);
it = j.find("no_repeat_ngram_window_size");
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_window");
if (it != j.end() && it->is_number_integer()) {
const int64_t v = it->get<int64_t>();
take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window);
}
return out->any();
}
@@ -105,7 +141,8 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
/* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original
* file share one set of range checks and one reading of `do_sample`. */
nlohmann::json j = nlohmann::json::object();
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" };
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
"no_repeat_ngram_size", "no_repeat_ngram_window_size" };
for (const char* k : kFields) {
const char* v = get(k);
if (!v || !*v) continue;
@@ -122,6 +159,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
continue;
}
if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d;
else if (std::strncmp(k, "no_repeat_ngram", 15) == 0) j[k] = (int64_t)d;
else j[k] = d;
}
if (j.empty()) return false;
+11 -3
View File
@@ -20,17 +20,25 @@
namespace rad {
/* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy
* temperature, top_k off, min_p off). */
* temperature, top_k off, min_p off, n-gram ban off). */
struct GenSampling {
float temp = -1.0f, top_p = -1.0f, min_p = -1.0f;
int top_k = -1;
/* The windowed no-repeat-n-gram ban (transformers' no_repeat_ngram_size /
* no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is
* normalized to 0, this sampler's "the whole sequence", when the config states it negative. */
int ngram_ban_n = -1, ngram_window = -1;
bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; }
bool any() const {
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
ngram_ban_n >= 0 || ngram_window >= 0;
}
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
SamplingParams onto(SamplingParams base) const;
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00, ngram ban n 35 over the last 128
* tokens", for the startup log line (the last part only when a ban is on). */
static std::string describe(const SamplingParams& sp);
};
+249 -16
View File
@@ -76,6 +76,7 @@ static const char* kv_kind_name(int k) {
case RAD_KV_WINDOW: return "window";
case RAD_KV_LINEAR: return "linear";
case RAD_KV_CONV: return "conv";
case RAD_KV_RING: return "ring";
default: return "?";
}
}
@@ -126,7 +127,10 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
KVGroupPlan p;
p.index = (int32_t)i;
p.name = g.name.empty() ? fmt("kv%zu", i) : g.name;
p.kind = g.decl.kind;
/* R-SWA: RAD_KV_RING is a window group whose floor is per sequence (declare_runtime_window
* / SeqWindow), so it plans as a RAD_KV_WINDOW group with `runtime_win` set below. No
* other plan-path code has to know the kind. */
p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind;
p.n_layers = (int64_t)g.layers.size();
if (p.n_layers <= 0) {
@@ -161,7 +165,9 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
}
if (p.kind == RAD_KV_WINDOW) {
if (g.decl.window <= 0) {
RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str());
RAD_ERR("KV group '%s': %s with window 0", p.name.c_str(),
g.decl.kind == RAD_KV_RING ? "RAD_KV_RING (the ring's W)"
: "RAD_KV_WINDOW");
return RAD_E_INVAL;
}
/* +1 because a window that is not block-aligned straddles one extra block. */
@@ -232,6 +238,28 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
}
bundling_ = compare_bundling(bundles);
/* R-SWA: a declared runtime window turns the group's plan over to per-sequence windows (see
* declare_runtime_window). Applied after every declaration above, so a fixed-window group's
* plan is exactly what it was. */
for (auto& p : plans_) apply_runtime_window(p);
/* A RAD_KV_RING group carries a runtime window by its kind, whether or not the caller had a
* manager to declare it on first (the engine's sizing probes declare it, but plan_groups must
* not depend on that). `window` is the ring's W. */
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
if (groups[i].decl.kind != RAD_KV_RING || p.runtime_win) continue;
p.runtime_win = true;
p.runtime_tokens = groups[i].decl.window;
p.win_snap = false;
}
for (const auto& [g, w] : runtime_decl_) {
if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].runtime_win) {
RAD_ERR("declare_runtime_window(%d): the group is not a RAD_KV_WINDOW or RAD_KV_RING "
"group in this program (a runtime window needs a windowed group)", (int)g);
return RAD_E_INVAL;
}
}
/* ---- fixed costs first: they are not per-token ---- */
checkpoint_bytes_ = 0;
window_ck_bytes_ = 0;
@@ -242,7 +270,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
for (size_t i = 1; i < plans_.size(); ++i) {
KVGroupPlan& p = plans_[i];
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
!groups[i].drafter;
!p.runtime_win && !groups[i].drafter;
if (p.win_snap && !p.zero && p.n_layers > 0)
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
}
@@ -256,26 +284,98 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
/* And one unit per paged group, whose size need not be a multiple of the alignment. */
for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
/* A runtime window's ring is per sequence and on top of the context the split sizes: one
* ring a sequence, carved as a fixed cost. Its reference is the context itself, which the
* split already covers (the group is not capped at window_blocks). */
for (const auto& p : plans_)
if (p.runtime_win && !p.zero)
fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT);
fixed_ = fixed;
ckpts_ = budget_ckpts;
return RAD_OK;
}
/* Windowed groups are capped at window_pool_cap, as in carve(). */
/* Windowed groups are capped at window_pool_cap, as in carve(). A runtime-window group is not:
* its blocks are the reference (one context a sequence, as a FULL group) plus the ring its fixed
* costs already carry. */
int64_t KVManager::ceiling(int64_t ctx) const {
if (ctx <= 0) return 0;
int64_t need = fixed_;
for (const auto& p : plans_) {
if (!p.paged() || p.block_size <= 0) continue;
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0)
blocks = std::min(blocks, window_pool_cap(p));
need += blocks * p.bytes_per_block;
}
return need;
}
/* Moves a WINDOW group's plan to per-sequence runtime windows (declare_runtime_window). Returns
* false for any other group, so plan_groups() can apply it to every plan unconditionally. */
bool KVManager::apply_runtime_window(KVGroupPlan& p) const {
auto it = runtime_decl_.find(p.index);
if (it == runtime_decl_.end() || p.kind != RAD_KV_WINDOW || p.runtime_win) return false;
p.runtime_win = true;
p.runtime_tokens = it->second;
/* The window a sequence may inherit (a fixed-window cap) is no longer the bound, and the
* declare-time window is not the sequence's own, so nothing here is snapshot-able. */
p.win_snap = false;
return true;
}
int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
if (g <= 0 || window_tokens <= 0) {
RAD_ERR("declare_runtime_window: group %d with a window of %lld (a runtime window needs a "
"real group and a positive W)", (int)g, (long long)window_tokens);
return RAD_E_INVAL;
}
const KVGroupPlan* p = plan(g);
if (p && p->kind != RAD_KV_WINDOW) {
RAD_ERR("group '%s' is not RAD_KV_WINDOW or RAD_KV_RING, so it cannot carry a runtime "
"window", p->name.c_str());
return RAD_E_INVAL;
}
if (p && p->runtime_win && p->runtime_tokens != window_tokens) {
/* A RAD_KV_RING group's W is its declaration's `window`, and one already planned for
* another W has its ring in the fixed costs. */
RAD_ERR("declare_runtime_window(%d): group '%s' already carries a runtime window of %lld "
"tokens, and its ring is sized for that", (int)g, p->name.c_str(),
(long long)p->runtime_tokens);
return RAD_E_INVAL;
}
if (configured_) {
RAD_ERR("declare_runtime_window(%d) after the carve: the group's blocks and fixed costs "
"are already sized for a different window", (int)g);
return RAD_E_STATE;
}
runtime_decl_[g] = window_tokens;
/* A plan built before the declaration (the engine's probes, or plan_groups() then declare)
* is updated in place; the next plan_groups() picks the declaration up on its own. */
if (!plans_.empty()) {
if (g >= (int32_t)plans_.size()) return RAD_E_INVAL;
KVGroupPlan& q = plans_[(size_t)g];
/* Whether the plan counted this group's window snapshot section (plan_groups' rule). */
const bool counted = q.win_snap && !q.zero && q.n_layers > 0;
if (!apply_runtime_window(q)) return RAD_OK; /* already applied */
/* The cost this declaration adds, against the plan as published: the ring is one a
* sequence, and the group gives up its window snapshot section. */
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
if (counted) {
const int64_t was = q.window_blocks * q.bytes_per_block;
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
}
}
return RAD_OK;
}
int64_t KVManager::runtime_window_tokens(int32_t g) const {
const KVGroupPlan* p = plan(g);
return p && p->runtime_win ? p->runtime_tokens : 0;
}
/* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve
* would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_)
* over empty block state. On failure forget() empties both, so every entry point refuses
@@ -328,11 +428,11 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_;
/* A windowed group cannot address past its pool cap; cap it and give the bytes back to
* the others. */
* the others. A runtime-window group's cap is the context plus its ring (a fixed cost). */
int32_t capped = -1;
for (int32_t i : open) {
const auto& p = plans_[i];
if (p.kind != RAD_KV_WINDOW) continue;
if (p.kind != RAD_KV_WINDOW || p.runtime_win) continue;
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
}
if (capped < 0) break;
@@ -369,7 +469,8 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
if (tokens == kUnboundedTokens) return 0;
const int64_t b = tokens / p.block_size;
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && b > window_pool_cap(p))
return window_pool_cap(p);
return b;
}
@@ -508,20 +609,31 @@ int KVManager::carve_into(Pool& kv_pool) {
configured_ = true;
report_ = bundling_.report();
/* A runtime-window group reads as "ring": its window is the sequence's own, not the plan's. */
auto kind_of = [](const KVGroupPlan& p) {
return p.runtime_win ? "ring" : kv_kind_name(p.kind);
};
for (const auto& p : plans_) {
if (p.paged())
report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s "
"%7lld blocks = %9s (%lld tokens)\n",
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
p.name.c_str(), kind_of(p), (long long)p.n_layers,
(long long)p.block_size, humanb(p.bytes_per_block).c_str(),
(long long)p.n_blocks, humanb(p.pool_bytes).c_str(),
(long long)(p.n_blocks * p.block_size));
else
report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n",
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
p.name.c_str(), kind_of(p), (long long)p.n_layers,
humanb(p.bytes_per_state).c_str(),
(long long)p.n_states, humanb(p.pool_bytes).c_str());
}
for (const auto& p : plans_) {
if (!p.runtime_win) continue;
report_ += fmt(" %-14s runtime window W=%lld: a sequence keeps its reference and a ring "
"of at most %lld block(s), rewritten in place\n",
p.name.c_str(), (long long)p.runtime_tokens,
(long long)p.ring_blocks_max());
}
/* The pool's address range, so a GPU fault address can be placed in the carve. */
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n",
pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
@@ -804,7 +916,17 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
const KVGroupPlan* p = plan(g);
if (!p || !p->paged() || n_tokens <= 0) return 0;
int64_t n = ceil_div(n_tokens, p->block_size);
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
if (p->kind == RAD_KV_WINDOW) {
if (p->runtime_win) {
/* The reference's blocks up to n, plus one ring. Without a sequence the floor is
* unknown, so the whole context is the bound on the reference. */
const int64_t ring = p->ring_blocks_max();
const int64_t ctx = max_ctx_ > 0 ? max_ctx_ : n_tokens;
n = std::min(n, ceil_div(ctx, p->block_size)) + ring;
} else {
n = std::min(n, window_seq_cap(*p));
}
}
return n;
}
@@ -835,6 +957,7 @@ int KVManager::add_sequence(uint64_t id) {
s.id = id;
s.blocks.resize(plans_.size());
s.first_block_pos.assign(plans_.size(), 0);
s.win.resize(plans_.size());
s.state.assign(plans_.size(), -1);
s.dirty_from.assign(plans_.size(), 0);
seqs_.emplace(id, std::move(s));
@@ -852,6 +975,7 @@ int KVManager::preempt(uint64_t id) {
for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b);
s->blocks[g].clear();
s->first_block_pos[g] = 0;
s->win[g] = SeqWindow{};
s->dirty_from[g] = 0;
/* The recurrent state goes too (see preempt in kv.h, spec §7.1). */
if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; }
@@ -869,6 +993,11 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) {
if (n_tokens < 0) return RAD_E_INVAL;
/* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */
if (n_tokens >= s->n_tokens) return RAD_OK;
/* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full,
* so the slots a rejected verify wrote may already hold newer keys. Speculation stays off for
* these requests (the scheduler never drafts for them); this refuses rather than corrupt. */
for (const SeqWindow& w : s->win)
if (w.set) return RAD_E_UNSUPPORTED;
for (size_t g = 0; g < plans_.size(); ++g) {
const auto& p = plans_[g];
@@ -898,6 +1027,81 @@ int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const {
return s->first_block_pos[(size_t)g];
}
/* ------------------------------------------------------------------ the runtime window */
int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens) {
if (!configured_) return RAD_E_STATE;
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
if (visible_lo < 0 || window_tokens <= 0) return RAD_E_INVAL;
/* The reference is written linearly, so the floor cannot be behind KV the sequence already
* holds: rebasing would have to move blocks the ring has not been shaped for. */
if (visible_lo < s->n_tokens) {
RAD_ERR("sequence %llu: runtime window floor %lld is behind its %lld held tokens",
(unsigned long long)id, (long long)visible_lo, (long long)s->n_tokens);
return RAD_E_STATE;
}
bool any = false;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (p.kind != RAD_KV_WINDOW) continue;
SeqWindow w;
w.set = true;
w.window = window_tokens;
w.visible_lo = visible_lo;
/* Whole blocks: the ring starts at the first boundary at or after the floor, and the
* tokens in [visible_lo, ring_pos) stay in the reference's last block (SeqWindow). The
* ring itself must span all of W: the frozen tokens are the oldest of the tail, so a
* smaller ring would lose the last W - span positions. */
w.ring_pos = ceil_div(visible_lo, p.block_size) * p.block_size;
w.ring_blocks = ceil_div(window_tokens, p.block_size);
if (w.ring_blocks < 1) w.ring_blocks = 1; /* the ring always has somewhere to write */
/* What the sequence can hold: the reference's blocks, then the whole ring. */
const int64_t need = w.ring_pos / p.block_size + w.ring_blocks;
if (p.n_blocks > 0 && need > p.n_blocks) return RAD_E_FULL;
s->win[g] = w;
any = true;
}
if (!any) return RAD_E_UNSUPPORTED;
return RAD_OK;
}
bool KVManager::runtime_window(uint64_t id, int32_t g, SeqWindow* out) const {
const Seq* s = find(id);
if (!s || g < 0 || g >= (int32_t)s->win.size() || !s->win[(size_t)g].set) return false;
if (out) *out = s->win[(size_t)g];
return true;
}
bool KVManager::has_runtime_window(uint64_t id) const {
const Seq* s = find(id);
if (!s) return false;
for (const SeqWindow& w : s->win) if (w.set) return true;
return false;
}
/* The block-table index of the block holding `pos`, or -1 past the table. A runtime window's
* reference maps as a fixed group does (first_block_pos is 0 there: the table starts at position
* 0); its ring maps modulo its blocks, which is what recycles the ring's slots in place. */
int64_t KVManager::table_index(const KVGroupPlan& p, const SeqWindow& w, int64_t first_block_pos,
int64_t pos, int64_t table_len) {
int64_t bi = (pos - first_block_pos) / p.block_size;
if (w.set && pos >= w.ring_pos) {
bi = w.ring_pos / p.block_size +
((pos - w.ring_pos) / p.block_size) % w.ring_blocks;
}
if (bi < 0 || bi >= table_len) return -1;
return bi;
}
/* What ensure() must have in the table for `n_tokens`: the reference grows linearly until the
* floor, then the ring fills up to its whole span and never grows again. */
int64_t KVManager::window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens) {
const int64_t ref = w.ring_pos / p.block_size;
if (n_tokens <= w.ring_pos) return ceil_div(n_tokens, p.block_size);
return ref + std::min(w.ring_blocks, ceil_div(n_tokens - w.ring_pos, p.block_size));
}
int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; }
int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const {
@@ -1022,11 +1226,15 @@ int64_t KVManager::step_blocks(const KVGroupPlan& p) const {
/* Slides from the step's first query, not its last. The query at keep_from reads keys down to
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
* (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode
* step but drops keys the earlier rows of a prefill chunk still need. */
* step but drops keys the earlier rows of a prefill chunk still need.
*
* A sequence with a runtime window is left alone. Its visible set is anchored at 0, so nothing in
* the table is below a sliding floor to recycle; the ring's blocks are rewritten in place and
* the table never moves (SeqWindow). */
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
for (size_t g = 0; g < plans_.size(); ++g) {
const auto& p = plans_[g];
if (p.kind != RAD_KV_WINDOW) continue;
if (p.kind != RAD_KV_WINDOW || s->win[g].set) continue;
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t target = std::max<int64_t>(first,
keep_from / p.block_size - (p.window_blocks - 1));
@@ -1065,7 +1273,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
const auto& p = plans_[g];
if (p.paged()) {
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t want = ceil_div(n_tokens, p.block_size) - first;
int64_t want = s->win[g].set
? window_table_len(p, s->win[g], n_tokens) - first
: ceil_div(n_tokens, p.block_size) - first;
need[g] = want - (int64_t)s->blocks[g].size();
if (need[g] < 0) need[g] = 0;
/* Copy-on-write: the partial block is the only one a write reaches; if it is shared,
@@ -1101,7 +1311,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
}
}
}
int64_t want = ceil_div(n_tokens, p.block_size) - first;
int64_t want = s->win[g].set
? window_table_len(p, s->win[g], n_tokens) - first
: ceil_div(n_tokens, p.block_size) - first;
if ((int64_t)s->blocks[g].size() < want)
s->dirty_from[g] = std::min<int64_t>(s->dirty_from[g],
(int64_t)s->blocks[g].size());
@@ -1125,6 +1337,10 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector<int32_t>& blocks,
if (!s) return RAD_E_NOTFOUND;
const KVGroupPlan* p = plan(g);
if (!p || !p->paged()) return RAD_E_INVAL;
/* A runtime window's table is its own reference plus ring, laid out against a floor no cache
* entry knows (set_window), so blocks adopted from a prefix hit would sit at the wrong
* positions. Prefix publish is skipped for such a sequence; this is the backstop. */
if (s->win[(size_t)g].set) return RAD_E_STATE;
/* Whole blocks only (see adopt in kv.h). */
if (n_tokens % p->block_size != 0) return RAD_E_INVAL;
if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL;
@@ -1145,6 +1361,14 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
Seq* pa = find(parent);
if (!pa) return RAD_E_NOTFOUND;
if (seqs_.count(child)) return RAD_E_DUPLICATE;
/* The window is runtime data: a child that shared the table without it would read the ring
* as if it were a reference. A forking model (speculative decoding) does not carry one. */
for (const SeqWindow& w : pa->win)
if (w.set) {
RAD_ERR("sequence %llu: fork refused, it carries a runtime window",
(unsigned long long)parent);
return RAD_E_UNSUPPORTED;
}
/* Pass 1: the child needs its own state slot in every stateful group before anything is
* shared (see fork in kv.h, spec §7.3). */
@@ -1159,6 +1383,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
if (plans_[g].paged()) {
ch->blocks[g] = pa->blocks[g];
ch->first_block_pos[g] = pa->first_block_pos[g];
ch->win[g] = pa->win[g];
for (int32_t b : ch->blocks[g]) add_ref(g, b);
} else {
grab_state((int32_t)g, &ch->state[g]);
@@ -1188,7 +1413,10 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
if (p.paged()) {
int64_t first = s->first_block_pos[g] / p.block_size;
int64_t want = ceil_div(n_tokens, p.block_size) - first;
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
if (p.kind == RAD_KV_WINDOW) {
if (s->win[g].set) want = window_table_len(p, s->win[g], n_tokens) - first;
else want = std::min(want, window_seq_cap(p));
}
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
if (extra > available_blocks((int32_t)g)) return false;
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
@@ -1368,6 +1596,9 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
out->clear();
const Seq* s = find(id);
if (!s || pos <= 0) return false;
/* A runtime window is excluded from window snapshots (set_window): the window length is
* runtime data and the table is a reference plus a ring, not [lo, pos). */
for (const SeqWindow& w : s->win) if (w.set) return false;
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
if (!p.win_snap) continue;
@@ -1389,6 +1620,8 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
int KVManager::seed_window(uint64_t id, int64_t pos) {
Seq* s = find(id);
if (!s) return RAD_E_NOTFOUND;
/* A sequence with a runtime window is never resumed from a window snapshot (set_window). */
for (const SeqWindow& w : s->win) if (w.set) return RAD_E_STATE;
/* Check every group before taking anything, as ensure() does. */
for (size_t g = 0; g < plans_.size(); ++g) {
const KVGroupPlan& p = plans_[g];
+114 -3
View File
@@ -11,6 +11,10 @@
* RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state
* RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries
*
* A RAD_KV_RING group is a RAD_KV_WINDOW whose floor is per sequence and set at runtime (R-SWA,
* see SeqWindow); it is planned as a WINDOW group with `runtime_win` set, so no kind of its own
* reaches the plan.
*
* The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what
* a sequence owns. With two, a freed sequence's state slot could still be handed to the next
* request by the other.
@@ -50,6 +54,45 @@ struct BundleComparison {
};
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
/* ------------------------------------------------------------------ the runtime window */
/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the
* "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image
* tokens, then a ring of W decode slots right after it, rewritten in place forever).
*
* A fixed sliding window (`KVGroupPlan::window_blocks`, gemma4's) keeps the last W tokens: the
* table starts where the window begins and blocks leave from its front. A runtime window instead
* retains the whole prefill as the reference and appends into a ring after it:
*
* visible = [0, visible_lo) U [visible_lo, visible_lo + W)
*
* `visible_lo` is the sequence's own prefill length (image tokens included), so the visible set is
* per sequence. The reference is never recycled and first_block_pos stays 0 (the table still
* starts at position 0); only the ring's slot mapping recycles, so RoPE positions keep increasing
* with the token's own position and a decode query sees the whole reference plus the ring.
*
* Blocks are whole, so the ring can start only on a block boundary: it starts at
* `ring_pos = ceil(visible_lo / block) * block` with `ceil(W / block)` blocks, and the tokens in
* [visible_lo, ring_pos) stay in the reference's last block (they are the oldest of the tail and
* are never rewritten). The visible tail is therefore W .. W + block - 1 tokens when W is a block
* multiple -- with block_size 128 = W the 128-256 token granularity of the plan, exact even when
* the floor is not aligned -- and up to one block more otherwise, always a superset of the
* reference implementation's last W. The ring's blocks hold the newest positions in place (no
* block is allocated past them, so the sequence's bytes are flat once the floor is set):
*
* block index = ring_pos / block + ((pos - ring_pos) / block) % ring_blocks
*
* A sequence with a runtime window is excluded from prefix-cache reuse, window snapshots, forking
* and speculative rollback: all three assume the declare-time window, and the runtime length is
* not in any cache key (see KVManager::set_window). */
struct SeqWindow {
bool set = false;
int64_t window = 0; /* W as set */
int64_t visible_lo = 0; /* the retained reference ends here */
int64_t ring_pos = 0; /* block-aligned first ring token position */
int64_t ring_blocks = 0; /* whole blocks the ring holds */
int64_t ring_span(int64_t block) const { return ring_blocks * block; }
};
/* ------------------------------------------------------------------ per-group plan */
struct KVGroupPlan {
int32_t index = -1; /* position in Program::kv_groups */
@@ -62,6 +105,18 @@ struct KVGroupPlan {
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
/* WINDOW: sequences may be given a runtime window (declare_runtime_window). Such a group is
* sized for the whole context plus one ring per sequence instead of being capped at
* window_blocks, its window is not snapshotted, and a sequence armed with one is bounded by
* its own reference + ring rather than by window_blocks. */
bool runtime_win = false;
int64_t runtime_tokens = 0; /* the W set_window arms a sequence with */
/* The most ring blocks one sequence needs: ceil(W / block), the reference's fraction d of
* the ring's first block being frozen in it (see SeqWindow). */
int64_t ring_blocks_max() const {
return runtime_tokens > 0 && block_size > 0
? (runtime_tokens + block_size - 1) / block_size : 0;
}
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
@@ -202,9 +257,46 @@ public:
/* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the
* window and only the next ensure() recycles them, so a prefill waiting for its next chunk
* would hold a whole chunk of blocks; several such prefills can exhaust the pool. The
* scheduler calls this when it advances n_computed, passing the new n_computed. */
* scheduler calls this when it advances n_computed, passing the new n_computed.
*
* A sequence with a runtime window retains its reference and rewrites its ring in place, so
* nothing below the floor may be recycled and this is a no-op for it. */
void trim_window(uint64_t seq, int64_t keep_from);
/* ---------------- the runtime window (R-SWA; see SeqWindow) ---------------- */
/* Mark a WINDOW group as carrying per-sequence runtime windows of `window_tokens`. Call before
* plan_groups()/configure(): it changes the plan (the group is sized for the whole context
* plus one ring a sequence, its window is not snapshotted, and the ring joins the fixed
* costs), so a group declared after the plan is refused. A fixed-window group is untouched.
*
* A group that is not marked still accepts set_window() -- the caller then sizes the pool
* itself, e.g. by declaring the group's window as the whole context -- and each sequence's
* capacity is checked at set_window()/ensure() against the blocks actually carved. */
int declare_runtime_window(int32_t group, int64_t window_tokens);
/* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens
* included) as the retained reference's end and a ring of `window_tokens` after it. Every
* paged WINDOW group of the sequence gets the same floor. Call it before the sequence's KV
* grows past `visible_lo` -- at admission, where the scheduler knows the prompt length -- so
* the reference is written linearly and no checkpoint can be reserved for it (a snapshot
* would describe a window the sequence no longer has).
*
* RAD_E_UNSUPPORTED no windowed group;
* RAD_E_INVAL a negative floor or a window of 0;
* RAD_E_STATE the sequence already holds tokens past the floor;
* RAD_E_FULL the reference plus the ring exceeds what this group carved. */
int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens);
/* The sequence's window in `group`, or false when it has none (a fixed-window group keeps
* KVGroupPlan::window_blocks and first_block_pos). The step batch maps a ring position with
* SeqWindow's rule; every other position maps as (pos - first_block_pos) / block_size. */
bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const;
/* Whether any group has a runtime window set for the sequence. Prefix publish, checkpoint
* reservation and snapshots are skipped for it (see set_window). */
bool has_runtime_window(uint64_t seq) const;
/* The W declare_runtime_window gave the group, 0 if it carries no runtime windows. */
int64_t runtime_window_tokens(int32_t group) const;
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
* block size: a partial block is never shared, because the next token written into it would
* corrupt the cache entry. Bumps each block's refcount. */
@@ -359,7 +451,11 @@ public:
/* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the
* recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) /
* block_size; without the offset a sliding-window sequence writes to the wrong slot once it
* passes its window. */
* passes its window.
*
* A sequence with a runtime window (set_window) keeps 0 for the group's whole life: its table
* is [reference][ring] from position 0 and only the ring's slot index recycles (SeqWindow),
* so the mapping above holds for the reference and SeqWindow's rule for the ring. */
int64_t first_block_pos(uint64_t seq, int32_t group) const;
/* The first table entry changed since the last call; entries below it are unchanged, and
@@ -457,6 +553,9 @@ private:
* for a windowed group. 0 for kUnboundedTokens, which is not a count. */
int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const;
void forget();
/* Turns a WINDOW group into a runtime-window one (declare_runtime_window). Returns false for a
* group that is not windowed. */
bool apply_runtime_window(KVGroupPlan& p) const;
/* One traversal serving both checkpoint directions; see checkpoint_save. */
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
@@ -467,6 +566,7 @@ private:
int64_t n_tokens = 0;
std::vector<std::vector<int32_t>> blocks; /* per group */
std::vector<int64_t> first_block_pos; /* WINDOW: token pos of blocks[0] */
std::vector<SeqWindow> win; /* per group: the runtime window, if any */
std::vector<int32_t> state; /* per group, -1 when not stateful */
/* Per group, the lowest table entry written since the batch builder last staged this
* sequence. An append or truncation lowers it to where it touched; a shift lowers it to
@@ -482,8 +582,16 @@ private:
void drop_state(int32_t g, int32_t s);
Seq* find(uint64_t seq);
const Seq* find(uint64_t seq) const;
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. A runtime window
* (SeqWindow) is not trimmed: its reference must stay and its ring rewrites slots in place. */
void recycle_window(Seq* s, int64_t keep_from);
/* The block-table index the block holding `pos` has, or -1 past the table: the fixed mapping
* (pos - first_block_pos) / block_size, or the ring's for a runtime window. */
static int64_t table_index(const KVGroupPlan& p, const SeqWindow& w, int64_t first_block_pos,
int64_t pos, int64_t table_len);
/* The table length a runtime-windowed sequence needs to hold `n_tokens`: the reference's
* blocks, then the ring's up to its whole span. */
static int64_t window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens);
std::vector<KVGroupPlan> plans_;
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
@@ -511,6 +619,9 @@ private:
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
/* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its
* start: it is a declaration about the program, not about a plan. */
std::unordered_map<int32_t, int64_t> runtime_decl_;
/* ---- the loan (see the public block) ----
*
+12 -5
View File
@@ -31,11 +31,18 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
const int64_t within = first + k - patch_at(s);
const int64_t bw = seg_w(s) / merge;
const int64_t in_col = within % merge;
const int64_t in_row = (within / merge) % merge;
const int64_t blk = within / (merge * merge);
const int64_t row = (blk / bw) * merge + in_row;
const int64_t col = (blk % bw) * merge + in_col;
int64_t row, col;
if (patch_raster) {
/* Raster order is its own inverse: patch i is row i / w, column i % w. */
row = within / seg_w(s);
col = within % seg_w(s);
} else {
const int64_t in_col = within % merge;
const int64_t in_row = (within / merge) % merge;
const int64_t blk = within / (merge * merge);
row = (blk / bw) * merge + in_row;
col = (blk % bw) * merge + in_col;
}
planes[k] = (int32_t)row;
planes[count + k] = (int32_t)col;
planes[2 * count + k] = seg_h(s);
+419 -55
View File
@@ -40,6 +40,49 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
}
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
/* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and
* processor_config.json (`processor.*`). Every key has the reference's default, so a container
* converted before the tower landed still states a processor. */
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "unlimited_ocr")) {
family = Family::UnlimitedOcr;
patch = (int32_t)rad_meta_geti(&m, "processor.patch_size",
rad_meta_geti(&m, "vision_config.patch_size", 16));
downsample = (int32_t)rad_meta_geti(&m, "processor.downsample_ratio", 4);
merge = downsample;
temporal = 1;
base_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.height", 1024);
tile = (int32_t)rad_meta_geti(&m, "preprocessor.tile_size", 640);
/* The base mode's whole view: what the reference states for its input, and what the
* preprocessor's `size` is. Multi-page inference may ask for the tile instead. */
image_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.width", base_size);
crop_mode = meta_bool(m, "preprocessor.crop_to_patches", true);
if (const char* t = rad_meta_gets(&m, "processor.image_token", nullptr); t && *t)
image_token = t;
min_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.min_patches", 2);
max_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.max_patches", 32);
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
if (!read_triple(m, "preprocessor.image_mean", mean)) mean[0] = mean[1] = mean[2] = 0.5f;
if (!read_triple(m, "preprocessor.image_std", stdv)) stdv[0] = stdv[1] = stdv[2] = 0.5f;
/* 3 is PIL's bicubic, the only filter this processor stages. */
const int64_t resample = rad_meta_geti(&m, "preprocessor.resample", 3);
if (resample != 3) {
if (why) *why = "the container resamples pictures with filter " +
std::to_string(resample) + "; this processor stages PIL's bicubic (3)";
return RAD_E_UNSUPPORTED;
}
/* No video; the bands only have to be consistent for check(). */
const int64_t f2 = (int64_t)factor() * factor();
image_min_pixels = video_min_pixels = f2;
image_max_pixels = video_max_pixels = (int64_t)base_size * base_size;
min_frames = 1;
std::string bad;
if (check(&bad) < 0) {
if (why) *why = "the container's Unlimited-OCR processor configuration is "
"inconsistent: " + bad;
return RAD_E_INVAL;
}
return RAD_OK;
}
/* LFM2-VL states its processor twice, in config.json and in processor_config.json's
* image_processor; the latter is what the reference processor reads, so it goes first. */
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) {
@@ -200,6 +243,20 @@ int VisionConfig::check(std::string* why) const {
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
return no("max_pixels_tolerance and max_num_patches must be positive");
}
if (family == Family::UnlimitedOcr) {
if (patch <= 0 || downsample <= 0 || merge != downsample)
return no("the tower's geometry (patch_size " + std::to_string(patch) +
", downsample_ratio " + std::to_string(downsample) +
") does not cut a whole merged patch");
if (base_size <= 0 || base_size % factor() || image_size <= 0 || image_size % factor())
return no("the global view's side (" + std::to_string(base_size) + " and " +
std::to_string(image_size) + " pixels) is not a whole number of merged "
"patches");
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
return no("the tiling (min_patches " + std::to_string(min_tiles) + ", max_patches " +
std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) +
") is not a range of whole merged patches");
}
if (family == Family::Gemma4) {
if (!soft_budget_ok(image_soft_tokens))
return no("the image soft-token budget " + std::to_string(image_soft_tokens) +
@@ -425,69 +482,95 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
} /* namespace */
/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns;
* `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and
* round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the
* function. */
static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w,
const std::vector<int32_t>& bh, const std::vector<int32_t>& kh,
int32_t ksh, int prec, Frame* out) {
out->w = w;
out->h = rows;
out->rgb.assign((size_t)w * (size_t)rows * 3, 0);
for (int32_t yy = 0; yy < rows; ++yy) {
const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3;
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3;
for (int32_t xx = 0; xx < w; ++xx) {
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const int32_t* k = kh.data() + (size_t)xx * (size_t)ksh;
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
for (int32_t x = 0; x < xmax; ++x) {
const uint8_t* p = row + (size_t)(x + xmin) * 3;
s0 += p[0] * k[x];
s1 += p[1] * k[x];
s2 += p[2] * k[x];
}
o[xx * 3 + 0] = clip8(s0, prec);
o[xx * 3 + 1] = clip8(s1, prec);
o[xx * 3 + 2] = clip8(s2, prec);
}
}
}
static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
const std::vector<int32_t>& bv, const std::vector<int32_t>& kv,
int32_t ksv, int prec, Frame* out) {
out->w = src.w;
out->h = h;
out->rgb.assign((size_t)src.w * (size_t)h * 3, 0);
for (int32_t yy = 0; yy < h; ++yy) {
const int32_t ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
const int32_t* k = kv.data() + (size_t)yy * (size_t)ksv;
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)src.w * 3;
for (int32_t xx = 0; xx < src.w; ++xx) {
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
for (int32_t y = 0; y < ymax; ++y) {
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
s0 += p[0] * k[y];
s1 += p[1] * k[y];
s2 += p[2] * k[y];
}
o[xx * 3 + 0] = clip8(s0, prec);
o[xx * 3 + 1] = clip8(s1, prec);
o[xx * 3 + 2] = clip8(s2, prec);
}
}
}
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
if (in.w == w && in.h == h) { *out = in; return; }
std::vector<int32_t> bh, kh, bv, kv;
int ph = kPrec, pv = kPrec;
const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph);
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv);
const bool need_h = w != in.w, need_v = h != in.h;
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
const int y_first = bv[0];
const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1];
const bool need_h = w != in.w;
const bool need_v = h != in.h;
/* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by
* more than twice what the width does, so the horizontal pass runs over fewer rows. The
* intermediate is eight bits, so the order changes the picture: both are the reference's.
* torchvision's on a uint8 tensor (ATen's CPU kernel) is horizontal first at every size. */
const bool horizontal_first =
torch || !((int64_t)in.h - h > 0 && (int64_t)in.h - h > 2 * ((int64_t)in.w - w));
Frame tmp;
const Frame* src = &in;
if (need_h && need_v) {
if (horizontal_first) {
/* Only the source rows the vertical pass reads are resampled horizontally. */
const int32_t y0 = bv[0];
const int32_t rows = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1] - y0;
pass_horizontal(in, y0, rows, w, bh, kh, ksh, ph, &tmp);
pass_vertical(tmp, y0, h, bv, kv, ksv, pv, out);
} else {
pass_vertical(in, 0, h, bv, kv, ksv, pv, &tmp);
pass_horizontal(tmp, 0, h, w, bh, kh, ksh, ph, out);
}
return;
}
if (need_h) {
const int rows = need_v ? y_last - y_first : in.h;
const int y0 = need_v ? y_first : 0;
tmp.w = w;
tmp.h = rows;
tmp.rgb.assign((size_t)w * rows * 3, 0);
for (int yy = 0; yy < rows; ++yy) {
const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3;
uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3;
for (int xx = 0; xx < w; ++xx) {
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const int32_t* k = kh.data() + (size_t)xx * ksh;
int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0;
for (int x = 0; x < xmax; ++x) {
const uint8_t* p = row + (size_t)(x + xmin) * 3;
s0 += p[0] * k[x];
s1 += p[1] * k[x];
s2 += p[2] * k[x];
}
o[xx * 3 + 0] = clip8(s0, ph);
o[xx * 3 + 1] = clip8(s1, ph);
o[xx * 3 + 2] = clip8(s2, ph);
}
}
src = &tmp;
}
if (!need_v) { *out = std::move(tmp); return; }
const int shift = need_h ? y_first : 0;
out->w = src->w;
out->h = h;
out->rgb.assign((size_t)src->w * h * 3, 0);
for (int yy = 0; yy < h; ++yy) {
const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
const int32_t* k = kv.data() + (size_t)yy * ksv;
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
for (int xx = 0; xx < src->w; ++xx) {
int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0;
for (int y = 0; y < ymax; ++y) {
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
s0 += p[0] * k[y];
s1 += p[1] * k[y];
s2 += p[2] * k[y];
}
o[xx * 3 + 0] = clip8(s0, pv);
o[xx * 3 + 1] = clip8(s1, pv);
o[xx * 3 + 2] = clip8(s2, pv);
}
pass_horizontal(in, 0, in.h, w, bh, kh, ksh, ph, out);
return;
}
pass_vertical(in, 0, h, bv, kv, ksv, pv, out);
}
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
@@ -678,6 +761,19 @@ int Processor::init(const VisionConfig& cfg,
encode_text_ = std::move(encode_text);
return RAD_OK;
}
if (cfg.family == Family::UnlimitedOcr) {
/* The vocabulary spells the marker (`processor.image_token`), and every placeholder of a
* picture is that same id: there is nothing else to resolve. */
if (!token_id) return RAD_E_INVAL;
if (cfg_.tok_image < 0) cfg_.tok_image = token_id(cfg_.image_token);
if (cfg_.tok_image < 0) return RAD_E_NOTFOUND;
/* A tile's line and the global view are each one segment, so each must fit one pass. */
const int64_t q = cfg.tile / cfg.patch;
const int64_t g = std::max(cfg.base_size, cfg.image_size) / cfg.patch;
if (q * (q + 4) > cfg.max_patches || g * (g + 4) > cfg.max_patches) return RAD_E_INVAL;
encode_text_ = std::move(encode_text);
return RAD_OK;
}
/* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes
* smart_resize keep every image inside a pass. */
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
@@ -727,6 +823,55 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
}
}
/* Unlimited-OCR's ratios of one tile count tie only when they are each other's transpose: two
* ratios of the same count are equally near an aspect only if one mirrors the other about it. So
* the reference's set order matters for exactly the (c, r) pairs below, the tall ones (c < r)
* its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set
* has for the 2..32-tile range the checkpoint states. It comes from the reference itself
* (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */
bool uocr_tall_last(int32_t c, int32_t r) {
static const int8_t kTallLast[][2] = {
{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14},
{1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4},
{2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16},
{3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8},
};
for (const auto& p : kTallLast)
if (p[0] == c && p[1] == r) return true;
return false;
}
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows) {
*cols = *rows = 1;
if (h <= 0 || w <= 0 || min_tiles < 1 || max_tiles < min_tiles) return;
const double aspect = (double)w / (double)h;
const double area = (double)w * (double)h;
const double half = 0.5 * (double)tile * (double)tile;
double best = INFINITY;
for (int32_t n = min_tiles; n <= max_tiles; ++n) {
int32_t deferred[8]; /* the transposed ratios the reference visits last */
int32_t n_deferred = 0;
auto visit = [&](int32_t c, int32_t r) {
const double diff = std::fabs(aspect - (double)c / (double)r);
if (diff < best) {
best = diff; *cols = c; *rows = r;
} else if (diff == best && area > half * (double)n) {
*cols = c; *rows = r;
}
};
for (int32_t c = 1; c <= n; ++c) {
if (n % c) continue;
if (c < n / c && uocr_tall_last(c, n / c)) {
if (n_deferred < 8) deferred[n_deferred++] = c;
continue;
}
visit(c, n / c);
}
for (int32_t k = 0; k < n_deferred; ++k) visit(deferred[k], n / deferred[k]);
}
}
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
* in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each
* merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so
@@ -804,10 +949,224 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::strin
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
int32_t* image_size, std::string* why) {
auto no = [why](const std::string& w) {
if (why) *why = w;
return RAD_E_INVAL;
};
if (c.family != Family::UnlimitedOcr) return no("this model has one picture mode, not two");
const int32_t F = c.factor();
const bool cr = mode.kind == ImageMode::Base ? false
: mode.kind == ImageMode::Gundam ? true
: c.crop_mode;
const int32_t bs = mode.base_size > 0 ? mode.base_size : c.base_size;
const int32_t is = mode.image_size > 0 ? mode.image_size : c.image_size;
if (cr) {
/* The crops are the tile the checkpoint was trained at; the reference's image_size is
* that same number, so a request may only restate it. */
if (bs % F)
return no("base_size " + std::to_string(bs) + " is not a whole number of merged "
"patches (" + std::to_string(F) + ")");
if (bs < 4 * F)
return no("base_size " + std::to_string(bs) + " is under two output rows");
if (mode.image_size > 0 && mode.image_size != c.tile)
return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; "
"image_size " + std::to_string(mode.image_size) + " is not one");
*crop = true; *base_size = bs; *image_size = c.tile;
return RAD_OK;
}
if (is % F)
return no("image_size " + std::to_string(is) + " is not a whole number of merged patches "
"(" + std::to_string(F) + ")");
if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows");
if (mode.base_size > 0 && mode.base_size != bs)
return no("the base mode pads a page to image_size, not base_size");
*crop = false; *base_size = bs; *image_size = is;
return RAD_OK;
}
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows) {
bool crop = false;
int32_t bs = 0, is = 0;
if (uocr_mode(c, mode, &crop, &bs, &is, nullptr) < 0) return -1;
const int32_t P = c.patch, D = c.downsample;
/* The global view: `g` lines of `g` features, each followed by a newline, then the view
* separator (`[tok] * g + [tok]) * g + [tok]`). */
const int32_t g = (crop ? bs : is) / P / D;
int64_t t = (int64_t)(g + 1) * g + 1;
/* The local views, when the picture is tiled: one line per feature row holding every tile's
* row, a newline after it (`[tok] * q * cols + [tok]) * q * rows`). */
if (crop && (int64_t)cols * rows > 1) {
const int32_t q = c.tile / P / D;
t += (int64_t)(q * cols + 1) * q * rows;
}
return t;
}
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out) {
/* ImageOps.pad: contain() fits the picture inside w x h at its own aspect (PIL's bicubic,
* rounded as its round() does), then it is pasted centred on `fill`. */
int32_t nw = w, nh = h;
if (in.w > 0 && in.h > 0) {
const double im_ratio = (double)in.w / (double)in.h;
const double dst_ratio = (double)w / (double)h;
if (im_ratio != dst_ratio) {
if (im_ratio > dst_ratio) {
nh = (int32_t)pyround((double)in.h / (double)in.w * (double)w);
if (nh == 0) nh = 1;
} else {
nw = (int32_t)pyround((double)in.w / (double)in.h * (double)h);
if (nw == 0) nw = 1;
}
}
}
const Frame* src = &in;
Frame fitted;
if (nw != in.w || nh != in.h) {
resize_bicubic(in, nw, nh, &fitted);
src = &fitted;
}
out->w = w;
out->h = h;
out->rgb.assign((size_t)w * (size_t)h * 3, fill);
const int32_t x = nw != w ? (int32_t)pyround((double)(w - nw) * 0.5) : 0;
const int32_t y = nw != w ? 0 : (int32_t)pyround((double)(h - nh) * 0.5);
for (int32_t yy = 0; yy < src->h; ++yy)
std::memcpy(out->rgb.data() + ((size_t)(y + yy) * (size_t)w + (size_t)x) * 3,
src->rgb.data() + (size_t)yy * (size_t)src->w * 3, (size_t)src->w * 3);
}
/* Unlimited-OCR's picture processor, the reference's infer() and infer_multi() exactly: the
* global view is the picture ImageOps.pad-ed to base_size (in the base mode, to image_size,
* squared first when that side is a tile or less), and in the gundam mode a picture larger than a
* tile is cut the way dynamic_preprocess cuts it. Each view is staged as its feature grid plus
* `downsample` patch columns nothing is read from, because the reference's layout puts a newline
* after every line of features: one output row per downsample x downsample patches, and the last
* column's rows are where those newlines go. The segments are, in the reference's order, the
* local grid's lines (one per tile row; a line wider than a pass is cut into chunks of whole
* tiles, its last chunk carrying the newline column), then the global view's grid, then the view
* separator's single row. */
int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
std::shared_ptr<Item>* out, std::string* why) const {
const VisionConfig& c = cfg_;
const int32_t P = c.patch, M = c.merge;
bool crop = false;
int32_t base_size = 0, image_size = 0;
RAD_TRY(uocr_mode(c, mode, &crop, &base_size, &image_size, why));
if (f.w <= 0 || f.h <= 0) {
if (why) *why = "the picture has no size";
return RAD_E_INVAL;
}
const int32_t q = c.tile / P; /* a tile's patch rows */
int32_t cols = 1, rows = 1;
const bool tiled = crop && (f.w > c.tile || f.h > c.tile);
if (tiled) uocr_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows);
/* The global view. The base mode squares a page of a tile or less before padding it, as the
* reference's multi-page path does. */
Frame global;
if (crop) {
pad_bicubic(f, base_size, base_size, 127, &global);
} else if (image_size <= c.tile) {
Frame sq;
resize_bicubic(f, image_size, image_size, &sq);
pad_bicubic(sq, image_size, image_size, 127, &global);
} else {
pad_bicubic(f, image_size, image_size, 127, &global);
}
const int32_t g = (crop ? base_size : image_size) / P;
if ((int64_t)g * (g + 4) > c.max_patches) {
if (why) *why = "the global view's " + std::to_string((long long)g * (g + 4)) +
" patches are more than one encoder pass holds (" +
std::to_string(c.max_patches) + ")";
return RAD_E_INVAL;
}
/* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */
uint16_t lut[3][256];
for (int ch = 0; ch < 3; ++ch)
for (int v = 0; v < 256; ++v) {
const float p = (float)v / 255.0f;
lut[ch][v] = rad_f32_to_bf16((p - c.mean[ch]) / c.stdv[ch]);
}
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
it->patch_dim = c.patch_dim();
it->rope_1d = true;
it->patch_raster = true;
int64_t seg_row = 0;
/* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w`
* patches a row carry pixels; the rest are the newline column. */
auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw,
int32_t real_w) {
it->segments.push_back({ gh, gw, it->n_patch });
it->seg_at.push_back((int32_t)seg_row);
it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image);
seg_row += (int64_t)(gh / M) * (gw / M);
it->n_patch += (int64_t)gh * gw;
const size_t at = it->pixels.size();
it->pixels.resize(at + (size_t)gh * (size_t)gw * (size_t)it->patch_dim, 0);
uint16_t* dst = it->pixels.data() + at;
for (int32_t py = 0; py < gh; ++py)
for (int32_t px = 0; px < real_w; ++px) {
uint16_t* pp = dst + ((size_t)py * (size_t)gw + (size_t)px) * (size_t)it->patch_dim;
const int32_t py0 = y0 + py * P, px0 = x0 + px * P;
for (int ch = 0; ch < 3; ++ch)
for (int y = 0; y < P; ++y) {
const uint8_t* row = src.rgb.data() +
((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3 + (size_t)ch;
for (int x = 0; x < P; ++x) *pp++ = lut[ch][row[x * 3]];
}
}
};
if (tiled) {
Frame big;
resize_bicubic(f, cols * c.tile, rows * c.tile, &big);
/* A chunk of a line must fit one pass: q rows of q patches a tile, plus the newline
* column its last chunk holds. */
int64_t per_row = c.max_patches / q;
const int64_t chunk = per_row > 4 ? (per_row - 4) / q : 0;
if (chunk < 1) {
if (why) *why = "one encoder pass holds no line of " + std::to_string(q) +
"-patch tiles (" + std::to_string(c.max_patches) + " patches)";
return RAD_E_INVAL;
}
for (int32_t r = 0; r < rows; ++r)
for (int32_t c0 = 0; c0 < cols; c0 += (int32_t)chunk) {
const int32_t n = std::min<int32_t>((int32_t)chunk, cols - c0);
const bool last = c0 + n == cols;
append(big, c0 * c.tile, r * c.tile, q, q * n + (last ? 4 : 0), q * n);
}
}
append(global, 0, 0, g, g + 4, g);
/* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */
append(global, 0, 0, M, M, 0);
it->n_seg = (int32_t)it->segments.size();
it->grid_t = 1;
it->grid_h = it->segments[0].h;
it->grid_w = it->segments[0].w;
it->rows_h = it->grid_h / M;
it->rows_w = it->grid_w / M;
it->seg_rows = it->rows_h * it->rows_w;
content_key(*it, &it->key_hi, &it->key_lo);
*out = std::move(it);
return RAD_OK;
}
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
const ImageMode& mode) const {
const VisionConfig& c = cfg_;
if (mode.kind != ImageMode::Default && c.family != Family::UnlimitedOcr) {
if (why) *why = "this model has one picture mode; images_config names one of two";
return RAD_E_UNSUPPORTED;
}
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
int64_t h = 0, w = 0;
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
&h, &w, why));
@@ -979,7 +1338,12 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
}
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels,
const ImageMode& mode) const {
if (mode.kind != ImageMode::Default && cfg_.family != Family::UnlimitedOcr) {
if (why) *why = "this model has one picture mode; images_config names one of two";
return RAD_E_UNSUPPORTED;
}
if (image_tokens != 0) {
if (cfg_.family != Family::Gemma4) {
if (why) *why = "this model's processor sizes an image by its pixels, not by a token "
@@ -1003,7 +1367,7 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
}
if (cfg_.family == Family::Gemma4)
return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why);
return image_from(f, out, why);
return image_from(f, out, why, mode);
}
namespace {
+66 -5
View File
@@ -55,8 +55,20 @@ enum class Kind { Image, Video, Audio };
* is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
* fixed-point bicubic; images only, and the tokens rotate at their positions. */
enum class Family { QwenVL, Gemma4, Lfm2 };
* fixed-point bicubic; images only, and the tokens rotate at their positions.
* UnlimitedOcr
* Unlimited-OCR's DeepSeek-OCR shape, in the checkpoint's two modes (ImageMode): the
* picture padded (ImageOps.pad) to base_size x base_size on a 127 grey as the global
* view, and, in the gundam mode, a picture larger than one tile cut into min_tiles..
* max_tiles tile x tile crops at the tile in the ratio nearest its own (its
* dynamic_preprocess). The SAM neck downsamples by `downsample`, so patch * downsample
* is one output row. A view's rows are laid out as the reference's feature grid plus a
* column of newlines, which is why every segment carries `downsample` extra patch
* columns that nothing is read from: patches are raster order (Item::patch_raster), one
* patch (channel, y, x), each value (u / 255 - mean) / std in f32, rounded to bf16.
* Every placeholder is one id (the picture marker itself); the tokens rotate at their
* positions. */
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr };
struct VisionConfig {
Family family = Family::QwenVL;
@@ -81,6 +93,17 @@ struct VisionConfig {
double max_pixels_tolerance = 0.0;
int64_t max_segment_patches = 0;
/* UnlimitedOcr: the two modes' sizes, from the checkpoint's preprocessor config. The gundam
* mode pads the global view to `base_size` and cuts crops at `tile`; the base mode (a page of
* a multi-page document) pads the whole picture to `image_size`. `downsample` is the SAM
* neck's ratio: one output row is `patch * downsample` pixels a side. `crop_mode` is the
* deployment's mode when a request names none. */
int32_t base_size = 0, image_size = 0, downsample = 0;
bool crop_mode = false;
/* The vocabulary's spelling of the picture marker (`processor.image_token`); every
* placeholder of a picture is that one id. */
std::string image_token = "<image>";
/* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
* is one segment and a segment is never split, so the image band's ceiling is lowered to fit
* it. `max_source_pixels` bounds what the decoder may hold before any resize. */
@@ -102,6 +125,18 @@ struct VisionConfig {
int from_meta(const RadModelMeta& m, std::string* why);
};
/* Which picture processor a request gets, for a checkpoint that has more than one: Unlimited-OCR
* states two modes and the reference names them gundam (one picture: the global view at base_size
* plus crops) and base (a page of a multi-page document: the global view only, at image_size).
* `Default` is the deployment's (`VisionConfig::crop_mode`); a request may pick either mode and,
* with it, the sizes the checkpoint states differently. `base_size` and `image_size` of 0 keep the
* mode's own. */
struct ImageMode {
enum Kind : int32_t { Default = 0, Gundam = 1, Base = 2 };
int32_t kind = Default;
int32_t base_size = 0, image_size = 0;
};
/* The audio feature extractor family, from the container's audio_config.model_type. The
* families differ in the spectrogram and in how a clip's frames are laid out for the encoder;
* the Item they produce is shared.
@@ -199,6 +234,9 @@ struct Item {
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
bool rope_1d = false;
/* Patches are in raster order (row by row), not merge-block order: the coordinate planes
* invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */
bool patch_raster = false;
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
@@ -309,13 +347,15 @@ public:
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
* scales a larger picture down to that area with PIL's bicubic. */
* scales a larger picture down to that area with PIL's bicubic. `mode` picks one of the
* checkpoint's picture modes where it has more than one (Unlimited-OCR). */
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
std::string* why, int64_t max_pixels = 0) const;
std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const;
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
/* From an already-decoded picture or frame list; for tests. */
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
const ImageMode& mode = ImageMode{}) const;
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
@@ -332,6 +372,8 @@ private:
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
std::string* why) const;
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr<Item>* out,
std::string* why) const;
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
int32_t tok_thumbnail_ = -1;
std::vector<int32_t> tok_tiles_;
@@ -388,6 +430,25 @@ void cap_area(const Frame& in, int64_t max_pixels, Frame* out);
* aspect, the larger grid of two equally near when the picture fills over half of it. */
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows);
/* Whether the reference's ratio set visits the tall side (c, r), c < r, of a transposed pair after
* the wide one: the only tie two ratios of one tile count can have. From the reference itself. */
bool uocr_tall_last(int32_t c, int32_t r);
/* Unlimited-OCR's tile grid (its dynamic_preprocess): the min..max-tile grid nearest the picture's
* aspect, the one whose area the picture covers over half of when two are equally near, exactly
* as the reference's set ordering resolves it. The reference calls it only for a picture larger
* than one tile; this answers for any size. */
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
int32_t* cols, int32_t* rows);
/* The placeholders a picture takes: the global view's rows plus its separator, and, when tiled,
* one line of `cols` tiles per feature row with a newline after it. `cols` * `rows` is the tile
* grid. */
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows);
/* The mode `mode` resolves to for this deployment; RAD_E_INVAL names an unsupported size. */
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
int32_t* image_size, std::string* why);
/* PIL's ImageOps.pad: `in` fitted inside w x h keeping its aspect (its bicubic), centred on `fill`
* in the channels' order (127 127 127 for the reference's 0.5 mean). */
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out);
} /* namespace mm */
} /* namespace rad */
+8
View File
@@ -588,6 +588,14 @@ struct SamplingParams {
* scheduler thread where every other request's step waits; held here, starting is a lookup.
* Null for a request not admitted through the server; the sampler then compiles. */
std::shared_ptr<const GbnfProgram> grammar_program;
/* The windowed no-repeat-ngram ban (core/sample/sampler.h, `sample_ngram_ban`): a token that
* would complete an `ngram_ban_n`-gram already present in the last `ngram_window` tokens of
* the sequence is banned. `ngram_ban_n` 0 is off, the default; `ngram_window` <= 0 searches
* the whole staged history (the un-windowed processor). Unlimited-OCR's generation_config
* asks for 35 and 128 (the model card's document mode uses 1024). */
int ngram_ban_n = 0;
int ngram_window = 0;
};
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
+1
View File
@@ -32,6 +32,7 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
switch (gp->kind) {
case RAD_KV_FULL:
case RAD_KV_WINDOW:
case RAD_KV_RING:
b.rank = 4;
b.shape[0] = gp->n_blocks;
b.shape[1] = d.n_head_kv;
+31 -1
View File
@@ -12,6 +12,7 @@
#include <cfloat>
#include <cmath>
#include <numeric>
#include <unordered_set>
namespace rad {
@@ -526,8 +527,33 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
return (int32_t)best;
}
/* ================================================================== the chain */
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
int32_t window) {
if (n <= 0 || !history || n_history < (int64_t)n) return;
const int64_t len = n_history;
const int64_t win = (window > 0 && window < len) ? window : len;
const int64_t start = len - win, end = len - n + 1;
if (end <= start) return;
const int64_t plen = (int64_t)n - 1, p0 = len - plen;
/* The set of tokens a continuation would complete an n-gram with, as the reference builds it:
* every n-gram in the window whose first n-1 tokens equal the current prefix contributes the
* token after them. */
std::unordered_set<int32_t> banned;
for (int64_t idx = start; idx < end; ++idx) {
bool match = true;
for (int64_t j = 0; j < plen; ++j) {
if (history[idx + j] != history[p0 + j]) { match = false; break; }
}
if (match) banned.insert(history[idx + plen]);
}
if (banned.empty()) return;
s.sorted = false; /* a -infinity candidate belongs after every finite one */
for (Candidate& c : s.c)
if (banned.count(c.id) != 0) c.logit = -INFINITY;
}
/* ================================================================== the chain */
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
ChainOrder order) {
/* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */
@@ -547,6 +573,10 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
in.dry_breakers ? *in.dry_breakers : kNone);
}
/* The n-gram ban, after the penalties and before the greedy split: the device chain issues it
* there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */
host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window);
/* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
* logit to -inf, so a mask applied after it could leave nothing. */
if (sp.greedy()) {
+10 -1
View File
@@ -177,6 +177,14 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
uint64_t seed, uint64_t pos);
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`, Unlimited-OCR's
* SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the
* last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0
* is the whole history. It runs after the penalties and DRY and before every cut, so the greedy
* path sees it too. */
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
int32_t window);
/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
* instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
* ceil(n_vocab/32). */
@@ -203,7 +211,8 @@ constexpr int64_t kSampleCandidates = 1024;
constexpr int64_t kSampleMergeCandidates = 4096;
enum class ChainOrder {
Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
/* penalties, DRY, n-gram ban, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
Radiance = 0,
LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */
};
+64 -13
View File
@@ -178,6 +178,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
/* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
* penalised). Resolved on the host, which has the vocabulary. */
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
/* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row
* is the fixed RadSampleParams wire format every sampler op shares. */
buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST);
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
@@ -197,7 +200,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ || !buf_mask_ ||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
RAD_ERR("sampler: a staging buffer failed to declare");
@@ -239,6 +242,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
op_penalties_ = op_vocab_off("sample_penalties");
op_dry_ = op_vocab_off("sample_dry");
op_ngram_ban_ = op_vocab_off("sample_ngram_ban");
op_temp_ = op_vocab("sample_temp");
op_mask_ = op_vocab("sample_mask");
op_topk_ = op_vocab_off("sample_topk");
@@ -320,6 +324,7 @@ int Sampler::stage_alloc() {
greedy_ready_ = false;
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED);
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
/* Logprobs readback; only rank 0 reads it. */
@@ -337,10 +342,10 @@ int Sampler::stage_alloc() {
}
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
!mask_stage_) {
!ngram_stage_ || !mask_stage_) {
RAD_ERR("sampler: could not pin %s of staging",
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
mask_words_ * 4)).c_str());
mask_words_ * 4 + 8)).c_str());
stage_free();
return RAD_E_NOMEM;
}
@@ -353,6 +358,7 @@ void Sampler::stage_free() {
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED);
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
@@ -366,6 +372,7 @@ void Sampler::stage_free() {
cur_stage_ = nullptr;
hist_stage_ = nullptr;
brk_stage_ = nullptr;
ngram_stage_ = nullptr;
mask_stage_ = nullptr;
}
@@ -373,9 +380,9 @@ Sampler::~Sampler() { stage_free(); }
/* ================================================================== admission */
/* Whether the two history stages run, shared by admission, request setup and step staging so
* they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
* also requires a positive multiplier; a negative one would reward repetition. */
/* Whether the history stages run, shared by admission, request setup and step staging so they
* agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY also
* requires a positive multiplier; a negative one would reward repetition. */
static bool penalties_on(const SamplingParams& sp) {
return sp.penalty_last_n != 0 &&
(sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
@@ -385,6 +392,14 @@ static bool dry_on(const SamplingParams& sp) {
return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0;
}
/* The windowed no-repeat-ngram ban: n-gram length 0 is off (the request default). A window <= 0
* is legal and means the whole staged history, the un-windowed processor; it is not a separate
* switch, because the reference's windowed form is what the model ships and a ban with no window
* is still a ban. */
static bool ngram_ban_on(const SamplingParams& sp) {
return sp.ngram_ban_n > 0;
}
int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
auto refuse = [&](const char* what, int st) {
if (why) *why = what;
@@ -418,6 +433,12 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
/* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
if (dry_on(sp) && sp.dry_allowed_length < 1)
return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
/* The n-gram ban: an n-gram shorter than 2 is a single-token ban, which the reference defines
* (an empty prefix) and this chain implements, so 1 is accepted. A negative n or window has no
* meaning; window 0 is the whole staged history. */
if (sp.ngram_ban_n < 0) return refuse("ngram_ban_n is negative", RAD_E_INVAL);
if (sp.ngram_window < 0)
return refuse("ngram_window is negative (0 searches the whole history)", RAD_E_INVAL);
if (sp.n_probs > RAD_MAX_LOGPROBS) {
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
" logprobs alternatives may be asked for";
@@ -457,6 +478,7 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
"sample_temp (over the candidates, for temperature last)");
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
if (!missing) missing = need(ngram_ban_on(sp), op_ngram_ban_, "sample_ngram_ban");
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
"sample_mask");
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
@@ -581,6 +603,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
n_seq_ = 0;
any_brk_ = false;
any_late_ = false;
any_ngram_ = false;
cur_stage_ = params_stage_;
lp_rows_.clear();
@@ -635,6 +658,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
const int64_t n_total = n_prompt + n_out;
const bool pen = penalties_on(sp);
const bool dry = dry_on(sp);
const bool ngram = ngram_ban_on(sp);
auto it = seqs_.find(r->id);
SeqState* st = it == seqs_.end() ? nullptr : &it->second;
@@ -695,6 +719,11 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
p.dry_penalty_last_n = sp.dry_penalty_last_n;
p.mask_row = -1;
/* The n-gram ban's pair, staged for every row so a row that turns it off cannot inherit
* its predecessor's values. */
ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n;
ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window;
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
* global ids, and the pick over one candidate is deterministic. A greedy row asking
@@ -723,12 +752,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
any_late_ = true;
}
/* History for the penalties and DRY, staged only for rows that run one of them:
* prompt, output so far and, at draft position k, the k drafts before it (they are
* emitted only if accepted, as one token at a time). Oldest first, truncated to
/* History for the penalties, DRY and the n-gram ban, staged only for rows that run one
* of them: prompt, output so far and, at draft position k, the k drafts before it (they
* are emitted only if accepted, as one token at a time). Oldest first, truncated to
* max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
* plane, so hist_off stays 0. */
if (pen || dry) {
* plane, so hist_off stays 0. The n-gram ban's own window is `ngram_window`, applied to
* this span, so the reference's update order holds at a verify: position k sees the
* drafts before it, as the processor would after emitting them. */
if (pen || dry || ngram) {
const int64_t len = n_total + k;
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
int32_t* h = hist_stage_ + row * cfg_.max_hist;
@@ -741,6 +772,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
p.hist_len = (int32_t)take;
if (pen) p.flags |= RAD_SP_PENALTY;
if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY;
/* A row whose history is shorter than its n-gram has nothing to ban (the reference
* skips it too), so the op is issued only when some row has a full n-gram. */
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
}
if (gr && !dead && gr->constrains()) {
@@ -881,7 +915,12 @@ int Sampler::build_greedy(int64_t n) {
n_seq_ = n;
any_brk_ = false;
any_late_ = false;
any_ngram_ = false;
cur_stage_ = greedy_stage_;
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from
* the staging, and a stale pair from an earlier request's build must not issue the ban over
* history that was not staged this step. */
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
if (greedy_ready_) return RAD_OK;
for (int64_t i = 0; i < cap; ++i) {
DeviceSampleParams& p = greedy_stage_[i];
@@ -904,7 +943,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
const RadStream s = rad_stream(c);
bool any_mask = false, any_greedy = false, any_chain = false;
bool any_penalty = false, any_dry = false, any_xtc = false;
bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false;
bool any_topp = false, any_minp = false, any_typ = false;
for (int64_t i = 0; i < n_seq_; ++i) {
const DeviceSampleParams& p = cur_stage_[i];
@@ -912,6 +951,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
any_dry |= (p.flags & RAD_SP_DRY) != 0;
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
any_ngram |= ngram_stage_[2 * i] > 0;
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
else {
any_chain = true;
@@ -939,13 +979,16 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (late)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
if (any_penalty || any_dry)
if (any_penalty || any_dry || any_ngram)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
n_seq_ * cfg_.max_hist * 4, s));
const bool pass_brk = any_dry && any_brk_;
if (pass_brk)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_,
n_seq_ * cfg_.max_hist, s));
if (any_ngram)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_,
n_seq_ * 2 * (int64_t)sizeof(int32_t), s));
if (any_mask)
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
n_seq_ * mask_words_ * 4, s));
@@ -954,6 +997,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
const RadOperand o_params = opd_rows(buf_params_, n_seq_);
const RadOperand o_hist = opd_rows(buf_hist_, n_seq_);
const RadOperand o_brk = opd_rows(buf_brk_, n_seq_);
const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_);
const RadOperand o_mask = opd_rows(buf_mask_, n_seq_);
const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_);
const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_);
@@ -981,6 +1025,13 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
if (any_dry)
RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
/* The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor),
* after the penalties and before every cut: a banned logit is -infinity for the greedy argmax
* below as well as for the chain, which is the reference processor's effect on the
* distribution. Off (the default) the op is not issued at all, so a request without it
* samples exactly as before. */
if (any_ngram) RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram }));
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
* and the chain run over the whole batch: the argmax writes every row, then the candidate
* stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
+11
View File
@@ -9,6 +9,7 @@
* Chain order (reordering changes which tokens survive):
*
* penalties (repetition / frequency / presence, then DRY)
* the windowed no-repeat-ngram ban
* temperature
* the grammar mask
* top-k
@@ -47,6 +48,8 @@
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
* -> logits (inout)
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram
* -> logits (inout)
* sample_temp M(range) n_vocab logits, params -> logits (inout)
* sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout)
* sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val,
@@ -232,6 +235,9 @@ private:
/* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
rad_op op_penalties_ = RAD_NULL_HANDLE;
rad_op op_dry_ = RAD_NULL_HANDLE;
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's
* generation_config asks for. It reads the same history plane as the two above. */
rad_op op_ngram_ban_ = RAD_NULL_HANDLE;
rad_op op_temp_ = RAD_NULL_HANDLE;
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
rad_op op_mask_ = RAD_NULL_HANDLE;
@@ -252,6 +258,7 @@ private:
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
rad_buf buf_hist_ = RAD_NULL_HANDLE;
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */
rad_buf buf_mask_ = RAD_NULL_HANDLE;
rad_buf buf_cand_i_ = RAD_NULL_HANDLE;
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
@@ -275,6 +282,7 @@ private:
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
int32_t* hist_stage_ = nullptr;
uint8_t* brk_stage_ = nullptr;
int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */
uint32_t* mask_stage_ = nullptr;
int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */
@@ -282,6 +290,9 @@ private:
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
* passed to sample_dry. */
bool any_brk_ = false;
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use,
* so this only decides whether that plane is uploaded and the op issued. */
bool any_ngram_ = false;
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
* only when the head is sharded; see declare(). */
+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
+7 -4
View File
@@ -706,10 +706,13 @@ public:
std::shared_ptr<mm::Item>* out, std::string* why) override {
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why);
return k == MediaKind::Image
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels)
: p_->video(bytes.data(), bytes.size(), out, why);
if (k == MediaKind::Video) return p_->video(bytes.data(), bytes.size(), out, why);
mm::ImageMode mode;
mode.kind = (int32_t)opts.image_mode;
mode.base_size = opts.image_base_size;
mode.image_size = opts.image_size;
return p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels, mode);
}
int32_t audio_rate() const override {
+6
View File
@@ -524,6 +524,12 @@ struct MediaOpts {
/* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides
* truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */
int64_t max_pixels = 0;
/* Which of the checkpoint's picture modes, for one that has two (Unlimited-OCR): 0 is the
* server's choice (mm::ImageMode::Default), 1 gundam, 2 base. A request that carries
* several pictures chooses base unless it says otherwise. */
int32_t image_mode = 0;
/* The mode's sizes, when the request states them; 0 keeps the mode's own. */
int32_t image_base_size = 0, image_size = 0;
};
class IMultimodal {
+92 -2
View File
@@ -240,6 +240,7 @@ const char* kAcceptedCommon[] = {
"dry_sequence_breakers", "samplers",
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
"timings_per_token", "return_progress", "session_id", "n_probs",
"ngram_ban_n", "ngram_window",
};
const char* kAcceptedChat[] = {
@@ -249,6 +250,8 @@ const char* kAcceptedChat[] = {
"thinking_token_budget", "thinking_budget", "thinking_budget_tokens",
"reasoning_budget_tokens", "reasoning_format", "continue_final_message",
"functions", "function_call",
/* Unlimited-OCR's picture modes: which of the checkpoint's two a request's pictures get. */
"images_config",
};
/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
@@ -891,6 +894,64 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
auto sid = b.find("session_id");
if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get<std::string>());
/* The windowed no-repeat-ngram ban (core/sample/sampler.h): `ngram_ban_n` is the banned
* n-gram's length and `ngram_window` how far back it looks; the checkpoint's own generation
* config asks for 35 and 128 (Unlimited-OCR). The reference spells them
* no_repeat_ngram_size and no_repeat_ngram_window_size; both are taken. */
i64 = r->sp.ngram_ban_n;
if (!get_any(b, { "ngram_ban_n", "no_repeat_ngram_size" }, &i64, nullptr, err))
return RAD_E_INVAL;
if (i64 < 0 || i64 > 256) {
*err = err_bad("ngram_ban_n", "must be in [0, 256]");
return RAD_E_INVAL;
}
r->sp.ngram_ban_n = (int)i64;
i64 = r->sp.ngram_window;
if (!get_any(b, { "ngram_window", "no_repeat_ngram_window_size" }, &i64, nullptr, err))
return RAD_E_INVAL;
if (i64 > 131072) {
*err = err_bad("ngram_window", "must be at most 131072 tokens of history; 0 or less "
"searches the whole sequence");
return RAD_E_INVAL;
}
r->sp.ngram_window = (int)i64;
/* `images_config`: Unlimited-OCR's two picture modes. A string names one ("gundam" for a
* single picture -- the global view plus crops --, "base" for a page of a multi-page
* document); an object carries the reference runner's own dict. */
auto ic = b.find("images_config");
if (ic != b.end() && !ic->is_null()) {
if (ic->is_string()) {
const std::string m = ic->get<std::string>();
if (m == "gundam") r->image_mode = 1;
else if (m == "base") r->image_mode = 2;
else if (!m.empty()) {
*err = err_bad("images_config", "expected \"gundam\" or \"base\", got \"" + m +
"\"");
return RAD_E_INVAL;
}
} else if (ic->is_object()) {
const json& o = *ic;
int64_t bs = 0, is = 0;
if (!get_int(o, "base_size", &bs, err)) return RAD_E_INVAL;
if (!get_int(o, "image_size", &is, err)) return RAD_E_INVAL;
bool crop = true;
if (!get_bool(o, "crop_mode", &crop, err)) return RAD_E_INVAL;
if (bs < 0 || bs > 65536 || is < 0 || is > 65536) {
*err = err_bad("images_config", "base_size and image_size must be in [0, 65536]");
return RAD_E_INVAL;
}
r->image_mode = crop ? 1 : 2;
r->image_base_size = (int32_t)bs;
r->image_size = (int32_t)is;
} else {
*err = err_bad("images_config",
"expected \"gundam\", \"base\", or an object with base_size, "
"image_size and crop_mode");
return RAD_E_INVAL;
}
}
RAD_TRY(apply_sampler_order(b, &r->sp, err));
auto so = b.find("stream_options");
@@ -1472,6 +1533,16 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
out->text = rendered;
auto pm = std::make_shared<mm::PromptMedia>();
const std::string marker = RAD_MEDIA_MARKER;
/* The checkpoint's mode for a picture no request named: a request that carries several
* pictures is a multi-page document, which the reference processes page by page without
* crops (infer_multi); one picture is the page-with-crops mode (infer). */
size_t n_images = 0;
for (const auto& m : media) n_images += m.first == MediaKind::Image ? 1 : 0;
auto opts_for = [&](MediaKind k) {
MediaOpts mo = opts;
if (k == MediaKind::Image && mo.image_mode == 0 && n_images > 1) mo.image_mode = 2;
return mo;
};
size_t pos = 0, mi = 0;
for (;;) {
size_t at = rendered.find(marker, pos);
@@ -1491,7 +1562,8 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
}
std::shared_ptr<mm::Item> item;
std::string why;
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts, &item, &why);
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts_for(media[mi].first),
&item, &why);
if (s < 0 || !item) {
*err = err_bad("messages[].content[]", "the media could not be used: " +
(why.empty() ? std::string(rad_strerror(s))
@@ -2058,7 +2130,25 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true);
p.text = rendered;
} else {
RAD_TRY(tokenize_with_media(rendered, d, media, MediaOpts{}, &p, err));
MediaOpts mo;
mo.image_mode = out->image_mode;
mo.image_base_size = out->image_base_size;
mo.image_size = out->image_size;
RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, err));
}
/* Not every template renders BOS: this checkpoint's is a bare concatenation of the parts, while
* its tokenizer states `add_bos_token: true` (and the reference's own `infer` prepends id 0).
* Add it only when the rendered prompt does not already start with it, so a template that does
* render it is untouched. A media run's placeholders shift by one with it. */
{
const ITokenizer::VocabInfo vi = d.tok->vocab_info();
if (vi.add_bos && vi.bos >= 0 && (p.tokens.empty() || p.tokens.front() != vi.bos)) {
p.tokens.insert(p.tokens.begin(), vi.bos);
if (p.media) {
for (auto& pl : p.media->items) pl.tok += 1;
p.media->layout();
}
}
}
if (p.tokens.empty()) {
*err = err_bad("messages", "the rendered prompt tokenised to nothing");
+5
View File
@@ -158,6 +158,11 @@ struct OaiRequest {
/* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */
int32_t image_tokens = 0;
/* `images_config`: which of the checkpoint's picture modes a request's pictures get, and the
* sizes it states (Unlimited-OCR's gundam and base modes). 0 keeps the server's choice: base
* for a request with several pictures, gundam otherwise. */
int32_t image_mode = 0, image_base_size = 0, image_size = 0;
int n_choices() const { return (int)prompts.size() * n; }
};