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

File diff suppressed because it is too large. Load diff
+36 -24
View File
@@ -64,6 +64,7 @@ struct AttnLlamaBF16 {
rad_op op_norm = 0, op_qkv = 0;
rad_op op_rope_q = 0, op_rope_k = 0;
rad_op op_qs = 0; /* cast: lift the fused plane's q slice into dense qs */
int qrow = 0; /* attn_paged_qrow served: q is read in place at its pitch */
rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0;
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
@@ -134,31 +135,41 @@ inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
{w.k}, {w.k});
/* attn_paged's prefill kernels read q only contiguous, and here q is a column slice of the
* fused q|k|v plane (row pitch q_dim + 2*kv_dim), so the slice is lifted into a dense
* [T, q_dim] buffer first (gemma4.cpp's `q_s` cast when attn_paged_qrow is not served).
* attn_paged_qrow would read the pitch in place, but libr4d's qrow rows cover only head_dim
* 256/512 (r4d_rows.cpp R4D_WIN_PAIR), not this decoder's head_dim 128. */
* fused q|k|v plane (row pitch q_dim + 2*kv_dim). attn_paged_qrow reads that pitch in place
* (libr4d's qrow rows cover head_dim 128/256/512). It is a separate op so no `--kernels` order
* can hand the slice to a kernel that reads q only dense (gemma4.cpp:1001-1023). Where the op
* is not declared or does not resolve, the slice is lifted into dense qs first. The cast is
* always declared (qs stays planned as today) but issued only in the fallback. */
op_qs = rw(b, RAD_OP(b, "cast",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
RAD_NOWEIGHTS),
{w.q}, {w.qs});
/* Declared before kv_store so block_size derives from the resolved attention kernel (spec
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the
* plain causal rule through the R-SWA ring: the ring's visible set is the block table's
* job (the runtime window prunes the table, not the kernel), so no re-declaration. */
op_attn = rw(b, RAD_OP(b, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{w.qs}, {w.attn});
auto declare_attn = [&](const char* op, rad_buf q) {
/* Declared before kv_store so block_size derives from the resolved attention kernel (spec
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the
* plain causal rule through the R-SWA ring: the ring's visible set is the block table's
* job (the runtime window prunes the table, not the kernel), so no re-declaration. */
return rw(b, RAD_OP(b, op,
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
RAD_INT("window", 0),
RAD_INT("n_head", g.n_head),
RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs),
RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS),
{q}, {w.attn});
};
if (rad_op_declared(b, "attn_paged_qrow") != 0)
op_attn = declare_attn("attn_paged_qrow", w.q);
if (op_attn) {
qrow = 1;
} else {
qrow = 0;
op_attn = declare_attn("attn_paged", w.qs);
}
op_kv_store = rw(b, RAD_OP(b, "kv_store",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
@@ -204,12 +215,13 @@ inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const {
RAD_ISSUE(c, op_qkv, brows(w.h, T), RAD_W(w_qkv), brows(w.q, T));
/* q, k and v are column views of the fused plane, walked by its row pitch: the rope and
* kv_store kernels take the slice's pitch (r4d_rows_pitch). Attention does not -- it needs
* q dense -- so the q slice is lifted into qs after rope and before the store. */
* kv_store kernels take the slice's pitch (r4d_rows_pitch). Attention reads the q slice in
* place when attn_paged_qrow is served; otherwise it needs q dense, so the slice is lifted
* into qs after rope and before the store. */
RAD_ISSUE(c, op_rope_q, bcol(w.q, 0, g.q_dim(), T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_rope_k, bcol(w.q, g.q_dim(), g.kv_dim(), T), rope_posmc(g, batch, T));
RAD_ISSUE(c, op_qs, bcol(w.q, 0, g.q_dim(), T), brows(w.qs, T));
if (op_qs) RAD_ISSUE(c, op_qs, bcol(w.q, 0, g.q_dim(), T), brows(w.qs, T));
RAD_ISSUE(c, op_kv_store,
bcol(w.q, g.q_dim(), g.kv_dim(), T),
@@ -217,7 +229,7 @@ inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const {
praw(slot, RAD_I32, T), kv_cache(kv, layer));
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
brows(w.qs, T), kv_cache(kv, layer),
qrow ? bcol(w.q, 0, g.q_dim(), T) : brows(w.qs, T), kv_cache(kv, layer),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq),
RAD_NONE, RAD_NONE,
+5 -3
View File
@@ -235,9 +235,11 @@ int Engine::run_encodes() {
it.pixels.shrink_to_fit();
if (dump_dir && *dump_dir) dump(it, ".bf16", it.embd.data(), it.embd.size());
}
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(),
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
.count());
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0).count();
if (std::getenv("RADIANCE_DEBUG_MM_TIME"))
RAD_INFO("encoder: tower pass for %zu item(s) -> %.1f ms", items.size(), ms);
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(), ms);
return RAD_OK;
}
+253 -13
View File
@@ -7,8 +7,16 @@
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <sstream>
#include <thread>
#if defined(__x86_64__) || defined(__i386__) || defined(_M_X64)
#include <immintrin.h>
#define RAD_MM_HAVE_AVX2 1
#endif
namespace rad {
namespace mm {
@@ -482,6 +490,172 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
} /* namespace */
/* ================================================================== AVX2 resample helpers
*
* The two passes below are fixed-point int32 per tap. Integer addition is exact and associative at
* these magnitudes (the coefficients of one output sum to 1 << prec and 255 << prec is about
* 1.07e9, so no wrapper), so evaluating eight output pixels at once in any tap order is the same
* function as the scalar loop; the rounding is only the final shift and clip. The horizontal pass
* has variable tap counts and arbitrary stride-3 starts, so its lanes gather one 32-bit word per
* tap (the RGB bytes of a pixel) and mask off inactive taps; the vertical pass reads whole rows,
* where eight pixels are 24 contiguous bytes.
*
* Dispatch is local rather than through libavx: this file is core host code, and the AVX2 bodies
* are target-attributed so the baseline object they live in still cannot execute AVX2 before the
* check. RAD_MM_NO_AVX2 forces the scalar path (the bit-exactness test uses it). */
static bool mm_use_avx2() {
#ifdef RAD_MM_HAVE_AVX2
static const bool cpu = [] {
__builtin_cpu_init();
return __builtin_cpu_supports("avx2");
}();
const char* off = std::getenv("RAD_MM_NO_AVX2");
return cpu && !(off && *off && *off != '0');
#else
return false;
#endif
}
#if defined(RAD_MM_HAVE_AVX2)
#define RAD_MM_AVX2 __attribute__((target("avx2")))
#define RAD_MM_INLINE_AVX2 __attribute__((target("avx2"), always_inline)) inline
#define RAD_MM_EXTRACT16(v) _mm256_extracti128_si256((v), 1)
/* Eight RGB pixels from 24 contiguous bytes (bytes 0..23 of p). */
RAD_MM_INLINE_AVX2 void load_rgb8(const uint8_t* p, __m256i* r, __m256i* g, __m256i* b) {
const __m128i a = _mm_loadu_si128((const __m128i*)p);
const __m128i c = _mm_loadl_epi64((const __m128i*)(p + 16));
const __m128i mr0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i mg0 = _mm_setr_epi8(1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i mb0 = _mm_setr_epi8(2, 5, 8, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i mr1 = _mm_setr_epi8(2, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i mg1 = _mm_setr_epi8(0, 3, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i mb1 = _mm_setr_epi8(1, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
const __m128i rb = _mm_or_si128(_mm_shuffle_epi8(a, mr0), _mm_slli_si128(_mm_shuffle_epi8(c, mr1), 6));
const __m128i gb = _mm_or_si128(_mm_shuffle_epi8(a, mg0), _mm_slli_si128(_mm_shuffle_epi8(c, mg1), 5));
const __m128i bb = _mm_or_si128(_mm_shuffle_epi8(a, mb0), _mm_slli_si128(_mm_shuffle_epi8(c, mb1), 5));
*r = _mm256_cvtepu8_epi32(rb);
*g = _mm256_cvtepu8_epi32(gb);
*b = _mm256_cvtepu8_epi32(bb);
}
/* Eight rounded, clipped int32 sums written as eight RGB triplets (exactly 24 bytes). */
RAD_MM_INLINE_AVX2 void store_rgb8(uint8_t* o, __m256i s0, __m256i s1, __m256i s2, int prec) {
const __m256i sh = _mm256_set1_epi32(prec);
const __m256i v0 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s0, sh), _mm256_setzero_si256()),
_mm256_set1_epi32(255));
const __m256i v1 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s1, sh), _mm256_setzero_si256()),
_mm256_set1_epi32(255));
const __m256i v2 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s2, sh), _mm256_setzero_si256()),
_mm256_set1_epi32(255));
const __m128i r16 = _mm_packus_epi32(_mm256_castsi256_si128(v0), RAD_MM_EXTRACT16(v0));
const __m128i g16 = _mm_packus_epi32(_mm256_castsi256_si128(v1), RAD_MM_EXTRACT16(v1));
const __m128i b16 = _mm_packus_epi32(_mm256_castsi256_si128(v2), RAD_MM_EXTRACT16(v2));
const __m128i r8 = _mm_packus_epi16(r16, r16);
const __m128i g8 = _mm_packus_epi16(g16, g16);
const __m128i b8 = _mm_packus_epi16(b16, b16);
/* Layout [r0..r3 g0..g3 b0..b3] then shuffle to 12 RGB bytes; twice for eight pixels.
* Mask the low four bytes before shifting, or each shift would overwrite the previous
* channel's bytes. */
const __m128i low4 = _mm_set_epi64x(0, 0xffffffffll);
const __m128i m = _mm_setr_epi8(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11, -1, -1, -1, -1);
const __m128i lo = _mm_shuffle_epi8(
_mm_or_si128(_mm_or_si128(_mm_and_si128(r8, low4),
_mm_slli_si128(_mm_and_si128(g8, low4), 4)),
_mm_slli_si128(_mm_and_si128(b8, low4), 8)),
m);
const __m128i hi = _mm_shuffle_epi8(
_mm_or_si128(_mm_or_si128(_mm_and_si128(_mm_srli_si128(r8, 4), low4),
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(g8, 4), low4), 4)),
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(b8, 4), low4), 8)),
m);
_mm_storel_epi64((__m128i*)o, lo);
_mm_storeu_si32(o + 8, _mm_srli_si128(lo, 8));
_mm_storel_epi64((__m128i*)(o + 12), hi);
_mm_storeu_si32(o + 20, _mm_srli_si128(hi, 8));
}
/* One horizontal row, eight output pixels a step. plans is [group][tap] of eight (offset, coeff,
* mask) int32s. The gather reads four bytes at the last input pixel's B channel, so the caller
* keeps the buffer's final row on the scalar path. */
RAD_MM_AVX2 void hpass_row(const uint8_t* row, uint8_t* o, int32_t ngroups, int32_t ksh,
int prec, const int32_t* plans) {
const __m256i zero = _mm256_setzero_si256();
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
const __m256i mask8 = _mm256_set1_epi32(0xff);
for (int32_t g = 0; g < ngroups; ++g) {
__m256i s0 = round, s1 = round, s2 = round;
const int32_t* pl = plans + (size_t)g * (size_t)ksh * 24;
for (int32_t t = 0; t < ksh; ++t, pl += 24) {
const __m256i off = _mm256_loadu_si256((const __m256i*)pl);
const __m256i coef = _mm256_loadu_si256((const __m256i*)(pl + 8));
const __m256i msk = _mm256_loadu_si256((const __m256i*)(pl + 16));
const __m256i word = _mm256_mask_i32gather_epi32(zero, (const int*)row, off, msk, 1);
const __m256i r = _mm256_and_si256(word, mask8);
const __m256i gg = _mm256_and_si256(_mm256_srli_epi32(word, 8), mask8);
const __m256i bb = _mm256_and_si256(_mm256_srli_epi32(word, 16), mask8);
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, coef));
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(gg, coef));
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(bb, coef));
}
store_rgb8(o + (size_t)g * 24, s0, s1, s2, prec);
}
}
/* One vertical row: every tap is a whole source row, eight output pixels at a time. */
RAD_MM_AVX2 void vpass_row(const Frame& src, int32_t ymin, int32_t ymax, const int32_t* k,
uint8_t* o, int prec) {
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
int32_t xx = 0;
for (; xx + 8 <= src.w; xx += 8) {
__m256i s0 = round, s1 = round, s2 = round;
for (int32_t y = 0; y < ymax; ++y) {
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
__m256i r, g, b;
load_rgb8(p, &r, &g, &b);
const __m256i kk = _mm256_set1_epi32(k[y]);
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, kk));
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(g, kk));
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(b, kk));
}
store_rgb8(o + (size_t)xx * 3, s0, s1, s2, prec);
}
for (; xx < src.w; ++xx) {
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
for (int32_t y = 0; y < ymax; ++y) {
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
s0 += p[0] * k[y];
s1 += p[1] * k[y];
s2 += p[2] * k[y];
}
o[xx * 3 + 0] = clip8(s0, prec);
o[xx * 3 + 1] = clip8(s1, prec);
o[xx * 3 + 2] = clip8(s2, prec);
}
}
/* One patch row: for each channel, P strided source bytes through that channel's LUT. lut32 is
* the same LUT as 32-bit words, so one gather gets all three channels' table entries. */
RAD_MM_AVX2 void patch_row(const uint8_t* row, uint16_t* dst, int32_t P, size_t chstride,
const uint32_t* lut32, const uint16_t* lut) {
for (int32_t x = 0; x + 8 <= P; x += 8) {
__m256i r, g, b;
load_rgb8(row + (size_t)x * 3, &r, &g, &b);
const __m256i idx[3] = { r, g, b };
for (int ch = 0; ch < 3; ++ch) {
const __m256i ii = _mm256_add_epi32(idx[ch], _mm256_set1_epi32(ch * 256));
const __m256i v = _mm256_i32gather_epi32((const int*)lut32, ii, 4);
const __m128i h = _mm_packus_epi32(_mm256_castsi256_si128(v), RAD_MM_EXTRACT16(v));
_mm_storeu_si128((__m128i*)(dst + (size_t)ch * chstride + x), h);
}
}
for (int ch = 0; ch < 3; ++ch)
for (int32_t x = (P / 8) * 8; x < P; ++x)
dst[(size_t)ch * chstride + x] = lut[ch * 256 + row[(size_t)x * 3 + ch]];
}
#endif /* RAD_MM_HAVE_AVX2 */
/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns;
* `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and
* round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the
@@ -492,16 +666,50 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
* implementation (stride-3 deinterleave + 8-lane int dot, in the libavx leg like the other
* bit-safe offloads) is bit-safe and pinned by the resample goldens -- a deliberate follow-up
* task, not a drive-by. The scalar order must not change. */
/* Both passes are row-independent: every output row reads only its own input rows and writes only
* its own output row, in the same per-tap order, so splitting the rows across threads is bit-exact
* (the goldens pin it). P2 in UNLIMITED-OCR-PERF.md: the scalar loop is ~20-30% of a picture's
* prefill now that the tower is fast. */
static void run_rows(int32_t rows, const std::function<void(int32_t)>& row) {
unsigned hw = std::thread::hardware_concurrency();
const int32_t nt = (int32_t)std::min<int32_t>(rows, (int32_t)std::min<unsigned>(hw ? hw : 1, 8));
if (nt <= 1) {
for (int32_t y = 0; y < rows; ++y) row(y);
return;
}
std::vector<std::thread> ts;
ts.reserve((size_t)nt);
for (int32_t t = 0; t < nt; ++t)
ts.emplace_back([&row, t, nt, rows] { for (int32_t y = t; y < rows; y += nt) row(y); });
for (std::thread& th : ts) th.join();
}
static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w,
const std::vector<int32_t>& bh, const std::vector<int32_t>& kh,
int32_t ksh, int prec, Frame* out) {
out->w = w;
out->h = rows;
out->rgb.assign((size_t)w * (size_t)rows * 3, 0);
for (int32_t yy = 0; yy < rows; ++yy) {
const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3;
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3;
for (int32_t xx = 0; xx < w; ++xx) {
const bool simd = mm_use_avx2();
const int32_t ngroups = simd ? w / 8 : 0;
std::vector<int32_t> plans;
if (ngroups) {
plans.resize((size_t)ngroups * (size_t)ksh * 24);
for (int32_t g = 0; g < ngroups; ++g)
for (int32_t t = 0; t < ksh; ++t) {
int32_t* p = plans.data() + ((size_t)g * (size_t)ksh + (size_t)t) * 24;
for (int32_t j = 0; j < 8; ++j) {
const int32_t xx = g * 8 + j;
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const bool on = t < xmax;
p[j] = on ? (xmin + t) * 3 : 0;
p[8 + j] = on ? kh[(size_t)xx * (size_t)ksh + (size_t)t] : 0;
p[16 + j] = on ? -1 : 0;
}
}
}
auto scalar_row = [&](const uint8_t* row, uint8_t* o, int32_t x0) {
for (int32_t xx = x0; xx < w; ++xx) {
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
const int32_t* k = kh.data() + (size_t)xx * (size_t)ksh;
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
@@ -515,7 +723,18 @@ static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t
o[xx * 3 + 1] = clip8(s1, prec);
o[xx * 3 + 2] = clip8(s2, prec);
}
}
};
run_rows(rows, [&](int32_t yy) {
const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3;
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3;
/* The gather reads one byte past the row; that is harmless on every row but the buffer's
* last, which stays scalar. */
if (!ngroups || yy + y0 == src.h - 1) { scalar_row(row, o, 0); return; }
#ifdef RAD_MM_HAVE_AVX2
hpass_row(row, o, ngroups, ksh, prec, plans.data());
scalar_row(row, o, ngroups * 8);
#endif
});
}
static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
@@ -524,10 +743,15 @@ static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
out->w = src.w;
out->h = h;
out->rgb.assign((size_t)src.w * (size_t)h * 3, 0);
for (int32_t yy = 0; yy < h; ++yy) {
const bool simd = mm_use_avx2();
run_rows(h, [&](int32_t yy) {
const int32_t ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
const int32_t* k = kv.data() + (size_t)yy * (size_t)ksv;
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)src.w * 3;
#ifdef RAD_MM_HAVE_AVX2
if (simd) { vpass_row(src, ymin, ymax, k, o, prec); return; }
#endif
(void)simd;
for (int32_t xx = 0; xx < src.w; ++xx) {
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
for (int32_t y = 0; y < ymax; ++y) {
@@ -540,7 +764,7 @@ static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
o[xx * 3 + 1] = clip8(s1, prec);
o[xx * 3 + 2] = clip8(s2, prec);
}
}
});
}
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
@@ -1120,11 +1344,14 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
/* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */
uint16_t lut[3][256];
uint32_t lut32[3 * 256];
for (int ch = 0; ch < 3; ++ch)
for (int v = 0; v < 256; ++v) {
const float p = (float)v / 255.0f;
lut[ch][v] = rad_f32_to_bf16((p - c.mean[ch]) / c.stdv[ch]);
lut32[ch * 256 + v] = lut[ch][v];
}
const bool simd = mm_use_avx2();
auto it = std::make_shared<Item>();
it->kind = Kind::Image;
@@ -1144,17 +1371,30 @@ int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
const size_t at = it->pixels.size();
it->pixels.resize(at + (size_t)gh * (size_t)gw * (size_t)it->patch_dim, 0);
uint16_t* dst = it->pixels.data() + at;
for (int32_t py = 0; py < gh; ++py)
/* Each patch row writes its own disjoint run of dst, in the same order, so splitting the
* rows across threads is bit-exact (P2's LUT staging half). */
run_rows(gh, [&](int32_t py) {
for (int32_t px = 0; px < real_w; ++px) {
uint16_t* pp = dst + ((size_t)py * (size_t)gw + (size_t)px) * (size_t)it->patch_dim;
const int32_t py0 = y0 + py * P, px0 = x0 + px * P;
for (int ch = 0; ch < 3; ++ch)
for (int y = 0; y < P; ++y) {
const uint8_t* row = src.rgb.data() +
((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3 + (size_t)ch;
for (int x = 0; x < P; ++x) *pp++ = lut[ch][row[x * 3]];
for (int y = 0; y < P; ++y) {
const uint8_t* row = src.rgb.data() +
((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3;
#ifdef RAD_MM_HAVE_AVX2
if (simd) {
patch_row(row, pp + (size_t)y * P, P, (size_t)P * P, lut32, &lut[0][0]);
continue;
}
#endif
(void)simd;
for (int ch = 0; ch < 3; ++ch) {
const uint8_t* r = row + (size_t)ch;
uint16_t* q = pp + ((size_t)ch * P + (size_t)y) * P;
for (int x = 0; x < P; ++x) q[x] = lut[ch][r[(size_t)x * 3]];
}
}
}
});
};
if (tiled) {
+14 -2
View File
@@ -28,6 +28,8 @@
#include "text/chat.h"
#include "text/chatfmt.h"
#include "text/chatparse.h"
#include <chrono>
#include <cstdlib>
#include "text/tokenizer.h"
#include "mm/processor.h"
@@ -711,8 +713,18 @@ public:
mode.kind = (int32_t)opts.image_mode;
mode.base_size = opts.image_base_size;
mode.image_size = opts.image_size;
return p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels, mode);
/* G1 (UNLIMITED-OCR-PERF.md): the host-side decode/resample/LUT share of a picture,
* separate from the tower pass timed in engine_mm.cpp. RADIANCE_DEBUG_MM_TIME=1. */
static const bool mm_time = std::getenv("RADIANCE_DEBUG_MM_TIME") != nullptr;
const auto t0 = std::chrono::steady_clock::now();
const int rc = p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
opts.max_pixels, mode);
if (mm_time)
RAD_INFO("mm: host processor %lld bytes -> %.1f ms (rc %d)",
(long long)bytes.size(),
std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0).count(), rc);
return rc;
}
int32_t audio_rate() const override {
+4 -3
View File
@@ -60,9 +60,10 @@ set(R4D_UNITS
# gqa6, head_dim 256, 4-token page: the same QSA layers at four ranks, each KV head replicated
# across a rank pair.
"r4d_attn_paged_h256_gqa6_bs4|"
# head_dim 256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers. One kernel per geometry
# covers every q_len and reads q at any row pitch (attn_paged_qrow).
# head_dim 128/256 and 512 at 1, 2, 4 or 8 queries per KV head with any window: Gemma 4's sliding
# (h256/gqa2, window 1024) and full (h512, gqa 8 at TP1/TP2) layers and Unlimited-OCR's h128 MHA
# decoder. One kernel per geometry covers every q_len and reads q at any row pitch
# (attn_paged_qrow).
"r4d_attn_paged_window|"
# Two queries per KV head at head_dim 128 only (Qwen3-1.7B's 16 over 8, Qwen3-ASR's decoder):
# the gqa8 body with the ratio set.
+10 -3
View File
@@ -1,5 +1,9 @@
/* r4d_attn_paged_window.hip -- paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV
* head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
/* r4d_attn_paged_window.hip -- paged attention at head_dim 128, 256 and 512, 1/2/4/8 queries per
* KV head, any sliding window, causal or not, bf16 or fp8-e4m3 cache, q at any row pitch.
*
* head_dim 128 is Unlimited-OCR's decoder (10 query heads over 10 KV heads): the plain MHA case,
* served here so its q slice of the fused q|k|v plane is read in place (attn_paged_qrow) instead
* of being lifted into a dense buffer.
*
* Gemma 4's text layers: sliding layers are 16 query heads over 8 KV heads at head_dim 256 with a
* 1024-token window (gqa 2 at every TP); full layers are 16 over 2 at head_dim 512 (gqa 8 at
@@ -61,7 +65,8 @@ constexpr int kMaxSplit = 64;
template <int HD> struct Geo;
/* R query rows per workgroup (R / 8 per wave), BK keys per tile. BK * 2 * HD bf16 = 32 KiB of LDS
* either way: two paged blocks at 256, one at 512. */
* either way: two paged blocks at 256, one at 512, four at 128. */
template <> struct Geo<128> { static constexpr int R = 32, BK = 32; };
template <> struct Geo<256> { static constexpr int R = 32, BK = 32; };
template <> struct Geo<512> { static constexpr int R = 16, BK = 16; };
@@ -1104,12 +1109,14 @@ extern "C" {
int r4d_rad_attn_window_h##HD##_gqa##G##_fp8(const RadArgs* a, RadStream s) { \
return r4d_win::launch_attn<HD, G, true>(a, s); \
}
R4D_WIN_DEF(128, 1)
R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8)
R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8)
#undef R4D_WIN_DEF
/* Called at declare with no tensors. Partials are capped at kPartBudget (tile, head, split)
* triples for any batch, so the size is a constant. */
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*) { return r4d_win::scratch_need<128>(); }
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*) { return r4d_win::scratch_need<256>(); }
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*) { return r4d_win::scratch_need<512>(); }
+3
View File
@@ -120,6 +120,8 @@ int64_t r4d_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*);
/* Paged attention at head_dim 256 and 512, 1/2/4/8 queries per KV head, any window, causal or not
* (r4d_attn_paged_window.hip): one entry point per geometry and cache dtype, every q_len and any q
* row pitch, so they serve both attn_paged and attn_paged_qrow. */
int r4d_rad_attn_window_h128_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h128_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa1_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h256_gqa2_bf16(const RadArgs*, RadStream);
@@ -136,6 +138,7 @@ int r4d_rad_attn_window_h512_gqa4_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa4_fp8 (const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_bf16(const RadArgs*, RadStream);
int r4d_rad_attn_window_h512_gqa8_fp8 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_window_h128_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_window_h512_scratch(const RadArgs*);
/* The top-1 of a row of all-gathered (id, value) pairs, written one id a row: the vocab-sharded
+8 -5
View File
@@ -3610,11 +3610,12 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* The windowed kernels (r4d_attn_paged_window.hip): head_dim 256 and 512, 1/2/4/8 queries per KV
* head, any window, causal or not. Gemma 4's sliding layers are h256/gqa2 with a 1024-token
* window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8). One kernel serves every
* q_len (splitting the key range when there are too few tiles to fill the card), so `q_len` cuts
* no band. `causal` and `window` are runtime fields; block_size is derived: 16.
/* The windowed kernels (r4d_attn_paged_window.hip): head_dim 128, 256 and 512, 1/2/4/8 queries per
* KV head, any window, causal or not. Gemma 4's sliding layers are h256/gqa2 with a 1024-token
* window, its full layers h512 at gqa 8 (TP1/TP2), 4 (TP4) or 2 (TP8); h128/gqa1 is Unlimited-OCR's
* MHA decoder. One kernel serves every q_len (splitting the key range when there are too few tiles
* to fill the card), so `q_len` cuts no band. `causal` and `window` are runtime fields; block_size
* is derived: 16.
*
* h256 at gqa 4 and 8 take a window only (C_GE 1), leaving the window-0 band to the gqa4 / gqa8
* legs above. At h256/gqa2 these rows overlap the sliding leg's bands and rank below it
@@ -3624,6 +3625,7 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = {
C_EQ("head_dim", HD), C_EQ("gqa", G), C_EQ("block_size", 16), C_GE("causal", 0), \
C_GE("window", WMIN), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", KV), \
};
R4D_WIN_C(cWinH128G1Bf16, 128, 1, "bf16", 0) R4D_WIN_C(cWinH128G1Fp8, 128, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G1Bf16, 256, 1, "bf16", 0) R4D_WIN_C(cWinH256G1Fp8, 256, 1, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G2Bf16, 256, 2, "bf16", 0) R4D_WIN_C(cWinH256G2Fp8, 256, 2, "fp8_e4m3", 0)
R4D_WIN_C(cWinH256G4Bf16, 256, 4, "bf16", 1) R4D_WIN_C(cWinH256G4Fp8, 256, 4, "fp8_e4m3", 1)
@@ -6027,6 +6029,7 @@ static const RadKernelInfo kKernels[] = {
#define R4D_WIN_PAIR(HD, GQ) \
R4D_WIN_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \
R4D_WIN_ROW(HD, GQ, fp8kv, fp8, cWinH##HD##G##GQ##Fp8, "fp8-e4m3 (per-(seq,head) descales)")
R4D_WIN_PAIR(128, 1)
R4D_WIN_PAIR(256, 1) R4D_WIN_PAIR(256, 2) R4D_WIN_PAIR(256, 4) R4D_WIN_PAIR(256, 8)
R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, 8)
#undef R4D_WIN_PAIR
+69 -18
View File
@@ -157,15 +157,9 @@ __device__ inline void sam_attn_body(
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, float scale) {
// blockIdx.x = ((seq * nth + ty) * ntw + tx) * nhead + head: heads adjacent, so the tile's k/v
// rows stay hot across them.
int b = blockIdx.x;
const int head = b % nhead; b /= nhead;
const int tx = b % ntw; b /= ntw;
const int ty = b % nth; b /= nth;
const int seq = b;
int seq, int head, int ty, int tx, int row_lo, int row_hi, float scale) {
// The caller supplies the (segment, tile, head) block coordinates: the windowed kernel reads
// them from blockIdx.x's window-tile layout, the global one from its query-tile layout.
const int s0 = cu[seq];
if (cu[seq + 1] - s0 != gh * gw) {
// A segment that is not one grid is a tower bug, not a shape: the shim pre-checks the
@@ -181,7 +175,7 @@ __device__ inline void sam_attn_body(
}
const int keys = th * tw;
for (int r = (int)threadIdx.x; r < keys; r += (int)kThreads) {
for (int r = row_lo + (int)threadIdx.x; r < row_hi; r += (int)kThreads) {
const int lh = r / tw, lw = r % tw;
const int ih = ty * th + lh, iw = tx * tw + lw;
if (ih >= gh || iw >= gw) continue; // a pad row: no output
@@ -197,13 +191,20 @@ __device__ inline void sam_attn_body(
float m = -INFINITY, l = 0.0f;
/* The w rel-pos dots depend on (lw, jw) only: computed once for the query row when the
* tile is narrow (the windowed tiles are 14 wide), recomputed per key otherwise (a
* whole-grid tile of 64 columns would cost more registers than the dots save). */
* tile is narrow (the windowed tiles are 14 wide), recomputed per key otherwise. For a
* whole-grid tile that is gw dots a query row instead of gw per key row, i.e. the same
* count as the q.k dots rather than gh times it; the array is spilled to local memory
* when the compiler runs out of registers, which is still far cheaper than the dot. */
float wr[16];
float wr_all[64];
const bool wr_hoist = tw <= 16;
const bool wr_wide = !wr_hoist && tw <= 64;
if (wr_hoist)
for (int jw = 0; jw < tw; ++jw)
wr[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
else if (wr_wide)
for (int jw = 0; jw < tw; ++jw)
wr_all[jw] = tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf);
for (int jh = 0; jh < th; ++jh) {
const float hr = tab_dot<HD>(rh, rh_rows, 2 * th - 1, lh - jh + th - 1, qf);
@@ -212,8 +213,9 @@ __device__ inline void sam_attn_body(
const bool hreal = kh < gh;
for (int jw = 0; jw < tw; ++jw) {
float s = hr + (wr_hoist ? wr[jw]
: tab_dot<HD>(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1,
qf));
: (wr_wide ? wr_all[jw]
: tab_dot<HD>(rw, rw_rows, 2 * tw - 1,
lw - jw + tw - 1, qf)));
const int kw = tx * tw + jw;
const bool real = hreal && kw < gw;
@@ -256,12 +258,47 @@ __global__ __launch_bounds__(kThreads) void sam_attn_kernel(
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw, int th, int tw,
int nth, int ntw, int vec_rows, float scale) {
// blockIdx.x = ((seq * nth + ty) * ntw + tx) * nhead + head: heads adjacent, so the tile's k/v
// rows stay hot across them.
int b = blockIdx.x;
const int head = b % nhead; b /= nhead;
const int tx = b % ntw; b /= ntw;
const int ty = b % nth; b /= nth;
const int seq = b;
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
o_ld, nhead, gh, gw, th, tw, seq, head, ty, tx, 0, th * tw, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, th, tw, nth, ntw, scale);
o_ld, nhead, gh, gw, th, tw, seq, head, ty, tx, 0, th * tw, scale);
}
/* The global path (window 0) is one tile over the whole segment, so the kernel above would launch
* nseq*nhead blocks with each thread walking rows/N-threads query rows in series (12-32 on a 40 or
* 64 grid): 60 blocks for a 5-tile page, far too few to fill the card. This variant keeps the same
* per-row math and key order but tiles the query rows, one block per (segment, query tile, head).
* Grid positions are the segment's row-major cells, so a tile is a contiguous row range. */
template <int HD>
__global__ __launch_bounds__(kThreads) void sam_attn_qtile_kernel(
const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, const uint16_t* __restrict__ rh,
const uint16_t* __restrict__ rw, int rh_rows, int rw_rows,
int q_ld, int k_ld, int v_ld, int o_ld, int nhead, int gh, int gw,
int nqb, int qrows, int vec_rows, float scale) {
int b = blockIdx.x;
const int head = b % nhead; b /= nhead;
const int qblk = b % nqb; b /= nqb;
const int seq = b;
const int keys = gh * gw;
const int lo = qblk * qrows;
const int hi = keys < lo + qrows ? keys : lo + qrows;
if (vec_rows)
sam_attn_body<HD, true>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, gh, gw, seq, head, 0, 0, lo, hi, scale);
else
sam_attn_body<HD, false>(gq, gk, gv, go, cu, rh, rw, rh_rows, rw_rows, q_ld, k_ld, v_ld,
o_ld, nhead, gh, gw, gh, gw, seq, head, 0, 0, lo, hi, scale);
}
int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o,
@@ -271,14 +308,28 @@ int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uin
int win, float scale, long stream) {
const int th = win > 0 ? win : gh, tw = win > 0 ? win : gw;
const int nth = (gh + th - 1) / th, ntw = (gw + tw - 1) / tw;
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
/* The 16-byte row loads are legal only when every q/k/v/out row starts on a 16-byte
* boundary: all four bases aligned, every row pitch a multiple of 8 bf16. The selftest's
* padded pitch and a slice with a filler column both fail this and take the scalar path. */
const uintptr_t addr_bits = (uintptr_t)q | (uintptr_t)k | (uintptr_t)v | (uintptr_t)o;
const bool vec_rows = (addr_bits & 15u) == 0 &&
((q_ld | k_ld | v_ld | o_ld) & 7) == 0;
if (win == 0) {
/* One block per (segment, 128-row query tile, head): the whole-segment tile above would
* give each thread 12-32 query rows in series and launch only nseq*nhead blocks. */
const int qrows = 128;
const int keys = gh * gw;
const int nqb = (keys + qrows - 1) / qrows;
const size_t qblocks = (size_t)nseq * nqb * nhead;
if (qblocks == 0 || qblocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL((sam_attn_qtile_kernel<64>), dim3((uint32_t)qblocks),
dim3(kThreads), 0, (hipStream_t)stream, q, k, v, o, cu, rh, rw,
rh_rows, rw_rows, q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, nqb, qrows,
vec_rows ? 1 : 0, scale);
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
const size_t blocks = (size_t)nseq * nth * ntw * nhead;
if (blocks == 0 || blocks > 0x7fffffff) return R4D_NO(RAD_E_SHAPE);
hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0,
(hipStream_t)stream, q, k, v, o, cu, rh, rw, rh_rows, rw_rows,
q_ld, k_ld, v_ld, o_ld, nhead, gh, gw, th, tw, nth, ntw,
+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}},