unlimitedocr: prefill and decode performance work

- sam_attn: tile queries and hoist the relative-position dots; the tower
  drops from 0.44-2.09 s to 0.10-0.36 s per tile.
- processor: split OCR patch/LUT staging across rows, then make both bicubic
  passes and the LUT append AVX2 (bit-exact, 1.15-1.38x host preprocessing).
- tower: batch the DeepEncoder across every tile segment of an encode pass.
  Patch embed, the 12 SAM blocks, neck, the 24 CLIP blocks and the projector
  run once per batch of up to 8 tiles (4 at the 64 grid); sam_attn and
  attn_dense stay segment-independent through B+1 cu tables, and position
  tables are host-staged PERSIST planes. B == 1 emits the old graph.
  Fix the newline layout: the reference expands image_newline over every map
  row, while the copy read past the one-row vector; with a multi-tile batch
  that made the trailing cells live data and the decoder dropped the text at
  the right margin of every line.
- attn: instantiate attn_paged_qrow at head_dim 128 (bf16 and fp8 caches) and
  read OCR's q slice of the fused q|k|v plane in place, keeping the dense cast
  as the fallback when the library does not serve the qrow row.
- tests: h128 attention emulator cases, a batched-tower arch test, an AVX2
  bit-identity test, and a 15 s arch_test CPU budget for the image.

Measured through the router at 256 tokens: 8-page TTFT 4157 -> 1327 ms, 640
page 608 -> 284 ms, 8 concurrent pages 17.6 -> 4.26 s wall; decode unchanged
at ~344 tok/s. Parse gate 0.9901 text / 1 px on the deployed image.
This commit is contained in:
Juup committed 2026-10-20 15:28:34 +00:00
1 parent 8bcf695db9
commit 912c57cb21
14 files changed
+1026 -398

No files matched your search

+1
View File
@@ -114,6 +114,7 @@ set(RAD_TEST_ENV ${RAD_TEST_CARD_ENV} "ROCR_VISIBLE_DEVICES=99")
# cost comes down, so the tripwire stays tight.
set(RAD_TEST_CPU_BUDGET_quant_ggml_test 25) # llama.cpp's iq1_s and iq2_* grid searches, ~13 s
set(RAD_TEST_CPU_BUDGET_tokenizer_test 20) # the reference encoder over every corpus: ~3 s built by GCC 16, ~10.5 s by GCC 14 (the image's Ubuntu)
set(RAD_TEST_CPU_BUDGET_arch_test 15) # every plugin's graph declared; ~10.8 s with the batched-tower case
# Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a
# team's worth of slots rather than one.
+153
View File
@@ -437,6 +437,17 @@ extern "C" int rad_memcpy_async(void* dst, const void* src, int64_t bytes, RadSt
c->copies.push_back({ c->issues.size(), h });
return RAD_OK;
}
/* The pitched copy: recorded exactly as the 1-D one (its destination's first byte names the
* buffer); the unlimitedocr tower packs patch rows and lays out its map with it. */
extern "C" int rad_memcpy_2d_async(void* dst, int64_t dpitch, const void* src, int64_t spitch,
int64_t width, int64_t height, RadStream s) {
(void)dpitch; (void)src; (void)spitch; (void)width; (void)height;
RadCtx* c = (RadCtx*)s;
if (c && c->b)
if (const rad_buf h = fake_buf_of(dst, c->b->bufs.size()))
c->copies.push_back({ c->issues.size(), h });
return RAD_OK;
}
extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s) {
(void)dst; (void)value; (void)bytes; (void)s;
return RAD_OK;
@@ -457,6 +468,8 @@ extern "C" int rad_memset_async(void* dst, int value, int64_t bytes, RadStream s
#include "../arch/gemma4/gemma4.cpp"
/* Qwen3-ASR: a Whisper-style audio tower over a dense Qwen3 decoder. */
#include "../arch/qwen3asr_bf16/qwen3asr_bf16.cpp"
/* Unlimited-OCR: the Llama-MoE decoder and its DeepEncoder tower (SAM + CLIP). */
#include "../arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp"
/* The PLE block alone: no architecture here declares it, and what its step() hands the two
* windowed ops is its own contract (rad_block_ple.h). */
#include <arch/rad_block_ple.h>
@@ -9492,3 +9505,143 @@ TEST(flashnext_a_spanned_prefill_runs_a_pass_at_a_time_with_its_all_reduces_besi
CHECK(!c.joins.empty());
}
}
/* ============================ unlimitedocr: the DeepEncoder batch ============================= */
namespace {
const char* k_uocr_keys[] = {
"n_routed_experts", "num_experts_per_tok", "moe_intermediate_size", "n_shared_experts",
"first_k_dense_replace", "scoring_func", "routed_scaling_factor", "topk_group", "n_group",
"use_mla", "norm_topk_prob", "sliding_window_size",
};
const char* k_uocr_vals[] = { "64", "6", "896", "2", "1", "softmax", "1.0", "1", "1", "0", "0",
"128" };
RadModelMeta uocr_meta() {
RadModelMeta m{};
m.arch_id = "unlimitedocr";
m.name = "test-unlimitedocr";
m.quant = "bf16";
m.n_layers = 12;
m.n_embd = 1280;
m.n_head = 10;
m.n_head_kv = 10;
m.head_dim = 128;
m.n_ff = 6848;
m.n_vocab = 129280;
m.n_ctx_train = 32768;
m.rms_eps = 1e-6f;
m.rope_theta = 10000.0f;
m.n_kv = (int)(sizeof(k_uocr_keys) / sizeof(k_uocr_keys[0]));
m.kv_key = k_uocr_keys;
m.kv_val = k_uocr_vals;
return m;
}
} /* namespace */
/* One encode pass of two 640 tile lines (four tiles): the tower batches every GEMM over the whole
* pass, and the segment-bounded ops carry one cu entry a tile. */
TEST(unlimitedocr_batches_the_tower_across_tile_segments) {
RadBuilder b;
const RadEncoding plain = rad_enc_plain(RAD_BF16);
b.encs = { { "ffn_gate_up_exps", plain }, { "ffn_down_exps", plain } };
RadModelMeta meta = uocr_meta();
RadBuildCtx ctx = build_ctx();
ctx.max_enc_patches = 16384;
CHECK_OK(unlimitedocr_bf16::declare(&b, &meta, &ctx));
const int64_t q = 40, nseg = 2, n_patch = nseg * (2 * q + 4) * q; /* two lines of two tiles */
std::vector<int32_t> sh((size_t)nseg, (int32_t)q), sw((size_t)nseg, (int32_t)(2 * q + 4));
std::vector<int32_t> cu = { 0, (int32_t)((2 * q + 4) * q), (int32_t)n_patch };
std::vector<uint16_t> pix((size_t)n_patch * 768, 0);
RadBatch batch{};
batch.enc = RAD_MM_IMAGE;
batch.enc_n_patch = n_patch;
batch.enc_pixels = pix.data();
batch.enc_n_seg = nseg;
batch.enc_cu = cu.data();
batch.enc_seg_h = sh.data();
batch.enc_seg_w = sw.data();
batch.enc_max_seg = (2 * q + 4) * q;
RadCtx c{ .b = &b, .batch = &batch };
unlimitedocr_bf16::step(&c, &batch);
CHECK(c.step_fail.empty());
CHECK_LINT(b, &c);
/* The batch bound is the pass bound over this grid's tokens, capped at 8 (10 tiles at 40,
* 4 at 64 for 16384 patches). */
const auto& enc = unlimitedocr_bf16::g_model[0].enc;
CHECK_EQ(enc.t40.Bmax, 8);
CHECK_EQ(enc.t64.Bmax, 4);
constexpr int64_t kTok40 = 1600, kTokP40 = 1764, kClip40 = 101;
/* One patch-embed GEMM over all four tiles, not four of one. */
const RecIssue* patch = issue_of(b, c, "gemm_nt_bias");
REQUIRE(patch != nullptr);
CHECK_EQ(patch->n, 4 * kTok40);
/* SAM's first attention is layer 0's windowed path over the padded grid. */
const RecIssue* sat = issue_of(b, c, "sam_attn");
REQUIRE(sat != nullptr);
CHECK_EQ(sat->n, 4 * kTokP40);
REQUIRE(sat->opd.size() > 4);
CHECK_EQ(sat->opd[3].rows, 5);
/* Layer 2 is the first global block: no padding, four kSamTok-row segments. */
const RecIssue* satg = issue_of(b, c, "sam_attn", 2);
REQUIRE(satg != nullptr);
CHECK_EQ(satg->n, 4 * kTok40);
CHECK_EQ(satg->opd[3].rows, 5);
/* CLIP's attention is one dense call over four kClipTok-row segments. */
const RecIssue* cat = issue_of(b, c, "attn_dense");
REQUIRE(cat != nullptr);
CHECK_EQ(cat->n, 4 * kClip40);
REQUIRE(cat->opd.size() > 4);
CHECK_EQ(cat->opd[3].rows, 5);
/* The unfold sees the four tiles as four kGrid-row segments. */
const RecIssue* unf = issue_of(b, c, "conv2d_unfold");
REQUIRE(unf != nullptr);
CHECK_EQ(unf->opd[0].rows, 4 * q);
/* The class row, the map cast, the fuse and the newline stay per tile: 4 / 4 / 4 / 2. */
int cls = 0, cmap = 0, fuse = 0, nl = 0;
for (const RecIssue& i : c.issues) {
if (i.op == enc.t40.op_cls) ++cls;
else if (i.op == enc.t40.op_cmap) ++cmap;
else if (i.op == enc.t40.op_fuse_clip) ++fuse;
else if (i.op == enc.t40.op_newline) ++nl;
}
CHECK_EQ(cls, 4);
CHECK_EQ(cmap, 4);
CHECK_EQ(fuse, 4);
CHECK_EQ(nl, nseg);
/* A one-tile pass is the same graph at B = 1. */
std::vector<int32_t> sh1 = { (int32_t)q }, sw1 = { (int32_t)(q + 4) };
std::vector<int32_t> cu1 = { 0, (int32_t)((q + 4) * q) };
std::vector<uint16_t> pix1((size_t)((q + 4) * q) * 768, 0);
RadBatch one{};
one.enc = RAD_MM_IMAGE;
one.enc_n_patch = (q + 4) * q;
one.enc_pixels = pix1.data();
one.enc_n_seg = 1;
one.enc_cu = cu1.data();
one.enc_seg_h = sh1.data();
one.enc_seg_w = sw1.data();
one.enc_max_seg = (q + 4) * q;
RadCtx c1{ .b = &b, .batch = &one };
unlimitedocr_bf16::step(&c1, &one);
CHECK(c1.step_fail.empty());
CHECK_LINT(b, &c1);
const RecIssue* p1 = issue_of(b, c1, "gemm_nt_bias");
REQUIRE(p1 != nullptr);
CHECK_EQ(p1->n, kTok40);
const RecIssue* s1 = issue_of(b, c1, "sam_attn");
REQUIRE(s1 != nullptr);
CHECK_EQ(s1->n, kTokP40);
REQUIRE(s1->opd.size() > 4);
CHECK_EQ(s1->opd[3].rows, 2);
const RecIssue* c_1 = issue_of(b, c1, "attn_dense");
REQUIRE(c_1 != nullptr);
CHECK_EQ(c_1->n, kClip40);
}
+63
View File
@@ -34,6 +34,7 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
@@ -1805,4 +1806,66 @@ TEST(unlimitedocr_bicubic_antialias_resample_is_the_reference) {
(void)clip_mism;
}
/* The AVX2 resample and patch-staging paths must be the scalar function, not an approximation:
* the goldens above pin the modelled result, and this pins the vector lanes against the scalar
* loop that produced them. RAD_MM_NO_AVX2 selects the scalar path (core/mm/processor.cpp), so the
* same input goes through both dispatches on this host. Sizes cover growth and shrink (different
* tap counts), both pass orders, odd widths/tails, and a 1-pixel side. */
TEST(avx2_preprocessing_is_bit_identical_to_scalar) {
const struct { int32_t ih, iw, oh, ow; } cases[] = {
{ 53, 67, 35, 40 }, { 53, 67, 55, 57 }, { 64, 64, 1024, 1024 },
{ 1024, 1024, 640, 640 }, { 200, 100, 50, 200 }, { 97, 129, 96, 128 },
{ 1, 1, 7, 5 }, { 71, 131, 70, 130 }, { 17, 31, 9, 8 },
{ 300, 500, 299, 501 },
};
int seed = 11;
for (const auto& c : cases) {
Frame in = frame(seed++, c.ih, c.iw);
Frame sv, sm, tv, tm;
setenv("RAD_MM_NO_AVX2", "1", 1);
resize_bicubic(in, c.ow, c.oh, &sv);
resize_bicubic_torch(in, c.ow, c.oh, &tv);
unsetenv("RAD_MM_NO_AVX2");
resize_bicubic(in, c.ow, c.oh, &sm);
resize_bicubic_torch(in, c.ow, c.oh, &tm);
CHECK_EQ(sm.w, sv.w);
CHECK_EQ(sm.h, sv.h);
CHECK(sm.rgb == sv.rgb);
CHECK(tm.rgb == tv.rgb);
if (sm.rgb != sv.rgb) {
for (size_t i = 0; i < sv.rgb.size(); ++i)
if (sm.rgb[i] != sv.rgb[i]) {
std::fprintf(stderr, " %dx%d -> %dx%d: first byte %zu differs (%d vs %d)\n",
c.iw, c.ih, c.ow, c.oh, i, (int)sv.rgb[i], (int)sm.rgb[i]);
break;
}
}
}
/* Patch/LUT staging (the Unlimited-OCR append path), through the whole processor so the
* segment order and both views are covered. */
Processor p;
REQUIRE_EQ(p.init(uocr_cfg(), [](const std::string&) { return std::vector<int32_t>{}; },
uocr_marker), RAD_OK);
const struct { int32_t seed, h, w; } imgs[] = { { 3, 640, 640 }, { 4, 900, 1400 } };
for (const auto& g : imgs) {
Frame in = frame(g.seed, g.h, g.w);
for (int kind = 0; kind < 2; ++kind) {
ImageMode mode;
mode.kind = kind ? ImageMode::Base : ImageMode::Gundam;
std::shared_ptr<Item> a, b;
std::string why;
setenv("RAD_MM_NO_AVX2", "1", 1);
REQUIRE_EQ(p.image_from(in, &a, &why, mode), RAD_OK);
unsetenv("RAD_MM_NO_AVX2");
REQUIRE_EQ(p.image_from(in, &b, &why, mode), RAD_OK);
REQUIRE(a != nullptr);
REQUIRE(b != nullptr);
CHECK_EQ(b->n_patch, a->n_patch);
CHECK(b->pixels == a->pixels);
CHECK(b->expand == a->expand);
}
}
}
RAD_TEST_MAIN()
+12 -1
View File
@@ -42,7 +42,7 @@ struct Case {
using Fn = int (*)(const RadArgs*, RadStream);
static Fn pick(int hd, int gqa, bool fp8) {
#define P(H, G) if (hd == H && gqa == G) return fp8 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
P(128, 1) P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
#undef P
return nullptr;
}
@@ -169,8 +169,19 @@ static int run(const Case& c) {
}
int main(int argc, char** argv) {
const int64_t s128 = r4d_rad_attn_window_h128_scratch(nullptr);
const int64_t s256 = r4d_rad_attn_window_h256_scratch(nullptr), s512 = r4d_rad_attn_window_h512_scratch(nullptr);
std::vector<Case> cases = {
/* Unlimited-OCR's decoder: h128 MHA, the fused q|k|v plane read at its pitch */
{"h128 gqa1 decode split", 128, 1, 1, false, true, false, false, 0, {1}, {700}, -1, 0, s128},
{"h128 gqa1 swa w64 verify16", 128, 1, 1, false, true, false, false, 64, {16}, {1100}},
{"h128 gqa1 noncausal full", 128, 1, 1, false, false, false, false, 0, {3}, {77}},
{"wmma h128 gqa1 prefill 200 of 900", 128, 1, 1, false, true, false, false, 0, {200}, {900},
-1, 0, 0, 0, 1},
{"wmma h128 gqa1 q-pitch slice", 128, 1, 1, false, true, false, false, 0, {96}, {150}, -1,
0, 0, 512, 1},
{"wmma h128 gqa1 swa w1024 ragged", 128, 1, 1, false, true, true, false, 1024, {150, 70},
{300, 70}, -1, 0, 0, 0, 1},
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},