merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across

conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
gearwave00001 committed 2026-10-24 19:03:26 -05:00
commit 7c3b5ab7d5
285 files changed
+30500 -2898

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
+13 -9
View File
@@ -528,6 +528,18 @@ AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]);
}
/* P row (64 floats) to bf16 pairs. Kept out of attn_dense_bf16's OpenMP loop: clang's OpenMP
* outlining drops the enclosing function's target attribute, and a bf16 intrinsic in the
* outlined body then crashes the backend. The outlined function calls this, as it already calls
* qk_rows and pv_rows. */
AVX_BF16_TARGET static inline void p_to_bf16_pairs(const float* sr, uint32_t* pr) {
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
_mm512_loadu_ps(sr)));
_mm512_storeu_si512((void*)(pr + 16),
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
_mm512_loadu_ps(sr + 32)));
}
AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* k,
const RadTensor* v, const RadTensor* cu,
const RadTensor* o, int64_t D, int64_t gqa,
@@ -687,15 +699,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
}
}
/* P to bf16, round to nearest even: a row's 64 values become its 32 key pairs. */
for (int64_t r = 0; r < R; ++r) {
const float* sr = S + r * KT;
uint32_t* pr = ppack + r * 32;
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
_mm512_loadu_ps(sr)));
_mm512_storeu_si512((void*)(pr + 16),
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
_mm512_loadu_ps(sr + 32)));
}
for (int64_t r = 0; r < R; ++r) p_to_bf16_pairs(S + r * KT, ppack + r * 32);
for (int64_t c0 = 0; c0 < D; c0 += 64) {
int64_t r = 0;
for (; r + 6 <= R; r += 6) pv_rows<6>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
+172 -28
View File
@@ -227,7 +227,10 @@ inline float sin_sq1(float v) {
* k input rows' channel runs back to back, zeros outside its own sequence (padded on both sides,
* or with `causal` on the left only). A band's patches are one gemm_nt_into call into f32 rows (the
* bias added there); `res` and the tanh or the clamp to [-1, 1] are applied to the f32 rows, which
* are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. */
* are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. With a
* `stride` (causal only) output row o's patch starts at input row o stride - pad, the pad the
* reach less the stride, and a sequence of L rows makes L / stride. `cu_div`: the bounds in units
* that many input rows apart, as libref reads them. */
AVX_KERNEL(conv1d) {
if (!rad_args_have(a, 3) || a->n_t < 5) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *cu = &a->t[2];
@@ -235,32 +238,40 @@ AVX_KERNEL(conv1d) {
if (!Y->data) return RAD_E_INVAL;
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
const int64_t st = p_int(a, "stride", 1), ep = p_int(a, "pad", -1);
const int64_t st = p_int(a, "stride", 1), ep = p_int(a, "pad", -1), cd = p_int(a, "cu_div", 1);
const char* act = p_str(a, "act", "none");
const bool tanh_out = act && !std::strcmp(act, "tanh");
const bool clamp_out = act && !std::strcmp(act, "clamp");
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
/* A stride comes in the causal form (no pad operand, cu_div bounds) or the zero-padded one
* with an explicit `pad` (bf16, one full sequence, PyTorch's formula) - never both. */
const bool padded = ep >= 0 && st > 1;
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && st <= 1 && (k & 1) == 0) || dil <= 0 ||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (causal || ep < 0)) ||
(st <= 1 && ep >= 0))
causal < 0 || causal > 1 || st < 1 || (ep >= 0 && (st <= 1 || causal || cd != 1)) ||
(st > 1 && ep < 0 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
if (r0 < 0 || r1 <= r0 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
const int64_t cdv = padded ? 1 : cd;
for (int64_t e = 0; !padded && e <= n_seq; ++e)
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
const int64_t x0 = cu_at(cu, 0) / cdv, x1 = cu_at(cu, n_seq) / cdv;
if (x0 < 0 || x1 <= x0 || rows_of(X, cin) < x1) return RAD_E_SHAPE;
if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE;
/* The strided form (libref's rule): bf16, one full sequence, y the formula's rows. */
int64_t hi = r1;
if (st > 1) {
/* r0, r1: the output rows. The causal stride takes each sequence of L rows to L / stride;
* the padded form (libref's rule) is bf16, one full sequence, y exactly the formula's rows. */
int64_t r0 = x0 / st, r1 = x1 / st;
if (padded) {
if (X->dtype != RAD_BF16) return RAD_E_DTYPE;
if (n_seq != 1 || r0 != 0 || r1 != rows_of(X, cin)) return RAD_E_SHAPE;
hi = (r1 + 2 * ep - dil * (k - 1) - 1) / st + 1;
if (hi <= 0 || rows_of(Y, cout) != hi) return RAD_E_SHAPE;
} else if (rows_of(Y, cout) < r1) {
return RAD_E_SHAPE;
if (n_seq != 1 || x0 != 0 || x1 != rows_of(X, cin)) return RAD_E_SHAPE;
r0 = 0;
r1 = (x1 + 2 * ep - dil * (k - 1) - 1) / st + 1;
}
if (res && rows_of(res, cout) < hi) return RAD_E_SHAPE;
const int64_t pad = ep >= 0 ? ep : (causal ? dil * (k - 1) : dil * (k - 1) / 2), KK = k * cin;
if (r0 >= r1) return RAD_E_SHAPE;
if (padded ? rows_of(Y, cout) != r1 : rows_of(Y, cout) < r1) return RAD_E_SHAPE;
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
const int64_t pad = padded ? ep : (causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2),
KK = k * cin;
static thread_local std::vector<uint8_t> wbuf, pbuf;
static thread_local std::vector<float> ybuf;
@@ -279,14 +290,13 @@ AVX_KERNEL(conv1d) {
* always builds patches. */
const bool direct = k == 1 && st == 1 && X->rank == 2 && X->shape[1] == cin &&
X->stride[1] == 1 && (X->dtype == RAD_BF16 || X->dtype == RAD_F32);
const int64_t lo = st > 1 ? 0 : r0; /* a strided op's rows are output rows from 0 */
const int64_t band = band_rows(KK, cout, hi - lo);
const int64_t band = band_rows(KK, cout, r1 - r0);
if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64);
ybuf.resize((size_t)(band * cout) + 16);
char* pp = (char*)pbuf.data();
float* yp = ybuf.data();
for (int64_t b0 = lo; b0 < hi; b0 += band) {
const int64_t nb = std::min(band, hi - b0);
for (int64_t b0 = r0; b0 < r1; b0 += band) {
const int64_t nb = std::min(band, r1 - b0);
RadTensor pt;
if (direct) {
pt = mat_view((char*)X->data + (size_t)(b0 * X->stride[0]) * rad_dtype_bits(X->dtype) / 8,
@@ -296,8 +306,8 @@ AVX_KERNEL(conv1d) {
pt = mat_view(pp, adt, nb, KK);
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
for (int64_t p = 0; p < nb; ++p) {
const int64_t r = b0 + p, e = seq_of(cu, n_seq, st > 1 ? r * st : r);
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r * st * cdv);
const int64_t s0 = cu_at(cu, e) / cdv, s1 = cu_at(cu, e + 1) / cdv;
for (int64_t t = 0; t < k; ++t) {
const int64_t ir = r * st + t * dil - pad;
patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16,
@@ -604,8 +614,10 @@ AVX_KERNEL(cfg_topk_sample) {
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
const float pen = p_f32(a, "penalty", 1.0f);
const double top_p = (double)p_f32(a, "top_p", 1.0f);
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) ||
!(top_p >= 0))
return RAD_E_SHAPE;
const int64_t n = numel(ids) / rep;
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
@@ -664,11 +676,29 @@ AVX_KERNEL(cfg_topk_sample) {
} else {
for (int64_t j = 0; j < V; ++j) if (open(j)) idx[nc++] = j;
}
const int64_t kk = std::min(K, nc);
/* top_p's normaliser over every candidate in index order (idx still is), as libref. */
double z = 0;
if (top_p < 1.0) {
float gm = g[idx[0]];
for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[idx[t]]);
const float m0 = gm / temp;
for (int64_t t = 0; t < nc; ++t) z += std::exp((double)(g[idx[t]] / temp - m0));
}
int64_t kk = std::min(K, nc);
std::partial_sort(idx, idx + kk, idx + nc, [g](int64_t p, int64_t q) {
return g[p] > g[q] || (g[p] == g[q] && p < q);
});
const float m = g[idx[0]] / temp;
if (top_p < 1.0) {
double cum = 0;
int64_t keep = 1;
for (int64_t t = 0; t < kk; ++t) {
cum += std::exp((double)(g[idx[t]] / temp - m)) / z;
if (t > 0 && cum > top_p) break;
keep = t + 1;
}
kk = keep;
}
double tot = 0;
for (int64_t t = 0; t < kk; ++t) {
e[t] = std::exp((double)(g[idx[t]] / temp - m));
@@ -707,17 +737,18 @@ AVX_KERNEL(rvq_embed) {
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
const float scale = p_f32(a, "scale", 1.0f);
const int64_t round1 = p_int(a, "round", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0);
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, D);
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
const int64_t n0 = rows_of(t0, D), n1 = rows_of(t1, D);
auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
AVX_PARALLEL_FOR_IF(rows * D * K >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const int64_t c0 = ld_int_dt(codes->dtype, codes->data, r * rp) + off0;
const int64_t c0 = cl(ld_int_dt(codes->dtype, codes->data, r * rp)) + off0;
if (c0 < 0 || c0 >= n0) continue;
float* acc = scratch_f32((size_t)D + 16);
float* buf = scratch_f32_b((size_t)D + 16);
@@ -730,7 +761,7 @@ AVX_KERNEL(rvq_embed) {
}
for (int64_t k = 1; k < K; ++k) {
const int64_t cb =
ld_int_dt(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
cl(ld_int_dt(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc;
if (cb < 0 || cb >= n1) continue;
const float* tr = in_row(t1, rowoff(t1, cb, D), D, buf);
for (int64_t d = 0; d < D; ++d) acc[d] += tr[d];
@@ -750,6 +781,70 @@ AVX_KERNEL(rvq_embed) {
return RAD_OK;
}
/* ------------------------------------------------------------------ vq_encode */
/* libref's step a row at a time: e as dim dot products over x's row, the codebook normalised once
* a launch (F.normalize's division) and scored against e normalised, ties to the lower index, the
* chosen raw row's out-projection subtracted and the row rounded once into x. */
AVX_KERNEL(vq_encode) {
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(X, n);
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
return RAD_E_SHAPE;
/* The weights dense in f32, held by this thread for the launch's parallel region. */
auto dense = [](const RadTensor* t, int64_t m) {
std::vector<float> v((size_t)m);
for (int64_t i = 0; i < m; ++i) v[(size_t)i] = ldt(t, i);
return v;
};
const std::vector<float> wi = dense(iw, dim * n), bi = dense(ib, dim);
const std::vector<float> raw = dense(cb, bins * dim), wo = dense(ow, n * dim), bo = dense(ob, n);
std::vector<float> cn((size_t)(bins * dim));
for (int64_t c = 0; c < bins; ++c) {
const float* cr = raw.data() + c * dim;
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) ss += cr[j] * cr[j];
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = cr[j] / nrm;
}
const float *Wi = wi.data(), *Bi = bi.data(), *Raw = raw.data(), *Cn = cn.data();
const float *Wo = wo.data(), *Bo = bo.data();
AVX_PARALLEL_FOR_IF(rows * (2 * n + bins) * dim >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n);
const float* xv = in_row(X, xb, n, scratch_f32((size_t)n + 16));
float* e = scratch_f32_c((size_t)dim + 16);
float ss = 0.0f;
for (int64_t j = 0; j < dim; ++j) {
e[j] = dotf(Wi + j * n, xv, n) + Bi[j];
ss += e[j] * e[j];
}
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t j = 0; j < dim; ++j) e[j] /= nrm;
int64_t best = 0;
float bs = -INFINITY;
for (int64_t c = 0; c < bins; ++c) {
float s = 0.0f;
for (int64_t j = 0; j < dim; ++j) s += e[j] * Cn[c * dim + j];
if (s > bs) { bs = s; best = c; }
}
st_int_dt(codes->dtype, codes->data, offlin(codes, r), best);
float* y = scratch_f32_b((size_t)n + 16);
const float* row = Raw + best * dim;
for (int64_t d = 0; d < n; ++d) {
float q = 0.0f;
for (int64_t j = 0; j < dim; ++j) q += Wo[d * dim + j] * row[j];
y[d] = xv[d] - (q + Bo[d]);
}
out_row(X, xb, n, y);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ frame_mix_store */
/* m = bf16(bf16(sum_l w_l h_l) * bf16(scale)), w = bf16(softmax(bf16(logits))) in libref's double
* arithmetic, the planes summed in order with each product rounded before its add (`keep`). Entries
@@ -803,6 +898,42 @@ AVX_KERNEL(frame_mix_store) {
return RAD_OK;
}
/* ------------------------------------------------------------------ ras_pick */
/* libref's rule: the first draw unless it lies in [lo, hi) and the lane's window of its last `win`
* picks holds it, then the alternative; the pick enters the window. Lanes are checked before
* anything is written and run in order, as two entries may share a lane's window. */
AVX_KERNEL(ras_pick) {
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3];
const RadTensor* ids = &a->t[4];
const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0);
const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0);
const int64_t n = numel(lane);
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n)
return RAD_E_SHAPE;
for (int64_t i = 0; i < n; ++i) {
const int64_t L = at(lane, i);
if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE;
}
for (int64_t i = 0; i < n; ++i) {
const int64_t hb = at(lane, i) * W;
if (clear)
for (int64_t w = 0; w < W; ++w) st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), -1);
const int64_t f = at(first, rep * i);
int64_t pick = f;
if (f >= lo && f < hi)
for (int64_t w = 0; w < W; ++w)
if (at(hist, hb + w) == f) { pick = at(alt, rep * i); break; }
for (int64_t r = 0; r < rep; ++r)
st_int_dt(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
for (int64_t w = 0; w + 1 < W; ++w)
st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), at(hist, hb + w + 1));
st_int_dt(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ end_status */
/* status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]. */
AVX_KERNEL(end_status) {
@@ -1139,6 +1270,19 @@ AVX_KERNEL(int_affine) {
return RAD_OK;
}
/* ------------------------------------------------------------------ sub_i32 */
/* y[i] = x[i] - s[0], int32. */
AVX_KERNEL(sub_i32) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *S = &a->t[1], *Y = &a->t[2];
const int64_t n = numel(Y);
if (n <= 0 || numel(X) < n || numel(S) < 1) return RAD_E_SHAPE;
const int64_t s0 = at(S, 0);
for (int64_t i = 0; i < n; ++i)
st_int_dt(Y->dtype, Y->data, offlin(Y, i), (int64_t)(int32_t)(at(X, i) - s0));
return RAD_OK;
}
/* ------------------------------------------------------------------ cu_repeat */
/* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */
AVX_KERNEL(cu_repeat) {
+71 -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));
@@ -387,6 +387,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. */
@@ -574,6 +599,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". */
@@ -666,8 +703,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
@@ -921,7 +958,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) });
@@ -982,6 +1018,13 @@ std::vector<Case> build_cases() {
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
HI("dil", 1), HI("stride", s), HI("pad", (s + 1) / 2),
HS("dtype", dt) });
/* Strided, causal: Fish Audio's codec encoder downsamples with kernels of two strides
* (2, 4, 8) and its quantiser with a kernel of one (k 2, stride 2). */
for (int s : { 2, 4, 8 })
add("conv1d", { HI("M", 64), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
HI("dil", 1), HI("causal", 1), HI("stride", s), HS("dtype", dt) });
add("conv1d", { HI("M", 64), HI("cin", 24), HI("cout", 16), HI("k", 2), HI("dil", 1),
HI("causal", 1), HI("stride", 2), HS("dtype", dt) });
for (int s : { 2, 4, 8 })
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
HS("dtype", dt) });
@@ -1026,6 +1069,12 @@ std::vector<Case> build_cases() {
add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2),
HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0),
HS("dtype", "f32") });
/* Fish Audio's draw: the nucleus over the whole candidate set's softmax, then the top-k cut;
* at a small top_p the head alone, and above 1 none. */
for (double tp : { 0.7, 0.05, 0.95 })
add("cfg_topk_sample", { HI("M", 4), HI("n_vocab", 645), HI("k", 30), HI("rep", 1),
HF("cfg", 1.0), HF("temp", 0.7), HI("stream", 2),
HF("top_p", tp), HS("dtype", "f32") });
/* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a
* candidate), a temperature, the penalty idle without a history. */
for (int rep : { 1, 2 })
@@ -1037,6 +1086,9 @@ std::vector<Case> build_cases() {
for (double sc : { 1.0, 0.7 })
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64),
HI("off0", 5), HF("scale", sc), HS("dtype", dt) });
/* Codes past a codebook smaller than its heads read its last row (Fish Audio's codec). */
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 4), HI("vocab", 64),
HI("off0", 0), HF("scale", 1.0), HI("clamp", 40), HS("dtype", dt) });
/* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */
for (double sc : { 1.0, 0.7 })
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64),
@@ -1066,6 +1118,19 @@ std::vector<Case> build_cases() {
}
add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) });
add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) });
add("ras_pick", { HI("M", 4), HI("win", 16), HI("lo", 1), HI("hi", 9), HI("rep", 1) });
add("ras_pick", { HI("M", 2), HI("win", 4), HI("lo", 0), HI("hi", 12), HI("rep", 2),
HI("clear", 1) });
/* A codec encoder's residual quantiser step: DAC's eight-wide codes over a semantic codebook
* and a residual one, both dtypes; a dimension that is no vector's width. */
for (const char* dt : { "f32", "bf16" }) {
add("vq_encode", { HI("M", 7), HI("n", 64), HI("dim", 8), HI("bins", 4096),
HS("dtype", dt) });
add("vq_encode", { HI("M", 5), HI("n", 128), HI("dim", 8), HI("bins", 1024),
HS("dtype", dt) });
}
add("vq_encode", { HI("M", 3), HI("n", 40), HI("dim", 5), HI("bins", 33),
HS("dtype", "f32") });
add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2),
HI("skip", 0) });
add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1),
@@ -1078,6 +1143,8 @@ std::vector<Case> build_cases() {
add("cu_repeat", { HI("M", 9), HI("mult", 1) });
add("int_affine", { HI("M", 4), HS("src", "0 -1 2 1"), HS("mul", "2 0 8 4"),
HS("add", "-1 7 -7 -3") });
add("sub_i32", { HI("M", 1) });
add("sub_i32", { HI("M", 37) });
/* ================================================================== speed-only, at model size
*
+66
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 ------------------------------------------ */
{
@@ -4126,6 +4176,22 @@ void audio_cases(std::vector<Hand>& hs) {
hs.push_back(std::move(h));
}
}
for (const int64_t s : { 2, 4 }) {
/* A codec encoder's downsampling: kernel 2 stride, causal, the bounds in samples
* (cu_div 8 input rows), two clips of 4 and 2 strides from input row 2 s. */
const int64_t cin = 12, cout = 9, M = 8 * s;
Hand h(("stride " + std::to_string(s) + ", bounds in units of 8 rows" + sfx).c_str(),
"conv1d", norm_tol);
h.dense(dt, { M, cin }, hfill(330 + s))
.dense(dt, { cout, cin, 2 * s }, hfill(334, 0.3f))
.idx({ (int32_t)(16 * s), (int32_t)(48 * s), (int32_t)(64 * s) })
.none()
.dense(dt, { M / s, cout }, hfill(335), true)
.dense(dt, { cout }, hfill(336, 0.5f))
.pi("M", M).pi("cin", cin).pi("cout", cout).pi("k", 2 * s).pi("dil", 1)
.pi("causal", 1).pi("stride", s).pi("cu_div", 8).ps("dtype", dn);
hs.push_back(std::move(h));
}
for (const int64_t s : { 5, 3 }) {
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
* from row 1. */
+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);
}
}
+4 -2
View File
@@ -260,8 +260,10 @@ AVX_QB_TARGET static void qb_codes(const QbTab& q, const uint8_t* src, int64_t n
* first code), as code - zero in bf16 into dst[0, npad), the words past n zero. zr[j] is the zero
* of the j-th 32 codes. A code minus its zero lies in [-31, 31], exact in bf16: `t` holds bf16(i -
* 32) for i < 64, which one vpermt2w indexes by code - zero + 32. u5 codes are 40 bits for each
* eight, deposited into bytes by pdep (BMI2, which the caller checked). */
AVX_QB_TARGET __attribute__((target("bmi2"))) static void qb_codes_zp(
* eight, deposited into bytes by pdep (BMI2, which the caller checked). BMI2 is named in the one
* target attribute with the level's features: clang keeps only one of two stacked target
* attributes and then refuses to inline _pdep_u64. */
__attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16,bmi2"))) static void qb_codes_zp(
const uint8_t* row, int bits, int64_t n, int64_t npad, uint16_t* dst, const int32_t* zr,
const __m512i* t) {
for (int64_t i = 0; i < npad; i += 32) {
+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;
+7 -4
View File
@@ -104,10 +104,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) \
@@ -128,7 +130,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 */ \
@@ -136,12 +138,13 @@ int avx_par_force(int threads);
X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \
X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \
X(win_finish) X(chan_split) X(interleave2) X(iota) \
X(cu_repeat) X(snake_aa) X(int_affine) \
X(cu_repeat) X(snake_aa) X(int_affine) X(sub_i32) \
X(ras_pick) X(vq_encode) \
/* ---- sampling, and the drafter's token walk */ \
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);
}
+86 -6
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"),
@@ -693,7 +721,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
P_INTO("causal"), P_INTO("stride"), P_INTO("pad") };
P_INTO("causal"), P_INTO("stride"), P_INTO("pad"),
P_INTO("cu_div") };
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
OUT("y"), WGT_O("b") };
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
@@ -709,19 +738,28 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"),
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
P_INTO("sup_hi"), P_F64O("penalty") };
P_INTO("sup_hi"), P_F64O("penalty"),
P_F64O("top_p") };
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
P_STR("dtype"), P_INTO("round") };
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
P_STR("dtype") };
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
WGT("out_w"), WGT("out_b"), OUT("codes") };
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
P_INTO("rep"), P_STR("dtype") };
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
OPD("frame"), OPD("status"), INOUT("dst") };
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
P_INTO("rep"), P_INTO("clear") };
static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"),
OUT("ids") };
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
P_INTO("rep"), P_INTO("skip") };
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
@@ -752,6 +790,8 @@ static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
static const RadParamSpec pSubI32[] = { P_INT("M") };
static const RadOperandSpec oSubI32[] = { OPD("x"), OPD("s"), OUT("y") };
/* ---- vocabulary edges --------------------------------------------------------------------- */
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
@@ -778,6 +818,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") };
@@ -983,6 +1027,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),
@@ -1011,6 +1060,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." },
@@ -1172,7 +1225,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." },
@@ -1203,10 +1255,16 @@ static const RadOpSchema kSchemas[] = {
"libref's." },
{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed),
"a frame's embedding from code-major residual codes, libref's roundings (`round` 1: one)." },
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
"one residual vector quantiser step: the code of greatest cosine with in_w x + in_b, then "
"x -= out_w cb[code] + out_b; libref's arithmetic in another summation order." },
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
"a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." },
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
{ "ras_pick", ARR(pRasPick), ARR(oRasPick),
"repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in the "
"lane's window of its last picks, else the first; the pick enters the window." },
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
"a frame's codes into its lane's history, code-major rows over the lane's frames." },
{ "resample_nearest", ARR(pMnD), ARR(oUnary),
@@ -1225,6 +1283,7 @@ static const RadOpSchema kSchemas[] = {
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." },
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists." },
{ "sub_i32", ARR(pSubI32), ARR(oSubI32), "y[i] = x[i] - s[0], int32." },
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
@@ -1233,6 +1292,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." },
@@ -1547,6 +1611,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)),
@@ -1572,6 +1639,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,
@@ -1717,7 +1790,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)),
@@ -1739,10 +1811,14 @@ SIMPLE("avx_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
L(cfg_topk_sample)),
SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
DT_FLOAT, L(rvq_embed)),
SIMPLE("avx_vq_encode", "vq_encode", "elem",
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, L(vq_encode)),
SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem",
"a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)),
SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
L(end_status)),
SIMPLE("avx_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane",
DT_ANY, L(ras_pick)),
SIMPLE("avx_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
L(frame_store)),
SIMPLE("avx_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
@@ -1763,6 +1839,8 @@ SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iot
SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)),
SIMPLE("avx_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
L(int_affine)),
SIMPLE("avx_sub_i32", "sub_i32", "elem", "a device int32 vector less a device scalar", DT_ANY,
L(sub_i32)),
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
/* Its layout hook only validates: the table is read as stored and other encodings are refused
@@ -1785,6 +1863,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) {