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

+3 -1
View File
@@ -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)
+5
View File
@@ -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);
+32
View File
@@ -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",
+197
View File
@@ -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 <algorithm>
#include <cmath>
#include <vector>
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<float> table_rows(const RadTensor* t, int64_t hd, int64_t want) {
const int64_t rows = hd > 0 ? numel(t) / hd : 0;
std::vector<float> 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<float> 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<float> Rh = table_rows(th_tab, hd, 2 * th - 1);
std::vector<float> 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;
}
+80
View File
@@ -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) {
+48
View File
@@ -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;