radiance 1.11.0

New models:
- GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget),
  with decode kernels for a few rows and the DSA indexer split over the ranks
- Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter
- Unlimited-OCR (bf16)
- Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces
  are fused with the junctions, overlapped with the compute and sent compressed
- Ornith-1.5-35B-A3B w4a8 compose files

Speed:
- Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued
  ahead
- The four-rank all-reduce is faster for every --tp 4 model
- qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly
- --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20%
  prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default

Features:
- Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch,
  and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE)
- Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance
- Cards with a small PCI BAR run, with kernel arguments kept in host memory
- Dashboard: live acceptance figures; statsdump rotates its file at a size cap
- KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot

Fixes:
- Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore
  makes room as memory pressure does and waits a step for the previous turn's release (two
  conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now)
- Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory
  management is turned off there, with a warning
- Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output
- The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start
- GLM-5.3: every refusal names the setting and the reason; its template keeps string content
- Several pictures in one request no longer refuse processors that take one image at a time

Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs
added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
Deadcode committed 2026-10-23 11:57:52 +02:00
210 files changed
+14363 -2138

No files matched your search

+1
View File
@@ -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
+40 -4
View File
@@ -58,7 +58,7 @@ std::vector<Case> build_cases() {
add("scale", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2));
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" })
for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" })
add("act_mul", { HI("M", 6), HI("n", 645), HS("act", act), HS("dtype", dt) },
EB(6, 645, w, 3));
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 2));
@@ -378,6 +378,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. */
@@ -565,6 +590,18 @@ std::vector<Case> build_cases() {
HS("dtype", dt) });
add("router_topk", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2), HI("norm", 0),
HS("dtype", dt) });
/* The pair and the pair behind the router GEMM: the whole-model form and a rank's slice
* with a nonzero expert base, since the sort's slicing is the part the fuse adds. */
add("router_topk_scatter", { HI("M", 9), HI("n_expert", 8), HI("top_k", 2),
HI("norm", 1), HS("dtype", dt) });
add("router_topk_scatter", { HI("M", 9), HI("n_expert", 8), HI("n_local", 4),
HI("top_k", 2), HI("norm", 0), HI("expert_base", 2),
HS("dtype", dt) });
add("router_gemm_topk_scatter", { HI("M", 9), HI("K", 128), HI("n_expert", 8),
HI("top_k", 2), HI("norm", 0), HS("dtype", dt) });
add("router_gemm_topk_scatter", { HI("M", 9), HI("K", 128), HI("n_expert", 8),
HI("n_local", 4), HI("top_k", 2), HI("norm", 1),
HI("expert_base", 2), HS("dtype", dt) });
add("moe_gather", { HI("M", 9), HI("n", 128), HI("top_k", 2), HS("dtype", dt) });
/* The shared-expert fold: `shared`/`shared_gate` are always described, so always
* present; this case uses sigmoid, the one above "none". */
@@ -657,8 +694,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
@@ -907,7 +944,6 @@ std::vector<Case> build_cases() {
add("s2d3d", { HI("M", 64), HI("C", 6), HI("st", 2), HI("sh", 2), HI("sw", 2),
HI("group", 4), HS("mode", "mean"), HI("add", 1), HS("dtype", dt) });
add("pix_patch", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
add("patch_pix8", { HI("M", 12), HI("p", 4), HI("C", 3), HS("dtype", dt) });
add("stft_logmel", { HI("M", 6), HI("hop", 80), HI("nfft", 512), HI("n_mel", 64),
HI("ch", 2), HS("dtype", dt) });
add("bwe_up", { HI("M", 600), HI("ratio", 3), HI("ch", 2), HS("dtype", dt) });
+50
View File
@@ -645,6 +645,56 @@ void shape_cases(std::vector<Hand>& hs) {
.pi("seqs", 1)
.ps("dtype", "fp8_e4m3");
hs.push_back(std::move(s));
/* `row_part` scores one run of the step's rows from query operands that span the step,
* and writes the bounds rebased to the run's first row. Six rows in runs of two over two
* sequences ending at row 5: run 1 straddles the sequences, run 2 ends past the step. */
for (int part : { 1, 2 }) {
Hand r(part == 1 ? "DSA scorer row_part: a run across two sequences"
: "DSA scorer row_part: a run past the step's last row",
"dsa_score", 1e-5);
r.dense(RAD_F8E4M3, { 6 * 32, 128 }, hfill(215, 0.25f))
.dense(RAD_F32, { 6 * 32, 1 }, hfill(216))
.dense(RAD_F32, { 6, 32 }, hfill(217))
.dense(RAD_F8E4M3, { 6, 128 }, hfill(218, 0.25f))
.dense(RAD_F32, { 6 }, [](int64_t i) { return 0.25f + 0.125f * (float)i; })
.dense(RAD_I32, { 2, 4 },
[](int64_t i) { return (float)(i == 3 ? -1 : i < 4 ? i : 7 - i); })
.idx({ 0, 3, 5 })
.idx({ 3, 4 })
.dense(
RAD_F32, { 2, 4 }, [](int64_t) { return 0.0f; }, true)
.idx({ 0, 0, 0 }, true)
.expect(9, { -2 * part, 3 - 2 * part, 5 - 2 * part })
.pi("M", 2)
.pi("n", 128)
.pi("heads", 32)
.pi("blocks", 4)
.pi("seqs", 2)
.ps("dtype", "fp8_e4m3")
.pi("row_part", part);
hs.push_back(std::move(r));
}
/* Rebased bounds without a run to rebase them to are refused. */
Hand u("DSA scorer refuses cu_part without row_part", "dsa_score", 1e-5);
u.dense(RAD_F8E4M3, { 2 * 32, 128 }, hfill(219, 0.25f))
.dense(RAD_F32, { 2 * 32, 1 }, hfill(220))
.dense(RAD_F32, { 2, 32 }, hfill(221))
.dense(RAD_F8E4M3, { 3, 128 }, hfill(222, 0.25f))
.dense(RAD_F32, { 3 }, [](int64_t) { return 0.5f; })
.dense(RAD_I32, { 1, 3 }, [](int64_t i) { return (float)i; })
.idx({ 0, 2 })
.idx({ 3 })
.dense(
RAD_F32, { 2, 3 }, [](int64_t) { return 0.0f; }, true)
.idx({ 0, 0 }, true)
.refuses(RAD_E_INVAL)
.pi("M", 2)
.pi("n", 128)
.pi("heads", 32)
.pi("blocks", 3)
.pi("seqs", 1)
.ps("dtype", "fp8_e4m3");
hs.push_back(std::move(u));
}
/* ---- packed weight codes at odd element offsets ------------------------------------------ */
{
+18 -7
View File
@@ -117,16 +117,27 @@ AVX_KERNEL(mul_weight) {
* rather than the algebraically equal g / (1 + e^(-2z)), which differs by an ulp or two and after
* bf16 rounding measurably moves embeddings away from transformers'. vf_exp saturates, so the
* large-|g| limits come out as g and 0. erf has no vector form here, so gelu stays scalar. */
static inline float act_of(int act, float g) {
static inline float round1(uint32_t dt, float v) {
if (dt == RAD_F32) return v;
uint16_t t;
row_from_f32(dt, &v, &t, 1);
float r;
row_to_f32(dt, &t, &r, 1);
return r;
}
static inline float act_of(int act, float g, uint32_t dt) {
if (act == 0) return g / (1.0f + sc_exp(-g));
if (act == 1) return 0.5f * g * (1.0f + sc_erf(g * 0.70710678118654752f));
if (act == 3) return 1.0f / (1.0f + sc_exp(-g));
if (act == 4) // quick_gelu: sigmoid of the 1.702*g the unfused mul would have stored
return 1.0f / (1.0f + sc_exp(-round1(dt, g * round1(RAD_BF16, 1.702f))));
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * g * (1.0f + sc_tanh(k0 * (g + k1 * g * g * g)));
}
/* sy[0..n) = act(g[0..n)) for silu (0) and gelu_tanh (2); the tail is the scalar form. */
static inline void act_row(int act, const float* g, float* sy, int64_t n) {
static inline void act_row(int act, const float* g, float* sy, int64_t n, uint32_t dt) {
int64_t i = 0;
const vf one = vf_set1(1.0f);
if (act == 0) {
@@ -145,7 +156,7 @@ static inline void act_row(int act, const float* g, float* sy, int64_t n) {
vf_storeu(sy + i, vf_mul(vf_mul(half, x), vf_add(one, t)));
}
}
for (; i < n; ++i) sy[i] = act_of(act, g[i]);
for (; i < n; ++i) sy[i] = act_of(act, g[i], dt);
}
AVX_KERNEL(act_mul) {
@@ -155,8 +166,8 @@ AVX_KERNEL(act_mul) {
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n || numel(B) < rows * n) return RAD_E_SHAPE;
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid" };
const int act = p_enum(a, "act", kActs, 4, -1);
static const char* kActs[] = { "silu", "gelu", "gelu_tanh", "sigmoid", "quick_gelu" };
const int act = p_enum(a, "act", kActs, 5, -1);
if (act < 0) return RAD_E_INVAL;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
@@ -166,7 +177,7 @@ AVX_KERNEL(act_mul) {
float* sy = scratch_f32_c((size_t)n);
const float* g = in_row(A, rowoff(A, r, n), n, sa);
const float* u = in_row(B, rowoff(B, r, n), n, sb);
act_row(act, g, sy, n);
act_row(act, g, sy, n, Y->dtype);
/* sa is free once the activation is taken (g is sa or the tensor); sb may hold u, which
* is still needed. */
roundtrip(Y->dtype, sy, n, sa);
@@ -314,7 +325,7 @@ AVX_KERNEL(conv2d) {
if (gelu) {
/* The biased sum as y's dtype holds it, then the activation of the rounded value. */
const float* yr = in_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e]);
for (int64_t e = 0; e < rout; ++e) acc[e] = act_of(1, yr[e], RAD_F32);
out_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
}
}
+10
View File
@@ -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;
+5 -3
View File
@@ -103,10 +103,12 @@ 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) \
X(moe_gemm_q_mod4) X(pair_argmax) \
X(moe_gemm_q_mod4) X(pair_argmax) \
X(router_topk_scatter) X(router_gemm_topk_scatter) \
/* ---- gated delta net */ \
X(gdn_conv_prep) X(gdn_conv_update) X(gdn_kkt_solve) X(gdn_chunk_scan) \
X(gdn_recurrent_update) X(gdn_conv_recurrent_update) X(gdn_gated_rmsnorm) \
@@ -126,7 +128,7 @@ int avx_par_force(int threads);
X(resize_bilinear) X(patch_fold) X(flow_renoise) \
/* ---- LTX-2 */ \
X(rope_split) X(head_gate) X(ltx_guide) X(pixel_norm) \
X(d2s3d) X(s2d3d) X(pix_patch) X(patch_pix8) \
X(d2s3d) X(s2d3d) X(pix_patch) \
X(stft_logmel) X(bwe_up) X(tile_grid) X(tile_crop) \
X(tile_stitch) X(vol_index) \
/* ---- audio generation */ \
@@ -139,7 +141,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. */
+1 -28
View File
@@ -279,7 +279,7 @@ AVX_KERNEL(s2d3d) {
return RAD_OK;
}
/* ------------------------------------------------------------------ pix_patch / patch_pix8 */
/* ------------------------------------------------------------------ pix_patch */
static inline int64_t patch_col(int64_t c, int64_t ph, int64_t pw, int64_t p, bool wh) {
return c * p * p + (wh ? pw * p + ph : ph * p + pw);
}
@@ -305,33 +305,6 @@ AVX_KERNEL(pix_patch) {
return RAD_OK;
}
AVX_KERNEL(patch_pix8) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t p = p_int(a, "p", 0), C = p_int(a, "C", 0);
const bool wh = std::strcmp(p_str(a, "order", "wh"), "hw") != 0;
if (p <= 0 || C <= 0 || X->rank != 2 || Y->rank != 2 || Y->dtype != RAD_U8 ||
X->shape[1] % (C * p * p))
return RAD_E_SHAPE;
const int64_t R = X->shape[0], w = X->shape[1] / (C * p * p);
if (R <= 0 || w <= 0 || Y->shape[0] != R * p || Y->shape[1] != w * p * C) return RAD_E_SHAPE;
const int64_t xr = X->stride[0], yr = Y->stride[0];
const uint32_t dt = X->dtype;
uint8_t* yb = (uint8_t*)Y->data;
AVX_PARALLEL_FOR_IF(R * p * w * p * C >= AVX_PAR_MIN)
for (int64_t y = 0; y < R * p; ++y)
for (int64_t x = 0; x < w * p; ++x)
for (int64_t c = 0; c < C; ++c) {
const float v = ldt(X, (y / p) * xr + (x / p) * C * p * p +
patch_col(c, y % p, x % p, p, wh));
const float cl = std::min(std::max(v, -1.0f), 1.0f);
float u = narrow1(dt, narrow1(dt, cl / 2.0f) + 0.5f);
u = std::min(std::max(u, 0.0f), 1.0f);
yb[y * yr + x * C + c] = (uint8_t)std::nearbyint(u * 255.0f);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ vol_index */
AVX_KERNEL(vol_index) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
+77
View File
@@ -1218,10 +1218,14 @@ AVX_KERNEL(moe_gemm_q_mod4) { return moe_gemm_impl(a, true, 4); }
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)], summed in
* ascending slot j (see the file header). The inverse permutation is built once per batch. */
AVX_KERNEL(moe_gather) {
/* NOT `rad_args_have(a, 6)`: the required operands are not a prefix -- the shared pair at 3
* and 4 is a NULL SLOTS form for a layer whose shared arm runs beside the block, and the
* prefix test reads a legal unfolded call as a missing operand. */
if (!a || !a->t || a->n_t < 6 || !rad_args_have(a, 3) || !rad_arg_in(a, 5)) return RAD_E_INVAL;
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
/* Optional shared-expert fold: y = narrow(shared * act(gate)) + narrow(gathered). Both
* operands or neither, as in libref. */
if (!ye->data || !ew->data || !sorted->data || !Y->data) return RAD_E_INVAL;
const RadTensor *sh = rad_arg_in(a, 3), *sg = rad_arg_in(a, 4);
if ((sh != nullptr) != (sg != nullptr)) return RAD_E_INVAL;
const char* act = p_str(a, "act", "none");
@@ -1492,3 +1496,76 @@ AVX_KERNEL(pair_argmax) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ router_topk_scatter */
/* The pair as one op: `router_topk` then `moe_scatter` over the ids it just wrote. The selection
* reads the whole router's `n_expert` logits; the sort runs over this rank's slice, which is the
* fused op's `n_local` standing where `moe_scatter`'s `n_expert` names the slice it owns.
*
* The operands line up with `router_topk`'s own first three slots (logits, ids, weights), so the
* selection is the sibling kernel called on this very RadArgs -- no copy, no re-derivation of the
* softmax -- and the sort is `moe_scatter` over the four operands it takes. */
AVX_KERNEL(router_topk_scatter) {
if (!rad_args_have(a, 6)) return RAD_E_INVAL;
const int64_t ne = p_int(a, "n_expert", 0);
const int64_t nl = p_int(a, "n_local", ne);
const int64_t k = p_int(a, "top_k", 1);
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne) return RAD_E_SHAPE;
const int rc = AVX_FN(avx_router_topk)(a, stream);
if (rc != RAD_OK) return rc;
const RadTensor t2[] = { a->t[1], a->t[3], a->t[4], a->t[5] };
const RadParam sp[] = { RAD_INT("n_expert", nl), RAD_INT("top_k", k),
RAD_INT("expert_base", p_int(a, "expert_base", 0)),
RAD_STR("protect", p_str(a, "protect", nullptr)) };
const RadArgs sa{ t2, 4, sp, 4, a->scratch, a->scratch_bytes, a->instance, a->rank,
a->world_size };
return AVX_FN(avx_moe_scatter)(&sa, stream);
}
/* ------------------------------------------------------------------ router_gemm_topk_scatter */
/* The router GEMM in front of the pair, and with `gate_b`/`gate` present the shared expert's
* one-column gate over the same input, at N = 1. `gate_b` and `gate` come together or not at all,
* and the operand count says which. */
extern "C" int AVX_FN(avx_gemm_nt)(const RadArgs*, RadStream);
AVX_KERNEL(router_gemm_topk_scatter) {
/* NOT `rad_args_have`: the required operands are not a prefix -- `gate_b` sits between the
* router's weight and the outputs, and it and `gate` are null slots in the gate-absent form. */
if (!a || !a->t || a->n_t < 9) return RAD_E_INVAL;
const bool gate_b = a->t[2].data != nullptr;
const bool gate = a->n_t > 9 && a->t[9].data != nullptr;
if (gate_b != gate) return RAD_E_INVAL;
for (int i : {0, 1, 3, 4, 5, 6, 7, 8})
if (!a->t[i].data) return RAD_E_INVAL;
const int64_t ne = p_int(a, "n_expert", 0);
const int64_t nl = p_int(a, "n_local", ne);
const int64_t k = p_int(a, "top_k", 1);
const int64_t K = p_int(a, "K", 0);
if (ne <= 0 || k <= 0 || k > ne || nl <= 0 || nl > ne || K <= 0) return RAD_E_SHAPE;
const char* dt = p_str(a, "dtype", "bf16");
const RadTensor g3[] = { a->t[0], a->t[1], a->t[3] };
const RadParam gp[] = { RAD_INT("N", ne), RAD_INT("K", K), RAD_STR("dtype", dt) };
const RadArgs ga{ g3, 3, gp, 3, a->scratch, a->scratch_bytes, a->instance, a->rank,
a->world_size };
const int gc = AVX_FN(avx_gemm_nt)(&ga, stream);
if (gc != RAD_OK) return gc;
if (gate) {
const RadTensor p3[] = { a->t[0], a->t[2], a->t[9] };
const RadParam pp[] = { RAD_INT("N", 1), RAD_INT("K", K), RAD_STR("dtype", dt) };
const RadArgs pa{ p3, 3, pp, 3, a->scratch, a->scratch_bytes, a->instance, a->rank,
a->world_size };
const int pc = AVX_FN(avx_gemm_nt)(&pa, stream);
if (pc != RAD_OK) return pc;
}
/* The pair over the logits the GEMM just wrote. Every parameter the pair reads is a parameter
* of this op, under the same name -- the fused lists are unions. */
const RadTensor t6[] = { a->t[3], a->t[4], a->t[5], a->t[6], a->t[7], a->t[8] };
const RadArgs fa{ t6, 6, a->p, a->n_p, a->scratch, a->scratch_bytes, a->instance, a->rank,
a->world_size };
return AVX_FN(avx_router_topk_scatter)(&fa, stream);
}
+58 -3
View File
@@ -288,7 +288,7 @@ static const RadOperandSpec oGemmQGated[] = { OPD("a"), OPD("a_scale"), WGT("b"
static const RadParamSpec pAttnPaged[] = {
P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"), P_INTD("block_size"), P_INT("causal"),
P_INT("window"), P_STR("q_dtype"), P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
P_INTO("n_head"), P_INTO("max_seqs")
P_INTO("n_head"), P_INTO("max_seqs"), P_INTO("prefill_fp8")
};
static const RadOperandSpec oAttnPaged[] = {
OPD("q"), OPD("kv_cache"), OPD("block_table"), OPD("seqused"),
@@ -311,6 +311,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") };
@@ -393,6 +401,26 @@ static const RadParamSpec pScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT(
static const RadOperandSpec oScatter[] = { OPD("expert_ids"), OUT("sorted_tok"),
OUT("expert_offset"), OUT("expert_count") };
/* The pair as one op, and the router GEMM in front of it: libref's schemas for the same two rows,
* where the operand lists are unions and `expert_ids`/`logits` are named once as outputs. */
static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"),
P_INTO("n_local"), P_INT("top_k"),
P_INT("norm"), P_STR("dtype"),
P_INTO("expert_base"),
P_STRO("protect") };
static const RadOperandSpec oRouterTopkScatter[] = { OPD("logits"), OUT("expert_ids"),
OUT("expert_w"), OUT("sorted_tok"),
OUT("expert_offset"),
OUT("expert_count") };
static const RadParamSpec pRouterGemmTopkScatter[] = { P_INT("M"), P_INT("K"),
P_INT("n_expert"), P_INTO("n_local"),
P_INT("top_k"), P_INT("norm"),
P_STR("dtype"), P_INTO("expert_base"),
P_STRO("protect") };
static const RadOperandSpec oRouterGemmTopkScatter[] = {
OPD("a"), WGT("b"), WGT_O("gate_b"), OUT("logits"), OUT("expert_ids"), OUT("expert_w"),
OUT("sorted_tok"), OUT("expert_offset"), OUT("expert_count"), OUT_O("gate") };
static const RadParamSpec pMoeGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("n_expert"),
P_INT("top_k"), P_STR("a_order"), P_STR("dtype") };
static const RadOperandSpec oMoeGemm[] = { OPD("a"), WTAB("w"), OPD("sorted_tok"),
@@ -774,6 +802,10 @@ 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") };
/* `whitelist` is optional, libref's: a bitmask plane a row, a SET bit exempting a token from
* the ban. Absent, nothing is exempt. */
static const RadOperandSpec oNgramBan[] = { INOUT("logits"), OPD("params"), OPD("history"),
OPD("ngram"), OPD_O("whitelist") };
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") };
@@ -976,6 +1008,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),
@@ -1004,6 +1041,10 @@ static const RadOpSchema kSchemas[] = {
{ "router_sigmoid_topk", ARR(pRouterSigmoid), ARR(oRouterSigmoid),
"Single-group sigmoid routing; correction bias selects experts, original scores weight them." },
{ "router_topk", ARR(pRouter), ARR(oRouter), "softmax then exact top-k routing." },
{ "router_topk_scatter", ARR(pRouterTopkScatter), ARR(oRouterTopkScatter),
"the selection and the sort in one op, run as exactly the pair." },
{ "router_gemm_topk_scatter", ARR(pRouterGemmTopkScatter), ARR(oRouterGemmTopkScatter),
"the router GEMM, the shared expert's gate GEMM and the pair, run as exactly the launches." },
{ "moe_scatter", ARR(pScatter), ARR(oScatter),
"stable counting sort of routing slots by expert." },
{ "moe_gemm", ARR(pMoeGemm), ARR(oMoeGemm), "grouped GEMM over the expert-sorted rows." },
@@ -1159,7 +1200,6 @@ static const RadOpSchema kSchemas[] = {
{ "s2d3d", ARR(pS2d3d), ARR(oS2d3d),
"space to depth over voxel rows, a copy or the mean of each group, libref's." },
{ "pix_patch", ARR(pPixPatch), ARR(oPixPatch), "an image to patch rows, libref's copy." },
{ "patch_pix8", ARR(pPixPatch), ARR(oPixPatch), "patch rows to RGB bytes, libref's rule." },
{ "vol_index", ARR(pVolIndex), ARR(oVolIndex), "a volume's voxel coordinates, libref's." },
{ "tile_grid", ARR(pTileGrid), ARR(oTileGrid), "a tiled decode's boxes, libref's cut." },
{ "tile_crop", ARR(pTileCrop), ARR(oTileCrop), "a tile out of a volume, libref's copy." },
@@ -1220,6 +1260,11 @@ 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. The optional `whitelist` bitmask exempts a token whose column bit is set; absent, "
"nothing is exempt." },
{ "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." },
@@ -1532,6 +1577,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)),
@@ -1557,6 +1605,12 @@ SIMPLE("avx_router_topk", "router_topk", "moe", "softmax then exact top-k routin
L(router_topk)),
SIMPLE("avx_router_sigmoid_topk", "router_sigmoid_topk", "moe", "sigmoid correction-bias routing", DT_FLOAT,
L(router_sigmoid_topk)),
SIMPLE("avx_router_topk_scatter", "router_topk_scatter", "moe",
"the selection and the sort in one op, run as exactly the pair", DT_FLOAT,
L(router_topk_scatter)),
SIMPLE("avx_router_gemm_topk_scatter", "router_gemm_topk_scatter", "moe",
"the router GEMM, the shared expert's gate GEMM and the pair, run as exactly the launches",
DT_FLOAT, L(router_gemm_topk_scatter)),
SIMPLE("avx_moe_scatter", "moe_scatter", "moe", "stable counting sort of routing slots by expert",
"i32 indices", L(moe_scatter)),
SIMPLE("avx_moe_gemm", "moe_gemm", "moe", "grouped GEMM over the expert-sorted rows", DT_FLOAT,
@@ -1700,7 +1754,6 @@ SIMPLE("avx_pixel_norm", "pixel_norm", "norm", "an RMS norm as bf16 tensors comp
SIMPLE("avx_d2s3d", "d2s3d", "elem", "depth to space over voxel rows", DT_FLOAT, L(d2s3d)),
SIMPLE("avx_s2d3d", "s2d3d", "elem", "space to depth over voxel rows", DT_FLOAT, L(s2d3d)),
SIMPLE("avx_pix_patch", "pix_patch", "elem", "an image to patch rows", DT_FLOAT, L(pix_patch)),
SIMPLE("avx_patch_pix8", "patch_pix8", "elem", "patch rows to RGB bytes", DT_FLOAT, L(patch_pix8)),
SIMPLE("avx_vol_index", "vol_index", "elem", "a volume's voxel coordinates", DT_ANY, L(vol_index)),
SIMPLE("avx_tile_grid", "tile_grid", "elem", "a tiled decode's boxes", DT_ANY, L(tile_grid)),
SIMPLE("avx_tile_crop", "tile_crop", "elem", "a tile out of a volume", DT_FLOAT, L(tile_crop)),
@@ -1768,6 +1821,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,
+179
View File
@@ -0,0 +1,179 @@
/* 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 and the q.Rw dots are
* hoisted per query row (the hip kernel's hoist, bit-identical reuse), the softmax subtracts the
* tile maximum, and the output is rounded once. The dots stay scalar f32 loops over head_dim on
* purpose: the x86 leg is the no-GPU/harness path, and a SIMD reduction would reassociate the f32
* accumulation and break bit-parity with the libref oracle. 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);
/* The w rel-pos dot depends on (lw, jw) alone, not on jh: dot it once per query
* row and reuse it through the tile rows. The same scalar loop in the same order,
* so every reused value is bit-identical to the per-(jh, jw) recompute. */
std::vector<float> wr((size_t)tw);
for (int64_t jw = 0; jw < tw; ++jw) {
const float* rwrow = &Rw[(size_t)((lw - jw + tw - 1) * hd)];
float wv = 0.0f;
for (int64_t c = 0; c < hd; ++c) wv += qt[c] * rwrow[c];
wr[(size_t)jw] = wv;
}
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) {
float lgt = hr + wr[(size_t)jw];
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;
}
+86
View File
@@ -29,6 +29,7 @@
#include "rad_sample.h"
#include <cfloat>
#include <vector>
using namespace avx;
@@ -222,6 +223,91 @@ 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.
*
* The optional `whitelist` bitmask (a SET bit, the row's own plane row) exempts a token from
* the ban, the reference's `banned.difference_update(self.whitelist)`; absent, nothing is
* exempt, and the result is bit-for-bit the ban without it. */
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 RadTensor* wl = rad_arg_in(a, 4);
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);
const int64_t wwords = (n_vocab + 31) / 32;
if (wl && wl->dtype != RAD_I32 && wl->dtype != RAD_U32) return RAD_E_DTYPE;
if (wl && numel(wl) < M * wwords) return RAD_E_SHAPE;
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);
const int64_t wb = wl ? rowoff(wl, m, wwords) : 0, ws = wl ? laststride(wl) : 0;
auto tok_at = [&](int64_t i) { return (int64_t)(int32_t)ldi(hist, hb + i * hs); };
auto exempt = [&](int64_t col) {
if (!wl) return false;
const uint32_t word = (uint32_t)ldi(wl, wb + (col / 32) * ws);
return ((word >> (uint32_t)(col % 32)) & 1u) != 0u;
};
const int64_t plen = n - 1, p0 = hl - plen;
/* The prefix is the same n-1 tokens compared at every search position: read once. */
std::vector<int64_t> pref((size_t)plen);
for (int64_t j = 0; j < plen; ++j) pref[(size_t)j] = tok_at(p0 + j);
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) != pref[(size_t)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;
if (exempt(col)) 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) {