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

+4
View File
@@ -67,6 +67,10 @@ set(R4D_UNITS
# head is replicated across a rank pair. Again four lines that set the ratio and include the body.
"r4d_attn_paged_h256_gqa6_bs4|"
"r4d_attn_vit_h72_bf16|"
# An encoder's dense attention (bidirectional, GQA in the workgroup, a two-sided window) and
# the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening.
"r4d_attn_dense_bf16|"
"r4d_encoder_bf16|"
# The vision tower's own small ops: layer norm, the learned-grid position embedding, and the
# biased GEMM with a linear layer's activation and residual in its store.
"r4d_vit_bf16|"
+384
View File
@@ -0,0 +1,384 @@
// R4D dense attention for an encoder: non-causal, varlen over cu_seqlens segments, grouped-query,
// with an optional two-sided window |i - j| < window. bf16 in and out, f16 operands, f32
// accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
//
// The core is the vision kernel's (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
// column-distributed accumulator gives each lane one query row, the softmax state is lane-private,
// and the C fragment of S^T is already the B fragment the PV matmul wants -- P never goes through
// LDS. What this file adds:
//
// GQA IN THE WORKGROUP. A workgroup owns one KV head and every query head that reads it, so a
// staged K/V tile is consumed by GQA times as many WMMAs as one head would give it. The grid is
// (query blocks, kv heads, segments).
//
// A WINDOW. A workgroup's key range is cut to the keys any of its queries can see, and the
// per-element test runs only on tiles that straddle a window edge or the segment's end; an
// interior tile pays nothing. Sliding layers at |i - j| <= 512 then cost O(T * window), not
// O(T^2).
//
// A HEAD SPLIT ACROSS WAVES (DSPLIT). One lane's output is head_dim / 2 floats, so head_dim 512
// would need 256 accumulator VGPRs before the query fragments -- more than a lane has. At
// DSPLIT 2 two waves own the same 16 queries and half the head each: each contracts its half
// of q.k, the two partial scores are summed through LDS, both run the same softmax (a + b ==
// b + a, so the two copies agree to the bit), and each accumulates its half of P.V.
//
// Every operand is read at its own token pitch, so q, k and v may be column slices of one fused
// projection; pitches and head offsets must be multiples of 8 elements for the 16-byte fetches.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_dt16.h"
#include <cmath>
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
__global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, float scale, int window,
int q_ld, int k_ld, int v_ld, int o_ld)
{
typedef DT16<1> D;
typedef D::frag frag16;
constexpr int NWARPS = NQB * GQA * DSPLIT;
constexpr int NTHR = NWARPS * 32;
constexpr int BQ = NQB * 16; // query rows per head per workgroup
constexpr int HDP = HD / DSPLIT; // the head dims one wave owns
constexpr int NKS = HDP / 16; // its 16-wide k-tiles
constexpr int MT = TILE / 16;
// Row strides padded by 8 shorts: 16-byte aligned, and off the bank period.
constexpr int KSTR = HD + 8;
constexpr int VSTR = TILE + 8;
constexpr int DG = HD / 8; // eight-element dim groups in a row
constexpr int KGRP = TILE / 8; // eight-key groups in a tile
constexpr int KITEMS = TILE * DG; // 16-byte K fetches a tile
constexpr int KP = (KITEMS + NTHR - 1) / NTHR;
constexpr int NTR = KGRP * DG; // transposed V units, eight lanes each
constexpr int LGRP = NTHR / 8;
constexpr int VP = (NTR + LGRP - 1) / LGRP;
constexpr float GROW = D::GROW;
static_assert(HD % (16 * DSPLIT) == 0 && TILE % 16 == 0, "geometry");
static_assert(DSPLIT == 1 || DSPLIT == 2, "a head is split across at most two waves");
__shared__ __align__(16) uint16_t sK[TILE * KSTR];
__shared__ __align__(16) uint16_t sV[HD * VSTR];
__shared__ __align__(16) float sX[DSPLIT > 1 ? NWARPS * 32 * 8 : 4];
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int c = lane & 15, h = lane >> 4;
const int dp = warp % DSPLIT;
const int g = (warp / DSPLIT) % GQA;
const int qbi = warp / (DSPLIT * GQA);
const int kvh = blockIdx.y, seq = blockIdx.z;
const int hq = kvh * GQA + g;
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
const int q0 = blockIdx.x * BQ;
if (slen <= 0 || q0 >= slen) return;
const int qlast = min(q0 + BQ, slen) - 1;
// The keys any query of this workgroup can see.
int kb = 0, ke = slen;
if (window > 0) {
kb = max(0, q0 - (window - 1));
ke = min(slen, qlast + window);
}
const float mul = scale * 1.44269504089f;
const int qpos = q0 + qbi * 16 + c;
const bool live = qpos < slen;
// ---- this wave's half (or whole) of its 16 query rows, scaled once -------------------------
frag16 qf[NKS];
{
const int qrow = live ? qpos : slen - 1;
const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hq * HD + dp * HDP;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h);
auto cv = [&](uint32_t w) {
return D::pk(__builtin_bit_cast(float, w << 16) * mul,
__builtin_bit_cast(float, w & 0xffff0000u) * mul);
};
qf[t] = D::mk(make_uint2(cv(u.x), cv(u.y)), make_uint2(cv(u.z), cv(u.w)));
}
}
float m_ref = -3.0e38f, soff = 3.0e38f, l_i = 0.0f;
v8f acc[NKS];
#pragma unroll
for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
const int vj = tid & 7, lgi = tid >> 3;
const uint16_t* kbase = gk + (long)kvh * HD;
const uint16_t* vbase = gv + (long)kvh * HD;
const int ntiles = (ke - kb + TILE - 1) / TILE;
for (int ti = 0; ti < ntiles; ++ti) {
const int k0 = kb + ti * TILE;
// Whether any (query, key) pair of this tile is outside the window or past the keys:
// uniform over the workgroup, so the interior tiles skip the test entirely.
const bool mask = (k0 + TILE > ke) ||
(window > 0 && (k0 < qlast - (window - 1) ||
k0 + TILE - 1 > q0 + (window - 1)));
uint4 kr[KP], vr[VP];
#pragma unroll
for (int p = 0; p < KP; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
const int key = i / DG, gg = i % DG;
const int kk = (k0 + key < ke) ? k0 + key : ke - 1;
kr[p] = *(const uint4*)(kbase + (long)(s0 + kk) * k_ld + gg * 8);
}
}
// V transposed on the way in: the eight lanes of a group name eight key rows at the same
// eight dims, and global_load_tr_b128 hands lane j dim d0+j across all eight.
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
const int kk0 = k0 + kg * 8 + vj;
const int kk = (kk0 < ke) ? kk0 : ke - 1;
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vbase + (long)(s0 + kk) * v_ld +
dg * 8));
}
}
lds_barrier(); // the previous tile's readers are done
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
const uint4 w = vr[r];
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] =
make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y),
D::from_bf16w(w.z), D::from_bf16w(w.w));
}
}
#pragma unroll
for (int p = 0; p < KP; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
const uint4 w = kr[p];
*(uint4*)&sK[(i / DG) * KSTR + (i % DG) * 8] =
make_uint4(D::from_bf16w(w.x), D::from_bf16w(w.y),
D::from_bf16w(w.z), D::from_bf16w(w.w));
}
}
lds_barrier();
#pragma unroll 1
for (int mt = 0; mt < MT; ++mt) {
v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
{
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR + dp * HDP] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
frag16 kf[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) {
const uint4 u = *(const uint4*)(krow + 16 * (t0 + j));
kf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) s = D::wmma(kf[j], qf[t0 + j], s);
}
}
if (DSPLIT > 1) {
// The other half of q.k, from the wave that owns it.
float* mine = &sX[(warp * 32 + lane) * 8];
const float* theirs = &sX[((warp ^ 1) * 32 + lane) * 8];
*(float4*)mine = make_float4(s[0], s[1], s[2], s[3]);
*(float4*)(mine + 4) = make_float4(s[4], s[5], s[6], s[7]);
lds_barrier();
const float4 a = *(const float4*)theirs, b = *(const float4*)(theirs + 4);
s[0] += a.x; s[1] += a.y; s[2] += a.z; s[3] += a.w;
s[4] += b.x; s[5] += b.y; s[6] += b.z; s[7] += b.w;
lds_barrier();
}
float sc[8];
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = s[e];
if (mask) {
const int kq = k0 + mt * 16 + 8 * h;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int key = kq + e;
const int d = qpos - key;
const bool ok = key < ke && (window <= 0 || (d < window && -d < window));
sc[e] = ok ? sc[e] : -INFINITY;
}
}
// The softmax against a reference max, rescaled only when the row max outgrows what
// the f16 P can hold (r4d_dt16.h).
float smax = sc[0];
#pragma unroll
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
if (wave_any(smax > m_ref + GROW)) {
const float rmax = fmaxf(smax, swap16(smax));
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
const float alpha = ex2(m_ref - mnew);
#pragma unroll
for (int t = 0; t < NKS; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[t][e] *= alpha;
l_i *= alpha;
m_ref = mnew;
soff = -mnew;
}
uint32_t pw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2)
pw[e >> 1] = D::pk(ex2(sc[e] + soff), ex2(sc[e + 1] + soff));
// The row sum off the packed P, so the denominator is the values P.V used.
const v2hf one = {(__fp16)1.0f, (__fp16)1.0f};
#pragma unroll
for (int e = 0; e < 4; ++e)
l_i = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf, pw[e]), one, l_i, false);
const frag16 p16 = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3]));
{
const uint16_t* vrow = &sV[(dp * HDP + c) * VSTR + mt * 16] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
frag16 vf[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) {
const uint4 u = *(const uint4*)(vrow + (t0 + j) * 16 * VSTR);
vf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) acc[t0 + j] = D::wmma(vf[j], p16, acc[t0 + j]);
}
}
}
}
if (!live) return;
const float ls = l_i + swap16(l_i);
const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f;
uint16_t* op = go + (long)(s0 + qpos) * o_ld + (long)hq * HD + dp * HDP;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
uint32_t tw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2)
tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv)
| ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16);
*(uint4*)(op + t * 16 + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]);
}
}
// ---- launch ----------------------------------------------------------------------------------
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
float scale, int window, int q_ld, int k_ld, int v_ld, int o_ld,
hipStream_t s)
{
constexpr int BQ = NQB * 16;
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs);
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, q_ld,
k_ld, v_ld, o_ld);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
// q, o: [tokens, n_head * head_dim]; k, v: [tokens, n_head_kv * head_dim], each at its own token
// pitch in elements. cu_seqlens is [num_seqs + 1] int32 on the device; max_seqlen is a host-side
// bound on the segment lengths and sizes the grid. window 0 is the whole segment.
extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, void* o,
const void* cu_seqlens, int num_seqs, int max_seqlen,
int n_head, int n_head_kv, int head_dim, float scale,
int window, int q_ld, int k_ld, int v_ld, int o_ld,
void* stream)
{
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
if (window < 0) return -4;
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
const int gqa = n_head / n_head_kv;
hipStream_t s = (hipStream_t)stream;
if (head_dim == 64 && gqa == 1)
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
n_head_kv, scale, window, q_ld, k_ld, v_ld,
o_ld, s);
if (head_dim == 256 && gqa == 2)
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window, q_ld,
k_ld, v_ld, o_ld, s);
if (head_dim == 512 && gqa == 4)
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
max_seqlen, n_head_kv, scale, window, q_ld,
k_ld, v_ld, o_ld, s);
return -1;
}
// ============================================================== the plugin ABI entry point
enum { DN_Q = 0, DN_K, DN_V, DN_CU, DN_OUT };
extern "C" int r4d_rad_attn_dense(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, DN_Q);
const RadTensor* k = r4d_opt(a, DN_K);
const RadTensor* v = r4d_opt(a, DN_V);
const RadTensor* cu = r4d_opt(a, DN_CU);
const RadTensor* o = r4d_opt(a, DN_OUT);
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
if (r4d_geti_or(a, "causal", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED);
const long long head_dim = r4d_geti_or(a, "head_dim", 0);
const long long gqa = r4d_geti_or(a, "gqa", 1);
if (head_dim <= 0 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
/* [tokens, heads * head_dim] (or [tokens, heads, head_dim]) at the operand's own row pitch. */
auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) {
long long width = 1;
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
if (t->rank < 2 || width % head_dim) return false;
*n_head = width / head_dim;
*ld = r4d_rows_pitch(t, width, n_tok);
return *ld >= 0;
};
long long total = 0, nh = 0, q_ld = 0;
long long tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0, to = 0, ho = 0, o_ld = 0;
if (!rows(q, &total, &nh, &q_ld) || !rows(k, &tk, &hk, &k_ld) ||
!rows(v, &tv, &hv, &v_ld) || !rows(o, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE);
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
if (cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
const int num_seqs = (int)(cu->shape[0] - 1);
/* max_seqlen sizes the grid and is a bound, not a length: the kernel reads the device-side
* cu_seqlens. Absent, the total token count is a valid bound. */
long long msl = r4d_geti_or(a, "max_seqlen", 0);
if (msl <= 0 || msl > total) msl = total;
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)head_dim));
const long long window = r4d_geti_or(a, "window", 0);
const int e = r4d_attn_dense_bf16(q->data, k->data, v->data, o->data, cu->data, num_seqs,
(int)msl, (int)nh, (int)hk, (int)head_dim, scale,
(int)window, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld, s);
if (e == -1) return R4D_NO(RAD_E_SHAPE);
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
+2
View File
@@ -531,6 +531,8 @@ extern "C" int r4d_rad_attn_vit(const RadArgs* a, RadStream s) {
* kernel steps by. */
const long long head_dim = r4d_geti_or(a, "head_dim", q->rank == 3 ? q->shape[2] : 72);
if (head_dim != 72) return R4D_NO(RAD_E_SHAPE);
/* Every key of a segment is attended to; a window would be ignored, so it is refused. */
if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_INVAL);
auto rows = [&](const RadTensor* t, long long* n_tok, long long* n_head, long long* ld) {
long long width = 1;
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
File diff suppressed because it is too large. Load diff
+6 -9
View File
@@ -415,15 +415,12 @@ extern "C" int r4d_fuse_gated_quant_fp8(const RadParam* p, int n_p, uint64_t pre
* half-of-an-operand problem. Three launches an attention layer becoming one is what the fusion
* bought; the three are named here.
*
* `act` silu IS DECLINED, and not because the arithmetic differs -- `silu` is an op of the
* vocabulary and `f2bf(gv / (1.0f + expf(-gv)))` is what a silu step would have to compute. It is
* declined because THIS PLUGIN HAS NO `silu` ROW: libr4d declares `sigmoid` (sigmoid_bf16) and
* `silu_mul` (silu_mul_bf16) and no bare `silu`, so the only implementation a caller could reach
* is libref's, whose `act_silu(x)` is `x * act_sigmoid(x)` -- two f32 roundings where this
* kernel does one divide. A chain that resolved there would report a difference in the last bit of
* every element and call it a fault in the kernel, and a false failure is worse than a skip. A
* libr4d `silu` row spelled `x / (1 + expf(-x))` would close the gap; without one the decline
* stands. Nothing in the tree issues this row with silu -- the gated attention's gate is a
* `act` silu IS DECLINED because the arithmetic differs in the last bit. The chain's `silu` step
* resolves to silu_bf16 or libref, and both compute libref's `act_silu(x)`, `x * act_sigmoid(x)`
* -- two f32 roundings where this kernel does one divide, `f2bf(gv / (1.0f + expf(-gv)))`. A
* chain checked against it would report a difference in the last bit of many elements and call it
* a fault in the kernel, and a false failure is worse than a skip. Accepting silu needs this
* kernel to take the sigmoid first as well. Nothing in the tree issues this row with silu -- the gated attention's gate is a
* sigmoid, which is why the shim's `mode` defaults to 1.
*
* TMP(0) is act(gate): an [M, n] bf16 plane the fusion genuinely never writes, so it is a
+80 -19
View File
@@ -100,9 +100,11 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
// vocab-parallel: ids stay global, a rank subtracts the offset, and a token belonging to another
// rank takes the same zero-row path the padding id takes. Summing the ranks then reconstructs x.
// At vocab_off = 0 this is the plain gather, to the bit.
// `mult` multiplies every gathered entry, the product rounded once (Gemma's sqrt(hidden)); 1 is the
// plain copy, to the bit.
__global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
const int32_t* __restrict__ tok, const uint16_t* __restrict__ wte, uint16_t* __restrict__ x,
uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld) {
uint32_t n_embd, int32_t n_vocab, int32_t vocab_off, uint32_t x_ld, float mult) {
const uint32_t m = blockIdx.x;
const int32_t id = tok[m] - vocab_off;
uint16_t* __restrict__ dst = x + (size_t)m * x_ld;
@@ -111,7 +113,11 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_kernel(
return;
}
const uint16_t* __restrict__ src = wte + (size_t)id * n_embd;
for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i];
if (mult == 1.0f) {
for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = src[i];
return;
}
for (uint32_t i = threadIdx.x; i < n_embd; i += kThreads) dst[i] = f32_to_bf16(bf2f(src[i]) * mult);
}
// ---------------------------------------------------------------------------- embed_lookup_q
@@ -251,7 +257,7 @@ __global__ __launch_bounds__(kThreads) void scatter_rows_u8_kernel(
template <bool WF32, uint32_t THR>
__global__ __launch_bounds__(THR) void rmsnorm_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y,
uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t y_ld) {
uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld) {
__shared__ float lds[THR / kWave];
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
@@ -262,8 +268,8 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const float g = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(bf2f(xr[i]) * s * (g + wadd));
const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
yr[i] = f32_to_bf16(bf2f(xr[i]) * s * (g + wadd) * mult);
}
}
@@ -272,15 +278,16 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
// against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is
// what makes a bias add this op instead of a second one, and the narrowness is the point -- silent
// broadcasting of an arbitrary shape is how a shape bug becomes a plausible number.
// `b_step` 0 reads one element for the whole row -- with b_ld 0 too, a scalar for the whole op.
__global__ __launch_bounds__(kThreads) void binary_kernel(
const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, uint16_t* __restrict__ y,
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul) {
uint32_t n, uint32_t a_ld, uint32_t b_ld, uint32_t y_ld, int mul, uint32_t b_step) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ ar = a + (size_t)m * a_ld;
const uint16_t* __restrict__ br = b + (size_t)m * b_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float u = bf2f(ar[i]), v = bf2f(br[i]);
const float u = bf2f(ar[i]), v = bf2f(br[i * b_step]);
yr[i] = f32_to_bf16(mul ? u * v : u + v);
}
}
@@ -579,20 +586,20 @@ __global__ __launch_bounds__(kThreads) void kv_store_fp8_kernel(
* the launch has to be describable, and writing the geometry twice is the one thing ABI v10's
* contract says not to do. One body, two ways in. */
static int embed_lookup_bf16_emit(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, const R4dSink& sk) {
int vocab_off, int x_ld, float mult, const R4dSink& sk) {
if (!tok || !wte || !x) return -1;
if (M <= 0 || n_embd <= 0 || n_vocab <= 0 || vocab_off < 0) return -2;
if (!x_ld) x_ld = n_embd;
return R4D_EMIT(sk, embed_lookup_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(const int32_t*)tok, (const uint16_t*)wte,
(uint16_t*)x, (uint32_t)n_embd, (int32_t)n_vocab, (int32_t)vocab_off,
(uint32_t)x_ld) == RAD_OK ? 0 : -4;
(uint32_t)x_ld, mult) == RAD_OK ? 0 : -4;
}
extern "C" int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, long stream) {
R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream;
return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, sk);
return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, 1.0f, sk);
}
/* The quad walk when the width, the pitch and both bases allow its 4- and 8-byte accesses (a bf16
@@ -674,10 +681,11 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d
return scatter_rows_u8_emit(v, idx, x, M, n, dst_rows, v_ld, x_ld, sk);
}
// `w_f32` says whether the gain is f32 (every norm gain the architecture plugins declare) or bf16.
extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
int w_f32, int x_ld, int y_ld, long stream) {
if (!x || !w || !y) return -1;
// `w_f32` says whether the gain is f32 (every norm gain the architecture plugins declare) or bf16;
// a null `w` is a gain of one. `mult` scales the row before its one rounding (rmsnorm's `mult`).
extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
float mult, int w_f32, int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
@@ -691,7 +699,7 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
#define R4D_RN_T(wf, T) \
hipLaunchKernelGGL((rmsnorm_kernel<wf, T>), dim3((uint32_t)M), dim3(T), 0, \
(hipStream_t)stream, (const uint16_t*)x, (const void*)w, (uint16_t*)y, \
(uint32_t)n, eps, wadd, (uint32_t)x_ld, (uint32_t)y_ld)
(uint32_t)n, eps, wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld)
#define R4D_RN(wf) \
do { if (thr == 1024) R4D_RN_T(wf, 1024); \
else if (thr == 512) R4D_RN_T(wf, 512); \
@@ -703,17 +711,26 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
/* The unscaled form, the entry point every caller before `mult` used: times one is exact. */
extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd,
int w_f32, int x_ld, int y_ld, long stream) {
return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream);
}
// `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the
// caller passes a b_ld of zero and every row reads the same n elements.
// b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows.
extern "C" int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
int a_ld, int b_ld, int y_ld, long stream) {
if (!a || !b || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!a_ld) a_ld = n;
if (!y_ld) y_ld = n;
const uint32_t b_step = b_ld < 0 ? 0u : 1u;
if (b_ld < 0) b_ld = 0;
hipLaunchKernelGGL(binary_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)a, (const uint16_t*)b, (uint16_t*)y, (uint32_t)n,
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op);
(uint32_t)a_ld, (uint32_t)b_ld, (uint32_t)y_ld, op, b_step);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1002,9 +1019,10 @@ static int rad_embed_lookup_body(const RadArgs* a, const R4dSink& sk) {
if (x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
const float mult = (float)r4d_getf(a, "mult", 1.0);
return embed_lookup_bf16_emit(r4d_addr(tok), r4d_addr(wte), r4d_addr(x),
(int)M, (int)n_embd, (int)n_vocab, (int)voff, (int)x_ld,
sk) == 0 ? RAD_OK : RAD_E_DEVICE;
mult, sk) == 0 ? RAD_OK : RAD_E_DEVICE;
}
R4D_ENTRY(r4d_rad_embed_lookup, rad_embed_lookup_body)
@@ -1201,9 +1219,25 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, RN_X);
const RadTensor* w = r4d_opt(a, RN_W);
const RadTensor* y = r4d_opt(a, RN_Y);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
/* An ABSENT gain is one: a norm with no scale (Gemma 4's value norm, its multimodal
* embedder's pre-projection norm). `wadd` belongs to a gain and is refused without one. */
if (!w) {
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
if (r4d_getf(a, "wadd", 0.0) != 0.0) return R4D_NO(RAD_E_INVAL);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n, &M);
const long long y_ld = r4d_rows_pitch(y, n, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
return r4d_rmsnorm_mult_bf16(r4d_addr(x), 0, r4d_addr(y), (int)M, (int)n,
(float)r4d_getf(a, "eps", 1e-6), 0.0f,
(float)r4d_getf(a, "mult", 1.0), 0, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
/* THE GAIN IS THE ONE OPERAND THAT IS NOT bf16. Every architecture plugin here declares its
* norm gains RAD_F32 -- a few thousand elements against gigabytes of weights, and the norm is
@@ -1223,7 +1257,8 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
return r4d_rmsnorm_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
return r4d_rmsnorm_mult_bf16(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd,
(float)r4d_getf(a, "mult", 1.0),
w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
@@ -1272,6 +1307,32 @@ static int binary(const RadArgs* a, int mul, RadStream s) {
extern "C" int r4d_rad_add(const RadArgs* a, RadStream s) { return binary(a, 0, s); }
extern "C" int r4d_rad_mul(const RadArgs* a, RadStream s) { return binary(a, 1, s); }
/* mul_weight: y = x * w, `w` a bf16 weight of one element (pitch -1, a scalar) or one row (pitch
* 0, broadcast down the rows) -- the binary kernel's two broadcast forms. */
extern "C" int r4d_rad_mul_weight(const RadArgs* a, RadStream s) {
const RadTensor* X = r4d_opt(a, 0);
const RadTensor* W = r4d_opt(a, 1);
const RadTensor* Y = r4d_opt(a, 2);
if (!X || !W || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(X));
R4D_NEED(dt_bf16(W));
R4D_NEED(dt_bf16(Y));
const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0, Mx = 0;
const long long y_ld = r4d_rows_pitch(Y, n, &M);
const long long x_ld = r4d_rows_pitch(X, n, &Mx);
if (y_ld < 0 || x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
long long w_ld;
if (r4d_numel(W) == 1) w_ld = -1;
else if (r4d_numel(W) == n && r4d_contig(W)) w_ld = 0;
else return R4D_NO(RAD_E_SHAPE);
return r4d_binary_bf16(r4d_addr(X), r4d_addr(W), r4d_addr(Y), (int)M, (int)n, 1,
(int)x_ld, (int)w_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ sigmoid */
extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) {
+15
View File
@@ -90,6 +90,7 @@ int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream);
int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*);
int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256
* and MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify
* width is 8 here against the gqa6 leg's 10 -- which is the row's constraint value. */
@@ -409,6 +410,19 @@ int r4d_rad_gather_rows_describe(const RadArgs*, RadStream, RadLaunchDesc*, int,
int r4d_rad_rmsnorm (const RadArgs*, RadStream);
int r4d_rad_add (const RadArgs*, RadStream);
int r4d_rad_mul (const RadArgs*, RadStream);
int r4d_rad_mul_weight (const RadArgs*, RadStream);
int r4d_rad_act_mul (const RadArgs*, RadStream);
int r4d_rad_seg_mean (const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope (const RadArgs*, RadStream);
int r4d_rad_cast_widen (const RadArgs*, RadStream);
int r4d_rad_pool_rows (const RadArgs*, RadStream);
int r4d_rad_relu (const RadArgs*, RadStream);
int r4d_rad_silu (const RadArgs*, RadStream);
int r4d_rad_clamp (const RadArgs*, RadStream);
int r4d_rad_conv2d (const RadArgs*, RadStream);
int r4d_rad_conv1d_dw (const RadArgs*, RadStream);
int r4d_rad_rel_sinusoid (const RadArgs*, RadStream);
int r4d_rad_attn_local_rel (const RadArgs*, RadStream);
int r4d_rad_sigmoid (const RadArgs*, RadStream);
int r4d_rad_fill (const RadArgs*, RadStream);
int r4d_rad_silu_mul (const RadArgs*, RadStream);
@@ -466,6 +480,7 @@ int r4d_shape_mtp_enter (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_read (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_hc_write (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_binary (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_mul_weight (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_layernorm (const RadParam*, int, int operand, RadOpdDesc*);
int r4d_shape_grid_embed (const RadParam*, int, int operand, RadOpdDesc*);
+306 -3
View File
@@ -191,6 +191,8 @@ static const RadParamSpec pAttnDense[] = {
* cu_seqlens segments. Absent, the shim passes the total token count, which is a valid bound
* and picks the tall arm -- a speed choice, never a correctness one. */
P_INTO("max_seqlen"),
/* attn_paged's window over a segment's own positions (docs/OPS.md); 0 is none. */
P_INTO("window"),
};
static const RadOperandSpec oAttnDense[] = {
{ "q", RAD_OPD_IN, 0 },
@@ -1520,10 +1522,12 @@ static const RadParamSpec pRmsNorm[] = {
P_F64("eps"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
P_F64O("wadd"),
P_F64O("mult"), /* scales the row before its one rounding */
};
/* `w` optional: absent, the gain is one. */
static const RadOperandSpec oRmsNorm[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "w", RAD_OPD_WEIGHT, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
@@ -1537,6 +1541,90 @@ static const RadOperandSpec oBinary[] = {
{ "b", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pActMul[] = {
P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype"),
};
/* `M` is the step's token count and bands the op; the segment count is cu_seqlens' length. */
static const RadParamSpec pSegMean[] = {
P_INT("M"), P_INT("n"), P_STR("dtype"),
};
static const RadOperandSpec oSegMean[] = {
{ "x", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
/* docs/OPS.md's `qk_norm_rope`: a fused [q | k | v] row in place, theta and not a table. */
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("v_norm"), P_STRO("sections"), P_STRO("comps"),
};
/* `M` is the INPUT row count, a multiple of `k`. */
static const RadParamSpec pPoolRows[] = {
P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"), P_STR("dtype"),
};
static const RadOperandSpec oQkNormRope[] = {
{ "qkv", RAD_OPD_INOUT, 0 },
{ "positions", RAD_OPD_IN, 0 },
{ "q_w", RAD_OPD_WEIGHT, 0 },
{ "k_w", RAD_OPD_WEIGHT, 0 },
};
/* `scalar` 1 says `w` is one element rather than one row -- for the shape description; the shim
* reads it off the operand. */
static const RadParamSpec pMulWeight[] = {
P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar"),
};
/* The audio (USM conformer) tower's operators; libref's lists, field for field. */
static const RadOperandSpec oClamp[] = {
{ "x", RAD_OPD_IN, 0 },
{ "lo", RAD_OPD_WEIGHT, 0 },
{ "hi", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
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[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "valid", RAD_OPD_IN, 1 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pConv1dDw[] = {
P_INT("M"), P_INT("n"), P_INT("k"), P_INTO("cu_div"), P_STR("dtype"),
};
static const RadOperandSpec oConv1dDw[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pRelSin[] = {
P_INT("M"), P_INT("n"), P_F64O("max_timescale"), P_STR("dtype"),
};
static const RadOperandSpec oRelSin[] = {
{ "y", RAD_OPD_OUT, 0 },
};
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[] = {
{ "q", RAD_OPD_IN, 0 },
{ "k", RAD_OPD_IN, 0 },
{ "v", RAD_OPD_IN, 0 },
{ "relk", RAD_OPD_IN, 0 },
{ "pds", RAD_OPD_WEIGHT, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "out", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oMulWeight[] = {
{ "x", RAD_OPD_IN, 0 },
{ "w", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oGateUp[] = {
{ "gate_up", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
@@ -1653,6 +1741,17 @@ static const RadParamSpec pEmbed[] = {
* libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */
{ "wscale", RAD_P_F64, RAD_OPTIONAL },
};
/* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's
* sqrt(hidden)); libref's list, which embed_lookup_q does not share. */
static const RadParamSpec pEmbedM[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n_embd", RAD_P_INT, RAD_REQUIRED },
{ "n_vocab", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "vocab_offset", RAD_P_INT, RAD_OPTIONAL },
{ "wscale", RAD_P_F64, RAD_OPTIONAL },
{ "mult", RAD_P_F64, RAD_OPTIONAL },
};
static const RadOperandSpec oEmbed[] = {
{ "tokens", RAD_OPD_IN, 0 },
{ "wte", RAD_OPD_WEIGHT, 0 },
@@ -1836,10 +1935,45 @@ static const RadOpSchema kSchemas[] = {
"y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts "
"along rows, and nothing else broadcasts at all."),
SCHEMA("mul", pMnDtype, oBinary, "y = a * b, with the same one broadcast rule as `add`."),
SCHEMA("mul_weight", pMulWeight, oMulWeight,
"y = x * w, `w` a WEIGHT of one element (a scalar for the whole output) or of one row "
"(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."),
SCHEMA("silu_mul", pMnDtype, oGateUp,
"y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, "
"which is the order rad-convert fuses gate_proj and up_proj in."),
SCHEMA("act_mul", pActMul, oBinary,
"y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before "
"the product: silu_mul with its two halves in two operands."),
SCHEMA("seg_mean", pSegMean, oSegMean,
"Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 "
"and rounded once; an empty segment is zeros."),
SCHEMA("qk_norm_rope", pQkNormRope, oQkNormRope,
"In place over a fused [q | k | v] row: each q and k head RMS-normed against its gain "
"(plus wadd) and rounded, then rotated (neox or gptj, rotary_dim of head_dim); with "
"v_norm each v head is RMS-normed with a unit gain and not rotated."),
SCHEMA("pool_rows", pPoolRows, oUnary,
"Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded, then "
"times `mult` and rounded again."),
SCHEMA("sigmoid", pMnDtype, oUnary, "y = 1 / (1 + exp(-x))."),
SCHEMA("relu", pMnDtype, oUnary, "y = max(x, 0)."),
SCHEMA("silu", pMnDtype, oUnary, "y = x * sigmoid(x)."),
SCHEMA("clamp", pMnDtype, oClamp,
"y = min(max(x, lo), hi), lo and hi WEIGHTS of one element each: a clipped linear's range."),
SCHEMA("conv2d", pConv2d, oConv2d,
"A 2-D convolution over (time, width), channels innermost, w [cout, cin, kh, kw]. Each "
"cu_seqlens segment (rows cu/cu_div) is convolved on its own with zero padding at its "
"edges; its output rows start at cu/(cu_div*stride). With `valid`, input row t reads "
"as zeros unless valid[t * valid_stride] != 0. f32 sum, one rounding."),
SCHEMA("conv1d_dw", pConv1dDw, oConv1dDw,
"Causal depthwise convolution over time, w [C, 1, k], rows before the segment's start "
"(cu/cu_div) reading as zeros. f32 sum, one rounding."),
SCHEMA("rel_sinusoid", pRelSin, oRelSin,
"The sinusoidal relative-position table: row d is sin(d * inv[i]) then cos(d * inv[i]), "
"inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)), in f32, rounded once."),
SCHEMA("attn_local_rel", pAttnLocalRel, oAttnLocalRel,
"Local attention with a relative-position term and a softcap (Gemma 4's audio): query i "
"of a segment sees keys j with 0 <= i - j <= left; qf = q * head_dim^-0.5/ln2 * "
"softplus(pds); logit = qf.k * ln(1+e)/ln2 + qf.relk[i-j], softcapped; softmax; .v."),
SCHEMA("fill", pFill, oFill,
"y = value, every element of an [M, n] extent (default 0). The op a rank issues where "
"it computes nothing and a reader downstream -- an all-reduce, a residual -- still "
@@ -1874,7 +2008,7 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("kv_store", pKvStore, oKvStore,
"scatter k and v into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim] -- K at "
"[.., d] and V at [.., head_dim + d]. A negative slot stores nothing."),
SCHEMA("embed_lookup", pEmbed, oEmbed,
SCHEMA("embed_lookup", pEmbedM, oEmbed,
"the embedding gather. A negative token id writes a zero row, and so does one outside "
"[vocab_offset, vocab_offset + n_vocab) -- which is what makes the table shardable "
"across the vocabulary, the symmetry lm_head already had. Ids stay GLOBAL; summing the "
@@ -1959,7 +2093,8 @@ static const RadOpSchema kSchemas[] = {
"merged (token, head) row is gated, rounded, written to `out` and quantised to E4M3 "
"with one scale per 128 columns into `q8` / `q8_scale`."),
SCHEMA("attn_dense", pAttnDense, oAttnDense,
"dense non-causal attention over cu_seqlens segments -- the vision tower's."),
"dense attention over cu_seqlens segments, with attn_paged's window rule over a "
"segment's positions."),
SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate,
"split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate "
"copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a "
@@ -2407,6 +2542,10 @@ static const RadConstraint cAttnDecodeH128G8Bf16[] = {
/* KEY RENAME. libr4d writes C_IN("q_dtype","bf16") and C_IN("kv_dtype","bf16"); docs/OPS.md's
* `attn_dense` has one `dtype` because nothing about a dense bf16 tower is mixed-precision. The
* predicate -- "bf16, and nothing else" -- is unchanged. */
/* NO CONSTRAINT ON `window`. It is optional in the schema, a tower without one does not pass it,
* and a constraint whose key the geometry lacks does not hold -- so C_EQ("window", 0) here made
* this row unreachable for every Qwen vision tower. The kernel attends to the whole segment and
* refuses a non-zero window at launch instead (r4d_rad_attn_vit). */
static const RadConstraint cAttnVit[] = {
C_EQ("head_dim", 72), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
@@ -2423,6 +2562,31 @@ static const RadConstraint cAttnVit[] = {
static const RadConstraint cCastBf16[] = {
C_IN("from", "bf16"), C_IN("to", "bf16"),
};
/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the
* device in. */
/* The audio attention's window: a query's keys are held in LDS, 64 of them at most. */
static const RadConstraint cAttnLocalRel[] = {
C_IN("dtype", "bf16"), C_LE("left", 63), C_EQ("right", 0),
};
static const RadConstraint cCastWiden[] = {
C_IN("from", "bf16"), C_IN("to", "f32"),
};
/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs
* r4d_attn_dense_bf16.hip compiles. */
static const RadConstraint cAttnDenseH64[] = {
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH256G2[] = {
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH512G4[] = {
C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
/* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to
* 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */
static const RadConstraint cQkNormRope[] = {
C_LE("head_dim", 1024), C_DIV("head_dim", 32),
};
/* ---- gated delta net ----------------------------------------------------------------------- */
static const RadConstraint cGdnChunkScan[] = {
@@ -3340,6 +3504,111 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr,
r4d_shape_cast },
{ "cast_bf16_f32", "cast", "elem",
"y = x, bf16 widened to f32",
"any M and n; both row pitches are read off the operands",
"bf16 in, f32 out, exact",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cCastWiden), NOTUNE,
nullptr, nullptr, r4d_rad_cast_widen, nullptr, nullptr, nullptr,
r4d_shape_cast },
{ "act_mul_bf16", "act_mul", "elem",
"gated activation over two operands: act(a) rounded, times b",
"any n; a, b and y each at their own row pitch, so both may be column slices of one buffer",
"bf16 in and out, f32 arithmetic, libm silu / erf / tanh",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_act_mul, nullptr, nullptr, nullptr,
r4d_shape_binary },
{ "seg_mean_bf16", "seg_mean", "elem",
"mean pooling: one row a cu_seqlens segment",
"any n; 32 columns by 8 row lanes a workgroup, one workgroup row a segment",
"bf16 in and out, f64 sum, one rounding",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_seg_mean, nullptr, nullptr, nullptr },
{ "qk_norm_rope_bf16", "qk_norm_rope", "attn",
"per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place",
"head_dim a multiple of 32 up to 1024, neox (rotary_dim / 2 a multiple of 32), gptj, or "
"blocks (sections of 16 or a multiple of 32 pairs, each starting on a 32-channel slice); one "
"workgroup a token and a wave a head, sin/cos computed once for all its heads",
"bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cQkNormRope), NOTUNE,
nullptr, nullptr, r4d_rad_qk_norm_rope, nullptr, nullptr, nullptr },
{ "relu_bf16", "relu", "elem",
"max(x, 0)",
"any n; both row pitches read off the operands",
"bf16 in and out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_relu, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "silu_bf16", "silu", "elem",
"x * sigmoid(x), the sigmoid rounded nowhere: libref's act_silu",
"any n; both row pitches read off the operands",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_silu, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "clamp_bf16", "clamp", "elem",
"x clamped to two one-element weights: a clipped linear's range",
"any n; bf16 or f32 bounds",
"bf16 in and out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_clamp, nullptr, nullptr, nullptr },
{ "conv2d_bf16", "conv2d", "elem",
"segment-wise 2-D convolution over (time, width), channels innermost, optional row mask",
"any geometry; a workgroup an output time row, a thread an output element; sized for an audio "
"subsampler (a few thousand frames, kernels of 3)",
"bf16 x / w / y, i32 cu_seqlens and mask, f32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_conv2d, nullptr, nullptr, nullptr },
{ "conv1d_dw_bf16", "conv1d_dw", "elem",
"segment-wise causal depthwise convolution over time",
"any channels and taps; a thread a (row, channel)",
"bf16 x / w / y, i32 cu_seqlens, f32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_conv1d_dw, nullptr, nullptr, nullptr },
{ "rel_sinusoid_bf16", "rel_sinusoid", "elem",
"the sinusoidal relative-position table",
"any rows and even width; a workgroup a row",
"bf16 out, f32 libm sin / cos / exp",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_rel_sinusoid, nullptr, nullptr, nullptr },
{ "attn_local_rel_bf16", "attn_local_rel", "attn",
"local attention with a relative-position term and a softcap (Gemma 4's audio)",
"any head_dim and heads, left <= 63, right 0; a workgroup a (row, head), each logit a "
"workgroup sum",
"bf16 q / k / v / relk / out, bf16 or f32 per-dim scale, f32 softmax",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnLocalRel), NOTUNE,
nullptr, nullptr, r4d_rad_attn_local_rel, nullptr, nullptr, nullptr },
{ "pool_rows_bf16", "pool_rows", "elem",
"mean of every k consecutive rows, then a multiplier: a vision pooler over windows its "
"processor laid out consecutively",
"any n and k; a workgroup an output row, a thread a column",
"bf16 in and out, f32 sum, two roundings",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_pool_rows, nullptr, nullptr, nullptr },
{ "rmsnorm_bf16", "rmsnorm", "norm",
"root-mean-square norm with a gain, two passes over the row",
"any n; the sum of squares accumulates in f32 and only the store narrows",
@@ -3395,6 +3664,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_mul, nullptr, nullptr, nullptr,
r4d_shape_binary },
{ "mul_weight_bf16", "mul_weight", "elem",
"activation times a learned scalar or one-row gain",
"any n; the weight is one element or exactly n",
"bf16 in, weight and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_mul_weight, nullptr, nullptr, nullptr,
r4d_shape_mul_weight },
{ "fill_bf16", "fill", "elem",
"constant fill, a row a workgroup",
"any M, n; a row pitch is honoured",
@@ -3903,6 +4181,31 @@ static const RadKernelInfo kKernels[] = {
ROW(cAttnVit), NOTUNE,
nullptr, nullptr, r4d_rad_attn_vit, nullptr, nullptr, nullptr },
{ "attn_dense_h64_bf16", "attn_dense", "attn",
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
"head_dim 64, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a "
"fused projection allowed)",
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH64), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr },
{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn",
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
"head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window",
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH256G2), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr },
{ "attn_dense_h512_gqa4_bf16", "attn_dense", "attn",
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
"head_dim 512 split across two waves, four query heads a KV head in one workgroup",
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH512G4), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense, nullptr, nullptr, nullptr },
/* -------------------------------------------------------------------------- gated delta net */
{ "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn",
"gated delta net chunked scan: WY recompute, state recurrence and output in one kernel",
+425
View File
@@ -11010,6 +11010,431 @@ static void device_phase(const Plugin& pl) {
run_case(r, ts, ps);
}
}
/* The encoder attention rows: a fused [q|k|v] projection read through column slices, at each
* compiled (head_dim, gqa), with and without a window. Numerics are rad-kbench's (libref is
* the oracle); this is the launch at every geometry. */
{
struct G { const char* name; int64_t hd, nh, nkv; };
for (const G& g : { G{ "attn_dense_h64_bf16", 64, 4, 4 },
G{ "attn_dense_h256_gqa2_bf16", 256, 4, 2 },
G{ "attn_dense_h512_gqa4_bf16", 512, 4, 1 } }) {
if (!sel(g.name)) continue;
const RadKernelInfo* r = find(pl, g.name);
if (!r) { ok(g.name, false, "row absent"); continue; }
for (const int64_t window : { (int64_t)0, (int64_t)9 }) {
const int64_t total = 48, wq = g.nh * g.hd, wkv = g.nkv * g.hd;
const int64_t width = wq + 2 * wkv;
void* qkv = dalloc((size_t)(total * width * 2));
auto col = [&](int64_t first, int64_t w) {
RadTensor t = T(qkv, RAD_BF16, { total, w });
t.data = (void*)((uint16_t*)qkv + first);
t.stride[0] = width;
return t;
};
std::vector<RadTensor> ts = {
col(0, wq), col(wq, wkv), col(wq + wkv, wkv),
T(nullptr, RAD_I32, { 3 }), T(nullptr, RAD_BF16, { total, wq }),
};
std::vector<RadParam> ps = {
PI("M", total), PI("head_dim", g.hd), PI("gqa", g.nh / g.nkv),
PI("causal", 0), PS("dtype", "bf16"), PF("scale", 1.0),
PI("max_seqlen", 32), PI("window", window),
};
run_case(r, ts, ps);
}
}
}
if (sel("act_mul_bf16")) {
const RadKernelInfo* r = find(pl, "act_mul_bf16");
if (!r) ok("act_mul_bf16", false, "row absent");
else
for (const char* act : { "silu", "gelu", "gelu_tanh" }) {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }),
T(nullptr, RAD_BF16, { 5, 645 }) };
std::vector<RadParam> ps = { PI("M", 5), PI("n", 645), PS("act", act),
PS("dtype", "bf16") };
run_case(r, ts, ps);
}
}
if (sel("seg_mean_bf16")) {
const RadKernelInfo* r = find(pl, "seg_mean_bf16");
if (!r) ok("seg_mean_bf16", false, "row absent");
else {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 23, 645 }),
T(nullptr, RAD_I32, { 4 }),
T(nullptr, RAD_BF16, { 3, 645 }) };
std::vector<RadParam> ps = { PI("M", 23), PI("n", 645), PS("dtype", "bf16") };
run_case(r, ts, ps);
}
}
if (sel("qk_norm_rope_bf16")) {
const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16");
if (!r) ok("qk_norm_rope_bf16", false, "row absent");
else
for (const int64_t hd : { (int64_t)256, (int64_t)512 }) {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 7, 8 * hd }),
T(nullptr, RAD_I32, { 7 }),
T(nullptr, RAD_BF16, { hd }),
T(nullptr, RAD_BF16, { hd }) };
std::vector<RadParam> ps = { PI("M", 7), PI("head_dim", hd), PI("n_head", 4),
PI("n_head_kv", 2), PF("theta", 10000.0),
PF("eps", 1e-6), PS("mode", "neox"),
PI("v_norm", 1) };
run_case(r, ts, ps);
}
}
if (sel("mul_weight_bf16")) {
const RadKernelInfo* r = find(pl, "mul_weight_bf16");
if (!r) ok("mul_weight_bf16", false, "row absent");
else
for (const int64_t wn : { (int64_t)1, (int64_t)512 }) {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 5, 512 }),
T(nullptr, RAD_BF16, { wn }),
T(nullptr, RAD_BF16, { 5, 512 }) };
std::vector<RadParam> ps = { PI("M", 5), PI("n", 512), PS("dtype", "bf16"),
PI("scalar", wn == 1) };
run_case(r, ts, ps);
}
}
if (sel("qk_norm_rope_bf16")) {
const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16");
if (r) {
/* blocks, the vision form: 12 heads of 64, x and y halves, components (row, col). */
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 9, 36 * 64 }),
T(nullptr, RAD_I32, { 2, 9 }),
T(nullptr, RAD_BF16, { 64 }),
T(nullptr, RAD_BF16, { 64 }) };
std::vector<RadParam> ps = { PI("M", 9), PI("head_dim", 64), PI("n_head", 12),
PI("n_head_kv", 12), PF("theta", 100.0), PF("eps", 1e-6),
PS("mode", "blocks"), PS("sections", "16 16"),
PS("comps", "1 0"), PI("v_norm", 1) };
run_case(r, ts, ps);
}
}
if (sel("pool_rows_bf16")) {
const RadKernelInfo* r = find(pl, "pool_rows_bf16");
if (!r) ok("pool_rows_bf16", false, "row absent");
else {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 27, 768 }),
T(nullptr, RAD_BF16, { 3, 768 }) };
std::vector<RadParam> ps = { PI("M", 27), PI("n", 768), PI("k", 9),
PF("mult", 27.712812921102035), PS("dtype", "bf16") };
run_case(r, ts, ps);
}
}
/* --- the audio tower's ops, NUMERICALLY: each kernel against the formula libref implements,
* computed here on the host from the same bf16 inputs. rad-kbench's replay fixture predates
* these ops and a container-driven run needs the model, so this is where a wrong index in
* one of them shows up without either. Relative L2 against a bf16 rounding of the answer. */
{
uint64_t seed = 0x5eedull;
auto rnd = [&]() {
seed = seed * 6364136223846793005ull + 1442695040888963407ull;
return (float)((int64_t)(seed >> 40) % 2001 - 1000) / 1000.0f;
};
auto up = [&](std::vector<float>& h) {
std::vector<uint16_t> b(h.size());
for (size_t i = 0; i < h.size(); ++i) { b[i] = h_to_bf16(h[i]); h[i] = h_bf16(b[i]); }
void* d = dalloc(b.size() * 2);
if (d) st_memcpy(d, b.data(), b.size() * 2, hipMemcpyHostToDevice);
return d;
};
auto down = [&](void* d, size_t n) {
std::vector<uint16_t> b(n);
st_memcpy(b.data(), d, n * 2, hipMemcpyDeviceToHost);
std::vector<float> f(n);
for (size_t i = 0; i < n; ++i) f[i] = h_bf16(b[i]);
return f;
};
auto rel = [](const std::vector<float>& got, const std::vector<float>& want) {
double e = 0, r = 0;
for (size_t i = 0; i < want.size(); ++i) {
const double w = h_bf16(h_to_bf16(want[i]));
e += (got[i] - w) * (got[i] - w);
r += w * w;
}
return r > 0 ? std::sqrt(e / r) : std::sqrt(e);
};
auto check = [&](const char* name, const std::vector<float>& got,
const std::vector<float>& want, double tol) {
const double r = rel(got, want);
char d[96];
std::snprintf(d, sizeof d, "rel_l2 %.3g", r);
ok(name, r <= tol, d);
};
auto randv = [&](size_t n, float scale) {
std::vector<float> v(n);
for (auto& x : v) x = rnd() * scale;
return v;
};
if (sel("relu_bf16") || sel("silu_bf16") || sel("clamp_bf16")) {
const int64_t M = 5, n = 300;
std::vector<float> x = randv((size_t)(M * n), 2.0f);
void* dx = up(x);
void* dy = dalloc((size_t)(M * n) * 2);
if (const RadKernelInfo* r = find(pl, "relu_bf16")) {
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<float> want(x.size());
for (size_t i = 0; i < x.size(); ++i) want[i] = x[i] > 0 ? x[i] : 0;
check("relu_bf16 numerics", down(dy, x.size()), want, 0.0);
} else ok("relu_bf16", false, "row absent");
if (const RadKernelInfo* r = find(pl, "silu_bf16")) {
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<float> want(x.size());
for (size_t i = 0; i < x.size(); ++i) {
const float v = h_bf16(h_to_bf16(x[i]));
want[i] = v * (1.0f / (1.0f + std::exp(-v)));
}
/* expf on the card and std::exp here may differ by an ulp of f32, which can move
* a bf16 rounding; anything beyond that is a wrong kernel. */
check("silu_bf16 numerics", down(dy, x.size()), want, 1e-3);
} else ok("silu_bf16", false, "row absent");
/* PAST THE GRID'S Y LIMIT: the audio subsampler's rectifier runs over 96000 rows of
* 128, and a launch of one grid row a matrix row stops at 65535. */
if (const RadKernelInfo* r = find(pl, "relu_bf16")) {
const int64_t Mb = 70000, nb = 32;
std::vector<float> xb = randv((size_t)(Mb * nb), 2.0f);
void* dxb = up(xb);
void* dyb = dalloc((size_t)(Mb * nb) * 2);
std::vector<RadTensor> ts = { T(dxb, RAD_BF16, { Mb, nb }), T(dyb, RAD_BF16, { Mb, nb }) };
std::vector<RadParam> ps = { PI("M", Mb), PI("n", nb), PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<float> want(xb.size());
for (size_t i = 0; i < xb.size(); ++i) want[i] = xb[i] > 0 ? xb[i] : 0;
check("relu_bf16 numerics past 65535 rows", down(dyb, xb.size()), want, 0.0);
}
if (const RadKernelInfo* r = find(pl, "clamp_bf16")) {
std::vector<float> lo = { -0.5f }, hi = { 0.7f };
void* dl = up(lo);
void* dh = up(hi);
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dl, RAD_BF16, { 1 }),
T(dh, RAD_BF16, { 1 }), T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<float> want(x.size());
for (size_t i = 0; i < x.size(); ++i)
want[i] = x[i] < lo[0] ? lo[0] : (x[i] > hi[0] ? hi[0] : x[i]);
check("clamp_bf16 numerics", down(dy, x.size()), want, 0.0);
} else ok("clamp_bf16", false, "row absent");
}
if (sel("act_mul_bf16")) {
const RadKernelInfo* r = find(pl, "act_mul_bf16");
const int64_t M = 4, n = 200;
std::vector<float> g = randv((size_t)(M * n), 4.0f), u = randv((size_t)(M * n), 1.0f);
void* dg = up(g);
void* du = up(u);
void* dy = dalloc((size_t)(M * n) * 2);
std::vector<RadTensor> ts = { T(dg, RAD_BF16, { M, n }), T(du, RAD_BF16, { M, n }),
T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PS("act", "sigmoid"),
PS("dtype", "bf16") };
if (r) run_case(r, ts, ps);
std::vector<float> want(g.size());
for (size_t i = 0; i < g.size(); ++i)
want[i] = h_bf16(h_to_bf16(1.0f / (1.0f + std::exp(-g[i])))) * u[i];
check("act_mul_bf16 sigmoid numerics", down(dy, g.size()), want, 1e-2);
}
if (sel("rmsnorm_bf16")) {
const RadKernelInfo* r = find(pl, "rmsnorm_bf16");
const int64_t M = 3, n = 1024;
std::vector<float> x = randv((size_t)(M * n), 3.0f), w = randv((size_t)n, 1.0f);
void* dx = up(x);
void* dw = up(w);
void* dy = dalloc((size_t)(M * n) * 2);
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, n }), T(dw, RAD_BF16, { n }),
T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PF("eps", 1e-6),
PS("dtype", "bf16"), PF("mult", 0.5) };
if (r) run_case(r, ts, ps);
std::vector<float> want(x.size());
for (int64_t m = 0; m < M; ++m) {
double ss = 0;
for (int64_t i = 0; i < n; ++i) ss += (double)x[(size_t)(m * n + i)] * x[(size_t)(m * n + i)];
const float s = 1.0f / std::sqrt((float)(ss / n) + 1e-6f);
for (int64_t i = 0; i < n; ++i)
want[(size_t)(m * n + i)] = x[(size_t)(m * n + i)] * s * w[(size_t)i] * 0.5f;
}
check("rmsnorm_bf16 mult numerics", down(dy, x.size()), want, 1e-2);
}
if (sel("conv2d_bf16")) {
const RadKernelInfo* r = find(pl, "conv2d_bf16");
if (!r) ok("conv2d_bf16", false, "row absent");
/* The subsampler's two layers, two segments each, with a masked row. */
struct G { int64_t M, W, cin, cout, cdiv, vst; };
for (const G& g : { G{ 24, 128, 1, 128, 1, 1 }, G{ 12, 64, 128, 32, 2, 2 } }) {
if (!r) break;
const int64_t kh = 3, kw = 3, st = 2, pad = 1;
const int64_t Wo = (g.W + 2 * pad - kw) / st + 1;
const int64_t T0 = g.M / 2; /* rows a segment */
const int64_t To = (T0 + 2 * pad - kh) / st + 1, Mo = 2 * To;
std::vector<float> x = randv((size_t)(g.M * g.W * g.cin), 1.0f);
std::vector<float> w = randv((size_t)(g.cout * g.cin * kh * kw), 0.3f);
std::vector<int32_t> cu = { 0, (int32_t)(T0 * g.cdiv), (int32_t)(g.M * g.cdiv) };
std::vector<int32_t> valid((size_t)(g.M * g.vst), 1);
valid[(size_t)(3 * g.vst)] = 0;
void* dx = up(x);
void* dw = up(w);
void* dcu = dalloc(cu.size() * 4);
void* dv = dalloc(valid.size() * 4);
fill_i32(dcu, cu);
fill_i32(dv, valid);
void* dy = dalloc((size_t)(Mo * Wo * g.cout) * 2);
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { g.M, g.W * g.cin }),
T(dw, RAD_BF16, { g.cout, g.cin, kh, kw }),
T(dcu, RAD_I32, { 3 }),
T(dv, RAD_I32, { g.M * g.vst }),
T(dy, RAD_BF16, { Mo, Wo * g.cout }) };
std::vector<RadParam> ps = { PI("M", g.M), PI("width", g.W), PI("cin", g.cin),
PI("cout", g.cout), PI("kh", kh), PI("kw", kw),
PI("stride", st), PI("pad", pad), PI("cu_div", g.cdiv),
PI("valid_stride", g.vst), PS("dtype", "bf16") };
run_case(r, ts, ps);
std::vector<float> want((size_t)(Mo * Wo * g.cout), 0.0f);
for (int64_t s = 0; s < 2; ++s)
for (int64_t to = 0; to < To; ++to)
for (int64_t wo = 0; wo < Wo; ++wo)
for (int64_t co = 0; co < g.cout; ++co) {
float acc = 0.0f;
for (int64_t i = 0; i < kh; ++i) {
const int64_t ti = to * st - pad + i;
if (ti < 0 || ti >= T0) continue;
const int64_t tg = s * T0 + ti;
if (!valid[(size_t)(tg * g.vst)]) continue;
for (int64_t j = 0; j < kw; ++j) {
const int64_t wi = wo * st - pad + j;
if (wi < 0 || wi >= g.W) continue;
for (int64_t ci = 0; ci < g.cin; ++ci)
acc += x[(size_t)((tg * g.W + wi) * g.cin + ci)] *
w[(size_t)(((co * g.cin + ci) * kh + i) * kw + j)];
}
}
want[(size_t)(((s * To + to) * Wo + wo) * g.cout + co)] = acc;
}
check(g.cin == 1 ? "conv2d_bf16 layer0 numerics" : "conv2d_bf16 layer1 numerics",
down(dy, want.size()), want, 1e-2);
}
}
if (sel("conv1d_dw_bf16")) {
const RadKernelInfo* r = find(pl, "conv1d_dw_bf16");
const int64_t M = 20, C = 1024, K = 5;
std::vector<float> x = randv((size_t)(M * C), 1.0f), w = randv((size_t)(C * K), 0.5f);
std::vector<int32_t> cu = { 0, 7, 20 };
void* dx = up(x);
void* dw = up(w);
void* dcu = dalloc(12);
fill_i32(dcu, cu);
void* dy = dalloc((size_t)(M * C) * 2);
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, C }), T(dw, RAD_BF16, { C, 1, K }),
T(dcu, RAD_I32, { 3 }), T(dy, RAD_BF16, { M, C }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", C), PI("k", K), PS("dtype", "bf16") };
if (r) run_case(r, ts, ps);
std::vector<float> want((size_t)(M * C));
for (int64_t t = 0; t < M; ++t) {
const int64_t t0 = t < 7 ? 0 : 7;
for (int64_t c = 0; c < C; ++c) {
float acc = 0.0f;
for (int64_t j = 0; j < K; ++j) {
const int64_t tt = t - (K - 1) + j;
if (tt >= t0) acc += x[(size_t)(tt * C + c)] * w[(size_t)(c * K + j)];
}
want[(size_t)(t * C + c)] = acc;
}
}
check("conv1d_dw_bf16 numerics", down(dy, want.size()), want, 1e-2);
}
if (sel("rel_sinusoid_bf16")) {
const RadKernelInfo* r = find(pl, "rel_sinusoid_bf16");
const int64_t M = 13, n = 1024, h = n / 2;
void* dy = dalloc((size_t)(M * n) * 2);
std::vector<RadTensor> ts = { T(dy, RAD_BF16, { M, n }) };
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PF("max_timescale", 10000.0),
PS("dtype", "bf16") };
if (r) run_case(r, ts, ps);
const float inc = (float)(std::log(10000.0) / (double)(h - 1));
std::vector<float> want((size_t)(M * n));
for (int64_t d = 0; d < M; ++d)
for (int64_t i = 0; i < h; ++i) {
const float ang = (float)d * std::exp((float)i * -inc);
want[(size_t)(d * n + i)] = std::sin(ang);
want[(size_t)(d * n + h + i)] = std::cos(ang);
}
check("rel_sinusoid_bf16 numerics", down(dy, want.size()), want, 1e-2);
}
if (sel("attn_local_rel_bf16")) {
const RadKernelInfo* r = find(pl, "attn_local_rel_bf16");
const int64_t M = 40, H = 8, D = 128, L = 12, W = H * D;
const float cap = 50.0f;
std::vector<float> q = randv((size_t)(M * W), 2.0f), k = randv((size_t)(M * W), 2.0f);
std::vector<float> v = randv((size_t)(M * W), 1.0f);
std::vector<float> rk = randv((size_t)((L + 1) * W), 1.0f), pds = randv((size_t)D, 3.0f);
std::vector<int32_t> cu = { 0, 17, 40 };
void* dq = up(q);
void* dk = up(k);
void* dv = up(v);
void* drk = up(rk);
void* dp = up(pds);
void* dcu = dalloc(12);
fill_i32(dcu, cu);
void* dout = dalloc((size_t)(M * W) * 2);
std::vector<RadTensor> ts = { T(dq, RAD_BF16, { M, W }), T(dk, RAD_BF16, { M, W }),
T(dv, RAD_BF16, { M, W }), T(drk, RAD_BF16, { L + 1, W }),
T(dp, RAD_BF16, { D }), T(dcu, RAD_I32, { 3 }),
T(dout, RAD_BF16, { M, W }) };
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", D), PI("n_head", H),
PI("left", L), PI("right", 0), PF("softcap", cap),
PS("dtype", "bf16") };
if (r) run_case(r, ts, ps);
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));
std::vector<float> want((size_t)(M * W));
for (int64_t i = 0; i < M; ++i)
for (int64_t hh = 0; hh < H; ++hh) {
const int64_t t0 = i < 17 ? 0 : 17, j0 = std::max(t0, i - L);
std::vector<float> lg;
float mx = -1e30f;
for (int64_t j = j0; j <= i; ++j) {
float ss = 0.0f;
for (int64_t d = 0; d < D; ++d) {
const float x = pds[(size_t)d];
const float sp = h_bf16(h_to_bf16(
x > 20.0f ? x : (x > 0 ? x + std::log1p(std::exp(-x))
: std::log1p(std::exp(x)))));
const float qf = q[(size_t)(i * W + hh * D + d)] * qs * sp;
ss += qf * (k[(size_t)(j * W + hh * D + d)] * ks) +
qf * rk[(size_t)((i - j) * W + hh * D + d)];
}
lg.push_back(cap * std::tanh(ss / cap));
mx = std::max(mx, lg.back());
}
float sum = 0.0f;
for (float& l : lg) { l = std::exp(l - mx); sum += l; }
for (int64_t d = 0; d < D; ++d) {
float acc = 0.0f;
for (int64_t j = j0; j <= i; ++j)
acc += lg[(size_t)(j - j0)] / sum * v[(size_t)(j * W + hh * D + d)];
want[(size_t)(i * W + hh * D + d)] = acc;
}
}
check("attn_local_rel_bf16 numerics", down(dout, want.size()), want, 1e-2);
}
}
if (sel("cast_bf16_f32")) {
const RadKernelInfo* r = find(pl, "cast_bf16_f32");
if (!r) ok("cast_bf16_f32", false, "row absent");
else {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 3, 768 }),
T(nullptr, RAD_F32, { 3, 768 }) };
std::vector<RadParam> ps = { PI("M", 3), PI("n", 768), PS("from", "bf16"),
PS("to", "f32") };
run_case(r, ts, ps);
}
}
/* --- cast: the strided row copy an intermediate-hidden-state tap writes with -------------
+16 -4
View File
@@ -382,11 +382,12 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand,
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
/* `from` and `to` are separate keys because the whole point of the op is that the two ends
* differ. This row is compiled for bf16 -> bf16 only -- it is a strided row copy -- and the
* shim refuses anything else on dtype, so a geometry that names another pair is declined here
* rather than described into a refusal. */
* differ. Two rows serve it -- bf16 -> bf16 (a strided row copy) and bf16 -> f32 (the
* widening) -- and the shims refuse anything else on dtype, so a geometry that names another
* pair is declined here rather than described into a refusal. */
const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to");
if (f != (uint32_t)RAD_BF16 || t != (uint32_t)RAD_BF16) return RAD_E_UNSUPPORTED;
if (f != (uint32_t)RAD_BF16 || (t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32))
return RAD_E_UNSUPPORTED;
const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) };
R4D_PICK(l);
}
@@ -528,6 +529,17 @@ extern "C" int r4d_shape_binary(const RadParam* p, int n_p, int operand,
R4D_PICK(l);
}
/* mul_weight: the one-row form of the weight (a per-channel gain), or with `scalar` the
* one-element form. */
extern "C" int r4d_shape_mul_weight(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");
const uint32_t D = dt_act(p, n_p, "dtype");
const int64_t wn = pi(p, n_p, "scalar") ? 1 : n;
const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1, wn), opd(D, M, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_fill(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t n = pi(p, n_p, "n");