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

+3 -3
View File
@@ -18,7 +18,7 @@ using namespace rad;
namespace {
static_assert(sizeof(AdvGroup) == 48, "AdvGroup's layout is part of the card's slab");
static_assert(sizeof(AdvGroup) == 72, "AdvGroup's layout is part of the card's slab");
/* Word offsets of every array the advance reads or writes. Up to kSeq rows, kTok tokens and
* kGroups KV groups, each group with a kPitch-entry block table per row. */
@@ -35,8 +35,8 @@ struct Slab {
CU = SID + kSeq,
Q = CU + kSeq + 8,
ROPE = Q + kSeq, /* [3][kTok] */
GRP = ROPE + 3 * kTok, /* [kGroups] AdvGroup, 12 words each */
SLOT = GRP + 12 * kGroups, /* [kGroups][kTok] */
GRP = ROPE + 3 * kTok, /* [kGroups] AdvGroup, sizeof/4 words each */
SLOT = GRP + (int)(sizeof(AdvGroup) / 4) * kGroups, /* [kGroups][kTok] */
USED = SLOT + kGroups * kTok, /* [kGroups][kSeq] */
BT = USED + kGroups * kSeq, /* [kGroups][kSeq][kPitch] */
FIRST = BT + kGroups * kSeq * kPitch, /* [kGroups][kSeq] */
+52
View File
@@ -206,4 +206,56 @@ TEST(gen_config_derives_the_sidecar_path) {
CHECK_EQ(gen_sidecar_path("/a.b/model.rad"), std::string("/a.b/model.generation.json"));
}
/* Unlimited-OCR's generation_config.json, verbatim: it states no temperature or top-k, only the
* windowed no-repeat-n-gram ban, so it must be claimed as stated (or the ban would never reach a
* request that sends no sampler fields). `do_sample: false` still means greedy and ignores it. */
TEST(gen_config_reads_the_ngram_ban) {
const char* const kUnlimitedOcr = R"({
"bos_token_id": 0,
"eos_token_id": 1,
"no_repeat_ngram_size": 35,
"no_repeat_ngram_window_size": 128,
"max_new_tokens": 32768,
"use_cache": true
})";
GenSampling g;
CHECK(gen_sampling_parse(kUnlimitedOcr, "test", &g));
CHECK_EQ(g.ngram_ban_n, 35);
CHECK_EQ(g.ngram_window, 128);
CHECK(g.temp < 0.0f);
const SamplingParams sp = g.onto(SamplingParams{});
CHECK_EQ(sp.ngram_ban_n, 35);
CHECK_EQ(sp.ngram_window, 128);
CHECK(GenSampling::describe(sp).find("ngram ban n 35 over the last 128 tokens") !=
std::string::npos);
/* The container's flattened copy reads the same. */
GenSampling kv;
CHECK(gen_sampling_from_kv(kv_of({ { "no_repeat_ngram_size", "35" },
{ "no_repeat_ngram_window_size", "128" } }),
&kv));
CHECK_EQ(kv.ngram_ban_n, 35);
CHECK_EQ(kv.ngram_window, 128);
/* This sampler's spellings, and the reference's negative window as "the whole sequence". */
GenSampling own;
CHECK(gen_sampling_parse(R"({"ngram_ban_n": 35, "ngram_window": -1})", "test", &own));
CHECK_EQ(own.ngram_ban_n, 35);
CHECK_EQ(own.ngram_window, 0);
/* A size outside [0, 256] is dropped on its own; the window still reads. */
GenSampling bad;
CHECK(gen_sampling_parse(R"({"no_repeat_ngram_size": 5000,
"no_repeat_ngram_window_size": 128})", "test", &bad));
CHECK_EQ(bad.ngram_ban_n, -1);
CHECK_EQ(bad.ngram_window, 128);
/* do_sample false is greedy: transformers ignores the ban under it, and so does this. */
GenSampling greedy;
CHECK(gen_sampling_parse(R"({"do_sample": false, "no_repeat_ngram_size": 35})", "test",
&greedy));
CHECK_EQ(greedy.ngram_ban_n, -1);
CHECK_EQ(greedy.onto(SamplingParams{}).ngram_ban_n, 0);
}
RAD_TEST_MAIN()
+463
View File
@@ -0,0 +1,463 @@
/* kv_window_test.cpp -- the runtime per-sequence window on a RAD_KV_WINDOW group (R-SWA).
*
* R-SWA (Unlimited-OCR) keeps a sequence's whole prefill as a retained reference and decodes into
* a ring of W slots right after it: visible = [0, prefill) U [prefill, prefill + W). The reference
* is never recycled, the ring rewrites its slots in place, and RoPE positions keep increasing --
* only the block/slot mapping recycles. These tests pin the manager's side of that: the visible
* token set, flat bytes after the floor is set, the recycling boundary, the exclusion from the
* prefix cache and snapshots, and that a fixed-window group (gemma4's) is exactly what it was.
*/
#include "rad_test.h"
#include "mem/kv.h"
#include "mem/pools.h"
#include "sched/advance_impl.h"
#include "sched/mem_iface.h"
#include "rad_internal.h"
#include <algorithm>
#include <map>
#include <set>
#include <vector>
using namespace rad;
/* Handle 0 is the null group (see mem_test): a real group at index 0 would read as "no group". */
enum : int32_t { G_NULL = 0, G_WIN = 1 };
static Config window_config() {
Config c;
c.vram_weights_mib = 1;
c.vram_kv_mib = 4; /* 4 MiB: an 8 KiB page at block 128, room for 4 x 4096 tokens */
c.gpu_headroom_mib = 1;
c.host_pool_mib = 0;
c.max_seqs = 4;
c.max_tok = 128; /* one block a step, as a decode deployment */
c.max_ctx = 4096;
c.checkpoint_interval = 512;
c.prefix_cache = true;
return c;
}
/* A single windowed group of one layer at `block` (page block*2*8*2*2 bytes), so a test can use
* the geometry R-SWA runs at: block_size 128 = W. */
static KVGroupInfo window_group(int64_t block, int64_t declared_window) {
KVGroupInfo k;
k.name = "rswa";
k.decl.kind = RAD_KV_WINDOW;
k.decl.dtype = RAD_BF16;
k.decl.n_head_kv = 2;
k.decl.head_dim = 8;
k.decl.window = declared_window;
k.block_size = block;
k.layers = { 0 };
return k;
}
static std::vector<KVGroupInfo> groups_of(const KVGroupInfo& g) {
std::vector<KVGroupInfo> v;
v.push_back(KVGroupInfo{});
v.push_back(g);
return v;
}
static int configure_pools(Pools& p, const Config& c) {
return p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator());
}
/* A sequence's slot for `pos`, through the rule the step batch uses (KVGeom::slot_ring). */
struct Ring {
KVManager* kv;
KVGeom geo;
int32_t g = G_WIN;
bool has_window() const { return kv->runtime_window(1, g, nullptr); }
SeqWindow window() const {
SeqWindow w;
kv->runtime_window(1, g, &w);
return w;
}
int32_t slot(int64_t pos) const {
SeqWindow w;
if (!kv->runtime_window(1, g, &w)) return -1;
return geo.slot_ring(g, kv->block_table(1, g), kv->first_block_pos(1, g), pos, w);
}
};
TEST(rswa_reference_and_ring_keeps_the_visible_set_and_flat_bytes) {
const int64_t B = 128, W = 128, P = 400; /* P is not a block multiple on purpose */
const KVGroupInfo grp = window_group(B, W);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, W));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
/* A runtime-window group keeps no window snapshot: the window is the sequence's own data. */
CHECK(kv.plan(G_WIN)->runtime_win);
CHECK_EQ(kv.plan(G_WIN)->runtime_tokens, W);
CHECK(!kv.plan(G_WIN)->win_snap);
CHECK(!kv.has_window_snapshot());
CHECK_EQ(kv.checkpoint_bytes(), 0ll);
CHECK_EQ(kv.runtime_window_tokens(G_WIN), W);
/* Sized for the context plus one ring a sequence, not capped at window_blocks. */
CHECK(kv.total_blocks(G_WIN) >= cfg.max_seqs * (cfg.max_ctx / B + 1));
CHECK_OK(kv.add_sequence(1));
CHECK_OK(kv.set_window(1, P, W));
const Ring r{ &kv, KVGeom::of(g), G_WIN };
CHECK(r.has_window());
const SeqWindow w = r.window();
CHECK_EQ(w.visible_lo, P);
/* Whole blocks: the ring starts at the first boundary at or after the floor, and the tokens
* in [P, ring_pos) stay in the reference's last block. */
CHECK_EQ(w.ring_pos, 512ll);
CHECK_EQ(w.ring_blocks, 1ll);
CHECK_EQ(w.ring_span(B), 128ll);
/* Prefill: the reference is written linearly; the table is ceil(P / B) blocks. */
CHECK_OK(kv.ensure(1, P));
CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 4ll);
std::map<int32_t, int64_t> content; /* slot -> position it holds */
for (int64_t p = 0; p < P; ++p) {
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
content[s] = p;
}
/* Generate L tokens. The visible set must be [0, P) plus, in the ring, the newest ring_span
* positions: [0, P) U [P, ring_pos) (frozen: written once, kept) U the last `span` of
* [ring_pos, n). Block granularity is the accepted consequence -- with W = 128 and block 128
* the visible tail is 112 frozen + 128 ring = 240 tokens, always W..W+B-1 = 128..255 and a
* superset of the reference implementation's last 128. Once n >= ring_pos + span the set is
* exactly that, so the test asserts equality. */
const int64_t L = 2000;
int64_t flat_blocks = -1;
int64_t bad_step = -1;
for (int64_t p = P; p < P + L && bad_step < 0; ++p) {
CHECK_OK(kv.ensure(1, p + 1, p));
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
content[s] = p;
const int64_t n = p + 1;
/* The table never moves and the floor stays 0: only slots recycle. */
CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll);
const int64_t want_blocks =
n <= w.ring_pos ? (n + B - 1) / B
: w.ring_pos / B + std::min(w.ring_blocks,
(n - w.ring_pos + B - 1) / B);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), want_blocks);
/* Bytes are flat once the ring is full: no block is allocated past it, ever. */
if (n >= w.ring_pos + w.ring_span(B)) {
if (flat_blocks < 0) flat_blocks = (int64_t)kv.block_table(1, G_WIN).size();
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), flat_blocks);
CHECK_EQ(kv.held_blocks(G_WIN), flat_blocks);
}
/* The slots hold exactly the rule's set. */
std::set<int64_t> held, want;
for (const auto& kvp : content) held.insert(kvp.second);
for (int64_t q = 0; q < std::min<int64_t>(P, n); ++q) want.insert(q);
for (int64_t q = P; q < std::min(w.ring_pos, n); ++q) want.insert(q);
for (int64_t q = std::max<int64_t>(w.ring_pos, n - w.ring_span(B)); q < n; ++q)
want.insert(q);
if (held != want) bad_step = n;
}
CHECK_EQ(bad_step, -1ll);
/* The reference's blocks were never recycled: blocks 0..2 are untouched and block 3's
* reference slots (0..111 = positions 384..399) still hold their prefill values. */
const std::vector<int32_t>& bt = kv.block_table(1, G_WIN);
REQUIRE_EQ((long long)bt.size(), 5ll);
for (int64_t p = 0; p < P; ++p) {
const int64_t bi = p / B;
const int32_t slot = (int32_t)(bt[(size_t)bi] * B + p % B);
REQUIRE(content.count(slot) > 0);
CHECK_EQ(content[slot], p);
}
/* The recycling boundary: the ring is one block, so a position and the position one span
* later share a slot, while neighbours do not. ring_pos + span is the first token that
* overwrites ring_pos. */
CHECK_EQ(r.slot(w.ring_pos), r.slot(w.ring_pos + w.ring_span(B)));
CHECK(r.slot(w.ring_pos) != r.slot(w.ring_pos + 1));
const int32_t first_ring_slot = (int32_t)(bt[4] * B + w.ring_pos % B);
CHECK_EQ(r.slot(w.ring_pos), first_ring_slot);
/* Flat to the end, and the free list gets everything back on free. */
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), flat_blocks);
const int64_t free0 = kv.free_blocks(G_WIN);
kv.free_sequence(1);
CHECK_EQ(kv.free_blocks(G_WIN), free0 + flat_blocks);
}
/* A block-aligned floor is the exact reference rule: the ring starts at the floor, so the visible
* tail is exactly the last W tokens. */
TEST(rswa_aligned_floor_shows_exactly_the_last_w_tokens) {
const int64_t B = 128, W = 128, P = 512;
const KVGroupInfo grp = window_group(B, W);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, W));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
CHECK_OK(kv.add_sequence(1));
CHECK_OK(kv.set_window(1, P, W));
const Ring r{ &kv, KVGeom::of(g), G_WIN };
const SeqWindow w = r.window();
CHECK_EQ(w.ring_pos, P);
CHECK_EQ(w.ring_blocks, 1ll);
CHECK_EQ(w.ring_span(B), W);
CHECK_OK(kv.ensure(1, P));
REQUIRE_EQ((long long)kv.block_table(1, G_WIN).size(), 4ll);
for (int64_t p = P; p < P + 1024; ++p) CHECK_OK(kv.ensure(1, p + 1, p));
/* Every tail position maps into the one ring block, at the position mod B. */
REQUIRE_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll);
const int32_t ring_block = kv.block_table(1, G_WIN)[4];
for (int64_t p = P; p < P + 1024; ++p) {
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
CHECK_EQ(s, (int32_t)(ring_block * B + p % B));
}
/* Held = 4 reference blocks + 1 ring, and nothing more however long the generation is. */
CHECK_EQ(kv.held_blocks(G_WIN), 5ll);
kv.free_sequence(1);
}
/* A group that is never given a runtime window keeps today's recycling exactly: the same numbers
* as mem_test's kv_window_group_recycles_below_the_window, so gemma4_bf16 is untouched. */
TEST(fixed_window_group_is_unchanged) {
const KVGroupInfo grp = window_group(16, 64);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
cfg.max_tok = 64;
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.configure(g, cfg, pools.kv())); /* no declare_runtime_window */
CHECK(!kv.plan(G_WIN)->runtime_win);
CHECK_EQ(kv.runtime_window_tokens(G_WIN), 0ll);
/* Window 64 at block 16 is 4 blocks plus one for the straddle, as before. */
CHECK_EQ(kv.plan(G_WIN)->window_blocks, 5ll);
const int64_t n0 = kv.free_blocks(G_WIN);
CHECK_OK(kv.add_sequence(1));
CHECK(!kv.has_runtime_window(1));
CHECK_OK(kv.ensure(1, 80));
CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll);
CHECK_OK(kv.ensure(1, 400));
CHECK_EQ(kv.first_block_pos(1, G_WIN), 16ll);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 24ll);
CHECK_OK(kv.ensure(1, 401));
CHECK_EQ(kv.first_block_pos(1, G_WIN), 336ll);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll);
kv.trim_window(1, 401);
CHECK_EQ(kv.first_block_pos(1, G_WIN), 336ll);
CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll);
CHECK_EQ(kv.free_blocks(G_WIN), n0 - 5);
kv.free_sequence(1);
CHECK_EQ(kv.free_blocks(G_WIN), n0);
}
/* A sequence with a runtime window is excluded from every reuse path that assumes the declare-time
* window, and the manager refuses the ones a caller could still reach. */
TEST(rswa_sequence_is_excluded_from_prefix_and_snapshots) {
const KVGroupInfo grp = window_group(128, 128);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, 128));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
/* The declare-time window is still what an unarmed sequence gets. */
CHECK_OK(kv.add_sequence(1));
CHECK(!kv.has_runtime_window(1));
CHECK_OK(kv.set_window(1, 256, 128));
CHECK(kv.has_runtime_window(1));
CHECK_OK(kv.ensure(1, 256));
CHECK_OK(kv.ensure(1, 300, 256));
std::vector<int32_t> rows;
CHECK(!kv.window_rows(1, 256, &rows)); /* no snapshot describes this window */
CHECK(rows.empty());
CHECK_EQ(kv.seed_window(1, 256), RAD_E_STATE); /* no hit resumes into it */
CHECK_EQ(kv.adopt(1, G_WIN, kv.block_table(1, G_WIN), 256), RAD_E_STATE);
CHECK_EQ(kv.fork(1, 2), RAD_E_UNSUPPORTED);
CHECK_EQ(kv.rollback(1, 200), RAD_E_UNSUPPORTED);
/* A fresh retry: preempt clears the window so admission re-arms it. */
CHECK_OK(kv.preempt(1));
CHECK(!kv.has_runtime_window(1));
kv.free_sequence(1);
}
/* Refusals: a runtime window needs a windowed group, a floor at or ahead of the KV it holds, and
* blocks that can hold the reference plus the ring. */
TEST(rswa_refusals_are_explicit) {
Config cfg = window_config();
{
/* A FULL group cannot carry one: the declaration is recorded, and the plan refuses it. */
std::vector<KVGroupInfo> g = groups_of(window_group(128, 0));
g[G_WIN].decl.kind = RAD_KV_FULL;
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, 128));
CHECK_EQ(kv.configure(g, cfg, pools.kv()), RAD_E_INVAL);
}
{
/* A model with no windowed group has nothing to arm. */
std::vector<KVGroupInfo> g = groups_of(window_group(128, 0));
g[G_WIN].decl.kind = RAD_KV_FULL;
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.configure(g, cfg, pools.kv()));
CHECK_OK(kv.add_sequence(1));
CHECK_EQ(kv.set_window(1, 256, 128), RAD_E_UNSUPPORTED);
kv.free_sequence(1);
}
{
/* A windowed group plans; the refusals are about the sequence. */
const std::vector<KVGroupInfo> g = groups_of(window_group(128, 128));
Pools pools;
CHECK_OK(configure_pools(pools, cfg));
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_WIN, 128));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
CHECK_OK(kv.add_sequence(1));
CHECK_EQ(kv.set_window(1, 256, 0), RAD_E_INVAL);
CHECK_EQ(kv.set_window(1, -1, 128), RAD_E_INVAL);
CHECK_OK(kv.ensure(1, 256));
/* The floor cannot move behind KV already written. */
CHECK_EQ(kv.set_window(1, 128, 128), RAD_E_STATE);
CHECK(!kv.has_runtime_window(1));
kv.free_sequence(1);
}
}
/* The block rounding must never lose a token of the last W: the ring is W..W+B-1 tokens wide,
* whatever W is relative to the block. */
TEST(rswa_ring_always_covers_the_last_w_tokens) {
const int64_t B = 128;
for (int64_t w_tokens : { 1, 64, 100, 128, 129, 200, 300 }) {
for (int64_t P : { 400, 512 }) {
const KVGroupInfo grp = window_group(B, 128);
const std::vector<KVGroupInfo> g = groups_of(grp);
Config cfg = window_config();
Pools pools;
REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK);
KVManager kv;
REQUIRE_EQ(kv.declare_runtime_window(G_WIN, w_tokens), RAD_OK);
REQUIRE_EQ(kv.configure(g, cfg, pools.kv()), RAD_OK);
REQUIRE_EQ(kv.add_sequence(1), RAD_OK);
REQUIRE_EQ(kv.set_window(1, P, w_tokens), RAD_OK);
const Ring r{ &kv, KVGeom::of(g), G_WIN };
const SeqWindow w = r.window();
const int64_t span = w.ring_span(B);
CHECK_EQ(w.ring_pos, (P + B - 1) / B * B);
CHECK_EQ(w.ring_blocks, (w_tokens + B - 1) / B);
/* The frozen tail [P, ring_pos) plus the ring always covers the last W: at least W
* wide, and never more than the ring's rounding plus the frozen fraction (W + B - 1
* when W is a block multiple, W + 2B - 2 otherwise). */
CHECK(w.ring_pos - P + span >= w_tokens);
CHECK(w.ring_pos - P + span <= w_tokens + 2 * B - 2);
if (w_tokens % B == 0) CHECK(w.ring_pos - P + span <= w_tokens + B - 1);
REQUIRE_EQ(kv.ensure(1, P), RAD_OK);
const int64_t n = P + 3 * span;
for (int64_t p = P; p < n; ++p) REQUIRE_EQ(kv.ensure(1, p + 1, p), RAD_OK);
/* Held blocks: the reference's, then the ring's -- flat. */
const int64_t blocks = (int64_t)kv.block_table(1, G_WIN).size();
CHECK_EQ(blocks, w.ring_pos / B + w.ring_blocks);
std::map<int32_t, int64_t> content;
for (int64_t p = 0; p < n; ++p) {
const int32_t s = r.slot(p);
REQUIRE(s >= 0);
content[s] = p; /* a ring slot's newest write wins */
}
std::set<int64_t> held;
for (const auto& kvp : content) held.insert(kvp.second);
/* The last W positions of the generation are among what the slots hold... */
for (int64_t p = n - w_tokens; p < n; ++p) CHECK(held.count(p) > 0);
/* ...and nothing outside the rule is. */
std::set<int64_t> want;
for (int64_t p = 0; p < std::min<int64_t>(P, n); ++p) want.insert(p);
for (int64_t p = P; p < std::min(w.ring_pos, n); ++p) want.insert(p);
for (int64_t p = std::max<int64_t>(w.ring_pos, n - span); p < n; ++p) want.insert(p);
CHECK(held == want);
kv.free_sequence(1);
}
}
}
/* The card's advance (core/sched/advance_impl.h, adv_groups) runs AFTER the batch builder and
* overwrites every group's `seqused` and slot_mapping, so for a runtime window it must reproduce
* the ring's mapping. This is the P4a GPU fault: the advance wrote used = ctx + n (177 for a
* 176-token held span) and mapped a wrapped position linearly, so the decode walked
* bt[ceil(used/16)-1] = bt[11] -- the first entry past the 11-block table, which the builder pads
* with -1 -- and faulted the card below the KV pool. With block 16 and the ring 8 blocks
* (128 tokens), the table is the reference's 3 blocks plus the ring's 8. */
TEST(rswa_advance_keeps_the_ring_span_and_slots) {
const int64_t B = 16, PITCH = 32;
const int32_t ring_pos = 48, ring_blocks = 8, table_len = 11;
int32_t pos[5] = { 176, 177, 183, 191, 192 }; /* wrapped ring positions */
const int32_t base = 176, n = 5;
AdvanceArgs a;
std::vector<char> slab(4096, 0);
const int64_t used_off = 0, slot_off = 16, bt_off = slot_off + 8 * 4;
const int64_t first_off = bt_off + PITCH * 4, pos_off = first_off + 4;
const int64_t rpos_off = pos_off + 32, tlen_off = rpos_off + 4;
const int64_t grp_off = tlen_off + 8;
a.slab = slab.data();
a.pos_off = pos_off; a.grp_off = grp_off;
a.n_groups = 1;
std::memcpy(slab.data() + pos_off, pos, sizeof pos);
int32_t* bt = reinterpret_cast<int32_t*>(slab.data() + bt_off);
for (int32_t b = 0; b < table_len; ++b) bt[b] = b; /* blocks 0..10 */
for (int64_t b = table_len; b < PITCH; ++b) bt[b] = -1; /* the builder's padding */
*reinterpret_cast<int32_t*>(slab.data() + first_off) = 0;
/* Per sequence, as the builder fills them: this row's floor and its table's length. */
*reinterpret_cast<int32_t*>(slab.data() + rpos_off) = ring_pos;
*reinterpret_cast<int32_t*>(slab.data() + tlen_off) = (int32_t)table_len;
AdvGroup* g = reinterpret_cast<AdvGroup*>(slab.data() + grp_off);
g->block_size = (int32_t)B; g->paged = 1; g->pitch = (int32_t)PITCH;
g->slot_off = slot_off; g->used_off = used_off; g->bt_off = bt_off;
g->first_off = first_off; g->rpos_off = rpos_off; g->tlen_off = tlen_off;
g->ring = 1; g->ring_blocks = ring_blocks;
adv_groups(a, 0, 0, base, n);
/* used stops at the table: the ring holds 3 reference blocks + 8 ring blocks = 176 tokens,
* while the context is 181. Without the clamp the decode reads bt[11] = -1. */
CHECK_EQ(*reinterpret_cast<int32_t*>(slab.data() + used_off), 176);
const int32_t* slot = reinterpret_cast<const int32_t*>(slab.data() + slot_off);
/* A position at or past ring_pos maps into the ring, modulo its blocks: 176 -> block 3
* (slot 48), 192 -> block 4 (slot 64), never the linear (p - first)/block = 11..12. */
CHECK_EQ(slot[0], 48); /* 176: ring block 3, offset 0 */
CHECK_EQ(slot[1], 49); /* 177 */
CHECK_EQ(slot[2], 55); /* 183 */
CHECK_EQ(slot[3], 63); /* 191: last slot of ring block 3 */
CHECK_EQ(slot[4], 64); /* 192: ring block 4, offset 0 */
/* Every slot is a real slot of the table (never -1). */
for (int32_t j = 0; j < n; ++j) CHECK(slot[j] >= 0);
/* The same row without a runtime window keeps the linear mapping -- used = base + n, and the
* wrapped position lands past the table (the old behaviour). */
g->ring = 0;
adv_groups(a, 0, 0, base, n);
CHECK_EQ(*reinterpret_cast<int32_t*>(slab.data() + used_off), 181);
CHECK_EQ(slot[0], -1);
}
RAD_TEST_MAIN()
+269
View File
@@ -0,0 +1,269 @@
"""mkuocrgolden.py MODELDIR OUT.h [REPORT] -- goldens for the Unlimited-OCR processor in
tests/mm_test.cpp (P3 of aijuus/plans/UNLIMITED-OCR-PLUGIN.md), every number from the checkpoint's
own remote code as MODELDIR ships it:
- the tile grid, from modeling_unlimitedocr.dynamic_preprocess (find_closest_aspect_ratio over
its sorted set of ratios), for a sweep of sizes including the exact ties its set order resolves;
- the placeholders that replace a picture's <image>, from infer() (gundam mode) and infer_multi()
(base mode: the whole page, and the 640-pixel page the reference's default asks for);
- the pixels: the global view (ImageOps.pad) and the local one (the picture resized to its tile
grid and cut), transformed by the model's BasicImageTransform and rounded to bf16, in the patch
order the radiance processor stages them (Item::patch_raster: row by row, each patch
(channel, y, x)). The segment plan is the radiance Item's (see the header of
Processor::image_unlimitedocr): a line of tiles per tile row, the global view's grid, and the
view separator's single row -- each with `downsample` filler patch columns for the newline
column the reference's layout puts after every line of features.
REPORT, when given, gets one line per picture and mode: the grid, the placeholder count and
whether the segment plan's counts match, for the gate's log.
"""
import sys, math, json
import numpy as np, torch
from PIL import Image, ImageOps
from torchvision import transforms
model_dir, out = sys.argv[1], sys.argv[2]
report = open(sys.argv[3], "w") if len(sys.argv) > 3 else None
# ---- the checkpoint's two configs, and its remote module as a package (its relative imports need
# one)
import types, importlib
pkg = types.ModuleType("uocr")
pkg.__path__ = [model_dir]
sys.modules["uocr"] = pkg
M = importlib.import_module("uocr.modeling_unlimitedocr")
pre = json.load(open(model_dir + "/preprocessor_config.json"))
proc = json.load(open(model_dir + "/processor_config.json"))
PATCH = int(proc["patch_size"])
DS = int(proc["downsample_ratio"])
BASE = int(pre["size"]["height"])
TILE = int(pre["tile_size"])
MIN_PATCHES = int(pre["min_patches"])
MAX_PATCHES = int(pre["max_patches"])
CROP = bool(pre["crop_to_patches"])
MEAN = tuple(float(x) for x in pre["image_mean"])
STD = tuple(float(x) for x in pre["image_std"])
assert proc["image_token"] == "<image>" and proc["normalize"]
assert [int(x) for x in pre["background_color"]] == [127, 127, 127]
assert abs(MEAN[0] - 0.5) < 1e-9 and abs(STD[0] - 0.5) < 1e-9
from transformers import AutoTokenizer
tok = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False)
IMAGE_TOKEN = tok.convert_tokens_to_ids("<image>")
assert IMAGE_TOKEN == 128815, IMAGE_TOKEN
# the model's own transform: ToTensor then Normalize(0.5, 0.5), in f32, rounded to bf16
transform = transforms.Compose([transforms.ToTensor(),
transforms.Normalize(MEAN, STD)])
def bf16_patches(im, grids):
"""The patches of `im`, in Item::patch_raster order: (channel, y, x) per patch, row by row,
bf16 bit patterns. `grids` is (gh, gw): the patch grid the tensor is cut into."""
t = transform(im).to(torch.bfloat16)
ch, h, w = t.shape
gh, gw = grids
assert h == gh * PATCH and w == gw * PATCH, (h, w, gh, gw)
a = t.reshape(ch, gh, PATCH, gw, PATCH).permute(1, 3, 0, 2, 4).contiguous()
return a.view(torch.int16).numpy().astype(np.uint16)
def fnv(arr):
b = arr.tobytes()
h = 0xcbf29ce484222325
mul = 0x100000001b3
mask = (1 << 64) - 1
for v in b:
h = ((h ^ v) * mul) & mask
return h
def expand_gundam(im):
"""modeling_unlimitedocr.infer, verbatim for one picture: the global view at BASE, then the
local views if the picture is larger than a tile. Returns (placeholders, cols, rows, tiles,
global view)."""
w, h = im.size
global_view = ImageOps.pad(im, (BASE, BASE), color=tuple(int(x * 255) for x in MEAN))
if w > TILE or h > TILE:
tiles, ratio = M.dynamic_preprocess(im, MIN_PATCHES, MAX_PATCHES, TILE, False)
cols, rows = ratio
else:
tiles, cols, rows = [], 1, 1
nq_base = math.ceil((BASE // PATCH) / DS)
n = (nq_base + 1) * nq_base + 1 # ([tok] * n + [tok]) * n + [tok]
if cols * rows > 1:
nq = math.ceil((TILE // PATCH) / DS)
n += (nq * cols + 1) * nq * rows # ([tok] * nq * cols + [tok]) * nq * rows
return n, cols, rows, tiles, global_view
def expand_base(im, image_size):
"""modeling_unlimitedocr.infer_multi, verbatim for one page: the page squared when the side is
a tile or less, then padded to image_size."""
w, h = im.size
if image_size <= TILE:
im = im.resize((image_size, image_size))
global_view = ImageOps.pad(im, (image_size, image_size),
color=tuple(int(x * 255) for x in MEAN))
nq = math.ceil((image_size // PATCH) / DS)
n = (nq + 1) * nq + 1
return n, 1, 1, [], global_view
def plan_segments(cols, rows, base_grid):
"""The Item's segment plan: one line of tiles per tile row (split so a pass holds it; the last
chunk carries the newline column), the global view's grid, the separator. (gh, gw, real)."""
q = TILE // PATCH
segs = []
if cols * rows > 1:
c_max = (16384 // q - 4) // q # the server's pass, --mm-max-patches
c_max = max(1, c_max)
for r in range(rows):
c0 = 0
while c0 < cols:
n = min(c_max, cols - c0)
last = (c0 + n) == cols
segs.append((q, q * n + (4 if last else 0), q * n))
c0 += n
segs.append((base_grid, base_grid + 4, base_grid))
segs.append((DS, DS, 0))
return segs
def picture(f, h, w):
y, x, c = np.meshgrid(np.arange(h, dtype=np.uint64), np.arange(w, dtype=np.uint64),
np.arange(3, dtype=np.uint64), indexing="ij")
with np.errstate(over="ignore"):
z = (np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9) +
x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345))
z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9)
z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB)
z = z ^ (z >> np.uint64(31))
return Image.fromarray((z & np.uint64(255)).astype(np.uint8))
def names():
return ["kUocrPictures", "kUocrSegs", "kUocrGrid"]
L = ["/* uocr_golden.h -- GENERATED by mkuocrgolden.py from the checkpoint's remote code; do not "
"edit. */",
"#pragma once", "#include <cstdint>", "",
f"static const int32_t kUocrPatch = {PATCH}, kUocrDownsample = {DS};",
f"static const int32_t kUocrBaseSize = {BASE}, kUocrTile = {TILE};",
f"static const int32_t kUocrMinTiles = {MIN_PATCHES}, kUocrMaxTiles = {MAX_PATCHES};",
f"static const bool kUocrCropMode = {'true' if CROP else 'false'};",
f"static const int32_t kUocrImageToken = {IMAGE_TOKEN};", ""]
# ---- the tile grid, for sizes that cover every shape and the exact ties of dynamic_preprocess
sizes = [(1, 1), (40, 30), (100, 100), (300, 500), (500, 300), (640, 640), (641, 641), (500, 700),
(700, 500), (800, 1000), (1000, 800), (1024, 1024), (1280, 1024), (1024, 1280), (900, 1400),
(1400, 900), (2000, 600), (600, 2000), (2400, 400), (400, 2400), (1080, 1920), (1920, 1080),
(515, 1031), (1031, 515), (100, 5000), (5000, 100), (3000, 3000), (720, 1280), (800, 640),
(640, 800), (960, 720), (720, 960), (1600, 1200), (1200, 1600), (33, 4096), (4096, 33)]
L.append("struct GoldUocrGrid { int64_t h, w; int32_t cols, rows; };")
L.append("static const GoldUocrGrid kUocrGrid[] = {")
for h, w in sizes:
im = Image.new("RGB", (w, h))
if w > TILE or h > TILE:
_, ratio = M.dynamic_preprocess(im, MIN_PATCHES, MAX_PATCHES, TILE, False)
cols, rows = ratio
else:
cols, rows = 1, 1
L.append(f" {{ {h}, {w}, {cols}, {rows} }},")
L.append("};")
L.append("")
# ---- whole pictures: gundam (1), base at 1024 (2) and base at 640 (3), and a two-page pair
pics = [(0, 300, 500, 1), (1, 900, 1400, 1), (2, 2400, 400, 1), (3, 500, 700, 1), (4, 64, 48, 1),
(5, 800, 1000, 1), (0, 300, 500, 2), (1, 900, 1400, 2), (2, 2400, 400, 2), (3, 500, 700, 2),
(4, 64, 48, 2), (5, 800, 1000, 2), (1, 900, 1400, 3), (3, 500, 700, 3)]
segs, rows, seg0 = [], [], 0
L.append("struct GoldUocrPic { int32_t f, h, w, mode; int32_t cols, rows, n_ids; int32_t n_seg, "
"seg0; uint64_t global_fnv, local_fnv; };")
for f, h, w, mode in pics:
im = picture(f, h, w)
if mode == 1:
n, cols, rows_, tiles, gv = expand_gundam(im)
base_grid = BASE // PATCH
g_fnv = fnv(bf16_patches(gv, (base_grid, base_grid)))
if cols * rows_ > 1:
big = im.resize((TILE * cols, TILE * rows_), Image.Resampling.BICUBIC)
l_fnv = fnv(bf16_patches(big, (TILE // PATCH * rows_, TILE // PATCH * cols)))
else:
l_fnv = 0
else:
size = 1024 if mode == 2 else 640
n, cols, rows_, tiles, gv = expand_base(im, size)
base_grid = size // PATCH
g_fnv = fnv(bf16_patches(gv, (base_grid, base_grid)))
l_fnv = 0
pl = plan_segments(cols, rows_, base_grid)
# every segment's row count is its patches / downsample^2, and the sum is the reference's
total = sum((gh // DS) * (gw // DS) for gh, gw, _ in pl)
assert total == n, (h, w, mode, total, n)
rows.append(f" {{ {f}, {h}, {w}, {mode}, {cols}, {rows_}, {n}, {len(pl)}, {seg0}, "
f"0x{g_fnv:016x}ull, 0x{l_fnv:016x}ull }},")
for gh, gw, real in pl:
segs.append((gh, gw, real))
seg0 += len(pl)
if report:
report.write(f"picture {f} {w}x{h} mode {'gundam' if mode == 1 else 'base@%d' % size}: "
f"reference grid {cols}x{rows_} ({cols * rows_} tiles), placeholders {n}; "
f"item plan {len(pl)} segments, {total} rows: MATCH\n")
if cols * rows_ > 1:
report.write(f" tiles row-major {cols} wide x {rows_} tall, one line of "
f"{10 * cols} features + 1 newline per feature row: "
f"{(10 * cols + 1) * 10 * rows_} placeholders\n")
L.append("static const GoldUocrPic kUocrPictures[] = {")
L += rows
L.append("};")
L.append("struct GoldUocrSeg { int32_t h, w, real; };")
L.append("static const GoldUocrSeg kUocrSegs[] = {")
for gh, gw, real in segs:
L.append(f" {{ {gh}, {gw}, {real} }},")
L.append("};")
L.append("")
# ---- the ratios' set order: the reference's tie resolution, area by area
target = set((i, j) for n in range(MIN_PATCHES, MAX_PATCHES + 1) for i in range(1, n + 1)
for j in range(1, n + 1) if i * j <= MAX_PATCHES and i * j >= MIN_PATCHES)
ordered = sorted(target, key=lambda t: t[0] * t[1])
tall_last = []
for (i, j) in sorted(target):
if i < j and (j, i) in target and ordered.index((i, j)) > ordered.index((j, i)):
tall_last.append((i, j))
# ---- Pillow's bicubic resize: both pass orders (its Resample.c runs the vertical pass first when
# the height shrinks by more than twice what the width does), the one-axis forms and an exact tie.
L.append("/* Pillow's Image.resize(BICUBIC) of a splitmix picture: its two-pass order is part of the")
L.append(" * function (the intermediate rounds to eight bits). */")
L.append("struct GoldUocrResize { int32_t sh, sw, dh, dw; uint64_t fnv; };")
L.append("static const GoldUocrResize kUocrResize[] = {")
resize_cases = [(0, 2400, 400, 1024, 171), (0, 300, 300, 90, 100), (0, 400, 300, 171, 1024),
(0, 300, 400, 1024, 171), (0, 400, 1000, 200, 500), (0, 1000, 400, 200, 300),
(0, 700, 500, 650, 470), (0, 500, 700, 640, 650), (0, 320, 480, 320, 480),
(0, 240, 320, 160, 320), (0, 240, 320, 240, 200), (0, 64, 48, 1024, 1024)]
for f, sh, sw, dh, dw in resize_cases:
im = picture(f, sh, sw)
r = np.asarray(im.resize((dw, dh), Image.Resampling.BICUBIC))
L.append(f" {{ {sh}, {sw}, {dh}, {dw}, 0x{fnv(r):016x}ull }},")
L.append("};")
L.append("")
L.append("/* The transposed pairs whose tall side the reference's set visits last. */")
L.append("struct GoldUocrTie { int32_t c, r; };")
L.append("static const GoldUocrTie kUocrTallLast[] = {")
L.append(" " + " ".join(f"{{{c}, {r}}}," for c, r in tall_last))
L.append("};")
L.append(f"static const int32_t kUocrNTallLast = {len(tall_last)};")
if report:
# The multi-page form: the reference concatenates the pages' runs at one <image>.
pair = [picture(0, 500, 300), picture(1, 1400, 900)]
per = [expand_base(im, 1024)[0] for im in pair]
report.write(f"multi-page pair (infer_multi, 2 pages at one marker, image_size 1024): "
f"{per[0]} + {per[1]} = {sum(per)} placeholders, "
f"{'MATCH' if per == [273, 273] else 'MISMATCH'}\n")
open(out, "w").write("\n".join(L) + "\n")
print("wrote", out, len(L), "lines;", len(pics), "pictures,", len(segs), "segments,",
len(tall_last), "tie pairs")
+346
View File
@@ -25,7 +25,9 @@
#include "lfm2_golden.h"
#include "mm/resample.h"
#include "mm_golden.h"
#include "rad_builder.h"
#include "rad_plugin.h"
#include "uocr_golden.h"
#include <algorithm>
#include <cmath>
@@ -1309,4 +1311,348 @@ TEST(a_resampled_stream_is_its_tone_whether_pushed_whole_or_in_pieces) {
CHECK(!mm::Resampler::takes(23999));
}
/* ================================================================== Unlimited-OCR
*
* The checkpoint's two picture modes, from its own remote code (tests/mkuocrgolden.py): the tile
* grid dynamic_preprocess chooses (its ratio set sorted by area, ties in the set's order), the
* placeholders that replace the picture (infer()'s global view plus crops; infer_multi()'s page),
* and the pixels of the global view and of the tile mosaic, in the order Item::patch_raster
* stages them: row by row, each patch (channel, y, x).
*/
/* The checkpoint's processor configuration, as a converted container states it. */
VisionConfig uocr_cfg() {
VisionConfig c;
c.family = Family::UnlimitedOcr;
c.patch = kUocrPatch;
c.temporal = 1;
c.merge = kUocrDownsample;
c.downsample = kUocrDownsample;
c.base_size = kUocrBaseSize;
c.image_size = kUocrBaseSize;
c.tile = kUocrTile;
c.min_tiles = kUocrMinTiles;
c.max_tiles = kUocrMaxTiles;
c.crop_mode = kUocrCropMode;
c.tok_image = kUocrImageToken;
c.max_patches = 16384; /* the server's --mm-max-patches default */
const int64_t f2 = (int64_t)c.factor() * c.factor();
c.image_min_pixels = c.video_min_pixels = f2;
c.image_max_pixels = c.video_max_pixels = (int64_t)c.base_size * c.base_size;
c.min_frames = 1;
return c;
}
int32_t uocr_marker(const std::string& s) { return s == "<image>" ? kUocrImageToken : -1; }
/* A segment's patches in raster order, its first `real_w` patches a row: the tensor the reference
* holds for that view, patch by patch. */
std::vector<uint16_t> segment_pixels(const Item& it, int32_t s, int32_t real_w) {
const int64_t pd = it.patch_dim;
const int32_t gh = it.seg_h(s), gw = it.seg_w(s);
const int64_t p0 = it.patch_at(s);
std::vector<uint16_t> out;
out.reserve((size_t)gh * (size_t)real_w * (size_t)pd);
for (int32_t py = 0; py < gh; ++py)
for (int32_t px = 0; px < real_w; ++px) {
const uint16_t* p = it.pixels.data() + (p0 + (int64_t)py * gw + px) * pd;
out.insert(out.end(), p, p + pd);
}
return out;
}
/* The container's model_type selects the family; a key it does not carry takes the reference's
* default, so a container converted before the tower landed still states a processor. */
TEST(unlimitedocr_configures_itself_from_the_container) {
const char* keys[] = { "model_type", "preprocessor.crop_to_patches", "preprocessor.max_patches",
"preprocessor.min_patches", "preprocessor.resample",
"preprocessor.size.height", "preprocessor.size.width",
"preprocessor.tile_size", "processor.downsample_ratio",
"processor.image_token", "processor.patch_size" };
const char* vals[] = { "unlimited_ocr", "true", "32", "2", "3", "1024", "1024", "640", "4",
"<image>", "16" };
RadModelMeta m{};
m.n_kv = (int)(sizeof keys / sizeof keys[0]);
m.kv_key = keys;
m.kv_val = vals;
VisionConfig c;
std::string why;
REQUIRE_EQ(c.from_meta(m, &why), RAD_OK);
CHECK(c.family == Family::UnlimitedOcr);
CHECK_EQ(c.patch, 16);
CHECK_EQ(c.downsample, 4);
CHECK_EQ(c.merge, 4);
CHECK_EQ(c.temporal, 1);
CHECK_EQ(c.base_size, 1024);
CHECK_EQ(c.image_size, 1024);
CHECK_EQ(c.tile, 640);
CHECK_EQ(c.min_tiles, 2);
CHECK_EQ(c.max_tiles, 32);
CHECK(c.crop_mode);
CHECK_EQ(c.factor(), 64);
CHECK_EQ(c.patch_dim(), (int64_t)3 * 16 * 16);
CHECK_EQ(c.mean[0], 0.5f);
CHECK_EQ(c.stdv[2], 0.5f);
CHECK(c.image_token == "<image>");
/* Only model_type: every processor key takes the reference's default. */
const char* one_key[] = { "model_type" };
const char* one_val[] = { "unlimited_ocr" };
RadModelMeta mt{};
mt.n_kv = 1;
mt.kv_key = one_key;
mt.kv_val = one_val;
VisionConfig d;
REQUIRE_EQ(d.from_meta(mt, &why), RAD_OK);
CHECK_EQ(d.patch, 16);
CHECK_EQ(d.downsample, 4);
CHECK_EQ(d.base_size, 1024);
CHECK_EQ(d.image_size, 1024);
CHECK_EQ(d.tile, 640);
CHECK_EQ(d.min_tiles, 2);
CHECK_EQ(d.max_tiles, 32);
CHECK(d.crop_mode);
CHECK(d.image_token == "<image>");
/* PIL's bicubic is the only filter this processor stages. */
const char* bad_key[] = { "model_type", "preprocessor.resample" };
const char* bad_val[] = { "unlimited_ocr", "2" };
RadModelMeta mb{};
mb.n_kv = 2;
mb.kv_key = bad_key;
mb.kv_val = bad_val;
VisionConfig b;
CHECK_EQ(b.from_meta(mb, &why), RAD_E_UNSUPPORTED);
}
/* The transposed ratios whose tall side the reference's Python set visits last, which is what its
* tie rule needs beyond "the wider grid wins": the table in core/mm/processor.cpp must be the
* golden's, pair for pair. */
TEST(unlimitedocr_tie_order_is_the_references) {
int32_t listed = 0;
for (int32_t c = 1; c <= kUocrMaxTiles; ++c)
for (int32_t r = c + 1; r <= kUocrMaxTiles; ++r) {
if ((int64_t)c * r < kUocrMinTiles || (int64_t)c * r > kUocrMaxTiles) continue;
bool want = false;
for (int32_t k = 0; k < kUocrNTallLast; ++k)
if (kUocrTallLast[k].c == c && kUocrTallLast[k].r == r) want = true;
if (want) ++listed;
if (uocr_tall_last(c, r) != want)
std::fprintf(stderr, " pair %dx%d: %s last here, %s in the reference\n", c, r,
uocr_tall_last(c, r) ? "tall" : "wide",
want ? "tall" : "wide");
CHECK_EQ((int)uocr_tall_last(c, r), (int)want);
}
CHECK_EQ(listed, kUocrNTallLast);
}
/* dynamic_preprocess's grid for a sweep of shapes, the exact ties of its ratio set included. */
TEST(unlimitedocr_tile_grids_are_the_references) {
for (const GoldUocrGrid& g : kUocrGrid) {
int32_t cols = 1, rows = 1;
/* The reference asks dynamic_preprocess only for a picture larger than one tile. */
if (g.w > kUocrTile || g.h > kUocrTile)
uocr_grid(g.h, g.w, kUocrMinTiles, kUocrMaxTiles, kUocrTile, &cols, &rows);
if (cols != g.cols || rows != g.rows)
std::fprintf(stderr, " picture %lldx%lld: grid %dx%d, reference %dx%d\n",
(long long)g.w, (long long)g.h, cols, rows, g.cols, g.rows);
CHECK_EQ(cols, g.cols);
CHECK_EQ(rows, g.rows);
}
}
/* Whole pictures in both modes: the segments (a line of tiles per tile row, the global view, the
* view separator), every placeholder the picture marker, the pixel count the reference's layout
* has, and the patches of the global view and of the tile mosaic. */
TEST(unlimitedocr_pictures_are_the_references) {
Processor p;
REQUIRE_EQ(p.init(uocr_cfg(), [](const std::string&) { return std::vector<int32_t>{}; },
uocr_marker), RAD_OK);
const int32_t q = kUocrTile / kUocrPatch;
for (const GoldUocrPic& g : kUocrPictures) {
ImageMode mode;
if (g.mode == 1) {
mode.kind = ImageMode::Gundam;
} else {
mode.kind = ImageMode::Base;
mode.image_size = g.mode == 2 ? kUocrBaseSize : kUocrTile;
}
std::shared_ptr<Item> it;
std::string why;
const int rc = p.image_from(frame(g.f, g.h, g.w), &it, &why, mode);
if (rc < 0) std::fprintf(stderr, " %dx%d mode %d: %s\n", g.w, g.h, g.mode, why.c_str());
CHECK_OK(rc);
REQUIRE(it != nullptr);
REQUIRE_EQ(it->n_seg, g.n_seg);
REQUIRE_EQ((int64_t)it->expand.size(), (int64_t)g.n_ids);
CHECK_EQ(it->n_rows(), (int64_t)g.n_ids);
REQUIRE_EQ(it->seg_at.size(), (size_t)it->n_seg);
for (int32_t v : it->expand) CHECK_EQ(v, kUocrImageToken);
CHECK(it->rope_1d);
CHECK(it->patch_raster);
int32_t cols = 0, rows = 0;
for (int32_t s = 0; s < it->n_seg; ++s) {
const GoldUocrSeg& gs = kUocrSegs[g.seg0 + s];
CHECK_EQ(it->seg_h(s), gs.h);
CHECK_EQ(it->seg_w(s), gs.w);
CHECK_EQ(it->seg_at[(size_t)s], (int32_t)it->row_at(s));
const int64_t np = it->patch_at(s + 1) - it->patch_at(s);
CHECK_EQ(np, (int64_t)gs.h * gs.w);
if (gs.h == q && s + 2 < it->n_seg) { /* a line of tiles */
if (cols) { CHECK_EQ(cols, gs.real / q); }
cols = gs.real / q;
rows += 1;
}
/* Raster order: patch k of a segment sits at (k / w, k % w). */
std::vector<int32_t> planes((size_t)(4 * np));
it->coords(it->patch_at(s), np, planes.data());
for (int64_t k = 0; k < np; ++k) {
CHECK_EQ(planes[(size_t)k], (int32_t)(k / gs.w));
CHECK_EQ(planes[(size_t)(np + k)], (int32_t)(k % gs.w));
CHECK_EQ(planes[(size_t)(2 * np + k)], gs.h);
CHECK_EQ(planes[(size_t)(3 * np + k)], gs.w);
}
}
const bool tiled_ref = g.mode == 1 && g.cols * g.rows > 1;
if (cols != (tiled_ref ? g.cols : 0) || rows != (tiled_ref ? g.rows : 0))
std::fprintf(stderr, " picture %dx%d mode %d: %d lines of %d tiles, reference %dx%d\n",
g.w, g.h, g.mode, rows, cols, g.cols, g.rows);
CHECK_EQ(cols, tiled_ref ? g.cols : 0);
CHECK_EQ(rows, tiled_ref ? g.rows : 0);
/* The global view, then the mosaic of the crops (if any). */
const int32_t sg = it->n_seg - 2;
const GoldUocrSeg& gg = kUocrSegs[g.seg0 + sg];
if (fnv(segment_pixels(*it, sg, gg.real)) != g.global_fnv)
std::fprintf(stderr, " picture %dx%d mode %d: the global view's patches differ\n",
g.w, g.h, g.mode);
CHECK_EQ(fnv(segment_pixels(*it, sg, gg.real)), g.global_fnv);
std::vector<uint16_t> local;
for (int32_t s = 0; s < sg; ++s) {
const std::vector<uint16_t> v = segment_pixels(*it, s, kUocrSegs[g.seg0 + s].real);
local.insert(local.end(), v.begin(), v.end());
}
if (g.local_fnv) {
if (fnv(local) != g.local_fnv)
std::fprintf(stderr, " picture %dx%d mode %d: the crops' patches differ\n",
g.w, g.h, g.mode);
CHECK_EQ(fnv(local), g.local_fnv);
} else {
CHECK(local.empty());
}
/* The token count is the reference's arithmetic. */
CHECK_EQ(uocr_tokens(p.config(), mode, g.cols, g.rows), (int64_t)g.n_ids);
}
}
/* Pillow's antialiased bicubic runs its two passes in its own order (libImaging/Resample.c: the
* vertical one first when the height shrinks by more than twice what the width does) and rounds
* the intermediate to eight bits; this pins the order at sizes where the choice changes the
* picture, since a one-pixel difference is invisible in a summary and visible to the model. */
TEST(pillow_bicubic_resizes_in_the_references_pass_order) {
for (const GoldUocrResize& g : kUocrResize) {
Frame out;
resize_bicubic(frame(0, g.sh, g.sw), g.dw, g.dh, &out);
CHECK_EQ(out.w, g.dw);
CHECK_EQ(out.h, g.dh);
if (fnv(out.rgb) != g.fnv)
std::fprintf(stderr, " %dx%d -> %dx%d: pixels differ\n", g.sw, g.sh, g.dw, g.dh);
CHECK_EQ(fnv(out.rgb), g.fnv);
}
}
/* The runs: one per segment, every token the picture marker, and a 1-D rotary that gives each
* placeholder its own position. The reference's assembled order is the item's row order -- the
* local lines, the global view's lines, then the view separator. */
TEST(unlimitedocr_runs_follow_the_reference_layout) {
Processor p;
REQUIRE_EQ(p.init(uocr_cfg(), [](const std::string&) { return std::vector<int32_t>{}; },
uocr_marker), RAD_OK);
ImageMode gundam;
gundam.kind = ImageMode::Gundam;
std::shared_ptr<Item> it;
std::string why;
CHECK_OK(p.image_from(frame(1, 900, 1400), &it, &why, gundam));
REQUIRE(it != nullptr);
auto pm = std::make_shared<PromptMedia>();
pm->items.push_back({ it, 1 }); /* after one text token */
pm->layout();
REQUIRE_EQ(pm->rope.runs.size(), (size_t)it->n_seg);
for (int32_t s = 0; s < it->n_seg; ++s) {
const RopeLayout::Run& r = pm->rope.runs[(size_t)s];
CHECK(r.flat);
CHECK_EQ(r.tok, 1 + it->seg_at[(size_t)s]);
CHECK_EQ(r.n, (int32_t)(it->row_at(s + 1) - it->row_at(s)));
CHECK_EQ(r.base, 1 + it->seg_at[(size_t)s]);
CHECK_EQ(r.shift, 0);
CHECK_EQ(r.item, 0);
CHECK_EQ(r.row0, (int32_t)it->row_at(s));
}
const int64_t n = (int64_t)it->expand.size();
for (int64_t i = 0; i < n; ++i) {
int32_t pos[3];
pm->rope.at(1 + i, pos);
CHECK_EQ(pos[0], (int32_t)(1 + i));
CHECK_EQ(pos[1], (int32_t)(1 + i));
CHECK_EQ(pos[2], (int32_t)(1 + i));
}
/* The reference's arithmetic, spelled out: the global view's 16 lines of 16 features with a
* newline each plus the separator, then the local grid's lines (a newline after each). */
const VisionConfig& c = p.config();
CHECK_EQ(uocr_tokens(c, gundam, 1, 1), (int64_t)273);
ImageMode base;
base.kind = ImageMode::Base;
CHECK_EQ(uocr_tokens(c, base, 1, 1), (int64_t)273);
ImageMode page640;
page640.kind = ImageMode::Base;
page640.image_size = kUocrTile;
CHECK_EQ(uocr_tokens(c, page640, 1, 1), (int64_t)111);
CHECK_EQ(uocr_tokens(c, gundam, 3, 2), (int64_t)273 + (int64_t)(10 * 3 + 1) * 20);
CHECK_EQ(uocr_tokens(c, gundam, 4, 3), (int64_t)273 + (int64_t)(10 * 4 + 1) * 30);
/* A request may restate the global view's side, but not cut crops at another tile or pad a
* page to a side that is not whole merged patches. */
bool crop = false;
int32_t bs = 0, is = 0;
ImageMode b2048;
b2048.kind = ImageMode::Gundam;
b2048.base_size = 2048;
CHECK_EQ(uocr_mode(c, b2048, &crop, &bs, &is, &why), RAD_OK);
CHECK_EQ(uocr_tokens(c, b2048, 1, 1), (int64_t)(32 + 1) * 32 + 1);
ImageMode tile512;
tile512.kind = ImageMode::Gundam;
tile512.image_size = 512;
CHECK_EQ(uocr_mode(c, tile512, &crop, &bs, &is, &why), RAD_E_INVAL);
ImageMode odd;
odd.kind = ImageMode::Base;
odd.image_size = 700;
CHECK_EQ(uocr_mode(c, odd, &crop, &bs, &is, &why), RAD_E_INVAL);
ImageMode ok640;
ok640.kind = ImageMode::Base;
ok640.image_size = 640;
REQUIRE_EQ(uocr_mode(c, ok640, &crop, &bs, &is, &why), RAD_OK);
CHECK(!crop);
CHECK_EQ(is, 640);
/* The multi-page form: two pages at the base mode are two runs of 273, back to back. */
ImageMode base2;
base2.kind = ImageMode::Base;
std::shared_ptr<Item> a, b;
CHECK_OK(p.image_from(frame(0, 300, 500), &a, &why, base2));
CHECK_OK(p.image_from(frame(1, 900, 1400), &b, &why, base2));
auto mp = std::make_shared<PromptMedia>();
mp->items.push_back({ a, 1 });
mp->items.push_back({ b, 1 + (int32_t)a->expand.size() });
mp->layout();
CHECK_EQ((int64_t)mp->rope.runs.size(), (int64_t)4);
CHECK_EQ(a->expand.size(), (size_t)273);
CHECK_EQ(b->expand.size(), (size_t)273);
int32_t pos[3];
mp->rope.at(1 + 273 + 100, pos);
CHECK_EQ(pos[0], (int32_t)(1 + 273 + 100));
}
RAD_TEST_MAIN()
+281
View File
@@ -0,0 +1,281 @@
/* p4b_kv_ring_test.cpp -- RAD_KV_RING, the declaration-side of R-SWA (Unlimited-OCR P4b).
*
* RAD_KV_RING is RAD_KV_WINDOW whose floor is each sequence's own prompt length: the group is
* sized for the whole context plus one ring a sequence (the ring among the fixed costs), never
* capped at a declared window, never given a window snapshot, and never checkpointed. These
* tests pin the core's admission of the kind -- the builder, the KV plan, and the chunk geometry
* -- and that a fixed-window (RAD_KV_WINDOW) group beside it is exactly what it was.
*/
#include "rad_test.h"
#include "build/rad_build.h"
#include "mem/kv.h"
#include "mem/pools.h"
#include "rad_internal.h"
#include "sched/geometry.h"
#include <cstring>
#include <vector>
using namespace rad;
/* Handle 0 is the null group. */
enum : int32_t { G_NULL = 0, G_RING = 1, G_FIXED = 2 };
static Config ring_config(int64_t max_tok = 128) {
Config c;
c.vram_weights_mib = 1;
c.vram_kv_mib = 4;
c.gpu_headroom_mib = 1;
c.host_pool_mib = 0;
c.max_seqs = 4;
c.max_tok = max_tok;
c.max_ctx = 4096;
c.checkpoint_interval = 512;
c.prefix_cache = true;
return c;
}
/* One layer at `block`; the page is block * n_head_kv(2) * head_dim(8) * bf16(2) * K,V. */
static KVGroupInfo ring_group(int64_t block, int64_t w, int layer = 0) {
KVGroupInfo k;
k.name = "rswa";
k.decl.kind = RAD_KV_RING;
k.decl.dtype = RAD_BF16;
k.decl.n_head_kv = 2;
k.decl.head_dim = 8;
k.decl.window = w;
k.block_size = block;
k.layers = { layer };
return k;
}
static KVGroupInfo fixed_window_group(int64_t block, int64_t w, int layer = 0) {
KVGroupInfo k;
k.name = "swa";
k.decl.kind = RAD_KV_WINDOW;
k.decl.dtype = RAD_BF16;
k.decl.n_head_kv = 2;
k.decl.head_dim = 8;
k.decl.window = w;
k.block_size = block;
k.layers = { layer };
return k;
}
static std::vector<KVGroupInfo> one(const KVGroupInfo& g) {
return { KVGroupInfo{}, g };
}
static int configure_pools(Pools& p, const Config& c) {
return p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator());
}
/* A RAD_KV_RING group plans as a runtime window without anyone declaring it first (the kind is
* the declaration), and with the engine's declare_runtime_window() call it plans identically.
* The ring is a fixed cost: one ring a sequence on top of the context the split sizes. */
TEST(a_ring_group_plans_as_a_runtime_window_with_the_ring_in_the_fixed_cost) {
const int64_t B = 128, W = 128;
const KVGroupInfo grp = ring_group(B, W);
const std::vector<KVGroupInfo> g = one(grp);
const Config cfg = ring_config();
const int64_t page = B * 2 * 8 * 2 * 2; /* 8192 bytes */
const int64_t ring_cost = (int64_t)cfg.max_seqs * ((W + B - 1) / B) * page;
/* Without declare_runtime_window: the kind alone turns the plan over to runtime windows. */
{
Pools pools;
REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK);
KVManager kv;
CHECK_OK(kv.configure(g, cfg, pools.kv()));
const KVGroupPlan* p = kv.plan(G_RING);
REQUIRE(p);
CHECK(p->runtime_win);
CHECK_EQ(p->runtime_tokens, W);
CHECK_EQ(kv.runtime_window_tokens(G_RING), W);
/* No window snapshot, so nothing to checkpoint: the window is each sequence's own. */
CHECK(!p->win_snap);
CHECK(!kv.has_window_snapshot());
CHECK_EQ(kv.checkpoint_bytes(), 0ll);
/* Sized for the whole context plus the ring a sequence, not capped at window_blocks. */
CHECK_EQ(kv.ceiling(cfg.max_ctx),
kv.fixed_bytes() + (int64_t)cfg.max_seqs * (cfg.max_ctx / B) * page);
/* The ring is in the fixed cost (the plan's one alignment unit is for the group). */
CHECK_EQ(kv.fixed_bytes(), (int64_t)RAD_ALIGN_UNIT + ring_cost);
/* The report calls it a ring, not a fixed window. */
CHECK(has(kv.report(), "ring"));
CHECK(has(kv.report(), "runtime window W=128"));
}
/* The engine's path: declare, then plan. Same plan, and the declaration is idempotent
* against the kind's own. */
{
Pools pools;
REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK);
KVManager kv;
CHECK_OK(kv.declare_runtime_window(G_RING, W));
CHECK_OK(kv.configure(g, cfg, pools.kv()));
const KVGroupPlan* p = kv.plan(G_RING);
REQUIRE(p);
CHECK(p->runtime_win);
CHECK_EQ(p->runtime_tokens, W);
CHECK_EQ(kv.fixed_bytes(), (int64_t)RAD_ALIGN_UNIT + ring_cost);
CHECK(!kv.has_window_snapshot());
/* A ring carries no declared-window cap; window_blocks still reports the ring's own
* rounding (rarely read: every plan path gates on runtime_win first). */
CHECK_EQ(p->window_blocks, W / B + 1);
}
/* A second W would contradict the ring already in the fixed cost. */
{
KVManager kv;
CHECK_OK(kv.plan_groups(g, cfg));
int rc = 0;
const std::string why = stderr_of([&] { rc = kv.declare_runtime_window(G_RING, W * 2); });
CHECK_EQ(rc, RAD_E_INVAL);
CHECK(has(why, "already carries a runtime window"));
CHECK_EQ(kv.declare_runtime_window(G_RING, W), RAD_OK);
}
}
/* A fixed-width window group beside a ring group keeps today's plan exactly, so gemma4_bf16's
* recycling and window snapshot are untouched by R-SWA's presence. */
TEST(a_fixed_window_group_is_unaffected_beside_a_ring_group) {
const KVGroupInfo ring = ring_group(128, 128, /*layer=*/0);
const KVGroupInfo fixed = fixed_window_group(16, 64, /*layer=*/1);
std::vector<KVGroupInfo> both = { KVGroupInfo{}, ring, fixed };
std::vector<KVGroupInfo> alone = { KVGroupInfo{}, fixed };
Config cfg = ring_config();
cfg.max_tok = 64;
Pools pa, pb;
REQUIRE_EQ(configure_pools(pa, cfg), RAD_OK);
REQUIRE_EQ(configure_pools(pb, cfg), RAD_OK);
KVManager kva, kvb;
CHECK_OK(kva.declare_runtime_window(G_RING, 128));
CHECK_OK(kva.configure(both, cfg, pa.kv()));
CHECK_OK(kvb.configure(alone, cfg, pb.kv()));
const KVGroupPlan* p = kva.plan(G_FIXED); /* index 2: {null, ring, fixed} */
const KVGroupPlan* q = kvb.plan(1); /* the fixed group alone: {null, fixed} */
REQUIRE(p);
REQUIRE(q);
CHECK(!p->runtime_win);
CHECK_EQ(p->runtime_tokens, 0ll);
CHECK(p->win_snap);
CHECK(q->win_snap);
CHECK_EQ(p->window_blocks, q->window_blocks);
CHECK_EQ(p->window_blocks, 64 / 16 + 1);
CHECK_EQ(p->bytes_per_block, q->bytes_per_block);
CHECK_EQ(p->block_size, q->block_size);
/* Only the fixed group's window is checkpointed, and it is the same number either way. */
CHECK_EQ(kva.checkpoint_bytes(), kvb.checkpoint_bytes());
CHECK(kva.has_window_snapshot() == kvb.has_window_snapshot());
/* The ring's own plan is the runtime window, not the fixed one. */
CHECK(kva.plan(G_RING)->runtime_win);
CHECK(!kva.plan(G_RING)->win_snap);
}
/* The chunk geometry must not advertise a window snapshot for a ring: there is none to take, and
* an interval grid would only claim one. A fixed window group keeps it exactly. */
TEST(a_ring_group_gets_no_window_snapshot_geometry) {
Config cfg = ring_config();
Program prog;
prog.kv_groups = one(ring_group(128, 128));
ChunkGeometry geo;
CHECK_OK(chunk_geometry_resolve(prog, cfg, &geo));
CHECK_EQ(geo.attn_block, 128ll);
CHECK_EQ(geo.quantum, 128ll);
CHECK(!geo.window_ckpt);
CHECK_EQ(geo.checkpoint_interval, 0ll);
CHECK(!geo.checkpoints());
/* The same group declared as a fixed window keeps the snapshot geometry (gemma4's). */
Program w;
w.kv_groups = one(fixed_window_group(128, 128));
CHECK_OK(chunk_geometry_resolve(w, cfg, &geo));
CHECK(geo.window_ckpt);
CHECK_EQ(geo.checkpoint_interval, 512ll);
CHECK(geo.checkpoints());
/* A ring beside a fixed window still snapshots the fixed one, as a hybrid always did. */
Program h;
h.kv_groups = { KVGroupInfo{}, ring_group(128, 128, 0), fixed_window_group(128, 128, 1) };
CHECK_OK(chunk_geometry_resolve(h, cfg, &geo));
CHECK_EQ(geo.attn_block, 128ll);
CHECK(geo.window_ckpt);
CHECK_EQ(geo.checkpoint_interval, 512ll);
}
/* ================================================================== the declare phase */
static std::string kernels_dir() { return home() + "/testkernels"; }
static int load_plugins(Registry& r) {
return r.load_dir(kernels_dir(), { "radtest_over", "radtest_base" });
}
static rad_op decl_t_attn(Builder& b) {
const RadParam p[] = { RAD_RANGE("q_len", 1, 16), RAD_INT("head_dim", 128),
RAD_INT("window", 0), RAD_INT("block_size", 16),
RAD_INT("causal", 1), RAD_INT("n_head", 8),
RAD_STR("kv_dtype", "bf16") };
return b.decl_op("t_attn", p, 7, nullptr, 0);
}
static RadModelMeta make_meta() {
RadModelMeta m{};
m.arch_id = "test_arch";
m.name = "test_model";
m.quant = "bf16";
m.n_layers = 2;
m.n_embd = 4096;
return m;
}
static RadBuildCtx make_ctx() {
RadBuildCtx c{};
c.rank = 0;
c.world_size = 1;
c.max_tok = 8192;
c.max_seqs = 256;
c.max_ctx = 4096;
c.scope = "";
return c;
}
/* The ABI admits the kind, its block size still comes off the resolved attention kernel, and its
* page is sized as a paged group's (so KVManager::plan_groups accepts it). */
TEST(the_builder_accepts_a_ring_group) {
Registry reg;
if (load_plugins(reg) < 0) ARTIFACT_MISSING("the test plugins in " + kernels_dir());
Builder b(reg, make_meta(), make_ctx());
RadKVGroupDecl kd{};
kd.kind = RAD_KV_RING;
kd.dtype = RAD_BF16;
kd.window = 128;
kd.n_head_kv = 8;
kd.head_dim = 128;
const rad_kvgroup g = b.decl_kv_group("kv_ring", &kd);
CHECK(g == 1);
CHECK_EQ((int)b.program().kv_groups[g].decl.kind, (int)RAD_KV_RING);
decl_t_attn(b);
/* 16 because the resolved test kernel's constraints say so. */
CHECK_EQ(b.kv_block_size(g), 16);
CHECK_OK(b.bind_layer_kv(0, g));
CHECK_OK(b.bind_layer_kv(1, g));
b.finish();
const KVGroupInfo& gi = b.program().kv_groups[g];
CHECK_EQ(gi.block_size, 16ll);
CHECK_EQ(gi.decl.window, 128ll);
/* One page covers both bound layers, as for a full or fixed-window group. */
CHECK_EQ(gi.bytes_per_block, 2 * 16 * 8 * 128 * 2 * 2);
CHECK_EQ(gi.bytes_per_state, 0ll);
/* Named, not "?". */
CHECK(std::strcmp(bld_kv_kind_name(RAD_KV_RING), "?") != 0);
}
RAD_TEST_MAIN()
+520 -2
View File
@@ -953,8 +953,8 @@ TEST(op_vocabulary) {
"gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm",
"all_reduce", "all_gather",
"embed_lookup", "logits_gemm",
"sample_penalties", "sample_dry", "sample_temp", "sample_topk", "sample_topp",
"sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick",
"sample_penalties", "sample_dry", "sample_ngram_ban", "sample_temp", "sample_topk",
"sample_topp", "sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick",
"sample_argmax", "sample_merge_topk", "sample_logprobs",
/* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane
* sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */
@@ -994,6 +994,8 @@ TEST(op_vocabulary) {
/* LTX-2.5's diffusion decoder: its rotary's voxel coordinates and its neighborhood
* attention. */
"vol_index", "attn_na3d",
/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position. */
"sam_attn",
};
for (const char* op : kOps) {
if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op);
@@ -5099,6 +5101,181 @@ TEST(op_sample_pick_draws_the_specified_uniform) {
CHECK(agree > 60);
}
/* ================================================================== the n-gram ban */
/* Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor, ported straight from
* modeling_unlimitedocr.py:353-383 as the oracle's second formulation. `s` is the row's history
* oldest first; the result marks every global token id it bans. */
static std::vector<char> ref_ngram_banned(const std::vector<int32_t>& s, int n, int window) {
std::vector<char> banned(256, 0);
if (n <= 0 || (int64_t)s.size() < (int64_t)n) return banned;
const int64_t len = (int64_t)s.size();
const int64_t search_start = window > 0 ? std::max<int64_t>(0, len - window) : 0;
const int64_t search_end = len - n + 1;
if (search_end <= search_start) return banned;
std::vector<int32_t> prefix;
if (n > 1) prefix.assign(s.begin() + (size_t)(len - n + 1), s.end());
for (int64_t idx = search_start; idx < search_end; ++idx) {
bool match = true;
for (size_t j = 0; j < prefix.size(); ++j)
if (s[(size_t)(idx + (int64_t)j)] != prefix[j]) { match = false; break; }
if (!match) continue;
const int32_t tok = s[(size_t)(idx + n - 1)];
if (tok >= 0 && tok < (int32_t)banned.size()) banned[(size_t)tok] = 1;
}
return banned;
}
/* The op over one row: returns the banned global ids it wrote as -infinity, and whether every other
* column is bit-for-bit its input. */
static std::vector<int32_t> ref_ngram_op(const std::vector<int32_t>& s, int n, int window,
int n_vocab, bool* untouched_out) {
const int64_t H = 8; /* the history plane's extent in these cases */
T lg(RAD_F32, {1, n_vocab});
std::vector<float> in((size_t)n_vocab);
for (int64_t i = 0; i < n_vocab; ++i) in[(size_t)i] = 0.5f * (float)i - 1.0f;
lg.f(in);
T hist(RAD_I32, {1, H});
std::vector<int64_t> hv((size_t)H, 0);
for (size_t i = 0; i < s.size() && i < (size_t)H; ++i) hv[i] = s[i];
hist.n(hv);
SP sp(1);
sp[0].hist_off = 0;
sp[0].hist_len = (int32_t)std::min<size_t>(s.size(), (size_t)H);
T ng(RAD_I32, {1, 2}); ng.n({ n, window });
A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", n_vocab);
if (run("sample_ngram_ban", a) != RAD_OK) return { -99 };
std::vector<int32_t> banned;
bool untouched = true;
for (int64_t i = 0; i < n_vocab; ++i) {
const float v = lg.at(i);
if (std::isinf(v) && v < 0.0f) banned.push_back((int32_t)i);
else if (std::memcmp(&v, &in[(size_t)i], 4) != 0) untouched = false;
}
if (untouched_out) *untouched_out = untouched;
return banned;
}
/* The reference's banned set and the op's, over:
* - every binary history of length 0..6, n 1..4 and windows 0, 2, 3, 4 and 64. A binary
* alphabet makes repeats and the "abcabc" shapes dense, and lengths short of, equal to and
* longer than n cover the early exits;
* - 200 random histories over five ids, lengths 1..24, n 1..8 and windows 0..16, where the
* window boundary falls inside repeated runs;
* - the named shapes: an n-gram whose last token is the window's last (idx == search_end - 1),
* an n-gram that starts at search_start while an earlier copy starts before it, n == 1 (the
* empty prefix, every window token banned) and n == 0 (off). */
TEST(op_sample_ngram_ban_matches_the_reference_processor) {
int64_t trials = 0, mismatches = 0, bans = 0;
bool all_untouched = true;
auto trial = [&](const std::vector<int32_t>& s_in, int n, int window) {
/* The engine's plane holds the LAST H tokens of the sequence (build_step truncates the
* oldest), so the oracle and the op must both see that span. */
const std::vector<int32_t> s = s_in.size() > 8
? std::vector<int32_t>(s_in.end() - 8, s_in.end())
: s_in;
const int n_vocab = 8;
bool untouched = true;
const std::vector<int32_t> got = ref_ngram_op(s, n, window, n_vocab, &untouched);
if (got.size() == 1 && got[0] == -99) { ++mismatches; return; }
const std::vector<char> want = ref_ngram_banned(s, n, window);
++trials;
bans += (int64_t)got.size();
all_untouched = all_untouched && untouched;
int64_t live = 0;
for (int id = 0; id < n_vocab; ++id) live += want[(size_t)id] ? 1 : 0;
if (live != (int64_t)got.size()) { ++mismatches; return; }
for (int32_t id : got)
if (id < 0 || id >= n_vocab || !want[(size_t)id]) { ++mismatches; return; }
};
/* Every binary history of length 0..6. */
for (int64_t len = 0; len <= 6; ++len) {
for (int64_t bits = 0; bits < (int64_t)1 << len; ++bits) {
std::vector<int32_t> s;
for (int64_t i = 0; i < len; ++i) s.push_back((int32_t)((bits >> i) & 1));
for (int n = 1; n <= 4; ++n)
for (int w : { 0, 2, 3, 4, 64 }) trial(s, n, w);
}
}
/* Random histories over five ids. */
uint32_t rs = 0x9e3779b9u;
for (int it = 0; it < 200; ++it) {
rs = rs * 1664525u + 1013904223u;
const int64_t len = 1 + (int64_t)((rs >> 8) % 24u);
std::vector<int32_t> s((size_t)len);
for (int64_t i = 0; i < len; ++i) {
rs = rs * 1664525u + 1013904223u;
s[(size_t)i] = (int32_t)((rs >> 12) % 5u);
}
rs = rs * 1664525u + 1013904223u;
const int n = 1 + (int)((rs >> 8) % 8u);
rs = rs * 1664525u + 1013904223u;
const int w = (int)((rs >> 8) % 17u);
trial(s, n, w);
}
/* The named shapes. [4,1,2, 4,1,2, 4,1,2] with n 3 and window 6: the newest complete n-gram
* starts exactly at search_end - 1, and the earlier copy at search_start bans the same token;
* window 3 moves search_start so that only the spanning copy is searched. */
trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 6);
trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 3);
trial({ 1, 1, 1, 1, 1, 1 }, 2, 4); /* repeated tokens, every position matches */
trial({ 1, 1, 1, 1, 1, 1 }, 1, 3); /* n 1: the entire window is banned */
trial({ 1, 1, 1, 1, 1, 1 }, 0, 3); /* off */
trial({ 7, 2, 7, 2, 7 }, 2, 0); /* window 0: the whole span */
CHECK(trials > 2500);
CHECK(mismatches == 0);
CHECK(bans > 0);
/* Every column the reference does not ban is bit-for-bit its input: the op writes -infinity
* and nothing else, so penalties and temperature see the same numbers. */
CHECK(all_untouched);
}
/* Off is the default, and off must be invisible to greedy decoding: sample_ngram_ban writes
* nothing for a row with ngram_ban_n 0, so the argmax over the same row is the same token. With
* the ban on, the outcome changes exactly when the ban covers the argmax's token. */
TEST(op_sample_ngram_ban_off_leaves_greedy_decoding_unchanged) {
/* Token 5 is the clear maximum. Its id appears 4 times in the history, so both the ban and the
* penalties have something to do; the ban is off here. */
T hist(RAD_I32, {1, 8}); hist.n({ 5, 1, 5, 2, 5, 3, 5, 1 });
auto greedy = [&](int n, int window, std::vector<float>* after) {
T lg(RAD_F32, {1, 8});
lg.f({ 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f });
SP sp(1);
sp[0].hist_off = 0;
sp[0].hist_len = 8;
T ng(RAD_I32, {1, 2}); ng.n({ n, window });
A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", 8);
CHECK_OK(run("sample_ngram_ban", a));
T tk(RAD_I32, {1});
A b; b.t(lg).t(sp.operand()).t(tk).i("M", 1).i("n_vocab", 8);
CHECK_OK(run("sample_argmax", b));
if (after)
for (int64_t i = 0; i < 8; ++i) after->push_back(lg.at(i));
return tk.iat(0);
};
std::vector<float> off_logits;
CHECK_EQ(greedy(0, 0, &off_logits), 5);
/* Bit-identical to the input: the stage did not run. */
static const float kIn[8] = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f };
for (int64_t i = 0; i < 8; ++i) CHECK(std::memcmp(&off_logits[(size_t)i], &kIn[i], 4) == 0);
/* The history's prefix (5,1) is followed by token 5 at positions 0 and 2 in [5,1,5,2,5,3,5,1]:
* with n 2 the ban covers 5, so greedy moves to the next best (token 7). */
CHECK_EQ(greedy(2, 8, nullptr), 7);
/* A ban that only names other tokens leaves the argmax alone: with n 2 and a one-token window,
* search_start == search_end - 1 is impossible (window 1 < n), so nothing is banned. */
CHECK_EQ(greedy(2, 1, nullptr), 5);
}
/* ================================================================== failure modes */
/* Nothing that did not do the work returns RAD_OK. The engine turns these into a named abort
* rather than a silent fallback (spec §17). */
@@ -7847,6 +8024,11 @@ std::vector<Geo> geometries() {
.s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)),
G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1)
.s("dtype", "f32").i("n_head", 4)),
/* One-row segments, so M is also the segment count (n_seq, the description's hint for
* cu_seqlens). The real grids are op_sam_attn_*'s. */
G("sam_attn", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("grid_h", 1)
.i("grid_w", 1).i("window", 1).i("n_seq", R)
.d("scale", 0.3535533905932738).s("dtype", "bf16")),
G("kv_store", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head_kv", 2).i("block_size", 4)
.s("kv_dtype", "f32")),
G("rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1)
@@ -7914,6 +8096,7 @@ std::vector<Geo> geometries() {
G("logits_gemm", "M", 3, a.i("M", R).i("n_vocab", 20).i("n_embd", 8).s("dtype", "f32")),
G("sample_penalties", "M", 2, a.i("M", R).i("n_vocab", 64)),
G("sample_dry", "M", 2, a.i("M", R).i("n_vocab", 64)),
G("sample_ngram_ban", "M", 2, a.i("M", R).i("n_vocab", 64)),
G("sample_temp", "M", 2, a.i("M", R).i("n_vocab", 64)),
G("sample_topk", "M", 2, a.i("M", R).i("n_vocab", 64)),
G("sample_topp", "M", 2, a.i("M", R).i("n_cand", 16)),
@@ -8497,3 +8680,338 @@ TEST(gather_rows_moves_packed_codes_exactly) {
const float wf[6] = { 0.5f, 1.0f, -2.0f, 6.0f, 0.0f, 4.0f };
for (int i = 0; i < 6; ++i) CHECK_EQ(e.at(i), wf[i]);
}
/* ================================================================== sam_attn
* Unlimited-OCR's SAM tower attention (arch/common/rad_block_sam.h, libref/ref_sam_attn.cpp).
*
* The expected values are a direct port of deepencoder.py's Attention.forward /
* add_decomposed_rel_pos / window_partition in double, not a second call into libref: the padding
* rule, the per-head rel_pos channel dot and the resampling of a table along its row axis each have
* a way to be wrong that an oracle sharing libref's code could not see. */
namespace {
struct SamIn {
int64_t gh = 1, gw = 1, win = 0, nh = 1, hd = 1, nseq = 1;
std::vector<float> q, k, v, rh, rw; /* [M, nh*hd] and [2*L-1, hd], row-major */
int64_t W() const { return nh * hd; }
int64_t rows() const { return nseq * gh * gw; }
int64_t tab() const { return 2 * (win > 0 ? win : (gh > gw ? gh : gw)) - 1; }
};
/* A deterministic draw in [-1, 1]: index-driven, so a wrong pitch or row map reads other numbers. */
static void sam_fill(SamIn& in, uint32_t seed) {
uint32_t s = seed | 1u;
auto next = [&s] { s = s * 1664525u + 1013904223u; return ((s >> 8) & 0xffffu) / 32767.5f - 1.0f; };
in.q.resize((size_t)(in.rows() * in.W()));
in.k.resize(in.q.size());
in.v.resize(in.q.size());
for (auto* x : { &in.q, &in.k, &in.v })
for (auto& f : *x) f = next();
in.rh.resize((size_t)(in.tab() * in.hd));
in.rw.resize(in.rh.size());
for (auto* x : { &in.rh, &in.rw })
for (auto& f : *x) f = 0.1f * next();
}
/* F.interpolate(..., size=want, mode="linear"), align_corners False, over dim 0. */
static std::vector<double> sam_table(const std::vector<float>& raw, int64_t hd, int64_t want) {
const int64_t rows = hd > 0 ? (int64_t)raw.size() / hd : 0;
std::vector<double> out((size_t)(want * hd), 0.0);
const double span = (double)rows / (double)want;
for (int64_t d = 0; d < want; ++d) {
double src = ((double)d + 0.5) * span - 0.5;
if (src < 0.0) src = 0.0;
if (src > (double)(rows - 1)) src = (double)(rows - 1);
const int64_t i0 = (int64_t)src, i1 = i0 + 1 < rows ? i0 + 1 : i0;
const double f = src - (double)i0;
for (int64_t c = 0; c < hd; ++c)
out[(size_t)(d * hd + c)] = raw[(size_t)(i0 * hd + c)] * (1.0 - f) +
raw[(size_t)(i1 * hd + c)] * f;
}
return out;
}
/* `drop_pads` is the WRONG reading of window_partition: pad keys removed from the softmax instead of
* attending as zeros. Used only to prove a case can tell the two apart. */
static std::vector<float> sam_oracle(const SamIn& in, bool drop_pads = false) {
const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows();
const int64_t th = in.win > 0 ? in.win : in.gh, tw = in.win > 0 ? in.win : in.gw;
const std::vector<double> Rh = sam_table(in.rh, in.hd, 2 * th - 1);
const std::vector<double> Rw = sam_table(in.rw, in.hd, 2 * tw - 1);
const double scale = 1.0 / std::sqrt((double)in.hd);
std::vector<float> out((size_t)(M * W), 0.0f);
std::vector<double> logits, acc;
for (int64_t s = 0; s < in.nseq; ++s)
for (int64_t ih = 0; ih < in.gh; ++ih)
for (int64_t iw = 0; iw < in.gw; ++iw) {
const int64_t row = s * R + ih * in.gw + iw;
const int64_t ty = in.win > 0 ? ih / in.win : 0;
const int64_t tx = in.win > 0 ? iw / in.win : 0;
const int64_t lh = ih - ty * th, lw = iw - tx * tw;
for (int64_t h = 0; h < in.nh; ++h) {
const float* qf = &in.q[(size_t)(row * W + h * in.hd)];
logits.clear();
std::vector<int64_t> kvrow;
for (int64_t jh = 0; jh < th; ++jh) {
const double* hrp = &Rh[(size_t)((lh - jh + th - 1) * in.hd)];
double hr = 0.0;
for (int64_t c = 0; c < in.hd; ++c) hr += qf[c] * hrp[c];
for (int64_t jw = 0; jw < tw; ++jw) {
const int64_t kh = ty * th + jh, kw = tx * tw + jw;
const bool real = kh < in.gh && kw < in.gw;
if (drop_pads && !real) continue;
const double* wrp = &Rw[(size_t)((lw - jw + tw - 1) * in.hd)];
double sc = hr;
for (int64_t c = 0; c < in.hd; ++c) sc += qf[c] * wrp[c];
if (real) {
const float* kf = &in.k[(size_t)((s * R + kh * in.gw + kw) * W +
h * in.hd)];
double d = 0.0;
for (int64_t c = 0; c < in.hd; ++c) d += qf[c] * kf[c];
sc += scale * d;
kvrow.push_back(s * R + kh * in.gw + kw);
} else {
kvrow.push_back(-1);
}
logits.push_back(sc);
}
}
double mx = -INFINITY;
for (double v : logits) mx = std::max(mx, v);
double sum = 0.0;
for (double& v : logits) { v = std::exp(v - mx); sum += v; }
acc.assign((size_t)in.hd, 0.0);
for (size_t j = 0; j < logits.size(); ++j) {
if (kvrow[j] < 0) continue;
const float* vf = &in.v[(size_t)(kvrow[j] * W + h * in.hd)];
const double p = logits[j] / sum;
for (int64_t c = 0; c < in.hd; ++c) acc[(size_t)c] += p * vf[c];
}
for (int64_t c = 0; c < in.hd; ++c)
out[(size_t)(row * W + h * in.hd + c)] = (float)acc[(size_t)c];
}
}
return out;
}
/* Run the op; `pitch` > 0 stores every operand at that row pitch (a column slice of a wider
* buffer), 0 uses W. Returns the output read back at the same pitch. */
static std::vector<float> sam_run(const SamIn& in, int64_t pitch, int* rc) {
const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows();
const int64_t ld = pitch > 0 ? pitch : W;
T q(RAD_BF16, { M, ld }), k(RAD_BF16, { M, ld }), v(RAD_BF16, { M, ld }), o(RAD_BF16, { M, ld });
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < W; ++c) {
st_dt(RAD_BF16, q.t.data, r * ld + c, in.q[(size_t)(r * W + c)]);
st_dt(RAD_BF16, k.t.data, r * ld + c, in.k[(size_t)(r * W + c)]);
st_dt(RAD_BF16, v.t.data, r * ld + c, in.v[(size_t)(r * W + c)]);
}
T rh(RAD_BF16, { in.tab(), in.hd }), rw(RAD_BF16, { in.tab(), in.hd });
for (size_t i = 0; i < in.rh.size(); ++i) {
st_dt(RAD_BF16, rh.t.data, (int64_t)i, in.rh[i]);
st_dt(RAD_BF16, rw.t.data, (int64_t)i, in.rw[i]);
}
T cu(RAD_I32, { in.nseq + 1 });
for (int64_t s = 0; s <= in.nseq; ++s) st_int(RAD_I32, cu.t.data, s, s * R);
A a;
/* A pitch wider than W is a strided VIEW of the storage: shape [M, W], stride[0] = ld, which is
* what the tower's column slices of one fused projection are. */
auto view = [&](const T& x) {
RadTensor v = x.t;
v.shape[1] = W;
v.stride[0] = ld;
v.stride[1] = 1;
return v;
};
a.ts.push_back(view(q));
a.ts.push_back(view(k));
a.ts.push_back(view(v));
a.t(cu);
a.ts.push_back(view(o));
a.t(rh).t(rw)
.i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh).i("grid_w", in.gw)
.i("window", in.win).d("scale", 1.0 / std::sqrt((double)in.hd)).s("dtype", "bf16");
*rc = run("sam_attn", a);
std::vector<float> out((size_t)(M * W), 0.0f);
for (int64_t r = 0; r < M; ++r)
for (int64_t c = 0; c < W; ++c) out[(size_t)(r * W + c)] = ld_dt(RAD_BF16, o.t.data, r * ld + c);
return out;
}
/* Compare two [M, W] rows: max absolute difference and the number outside 2e-3 + 2e-2 * |want|. */
static void sam_cmp(const std::vector<float>& got, const std::vector<float>& want, float* maxd,
int64_t* bad) {
*maxd = 0.0f;
*bad = 0;
for (size_t i = 0; i < want.size(); ++i) {
const float d = std::fabs(got[i] - want[i]);
if (d > *maxd) *maxd = d;
if (d > 2e-3f + 2e-2f * std::fabs(want[i])) ++*bad;
}
}
} /* namespace */
/* One row, one key: the softmax is 1 and the output is v, bit for bit after bf16 rounding. The same
* with window 1 over a 1x3 grid, where every row is a tile of its own. */
TEST(op_sam_attn_single_key_returns_v) {
SamIn one;
one.gh = one.gw = 1; one.win = 1; one.nh = 1; one.hd = 4;
one.q = { 3.0f, -1.0f, 0.5f, 2.0f };
one.k = { 1.0f, 2.0f, 3.0f, 4.0f };
one.v = { 0.5f, -1.0f, 2.0f, 0.25f };
one.rh.assign(4, 0.0f);
one.rw.assign(4, 0.0f);
int rc = 0;
std::vector<float> got = sam_run(one, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
for (int64_t c = 0; c < 4; ++c) CHECK_EQ(got[(size_t)c], one.v[(size_t)c]);
SamIn strip = one;
strip.gh = 1; strip.gw = 3;
strip.q = { 1, 2, 3, 4, -1, 0, 1, -2, 0.5f, 0.5f, 0.5f, 0.5f };
strip.k = { 1, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2 };
strip.v = { 0.5f, 0.25f, 0.125f, 0.0625f, -0.5f, -0.25f, -0.125f, -0.0625f,
9.0f, 8.0f, 7.0f, 6.0f };
strip.rh.assign(4, 0.25f);
strip.rw.assign(4, -0.25f);
got = sam_run(strip, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
for (int64_t i = 0; i < 12; ++i) CHECK_EQ(got[(size_t)i], strip.v[(size_t)i]);
}
/* Window 14 over 16x16: the grid pads to 28x28, so the last two rows and columns of the last window
* are ZERO keys that still take part in the softmax. Compared against the double port, then against
* the port with the pads removed: the two differ, which is what makes this case able to see the
* rule. */
TEST(op_sam_attn_windowed_matches_the_reference_port) {
SamIn in;
in.gh = 16; in.gw = 16; in.win = 14; in.nh = 2; in.hd = 8;
sam_fill(in, 0x51ed2701u);
int rc = 0;
const std::vector<float> got = sam_run(in, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
float maxd = 0.0f; int64_t bad = 0;
const std::vector<float> want = sam_oracle(in);
sam_cmp(got, want, &maxd, &bad);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
const std::vector<float> nopad = sam_oracle(in, true);
float pad_max = 0.0f;
for (size_t i = 0; i < nopad.size(); ++i)
pad_max = std::max(pad_max, std::fabs(nopad[i] - want[i]));
CHECK(pad_max > 1e-3f); /* the case can tell the two rules apart */
}
/* Window 0: the whole segment is one tile, over a square grid and over a 6x10 one whose rel_pos
* tables are 2*10-1 rows long and must be resampled to 2*6-1 for the row axis. */
TEST(op_sam_attn_global_and_non_square) {
SamIn sq;
sq.gh = 16; sq.gw = 16; sq.win = 0; sq.nh = 2; sq.hd = 8;
sam_fill(sq, 0xa341316cu);
int rc = 0;
float maxd = 0.0f; int64_t bad = 0;
sam_cmp(sam_run(sq, 0, &rc), sam_oracle(sq), &maxd, &bad);
CHECK_EQ(rc, (int)RAD_OK);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
SamIn ns;
ns.gh = 6; ns.gw = 10; ns.win = 0; ns.nh = 3; ns.hd = 4;
sam_fill(ns, 0x7f4a7c15u);
CHECK_EQ(ns.tab(), 19LL);
sam_cmp(sam_run(ns, 0, &rc), sam_oracle(ns), &maxd, &bad);
CHECK_EQ(rc, (int)RAD_OK);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
}
/* Two segments: each is one tile (window 0). The second segment's rows are computed from its own
* data only, so changing the first segment's q/k/v must leave them bit for bit unchanged while the
* first segment's move. */
TEST(op_sam_attn_segments_are_independent) {
SamIn in;
in.gh = 8; in.gw = 8; in.win = 0; in.nh = 2; in.hd = 8; in.nseq = 2;
sam_fill(in, 0x2545f491u);
int rc = 0;
const std::vector<float> base = sam_run(in, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
float maxd = 0.0f; int64_t bad = 0;
sam_cmp(base, sam_oracle(in), &maxd, &bad);
CHECK_EQ(bad, 0LL);
CHECK(maxd < 2e-3f);
SamIn alt = in;
for (int64_t i = 0; i < 64 * in.W(); ++i) { /* the first segment's rows */
alt.q[(size_t)i] = -alt.q[(size_t)i];
alt.k[(size_t)i] += 0.25f;
}
const std::vector<float> moved = sam_run(alt, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
const size_t half = base.size() / 2;
bool first_changed = false, second_same = true;
for (size_t i = 0; i < half; ++i)
first_changed |= base[i] != moved[i];
for (size_t i = half; i < base.size(); ++i)
second_same &= base[i] == moved[i];
CHECK(first_changed);
CHECK(second_same);
}
/* The tower's q/k/v are the three column slices of one fused projection, so every operand is read
* at a row pitch wider than W. The result must be bit-identical to the dense-pitch one. */
TEST(op_sam_attn_reads_at_a_row_pitch) {
SamIn in;
in.gh = 16; in.gw = 16; in.win = 14; in.nh = 2; in.hd = 8;
sam_fill(in, 0x1234567u);
int rc = 0;
const std::vector<float> dense = sam_run(in, 0, &rc);
CHECK_EQ(rc, (int)RAD_OK);
const std::vector<float> strided = sam_run(in, in.W() + 3, &rc);
CHECK_EQ(rc, (int)RAD_OK);
for (size_t i = 0; i < dense.size(); ++i) CHECK_EQ(strided[i], dense[i]);
}
/* Refusals: a segment that is not one grid, an absent table, a negative window, a zero head. */
TEST(op_sam_attn_refuses_malformed_geometry) {
SamIn in;
in.gh = 4; in.gw = 4; in.win = 0; in.nh = 1; in.hd = 4; in.nseq = 2;
sam_fill(in, 0x9e3779b9u);
const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows();
auto build = [&](T& q, T& k, T& v, T& cu, T& o, T& rh, T& rw, A& a, int64_t window) {
a.t(q).t(k).t(v).t(cu).t(o).t(rh).t(rw)
.i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh)
.i("grid_w", in.gw).i("window", window).d("scale", 0.5).s("dtype", "bf16");
};
T q(RAD_BF16, { M, W }), k(RAD_BF16, { M, W }), v(RAD_BF16, { M, W }), o(RAD_BF16, { M, W });
q.f(in.q); k.f(in.k); v.f(in.v);
T rh(RAD_BF16, { in.tab(), in.hd }), rw(RAD_BF16, { in.tab(), in.hd });
rh.f(in.rh); rw.f(in.rw);
/* cu says the first segment is half a grid. */
T cu_short(RAD_I32, { 3 }); cu_short.n({ 0, R / 2, M });
A a1; build(q, k, v, cu_short, o, rh, rw, a1, 0);
CHECK_EQ(run("sam_attn", a1), (int)RAD_E_SHAPE);
T cu_ok(RAD_I32, { 3 }); cu_ok.n({ 0, R, M });
A a2; build(q, k, v, cu_ok, o, rh, rw, a2, 0);
CHECK_OK(run("sam_attn", a2));
/* An absent rel_pos table. */
A a3; a3.t(q).t(k).t(v).t(cu_ok).t(o).t(rh).tnull()
.i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh)
.i("grid_w", in.gw).i("window", 0).d("scale", 0.5).s("dtype", "bf16");
CHECK_EQ(run("sam_attn", a3), (int)RAD_E_INVAL);
/* A negative window, and a zero head width. */
A a4; build(q, k, v, cu_ok, o, rh, rw, a4, -1);
CHECK_EQ(run("sam_attn", a4), (int)RAD_E_SHAPE);
A a5; a5.t(q).t(k).t(v).t(cu_ok).t(o).t(rh).t(rw)
.i("M", M).i("head_dim", 0).i("n_head", in.nh).i("grid_h", in.gh)
.i("grid_w", in.gw).i("window", 0).d("scale", 0.5).s("dtype", "bf16");
CHECK_EQ(run("sam_attn", a5), (int)RAD_E_SHAPE);
}
+3
View File
@@ -4619,6 +4619,9 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) {
{ "timings_per_token", { true, json::parse(R"({"stream":true})") } },
{ "return_progress", { true, json::parse(R"({"stream":true})") } },
{ "session_id", { "s", none } }, { "n_probs", { 2, none } },
/* The windowed no-repeat-ngram ban and Unlimited-OCR's picture mode. */
{ "ngram_ban_n", { 35, none } }, { "ngram_window", { 128, none } },
{ "images_config", { "gundam", none } },
{ "messages", { json::parse(R"([{"role":"user","content":"yo"}])"), none } },
{ "tools", { json::parse(R"([{"type":"function","function":{"name":"f"}}])"), none } },
{ "tool_choice", { "auto", none } },
+138
View File
@@ -0,0 +1,138 @@
/* uocr_golden.h -- GENERATED by mkuocrgolden.py from the checkpoint's remote code; do not edit. */
#pragma once
#include <cstdint>
static const int32_t kUocrPatch = 16, kUocrDownsample = 4;
static const int32_t kUocrBaseSize = 1024, kUocrTile = 640;
static const int32_t kUocrMinTiles = 2, kUocrMaxTiles = 32;
static const bool kUocrCropMode = true;
static const int32_t kUocrImageToken = 128815;
struct GoldUocrGrid { int64_t h, w; int32_t cols, rows; };
static const GoldUocrGrid kUocrGrid[] = {
{ 1, 1, 1, 1 },
{ 40, 30, 1, 1 },
{ 100, 100, 1, 1 },
{ 300, 500, 1, 1 },
{ 500, 300, 1, 1 },
{ 640, 640, 1, 1 },
{ 641, 641, 2, 2 },
{ 500, 700, 4, 3 },
{ 700, 500, 3, 4 },
{ 800, 1000, 5, 4 },
{ 1000, 800, 4, 5 },
{ 1024, 1024, 2, 2 },
{ 1280, 1024, 4, 5 },
{ 1024, 1280, 5, 4 },
{ 900, 1400, 3, 2 },
{ 1400, 900, 2, 3 },
{ 2000, 600, 3, 10 },
{ 600, 2000, 10, 3 },
{ 2400, 400, 1, 6 },
{ 400, 2400, 6, 1 },
{ 1080, 1920, 7, 4 },
{ 1920, 1080, 4, 7 },
{ 515, 1031, 2, 1 },
{ 1031, 515, 1, 2 },
{ 100, 5000, 32, 1 },
{ 5000, 100, 1, 32 },
{ 3000, 3000, 5, 5 },
{ 720, 1280, 7, 4 },
{ 800, 640, 4, 5 },
{ 640, 800, 5, 4 },
{ 960, 720, 3, 4 },
{ 720, 960, 4, 3 },
{ 1600, 1200, 3, 4 },
{ 1200, 1600, 4, 3 },
{ 33, 4096, 32, 1 },
{ 4096, 33, 1, 32 },
};
struct GoldUocrPic { int32_t f, h, w, mode; int32_t cols, rows, n_ids; int32_t n_seg, seg0; uint64_t global_fnv, local_fnv; };
static const GoldUocrPic kUocrPictures[] = {
{ 0, 300, 500, 1, 1, 1, 273, 2, 0, 0xabc7f1eabc334430ull, 0x0000000000000000ull },
{ 1, 900, 1400, 1, 3, 2, 893, 4, 2, 0xb068ca82d7ec14c3ull, 0x93a9d30576e60c3eull },
{ 2, 2400, 400, 1, 1, 6, 933, 8, 6, 0x92636385d3bfb221ull, 0x2df135a4207447b6ull },
{ 3, 500, 700, 1, 4, 3, 1503, 5, 14, 0x2feb196ccb92c0feull, 0x2627954c4ca5bc98ull },
{ 4, 64, 48, 1, 1, 1, 273, 2, 19, 0x406b72ef3c95b8b6ull, 0x0000000000000000ull },
{ 5, 800, 1000, 1, 5, 4, 2313, 6, 21, 0xa449cce59a03d7dcull, 0x36b9d429ad266a50ull },
{ 0, 300, 500, 2, 1, 1, 273, 2, 27, 0xabc7f1eabc334430ull, 0x0000000000000000ull },
{ 1, 900, 1400, 2, 1, 1, 273, 2, 29, 0xb068ca82d7ec14c3ull, 0x0000000000000000ull },
{ 2, 2400, 400, 2, 1, 1, 273, 2, 31, 0x92636385d3bfb221ull, 0x0000000000000000ull },
{ 3, 500, 700, 2, 1, 1, 273, 2, 33, 0x2feb196ccb92c0feull, 0x0000000000000000ull },
{ 4, 64, 48, 2, 1, 1, 273, 2, 35, 0x406b72ef3c95b8b6ull, 0x0000000000000000ull },
{ 5, 800, 1000, 2, 1, 1, 273, 2, 37, 0xa449cce59a03d7dcull, 0x0000000000000000ull },
{ 1, 900, 1400, 3, 1, 1, 111, 2, 39, 0x45321be8ce76d69dull, 0x0000000000000000ull },
{ 3, 500, 700, 3, 1, 1, 111, 2, 41, 0xde290af82e82620full, 0x0000000000000000ull },
};
struct GoldUocrSeg { int32_t h, w, real; };
static const GoldUocrSeg kUocrSegs[] = {
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 40, 124, 120 },
{ 40, 124, 120 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 40, 44, 40 },
{ 40, 44, 40 },
{ 40, 44, 40 },
{ 40, 44, 40 },
{ 40, 44, 40 },
{ 40, 44, 40 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 40, 164, 160 },
{ 40, 164, 160 },
{ 40, 164, 160 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 40, 204, 200 },
{ 40, 204, 200 },
{ 40, 204, 200 },
{ 40, 204, 200 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 64, 68, 64 },
{ 4, 4, 0 },
{ 40, 44, 40 },
{ 4, 4, 0 },
{ 40, 44, 40 },
{ 4, 4, 0 },
};
/* Pillow's Image.resize(BICUBIC) of a splitmix picture: its two-pass order is part of the
* function (the intermediate rounds to eight bits). */
struct GoldUocrResize { int32_t sh, sw, dh, dw; uint64_t fnv; };
static const GoldUocrResize kUocrResize[] = {
{ 2400, 400, 1024, 171, 0xbccdeb5e050ce815ull },
{ 300, 300, 90, 100, 0xac4b3e6526dfbbb5ull },
{ 400, 300, 171, 1024, 0x799a058e681618b5ull },
{ 300, 400, 1024, 171, 0x82e65a0a71c6ee00ull },
{ 400, 1000, 200, 500, 0x7ef049c0990c00f6ull },
{ 1000, 400, 200, 300, 0x5a8d982164d9ff27ull },
{ 700, 500, 650, 470, 0x4697cb390555b911ull },
{ 500, 700, 640, 650, 0x90a6214f04fe8c0bull },
{ 320, 480, 320, 480, 0x8ce46502c9f58463ull },
{ 240, 320, 160, 320, 0x8ba4f63a78cc06bdull },
{ 240, 320, 240, 200, 0x9210b76889ecfbceull },
{ 64, 48, 1024, 1024, 0x3ccf3b8e768cfcd2ull },
};
/* The transposed pairs whose tall side the reference's set visits last. */
struct GoldUocrTie { int32_t c, r; };
static const GoldUocrTie kUocrTallLast[] = {
{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},
};
static const int32_t kUocrNTallLast = 31;