diff --git a/arch/common/rad_block_sam.h b/arch/common/rad_block_sam.h index 2e6c7ed9..3048928f 100644 --- a/arch/common/rad_block_sam.h +++ b/arch/common/rad_block_sam.h @@ -107,6 +107,9 @@ struct DeepEncoder { static constexpr int64_t kNEmbd = 1280; static constexpr int64_t kPatchDim = 3 * kPatch * kPatch; /* 768: a staged patch row */ static constexpr int64_t kMerge = kDown * kDown; /* 16 patches a row */ + /* Tiles one tower invocation batches. max_patches/kSamTok bounds a pass (10 at the 40 grid, + * 4 at 64 for the 16384-patch default); the cap keeps the activation set modest. */ + static constexpr int64_t kBatchCap = 8; static bool global_block(int64_t i) { return i == 2 || i == 5 || i == 8 || i == 11; } @@ -173,26 +176,34 @@ struct DeepEncoder { /* ------------------------------------------------------------------ one tower a geometry * All of the tower's OPS and ACTIVATIONS; the weights live in DeepEncoder (one checkpoint * tensor a name, both geometries read the same planes). */ + /* One staged tile of a pass: segment `patch0`/`gw`, tile `t` of `n` in it, its output row + * block, and whether this tile closes a line (the newline row follows its map). */ + struct Tile { + int64_t patch0 = 0, gw = 0, t = 0, n = 0, rowbase = 0; + bool nl = false; + }; + template struct Tower { std::vector> sam; std::vector> clip; /* pass constants */ - rad_op op_cu_sam = 0, op_cu_clip = 0, op_cu_pad = 0; /* {0, tokens} tables */ + rad_op op_cu_sam = 0, op_cu_clip = 0, op_cu_pad = 0; /* segment bounds tables */ rad_buf b_cu_sam = 0, b_cu_clip = 0, b_cu_pad = 0; /* stem, neck, layout ops */ - rad_op op_patch = 0, op_ids_sam = 0, op_sampos = 0, op_sampadd = 0; + rad_op op_patch = 0, op_sampos = 0, op_sampadd = 0; rad_op op_neck0 = 0, op_nk1 = 0, op_unf3 = 0, op_nk2 = 0, op_nk3 = 0; rad_op op_unf_net2 = 0, op_net2 = 0, op_unf_net3 = 0, op_net3 = 0; - rad_op op_cls = 0, op_cmap = 0, op_ids_clip = 0, op_cpos = 0, op_cadd = 0, op_playr = 0; + rad_op op_cls = 0, op_cmap = 0, op_cpos = 0, op_cadd = 0, op_playr = 0; rad_op op_ccopy = 0; /* pre_layrnorm output into the residual stream */ rad_op op_fuse_clip = 0, op_fuse_sam = 0, op_proj = 0; rad_op op_dbg1024 = 0, op_dbg1280 = 0, op_dbg768 = 0, op_dbg256 = 0; rad_op op_newline = 0, op_sep = 0; - /* activations, one view's, reused by every view a pass carries. */ + /* activations, one batched run's: `B` tiles, tile-major (tile t's rows at + * [t*kSamTok, (t+1)*kSamTok)). */ rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_sampos = 0; rad_buf b_nlrow = 0; /* the newline row, computed once, pitched into the layout */ rad_buf b_pixstg = 0; /* a tile's patch rows, packed for the single patch-embed GEMM */ @@ -219,7 +230,8 @@ struct DeepEncoder { int dbg = 0, dbg_row = 0; /* RAD_UNLIMITEDOCR_DBG / _ROW: dump one stage, from a row */ mutable uint32_t tabs_done = 0; /* bit per rank: the resampled tables are staged */ - mutable uint32_t ids_done = 0; /* bit per rank: the window index tables are staged */ + mutable uint32_t ids_done = 0; /* bit per rank: the position/index tables are staged */ + int64_t Bmax = 1; /* tiles one invocation batches; every per-view plane is Bmax of them */ static constexpr int64_t kGrid = G::kGrid; static constexpr int64_t kMap = G::kMap; @@ -234,10 +246,10 @@ struct DeepEncoder { int declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad_buf out, rad_buf one, rad_buf one_c); void fill_tables(RadCtx* c, const DeepEncoder& w) const; - void view(RadCtx* c, const RadBatch* batch, int64_t patch0, int64_t gw, int64_t t, - int64_t n, int64_t rowbase, bool tap, const DeepEncoder& w) const; - void segment(RadCtx* c, const RadBatch* batch, int64_t patch0, int64_t gw, int64_t n, - int64_t rowbase, bool nl, bool tap, const DeepEncoder& w); + void stage_ids(RadCtx* c) const; + /* One batched tower run over `nt` (<= Bmax) staged tiles. */ + void batch(RadCtx* c, const RadBatch* batch, const Tile* tiles, int64_t nt, + bool tap, const DeepEncoder& w); }; Tower t64; @@ -546,8 +558,14 @@ struct DeepEncoder { on = false; return RAD_OK; } - max_views64 = max_patches / Geom64::kSegView; - max_views40 = max_patches / Geom40::kSegView; + /* The towers size their activations for the tiles one invocation batches. A pass is + * max_patches/(G::kSamTok) whole tiles at most; kBatchCap keeps the set modest. */ + max_views64 = max_patches / Geom64::kSamTok; + max_views40 = max_patches / Geom40::kSamTok; + if (max_views64 > kBatchCap) max_views64 = kBatchCap; + if (max_views40 > kBatchCap) max_views40 = kBatchCap; + if (max_views64 < 1) max_views64 = 1; + if (max_views40 < 1) max_views40 = 1; b_out = decl_b(b, "v.out", RAD_BF16, {max_patches / kMerge, kNEmbd}); if (const char* e = getenv("RAD_UNLIMITEDOCR_DBG")) t64.dbg = t40.dbg = atoi(e); if (const char* e = getenv("RAD_UNLIMITEDOCR_DBG_ROW")) @@ -620,7 +638,7 @@ struct DeepEncoder { /* Validate the pass: every view segment one grid, every separator exactly one merged * cell. A view row is a line chunk: n = w/h tiles, its last chunk carrying the line's * newline column (w = n*h + kDown), an earlier chunk not (w = n*h). */ - int64_t tiles = 0; + int64_t n_tiles = 0; int32_t grid = 0; for (int64_t s = 0; s < n_seg; ++s) { const int32_t h = sh[s], w = sw[s]; @@ -645,9 +663,9 @@ struct DeepEncoder { "must break a pass at a geometry change"); return; } - tiles += w / h; + n_tiles += w / h; } - if (tiles > 0 && grid != Geom64::kGrid && grid != Geom40::kGrid) { + if (n_tiles > 0 && grid != Geom64::kGrid && grid != Geom40::kGrid) { char msg[192]; std::snprintf(msg, sizeof msg, "unlimitedocr: an encoder pass at a %d-patch grid the DeepEncoder " @@ -658,28 +676,52 @@ struct DeepEncoder { /* Shared constants. */ RAD_ISSUE(c, op_fill_one, RAD_B(b_one)); RAD_ISSUE(c, op_fill_one_c, RAD_B(b_one_c)); - /* Walk the segments, writing each one's output rows where the pass's row block puts it. */ - const bool do_tap = !tapped_; - bool tapped_view = false; + /* Walk the segments into a flat tile list. Every view tile is batched with the pass's + * other tiles (chunked at the tower's Bmax); only the separator rows are issued on their + * own. */ + std::vector tiles; + std::vector sep_rows; int64_t pc = 0; for (int64_t s = 0; s < n_seg; ++s) { const int64_t h = sh[s], sw_ = sw[s]; const int64_t rowbase = pc / kMerge; if (h == kDown && sw_ == kDown) { - /* One learned row; geometry-independent, so the 64 tower carries the op. */ - RAD_ISSUE(c, t64.op_sep, RAD_B(b_one), RAD_W(w_sep), - brow_slice(b_out, rowbase, 1, kNEmbd)); + sep_rows.push_back(rowbase); pc += h * sw_; continue; } const int64_t n = sw_ / h; const bool nl = (sw_ % h) != 0; /* the line's last chunk holds the newline col */ - const bool tap0 = do_tap && !tapped_view; - if (h == Geom64::kGrid) t64.segment(c, batch, pc, sw_, n, rowbase, nl, tap0, *this); - else t40.segment(c, batch, pc, sw_, n, rowbase, nl, tap0, *this); - tapped_view = true; + for (int64_t t = 0; t < n; ++t) { + Tile tl; + tl.patch0 = pc; + tl.gw = sw_; + tl.t = t; + tl.n = n; + tl.rowbase = rowbase; + tl.nl = nl && t == n - 1; + tiles.push_back(tl); + } pc += h * sw_; } + const bool do_tap = !tapped_; + bool tapped_view = false; + for (size_t i = 0; i < tiles.size(); ) { + const int64_t bm = (grid == Geom64::kGrid) ? t64.Bmax : t40.Bmax; + int64_t nb = (int64_t)(tiles.size() - i); + if (nb > bm) nb = bm; + const bool tap0 = do_tap && !tapped_view; + if (grid == Geom64::kGrid) + t64.batch(c, batch, &tiles[i], nb, tap0, *this); + else + t40.batch(c, batch, &tiles[i], nb, tap0, *this); + tapped_view = true; + i += (size_t)nb; + } + /* One learned separator row; geometry-independent, so the 64 tower carries the op. */ + for (int64_t rowbase : sep_rows) + RAD_ISSUE(c, t64.op_sep, RAD_B(b_one), RAD_W(w_sep), + brow_slice(b_out, rowbase, 1, kNEmbd)); if (tapped_view) tapped_ = true; } }; @@ -696,65 +738,73 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad char bn[64]; #define RAD_VN(fmtv) std::snprintf(bn, sizeof bn, fmtv, sfx) - /* ---- activations, one view's. */ - RAD_VN("v%s.sam.x"); b_x = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.h"); b_h = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.qkv"); b_qkv = decl_b(b, bn, RAD_BF16, {kSamTok, 3 * DeepEncoder::kSamW}); - RAD_VN("v%s.sam.att"); b_att = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.ff"); b_ff = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamFf}); - RAD_VN("v%s.sam.pos"); b_sampos = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.ids"); b_ids_sam = decl_b(b, bn, RAD_I32, {kSamTok}); - RAD_VN("v%s.sam.hw"); b_hw = decl_b(b, bn, RAD_BF16, {kSamTokP, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.qkvw"); b_qkvw = decl_b(b, bn, RAD_BF16, {kSamTokP, 3 * DeepEncoder::kSamW}); - RAD_VN("v%s.sam.attw"); b_attw = decl_b(b, bn, RAD_BF16, {kSamTokP, DeepEncoder::kSamW}); - RAD_VN("v%s.sam.idsp"); b_ids_pad = decl_b(b, bn, RAD_I32, {kSamTokP}, RAD_BUF_PERSIST); - RAD_VN("v%s.sam.idsr"); b_ids_real = decl_b(b, bn, RAD_I32, {kSamTok}, RAD_BUF_PERSIST); + /* Tiles one invocation batches: the pass bound over this grid's tokens, capped. */ + Bmax = w.max_patches / kSamTok; + if (Bmax < 1) Bmax = 1; + if (Bmax > DeepEncoder::kBatchCap) Bmax = DeepEncoder::kBatchCap; + const int64_t B = Bmax; - RAD_VN("v%s.n0"); b_n0 = decl_b(b, bn, RAD_BF16, {kSamTok, 256}); - RAD_VN("v%s.n1"); b_n1 = decl_b(b, bn, RAD_BF16, {kSamTok, 256}); - RAD_VN("v%s.nfu"); b_unf3 = decl_b(b, bn, RAD_BF16, {kSamTok, 256 * 9}); - RAD_VN("v%s.n2"); b_n2 = decl_b(b, bn, RAD_BF16, {kSamTok, 256}); - RAD_VN("v%s.n3"); b_n3 = decl_b(b, bn, RAD_BF16, {kSamTok, 256}); - RAD_VN("v%s.n2u"); b_unf_2 = decl_b(b, bn, RAD_BF16, {kSamTok / 4, 256 * 9}); - RAD_VN("v%s.m2"); b_map2 = decl_b(b, bn, RAD_BF16, {kSamTok / 4, 512}); - RAD_VN("v%s.n3u"); b_unf_3 = decl_b(b, bn, RAD_BF16, {kMap * kMap, 512 * 9}); - RAD_VN("v%s.map"); b_map = decl_b(b, bn, RAD_BF16, {kMap * kMap, DeepEncoder::kClipW}); + /* ---- activations, B tiles' worth, tile-major. */ + RAD_VN("v%s.sam.x"); b_x = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.h"); b_h = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.qkv"); b_qkv = decl_b(b, bn, RAD_BF16, {B * kSamTok, 3 * DeepEncoder::kSamW}); + RAD_VN("v%s.sam.att"); b_att = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.ff"); b_ff = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamFf}); + RAD_VN("v%s.sam.pos"); b_sampos = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.ids"); b_ids_sam = decl_b(b, bn, RAD_I32, {B * kSamTok}, RAD_BUF_PERSIST); + RAD_VN("v%s.sam.hw"); b_hw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.qkvw"); b_qkvw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, 3 * DeepEncoder::kSamW}); + RAD_VN("v%s.sam.attw"); b_attw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.idsp"); b_ids_pad = decl_b(b, bn, RAD_I32, {B * kSamTokP}, RAD_BUF_PERSIST); + RAD_VN("v%s.sam.idsr"); b_ids_real = decl_b(b, bn, RAD_I32, {B * kSamTok}, RAD_BUF_PERSIST); - RAD_VN("v%s.cx"); b_c = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); - RAD_VN("v%s.ch"); b_ch = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); - RAD_VN("v%s.cq"); b_cq = decl_b(b, bn, RAD_BF16, {kClipTok, 3 * DeepEncoder::kClipW}); - RAD_VN("v%s.ca"); b_ca = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); - RAD_VN("v%s.cf"); b_cf = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipFf}); - RAD_VN("v%s.cg2"); b_cg2 = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipFf}); - RAD_VN("v%s.ct"); b_ct = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); - RAD_VN("v%s.cp"); b_cp = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); - RAD_VN("v%s.cids"); b_ids_clip = decl_b(b, bn, RAD_I32, {kClipTok}); - RAD_VN("v%s.cpos"); b_cpos = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.n0"); b_n0 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n1"); b_n1 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.nfu"); b_unf3 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256 * 9}); + RAD_VN("v%s.n2"); b_n2 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n3"); b_n3 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n2u"); b_unf_2 = decl_b(b, bn, RAD_BF16, {B * kSamTok / 4, 256 * 9}); + RAD_VN("v%s.m2"); b_map2 = decl_b(b, bn, RAD_BF16, {B * kSamTok / 4, 512}); + RAD_VN("v%s.n3u"); b_unf_3 = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, 512 * 9}); + RAD_VN("v%s.map"); b_map = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kClipW}); - RAD_VN("v%s.fuse"); b_fuse = decl_b(b, bn, RAD_BF16, {kMap * kMap, DeepEncoder::kFused}); - RAD_VN("v%s.proj"); b_projbuf = decl_b(b, bn, RAD_BF16, {kMap * kMap, DeepEncoder::kNEmbd}); + RAD_VN("v%s.cx"); b_c = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.ch"); b_ch = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cq"); b_cq = decl_b(b, bn, RAD_BF16, {B * kClipTok, 3 * DeepEncoder::kClipW}); + RAD_VN("v%s.ca"); b_ca = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cf"); b_cf = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipFf}); + RAD_VN("v%s.cg2"); b_cg2 = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipFf}); + RAD_VN("v%s.ct"); b_ct = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cp"); b_cp = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cids"); b_ids_clip = decl_b(b, bn, RAD_I32, {B * kClipTok}, RAD_BUF_PERSIST); + RAD_VN("v%s.cpos"); b_cpos = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + + RAD_VN("v%s.fuse"); b_fuse = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kFused}); + RAD_VN("v%s.proj"); b_projbuf = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kNEmbd}); RAD_VN("v%s.nlrow"); b_nlrow = decl_b(b, bn, RAD_BF16, {1, DeepEncoder::kNEmbd}); - RAD_VN("v%s.pixstg"); b_pixstg = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kPatchDim}); + RAD_VN("v%s.pixstg"); b_pixstg = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kPatchDim}); - /* One cu_seqlens table each, {0, tokens}, one segment: `iota` writes both entries. The three - * unfolds read b_cu_sam through their cu_div (kSamTok/kGrid rows a grid row; net_3's divides - * by 2*kGrid), so one table serves all of them. */ + /* One cu_seqlens table each, a bound a tile: the batched SAM/CLIP attention reads B segments + * and the three unfolds divide by kGrid (net_3 by 2*kGrid). */ RAD_VN("v%s.cus"); - b_cu_sam = decl_b(b, bn, RAD_I32, {2}); + b_cu_sam = decl_b(b, bn, RAD_I32, {B + 1}); op_cu_sam = rw(b, RAD_OP(b, "iota", - RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), RAD_INT("step", kSamTok)), + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kSamTok)), RAD_NOWEIGHTS), {}, {b_cu_sam}); RAD_VN("v%s.cuc"); - b_cu_clip = decl_b(b, bn, RAD_I32, {2}); + b_cu_clip = decl_b(b, bn, RAD_I32, {B + 1}); op_cu_clip = rw(b, RAD_OP(b, "iota", - RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), RAD_INT("step", kClipTok)), + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kClipTok)), RAD_NOWEIGHTS), {}, {b_cu_clip}); RAD_VN("v%s.cup"); - b_cu_pad = decl_b(b, bn, RAD_I32, {2}); + b_cu_pad = decl_b(b, bn, RAD_I32, {B + 1}); op_cu_pad = rw(b, RAD_OP(b, "iota", - RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), RAD_INT("step", kSamTokP)), + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kSamTokP)), RAD_NOWEIGHTS), {}, {b_cu_pad}); @@ -773,28 +823,24 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad * stages kDown zero patch columns at the end of each row, skipped by the pitched pack into * `pixstg`), then the position table added in: a row gather, from the 64x64 plane at the 64 * grid (exact, unchanged) and the staged 40x40 resample at 40. */ - op_patch = rw(b, gemm_b(b, kSamTok, DeepEncoder::kSamW, DeepEncoder::kPatchDim, "none", - w.w_patch, w.b_patch), {}, {b_x}); - op_ids_sam = rw(b, RAD_OP(b, "iota", - RAD_PARAMS(RAD_INT("M", kSamTok), RAD_INT("start", 0), RAD_INT("step", 1)), - RAD_NOWEIGHTS), - {}, {b_ids_sam}); + op_patch = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kPatchDim, "none", + w.w_patch, w.b_patch), {b_pixstg}, {b_x}); if (!is40) op_sampos = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n_embd", DeepEncoder::kSamW), RAD_INT("n_vocab", kSamTok), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w.w_pos)), {b_ids_sam}, {b_sampos}); else op_sampos = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_pos_tab, b_ids_sam}, {b_sampos}); op_sampadd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), @@ -802,22 +848,23 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad for (size_t i = 0; i < sam.size(); ++i) { SamLayerT& l = sam[i]; - l.op_n1 = rw(b, lnorm(b, kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n1, l.b_n1), {b_x}, {b_h}); + l.op_n1 = rw(b, lnorm(b, B * kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n1, l.b_n1), + {b_x}, {b_h}); /* The windowed path: `h` into window_partition's padded order with zero pad rows * (a negative gather index is a zero row), so the qkv linear gives the pad rows the * reference's bias -- deepencoder pads AFTER norm1 and runs the whole attention on the * padded window, so a pad key's k and v are the qkv bias, not zero. */ l.op_gpad = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTokP), RAD_INT("n", DeepEncoder::kSamW), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTokP), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_h, b_ids_pad}, {b_hw}); - l.op_qkv = rw(b, gemm_b(b, kSamTok, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.op_qkv = rw(b, gemm_b(b, B * kSamTok, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", l.w_qkv, l.b_qkv), {b_h}, {b_qkv}); - l.op_qkvw = rw(b, gemm_b(b, kSamTokP, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.op_qkvw = rw(b, gemm_b(b, B * kSamTokP, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", l.w_qkv, l.b_qkv), {b_hw}, {b_qkvw}); l.op_attn = rw(b, RAD_OP(b, "sam_attn", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("head_dim", DeepEncoder::kSamHd), RAD_INT("n_head", DeepEncoder::kSamHeads), RAD_INT("grid_h", kGrid), RAD_INT("grid_w", kGrid), @@ -826,7 +873,7 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_WEIGHTS(l.w_rh, l.w_rw)), {b_qkv, b_cu_sam}, {b_att}); l.op_attnw = rw(b, RAD_OP(b, "sam_attn", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTokP), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTokP), RAD_INT("head_dim", DeepEncoder::kSamHd), RAD_INT("n_head", DeepEncoder::kSamHeads), RAD_INT("grid_h", kGridP), RAD_INT("grid_w", kGridP), @@ -835,27 +882,28 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_WEIGHTS(l.w_rh, l.w_rw)), {b_qkvw, b_cu_pad}, {b_attw}); l.op_greal = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_attw, b_ids_real}, {b_att}); - l.op_proj = rw(b, gemm_b(b, kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.op_proj = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamW, "none", l.w_proj, l.b_proj), {b_att}, {b_h}); /* deepencoder rounds the projection before adding the shortcut (`x + attn(norm(x))` * is two bf16 operations), so the residual add is its own op: fusing it into the * GEMM's f32 accumulator skips a rounding and drifts from the reference. */ l.op_padd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_h, b_x}, {b_x}); - l.op_n2 = rw(b, lnorm(b, kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n2, l.b_n2), {b_x}, {b_h}); - l.op_l1 = rw(b, gemm_b(b, kSamTok, DeepEncoder::kSamFf, DeepEncoder::kSamW, "gelu", + l.op_n2 = rw(b, lnorm(b, B * kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n2, l.b_n2), + {b_x}, {b_h}); + l.op_l1 = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamFf, DeepEncoder::kSamW, "gelu", l.w_l1, l.b_l1), {b_h}, {b_ff}); - l.op_l2 = rw(b, gemm_b(b, kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamFf, "none", + l.op_l2 = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamFf, "none", l.w_l2, l.b_l2), {b_ff}, {b_h}); l.op_ladd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_h, b_x}, {b_x}); @@ -864,17 +912,17 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad /* ---- neck. The 1x1 is a GEMM; the 3x3s are unfold + gemm because they carry no bias and * conv2d_nhwc's `b` is required. LayerNorm2d is a layernorm across a pixel's channels, * which are innermost. */ - op_neck0 = rw(b, gemm_u(b, kSamTok, 256, DeepEncoder::kSamW, w.w_neck0), {b_x}, {b_n0}); - op_nk1 = rw(b, lnorm(b, kSamTok, 256, 1e-6f, w.w_nk1, w.b_nk1), {b_n0}, {b_n1}); + op_neck0 = rw(b, gemm_u(b, B * kSamTok, 256, DeepEncoder::kSamW, w.w_neck0), {b_x}, {b_n0}); + op_nk1 = rw(b, lnorm(b, B * kSamTok, 256, 1e-6f, w.w_nk1, w.b_nk1), {b_n0}, {b_n1}); op_unf3 = rw(b, unfold(b, kGrid, kGrid, 256, 1, kGrid), {b_n1, b_cu_sam}, {b_unf3}); - op_nk2 = rw(b, gemm_u(b, kSamTok, 256, 256 * 9, w.w_nk2), {b_unf3}, {b_n2}); - op_nk3 = rw(b, lnorm(b, kSamTok, 256, 1e-6f, w.w_nk3, w.b_nk3), {b_n2}, {b_n3}); + op_nk2 = rw(b, gemm_u(b, B * kSamTok, 256, 256 * 9, w.w_nk2), {b_unf3}, {b_n2}); + op_nk3 = rw(b, lnorm(b, B * kSamTok, 256, 1e-6f, w.w_nk3, w.b_nk3), {b_n2}, {b_n3}); op_unf_net2 = rw(b, unfold(b, kGrid, kGrid, 256, 2, kGrid), {b_n3, b_cu_sam}, {b_unf_2}); - op_net2 = rw(b, gemm_u(b, kSamTok / 4, 512, 256 * 9, w.w_net2), {b_unf_2}, {b_map2}); + op_net2 = rw(b, gemm_u(b, B * kSamTok / 4, 512, 256 * 9, w.w_net2), {b_unf_2}, {b_map2}); op_unf_net3 = rw(b, unfold(b, kGrid / 2, kGrid / 2, 512, 2, kGrid * 2), {b_map2, b_cu_sam}, {b_unf_3}); - op_net3 = rw(b, gemm_u(b, kMap * kMap, DeepEncoder::kClipW, 512 * 9, w.w_net3), {b_unf_3}, - {b_map}); + op_net3 = rw(b, gemm_u(b, B * kMap * kMap, DeepEncoder::kClipW, 512 * 9, w.w_net3), + {b_unf_3}, {b_map}); /* ---- CLIP. The class row goes first and the map's rows below it: absolute position * pairs row for row, and attention is permutation-equivariant, so the class row's place @@ -890,33 +938,28 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), RAD_NOWEIGHTS), {b_map}, {b_c}); - op_ids_clip = rw(b, RAD_OP(b, "iota", - RAD_PARAMS(RAD_INT("M", kClipTok), RAD_INT("start", 0), - RAD_INT("step", 1)), - RAD_NOWEIGHTS), - {}, {b_ids_clip}); if (!is40) op_cpos = rw(b, RAD_OP(b, "embed_lookup", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n_embd", DeepEncoder::kClipW), RAD_INT("n_vocab", kClipTok), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w.w_cpos)), {b_ids_clip}, {b_cpos}); else op_cpos = rw(b, RAD_OP(b, "gather_rows", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n", DeepEncoder::kClipW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_cpos_tab, b_ids_clip}, {b_cpos}); op_cadd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n", DeepEncoder::kClipW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_c, b_cpos}, {b_c}); - op_playr = rw(b, lnorm(b, kClipTok, DeepEncoder::kClipW, 1e-5f, w.w_playr, w.b_playr), {b_c}, - {b_cp}); + op_playr = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, w.w_playr, w.b_playr), + {b_c}, {b_cp}); /* deepencoder normalises the embedding once (pre_layrnorm) and the transformer's residual * stream starts there, not at the embedding: layer 0's norm1 and its residual add both * read the pre_layrnorm output. */ @@ -927,12 +970,12 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad {b_cp}, {b_c}); for (ClipLayerT& l : clip) { - l.op_n1 = rw(b, lnorm(b, kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n1, l.b_n1), {b_c}, - {b_ch}); - l.op_qkv = rw(b, gemm_b(b, kClipTok, 3 * DeepEncoder::kClipW, DeepEncoder::kClipW, "none", - l.w_qkv, l.b_qkv), {b_ch}, {b_cq}); + l.op_n1 = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n1, l.b_n1), + {b_c}, {b_ch}); + l.op_qkv = rw(b, gemm_b(b, B * kClipTok, 3 * DeepEncoder::kClipW, DeepEncoder::kClipW, + "none", l.w_qkv, l.b_qkv), {b_ch}, {b_cq}); l.op_attn = rw(b, RAD_OP(b, "attn_dense", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("head_dim", DeepEncoder::kClipHd), RAD_INT("gqa", 1), RAD_INT("causal", 0), RAD_F64("scale", 1.0 / 8.0), RAD_INT("cu_div", 1), @@ -940,32 +983,32 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_cq, b_cu_clip}, {b_ca}); - l.op_out = rw(b, gemm_b(b, kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipW, "none", + l.op_out = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipW, "none", l.w_out, l.b_out), {b_ca}, {b_ct}); l.op_cadd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n", DeepEncoder::kClipW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_ct, b_c}, {b_c}); - l.op_n2 = rw(b, lnorm(b, kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n2, l.b_n2), {b_c}, - {b_ch}); - l.op_fc1 = rw(b, gemm_b(b, kClipTok, DeepEncoder::kClipFf, DeepEncoder::kClipW, "none", + l.op_n2 = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n2, l.b_n2), + {b_c}, {b_ch}); + l.op_fc1 = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipFf, DeepEncoder::kClipW, "none", l.w_fc1, l.b_fc1), {b_ch}, {b_cf}); /* quick_gelu: fc1's output times sigmoid(1.702 * itself), fused into one act. The * kernel rounds the scaled value to bf16 before the sigmoid, which is exactly the * store the unfused mul did, so the fusion is bit-identical to the pair it replaces * (and saves a 257x4096 bf16 round-trip per layer x 24 layers x tile). */ l.op_qg = rw(b, RAD_OP(b, "act_mul", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n", DeepEncoder::kClipFf), RAD_STR("act", "quick_gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {b_cf, b_cf}, {b_cg2}); - l.op_fc2 = rw(b, gemm_b(b, kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipFf, "none", - l.w_fc2, l.b_fc2), {b_cg2}, {b_ct}); + l.op_fc2 = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipFf, + "none", l.w_fc2, l.b_fc2), {b_cg2}, {b_ct}); l.op_madd = rw(b, RAD_OP(b, "add", - RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), RAD_INT("n", DeepEncoder::kClipW), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), @@ -985,7 +1028,7 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), RAD_NOWEIGHTS), {b_map}, {b_fuse}); - op_proj = rw(b, gemm_b(b, kMap * kMap, DeepEncoder::kNEmbd, DeepEncoder::kFused, "none", + op_proj = rw(b, gemm_b(b, B * kMap * kMap, DeepEncoder::kNEmbd, DeepEncoder::kFused, "none", w.w_proj, w.b_proj), {b_fuse}, {b_projbuf}); /* Debug taps: one stage's 256 rows into the out buffer instead of the layout. */ op_dbg1024 = rw(b, RAD_OP(b, "cast", @@ -1015,7 +1058,7 @@ int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kNEmbd), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w.w_newline)), - {p_one}, {p_out}); + {p_one}, {b_nlrow}); op_sep = rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kNEmbd), RAD_STR("dtype", "bf16")), @@ -1096,45 +1139,114 @@ void DeepEncoder::Tower::fill_tables(RadCtx* c, const DeepEncoder& w) const { tabs_done |= (1u << rk); } -/* ------------------------------------------------------------------ tower step / view */ +/* ------------------------------------------------------------------ tower batch step */ +/* The position and window tables do not depend on the pass: tile t reads its own copy of the + * same kSamTok (kClipTok) rows, so Bmax copies are staged once a rank and every batch run + * gathers the first B copies. The window tables carry the tile's own row offset. */ template -void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch0, - int64_t gw, int64_t t, int64_t n, int64_t rowbase, - bool tap, const DeepEncoder& w) const { - /* Tile t of a line: its patches are columns [t*kGrid, t*kGrid + kGrid) of the line's rows, - * each row `gw` patches wide (the last kDown columns are the newline column, never read). */ - const char* pix = (const char*)batch->enc_pixels + (patch0 + t * kGrid) * DeepEncoder::kPatchDim * 2; +void DeepEncoder::Tower::stage_ids(RadCtx* c) const { + const int rk = rad_rank(c); + if (rk < 0 || rk >= 32 || (ids_done & (1u << rk))) return; + std::vector ids_s((size_t)(Bmax * kSamTok)); + std::vector ids_c((size_t)(Bmax * kClipTok)); + std::vector pad((size_t)(Bmax * kSamTokP), -1); + std::vector real((size_t)(Bmax * kSamTok)); + for (int64_t t = 0; t < Bmax; ++t) { + for (int64_t r = 0; r < kSamTok; ++r) + ids_s[(size_t)(t * kSamTok + r)] = (int32_t)r; + for (int64_t r = 0; r < kClipTok; ++r) + ids_c[(size_t)(t * kClipTok + r)] = (int32_t)r; + for (int64_t r = 0; r < kGrid; ++r) + for (int64_t cc = 0; cc < kGrid; ++cc) { + pad[(size_t)(t * kSamTokP + r * kGridP + cc)] = + (int32_t)(t * kSamTok + r * kGrid + cc); + real[(size_t)(t * kSamTok + r * kGrid + cc)] = + (int32_t)(t * kSamTokP + r * kGridP + cc); + } + } + void* p_ids_s = rad_buf_ptr(c, b_ids_sam); + void* p_ids_c = rad_buf_ptr(c, b_ids_clip); + void* p_pad = rad_buf_ptr(c, b_ids_pad); + void* p_real = rad_buf_ptr(c, b_ids_real); + if (!p_ids_s || !p_ids_c || !p_pad || !p_real) { + rad_step_fail(c, "unlimitedocr: a staged index table of the DeepEncoder did not bind"); + return; + } + if (rad_memcpy_async(p_ids_s, ids_s.data(), (int64_t)(ids_s.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_ids_c, ids_c.data(), (int64_t)(ids_c.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_pad, pad.data(), (int64_t)(pad.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_real, real.data(), (int64_t)(real.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_stream_sync(rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the staged index tables of the DeepEncoder could not be " + "filled"); + return; + } + ids_done |= (1u << rk); +} - /* The patch embed: one pitched copy packs the tile's grid rows out of the line's rows (the - * kDown zero patch columns at each row's end are the copy's dead space, skipped like the - * old per-row GEMMs skipped them), then ONE GEMM over M = kGrid*kGrid replaces the launch - * of kGrid M=kGrid GEMMs. The copy rides the pass's stream, ordered with the ops. */ +/* One batched tower run over `nt` staged tiles. Tile t's rows are [t*kSamTok, (t+1)*kSamTok) of + * every SAM plane (and its CLIP block at [t*kClipTok, (t+1)*kClipTok)); the segment-bounded ops + * read a B+1-entry cu table, so attention and the unfolds never see across a tile. */ +template +void DeepEncoder::Tower::batch(RadCtx* c, const RadBatch* batch, const Tile* tiles, + int64_t nt, bool tap, const DeepEncoder& w) { + if (nt < 1 || nt > Bmax) { + rad_step_fail(c, "unlimitedocr: a DeepEncoder batch exceeded the declared tile bound"); + return; + } + /* The 40 tower stages its resampled position tables once on the rank's first tile pass. */ + if (b_pos_tab) fill_tables(c, w); + stage_ids(c); + + const int64_t BT = nt * kSamTok; + const int64_t BTP = nt * kSamTokP; + const int64_t BCT = nt * kClipTok; + const int64_t BM = nt * kMap * kMap; + + /* The patch embed: one pitched copy a tile packs its grid rows out of the line's rows (the + * kDown zero patch columns at each row's end are the copy's dead space), then ONE GEMM over + * all B tiles. The copies ride the pass's stream, ordered with the ops. */ char* stg = (char*)rad_buf_ptr(c, b_pixstg); const int64_t rowb = kGrid * DeepEncoder::kPatchDim * 2; - if (!stg || - rad_memcpy_2d_async(stg, rowb, pix, gw * DeepEncoder::kPatchDim * 2, rowb, kGrid, - rad_stream(c)) < 0) { + if (!stg) { rad_step_fail(c, "unlimitedocr: the patch rows of the DeepEncoder could not be packed"); return; } - RAD_ISSUE(c, op_patch, - RAD_P_T2(stg, RAD_BF16, kSamTok, DeepEncoder::kPatchDim), - RAD_W(w.w_patch), RAD_W(w.b_patch), RAD_NONE, - brow_slice(b_x, 0, kSamTok, DeepEncoder::kSamW)); + for (int64_t t = 0; t < nt; ++t) { + const char* pix = (const char*)batch->enc_pixels + + (tiles[t].patch0 + tiles[t].t * kGrid) * DeepEncoder::kPatchDim * 2; + char* dst = stg + t * kSamTok * DeepEncoder::kPatchDim * 2; + if (rad_memcpy_2d_async(dst, rowb, pix, tiles[t].gw * DeepEncoder::kPatchDim * 2, + rowb, kGrid, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the patch rows of the DeepEncoder could not be packed"); + return; + } + } + RAD_ISSUE_N(c, op_patch, BT, + RAD_P_T2(stg, RAD_BF16, BT, DeepEncoder::kPatchDim), + RAD_W(w.w_patch), RAD_W(w.b_patch), RAD_NONE, + brow_slice(b_x, 0, BT, DeepEncoder::kSamW)); + + /* The pass's segment tables: B tiles, a bound each. */ + RAD_ISSUE_N(c, op_cu_sam, nt + 1, brows(b_cu_sam, nt + 1)); + RAD_ISSUE_N(c, op_cu_clip, nt + 1, brows(b_cu_clip, nt + 1)); + RAD_ISSUE_N(c, op_cu_pad, nt + 1, brows(b_cu_pad, nt + 1)); /* The position table, a row for a token (a gather, exact at 64 and from the staged - * resample at 40), added in. */ + * resample at 40), added in. The ids repeat per tile, so every tile sees the same table. */ if (tap) w.tap(c, "st_emb", b_x, 256, DeepEncoder::kSamW); - RAD_ISSUE(c, op_ids_sam, RAD_B(b_ids_sam)); if (b_pos_tab) - RAD_ISSUE_N(c, op_sampos, kSamTok, RAD_B(b_pos_tab), RAD_B(b_ids_sam), - brows(b_sampos, kSamTok)); + RAD_ISSUE_N(c, op_sampos, BT, RAD_B(b_pos_tab), brows(b_ids_sam, BT), + brows(b_sampos, BT)); else - RAD_ISSUE_N(c, op_sampos, kSamTok, RAD_B(b_ids_sam), RAD_W(w.w_pos), - brows(b_sampos, kSamTok)); + RAD_ISSUE_N(c, op_sampos, BT, brows(b_ids_sam, BT), RAD_W(w.w_pos), + brows(b_sampos, BT)); if (tap) w.tap(c, "st_sampos", b_sampos, 256, DeepEncoder::kSamW); - RAD_ISSUE_N(c, op_sampadd, kSamTok, brows(b_x, kSamTok), brows(b_sampos, kSamTok), - brows(b_x, kSamTok)); + RAD_ISSUE_N(c, op_sampadd, BT, brows(b_x, BT), brows(b_sampos, BT), brows(b_x, BT)); if (tap) w.tap(c, "st_x0", b_x, 256, DeepEncoder::kSamW); if (dbg == 10) { @@ -1145,32 +1257,32 @@ void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch for (size_t li = 0; li < sam.size(); ++li) { const SamLayerT& l = sam[li]; - RAD_ISSUE_N(c, l.op_n1, kSamTok, brows(b_x, kSamTok), RAD_W(l.w_n1), RAD_W(l.b_n1), - brows(b_h, kSamTok)); + RAD_ISSUE_N(c, l.op_n1, BT, brows(b_x, BT), RAD_W(l.w_n1), RAD_W(l.b_n1), + brows(b_h, BT)); if (l.window > 0) { /* The reference's window path: pad the normed grid to a multiple of 14, run qkv * over the pad rows too (they carry the qkv bias), attend inside each 14x14 window, * and take the real rows back out. The pad rows take softmax mass with the bias as v. */ - RAD_ISSUE_N(c, l.op_gpad, kSamTokP, brows(b_h, kSamTok), RAD_B(b_ids_pad), - brows(b_hw, kSamTokP)); - RAD_ISSUE_N(c, l.op_qkvw, kSamTokP, brows(b_hw, kSamTokP), RAD_W(l.w_qkv), - RAD_W(l.b_qkv), RAD_NONE, brows(b_qkvw, kSamTokP)); - RAD_ISSUE_N(c, l.op_attnw, kSamTokP, - bcol(b_qkvw, 0, DeepEncoder::kSamW, kSamTokP), - bcol(b_qkvw, DeepEncoder::kSamW, DeepEncoder::kSamW, kSamTokP), - bcol(b_qkvw, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, kSamTokP), - RAD_B(b_cu_pad), brows(b_attw, kSamTokP), + RAD_ISSUE_N(c, l.op_gpad, BTP, brows(b_h, BT), brows(b_ids_pad, BTP), + brows(b_hw, BTP)); + RAD_ISSUE_N(c, l.op_qkvw, BTP, brows(b_hw, BTP), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_qkvw, BTP)); + RAD_ISSUE_N(c, l.op_attnw, BTP, + bcol(b_qkvw, 0, DeepEncoder::kSamW, BTP), + bcol(b_qkvw, DeepEncoder::kSamW, DeepEncoder::kSamW, BTP), + bcol(b_qkvw, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, BTP), + brows(b_cu_pad, nt + 1), brows(b_attw, BTP), RAD_W(l.w_rh), RAD_W(l.w_rw)); - RAD_ISSUE_N(c, l.op_greal, kSamTok, brows(b_attw, kSamTokP), RAD_B(b_ids_real), - brows(b_att, kSamTok)); + RAD_ISSUE_N(c, l.op_greal, BT, brows(b_attw, BTP), brows(b_ids_real, BT), + brows(b_att, BT)); } else { - RAD_ISSUE_N(c, l.op_qkv, kSamTok, brows(b_h, kSamTok), RAD_W(l.w_qkv), - RAD_W(l.b_qkv), RAD_NONE, brows(b_qkv, kSamTok)); - RAD_ISSUE_N(c, l.op_attn, kSamTok, - bcol(b_qkv, 0, DeepEncoder::kSamW, kSamTok), - bcol(b_qkv, DeepEncoder::kSamW, DeepEncoder::kSamW, kSamTok), - bcol(b_qkv, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, kSamTok), - RAD_B(b_cu_sam), brows(b_att, kSamTok), + RAD_ISSUE_N(c, l.op_qkv, BT, brows(b_h, BT), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_qkv, BT)); + RAD_ISSUE_N(c, l.op_attn, BT, + bcol(b_qkv, 0, DeepEncoder::kSamW, BT), + bcol(b_qkv, DeepEncoder::kSamW, DeepEncoder::kSamW, BT), + bcol(b_qkv, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, BT), + brows(b_cu_sam, nt + 1), brows(b_att, BT), RAD_W(l.w_rh), RAD_W(l.w_rw)); } char tag[40]; @@ -1181,10 +1293,9 @@ void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch bcol(p_out, 0, DeepEncoder::kSamW, 256)); return; } - RAD_ISSUE_N(c, l.op_proj, kSamTok, brows(b_att, kSamTok), RAD_W(l.w_proj), - RAD_W(l.b_proj), RAD_NONE, brows(b_h, kSamTok)); - RAD_ISSUE_N(c, l.op_padd, kSamTok, brows(b_h, kSamTok), brows(b_x, kSamTok), - brows(b_x, kSamTok)); + RAD_ISSUE_N(c, l.op_proj, BT, brows(b_att, BT), RAD_W(l.w_proj), + RAD_W(l.b_proj), RAD_NONE, brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_padd, BT, brows(b_h, BT), brows(b_x, BT), brows(b_x, BT)); std::snprintf(tag, sizeof tag, "st_pre%lld", (long long)li); if (tap) w.tap(c, tag, b_x, 256, DeepEncoder::kSamW); if (dbg >= 70 && dbg < 70 + (int)DeepEncoder::kSamDepth && dbg == 70 + (int)li) { @@ -1192,14 +1303,13 @@ void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch bcol(p_out, 0, DeepEncoder::kSamW, 256)); return; } - RAD_ISSUE_N(c, l.op_n2, kSamTok, brows(b_x, kSamTok), RAD_W(l.w_n2), RAD_W(l.b_n2), - brows(b_h, kSamTok)); - RAD_ISSUE_N(c, l.op_l1, kSamTok, brows(b_h, kSamTok), RAD_W(l.w_l1), RAD_W(l.b_l1), - RAD_NONE, brows(b_ff, kSamTok)); - RAD_ISSUE_N(c, l.op_l2, kSamTok, brows(b_ff, kSamTok), RAD_W(l.w_l2), RAD_W(l.b_l2), - RAD_NONE, brows(b_h, kSamTok)); - RAD_ISSUE_N(c, l.op_ladd, kSamTok, brows(b_h, kSamTok), brows(b_x, kSamTok), - brows(b_x, kSamTok)); + RAD_ISSUE_N(c, l.op_n2, BT, brows(b_x, BT), RAD_W(l.w_n2), RAD_W(l.b_n2), + brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_l1, BT, brows(b_h, BT), RAD_W(l.w_l1), RAD_W(l.b_l1), + RAD_NONE, brows(b_ff, BT)); + RAD_ISSUE_N(c, l.op_l2, BT, brows(b_ff, BT), RAD_W(l.w_l2), RAD_W(l.b_l2), + RAD_NONE, brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_ladd, BT, brows(b_h, BT), brows(b_x, BT), brows(b_x, BT)); std::snprintf(tag, sizeof tag, "st_b%lld", (long long)li); if (tap) w.tap(c, tag, b_x, 256, DeepEncoder::kSamW); if (li < 3) { @@ -1213,123 +1323,128 @@ void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch } } - /* neck + net_2 + net_3. The 3x3s are a dense view of the map rows, unfolded. */ - RAD_ISSUE_N(c, op_neck0, kSamTok, brows(b_x, kSamTok), RAD_W(w.w_neck0), - brows(b_n0, kSamTok)); + /* neck + net_2 + net_3. The 3x3s are a dense view of the map rows, unfolded; the cu table + * gives each tile its own grid. */ + RAD_ISSUE_N(c, op_neck0, BT, brows(b_x, BT), RAD_W(w.w_neck0), brows(b_n0, BT)); if (tap) w.tap(c, "st_n0", b_n0, 256, 256); if (dbg == 30) { RAD_ISSUE(c, op_dbg256, brows(b_n0, 256), bcol(p_out, 0, 256, 256)); return; } - RAD_ISSUE_N(c, op_nk1, kSamTok, brows(b_n0, kSamTok), RAD_W(w.w_nk1), RAD_W(w.b_nk1), - brows(b_n1, kSamTok)); + RAD_ISSUE_N(c, op_nk1, BT, brows(b_n0, BT), RAD_W(w.w_nk1), RAD_W(w.b_nk1), + brows(b_n1, BT)); if (tap) w.tap(c, "st_n1", b_n1, 256, 256); if (dbg == 31) { RAD_ISSUE(c, op_dbg256, brows(b_n1, 256), bcol(p_out, 0, 256, 256)); return; } RAD_ISSUE(c, op_unf3, - RAD_P_T2(rad_buf_ptr(c, b_n1), RAD_BF16, kGrid, kGrid * 256), - RAD_B(b_cu_sam), RAD_NONE, brows(b_unf3, kSamTok)); - RAD_ISSUE_N(c, op_nk2, kSamTok, brows(b_unf3, kSamTok), RAD_W(w.w_nk2), - brows(b_n2, kSamTok)); + RAD_P_T2(rad_buf_ptr(c, b_n1), RAD_BF16, nt * kGrid, kGrid * 256), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf3, BT)); + RAD_ISSUE_N(c, op_nk2, BT, brows(b_unf3, BT), RAD_W(w.w_nk2), brows(b_n2, BT)); if (tap) w.tap(c, "st_n2", b_n2, 256, 256); if (dbg == 32) { RAD_ISSUE(c, op_dbg256, brows(b_n2, 256), bcol(p_out, 0, 256, 256)); return; } - RAD_ISSUE_N(c, op_nk3, kSamTok, brows(b_n2, kSamTok), RAD_W(w.w_nk3), RAD_W(w.b_nk3), - brows(b_n3, kSamTok)); + RAD_ISSUE_N(c, op_nk3, BT, brows(b_n2, BT), RAD_W(w.w_nk3), RAD_W(w.b_nk3), + brows(b_n3, BT)); if (tap) w.tap(c, "st_n3", b_n3, 256, 256); if (dbg == 33) { RAD_ISSUE(c, op_dbg256, brows(b_n3, 256), bcol(p_out, 0, 256, 256)); return; } RAD_ISSUE(c, op_unf_net2, - RAD_P_T2(rad_buf_ptr(c, b_n3), RAD_BF16, kGrid, kGrid * 256), - RAD_B(b_cu_sam), RAD_NONE, brows(b_unf_2, kSamTok / 4)); + RAD_P_T2(rad_buf_ptr(c, b_n3), RAD_BF16, nt * kGrid, kGrid * 256), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf_2, nt * kSamTok / 4)); if (dbg == 40) { RAD_ISSUE(c, op_dbg1024, brows(b_unf_2, 256), bcol(p_out, 0, DeepEncoder::kClipW, 256)); return; } - RAD_ISSUE_N(c, op_net2, kSamTok / 4, brows(b_unf_2, kSamTok / 4), RAD_W(w.w_net2), - brows(b_map2, kSamTok / 4)); + RAD_ISSUE_N(c, op_net2, nt * kSamTok / 4, brows(b_unf_2, nt * kSamTok / 4), + RAD_W(w.w_net2), brows(b_map2, nt * kSamTok / 4)); if (tap) w.tap(c, "st_map2", b_map2, 256, 512); RAD_ISSUE(c, op_unf_net3, - RAD_P_T2(rad_buf_ptr(c, b_map2), RAD_BF16, kGrid / 2, (kGrid / 2) * 512), - RAD_B(b_cu_sam), RAD_NONE, brows(b_unf_3, kMap * kMap)); + RAD_P_T2(rad_buf_ptr(c, b_map2), RAD_BF16, nt * kGrid / 2, (kGrid / 2) * 512), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf_3, BM)); if (dbg == 34) { RAD_ISSUE(c, op_dbg256, brows(b_map2, 256), bcol(p_out, 0, 256, 256)); return; } - RAD_ISSUE_N(c, op_net3, kMap * kMap, brows(b_unf_3, kMap * kMap), RAD_W(w.w_net3), - brows(b_map, kMap * kMap)); + RAD_ISSUE_N(c, op_net3, BM, brows(b_unf_3, BM), RAD_W(w.w_net3), brows(b_map, BM)); if (tap) w.tap(c, "st_map", b_map, kMap * kMap, DeepEncoder::kClipW); - /* CLIP: the class row, the map, the absolute table. */ - RAD_ISSUE(c, op_cls, RAD_B(p_one_c), RAD_W(w.w_cls), brow_slice(b_c, 0, 1, DeepEncoder::kClipW)); - RAD_ISSUE(c, op_cmap, bcol(b_map, 0, DeepEncoder::kClipW, kMap * kMap), - brow_slice(b_c, 1, kMap * kMap, DeepEncoder::kClipW)); - RAD_ISSUE(c, op_ids_clip, RAD_B(b_ids_clip)); + /* CLIP: the class row and the map, tile by tile (each block's rows are strided in the + * tile-major plane), then the batched transformer and absolute table. */ + for (int64_t t = 0; t < nt; ++t) { + RAD_ISSUE(c, op_cls, RAD_B(p_one_c), RAD_W(w.w_cls), + brow_slice(b_c, t * kClipTok, 1, DeepEncoder::kClipW)); + RAD_ISSUE(c, op_cmap, + brow_slice(b_map, t * kMap * kMap, kMap * kMap, DeepEncoder::kClipW), + brow_slice(b_c, t * kClipTok + 1, kMap * kMap, DeepEncoder::kClipW)); + } if (b_cpos_tab) - RAD_ISSUE_N(c, op_cpos, kClipTok, RAD_B(b_cpos_tab), RAD_B(b_ids_clip), - brows(b_cpos, kClipTok)); + RAD_ISSUE_N(c, op_cpos, BCT, RAD_B(b_cpos_tab), brows(b_ids_clip, BCT), + brows(b_cpos, BCT)); else - RAD_ISSUE_N(c, op_cpos, kClipTok, RAD_B(b_ids_clip), RAD_W(w.w_cpos), - brows(b_cpos, kClipTok)); - RAD_ISSUE_N(c, op_cadd, kClipTok, brows(b_c, kClipTok), brows(b_cpos, kClipTok), - brows(b_c, kClipTok)); + RAD_ISSUE_N(c, op_cpos, BCT, brows(b_ids_clip, BCT), RAD_W(w.w_cpos), + brows(b_cpos, BCT)); + RAD_ISSUE_N(c, op_cadd, BCT, brows(b_c, BCT), brows(b_cpos, BCT), brows(b_c, BCT)); if (tap) w.tap(c, "clip_x", b_c, kClipTok, DeepEncoder::kClipW); - RAD_ISSUE_N(c, op_playr, kClipTok, brows(b_c, kClipTok), RAD_W(w.w_playr), - RAD_W(w.b_playr), brows(b_cp, kClipTok)); - RAD_ISSUE_N(c, op_ccopy, kClipTok, brows(b_cp, kClipTok), brows(b_c, kClipTok)); + RAD_ISSUE_N(c, op_playr, BCT, brows(b_c, BCT), RAD_W(w.w_playr), + RAD_W(w.b_playr), brows(b_cp, BCT)); + RAD_ISSUE_N(c, op_ccopy, BCT, brows(b_cp, BCT), brows(b_c, BCT)); for (size_t ci = 0; ci < clip.size(); ++ci) { const ClipLayerT& l = clip[ci]; char ctag[40]; - RAD_ISSUE_N(c, l.op_n1, kClipTok, brows(b_c, kClipTok), RAD_W(l.w_n1), - RAD_W(l.b_n1), brows(b_ch, kClipTok)); + RAD_ISSUE_N(c, l.op_n1, BCT, brows(b_c, BCT), RAD_W(l.w_n1), + RAD_W(l.b_n1), brows(b_ch, BCT)); std::snprintf(ctag, sizeof ctag, "clip_pre%lld", (long long)ci); if (tap) w.tap(c, ctag, b_ch, kClipTok, DeepEncoder::kClipW); - RAD_ISSUE_N(c, l.op_qkv, kClipTok, brows(b_ch, kClipTok), RAD_W(l.w_qkv), - RAD_W(l.b_qkv), RAD_NONE, brows(b_cq, kClipTok)); - RAD_ISSUE_N(c, l.op_attn, kClipTok, - bcol(b_cq, 0, DeepEncoder::kClipW, kClipTok), - bcol(b_cq, DeepEncoder::kClipW, DeepEncoder::kClipW, kClipTok), - bcol(b_cq, 2 * DeepEncoder::kClipW, DeepEncoder::kClipW, kClipTok), - RAD_B(b_cu_clip), brows(b_ca, kClipTok)); + RAD_ISSUE_N(c, l.op_qkv, BCT, brows(b_ch, BCT), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_cq, BCT)); + RAD_ISSUE_N(c, l.op_attn, BCT, + bcol(b_cq, 0, DeepEncoder::kClipW, BCT), + bcol(b_cq, DeepEncoder::kClipW, DeepEncoder::kClipW, BCT), + bcol(b_cq, 2 * DeepEncoder::kClipW, DeepEncoder::kClipW, BCT), + brows(b_cu_clip, nt + 1), brows(b_ca, BCT)); std::snprintf(ctag, sizeof ctag, "clip_att%lld", (long long)ci); if (tap) w.tap(c, ctag, b_ca, kClipTok, DeepEncoder::kClipW); - RAD_ISSUE_N(c, l.op_out, kClipTok, brows(b_ca, kClipTok), RAD_W(l.w_out), - RAD_W(l.b_out), RAD_NONE, brows(b_ct, kClipTok)); - RAD_ISSUE_N(c, l.op_cadd, kClipTok, brows(b_ct, kClipTok), brows(b_c, kClipTok), - brows(b_c, kClipTok)); + RAD_ISSUE_N(c, l.op_out, BCT, brows(b_ca, BCT), RAD_W(l.w_out), + RAD_W(l.b_out), RAD_NONE, brows(b_ct, BCT)); + RAD_ISSUE_N(c, l.op_cadd, BCT, brows(b_ct, BCT), brows(b_c, BCT), brows(b_c, BCT)); std::snprintf(ctag, sizeof ctag, "clip_h%lld", (long long)ci); if (tap) w.tap(c, ctag, b_c, kClipTok, DeepEncoder::kClipW); - RAD_ISSUE_N(c, l.op_n2, kClipTok, brows(b_c, kClipTok), RAD_W(l.w_n2), - RAD_W(l.b_n2), brows(b_ch, kClipTok)); - RAD_ISSUE_N(c, l.op_fc1, kClipTok, brows(b_ch, kClipTok), RAD_W(l.w_fc1), - RAD_W(l.b_fc1), RAD_NONE, brows(b_cf, kClipTok)); - RAD_ISSUE_N(c, l.op_qg, kClipTok, brows(b_cf, kClipTok), brows(b_cf, kClipTok), - brows(b_cg2, kClipTok)); - RAD_ISSUE_N(c, l.op_fc2, kClipTok, brows(b_cg2, kClipTok), RAD_W(l.w_fc2), - RAD_W(l.b_fc2), RAD_NONE, brows(b_ct, kClipTok)); - RAD_ISSUE_N(c, l.op_madd, kClipTok, brows(b_ct, kClipTok), brows(b_c, kClipTok), - brows(b_c, kClipTok)); + RAD_ISSUE_N(c, l.op_n2, BCT, brows(b_c, BCT), RAD_W(l.w_n2), + RAD_W(l.b_n2), brows(b_ch, BCT)); + RAD_ISSUE_N(c, l.op_fc1, BCT, brows(b_ch, BCT), RAD_W(l.w_fc1), + RAD_W(l.b_fc1), RAD_NONE, brows(b_cf, BCT)); + RAD_ISSUE_N(c, l.op_qg, BCT, brows(b_cf, BCT), brows(b_cf, BCT), + brows(b_cg2, BCT)); + RAD_ISSUE_N(c, l.op_fc2, BCT, brows(b_cg2, BCT), RAD_W(l.w_fc2), + RAD_W(l.b_fc2), RAD_NONE, brows(b_ct, BCT)); + RAD_ISSUE_N(c, l.op_madd, BCT, brows(b_ct, BCT), brows(b_c, BCT), brows(b_c, BCT)); std::snprintf(ctag, sizeof ctag, "clip_b%lld", (long long)ci); if (tap) w.tap(c, ctag, b_c, kClipTok, DeepEncoder::kClipW); } if (tap) w.tap(c, "clip_out", b_c, kMap * kMap, DeepEncoder::kClipW, 1); - /* Fuse (CLIP's patch rows | the map) and project. */ - RAD_ISSUE(c, op_fuse_clip, brow_slice(b_c, 1, kMap * kMap, DeepEncoder::kClipW), - bcol(b_fuse, 0, DeepEncoder::kClipW, kMap * kMap)); - RAD_ISSUE(c, op_fuse_sam, bcol(b_map, 0, DeepEncoder::kClipW, kMap * kMap), - bcol(b_fuse, DeepEncoder::kClipW, DeepEncoder::kClipW, kMap * kMap)); + /* Fuse (CLIP's patch rows | the map) and project, tile by tile into the tile-major fuse. */ + for (int64_t t = 0; t < nt; ++t) { + RAD_ISSUE(c, op_fuse_clip, + brow_slice(b_c, t * kClipTok + 1, kMap * kMap, DeepEncoder::kClipW), + bcol_at(b_fuse, t * kMap * kMap, DeepEncoder::kFused, 0, + DeepEncoder::kClipW, kMap * kMap)); + RAD_ISSUE(c, op_fuse_sam, + brow_slice(b_map, t * kMap * kMap, kMap * kMap, DeepEncoder::kClipW), + bcol_at(b_fuse, t * kMap * kMap, DeepEncoder::kFused, DeepEncoder::kClipW, + DeepEncoder::kClipW, kMap * kMap)); + } if (tap) w.tap(c, "fuse", b_fuse, kMap * kMap, DeepEncoder::kFused); - RAD_ISSUE_N(c, op_proj, kMap * kMap, brows(b_fuse, kMap * kMap), RAD_W(w.w_proj), - RAD_W(w.b_proj), RAD_NONE, brows(b_projbuf, kMap * kMap)); + RAD_ISSUE_N(c, op_proj, BM, brows(b_fuse, BM), RAD_W(w.w_proj), + RAD_W(w.b_proj), RAD_NONE, brows(b_projbuf, BM)); if (tap) w.tap(c, "proj", b_projbuf, kMap * kMap, DeepEncoder::kNEmbd); if (dbg) { @@ -1342,96 +1457,50 @@ void DeepEncoder::Tower::view(RadCtx* c, const RadBatch* batch, int64_t patch return; } - /* The line's layout: tile t's map goes to columns [t*kMap, (t+1)*kMap) of every map row -- - * a pitched copy of the projected tile into the plane (the layout pitch is the line's row + /* The layout: each tile's map goes to columns [t*kMap, (t+1)*kMap) of every map row -- a + * pitched copy of the projected tile into the plane (the layout pitch is the line's row * count plus the newline column), one copy replacing kMap cast-launches. The newline cell - * after the last tile belongs to the line, so segment() writes it once. */ + * after a line's last tile belongs to the line and follows that tile's copy. */ char* po = (char*)rad_buf_ptr(c, p_out); + const char* proj = (const char*)rad_buf_ptr(c, b_projbuf); const int64_t wbytes = kMap * DeepEncoder::kNEmbd * 2; - if (!po || - rad_memcpy_2d_async(po + (rowbase + t * kMap) * DeepEncoder::kNEmbd * 2, - (n * kMap + 1) * DeepEncoder::kNEmbd * 2, - rad_buf_ptr(c, b_projbuf), wbytes, wbytes, kMap, - rad_stream(c)) < 0) { - rad_step_fail(c, "unlimitedocr: the projected map of the DeepEncoder could not be laid " - "out"); + if (!po || !proj) { + rad_step_fail(c, "unlimitedocr: a layout plane of the DeepEncoder did not bind"); return; } -} - -template -void DeepEncoder::Tower::segment(RadCtx* c, const RadBatch* batch, int64_t patch0, - int64_t gw, int64_t n, int64_t rowbase, bool nl, bool tap, - const DeepEncoder& w) { - /* The 40 tower stages its resampled position tables once on the rank's first tile pass. */ - if (b_pos_tab) fill_tables(c, w); - - /* One view's constants for the whole pass. */ - RAD_ISSUE(c, op_cu_sam, RAD_B(b_cu_sam)); - RAD_ISSUE(c, op_cu_clip, RAD_B(b_cu_clip)); - RAD_ISSUE(c, op_cu_pad, RAD_B(b_cu_pad)); - - /* window_partition's two index tables: padded position (r*kGridP + c) holds real row - * r*kGrid + c, every other padded row is the pad (gather -1 = a zero row, which the qkv - * linear turns into the qkv bias). The values are compile-time constants and the planes are - * PERSIST, so each rank stages them once, on its first segment. */ - static const std::vector pad_idx = [] { - std::vector v((size_t)kSamTokP, -1); - for (int64_t r = 0; r < kGrid; ++r) - for (int64_t cc = 0; cc < kGrid; ++cc) - v[(size_t)(r * kGridP + cc)] = (int32_t)(r * kGrid + cc); - return v; - }(); - static const std::vector real_idx = [] { - std::vector v((size_t)kSamTok); - for (int64_t r = 0; r < kGrid; ++r) - for (int64_t cc = 0; cc < kGrid; ++cc) - v[(size_t)(r * kGrid + cc)] = (int32_t)(r * kGridP + cc); - return v; - }(); - const int rk = rad_rank(c); - if (rk >= 0 && rk < 32 && !(ids_done & (1u << rk))) { - void* p_pad = rad_buf_ptr(c, b_ids_pad); - void* p_real = rad_buf_ptr(c, b_ids_real); - if (!p_pad || !p_real) { - rad_step_fail(c, "unlimitedocr: the padded-grid index table of the DeepEncoder did not " - "bind"); - return; - } - if (rad_memcpy_async(p_pad, pad_idx.data(), - (int64_t)(pad_idx.size() * sizeof(int32_t)), - rad_stream(c)) < 0 || - rad_memcpy_async(p_real, real_idx.data(), - (int64_t)(real_idx.size() * sizeof(int32_t)), - rad_stream(c)) < 0) { - rad_step_fail(c, "unlimitedocr: could not stage the DeepEncoder's padded-grid index " - "table"); - return; - } - ids_done |= (1u << rk); - } - - for (int64_t t = 0; t < n; ++t) view(c, batch, patch0, gw, t, n, rowbase, tap && t == 0, w); - - /* The line's newline cell closes each map line: one learned row after the last tile. Only - * the line's last chunk carries it; an earlier chunk ends at its last tile's map. The row - * is computed once and pitched to the line's map rows -- one launch, one copy. */ - if (nl) { - char* nlrow = (char*)rad_buf_ptr(c, b_nlrow); - char* po = (char*)rad_buf_ptr(c, p_out); - if (!nlrow || !po) { - rad_step_fail(c, "unlimitedocr: a layout plane of the DeepEncoder did not bind"); - return; - } - RAD_ISSUE(c, op_newline, RAD_B(p_one), RAD_W(w.w_newline), RAD_B(b_nlrow)); - if (rad_memcpy_2d_async(po + (rowbase + n * kMap) * DeepEncoder::kNEmbd * 2, - (n * kMap + 1) * DeepEncoder::kNEmbd * 2, nlrow, - DeepEncoder::kNEmbd * 2, DeepEncoder::kNEmbd * 2, kMap, - rad_stream(c)) < 0) { - rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder could not be " + for (int64_t t = 0; t < nt; ++t) { + const int64_t rowbase = tiles[t].rowbase; + const int64_t tt = tiles[t].t, n = tiles[t].n; + if (rad_memcpy_2d_async(po + (rowbase + tt * kMap) * DeepEncoder::kNEmbd * 2, + (n * kMap + 1) * DeepEncoder::kNEmbd * 2, + proj + t * kMap * kMap * DeepEncoder::kNEmbd * 2, + wbytes, wbytes, kMap, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the projected map of the DeepEncoder could not be " "laid out"); return; } + if (tiles[t].nl) { + /* The reference expands image_newline over every map row of the line + * (modeling_unlimitedocr.py: `image_newline.expand(h, 1, n_dim)`), so the one + * learned row is replicated into each newline cell. Copy one cell at a time: + * b_nlrow is a single row, and a 2D copy with a zero source pitch is not a + * portable device operation. */ + RAD_ISSUE(c, op_newline, RAD_B(p_one), RAD_W(w.w_newline), RAD_B(b_nlrow)); + const char* nl = (const char*)rad_buf_ptr(c, b_nlrow); + if (!nl) { + rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder did not bind"); + return; + } + for (int64_t r = 0; r < kMap; ++r) { + char* dst = po + ((rowbase + n * kMap) + r * (n * kMap + 1)) * + DeepEncoder::kNEmbd * 2; + if (rad_memcpy_async(dst, nl, DeepEncoder::kNEmbd * 2, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder could " + "not be laid out"); + return; + } + } + } } } diff --git a/arch/unlimitedocr_bf16/attn_llama.h b/arch/unlimitedocr_bf16/attn_llama.h index 6b6916ab..6e81d6f2 100644 --- a/arch/unlimitedocr_bf16/attn_llama.h +++ b/arch/unlimitedocr_bf16/attn_llama.h @@ -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, diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp index 0ab1325b..1a147c95 100644 --- a/core/engine_mm.cpp +++ b/core/engine_mm.cpp @@ -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(std::chrono::steady_clock::now() - t0) - .count()); + const double ms = std::chrono::duration( + 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; } diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 44459b12..57228af7 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -7,8 +7,16 @@ #include #include #include +#include #include +#include #include +#include + +#if defined(__x86_64__) || defined(__i386__) || defined(_M_X64) +#include +#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* 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* 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& row) { + unsigned hw = std::thread::hardware_concurrency(); + const int32_t nt = (int32_t)std::min(rows, (int32_t)std::min(hw ? hw : 1, 8)); + if (nt <= 1) { + for (int32_t y = 0; y < rows; ++y) row(y); + return; + } + std::vector 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& bh, const std::vector& 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 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(); 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) { diff --git a/core/server/adapters.h b/core/server/adapters.h index a1ff5c5a..b658b8e8 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -28,6 +28,8 @@ #include "text/chat.h" #include "text/chatfmt.h" #include "text/chatparse.h" +#include +#include #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( + std::chrono::steady_clock::now() - t0).count(), rc); + return rc; } int32_t audio_rate() const override { diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 6bb422c1..0bac6792 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -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. diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index 7a1056a5..694de1e3 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -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 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(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>(); } diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 11d06658..0b7fd9f3 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -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 diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index e19378dc..c2ad7b62 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -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 diff --git a/libr4d/r4d_sam_attn_bf16.hip b/libr4d/r4d_sam_attn_bf16.hip index 79eb5922..2e587095 100644 --- a/libr4d/r4d_sam_attn_bf16.hip +++ b/libr4d/r4d_sam_attn_bf16.hip @@ -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(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(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, qf); for (int jh = 0; jh < th; ++jh) { const float hr = tab_dot(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(rw, rw_rows, 2 * tw - 1, lw - jw + tw - 1, - qf)); + : (wr_wide ? wr_all[jw] + : tab_dot(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(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(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 +__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(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(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, diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e66f1ee5..a311afb3 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -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. diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 39ba088c..7aa0879f 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -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 @@ -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 sh((size_t)nseg, (int32_t)q), sw((size_t)nseg, (int32_t)(2 * q + 4)); + std::vector cu = { 0, (int32_t)((2 * q + 4) * q), (int32_t)n_patch }; + std::vector 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 sh1 = { (int32_t)q }, sw1 = { (int32_t)(q + 4) }; + std::vector cu1 = { 0, (int32_t)((q + 4) * q) }; + std::vector 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); +} diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp index 4510988b..6bbd8326 100644 --- a/tests/mm_test.cpp +++ b/tests/mm_test.cpp @@ -34,6 +34,7 @@ #include #include #include +#include #include #include #include @@ -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{}; }, + 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 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() diff --git a/tests/r4d_emu/test_attn.cpp b/tests/r4d_emu/test_attn.cpp index 59f94938..aea611c9 100644 --- a/tests/r4d_emu/test_attn.cpp +++ b/tests/r4d_emu/test_attn.cpp @@ -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 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}},