From fad4ba7f1aca9f0f472723396e97022abdae46fd Mon Sep 17 00:00:00 2001 From: Juup Date: Mon, 19 Oct 2026 06:18:47 +0000 Subject: [PATCH] unlimitedocr: the DeepEncoder tower, R-SWA ring KV and the n-gram ban DeepEncoder (arch/common/rad_block_sam.h): the checkpoint's SAM ViT-B/16, neck and CLIP ViT-L/14 producing its 16x17+1 row layout, with a new `sam_attn` op for the windowed, zero-padded SAM attention and its decomposed relative-position bias (libref oracle, libavx kernel, libr4d kernel and selftest). The plugin declares the tower when the container records `radiance.encoder`, and splices its rows over the placeholders after embed_lookup. BOS: the chat path adds BOS when the rendered template does not already start with it. This checkpoint's template is a bare concatenation and its tokenizer states add_bos_token, so without it every position was off by one and the det boxes came out wrong. A media run's placeholders shift with it. R-SWA: RAD_KV_RING, paged like a window group but with a per-sequence floor armed at admission. adv_groups now computes the same clamped seqused and modulo ring slots the builder stages; the mismatch read the block table's -1 padding and faulted the card. Prefill stays causal; prefix cache, checkpoints and speculation are off for the group. Sampling: sample_ngram_ban in libref/libavx/libr4d and the host chain, the request knobs, and the container's generation config (35 over 128). Processor: the checkpoint's grid/mode selection, its tall-last tie order, Pillow's bicubic pass order, and goldens generated from its own code. Tools: --mm-max-patches auto-detection accepts a tower stated as per-width tables under vision_config.image_size, and rad-convert records radiance.encoder. Verified: tower stages match the checkpoint's code (rows cos 0.9998), the device sam_attn selftest is within tolerance, the R-SWA device repro returns text, a GPU e2e reproduces the reference's first det block, and the host suite is 88/89 (known webp decode baseline). --- abi/rad_builder.h | 11 +- arch/common/rad_block_sam.h | 1049 ++++++++++++++++++ arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp | 88 +- core/build/rad_builder.cpp | 9 +- core/engine_bringup.cpp | 57 +- core/engine_mm.cpp | 74 ++ core/gen_config.cpp | 44 +- core/gen_config.h | 14 +- core/mem/kv.cpp | 265 ++++- core/mem/kv.h | 117 +- core/mm/item.cpp | 17 +- core/mm/processor.cpp | 474 +++++++- core/mm/processor.h | 71 +- core/rad_core.h | 8 + core/runtime/kvbind.cpp | 1 + core/sample/host_ref.cpp | 32 +- core/sample/host_ref.h | 11 +- core/sample/sampler.cpp | 77 +- core/sample/sampler.h | 11 + core/sched/advance.h | 10 + core/sched/advance_impl.h | 31 +- core/sched/batch.cpp | 50 +- core/sched/batch.h | 5 + core/sched/geometry.cpp | 8 +- core/sched/mem_iface.h | 49 +- core/sched/scheduler.cpp | 40 +- core/sched/scheduler.h | 7 + core/server/adapters.h | 11 +- core/server/iface.h | 6 + core/server/oai.cpp | 94 +- core/server/oai.h | 5 + data/recipes/unlimited-ocr-bf16.recipe | 13 +- docs/GUIDE.md | 11 + docs/OPS.md | 25 + libavx/CMakeLists.txt | 1 + libavx/avx_cases.cpp | 29 +- libavx/avx_harness.h | 10 + libavx/avx_isa.h | 3 +- libavx/avx_registry.cpp | 24 + libavx/avx_sam_attn.cpp | 168 +++ libavx/avx_sample.cpp | 67 ++ libr4d/CMakeLists.txt | 4 + libr4d/r4d_plugin.h | 6 + libr4d/r4d_rows.cpp | 73 ++ libr4d/r4d_sam_attn_bf16.hip | 206 ++++ libr4d/r4d_sample_ngram_f32.hip | 190 ++++ libr4d/r4d_selftest.cpp | 300 +++++ libref/ref_elementwise.cpp | 4 +- libref/ref_ops.h | 5 + libref/ref_registry.cpp | 32 + libref/ref_sam_attn.cpp | 197 ++++ libref/ref_sample.cpp | 80 ++ libref/ref_shapes.cpp | 48 + tests/advance_test.cpp | 6 +- tests/gen_config_test.cpp | 52 + tests/kv_window_test.cpp | 463 ++++++++ tests/mkuocrgolden.py | 269 +++++ tests/mm_test.cpp | 346 ++++++ tests/p4b_kv_ring_test.cpp | 281 +++++ tests/ref_test.cpp | 522 ++++++++- tests/server_test.cpp | 3 + tests/uocr_golden.h | 138 +++ tools/rad_convert.cpp | 9 +- 63 files changed, 6162 insertions(+), 169 deletions(-) create mode 100644 arch/common/rad_block_sam.h create mode 100644 libavx/avx_sam_attn.cpp create mode 100644 libr4d/r4d_sam_attn_bf16.hip create mode 100644 libr4d/r4d_sample_ngram_f32.hip create mode 100644 libref/ref_sam_attn.cpp create mode 100644 tests/kv_window_test.cpp create mode 100644 tests/mkuocrgolden.py create mode 100644 tests/p4b_kv_ring_test.cpp create mode 100644 tests/uocr_golden.h diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 5b1713c5..1ec666f9 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -310,13 +310,20 @@ enum { RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */ RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */ RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */ - RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */ + RAD_KV_CONV = 3, /* per-sequence, a rolling window of width-1 + num_spec entries */ + /* Paged exactly like RAD_KV_WINDOW, but the window's floor is per sequence and set at + * runtime (R-SWA, spec §7.2): `window` is the ring's W, and a sequence keeps everything from + * position 0 up to its own prompt (prefill and image rows) plus a ring of W slots after it, + * rewritten in place. So the group is sized for the whole context plus one ring a sequence, + * never checkpointed, and never reused from the prefix cache. A model that serves a fixed + * sliding window declares RAD_KV_WINDOW instead. */ + RAD_KV_RING = 4 }; typedef struct RadKVGroupDecl { int kind; /* RAD_KV_* */ uint32_t dtype; - int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */ + int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; 0 otherwise */ int64_t n_head_kv; int64_t head_dim; int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */ diff --git a/arch/common/rad_block_sam.h b/arch/common/rad_block_sam.h new file mode 100644 index 00000000..7d32a789 --- /dev/null +++ b/arch/common/rad_block_sam.h @@ -0,0 +1,1049 @@ +/* rad_block_sam.h -- Unlimited-OCR's DeepEncoder: SAM ViT-B/16, then CLIP ViT-L/14 on its map. + * + * The reference is the checkpoint's own deepencoder.py (cached at /tmp/kilo/uocr/), used by + * modeling_unlimitedocr.py's image branch: + * + * sam_model(1024x1024 picture) -> [1, 1024, 16, 16] + * patch_embed: conv 16x16 stride 16 (768 out), + pos_embed [1,64,64,768] + * 12 blocks, w 768, 12 heads x 64: LayerNorm, qkv, attention with DECOMPOSED RELATIVE + * POSITION (rel_pos_h/rel_pos_w, 27 rows) inside a 14x14 window of the 64x64 patch grid + * (padded to 70x70 = 25 windows), and one 64x64 window on blocks 2, 5, 8 and 11 (tables of + * 127 rows); proj; LayerNorm; mlp 3072 exact gelu; mlp proj + * neck: conv 1x1 256 (no bias), LayerNorm2d 256, conv 3x3 256 (no bias), LayerNorm2d 256 + * net_2: conv 3x3 stride 2 -> 512 at 32x32 (no bias); net_3: -> 1024 at 16x16 (no bias) + * vision_model(patches=the sam map) -> CLIP ViT-L/14, 257 tokens + * class token + the 16x16 map as patch_embeds (NO pixels) + position_embedding[257]; + * pre_layrnorm eps 1e-5; 24 layers, w 1024, 16 heads x 64: LayerNorm, fused qkv, dense + * attention over all 257 tokens, out_proj; LayerNorm; fc1 4096 quick_gelu; fc2 + * fuse: cat(clip rows 1:, the 16x16 map) -> 2048 -> the projector linear -> 1280 + * layout: every map line of 16 rows is closed by `image_newline`, the view by + * `view_seperator` -> 16*(16+1) + 1 = 273 rows for one 1024x1024 view + * + * ============================== THE ONE OP THE ENGINE MUST ADD ============================== + * + * SAM's attention logits are + * + * scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w] + * + * with Rh/Rw read from the relative-position tables at the (query, key) grid offsets. The + * per-pair term is a dot of the query with a vector that depends on BOTH rows, so it folds into + * neither q, k nor v, and no declared op takes a bias operand (attn_dense's operands are + * q, k, v, cu, out). This block therefore declares its attention as `sam_attn`: + * + * params M(range), head_dim, n_head, grid_h, grid_w, window, scale(f64), dtype + * operands q, k, v, cu_seqlens (i32), out -- rows n_head*head_dim each + * weights rel_pos_h, rel_pos_w -- [2*win-1 or 2*grid-1, head_dim] + * for each cu segment of grid_h*grid_w rows in row-major order: with `window` > 0 pad the grid + * to multiples of `window` with zero rows (deepencoder's window_partition pads AFTER norm1; + * the pad rows take part in the softmax exactly as the reference's do), cut it into + * window x window tiles, each tile attending to all of its rows; with `window` 0 one tile is + * the whole segment. logits as above, softmax in f32 over the tile's keys, out = sum_j p v_j, + * written back in the segment's row order with the pad rows dropped. Rh is deepencoder's + * get_rel_pos(table, q_h, k_h): the table at (i_h - j_h + len - 1), linearly interpolated when + * its length is not 2*max(q_h,k_h)-1 (all three geometries here match exactly). + * + * probe() answers whether that op resolves. When it does not, declare() still maps and declares + * every weight (a converted container carries the tower) but declares NO tower op and NO encoder, + * which leaves the plugin on P1's text-only behaviour. Dropping the tables instead is not a + * usable approximation: against them the reference's rows move by cosine 0.35-0.77 (P2 report). + * + * ============================== ROWS AND PATCHES ============================== + * + * core/mm stages one view as a 64 x (64 + 4) grid of 16x16 patch rows: the last kDown = 4 patch + * columns of every row are zeros the encoder must not read. The patch embed therefore runs one + * grid row at a time -- a 64-row GEMM reading that row's first 64 staged patch rows where they + * lie -- so the tower sees exactly the reference's raster 64x64 grid. A view's 272 rows are then + * written with a `image_newline` row closing each 17-row map line, and the view-separator segment + * (an empty kDown x kDown grid) one `view_seperator` row: 273 rows a view at merge 16 (4x4 + * patches a row). A pass may carry several views; every one has this geometry (the base mode's + * 1024 picture). Anything else is refused by name: crops need a resampled position table + * (bicubic antialias, which no op provides) and tiling is the plan's later gundam mode. + */ +#ifndef RAD_BLOCK_SAM_H +#define RAD_BLOCK_SAM_H + +#include + +#include +#include +#include +#include + +namespace rad { +namespace arch { + +struct DeepEncoder { + /* ---- the reference's geometry. */ + static constexpr int64_t kPatch = 16; /* SAM's patch size in pixels */ + static constexpr int64_t kDown = 4; /* patch columns per map token (net_2 x net_3) */ + static constexpr int64_t kGrid = 64; /* 1024 / 16 patches a side */ + static constexpr int64_t kMap = 16; /* kGrid / kDown */ + static constexpr int64_t kWin = 14; /* SAM's window on the patch grid */ + static constexpr int64_t kPadCols = (kWin - kGrid % kWin) % kWin; /* window_partition's pad */ + static constexpr int64_t kGridP = kGrid + kPadCols; /* 70: padded grid side */ + static constexpr int64_t kSamTokP = kGridP * kGridP; /* 4900 padded tokens */ + static constexpr int64_t kSamW = 768; + static constexpr int64_t kSamHeads = 12; + static constexpr int64_t kSamHd = 64; + static constexpr int64_t kSamDepth = 12; + static constexpr int64_t kSamFf = 3072; /* mlp_ratio 4 */ + static constexpr int64_t kSamTok = kGrid * kGrid; /* 4096 */ + static constexpr int64_t kClipW = 1024; + static constexpr int64_t kClipHeads = 16; + static constexpr int64_t kClipHd = 64; + static constexpr int64_t kClipDepth = 24; + static constexpr int64_t kClipFf = 4096; + static constexpr int64_t kClipTok = kMap * kMap + 1; /* 257: cls + the map */ + static constexpr int64_t kFused = 2048; + static constexpr int64_t kNEmbd = 1280; + static constexpr int64_t kPatchDim = 3 * kPatch * kPatch; /* 768: a staged patch row */ + static constexpr int64_t kRowsView = kMap * (kMap + 1) + 1; /* 273 rows of one view */ + static constexpr int64_t kPatchView = kGrid * (kGrid + kDown); /* 4352 staged patches */ + static constexpr int64_t kSegView = kPatchView + kDown * kDown; /* 4368 patches an item */ + static constexpr int64_t kMerge = kDown * kDown; /* 16 patches a row */ + + static bool global_block(int64_t i) { return i == 2 || i == 5 || i == 8 || i == 11; } + + struct SamLayer { + rad_weight w_n1 = 0, b_n1 = 0, w_qkv = 0, b_qkv = 0, w_proj = 0, b_proj = 0; + rad_weight w_rh = 0, w_rw = 0; + rad_weight w_n2 = 0, b_n2 = 0, w_l1 = 0, b_l1 = 0, w_l2 = 0, b_l2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_l1 = 0, op_l2 = 0; + rad_op op_padd = 0, op_ladd = 0; /* the residual adds, rounded apart from the GEMM */ + rad_op op_qkvw = 0, op_attnw = 0; /* the windowed path, over the padded grid */ + rad_op op_gpad = 0, op_greal = 0; /* into window_partition's order, and back */ + int64_t rel_rows = 0; + int64_t window = 0; /* 0 = the whole grid */ + }; + struct ClipLayer { + rad_weight w_n1 = 0, b_n1 = 0, w_qkv = 0, b_qkv = 0, w_out = 0, b_out = 0; + rad_weight w_n2 = 0, b_n2 = 0, w_fc1 = 0, b_fc1 = 0, w_fc2 = 0, b_fc2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0; + rad_op op_cadd = 0, op_madd = 0; /* the residual adds, rounded apart from the GEMM */ + rad_op op_n2 = 0, op_fc1 = 0, op_scale = 0, op_qg = 0, op_fc2 = 0; + }; + + std::vector sam; + std::vector clip; + + /* stems, neck, projector, layout */ + rad_weight w_patch = 0, b_patch = 0, w_pos = 0; + rad_weight w_neck0 = 0, w_nk1 = 0, b_nk1 = 0, w_nk2 = 0, w_nk3 = 0, b_nk3 = 0; + rad_weight w_net2 = 0, w_net3 = 0; + rad_weight w_cls = 0, w_cpos = 0, w_playr = 0, b_playr = 0; + rad_weight w_proj = 0, b_proj = 0, w_newline = 0, w_sep = 0; + + rad_op op_patch = 0, op_ids_sam = 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_cp1 = 0; /* clip[0].norm1 over the pre_layrnorm output */ + 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, op_line = 0; + rad_op op_dbg1024 = 0, op_dbg1280 = 0, op_dbg768 = 0, op_dbg256 = 0; + int dbg = 0, dbg_row = 0; /* RAD_UNLIMITEDOCR_DBG / _ROW: dump one stage, from a row */ + rad_op op_fill_one = 0, op_fill_one_c = 0, op_fill_1702 = 0; + rad_op op_newline = 0, op_sep = 0; + rad_op op_cu_sam = 0, op_cu_clip = 0; /* {0, kSamTok} and {0, kClipTok} */ + rad_op op_cu_pad = 0; /* {0, kSamTokP} */ + rad_op op_gather_pad = 0, op_gather_real = 0; + + /* activations -- one view's, reused by every view a pass carries. */ + rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_sampos = 0; + /* The windowed path's padded grid: h gathered into window_partition's 70x70 order with the pad + * rows zero (so the qkv linear yields the reference's bias on them), then qkv, then attention. + * `hw`/`attw` hold kSamTokP rows. */ + rad_buf b_hw = 0, b_qkvw = 0, b_attw = 0; + rad_buf b_ids_pad = 0, b_ids_real = 0; /* pad position -> real row (-1 pad); the inverse */ + rad_buf b_n0 = 0, b_n1 = 0, b_unf3 = 0, b_n2 = 0, b_n3 = 0; + rad_buf b_unf_2 = 0, b_map2 = 0, b_unf_3 = 0, b_map = 0; + rad_buf b_c = 0, b_ch = 0, b_cq = 0, b_ca = 0, b_cf = 0, b_cg = 0, b_cg2 = 0; + rad_buf b_cpos = 0, b_fuse = 0, b_projbuf = 0; + rad_buf b_ct = 0; /* a CLIP block's projection output, before its residual add */ + /* CLIP's pre_layrnorm output: the first layer's norm1 reads this, every later one the residual + * stream (deepencoder's VitModel normalises once, before the transformer). */ + rad_buf b_cp = 0; + rad_buf b_one = 0, b_one_c = 0, b_c1702 = 0; + rad_buf b_ids_sam = 0, b_ids_clip = 0; + rad_buf b_cu_sam = 0, b_cu_clip = 0, b_cu_pad = 0; + rad_buf b_out = 0; + int64_t max_patches = 0; + int64_t max_views = 0; + bool on = false; + + /* ------------------------------------------------------------------ stage taps + * RADIANCE_DEBUG_MM_BUFFERS names intermediate stages (comma separated; a name matches a tag + * by substring) and RADIANCE_DEBUG_MM_DUMP's directory receives .bf16: raw bf16 rows, one + * file a stage, for a stage-by-stage comparison against a reference encoder. The copy is + * issued on the pass's stream behind the producing op and synced, so it reads the op's output + * (unlike the after-pass dump in core/engine_mm.cpp, which sees each buffer's last writer). */ + static bool tap_names(const char** list, size_t* n) { + static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS"); + static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP"); + *list = env; + *n = 0; + if (!env || !*env || !dir || !*dir) return false; + return true; + } + static bool tap_wants(const char* tag) { + const char* list; size_t n; + if (!tap_names(&list, &n)) return false; + const size_t tl = std::strlen(tag); + for (const char* s = list; *s; ) { + const char* e = s; + while (*e && *e != ',') ++e; + const size_t l = (size_t)(e - s); + if (l) { + for (size_t i = 0; i + l <= tl; ++i) + if (std::strncmp(tag + i, s, l) == 0) return true; + } + s = *e ? e + 1 : e; + } + return false; + } + void tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols, + int64_t off = 0) const { + if (rows <= 0 || cols <= 0 || !tap_wants(tag)) return; + void* p = rad_buf_ptr(c, b); + if (!p) return; + std::vector h((size_t)(rows * cols)); + if (rad_memcpy_async(h.data(), (const char*)p + off * cols * 2, + (size_t)(rows * cols * 2), rad_stream(c)) < 0) return; + rad_stream_sync(rad_stream(c)); + char path[512]; + std::snprintf(path, sizeof path, "%s/tap.%s.bf16", std::getenv("RADIANCE_DEBUG_MM_DUMP"), + tag); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(h.data(), sizeof(uint16_t), h.size(), f); + std::fclose(f); + } + } + + /* ------------------------------------------------------------------ probe / weights */ + /* SAM's attention has no op unless one is added (the note above states it). */ + static bool probe(RadBuilder* b) { return rad_op_declared(b, "sam_attn") != 0; } + + static int wcopy(RadBuilder* b, const char* dn, const char* ck, + std::initializer_list sh, rad_weight* w, RadWeightGroup g, + int access = RAD_ACCESS_PER_REQUEST) { + RAD_ARCH_TRY(map_copy(b, dn, ck)); + *w = decl_w(b, dn, RAD_BF16, sh, access, RAD_SHARD_NONE, g); + return *w ? RAD_OK : RAD_E_INVAL; + } + + /* Every vision tensor, at the checkpoint's names. Always declared, whether or not the tower + * runs, so a converted container is complete for the pass that will. */ + int declare_weights(RadBuilder* b, Names& nm, int grp_base) { + int rc; + const RadWeightGroup gm = grp_model(); + if ((rc = wcopy(b, nm.f("sam.patch_embed.weight"), + nm.ckpt("model.sam_model.patch_embed.proj.weight"), {kSamW, kPatchDim}, + &w_patch, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.patch_embed.bias"), + nm.ckpt("model.sam_model.patch_embed.proj.bias"), {kSamW}, &b_patch, + gm)) != RAD_OK) return rc; + /* pos_embed is [1, 64, 64, 768]: one bf16 plane reshaped, which decl_weight admits. */ + if ((rc = wcopy(b, nm.f("sam.pos_embed"), nm.ckpt("model.sam_model.pos_embed"), + {kSamTok, kSamW}, &w_pos, gm, RAD_ACCESS_VOCAB)) != RAD_OK) return rc; + + sam.assign((size_t)kSamDepth, SamLayer{}); + for (int64_t i = 0; i < kSamDepth; ++i) { + SamLayer& l = sam[(size_t)i]; + const RadWeightGroup g = grp_layer(grp_base + (int)i); + const long long L = (long long)i; + l.rel_rows = global_block(i) ? 2 * kGrid - 1 : 2 * kWin - 1; + l.window = global_block(i) ? 0 : kWin; + /* One checkpoint tensor, its declared name and shape. */ + auto SW = [&](const char* dn, const char* ck, std::initializer_list sh, + rad_weight* w) -> int { + char d[96], k[160]; + std::snprintf(d, sizeof d, "sam.blk.%lld.%s", L, dn); + std::snprintf(k, sizeof k, "model.sam_model.blocks.%lld.%s", L, ck); + return wcopy(b, nm.f("%s", d), nm.ckpt("%s", k), sh, w, g); + }; + if ((rc = SW("attn_norm.weight", "norm1.weight", {kSamW}, &l.w_n1)) != RAD_OK) return rc; + if ((rc = SW("attn_norm.bias", "norm1.bias", {kSamW}, &l.b_n1)) != RAD_OK) return rc; + if ((rc = SW("attn.qkv.weight", "attn.qkv.weight", {3 * kSamW, kSamW}, + &l.w_qkv)) != RAD_OK) return rc; + if ((rc = SW("attn.qkv.bias", "attn.qkv.bias", {3 * kSamW}, &l.b_qkv)) != RAD_OK) + return rc; + if ((rc = SW("attn.proj.weight", "attn.proj.weight", {kSamW, kSamW}, + &l.w_proj)) != RAD_OK) return rc; + if ((rc = SW("attn.proj.bias", "attn.proj.bias", {kSamW}, &l.b_proj)) != RAD_OK) + return rc; + if ((rc = SW("attn.rel_pos_h", "attn.rel_pos_h", {l.rel_rows, kSamHd}, + &l.w_rh)) != RAD_OK) return rc; + if ((rc = SW("attn.rel_pos_w", "attn.rel_pos_w", {l.rel_rows, kSamHd}, + &l.w_rw)) != RAD_OK) return rc; + if ((rc = SW("mlp_norm.weight", "norm2.weight", {kSamW}, &l.w_n2)) != RAD_OK) return rc; + if ((rc = SW("mlp_norm.bias", "norm2.bias", {kSamW}, &l.b_n2)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin1.weight", "mlp.lin1.weight", {kSamFf, kSamW}, + &l.w_l1)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin1.bias", "mlp.lin1.bias", {kSamFf}, &l.b_l1)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin2.weight", "mlp.lin2.weight", {kSamW, kSamFf}, + &l.w_l2)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin2.bias", "mlp.lin2.bias", {kSamW}, &l.b_l2)) != RAD_OK) return rc; + } + + if ((rc = wcopy(b, nm.f("sam.neck.0.weight"), nm.ckpt("model.sam_model.neck.0.weight"), + {256, kSamW}, &w_neck0, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.1.weight"), nm.ckpt("model.sam_model.neck.1.weight"), + {256}, &w_nk1, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.1.bias"), nm.ckpt("model.sam_model.neck.1.bias"), + {256}, &b_nk1, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.2.weight"), nm.ckpt("model.sam_model.neck.2.weight"), + {256, 256 * 9}, &w_nk2, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.3.weight"), nm.ckpt("model.sam_model.neck.3.weight"), + {256}, &w_nk3, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.3.bias"), nm.ckpt("model.sam_model.neck.3.bias"), + {256}, &b_nk3, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.net_2.weight"), nm.ckpt("model.sam_model.net_2.weight"), + {512, 256 * 9}, &w_net2, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.net_3.weight"), nm.ckpt("model.sam_model.net_3.weight"), + {1024, 512 * 9}, &w_net3, gm)) != RAD_OK) return rc; + + const char* cp = "model.vision_model."; + if ((rc = wcopy(b, nm.f("clip.cls"), nm.ckpt("%sembeddings.class_embedding", cp), + {kClipW}, &w_cls, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("clip.pos_embed"), + nm.ckpt("%sembeddings.position_embedding.weight", cp), + {kClipTok, kClipW}, &w_cpos, gm, RAD_ACCESS_VOCAB)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("clip.pre_norm.weight"), nm.ckpt("%spre_layrnorm.weight", cp), + {kClipW}, &w_playr, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("clip.pre_norm.bias"), nm.ckpt("%spre_layrnorm.bias", cp), + {kClipW}, &b_playr, gm)) != RAD_OK) return rc; + + clip.assign((size_t)kClipDepth, ClipLayer{}); + for (int64_t i = 0; i < kClipDepth; ++i) { + ClipLayer& l = clip[(size_t)i]; + const RadWeightGroup g = grp_layer(grp_base + 32 + (int)i); + const long long L = (long long)i; + auto CW = [&](const char* dn, const char* ck, std::initializer_list sh, + rad_weight* w) -> int { + char d[96], k[192]; + std::snprintf(d, sizeof d, "clip.blk.%lld.%s", L, dn); + std::snprintf(k, sizeof k, "model.vision_model.transformer.layers.%lld.%s", L, ck); + return wcopy(b, nm.f("%s", d), nm.ckpt("%s", k), sh, w, g); + }; + if ((rc = CW("attn_norm.weight", "layer_norm1.weight", {kClipW}, &l.w_n1)) != RAD_OK) + return rc; + if ((rc = CW("attn_norm.bias", "layer_norm1.bias", {kClipW}, &l.b_n1)) != RAD_OK) + return rc; + if ((rc = CW("attn.qkv.weight", "self_attn.qkv_proj.weight", {3 * kClipW, kClipW}, + &l.w_qkv)) != RAD_OK) return rc; + if ((rc = CW("attn.qkv.bias", "self_attn.qkv_proj.bias", {3 * kClipW}, + &l.b_qkv)) != RAD_OK) return rc; + if ((rc = CW("attn.out.weight", "self_attn.out_proj.weight", {kClipW, kClipW}, + &l.w_out)) != RAD_OK) return rc; + if ((rc = CW("attn.out.bias", "self_attn.out_proj.bias", {kClipW}, &l.b_out)) != RAD_OK) + return rc; + if ((rc = CW("mlp_norm.weight", "layer_norm2.weight", {kClipW}, &l.w_n2)) != RAD_OK) + return rc; + if ((rc = CW("mlp_norm.bias", "layer_norm2.bias", {kClipW}, &l.b_n2)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc1.weight", "mlp.fc1.weight", {kClipFf, kClipW}, &l.w_fc1)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc1.bias", "mlp.fc1.bias", {kClipFf}, &l.b_fc1)) != RAD_OK) return rc; + if ((rc = CW("mlp.fc2.weight", "mlp.fc2.weight", {kClipW, kClipFf}, &l.w_fc2)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc2.bias", "mlp.fc2.bias", {kClipW}, &l.b_fc2)) != RAD_OK) return rc; + } + + if ((rc = wcopy(b, nm.f("proj.weight"), nm.ckpt("model.projector.layers.weight"), + {kNEmbd, kFused}, &w_proj, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("proj.bias"), nm.ckpt("model.projector.layers.bias"), + {kNEmbd}, &b_proj, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("layout.image_newline"), nm.ckpt("model.image_newline"), + {kNEmbd}, &w_newline, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("layout.view_seperator"), nm.ckpt("model.view_seperator"), + {kNEmbd}, &w_sep, gm)) != RAD_OK) return rc; + return RAD_OK; + } + + /* ------------------------------------------------------------------ op builders */ + static rad_op gemm_b(RadBuilder* b, int64_t max_m, int64_t N, int64_t K, const char* act, + rad_weight w, rad_weight bias) { + return RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("act", act), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + } + static rad_op gemm_u(RadBuilder* b, int64_t max_m, int64_t N, int64_t K, rad_weight w) { + return RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + } + static rad_op lnorm(RadBuilder* b, int64_t max_m, int64_t n, float eps, rad_weight w, + rad_weight bias) { + return RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + } + /* A bias-free 3x3 convolution as conv2d_unfold + gemm_nt: the unfolded rows are exactly what + * a GEMM against the checkpoint's [cout, cin, 3, 3] weight (read as [cout, cin*9]) needs. */ + static rad_op unfold(RadBuilder* b, int64_t h, int64_t w, int64_t cin, int64_t stride, + int64_t cu_div) { + return RAD_OP(b, "conv2d_unfold", + RAD_PARAMS(RAD_INT("M", h), RAD_INT("width", w), RAD_INT("cin", cin), + RAD_INT("kh", 3), RAD_INT("kw", 3), RAD_INT("stride", stride), + RAD_INT("pad", 1), RAD_INT("cu_div", cu_div), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + } + + int declare_ops(RadBuilder* b) { + /* ---- activations, one view's. */ + b_x = decl_b(b, "v.sam.x", RAD_BF16, {kSamTok, kSamW}); + b_h = decl_b(b, "v.sam.h", RAD_BF16, {kSamTok, kSamW}); + b_qkv = decl_b(b, "v.sam.qkv", RAD_BF16, {kSamTok, 3 * kSamW}); + b_att = decl_b(b, "v.sam.att", RAD_BF16, {kSamTok, kSamW}); + b_ff = decl_b(b, "v.sam.ff", RAD_BF16, {kSamTok, kSamFf}); + b_sampos = decl_b(b, "v.sam.pos", RAD_BF16, {kSamTok, kSamW}); + b_ids_sam = decl_b(b, "v.sam.ids", RAD_I32, {kSamTok}); + b_hw = decl_b(b, "v.sam.hw", RAD_BF16, {kSamTokP, kSamW}); + b_qkvw = decl_b(b, "v.sam.qkvw", RAD_BF16, {kSamTokP, 3 * kSamW}); + b_attw = decl_b(b, "v.sam.attw", RAD_BF16, {kSamTokP, kSamW}); + b_ids_pad = decl_b(b, "v.sam.ids.pad", RAD_I32, {kSamTokP}, RAD_BUF_PERSIST); + b_ids_real = decl_b(b, "v.sam.ids.real", RAD_I32, {kSamTok}, RAD_BUF_PERSIST); + + b_n0 = decl_b(b, "v.neck.0", RAD_BF16, {kSamTok, 256}); + b_n1 = decl_b(b, "v.neck.1", RAD_BF16, {kSamTok, 256}); + b_unf3 = decl_b(b, "v.neck.unf", RAD_BF16, {kSamTok, 256 * 9}); + b_n2 = decl_b(b, "v.neck.2", RAD_BF16, {kSamTok, 256}); + b_n3 = decl_b(b, "v.neck.3", RAD_BF16, {kSamTok, 256}); + b_unf_2 = decl_b(b, "v.net2.unf", RAD_BF16, {kSamTok / 4, 256 * 9}); + b_map2 = decl_b(b, "v.net2.out", RAD_BF16, {kSamTok / 4, 512}); + b_unf_3 = decl_b(b, "v.net3.unf", RAD_BF16, {kMap * kMap, 512 * 9}); + b_map = decl_b(b, "v.map", RAD_BF16, {kMap * kMap, kClipW}); + + b_c = decl_b(b, "v.clip.x", RAD_BF16, {kClipTok, kClipW}); + b_ch = decl_b(b, "v.clip.h", RAD_BF16, {kClipTok, kClipW}); + b_cq = decl_b(b, "v.clip.qkv", RAD_BF16, {kClipTok, 3 * kClipW}); + b_ca = decl_b(b, "v.clip.att", RAD_BF16, {kClipTok, kClipW}); + b_cf = decl_b(b, "v.clip.ff", RAD_BF16, {kClipTok, kClipFf}); + b_cg = decl_b(b, "v.clip.g", RAD_BF16, {kClipTok, kClipFf}); + b_cg2 = decl_b(b, "v.clip.g2", RAD_BF16, {kClipTok, kClipFf}); + b_cpos = decl_b(b, "v.clip.pos", RAD_BF16, {kClipTok, kClipW}); + b_ct = decl_b(b, "v.clip.tmp", RAD_BF16, {kClipTok, kClipW}); + b_cp = decl_b(b, "v.clip.pre", RAD_BF16, {kClipTok, kClipW}); + b_ids_clip = decl_b(b, "v.clip.ids", RAD_I32, {kClipTok}); + + b_fuse = decl_b(b, "v.fuse", RAD_BF16, {kMap * kMap, kFused}); + b_projbuf = decl_b(b, "v.proj", RAD_BF16, {kMap * kMap, kNEmbd}); + + b_one = decl_b(b, "v.one", RAD_BF16, {1, kNEmbd}); + b_one_c = decl_b(b, "v.one.clip", RAD_BF16, {1, kClipW}); + b_c1702 = decl_b(b, "v.one.1702", RAD_BF16, {1, kClipFf}); + b_cu_sam = decl_b(b, "v.cu.sam", RAD_I32, {2}); + b_cu_clip = decl_b(b, "v.cu.clip", RAD_I32, {2}); + b_cu_pad = decl_b(b, "v.cu.pad", RAD_I32, {2}); + + /* ---- the pass's constants, declared FIRST because they are issued first. Liveness is + * computed over this op order, so an op declared after its readers leaves its buffer with + * a live range that begins at the reader: the packer then aliases that buffer with an + * activation written in between, and the value is gone by the time it is read (this is + * exactly what corrupted the cu_seqlens tables while they were declared at the bottom). */ + op_fill_one = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kNEmbd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, {b_one}); + op_fill_one_c = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kClipW), + RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, {b_one_c}); + op_fill_1702 = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kClipFf), + RAD_STR("dtype", "bf16"), RAD_F64("value", 1.702)), + RAD_NOWEIGHTS), + {}, {b_c1702}); + /* One cu_seqlens table each, {0, tokens}, one segment: `iota` writes both entries in one + * op. The three unfolds read b_cu_sam through their `cu_div` (4096/64 = 64 rows for the + * neck and net_2 maps, 4096/128 = 32 for net_3's), so one table serves all of them. */ + op_cu_sam = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), RAD_INT("step", kSamTok)), + RAD_NOWEIGHTS), + {}, {b_cu_sam}); + op_cu_clip = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), + RAD_INT("step", kClipTok)), + RAD_NOWEIGHTS), + {}, {b_cu_clip}); + op_cu_pad = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_INT("M", 2), RAD_INT("start", 0), + RAD_INT("step", kSamTokP)), + RAD_NOWEIGHTS), + {}, {b_cu_pad}); + + /* ---- SAM stem. The patch embed is one GEMM a grid row (the staged rows carry kDown + * zero patch columns nothing reads), then the 64x64 position table added in: at this + * grid the reference's get_abs_pos_sam returns the table unchanged, so a row gather is + * exact. */ + op_patch = rw(b, gemm_b(b, kGrid, kSamW, kPatchDim, "none", w_patch, 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_sampos = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), RAD_INT("n_embd", kSamW), + RAD_INT("n_vocab", kSamTok), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_pos)), + {b_ids_sam}, {b_sampos}); + op_sampadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, kSamTok), RAD_INT("n", kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_x, b_sampos}, {b_x}); + + for (SamLayer& l : sam) { + l.op_n1 = rw(b, lnorm(b, kSamTok, kSamW, 1e-6f, l.w_n1, l.b_n1), {b_x}, {b_h}); + /* The windowed path: `h` into window_partition's padded 70x70 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", kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_ids_pad}, {b_hw}); + l.op_qkv = rw(b, gemm_b(b, kSamTok, 3 * kSamW, kSamW, "none", l.w_qkv, l.b_qkv), + {b_h}, {b_qkv}); + l.op_qkvw = rw(b, gemm_b(b, kSamTokP, 3 * kSamW, 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_INT("head_dim", kSamHd), + RAD_INT("n_head", kSamHeads), + RAD_INT("grid_h", kGrid), RAD_INT("grid_w", kGrid), + RAD_INT("window", l.window), + RAD_F64("scale", 1.0 / 8.0), RAD_STR("dtype", "bf16")), + 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_INT("head_dim", kSamHd), + RAD_INT("n_head", kSamHeads), + RAD_INT("grid_h", kGridP), RAD_INT("grid_w", kGridP), + RAD_INT("window", kWin), + RAD_F64("scale", 1.0 / 8.0), RAD_STR("dtype", "bf16")), + 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", kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_attw, b_ids_real}, {b_att}); + l.op_proj = rw(b, gemm_b(b, kSamTok, kSamW, 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", kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_x}, {b_x}); + l.op_n2 = rw(b, lnorm(b, kSamTok, kSamW, 1e-6f, l.w_n2, l.b_n2), {b_x}, {b_h}); + l.op_l1 = rw(b, gemm_b(b, kSamTok, kSamFf, kSamW, "gelu", l.w_l1, l.b_l1), {b_h}, + {b_ff}); + l.op_l2 = rw(b, gemm_b(b, kSamTok, kSamW, 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", kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_x}, {b_x}); + } + + /* ---- 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, kSamW, w_neck0), {b_x}, {b_n0}); + op_nk1 = rw(b, lnorm(b, kSamTok, 256, 1e-6f, w_nk1, 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_nk2), {b_unf3}, {b_n2}); + op_nk3 = rw(b, lnorm(b, kSamTok, 256, 1e-6f, w_nk3, 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_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, kClipW, 512 * 9, 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 + * is free. (The reference cats class first too.) */ + op_cls = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kClipW), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_cls)), + {b_one_c}, {b_c}); + op_cmap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", kClipW), + 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}); + op_cpos = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), RAD_INT("n_embd", kClipW), + RAD_INT("n_vocab", kClipTok), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_cpos)), + {b_ids_clip}, {b_cpos}); + op_cadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), RAD_INT("n", kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_c, b_cpos}, {b_c}); + op_playr = rw(b, lnorm(b, kClipTok, kClipW, 1e-5f, w_playr, 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. */ + op_ccopy = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kClipTok), RAD_INT("n", kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_cp}, {b_c}); + + for (ClipLayer& l : clip) { + l.op_n1 = rw(b, lnorm(b, kClipTok, kClipW, 1e-5f, l.w_n1, l.b_n1), {b_c}, {b_ch}); + l.op_qkv = rw(b, gemm_b(b, kClipTok, 3 * kClipW, 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_INT("head_dim", kClipHd), RAD_INT("gqa", 1), + RAD_INT("causal", 0), RAD_F64("scale", 1.0 / 8.0), + RAD_INT("cu_div", 1), RAD_INT("max_seqlen", kClipTok), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cq, b_cu_clip}, {b_ca}); + l.op_out = rw(b, gemm_b(b, kClipTok, kClipW, 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_INT("n", kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_ct, b_c}, {b_c}); + l.op_n2 = rw(b, lnorm(b, kClipTok, kClipW, 1e-5f, l.w_n2, l.b_n2), {b_c}, {b_ch}); + l.op_fc1 = rw(b, gemm_b(b, kClipTok, kClipFf, kClipW, "none", l.w_fc1, l.b_fc1), + {b_ch}, {b_cf}); + /* quick_gelu: fc1's output times sigmoid(1.702 * itself). */ + l.op_scale = rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), RAD_INT("n", kClipFf), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cf, b_c1702}, {b_cg}); + l.op_qg = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, kClipTok), RAD_INT("n", kClipFf), + RAD_STR("act", "sigmoid"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cg, b_cf}, {b_cg2}); + l.op_fc2 = rw(b, gemm_b(b, kClipTok, kClipW, 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_INT("n", kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_ct, b_c}, {b_c}); + } + + /* ---- fuse, project. */ + op_fuse_clip = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_c}, {b_fuse}); + op_fuse_sam = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_map}, {b_fuse}); + op_proj = rw(b, gemm_b(b, kMap * kMap, kNEmbd, kFused, "none", w_proj, 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", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_map, b_c, b_unf_2}, {b_out}); + op_dbg768 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", kSamW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_x, b_att}, {b_out}); + op_dbg256 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", 256), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_n0, b_n1, b_n2, b_n3, b_map2, b_unf_2}, {b_out}); + op_dbg1280 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", kNEmbd), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_projbuf}, {b_out}); + + /* A projected map line into its place among the layout rows. */ + op_line = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap), RAD_INT("n", kNEmbd), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_projbuf}, {b_out}); + + /* ---- constants and the two layout rows. */ + op_newline = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kNEmbd), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_newline)), + {b_one}, {b_out}); + op_sep = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kNEmbd), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_sep)), + {b_one}, {b_out}); + return RAD_OK; + } + + + /* ------------------------------------------------------------------ declare */ + /* Maps and declares the tower's weights always; declares the ops and the encoder only when + * SAM's attention op exists. `grp_base` is a free movement-group number. */ + int declare(RadBuilder* b, const RadBuildCtx* ctx, Names& nm, int64_t n_embd_model, + int grp_base) { + RAD_ARCH_TRY(declare_weights(b, nm, grp_base)); + if (n_embd_model != kNEmbd) { + fprintf(stderr, "radiance: unlimitedocr: the decoder's hidden size %lld is not the " + "DeepEncoder's %lld\n", (long long)n_embd_model, (long long)kNEmbd); + return RAD_E_UNSUPPORTED; + } + if (!probe(b)) { + rad_note(b, "the DeepEncoder tower is NOT declared: SAM's attention needs the " + "`sam_attn` op (windowed 14x14 / global 64x64 attention with decomposed " + "rel_pos_h/rel_pos_w), which no loaded kernel library provides. Its " + "weights are mapped and declared, so a converted container carries them; " + "images are refused until the op lands"); + on = false; + return RAD_OK; + } + max_patches = ctx->max_enc_patches; + if (max_patches < kSegView) { + /* --mm-max-patches 0 (text only) or a bound below one 1024x1024 view: the tower stays + * off and the trunk serves text, which is what the flag asks for. */ + rad_note(b, "the DeepEncoder tower is NOT declared: one 1024x1024 view is %lld staged " + "patches and --mm-max-patches is %lld; images are refused", + (long long)kSegView, (long long)max_patches); + on = false; + return RAD_OK; + } + max_views = max_patches / kSegView; + b_out = decl_b(b, "v.out", RAD_BF16, {max_patches / kMerge, kNEmbd}); + if (const char* e = getenv("RAD_UNLIMITEDOCR_DBG")) dbg = atoi(e); + if (const char* e = getenv("RAD_UNLIMITEDOCR_DBG_ROW")) dbg_row = atoi(e); + RAD_ARCH_TRY(declare_ops(b)); + if (!ctx->shape_probe) { + RadEncoderDecl e{}; + e.name = "deepencoder"; + e.modalities = RAD_MM_IMAGE; + e.patch_dim = kPatchDim; + e.merge = kMerge; + e.max_patches = max_patches; + e.n_embd = kNEmbd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + } + on = true; + rad_note(b, "DeepEncoder: SAM ViT-B/16 at 1024 (%lld blocks of %lld, %lld heads x %lld, " + "window %lld on a %lldx%lld grid, global on 2/5/8/11, rel_pos tables 27/127 " + "rows) -> 16x16x1024 map -> CLIP ViT-L/14 (%lld layers of %lld, %lld heads x " + "%lld, %lld tokens) -> %lld -> projector -> %lld; %lld patches a view " + "(64x%lld staged, %lld patches a row) -> %lld rows a view", + (long long)kSamDepth, (long long)kSamW, (long long)kSamHeads, (long long)kSamHd, + (long long)kWin, (long long)kGrid, (long long)kGrid, (long long)kClipDepth, + (long long)kClipW, (long long)kClipHeads, (long long)kClipHd, + (long long)kClipTok, (long long)kFused, (long long)kNEmbd, + (long long)kPatchView, (long long)(kGrid + kDown), (long long)kMerge, + (long long)kRowsView); + return RAD_OK; + } + + /* ------------------------------------------------------------------ step */ + /* One view: the staged 64 x (64+4) patch grid -> 273 rows at `rowbase`. */ + void view(RadCtx* c, const RadBatch* batch, int64_t v) const { + const int64_t pbase = v * kSegView; + const int64_t rowbase = pbase / kMerge; + const char* pix = (const char*)batch->enc_pixels + pbase * kPatchDim * 2; + + /* The patch embed, one grid row at a time: the kDown zero patch columns the processor + * stages at the end of each row are skipped, not read. */ + for (int64_t r = 0; r < kGrid; ++r) + RAD_ISSUE_N(c, op_patch, kGrid, + RAD_P_T2(pix + (r * (kGrid + kDown)) * kPatchDim * 2, RAD_BF16, kGrid, + kPatchDim), + RAD_W(w_patch), RAD_W(b_patch), RAD_NONE, + brow_slice(b_x, r * kGrid, kGrid, kSamW)); + + /* The 64x64 position table, a row for a token (a gather, exact at this grid), added in. */ + RAD_ISSUE(c, op_ids_sam, RAD_B(b_ids_sam)); + RAD_ISSUE_N(c, op_sampos, kSamTok, RAD_B(b_ids_sam), RAD_W(w_pos), brows(b_sampos, kSamTok)); + RAD_ISSUE_N(c, op_sampadd, kSamTok, brows(b_x, kSamTok), brows(b_sampos, kSamTok), + brows(b_x, kSamTok)); + tap(c, "st_x0", b_x, 256, kSamW); + + if (dbg == 10) { RAD_ISSUE(c, op_dbg768, brow_slice(b_x, dbg_row, 256, kSamW), bcol(b_out, 0, kSamW, 256)); return; } + + for (size_t li = 0; li < sam.size(); ++li) { + const SamLayer& 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)); + if (l.window > 0) { + /* The reference's window path: pad the normed grid to 70x70, 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, kSamW, kSamTokP), bcol(b_qkvw, kSamW, kSamW, kSamTokP), + bcol(b_qkvw, 2 * kSamW, kSamW, kSamTokP), RAD_B(b_cu_pad), + brows(b_attw, kSamTokP), 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)); + } 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, kSamW, kSamTok), bcol(b_qkv, kSamW, kSamW, kSamTok), + bcol(b_qkv, 2 * kSamW, kSamW, kSamTok), RAD_B(b_cu_sam), + brows(b_att, kSamTok), RAD_W(l.w_rh), RAD_W(l.w_rw)); + } + char tag[40]; + std::snprintf(tag, sizeof tag, "sam_att%lld_raw", (long long)li); + tap(c, tag, b_att, 256, kSamW); + if (dbg >= 50 && dbg < 50 + (int)kSamDepth && dbg == 50 + (int)li) { + RAD_ISSUE(c, op_dbg768, brow_slice(b_att, dbg_row, 256, kSamW), bcol(b_out, 0, 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)); + std::snprintf(tag, sizeof tag, "st_pre%lld", (long long)li); + tap(c, tag, b_x, 256, kSamW); + if (dbg >= 70 && dbg < 70 + (int)kSamDepth && dbg == 70 + (int)li) { + RAD_ISSUE(c, op_dbg768, brow_slice(b_x, dbg_row, 256, kSamW), bcol(b_out, 0, 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)); + std::snprintf(tag, sizeof tag, "st_b%lld", (long long)li); + tap(c, tag, b_x, 256, kSamW); + if (li < 3) { + std::snprintf(tag, sizeof tag, "st_full%lld", (long long)li); + tap(c, tag, b_x, kSamTok, kSamW); + } + if (dbg == 11 + (int)li) { + RAD_ISSUE(c, op_dbg768, brow_slice(b_x, dbg_row, 256, kSamW), bcol(b_out, 0, kSamW, 256)); + return; + } + } + + /* 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_neck0), + brows(b_n0, kSamTok)); + tap(c, "st_n0", b_n0, 256, 256); + if (dbg == 30) { RAD_ISSUE(c, op_dbg256, brows(b_n0, 256), bcol(b_out, 0, 256, 256)); return; } + RAD_ISSUE_N(c, op_nk1, kSamTok, brows(b_n0, kSamTok), RAD_W(w_nk1), RAD_W(b_nk1), + brows(b_n1, kSamTok)); + tap(c, "st_n1", b_n1, 256, 256); + if (dbg == 31) { RAD_ISSUE(c, op_dbg256, brows(b_n1, 256), bcol(b_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_nk2), + brows(b_n2, kSamTok)); + tap(c, "st_n2", b_n2, 256, 256); + if (dbg == 32) { RAD_ISSUE(c, op_dbg256, brows(b_n2, 256), bcol(b_out, 0, 256, 256)); return; } + RAD_ISSUE_N(c, op_nk3, kSamTok, brows(b_n2, kSamTok), RAD_W(w_nk3), RAD_W(b_nk3), + brows(b_n3, kSamTok)); + tap(c, "st_n3", b_n3, 256, 256); + if (dbg == 33) { RAD_ISSUE(c, op_dbg256, brows(b_n3, 256), bcol(b_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)); + if (dbg == 40) { + RAD_ISSUE(c, op_dbg1024, brows(b_unf_2, 256), bcol(b_out, 0, kClipW, 256)); + return; + } + RAD_ISSUE_N(c, op_net2, kSamTok / 4, brows(b_unf_2, kSamTok / 4), RAD_W(w_net2), + brows(b_map2, kSamTok / 4)); + 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)); + if (dbg == 34) { RAD_ISSUE(c, op_dbg256, brows(b_map2, 256), bcol(b_out, 0, 256, 256)); return; } + RAD_ISSUE_N(c, op_net3, kMap * kMap, brows(b_unf_3, kMap * kMap), RAD_W(w_net3), + brows(b_map, kMap * kMap)); + tap(c, "st_map", b_map, kMap * kMap, kClipW); + + /* CLIP at 257 tokens: the class row, the map, the absolute table. */ + RAD_ISSUE(c, op_cls, RAD_B(b_one_c), RAD_W(w_cls), brow_slice(b_c, 0, 1, kClipW)); + RAD_ISSUE(c, op_cmap, bcol(b_map, 0, kClipW, kMap * kMap), + brow_slice(b_c, 1, kMap * kMap, kClipW)); + RAD_ISSUE(c, op_ids_clip, RAD_B(b_ids_clip)); + RAD_ISSUE_N(c, op_cpos, kClipTok, RAD_B(b_ids_clip), RAD_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)); + tap(c, "clip_x", b_c, kClipTok, kClipW); + RAD_ISSUE_N(c, op_playr, kClipTok, brows(b_c, kClipTok), RAD_W(w_playr), + RAD_W(b_playr), brows(b_cp, kClipTok)); + RAD_ISSUE_N(c, op_ccopy, kClipTok, brows(b_cp, kClipTok), brows(b_c, kClipTok)); + + for (size_t ci = 0; ci < clip.size(); ++ci) { + const ClipLayer& 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)); + std::snprintf(ctag, sizeof ctag, "clip_pre%lld", (long long)ci); + tap(c, ctag, b_ch, kClipTok, 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, kClipW, kClipTok), bcol(b_cq, kClipW, kClipW, kClipTok), + bcol(b_cq, 2 * kClipW, kClipW, kClipTok), RAD_B(b_cu_clip), + brows(b_ca, kClipTok)); + std::snprintf(ctag, sizeof ctag, "clip_att%lld", (long long)ci); + tap(c, ctag, b_ca, kClipTok, 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)); + std::snprintf(ctag, sizeof ctag, "clip_h%lld", (long long)ci); + tap(c, ctag, b_c, kClipTok, 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_scale, kClipTok, brows(b_cf, kClipTok), brows(b_c1702, 1), + brows(b_cg, kClipTok)); + RAD_ISSUE_N(c, l.op_qg, kClipTok, brows(b_cg, 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)); + std::snprintf(ctag, sizeof ctag, "clip_b%lld", (long long)ci); + tap(c, ctag, b_c, kClipTok, kClipW); + } + + tap(c, "clip_out", b_c, kMap * kMap, kClipW, 1); + + /* Fuse (CLIP's patch rows | the map) and project. */ + RAD_ISSUE(c, op_fuse_clip, brow_slice(b_c, 1, kMap * kMap, kClipW), + bcol(b_fuse, 0, kClipW, kMap * kMap)); + RAD_ISSUE(c, op_fuse_sam, bcol(b_map, 0, kClipW, kMap * kMap), + bcol(b_fuse, kClipW, kClipW, kMap * kMap)); + tap(c, "fuse", b_fuse, kMap * kMap, kFused); + RAD_ISSUE_N(c, op_proj, kMap * kMap, brows(b_fuse, kMap * kMap), RAD_W(w_proj), + RAD_W(b_proj), RAD_NONE, brows(b_projbuf, kMap * kMap)); + tap(c, "proj", b_projbuf, kMap * kMap, kNEmbd); + + if (dbg) { + const RadOperand src = dbg == 1 ? bcol(b_map, 0, kClipW, kMap * kMap) + : dbg == 2 ? brow_slice(b_c, 1, kMap * kMap, kClipW) + : brows(b_projbuf, kMap * kMap); + const RadOperand dst = dbg == 4 ? bcol(b_out, 0, kNEmbd, kMap * kMap) + : bcol(b_out, 0, kClipW, kMap * kMap); + RAD_ISSUE(c, dbg == 4 ? op_dbg1280 : op_dbg1024, src, dst); + return; + } + + /* The layout: every map line of 16 rows is closed by `image_newline`, and the view by a + * `view_seperator` row. */ + for (int64_t m = 0; m < kMap; ++m) { + const int64_t dst = rowbase + m * (kMap + 1); + RAD_ISSUE_N(c, op_line, kMap, brow_slice(b_projbuf, m * kMap, kMap, kNEmbd), + brow_slice(b_out, dst, kMap, kNEmbd)); + RAD_ISSUE(c, op_newline, RAD_B(b_one), RAD_W(w_newline), + brow_slice(b_out, dst + kMap, 1, kNEmbd)); + } + RAD_ISSUE(c, op_sep, RAD_B(b_one), RAD_W(w_sep), + brow_slice(b_out, rowbase + kRowsView - 1, 1, kNEmbd)); + } + + void step(RadCtx* c, const RadBatch* batch) { + if (!on) { + rad_step_fail(c, "unlimitedocr: an image pass reached the DeepEncoder, which this " + "program did not declare"); + return; + } + const int64_t n_patch = batch->enc_n_patch; + const int64_t n_seg = batch->enc_n_seg; + const int64_t views = n_patch / kSegView; + if (n_patch <= 0 || views <= 0 || views > max_views || n_seg != 2 * views) { + rad_step_fail(c, "unlimitedocr: an encoder pass the DeepEncoder does not serve: one " + "1024x1024 view is 4352 staged patches + a separator segment, and " + "only that geometry is declared (crops need a resampled position " + "table, tiling is gundam mode)"); + return; + } + + /* One view's constants for the whole pass. */ + RAD_ISSUE(c, op_fill_one, RAD_B(b_one)); + RAD_ISSUE(c, op_fill_one_c, RAD_B(b_one_c)); + RAD_ISSUE(c, op_fill_1702, RAD_B(b_c1702)); + 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). Constants, written before the pass's ops. */ + static const std::vector pad_idx = [] { + std::vector v((size_t)kSamTokP, -1); + for (int64_t r = 0; r < kGrid; ++r) + for (int64_t c = 0; c < kGrid; ++c) + v[(size_t)(r * kGridP + c)] = (int32_t)(r * kGrid + c); + 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 c = 0; c < kGrid; ++c) + v[(size_t)(r * kGrid + c)] = (int32_t)(r * kGridP + c); + return v; + }(); + 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; + } + + for (int64_t v = 0; v < views; ++v) view(c, batch, v); + } +}; + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_SAM_H */ diff --git a/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp index 459e8ff1..77857ae6 100644 --- a/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp +++ b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp @@ -1,10 +1,18 @@ /* unlimitedocr_bf16 -- baidu/Unlimited-OCR's decoder: a small Llama-MoE, bf16 weights and bf16 * activations. * - * P1 scope (aijuus/plans/UNLIMITED-OCR-PLUGIN.md): the TEXT-ONLY trunk. The DeepEncoder vision - * tower (SAM ViT-B/16 + CLIP ViT-L/14, `model.vision_tower`/`model.projector`) is P2 and not - * declared here; the R-SWA ring KV is P4 and every layer serves plain causal paged attention; the - * windowed no-repeat-ngram sampler is P5. + * Scope (aijuus/plans/UNLIMITED-OCR-PLUGIN.md): the text trunk (P1) plus the DeepEncoder vision + * tower (P2, arch/common/rad_block_sam.h: SAM ViT-B/16 at 1024 -> 16x16x1024 map -> CLIP ViT-L/14 + * -> the projector -> the 273-row layout, declared with rad_declare_encoder(RAD_MM_IMAGE), + * patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower's weights are mapped always; its ops + * and the encoder pass are declared only when SAM's `sam_attn` op resolves, because no existing op + * can carry the decomposed rel_pos_h/rel_pos_w attention bias (rad_block_sam.h's header states the + * op and why). Without it this plugin is the P1 text-only trunk and refuses images by name. The + * decoder's KV is one RAD_KV_RING group with the checkpoint's `sliding_window_size` (128), the + * reference's own R-SWA: prefill is fully causal, and from the end of the prefill the ring of the + * last W generated tokens is appended to the prompt (`SlidingWindowLlamaAttention`, which keeps + * the prompt as reference and overwrites ring slots in place). The windowed no-repeat-ngram + * sampler is P5. * * ============================== THE SHAPE (config.json) ============================== * @@ -30,6 +38,7 @@ #include #include #include +#include #include "attn_llama.h" @@ -58,7 +67,7 @@ struct Model { int64_t n_rot = 0; int64_t first_dense = 1; /* layers [0, first_dense) are dense MLPs */ - rad_kvgroup kv_full = 0; + rad_kvgroup kv = 0; /* the residual stream and the vocabulary edges */ rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; @@ -76,9 +85,13 @@ struct Model { rad_buf b_sgu = 0, b_sff = 0, b_sout = 0; MoeFP8::Config moecfg{}; + /* The DeepEncoder vision tower (arch/common/rad_block_sam.h). Its weights are mapped always; + * its ops and the encoder pass only when SAM's attention op resolves. */ + DeepEncoder enc; rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; - rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_gather = 0, op_logits = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_mm = 0, op_final_norm = 0, op_gather = 0, + op_logits = 0; std::vector layers; }; @@ -248,14 +261,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const int64_t moe_rows = 2048; mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; - /* ---- KV: one full group. R-SWA (P4) turns this into a windowed group with the window set at - * prefill end; P1 is the plain full-cache decode the plan uses as the P1-P3 baseline. */ + /* ---- KV: one R-SWA ring group. + * + * The reference's `SlidingWindowLlamaAttention` keeps the prefill as reference and from the + * prefill's end keeps the last `sliding_window_size` generated tokens in a ring it overwrites + * in place, attending over both. RAD_KV_RING is that: paged like a window group, but the floor + * is per sequence and armed at admission (`visible_lo = prefill length`), so a decode query + * sees [0, prefill) U [prefill, prefill + W). Prefill itself stays fully causal, which is why + * the attention op keeps `causal=1` and `window=0`: the visible set is the block table's job, + * and `causal=0` would make a prefill chunk non-causal. + * + * A checkpoint that states no window gets the plain full cache, so the text trunk still + * serves. Prefix caching and speculation switch off for the group automatically (a runtime + * window's KV before the prompt end is not reusable and a draft cannot know where the ring + * starts). */ + const int64_t win = rad_meta_geti(meta, "sliding_window_size", 0) > 0 + ? rad_meta_geti(meta, "sliding_window_size", 0) + : rad_meta_geti(meta, "sliding_window", 0); RadKVGroupDecl fd{}; - fd.kind = RAD_KV_FULL; + fd.kind = win > 0 ? RAD_KV_RING : RAD_KV_FULL; fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.window = win > 0 ? win : 0; fd.n_head_kv = g.n_head_kv; fd.head_dim = g.head_dim; - m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); g.kv_dtype = rad_dtype_name(fd.dtype); /* ---- activation buffers. */ @@ -339,6 +368,20 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } } + /* ---- the DeepEncoder tower: map and declare its weights, then (when `sam_attn` resolves) its + * ops and the encoder pass. Without that op the tower stays off and images are refused. */ + RAD_ARCH_TRY(m.enc.declare(b, ctx, nm, g.n_embd, (int)g.n_layer + 64)); + + /* A picture's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and + * before the first block. Declared only when the tower is, since otherwise no step can carry + * media rows. */ + if (m.enc.on) + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + AttnLlamaBF16::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn; @@ -365,8 +408,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c as.k = nm.ckpt("model.layers.%lld.self_attn.k_proj.weight", (long long)l); as.v = nm.ckpt("model.layers.%lld.self_attn.v_proj.weight", (long long)l); as.o = nm.ckpt("model.layers.%lld.self_attn.o_proj.weight", (long long)l); - RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full)); - RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, m.n_rot, aw, as)); if (lay.dense) { MlpBF16::Src ms{}; @@ -420,10 +463,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)mc.n_ff_shared, (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); - rad_note(b, "R-SWA is NOT served by this plugin pass: every layer decodes full-cache causal. " - "The ring (sliding_window_size %lld) is the plan's P4 (per-sequence RAD_KV_WINDOW " - "window set at prefill end, causal=0 over reference+ring)", - (long long)rad_meta_geti(meta, "sliding_window_size", 0)); + if (win > 0) + rad_note(b, "R-SWA: the KV group is a runtime ring (RAD_KV_RING), window %lld tokens from " + "the prefill's end (the reference's SlidingWindowLlamaAttention); prefill is " + "fully causal, and prefix cache and speculation are off for it", (long long)win); + else + rad_note(b, "R-SWA: the checkpoint states no sliding_window_size, so the KV group is a " + "plain full cache"); rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=35 -- the " "plan's P5 sample_ngram_ban op; temp-0 parity checks run with it off"); return RAD_OK; @@ -432,8 +478,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c static void step(RadCtx* c, const RadBatch* batch) { Model& m = g_model[rad_rank(c)]; - /* No encoder pass is declared (the vision tower is P2). */ - if (batch->enc) return; + if (batch->enc) { + m.enc.step(c, batch); + return; + } RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok), @@ -441,6 +489,10 @@ static void step(RadCtx* c, const RadBatch* batch) { if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd, brows(m.b_x, batch->n_tok), RAD_NONE); + if (m.op_mm && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows, + praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd), + praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok)); for (const Layer& l : m.layers) { l.attn.step(c, batch); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 236f2c4c..29842f00 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -87,6 +87,7 @@ const char* bld_kv_kind_name(int k) { case RAD_KV_WINDOW: return "window"; case RAD_KV_LINEAR: return "linear"; case RAD_KV_CONV: return "conv"; + case RAD_KV_RING: return "ring"; default: return "?"; } } @@ -336,7 +337,7 @@ rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) { rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) { if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : ""); if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration"); - if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV) + if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING) return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind); std::string n = scoped(name); @@ -923,7 +924,7 @@ int Builder::kv_group_zero(rad_kvgroup h) { * state is saved and cleared on every rank, so a zero-sized one would mismatch those * copies. */ const int kind = prog_.kv_groups[h].decl.kind; - if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) { + if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW && kind != RAD_KV_RING) { err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged", prog_.kv_groups[h].name.c_str()); return RAD_E_INVAL; @@ -1964,7 +1965,8 @@ void Builder::finish_kv_groups() { KVGroupInfo& gi = prog_.kv_groups[g]; const RadKVGroupDecl& d = gi.decl; - if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) { + if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW || d.kind == RAD_KV_RING) && + gi.block_size == 0) { /* The plugin may never have asked; the manifest still needs the answer. */ kv_block_size((rad_kvgroup)g); } @@ -1977,6 +1979,7 @@ void Builder::finish_kv_groups() { switch (d.kind) { case RAD_KV_FULL: case RAD_KV_WINDOW: + case RAD_KV_RING: /* One block holds K and V for block_size tokens, the block manager's unit. */ gi.bytes_per_block = rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound; diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 55252355..3dad6e4d 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -1037,7 +1037,10 @@ int Engine::declare() { * area, which would need 16x the activation memory on every card. */ if (cfg_.mm_max_patches < 0) { const char* enc = rad_meta_gets(&meta_, "radiance.encoder", ""); - const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0; + /* A checkpoint's vision_config states a tower as a flat patch_size, or (Unlimited-OCR's + * DeepEncoder) only the per-width tables under a `vision_config.image_size`. */ + const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 || + rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0; cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0; /* Whole output rows a pass: the plugin's merge, when it states one. */ RadArchProbe pb{}; @@ -1295,6 +1298,21 @@ void Engine::probe_arena_levels() { } /* ================================================================== 5. plan */ + +/* R-SWA: a RAD_KV_RING group names its ring's W in the declaration (`window`). Tell the manager + * before it plans, so the group is planned for per-sequence windows: sized for the whole context + * plus one ring a sequence (the ring in the fixed costs), never capped at the declare-time + * window, never snapshotted. Every plan (each sizing probe and the real manager) goes through + * here, so they all plan the same bytes. */ +static int declare_ring_windows(KVManager& kv, const Program& prog) { + for (size_t g = 1; g < prog.kv_groups.size(); ++g) { + const RadKVGroupDecl& d = prog.kv_groups[g].decl; + if (d.kind != RAD_KV_RING) continue; + RAD_TRY(kv.declare_runtime_window((int32_t)g, d.window)); + } + return RAD_OK; +} + int Engine::plan() { /* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve * folds the smallest capacity with the largest program so one split fits every card, and @@ -1373,6 +1391,19 @@ int Engine::plan() { ngram_bytes = std::max(ngram_bytes, wf.ngram); ngram_device = ngram_device || wf.ngram_device; ngram_host = ngram_host || wf.ngram_host; + /* One --max-model-len sequence's cache: the least a KV pool can hold and still serve + * every acceptable request (configure_kv warns below it). --ngram-placement auto puts + * the table on the card only if the pool stays above it. */ + { + Config one = cfg_; + one.max_seqs = 1; + KVManager single; + if (declare_ring_windows(single, r->program) == RAD_OK && + single.plan_groups(r->program.kv_groups, one) == RAD_OK) { + kv_floor = std::max(kv_floor, single.ceiling(ctx)); + f.kv_one = single.ceiling(ctx); + } + } /* The staging region is sized only where the arena lends its top: without smaller * levels nothing returns it to the slab at decode, and a deterministic plan moves * nothing. */ @@ -1381,7 +1412,8 @@ int Engine::plan() { * memory, and the real pool does not exist yet. */ KVManager probe; host_arenas += arena_host_bytes(r->program); - if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { + if (declare_ring_windows(probe, r->program) == RAD_OK && + probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { ck_slot += probe.checkpoint_bytes(); f.kv_ceiling = probe.ceiling(ctx); f.kv_fixed = probe.fixed_bytes(); @@ -1512,7 +1544,8 @@ int Engine::plan() { * its carve). */ for (size_t i = 0; i < ranks_.size(); ++i) { probes[i] = std::make_unique(); - if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) { + if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK || + probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) { kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index); break; } @@ -2850,6 +2883,7 @@ int Engine::configure_kv() { for (size_t i = 0; i < ranks_.size(); ++i) { auto& r = ranks_[i]; LogRank lr(r->index); + RAD_TRY(declare_ring_windows(r->kv, r->program)); RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_)); const int64_t t = r->kv.paged_tokens(r->pools.kv().avail()); /* A rank plan() re-sized for the common token count must page at least that count (same @@ -3074,13 +3108,16 @@ int Engine::configure_kv() { /* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated * flags; otherwise such a request is accepted and then refused at admission with a message * about blocks. Only full paged groups apply: a window group costs the window, and a linear - * group is O(1) in context. */ + * group is O(1) in context. A runtime-window (RAD_KV_RING) group is not checked here either: + * it is sized for the whole context plus one ring a sequence and its tokens are a per-sequence + * reference rather than the pool's capacity, so the comparison would be about the wrong + * number. */ { const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; const KVManager& kv = ranks_[0]->kv; for (int32_t g = 0; g < kv.n_groups(); ++g) { const KVGroupPlan* p = kv.plan(g); - if (!p || !p->paged() || p->window_blocks > 0) continue; + if (!p || !p->paged() || p->window_blocks > 0 || p->runtime_win) continue; const int64_t cap = p->n_blocks * p->block_size; if (cap >= want) continue; /* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the @@ -3368,16 +3405,18 @@ int Engine::start() { (void)rad_dev_set(ranks_[0]->device); /* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them - * in the same step). Tokens are the smallest over the full paged groups; a windowed group - * bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max, - * radiance:kv_cache_max_tokens). */ + * in the same step). Tokens are the smallest over the full paged groups; a fixed-window group + * bounds history, not capacity. A runtime-window (RAD_KV_RING) group does hold its sequences' + * references, so it counts like a full group. /stats and /metrics report the same numbers + * (kv_tokens_max, radiance:kv_cache_max_tokens). */ { const KVManager& kv = ranks_[0]->kv; int64_t bytes = 0, state = 0, tokens = 0; for (const KVGroupPlan& p : kv.plans()) { bytes += kv.pool_bytes_carved(p.index); if (p.stateful()) state += kv.pool_bytes_carved(p.index); - if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue; + if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0) + continue; const int64_t t = p.n_blocks * p.block_size; if (tokens == 0 || t < tokens) tokens = t; } diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp index 2495cc5c..6241b50c 100644 --- a/core/engine_mm.cpp +++ b/core/engine_mm.cpp @@ -20,6 +20,8 @@ #include #include #include +#include +#include namespace rad { @@ -47,10 +49,53 @@ int Engine::run_encodes() { Rank& r0 = *ranks_[0]; const Program& prog = r0.program; + + /* Diagnostic: RADIANCE_DEBUG_MM_BUFFERS names encoder buffers (comma separated, with an + * optional `:rows` cap) and each pass writes them, as raw bytes, to `/buf.`. + * The pass has finished and been read back, so the copy sees each buffer's last writer; the + * tower's per-stage intermediates are tapped inside the pass instead (rad_block_sam.h). */ + struct DumpBuf { std::string name; int64_t rows; }; + std::vector dump_bufs; + static const char* const dump_list = std::getenv("RADIANCE_DEBUG_MM_BUFFERS"); + if (dump_dir && *dump_dir && dump_list) { + for (const char* s = dump_list; *s; ) { + const char* e = s; + while (*e && *e != ',') ++e; + std::string want(s, (size_t)(e - s)); + s = *e ? e + 1 : e; + int64_t rows = 0; + if (const size_t colon = want.find(':'); colon != std::string::npos) { + rows = std::strtoll(want.c_str() + colon + 1, nullptr, 10); + want.resize(colon); + } + if (!want.empty()) dump_bufs.push_back({ want, rows }); + } + } + auto answers_to = [](const std::string& name, const std::string& want) { + if (name.size() < want.size() || + name.compare(name.size() - want.size(), want.size(), want) != 0) return false; + return name.size() == want.size() || name[name.size() - want.size() - 1] == '.'; + }; for (auto& ip : items) { if (ip->encoded) continue; const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder; ip->embd.assign((size_t)(ip->n_rows() * e.n_embd), 0); + /* Diagnostic: RADIANCE_DEBUG_MM_ROWS= substitutes a reference encoder's + * rows for the tower's, to tell a tower difference from a language-model one. */ + if (const char* rp = std::getenv("RADIANCE_DEBUG_MM_ROWS")) { + if (FILE* rf = std::fopen(rp, "rb")) { + const size_t want = ip->embd.size() * sizeof(uint16_t); + const size_t got = std::fread(ip->embd.data(), 1, want, rf); + std::fclose(rf); + if (got == want) { + ip->encoded = true; + RAD_INFO("encoder: %zu row(s) taken from %s instead of the tower", + (size_t)ip->n_rows(), rp); + continue; + } + RAD_ERR("encoder: %s holds %zu bytes, wanted %zu", rp, got, want); + } + } if (dump_dir && *dump_dir) dump(*ip, ".pix.bf16", ip->pixels.data(), ip->pixels.size()); } @@ -132,6 +177,35 @@ int Engine::run_encodes() { } /* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */ for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream())); + + if (dump_dir && *dump_dir && !dump_bufs.empty()) { + for (const DumpBuf& d : dump_bufs) { + for (size_t bi = 1; bi < prog.buffers.size(); ++bi) { + const BufferInfo& info = prog.buffers[bi]; + if (!answers_to(info.name, d.name) || info.bytes <= 0) continue; + const int64_t nrow = info.decl.rank >= 1 ? info.decl.shape[0] : 1; + const int64_t rowb = nrow > 0 ? info.bytes / nrow : info.bytes; + const int64_t rows = d.rows > 0 ? std::min(d.rows, nrow) : nrow; + void* ptr = r0.ctx.buf_ptr((rad_buf)bi); + std::vector raw((size_t)(rows * rowb)); + if (!ptr || rad_memcpy_async(raw.data(), ptr, raw.size(), + r0.ctx.stream()) < 0) + continue; + rad_stream_sync(r0.ctx.stream()); + char path[512]; + std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_buf.%s.raw", + dump_dir, (unsigned long long)parts.front().item->key_hi, + (unsigned long long)parts.front().item->key_lo, + info.name.c_str()); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(raw.data(), 1, raw.size(), f); + std::fclose(f); + RAD_INFO("encoder: wrote %s (%lld rows of %lld bytes)", path, + (long long)rows, (long long)rowb); + } + } + } + } } } diff --git a/core/gen_config.cpp b/core/gen_config.cpp index aeebd68d..9043047c 100644 --- a/core/gen_config.cpp +++ b/core/gen_config.cpp @@ -22,6 +22,13 @@ void take(const char* what, const char* src, double v, double lo, double hi, boo src, what, v, lo_open ? "(" : "[", lo, hi); } +/* An integer field (a token count), same contract. */ +void take_i(const char* what, const char* src, int64_t v, int64_t lo, int64_t hi, int* dst) { + if (v >= lo && v <= hi) { *dst = (int)v; return; } + RAD_WARN("%s states %s %lld, which is outside [%lld, %lld]; ignoring it", + src, what, (long long)v, (long long)lo, (long long)hi); +} + } /* namespace */ SamplingParams GenSampling::onto(SamplingParams base) const { @@ -29,16 +36,29 @@ SamplingParams GenSampling::onto(SamplingParams base) const { if (top_p >= 0.0f) base.top_p = top_p; if (min_p >= 0.0f) base.min_p = min_p; if (top_k >= 0) base.top_k = top_k; + if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n; + if (ngram_window >= 0) base.ngram_window = ngram_window; return base; } std::string GenSampling::describe(const SamplingParams& sp) { - char buf[200]; + char buf[320]; std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f", (double)sp.temp, sp.top_k, sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "", (double)sp.top_p, (double)sp.min_p); - return buf; + std::string s(buf); + if (sp.ngram_ban_n > 0) { + char ban[96]; + if (sp.ngram_window > 0) + std::snprintf(ban, sizeof ban, ", ngram ban n %d over the last %d tokens", + sp.ngram_ban_n, sp.ngram_window); + else + std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence", + sp.ngram_ban_n); + s += ban; + } + return s; } std::vector gen_sampling_sources(const GenSampling& stated, const std::string& src, @@ -88,6 +108,22 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v); else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v); } + + /* The windowed no-repeat-n-gram ban. Its checkpoint name in transformers is + * no_repeat_ngram_size / no_repeat_ngram_window_size (Unlimited-OCR ships 35 over the last + * 128); this sampler's own names are taken too. The reference's negative window means the + * whole sequence, which this sampler spells 0. */ + it = j.find("no_repeat_ngram_size"); + if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_ban_n"); + if (it != j.end() && it->is_number_integer()) + take_i("no_repeat_ngram_size", src, it->get(), 0, 256, &out->ngram_ban_n); + + it = j.find("no_repeat_ngram_window_size"); + if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_window"); + if (it != j.end() && it->is_number_integer()) { + const int64_t v = it->get(); + take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window); + } return out->any(); } @@ -105,7 +141,8 @@ bool gen_sampling_from_kv(const std::function& get, Ge /* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original * file share one set of range checks and one reading of `do_sample`. */ nlohmann::json j = nlohmann::json::object(); - static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" }; + static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k", + "no_repeat_ngram_size", "no_repeat_ngram_window_size" }; for (const char* k : kFields) { const char* v = get(k); if (!v || !*v) continue; @@ -122,6 +159,7 @@ bool gen_sampling_from_kv(const std::function& get, Ge continue; } if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d; + else if (std::strncmp(k, "no_repeat_ngram", 15) == 0) j[k] = (int64_t)d; else j[k] = d; } if (j.empty()) return false; diff --git a/core/gen_config.h b/core/gen_config.h index fa24225b..9d76e884 100644 --- a/core/gen_config.h +++ b/core/gen_config.h @@ -20,17 +20,25 @@ namespace rad { /* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy - * temperature, top_k off, min_p off). */ + * temperature, top_k off, min_p off, n-gram ban off). */ struct GenSampling { float temp = -1.0f, top_p = -1.0f, min_p = -1.0f; int top_k = -1; + /* The windowed no-repeat-n-gram ban (transformers' no_repeat_ngram_size / + * no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is + * normalized to 0, this sampler's "the whole sequence", when the config states it negative. */ + int ngram_ban_n = -1, ngram_window = -1; - bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; } + bool any() const { + return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 || + ngram_ban_n >= 0 || ngram_window >= 0; + } /* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */ SamplingParams onto(SamplingParams base) const; - /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */ + /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00, ngram ban n 35 over the last 128 + * tokens", for the startup log line (the last part only when a ban is on). */ static std::string describe(const SamplingParams& sp); }; diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 2d2eb0cb..89ad4180 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -76,6 +76,7 @@ static const char* kv_kind_name(int k) { case RAD_KV_WINDOW: return "window"; case RAD_KV_LINEAR: return "linear"; case RAD_KV_CONV: return "conv"; + case RAD_KV_RING: return "ring"; default: return "?"; } } @@ -126,7 +127,10 @@ int KVManager::plan_groups(const std::vector& groups, const Config& KVGroupPlan p; p.index = (int32_t)i; p.name = g.name.empty() ? fmt("kv%zu", i) : g.name; - p.kind = g.decl.kind; + /* R-SWA: RAD_KV_RING is a window group whose floor is per sequence (declare_runtime_window + * / SeqWindow), so it plans as a RAD_KV_WINDOW group with `runtime_win` set below. No + * other plan-path code has to know the kind. */ + p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind; p.n_layers = (int64_t)g.layers.size(); if (p.n_layers <= 0) { @@ -161,7 +165,9 @@ int KVManager::plan_groups(const std::vector& groups, const Config& } if (p.kind == RAD_KV_WINDOW) { if (g.decl.window <= 0) { - RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str()); + RAD_ERR("KV group '%s': %s with window 0", p.name.c_str(), + g.decl.kind == RAD_KV_RING ? "RAD_KV_RING (the ring's W)" + : "RAD_KV_WINDOW"); return RAD_E_INVAL; } /* +1 because a window that is not block-aligned straddles one extra block. */ @@ -232,6 +238,28 @@ int KVManager::plan_groups(const std::vector& groups, const Config& } bundling_ = compare_bundling(bundles); + /* R-SWA: a declared runtime window turns the group's plan over to per-sequence windows (see + * declare_runtime_window). Applied after every declaration above, so a fixed-window group's + * plan is exactly what it was. */ + for (auto& p : plans_) apply_runtime_window(p); + /* A RAD_KV_RING group carries a runtime window by its kind, whether or not the caller had a + * manager to declare it on first (the engine's sizing probes declare it, but plan_groups must + * not depend on that). `window` is the ring's W. */ + for (size_t i = 1; i < plans_.size(); ++i) { + KVGroupPlan& p = plans_[i]; + if (groups[i].decl.kind != RAD_KV_RING || p.runtime_win) continue; + p.runtime_win = true; + p.runtime_tokens = groups[i].decl.window; + p.win_snap = false; + } + for (const auto& [g, w] : runtime_decl_) { + if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].runtime_win) { + RAD_ERR("declare_runtime_window(%d): the group is not a RAD_KV_WINDOW or RAD_KV_RING " + "group in this program (a runtime window needs a windowed group)", (int)g); + return RAD_E_INVAL; + } + } + /* ---- fixed costs first: they are not per-token ---- */ checkpoint_bytes_ = 0; window_ck_bytes_ = 0; @@ -242,7 +270,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config& for (size_t i = 1; i < plans_.size(); ++i) { KVGroupPlan& p = plans_[i]; p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && - !groups[i].drafter; + !p.runtime_win && !groups[i].drafter; if (p.win_snap && !p.zero && p.n_layers > 0) window_ck_bytes_ += p.window_blocks * p.bytes_per_block; } @@ -256,26 +284,98 @@ int KVManager::plan_groups(const std::vector& groups, const Config& if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT); /* And one unit per paged group, whose size need not be a multiple of the alignment. */ for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT; + /* A runtime window's ring is per sequence and on top of the context the split sizes: one + * ring a sequence, carved as a fixed cost. Its reference is the context itself, which the + * split already covers (the group is not capped at window_blocks). */ + for (const auto& p : plans_) + if (p.runtime_win && !p.zero) + fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT); fixed_ = fixed; ckpts_ = budget_ckpts; return RAD_OK; } -/* Windowed groups are capped at window_pool_cap, as in carve(). */ +/* Windowed groups are capped at window_pool_cap, as in carve(). A runtime-window group is not: + * its blocks are the reference (one context a sequence, as a FULL group) plus the ring its fixed + * costs already carry. */ int64_t KVManager::ceiling(int64_t ctx) const { if (ctx <= 0) return 0; int64_t need = fixed_; for (const auto& p : plans_) { if (!p.paged() || p.block_size <= 0) continue; int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size); - if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0) + if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0) blocks = std::min(blocks, window_pool_cap(p)); need += blocks * p.bytes_per_block; } return need; } +/* Moves a WINDOW group's plan to per-sequence runtime windows (declare_runtime_window). Returns + * false for any other group, so plan_groups() can apply it to every plan unconditionally. */ +bool KVManager::apply_runtime_window(KVGroupPlan& p) const { + auto it = runtime_decl_.find(p.index); + if (it == runtime_decl_.end() || p.kind != RAD_KV_WINDOW || p.runtime_win) return false; + p.runtime_win = true; + p.runtime_tokens = it->second; + /* The window a sequence may inherit (a fixed-window cap) is no longer the bound, and the + * declare-time window is not the sequence's own, so nothing here is snapshot-able. */ + p.win_snap = false; + return true; +} + +int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) { + if (g <= 0 || window_tokens <= 0) { + RAD_ERR("declare_runtime_window: group %d with a window of %lld (a runtime window needs a " + "real group and a positive W)", (int)g, (long long)window_tokens); + return RAD_E_INVAL; + } + const KVGroupPlan* p = plan(g); + if (p && p->kind != RAD_KV_WINDOW) { + RAD_ERR("group '%s' is not RAD_KV_WINDOW or RAD_KV_RING, so it cannot carry a runtime " + "window", p->name.c_str()); + return RAD_E_INVAL; + } + if (p && p->runtime_win && p->runtime_tokens != window_tokens) { + /* A RAD_KV_RING group's W is its declaration's `window`, and one already planned for + * another W has its ring in the fixed costs. */ + RAD_ERR("declare_runtime_window(%d): group '%s' already carries a runtime window of %lld " + "tokens, and its ring is sized for that", (int)g, p->name.c_str(), + (long long)p->runtime_tokens); + return RAD_E_INVAL; + } + if (configured_) { + RAD_ERR("declare_runtime_window(%d) after the carve: the group's blocks and fixed costs " + "are already sized for a different window", (int)g); + return RAD_E_STATE; + } + runtime_decl_[g] = window_tokens; + /* A plan built before the declaration (the engine's probes, or plan_groups() then declare) + * is updated in place; the next plan_groups() picks the declaration up on its own. */ + if (!plans_.empty()) { + if (g >= (int32_t)plans_.size()) return RAD_E_INVAL; + KVGroupPlan& q = plans_[(size_t)g]; + /* Whether the plan counted this group's window snapshot section (plan_groups' rule). */ + const bool counted = q.win_snap && !q.zero && q.n_layers > 0; + if (!apply_runtime_window(q)) return RAD_OK; /* already applied */ + /* The cost this declaration adds, against the plan as published: the ring is one a + * sequence, and the group gives up its window snapshot section. */ + fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT); + if (counted) { + const int64_t was = q.window_blocks * q.bytes_per_block; + window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0; + checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0; + } + } + return RAD_OK; +} + +int64_t KVManager::runtime_window_tokens(int32_t g) const { + const KVGroupPlan* p = plan(g); + return p && p->runtime_win ? p->runtime_tokens : 0; +} + /* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve * would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_) * over empty block state. On failure forget() empties both, so every entry point refuses @@ -328,11 +428,11 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_; /* A windowed group cannot address past its pool cap; cap it and give the bytes back to - * the others. */ + * the others. A runtime-window group's cap is the context plus its ring (a fixed cost). */ int32_t capped = -1; for (int32_t i : open) { const auto& p = plans_[i]; - if (p.kind != RAD_KV_WINDOW) continue; + if (p.kind != RAD_KV_WINDOW || p.runtime_win) continue; if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; } } if (capped < 0) break; @@ -369,7 +469,8 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const { int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const { if (tokens == kUnboundedTokens) return 0; const int64_t b = tokens / p.block_size; - if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p); + if (p.kind == RAD_KV_WINDOW && !p.runtime_win && b > window_pool_cap(p)) + return window_pool_cap(p); return b; } @@ -508,20 +609,31 @@ int KVManager::carve_into(Pool& kv_pool) { configured_ = true; report_ = bundling_.report(); + /* A runtime-window group reads as "ring": its window is the sequence's own, not the plan's. */ + auto kind_of = [](const KVGroupPlan& p) { + return p.runtime_win ? "ring" : kv_kind_name(p.kind); + }; for (const auto& p : plans_) { if (p.paged()) report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s " "%7lld blocks = %9s (%lld tokens)\n", - p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + p.name.c_str(), kind_of(p), (long long)p.n_layers, (long long)p.block_size, humanb(p.bytes_per_block).c_str(), (long long)p.n_blocks, humanb(p.pool_bytes).c_str(), (long long)(p.n_blocks * p.block_size)); else report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n", - p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + p.name.c_str(), kind_of(p), (long long)p.n_layers, humanb(p.bytes_per_state).c_str(), (long long)p.n_states, humanb(p.pool_bytes).c_str()); } + for (const auto& p : plans_) { + if (!p.runtime_win) continue; + report_ += fmt(" %-14s runtime window W=%lld: a sequence keeps its reference and a ring " + "of at most %lld block(s), rewritten in place\n", + p.name.c_str(), (long long)p.runtime_tokens, + (long long)p.ring_blocks_max()); + } /* The pool's address range, so a GPU fault address can be placed in the carve. */ report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n", pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(), @@ -804,7 +916,17 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const { const KVGroupPlan* p = plan(g); if (!p || !p->paged() || n_tokens <= 0) return 0; int64_t n = ceil_div(n_tokens, p->block_size); - if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p)); + if (p->kind == RAD_KV_WINDOW) { + if (p->runtime_win) { + /* The reference's blocks up to n, plus one ring. Without a sequence the floor is + * unknown, so the whole context is the bound on the reference. */ + const int64_t ring = p->ring_blocks_max(); + const int64_t ctx = max_ctx_ > 0 ? max_ctx_ : n_tokens; + n = std::min(n, ceil_div(ctx, p->block_size)) + ring; + } else { + n = std::min(n, window_seq_cap(*p)); + } + } return n; } @@ -835,6 +957,7 @@ int KVManager::add_sequence(uint64_t id) { s.id = id; s.blocks.resize(plans_.size()); s.first_block_pos.assign(plans_.size(), 0); + s.win.resize(plans_.size()); s.state.assign(plans_.size(), -1); s.dirty_from.assign(plans_.size(), 0); seqs_.emplace(id, std::move(s)); @@ -852,6 +975,7 @@ int KVManager::preempt(uint64_t id) { for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b); s->blocks[g].clear(); s->first_block_pos[g] = 0; + s->win[g] = SeqWindow{}; s->dirty_from[g] = 0; /* The recurrent state goes too (see preempt in kv.h, spec §7.1). */ if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; } @@ -869,6 +993,11 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) { if (n_tokens < 0) return RAD_E_INVAL; /* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */ if (n_tokens >= s->n_tokens) return RAD_OK; + /* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full, + * so the slots a rejected verify wrote may already hold newer keys. Speculation stays off for + * these requests (the scheduler never drafts for them); this refuses rather than corrupt. */ + for (const SeqWindow& w : s->win) + if (w.set) return RAD_E_UNSUPPORTED; for (size_t g = 0; g < plans_.size(); ++g) { const auto& p = plans_[g]; @@ -898,6 +1027,81 @@ int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const { return s->first_block_pos[(size_t)g]; } +/* ------------------------------------------------------------------ the runtime window */ + +int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens) { + if (!configured_) return RAD_E_STATE; + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + if (visible_lo < 0 || window_tokens <= 0) return RAD_E_INVAL; + /* The reference is written linearly, so the floor cannot be behind KV the sequence already + * holds: rebasing would have to move blocks the ring has not been shaped for. */ + if (visible_lo < s->n_tokens) { + RAD_ERR("sequence %llu: runtime window floor %lld is behind its %lld held tokens", + (unsigned long long)id, (long long)visible_lo, (long long)s->n_tokens); + return RAD_E_STATE; + } + bool any = false; + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (p.kind != RAD_KV_WINDOW) continue; + SeqWindow w; + w.set = true; + w.window = window_tokens; + w.visible_lo = visible_lo; + /* Whole blocks: the ring starts at the first boundary at or after the floor, and the + * tokens in [visible_lo, ring_pos) stay in the reference's last block (SeqWindow). The + * ring itself must span all of W: the frozen tokens are the oldest of the tail, so a + * smaller ring would lose the last W - span positions. */ + w.ring_pos = ceil_div(visible_lo, p.block_size) * p.block_size; + w.ring_blocks = ceil_div(window_tokens, p.block_size); + if (w.ring_blocks < 1) w.ring_blocks = 1; /* the ring always has somewhere to write */ + /* What the sequence can hold: the reference's blocks, then the whole ring. */ + const int64_t need = w.ring_pos / p.block_size + w.ring_blocks; + if (p.n_blocks > 0 && need > p.n_blocks) return RAD_E_FULL; + s->win[g] = w; + any = true; + } + if (!any) return RAD_E_UNSUPPORTED; + return RAD_OK; +} + +bool KVManager::runtime_window(uint64_t id, int32_t g, SeqWindow* out) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->win.size() || !s->win[(size_t)g].set) return false; + if (out) *out = s->win[(size_t)g]; + return true; +} + +bool KVManager::has_runtime_window(uint64_t id) const { + const Seq* s = find(id); + if (!s) return false; + for (const SeqWindow& w : s->win) if (w.set) return true; + return false; +} + +/* The block-table index of the block holding `pos`, or -1 past the table. A runtime window's + * reference maps as a fixed group does (first_block_pos is 0 there: the table starts at position + * 0); its ring maps modulo its blocks, which is what recycles the ring's slots in place. */ +int64_t KVManager::table_index(const KVGroupPlan& p, const SeqWindow& w, int64_t first_block_pos, + int64_t pos, int64_t table_len) { + int64_t bi = (pos - first_block_pos) / p.block_size; + if (w.set && pos >= w.ring_pos) { + bi = w.ring_pos / p.block_size + + ((pos - w.ring_pos) / p.block_size) % w.ring_blocks; + } + if (bi < 0 || bi >= table_len) return -1; + return bi; +} + +/* What ensure() must have in the table for `n_tokens`: the reference grows linearly until the + * floor, then the ring fills up to its whole span and never grows again. */ +int64_t KVManager::window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens) { + const int64_t ref = w.ring_pos / p.block_size; + if (n_tokens <= w.ring_pos) return ceil_div(n_tokens, p.block_size); + return ref + std::min(w.ring_blocks, ceil_div(n_tokens - w.ring_pos, p.block_size)); +} + int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; } int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const { @@ -1022,11 +1226,15 @@ int64_t KVManager::step_blocks(const KVGroupPlan& p) const { /* Slides from the step's first query, not its last. The query at keep_from reads keys down to * keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later * (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode - * step but drops keys the earlier rows of a prefill chunk still need. */ + * step but drops keys the earlier rows of a prefill chunk still need. + * + * A sequence with a runtime window is left alone. Its visible set is anchored at 0, so nothing in + * the table is below a sliding floor to recycle; the ring's blocks are rewritten in place and + * the table never moves (SeqWindow). */ void KVManager::recycle_window(Seq* s, int64_t keep_from) { for (size_t g = 0; g < plans_.size(); ++g) { const auto& p = plans_[g]; - if (p.kind != RAD_KV_WINDOW) continue; + if (p.kind != RAD_KV_WINDOW || s->win[g].set) continue; int64_t first = s->first_block_pos[g] / p.block_size; int64_t target = std::max(first, keep_from / p.block_size - (p.window_blocks - 1)); @@ -1065,7 +1273,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) { const auto& p = plans_[g]; if (p.paged()) { int64_t first = s->first_block_pos[g] / p.block_size; - int64_t want = ceil_div(n_tokens, p.block_size) - first; + int64_t want = s->win[g].set + ? window_table_len(p, s->win[g], n_tokens) - first + : ceil_div(n_tokens, p.block_size) - first; need[g] = want - (int64_t)s->blocks[g].size(); if (need[g] < 0) need[g] = 0; /* Copy-on-write: the partial block is the only one a write reaches; if it is shared, @@ -1101,7 +1311,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) { } } } - int64_t want = ceil_div(n_tokens, p.block_size) - first; + int64_t want = s->win[g].set + ? window_table_len(p, s->win[g], n_tokens) - first + : ceil_div(n_tokens, p.block_size) - first; if ((int64_t)s->blocks[g].size() < want) s->dirty_from[g] = std::min(s->dirty_from[g], (int64_t)s->blocks[g].size()); @@ -1125,6 +1337,10 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector& blocks, if (!s) return RAD_E_NOTFOUND; const KVGroupPlan* p = plan(g); if (!p || !p->paged()) return RAD_E_INVAL; + /* A runtime window's table is its own reference plus ring, laid out against a floor no cache + * entry knows (set_window), so blocks adopted from a prefix hit would sit at the wrong + * positions. Prefix publish is skipped for such a sequence; this is the backstop. */ + if (s->win[(size_t)g].set) return RAD_E_STATE; /* Whole blocks only (see adopt in kv.h). */ if (n_tokens % p->block_size != 0) return RAD_E_INVAL; if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL; @@ -1145,6 +1361,14 @@ int KVManager::fork(uint64_t parent, uint64_t child) { Seq* pa = find(parent); if (!pa) return RAD_E_NOTFOUND; if (seqs_.count(child)) return RAD_E_DUPLICATE; + /* The window is runtime data: a child that shared the table without it would read the ring + * as if it were a reference. A forking model (speculative decoding) does not carry one. */ + for (const SeqWindow& w : pa->win) + if (w.set) { + RAD_ERR("sequence %llu: fork refused, it carries a runtime window", + (unsigned long long)parent); + return RAD_E_UNSUPPORTED; + } /* Pass 1: the child needs its own state slot in every stateful group before anything is * shared (see fork in kv.h, spec §7.3). */ @@ -1159,6 +1383,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) { if (plans_[g].paged()) { ch->blocks[g] = pa->blocks[g]; ch->first_block_pos[g] = pa->first_block_pos[g]; + ch->win[g] = pa->win[g]; for (int32_t b : ch->blocks[g]) add_ref(g, b); } else { grab_state((int32_t)g, &ch->state[g]); @@ -1188,7 +1413,10 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens, if (p.paged()) { int64_t first = s->first_block_pos[g] / p.block_size; int64_t want = ceil_div(n_tokens, p.block_size) - first; - if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p)); + if (p.kind == RAD_KV_WINDOW) { + if (s->win[g].set) want = window_table_len(p, s->win[g], n_tokens) - first; + else want = std::min(want, window_seq_cap(p)); + } int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */ if (extra > available_blocks((int32_t)g)) return false; } else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false; @@ -1368,6 +1596,9 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector* out) out->clear(); const Seq* s = find(id); if (!s || pos <= 0) return false; + /* A runtime window is excluded from window snapshots (set_window): the window length is + * runtime data and the table is a reference plus a ring, not [lo, pos). */ + for (const SeqWindow& w : s->win) if (w.set) return false; for (size_t g = 0; g < plans_.size(); ++g) { const KVGroupPlan& p = plans_[g]; if (!p.win_snap) continue; @@ -1389,6 +1620,8 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector* out) int KVManager::seed_window(uint64_t id, int64_t pos) { Seq* s = find(id); if (!s) return RAD_E_NOTFOUND; + /* A sequence with a runtime window is never resumed from a window snapshot (set_window). */ + for (const SeqWindow& w : s->win) if (w.set) return RAD_E_STATE; /* Check every group before taking anything, as ensure() does. */ for (size_t g = 0; g < plans_.size(); ++g) { const KVGroupPlan& p = plans_[g]; diff --git a/core/mem/kv.h b/core/mem/kv.h index a29e8c64..81a9a102 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -11,6 +11,10 @@ * RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state * RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries * + * A RAD_KV_RING group is a RAD_KV_WINDOW whose floor is per sequence and set at runtime (R-SWA, + * see SeqWindow); it is planned as a WINDOW group with `runtime_win` set, so no kind of its own + * reaches the plan. + * * The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what * a sequence owns. With two, a freed sequence's state slot could still be handed to the next * request by the other. @@ -50,6 +54,45 @@ struct BundleComparison { }; BundleComparison compare_bundling(const std::vector& bundles); +/* ------------------------------------------------------------------ the runtime window */ +/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the + * "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image + * tokens, then a ring of W decode slots right after it, rewritten in place forever). + * + * A fixed sliding window (`KVGroupPlan::window_blocks`, gemma4's) keeps the last W tokens: the + * table starts where the window begins and blocks leave from its front. A runtime window instead + * retains the whole prefill as the reference and appends into a ring after it: + * + * visible = [0, visible_lo) U [visible_lo, visible_lo + W) + * + * `visible_lo` is the sequence's own prefill length (image tokens included), so the visible set is + * per sequence. The reference is never recycled and first_block_pos stays 0 (the table still + * starts at position 0); only the ring's slot mapping recycles, so RoPE positions keep increasing + * with the token's own position and a decode query sees the whole reference plus the ring. + * + * Blocks are whole, so the ring can start only on a block boundary: it starts at + * `ring_pos = ceil(visible_lo / block) * block` with `ceil(W / block)` blocks, and the tokens in + * [visible_lo, ring_pos) stay in the reference's last block (they are the oldest of the tail and + * are never rewritten). The visible tail is therefore W .. W + block - 1 tokens when W is a block + * multiple -- with block_size 128 = W the 128-256 token granularity of the plan, exact even when + * the floor is not aligned -- and up to one block more otherwise, always a superset of the + * reference implementation's last W. The ring's blocks hold the newest positions in place (no + * block is allocated past them, so the sequence's bytes are flat once the floor is set): + * + * block index = ring_pos / block + ((pos - ring_pos) / block) % ring_blocks + * + * A sequence with a runtime window is excluded from prefix-cache reuse, window snapshots, forking + * and speculative rollback: all three assume the declare-time window, and the runtime length is + * not in any cache key (see KVManager::set_window). */ +struct SeqWindow { + bool set = false; + int64_t window = 0; /* W as set */ + int64_t visible_lo = 0; /* the retained reference ends here */ + int64_t ring_pos = 0; /* block-aligned first ring token position */ + int64_t ring_blocks = 0; /* whole blocks the ring holds */ + int64_t ring_span(int64_t block) const { return ring_blocks * block; } +}; + /* ------------------------------------------------------------------ per-group plan */ struct KVGroupPlan { int32_t index = -1; /* position in Program::kv_groups */ @@ -62,6 +105,18 @@ struct KVGroupPlan { int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */ int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */ int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */ + /* WINDOW: sequences may be given a runtime window (declare_runtime_window). Such a group is + * sized for the whole context plus one ring per sequence instead of being capped at + * window_blocks, its window is not snapshotted, and a sequence armed with one is bounded by + * its own reference + ring rather than by window_blocks. */ + bool runtime_win = false; + int64_t runtime_tokens = 0; /* the W set_window arms a sequence with */ + /* The most ring blocks one sequence needs: ceil(W / block), the reference's fraction d of + * the ring's first block being frozen in it (see SeqWindow). */ + int64_t ring_blocks_max() const { + return runtime_tokens > 0 && block_size > 0 + ? (runtime_tokens + block_size - 1) / block_size : 0; + } /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a * trunk group of a model with no linear state. A drafter's window is recomputed by draft * refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither @@ -202,9 +257,46 @@ public: /* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the * window and only the next ensure() recycles them, so a prefill waiting for its next chunk * would hold a whole chunk of blocks; several such prefills can exhaust the pool. The - * scheduler calls this when it advances n_computed, passing the new n_computed. */ + * scheduler calls this when it advances n_computed, passing the new n_computed. + * + * A sequence with a runtime window retains its reference and rewrites its ring in place, so + * nothing below the floor may be recycled and this is a no-op for it. */ void trim_window(uint64_t seq, int64_t keep_from); + /* ---------------- the runtime window (R-SWA; see SeqWindow) ---------------- */ + /* Mark a WINDOW group as carrying per-sequence runtime windows of `window_tokens`. Call before + * plan_groups()/configure(): it changes the plan (the group is sized for the whole context + * plus one ring a sequence, its window is not snapshotted, and the ring joins the fixed + * costs), so a group declared after the plan is refused. A fixed-window group is untouched. + * + * A group that is not marked still accepts set_window() -- the caller then sizes the pool + * itself, e.g. by declaring the group's window as the whole context -- and each sequence's + * capacity is checked at set_window()/ensure() against the blocks actually carved. */ + int declare_runtime_window(int32_t group, int64_t window_tokens); + + /* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens + * included) as the retained reference's end and a ring of `window_tokens` after it. Every + * paged WINDOW group of the sequence gets the same floor. Call it before the sequence's KV + * grows past `visible_lo` -- at admission, where the scheduler knows the prompt length -- so + * the reference is written linearly and no checkpoint can be reserved for it (a snapshot + * would describe a window the sequence no longer has). + * + * RAD_E_UNSUPPORTED no windowed group; + * RAD_E_INVAL a negative floor or a window of 0; + * RAD_E_STATE the sequence already holds tokens past the floor; + * RAD_E_FULL the reference plus the ring exceeds what this group carved. */ + int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens); + + /* The sequence's window in `group`, or false when it has none (a fixed-window group keeps + * KVGroupPlan::window_blocks and first_block_pos). The step batch maps a ring position with + * SeqWindow's rule; every other position maps as (pos - first_block_pos) / block_size. */ + bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const; + /* Whether any group has a runtime window set for the sequence. Prefix publish, checkpoint + * reservation and snapshots are skipped for it (see set_window). */ + bool has_runtime_window(uint64_t seq) const; + /* The W declare_runtime_window gave the group, 0 if it carries no runtime windows. */ + int64_t runtime_window_tokens(int32_t group) const; + /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's * block size: a partial block is never shared, because the next token written into it would * corrupt the cache entry. Bumps each block's refcount. */ @@ -359,7 +451,11 @@ public: /* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the * recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) / * block_size; without the offset a sliding-window sequence writes to the wrong slot once it - * passes its window. */ + * passes its window. + * + * A sequence with a runtime window (set_window) keeps 0 for the group's whole life: its table + * is [reference][ring] from position 0 and only the ring's slot index recycles (SeqWindow), + * so the mapping above holds for the reference and SeqWindow's rule for the ring. */ int64_t first_block_pos(uint64_t seq, int32_t group) const; /* The first table entry changed since the last call; entries below it are unchanged, and @@ -457,6 +553,9 @@ private: * for a windowed group. 0 for kUnboundedTokens, which is not a count. */ int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const; void forget(); + /* Turns a WINDOW group into a runtime-window one (declare_runtime_window). Returns false for a + * group that is not windowed. */ + bool apply_runtime_window(KVGroupPlan& p) const; /* One traversal serving both checkpoint directions; see checkpoint_save. */ int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save, @@ -467,6 +566,7 @@ private: int64_t n_tokens = 0; std::vector> blocks; /* per group */ std::vector first_block_pos; /* WINDOW: token pos of blocks[0] */ + std::vector win; /* per group: the runtime window, if any */ std::vector state; /* per group, -1 when not stateful */ /* Per group, the lowest table entry written since the batch builder last staged this * sequence. An append or truncation lowers it to where it touched; a shift lowers it to @@ -482,8 +582,16 @@ private: void drop_state(int32_t g, int32_t s); Seq* find(uint64_t seq); const Seq* find(uint64_t seq) const; - /* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */ + /* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. A runtime window + * (SeqWindow) is not trimmed: its reference must stay and its ring rewrites slots in place. */ void recycle_window(Seq* s, int64_t keep_from); + /* The block-table index the block holding `pos` has, or -1 past the table: the fixed mapping + * (pos - first_block_pos) / block_size, or the ring's for a runtime window. */ + static int64_t table_index(const KVGroupPlan& p, const SeqWindow& w, int64_t first_block_pos, + int64_t pos, int64_t table_len); + /* The table length a runtime-windowed sequence needs to hold `n_tokens`: the reference's + * blocks, then the ring's up to its whole span. */ + static int64_t window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens); std::vector plans_; std::vector> free_blocks_; /* per group */ @@ -511,6 +619,9 @@ private: int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */ int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */ int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */ + /* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its + * start: it is a declaration about the program, not about a plan. */ + std::unordered_map runtime_decl_; /* ---- the loan (see the public block) ---- * diff --git a/core/mm/item.cpp b/core/mm/item.cpp index df461703..d263ab3e 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -31,11 +31,18 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s; const int64_t within = first + k - patch_at(s); const int64_t bw = seg_w(s) / merge; - const int64_t in_col = within % merge; - const int64_t in_row = (within / merge) % merge; - const int64_t blk = within / (merge * merge); - const int64_t row = (blk / bw) * merge + in_row; - const int64_t col = (blk % bw) * merge + in_col; + int64_t row, col; + if (patch_raster) { + /* Raster order is its own inverse: patch i is row i / w, column i % w. */ + row = within / seg_w(s); + col = within % seg_w(s); + } else { + const int64_t in_col = within % merge; + const int64_t in_row = (within / merge) % merge; + const int64_t blk = within / (merge * merge); + row = (blk / bw) * merge + in_row; + col = (blk % bw) * merge + in_col; + } planes[k] = (int32_t)row; planes[count + k] = (int32_t)col; planes[2 * count + k] = seg_h(s); diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 4c304232..cbb869a4 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -40,6 +40,49 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) { } int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { + /* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and + * processor_config.json (`processor.*`). Every key has the reference's default, so a container + * converted before the tower landed still states a processor. */ + if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "unlimited_ocr")) { + family = Family::UnlimitedOcr; + patch = (int32_t)rad_meta_geti(&m, "processor.patch_size", + rad_meta_geti(&m, "vision_config.patch_size", 16)); + downsample = (int32_t)rad_meta_geti(&m, "processor.downsample_ratio", 4); + merge = downsample; + temporal = 1; + base_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.height", 1024); + tile = (int32_t)rad_meta_geti(&m, "preprocessor.tile_size", 640); + /* The base mode's whole view: what the reference states for its input, and what the + * preprocessor's `size` is. Multi-page inference may ask for the tile instead. */ + image_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.width", base_size); + crop_mode = meta_bool(m, "preprocessor.crop_to_patches", true); + if (const char* t = rad_meta_gets(&m, "processor.image_token", nullptr); t && *t) + image_token = t; + min_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.min_patches", 2); + max_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.max_patches", 32); + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + if (!read_triple(m, "preprocessor.image_mean", mean)) mean[0] = mean[1] = mean[2] = 0.5f; + if (!read_triple(m, "preprocessor.image_std", stdv)) stdv[0] = stdv[1] = stdv[2] = 0.5f; + /* 3 is PIL's bicubic, the only filter this processor stages. */ + const int64_t resample = rad_meta_geti(&m, "preprocessor.resample", 3); + if (resample != 3) { + if (why) *why = "the container resamples pictures with filter " + + std::to_string(resample) + "; this processor stages PIL's bicubic (3)"; + return RAD_E_UNSUPPORTED; + } + /* No video; the bands only have to be consistent for check(). */ + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = video_min_pixels = f2; + image_max_pixels = video_max_pixels = (int64_t)base_size * base_size; + min_frames = 1; + std::string bad; + if (check(&bad) < 0) { + if (why) *why = "the container's Unlimited-OCR processor configuration is " + "inconsistent: " + bad; + return RAD_E_INVAL; + } + return RAD_OK; + } /* LFM2-VL states its processor twice, in config.json and in processor_config.json's * image_processor; the latter is what the reference processor reads, so it goes first. */ if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) { @@ -200,6 +243,20 @@ int VisionConfig::check(std::string* why) const { if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0) return no("max_pixels_tolerance and max_num_patches must be positive"); } + if (family == Family::UnlimitedOcr) { + if (patch <= 0 || downsample <= 0 || merge != downsample) + return no("the tower's geometry (patch_size " + std::to_string(patch) + + ", downsample_ratio " + std::to_string(downsample) + + ") does not cut a whole merged patch"); + if (base_size <= 0 || base_size % factor() || image_size <= 0 || image_size % factor()) + return no("the global view's side (" + std::to_string(base_size) + " and " + + std::to_string(image_size) + " pixels) is not a whole number of merged " + "patches"); + if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor()) + return no("the tiling (min_patches " + std::to_string(min_tiles) + ", max_patches " + + std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) + + ") is not a range of whole merged patches"); + } if (family == Family::Gemma4) { if (!soft_budget_ok(image_soft_tokens)) return no("the image soft-token budget " + std::to_string(image_soft_tokens) + @@ -425,69 +482,95 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, } /* namespace */ +/* 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 + * function. */ +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 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; + for (int32_t x = 0; x < xmax; ++x) { + const uint8_t* p = row + (size_t)(x + xmin) * 3; + s0 += p[0] * k[x]; + s1 += p[1] * k[x]; + s2 += p[2] * k[x]; + } + o[xx * 3 + 0] = clip8(s0, prec); + o[xx * 3 + 1] = clip8(s1, prec); + o[xx * 3 + 2] = clip8(s2, prec); + } + } +} + +static void pass_vertical(const Frame& src, int32_t shift, int32_t h, + const std::vector& bv, const std::vector& kv, + int32_t ksv, int prec, Frame* out) { + 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 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; + 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) { + 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); + } + } +} + static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) { if (in.w == w && in.h == h) { *out = in; return; } std::vector bh, kh, bv, kv; int ph = kPrec, pv = kPrec; const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph); const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv); + const bool need_h = w != in.w, need_v = h != in.h; - /* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */ - const int y_first = bv[0]; - const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1]; - const bool need_h = w != in.w; - const bool need_v = h != in.h; + /* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by + * more than twice what the width does, so the horizontal pass runs over fewer rows. The + * intermediate is eight bits, so the order changes the picture: both are the reference's. + * torchvision's on a uint8 tensor (ATen's CPU kernel) is horizontal first at every size. */ + const bool horizontal_first = + torch || !((int64_t)in.h - h > 0 && (int64_t)in.h - h > 2 * ((int64_t)in.w - w)); Frame tmp; - const Frame* src = ∈ + if (need_h && need_v) { + if (horizontal_first) { + /* Only the source rows the vertical pass reads are resampled horizontally. */ + const int32_t y0 = bv[0]; + const int32_t rows = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1] - y0; + pass_horizontal(in, y0, rows, w, bh, kh, ksh, ph, &tmp); + pass_vertical(tmp, y0, h, bv, kv, ksv, pv, out); + } else { + pass_vertical(in, 0, h, bv, kv, ksv, pv, &tmp); + pass_horizontal(tmp, 0, h, w, bh, kh, ksh, ph, out); + } + return; + } if (need_h) { - const int rows = need_v ? y_last - y_first : in.h; - const int y0 = need_v ? y_first : 0; - tmp.w = w; - tmp.h = rows; - tmp.rgb.assign((size_t)w * rows * 3, 0); - for (int yy = 0; yy < rows; ++yy) { - const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3; - uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3; - for (int xx = 0; xx < w; ++xx) { - const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; - const int32_t* k = kh.data() + (size_t)xx * ksh; - int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0; - for (int x = 0; x < xmax; ++x) { - const uint8_t* p = row + (size_t)(x + xmin) * 3; - s0 += p[0] * k[x]; - s1 += p[1] * k[x]; - s2 += p[2] * k[x]; - } - o[xx * 3 + 0] = clip8(s0, ph); - o[xx * 3 + 1] = clip8(s1, ph); - o[xx * 3 + 2] = clip8(s2, ph); - } - } - src = &tmp; - } - if (!need_v) { *out = std::move(tmp); return; } - const int shift = need_h ? y_first : 0; - out->w = src->w; - out->h = h; - out->rgb.assign((size_t)src->w * h * 3, 0); - for (int yy = 0; yy < h; ++yy) { - const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1]; - const int32_t* k = kv.data() + (size_t)yy * ksv; - uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3; - for (int xx = 0; xx < src->w; ++xx) { - int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0; - for (int y = 0; y < ymax; ++y) { - const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * 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, pv); - o[xx * 3 + 1] = clip8(s1, pv); - o[xx * 3 + 2] = clip8(s2, pv); - } + pass_horizontal(in, 0, in.h, w, bh, kh, ksh, ph, out); + return; } + pass_vertical(in, 0, h, bv, kv, ksv, pv, out); } void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { @@ -678,6 +761,19 @@ int Processor::init(const VisionConfig& cfg, encode_text_ = std::move(encode_text); return RAD_OK; } + if (cfg.family == Family::UnlimitedOcr) { + /* The vocabulary spells the marker (`processor.image_token`), and every placeholder of a + * picture is that same id: there is nothing else to resolve. */ + if (!token_id) return RAD_E_INVAL; + if (cfg_.tok_image < 0) cfg_.tok_image = token_id(cfg_.image_token); + if (cfg_.tok_image < 0) return RAD_E_NOTFOUND; + /* A tile's line and the global view are each one segment, so each must fit one pass. */ + const int64_t q = cfg.tile / cfg.patch; + const int64_t g = std::max(cfg.base_size, cfg.image_size) / cfg.patch; + if (q * (q + 4) > cfg.max_patches || g * (g + 4) > cfg.max_patches) return RAD_E_INVAL; + encode_text_ = std::move(encode_text); + return RAD_OK; + } /* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes * smart_resize keep every image inside a pass. */ const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch; @@ -727,6 +823,55 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32 } } +/* Unlimited-OCR's ratios of one tile count tie only when they are each other's transpose: two + * ratios of the same count are equally near an aspect only if one mirrors the other about it. So + * the reference's set order matters for exactly the (c, r) pairs below, the tall ones (c < r) + * its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set + * has for the 2..32-tile range the checkpoint states. It comes from the reference itself + * (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */ +bool uocr_tall_last(int32_t c, int32_t r) { + static const int8_t kTallLast[][2] = { + {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14}, + {1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4}, + {2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16}, + {3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, + }; + for (const auto& p : kTallLast) + if (p[0] == c && p[1] == r) return true; + return false; +} + +void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, + int32_t* cols, int32_t* rows) { + *cols = *rows = 1; + if (h <= 0 || w <= 0 || min_tiles < 1 || max_tiles < min_tiles) return; + const double aspect = (double)w / (double)h; + const double area = (double)w * (double)h; + const double half = 0.5 * (double)tile * (double)tile; + double best = INFINITY; + for (int32_t n = min_tiles; n <= max_tiles; ++n) { + int32_t deferred[8]; /* the transposed ratios the reference visits last */ + int32_t n_deferred = 0; + auto visit = [&](int32_t c, int32_t r) { + const double diff = std::fabs(aspect - (double)c / (double)r); + if (diff < best) { + best = diff; *cols = c; *rows = r; + } else if (diff == best && area > half * (double)n) { + *cols = c; *rows = r; + } + }; + for (int32_t c = 1; c <= n; ++c) { + if (n % c) continue; + if (c < n / c && uocr_tall_last(c, n / c)) { + if (n_deferred < 8) deferred[n_deferred++] = c; + continue; + } + visit(c, n / c); + } + for (int32_t k = 0; k < n_deferred; ++k) visit(deferred[k], n / deferred[k]); + } +} + /* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles * in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each * merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so @@ -804,10 +949,224 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr* out, std::strin return RAD_OK; } -int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why) const { +int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size, + int32_t* image_size, std::string* why) { + auto no = [why](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + if (c.family != Family::UnlimitedOcr) return no("this model has one picture mode, not two"); + const int32_t F = c.factor(); + const bool cr = mode.kind == ImageMode::Base ? false + : mode.kind == ImageMode::Gundam ? true + : c.crop_mode; + const int32_t bs = mode.base_size > 0 ? mode.base_size : c.base_size; + const int32_t is = mode.image_size > 0 ? mode.image_size : c.image_size; + if (cr) { + /* The crops are the tile the checkpoint was trained at; the reference's image_size is + * that same number, so a request may only restate it. */ + if (bs % F) + return no("base_size " + std::to_string(bs) + " is not a whole number of merged " + "patches (" + std::to_string(F) + ")"); + if (bs < 4 * F) + return no("base_size " + std::to_string(bs) + " is under two output rows"); + if (mode.image_size > 0 && mode.image_size != c.tile) + return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; " + "image_size " + std::to_string(mode.image_size) + " is not one"); + *crop = true; *base_size = bs; *image_size = c.tile; + return RAD_OK; + } + if (is % F) + return no("image_size " + std::to_string(is) + " is not a whole number of merged patches " + "(" + std::to_string(F) + ")"); + if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows"); + if (mode.base_size > 0 && mode.base_size != bs) + return no("the base mode pads a page to image_size, not base_size"); + *crop = false; *base_size = bs; *image_size = is; + return RAD_OK; +} + +int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows) { + bool crop = false; + int32_t bs = 0, is = 0; + if (uocr_mode(c, mode, &crop, &bs, &is, nullptr) < 0) return -1; + const int32_t P = c.patch, D = c.downsample; + /* The global view: `g` lines of `g` features, each followed by a newline, then the view + * separator (`[tok] * g + [tok]) * g + [tok]`). */ + const int32_t g = (crop ? bs : is) / P / D; + int64_t t = (int64_t)(g + 1) * g + 1; + /* The local views, when the picture is tiled: one line per feature row holding every tile's + * row, a newline after it (`[tok] * q * cols + [tok]) * q * rows`). */ + if (crop && (int64_t)cols * rows > 1) { + const int32_t q = c.tile / P / D; + t += (int64_t)(q * cols + 1) * q * rows; + } + return t; +} + +void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out) { + /* ImageOps.pad: contain() fits the picture inside w x h at its own aspect (PIL's bicubic, + * rounded as its round() does), then it is pasted centred on `fill`. */ + int32_t nw = w, nh = h; + if (in.w > 0 && in.h > 0) { + const double im_ratio = (double)in.w / (double)in.h; + const double dst_ratio = (double)w / (double)h; + if (im_ratio != dst_ratio) { + if (im_ratio > dst_ratio) { + nh = (int32_t)pyround((double)in.h / (double)in.w * (double)w); + if (nh == 0) nh = 1; + } else { + nw = (int32_t)pyround((double)in.w / (double)in.h * (double)h); + if (nw == 0) nw = 1; + } + } + } + const Frame* src = ∈ + Frame fitted; + if (nw != in.w || nh != in.h) { + resize_bicubic(in, nw, nh, &fitted); + src = &fitted; + } + out->w = w; + out->h = h; + out->rgb.assign((size_t)w * (size_t)h * 3, fill); + const int32_t x = nw != w ? (int32_t)pyround((double)(w - nw) * 0.5) : 0; + const int32_t y = nw != w ? 0 : (int32_t)pyround((double)(h - nh) * 0.5); + for (int32_t yy = 0; yy < src->h; ++yy) + std::memcpy(out->rgb.data() + ((size_t)(y + yy) * (size_t)w + (size_t)x) * 3, + src->rgb.data() + (size_t)yy * (size_t)src->w * 3, (size_t)src->w * 3); +} + +/* Unlimited-OCR's picture processor, the reference's infer() and infer_multi() exactly: the + * global view is the picture ImageOps.pad-ed to base_size (in the base mode, to image_size, + * squared first when that side is a tile or less), and in the gundam mode a picture larger than a + * tile is cut the way dynamic_preprocess cuts it. Each view is staged as its feature grid plus + * `downsample` patch columns nothing is read from, because the reference's layout puts a newline + * after every line of features: one output row per downsample x downsample patches, and the last + * column's rows are where those newlines go. The segments are, in the reference's order, the + * local grid's lines (one per tile row; a line wider than a pass is cut into chunks of whole + * tiles, its last chunk carrying the newline column), then the global view's grid, then the view + * separator's single row. */ +int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode, + std::shared_ptr* out, std::string* why) const { const VisionConfig& c = cfg_; + const int32_t P = c.patch, M = c.merge; + bool crop = false; + int32_t base_size = 0, image_size = 0; + RAD_TRY(uocr_mode(c, mode, &crop, &base_size, &image_size, why)); + if (f.w <= 0 || f.h <= 0) { + if (why) *why = "the picture has no size"; + return RAD_E_INVAL; + } + const int32_t q = c.tile / P; /* a tile's patch rows */ + int32_t cols = 1, rows = 1; + const bool tiled = crop && (f.w > c.tile || f.h > c.tile); + if (tiled) uocr_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows); + + /* The global view. The base mode squares a page of a tile or less before padding it, as the + * reference's multi-page path does. */ + Frame global; + if (crop) { + pad_bicubic(f, base_size, base_size, 127, &global); + } else if (image_size <= c.tile) { + Frame sq; + resize_bicubic(f, image_size, image_size, &sq); + pad_bicubic(sq, image_size, image_size, 127, &global); + } else { + pad_bicubic(f, image_size, image_size, 127, &global); + } + const int32_t g = (crop ? base_size : image_size) / P; + if ((int64_t)g * (g + 4) > c.max_patches) { + if (why) *why = "the global view's " + std::to_string((long long)g * (g + 4)) + + " patches are more than one encoder pass holds (" + + std::to_string(c.max_patches) + ")"; + return RAD_E_INVAL; + } + + /* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */ + uint16_t lut[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]); + } + + auto it = std::make_shared(); + it->kind = Kind::Image; + it->patch_dim = c.patch_dim(); + it->rope_1d = true; + it->patch_raster = true; + int64_t seg_row = 0; + /* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w` + * patches a row carry pixels; the rest are the newline column. */ + auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw, + int32_t real_w) { + it->segments.push_back({ gh, gw, it->n_patch }); + it->seg_at.push_back((int32_t)seg_row); + it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image); + seg_row += (int64_t)(gh / M) * (gw / M); + it->n_patch += (int64_t)gh * gw; + 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) + 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]]; + } + } + }; + + if (tiled) { + Frame big; + resize_bicubic(f, cols * c.tile, rows * c.tile, &big); + /* A chunk of a line must fit one pass: q rows of q patches a tile, plus the newline + * column its last chunk holds. */ + int64_t per_row = c.max_patches / q; + const int64_t chunk = per_row > 4 ? (per_row - 4) / q : 0; + if (chunk < 1) { + if (why) *why = "one encoder pass holds no line of " + std::to_string(q) + + "-patch tiles (" + std::to_string(c.max_patches) + " patches)"; + return RAD_E_INVAL; + } + for (int32_t r = 0; r < rows; ++r) + for (int32_t c0 = 0; c0 < cols; c0 += (int32_t)chunk) { + const int32_t n = std::min((int32_t)chunk, cols - c0); + const bool last = c0 + n == cols; + append(big, c0 * c.tile, r * c.tile, q, q * n + (last ? 4 : 0), q * n); + } + } + append(global, 0, 0, g, g + 4, g); + /* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */ + append(global, 0, 0, M, M, 0); + + it->n_seg = (int32_t)it->segments.size(); + it->grid_t = 1; + it->grid_h = it->segments[0].h; + it->grid_w = it->segments[0].w; + it->rows_h = it->grid_h / M; + it->rows_w = it->grid_w / M; + it->seg_rows = it->rows_h * it->rows_w; + content_key(*it, &it->key_hi, &it->key_lo); + *out = std::move(it); + return RAD_OK; +} + +int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why, + const ImageMode& mode) const { + const VisionConfig& c = cfg_; + if (mode.kind != ImageMode::Default && c.family != Family::UnlimitedOcr) { + if (why) *why = "this model has one picture mode; images_config names one of two"; + return RAD_E_UNSUPPORTED; + } if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why); if (c.family == Family::Lfm2) return image_lfm2(f, out, why); + if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why); int64_t h = 0, w = 0; RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, &h, &w, why)); @@ -979,7 +1338,12 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin } int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, - std::shared_ptr* out, std::string* why, int64_t max_pixels) const { + std::shared_ptr* out, std::string* why, int64_t max_pixels, + const ImageMode& mode) const { + if (mode.kind != ImageMode::Default && cfg_.family != Family::UnlimitedOcr) { + if (why) *why = "this model has one picture mode; images_config names one of two"; + return RAD_E_UNSUPPORTED; + } if (image_tokens != 0) { if (cfg_.family != Family::Gemma4) { if (why) *why = "this model's processor sizes an image by its pixels, not by a token " @@ -1003,7 +1367,7 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, } if (cfg_.family == Family::Gemma4) return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why); - return image_from(f, out, why); + return image_from(f, out, why, mode); } namespace { diff --git a/core/mm/processor.h b/core/mm/processor.h index 5be2cf42..20a3b5d3 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -55,8 +55,20 @@ enum class Kind { Image, Video, Audio }; * is cut into tile x tile crops, min_tiles..max_tiles of them in the ratio nearest its * own, followed by the whole picture at the budgeted size as a thumbnail. Patches * (y, x, channel) normalised by the mean and deviation, resized with torchvision's - * fixed-point bicubic; images only, and the tokens rotate at their positions. */ -enum class Family { QwenVL, Gemma4, Lfm2 }; + * fixed-point bicubic; images only, and the tokens rotate at their positions. + * UnlimitedOcr + * Unlimited-OCR's DeepSeek-OCR shape, in the checkpoint's two modes (ImageMode): the + * picture padded (ImageOps.pad) to base_size x base_size on a 127 grey as the global + * view, and, in the gundam mode, a picture larger than one tile cut into min_tiles.. + * max_tiles tile x tile crops at the tile in the ratio nearest its own (its + * dynamic_preprocess). The SAM neck downsamples by `downsample`, so patch * downsample + * is one output row. A view's rows are laid out as the reference's feature grid plus a + * column of newlines, which is why every segment carries `downsample` extra patch + * columns that nothing is read from: patches are raster order (Item::patch_raster), one + * patch (channel, y, x), each value (u / 255 - mean) / std in f32, rounded to bf16. + * Every placeholder is one id (the picture marker itself); the tokens rotate at their + * positions. */ +enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr }; struct VisionConfig { Family family = Family::QwenVL; @@ -81,6 +93,17 @@ struct VisionConfig { double max_pixels_tolerance = 0.0; int64_t max_segment_patches = 0; + /* UnlimitedOcr: the two modes' sizes, from the checkpoint's preprocessor config. The gundam + * mode pads the global view to `base_size` and cuts crops at `tile`; the base mode (a page of + * a multi-page document) pads the whole picture to `image_size`. `downsample` is the SAM + * neck's ratio: one output row is `patch * downsample` pixels a side. `crop_mode` is the + * deployment's mode when a request names none. */ + int32_t base_size = 0, image_size = 0, downsample = 0; + bool crop_mode = false; + /* The vocabulary's spelling of the picture marker (`processor.image_token`); every + * placeholder of a picture is that one id. */ + std::string image_token = ""; + /* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image * is one segment and a segment is never split, so the image band's ceiling is lowered to fit * it. `max_source_pixels` bounds what the decoder may hold before any resize. */ @@ -102,6 +125,18 @@ struct VisionConfig { int from_meta(const RadModelMeta& m, std::string* why); }; +/* Which picture processor a request gets, for a checkpoint that has more than one: Unlimited-OCR + * states two modes and the reference names them gundam (one picture: the global view at base_size + * plus crops) and base (a page of a multi-page document: the global view only, at image_size). + * `Default` is the deployment's (`VisionConfig::crop_mode`); a request may pick either mode and, + * with it, the sizes the checkpoint states differently. `base_size` and `image_size` of 0 keep the + * mode's own. */ +struct ImageMode { + enum Kind : int32_t { Default = 0, Gundam = 1, Base = 2 }; + int32_t kind = Default; + int32_t base_size = 0, image_size = 0; +}; + /* The audio feature extractor family, from the container's audio_config.model_type. The * families differ in the spectrogram and in how a clip's frames are laid out for the encoder; * the Item they produce is shared. @@ -199,6 +234,9 @@ struct Item { /* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not * on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */ bool rope_1d = false; + /* Patches are in raster order (row by row), not merge-block order: the coordinate planes + * invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */ + bool patch_raster = false; int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; } int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; } @@ -309,13 +347,15 @@ public: /* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a * processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first - * scales a larger picture down to that area with PIL's bicubic. */ + * scales a larger picture down to that area with PIL's bicubic. `mode` picks one of the + * checkpoint's picture modes where it has more than one (Unlimited-OCR). */ int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out, - std::string* why, int64_t max_pixels = 0) const; + std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const; int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; /* From an already-decoded picture or frame list; for tests. */ - int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_from(const Frame& f, std::shared_ptr* out, std::string* why, + const ImageMode& mode = ImageMode{}) const; int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; /* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the @@ -332,6 +372,8 @@ private: int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, std::string* why) const; int image_lfm2(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr* out, + std::string* why) const; /* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */ int32_t tok_thumbnail_ = -1; std::vector tok_tiles_; @@ -388,6 +430,25 @@ void cap_area(const Frame& in, int64_t max_pixels, Frame* out); * aspect, the larger grid of two equally near when the picture fills over half of it. */ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, int32_t* cols, int32_t* rows); +/* Whether the reference's ratio set visits the tall side (c, r), c < r, of a transposed pair after + * the wide one: the only tie two ratios of one tile count can have. From the reference itself. */ +bool uocr_tall_last(int32_t c, int32_t r); +/* Unlimited-OCR's tile grid (its dynamic_preprocess): the min..max-tile grid nearest the picture's + * aspect, the one whose area the picture covers over half of when two are equally near, exactly + * as the reference's set ordering resolves it. The reference calls it only for a picture larger + * than one tile; this answers for any size. */ +void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, + int32_t* cols, int32_t* rows); +/* The placeholders a picture takes: the global view's rows plus its separator, and, when tiled, + * one line of `cols` tiles per feature row with a newline after it. `cols` * `rows` is the tile + * grid. */ +int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows); +/* The mode `mode` resolves to for this deployment; RAD_E_INVAL names an unsupported size. */ +int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size, + int32_t* image_size, std::string* why); +/* PIL's ImageOps.pad: `in` fitted inside w x h keeping its aspect (its bicubic), centred on `fill` + * in the channels' order (127 127 127 for the reference's 0.5 mean). */ +void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out); } /* namespace mm */ } /* namespace rad */ diff --git a/core/rad_core.h b/core/rad_core.h index c552cf73..f41c7454 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -588,6 +588,14 @@ struct SamplingParams { * scheduler thread where every other request's step waits; held here, starting is a lookup. * Null for a request not admitted through the server; the sampler then compiles. */ std::shared_ptr grammar_program; + + /* The windowed no-repeat-ngram ban (core/sample/sampler.h, `sample_ngram_ban`): a token that + * would complete an `ngram_ban_n`-gram already present in the last `ngram_window` tokens of + * the sequence is banned. `ngram_ban_n` 0 is off, the default; `ngram_window` <= 0 searches + * the whole staged history (the un-windowed processor). Unlimited-OCR's generation_config + * asks for 35 and 128 (the model card's document mode uses 1024). */ + int ngram_ban_n = 0; + int ngram_window = 0; }; /* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp index 406e77ab..44f57716 100644 --- a/core/runtime/kvbind.cpp +++ b/core/runtime/kvbind.cpp @@ -32,6 +32,7 @@ void bind_kv_pools(const Program& p, const std::functionkind) { case RAD_KV_FULL: case RAD_KV_WINDOW: + case RAD_KV_RING: b.rank = 4; b.shape[0] = gp->n_blocks; b.shape[1] = d.n_head_kv; diff --git a/core/sample/host_ref.cpp b/core/sample/host_ref.cpp index 153fc873..8726715e 100644 --- a/core/sample/host_ref.cpp +++ b/core/sample/host_ref.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace rad { @@ -526,8 +527,33 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) { return (int32_t)best; } -/* ================================================================== the chain */ +void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n, + int32_t window) { + if (n <= 0 || !history || n_history < (int64_t)n) return; + const int64_t len = n_history; + const int64_t win = (window > 0 && window < len) ? window : len; + const int64_t start = len - win, end = len - n + 1; + if (end <= start) return; + const int64_t plen = (int64_t)n - 1, p0 = len - plen; + /* The set of tokens a continuation would complete an n-gram with, as the reference builds it: + * every n-gram in the window whose first n-1 tokens equal the current prefix contributes the + * token after them. */ + std::unordered_set banned; + for (int64_t idx = start; idx < end; ++idx) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (history[idx + j] != history[p0 + j]) { match = false; break; } + } + if (match) banned.insert(history[idx + plen]); + } + if (banned.empty()) return; + s.sorted = false; /* a -infinity candidate belongs after every finite one */ + for (Candidate& c : s.c) + if (banned.count(c.id) != 0) c.logit = -INFINITY; +} + +/* ================================================================== the chain */ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in, ChainOrder order) { /* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */ @@ -547,6 +573,10 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe in.dry_breakers ? *in.dry_breakers : kNone); } + /* The n-gram ban, after the penalties and before the greedy split: the device chain issues it + * there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */ + host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window); + /* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other * logit to -inf, so a mask applied after it could leave nothing. */ if (sp.greedy()) { diff --git a/core/sample/host_ref.h b/core/sample/host_ref.h index 787309a5..efadee81 100644 --- a/core/sample/host_ref.h +++ b/core/sample/host_ref.h @@ -177,6 +177,14 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history, void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep, uint64_t seed, uint64_t pos); +/* The windowed no-repeat-ngram ban (`sample_ngram_ban`, Unlimited-OCR's + * SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the + * last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0 + * is the whole history. It runs after the penalties and DRY and before every cut, so the greedy + * path sees it too. */ +void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n, + int32_t window); + /* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf * instead of removing the candidate, so nothing downstream is renumbered. `n_words` is * ceil(n_vocab/32). */ @@ -203,7 +211,8 @@ constexpr int64_t kSampleCandidates = 1024; constexpr int64_t kSampleMergeCandidates = 4096; enum class ChainOrder { - Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ + /* penalties, DRY, n-gram ban, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ + Radiance = 0, LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */ }; diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 7a16de8b..4a0065c7 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -178,6 +178,9 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { /* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never * penalised). Resolved on the host, which has the vocabulary. */ buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST); + /* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row + * is the fixed RadSampleParams wire format every sampler op shares. */ + buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST); buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST); buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT); buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT); @@ -197,7 +200,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows, lp_width() * cfg_.world_size, RAD_BUF_PERSIST); - if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || + if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_ || !buf_lp_ || (vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) { RAD_ERR("sampler: a staging buffer failed to declare"); @@ -239,6 +242,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { op_penalties_ = op_vocab_off("sample_penalties"); op_dry_ = op_vocab_off("sample_dry"); + op_ngram_ban_ = op_vocab_off("sample_ngram_ban"); op_temp_ = op_vocab("sample_temp"); op_mask_ = op_vocab("sample_mask"); op_topk_ = op_vocab_off("sample_topk"); @@ -320,6 +324,7 @@ int Sampler::stage_alloc() { greedy_ready_ = false; hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED); brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED); + ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED); mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED); /* Logprobs readback; only rank 0 reads it. */ @@ -337,10 +342,10 @@ int Sampler::stage_alloc() { } if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ || - !mask_stage_) { + !ngram_stage_ || !mask_stage_) { RAD_ERR("sampler: could not pin %s of staging", humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 + - mask_words_ * 4)).c_str()); + mask_words_ * 4 + 8)).c_str()); stage_free(); return RAD_E_NOMEM; } @@ -353,6 +358,7 @@ void Sampler::stage_free() { if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED); if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED); if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED); + if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED); if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED); if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED); if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED); @@ -366,6 +372,7 @@ void Sampler::stage_free() { cur_stage_ = nullptr; hist_stage_ = nullptr; brk_stage_ = nullptr; + ngram_stage_ = nullptr; mask_stage_ = nullptr; } @@ -373,9 +380,9 @@ Sampler::~Sampler() { stage_free(); } /* ================================================================== admission */ -/* Whether the two history stages run, shared by admission, request setup and step staging so - * they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY - * also requires a positive multiplier; a negative one would reward repetition. */ +/* Whether the history stages run, shared by admission, request setup and step staging so they + * agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY also + * requires a positive multiplier; a negative one would reward repetition. */ static bool penalties_on(const SamplingParams& sp) { return sp.penalty_last_n != 0 && (sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f); @@ -385,6 +392,14 @@ static bool dry_on(const SamplingParams& sp) { return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0; } +/* The windowed no-repeat-ngram ban: n-gram length 0 is off (the request default). A window <= 0 + * is legal and means the whole staged history, the un-windowed processor; it is not a separate + * switch, because the reference's windowed form is what the model ships and a ban with no window + * is still a ban. */ +static bool ngram_ban_on(const SamplingParams& sp) { + return sp.ngram_ban_n > 0; +} + int Sampler::check_request(const SamplingParams& sp, std::string* why) const { auto refuse = [&](const char* what, int st) { if (why) *why = what; @@ -418,6 +433,12 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { /* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */ if (dry_on(sp) && sp.dry_allowed_length < 1) return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL); + /* The n-gram ban: an n-gram shorter than 2 is a single-token ban, which the reference defines + * (an empty prefix) and this chain implements, so 1 is accepted. A negative n or window has no + * meaning; window 0 is the whole staged history. */ + if (sp.ngram_ban_n < 0) return refuse("ngram_ban_n is negative", RAD_E_INVAL); + if (sp.ngram_window < 0) + return refuse("ngram_window is negative (0 searches the whole history)", RAD_E_INVAL); if (sp.n_probs > RAD_MAX_LOGPROBS) { if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) + " logprobs alternatives may be asked for"; @@ -457,6 +478,7 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_, "sample_temp (over the candidates, for temperature last)"); if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry"); + if (!missing) missing = need(ngram_ban_on(sp), op_ngram_ban_, "sample_ngram_ban"); if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_, "sample_mask"); if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties"); @@ -581,6 +603,7 @@ int Sampler::build_step(const std::vector& reqs) { n_seq_ = 0; any_brk_ = false; any_late_ = false; + any_ngram_ = false; cur_stage_ = params_stage_; lp_rows_.clear(); @@ -635,6 +658,7 @@ int Sampler::build_step(const std::vector& reqs) { const int64_t n_total = n_prompt + n_out; const bool pen = penalties_on(sp); const bool dry = dry_on(sp); + const bool ngram = ngram_ban_on(sp); auto it = seqs_.find(r->id); SeqState* st = it == seqs_.end() ? nullptr : &it->second; @@ -695,6 +719,11 @@ int Sampler::build_step(const std::vector& reqs) { p.dry_penalty_last_n = sp.dry_penalty_last_n; p.mask_row = -1; + /* The n-gram ban's pair, staged for every row so a row that turns it off cannot inherit + * its predecessor's values. */ + ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n; + ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window; + /* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax * writes a column of this rank's shard, not a token id. Top-k plus the merge produce * global ids, and the pick over one candidate is deterministic. A greedy row asking @@ -723,12 +752,14 @@ int Sampler::build_step(const std::vector& reqs) { any_late_ = true; } - /* History for the penalties and DRY, staged only for rows that run one of them: - * prompt, output so far and, at draft position k, the k drafts before it (they are - * emitted only if accepted, as one token at a time). Oldest first, truncated to + /* History for the penalties, DRY and the n-gram ban, staged only for rows that run one + * of them: prompt, output so far and, at draft position k, the k drafts before it (they + * are emitted only if accepted, as one token at a time). Oldest first, truncated to * max_hist; penalty_last_n still decides how much counts. Each row owns its row of the - * plane, so hist_off stays 0. */ - if (pen || dry) { + * plane, so hist_off stays 0. The n-gram ban's own window is `ngram_window`, applied to + * this span, so the reference's update order holds at a verify: position k sees the + * drafts before it, as the processor would after emitting them. */ + if (pen || dry || ngram) { const int64_t len = n_total + k; const int64_t take = std::min(len, cfg_.max_hist); int32_t* h = hist_stage_ + row * cfg_.max_hist; @@ -741,6 +772,9 @@ int Sampler::build_step(const std::vector& reqs) { p.hist_len = (int32_t)take; if (pen) p.flags |= RAD_SP_PENALTY; if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY; + /* A row whose history is shorter than its n-gram has nothing to ban (the reference + * skips it too), so the op is issued only when some row has a full n-gram. */ + if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true; } if (gr && !dead && gr->constrains()) { @@ -881,7 +915,12 @@ int Sampler::build_greedy(int64_t n) { n_seq_ = n; any_brk_ = false; any_late_ = false; + any_ngram_ = false; cur_stage_ = greedy_stage_; + /* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from + * the staging, and a stale pair from an earlier request's build must not issue the ban over + * history that was not staged this step. */ + std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t)); if (greedy_ready_) return RAD_OK; for (int64_t i = 0; i < cap; ++i) { DeviceSampleParams& p = greedy_stage_[i]; @@ -904,7 +943,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { const RadStream s = rad_stream(c); bool any_mask = false, any_greedy = false, any_chain = false; - bool any_penalty = false, any_dry = false, any_xtc = false; + bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false; bool any_topp = false, any_minp = false, any_typ = false; for (int64_t i = 0; i < n_seq_; ++i) { const DeviceSampleParams& p = cur_stage_[i]; @@ -912,6 +951,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { any_penalty |= (p.flags & RAD_SP_PENALTY) != 0; any_dry |= (p.flags & RAD_SP_DRY) != 0; any_xtc |= (p.flags & RAD_SP_XTC) != 0; + any_ngram |= ngram_stage_[2 * i] > 0; if (p.flags & RAD_SP_GREEDY) any_greedy = true; else { any_chain = true; @@ -939,13 +979,16 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (late) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_, n_seq_ * (int64_t)sizeof(DeviceSampleParams), s)); - if (any_penalty || any_dry) + if (any_penalty || any_dry || any_ngram) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_, n_seq_ * cfg_.max_hist * 4, s)); const bool pass_brk = any_dry && any_brk_; if (pass_brk) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_, n_seq_ * cfg_.max_hist, s)); + if (any_ngram) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_, + n_seq_ * 2 * (int64_t)sizeof(int32_t), s)); if (any_mask) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_, n_seq_ * mask_words_ * 4, s)); @@ -954,6 +997,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { const RadOperand o_params = opd_rows(buf_params_, n_seq_); const RadOperand o_hist = opd_rows(buf_hist_, n_seq_); const RadOperand o_brk = opd_rows(buf_brk_, n_seq_); + const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_); const RadOperand o_mask = opd_rows(buf_mask_, n_seq_); const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_); const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_); @@ -981,6 +1025,13 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (any_dry) RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() })); + /* The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor), + * after the penalties and before every cut: a banned logit is -infinity for the greedy argmax + * below as well as for the chain, which is the reference processor's effect on the + * distribution. Off (the default) the op is not issued at all, so a request without it + * samples exactly as before. */ + if (any_ngram) RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram })); + /* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax * and the chain run over the whole batch: the argmax writes every row, then the candidate * stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 87c1c65a..9adc4335 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -9,6 +9,7 @@ * Chain order (reordering changes which tokens survive): * * penalties (repetition / frequency / presence, then DRY) + * the windowed no-repeat-ngram ban * temperature * the grammar mask * top-k @@ -47,6 +48,8 @@ * sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout) * sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers? * -> logits (inout) + * sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram + * -> logits (inout) * sample_temp M(range) n_vocab logits, params -> logits (inout) * sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout) * sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val, @@ -232,6 +235,9 @@ private: /* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */ rad_op op_penalties_ = RAD_NULL_HANDLE; rad_op op_dry_ = RAD_NULL_HANDLE; + /* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's + * generation_config asks for. It reads the same history plane as the two above. */ + rad_op op_ngram_ban_ = RAD_NULL_HANDLE; rad_op op_temp_ = RAD_NULL_HANDLE; rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */ rad_op op_mask_ = RAD_NULL_HANDLE; @@ -252,6 +258,7 @@ private: rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */ rad_buf buf_hist_ = RAD_NULL_HANDLE; rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */ + rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */ rad_buf buf_mask_ = RAD_NULL_HANDLE; rad_buf buf_cand_i_ = RAD_NULL_HANDLE; rad_buf buf_cand_v_ = RAD_NULL_HANDLE; @@ -275,6 +282,7 @@ private: const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */ int32_t* hist_stage_ = nullptr; uint8_t* brk_stage_ = nullptr; + int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */ uint32_t* mask_stage_ = nullptr; int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */ @@ -282,6 +290,9 @@ private: /* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and * passed to sample_dry. */ bool any_brk_ = false; + /* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use, + * so this only decides whether that plane is uploaded and the op issued. */ + bool any_ngram_ = false; /* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used * only when the head is sharded; see declare(). */ diff --git a/core/sched/advance.h b/core/sched/advance.h index ec6dc705..b6e4a3f6 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -57,6 +57,16 @@ struct AdvGroup { int64_t used_off; /* [n_seq] seqused */ int64_t bt_off; /* [n_seq][pitch] block table */ int64_t first_off; /* [n_seq] the position each row's block table starts at */ + /* The runtime window (KVManager::set_window / SeqWindow), so the card computes the same + * `used` and slots the host builder staged: a ring sequence keeps its reference and rewrites + * a fixed ring of blocks, so its held span stops at its own table and a position past its + * ring_pos maps modulo ring_blocks. Without it (ring 0) the advance is the linear mapping, as + * before. ring_pos and the table length are per sequence (each prompt has its own floor and + * table), ring_blocks is the same for the group (one W). */ + int32_t ring; /* 1: the group carries runtime windows */ + int32_t ring_blocks; /* whole blocks the ring holds */ + int64_t rpos_off; /* [n_seq] the sequence's block-aligned first ring position, 0 if none */ + int64_t tlen_off; /* [n_seq] the sequence's block-table length in blocks, 0 if none */ }; /* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index df289759..a90be20c 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -30,21 +30,44 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) { /* Every group's slots for the row's `n` positions (from the positions just written) and its * length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes - * tables for the furthest reachable position, so only a row whose output is unused hits this. */ + * tables for the furthest reachable position, so only a row whose output is unused hits this. + * + * A runtime window (e.ring, KVManager::set_window) must be computed exactly as the host builder + * staged it (BatchBuilder::build_groups), because this runs after the build and overwrites what it + * wrote: + * - `used` stops at the table: the ring reuses its blocks, so the sequence's held span is the + * table's, not the context's. Without this the decode walks bt[(used-1)/block] past the end, + * reads the -1 padding the builder fills and faults the card on a negative block (the P4a + * regression); + * - a position at or past ring_pos lives in the ring, at block + * ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs + * off the table once the ring wraps. */ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) { const AdvGroup* G = reinterpret_cast(a.slab + a.grp_off); const int32_t* pos = adv_i32(a, a.pos_off); for (int g = 0; g < a.n_groups; ++g) { const AdvGroup& e = G[g]; const int32_t first = adv_i32(a, e.first_off)[i]; - adv_i32(a, e.used_off)[i] = base + n - first; + /* Per sequence: each prompt has its own floor and its own table (advance.h). */ + const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0; + const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0; + const bool ring = e.ring && tlen > 0; + int64_t used = (int64_t)base + n - first; + if (ring) { + const int64_t span = (int64_t)tlen * e.block_size; + if (used > span) used = span; + } + adv_i32(a, e.used_off)[i] = (int32_t)used; if (!e.paged) continue; const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch; int32_t* slot = adv_i32(a, e.slot_off); for (int32_t j = 0; j < n; ++j) { const int32_t p = pos[k + j]; - const int32_t bi = (p - first) / e.block_size; - slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0) + int32_t bi = (p - first) / e.block_size; + if (ring && p >= rpos && e.ring_blocks > 0) + bi = rpos / e.block_size + + ((p - rpos) / e.block_size) % e.ring_blocks; + slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0) ? bt[bi] * e.block_size + p % e.block_size : -1; } } diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 6cd9ac0a..d8983342 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -112,6 +112,9 @@ void BatchBuilder::carve(Set& s, char* h) { pair(&s.h_dout, &s.d_dout, S); pair(&s.h_rows, &s.d_rows, 4 * S); pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size()); + /* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */ + pair(&s.h_rpos, &s.d_rpos, S); + pair(&s.h_tlen, &s.d_tlen, S); s.h_grp = ::rad::carve(h, oh, (int64_t)s.groups.size()); s.d_grp = ::rad::carve(d, od, (int64_t)s.groups.size()); for (size_t gi = 0; gi < s.groups.size(); ++gi) { @@ -690,13 +693,24 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& const StepEntry& e = plan.e[(size_t)i]; int64_t first = 0; + SeqWindow win; + bool has_win = false; + int64_t bt_len = 0; /* the sequence's block table, in blocks */ + int64_t table_end = 0; /* the table's last position, for a runtime window's used */ if (L.paged) { /* The manager's block table, by sequence id; Request::blocks is not the source * of truth (see IKVManager). */ const std::vector& bt = kv.block_table(e.seq, (int32_t)gi); first = kv.first_block_pos(e.seq, (int32_t)gi); - for (int32_t j = 0; j < e.n_tokens; ++j) - g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j); + has_win = kv.runtime_window(e.seq, (int32_t)gi, &win); + bt_len = (int64_t)bt.size(); + table_end = bt_len * L.block_size; + for (int32_t j = 0; j < e.n_tokens; ++j) { + const int64_t pos = (int64_t)e.ctx_len + j; + g.h_slot[t + j] = has_win + ? kvgeom_.slot_ring((int)gi, bt, first, pos, win) + : kvgeom_.slot((int)gi, bt, first, pos); + } /* Restage relative to what the card holds (BtMirror). The same sequence in the * same row keeps entries below the first changed one and below the end of both * old and new tables, so a decode step stages nothing or one appended block. A @@ -737,6 +751,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s.h_convslot[(int64_t)gi * max_seqs_ + i] = st; } s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first; + /* The advance recomputes this row's used and slots after the build (advance_impl.h), + * so it needs the same per-sequence ring data this build staged: the row's floor and + * its table's length, 0 when the sequence has no runtime window. */ + s.h_rpos[i] = has_win ? (int32_t)win.ring_pos : 0; + s.h_tlen[i] = has_win ? (int32_t)bt_len : 0; t += e.n_tokens; /* Tokens the sequence holds in this table, not min(length, window). `seqused` counts @@ -745,8 +764,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& * unwritten slots at the end of the table, read as the newest context; a non-causal * window group would attend to them. Do not clamp to `window` either: the held span * may exceed it by under a block, and clamping would drop the newest tokens. Attending - * a few extra old positions is the cost of paging a window (vLLM does the same). */ + * a few extra old positions is the cost of paging a window (vLLM does the same). + * + * A runtime window (R-SWA) has reused its ring's slots once the sequence is past the + * ring's span, so the held span is the table's, not the context's: every slot of the + * reference and of the ring holds live KV, and the ring's blocks are what a non-causal + * decode reads. Before the ring is full the shorter of the two is the written count. */ int64_t used = (int64_t)e.ctx_len + e.n_tokens - first; + if (has_win) { + used = std::min(used, table_end); + } if (used < 0) used = 0; g.h_used[i] = (int32_t)used; if (L.paged) { @@ -773,6 +800,23 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& a.used_off = (const char*)g.d_used - d0; a.bt_off = (const char*)g.d_bt - d0; a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0; + /* The runtime window (KVManager::set_window): the advance runs after this build and + * overwrites `used` and the slots, so it must reproduce the ring's mapping rather + * than the linear one (advance_impl.h). The floor and table length are per sequence + * (s.h_rpos / s.h_tlen), the ring's block count is the group's W. */ + a.ring = 0; + a.ring_blocks = 0; + a.rpos_off = (const char*)s.d_rpos - d0; + a.tlen_off = (const char*)s.d_tlen - d0; + for (int64_t i = 0; i < n_seq; ++i) { + const StepEntry& e = plan.e[(size_t)i]; + SeqWindow w; + if (kv.runtime_window(e.seq, (int32_t)gi, &w)) { + a.ring = 1; + a.ring_blocks = (int32_t)w.ring_blocks; + break; + } + } } for (size_t r = 0; r < ranks_.size(); ++r) { diff --git a/core/sched/batch.h b/core/sched/batch.h index c8142275..2863aab3 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -199,6 +199,11 @@ private: int32_t *h_rows = nullptr, *d_rows = nullptr; int32_t *h_first = nullptr, *d_first = nullptr; AdvGroup *h_grp = nullptr, *d_grp = nullptr; + /* [max_seqs] per-sequence runtime-window data for the advance: the block-aligned first + * ring position and the block table's length in blocks, 0 when the sequence has no + * runtime window (advance.h). Per sequence because each prompt has its own floor. */ + int32_t *h_rpos = nullptr, *d_rpos = nullptr; + int32_t *h_tlen = nullptr, *d_tlen = nullptr; char* h_derived = nullptr; /* derivation staging, byte-addressed */ /* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos, diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index e4a4b472..94916bc4 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * served by a different kernel may differ (§7.2). */ bool has_linear = false, has_window = false; for (const KVGroupInfo& kg : prog.kv_groups) { - if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) { + if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW || + kg.decl.kind == RAD_KV_RING) { if (kg.block_size > 0) { g.attn_block = lcm64(g.attn_block, kg.block_size); note(g.why, "attn_block", kg.block_size, kg.name.c_str()); /* A drafter's window is recomputed by draft refill; only the trunk's needs a - * snapshot for a prefix hit to resume. */ + * snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all + * (KVManager::declare_runtime_window): its window is each sequence's own prompt + * length, which no slot could describe, so it is sized for the context plus a ring + * and is never checkpointed. */ if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter) has_window = true; } diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index caaa16be..82d2e11f 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -44,6 +44,24 @@ struct IKVManager { /* After a committed step, a window group frees what no later query can read * (KVManager::trim_window). */ virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; } + /* R-SWA (KVManager::declare_runtime_window): the W this group arms a sequence with, 0 when it + * carries no runtime windows. The scheduler arms every sequence it admits with + * set_window(seq, prompt length, W); a manager with no runtime window refuses it and the + * scheduler never asks. */ + virtual int64_t runtime_window_tokens(int32_t group) const { (void)group; return 0; } + virtual int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens) { + (void)seq; (void)visible_lo; (void)window_tokens; + return RAD_E_UNSUPPORTED; + } + /* The sequence's runtime window in `group`, if it has one (KVManager::runtime_window). A + * sequence with one is excluded from prefix publish, checkpoint snapshots and speculation: + * the window is runtime data and the ring rewrites its slots in place. */ + virtual bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const { + (void)seq; (void)group; (void)out; + return false; + } + + virtual bool has_runtime_window(uint64_t seq) const { (void)seq; return false; } /* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The * defaults mean no hit on a windowed trunk is ever resumed. */ virtual bool has_window_snapshot() const { return false; } @@ -95,7 +113,11 @@ struct IKVManager { /* Absolute token position that block_table(seq, group)[0] covers: zero for a full group, * non-zero for a window group once blocks below the window are recycled. The step batch maps - * a slot as `(pos - first_block_pos) / block_size`. */ + * a slot as `(pos - first_block_pos) / block_size`. + * + * A sequence with a runtime window (runtime_window) keeps first_block_pos 0 even once the ring + * recycles: its table is [reference][ring] from position 0 and the ring's positions map + * modulo ring_blocks (SeqWindow), so only the slot index recycles, never the table. */ virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0; /* Index of the first entry of block_table(seq, group) changed since the previous call; @@ -213,7 +235,7 @@ struct KVGeom { for (const KVGroupInfo& gi : groups) { G e; e.kind = gi.decl.kind; - e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW); + e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW || e.kind == RAD_KV_RING); e.block_size = gi.block_size > 0 ? gi.block_size : 1; e.window = gi.decl.window; k.g.push_back(e); @@ -229,6 +251,23 @@ struct KVGeom { if (bi < 0 || bi >= (int64_t)bt.size()) return -1; return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size)); } + + /* The same slot for a runtime window (SeqWindow): the reference maps linearly (first_pos is + * 0 there), and a position at or past the ring's start lives in block + * ring_pos/block + ((pos - ring_pos)/block) % ring_blocks, which is what rewrites the ring's + * slots in place. ring_pos is block-aligned, so `pos % block` stays the in-block offset. */ + int32_t slot_ring(int gi, const std::vector& bt, int64_t first_pos, int64_t pos, + const SeqWindow& w) const { + const G& e = g[(size_t)gi]; + int64_t bi; + if (w.set && pos >= w.ring_pos) { + bi = w.ring_pos / e.block_size + ((pos - w.ring_pos) / e.block_size) % w.ring_blocks; + } else { + bi = (pos - first_pos) / e.block_size; + } + if (bi < 0 || bi >= (int64_t)bt.size()) return -1; + return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size)); + } }; /* ------------------------------------------------------------------ binding the concrete classes */ @@ -244,6 +283,12 @@ struct KVBinding final : IKVManager { int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); } int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); } void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); } + int64_t runtime_window_tokens(int32_t g) const override { return m->runtime_window_tokens(g); } + int set_window(uint64_t s, int64_t lo, int64_t w) override { return m->set_window(s, lo, w); } + bool runtime_window(uint64_t s, int32_t g, SeqWindow* o) const override { + return m->runtime_window(s, g, o); + } + bool has_runtime_window(uint64_t s) const override { return m->has_runtime_window(s); } bool has_window_snapshot() const override { return m->has_window_snapshot(); } int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); } int adopt(uint64_t s, int32_t g, const std::vector& b, int64_t n) override { diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index b2fac3e8..fd2b4b0e 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -70,6 +70,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac has_linear_state_ = false; for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true; + /* R-SWA: which groups carry runtime per-sequence windows, and the W they arm a sequence + * with. Empty unless the engine declared one (KVManager::declare_runtime_window), so a model + * with a fixed window (gemma4) takes none of the runtime-window paths. */ + rswa_windows_.clear(); + for (size_t i = 1; i < kvgeom_.g.size(); ++i) { + const int64_t w = kv->runtime_window_tokens((int32_t)i); + if (w > 0) rswa_windows_.push_back({(int32_t)i, w}); + } + if (!rswa_windows_.empty()) + RAD_INFO("R-SWA: %zu KV group(s) with a runtime window; a sequence keeps its prompt as the " + "reference and decodes into a ring of %lld token(s) after it, and is excluded from " + "the prefix cache, checkpoints and speculation", + rswa_windows_.size(), (long long)rswa_windows_[0].tokens); + /* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached * (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is * true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */ @@ -407,7 +421,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool * and failed requests are published too; their prompts were computed, and a client that hangs * up mid-answer is likely to ask for that prefix again. */ if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) && - s.req->n_computed > 0) { + s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) { + /* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its + * table is a reference plus a ring rather than a prefix from position 0, and the window + * length is runtime data that no cache key carries; a hit would adopt blocks for a window + * this sequence does not have. prefix.cpp already skips a windowed group -- this makes the + * policy explicit, rather than a consequence of the kind declared at build time. */ const std::vector& cg = pc_->cached_groups(); pub_blocks_.assign(cg.size(), {}); bool ok = !cg.empty(); @@ -466,6 +485,11 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool * refusal leaves the entry without one. */ void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) { int32_t cs = -1; + /* R-SWA: a sequence with a runtime window is never checkpointed. The window is runtime data + * (the prompt's own length), so a slot would describe a window the sequence does not have, and + * the ring is not the [lo, pos) block list a restore seeds. The prefix cache can never reuse + * it either, so the copy would be dead weight. */ + if (kv_->has_runtime_window(r.id)) return; if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return; e.ckpt_tok = tok; e.ckpt_slot = cs; @@ -918,6 +942,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id)); + /* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The + * floor is this sequence's own prompt length (image tokens included, they are prompt rows), + * and it is armed here rather than at the prefill's end so no checkpoint is reserved for the + * sequence: a snapshot would describe a window the sequence no longer has (set_window). */ + for (const RswaWindow& w : rswa_windows_) { + const int rc = kv_->set_window(r.id, (int64_t)r.prompt.size(), w.tokens); + if (rc < 0) { + RAD_WARN("request %llu: runtime window of %lld tokens over a %zu-token prompt: %s", + (unsigned long long)r.id, (long long)w.tokens, r.prompt.size(), + rad_strerror(rc)); + return rc; + } + } + /* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier * attempt's hit (n_computed > 0) keeps what it found. */ if (r.n_computed == 0) { diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 06aa8711..7c3d692f 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -420,6 +420,13 @@ private: * meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index? * Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */ bool hit_holes_trunk_ = false; + /* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a + * sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does + * not declare one, in which case admission and commit are exactly as before. A sequence with + * one keeps its prompt as a reference and decodes into a ring after it; it is excluded from + * prefix publish, checkpoints and speculation (the window is runtime data). */ + struct RswaWindow { int32_t group = -1; int64_t tokens = 0; }; + std::vector rswa_windows_; /* Draft refill: the drafter's window where a hit can leave a hole in a windowed block * drafter's cache, else 0. The drafter would be declined until its window slid past the hole, * which on a chat's follow-up turn is most of the reply, so the hit ends one window before the diff --git a/core/server/adapters.h b/core/server/adapters.h index 6da4c418..a1ff5c5a 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -706,10 +706,13 @@ public: std::shared_ptr* out, std::string* why) override { if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; } if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why); - return k == MediaKind::Image - ? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why, - opts.max_pixels) - : p_->video(bytes.data(), bytes.size(), out, why); + if (k == MediaKind::Video) return p_->video(bytes.data(), bytes.size(), out, why); + mm::ImageMode mode; + 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); } int32_t audio_rate() const override { diff --git a/core/server/iface.h b/core/server/iface.h index e492463a..598456b5 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -524,6 +524,12 @@ struct MediaOpts { /* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides * truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */ int64_t max_pixels = 0; + /* Which of the checkpoint's picture modes, for one that has two (Unlimited-OCR): 0 is the + * server's choice (mm::ImageMode::Default), 1 gundam, 2 base. A request that carries + * several pictures chooses base unless it says otherwise. */ + int32_t image_mode = 0; + /* The mode's sizes, when the request states them; 0 keeps the mode's own. */ + int32_t image_base_size = 0, image_size = 0; }; class IMultimodal { diff --git a/core/server/oai.cpp b/core/server/oai.cpp index 85477067..f2d6036c 100644 --- a/core/server/oai.cpp +++ b/core/server/oai.cpp @@ -240,6 +240,7 @@ const char* kAcceptedCommon[] = { "dry_sequence_breakers", "samplers", "grammar", "json_schema", "priority", "logprobs", "ignore_eos", "timings_per_token", "return_progress", "session_id", "n_probs", + "ngram_ban_n", "ngram_window", }; const char* kAcceptedChat[] = { @@ -249,6 +250,8 @@ const char* kAcceptedChat[] = { "thinking_token_budget", "thinking_budget", "thinking_budget_tokens", "reasoning_budget_tokens", "reasoning_format", "continue_final_message", "functions", "function_call", + /* Unlimited-OCR's picture modes: which of the checkpoint's two a request's pictures get. */ + "images_config", }; /* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the @@ -891,6 +894,64 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap auto sid = b.find("session_id"); if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get()); + /* The windowed no-repeat-ngram ban (core/sample/sampler.h): `ngram_ban_n` is the banned + * n-gram's length and `ngram_window` how far back it looks; the checkpoint's own generation + * config asks for 35 and 128 (Unlimited-OCR). The reference spells them + * no_repeat_ngram_size and no_repeat_ngram_window_size; both are taken. */ + i64 = r->sp.ngram_ban_n; + if (!get_any(b, { "ngram_ban_n", "no_repeat_ngram_size" }, &i64, nullptr, err)) + return RAD_E_INVAL; + if (i64 < 0 || i64 > 256) { + *err = err_bad("ngram_ban_n", "must be in [0, 256]"); + return RAD_E_INVAL; + } + r->sp.ngram_ban_n = (int)i64; + i64 = r->sp.ngram_window; + if (!get_any(b, { "ngram_window", "no_repeat_ngram_window_size" }, &i64, nullptr, err)) + return RAD_E_INVAL; + if (i64 > 131072) { + *err = err_bad("ngram_window", "must be at most 131072 tokens of history; 0 or less " + "searches the whole sequence"); + return RAD_E_INVAL; + } + r->sp.ngram_window = (int)i64; + + /* `images_config`: Unlimited-OCR's two picture modes. A string names one ("gundam" for a + * single picture -- the global view plus crops --, "base" for a page of a multi-page + * document); an object carries the reference runner's own dict. */ + auto ic = b.find("images_config"); + if (ic != b.end() && !ic->is_null()) { + if (ic->is_string()) { + const std::string m = ic->get(); + if (m == "gundam") r->image_mode = 1; + else if (m == "base") r->image_mode = 2; + else if (!m.empty()) { + *err = err_bad("images_config", "expected \"gundam\" or \"base\", got \"" + m + + "\""); + return RAD_E_INVAL; + } + } else if (ic->is_object()) { + const json& o = *ic; + int64_t bs = 0, is = 0; + if (!get_int(o, "base_size", &bs, err)) return RAD_E_INVAL; + if (!get_int(o, "image_size", &is, err)) return RAD_E_INVAL; + bool crop = true; + if (!get_bool(o, "crop_mode", &crop, err)) return RAD_E_INVAL; + if (bs < 0 || bs > 65536 || is < 0 || is > 65536) { + *err = err_bad("images_config", "base_size and image_size must be in [0, 65536]"); + return RAD_E_INVAL; + } + r->image_mode = crop ? 1 : 2; + r->image_base_size = (int32_t)bs; + r->image_size = (int32_t)is; + } else { + *err = err_bad("images_config", + "expected \"gundam\", \"base\", or an object with base_size, " + "image_size and crop_mode"); + return RAD_E_INVAL; + } + } + RAD_TRY(apply_sampler_order(b, &r->sp, err)); auto so = b.find("stream_options"); @@ -1472,6 +1533,16 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d, out->text = rendered; auto pm = std::make_shared(); const std::string marker = RAD_MEDIA_MARKER; + /* The checkpoint's mode for a picture no request named: a request that carries several + * pictures is a multi-page document, which the reference processes page by page without + * crops (infer_multi); one picture is the page-with-crops mode (infer). */ + size_t n_images = 0; + for (const auto& m : media) n_images += m.first == MediaKind::Image ? 1 : 0; + auto opts_for = [&](MediaKind k) { + MediaOpts mo = opts; + if (k == MediaKind::Image && mo.image_mode == 0 && n_images > 1) mo.image_mode = 2; + return mo; + }; size_t pos = 0, mi = 0; for (;;) { size_t at = rendered.find(marker, pos); @@ -1491,7 +1562,8 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d, } std::shared_ptr item; std::string why; - const int s = d.mm->prepare(media[mi].first, media[mi].second, opts, &item, &why); + const int s = d.mm->prepare(media[mi].first, media[mi].second, opts_for(media[mi].first), + &item, &why); if (s < 0 || !item) { *err = err_bad("messages[].content[]", "the media could not be used: " + (why.empty() ? std::string(rad_strerror(s)) @@ -2058,7 +2130,25 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true); p.text = rendered; } else { - RAD_TRY(tokenize_with_media(rendered, d, media, MediaOpts{}, &p, err)); + MediaOpts mo; + mo.image_mode = out->image_mode; + mo.image_base_size = out->image_base_size; + mo.image_size = out->image_size; + RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, err)); + } + /* Not every template renders BOS: this checkpoint's is a bare concatenation of the parts, while + * its tokenizer states `add_bos_token: true` (and the reference's own `infer` prepends id 0). + * Add it only when the rendered prompt does not already start with it, so a template that does + * render it is untouched. A media run's placeholders shift by one with it. */ + { + const ITokenizer::VocabInfo vi = d.tok->vocab_info(); + if (vi.add_bos && vi.bos >= 0 && (p.tokens.empty() || p.tokens.front() != vi.bos)) { + p.tokens.insert(p.tokens.begin(), vi.bos); + if (p.media) { + for (auto& pl : p.media->items) pl.tok += 1; + p.media->layout(); + } + } } if (p.tokens.empty()) { *err = err_bad("messages", "the rendered prompt tokenised to nothing"); diff --git a/core/server/oai.h b/core/server/oai.h index ffbf5538..6bfd7d1b 100644 --- a/core/server/oai.h +++ b/core/server/oai.h @@ -158,6 +158,11 @@ struct OaiRequest { /* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */ int32_t image_tokens = 0; + /* `images_config`: which of the checkpoint's picture modes a request's pictures get, and the + * sizes it states (Unlimited-OCR's gundam and base modes). 0 keeps the server's choice: base + * for a request with several pictures, gundam otherwise. */ + int32_t image_mode = 0, image_base_size = 0, image_size = 0; + int n_choices() const { return (int)prompts.size() * n; } }; diff --git a/data/recipes/unlimited-ocr-bf16.recipe b/data/recipes/unlimited-ocr-bf16.recipe index 79ceec7a..68954e4e 100644 --- a/data/recipes/unlimited-ocr-bf16.recipe +++ b/data/recipes/unlimited-ocr-bf16.recipe @@ -8,10 +8,17 @@ # (arch/unlimitedocr_bf16) probes the first routed expert, reads the plain encoding and serves the # experts through the bf16 grouped GEMM. The checkpoint carries no quantization_config. # -# The container this writes is the P0/P1 decoder only: the plugin's name map covers the 12-layer -# Llama-MoE trunk and its tied head, and the DeepEncoder vision tensors are left out until the P2 -# tower is declared (aijuus/plans/UNLIMITED-OCR-PLUGIN.md). Reconvert with the same recipe then. +# The container carries the whole checkpoint the plugin's name map covers: the 12-layer Llama-MoE +# trunk and its tied head, and the DeepEncoder vision tower (sam_model.*, vision_model.*, +# projector.layers.*, image_newline, view_seperator) at the checkpoint's bf16. +# +# Two shapes the map re-reads as GEMM weights: SAM's patch_embed.proj.weight [768, 3, 16, 16] as +# [768, 768] (one bf16 plane reshaped), and the bias-free 3x3 convolutions (neck.2, net_2, net_3) +# as [cout, cin*9], which conv2d_unfold + gemm_nt consume. Everything else is copied unchanged. # # Quantisation follow-ups (after P5) get their own recipes: the 64-expert MoE is the qwen4exp # w4/w4nl64 tier's shape (moe_intermediate_size 896 = 7 x 128 scale groups, n_embd 1280 = 10 x 128 # -- whole scale blocks both ways), with the tied 331 MB head and the vision tower kept bf16. + +# Nothing here is quantised: a recipe's rules are PATTERN QUANTISER pairs, and a weight no rule +# matches keeps the checkpoint's own encoding (bf16 for every tensor here). diff --git a/docs/GUIDE.md b/docs/GUIDE.md index cad2fee6..f0c16c65 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1217,6 +1217,17 @@ Of sources 2 to 4, the first that states anything is used whole. radiance --model m.rad --temp 0.7 --top-p 0.8 --top-k 20 ``` +**The windowed no-repeat-n-gram ban** (`no_repeat_ngram_size` / +`no_repeat_ngram_window_size` in a `generation_config.json`, the same names under +`generation.*` in the container; `ngram_ban_n` / `ngram_window` in a request) comes from the same +four sources; there is no command-line flag. A negative window is the reference's "the whole +sequence", which this sampler spells 0. Unlimited-OCR's checkpoint states 35 over the last 128, +so that is what a request sending neither field gets: + +```json +{"messages": [...], "ngram_ban_n": 35, "ngram_window": 128} +``` + **The rest of the sampler** has a flag per field, spelled like the request field: `--presence-penalty`, `--frequency-penalty`, `--repetition-penalty`, `--repeat-last-n`, `--typical-p`, `--dry-multiplier`, `--dry-base`, `--dry-allowed-length`, `--dry-penalty-last-n`, diff --git a/docs/OPS.md b/docs/OPS.md index 94348275..512bc12f 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -775,6 +775,7 @@ bytes). | `attn_cross` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `cu_seqlens`, `cu_k` → `out` | | `attn_na3d` | `M`(range) `head_dim` `kt` `kh` `kw` `dtype` `scale`:f64/opt | `q`, `k`, `v`, `geom` → `out` | | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | +| `sam_attn` | `M`(range) `head_dim` `n_head` `grid_h` `grid_w` `window` `scale`:f64 `dtype` | `q`, `k`, `v`, `cu_seqlens`, `out`, `rel_pos_h`w, `rel_pos_w`w | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | @@ -831,6 +832,22 @@ softmax over the visible keys and the weighted sum of `v`, all in f32 and rounde reference computes this in 12-query blocks over 24-key windows with a Transformer-XL shift, giving every key outside the window a `-1e9` logit, so the sliding form is the same function. +**`sam_attn`** is Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention: windowed, with *decomposed* +relative position. Each `cu_seqlens` segment is `grid_h * grid_w` rows in raster grid order (row +`i_h * grid_w + i_w`). With `window > 0` the grid is padded to multiples of `window` with ZERO rows +(deepencoder's `window_partition`, applied after `norm1`), cut into `window x window` tiles and each +tile attends to all of its rows -- the pad rows are keys and values, so their logits (which carry the +relative-position terms even though their `q` and `k` are zero) take part in the softmax and their +`v` contributes nothing. `window` 0 is one tile over the whole segment (the global-attention layers). +The logits are `scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w]`, each dot over the head's whole +`head_dim`, with `i_h - j_h + L - 1` indexing `rel_pos_h` and `i_w - j_w + L - 1` indexing +`rel_pos_w` (`L` the window, or the grid axis for a global layer); softmax in f32 with the max +subtracted over the tile's keys, `out = sum p * v`, written back in segment row order with the pad +rows dropped. The tables are `[2*L - 1, head_dim]` where `L = window`, or `max(grid_h, grid_w)` for +a global layer; a geometry whose axes need a longer table has it resampled along dim 0 by +`get_rel_pos`'s linear interpolation. `q`, `k` and `v` are the three column slices of one fused +projection, so each may be a strided view of a `[M, 3 * n_head * head_dim]` buffer. + **`rope`'s multi-component modes.** `mrope`, `imrope` and `axial` rotate with NeoX pairing and let several position components drive different frequencies. `positions` is then `[C, M]`, component-major, and `sections` names how many of the `rotary_dim / 2` frequencies each component @@ -2365,10 +2382,18 @@ the usual rescale, pairs by value). | op | params | operands | |---|---|---| | `sample_dry` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `breakers`? | +| `sample_ngram_ban` | `M` `n_vocab` `vocab_off`/opt | `logits`:inout, `params`, `history`, `ngram` | | `sample_typical` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | | `sample_xtc` | `M` `n_cand` | `cand_idx`:inout, `cand_val`:inout, `params` | | `sample_chain` | `M` `n_vocab` `temp`:f64/opt `p`:f64/opt `min_p`:f64/opt `k`/opt | `logits`, `query`?, `u` → `draw` | +`sample_ngram_ban` is the windowed no-repeat-ngram ban (Unlimited-OCR's +`SlidingWindowNoRepeatNgramProcessor`): every token that would complete an n-gram the last `window` +tokens of the row's history already contain is set to -infinity. `ngram` is one i32 +`{n-gram length, window}` pair a row; the window bounds the n-gram's START index, so one that spans +the window boundary is still searched. `window` <= 0 searches the whole staged history (the +un-windowed processor) and `n` 0 turns the stage off, which is the default. + `sample_dry` is llama.cpp's DRY: it penalises, once, each token that would extend a repeated suffix of the history, by its longest such repeat. Sequence breakers are strings, so they are resolved against the vocabulary on the host: the row's `dry_rep_limit` carries the repeat limit the most diff --git a/libavx/CMakeLists.txt b/libavx/CMakeLists.txt index 3da5c89b..7fa41a55 100644 --- a/libavx/CMakeLists.txt +++ b/libavx/CMakeLists.txt @@ -46,6 +46,7 @@ set(AVX_KERNEL_SRC avx_planes.cpp avx_lora.cpp avx_attn.cpp + avx_sam_attn.cpp avx_qsa.cpp avx_moe.cpp avx_gdn.cpp diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index 3db092d4..cd02f5ea 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -370,6 +370,31 @@ std::vector build_cases() { for (int kw : { 3, 4 }) add("attn_na3d", { HI("M", 64), HI("head_dim", 64), HI("kt", 3), HI("kh", 3), HI("kw", kw), HS("dtype", dt) }); + /* Unlimited-OCR's SAM tower: window 14 on a 16x16 grid (padded to 2x2 windows of 14x14), the + * same over a 14x21 grid (a partial window in both directions, and the padded rows take part in + * the softmax), an exact 14x14 multiple, window 7 (21x21 after padding), the global form on a + * square grid, and the global form on a non-square grid whose rel_pos tables must be resampled + * along their row axis. Two segments where the case is multi-segment, so a wrong cu walk shows. + * `n_seq` is not a schema parameter: libref's shape hook sizes cu from it (the harness hint + * convention, avx_cases.cpp's gdn cases). */ + add("sam_attn", { HI("M", 256), HI("head_dim", 64), HI("n_head", 2), HI("grid_h", 16), + HI("grid_w", 16), HI("window", 14), HF("scale", 0.125), + HS("dtype", "bf16") }); + add("sam_attn", { HI("M", 588), HI("head_dim", 32), HI("n_head", 2), HI("grid_h", 14), + HI("grid_w", 21), HI("window", 14), HF("scale", 0.17677669529663687), + HS("dtype", "bf16"), HI("n_seq", 2) }); + add("sam_attn", { HI("M", 196), HI("head_dim", 64), HI("n_head", 2), HI("grid_h", 14), + HI("grid_w", 14), HI("window", 14), HF("scale", 0.125), + HS("dtype", "bf16") }); + add("sam_attn", { HI("M", 256), HI("head_dim", 64), HI("n_head", 2), HI("grid_h", 16), + HI("grid_w", 16), HI("window", 7), HF("scale", 0.125), + HS("dtype", "bf16") }); + add("sam_attn", { HI("M", 256), HI("head_dim", 16), HI("n_head", 4), HI("grid_h", 16), + HI("grid_w", 16), HI("window", 0), HF("scale", 0.25), + HS("dtype", "bf16") }); + add("sam_attn", { HI("M", 240), HI("head_dim", 32), HI("n_head", 2), HI("grid_h", 12), + HI("grid_w", 20), HI("window", 0), HF("scale", 0.17677669529663687), + HS("dtype", "bf16") }); for (const char* dt : { "f32", "bf16" }) add("seg_sinusoid", { HI("M", 30), HI("n", 64), HI("period", 13), HS("dtype", dt) }); /* Gemma 4's audio attention: left 12, over segments longer than the window. */ @@ -661,8 +686,8 @@ std::vector build_cases() { /* Sampling. n_vocab 517 exceeds every vector width and is not a multiple of any; n_cand 12 is * a realistic candidate set after top-k. */ - for (const char* op : { "sample_penalties", "sample_dry", "sample_temp", "sample_mask", - "sample_argmax" }) + for (const char* op : { "sample_penalties", "sample_dry", "sample_ngram_ban", "sample_temp", + "sample_mask", "sample_argmax" }) add(op, { HI("M", 5), HI("n_vocab", 517) }); add("sample_topk", { HI("M", 5), HI("n_vocab", 517), HI("vocab_off", 0) }); /* k 7 and 20 (OpenAI's top_logprobs bound) against 517 columns; the offset case checks that diff --git a/libavx/avx_harness.h b/libavx/avx_harness.h index e5c2f205..ad3d468a 100644 --- a/libavx/avx_harness.h +++ b/libavx/avx_harness.h @@ -517,11 +517,13 @@ static inline void h_sampler_rows(Prepared& pr, const Case& c) { if (std::strncmp(c.op, "sample_", 7) != 0) return; Opd* params = nullptr; Opd* hist = nullptr; + Opd* ngram = nullptr; for (size_t k = 0; k < pr.opd.size(); ++k) { const char* nm = pr.schema->operands[k].name; if (!nm || pr.opd[k].absent || pr.opd[k].d.rank != 2) continue; if (!std::strcmp(nm, "params")) params = &pr.opd[k]; if (!std::strcmp(nm, "history") && pr.opd[k].d.dtype == RAD_I32) hist = &pr.opd[k]; + if (!std::strcmp(nm, "ngram") && pr.opd[k].d.shape[1] == 2) ngram = &pr.opd[k]; } const int64_t words = (int64_t)(sizeof(RadSampleParams) / 4); if (!params || rad_dtype_bits(params->d.dtype) != 32 || params->d.shape[1] != words) return; @@ -549,6 +551,14 @@ static inline void h_sampler_rows(Prepared& pr, const Case& c) { sp.hist_off = 0; sp.hist_len = (int32_t)hw; sp.mask_row = r % 2 ? (int32_t)r : -1; + /* The n-gram ban's per-row pair: n 1 to 3 over windows short of the 64-token history, so + * the window boundary and the n == 1 form (an empty prefix) both run. Only the op whose + * schema has the `ngram` plane reads it. */ + if (ngram) { + int32_t* v = (int32_t*)ngram->master.data(); + v[2 * r] = 1 + (int32_t)(r % 3); + v[2 * r + 1] = 12 + 8 * (int32_t)(r % 4); + } sp.flags = RAD_SP_PENALTY | RAD_SP_XTC | RAD_SP_DRY | RAD_SP_LOGPROBS | (sp.mask_row >= 0 ? RAD_SP_MASK : 0); if (r == M - 1 && M > 1) sp.flags = RAD_SP_GREEDY; diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index fca40a77..9b371e57 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -103,6 +103,7 @@ int avx_par_force(int threads); X(attn_paged) X(attn_dense) X(attn_cross) X(attn_na3d) X(table_add) X(mix_rows) X(chan_stats) X(kv_store) X(rope) \ X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \ X(qsa_score) X(qsa_select) X(qsa_tail_store) X(qsa_work) \ + X(sam_attn) \ /* ---- mixture of experts */ \ X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \ X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \ @@ -139,7 +140,7 @@ int avx_par_force(int threads); X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ X(sample_merge_topk) X(sample_mask) X(sample_pick) X(sample_argmax) \ - X(sample_logprobs) X(dflash_select) X(dflash_conv) + X(sample_ngram_ban) X(sample_logprobs) X(dflash_select) X(dflash_conv) /* One ISA level's table: one member per op, in AVX_OP_LIST order. A missing definition is a link * error from that level's avx_table.cpp object. */ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index d5de6ff6..5f5e3a5f 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -305,6 +305,14 @@ static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT(" P_INT("kw"), P_STR("dtype"), P_F64O("scale") }; static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") }; +/* The SAM tower's attention: windowed tiles with a decomposed relative-position term, the two tables + * weights of [2*L-1, head_dim] (see libref/ref_registry.cpp and docs/OPS.md). */ +static const RadParamSpec pSamAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("grid_h"), P_INT("grid_w"), P_INT("window"), + P_F64("scale"), P_STR("dtype") }; +static const RadOperandSpec oSamAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), + OUT("out"), WGT("rel_pos_h"), WGT("rel_pos_w") }; + static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), P_INT("block_size"), P_STR("kv_dtype"), P_F64O("k_scale"), P_F64O("v_scale") }; @@ -775,6 +783,8 @@ static const RadParamSpec pPenal[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vo static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD("history") }; static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"), OPD_O("breakers") }; +static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"), + OPD("ngram") }; static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") }; static const RadOperandSpec oMask[] = { INOUT("logits"), OPD("params"), OPD("bitmask") }; static const RadParamSpec pTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INTO("vocab_off") }; @@ -971,6 +981,11 @@ static const RadOpSchema kSchemas[] = { "start." }, { "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d), "3-D neighborhood attention over a volume, libref's window and arithmetic." }, +{ "sam_attn", ARR(pSamAttn), ARR(oSamAttn), + "SAM tower attention: per cu segment of grid_h*grid_w rows, pad to multiples of `window` with " + "zero rows, tile into window x window windows (window 0 is one tile over the segment) and attend " + "each tile to all of its rows. logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w] over the head's " + "whole head_dim, softmax in f32 with the max subtracted, out = sum p*v, pad rows dropped." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." }, { "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." }, { "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey), @@ -1207,6 +1222,10 @@ static const RadOpSchema kSchemas[] = { { "sample_penalties", ARR(pPenal), ARR(oPenalties), "repetition, frequency and presence penalties." }, { "sample_dry", ARR(pPenal), ARR(oDry), "DRY repetition-suffix penalty, once per token." }, +{ "sample_ngram_ban", ARR(pPenal), ARR(oNgramBan), + "the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` tokens of " + "the row's history contain is set to -infinity. `ngram` is an i32 {n, window} pair a row; n 0 " + "is off." }, { "sample_temp", ARR(pMVocab), ARR(oTemp), "per-request temperature." }, { "sample_topk", ARR(pTopk), ARR(oTopk), "exact top-k candidate set, descending, ties to the " "lower id." }, @@ -1513,6 +1532,9 @@ SIMPLE("avx_attn_cross", "attn_cross", "attn", L(attn_cross)), SIMPLE("avx_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT, L(attn_na3d)), +SIMPLE("avx_sam_attn", "sam_attn", "attn", + "SAM tower attention: windowed tiles with decomposed relative position", DT_FLOAT, + L(sam_attn)), ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), L(kv_store)), SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)), @@ -1748,6 +1770,8 @@ SIMPLE("avx_sample_penalties", "sample_penalties", "sample", "repetition, frequency and presence penalties", DT_FLOAT, L(sample_penalties)), SIMPLE("avx_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT, L(sample_dry)), +SIMPLE("avx_sample_ngram_ban", "sample_ngram_ban", "sample", "windowed no-repeat-ngram ban", + DT_FLOAT, L(sample_ngram_ban)), SIMPLE("avx_sample_temp", "sample_temp", "sample", "per-request temperature", DT_FLOAT, L(sample_temp)), SIMPLE("avx_sample_topk", "sample_topk", "sample", "exact top-k candidate set", DT_FLOAT, diff --git a/libavx/avx_sam_attn.cpp b/libavx/avx_sam_attn.cpp new file mode 100644 index 00000000..77205210 --- /dev/null +++ b/libavx/avx_sam_attn.cpp @@ -0,0 +1,168 @@ +/* avx_sam_attn.cpp -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative + * position (arch/common/rad_block_sam.h; libref/ref_sam_attn.cpp is the oracle). + * + * The logits of a query row i against a key j of the same window tile are + * + * scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w] + * + * over the head's whole head_dim, the two tables indexed by the grid offset inside the tile. With + * `window` > 0 the grid is padded with ZERO rows to a multiple of the window and cut into + * window x window tiles (deepencoder's window_partition, after norm1), so the pad rows are keys and + * values of their tile and take part in the softmax; `window` 0 is one tile over the segment. + * + * This is the same structure as libref's: one thread owns one output row and one head, the tile's + * keys are walked jh-major so the q.Rh dot is computed once a tile row, the softmax subtracts the + * tile maximum, and the output is rounded once. The dots are plain f32 loops over head_dim, which + * LLVM vectorises at every level; the tile is small enough that no blocking is needed. The tables + * are widened to f32 once a launch and resampled along dim 0 when a geometry's axes need it + * (get_rel_pos's linear interpolation). + */ +#include "avx_vec.h" +#include "avx_common.h" + +#include +#include +#include + +using namespace avx; + +namespace { + +/* A rel_pos table as f32 rows of `hd`, resampled to `want` rows when its own length differs: + * F.interpolate(..., size=want, mode="linear") with align_corners False. */ +static std::vector table_rows(const RadTensor* t, int64_t hd, int64_t want) { + const int64_t rows = hd > 0 ? numel(t) / hd : 0; + std::vector raw((size_t)(rows * hd), 0.0f); + const int64_t st = laststride(t); + for (int64_t r = 0; r < rows; ++r) { + const int64_t base = rowoff(t, r, hd); + for (int64_t c = 0; c < hd; ++c) raw[(size_t)(r * hd + c)] = ldt(t, base + c * st); + } + if (rows == want || rows <= 0 || want <= 0) return raw; + std::vector out((size_t)(want * hd), 0.0f); + const double span = (double)rows / (double)want; + for (int64_t d = 0; d < want; ++d) { + double src = ((double)d + 0.5) * span - 0.5; + if (src < 0.0) src = 0.0; + if (src > (double)(rows - 1)) src = (double)(rows - 1); + const int64_t i0 = (int64_t)src; + const int64_t i1 = i0 + 1 < rows ? i0 + 1 : i0; + const float f = (float)(src - (double)i0); + for (int64_t c = 0; c < hd; ++c) { + const float a = raw[(size_t)(i0 * hd + c)], b = raw[(size_t)(i1 * hd + c)]; + out[(size_t)(d * hd + c)] = a + (b - a) * f; + } + } + return out; +} + +} /* namespace */ + +AVX_KERNEL(sam_attn) { + if (!a || a->n_t < 7) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3]; + const RadTensor *o = &a->t[4], *th_tab = &a->t[5], *tw_tab = &a->t[6]; + + const int64_t hd = p_int(a, "head_dim", 0); + const int64_t nh = p_int(a, "n_head", 0); + const int64_t gh = p_int(a, "grid_h", 0); + const int64_t gw = p_int(a, "grid_w", 0); + const int64_t win = p_int(a, "window", 0); + if (hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_SHAPE; + const int64_t W = nh * hd, R = gh * gw; + if (!q->data || !k->data || !v->data || !o->data || !th_tab->data || !tw_tab->data) + return RAD_E_INVAL; + for (const RadTensor* t : { q, k, v, o }) + if (t->rank < 2 || t->shape[t->rank - 1] != W) return RAD_E_SHAPE; + const int64_t M = numel(q) / W; + if (M <= 0) return RAD_E_SHAPE; + if (numel(k) != M * W || numel(v) != M * W || numel(o) < M * W) return RAD_E_SHAPE; + + int64_t nseq = 1; + if (cu->data) { + if (cu->rank == 0 || numel(cu) < 2) return RAD_E_SHAPE; + nseq = numel(cu) - 1; + if (ldi(cu, offlin(cu, 0)) != 0 || ldi(cu, offlin(cu, nseq)) != M) return RAD_E_SHAPE; + for (int64_t s = 0; s < nseq; ++s) + if (ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s)) != R) return RAD_E_SHAPE; + } else if (M != R) { + return RAD_E_SHAPE; + } + + const float scale = p_f32(a, "scale", (float)(1.0 / std::sqrt((double)hd))); + const int64_t th = win > 0 ? win : gh, tw = win > 0 ? win : gw; + const int64_t keys = th * tw; + if (numel(th_tab) < hd || numel(tw_tab) < hd) return RAD_E_SHAPE; + const std::vector Rh = table_rows(th_tab, hd, 2 * th - 1); + const std::vector Rw = table_rows(tw_tab, hd, 2 * tw - 1); + + AVX_PARALLEL_FOR_IF(nseq * R * nh * keys * hd >= AVX_PAR_MIN) + for (int64_t work = 0; work < nseq * R; ++work) { + const int64_t s = work / R, r = work % R; + const int64_t ih = r / gw, iw = r % gw; + const int64_t ty = win > 0 ? ih / win : 0, tx = win > 0 ? iw / win : 0; + const int64_t lh = ih - ty * th, lw = iw - tx * tw; + const int64_t base = cu->data ? ldi(cu, offlin(cu, s)) : 0; + const int64_t out_row = base + r; + + float* logits = scratch_f32((size_t)keys); + float* acc = scratch_f32_b((size_t)(2 * hd)); + float* qt = acc + hd; + + for (int64_t h = 0; h < nh; ++h) { + const int64_t qbase = rowoff(q, out_row, W) + h * hd; + const int64_t qst = laststride(q); + for (int64_t c = 0; c < hd; ++c) qt[c] = ldt(q, qbase + c * qst); + + for (int64_t jh = 0; jh < th; ++jh) { + const float* rhrow = &Rh[(size_t)((lh - jh + th - 1) * hd)]; + float hr = 0.0f; + for (int64_t c = 0; c < hd; ++c) hr += qt[c] * rhrow[c]; + for (int64_t jw = 0; jw < tw; ++jw) { + const float* rwrow = &Rw[(size_t)((lw - jw + tw - 1) * hd)]; + float lgt = hr; + for (int64_t c = 0; c < hd; ++c) lgt += qt[c] * rwrow[c]; + const int64_t kh = ty * th + jh, kw = tx * tw + jw; + if (kh < gh && kw < gw) { + const int64_t krow = base + kh * gw + kw; + const int64_t kb = rowoff(k, krow, W) + h * hd; + const int64_t ks = laststride(k); + float s_ = 0.0f; + for (int64_t c = 0; c < hd; ++c) s_ += qt[c] * ldt(k, kb + c * ks); + lgt += scale * s_; + } + logits[jh * tw + jw] = lgt; + } + } + + float m = -INFINITY; + for (int64_t j = 0; j < keys; ++j) m = logits[j] > m ? logits[j] : m; + float sum = 0.0f; + for (int64_t j = 0; j < keys; ++j) { + logits[j] = sc_exp(logits[j] - m); + sum += logits[j]; + } + for (int64_t c = 0; c < hd; ++c) acc[c] = 0.0f; + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t jh = 0; jh < th; ++jh) { + const int64_t kh = ty * th + jh; + if (kh >= gh) continue; + for (int64_t jw = 0; jw < tw; ++jw) { + const int64_t kw = tx * tw + jw; + if (kw >= gw) continue; + const float p = logits[jh * tw + jw] * inv; + if (p == 0.0f) continue; + const int64_t krow = base + kh * gw + kw; + const int64_t vb = rowoff(v, krow, W) + h * hd; + const int64_t vs = laststride(v); + for (int64_t c = 0; c < hd; ++c) acc[c] += p * ldt(v, vb + c * vs); + } + } + + const int64_t ob = rowoff(o, out_row, W) + h * hd; + const int64_t os = laststride(o); + for (int64_t c = 0; c < hd; ++c) stt(o, ob + c * os, acc[c]); + } + } + return RAD_OK; +} diff --git a/libavx/avx_sample.cpp b/libavx/avx_sample.cpp index 5f037ad8..eb192ebb 100644 --- a/libavx/avx_sample.cpp +++ b/libavx/avx_sample.cpp @@ -222,6 +222,73 @@ AVX_KERNEL(sample_dry) { return RAD_OK; } +/* ------------------------------------------------------------------ sample_ngram_ban */ +/* libref's ref_sample_ngram_ban: the windowed no-repeat-ngram ban. The row's history is + * `s[0, hl)` oldest first; with `n` and `w` from the row's `ngram` pair, + * + * search_start = max(0, hl - w) (w <= 0: the whole span) + * search_end = hl - n + 1 + * prefix = s[hl - n + 1, hl) (empty at n == 1) + * + * and every n-gram in [search_start, search_end) whose first n-1 tokens equal the prefix bans the + * token that follows it, by -infinity. The window bounds the n-gram's START, as the reference's + * SlidingWindowNoRepeatNgramProcessor does. Ids are global; a token's column is its id less + * `vocab_off`, and a token outside the shard is another rank's. + * + * The work is integer comparisons over at most a window of history, so the rows are parallel and + * the scan inside a row stays scalar: libref's own loop, bit for bit. A row with n 0 (the + * default) is skipped before it reads anything. */ +AVX_KERNEL(sample_ngram_ban) { + if (!rad_args_have(a, 4)) return RAD_E_INVAL; + const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3]; + const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0); + if (n_vocab <= 0) return RAD_E_SHAPE; + const int64_t M = numel(lg) / n_vocab; + if (M <= 0) return RAD_E_SHAPE; + Rows R; + AVX_TRY(rows_of_params(pr, M, &R)); + const int64_t hmax = numel(hist) / M; + if (hmax <= 0) return RAD_E_SHAPE; + if (numel(ng) < 2 * M) return RAD_E_SHAPE; + const int64_t voff = p_int(a, "vocab_off", 0); + + AVX_PARALLEL_FOR_IF(M >= 2) + for (int64_t m = 0; m < M; ++m) { + const RadSampleParams& sp = R.p[m]; + const int64_t nb = rowoff(ng, m, 2), ns = laststride(ng); + const int64_t n = ldi(ng, nb); + const int64_t win_req = ldi(ng, nb + ns); + if (n <= 0) continue; + + int64_t ho = 0, hl = 0; + if (!hist_window(sp, -1, hmax, &ho, &hl)) continue; + if (hl < n) continue; + const int64_t win = win_req > 0 && win_req < hl ? win_req : hl; + const int64_t search_start = hl - win; + const int64_t search_end = hl - n + 1; + if (search_end <= search_start) continue; + + const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist); + const int64_t hs = laststride(hist); + const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg); + auto tok_at = [&](int64_t i) { return (int64_t)(int32_t)ldi(hist, hb + i * hs); }; + const int64_t plen = n - 1, p0 = hl - plen; + + for (int64_t idx = search_start; idx < search_end; ++idx) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; } + } + if (!match) continue; + const int64_t tok = tok_at(idx + plen); + const int64_t col = tok - voff; + if (tok < 0 || col < 0 || col >= n_vocab) continue; + stt(lg, lb + col * ls, -INFINITY); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ sample_temp */ /* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */ AVX_KERNEL(sample_temp) { diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 57f6621b..6bb422c1 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -71,6 +71,8 @@ set(R4D_UNITS # An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and # the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening. "r4d_attn_dense_bf16|" + # Unlimited-OCR's SAM tower: windowed attention with decomposed relative position. + "r4d_sam_attn_bf16|" "r4d_encoder_bf16|" # The image generator: attention over a paged prefix plus the pass's own rows, the causal # head_dim-128 dense form and the 1152-wide decoder head; plus the sampler, adaptive norm, @@ -161,6 +163,8 @@ set(R4D_UNITS "r4d_sample_chain_f32|" "r4d_model_bf16|" "r4d_sample_stages_f32|" + # The windowed no-repeat-ngram ban: one block a row over the row's history. + "r4d_sample_ngram_f32|" "r4d_quant_act_i8|" "r4d_rmsnorm_quant_i8|" "r4d_qkv_norm_rope|" diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 8a16e50c..11d06658 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -158,6 +158,9 @@ int64_t r4d_rad_lora_shrink_wmma_scratch(const RadArgs*); int r4d_rad_lora_expand_tiled (const RadArgs*, RadStream); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); +/* Unlimited-OCR's SAM tower: windowed tiles with decomposed relative position + * (r4d_sam_attn_bf16.hip). */ +int r4d_rad_sam_attn (const RadArgs*, RadStream); int r4d_rad_seg_sinusoid (const RadArgs*, RadStream); /* The image generator's attention (r4d_attn_gen.hip): a paged prefix and the pass's own rows, the * causal-capable dense form at head_dim 128 (a text encoder's prompt), and one 1152-wide head @@ -709,6 +712,9 @@ int r4d_rad_logits_gemm (const RadArgs*, RadStream); * fused one lacks. */ int r4d_rad_sample_penalties (const RadArgs*, RadStream); int r4d_rad_sample_dry (const RadArgs*, RadStream); +/* The windowed no-repeat-ngram ban (r4d_sample_ngram_f32.hip): the row's history, one -infinity + * a banned column. */ +int r4d_rad_sample_ngram_ban(const RadArgs*, RadStream); int r4d_rad_sample_temp (const RadArgs*, RadStream); int r4d_rad_sample_mask (const RadArgs*, RadStream); int r4d_rad_sample_topk (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 98462ecb..584eed43 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -206,6 +206,28 @@ static const RadOperandSpec oAttnNa3d[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_O { "v", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 }, { "out", RAD_OPD_OUT, 0 } }; +/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): windowed attention with a decomposed relative + * position. The two tables are weights, [2*L-1, head_dim] with L the window or the grid. */ +static const RadParamSpec pSamAttn[] = { + P_INT("M"), + P_INT("head_dim"), + P_INT("n_head"), + P_INT("grid_h"), + P_INT("grid_w"), + P_INT("window"), + P_F64("scale"), + P_STR("dtype"), +}; +static const RadOperandSpec oSamAttn[] = { + { "q", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 }, + { "rel_pos_h", RAD_OPD_WEIGHT, 0 }, + { "rel_pos_w", RAD_OPD_WEIGHT, 0 }, +}; + /* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate] * projection per head, writes q, k and the gate to three destinations, and takes a precomputed * cos/sin table. Hence its own op name. */ @@ -2089,6 +2111,15 @@ static const RadOperandSpec oDry[] = { { "history", RAD_OPD_IN, 0 }, { "breakers", RAD_OPD_IN, 1 }, }; +/* The n-gram ban's own plane: one i32 {n-gram length, window} pair a row (n 0 = off, window <= 0 + * = the whole staged history). A plane beside `params` rather than fields in it, because the + * params row is the fixed 24-word RadSampleParams every sampler op shares. */ +static const RadOperandSpec oNgramBan[] = { + { "logits", RAD_OPD_INOUT, 0 }, + { "params", RAD_OPD_IN, 0 }, + { "history", RAD_OPD_IN, 0 }, + { "ngram", RAD_OPD_IN, 0 }, +}; static const RadOperandSpec oTemp[] = { { "logits", RAD_OPD_INOUT, 0 }, { "params", RAD_OPD_IN, 0 }, @@ -2806,6 +2837,11 @@ static const RadOpSchema kSchemas[] = { "DRY: penalise, once, each token that would extend a suffix of the history that has " "occurred before, by its longest such repeat -- what stops a model looping on a phrase " "rather than on a token. Tokens the breaker plane marks are exempt."), + SCHEMA("sample_ngram_ban", pPenal, oNgramBan, + "the windowed no-repeat-ngram ban: every token completing an n-gram the last `window` " + "tokens of the row's history contain is set to -infinity. `ngram` is one i32 " + "{n, window} pair a row; the window bounds the n-gram's START index, as in the " + "reference, window <= 0 searches the whole span and n 0 is off."), SCHEMA("sample_temp", pMVocab, oTemp, "per-request temperature. temp <= 0 leaves the row untouched; greedy is sample_argmax."), SCHEMA("sample_mask", pMVocab, oMask, @@ -2861,6 +2897,11 @@ static const RadOpSchema kSchemas[] = { SCHEMA("attn_na3d", pAttnNa3d, oAttnNa3d, "3-D neighborhood attention over the voxels of geom = (T, H, W): each query sees the " "kt x kh x kw window centred on it, shifted inward at the border."), + SCHEMA("sam_attn", pSamAttn, oSamAttn, + "Unlimited-OCR's SAM tower attention: per cu segment of grid_h*grid_w rows, pad to " + "multiples of `window` with zero rows, tile into window x window windows (0 = the whole " + "segment) and attend each tile to all of its rows. logits = scale*q.k + q.Rh[i_h,j_h] + " + "q.Rw[i_w,j_w], softmax in f32, out = sum p*v, pad rows dropped."), SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate, "split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate " "copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a " @@ -3818,6 +3859,14 @@ static const RadConstraint cCastNarrow[] = { static const RadConstraint cAttnDenseH64[] = { C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"), }; +/* Unlimited-OCR's SAM tower (r4d_sam_attn_bf16.hip): one block per (segment, tile, head), a thread + * a query row, q and the output accumulator in registers; only head_dim 64 is instantiated and the + * tables must be exactly 2*tile-1 rows (a geometry needing get_rel_pos's resampling is libref's + * and libavx's). */ +static const RadConstraint cSamAttn[] = { + C_EQ("head_dim", 64), C_IN("dtype", "bf16"), +}; + static const RadConstraint cAttnDenseH256G2[] = { C_EQ("head_dim", 256), C_EQ("gqa", 2), C_IN("dtype", "bf16"), }; @@ -5505,6 +5554,20 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_sample_dry, nullptr, nullptr, nullptr, r4d_shape_sample_dry }, +{ "sample_ngram_ban_f32", "sample_ngram_ban", "sample", + "the windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor): every " + "token that would complete an n-gram the last `window` tokens of the row's history contain is " + "set to -infinity", + "any vocabulary; ONE BLOCK A ROW, the search positions dealt across its threads, the n-1-token " + "prefix staged in LDS. Integer comparisons and one constant store, so it is bit-identical to " + "libref; the same column written by two positions is an idempotent -infinity", + "f32 logits in place, i32 history, i32 {n, window} per-row pair", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cSampleVoc), NOTUNE, + /* No `opd_shape`: r4d_shapes.cpp declares the sampler's shapes, and the oracle (libref) describes + * this op for the tools that ask. */ + nullptr, nullptr, r4d_rad_sample_ngram_ban }, + { "sample_temp_f32", "sample_temp", "sample", "per-request temperature", "any vocabulary; a row with temp <= 0 or exactly 1 is skipped whole", @@ -6295,6 +6358,16 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, ROW(cAttnVit), NOTUNE, nullptr, nullptr, r4d_rad_attn_vit }, +{ "sam_attn_bf16", "sam_attn", "attn", + "Unlimited-OCR's SAM tower attention: windowed tiles with a decomposed relative-position term", + "head_dim 64; any grid, window and segment count (a segment is one grid_h*grid_w); q/k/v/out at " + "their own row pitch (column slices of one fused projection); rel_pos tables exactly 2*tile-1 " + "rows (a geometry needing get_rel_pos's resampling is libref's and libavx's)", + "bf16 query / key / value / out and rel_pos tables, i32 cu_seqlens, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cSamAttn), NOTUNE, + nullptr, nullptr, r4d_rad_sam_attn }, + { "attn_dense_h64_bf16", "attn_dense", "attn", "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or " "blocks, or causal with an optional window behind", diff --git a/libr4d/r4d_sam_attn_bf16.hip b/libr4d/r4d_sam_attn_bf16.hip new file mode 100644 index 00000000..c509394b --- /dev/null +++ b/libr4d/r4d_sam_attn_bf16.hip @@ -0,0 +1,206 @@ +// r4d_sam_attn_bf16 -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative +// position (`sam_attn`; arch/common/rad_block_sam.h, libref/ref_sam_attn.cpp is the oracle). +// +// The logits of a query row i against a key j of the same window tile are +// +// scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w] +// +// over the head's whole head_dim, the tables indexed by the offset inside the tile. With `window` +// > 0 the grid is padded with ZERO rows to a multiple of the window and cut into window x window +// tiles (deepencoder's window_partition, after norm1): the pad rows are keys and values of their +// tile and take part in the softmax, their v being zero. `window` 0 is one tile over the segment. +// +// Shape. One block per (segment, tile, head), so the tile's keys are shared by the block's query +// rows and the k/v rows a wave reads at each step are one address (an L1/L2 hit, broadcast across +// the wave). Each thread owns one query row: q and the output accumulator are HD floats in +// registers, the softmax is the online form (running max and sum), and the rel_pos dot of a tile +// row is computed once per (query row, tile row) rather than once per key. +// +// Head widths. HD is a template parameter and only 64 is instantiated (SAM ViT-B's 12 x 64); the +// shim refuses any other width rather than reading past the registers. The tables must be exactly +// 2*tile-1 rows, which every geometry the tower declares is; the shim declines a table that would +// need get_rel_pos's resampling (libref and libavx serve that). +// +// Exactness. f32 throughout, one bf16 rounding of the output, exp2 (the hardware transcendental) +// with the log2(e) factor; the selftest holds it to the house tolerance against a host port of the +// reference, not to bits. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" + +#include + +namespace { + +constexpr uint32_t kThreads = 128; +constexpr float kLog2e = 1.4426950408889634f; + +template +__global__ __launch_bounds__(kThreads) void sam_attn_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 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; + + const int s0 = cu[seq]; + if (cu[seq + 1] - s0 != gh * gw) return; // a segment is exactly one grid + const int keys = th * tw; + + for (int r = (int)threadIdx.x; r < keys; 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 + + const size_t qrow = (size_t)(s0 + ih * gw + iw); + const uint16_t* qp = gq + qrow * (size_t)q_ld + (size_t)head * HD; + float qf[HD]; +#pragma unroll + for (int c = 0; c < HD; ++c) qf[c] = bf16_to_f32(qp[c]); + + float acc[HD]; +#pragma unroll + for (int c = 0; c < HD; ++c) acc[c] = 0.0f; + float m = -INFINITY, l = 0.0f; + + for (int jh = 0; jh < th; ++jh) { + const uint16_t* hrp = rh + (size_t)(lh - jh + th - 1) * HD; + float hr = 0.0f; +#pragma unroll + for (int c = 0; c < HD; ++c) hr += qf[c] * bf16_to_f32(hrp[c]); + + const int kh = ty * th + jh; + const bool hreal = kh < gh; + for (int jw = 0; jw < tw; ++jw) { + const uint16_t* wrp = rw + (size_t)(lw - jw + tw - 1) * HD; + float s = hr; +#pragma unroll + for (int c = 0; c < HD; ++c) s += qf[c] * bf16_to_f32(wrp[c]); + + const int kw = tx * tw + jw; + const bool real = hreal && kw < gw; + const uint16_t* vp = nullptr; + if (real) { + const size_t krow = (size_t)(s0 + kh * gw + kw); + const uint16_t* kp = gk + krow * (size_t)k_ld + (size_t)head * HD; + float d = 0.0f; +#pragma unroll + for (int c = 0; c < HD; ++c) d += qf[c] * bf16_to_f32(kp[c]); + s += scale * d; + vp = gv + krow * (size_t)v_ld + (size_t)head * HD; + } + + // Online softmax: a new maximum rescales what has been accumulated. + if (s > m) { + const float corr = ex2((m - s) * kLog2e); +#pragma unroll + for (int c = 0; c < HD; ++c) acc[c] *= corr; + l *= corr; + m = s; + } + const float p = ex2((s - m) * kLog2e); + l += p; + if (real) { +#pragma unroll + for (int c = 0; c < HD; ++c) acc[c] += p * bf16_to_f32(vp[c]); + } + } + } + + const float inv = l > 0.0f ? 1.0f / l : 0.0f; + uint16_t* op = go + qrow * (size_t)o_ld + (size_t)head * HD; +#pragma unroll + for (int c = 0; c < HD; ++c) op[c] = f32_to_bf16(acc[c] * inv); + } +} + +int launch_sam_attn(const uint16_t* q, const uint16_t* k, const uint16_t* v, uint16_t* o, + const int* cu, const uint16_t* rh, const uint16_t* rw, + int q_ld, int k_ld, int v_ld, int o_ld, int nseq, int nhead, int gh, int gw, + 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); + hipLaunchKernelGGL((sam_attn_kernel<64>), dim3((uint32_t)blocks), dim3(kThreads), 0, + (hipStream_t)stream, q, k, v, o, cu, rh, rw, q_ld, k_ld, v_ld, o_ld, nhead, + gh, gw, th, tw, nth, ntw, scale); + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); +} + +} // namespace + +// ================================================================================ entry point +// +// The shim checks what the kernel assumes: bf16 operands, rank 2 with dense columns and any row +// pitch (the tower's q/k/v are the three column slices of one fused projection), an i32 cu with one +// entry a segment plus the terminator, tables of exactly 2*tile-1 rows, head_dim 64. The segment +// lengths are the kernel's to check against cu (it cannot be read on the host at issue). + +#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) + +static inline int bf16_rows(const RadTensor* t, int64_t cols, int64_t* rows, int64_t* ld) { + if (!t || !t->data) return RAD_E_INVAL; + if (t->dtype != RAD_BF16) return RAD_E_DTYPE; + if (t->rank != 2) return RAD_E_SHAPE; + if (t->shape[1] != cols || t->stride[1] != 1) return RAD_E_SHAPE; + *rows = t->shape[0]; + *ld = t->stride[0]; + return RAD_OK; +} + +extern "C" int r4d_rad_sam_attn(const RadArgs* a, RadStream s) { + enum { V_Q = 0, V_K, V_V, V_CU, V_OUT, V_RH, V_RW }; + const RadTensor* q = r4d_opt(a, V_Q); + const RadTensor* k = r4d_opt(a, V_K); + const RadTensor* v = r4d_opt(a, V_V); + const RadTensor* cu = r4d_opt(a, V_CU); + const RadTensor* o = r4d_opt(a, V_OUT); + const RadTensor* rh = r4d_opt(a, V_RH); + const RadTensor* rw = r4d_opt(a, V_RW); + if (!q || !k || !v || !cu || !o || !rh || !rw) return R4D_NO(RAD_E_INVAL); + + const long long hd = r4d_geti_or(a, "head_dim", 0); + const long long nh = r4d_geti_or(a, "n_head", 0); + const long long gh = r4d_geti_or(a, "grid_h", 0); + const long long gw = r4d_geti_or(a, "grid_w", 0); + const long long win = r4d_geti_or(a, "window", 0); + if (hd != 64 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return R4D_NO(RAD_E_UNSUPPORTED); + const long long W = nh * hd; + + int64_t qrows = 0, qld = 0, krows = 0, kld = 0, vrows = 0, vld = 0, orows = 0, old = 0; + R4D_NEED(bf16_rows(q, W, &qrows, &qld)); + R4D_NEED(bf16_rows(k, W, &krows, &kld)); + R4D_NEED(bf16_rows(v, W, &vrows, &vld)); + R4D_NEED(bf16_rows(o, W, &orows, &old)); + if (qrows <= 0 || krows < qrows || vrows < qrows || orows < qrows) return R4D_NO(RAD_E_SHAPE); + + if (!cu->data) return R4D_NO(RAD_E_INVAL); + if (cu->dtype != RAD_I32 || !r4d_contig(cu)) return R4D_NO(RAD_E_DTYPE); + const long long nseq = r4d_numel(cu) - 1; + if (nseq < 1) return R4D_NO(RAD_E_SHAPE); + + // The tables: [2*tile-1, head_dim] each, the tile being the window or the whole grid. + const long long th = win > 0 ? win : gh, tw = win > 0 ? win : gw; + int64_t rhrows = 0, rhld = 0, rwrows = 0, rwld = 0; + R4D_NEED(bf16_rows(rh, hd, &rhrows, &rhld)); + R4D_NEED(bf16_rows(rw, hd, &rwrows, &rwld)); + if (rhrows != 2 * th - 1 || rwrows != 2 * tw - 1) return R4D_NO(RAD_E_UNSUPPORTED); + + const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd)); + + return launch_sam_attn((const uint16_t*)r4d_addr(q), (const uint16_t*)r4d_addr(k), + (const uint16_t*)r4d_addr(v), (uint16_t*)r4d_addr(o), + (const int*)r4d_addr(cu), (const uint16_t*)r4d_addr(rh), + (const uint16_t*)r4d_addr(rw), (int)qld, (int)kld, (int)vld, (int)old, + (int)nseq, (int)nh, (int)gh, (int)gw, (int)win, scale, + (long)(uintptr_t)s); +} diff --git a/libr4d/r4d_sample_ngram_f32.hip b/libr4d/r4d_sample_ngram_f32.hip new file mode 100644 index 00000000..77443645 --- /dev/null +++ b/libr4d/r4d_sample_ngram_f32.hip @@ -0,0 +1,190 @@ +// r4d_sample_ngram_f32 -- the windowed no-repeat-ngram ban (`sample_ngram_ban`). +// +// Unlimited-OCR's generation_config asks for SlidingWindowNoRepeatNgramProcessor(n=35, +// window=128): a token that would complete an n-gram the last `window` tokens of the sequence +// already contain is banned, by setting its logit to -infinity. modeling_unlimitedocr.py:353-383 +// is the reference, which SGLang ships as DeepseekOCRNoRepeatNGramLogitProcessor. A model that +// loops at the n-gram level (OCR layout rows repeat) otherwise repeats a phrase until the context +// ends. +// +// The reference's rule, with the row's history `s[0, hl)` oldest first (the committed tokens, +// including the one just emitted, plus this step's earlier drafts at a speculative verify): +// +// search_start = max(0, hl - w) with w from the row's {n, window} pair, w <= 0 whole span +// search_end = hl - n + 1 +// for idx in [search_start, search_end): +// if s[idx .. idx + n - 2] == s[hl - n + 1 .. hl - 1): ban s[idx + n - 1] +// +// and at n = 1 the prefix is empty, so every token in the window is banned. The window bounds the +// n-gram's START, not its end, exactly as the reference slices `sequence[search_start:search_end]` +// -- which is why an n-gram that spans the window boundary is still searched. +// +// Exactness. Nothing here rounds: the kernel compares int32 history ids and stores the constant +// -infinity, so its answer is libref's ref_sample_ngram_ban by construction, not by tolerance. The +// only ordering freedom is that two threads may store -infinity to the same column, and the store +// is idempotent. +// +// Ids are global and the logits row is this rank's vocabulary shard: a token's column is its id +// less `vocab_off`, and a token outside the shard is another rank's to mask (it is not a column +// here at all). +// +// The scan is O(w * n) a row over a history of at most max_hist tokens, so one block a row with +// the positions dealt out across the block's threads; the n-1-token prefix is staged in LDS once +// when it fits (n <= 256), which is every request the model card asks for (35). + +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_common.h" + +#include + +// The params row is the engine's wire format, included rather than restated (abi/rad_sample.h). +#include "rad_sample.h" + +namespace { + +constexpr uint32_t kThreads = 256; + +// The prefix staged in LDS, one int32 a token: 1 KiB. A longer n falls back to reading the +// history plane, which is correct but repeats the prefix's loads per position. +constexpr uint32_t kMaxPrefix = 256; + +using SP = RadSampleParams; + +__global__ __launch_bounds__(kThreads) void ngram_ban_kernel( + float* __restrict__ lg, const SP* __restrict__ sp, const int32_t* __restrict__ hist, + const int32_t* __restrict__ ng, uint32_t n_vocab, uint32_t lg_ld, uint32_t hmax, int32_t voff) { + __shared__ int32_t pf[kMaxPrefix]; + __shared__ int64_t s_start, s_end, s_plen, s_p0; + + const uint32_t m = blockIdx.x; + const SP p = sp[m]; + // The row's {n-gram length, window} pair (a separate plane, so the params row keeps the wire + // format every sampler op shares). + const int32_t ngram = ng[2 * m]; + const int32_t win_req = ng[2 * m + 1]; + // Every test before the barrier reads the row's own planes, so the block leaves together. + if (ngram <= 0) return; + + // The whole staged span of the row (hist_off/hist_len both come from the engine; a negative + // hist_off is 0), clamped to the plane. + int32_t hl = p.hist_len; + int32_t ho = p.hist_off < 0 ? 0 : p.hist_off; + if (ho > (int32_t)hmax) ho = (int32_t)hmax; + if (hl > (int32_t)hmax - ho) hl = (int32_t)hmax - ho; + + if (threadIdx.x == 0) { + int64_t start = 0, end = 0, plen = 0, p0 = 0; + if (hl >= ngram) { + // w <= 0 is the un-windowed processor: the whole staged history. + const int64_t win = win_req > 0 && win_req < hl ? win_req : hl; + start = hl - win; + end = (int64_t)hl - ngram + 1; + plen = (int64_t)ngram - 1; + p0 = (int64_t)hl - plen; + if (end <= start) end = start; /* nothing to search */ + } + s_start = start; + s_end = end; + s_plen = plen; + s_p0 = p0; + } + __syncthreads(); + + const int64_t start = s_start, end = s_end, plen = s_plen, p0 = s_p0; + if (end <= start) return; + + const int32_t* __restrict__ h = hist + (size_t)m * hmax + ho; + float* __restrict__ row = lg + (size_t)m * lg_ld; + + // The prefix: LDS when it fits, otherwise each position reads it from the plane. + const bool in_lds = plen <= (int64_t)kMaxPrefix; + if (in_lds) { + for (int64_t j = threadIdx.x; j < plen; j += (int64_t)kThreads) pf[j] = h[p0 + j]; + __syncthreads(); + } + auto prefix_at = [&](int64_t j) -> int32_t { + return in_lds ? pf[j] : h[p0 + j]; + }; + + for (int64_t idx = start + (int64_t)threadIdx.x; idx < end; idx += (int64_t)kThreads) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (h[idx + j] != prefix_at(j)) { match = false; break; } + } + if (!match) continue; + const int32_t tok = h[idx + plen]; + const int64_t col = (int64_t)tok - voff; + if (tok < 0 || col < 0 || col >= (int64_t)n_vocab) continue; + // Two positions may ban one token; the store is idempotent and the value is constant. + row[col] = -INFINITY; + } +} + +int r4d_sample_ngram_ban_f32(long lg, long params, long hist, long ng, int M, int n_vocab, + int hmax, int lg_ld, int vocab_off, long stream) { + if (!lg || !params || !hist || !ng) return R4D_NO(RAD_E_INVAL); + if (M <= 0 || n_vocab <= 0 || hmax <= 0) return R4D_NO(RAD_E_SHAPE); + if (!lg_ld) lg_ld = n_vocab; + hipLaunchKernelGGL(ngram_ban_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, + (float*)lg, (const SP*)params, (const int32_t*)hist, (const int32_t*)ng, + (uint32_t)n_vocab, (uint32_t)lg_ld, (uint32_t)hmax, (int32_t)vocab_off); + return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE); +} + +} // namespace + +// ================================================================================ entry point +// +// The shim checks what the kernel assumes: f32 logits, an i32 history contiguous in both rows and +// columns (the kernel walks it as one int32 a token), a params plane of whole RadSampleParams rows +// and the row pitches. `M` is the step's staged row count, never the band's upper bound. + +#define R4D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R4D_NO(_s); } while (0) + +static inline int dt_f32(const RadTensor* t) { + return (t && t->dtype == RAD_F32) ? RAD_OK : RAD_E_DTYPE; +} + +static inline int dt_i32(const RadTensor* t) { + return (t && (t->dtype == RAD_I32 || t->dtype == RAD_U32)) ? RAD_OK : RAD_E_DTYPE; +} + +static int params_ok(const RadTensor* t, long long M) { + if (!t || !t->data) return R4D_NO(RAD_E_INVAL); + if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(t)) return R4D_NO(RAD_E_STRIDE); + if (r4d_numel(t) * 4 < M * (long long)sizeof(RadSampleParams)) return R4D_NO(RAD_E_SHAPE); + return RAD_OK; +} + +extern "C" int r4d_rad_sample_ngram_ban(const RadArgs* a, RadStream s) { + enum { V_LOGITS = 0, V_PARAMS, V_HIST, V_NGRAM }; + const RadTensor* lg = r4d_opt(a, V_LOGITS); + if (!lg) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_f32(lg)); + const long long nv = r4d_geti_or(a, "n_vocab", r4d_dim(lg, (int)lg->rank - 1)); + if (nv <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0; + const long long ld = r4d_rows_pitch(lg, nv, &M); + if (ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + + const RadTensor* pr = r4d_opt(a, V_PARAMS); + const RadTensor* h = r4d_opt(a, V_HIST); + const RadTensor* ng = r4d_opt(a, V_NGRAM); + R4D_NEED(params_ok(pr, M)); + if (!h || !ng) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_i32(h)); + R4D_NEED(dt_i32(ng)); + if (!r4d_contig(h) || !r4d_contig(ng)) return R4D_NO(RAD_E_STRIDE); + const long long hmax = r4d_numel(h) / M; + if (hmax <= 0) return R4D_NO(RAD_E_SHAPE); + /* One {n, window} pair a row, at least M of them. */ + if (r4d_numel(ng) < 2 * M) return R4D_NO(RAD_E_SHAPE); + + const long long voff = r4d_geti_or(a, "vocab_off", 0); + return r4d_sample_ngram_ban_f32(r4d_addr(lg), r4d_addr(pr), r4d_addr(h), r4d_addr(ng), + (int)M, (int)nv, (int)hmax, (int)ld, (int)voff, + (long)(uintptr_t)s); +} diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 1a7853e9..2c71760c 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -42,6 +42,7 @@ #include "r4d_fp8_lm.h" #include "rad_encoding.h" #include "rad_philox.h" +#include "rad_sample.h" #include "rad_yarn.h" #include @@ -18802,6 +18803,295 @@ static void sample_argmax_case(const Plugin& pl) { " agree=" + (agree ? "1" : "0")); } +/* sample_ngram_ban, against a host port of the reference processor. + * + * The oracle is modeling_unlimitedocr.py:353-383's SlidingWindowNoRepeatNgramProcessor, restated + * here over int arrays: with the row's history s[0, hl) (oldest first), + * + * search_start = max(0, hl - window) (window <= 0: the whole span) + * search_end = hl - n + 1 + * prefix = s[hl - n + 1, hl) (empty at n == 1) + * + * and every n-gram whose first n-1 tokens equal the prefix bans the token after it. The window + * bounds the START, so an n-gram that spans the window boundary is searched, and repeated tokens + * make matches dense. + * + * Checked, over three vocabularies/shards and rows with n = 0 (off), 1 (empty prefix), 2, 3 and 5 + * and windows short of, equal to and longer than the history plus the whole-span form, the (n, + * window) pair coming from its own i32 plane as the engine sends it: + * a banned column is exactly -infinity and every other column is bit-identical to its input; + * a token on another rank's shard (under `vocab_off`) is never written; + * rows 2 and up repeat an earlier stretch, so the ban is exercised, and the totals are printed. + * The kernel does integer comparisons and stores one constant, so this is an equality check, not a + * tolerance. */ + +/* The reference rule for one row: `banned` gets 1 for every global id `s` bans. */ +static void ngram_ban_ref(const int32_t* s, int64_t hl, int n, int window, + std::vector* banned) { + std::fill(banned->begin(), banned->end(), (char)0); + if (n <= 0 || hl < n) return; + const int64_t win = (window > 0 && window < hl) ? window : hl; + const int64_t start = hl - win, end = hl - n + 1; + if (end <= start) return; + const int64_t plen = n - 1, p0 = hl - plen; + for (int64_t idx = start; idx < end; ++idx) { + bool match = true; + for (int64_t j = 0; j < plen && match; ++j) match = s[idx + j] == s[p0 + j]; + if (!match) continue; + const int32_t tok = s[idx + plen]; + if (tok >= 0 && (size_t)tok < banned->size()) (*banned)[(size_t)tok] = 1; + } +} + +static void sample_ngram_ban_case(const Plugin& pl) { + const char* what = "sample_ngram_ban vs the reference processor, banned columns exact"; + const RadKernelInfo* r = find(pl, "sample_ngram_ban_f32"); + if (!r) { ok(what, false, "row absent"); return; } + + /* Six rows over one 96-token history each. Eight ids spread over the vocabulary (a multiple of + * 7), so n-grams repeat and the banned ids straddle both shards; row 5 copies row 0's first 40 + * tokens into its last 40, which makes the first ban findable far from the end. */ + const int64_t M = 6, H = 96, V = 64; + struct Row { int32_t n; int32_t window; }; + const Row rows[M] = { { 0, 128 }, { 1, 96 }, { 2, 96 }, { 3, 96 }, { 4, 96 }, { 2, 48 } }; + + std::vector hist((size_t)(M * H)); + uint32_t rs = 0x2f6e2b1u; + for (int64_t m = 0; m < M; ++m) { + int32_t* h = &hist[(size_t)(m * H)]; + for (int64_t i = 0; i < H; ++i) { + rs = rs * 1664525u + 1013904223u; + h[i] = (int32_t)(((rs >> 9) % 8u) * 7u); + } + if (m == 5) + for (int64_t i = 0; i < 40; ++i) h[H - 40 + i] = h[i]; + } + + /* Two shard configurations: the whole vocabulary, and this rank holding ids [16, 64). */ + struct Shard { int64_t voff, nv; }; + const Shard shards[2] = { { 0, V }, { 16, V - 16 } }; + + int64_t n_cases = 0, banned_total = 0, mismatches = 0; + std::string first; + for (const Shard& sh : shards) { + const int64_t nv = sh.nv; + + std::vector lg((size_t)(M * nv)); + for (int64_t m = 0; m < M; ++m) + for (int64_t i = 0; i < nv; ++i) + lg[(size_t)(m * nv + i)] = 0.001f * (float)((m * 37 + i) % 511) - 0.25f; + + std::vector sp((size_t)M); + std::memset(sp.data(), 0, sizeof(RadSampleParams) * (size_t)M); + std::vector ng((size_t)(M * 2)); + for (int64_t m = 0; m < M; ++m) { + sp[(size_t)m].temp = 1.0f; + sp[(size_t)m].top_p = 1.0f; + sp[(size_t)m].rep_penalty = 1.0f; + sp[(size_t)m].mask_row = -1; + sp[(size_t)m].hist_off = 0; + sp[(size_t)m].hist_len = (int32_t)H; + ng[(size_t)(2 * m)] = rows[m].n; + ng[(size_t)(2 * m + 1)] = rows[m].window; + } + + void* d_lg = dalloc((size_t)(M * nv) * 4); + void* d_pr = dalloc((size_t)M * sizeof(RadSampleParams)); + void* d_h = dalloc((size_t)(M * H) * 4); + void* d_ng = dalloc((size_t)(M * 2) * 4); + st_memcpy(d_lg, lg.data(), (size_t)(M * nv) * 4, hipMemcpyHostToDevice); + st_memcpy(d_pr, sp.data(), (size_t)M * sizeof(RadSampleParams), hipMemcpyHostToDevice); + st_memcpy(d_h, hist.data(), (size_t)(M * H) * 4, hipMemcpyHostToDevice); + st_memcpy(d_ng, ng.data(), (size_t)(M * 2) * 4, hipMemcpyHostToDevice); + + std::vector ts = { T(d_lg, RAD_F32, { M, nv }), + T(d_pr, RAD_F32, { M, (int64_t)(sizeof(RadSampleParams) / 4) }), + T(d_h, RAD_I32, { M, H }), + T(d_ng, RAD_I32, { M, 2 }) }; + std::vector ps = { PI("M", M), PI("n_vocab", nv), PI("vocab_off", sh.voff) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { ok(what, false, "launch rc=" + std::to_string(rc)); return; } + + std::vector got((size_t)(M * nv), 0.0f); + st_memcpy(got.data(), d_lg, (size_t)(M * nv) * 4, hipMemcpyDeviceToHost); + + std::vector banned((size_t)V, 0); + for (int64_t m = 0; m < M; ++m) { + ngram_ban_ref(&hist[(size_t)(m * H)], H, rows[m].n, rows[m].window, &banned); + for (int64_t i = 0; i < nv; ++i) { + const int64_t g = sh.voff + i; + const size_t k = (size_t)(m * nv + i); + ++n_cases; + const bool want = (size_t)g < banned.size() && banned[(size_t)g] != 0; + if (want) ++banned_total; + const float gv = got[k]; + const bool is_inf = std::isinf(gv) && gv < 0.0f; + if (want != is_inf || (!want && std::memcmp(&gv, &lg[k], 4) != 0)) { + ++mismatches; + if (first.empty()) + first = fmt("row %lld col %lld (id %lld) want %s", (long long)m, + (long long)i, (long long)g, want ? "banned" : "kept"); + } + } + } + /* A token outside this rank's shard is another rank's column and has no column here, so + * the kernel's `col < 0` / `col >= n_vocab` tests skip it: the [0, nv) window above is the + * whole surface the kernel can write, and under `vocab_off` 16 its id space is + * [16, 64). dalloc's buffers are released by the case's dfree_all. */ + } + + std::printf(" ngram_ban: %lld columns over %lld rows x 2 shards, %lld banned, " + "%lld mismatches\n", (long long)n_cases, (long long)M, (long long)banned_total, + (long long)mismatches); + ok(what, mismatches == 0 && banned_total > 0, + "banned=" + std::to_string(banned_total) + " mismatch=" + std::to_string(mismatches) + + (first.empty() ? "" : " " + first)); +} + +/* sam_attn, against a host port of deepencoder.py's attention (get_rel_pos + window_partition). + * + * Two geometries: window 14 on a 16x16 grid (2x2 windows after padding to 28x28, so the zero pad + * rows take part in the softmax) over two segments, and the global form (window 0) on the same + * grid. q/k/v are stored at their own row pitch with a filler column in front, as the tower's three + * column slices of one fused projection are, so a kernel reading q dense fails. */ +static void sam_attn_case(const Plugin& pl) { + const char* what = "sam_attn vs a host port of the reference attention"; + const RadKernelInfo* r = find(pl, "sam_attn_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + struct Geo { int64_t gh, gw, win, nh, hd, nseq; }; + const Geo geos[2] = { { 16, 16, 14, 2, 64, 2 }, { 16, 16, 0, 2, 64, 1 } }; + int64_t checked = 0, bad_total = 0; + float worst = 0.0f; + + for (const Geo& g : geos) { + const int64_t W = g.nh * g.hd, R = g.gh * g.gw, M = g.nseq * R; + const int64_t tab = 2 * (g.win > 0 ? g.win : (g.gh > g.gw ? g.gh : g.gw)) - 1; + /* One filler column, so the row pitch is W + 1: q/k/v/out are all slices. */ + const int64_t ld = W + 1; + const float scale = 1.0f / std::sqrt((float)g.hd); + + std::vector q((size_t)(M * ld)), k((size_t)(M * ld)), v((size_t)(M * ld)); + std::vector rh((size_t)(tab * g.hd)), rw((size_t)(tab * g.hd)); + for (size_t i = 0; i < q.size(); ++i) { + q[i] = st_rand_bf16((uint32_t)i); + k[i] = st_rand_bf16((uint32_t)i + 0x51ed2701u); + v[i] = st_rand_bf16((uint32_t)i + 0xa341316cu); + } + for (size_t i = 0; i < rh.size(); ++i) { + rh[i] = h_to_bf16(0.1f * h_bf16(st_rand_bf16((uint32_t)i + 0x1234567u))); + rw[i] = h_to_bf16(0.1f * h_bf16(st_rand_bf16((uint32_t)i + 0x7654321u))); + } + std::vector cu((size_t)g.nseq + 1); + for (int64_t s = 0; s <= g.nseq; ++s) cu[(size_t)s] = (int32_t)(s * R); + + void* d_q = dalloc(q.size() * 2); + void* d_k = dalloc(k.size() * 2); + void* d_v = dalloc(v.size() * 2); + void* d_o = dalloc((size_t)(M * ld) * 2); + void* d_cu = dalloc(cu.size() * 4); + void* d_rh = dalloc(rh.size() * 2); + void* d_rw = dalloc(rw.size() * 2); + st_memcpy(d_q, q.data(), q.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_k, k.data(), k.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_v, v.data(), v.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_cu, cu.data(), cu.size() * 4, hipMemcpyHostToDevice); + st_memcpy(d_rh, rh.data(), rh.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_rw, rw.data(), rw.size() * 2, hipMemcpyHostToDevice); + + /* The two views: [M, W] at pitch ld. */ + RadTensor tq = T(d_q, RAD_BF16, { M, W }); tq.stride[0] = ld; + RadTensor tk = T(d_k, RAD_BF16, { M, W }); tk.stride[0] = ld; + RadTensor tv = T(d_v, RAD_BF16, { M, W }); tv.stride[0] = ld; + RadTensor to = T(d_o, RAD_BF16, { M, W }); to.stride[0] = ld; + std::vector ts = { tq, tk, tv, T(d_cu, RAD_I32, { g.nseq + 1 }), to, + T(d_rh, RAD_BF16, { tab, g.hd }), + T(d_rw, RAD_BF16, { tab, g.hd }) }; + std::vector ps = { + PI("M", M), PI("head_dim", g.hd), PI("n_head", g.nh), PI("grid_h", g.gh), + PI("grid_w", g.gw), PI("window", g.win), PF("scale", scale), PS("dtype", "bf16"), + }; + run_case(r, ts, ps); + + std::vector oh((size_t)(M * ld)); + st_memcpy(oh.data(), d_o, oh.size() * 2, hipMemcpyDeviceToHost); + + const int64_t th = g.win > 0 ? g.win : g.gh, tw = g.win > 0 ? g.win : g.gw; + const int64_t keys = th * tw; + std::vector logits((size_t)keys), acc((size_t)g.hd); + for (int64_t s = 0; s < g.nseq; ++s) + for (int64_t ih = 0; ih < g.gh; ++ih) + for (int64_t iw = 0; iw < g.gw; ++iw) { + const int64_t row = cu[(size_t)s] + ih * g.gw + iw; + const int64_t ty = g.win > 0 ? ih / g.win : 0; + const int64_t tx = g.win > 0 ? iw / g.win : 0; + const int64_t lh = ih - ty * th, lw = iw - tx * tw; + for (int64_t h = 0; h < g.nh; ++h) { + double qf[256]; + for (int64_t c = 0; c < g.hd; ++c) + qf[c] = h_bf16(q[(size_t)(row * ld + h * g.hd + c)]); + for (int64_t jh = 0; jh < th; ++jh) { + const uint16_t* hrp = &rh[(size_t)((lh - jh + th - 1) * g.hd)]; + double hr = 0.0; + for (int64_t c = 0; c < g.hd; ++c) hr += qf[c] * h_bf16(hrp[c]); + for (int64_t jw = 0; jw < tw; ++jw) { + const uint16_t* wrp = &rw[(size_t)((lw - jw + tw - 1) * g.hd)]; + double sc = hr; + for (int64_t c = 0; c < g.hd; ++c) sc += qf[c] * h_bf16(wrp[c]); + const int64_t kh = ty * th + jh, kw = tx * tw + jw; + if (kh < g.gh && kw < g.gw) { + const int64_t krow = cu[(size_t)s] + kh * g.gw + kw; + double d = 0.0; + for (int64_t c = 0; c < g.hd; ++c) + d += qf[c] * h_bf16(k[(size_t)(krow * ld + h * g.hd + c)]); + sc += scale * d; + } + logits[(size_t)(jh * tw + jw)] = sc; + } + } + double mx = -INFINITY; + for (int64_t j = 0; j < keys; ++j) mx = std::max(mx, logits[(size_t)j]); + double sum = 0.0; + for (int64_t j = 0; j < keys; ++j) { + logits[(size_t)j] = std::exp(logits[(size_t)j] - mx); + sum += logits[(size_t)j]; + } + for (int64_t c = 0; c < g.hd; ++c) acc[(size_t)c] = 0.0; + for (int64_t jh = 0; jh < th; ++jh) { + const int64_t kh = ty * th + jh; + if (kh >= g.gh) continue; + for (int64_t jw = 0; jw < tw; ++jw) { + const int64_t kw = tx * tw + jw; + if (kw >= g.gw) continue; + const double p = logits[(size_t)(jh * tw + jw)] / sum; + const int64_t krow = cu[(size_t)s] + kh * g.gw + kw; + for (int64_t c = 0; c < g.hd; ++c) + acc[(size_t)c] += + p * h_bf16(v[(size_t)(krow * ld + h * g.hd + c)]); + } + } + for (int64_t c = 0; c < g.hd; ++c) { + const float got = h_bf16(oh[(size_t)(row * ld + h * g.hd + c)]); + const float diff = std::fabs(got - (float)acc[(size_t)c]); + worst = std::max(worst, diff); + ++checked; + if (diff > 1e-3f + 2e-2f * std::fabs((float)acc[(size_t)c])) ++bad_total; + } + } + } + dfree_all(); + } + std::printf(" sam_attn: %lld values, max_err=%.5g, %lld outside the house tolerance\n", + (long long)checked, (double)worst, (long long)bad_total); + ok(what, bad_total == 0 && checked > 0, + "bad=" + std::to_string(bad_total) + "/" + std::to_string(checked)); +} + /* qsa_select, against a host sort of the same scores. * * Focused on ties and the tail. Block scores (sums of relus over a shared grid) tie often, so the @@ -24585,6 +24875,16 @@ static void device_phase(const Plugin& pl) { sample_argmax_case(pl); } + if (sel("sample_ngram_ban_f32")) { + if (!g_case) std::printf("\nthe n-gram ban, against the reference processor\n"); + sample_ngram_ban_case(pl); + } + + if (sel("sam_attn_bf16")) { + if (!g_case) std::printf("\nthe SAM tower attention, against a host port of the reference\n"); + sam_attn_case(pl); + } + if (sel("qsa_work_bf16")) { if (!g_case) std::printf("\nthe QSA work list, against a host walk of the batch\n"); qsa_work_case(pl); diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 8f3712e6..98e6dde7 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -625,7 +625,9 @@ int ref_conv2d_unfold(const RadArgs* a, RadStream) { if (T <= 0) continue; const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st; if (To <= 0) continue; - if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE; + if (t0 + T > Min || (o0 + To) * Wo > Mout) { + return RAD_E_SHAPE; + } if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE; REF_PAR_FOR(To * Wo * K) diff --git a/libref/ref_ops.h b/libref/ref_ops.h index be06287d..82b555cb 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -148,6 +148,8 @@ int ref_attn_cross (const RadArgs*, RadStream); int ref_table_add (const RadArgs*, RadStream); int ref_mix_rows (const RadArgs*, RadStream); int ref_chan_stats (const RadArgs*, RadStream); +/* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position (ref_sam_attn.cpp). */ +int ref_sam_attn (const RadArgs*, RadStream); int ref_kv_store (const RadArgs*, RadStream); int ref_rope (const RadArgs*, RadStream); int ref_rope_table (const RadArgs*, RadStream); @@ -276,6 +278,7 @@ void ref_collective_fini(void*); /* ---- sampling */ int ref_sample_penalties (const RadArgs*, RadStream); int ref_sample_dry (const RadArgs*, RadStream); +int ref_sample_ngram_ban (const RadArgs*, RadStream); int ref_sample_temp (const RadArgs*, RadStream); int ref_sample_topk (const RadArgs*, RadStream); int ref_sample_topp (const RadArgs*, RadStream); @@ -391,6 +394,7 @@ REF_SHAPE_FN(ref_attn_cross); REF_SHAPE_FN(ref_table_add); REF_SHAPE_FN(ref_mix_rows); REF_SHAPE_FN(ref_chan_stats); +REF_SHAPE_FN(ref_sam_attn); REF_SHAPE_FN(ref_kv_store); REF_SHAPE_FN(ref_rope); REF_SHAPE_FN(ref_rope_table); @@ -496,6 +500,7 @@ REF_SHAPE_FN(ref_all_gather); REF_SHAPE_FN(ref_sample_penalties); REF_SHAPE_FN(ref_sample_dry); +REF_SHAPE_FN(ref_sample_ngram_ban); REF_SHAPE_FN(ref_sample_temp); REF_SHAPE_FN(ref_sample_topk); REF_SHAPE_FN(ref_sample_topp); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index 797ea083..e18d68a7 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -375,6 +375,16 @@ static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT(" P_INT("kw"), P_STR("dtype"), P_F64O("scale") }; static const RadOperandSpec oAttnNa3d[] = { OPD("q"), OPD("k"), OPD("v"), OPD("geom"), OUT("out") }; +/* The SAM tower's attention. `q`, `k` and `v` are the three column slices of one fused projection, + * so each is read at its own row pitch. The two rel_pos tables are weights: [2*L-1, head_dim] with + * L the window (or the grid for a global layer), resampled along dim 0 when a geometry needs it. + * `grid_h` x `grid_w` rows a segment, `window` 0 for a whole-segment tile. */ +static const RadParamSpec pSamAttn[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"), + P_INT("grid_h"), P_INT("grid_w"), P_INT("window"), + P_F64("scale"), P_STR("dtype") }; +static const RadOperandSpec oSamAttn[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"), + OUT("out"), WGT("rel_pos_h"), WGT("rel_pos_w") }; + /* `k_scale` and `v_scale` are the descales an fp8 cache is read back with, so a store divides by * them; optional because a bf16 cache has none. */ static const RadParamSpec pKvStore[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head_kv"), @@ -694,6 +704,9 @@ static const RadOperandSpec oPenalties[] = { INOUT("logits"), OPD("params"), OPD * is a whole DRY sequence breaker and never penalised. Absent, no token is exempt. */ static const RadOperandSpec oDry[] = { INOUT("logits"), OPD("params"), OPD("history"), OPD_O("breakers") }; +/* The windowed n-gram ban: penalties' operands plus a {n, window} pair a row. */ +static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"), + OPD("ngram") }; static const RadOperandSpec oTemp[] = { INOUT("logits"), OPD("params") }; /* `bitmask` is [rows, ceil(n_vocab/32)] uint32, addressed by the row's mask_row -- which is -1 for * an unconstrained sequence, so the plane is shared and shorter than M. */ @@ -1308,6 +1321,14 @@ static const RadOpSchema kSchemas[] = { { "attn_na3d", ARR(pAttnNa3d), ARR(oAttnNa3d), "3-D neighborhood attention (NATTEN's na3d) over the voxels of geom = (T, H, W): a query sees the " "kt x kh x kw window centred on it, shifted inward at the border, each extent at most its axis." }, +{ "sam_attn", ARR(pSamAttn), ARR(oSamAttn), + "Unlimited-OCR's SAM tower attention: per cu segment of grid_h*grid_w rows in raster grid order, " + "pad to multiples of `window` with ZERO rows (window_partition, after norm1), cut into window x " + "window tiles and attend each tile to all of its rows; `window` 0 is one tile over the segment. " + "logits = scale*q.k + q.Rh[i_h,j_h] + q.Rw[i_w,j_w], dotted over the head's whole head_dim, " + "softmax in f32 over the tile's keys (pad keys included), out = sum p*v, written back in segment " + "row order with pad rows dropped. The tables are [2*L-1, head_dim], linearly resampled along " + "dim 0 when a geometry's axes need it (get_rel_pos)." }, { "kv_store", ARR(pKvStore), ARR(oKvStore), "Writes k and v into the paged cache at slot_mapping; a negative slot is skipped. The cache is " "INOUT rather than the OUT docs/OPS.md draws, because the op touches only the mapped slots." }, @@ -1515,6 +1536,12 @@ static const RadOpSchema kSchemas[] = { "repeats capped at the row's dry_rep_limit. Only lengths at or above allowed_length count, and " "a token the optional `breakers` plane marks is never penalised. dry_penalty_last_n windows the " "TAIL of the history; 0 turns the stage off for the row. Columns are ids less vocab_off." }, +{ "sample_ngram_ban", ARR(pPenal), ARR(oNgramBan), + "The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor): bans, " + "by setting -infinity, every token that would complete an n-gram the last `window` tokens of " + "the row's history already contain. `ngram` is one i32 {n, window} pair a row; the window " + "bounds the n-gram's START index, as in the reference, window <= 0 searches the whole span and " + "n 0 is off. Columns are ids less vocab_off." }, { "sample_temp", ARR(pMVocab), ARR(oTemp), "logits /= temp, per row. temp <= 0 leaves the row untouched -- greedy decoding is " "sample_argmax, and a temperature of zero silently meaning something else is how a sampler " @@ -2118,6 +2145,9 @@ SIMPLE("ref_attn_cross", "attn_cross", "attn", ref_attn_cross), SIMPLE("ref_attn_na3d", "attn_na3d", "attn", "3-D neighborhood attention over a volume", DT_FLOAT, ref_attn_na3d), +SIMPLE("ref_sam_attn", "sam_attn", "attn", + "SAM tower attention: windowed tiles with decomposed relative position", DT_FLOAT, + ref_sam_attn), ROW("ref_kv_store", "kv_store", "attn", "scatter k and v into the paged cache", DT_ANY, cPagedBlock, (int)(sizeof(cPagedBlock) / sizeof(cPagedBlock[0])), nullptr, nullptr, ref_kv_store, nullptr), @@ -2223,6 +2253,8 @@ SIMPLE("ref_sample_logprobs", "sample_logprobs", "sample", "the raw distribution DT_FLOAT, ref_sample_logprobs), SIMPLE("ref_sample_dry", "sample_dry", "sample", "DRY repetition-suffix penalty", DT_FLOAT, ref_sample_dry), +SIMPLE("ref_sample_ngram_ban", "sample_ngram_ban", "sample", + "windowed no-repeat-ngram ban", DT_FLOAT, ref_sample_ngram_ban), SIMPLE("ref_sample_typical", "sample_typical", "sample", "locally typical narrowing in place", DT_FLOAT, ref_sample_typical), SIMPLE("ref_sample_xtc", "sample_xtc", "sample", "exclude-top-choices narrowing in place", diff --git a/libref/ref_sam_attn.cpp b/libref/ref_sam_attn.cpp new file mode 100644 index 00000000..a279cfcc --- /dev/null +++ b/libref/ref_sam_attn.cpp @@ -0,0 +1,197 @@ +/* ref_sam_attn.cpp -- Unlimited-OCR's DeepEncoder (SAM ViT-B/16) attention with decomposed relative + * position (arch/common/rad_block_sam.h). + * + * The reference is the checkpoint's own deepencoder.py (Attention.forward and + * add_decomposed_rel_pos), whose logits are + * + * scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w] + * + * where Rh = get_rel_pos(rel_pos_h, q_h, k_h) indexes the table at (i_h - j_h + len - 1) and the dot + * runs over the whole head_dim of the head's own q (deepencoder computes r_q of shape + * (B*heads, q_h, q_w, head_dim) and einsums "bhwc,hkc->bhwk"). So the per-pair term folds into + * neither q, k nor v: no plain attention op can carry it, which is why this op exists. + * + * ============================== Windows ============================== + * + * Each cu segment is grid_h * grid_w rows in row-major grid order. With `window` > 0 the segment is + * padded to multiples of `window` with ZERO rows and cut into window x window tiles, exactly as + * window_partition does after norm1: the pad rows are keys AND values of their tile, so their + * logits (which carry the rel terms even though q.k is 0) take part in the softmax, and their v is + * zero. `window` 0 is one tile over the whole segment (the reference's global blocks). + * + * ============================== Table resizing ============================== + * + * get_rel_pos linearly interpolates the table along dim 0 when its length is not + * 2*max(q,k) - 1 (F.interpolate, mode linear, align_corners False). Every geometry the tower + * declares matches exactly, but a non-square global grid has axes of different extents, so the + * resampling is implemented here rather than assumed away. + * + * ============================== Numerics ============================== + * + * f32 throughout: q, k, v and the tables are widened once, every dot and softmax accumulates in + * f32 with the max subtracted, and the output is rounded once to the operand's dtype. Summation + * order is fixed (increasing channel, then key), so two runs agree bit for bit at any thread count. + */ +#include "ref_common.h" +#include "ref_ops.h" + +#include +#include +#include + +using namespace ref; + +namespace { + +/* A rel_pos table as f32 rows of `hd`, resampled to `want` rows when its own length differs. + * F.interpolate(..., size=want, mode="linear") with align_corners False: output d samples the input + * at (d + 0.5) * rows / want - 0.5, clamped to the ends, linearly between the neighbours. */ +static std::vector table_rows(const RadTensor* t, int64_t hd, int64_t want) { + const int64_t rows = hd > 0 ? numel(t) / hd : 0; + std::vector raw((size_t)(rows * hd), 0.0f); + const int64_t st = laststride(t); + for (int64_t r = 0; r < rows; ++r) { + const int64_t base = rowoff(t, r, hd); + for (int64_t c = 0; c < hd; ++c) raw[(size_t)(r * hd + c)] = ldt(t, base + c * st); + } + if (rows == want || rows <= 0 || want <= 0) return raw; + std::vector out((size_t)(want * hd), 0.0f); + const double span = (double)rows / (double)want; + for (int64_t d = 0; d < want; ++d) { + double src = ((double)d + 0.5) * span - 0.5; + if (src < 0.0) src = 0.0; + if (src > (double)(rows - 1)) src = (double)(rows - 1); + const int64_t i0 = (int64_t)src; + const int64_t i1 = i0 + 1 < rows ? i0 + 1 : i0; + const float f = (float)(src - (double)i0); + for (int64_t c = 0; c < hd; ++c) { + const float a = raw[(size_t)(i0 * hd + c)], b = raw[(size_t)(i1 * hd + c)]; + out[(size_t)(d * hd + c)] = a + (b - a) * f; + } + } + return out; +} + +} /* namespace */ + +/* See the file header for the semantics. `cu_seqlens` absent is one segment of every row: the + * reference's single-view form. */ +int ref_sam_attn(const RadArgs* a, RadStream) { + if (!have(a, 7)) return RAD_E_INVAL; + const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3]; + const RadTensor *o = &a->t[4], *th_tab = &a->t[5], *tw_tab = &a->t[6]; + + const int64_t hd = p_int(a, "head_dim", 0); + const int64_t nh = p_int(a, "n_head", 0); + const int64_t gh = p_int(a, "grid_h", 0); + const int64_t gw = p_int(a, "grid_w", 0); + const int64_t win = p_int(a, "window", 0); + if (hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_SHAPE; + const int64_t W = nh * hd, R = gh * gw; + if (!q->data || !k->data || !v->data || !o->data || !th_tab->data || !tw_tab->data) + return RAD_E_INVAL; + for (const RadTensor* t : { q, k, v, o }) + if (t->rank < 2 || t->shape[t->rank - 1] != W) return RAD_E_SHAPE; + const int64_t M = numel(q) / W; + if (M <= 0) return RAD_E_SHAPE; + if (numel(k) != M * W || numel(v) != M * W || numel(o) < M * W) return RAD_E_SHAPE; + + /* Segments: cu[s]..cu[s+1], each exactly one grid. */ + int64_t nseq = 1; + if (cu->data) { + if (cu->rank == 0 || numel(cu) < 2) return RAD_E_SHAPE; + nseq = numel(cu) - 1; + if (cu_at(cu, 0) != 0 || cu_at(cu, nseq) != M) return RAD_E_SHAPE; + for (int64_t s = 0; s < nseq; ++s) + if (cu_at(cu, s + 1) - cu_at(cu, s) != R) return RAD_E_SHAPE; + } else if (M != R) { + return RAD_E_SHAPE; + } + + const float scale = p_f32(a, "scale", (float)(1.0 / std::sqrt((double)hd))); + + /* The tile geometry: window x window, or the whole grid. Table lengths follow the tile axes. */ + const int64_t th = win > 0 ? win : gh, tw = win > 0 ? win : gw; + const int64_t keys = th * tw; + if (numel(th_tab) < hd || numel(tw_tab) < hd) return RAD_E_SHAPE; + std::vector Rh = table_rows(th_tab, hd, 2 * th - 1); + std::vector Rw = table_rows(tw_tab, hd, 2 * tw - 1); + + /* Every (channel-ordered) dot is written out in one place so the order is explicit: q[c] times + * the row's element c, increasing c. */ + auto dot = [hd](const float* x, const float* y) { + float s = 0.0f; + for (int64_t c = 0; c < hd; ++c) s += x[c] * y[c]; + return s; + }; + + /* One thread owns one output row; the work unit is about keys * head_dim per head. */ + REF_PAR_FOR(nseq * R * nh * keys * hd) + for (int64_t work = 0; work < nseq * R; ++work) { + const int64_t s = work / R, r = work % R; + const int64_t ih = r / gw, iw = r % gw; + const int64_t ty = win > 0 ? ih / win : 0, tx = win > 0 ? iw / win : 0; + const int64_t lh = ih - ty * th, lw = iw - tx * tw; + const int64_t base = cu->data ? cu_at(cu, s) : 0; + const int64_t out_row = base + r; + + /* logits[keys], qt[hd], acc[hd]. */ + float* buf = ws_get(keys + 2 * hd); + float* logits = buf; + float* qt = buf + keys; + float* acc = qt + hd; + + for (int64_t h = 0; h < nh; ++h) { + const int64_t qbase = rowoff(q, out_row, W) + h * hd; + const int64_t qst = laststride(q); + for (int64_t c = 0; c < hd; ++c) qt[c] = ldt(q, qbase + c * qst); + + for (int64_t jh = 0; jh < th; ++jh) { + const float hr = dot(qt, &Rh[(size_t)((lh - jh + th - 1) * hd)]); + for (int64_t jw = 0; jw < tw; ++jw) { + float lgt = hr + dot(qt, &Rw[(size_t)((lw - jw + tw - 1) * hd)]); + const int64_t kh = ty * th + jh, kw = tx * tw + jw; + if (kh < gh && kw < gw) { + const int64_t krow = base + kh * gw + kw; + const int64_t kb = rowoff(k, krow, W) + h * hd; + const int64_t ks = laststride(k); + float s_ = 0.0f; + for (int64_t c = 0; c < hd; ++c) s_ += qt[c] * ldt(k, kb + c * ks); + lgt += scale * s_; + } + logits[jh * tw + jw] = lgt; + } + } + + /* Softmax in f32 with the max subtracted, then the weighted sum of v. */ + float m = -INFINITY; + for (int64_t j = 0; j < keys; ++j) m = logits[j] > m ? logits[j] : m; + float sum = 0.0f; + for (int64_t j = 0; j < keys; ++j) { + logits[j] = ref_exp(logits[j] - m); + sum += logits[j]; + } + for (int64_t c = 0; c < hd; ++c) acc[c] = 0.0f; + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t jh = 0; jh < th; ++jh) { + const int64_t kh = ty * th + jh; + if (kh >= gh) continue; /* pad rows carry v = 0 */ + for (int64_t jw = 0; jw < tw; ++jw) { + const int64_t kw = tx * tw + jw; + if (kw >= gw) continue; + const float p = logits[jh * tw + jw] * inv; + if (p == 0.0f) continue; + const int64_t krow = base + kh * gw + kw; + const int64_t vb = rowoff(v, krow, W) + h * hd; + const int64_t vs = laststride(v); + for (int64_t c = 0; c < hd; ++c) acc[c] += p * ldt(v, vb + c * vs); + } + } + + const int64_t ob = rowoff(o, out_row, W) + h * hd; + const int64_t os = laststride(o); + for (int64_t c = 0; c < hd; ++c) stt(o, ob + c * os, acc[c]); + } + } + return RAD_OK; +} diff --git a/libref/ref_sample.cpp b/libref/ref_sample.cpp index dc0091bd..536977ba 100644 --- a/libref/ref_sample.cpp +++ b/libref/ref_sample.cpp @@ -235,6 +235,86 @@ int ref_sample_dry(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ sample_ngram_ban */ +/* The windowed no-repeat-ngram ban: Unlimited-OCR's `SlidingWindowNoRepeatNgramProcessor` + * (modeling_unlimitedocr.py:353-383), which SGLang ships as + * DeepseekOCRNoRepeatNGramLogitProcessor. With the row's history `s[0, hl)` (oldest first, `hl` + * committed tokens including the one just emitted), `n` and `w` from the `ngram` plane (an i32 + * pair a row, {n-gram length, window}): + * + * search_start = max(0, hl - w) (w <= 0: the whole span) + * search_end = hl - n + 1 + * prefix = s[hl - n + 1, hl) (empty at n == 1) + * for idx in [search_start, search_end): + * if s[idx, idx + n - 1) == prefix: ban s[idx + n - 1] + * + * A banned token's logit becomes -infinity, exactly as the reference writes it, so the argmax and + * every later stage see the same distribution. The n-gram that spans the window boundary is one + * of the searched ones, as in the reference: the window is applied to the START index, not to the + * n-gram's end. + * + * Ids are global and columns are global less `vocab_off`; a banned token on another rank's shard + * is that rank's to mask. Rows whose n is 0 (the default) are untouched, so a request without the + * ban leaves the logits bit for bit as they were. The scan is O(w * n) a row and compares + * integers, so every implementation (this one, libavx, libr4d) agrees by construction. */ +int ref_sample_ngram_ban(const RadArgs* a, RadStream) { + if (!have(a, 4)) return RAD_E_INVAL; + const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2], *ng = &a->t[3]; + const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0); + if (n_vocab <= 0) return RAD_E_SHAPE; + const int64_t M = numel(lg) / n_vocab; + if (M <= 0) return RAD_E_SHAPE; + Rows R; + RAD_REF_TRY(param_rows(pr, M, &R)); + const int64_t hmax = numel(hist) / M; + if (hmax <= 0) return RAD_E_SHAPE; + /* One {n, window} pair a row. At least M pairs, so a plane shared by sparser row sets is not + * read past its end. */ + if (numel(ng) < 2 * M) return RAD_E_SHAPE; + const int64_t voff = p_int(a, "vocab_off", 0); + + REF_PAR_FOR(M * hmax) + for (int64_t m = 0; m < M; ++m) { + const RadSampleParams& sp = R.p[m]; + const int64_t nb = rowoff(ng, m, 2), ns = laststride(ng); + const int64_t n = ld_int(ng->dtype, ng->data, nb); + const int64_t win_req = ld_int(ng->dtype, ng->data, nb + ns); + if (n <= 0) continue; + + /* The whole staged span; the window below keeps its tail. last_n -1 is hist_window's + * "the whole span". */ + int64_t ho = 0, hl = 0; + if (!hist_window(sp, -1, hmax, &ho, &hl)) continue; + if (hl < n) continue; + const int64_t win = win_req > 0 && win_req < hl ? win_req : hl; + const int64_t search_start = hl - win; + const int64_t search_end = hl - n + 1; + if (search_end <= search_start) continue; + + const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist); + const int64_t hs = laststride(hist); + const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg); + auto tok_at = [&](int64_t i) { + return ld_int(hist->dtype, hist->data, hb + i * hs); + }; + /* n == 1 bans every token in the window: the prefix is empty, as in the reference. */ + const int64_t plen = n - 1, p0 = hl - plen; + + for (int64_t idx = search_start; idx < search_end; ++idx) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (tok_at(idx + j) != tok_at(p0 + j)) { match = false; break; } + } + if (!match) continue; + const int64_t tok = tok_at(idx + plen); + const int64_t col = tok - voff; + if (tok < 0 || col < 0 || col >= n_vocab) continue; + stt(lg, lb + col * ls, -INFINITY); + } + } + return RAD_OK; +} + /* ------------------------------------------------------------------ sample_temp */ /* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */ int ref_sample_temp(const RadArgs* a, RadStream) { diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index 9525055c..a58403c4 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -1382,6 +1382,37 @@ int ref_chan_stats_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return o.finish("chan_stats", operand, out); } +/* The SAM tower's attention (ref_sam_attn.cpp): a row of `n_head * head_dim`, one raster + * grid_h x grid_w segment a cu entry, and the two rel_pos tables. Their length follows the contract + * in arch/common/rad_block_sam.h: 2*maxdist-1 rows with maxdist the window, or the longer grid axis + * for a global layer (which is the length a resampled table needs; the op resamples along dim 0 + * either way). */ +int ref_sam_attn_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0); + const int64_t hd = gi(p, n_p, "head_dim", 0); + const int64_t nh = gi(p, n_p, "n_head", 0); + const int64_t gh = gi(p, n_p, "grid_h", 0); + const int64_t gw = gi(p, n_p, "grid_w", 0); + const int64_t win = gi(p, n_p, "window", 0); + if (M <= 0 || hd <= 0 || nh <= 0 || gh <= 0 || gw <= 0 || win < 0) return RAD_E_UNSUPPORTED; + const int64_t W = nh * hd; + const int64_t S = n_seq_of(p, n_p); + const int64_t maxd = win > 0 ? win : (gh > gw ? gh : gw); + const int64_t tab = 2 * maxd - 1; + const uint32_t D = act_dt(p, n_p); + + Opd o; + o.t(D, { M, W }); /* q */ + o.t(D, { M, W }); /* k */ + o.t(D, { M, W }); /* v */ + /* [0, ..., M], the batch's shape, not a draw. */ + o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */ + o.t(D, { M, W }); /* out */ + o.t(D, { tab, hd }); /* rel_pos_h */ + o.t(D, { tab, hd }); /* rel_pos_w */ + return o.finish("sam_attn", operand, out); +} + int ref_kv_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t hd = gi(p, n_p, "head_dim", 0); @@ -2352,6 +2383,23 @@ int ref_sample_dry_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou return penalty_shape(p, n_p, operand, "sample_dry", true, out); } +/* The n-gram ban reads the same history the two penalty stages do and writes the logits in place, + * and adds one small plane beside them: `ngram`, an i32 {n-gram length, window} pair a row. It is + * a plane of its own rather than fields in `params` because the params row is a fixed 24-word wire + * format shared by every sampler op (and recorded in the kbench fixtures). Drawn in 0..63 so both + * a length inside the 64-token history and the 0 (= off) and whole-window forms occur. */ +int ref_sample_ngram_ban_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + int64_t M = 0, nv = 0; + if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t((uint32_t)RAD_F32, { M, nv }); /* logits, INOUT */ + sample_params(o, M, REF_SAMPLE_HIST, 0); /* params */ + o.t_idx({ M, (int64_t)REF_SAMPLE_HIST }, nv, -1, + (uint32_t)RAD_OPD_F_IDX_HISTORY); /* history */ + o.t_idx({ M, 2 }, 64, -1, 0); /* ngram: {n, window} */ + return o.finish("sample_ngram_ban", operand, out); +} + int ref_sample_temp_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { int64_t M = 0, nv = 0; if (sample_vocab(p, n_p, &M, &nv) < 0) return RAD_E_UNSUPPORTED; diff --git a/tests/advance_test.cpp b/tests/advance_test.cpp index 2e17a85b..a92af4ce 100644 --- a/tests/advance_test.cpp +++ b/tests/advance_test.cpp @@ -18,7 +18,7 @@ using namespace rad; namespace { -static_assert(sizeof(AdvGroup) == 48, "AdvGroup's layout is part of the card's slab"); +static_assert(sizeof(AdvGroup) == 72, "AdvGroup's layout is part of the card's slab"); /* Word offsets of every array the advance reads or writes. Up to kSeq rows, kTok tokens and * kGroups KV groups, each group with a kPitch-entry block table per row. */ @@ -35,8 +35,8 @@ struct Slab { CU = SID + kSeq, Q = CU + kSeq + 8, ROPE = Q + kSeq, /* [3][kTok] */ - GRP = ROPE + 3 * kTok, /* [kGroups] AdvGroup, 12 words each */ - SLOT = GRP + 12 * kGroups, /* [kGroups][kTok] */ + GRP = ROPE + 3 * kTok, /* [kGroups] AdvGroup, sizeof/4 words each */ + SLOT = GRP + (int)(sizeof(AdvGroup) / 4) * kGroups, /* [kGroups][kTok] */ USED = SLOT + kGroups * kTok, /* [kGroups][kSeq] */ BT = USED + kGroups * kSeq, /* [kGroups][kSeq][kPitch] */ FIRST = BT + kGroups * kSeq * kPitch, /* [kGroups][kSeq] */ diff --git a/tests/gen_config_test.cpp b/tests/gen_config_test.cpp index 3d1e238d..7e3a452a 100644 --- a/tests/gen_config_test.cpp +++ b/tests/gen_config_test.cpp @@ -206,4 +206,56 @@ TEST(gen_config_derives_the_sidecar_path) { CHECK_EQ(gen_sidecar_path("/a.b/model.rad"), std::string("/a.b/model.generation.json")); } +/* Unlimited-OCR's generation_config.json, verbatim: it states no temperature or top-k, only the + * windowed no-repeat-n-gram ban, so it must be claimed as stated (or the ban would never reach a + * request that sends no sampler fields). `do_sample: false` still means greedy and ignores it. */ +TEST(gen_config_reads_the_ngram_ban) { + const char* const kUnlimitedOcr = R"({ + "bos_token_id": 0, + "eos_token_id": 1, + "no_repeat_ngram_size": 35, + "no_repeat_ngram_window_size": 128, + "max_new_tokens": 32768, + "use_cache": true +})"; + GenSampling g; + CHECK(gen_sampling_parse(kUnlimitedOcr, "test", &g)); + CHECK_EQ(g.ngram_ban_n, 35); + CHECK_EQ(g.ngram_window, 128); + CHECK(g.temp < 0.0f); + const SamplingParams sp = g.onto(SamplingParams{}); + CHECK_EQ(sp.ngram_ban_n, 35); + CHECK_EQ(sp.ngram_window, 128); + CHECK(GenSampling::describe(sp).find("ngram ban n 35 over the last 128 tokens") != + std::string::npos); + + /* The container's flattened copy reads the same. */ + GenSampling kv; + CHECK(gen_sampling_from_kv(kv_of({ { "no_repeat_ngram_size", "35" }, + { "no_repeat_ngram_window_size", "128" } }), + &kv)); + CHECK_EQ(kv.ngram_ban_n, 35); + CHECK_EQ(kv.ngram_window, 128); + + /* This sampler's spellings, and the reference's negative window as "the whole sequence". */ + GenSampling own; + CHECK(gen_sampling_parse(R"({"ngram_ban_n": 35, "ngram_window": -1})", "test", &own)); + CHECK_EQ(own.ngram_ban_n, 35); + CHECK_EQ(own.ngram_window, 0); + + /* A size outside [0, 256] is dropped on its own; the window still reads. */ + GenSampling bad; + CHECK(gen_sampling_parse(R"({"no_repeat_ngram_size": 5000, + "no_repeat_ngram_window_size": 128})", "test", &bad)); + CHECK_EQ(bad.ngram_ban_n, -1); + CHECK_EQ(bad.ngram_window, 128); + + /* do_sample false is greedy: transformers ignores the ban under it, and so does this. */ + GenSampling greedy; + CHECK(gen_sampling_parse(R"({"do_sample": false, "no_repeat_ngram_size": 35})", "test", + &greedy)); + CHECK_EQ(greedy.ngram_ban_n, -1); + CHECK_EQ(greedy.onto(SamplingParams{}).ngram_ban_n, 0); +} + RAD_TEST_MAIN() diff --git a/tests/kv_window_test.cpp b/tests/kv_window_test.cpp new file mode 100644 index 00000000..75f17b91 --- /dev/null +++ b/tests/kv_window_test.cpp @@ -0,0 +1,463 @@ +/* kv_window_test.cpp -- the runtime per-sequence window on a RAD_KV_WINDOW group (R-SWA). + * + * R-SWA (Unlimited-OCR) keeps a sequence's whole prefill as a retained reference and decodes into + * a ring of W slots right after it: visible = [0, prefill) U [prefill, prefill + W). The reference + * is never recycled, the ring rewrites its slots in place, and RoPE positions keep increasing -- + * only the block/slot mapping recycles. These tests pin the manager's side of that: the visible + * token set, flat bytes after the floor is set, the recycling boundary, the exclusion from the + * prefix cache and snapshots, and that a fixed-window group (gemma4's) is exactly what it was. + */ +#include "rad_test.h" + +#include "mem/kv.h" +#include "mem/pools.h" +#include "sched/advance_impl.h" +#include "sched/mem_iface.h" +#include "rad_internal.h" + +#include +#include +#include +#include + +using namespace rad; + +/* Handle 0 is the null group (see mem_test): a real group at index 0 would read as "no group". */ +enum : int32_t { G_NULL = 0, G_WIN = 1 }; + +static Config window_config() { + Config c; + c.vram_weights_mib = 1; + c.vram_kv_mib = 4; /* 4 MiB: an 8 KiB page at block 128, room for 4 x 4096 tokens */ + c.gpu_headroom_mib = 1; + c.host_pool_mib = 0; + c.max_seqs = 4; + c.max_tok = 128; /* one block a step, as a decode deployment */ + c.max_ctx = 4096; + c.checkpoint_interval = 512; + c.prefix_cache = true; + return c; +} + +/* A single windowed group of one layer at `block` (page block*2*8*2*2 bytes), so a test can use + * the geometry R-SWA runs at: block_size 128 = W. */ +static KVGroupInfo window_group(int64_t block, int64_t declared_window) { + KVGroupInfo k; + k.name = "rswa"; + k.decl.kind = RAD_KV_WINDOW; + k.decl.dtype = RAD_BF16; + k.decl.n_head_kv = 2; + k.decl.head_dim = 8; + k.decl.window = declared_window; + k.block_size = block; + k.layers = { 0 }; + return k; +} + +static std::vector groups_of(const KVGroupInfo& g) { + std::vector v; + v.push_back(KVGroupInfo{}); + v.push_back(g); + return v; +} + +static int configure_pools(Pools& p, const Config& c) { + return p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator()); +} + +/* A sequence's slot for `pos`, through the rule the step batch uses (KVGeom::slot_ring). */ +struct Ring { + KVManager* kv; + KVGeom geo; + int32_t g = G_WIN; + + bool has_window() const { return kv->runtime_window(1, g, nullptr); } + SeqWindow window() const { + SeqWindow w; + kv->runtime_window(1, g, &w); + return w; + } + int32_t slot(int64_t pos) const { + SeqWindow w; + if (!kv->runtime_window(1, g, &w)) return -1; + return geo.slot_ring(g, kv->block_table(1, g), kv->first_block_pos(1, g), pos, w); + } +}; + +TEST(rswa_reference_and_ring_keeps_the_visible_set_and_flat_bytes) { + const int64_t B = 128, W = 128, P = 400; /* P is not a block multiple on purpose */ + const KVGroupInfo grp = window_group(B, W); + const std::vector g = groups_of(grp); + Config cfg = window_config(); + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_WIN, W)); + CHECK_OK(kv.configure(g, cfg, pools.kv())); + + /* A runtime-window group keeps no window snapshot: the window is the sequence's own data. */ + CHECK(kv.plan(G_WIN)->runtime_win); + CHECK_EQ(kv.plan(G_WIN)->runtime_tokens, W); + CHECK(!kv.plan(G_WIN)->win_snap); + CHECK(!kv.has_window_snapshot()); + CHECK_EQ(kv.checkpoint_bytes(), 0ll); + CHECK_EQ(kv.runtime_window_tokens(G_WIN), W); + /* Sized for the context plus one ring a sequence, not capped at window_blocks. */ + CHECK(kv.total_blocks(G_WIN) >= cfg.max_seqs * (cfg.max_ctx / B + 1)); + + CHECK_OK(kv.add_sequence(1)); + CHECK_OK(kv.set_window(1, P, W)); + const Ring r{ &kv, KVGeom::of(g), G_WIN }; + CHECK(r.has_window()); + const SeqWindow w = r.window(); + CHECK_EQ(w.visible_lo, P); + /* Whole blocks: the ring starts at the first boundary at or after the floor, and the tokens + * in [P, ring_pos) stay in the reference's last block. */ + CHECK_EQ(w.ring_pos, 512ll); + CHECK_EQ(w.ring_blocks, 1ll); + CHECK_EQ(w.ring_span(B), 128ll); + + /* Prefill: the reference is written linearly; the table is ceil(P / B) blocks. */ + CHECK_OK(kv.ensure(1, P)); + CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 4ll); + std::map content; /* slot -> position it holds */ + for (int64_t p = 0; p < P; ++p) { + const int32_t s = r.slot(p); + REQUIRE(s >= 0); + content[s] = p; + } + + /* Generate L tokens. The visible set must be [0, P) plus, in the ring, the newest ring_span + * positions: [0, P) U [P, ring_pos) (frozen: written once, kept) U the last `span` of + * [ring_pos, n). Block granularity is the accepted consequence -- with W = 128 and block 128 + * the visible tail is 112 frozen + 128 ring = 240 tokens, always W..W+B-1 = 128..255 and a + * superset of the reference implementation's last 128. Once n >= ring_pos + span the set is + * exactly that, so the test asserts equality. */ + const int64_t L = 2000; + int64_t flat_blocks = -1; + int64_t bad_step = -1; + for (int64_t p = P; p < P + L && bad_step < 0; ++p) { + CHECK_OK(kv.ensure(1, p + 1, p)); + const int32_t s = r.slot(p); + REQUIRE(s >= 0); + content[s] = p; + const int64_t n = p + 1; + + /* The table never moves and the floor stays 0: only slots recycle. */ + CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll); + const int64_t want_blocks = + n <= w.ring_pos ? (n + B - 1) / B + : w.ring_pos / B + std::min(w.ring_blocks, + (n - w.ring_pos + B - 1) / B); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), want_blocks); + + /* Bytes are flat once the ring is full: no block is allocated past it, ever. */ + if (n >= w.ring_pos + w.ring_span(B)) { + if (flat_blocks < 0) flat_blocks = (int64_t)kv.block_table(1, G_WIN).size(); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), flat_blocks); + CHECK_EQ(kv.held_blocks(G_WIN), flat_blocks); + } + + /* The slots hold exactly the rule's set. */ + std::set held, want; + for (const auto& kvp : content) held.insert(kvp.second); + for (int64_t q = 0; q < std::min(P, n); ++q) want.insert(q); + for (int64_t q = P; q < std::min(w.ring_pos, n); ++q) want.insert(q); + for (int64_t q = std::max(w.ring_pos, n - w.ring_span(B)); q < n; ++q) + want.insert(q); + if (held != want) bad_step = n; + } + CHECK_EQ(bad_step, -1ll); + + /* The reference's blocks were never recycled: blocks 0..2 are untouched and block 3's + * reference slots (0..111 = positions 384..399) still hold their prefill values. */ + const std::vector& bt = kv.block_table(1, G_WIN); + REQUIRE_EQ((long long)bt.size(), 5ll); + for (int64_t p = 0; p < P; ++p) { + const int64_t bi = p / B; + const int32_t slot = (int32_t)(bt[(size_t)bi] * B + p % B); + REQUIRE(content.count(slot) > 0); + CHECK_EQ(content[slot], p); + } + + /* The recycling boundary: the ring is one block, so a position and the position one span + * later share a slot, while neighbours do not. ring_pos + span is the first token that + * overwrites ring_pos. */ + CHECK_EQ(r.slot(w.ring_pos), r.slot(w.ring_pos + w.ring_span(B))); + CHECK(r.slot(w.ring_pos) != r.slot(w.ring_pos + 1)); + const int32_t first_ring_slot = (int32_t)(bt[4] * B + w.ring_pos % B); + CHECK_EQ(r.slot(w.ring_pos), first_ring_slot); + + /* Flat to the end, and the free list gets everything back on free. */ + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), flat_blocks); + const int64_t free0 = kv.free_blocks(G_WIN); + kv.free_sequence(1); + CHECK_EQ(kv.free_blocks(G_WIN), free0 + flat_blocks); +} + +/* A block-aligned floor is the exact reference rule: the ring starts at the floor, so the visible + * tail is exactly the last W tokens. */ +TEST(rswa_aligned_floor_shows_exactly_the_last_w_tokens) { + const int64_t B = 128, W = 128, P = 512; + const KVGroupInfo grp = window_group(B, W); + const std::vector g = groups_of(grp); + Config cfg = window_config(); + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_WIN, W)); + CHECK_OK(kv.configure(g, cfg, pools.kv())); + CHECK_OK(kv.add_sequence(1)); + CHECK_OK(kv.set_window(1, P, W)); + const Ring r{ &kv, KVGeom::of(g), G_WIN }; + const SeqWindow w = r.window(); + CHECK_EQ(w.ring_pos, P); + CHECK_EQ(w.ring_blocks, 1ll); + CHECK_EQ(w.ring_span(B), W); + + CHECK_OK(kv.ensure(1, P)); + REQUIRE_EQ((long long)kv.block_table(1, G_WIN).size(), 4ll); + for (int64_t p = P; p < P + 1024; ++p) CHECK_OK(kv.ensure(1, p + 1, p)); + /* Every tail position maps into the one ring block, at the position mod B. */ + REQUIRE_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll); + const int32_t ring_block = kv.block_table(1, G_WIN)[4]; + for (int64_t p = P; p < P + 1024; ++p) { + const int32_t s = r.slot(p); + REQUIRE(s >= 0); + CHECK_EQ(s, (int32_t)(ring_block * B + p % B)); + } + /* Held = 4 reference blocks + 1 ring, and nothing more however long the generation is. */ + CHECK_EQ(kv.held_blocks(G_WIN), 5ll); + kv.free_sequence(1); +} + +/* A group that is never given a runtime window keeps today's recycling exactly: the same numbers + * as mem_test's kv_window_group_recycles_below_the_window, so gemma4_bf16 is untouched. */ +TEST(fixed_window_group_is_unchanged) { + const KVGroupInfo grp = window_group(16, 64); + const std::vector g = groups_of(grp); + Config cfg = window_config(); + cfg.max_tok = 64; + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, pools.kv())); /* no declare_runtime_window */ + + CHECK(!kv.plan(G_WIN)->runtime_win); + CHECK_EQ(kv.runtime_window_tokens(G_WIN), 0ll); + /* Window 64 at block 16 is 4 blocks plus one for the straddle, as before. */ + CHECK_EQ(kv.plan(G_WIN)->window_blocks, 5ll); + + const int64_t n0 = kv.free_blocks(G_WIN); + CHECK_OK(kv.add_sequence(1)); + CHECK(!kv.has_runtime_window(1)); + CHECK_OK(kv.ensure(1, 80)); + CHECK_EQ(kv.first_block_pos(1, G_WIN), 0ll); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll); + CHECK_OK(kv.ensure(1, 400)); + CHECK_EQ(kv.first_block_pos(1, G_WIN), 16ll); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 24ll); + CHECK_OK(kv.ensure(1, 401)); + CHECK_EQ(kv.first_block_pos(1, G_WIN), 336ll); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll); + kv.trim_window(1, 401); + CHECK_EQ(kv.first_block_pos(1, G_WIN), 336ll); + CHECK_EQ((long long)kv.block_table(1, G_WIN).size(), 5ll); + CHECK_EQ(kv.free_blocks(G_WIN), n0 - 5); + kv.free_sequence(1); + CHECK_EQ(kv.free_blocks(G_WIN), n0); +} + +/* A sequence with a runtime window is excluded from every reuse path that assumes the declare-time + * window, and the manager refuses the ones a caller could still reach. */ +TEST(rswa_sequence_is_excluded_from_prefix_and_snapshots) { + const KVGroupInfo grp = window_group(128, 128); + const std::vector g = groups_of(grp); + Config cfg = window_config(); + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_WIN, 128)); + CHECK_OK(kv.configure(g, cfg, pools.kv())); + /* The declare-time window is still what an unarmed sequence gets. */ + CHECK_OK(kv.add_sequence(1)); + CHECK(!kv.has_runtime_window(1)); + CHECK_OK(kv.set_window(1, 256, 128)); + CHECK(kv.has_runtime_window(1)); + CHECK_OK(kv.ensure(1, 256)); + CHECK_OK(kv.ensure(1, 300, 256)); + + std::vector rows; + CHECK(!kv.window_rows(1, 256, &rows)); /* no snapshot describes this window */ + CHECK(rows.empty()); + CHECK_EQ(kv.seed_window(1, 256), RAD_E_STATE); /* no hit resumes into it */ + CHECK_EQ(kv.adopt(1, G_WIN, kv.block_table(1, G_WIN), 256), RAD_E_STATE); + CHECK_EQ(kv.fork(1, 2), RAD_E_UNSUPPORTED); + CHECK_EQ(kv.rollback(1, 200), RAD_E_UNSUPPORTED); + /* A fresh retry: preempt clears the window so admission re-arms it. */ + CHECK_OK(kv.preempt(1)); + CHECK(!kv.has_runtime_window(1)); + kv.free_sequence(1); +} + +/* Refusals: a runtime window needs a windowed group, a floor at or ahead of the KV it holds, and + * blocks that can hold the reference plus the ring. */ +TEST(rswa_refusals_are_explicit) { + Config cfg = window_config(); + { + /* A FULL group cannot carry one: the declaration is recorded, and the plan refuses it. */ + std::vector g = groups_of(window_group(128, 0)); + g[G_WIN].decl.kind = RAD_KV_FULL; + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_WIN, 128)); + CHECK_EQ(kv.configure(g, cfg, pools.kv()), RAD_E_INVAL); + } + { + /* A model with no windowed group has nothing to arm. */ + std::vector g = groups_of(window_group(128, 0)); + g[G_WIN].decl.kind = RAD_KV_FULL; + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, pools.kv())); + CHECK_OK(kv.add_sequence(1)); + CHECK_EQ(kv.set_window(1, 256, 128), RAD_E_UNSUPPORTED); + kv.free_sequence(1); + } + { + /* A windowed group plans; the refusals are about the sequence. */ + const std::vector g = groups_of(window_group(128, 128)); + Pools pools; + CHECK_OK(configure_pools(pools, cfg)); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_WIN, 128)); + CHECK_OK(kv.configure(g, cfg, pools.kv())); + CHECK_OK(kv.add_sequence(1)); + CHECK_EQ(kv.set_window(1, 256, 0), RAD_E_INVAL); + CHECK_EQ(kv.set_window(1, -1, 128), RAD_E_INVAL); + CHECK_OK(kv.ensure(1, 256)); + /* The floor cannot move behind KV already written. */ + CHECK_EQ(kv.set_window(1, 128, 128), RAD_E_STATE); + CHECK(!kv.has_runtime_window(1)); + kv.free_sequence(1); + } +} + +/* The block rounding must never lose a token of the last W: the ring is W..W+B-1 tokens wide, + * whatever W is relative to the block. */ +TEST(rswa_ring_always_covers_the_last_w_tokens) { + const int64_t B = 128; + for (int64_t w_tokens : { 1, 64, 100, 128, 129, 200, 300 }) { + for (int64_t P : { 400, 512 }) { + const KVGroupInfo grp = window_group(B, 128); + const std::vector g = groups_of(grp); + Config cfg = window_config(); + Pools pools; + REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK); + KVManager kv; + REQUIRE_EQ(kv.declare_runtime_window(G_WIN, w_tokens), RAD_OK); + REQUIRE_EQ(kv.configure(g, cfg, pools.kv()), RAD_OK); + REQUIRE_EQ(kv.add_sequence(1), RAD_OK); + REQUIRE_EQ(kv.set_window(1, P, w_tokens), RAD_OK); + const Ring r{ &kv, KVGeom::of(g), G_WIN }; + const SeqWindow w = r.window(); + const int64_t span = w.ring_span(B); + CHECK_EQ(w.ring_pos, (P + B - 1) / B * B); + CHECK_EQ(w.ring_blocks, (w_tokens + B - 1) / B); + /* The frozen tail [P, ring_pos) plus the ring always covers the last W: at least W + * wide, and never more than the ring's rounding plus the frozen fraction (W + B - 1 + * when W is a block multiple, W + 2B - 2 otherwise). */ + CHECK(w.ring_pos - P + span >= w_tokens); + CHECK(w.ring_pos - P + span <= w_tokens + 2 * B - 2); + if (w_tokens % B == 0) CHECK(w.ring_pos - P + span <= w_tokens + B - 1); + REQUIRE_EQ(kv.ensure(1, P), RAD_OK); + const int64_t n = P + 3 * span; + for (int64_t p = P; p < n; ++p) REQUIRE_EQ(kv.ensure(1, p + 1, p), RAD_OK); + /* Held blocks: the reference's, then the ring's -- flat. */ + const int64_t blocks = (int64_t)kv.block_table(1, G_WIN).size(); + CHECK_EQ(blocks, w.ring_pos / B + w.ring_blocks); + std::map content; + for (int64_t p = 0; p < n; ++p) { + const int32_t s = r.slot(p); + REQUIRE(s >= 0); + content[s] = p; /* a ring slot's newest write wins */ + } + std::set held; + for (const auto& kvp : content) held.insert(kvp.second); + /* The last W positions of the generation are among what the slots hold... */ + for (int64_t p = n - w_tokens; p < n; ++p) CHECK(held.count(p) > 0); + /* ...and nothing outside the rule is. */ + std::set want; + for (int64_t p = 0; p < std::min(P, n); ++p) want.insert(p); + for (int64_t p = P; p < std::min(w.ring_pos, n); ++p) want.insert(p); + for (int64_t p = std::max(w.ring_pos, n - span); p < n; ++p) want.insert(p); + CHECK(held == want); + kv.free_sequence(1); + } + } +} + +/* The card's advance (core/sched/advance_impl.h, adv_groups) runs AFTER the batch builder and + * overwrites every group's `seqused` and slot_mapping, so for a runtime window it must reproduce + * the ring's mapping. This is the P4a GPU fault: the advance wrote used = ctx + n (177 for a + * 176-token held span) and mapped a wrapped position linearly, so the decode walked + * bt[ceil(used/16)-1] = bt[11] -- the first entry past the 11-block table, which the builder pads + * with -1 -- and faulted the card below the KV pool. With block 16 and the ring 8 blocks + * (128 tokens), the table is the reference's 3 blocks plus the ring's 8. */ +TEST(rswa_advance_keeps_the_ring_span_and_slots) { + const int64_t B = 16, PITCH = 32; + const int32_t ring_pos = 48, ring_blocks = 8, table_len = 11; + + int32_t pos[5] = { 176, 177, 183, 191, 192 }; /* wrapped ring positions */ + const int32_t base = 176, n = 5; + AdvanceArgs a; + std::vector slab(4096, 0); + const int64_t used_off = 0, slot_off = 16, bt_off = slot_off + 8 * 4; + const int64_t first_off = bt_off + PITCH * 4, pos_off = first_off + 4; + const int64_t rpos_off = pos_off + 32, tlen_off = rpos_off + 4; + const int64_t grp_off = tlen_off + 8; + a.slab = slab.data(); + a.pos_off = pos_off; a.grp_off = grp_off; + a.n_groups = 1; + std::memcpy(slab.data() + pos_off, pos, sizeof pos); + int32_t* bt = reinterpret_cast(slab.data() + bt_off); + for (int32_t b = 0; b < table_len; ++b) bt[b] = b; /* blocks 0..10 */ + for (int64_t b = table_len; b < PITCH; ++b) bt[b] = -1; /* the builder's padding */ + *reinterpret_cast(slab.data() + first_off) = 0; + /* Per sequence, as the builder fills them: this row's floor and its table's length. */ + *reinterpret_cast(slab.data() + rpos_off) = ring_pos; + *reinterpret_cast(slab.data() + tlen_off) = (int32_t)table_len; + AdvGroup* g = reinterpret_cast(slab.data() + grp_off); + g->block_size = (int32_t)B; g->paged = 1; g->pitch = (int32_t)PITCH; + g->slot_off = slot_off; g->used_off = used_off; g->bt_off = bt_off; + g->first_off = first_off; g->rpos_off = rpos_off; g->tlen_off = tlen_off; + g->ring = 1; g->ring_blocks = ring_blocks; + + adv_groups(a, 0, 0, base, n); + + /* used stops at the table: the ring holds 3 reference blocks + 8 ring blocks = 176 tokens, + * while the context is 181. Without the clamp the decode reads bt[11] = -1. */ + CHECK_EQ(*reinterpret_cast(slab.data() + used_off), 176); + const int32_t* slot = reinterpret_cast(slab.data() + slot_off); + /* A position at or past ring_pos maps into the ring, modulo its blocks: 176 -> block 3 + * (slot 48), 192 -> block 4 (slot 64), never the linear (p - first)/block = 11..12. */ + CHECK_EQ(slot[0], 48); /* 176: ring block 3, offset 0 */ + CHECK_EQ(slot[1], 49); /* 177 */ + CHECK_EQ(slot[2], 55); /* 183 */ + CHECK_EQ(slot[3], 63); /* 191: last slot of ring block 3 */ + CHECK_EQ(slot[4], 64); /* 192: ring block 4, offset 0 */ + /* Every slot is a real slot of the table (never -1). */ + for (int32_t j = 0; j < n; ++j) CHECK(slot[j] >= 0); + + /* The same row without a runtime window keeps the linear mapping -- used = base + n, and the + * wrapped position lands past the table (the old behaviour). */ + g->ring = 0; + adv_groups(a, 0, 0, base, n); + CHECK_EQ(*reinterpret_cast(slab.data() + used_off), 181); + CHECK_EQ(slot[0], -1); +} + +RAD_TEST_MAIN() diff --git a/tests/mkuocrgolden.py b/tests/mkuocrgolden.py new file mode 100644 index 00000000..b151c7d2 --- /dev/null +++ b/tests/mkuocrgolden.py @@ -0,0 +1,269 @@ +"""mkuocrgolden.py MODELDIR OUT.h [REPORT] -- goldens for the Unlimited-OCR processor in +tests/mm_test.cpp (P3 of aijuus/plans/UNLIMITED-OCR-PLUGIN.md), every number from the checkpoint's +own remote code as MODELDIR ships it: + + - the tile grid, from modeling_unlimitedocr.dynamic_preprocess (find_closest_aspect_ratio over + its sorted set of ratios), for a sweep of sizes including the exact ties its set order resolves; + - the placeholders that replace a picture's , from infer() (gundam mode) and infer_multi() + (base mode: the whole page, and the 640-pixel page the reference's default asks for); + - the pixels: the global view (ImageOps.pad) and the local one (the picture resized to its tile + grid and cut), transformed by the model's BasicImageTransform and rounded to bf16, in the patch + order the radiance processor stages them (Item::patch_raster: row by row, each patch + (channel, y, x)). The segment plan is the radiance Item's (see the header of + Processor::image_unlimitedocr): a line of tiles per tile row, the global view's grid, and the + view separator's single row -- each with `downsample` filler patch columns for the newline + column the reference's layout puts after every line of features. + +REPORT, when given, gets one line per picture and mode: the grid, the placeholder count and +whether the segment plan's counts match, for the gate's log. +""" +import sys, math, json +import numpy as np, torch +from PIL import Image, ImageOps +from torchvision import transforms + +model_dir, out = sys.argv[1], sys.argv[2] +report = open(sys.argv[3], "w") if len(sys.argv) > 3 else None + +# ---- the checkpoint's two configs, and its remote module as a package (its relative imports need +# one) +import types, importlib +pkg = types.ModuleType("uocr") +pkg.__path__ = [model_dir] +sys.modules["uocr"] = pkg +M = importlib.import_module("uocr.modeling_unlimitedocr") +pre = json.load(open(model_dir + "/preprocessor_config.json")) +proc = json.load(open(model_dir + "/processor_config.json")) + +PATCH = int(proc["patch_size"]) +DS = int(proc["downsample_ratio"]) +BASE = int(pre["size"]["height"]) +TILE = int(pre["tile_size"]) +MIN_PATCHES = int(pre["min_patches"]) +MAX_PATCHES = int(pre["max_patches"]) +CROP = bool(pre["crop_to_patches"]) +MEAN = tuple(float(x) for x in pre["image_mean"]) +STD = tuple(float(x) for x in pre["image_std"]) +assert proc["image_token"] == "" and proc["normalize"] +assert [int(x) for x in pre["background_color"]] == [127, 127, 127] +assert abs(MEAN[0] - 0.5) < 1e-9 and abs(STD[0] - 0.5) < 1e-9 + +from transformers import AutoTokenizer +tok = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=False) +IMAGE_TOKEN = tok.convert_tokens_to_ids("") +assert IMAGE_TOKEN == 128815, IMAGE_TOKEN + +# the model's own transform: ToTensor then Normalize(0.5, 0.5), in f32, rounded to bf16 +transform = transforms.Compose([transforms.ToTensor(), + transforms.Normalize(MEAN, STD)]) + + +def bf16_patches(im, grids): + """The patches of `im`, in Item::patch_raster order: (channel, y, x) per patch, row by row, + bf16 bit patterns. `grids` is (gh, gw): the patch grid the tensor is cut into.""" + t = transform(im).to(torch.bfloat16) + ch, h, w = t.shape + gh, gw = grids + assert h == gh * PATCH and w == gw * PATCH, (h, w, gh, gw) + a = t.reshape(ch, gh, PATCH, gw, PATCH).permute(1, 3, 0, 2, 4).contiguous() + return a.view(torch.int16).numpy().astype(np.uint16) + + +def fnv(arr): + b = arr.tobytes() + h = 0xcbf29ce484222325 + mul = 0x100000001b3 + mask = (1 << 64) - 1 + for v in b: + h = ((h ^ v) * mul) & mask + return h + + +def expand_gundam(im): + """modeling_unlimitedocr.infer, verbatim for one picture: the global view at BASE, then the + local views if the picture is larger than a tile. Returns (placeholders, cols, rows, tiles, + global view).""" + w, h = im.size + global_view = ImageOps.pad(im, (BASE, BASE), color=tuple(int(x * 255) for x in MEAN)) + if w > TILE or h > TILE: + tiles, ratio = M.dynamic_preprocess(im, MIN_PATCHES, MAX_PATCHES, TILE, False) + cols, rows = ratio + else: + tiles, cols, rows = [], 1, 1 + nq_base = math.ceil((BASE // PATCH) / DS) + n = (nq_base + 1) * nq_base + 1 # ([tok] * n + [tok]) * n + [tok] + if cols * rows > 1: + nq = math.ceil((TILE // PATCH) / DS) + n += (nq * cols + 1) * nq * rows # ([tok] * nq * cols + [tok]) * nq * rows + return n, cols, rows, tiles, global_view + + +def expand_base(im, image_size): + """modeling_unlimitedocr.infer_multi, verbatim for one page: the page squared when the side is + a tile or less, then padded to image_size.""" + w, h = im.size + if image_size <= TILE: + im = im.resize((image_size, image_size)) + global_view = ImageOps.pad(im, (image_size, image_size), + color=tuple(int(x * 255) for x in MEAN)) + nq = math.ceil((image_size // PATCH) / DS) + n = (nq + 1) * nq + 1 + return n, 1, 1, [], global_view + + +def plan_segments(cols, rows, base_grid): + """The Item's segment plan: one line of tiles per tile row (split so a pass holds it; the last + chunk carries the newline column), the global view's grid, the separator. (gh, gw, real).""" + q = TILE // PATCH + segs = [] + if cols * rows > 1: + c_max = (16384 // q - 4) // q # the server's pass, --mm-max-patches + c_max = max(1, c_max) + for r in range(rows): + c0 = 0 + while c0 < cols: + n = min(c_max, cols - c0) + last = (c0 + n) == cols + segs.append((q, q * n + (4 if last else 0), q * n)) + c0 += n + segs.append((base_grid, base_grid + 4, base_grid)) + segs.append((DS, DS, 0)) + return segs + + +def picture(f, h, w): + y, x, c = np.meshgrid(np.arange(h, dtype=np.uint64), np.arange(w, dtype=np.uint64), + np.arange(3, dtype=np.uint64), indexing="ij") + with np.errstate(over="ignore"): + z = (np.uint64(f) * np.uint64(0x9E3779B97F4A7C15) + y * np.uint64(0xBF58476D1CE4E5B9) + + x * np.uint64(0x94D049BB133111EB) + c * np.uint64(0x2545F4914F6CDD1D) + np.uint64(12345)) + z = (z ^ (z >> np.uint64(30))) * np.uint64(0xBF58476D1CE4E5B9) + z = (z ^ (z >> np.uint64(27))) * np.uint64(0x94D049BB133111EB) + z = z ^ (z >> np.uint64(31)) + return Image.fromarray((z & np.uint64(255)).astype(np.uint8)) + + +def names(): + return ["kUocrPictures", "kUocrSegs", "kUocrGrid"] + + +L = ["/* uocr_golden.h -- GENERATED by mkuocrgolden.py from the checkpoint's remote code; do not " + "edit. */", + "#pragma once", "#include ", "", + f"static const int32_t kUocrPatch = {PATCH}, kUocrDownsample = {DS};", + f"static const int32_t kUocrBaseSize = {BASE}, kUocrTile = {TILE};", + f"static const int32_t kUocrMinTiles = {MIN_PATCHES}, kUocrMaxTiles = {MAX_PATCHES};", + f"static const bool kUocrCropMode = {'true' if CROP else 'false'};", + f"static const int32_t kUocrImageToken = {IMAGE_TOKEN};", ""] + +# ---- the tile grid, for sizes that cover every shape and the exact ties of dynamic_preprocess +sizes = [(1, 1), (40, 30), (100, 100), (300, 500), (500, 300), (640, 640), (641, 641), (500, 700), + (700, 500), (800, 1000), (1000, 800), (1024, 1024), (1280, 1024), (1024, 1280), (900, 1400), + (1400, 900), (2000, 600), (600, 2000), (2400, 400), (400, 2400), (1080, 1920), (1920, 1080), + (515, 1031), (1031, 515), (100, 5000), (5000, 100), (3000, 3000), (720, 1280), (800, 640), + (640, 800), (960, 720), (720, 960), (1600, 1200), (1200, 1600), (33, 4096), (4096, 33)] +L.append("struct GoldUocrGrid { int64_t h, w; int32_t cols, rows; };") +L.append("static const GoldUocrGrid kUocrGrid[] = {") +for h, w in sizes: + im = Image.new("RGB", (w, h)) + if w > TILE or h > TILE: + _, ratio = M.dynamic_preprocess(im, MIN_PATCHES, MAX_PATCHES, TILE, False) + cols, rows = ratio + else: + cols, rows = 1, 1 + L.append(f" {{ {h}, {w}, {cols}, {rows} }},") +L.append("};") +L.append("") + +# ---- whole pictures: gundam (1), base at 1024 (2) and base at 640 (3), and a two-page pair +pics = [(0, 300, 500, 1), (1, 900, 1400, 1), (2, 2400, 400, 1), (3, 500, 700, 1), (4, 64, 48, 1), + (5, 800, 1000, 1), (0, 300, 500, 2), (1, 900, 1400, 2), (2, 2400, 400, 2), (3, 500, 700, 2), + (4, 64, 48, 2), (5, 800, 1000, 2), (1, 900, 1400, 3), (3, 500, 700, 3)] +segs, rows, seg0 = [], [], 0 +L.append("struct GoldUocrPic { int32_t f, h, w, mode; int32_t cols, rows, n_ids; int32_t n_seg, " + "seg0; uint64_t global_fnv, local_fnv; };") +for f, h, w, mode in pics: + im = picture(f, h, w) + if mode == 1: + n, cols, rows_, tiles, gv = expand_gundam(im) + base_grid = BASE // PATCH + g_fnv = fnv(bf16_patches(gv, (base_grid, base_grid))) + if cols * rows_ > 1: + big = im.resize((TILE * cols, TILE * rows_), Image.Resampling.BICUBIC) + l_fnv = fnv(bf16_patches(big, (TILE // PATCH * rows_, TILE // PATCH * cols))) + else: + l_fnv = 0 + else: + size = 1024 if mode == 2 else 640 + n, cols, rows_, tiles, gv = expand_base(im, size) + base_grid = size // PATCH + g_fnv = fnv(bf16_patches(gv, (base_grid, base_grid))) + l_fnv = 0 + pl = plan_segments(cols, rows_, base_grid) + # every segment's row count is its patches / downsample^2, and the sum is the reference's + total = sum((gh // DS) * (gw // DS) for gh, gw, _ in pl) + assert total == n, (h, w, mode, total, n) + rows.append(f" {{ {f}, {h}, {w}, {mode}, {cols}, {rows_}, {n}, {len(pl)}, {seg0}, " + f"0x{g_fnv:016x}ull, 0x{l_fnv:016x}ull }},") + for gh, gw, real in pl: + segs.append((gh, gw, real)) + seg0 += len(pl) + if report: + report.write(f"picture {f} {w}x{h} mode {'gundam' if mode == 1 else 'base@%d' % size}: " + f"reference grid {cols}x{rows_} ({cols * rows_} tiles), placeholders {n}; " + f"item plan {len(pl)} segments, {total} rows: MATCH\n") + if cols * rows_ > 1: + report.write(f" tiles row-major {cols} wide x {rows_} tall, one line of " + f"{10 * cols} features + 1 newline per feature row: " + f"{(10 * cols + 1) * 10 * rows_} placeholders\n") +L.append("static const GoldUocrPic kUocrPictures[] = {") +L += rows +L.append("};") +L.append("struct GoldUocrSeg { int32_t h, w, real; };") +L.append("static const GoldUocrSeg kUocrSegs[] = {") +for gh, gw, real in segs: + L.append(f" {{ {gh}, {gw}, {real} }},") +L.append("};") +L.append("") + +# ---- the ratios' set order: the reference's tie resolution, area by area +target = set((i, j) for n in range(MIN_PATCHES, MAX_PATCHES + 1) for i in range(1, n + 1) + for j in range(1, n + 1) if i * j <= MAX_PATCHES and i * j >= MIN_PATCHES) +ordered = sorted(target, key=lambda t: t[0] * t[1]) +tall_last = [] +for (i, j) in sorted(target): + if i < j and (j, i) in target and ordered.index((i, j)) > ordered.index((j, i)): + tall_last.append((i, j)) +# ---- Pillow's bicubic resize: both pass orders (its Resample.c runs the vertical pass first when +# the height shrinks by more than twice what the width does), the one-axis forms and an exact tie. +L.append("/* Pillow's Image.resize(BICUBIC) of a splitmix picture: its two-pass order is part of the") +L.append(" * function (the intermediate rounds to eight bits). */") +L.append("struct GoldUocrResize { int32_t sh, sw, dh, dw; uint64_t fnv; };") +L.append("static const GoldUocrResize kUocrResize[] = {") +resize_cases = [(0, 2400, 400, 1024, 171), (0, 300, 300, 90, 100), (0, 400, 300, 171, 1024), + (0, 300, 400, 1024, 171), (0, 400, 1000, 200, 500), (0, 1000, 400, 200, 300), + (0, 700, 500, 650, 470), (0, 500, 700, 640, 650), (0, 320, 480, 320, 480), + (0, 240, 320, 160, 320), (0, 240, 320, 240, 200), (0, 64, 48, 1024, 1024)] +for f, sh, sw, dh, dw in resize_cases: + im = picture(f, sh, sw) + r = np.asarray(im.resize((dw, dh), Image.Resampling.BICUBIC)) + L.append(f" {{ {sh}, {sw}, {dh}, {dw}, 0x{fnv(r):016x}ull }},") +L.append("};") +L.append("") + +L.append("/* The transposed pairs whose tall side the reference's set visits last. */") +L.append("struct GoldUocrTie { int32_t c, r; };") +L.append("static const GoldUocrTie kUocrTallLast[] = {") +L.append(" " + " ".join(f"{{{c}, {r}}}," for c, r in tall_last)) +L.append("};") +L.append(f"static const int32_t kUocrNTallLast = {len(tall_last)};") +if report: + # The multi-page form: the reference concatenates the pages' runs at one . + pair = [picture(0, 500, 300), picture(1, 1400, 900)] + per = [expand_base(im, 1024)[0] for im in pair] + report.write(f"multi-page pair (infer_multi, 2 pages at one marker, image_size 1024): " + f"{per[0]} + {per[1]} = {sum(per)} placeholders, " + f"{'MATCH' if per == [273, 273] else 'MISMATCH'}\n") +open(out, "w").write("\n".join(L) + "\n") +print("wrote", out, len(L), "lines;", len(pics), "pictures,", len(segs), "segments,", + len(tall_last), "tie pairs") diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp index cacb1cd2..cd8b200e 100644 --- a/tests/mm_test.cpp +++ b/tests/mm_test.cpp @@ -25,7 +25,9 @@ #include "lfm2_golden.h" #include "mm/resample.h" #include "mm_golden.h" +#include "rad_builder.h" #include "rad_plugin.h" +#include "uocr_golden.h" #include #include @@ -1309,4 +1311,348 @@ TEST(a_resampled_stream_is_its_tone_whether_pushed_whole_or_in_pieces) { CHECK(!mm::Resampler::takes(23999)); } + +/* ================================================================== Unlimited-OCR + * + * The checkpoint's two picture modes, from its own remote code (tests/mkuocrgolden.py): the tile + * grid dynamic_preprocess chooses (its ratio set sorted by area, ties in the set's order), the + * placeholders that replace the picture (infer()'s global view plus crops; infer_multi()'s page), + * and the pixels of the global view and of the tile mosaic, in the order Item::patch_raster + * stages them: row by row, each patch (channel, y, x). + */ + +/* The checkpoint's processor configuration, as a converted container states it. */ +VisionConfig uocr_cfg() { + VisionConfig c; + c.family = Family::UnlimitedOcr; + c.patch = kUocrPatch; + c.temporal = 1; + c.merge = kUocrDownsample; + c.downsample = kUocrDownsample; + c.base_size = kUocrBaseSize; + c.image_size = kUocrBaseSize; + c.tile = kUocrTile; + c.min_tiles = kUocrMinTiles; + c.max_tiles = kUocrMaxTiles; + c.crop_mode = kUocrCropMode; + c.tok_image = kUocrImageToken; + c.max_patches = 16384; /* the server's --mm-max-patches default */ + const int64_t f2 = (int64_t)c.factor() * c.factor(); + c.image_min_pixels = c.video_min_pixels = f2; + c.image_max_pixels = c.video_max_pixels = (int64_t)c.base_size * c.base_size; + c.min_frames = 1; + return c; +} + +int32_t uocr_marker(const std::string& s) { return s == "" ? kUocrImageToken : -1; } + +/* A segment's patches in raster order, its first `real_w` patches a row: the tensor the reference + * holds for that view, patch by patch. */ +std::vector segment_pixels(const Item& it, int32_t s, int32_t real_w) { + const int64_t pd = it.patch_dim; + const int32_t gh = it.seg_h(s), gw = it.seg_w(s); + const int64_t p0 = it.patch_at(s); + std::vector out; + out.reserve((size_t)gh * (size_t)real_w * (size_t)pd); + for (int32_t py = 0; py < gh; ++py) + for (int32_t px = 0; px < real_w; ++px) { + const uint16_t* p = it.pixels.data() + (p0 + (int64_t)py * gw + px) * pd; + out.insert(out.end(), p, p + pd); + } + return out; +} + +/* The container's model_type selects the family; a key it does not carry takes the reference's + * default, so a container converted before the tower landed still states a processor. */ +TEST(unlimitedocr_configures_itself_from_the_container) { + const char* keys[] = { "model_type", "preprocessor.crop_to_patches", "preprocessor.max_patches", + "preprocessor.min_patches", "preprocessor.resample", + "preprocessor.size.height", "preprocessor.size.width", + "preprocessor.tile_size", "processor.downsample_ratio", + "processor.image_token", "processor.patch_size" }; + const char* vals[] = { "unlimited_ocr", "true", "32", "2", "3", "1024", "1024", "640", "4", + "", "16" }; + RadModelMeta m{}; + m.n_kv = (int)(sizeof keys / sizeof keys[0]); + m.kv_key = keys; + m.kv_val = vals; + VisionConfig c; + std::string why; + REQUIRE_EQ(c.from_meta(m, &why), RAD_OK); + CHECK(c.family == Family::UnlimitedOcr); + CHECK_EQ(c.patch, 16); + CHECK_EQ(c.downsample, 4); + CHECK_EQ(c.merge, 4); + CHECK_EQ(c.temporal, 1); + CHECK_EQ(c.base_size, 1024); + CHECK_EQ(c.image_size, 1024); + CHECK_EQ(c.tile, 640); + CHECK_EQ(c.min_tiles, 2); + CHECK_EQ(c.max_tiles, 32); + CHECK(c.crop_mode); + CHECK_EQ(c.factor(), 64); + CHECK_EQ(c.patch_dim(), (int64_t)3 * 16 * 16); + CHECK_EQ(c.mean[0], 0.5f); + CHECK_EQ(c.stdv[2], 0.5f); + CHECK(c.image_token == ""); + + /* Only model_type: every processor key takes the reference's default. */ + const char* one_key[] = { "model_type" }; + const char* one_val[] = { "unlimited_ocr" }; + RadModelMeta mt{}; + mt.n_kv = 1; + mt.kv_key = one_key; + mt.kv_val = one_val; + VisionConfig d; + REQUIRE_EQ(d.from_meta(mt, &why), RAD_OK); + CHECK_EQ(d.patch, 16); + CHECK_EQ(d.downsample, 4); + CHECK_EQ(d.base_size, 1024); + CHECK_EQ(d.image_size, 1024); + CHECK_EQ(d.tile, 640); + CHECK_EQ(d.min_tiles, 2); + CHECK_EQ(d.max_tiles, 32); + CHECK(d.crop_mode); + CHECK(d.image_token == ""); + + /* PIL's bicubic is the only filter this processor stages. */ + const char* bad_key[] = { "model_type", "preprocessor.resample" }; + const char* bad_val[] = { "unlimited_ocr", "2" }; + RadModelMeta mb{}; + mb.n_kv = 2; + mb.kv_key = bad_key; + mb.kv_val = bad_val; + VisionConfig b; + CHECK_EQ(b.from_meta(mb, &why), RAD_E_UNSUPPORTED); +} + +/* The transposed ratios whose tall side the reference's Python set visits last, which is what its + * tie rule needs beyond "the wider grid wins": the table in core/mm/processor.cpp must be the + * golden's, pair for pair. */ +TEST(unlimitedocr_tie_order_is_the_references) { + int32_t listed = 0; + for (int32_t c = 1; c <= kUocrMaxTiles; ++c) + for (int32_t r = c + 1; r <= kUocrMaxTiles; ++r) { + if ((int64_t)c * r < kUocrMinTiles || (int64_t)c * r > kUocrMaxTiles) continue; + bool want = false; + for (int32_t k = 0; k < kUocrNTallLast; ++k) + if (kUocrTallLast[k].c == c && kUocrTallLast[k].r == r) want = true; + if (want) ++listed; + if (uocr_tall_last(c, r) != want) + std::fprintf(stderr, " pair %dx%d: %s last here, %s in the reference\n", c, r, + uocr_tall_last(c, r) ? "tall" : "wide", + want ? "tall" : "wide"); + CHECK_EQ((int)uocr_tall_last(c, r), (int)want); + } + CHECK_EQ(listed, kUocrNTallLast); +} + +/* dynamic_preprocess's grid for a sweep of shapes, the exact ties of its ratio set included. */ +TEST(unlimitedocr_tile_grids_are_the_references) { + for (const GoldUocrGrid& g : kUocrGrid) { + int32_t cols = 1, rows = 1; + /* The reference asks dynamic_preprocess only for a picture larger than one tile. */ + if (g.w > kUocrTile || g.h > kUocrTile) + uocr_grid(g.h, g.w, kUocrMinTiles, kUocrMaxTiles, kUocrTile, &cols, &rows); + if (cols != g.cols || rows != g.rows) + std::fprintf(stderr, " picture %lldx%lld: grid %dx%d, reference %dx%d\n", + (long long)g.w, (long long)g.h, cols, rows, g.cols, g.rows); + CHECK_EQ(cols, g.cols); + CHECK_EQ(rows, g.rows); + } +} + +/* Whole pictures in both modes: the segments (a line of tiles per tile row, the global view, the + * view separator), every placeholder the picture marker, the pixel count the reference's layout + * has, and the patches of the global view and of the tile mosaic. */ +TEST(unlimitedocr_pictures_are_the_references) { + Processor p; + REQUIRE_EQ(p.init(uocr_cfg(), [](const std::string&) { return std::vector{}; }, + uocr_marker), RAD_OK); + const int32_t q = kUocrTile / kUocrPatch; + for (const GoldUocrPic& g : kUocrPictures) { + ImageMode mode; + if (g.mode == 1) { + mode.kind = ImageMode::Gundam; + } else { + mode.kind = ImageMode::Base; + mode.image_size = g.mode == 2 ? kUocrBaseSize : kUocrTile; + } + std::shared_ptr it; + std::string why; + const int rc = p.image_from(frame(g.f, g.h, g.w), &it, &why, mode); + if (rc < 0) std::fprintf(stderr, " %dx%d mode %d: %s\n", g.w, g.h, g.mode, why.c_str()); + CHECK_OK(rc); + REQUIRE(it != nullptr); + REQUIRE_EQ(it->n_seg, g.n_seg); + REQUIRE_EQ((int64_t)it->expand.size(), (int64_t)g.n_ids); + CHECK_EQ(it->n_rows(), (int64_t)g.n_ids); + REQUIRE_EQ(it->seg_at.size(), (size_t)it->n_seg); + for (int32_t v : it->expand) CHECK_EQ(v, kUocrImageToken); + CHECK(it->rope_1d); + CHECK(it->patch_raster); + + int32_t cols = 0, rows = 0; + for (int32_t s = 0; s < it->n_seg; ++s) { + const GoldUocrSeg& gs = kUocrSegs[g.seg0 + s]; + CHECK_EQ(it->seg_h(s), gs.h); + CHECK_EQ(it->seg_w(s), gs.w); + CHECK_EQ(it->seg_at[(size_t)s], (int32_t)it->row_at(s)); + const int64_t np = it->patch_at(s + 1) - it->patch_at(s); + CHECK_EQ(np, (int64_t)gs.h * gs.w); + if (gs.h == q && s + 2 < it->n_seg) { /* a line of tiles */ + if (cols) { CHECK_EQ(cols, gs.real / q); } + cols = gs.real / q; + rows += 1; + } + /* Raster order: patch k of a segment sits at (k / w, k % w). */ + std::vector planes((size_t)(4 * np)); + it->coords(it->patch_at(s), np, planes.data()); + for (int64_t k = 0; k < np; ++k) { + CHECK_EQ(planes[(size_t)k], (int32_t)(k / gs.w)); + CHECK_EQ(planes[(size_t)(np + k)], (int32_t)(k % gs.w)); + CHECK_EQ(planes[(size_t)(2 * np + k)], gs.h); + CHECK_EQ(planes[(size_t)(3 * np + k)], gs.w); + } + } + const bool tiled_ref = g.mode == 1 && g.cols * g.rows > 1; + if (cols != (tiled_ref ? g.cols : 0) || rows != (tiled_ref ? g.rows : 0)) + std::fprintf(stderr, " picture %dx%d mode %d: %d lines of %d tiles, reference %dx%d\n", + g.w, g.h, g.mode, rows, cols, g.cols, g.rows); + CHECK_EQ(cols, tiled_ref ? g.cols : 0); + CHECK_EQ(rows, tiled_ref ? g.rows : 0); + + /* The global view, then the mosaic of the crops (if any). */ + const int32_t sg = it->n_seg - 2; + const GoldUocrSeg& gg = kUocrSegs[g.seg0 + sg]; + if (fnv(segment_pixels(*it, sg, gg.real)) != g.global_fnv) + std::fprintf(stderr, " picture %dx%d mode %d: the global view's patches differ\n", + g.w, g.h, g.mode); + CHECK_EQ(fnv(segment_pixels(*it, sg, gg.real)), g.global_fnv); + std::vector local; + for (int32_t s = 0; s < sg; ++s) { + const std::vector v = segment_pixels(*it, s, kUocrSegs[g.seg0 + s].real); + local.insert(local.end(), v.begin(), v.end()); + } + if (g.local_fnv) { + if (fnv(local) != g.local_fnv) + std::fprintf(stderr, " picture %dx%d mode %d: the crops' patches differ\n", + g.w, g.h, g.mode); + CHECK_EQ(fnv(local), g.local_fnv); + } else { + CHECK(local.empty()); + } + /* The token count is the reference's arithmetic. */ + CHECK_EQ(uocr_tokens(p.config(), mode, g.cols, g.rows), (int64_t)g.n_ids); + } +} + +/* Pillow's antialiased bicubic runs its two passes in its own order (libImaging/Resample.c: the + * vertical one first when the height shrinks by more than twice what the width does) and rounds + * the intermediate to eight bits; this pins the order at sizes where the choice changes the + * picture, since a one-pixel difference is invisible in a summary and visible to the model. */ +TEST(pillow_bicubic_resizes_in_the_references_pass_order) { + for (const GoldUocrResize& g : kUocrResize) { + Frame out; + resize_bicubic(frame(0, g.sh, g.sw), g.dw, g.dh, &out); + CHECK_EQ(out.w, g.dw); + CHECK_EQ(out.h, g.dh); + if (fnv(out.rgb) != g.fnv) + std::fprintf(stderr, " %dx%d -> %dx%d: pixels differ\n", g.sw, g.sh, g.dw, g.dh); + CHECK_EQ(fnv(out.rgb), g.fnv); + } +} + +/* The runs: one per segment, every token the picture marker, and a 1-D rotary that gives each + * placeholder its own position. The reference's assembled order is the item's row order -- the + * local lines, the global view's lines, then the view separator. */ +TEST(unlimitedocr_runs_follow_the_reference_layout) { + Processor p; + REQUIRE_EQ(p.init(uocr_cfg(), [](const std::string&) { return std::vector{}; }, + uocr_marker), RAD_OK); + ImageMode gundam; + gundam.kind = ImageMode::Gundam; + std::shared_ptr it; + std::string why; + CHECK_OK(p.image_from(frame(1, 900, 1400), &it, &why, gundam)); + REQUIRE(it != nullptr); + + auto pm = std::make_shared(); + pm->items.push_back({ it, 1 }); /* after one text token */ + pm->layout(); + REQUIRE_EQ(pm->rope.runs.size(), (size_t)it->n_seg); + for (int32_t s = 0; s < it->n_seg; ++s) { + const RopeLayout::Run& r = pm->rope.runs[(size_t)s]; + CHECK(r.flat); + CHECK_EQ(r.tok, 1 + it->seg_at[(size_t)s]); + CHECK_EQ(r.n, (int32_t)(it->row_at(s + 1) - it->row_at(s))); + CHECK_EQ(r.base, 1 + it->seg_at[(size_t)s]); + CHECK_EQ(r.shift, 0); + CHECK_EQ(r.item, 0); + CHECK_EQ(r.row0, (int32_t)it->row_at(s)); + } + const int64_t n = (int64_t)it->expand.size(); + for (int64_t i = 0; i < n; ++i) { + int32_t pos[3]; + pm->rope.at(1 + i, pos); + CHECK_EQ(pos[0], (int32_t)(1 + i)); + CHECK_EQ(pos[1], (int32_t)(1 + i)); + CHECK_EQ(pos[2], (int32_t)(1 + i)); + } + /* The reference's arithmetic, spelled out: the global view's 16 lines of 16 features with a + * newline each plus the separator, then the local grid's lines (a newline after each). */ + const VisionConfig& c = p.config(); + CHECK_EQ(uocr_tokens(c, gundam, 1, 1), (int64_t)273); + ImageMode base; + base.kind = ImageMode::Base; + CHECK_EQ(uocr_tokens(c, base, 1, 1), (int64_t)273); + ImageMode page640; + page640.kind = ImageMode::Base; + page640.image_size = kUocrTile; + CHECK_EQ(uocr_tokens(c, page640, 1, 1), (int64_t)111); + CHECK_EQ(uocr_tokens(c, gundam, 3, 2), (int64_t)273 + (int64_t)(10 * 3 + 1) * 20); + CHECK_EQ(uocr_tokens(c, gundam, 4, 3), (int64_t)273 + (int64_t)(10 * 4 + 1) * 30); + + /* A request may restate the global view's side, but not cut crops at another tile or pad a + * page to a side that is not whole merged patches. */ + bool crop = false; + int32_t bs = 0, is = 0; + ImageMode b2048; + b2048.kind = ImageMode::Gundam; + b2048.base_size = 2048; + CHECK_EQ(uocr_mode(c, b2048, &crop, &bs, &is, &why), RAD_OK); + CHECK_EQ(uocr_tokens(c, b2048, 1, 1), (int64_t)(32 + 1) * 32 + 1); + ImageMode tile512; + tile512.kind = ImageMode::Gundam; + tile512.image_size = 512; + CHECK_EQ(uocr_mode(c, tile512, &crop, &bs, &is, &why), RAD_E_INVAL); + ImageMode odd; + odd.kind = ImageMode::Base; + odd.image_size = 700; + CHECK_EQ(uocr_mode(c, odd, &crop, &bs, &is, &why), RAD_E_INVAL); + ImageMode ok640; + ok640.kind = ImageMode::Base; + ok640.image_size = 640; + REQUIRE_EQ(uocr_mode(c, ok640, &crop, &bs, &is, &why), RAD_OK); + CHECK(!crop); + CHECK_EQ(is, 640); + + /* The multi-page form: two pages at the base mode are two runs of 273, back to back. */ + ImageMode base2; + base2.kind = ImageMode::Base; + std::shared_ptr a, b; + CHECK_OK(p.image_from(frame(0, 300, 500), &a, &why, base2)); + CHECK_OK(p.image_from(frame(1, 900, 1400), &b, &why, base2)); + auto mp = std::make_shared(); + mp->items.push_back({ a, 1 }); + mp->items.push_back({ b, 1 + (int32_t)a->expand.size() }); + mp->layout(); + CHECK_EQ((int64_t)mp->rope.runs.size(), (int64_t)4); + CHECK_EQ(a->expand.size(), (size_t)273); + CHECK_EQ(b->expand.size(), (size_t)273); + int32_t pos[3]; + mp->rope.at(1 + 273 + 100, pos); + CHECK_EQ(pos[0], (int32_t)(1 + 273 + 100)); +} + RAD_TEST_MAIN() diff --git a/tests/p4b_kv_ring_test.cpp b/tests/p4b_kv_ring_test.cpp new file mode 100644 index 00000000..a191c8a6 --- /dev/null +++ b/tests/p4b_kv_ring_test.cpp @@ -0,0 +1,281 @@ +/* p4b_kv_ring_test.cpp -- RAD_KV_RING, the declaration-side of R-SWA (Unlimited-OCR P4b). + * + * RAD_KV_RING is RAD_KV_WINDOW whose floor is each sequence's own prompt length: the group is + * sized for the whole context plus one ring a sequence (the ring among the fixed costs), never + * capped at a declared window, never given a window snapshot, and never checkpointed. These + * tests pin the core's admission of the kind -- the builder, the KV plan, and the chunk geometry + * -- and that a fixed-window (RAD_KV_WINDOW) group beside it is exactly what it was. + */ +#include "rad_test.h" + +#include "build/rad_build.h" +#include "mem/kv.h" +#include "mem/pools.h" +#include "rad_internal.h" +#include "sched/geometry.h" + +#include +#include + +using namespace rad; + +/* Handle 0 is the null group. */ +enum : int32_t { G_NULL = 0, G_RING = 1, G_FIXED = 2 }; + +static Config ring_config(int64_t max_tok = 128) { + Config c; + c.vram_weights_mib = 1; + c.vram_kv_mib = 4; + c.gpu_headroom_mib = 1; + c.host_pool_mib = 0; + c.max_seqs = 4; + c.max_tok = max_tok; + c.max_ctx = 4096; + c.checkpoint_interval = 512; + c.prefix_cache = true; + return c; +} + +/* One layer at `block`; the page is block * n_head_kv(2) * head_dim(8) * bf16(2) * K,V. */ +static KVGroupInfo ring_group(int64_t block, int64_t w, int layer = 0) { + KVGroupInfo k; + k.name = "rswa"; + k.decl.kind = RAD_KV_RING; + k.decl.dtype = RAD_BF16; + k.decl.n_head_kv = 2; + k.decl.head_dim = 8; + k.decl.window = w; + k.block_size = block; + k.layers = { layer }; + return k; +} + +static KVGroupInfo fixed_window_group(int64_t block, int64_t w, int layer = 0) { + KVGroupInfo k; + k.name = "swa"; + k.decl.kind = RAD_KV_WINDOW; + k.decl.dtype = RAD_BF16; + k.decl.n_head_kv = 2; + k.decl.head_dim = 8; + k.decl.window = w; + k.block_size = block; + k.layers = { layer }; + return k; +} + +static std::vector one(const KVGroupInfo& g) { + return { KVGroupInfo{}, g }; +} + +static int configure_pools(Pools& p, const Config& c) { + return p.configure(c, 0, &rad_malloc_allocator(), &rad_malloc_allocator()); +} + +/* A RAD_KV_RING group plans as a runtime window without anyone declaring it first (the kind is + * the declaration), and with the engine's declare_runtime_window() call it plans identically. + * The ring is a fixed cost: one ring a sequence on top of the context the split sizes. */ +TEST(a_ring_group_plans_as_a_runtime_window_with_the_ring_in_the_fixed_cost) { + const int64_t B = 128, W = 128; + const KVGroupInfo grp = ring_group(B, W); + const std::vector g = one(grp); + const Config cfg = ring_config(); + const int64_t page = B * 2 * 8 * 2 * 2; /* 8192 bytes */ + const int64_t ring_cost = (int64_t)cfg.max_seqs * ((W + B - 1) / B) * page; + + /* Without declare_runtime_window: the kind alone turns the plan over to runtime windows. */ + { + Pools pools; + REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, pools.kv())); + const KVGroupPlan* p = kv.plan(G_RING); + REQUIRE(p); + CHECK(p->runtime_win); + CHECK_EQ(p->runtime_tokens, W); + CHECK_EQ(kv.runtime_window_tokens(G_RING), W); + /* No window snapshot, so nothing to checkpoint: the window is each sequence's own. */ + CHECK(!p->win_snap); + CHECK(!kv.has_window_snapshot()); + CHECK_EQ(kv.checkpoint_bytes(), 0ll); + /* Sized for the whole context plus the ring a sequence, not capped at window_blocks. */ + CHECK_EQ(kv.ceiling(cfg.max_ctx), + kv.fixed_bytes() + (int64_t)cfg.max_seqs * (cfg.max_ctx / B) * page); + /* The ring is in the fixed cost (the plan's one alignment unit is for the group). */ + CHECK_EQ(kv.fixed_bytes(), (int64_t)RAD_ALIGN_UNIT + ring_cost); + /* The report calls it a ring, not a fixed window. */ + CHECK(has(kv.report(), "ring")); + CHECK(has(kv.report(), "runtime window W=128")); + } + + /* The engine's path: declare, then plan. Same plan, and the declaration is idempotent + * against the kind's own. */ + { + Pools pools; + REQUIRE_EQ(configure_pools(pools, cfg), RAD_OK); + KVManager kv; + CHECK_OK(kv.declare_runtime_window(G_RING, W)); + CHECK_OK(kv.configure(g, cfg, pools.kv())); + const KVGroupPlan* p = kv.plan(G_RING); + REQUIRE(p); + CHECK(p->runtime_win); + CHECK_EQ(p->runtime_tokens, W); + CHECK_EQ(kv.fixed_bytes(), (int64_t)RAD_ALIGN_UNIT + ring_cost); + CHECK(!kv.has_window_snapshot()); + /* A ring carries no declared-window cap; window_blocks still reports the ring's own + * rounding (rarely read: every plan path gates on runtime_win first). */ + CHECK_EQ(p->window_blocks, W / B + 1); + } + + /* A second W would contradict the ring already in the fixed cost. */ + { + KVManager kv; + CHECK_OK(kv.plan_groups(g, cfg)); + int rc = 0; + const std::string why = stderr_of([&] { rc = kv.declare_runtime_window(G_RING, W * 2); }); + CHECK_EQ(rc, RAD_E_INVAL); + CHECK(has(why, "already carries a runtime window")); + CHECK_EQ(kv.declare_runtime_window(G_RING, W), RAD_OK); + } +} + +/* A fixed-width window group beside a ring group keeps today's plan exactly, so gemma4_bf16's + * recycling and window snapshot are untouched by R-SWA's presence. */ +TEST(a_fixed_window_group_is_unaffected_beside_a_ring_group) { + const KVGroupInfo ring = ring_group(128, 128, /*layer=*/0); + const KVGroupInfo fixed = fixed_window_group(16, 64, /*layer=*/1); + std::vector both = { KVGroupInfo{}, ring, fixed }; + std::vector alone = { KVGroupInfo{}, fixed }; + Config cfg = ring_config(); + cfg.max_tok = 64; + + Pools pa, pb; + REQUIRE_EQ(configure_pools(pa, cfg), RAD_OK); + REQUIRE_EQ(configure_pools(pb, cfg), RAD_OK); + KVManager kva, kvb; + CHECK_OK(kva.declare_runtime_window(G_RING, 128)); + CHECK_OK(kva.configure(both, cfg, pa.kv())); + CHECK_OK(kvb.configure(alone, cfg, pb.kv())); + + const KVGroupPlan* p = kva.plan(G_FIXED); /* index 2: {null, ring, fixed} */ + const KVGroupPlan* q = kvb.plan(1); /* the fixed group alone: {null, fixed} */ + REQUIRE(p); + REQUIRE(q); + CHECK(!p->runtime_win); + CHECK_EQ(p->runtime_tokens, 0ll); + CHECK(p->win_snap); + CHECK(q->win_snap); + CHECK_EQ(p->window_blocks, q->window_blocks); + CHECK_EQ(p->window_blocks, 64 / 16 + 1); + CHECK_EQ(p->bytes_per_block, q->bytes_per_block); + CHECK_EQ(p->block_size, q->block_size); + /* Only the fixed group's window is checkpointed, and it is the same number either way. */ + CHECK_EQ(kva.checkpoint_bytes(), kvb.checkpoint_bytes()); + CHECK(kva.has_window_snapshot() == kvb.has_window_snapshot()); + /* The ring's own plan is the runtime window, not the fixed one. */ + CHECK(kva.plan(G_RING)->runtime_win); + CHECK(!kva.plan(G_RING)->win_snap); +} + +/* The chunk geometry must not advertise a window snapshot for a ring: there is none to take, and + * an interval grid would only claim one. A fixed window group keeps it exactly. */ +TEST(a_ring_group_gets_no_window_snapshot_geometry) { + Config cfg = ring_config(); + Program prog; + prog.kv_groups = one(ring_group(128, 128)); + ChunkGeometry geo; + CHECK_OK(chunk_geometry_resolve(prog, cfg, &geo)); + CHECK_EQ(geo.attn_block, 128ll); + CHECK_EQ(geo.quantum, 128ll); + CHECK(!geo.window_ckpt); + CHECK_EQ(geo.checkpoint_interval, 0ll); + CHECK(!geo.checkpoints()); + + /* The same group declared as a fixed window keeps the snapshot geometry (gemma4's). */ + Program w; + w.kv_groups = one(fixed_window_group(128, 128)); + CHECK_OK(chunk_geometry_resolve(w, cfg, &geo)); + CHECK(geo.window_ckpt); + CHECK_EQ(geo.checkpoint_interval, 512ll); + CHECK(geo.checkpoints()); + + /* A ring beside a fixed window still snapshots the fixed one, as a hybrid always did. */ + Program h; + h.kv_groups = { KVGroupInfo{}, ring_group(128, 128, 0), fixed_window_group(128, 128, 1) }; + CHECK_OK(chunk_geometry_resolve(h, cfg, &geo)); + CHECK_EQ(geo.attn_block, 128ll); + CHECK(geo.window_ckpt); + CHECK_EQ(geo.checkpoint_interval, 512ll); +} + +/* ================================================================== the declare phase */ + +static std::string kernels_dir() { return home() + "/testkernels"; } + +static int load_plugins(Registry& r) { + return r.load_dir(kernels_dir(), { "radtest_over", "radtest_base" }); +} + +static rad_op decl_t_attn(Builder& b) { + const RadParam p[] = { RAD_RANGE("q_len", 1, 16), RAD_INT("head_dim", 128), + RAD_INT("window", 0), RAD_INT("block_size", 16), + RAD_INT("causal", 1), RAD_INT("n_head", 8), + RAD_STR("kv_dtype", "bf16") }; + return b.decl_op("t_attn", p, 7, nullptr, 0); +} + +static RadModelMeta make_meta() { + RadModelMeta m{}; + m.arch_id = "test_arch"; + m.name = "test_model"; + m.quant = "bf16"; + m.n_layers = 2; + m.n_embd = 4096; + return m; +} + +static RadBuildCtx make_ctx() { + RadBuildCtx c{}; + c.rank = 0; + c.world_size = 1; + c.max_tok = 8192; + c.max_seqs = 256; + c.max_ctx = 4096; + c.scope = ""; + return c; +} + +/* The ABI admits the kind, its block size still comes off the resolved attention kernel, and its + * page is sized as a paged group's (so KVManager::plan_groups accepts it). */ +TEST(the_builder_accepts_a_ring_group) { + Registry reg; + if (load_plugins(reg) < 0) ARTIFACT_MISSING("the test plugins in " + kernels_dir()); + + Builder b(reg, make_meta(), make_ctx()); + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_RING; + kd.dtype = RAD_BF16; + kd.window = 128; + kd.n_head_kv = 8; + kd.head_dim = 128; + const rad_kvgroup g = b.decl_kv_group("kv_ring", &kd); + CHECK(g == 1); + CHECK_EQ((int)b.program().kv_groups[g].decl.kind, (int)RAD_KV_RING); + + decl_t_attn(b); + /* 16 because the resolved test kernel's constraints say so. */ + CHECK_EQ(b.kv_block_size(g), 16); + CHECK_OK(b.bind_layer_kv(0, g)); + CHECK_OK(b.bind_layer_kv(1, g)); + b.finish(); + + const KVGroupInfo& gi = b.program().kv_groups[g]; + CHECK_EQ(gi.block_size, 16ll); + CHECK_EQ(gi.decl.window, 128ll); + /* One page covers both bound layers, as for a full or fixed-window group. */ + CHECK_EQ(gi.bytes_per_block, 2 * 16 * 8 * 128 * 2 * 2); + CHECK_EQ(gi.bytes_per_state, 0ll); + /* Named, not "?". */ + CHECK(std::strcmp(bld_kv_kind_name(RAD_KV_RING), "?") != 0); +} + +RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 6f2c9a5e..142132cc 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -953,8 +953,8 @@ TEST(op_vocabulary) { "gdn_recurrent_update", "gdn_conv_recurrent_update", "gdn_gated_rmsnorm", "all_reduce", "all_gather", "embed_lookup", "logits_gemm", - "sample_penalties", "sample_dry", "sample_temp", "sample_topk", "sample_topp", - "sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick", + "sample_penalties", "sample_dry", "sample_ngram_ban", "sample_temp", "sample_topk", + "sample_topp", "sample_minp", "sample_typical", "sample_xtc", "sample_mask", "sample_pick", "sample_argmax", "sample_merge_topk", "sample_logprobs", /* The image generator's (arch/qwenimage21): a DiT's modulation and gates, the per-lane * sampler state, the VAE's convolutions and shortcuts, attention over a cached prefix. */ @@ -994,6 +994,8 @@ TEST(op_vocabulary) { /* LTX-2.5's diffusion decoder: its rotary's voxel coordinates and its neighborhood * attention. */ "vol_index", "attn_na3d", + /* Unlimited-OCR's SAM tower: windowed attention with decomposed relative position. */ + "sam_attn", }; for (const char* op : kOps) { if (!kern(op)) fprintf(stderr, " missing op '%s'\n", op); @@ -5099,6 +5101,181 @@ TEST(op_sample_pick_draws_the_specified_uniform) { CHECK(agree > 60); } +/* ================================================================== the n-gram ban */ +/* Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor, ported straight from + * modeling_unlimitedocr.py:353-383 as the oracle's second formulation. `s` is the row's history + * oldest first; the result marks every global token id it bans. */ +static std::vector ref_ngram_banned(const std::vector& s, int n, int window) { + std::vector banned(256, 0); + if (n <= 0 || (int64_t)s.size() < (int64_t)n) return banned; + const int64_t len = (int64_t)s.size(); + const int64_t search_start = window > 0 ? std::max(0, len - window) : 0; + const int64_t search_end = len - n + 1; + if (search_end <= search_start) return banned; + std::vector prefix; + if (n > 1) prefix.assign(s.begin() + (size_t)(len - n + 1), s.end()); + for (int64_t idx = search_start; idx < search_end; ++idx) { + bool match = true; + for (size_t j = 0; j < prefix.size(); ++j) + if (s[(size_t)(idx + (int64_t)j)] != prefix[j]) { match = false; break; } + if (!match) continue; + const int32_t tok = s[(size_t)(idx + n - 1)]; + if (tok >= 0 && tok < (int32_t)banned.size()) banned[(size_t)tok] = 1; + } + return banned; +} + +/* The op over one row: returns the banned global ids it wrote as -infinity, and whether every other + * column is bit-for-bit its input. */ +static std::vector ref_ngram_op(const std::vector& s, int n, int window, + int n_vocab, bool* untouched_out) { + const int64_t H = 8; /* the history plane's extent in these cases */ + T lg(RAD_F32, {1, n_vocab}); + std::vector in((size_t)n_vocab); + for (int64_t i = 0; i < n_vocab; ++i) in[(size_t)i] = 0.5f * (float)i - 1.0f; + lg.f(in); + T hist(RAD_I32, {1, H}); + std::vector hv((size_t)H, 0); + for (size_t i = 0; i < s.size() && i < (size_t)H; ++i) hv[i] = s[i]; + hist.n(hv); + + SP sp(1); + sp[0].hist_off = 0; + sp[0].hist_len = (int32_t)std::min(s.size(), (size_t)H); + T ng(RAD_I32, {1, 2}); ng.n({ n, window }); + + A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", n_vocab); + if (run("sample_ngram_ban", a) != RAD_OK) return { -99 }; + + std::vector banned; + bool untouched = true; + for (int64_t i = 0; i < n_vocab; ++i) { + const float v = lg.at(i); + if (std::isinf(v) && v < 0.0f) banned.push_back((int32_t)i); + else if (std::memcmp(&v, &in[(size_t)i], 4) != 0) untouched = false; + } + if (untouched_out) *untouched_out = untouched; + return banned; +} + +/* The reference's banned set and the op's, over: + * - every binary history of length 0..6, n 1..4 and windows 0, 2, 3, 4 and 64. A binary + * alphabet makes repeats and the "abcabc" shapes dense, and lengths short of, equal to and + * longer than n cover the early exits; + * - 200 random histories over five ids, lengths 1..24, n 1..8 and windows 0..16, where the + * window boundary falls inside repeated runs; + * - the named shapes: an n-gram whose last token is the window's last (idx == search_end - 1), + * an n-gram that starts at search_start while an earlier copy starts before it, n == 1 (the + * empty prefix, every window token banned) and n == 0 (off). */ +TEST(op_sample_ngram_ban_matches_the_reference_processor) { + int64_t trials = 0, mismatches = 0, bans = 0; + bool all_untouched = true; + + auto trial = [&](const std::vector& s_in, int n, int window) { + /* The engine's plane holds the LAST H tokens of the sequence (build_step truncates the + * oldest), so the oracle and the op must both see that span. */ + const std::vector s = s_in.size() > 8 + ? std::vector(s_in.end() - 8, s_in.end()) + : s_in; + const int n_vocab = 8; + bool untouched = true; + const std::vector got = ref_ngram_op(s, n, window, n_vocab, &untouched); + if (got.size() == 1 && got[0] == -99) { ++mismatches; return; } + const std::vector want = ref_ngram_banned(s, n, window); + ++trials; + bans += (int64_t)got.size(); + all_untouched = all_untouched && untouched; + int64_t live = 0; + for (int id = 0; id < n_vocab; ++id) live += want[(size_t)id] ? 1 : 0; + if (live != (int64_t)got.size()) { ++mismatches; return; } + for (int32_t id : got) + if (id < 0 || id >= n_vocab || !want[(size_t)id]) { ++mismatches; return; } + }; + + /* Every binary history of length 0..6. */ + for (int64_t len = 0; len <= 6; ++len) { + for (int64_t bits = 0; bits < (int64_t)1 << len; ++bits) { + std::vector s; + for (int64_t i = 0; i < len; ++i) s.push_back((int32_t)((bits >> i) & 1)); + for (int n = 1; n <= 4; ++n) + for (int w : { 0, 2, 3, 4, 64 }) trial(s, n, w); + } + } + + /* Random histories over five ids. */ + uint32_t rs = 0x9e3779b9u; + for (int it = 0; it < 200; ++it) { + rs = rs * 1664525u + 1013904223u; + const int64_t len = 1 + (int64_t)((rs >> 8) % 24u); + std::vector s((size_t)len); + for (int64_t i = 0; i < len; ++i) { + rs = rs * 1664525u + 1013904223u; + s[(size_t)i] = (int32_t)((rs >> 12) % 5u); + } + rs = rs * 1664525u + 1013904223u; + const int n = 1 + (int)((rs >> 8) % 8u); + rs = rs * 1664525u + 1013904223u; + const int w = (int)((rs >> 8) % 17u); + trial(s, n, w); + } + + /* The named shapes. [4,1,2, 4,1,2, 4,1,2] with n 3 and window 6: the newest complete n-gram + * starts exactly at search_end - 1, and the earlier copy at search_start bans the same token; + * window 3 moves search_start so that only the spanning copy is searched. */ + trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 6); + trial({ 4, 1, 2, 4, 1, 2, 4, 1, 2 }, 3, 3); + trial({ 1, 1, 1, 1, 1, 1 }, 2, 4); /* repeated tokens, every position matches */ + trial({ 1, 1, 1, 1, 1, 1 }, 1, 3); /* n 1: the entire window is banned */ + trial({ 1, 1, 1, 1, 1, 1 }, 0, 3); /* off */ + trial({ 7, 2, 7, 2, 7 }, 2, 0); /* window 0: the whole span */ + + CHECK(trials > 2500); + CHECK(mismatches == 0); + CHECK(bans > 0); + /* Every column the reference does not ban is bit-for-bit its input: the op writes -infinity + * and nothing else, so penalties and temperature see the same numbers. */ + CHECK(all_untouched); +} + +/* Off is the default, and off must be invisible to greedy decoding: sample_ngram_ban writes + * nothing for a row with ngram_ban_n 0, so the argmax over the same row is the same token. With + * the ban on, the outcome changes exactly when the ban covers the argmax's token. */ +TEST(op_sample_ngram_ban_off_leaves_greedy_decoding_unchanged) { + /* Token 5 is the clear maximum. Its id appears 4 times in the history, so both the ban and the + * penalties have something to do; the ban is off here. */ + T hist(RAD_I32, {1, 8}); hist.n({ 5, 1, 5, 2, 5, 3, 5, 1 }); + + auto greedy = [&](int n, int window, std::vector* after) { + T lg(RAD_F32, {1, 8}); + lg.f({ 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f }); + SP sp(1); + sp[0].hist_off = 0; + sp[0].hist_len = 8; + T ng(RAD_I32, {1, 2}); ng.n({ n, window }); + A a; a.t(lg).t(sp.operand()).t(hist).t(ng).i("M", 1).i("n_vocab", 8); + CHECK_OK(run("sample_ngram_ban", a)); + T tk(RAD_I32, {1}); + A b; b.t(lg).t(sp.operand()).t(tk).i("M", 1).i("n_vocab", 8); + CHECK_OK(run("sample_argmax", b)); + if (after) + for (int64_t i = 0; i < 8; ++i) after->push_back(lg.at(i)); + return tk.iat(0); + }; + + std::vector off_logits; + CHECK_EQ(greedy(0, 0, &off_logits), 5); + /* Bit-identical to the input: the stage did not run. */ + static const float kIn[8] = { 0.0f, 0.1f, 0.2f, 0.3f, 0.4f, 4.0f, 0.5f, 0.6f }; + for (int64_t i = 0; i < 8; ++i) CHECK(std::memcmp(&off_logits[(size_t)i], &kIn[i], 4) == 0); + + /* The history's prefix (5,1) is followed by token 5 at positions 0 and 2 in [5,1,5,2,5,3,5,1]: + * with n 2 the ban covers 5, so greedy moves to the next best (token 7). */ + CHECK_EQ(greedy(2, 8, nullptr), 7); + /* A ban that only names other tokens leaves the argmax alone: with n 2 and a one-token window, + * search_start == search_end - 1 is impossible (window 1 < n), so nothing is banned. */ + CHECK_EQ(greedy(2, 1, nullptr), 5); +} + /* ================================================================== failure modes */ /* Nothing that did not do the work returns RAD_OK. The engine turns these into a named abort * rather than a silent fallback (spec §17). */ @@ -7847,6 +8024,11 @@ std::vector geometries() { .s("kv_dtype", "f32").i("n_head", 4).i("ctx", 9)), G("attn_dense", "M", 6, a.i("M", R).i("head_dim", 8).i("gqa", 2).i("causal", 1) .s("dtype", "f32").i("n_head", 4)), + /* One-row segments, so M is also the segment count (n_seq, the description's hint for + * cu_seqlens). The real grids are op_sam_attn_*'s. */ + G("sam_attn", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("grid_h", 1) + .i("grid_w", 1).i("window", 1).i("n_seq", R) + .d("scale", 0.3535533905932738).s("dtype", "bf16")), G("kv_store", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head_kv", 2).i("block_size", 4) .s("kv_dtype", "f32")), G("rope", "M", 3, a.i("M", R).i("head_dim", 8).i("n_head", 2).i("n_head_kv", 1) @@ -7914,6 +8096,7 @@ std::vector geometries() { G("logits_gemm", "M", 3, a.i("M", R).i("n_vocab", 20).i("n_embd", 8).s("dtype", "f32")), G("sample_penalties", "M", 2, a.i("M", R).i("n_vocab", 64)), G("sample_dry", "M", 2, a.i("M", R).i("n_vocab", 64)), + G("sample_ngram_ban", "M", 2, a.i("M", R).i("n_vocab", 64)), G("sample_temp", "M", 2, a.i("M", R).i("n_vocab", 64)), G("sample_topk", "M", 2, a.i("M", R).i("n_vocab", 64)), G("sample_topp", "M", 2, a.i("M", R).i("n_cand", 16)), @@ -8497,3 +8680,338 @@ TEST(gather_rows_moves_packed_codes_exactly) { const float wf[6] = { 0.5f, 1.0f, -2.0f, 6.0f, 0.0f, 4.0f }; for (int i = 0; i < 6; ++i) CHECK_EQ(e.at(i), wf[i]); } + +/* ================================================================== sam_attn + * Unlimited-OCR's SAM tower attention (arch/common/rad_block_sam.h, libref/ref_sam_attn.cpp). + * + * The expected values are a direct port of deepencoder.py's Attention.forward / + * add_decomposed_rel_pos / window_partition in double, not a second call into libref: the padding + * rule, the per-head rel_pos channel dot and the resampling of a table along its row axis each have + * a way to be wrong that an oracle sharing libref's code could not see. */ + +namespace { + +struct SamIn { + int64_t gh = 1, gw = 1, win = 0, nh = 1, hd = 1, nseq = 1; + std::vector q, k, v, rh, rw; /* [M, nh*hd] and [2*L-1, hd], row-major */ + int64_t W() const { return nh * hd; } + int64_t rows() const { return nseq * gh * gw; } + int64_t tab() const { return 2 * (win > 0 ? win : (gh > gw ? gh : gw)) - 1; } +}; + +/* A deterministic draw in [-1, 1]: index-driven, so a wrong pitch or row map reads other numbers. */ +static void sam_fill(SamIn& in, uint32_t seed) { + uint32_t s = seed | 1u; + auto next = [&s] { s = s * 1664525u + 1013904223u; return ((s >> 8) & 0xffffu) / 32767.5f - 1.0f; }; + in.q.resize((size_t)(in.rows() * in.W())); + in.k.resize(in.q.size()); + in.v.resize(in.q.size()); + for (auto* x : { &in.q, &in.k, &in.v }) + for (auto& f : *x) f = next(); + in.rh.resize((size_t)(in.tab() * in.hd)); + in.rw.resize(in.rh.size()); + for (auto* x : { &in.rh, &in.rw }) + for (auto& f : *x) f = 0.1f * next(); +} + +/* F.interpolate(..., size=want, mode="linear"), align_corners False, over dim 0. */ +static std::vector sam_table(const std::vector& raw, int64_t hd, int64_t want) { + const int64_t rows = hd > 0 ? (int64_t)raw.size() / hd : 0; + std::vector out((size_t)(want * hd), 0.0); + const double span = (double)rows / (double)want; + for (int64_t d = 0; d < want; ++d) { + double src = ((double)d + 0.5) * span - 0.5; + if (src < 0.0) src = 0.0; + if (src > (double)(rows - 1)) src = (double)(rows - 1); + const int64_t i0 = (int64_t)src, i1 = i0 + 1 < rows ? i0 + 1 : i0; + const double f = src - (double)i0; + for (int64_t c = 0; c < hd; ++c) + out[(size_t)(d * hd + c)] = raw[(size_t)(i0 * hd + c)] * (1.0 - f) + + raw[(size_t)(i1 * hd + c)] * f; + } + return out; +} + +/* `drop_pads` is the WRONG reading of window_partition: pad keys removed from the softmax instead of + * attending as zeros. Used only to prove a case can tell the two apart. */ +static std::vector sam_oracle(const SamIn& in, bool drop_pads = false) { + const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows(); + const int64_t th = in.win > 0 ? in.win : in.gh, tw = in.win > 0 ? in.win : in.gw; + const std::vector Rh = sam_table(in.rh, in.hd, 2 * th - 1); + const std::vector Rw = sam_table(in.rw, in.hd, 2 * tw - 1); + const double scale = 1.0 / std::sqrt((double)in.hd); + std::vector out((size_t)(M * W), 0.0f); + std::vector logits, acc; + for (int64_t s = 0; s < in.nseq; ++s) + for (int64_t ih = 0; ih < in.gh; ++ih) + for (int64_t iw = 0; iw < in.gw; ++iw) { + const int64_t row = s * R + ih * in.gw + iw; + const int64_t ty = in.win > 0 ? ih / in.win : 0; + const int64_t tx = in.win > 0 ? iw / in.win : 0; + const int64_t lh = ih - ty * th, lw = iw - tx * tw; + for (int64_t h = 0; h < in.nh; ++h) { + const float* qf = &in.q[(size_t)(row * W + h * in.hd)]; + logits.clear(); + std::vector kvrow; + for (int64_t jh = 0; jh < th; ++jh) { + const double* hrp = &Rh[(size_t)((lh - jh + th - 1) * in.hd)]; + double hr = 0.0; + for (int64_t c = 0; c < in.hd; ++c) hr += qf[c] * hrp[c]; + for (int64_t jw = 0; jw < tw; ++jw) { + const int64_t kh = ty * th + jh, kw = tx * tw + jw; + const bool real = kh < in.gh && kw < in.gw; + if (drop_pads && !real) continue; + const double* wrp = &Rw[(size_t)((lw - jw + tw - 1) * in.hd)]; + double sc = hr; + for (int64_t c = 0; c < in.hd; ++c) sc += qf[c] * wrp[c]; + if (real) { + const float* kf = &in.k[(size_t)((s * R + kh * in.gw + kw) * W + + h * in.hd)]; + double d = 0.0; + for (int64_t c = 0; c < in.hd; ++c) d += qf[c] * kf[c]; + sc += scale * d; + kvrow.push_back(s * R + kh * in.gw + kw); + } else { + kvrow.push_back(-1); + } + logits.push_back(sc); + } + } + double mx = -INFINITY; + for (double v : logits) mx = std::max(mx, v); + double sum = 0.0; + for (double& v : logits) { v = std::exp(v - mx); sum += v; } + acc.assign((size_t)in.hd, 0.0); + for (size_t j = 0; j < logits.size(); ++j) { + if (kvrow[j] < 0) continue; + const float* vf = &in.v[(size_t)(kvrow[j] * W + h * in.hd)]; + const double p = logits[j] / sum; + for (int64_t c = 0; c < in.hd; ++c) acc[(size_t)c] += p * vf[c]; + } + for (int64_t c = 0; c < in.hd; ++c) + out[(size_t)(row * W + h * in.hd + c)] = (float)acc[(size_t)c]; + } + } + return out; +} + +/* Run the op; `pitch` > 0 stores every operand at that row pitch (a column slice of a wider + * buffer), 0 uses W. Returns the output read back at the same pitch. */ +static std::vector sam_run(const SamIn& in, int64_t pitch, int* rc) { + const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows(); + const int64_t ld = pitch > 0 ? pitch : W; + T q(RAD_BF16, { M, ld }), k(RAD_BF16, { M, ld }), v(RAD_BF16, { M, ld }), o(RAD_BF16, { M, ld }); + for (int64_t r = 0; r < M; ++r) + for (int64_t c = 0; c < W; ++c) { + st_dt(RAD_BF16, q.t.data, r * ld + c, in.q[(size_t)(r * W + c)]); + st_dt(RAD_BF16, k.t.data, r * ld + c, in.k[(size_t)(r * W + c)]); + st_dt(RAD_BF16, v.t.data, r * ld + c, in.v[(size_t)(r * W + c)]); + } + T rh(RAD_BF16, { in.tab(), in.hd }), rw(RAD_BF16, { in.tab(), in.hd }); + for (size_t i = 0; i < in.rh.size(); ++i) { + st_dt(RAD_BF16, rh.t.data, (int64_t)i, in.rh[i]); + st_dt(RAD_BF16, rw.t.data, (int64_t)i, in.rw[i]); + } + T cu(RAD_I32, { in.nseq + 1 }); + for (int64_t s = 0; s <= in.nseq; ++s) st_int(RAD_I32, cu.t.data, s, s * R); + + A a; + /* A pitch wider than W is a strided VIEW of the storage: shape [M, W], stride[0] = ld, which is + * what the tower's column slices of one fused projection are. */ + auto view = [&](const T& x) { + RadTensor v = x.t; + v.shape[1] = W; + v.stride[0] = ld; + v.stride[1] = 1; + return v; + }; + a.ts.push_back(view(q)); + a.ts.push_back(view(k)); + a.ts.push_back(view(v)); + a.t(cu); + a.ts.push_back(view(o)); + a.t(rh).t(rw) + .i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh).i("grid_w", in.gw) + .i("window", in.win).d("scale", 1.0 / std::sqrt((double)in.hd)).s("dtype", "bf16"); + *rc = run("sam_attn", a); + std::vector out((size_t)(M * W), 0.0f); + for (int64_t r = 0; r < M; ++r) + for (int64_t c = 0; c < W; ++c) out[(size_t)(r * W + c)] = ld_dt(RAD_BF16, o.t.data, r * ld + c); + return out; +} + +/* Compare two [M, W] rows: max absolute difference and the number outside 2e-3 + 2e-2 * |want|. */ +static void sam_cmp(const std::vector& got, const std::vector& want, float* maxd, + int64_t* bad) { + *maxd = 0.0f; + *bad = 0; + for (size_t i = 0; i < want.size(); ++i) { + const float d = std::fabs(got[i] - want[i]); + if (d > *maxd) *maxd = d; + if (d > 2e-3f + 2e-2f * std::fabs(want[i])) ++*bad; + } +} + +} /* namespace */ + +/* One row, one key: the softmax is 1 and the output is v, bit for bit after bf16 rounding. The same + * with window 1 over a 1x3 grid, where every row is a tile of its own. */ +TEST(op_sam_attn_single_key_returns_v) { + SamIn one; + one.gh = one.gw = 1; one.win = 1; one.nh = 1; one.hd = 4; + one.q = { 3.0f, -1.0f, 0.5f, 2.0f }; + one.k = { 1.0f, 2.0f, 3.0f, 4.0f }; + one.v = { 0.5f, -1.0f, 2.0f, 0.25f }; + one.rh.assign(4, 0.0f); + one.rw.assign(4, 0.0f); + int rc = 0; + std::vector got = sam_run(one, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + for (int64_t c = 0; c < 4; ++c) CHECK_EQ(got[(size_t)c], one.v[(size_t)c]); + + SamIn strip = one; + strip.gh = 1; strip.gw = 3; + strip.q = { 1, 2, 3, 4, -1, 0, 1, -2, 0.5f, 0.5f, 0.5f, 0.5f }; + strip.k = { 1, 0, 0, 0, 1, 1, 0, 0, 2, 2, 2, 2 }; + strip.v = { 0.5f, 0.25f, 0.125f, 0.0625f, -0.5f, -0.25f, -0.125f, -0.0625f, + 9.0f, 8.0f, 7.0f, 6.0f }; + strip.rh.assign(4, 0.25f); + strip.rw.assign(4, -0.25f); + got = sam_run(strip, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + for (int64_t i = 0; i < 12; ++i) CHECK_EQ(got[(size_t)i], strip.v[(size_t)i]); +} + +/* Window 14 over 16x16: the grid pads to 28x28, so the last two rows and columns of the last window + * are ZERO keys that still take part in the softmax. Compared against the double port, then against + * the port with the pads removed: the two differ, which is what makes this case able to see the + * rule. */ +TEST(op_sam_attn_windowed_matches_the_reference_port) { + SamIn in; + in.gh = 16; in.gw = 16; in.win = 14; in.nh = 2; in.hd = 8; + sam_fill(in, 0x51ed2701u); + int rc = 0; + const std::vector got = sam_run(in, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + float maxd = 0.0f; int64_t bad = 0; + const std::vector want = sam_oracle(in); + sam_cmp(got, want, &maxd, &bad); + CHECK_EQ(bad, 0LL); + CHECK(maxd < 2e-3f); + + const std::vector nopad = sam_oracle(in, true); + float pad_max = 0.0f; + for (size_t i = 0; i < nopad.size(); ++i) + pad_max = std::max(pad_max, std::fabs(nopad[i] - want[i])); + CHECK(pad_max > 1e-3f); /* the case can tell the two rules apart */ +} + +/* Window 0: the whole segment is one tile, over a square grid and over a 6x10 one whose rel_pos + * tables are 2*10-1 rows long and must be resampled to 2*6-1 for the row axis. */ +TEST(op_sam_attn_global_and_non_square) { + SamIn sq; + sq.gh = 16; sq.gw = 16; sq.win = 0; sq.nh = 2; sq.hd = 8; + sam_fill(sq, 0xa341316cu); + int rc = 0; + float maxd = 0.0f; int64_t bad = 0; + sam_cmp(sam_run(sq, 0, &rc), sam_oracle(sq), &maxd, &bad); + CHECK_EQ(rc, (int)RAD_OK); + CHECK_EQ(bad, 0LL); + CHECK(maxd < 2e-3f); + + SamIn ns; + ns.gh = 6; ns.gw = 10; ns.win = 0; ns.nh = 3; ns.hd = 4; + sam_fill(ns, 0x7f4a7c15u); + CHECK_EQ(ns.tab(), 19LL); + sam_cmp(sam_run(ns, 0, &rc), sam_oracle(ns), &maxd, &bad); + CHECK_EQ(rc, (int)RAD_OK); + CHECK_EQ(bad, 0LL); + CHECK(maxd < 2e-3f); +} + +/* Two segments: each is one tile (window 0). The second segment's rows are computed from its own + * data only, so changing the first segment's q/k/v must leave them bit for bit unchanged while the + * first segment's move. */ +TEST(op_sam_attn_segments_are_independent) { + SamIn in; + in.gh = 8; in.gw = 8; in.win = 0; in.nh = 2; in.hd = 8; in.nseq = 2; + sam_fill(in, 0x2545f491u); + int rc = 0; + const std::vector base = sam_run(in, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + float maxd = 0.0f; int64_t bad = 0; + sam_cmp(base, sam_oracle(in), &maxd, &bad); + CHECK_EQ(bad, 0LL); + CHECK(maxd < 2e-3f); + + SamIn alt = in; + for (int64_t i = 0; i < 64 * in.W(); ++i) { /* the first segment's rows */ + alt.q[(size_t)i] = -alt.q[(size_t)i]; + alt.k[(size_t)i] += 0.25f; + } + const std::vector moved = sam_run(alt, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + const size_t half = base.size() / 2; + bool first_changed = false, second_same = true; + for (size_t i = 0; i < half; ++i) + first_changed |= base[i] != moved[i]; + for (size_t i = half; i < base.size(); ++i) + second_same &= base[i] == moved[i]; + CHECK(first_changed); + CHECK(second_same); +} + +/* The tower's q/k/v are the three column slices of one fused projection, so every operand is read + * at a row pitch wider than W. The result must be bit-identical to the dense-pitch one. */ +TEST(op_sam_attn_reads_at_a_row_pitch) { + SamIn in; + in.gh = 16; in.gw = 16; in.win = 14; in.nh = 2; in.hd = 8; + sam_fill(in, 0x1234567u); + int rc = 0; + const std::vector dense = sam_run(in, 0, &rc); + CHECK_EQ(rc, (int)RAD_OK); + const std::vector strided = sam_run(in, in.W() + 3, &rc); + CHECK_EQ(rc, (int)RAD_OK); + for (size_t i = 0; i < dense.size(); ++i) CHECK_EQ(strided[i], dense[i]); +} + +/* Refusals: a segment that is not one grid, an absent table, a negative window, a zero head. */ +TEST(op_sam_attn_refuses_malformed_geometry) { + SamIn in; + in.gh = 4; in.gw = 4; in.win = 0; in.nh = 1; in.hd = 4; in.nseq = 2; + sam_fill(in, 0x9e3779b9u); + const int64_t W = in.W(), R = in.gh * in.gw, M = in.rows(); + + auto build = [&](T& q, T& k, T& v, T& cu, T& o, T& rh, T& rw, A& a, int64_t window) { + a.t(q).t(k).t(v).t(cu).t(o).t(rh).t(rw) + .i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh) + .i("grid_w", in.gw).i("window", window).d("scale", 0.5).s("dtype", "bf16"); + }; + T q(RAD_BF16, { M, W }), k(RAD_BF16, { M, W }), v(RAD_BF16, { M, W }), o(RAD_BF16, { M, W }); + q.f(in.q); k.f(in.k); v.f(in.v); + T rh(RAD_BF16, { in.tab(), in.hd }), rw(RAD_BF16, { in.tab(), in.hd }); + rh.f(in.rh); rw.f(in.rw); + + /* cu says the first segment is half a grid. */ + T cu_short(RAD_I32, { 3 }); cu_short.n({ 0, R / 2, M }); + A a1; build(q, k, v, cu_short, o, rh, rw, a1, 0); + CHECK_EQ(run("sam_attn", a1), (int)RAD_E_SHAPE); + + T cu_ok(RAD_I32, { 3 }); cu_ok.n({ 0, R, M }); + A a2; build(q, k, v, cu_ok, o, rh, rw, a2, 0); + CHECK_OK(run("sam_attn", a2)); + + /* An absent rel_pos table. */ + A a3; a3.t(q).t(k).t(v).t(cu_ok).t(o).t(rh).tnull() + .i("M", M).i("head_dim", in.hd).i("n_head", in.nh).i("grid_h", in.gh) + .i("grid_w", in.gw).i("window", 0).d("scale", 0.5).s("dtype", "bf16"); + CHECK_EQ(run("sam_attn", a3), (int)RAD_E_INVAL); + + /* A negative window, and a zero head width. */ + A a4; build(q, k, v, cu_ok, o, rh, rw, a4, -1); + CHECK_EQ(run("sam_attn", a4), (int)RAD_E_SHAPE); + A a5; a5.t(q).t(k).t(v).t(cu_ok).t(o).t(rh).t(rw) + .i("M", M).i("head_dim", 0).i("n_head", in.nh).i("grid_h", in.gh) + .i("grid_w", in.gw).i("window", 0).d("scale", 0.5).s("dtype", "bf16"); + CHECK_EQ(run("sam_attn", a5), (int)RAD_E_SHAPE); +} diff --git a/tests/server_test.cpp b/tests/server_test.cpp index c8862fa9..18aaf205 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -4619,6 +4619,9 @@ TEST(every_request_key_is_served_refused_or_ignored_as_its_list_says) { { "timings_per_token", { true, json::parse(R"({"stream":true})") } }, { "return_progress", { true, json::parse(R"({"stream":true})") } }, { "session_id", { "s", none } }, { "n_probs", { 2, none } }, + /* The windowed no-repeat-ngram ban and Unlimited-OCR's picture mode. */ + { "ngram_ban_n", { 35, none } }, { "ngram_window", { 128, none } }, + { "images_config", { "gundam", none } }, { "messages", { json::parse(R"([{"role":"user","content":"yo"}])"), none } }, { "tools", { json::parse(R"([{"type":"function","function":{"name":"f"}}])"), none } }, { "tool_choice", { "auto", none } }, diff --git a/tests/uocr_golden.h b/tests/uocr_golden.h new file mode 100644 index 00000000..6d35c3e0 --- /dev/null +++ b/tests/uocr_golden.h @@ -0,0 +1,138 @@ +/* uocr_golden.h -- GENERATED by mkuocrgolden.py from the checkpoint's remote code; do not edit. */ +#pragma once +#include + +static const int32_t kUocrPatch = 16, kUocrDownsample = 4; +static const int32_t kUocrBaseSize = 1024, kUocrTile = 640; +static const int32_t kUocrMinTiles = 2, kUocrMaxTiles = 32; +static const bool kUocrCropMode = true; +static const int32_t kUocrImageToken = 128815; + +struct GoldUocrGrid { int64_t h, w; int32_t cols, rows; }; +static const GoldUocrGrid kUocrGrid[] = { + { 1, 1, 1, 1 }, + { 40, 30, 1, 1 }, + { 100, 100, 1, 1 }, + { 300, 500, 1, 1 }, + { 500, 300, 1, 1 }, + { 640, 640, 1, 1 }, + { 641, 641, 2, 2 }, + { 500, 700, 4, 3 }, + { 700, 500, 3, 4 }, + { 800, 1000, 5, 4 }, + { 1000, 800, 4, 5 }, + { 1024, 1024, 2, 2 }, + { 1280, 1024, 4, 5 }, + { 1024, 1280, 5, 4 }, + { 900, 1400, 3, 2 }, + { 1400, 900, 2, 3 }, + { 2000, 600, 3, 10 }, + { 600, 2000, 10, 3 }, + { 2400, 400, 1, 6 }, + { 400, 2400, 6, 1 }, + { 1080, 1920, 7, 4 }, + { 1920, 1080, 4, 7 }, + { 515, 1031, 2, 1 }, + { 1031, 515, 1, 2 }, + { 100, 5000, 32, 1 }, + { 5000, 100, 1, 32 }, + { 3000, 3000, 5, 5 }, + { 720, 1280, 7, 4 }, + { 800, 640, 4, 5 }, + { 640, 800, 5, 4 }, + { 960, 720, 3, 4 }, + { 720, 960, 4, 3 }, + { 1600, 1200, 3, 4 }, + { 1200, 1600, 4, 3 }, + { 33, 4096, 32, 1 }, + { 4096, 33, 1, 32 }, +}; + +struct GoldUocrPic { int32_t f, h, w, mode; int32_t cols, rows, n_ids; int32_t n_seg, seg0; uint64_t global_fnv, local_fnv; }; +static const GoldUocrPic kUocrPictures[] = { + { 0, 300, 500, 1, 1, 1, 273, 2, 0, 0xabc7f1eabc334430ull, 0x0000000000000000ull }, + { 1, 900, 1400, 1, 3, 2, 893, 4, 2, 0xb068ca82d7ec14c3ull, 0x93a9d30576e60c3eull }, + { 2, 2400, 400, 1, 1, 6, 933, 8, 6, 0x92636385d3bfb221ull, 0x2df135a4207447b6ull }, + { 3, 500, 700, 1, 4, 3, 1503, 5, 14, 0x2feb196ccb92c0feull, 0x2627954c4ca5bc98ull }, + { 4, 64, 48, 1, 1, 1, 273, 2, 19, 0x406b72ef3c95b8b6ull, 0x0000000000000000ull }, + { 5, 800, 1000, 1, 5, 4, 2313, 6, 21, 0xa449cce59a03d7dcull, 0x36b9d429ad266a50ull }, + { 0, 300, 500, 2, 1, 1, 273, 2, 27, 0xabc7f1eabc334430ull, 0x0000000000000000ull }, + { 1, 900, 1400, 2, 1, 1, 273, 2, 29, 0xb068ca82d7ec14c3ull, 0x0000000000000000ull }, + { 2, 2400, 400, 2, 1, 1, 273, 2, 31, 0x92636385d3bfb221ull, 0x0000000000000000ull }, + { 3, 500, 700, 2, 1, 1, 273, 2, 33, 0x2feb196ccb92c0feull, 0x0000000000000000ull }, + { 4, 64, 48, 2, 1, 1, 273, 2, 35, 0x406b72ef3c95b8b6ull, 0x0000000000000000ull }, + { 5, 800, 1000, 2, 1, 1, 273, 2, 37, 0xa449cce59a03d7dcull, 0x0000000000000000ull }, + { 1, 900, 1400, 3, 1, 1, 111, 2, 39, 0x45321be8ce76d69dull, 0x0000000000000000ull }, + { 3, 500, 700, 3, 1, 1, 111, 2, 41, 0xde290af82e82620full, 0x0000000000000000ull }, +}; +struct GoldUocrSeg { int32_t h, w, real; }; +static const GoldUocrSeg kUocrSegs[] = { + { 64, 68, 64 }, + { 4, 4, 0 }, + { 40, 124, 120 }, + { 40, 124, 120 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 40, 44, 40 }, + { 40, 44, 40 }, + { 40, 44, 40 }, + { 40, 44, 40 }, + { 40, 44, 40 }, + { 40, 44, 40 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 40, 164, 160 }, + { 40, 164, 160 }, + { 40, 164, 160 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 40, 204, 200 }, + { 40, 204, 200 }, + { 40, 204, 200 }, + { 40, 204, 200 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 64, 68, 64 }, + { 4, 4, 0 }, + { 40, 44, 40 }, + { 4, 4, 0 }, + { 40, 44, 40 }, + { 4, 4, 0 }, +}; + +/* Pillow's Image.resize(BICUBIC) of a splitmix picture: its two-pass order is part of the + * function (the intermediate rounds to eight bits). */ +struct GoldUocrResize { int32_t sh, sw, dh, dw; uint64_t fnv; }; +static const GoldUocrResize kUocrResize[] = { + { 2400, 400, 1024, 171, 0xbccdeb5e050ce815ull }, + { 300, 300, 90, 100, 0xac4b3e6526dfbbb5ull }, + { 400, 300, 171, 1024, 0x799a058e681618b5ull }, + { 300, 400, 1024, 171, 0x82e65a0a71c6ee00ull }, + { 400, 1000, 200, 500, 0x7ef049c0990c00f6ull }, + { 1000, 400, 200, 300, 0x5a8d982164d9ff27ull }, + { 700, 500, 650, 470, 0x4697cb390555b911ull }, + { 500, 700, 640, 650, 0x90a6214f04fe8c0bull }, + { 320, 480, 320, 480, 0x8ce46502c9f58463ull }, + { 240, 320, 160, 320, 0x8ba4f63a78cc06bdull }, + { 240, 320, 240, 200, 0x9210b76889ecfbceull }, + { 64, 48, 1024, 1024, 0x3ccf3b8e768cfcd2ull }, +}; + +/* The transposed pairs whose tall side the reference's set visits last. */ +struct GoldUocrTie { int32_t c, r; }; +static const GoldUocrTie kUocrTallLast[] = { + {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14}, {1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16}, {3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, +}; +static const int32_t kUocrNTallLast = 31; diff --git a/tools/rad_convert.cpp b/tools/rad_convert.cpp index b56b93ca..87027297 100644 --- a/tools/rad_convert.cpp +++ b/tools/rad_convert.cpp @@ -476,8 +476,13 @@ int main(int argc, char** argv) { /* A generator sizes its passes itself (RadArchProbe::gen_rows) and may refuse a smaller one; * declare at that size unless the command line names one. */ if (!max_tok_given && probe.gen_rows > ctx.max_tok) ctx.max_tok = probe.gen_rows; - /* Likewise declare the encoders, the vision tower at the engine's default patch bound. */ - if (rad_meta_geti(&meta.m, "vision_config.patch_size", 0) > 0) { + /* Likewise declare the encoders, the vision tower at the engine's default patch bound. A + * checkpoint states one either way round: a flat `vision_config.patch_size`, or only the + * per-width tables with `vision_config.image_size` above them (Unlimited-OCR's DeepEncoder, + * whose widths each carry their own patch_size). Either means its weights are here to map, + * and the plugin declares the encoder only when `max_enc_patches` leaves it a whole view. */ + if (rad_meta_geti(&meta.m, "vision_config.patch_size", 0) > 0 || + rad_meta_geti(&meta.m, "vision_config.image_size", 0) > 0) { ctx.max_enc_patches = 16384; if (probe.enc_merge > 1) ctx.max_enc_patches -= ctx.max_enc_patches % probe.enc_merge; }