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).
This commit is contained in:
Juup committed 2026-10-20 07:04:01 +00:00
1 parent 543cba7416
commit fad4ba7f1a
63 files changed
+6162 -169

No files matched your search

+4
View File
@@ -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|"
+6
View File
@@ -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);
+73
View File
@@ -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",
+206
View File
@@ -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 <cmath>
namespace {
constexpr uint32_t kThreads = 128;
constexpr float kLog2e = 1.4426950408889634f;
template <int HD>
__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);
}
+190
View File
@@ -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 <cfloat>
// 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);
}
+300
View File
@@ -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 <dlfcn.h>
@@ -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<char>* 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<int32_t> 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<float> 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<RadSampleParams> sp((size_t)M);
std::memset(sp.data(), 0, sizeof(RadSampleParams) * (size_t)M);
std::vector<int32_t> 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<RadTensor> 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<RadParam> 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<float> got((size_t)(M * nv), 0.0f);
st_memcpy(got.data(), d_lg, (size_t)(M * nv) * 4, hipMemcpyDeviceToHost);
std::vector<char> 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<uint16_t> q((size_t)(M * ld)), k((size_t)(M * ld)), v((size_t)(M * ld));
std::vector<uint16_t> 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<int32_t> 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<RadTensor> 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<RadParam> 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<uint16_t> 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<double> 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);