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

+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,