Archived
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:
1 parent
543cba7416
commit
fad4ba7f1a
63 files changed
+6162
-169
No files matched your search
@@ -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
|
||||
|
||||
+27
-2
@@ -370,6 +370,31 @@ std::vector<Case> 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<Case> 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
|
||||
|
||||
@@ -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;
|
||||
|
||||
+2
-1
@@ -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. */
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
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<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 */
|
||||
|
||||
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<float> Rh = table_rows(th_tab, hd, 2 * th - 1);
|
||||
const std::vector<float> 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;
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user