radiance 1.2.4

- EmbeddingGemma 2 (google/embeddinggemma-2): text, image, video and audio embeddings on the
  card (libr4d) and on the CPU (libavx); prompt_name, Matryoshka dimensions, image budgets,
  mixed content parts and the messages form on /v1/embeddings
- #43: on serves that lend the activation arena to the experts (Qwen3.8-Flash-Next with
  expert_tiered), every image after the first read its rows from the wrong place -- garbage
  replies, or an earlier request's image. Fixed
- the Qwen vision towers' attention resolves on the card again (broken on main after 1.2.3,
  never released)
- #42: a warning at startup when amdgpu cwsr_enable is 0, and a stalled queue is reported as
  slow or stuck; the guide covers the GPU-hang-and-reset chain
This commit is contained in:
Deadcode committed 2026-10-07 22:42:45 +02:00
1 parent 05af4db458
commit 7d840861af
76 files changed
+8324 -467

No files matched your search

+481 -19
View File
@@ -54,6 +54,9 @@
*/
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <vector>
#include "rad_yarn.h"
using namespace avx;
@@ -490,6 +493,282 @@ AVX_KERNEL(attn_paged) {
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_dense, bf16 blocks */
/* AN ENCODER'S ATTENTION IS ALL PREFILL, and the per-query loop below is built for a decode row:
* it parallelises over (segment, head) -- eight units for one long input on a sixteen-core part --
* and widens every key row to f32 again for every query that reads it, so a 2000-token segment
* pays four million row conversions a head. Measured at 130 GFLOPS on the sliding layers.
*
* Where q, k and v are bf16 with unit element stride and the CPU has AVX512_BF16, this blocked
* form runs instead. A task is (segment, KV head, 32 query positions) and holds the rows of every
* query head that reads that KV head, so one key tile serves gqa x 32 rows. Per tile of 64 keys:
*
* S = Q K^T vdpbf16ps against the tile packed once as key-interleaved bf16 pairs, each
* query pair broadcast into 16-key vectors: no score is horizontally reduced
* the mask causal, window and segment end, on the scores
* the softmax online, the running max moved at tile boundaries (this file's arrangement)
* O += P V V's tile packed once for the task as key-interleaved bf16 pairs, P rounded to
* bf16 pairs along the keys (as PyTorch's CPU flash attention does), six rows of
* 64 output columns a block
*
* The key range of a task is cut to what its queries can see, so a sliding layer costs
* O(T * window). Each output row is one task's, so the result does not depend on the thread
* count. Same arithmetic class as the loop below: f32 scores (bf16 products are exact in f32),
* f32 softmax and accumulator, one rounding at the store. */
#if AVX_LEVEL == 3
#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16")))
/* S[r][0..63] for MB_ query rows against a key tile packed as bf16 PAIRS INTERLEAVED BY KEY:
* kp[d2 * 64 + j] holds key j's dims 2*d2 and 2*d2+1. Each step broadcasts one row's pair and
* multiplies it into four 16-key vectors, so a score is never horizontally reduced -- with a
* 64-wide head a reduction per score cost more than the two products it closed. */
template <int MB_>
AVX_BF16_TARGET static inline void qk_rows(const uint16_t* const* qr, const uint32_t* kp,
int64_t D2, float scale, float* S, int64_t ldS) {
__m512 acc[MB_][4];
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) acc[i][v] = _mm512_setzero_ps();
for (int64_t d2 = 0; d2 < D2; ++d2) {
const uint32_t* kr = kp + d2 * 64;
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(kr));
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 16));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 32));
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(kr + 48));
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i) {
uint32_t pr;
std::memcpy(&pr, qr[i] + 2 * d2, 4);
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pr);
acc[i][0] = _mm512_dpbf16_ps(acc[i][0], a, b0);
acc[i][1] = _mm512_dpbf16_ps(acc[i][1], a, b1);
acc[i][2] = _mm512_dpbf16_ps(acc[i][2], a, b2);
acc[i][3] = _mm512_dpbf16_ps(acc[i][3], a, b3);
}
}
const __m512 vs = _mm512_set1_ps(scale);
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(S + i * ldS + 16 * v, _mm512_mul_ps(acc[i][v], vs));
}
/* acc[r][c0 .. c0+63] += P[r] . V for MB_ rows, in bf16 pairs: pp[r * 32 + k2] holds row r's
* probabilities for keys 2*k2 and 2*k2+1, vp[k2 * D + d] holds those two keys' values at column
* d. PyTorch's CPU flash attention -- the reference's -- rounds P to bf16 for this product as
* well; the softmax's sum is kept in f32 from the unrounded P. */
template <int MB_>
AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t* pp,
const uint32_t* vp, int64_t K2, int64_t c0) {
__m512 o[MB_][4];
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) o[i][v] = _mm512_loadu_ps(acc + i * D + c0 + 16 * v);
for (int64_t k2 = 0; k2 < K2; ++k2) {
const uint32_t* vr = vp + k2 * D + c0;
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)(vr));
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 16));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 32));
const __m512bh b3 = (__m512bh)_mm512_loadu_si512((const void*)(vr + 48));
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i) {
const __m512bh a = (__m512bh)_mm512_set1_epi32((int)pp[i * 32 + k2]);
o[i][0] = _mm512_dpbf16_ps(o[i][0], a, b0);
o[i][1] = _mm512_dpbf16_ps(o[i][1], a, b1);
o[i][2] = _mm512_dpbf16_ps(o[i][2], a, b2);
o[i][3] = _mm512_dpbf16_ps(o[i][3], a, b3);
}
}
#pragma GCC unroll 8
for (int i = 0; i < MB_; ++i)
#pragma GCC unroll 4
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]);
}
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,
int64_t kv_heads, int causal, int64_t window,
float scale, int64_t q_rs, int64_t q_hs, int64_t q_ds,
int64_t k_rs, int64_t k_hs, int64_t k_ds, int64_t v_rs,
int64_t v_hs, int64_t v_ds, int64_t o_rs, int64_t o_hs,
int64_t o_ds) {
static const bool have = __builtin_cpu_supports("avx512bf16");
if (!have) return false;
if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return false;
if (q_ds != 1 || k_ds != 1 || v_ds != 1 || o_ds != 1 || D % 64 != 0 || gqa > 16) return false;
constexpr int64_t QB = 32, KT = 64;
const int64_t n_seq = numel(cu) - 1;
/* The task list: (segment, kv head, query block), flattened through a prefix over segments. */
std::vector<int64_t> first((size_t)n_seq + 1, 0);
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t len = ldi(cu, offlin(cu, s + 1)) - ldi(cu, offlin(cu, s));
first[(size_t)s + 1] = first[(size_t)s] + kv_heads * ((len + QB - 1) / QB);
}
const int64_t n_task = first[(size_t)n_seq];
const uint16_t* Q = (const uint16_t*)q->data;
const uint16_t* K = (const uint16_t*)k->data;
const uint16_t* V = (const uint16_t*)v->data;
const int64_t R_MAX = QB * gqa;
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size())
#endif
for (int64_t t = 0; t < n_task; ++t) {
int64_t s = (int64_t)(std::upper_bound(first.begin(), first.end(), t) - first.begin()) - 1;
const int64_t b0 = ldi(cu, offlin(cu, s)), len = ldi(cu, offlin(cu, s + 1)) - b0;
const int64_t local = t - first[(size_t)s];
const int64_t nqb = (len + QB - 1) / QB;
const int64_t kh = local / nqb, q0 = (local % nqb) * QB;
const int64_t q1 = std::min(q0 + QB, len), nq = q1 - q0, R = nq * gqa;
float* frame = scratch_f32((size_t)(R_MAX * D + R_MAX * KT + 2 * R_MAX + KT * D / 2 +
KT * D / 2 + R_MAX * KT / 2) + 64);
float* acc = frame;
float* S = acc + R_MAX * D;
float* m = S + R_MAX * KT;
float* l = m + R_MAX;
uint32_t* kpack = reinterpret_cast<uint32_t*>(l + R_MAX);
uint32_t* vpack = kpack + KT * D / 2;
uint32_t* ppack = vpack + KT * D / 2;
const int64_t D2 = D / 2;
const uint16_t* qrow[16 * QB];
for (int64_t r = 0; r < R; ++r) {
const int64_t qi = r / gqa, g = r % gqa;
qrow[r] = Q + (b0 + q0 + qi) * q_rs + (kh * gqa + g) * q_hs;
m[r] = -INFINITY;
l[r] = 0.0f;
}
std::memset(acc, 0, sizeof(float) * (size_t)(R * D));
int64_t jbeg = 0, jend = causal ? q1 : len;
if (window > 0) {
jbeg = std::max<int64_t>(0, q0 - window + 1);
if (!causal) jend = std::min<int64_t>(len, q1 - 1 + window);
}
for (int64_t j0 = jbeg; j0 < jend; j0 += KT) {
const int64_t kt = std::min(KT, jend - j0);
/* The key tile packed once for every row of the task: pairs interleaved by key, the
* keys past the tile's end zero (their scores are never read). */
for (int64_t d2 = 0; d2 < D2; ++d2) {
uint32_t* dst = kpack + d2 * KT;
for (int64_t j = 0; j < kt; ++j)
std::memcpy(dst + j, K + (b0 + j0 + j) * k_rs + kh * k_hs + 2 * d2, 4);
for (int64_t j = kt; j < KT; ++j) dst[j] = 0;
}
/* S, six rows a block against the whole packed tile. */
int64_t r = 0;
for (; r + 6 <= R; r += 6) qk_rows<6>(qrow + r, kpack, D2, scale, S + r * KT, KT);
for (; r < R; ++r) qk_rows<1>(qrow + r, kpack, D2, scale, S + r * KT, KT);
/* The mask, by position inside the segment. */
if (causal || window > 0) {
for (int64_t r = 0; r < R; ++r) {
const int64_t i = q0 + r / gqa;
for (int64_t j = 0; j < kt; ++j) {
const int64_t d = i - (j0 + j);
bool ok = !causal || d >= 0;
if (window > 0) ok = ok && (causal ? d < window : (d < window && -d < window));
if (!ok) S[r * KT + j] = -INFINITY;
}
}
}
/* The online softmax, row by row, four vectors a row; S becomes P in place. The keys
* past a short tile's end score -inf, so P is zero there and every row is full width. */
if (kt < KT)
for (int64_t r = 0; r < R; ++r)
for (int64_t j = kt; j < KT; ++j) S[r * KT + j] = -INFINITY;
for (int64_t r = 0; r < R; ++r) {
float* sr = S + r * KT;
const float tmax = _mm512_reduce_max_ps(
_mm512_max_ps(_mm512_max_ps(_mm512_loadu_ps(sr), _mm512_loadu_ps(sr + 16)),
_mm512_max_ps(_mm512_loadu_ps(sr + 32), _mm512_loadu_ps(sr + 48))));
if (tmax == -INFINITY) {
for (int64_t j = 0; j < KT; ++j) sr[j] = 0.0f;
continue;
}
if (tmax > m[r]) {
const float alpha = m[r] == -INFINITY ? 0.0f : std::exp(m[r] - tmax);
if (alpha != 1.0f) {
float* ar = acc + r * D;
const __m512 va = _mm512_set1_ps(alpha);
for (int64_t d = 0; d < D; d += 16)
_mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), va));
l[r] *= alpha;
}
m[r] = tmax;
}
const vf vm = vf_set1(m[r]);
__m512 sum = _mm512_setzero_ps();
for (int64_t j = 0; j < KT; j += 16) {
/* exp of -inf is the clamp's floor, ~1e-38: zero to every sum it joins. */
const vf e = vf_exp(vf_sub(vf_loadu(sr + j), vm));
vf_storeu(sr + j, e);
sum = _mm512_add_ps(sum, e);
}
l[r] += _mm512_reduce_add_ps(sum);
}
/* V's tile packed once for every row of the task, consecutive keys interleaved in
* pairs (a key past the tile's end is zero), and each row's P rounded to bf16 pairs
* along the keys. */
const int64_t K2 = (kt + 1) / 2;
{
/* Two key rows' words interleaved, 32 columns a step: lanes 0..15 of the first
* output are (k0[d], k1[d]) for d = 0..15, the second's for d = 16..31. */
const __m512i ilo = _mm512_set_epi16(47, 15, 46, 14, 45, 13, 44, 12, 43, 11, 42, 10,
41, 9, 40, 8, 39, 7, 38, 6, 37, 5, 36, 4, 35, 3,
34, 2, 33, 1, 32, 0);
const __m512i ihi = _mm512_set_epi16(63, 31, 62, 30, 61, 29, 60, 28, 59, 27, 58, 26,
57, 25, 56, 24, 55, 23, 54, 22, 53, 21, 52, 20,
51, 19, 50, 18, 49, 17, 48, 16);
for (int64_t k2 = 0; k2 < K2; ++k2) {
const uint16_t* v0 = V + (b0 + j0 + 2 * k2) * v_rs + kh * v_hs;
const bool two = 2 * k2 + 1 < kt;
uint32_t* dst = vpack + k2 * D;
for (int64_t d = 0; d < D; d += 32) {
const __m512i a = _mm512_loadu_si512((const void*)(v0 + d));
const __m512i bb = two ? _mm512_loadu_si512((const void*)(v0 + v_rs + d))
: _mm512_setzero_si512();
_mm512_storeu_si512((void*)(dst + d), _mm512_permutex2var_epi16(a, ilo, bb));
_mm512_storeu_si512((void*)(dst + d + 16),
_mm512_permutex2var_epi16(a, ihi, bb));
}
}
}
/* P to bf16, round to nearest even: a row's 64 values are its 32 key pairs in order. */
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 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);
for (; r < R; ++r) pv_rows<1>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
}
}
for (int64_t r = 0; r < R; ++r) {
const int64_t qi = r / gqa, g = r % gqa;
const int64_t ob = (b0 + q0 + qi) * o_rs + (kh * gqa + g) * o_hs;
float* ar = acc + r * D;
const float inv = (m[r] == -INFINITY || l[r] <= 0.0f) ? 0.0f : 1.0f / l[r];
const __m512 vi = _mm512_set1_ps(inv);
for (int64_t d = 0; d < D; d += 16)
_mm512_storeu_ps(ar + d, _mm512_mul_ps(_mm512_loadu_ps(ar + d), vi));
out_row(o, ob, D, ar);
}
}
return true;
}
#endif
/* ------------------------------------------------------------------ attn_dense */
/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
* attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
@@ -505,10 +784,15 @@ AVX_KERNEL(attn_dense) {
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
/* libref's window: causal, i - j < window; non-causal, |i - j| < window; 0 none. */
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE;
if (head_dim > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2] : 1;
/* A rank-2 operand is [tokens, heads * head_dim], so its head count is its width over the
* head; reading it as one head would take every head of a multi-head slice for one long one. */
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
const int64_t kv_heads = q_heads / gqa;
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
@@ -534,6 +818,11 @@ AVX_KERNEL(attn_dense) {
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#if AVX_LEVEL == 3
if (attn_dense_bf16(q, k, v, cu, o, head_dim, gqa, kv_heads, causal, window, scale, q_rs,
q_hs, q_ds, k_rs, k_hs, k_ds, v_rs, v_hs, v_ds, o_rs, o_hs, o_ds))
return RAD_OK;
#endif
AVX_PARALLEL_FOR_IF(n_seq * q_heads >= 2)
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
@@ -550,7 +839,11 @@ AVX_KERNEL(attn_dense) {
for (int64_t i = b0; i < b1; ++i) {
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
const int64_t jend = causal ? (i + 1) : b1;
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
if (window > 0) {
jbeg = std::max<int64_t>(b0, i - window + 1);
if (!causal) jend = std::min<int64_t>(b1, i + window);
}
const float* qv = head_f32(q, qb, q_ds, head_dim, 1.0f, qbuf);
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float m = -INFINITY, l = 0.0f;
@@ -589,7 +882,7 @@ AVX_KERNEL(attn_dense) {
ntile = 0;
};
for (int64_t j = b0; j < jend; ++j) {
for (int64_t j = jbeg; j < jend; ++j) {
const float* kvr = head_f32(k, j * k_rs + kh * k_hs, k_ds, head_dim, 1.0f, kbuf);
sbuf[ntile] = dotf(qv, kvr, head_dim) * scale;
vbase[ntile] = j * v_rs + kh * v_hs;
@@ -617,6 +910,92 @@ AVX_KERNEL(attn_dense) {
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_local_rel */
/* libref's local attention with a relative-position term (Gemma 4's audio). A query sees at most
* left + 1 keys -- thirteen at the checkpoint's geometry -- so the work is a few dot products a
* (row, head) and the loop is libref's, vectorised along the head and parallel over (row, head). */
AVX_KERNEL(attn_local_rel) {
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3];
const RadTensor *pds = &a->t[4], *cu = &a->t[5], *o = &a->t[6];
const int64_t D = p_int(a, "head_dim", 0), H = p_int(a, "n_head", 0);
const int64_t L = p_int(a, "left", 0), R = p_int(a, "right", 0);
const int64_t cdiv = p_int(a, "cu_div", 1);
const float cap = p_f32(a, "softcap", 0.0f);
if (D <= 0 || H <= 0 || L < 0 || cdiv <= 0 || !(cap > 0.0f)) return RAD_E_SHAPE;
if (R != 0) return RAD_E_UNSUPPORTED;
if (D > AVX_HD_MAX || L + 1 > AVX_HD_MAX) return RAD_E_UNSUPPORTED;
const int64_t Wd = H * D;
if (numel(pds) < D || numel(rk) < (L + 1) * Wd) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mq = numel(q) / Wd, Mk = numel(k) / Wd, Mv = numel(v) / Wd, Mo = numel(o) / Wd;
const int64_t q_rs = row_stride(q, Wd), k_rs = row_stride(k, Wd), v_rs = row_stride(v, Wd);
const int64_t r_rs = row_stride(rk, Wd), o_rs = row_stride(o, Wd);
const int64_t q_ds = laststride(q), k_ds = laststride(k), v_ds = laststride(v);
const int64_t r_ds = laststride(rk), o_ds = laststride(o);
const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0));
const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
/* softplus(pds), rounded to the weight's dtype as the reference evaluates it on the bf16
* parameter (libref's reading), and the query's whole scale folded into one vector. */
float* spd = (float*)scratch_raw((size_t)D * sizeof(float) + 64);
for (int64_t d = 0; d < D; ++d) {
const float x = ldt(pds, d * laststride(pds));
const float sp = x > 20.0f ? x : (x > 0.0f ? x + std::log1p(std::exp(-x))
: std::log1p(std::exp(x)));
float r = sp;
if (pds->dtype == RAD_BF16) r = rad_bf16_to_f32(rad_f32_to_bf16(sp));
else if (pds->dtype == RAD_F16) r = rad_f16_to_f32(rad_f32_to_f16(sp));
spd[d] = r;
}
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF((t1 - t0) * H * (L + 1) * D >= AVX_PAR_MIN)
for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) {
const int64_t i = t0 + ih / H, h = ih % H;
float* frame = scratch_f32((size_t)(4 * D + L + 1) + 16);
float* qf = frame;
float* kb = frame + D;
float* acc = frame + 2 * D;
float* tmp = frame + 3 * D;
float* lg = frame + 4 * D;
const float* qv = head_f32(q, i * q_rs + h * D * q_ds, q_ds, D, 1.0f, tmp);
for (int64_t d = 0; d < D; ++d) qf[d] = qv[d] * qs * spd[d];
const int64_t j0 = i - L > t0 ? i - L : t0;
float mx = -INFINITY;
for (int64_t j = j0; j <= i; ++j) {
const float* kv = head_f32(k, j * k_rs + h * D * k_ds, k_ds, D, 1.0f, tmp);
for (int64_t d = 0; d < D; ++d) kb[d] = kv[d] * ks;
float ac = dotf(qf, kb, D);
const float* rv = head_f32(rk, (i - j) * r_rs + h * D * r_ds, r_ds, D, 1.0f, tmp);
ac += dotf(qf, rv, D);
const float x = cap * std::tanh(ac / cap);
lg[j - j0] = x;
mx = x > mx ? x : mx;
}
float sum = 0.0f;
for (int64_t j = j0; j <= i; ++j) {
lg[j - j0] = std::exp(lg[j - j0] - mx);
sum += lg[j - j0];
}
for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f;
for (int64_t j = j0; j <= i; ++j)
axpy(acc, head_f32(v, j * v_rs + h * D * v_ds, v_ds, D, 1.0f, tmp),
lg[j - j0] / sum, D);
const int64_t ob = i * o_rs + h * D * o_ds;
if (o_ds == 1) out_row(o, ob, D, acc);
else for (int64_t d = 0; d < D; ++d) stt(o, ob + d * o_ds, acc[d]);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ kv_store */
/* The cache operand is INOUT and not OUT: this op touches only the mapped slots and every other
* slot in the pool must survive it, which is a liveness fact the buffer planner has to know.
@@ -888,27 +1267,77 @@ AVX_KERNEL(qk_norm_rope) {
const float eps = p_f32(a, "eps", 1e-6f);
const float rscale = p_f32(a, "scale", 1.0f);
const float wadd = p_f32(a, "wadd", 0.0f);
static const char* kModes[] = { "neox", "gptj" };
const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX);
const int v_norm = (int)p_int(a, "v_norm", 0);
static const char* kModes[] = { "neox", "gptj", "blocks" };
const int mode = p_enum(a, "mode", kModes, 3, ROPE_NEOX);
if (mode < 0) return RAD_E_UNSUPPORTED;
const bool blocks = mode == 2;
const int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
/* BLOCKS (libref): section c is sec[c] pairs over its own 2 * sec[c] channels, paired
* (start + j, start + sec[c] + j), turned by position component comps[c]. */
int64_t sec[8] = {}, comp[8] = {};
int n_sec = 0;
if (blocks) {
for (const char* v = p_str(a, "sections", nullptr); v && *v && n_sec < 8; ) {
char* end = nullptr;
const long long x = std::strtoll(v, &end, 10);
if (end == v) break;
if (x <= 0) return RAD_E_SHAPE;
comp[n_sec] = n_sec;
sec[n_sec++] = x;
v = end;
}
int64_t total = 0;
for (int c = 0; c < n_sec; ++c) total += sec[c];
if (n_sec <= 0 || 2 * total != rot) return RAD_E_SHAPE;
if (const char* cs = p_str(a, "comps", nullptr)) {
int k = 0;
for (const char* v = cs; *v && k < 8; ) {
char* end = nullptr;
const long long x = std::strtoll(v, &end, 10);
if (end == v) break;
comp[k++] = x;
v = end;
}
if (k != n_sec) return RAD_E_SHAPE;
}
}
const bool multi = pos->rank >= 2;
const int64_t n_comp = multi ? pos->shape[0] : 1;
if (multi && !blocks) return RAD_E_SHAPE;
for (int c = 0; c < n_sec; ++c)
if (comp[c] < 0 || comp[c] >= n_comp || n_comp > 8) return RAD_E_SHAPE;
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
const int64_t M = numel(pos);
const int64_t M = multi ? pos->shape[1] : numel(pos);
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
const int64_t half = rot / 2;
/* One arena call for the launch-invariant tables: the inverse frequencies and both widened
* gains. A second scratch_raw would reallocate under the parallel region. */
float* tab = (float*)scratch_raw((size_t)(half + 2 * head_dim) * sizeof(float) + 64);
/* One arena call for the launch-invariant tables: the inverse frequencies (and, for blocks,
* each pair's component) and both widened gains. A second scratch_raw would reallocate under
* the parallel region. */
float* tab = (float*)scratch_raw((size_t)(2 * half + 2 * head_dim) * sizeof(float) + 64);
float* invf = tab;
float* gq = tab + half;
float* gk = tab + half + head_dim;
for (int64_t i = 0; i < half; ++i)
invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
float* pcomp = tab + half;
float* gq = tab + 2 * half;
float* gk = tab + 2 * half + head_dim;
if (!blocks) {
for (int64_t i = 0; i < half; ++i)
invf[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
} else {
int64_t i = 0;
for (int c = 0; c < n_sec; ++c)
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
invf[i] = 1.0f / std::pow(theta, (float)j / (float)sec[c]);
pcomp[i] = (float)comp[c];
}
}
for (int64_t d = 0; d < head_dim; ++d) {
gq[d] = ldt(qw, d * laststride(qw)) + wadd;
gk[d] = ldt(kw, d * laststride(kw)) + wadd;
@@ -916,12 +1345,23 @@ AVX_KERNEL(qk_norm_rope) {
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * head_dim >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
const float p = (float)ldi(pos, offlin(pos, m)) / (rscale != 0.0f ? rscale : 1.0f);
const float div = rscale != 0.0f ? rscale : 1.0f;
float pc[8];
if (multi)
for (int64_t c = 0; c < n_comp; ++c) pc[c] = (float)ldi(pos, c * pcs + m * pms) / div;
else
pc[0] = (float)ldi(pos, offlin(pos, m)) / div;
const int64_t row = m * rs;
float* cs = scratch_f32((size_t)rot);
float* buf = scratch_f32_b((size_t)head_dim);
float* rbuf = scratch_f32_c((size_t)head_dim);
angles(cs, invf, half, p);
if (!blocks) angles(cs, invf, half, pc[0]);
else
for (int64_t i = 0; i < half; ++i) {
const float ang = pc[(int)pcomp[i]] * invf[i];
cs[i] = std::cos(ang);
cs[half + i] = std::sin(ang);
}
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
const float* g = h < n_head ? gq : gk;
const int64_t base = row + h * head_dim * ds;
@@ -932,11 +1372,33 @@ AVX_KERNEL(qk_norm_rope) {
for (; d + VF_N <= head_dim; d += VF_N)
vf_storeu(rbuf + d, vf_mul(vf_mul(vf_loadu(xv + d), vs), vf_loadu(g + d)));
for (; d < head_dim; ++d) rbuf[d] = xv[d] * sc * g[d];
/* Written back through the operand's dtype, then re-read by rope_head -- the rounding
* across the seam is the contract. */
/* Written back through the operand's dtype, then re-read by the rotation -- the
* rounding across the seam is the contract. */
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
else for (int64_t i = 0; i < head_dim; ++i) stt(qkv, base + i * ds, rbuf[i]);
rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
if (!blocks) {
rope_head(qkv, base, ds, rot, mode, cs, half, rbuf);
continue;
}
int64_t i = 0, start = 0;
for (int c = 0; c < n_sec; ++c) {
for (int64_t j = 0; j < sec[c]; ++j, ++i) {
const int64_t i0 = start + j, i1 = start + sec[c] + j;
const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds);
stt(qkv, base + i0 * ds, x0 * cs[i] - x1 * cs[half + i]);
stt(qkv, base + i1 * ds, x0 * cs[half + i] + x1 * cs[i]);
}
start += 2 * sec[c];
}
}
/* v_norm: the v heads RMS-normed with a unit gain and not rotated (libref). */
for (int64_t h = 0; v_norm && h < n_head_kv; ++h) {
const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds;
const float* xv = head_f32(qkv, base, ds, head_dim, 1.0f, buf);
const float sc = 1.0f / std::sqrt(row_sumsq(xv, head_dim) / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d) rbuf[d] = xv[d] * sc;
if (ds == 1) out_row(qkv, base, head_dim, rbuf);
else for (int64_t d = 0; d < head_dim; ++d) stt(qkv, base + d * ds, rbuf[d]);
}
}
return RAD_OK;
+72 -2
View File
@@ -58,6 +58,30 @@ std::vector<Case> build_cases() {
EB(6, 645, w, 1));
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" })
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));
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt), HI("scalar", 1) },
EB(9, 645, w, 2));
add("seg_mean", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 1));
add("relu", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2));
add("clamp", { HI("M", 7), HI("n", 645), HS("dtype", dt) }, EB(7, 645, w, 2));
add("rmsnorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-6), HS("dtype", dt),
HF("wadd", 0), HF("mult", 0.5) }, EB(5, 645, w, 2));
/* The audio subsampler's two geometries, scaled down in time, with and without the
* frame mask, and a segment boundary (cu_div 2: the cu counts finer than the rows). */
add("conv2d", { HI("M", 24), HI("width", 16), HI("cin", 1), HI("cout", 24), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1), HS("dtype", dt) });
add("conv2d", { HI("M", 24), HI("width", 8), HI("cin", 20), HI("cout", 12), HI("kh", 3),
HI("kw", 3), HI("stride", 2), HI("pad", 1), HI("cu_div", 2),
HI("valid_stride", 2), HS("dtype", dt) });
add("conv1d_dw", { HI("M", 26), HI("n", 645), HI("k", 5), HS("dtype", dt) });
add("conv1d_dw", { HI("M", 24), HI("n", 64), HI("k", 5), HI("cu_div", 4), HS("dtype", dt) });
add("rel_sinusoid", { HI("M", 13), HI("n", 1024), HF("max_timescale", 10000.0),
HS("dtype", dt) });
add("pool_rows", { HI("M", 27), HI("n", 645), HI("k", 9), HF("mult", 27.712812921102035),
HS("dtype", dt) }, EB(27, 645, w, 1));
add("scatter_rows", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2));
add("scale_rows", { HI("M", 6), HI("n", 645), HS("act", "sigmoid"), HS("dtype", dt) },
EB(6, 645, w, 2));
@@ -146,6 +170,18 @@ std::vector<Case> build_cases() {
add("logits_gemm", { HI("M", M), HI("n_vocab", 96), HI("n_embd", 259),
HS("dtype", dt) }, 0, fl);
}
/* Encoder-sized M at a width that is not a whole number of 48-column panels, with K odd and
* even: 37 rows take the bf16 dot-product path, 133 the outer-product one -- its column edge,
* its zero-paired last k and its five-row tail. */
for (const char* dt : { "f32", "bf16" })
for (int M : { 37, 133 })
for (int K : { 259, 64 }) {
const double fl = 2.0 * M * 100 * K;
add("gemm_nt", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt) },
0, fl);
add("gemm_nt_bias", { HI("M", M), HI("N", 100), HI("K", K), HS("dtype", dt),
HS("act", "gelu_tanh") }, 0, fl);
}
/* fp8a8 and fp8a16 ARE THE ONLY TWO libref CAN DESCRIBE, and that is a real limit rather than
* a gap in this table: `gemm_nt_q` is one op over six weight formats and the SCALE GRID is
* what differs between them -- per row, per row-group, per output-row-block, an e8m0 exponent
@@ -172,7 +208,9 @@ std::vector<Case> build_cases() {
HS("dtype", "fp8a8"), HS("act", "silu") }, 0, 2.0 * 7 * 512 * 256);
for (const char* dt : { "f32", "bf16" }) {
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("wscale", 0) });
HI("vocab_offset", 0), HF("mult", 1) });
add("embed_lookup", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("mult", 22.625) });
add("embed_lookup_q", { HI("M", 9), HI("n_embd", 128), HI("n_vocab", 64), HS("dtype", dt),
HI("vocab_offset", 0), HF("wscale", 0.01) });
}
@@ -191,7 +229,20 @@ std::vector<Case> build_cases() {
for (int causal : { 0, 1 })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
HI("max_seqlen", 24) });
HI("max_seqlen", 24), HI("window", 0) });
/* The sliding window both ways: bidirectional |i - j| < 5 and causal i - j < 5, over
* segments longer than the window so both bounds bite. */
for (const char* dt : { "f32", "bf16" })
for (int causal : { 0, 1 })
add("attn_dense", { HI("M", 24), HI("head_dim", 64), HI("gqa", 2),
HI("causal", causal), HS("dtype", dt), HF("scale", 0.125),
HI("max_seqlen", 24), HI("window", 5) });
/* Gemma 4's audio attention: left 12 over segments longer than the window. */
for (const char* dt : { "f32", "bf16" })
for (int cd : { 1, 4 })
add("attn_local_rel", { HI("M", 40), HI("head_dim", 32), HI("n_head", 3),
HI("left", 12), HI("right", 0), HF("softcap", 50.0),
HI("cu_div", cd), HS("dtype", dt) });
for (const char* dt : { "f32", "bf16" })
add("kv_store", { HI("M", 12), HI("head_dim", 64), HI("n_head_kv", 2),
HI("block_size", 16), HS("kv_dtype", dt), HF("k_scale", 1.0),
@@ -203,6 +254,18 @@ std::vector<Case> build_cases() {
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("eps", 1e-6), HF("scale", 1.0),
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0) });
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 10000.0), HF("eps", 1e-6), HF("scale", 1.0),
HS("mode", mode), HI("rotary_dim", 64), HF("wadd", 0),
HI("v_norm", 1) });
}
/* `blocks`, the two-component vision form: x over the first half, y over the second, the
* components named in the other order from the planes. */
for (const char* dt : { "f32", "bf16" }) {
add("qk_norm_rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 4),
HF("theta", 100.0), HF("eps", 1e-6), HS("mode", "blocks"),
HS("sections", "16 16"), HS("comps", "1 0"), HI("v_norm", 1),
HS("dtype", dt) });
}
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32") });
@@ -383,6 +446,13 @@ std::vector<Case> build_cases() {
0, 2.0 * M * 2048 * 2048);
speed("gemm_nt", { HI("M", M), HI("N", 5632), HI("K", 2048), HS("dtype", "bf16") },
0, 2.0 * M * 5632 * 2048);
}
/* An encoder step: every token of the batch at once, at EmbeddingGemma 2's two FFN shapes. */
for (int M : { 2048 }) {
speed("gemm_nt", { HI("M", M), HI("N", 4096), HI("K", 512), HS("dtype", "bf16") },
0, 2.0 * M * 4096 * 512);
speed("gemm_nt", { HI("M", M), HI("N", 512), HI("K", 2048), HS("dtype", "bf16") },
0, 2.0 * M * 512 * 2048);
speed("rmsnorm", { HI("M", M), HI("n", 2048), HF("eps", 1e-6), HS("dtype", "bf16"),
HF("wadd", 0) }, (double)M * 2048 * 2 * 2, 0);
speed("silu_mul", { HI("M", M), HI("n", 5632), HS("dtype", "bf16") },
+44 -2
View File
@@ -40,8 +40,49 @@
#ifdef _OPENMP
#include <omp.h>
#include <sched.h>
#include <cstdio>
#include <cstdlib>
/* THE TEAM IS ONE THREAD A PHYSICAL CORE, not one a logical CPU. These kernels are FMA- or
* bandwidth-bound, so an SMT sibling adds next to nothing to them -- and the engine runs threads
* of its own beside the team (a worker per stream, the scheduler, the HTTP server). A team as
* wide as the logical CPU count leaves those nowhere to run but on a core a team thread is
* spinning on, and a team barrier then waits for a descheduled thread: measured on a 16-core,
* 32-thread part, an encoder step of 576 tokens took 0.75 s at 32 threads and 0.09 s at 16.
* Counted over the process's affinity mask, so a pinned or containerised engine sizes its team to
* what it was given; OMP_NUM_THREADS, when set, is the operator's and wins, and a thread that
* asked OpenMP for fewer (omp_set_num_threads) gets fewer. */
static inline int avx_team_size() {
/* The physical core count is a property of the process and counted once; the OpenMP request
* is the calling thread's and read every time, so a caller that asks for fewer threads
* (omp_set_num_threads, as the benchmark does for its single-thread figures) gets them. */
static const int cores = [] {
if (const char* e = std::getenv("OMP_NUM_THREADS"); e && *e) return 0;
cpu_set_t set;
if (sched_getaffinity(0, sizeof set, &set) != 0) return 0;
int n = 0;
for (int c = 0; c < CPU_SETSIZE; ++c) {
if (!CPU_ISSET(c, &set)) continue;
/* A CPU counts when it is the first of its core's siblings that is in the mask. */
char path[96];
std::snprintf(path, sizeof path,
"/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", c);
int first = c;
if (FILE* f = std::fopen(path, "r")) {
int v = -1;
if (std::fscanf(f, "%d", &v) == 1 && v >= 0 && v < CPU_SETSIZE && CPU_ISSET(v, &set))
first = v;
std::fclose(f);
}
n += first == c;
}
return n;
}();
const int asked = omp_get_max_threads();
return cores > 0 && cores < asked ? cores : asked;
}
#define AVX_PRAGMA(x) _Pragma(#x)
#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static))
#define AVX_PARALLEL_FOR AVX_PRAGMA(omp parallel for schedule(static) num_threads(avx_team_size()))
/* THE OUTER LOOP IS WORTH A TEAM ONLY WHEN THERE IS ENOUGH WORK TO PAY FOR STARTING ONE, and the
* `if` clause is how that is said without writing the serial loop twice. A fork/join costs a few
* microseconds; an op below the threshold spends more time in the barrier than in the arithmetic,
@@ -49,7 +90,8 @@
* measured by `rad-avx-bench --threads`.
*
* `cond` is pasted into the pragma text, so it must contain no comma. */
#define AVX_PARALLEL_FOR_IF(cond) AVX_PRAGMA(omp parallel for schedule(static) if(cond))
#define AVX_PARALLEL_FOR_IF(cond) \
AVX_PRAGMA(omp parallel for schedule(static) if(cond) num_threads(avx_team_size()))
#else
#define AVX_PARALLEL_FOR
#define AVX_PARALLEL_FOR_IF(cond)
+360
View File
@@ -80,6 +80,366 @@ static int elementwise2(const RadArgs* a) {
AVX_KERNEL(add) { return elementwise2<false>(a); }
AVX_KERNEL(mul) { return elementwise2<true>(a); }
/* y = x * w, `w` a weight of one element or one row (libref's mul_weight). */
AVX_KERNEL(mul_weight) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const bool scalar = numel(W) == 1;
if (!scalar && numel(W) != n) return RAD_E_SHAPE;
/* The gain, widened once: it is the same row for every row of x. */
float* wrow = (float*)scratch_raw((size_t)n * sizeof(float) + 64);
if (scalar) { const float v = ldt(W, 0); for (int64_t i = 0; i < n; ++i) wrow[i] = v; }
else for (int64_t i = 0; i < n; ++i) wrow[i] = ldt(W, i * laststride(W));
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sa = scratch_f32((size_t)n);
float* sy = scratch_f32_c((size_t)n);
const float* x = in_row(X, rowoff(X, r, n), n, sa);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N)
vf_storeu(sy + i, vf_mul(vf_loadu(x + i), vf_loadu(wrow + i)));
for (; i < n; ++i) sy[i] = x[i] * wrow[i];
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ act_mul */
/* y = act(a) * b over two operands, libref's contract: the activation is rounded to y's dtype
* before the product, because the unfused pair stores it.
*
* silu and gelu_tanh are VECTORISED on vf_exp. An encoder's gated FFN puts this op on every token
* of every layer, and the scalar libm form was 9% of an EmbeddingGemma 2 step on a 9950X3D -- a
* per-element tanhf behind 2048 columns. gelu_tanh keeps the reference's own structure,
*
* 0.5 g (1 + tanh z), z = sqrt(2/pi) (g + 0.044715 g^3), tanh z = (1 - e^(-2z)) / (1 + e^(-2z))
*
* and not the algebraically equal g / (1 + e^(-2z)): the two differ by an ulp or two of f32, and
* after the bf16 rounding the rearranged form moved an EmbeddingGemma 2 embedding measurably
* further from transformers' (cosine 0.999919 -> 0.999894 on one input; torch computes this same
* 0.5 g (1 + tanh) in f32). vf_exp saturates rather than overflowing, so the large-|g| limits come
* out as g and 0. erf has no vector form in this plugin, so gelu stays scalar. */
static inline float act_of(int act, float g) {
if (act == 0) return g / (1.0f + std::exp(-g));
if (act == 1) return 0.5f * g * (1.0f + std::erf(g * 0.70710678118654752f));
if (act == 3) return 1.0f / (1.0f + std::exp(-g));
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * g * (1.0f + std::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) {
int64_t i = 0;
const vf one = vf_set1(1.0f);
if (act == 0) {
for (; i + VF_N <= n; i += VF_N) {
const vf x = vf_loadu(g + i);
vf_storeu(sy + i, vf_div(x, vf_add(one, vf_exp(vf_sub(vf_zero(), x)))));
}
} else if (act == 2) {
const vf m2k0 = vf_set1(-2.0f * 0.7978845608028654f), k1 = vf_set1(0.044715f);
const vf half = vf_set1(0.5f);
for (; i + VF_N <= n; i += VF_N) {
const vf x = vf_loadu(g + i);
const vf inner = vf_fma(vf_mul(k1, x), vf_mul(x, x), x); /* g + k1 g^3 */
const vf e = vf_exp(vf_mul(m2k0, inner)); /* e^(-2z) */
const vf t = vf_div(vf_sub(one, e), vf_add(one, e)); /* tanh z */
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]);
}
AVX_KERNEL(act_mul) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", numel(Y));
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);
if (act < 0) return RAD_E_INVAL;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sa = scratch_f32((size_t)n);
float* sb = scratch_f32_b((size_t)n);
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);
/* sa is free once the activation is taken (g is either sa or the tensor itself); sb may
* hold u, which the product still reads. */
roundtrip(Y->dtype, sy, n, sa);
for (int64_t i = 0; i < n; ++i) sy[i] *= u[i];
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ relu / clamp */
/* y = max(x, 0), and y = min(max(x, lo), hi) with lo and hi WEIGHTS of one element each (a
* clipped linear's range). Row-wise at each operand's own pitch, like the libref forms. */
AVX_KERNEL(relu) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* v = in_row(X, rowoff(X, r, n), n, sx);
int64_t i = 0;
for (; i + VF_N <= n; i += VF_N) vf_storeu(sy + i, vf_max(vf_loadu(v + i), vf_zero()));
for (; i < n; ++i) sy[i] = v[i] > 0.0f ? v[i] : 0.0f;
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
}
AVX_KERNEL(clamp) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0 || numel(L) < 1 || numel(H) < 1) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const float lo = ldt(L, 0), hi = ldt(H, 0);
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* sx = scratch_f32((size_t)n);
float* sy = scratch_f32_b((size_t)n);
const float* v = in_row(X, rowoff(X, r, n), n, sx);
for (int64_t i = 0; i < n; ++i) {
float t = v[i] < lo ? lo : v[i];
sy[i] = t > hi ? hi : t;
}
out_row(Y, rowoff(Y, r, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv2d */
/* libref's segment-wise convolution over (time, width), channels innermost. The weight is turned
* once a launch from PyTorch's [cout, cin, kh, kw] into [kh][kw][cin][cout], so each input value is
* broadcast against a contiguous run of output channels: the inner loop is a vector FMA over cout
* rather than a dot product over cin. Same sum (in a different order), one rounding. */
AVX_KERNEL(conv2d) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data)
return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4];
const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1);
if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 ||
vst <= 0)
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1;
if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, rout = Wo * cout;
const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout);
float* wt = (float*)scratch_raw((size_t)(kh * kw * cin * cout) * sizeof(float) + 64);
const int64_t ws = laststride(Wt);
for (int64_t co = 0; co < cout; ++co)
for (int64_t ci = 0; ci < cin; ++ci)
for (int64_t i = 0; i < kh; ++i)
for (int64_t j = 0; j < kw; ++j)
wt[((i * kw + j) * cin + ci) * cout + co] =
ldt(Wt, (((co * cin + ci) * kh + i) * kw + j) * ws);
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0;
if (T <= 0) continue;
const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st;
if (To <= 0) continue;
if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(To * rout * cin * kh * kw >= AVX_PAR_MIN)
for (int64_t to = 0; to < To; ++to) {
float* acc = scratch_f32((size_t)rout);
float* sx = scratch_f32_b((size_t)rin);
for (int64_t e = 0; e < rout; ++e) acc[e] = 0.0f;
for (int64_t i = 0; i < kh; ++i) {
const int64_t ti = to * st - pad + i;
if (ti < 0 || ti >= T) continue;
const int64_t tg = t0 + ti;
if (V && ldi(V, offlin(V, tg * vst)) == 0) continue;
const float* xr = in_row(X, rowoff(X, tg, rin), rin, sx);
for (int64_t wo = 0; wo < Wo; ++wo) {
float* ar = acc + wo * cout;
for (int64_t j = 0; j < kw; ++j) {
const int64_t wi = wo * st - pad + j;
if (wi < 0 || wi >= W) continue;
const float* xv = xr + wi * cin;
const float* wb = wt + (i * kw + j) * cin * cout;
for (int64_t ci = 0; ci < cin; ++ci) {
const vf b = vf_set1(xv[ci]);
const float* wr = wb + ci * cout;
int64_t c = 0;
for (; c + VF_N <= cout; c += VF_N)
vf_storeu(ar + c, vf_fma(b, vf_loadu(wr + c), vf_loadu(ar + c)));
for (; c < cout; ++c) ar[c] += xv[ci] * wr[c];
}
}
}
}
out_row(Y, rowoff(Y, o0 + to, rout), rout, acc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv1d_dw */
/* libref's causal depthwise convolution over time, the weight turned to [k][C] once a launch so
* a row is a vector FMA per tap. */
AVX_KERNEL(conv1d_dw) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
const int64_t C = p_int(a, "n", 0), K = p_int(a, "k", 0), cdiv = p_int(a, "cu_div", 1);
if (C <= 0 || K <= 0 || cdiv <= 0 || numel(Wt) < C * K) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
float* wt = (float*)scratch_raw((size_t)(K * C) * sizeof(float) + 64);
for (int64_t c = 0; c < C; ++c)
for (int64_t j = 0; j < K; ++j) wt[j * C + c] = ldt(Wt, (c * K + j) * laststride(Wt));
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ldi(cu, offlin(cu, s)), c1 = ldi(cu, offlin(cu, s + 1));
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
if (t1 > Mx || t1 > My) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF((t1 - t0) * C * K >= AVX_PAR_MIN)
for (int64_t t = t0; t < t1; ++t) {
float* acc = scratch_f32((size_t)C);
float* sx = scratch_f32_b((size_t)C);
for (int64_t c = 0; c < C; ++c) acc[c] = 0.0f;
for (int64_t j = 0; j < K; ++j) {
const int64_t tt = t - (K - 1) + j;
if (tt < t0) continue;
const float* xr = in_row(X, rowoff(X, tt, C), C, sx);
const float* wr = wt + j * C;
int64_t c = 0;
for (; c + VF_N <= C; c += VF_N)
vf_storeu(acc + c, vf_fma(vf_loadu(xr + c), vf_loadu(wr + c), vf_loadu(acc + c)));
for (; c < C; ++c) acc[c] += xr[c] * wr[c];
}
out_row(Y, rowoff(Y, t, C), C, acc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rel_sinusoid */
/* libref's table, to the operation: the same f32 steps and the same libm calls. */
AVX_KERNEL(rel_sinusoid) {
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
const RadTensor* Y = &a->t[0];
const int64_t n = p_int(a, "n", 0);
if (n <= 0 || n % 2) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0) return RAD_E_SHAPE;
const int64_t h = n / 2;
const double mt = (double)p_f32(a, "max_timescale", 10000.0f);
const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t d = 0; d < rows; ++d) {
float* sy = scratch_f32((size_t)n);
for (int64_t i = 0; i < h; ++i) {
const float inv = std::exp((float)i * -inc);
const float ang = (float)d * inv;
sy[i] = std::sin(ang);
sy[h + i] = std::cos(ang);
}
out_row(Y, rowoff(Y, d, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_mean */
/* One row a cu_seqlens segment: the mean of its rows, summed in double and rounded once, which is
* libref's arithmetic -- a pooled embedding should not depend on which host kernel pooled it. */
AVX_KERNEL(seg_mean) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = ldi(cu, offlin(cu, S));
if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(S >= 2)
for (int64_t s = 0; s < S; ++s) {
const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1));
double* acc = (double*)scratch_raw((size_t)n * sizeof(double) + 64);
float* sx = scratch_f32_b((size_t)n);
float* sy = scratch_f32_c((size_t)n);
for (int64_t i = 0; i < n; ++i) acc[i] = 0.0;
for (int64_t r = b0; r < b1; ++r) {
const float* x = in_row(X, rowoff(X, r, n), n, sx);
for (int64_t i = 0; i < n; ++i) acc[i] += x[i];
}
const double inv = b1 > b0 ? 1.0 / (double)(b1 - b0) : 0.0;
for (int64_t i = 0; i < n; ++i) sy[i] = b1 > b0 ? (float)(acc[i] * inv) : 0.0f;
out_row(Y, rowoff(Y, s, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_rows */
/* libref's: the mean of each k consecutive rows summed in f32 and rounded to y's dtype, then the
* multiplier and a second rounding -- the unfused pair. Parallel over output rows. */
AVX_KERNEL(pool_rows) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), k = p_int(a, "k", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n <= 0 || k <= 0) return RAD_E_SHAPE;
const int64_t rows_in = rows_of(X, n);
if (rows_in <= 0 || rows_in % k) return RAD_E_SHAPE;
const int64_t rows = rows_in / k;
if (numel(Y) < rows * n) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
AVX_PARALLEL_FOR_IF(rows * n * k >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
float* acc = scratch_f32((size_t)n);
float* sx = scratch_f32_b((size_t)n);
for (int64_t i = 0; i < n; ++i) acc[i] = 0.0f;
for (int64_t j = 0; j < k; ++j) {
const float* v = in_row(X, rowoff(X, r * k + j, n), n, sx);
for (int64_t i = 0; i < n; ++i) acc[i] += v[i];
}
for (int64_t i = 0; i < n; ++i) acc[i] *= inv;
roundtrip(Y->dtype, acc, n, sx);
for (int64_t i = 0; i < n; ++i) acc[i] *= mult;
out_row(Y, rowoff(Y, r, n), n, acc);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]), then + add[m, i] if the optional residual is passed.
*
+341 -6
View File
@@ -367,6 +367,333 @@ static int gemm_drive(const Mat& ma, const Mat& mb, const Scales* SA, const Scal
return RAD_OK;
}
/* ================================================================== the bf16 outer-product path
*
* AN ENCODER'S GEMM IS ALL PREFILL: M is the step's whole token count, thousands of rows, every
* launch. The driver above is shaped for decode -- it packs A on the calling thread one M block at
* a time and re-widens each weight row into f32 once per M block -- and at M = 3000, K = 2048 that
* is the weight widened a hundred times over, behind a single-threaded pack, for 0.14 TFLOPS on a
* 16-core part.
*
* Where both operands are bf16 with unit element stride and the CPU has AVX512_BF16 (Zen 4 on,
* Cooper Lake and Sapphire Rapids on), this path runs instead, and it is the OUTER-PRODUCT form
* this file otherwise argues against -- because here M is large enough to pay for the one thing
* that argument says it costs, a pack of B:
*
* B is packed ONCE A CALL, in parallel, into panels of 48 columns in vdpbf16ps's pair layout,
* Bp[panel][K/2][48][2]: one k-pair of 48 columns is three zmm, read contiguously. Columns past
* N and the second half of an odd K's last pair are zeros.
* The microkernel is 8 rows of A by one panel: per k-pair, three panel loads, eight 32-bit
* broadcasts of A's (k, k+1) pair, 24 vdpbf16ps into 24 accumulators. NO HORIZONTAL REDUCTION
* anywhere -- each accumulator lane is one output element -- and a row is stored as three
* 16-wide vectors.
* Threads take tiles of (64 rows) x (up to four panels), dynamically. Within a tile the panel
* loop is outer, so a panel (K x 96 bytes: 48 KiB at K = 512, 192 KiB at K = 2048) stays in L2
* while the tile's row blocks stream through it.
*
* MEASURED on a 9950X3D, 16 threads, M = 2048: 6.9 TFLOPS at N = 4096, K = 512 and 6.1 at
* N = 512, K = 2048. The dot-product form -- vdpbf16ps along K straight out of both rows, 4 x 6
* blocks -- reached 1.5 at both: at K = 512 a block does sixteen k steps and then 24 sixteen-lane
* reductions, so the reductions were most of its instruction stream. Below 128 rows the per-call
* pack is not paid back, and that form (gemm_bf16_dot) still runs there.
*
* It is one instruction stream inside the AVX-512 object, compiled for the extra feature with a
* function attribute and entered only after __builtin_cpu_supports says the CPU has it: an
* AVX-512 part without BF16 takes the driver above, unchanged.
*
* THE ARITHMETIC: products of bf16 pairs in f32, accumulated per output in k order two at a time,
* with bf16 denormals read as zero (the instruction's DAZ); the bias is the accumulator's start
* and the store rounds to nearest even. A different summation order from the driver's, inside the
* checker's bf16 tolerance like every vectorised reduction here. Each output element is computed
* by one thread, so the result does not depend on the thread count. */
#if AVX_LEVEL == 3
#define AVX_BF16_TARGET __attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16")))
constexpr int64_t BP_COLS = 48; /* columns a panel: three zmm of f32 accumulators */
constexpr int64_t BP_MR = 8; /* rows of A a microkernel */
/* f32 -> bf16 round-to-nearest-even, sixteen lanes, a NaN kept a (quiet) NaN: the scalar
* converter's arithmetic, vectorised. */
AVX_BF16_TARGET static inline __m256i bf16_rne16(__m512 x) {
const __m512i u = _mm512_castps_si512(x);
const __m512i lsb = _mm512_and_si512(_mm512_srli_epi32(u, 16), _mm512_set1_epi32(1));
__m512i r = _mm512_srli_epi32(_mm512_add_epi32(_mm512_add_epi32(u, _mm512_set1_epi32(0x7fff)),
lsb), 16);
const __mmask16 nan = _mm512_cmpgt_epu32_mask(_mm512_and_si512(u, _mm512_set1_epi32(0x7fffffff)),
_mm512_set1_epi32(0x7f800000));
r = _mm512_mask_mov_epi32(r, nan, _mm512_or_si512(_mm512_srli_epi32(u, 16),
_mm512_set1_epi32(0x40)));
return _mm512_cvtepi32_epi16(r);
}
/* MR_ rows of A against one packed panel, over all of K, stored to the panel's `cols` columns of
* Y rows 0..MR_-1 (Y already offset to the block's first element). `bv` starts the accumulators:
* the bias, or zeros. */
template <int MR_>
AVX_BF16_TARGET static inline void op_block(const uint16_t* A, int64_t lda, const uint16_t* panel,
int64_t K, const __m512* bv, void* Y, int64_t ys_r,
bool yb, int64_t cols) {
__m512 acc[MR_][3];
#pragma GCC unroll 8
for (int i = 0; i < MR_; ++i) {
acc[i][0] = bv[0];
acc[i][1] = bv[1];
acc[i][2] = bv[2];
}
const int64_t kp_full = K / 2;
const uint16_t* bp = panel;
for (int64_t kp = 0; kp < kp_full; ++kp, bp += 2 * BP_COLS) {
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp);
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64));
#pragma GCC unroll 8
for (int i = 0; i < MR_; ++i) {
uint32_t pr;
std::memcpy(&pr, A + i * lda + 2 * kp, 4);
const __m512bh av = (__m512bh)_mm512_set1_epi32((int)pr);
acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0);
acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1);
acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2);
}
}
if (K & 1) {
/* The odd last k: A's element alone in the pair's low half, never the one past the row. */
const __m512bh b0 = (__m512bh)_mm512_loadu_si512((const void*)bp);
const __m512bh b1 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 32));
const __m512bh b2 = (__m512bh)_mm512_loadu_si512((const void*)(bp + 64));
#pragma GCC unroll 8
for (int i = 0; i < MR_; ++i) {
const __m512bh av = (__m512bh)_mm512_set1_epi32((int)(uint32_t)A[i * lda + K - 1]);
acc[i][0] = _mm512_dpbf16_ps(acc[i][0], av, b0);
acc[i][1] = _mm512_dpbf16_ps(acc[i][1], av, b1);
acc[i][2] = _mm512_dpbf16_ps(acc[i][2], av, b2);
}
}
/* Every accumulator index is a constant, so the block never leaves the registers. */
auto mask = [&](int64_t c0) {
const int64_t w = cols - c0 <= 0 ? 0 : (cols - c0 < 16 ? cols - c0 : 16);
return (__mmask16)((1u << w) - 1);
};
const __mmask16 m0 = mask(0), m1 = mask(16), m2 = mask(32);
#pragma GCC unroll 8
for (int i = 0; i < MR_; ++i) {
if (yb) {
uint16_t* yr = (uint16_t*)Y + i * ys_r;
_mm256_mask_storeu_epi16(yr, m0, bf16_rne16(acc[i][0]));
_mm256_mask_storeu_epi16(yr + 16, m1, bf16_rne16(acc[i][1]));
_mm256_mask_storeu_epi16(yr + 32, m2, bf16_rne16(acc[i][2]));
} else {
float* yr = (float*)Y + i * ys_r;
_mm512_mask_storeu_ps(yr, m0, acc[i][0]);
_mm512_mask_storeu_ps(yr + 16, m1, acc[i][1]);
_mm512_mask_storeu_ps(yr + 32, m2, acc[i][2]);
}
}
}
/* THE SMALL-M FORM: vdpbf16ps along K straight out of both rows, 4 x 6 blocks, no pack. The pack
* in gemm_bf16_dp touches every weight once a call -- 250 MB a forward pass for EmbeddingGemma
* 2 -- which an encoder step of thousands of rows amortises and a single 16-token query does not:
* there the outer-product path took a query from 13 to 17 ms. The pack pays for itself where the rows it
* serves are many; by the measured rates (1.5 against 6 TFLOPS, the pack streaming at memory
* speed) that is from about 75 rows, and 128 is the switch. */
template <int MB_, int NB_>
AVX_BF16_TARGET static inline void dp_block(const uint16_t* A, int64_t lda, const uint16_t* B,
int64_t ldb, int64_t K, float out[MB_][NB_]) {
__m512 acc[MB_][NB_];
for (int i = 0; i < MB_; ++i)
for (int j = 0; j < NB_; ++j) acc[i][j] = _mm512_setzero_ps();
int64_t k = 0;
for (; k + 32 <= K; k += 32) {
__m512bh av[MB_];
for (int i = 0; i < MB_; ++i)
av[i] = (__m512bh)_mm512_loadu_si512((const void*)(A + i * lda + k));
for (int j = 0; j < NB_; ++j) {
const __m512bh bv = (__m512bh)_mm512_loadu_si512((const void*)(B + j * ldb + k));
for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv);
}
}
if (k < K) {
const __mmask32 mk = (__mmask32)((1ull << (K - k)) - 1);
__m512bh av[MB_];
for (int i = 0; i < MB_; ++i)
av[i] = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(A + i * lda + k));
for (int j = 0; j < NB_; ++j) {
const __m512bh bv = (__m512bh)_mm512_maskz_loadu_epi16(mk, (const void*)(B + j * ldb + k));
for (int i = 0; i < MB_; ++i) acc[i][j] = _mm512_dpbf16_ps(acc[i][j], av[i], bv);
}
}
for (int i = 0; i < MB_; ++i)
for (int j = 0; j < NB_; ++j) out[i][j] = _mm512_reduce_add_ps(acc[i][j]);
}
static inline uint16_t f32_bf16_rne(float f) {
uint32_t u;
std::memcpy(&u, &f, 4);
if ((u & 0x7f800000u) == 0x7f800000u && (u & 0x007fffffu)) return (uint16_t)((u >> 16) | 0x40u);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
AVX_BF16_TARGET static void gemm_bf16_dot(const uint16_t* A, int64_t lda, const uint16_t* B,
int64_t ldb, const RadTensor* Y, int64_t ys_r,
const RadTensor* bias, int64_t M, int64_t N, int64_t K) {
const bool yb = Y->dtype == RAD_BF16;
/* The tile grid: 64 rows of A by a column count chosen so there are at least four tiles a
* thread, capped at 192 columns. */
constexpr int64_t BMR = 4, BNR = 6, MC = 64;
const int64_t mt = (M + MC - 1) / MC;
#ifdef _OPENMP
const int64_t nth = (int64_t)avx_team_size();
#else
const int64_t nth = 1;
#endif
int64_t want_nt = (4 * nth + mt - 1) / mt;
if (want_nt < 1) want_nt = 1;
int64_t NC = (N + want_nt - 1) / want_nt;
NC = ((NC + BNR - 1) / BNR) * BNR;
if (NC > 192) NC = 192;
if (NC < BNR) NC = BNR;
const int64_t ntl = (N + NC - 1) / NC;
auto store = [&](int64_t m, int64_t n, float v) {
if (bias) v += ldt(bias, n * laststride(bias));
if (yb) ((uint16_t*)Y->data)[m * ys_r + n] = f32_bf16_rne(v);
else ((float*)Y->data)[m * ys_r + n] = v;
};
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size())
#endif
for (int64_t t = 0; t < mt * ntl; ++t) {
const int64_t m_lo = (t / ntl) * MC, n_lo = (t % ntl) * NC;
const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M;
const int64_t n_hi = n_lo + NC < N ? n_lo + NC : N;
for (int64_t n0 = n_lo; n0 < n_hi; n0 += BNR) {
const int64_t nn = n_hi - n0 < BNR ? n_hi - n0 : BNR;
for (int64_t m0 = m_lo; m0 < m_hi; m0 += BMR) {
const int64_t mm = m_hi - m0 < BMR ? m_hi - m0 : BMR;
if (mm == BMR && nn == BNR) {
float o[BMR][BNR];
dp_block<BMR, BNR>(A + m0 * lda, lda, B + n0 * ldb, ldb, K, o);
for (int i = 0; i < BMR; ++i)
for (int j = 0; j < BNR; ++j) store(m0 + i, n0 + j, o[i][j]);
} else {
for (int64_t i = 0; i < mm; ++i)
for (int64_t j = 0; j < nn; ++j) {
float o[1][1];
dp_block<1, 1>(A + (m0 + i) * lda, lda, B + (n0 + j) * ldb, ldb, K, o);
store(m0 + i, n0 + j, o[0][0]);
}
}
}
}
}
}
/* A bf16 x bf16 product into Y, or false when this path does not apply and the driver should run. */
AVX_BF16_TARGET static bool gemm_bf16_dp(const Mat& ma, const Mat& mb, const RadTensor* Y,
const RadTensor* bias, int64_t M, int64_t N, int64_t K) {
static const bool have = __builtin_cpu_supports("avx512bf16");
if (!have || M < 16) return false;
if (ma.t->dtype != RAD_BF16 || mb.t->dtype != RAD_BF16 || ma.cs != 1 || mb.cs != 1) return false;
if (Y->dtype != RAD_BF16 && Y->dtype != RAD_F32) return false;
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
if (ys_c != 1) return false;
const uint16_t* A = (const uint16_t*)ma.t->data;
const uint16_t* B = (const uint16_t*)mb.t->data;
const int64_t lda = ma.rs, ldb = mb.rs;
if (M < 128) {
gemm_bf16_dot(A, lda, B, ldb, Y, ys_r, bias, M, N, K);
return true;
}
const bool yb = Y->dtype == RAD_BF16;
const size_t yel = yb ? 2 : 4;
/* ---- the pack, into the calling thread's arena before any worker reads it */
const int64_t np = (N + BP_COLS - 1) / BP_COLS;
const int64_t kp_n = (K + 1) / 2;
const int64_t pstride = kp_n * 2 * BP_COLS; /* uint16 a panel */
uint16_t* Bp = (uint16_t*)scratch_raw((size_t)(np * pstride) * sizeof(uint16_t) + 64);
#ifdef _OPENMP
#pragma omp parallel for schedule(static) num_threads(avx_team_size()) if(np * pstride >= 65536)
#endif
for (int64_t p = 0; p < np; ++p) {
uint32_t* dst = (uint32_t*)(Bp + p * pstride);
const int64_t n0 = p * BP_COLS;
for (int64_t c = 0; c < BP_COLS; ++c) {
const int64_t n = n0 + c;
if (n >= N) {
for (int64_t kp = 0; kp < kp_n; ++kp) dst[kp * BP_COLS + c] = 0;
continue;
}
const uint16_t* row = B + n * ldb;
for (int64_t kp = 0; kp < K / 2; ++kp) {
uint32_t pr;
std::memcpy(&pr, row + 2 * kp, 4);
dst[kp * BP_COLS + c] = pr;
}
if (K & 1) dst[(kp_n - 1) * BP_COLS + c] = (uint32_t)row[K - 1];
}
}
/* ---- the tile grid: 64-row M blocks by groups of panels, at least four tiles a thread */
constexpr int64_t MC = 64;
const int64_t mt = (M + MC - 1) / MC;
#ifdef _OPENMP
const int64_t nth = (int64_t)avx_team_size();
#else
const int64_t nth = 1;
#endif
int64_t groups = (4 * nth + mt - 1) / mt;
if (groups < 1) groups = 1;
int64_t PG = (np + groups - 1) / groups;
if (PG > 4) PG = 4;
if (PG < 1) PG = 1;
const int64_t ng = (np + PG - 1) / PG;
#ifdef _OPENMP
#pragma omp parallel for schedule(dynamic, 1) num_threads(avx_team_size())
#endif
for (int64_t t = 0; t < mt * ng; ++t) {
const int64_t m_lo = (t / ng) * MC, p_lo = (t % ng) * PG;
const int64_t m_hi = m_lo + MC < M ? m_lo + MC : M;
const int64_t p_hi = p_lo + PG < np ? p_lo + PG : np;
for (int64_t p = p_lo; p < p_hi; ++p) {
const int64_t n0 = p * BP_COLS;
const int64_t cols = N - n0 < BP_COLS ? N - n0 : BP_COLS;
__m512 bv[3];
for (int v = 0; v < 3; ++v) {
alignas(64) float bb[16];
for (int e = 0; e < 16; ++e) {
const int64_t n = n0 + 16 * v + e;
bb[e] = (bias && n < N) ? ldt(bias, n * laststride(bias)) : 0.0f;
}
bv[v] = _mm512_load_ps(bb);
}
const uint16_t* panel = Bp + p * pstride;
for (int64_t m0 = m_lo; m0 < m_hi; m0 += BP_MR) {
const int64_t mm = m_hi - m0 < BP_MR ? m_hi - m0 : BP_MR;
const uint16_t* Ar = A + m0 * lda;
void* Yr = (char*)Y->data + (size_t)(m0 * ys_r + n0) * yel;
switch (mm) {
case 8: op_block<8>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 7: op_block<7>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 6: op_block<6>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 5: op_block<5>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 4: op_block<4>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 3: op_block<3>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
case 2: op_block<2>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
default: op_block<1>(Ar, lda, panel, K, bv, Yr, ys_r, yb, cols); break;
}
}
}
}
return true;
}
#endif
/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name which parameters carry
* N and K, because logits_gemm spells them n_vocab and n_embd. */
/* gemm_nt_bias's epilogue (docs/OPS.md): an activation of the stored product, then a residual,
@@ -409,8 +736,13 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c
if (res && numel(res) < M * N) return RAD_E_SHAPE;
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K);
if (st < 0) return st;
#if AVX_LEVEL == 3
if (!gemm_bf16_dp(ma, mb, Y, bias, M, N, K))
#endif
{
const int st = gemm_drive(ma, mb, nullptr, nullptr, Y, bias, M, N, K);
if (st < 0) return st;
}
if (act || res) gemm_epilogue(Y, res, act, M, N);
return RAD_OK;
}
@@ -546,8 +878,10 @@ static int embed_impl(const RadArgs* a) {
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / n_embd;
if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE;
/* An absent scale is one (ref_embed_lookup_q says why the op allows it). */
const float scale = QUANT && sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f;
/* An absent scale is one (ref_embed_lookup_q says why the op allows it). embed_lookup's
* `mult` is the same multiply, a parameter instead of a table scale. */
const float scale = QUANT ? (sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f)
: p_f32(a, "mult", 1.0f);
/* Validated before the loop, because an OpenMP body cannot return. */
if (voff == 0)
@@ -559,7 +893,8 @@ static int embed_impl(const RadArgs* a) {
/* A ROW COPY WHEN NOTHING HAS TO CHANGE, which for the unquantised gather is the usual case:
* the table and the activation are the same dtype and a memcpy moves the row at the width of
* the machine instead of through an f32 round trip that would also re-round it. */
const bool copy = !QUANT && wte->dtype == x->dtype && wc == 1 && laststride(x) == 1;
const bool copy = !QUANT && scale == 1.0f && wte->dtype == x->dtype && wc == 1 &&
laststride(x) == 1;
const size_t rowb = copy ? (size_t)((rad_dtype_bits(x->dtype) * n_embd) / 8) : 0;
AVX_PARALLEL_FOR_IF(M * n_embd >= AVX_PAR_MIN)
@@ -578,7 +913,7 @@ static int embed_impl(const RadArgs* a) {
for (int64_t i = 0; i < n_embd; ++i) s[i] = 0.0f;
} else if (wc == 1) {
row_to_f32(wte->dtype, byte_at(wte->data, wte->dtype, id * ws), s, n_embd);
if (QUANT) {
if (scale != 1.0f) {
const vf vs = vf_set1(scale);
int64_t i = 0;
for (; i + VF_N <= n_embd; i += VF_N) vf_storeu(s + i, vf_mul(vf_loadu(s + i), vs));
+4 -2
View File
@@ -90,7 +90,9 @@ int avx_isa_force(int level);
X(mul) X(silu_mul) X(gelu) X(silu) \
X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \
X(ple_gate) X(ple_conv) X(cast) X(softmax) \
X(scale_rows) X(fill) \
X(scale_rows) X(fill) X(act_mul) X(seg_mean) \
X(mul_weight) X(pool_rows) X(relu) X(clamp) \
X(conv2d) X(conv1d_dw) X(rel_sinusoid) \
/* ---- quantisation and rotation */ \
X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \
X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \
@@ -100,7 +102,7 @@ int avx_isa_force(int level);
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) X(attn_local_rel) \
/* ---- 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) \
+13 -5
View File
@@ -61,17 +61,25 @@ static void widen_gain(const RadTensor* w, int64_t n, float wadd, float* out) {
/* ------------------------------------------------------------------ rmsnorm */
/* y = x * rsqrt(mean(x^2) + eps) * (w + wadd) */
AVX_KERNEL(rmsnorm) {
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[2];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[2];
/* An absent gain is one (libref's reading), and `wadd` belongs to a gain. */
const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr;
const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
if (!w && wadd != 0.0f) return RAD_E_INVAL;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE;
if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE;
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
widen_gain(w, n, wadd, gain);
if (w) widen_gain(w, n, wadd, gain);
else for (int64_t i = 0; i < n; ++i) gain[i] = 1.0f;
/* `mult` folded into the gain: the row is scaled before its one rounding. */
const float mult = p_f32(a, "mult", 1.0f);
if (mult != 1.0f)
for (int64_t i = 0; i < n; ++i) gain[i] *= mult;
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
for (int64_t r = 0; r < rows; ++r) {
+77 -6
View File
@@ -75,9 +75,13 @@
#define ARR(a) (a), (int)(sizeof(a) / sizeof((a)[0]))
/* ---- elementwise and norms ---------------------------------------------------------------- */
/* rmsnorm_add has no `mult`: it is the fused pair, and nothing fuses a scaled branch. */
static const RadParamSpec pRmsnormAdd[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd") };
static const RadParamSpec pRmsnorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"),
P_F64O("wadd") };
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT("w"), OUT("y") };
P_F64O("wadd"), P_F64O("mult") };
/* `w` optional: absent, the gain is one. */
static const RadOperandSpec oRmsnorm[] = { OPD("x"), WGT_O("w"), OUT("y") };
static const RadParamSpec pHcRead[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_INT("lowrank"),
P_F64("eps"), P_STR("dtype"), P_F64O("wadd"),
@@ -126,9 +130,35 @@ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side
static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") };
static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") };
static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") };
static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"),
P_STR("dtype") };
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
static const RadOperandSpec oUnary[] = { OPD("x"), OUT("y") };
/* The audio (USM conformer) tower's operators; libref's lists, field for field. */
static const RadOperandSpec oClamp[] = { OPD("x"), WGT("lo"), WGT("hi"), OUT("y") };
static const RadParamSpec pConv2d[] = { P_INT("M"), P_INT("width"), P_INT("cin"), P_INT("cout"),
P_INT("kh"), P_INT("kw"), P_INT("stride"), P_INT("pad"),
P_INTO("cu_div"), P_INTO("valid_stride"),
P_STR("dtype") };
static const RadOperandSpec oConv2d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("valid"),
OUT("y") };
static const RadParamSpec pConv1dDw[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"),
P_STR("dtype") };
static const RadOperandSpec oConv1dDw[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pRelSin[] = { P_INT("M"), P_INT("n"), P_F64O("max_timescale"),
P_STR("dtype") };
static const RadOperandSpec oRelSin[] = { OUT("y") };
static const RadParamSpec pAttnLocalRel[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("left"), P_INT("right"), P_F64("softcap"),
P_INTO("cu_div"), P_STR("dtype") };
static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OPD("relk"),
WGT("pds"), OPD("cu_seqlens"), OUT("out") };
/* `fill` has no input: `value` is the whole of what it writes. */
static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") };
static const RadOperandSpec oFill[] = { OUT("y") };
@@ -206,7 +236,7 @@ static const RadConstraint cPagedBlock[] = { RAD_CGE("block_size", 1) };
static const RadParamSpec pAttnDense[] = { P_INT("M"), P_INT("head_dim"), P_INT("gqa"),
P_INT("causal"), P_STR("dtype"), P_F64O("scale"),
P_INTO("max_seqlen") };
P_INTO("max_seqlen"), P_INTO("window") };
static const RadOperandSpec oAttnDense[] = { OPD("q"), OPD("k"), OPD("v"), OPD("cu_seqlens"),
OUT("out") };
@@ -244,7 +274,9 @@ static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page")
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
P_F64O("scale"), P_STRO("mode"),
P_INTO("rotary_dim"), P_F64O("wadd") };
P_INTO("rotary_dim"), P_F64O("wadd"),
P_INTO("v_norm"), P_STRO("sections"),
P_STRO("comps") };
static const RadOperandSpec oQkNormRope[] = { INOUT("qkv"), OPD("positions"), WGT("q_w"),
WGT("k_w") };
@@ -391,6 +423,9 @@ static const RadOperandSpec oAllGather[] = { OPD("x"), OUT("y") };
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
P_STR("dtype"), P_INTO("vocab_offset"),
P_F64O("wscale") };
static const RadParamSpec pEmbedM[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
P_STR("dtype"), P_INTO("vocab_offset"),
P_F64O("wscale"), P_F64O("mult") };
static const RadOperandSpec oEmbed[] = { OPD("tokens"), WGT("wte"), OUT("x") };
static const RadOperandSpec oEmbedQ[] = { OPD("tokens"), WGT("wte"), WGT_O("scale"), OUT("x"),
OPD_O("ahead") };
@@ -438,7 +473,7 @@ static const RadOpSchema kSchemas[] = {
{ "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm),
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector "
"reduction, so it does not sum in libref's order and does not claim to." },
{ "rmsnorm_add", ARR(pRmsnorm), ARR(oRmsnormAdd),
{ "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd),
"residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the "
"unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's "
"rule and both are observable, so both are reproduced exactly." },
@@ -460,6 +495,23 @@ static const RadOpSchema kSchemas[] = {
{ "add", ARR(pMnD), ARR(oBinary), "elementwise sum." },
{ "mul", ARR(pMnD), ARR(oBinary),
"elementwise product; `b` may have extent 1 on any axis `a` does not and is broadcast along it." },
{ "mul_weight", ARR(pMulWeight), ARR(oMulWeight),
"y = x * w, `w` a weight of one element or one row, broadcast; f32 product rounded once." },
{ "act_mul", ARR(pActMul), ARR(oBinary),
"y = act(a) * b, act silu / gelu / gelu_tanh, the activation rounded to y's dtype first." },
{ "seg_mean", ARR(pSegMean), ARR(oSegMean),
"y[s] = the mean of x's rows in cu_seqlens segment s, summed in double, rounded once." },
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0)." },
{ "clamp", ARR(pMnD), ARR(oClamp), "y = min(max(x, lo), hi), lo and hi one-element weights." },
{ "conv2d", ARR(pConv2d), ARR(oConv2d),
"segment-wise 2-D convolution over (time, width), channels innermost, optional row mask." },
{ "conv1d_dw", ARR(pConv1dDw), ARR(oConv1dDw),
"segment-wise causal depthwise convolution over time." },
{ "rel_sinusoid", ARR(pRelSin), ARR(oRelSin), "the sinusoidal relative-position table." },
{ "attn_local_rel", ARR(pAttnLocalRel), ARR(oAttnLocalRel),
"local attention with a relative-position term and a softcap (Gemma 4's audio)." },
{ "pool_rows", ARR(pPoolRows), ARR(oUnary),
"y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." },
{ "silu_mul", ARR(pMnD), ARR(oGateUp),
"silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." },
{ "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." },
@@ -562,7 +614,8 @@ static const RadOpSchema kSchemas[] = {
{ "all_reduce", ARR(pAllReduce), ARR(oAllReduce),
"sum across ranks, f32, ascending rank order." },
{ "all_gather", ARR(pAllGather), ARR(oAllGather), "gather every rank's shard." },
{ "embed_lookup", ARR(pEmbed), ARR(oEmbed), "embedding gather, vocab-parallel with an offset." },
{ "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),
"embedding gather, one scale for the table; without a scale the table is read as it is." },
{ "logits_gemm", ARR(pLogits), ARR(oLogits), "the lm_head projection." },
@@ -640,6 +693,24 @@ SIMPLE("avx_grid_embed", "grid_embed", "elem",
"bilinear resample of a learned position grid, added in", DT_FLOAT, L(grid_embed)),
SIMPLE("avx_add", "add", "elem", "elementwise sum", DT_FLOAT, L(add)),
SIMPLE("avx_mul", "mul", "elem", "elementwise product, broadcasting b", DT_FLOAT, L(mul)),
SIMPLE("avx_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, L(act_mul)),
SIMPLE("avx_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT,
L(mul_weight)),
SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT,
L(seg_mean)),
SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, L(pool_rows)),
SIMPLE("avx_relu", "relu", "elem", "max(x, 0)", DT_FLOAT, L(relu)),
SIMPLE("avx_clamp", "clamp", "elem", "x clamped to two weight scalars", DT_FLOAT, L(clamp)),
SIMPLE("avx_conv2d", "conv2d", "elem", "segment-wise 2-D convolution, channels innermost",
DT_FLOAT, L(conv2d)),
SIMPLE("avx_conv1d_dw", "conv1d_dw", "elem", "segment-wise causal depthwise convolution",
DT_FLOAT, L(conv1d_dw)),
SIMPLE("avx_rel_sinusoid", "rel_sinusoid", "elem", "sinusoidal relative-position table",
DT_FLOAT, L(rel_sinusoid)),
SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn",
"local attention with a relative-position term and a softcap", DT_FLOAT,
L(attn_local_rel)),
SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT,
L(silu_mul)),
SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)),