ops: rmsnorm_p, gelu_mul, logit_softcap, scale in lockstep across libref/libavx/libr4d + OPS.md rows

Elementwise ops with numeric selftest cases against the f64 oracle (both legs
of logit_softcap: bf16 and the f32 band the sampling chain carries). libr4d
gains env-gated verification probes alongside them (R4D_VERIFY_OFF
recompute-on-host checks; default off — instruments, not features).
This commit is contained in:
sfjes committed 2026-10-10 00:36:07 -07:00
1 parent 73620ef00e
commit c37ce73d72
20 files changed
+2260 -51

No files matched your search

+35 -3
View File
@@ -108,6 +108,24 @@ int r4d_attn_h128_gqa4_have_prefill(void);
// Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache
// dtype: the partials are f16 either way.
long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a);
// The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window.
// Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band
// (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the
// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit turned on.
int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a);
// The Gemma 4 dense global geometry: head_dim 512, 8 queries per KV head, full attention (window 0).
// The one head_dim the library had not compiled -- a stand-alone instantiation, not the gqa8
// parameterised body (whose prefill tile of 48 does not fit 512-channel tiles in LDS). Both legs
// spill ~384 VGPRs at this head; a 3b tuning question, not a 3a one.
int r4d_attn_prefill_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream);
int r4d_attn_decode_h512_gqa8_bf16kv (const R4DArgs* a, hipStream_t stream);
long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a);
// The geometry the attention kernels above are compiled for, so a caller can test a model against
// it instead of discovering the mismatch at the first launch.
void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows);
@@ -892,6 +910,11 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in
// whole table, an unsliced lookup.
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);
// The same lookup with a RUNTIME gather scale on the rows that are found (x = table[id] *
// scale); 1.0 is the plain copy, and a missed row still writes zero rather than zero * scale.
// Gemma 4's embedding is scaled by sqrt(n_embd) at the lookup, not baked into the table.
int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab,
int vocab_off, int x_ld, float scale, long stream);
int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
int x_ld, int y_ld, long stream);
// y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after
@@ -900,6 +923,9 @@ int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows,
// is -- or bf16. The activation either side is bf16 in both cases.
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);
// y = x * rsqrt(mean(x^2) + eps). The weightless RMS: the same two-pass sum of squares as rmsnorm
// with the gain multiply dropped, gemma's bare value normalisation.
int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream);
// `op` 0 sums, 1 multiplies. A `b_ld` of 0 is the ONE broadcast form: every row reads the same n
// elements, which is what makes a bias add this op rather than a second one.
int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
@@ -909,6 +935,9 @@ int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF -- the order rad-convert
// fuses gate_proj and up_proj in.
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF, the tanh
// approximation (gemma's gelu_pytorch_tanh), not the erf one.
int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
// In place over `n_rope_heads` consecutive heads of a row; anything after them (the V heads of a
// fused projection) is untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope, which is the
// same arithmetic when every position component is equal); 1 pairs 2i with 2i+1. `rot` may be less
@@ -918,9 +947,12 @@ int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int
float theta, float rscale, int row_pitch, long stream);
// The multi-component rotary (docs/OPS.md, `rope`): `mode` 2 mrope, 3 imrope, 4 axial over
// `sec[0..n_sec)`, component c of token m at pos[c * plane + m]. plane 0 is the call above.
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj,
float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec,
int plane, long stream);
// `den` is the width the base ladder's exponent divides by: `rot` (the `rotary` ladder, the
// default) or `head_dim` (the `head` ladder, the proportional variant). The `rope` row resolves it
// from its `ladder` param; the plain form above passes `rot`.
int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec,
int n_sec, int plane, long stream);
// C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. THE OUTPUT IS f32 and that is why this
// is not r4d_gemm_bf16_nt_m16 under another name: the engine declares its logits buffer f32,
// because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbouring
+787 -19
View File
@@ -49,9 +49,360 @@
#include "r4d_fp8_wmma.h"
#include <cstdlib>
#include <vector>
#include <cmath>
#include <cstring>
// ================================================================== attn_paged verify
// Copy n bytes from a (possibly host-page-table-unmapped) device VA into a regular allocation, via
// the DEVICE page table (mapped) -- a host DtoH copy on such a VA faults. Global scope so the
// verify (which reads the KV cache) can use it. Utility for the env-gated verify path only.
__global__ void r4d_copy8_kernel(const uint8_t* __restrict__ src, uint8_t* __restrict__ dst, size_t n) {
for (size_t i = blockIdx.x * (size_t)256 + threadIdx.x; i < n;
i += (size_t)gridDim.x * 256)
dst[i] = src[i];
}
// DEBUG (env-gated, R4D_VERIFY_OFF): run the paged-attention kernel, then recompute the SAME
// attention on the host (the libref two-pass-softmax formula, f32) from the bf16/fp8 q and the
// paged k/v the kernel read, and report the max deviation. A deviation well above the bf16
// rounding (~1e-3) means the device kernel is wrong for the real (paged, ragged) inputs. GLOBAL
// scope (not the anonymous namespace below) so the attention wrappers -- a different translation
// unit -- can call it. Only the first few of each band (decode / prefill) are checked.
static float attn_verify_bf16(uint16_t b) {
uint32_t u = (uint32_t)b << 16;
float f;
std::memcpy(&f, &u, 4);
return f;
}
static float attn_verify_e4m3(uint8_t b) {
const float sign = (b & 0x80u) ? -1.0f : 1.0f;
const uint32_t ex = (uint32_t)(b >> 3) & 0x0Fu, mn = (uint32_t)b & 0x07u;
if (ex == 0) return sign * (float)mn * (1.0f / 512.0f);
return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7);
}
int g_attn_decode_verify_n = 0;
int g_attn_prefill_verify_n = 0;
/* Diagnostics master switch (degenerate-output investigation, 2026-10-08): OFF by default. Set
* R4D_DIAG=1 to arm the env-gated probes; the probe families each keep their own env:
* R4D_VERIFY_ATTN=1 -> verify_attn_paged (KV store + attention recompute, maxd);
* the [KVCHK]/[HIDD]/[LOGITS] store/GEMM probes and [SAMPIN] (sampler input) run their capped
* dumps under R4D_DIAG alone. Cleared 2026-10: KV store byte-exact, attention maxd ~0.04,
* hidden state rich, logits sharp, softcap applied, sampler argmax correct. */
int r4d_diag_on() {
static const int v = std::getenv("R4D_DIAG") ? 1 : 0;
return v;
}
void verify_attn_paged(const R4DArgs* r, long stream, int kv_is_fp8, int is_decode) {
static int on = -1;
if (on < 0) { const char* e = std::getenv("R4D_VERIFY_ATTN"); on = (e && *e) ? 1 : 0; }
if (!on) return;
int* cnt = is_decode ? &g_attn_decode_verify_n : &g_attn_prefill_verify_n;
const int cap = is_decode ? 10 : 4; /* decode 10 covers the first global (h512) layer too */
if (*cnt >= cap) return;
(*cnt)++;
/* SYNC BEFORE ANY DtoH COPY (see verify_rmsnorm_p): the q / kv / out buffers are the products
* of earlier ops on `stream`, and a subsequent op reuses the workspace. The DtoH copies below
* run on the DEFAULT stream (concurrent with `stream`), so without this sync they can read a
* buffer while a later op overwrites it. Syncing `stream` first guarantees the producers + this
* kernel have completed and the consumer has not yet been launched. */
hipStreamSynchronize((hipStream_t)stream);
const int ew = kv_is_fp8 ? 1 : 2;
const int num_seqs = r->num_seqs, q_len = r->q_len, q_heads = r->q_heads,
kv_heads = r->kv_heads, hd = r->head_dim, bs = r->block_size,
max_blocks = r->max_blocks;
const bool ragged = (r->cu_q != nullptr);
const int total_q = ragged ? r->total_q : num_seqs * q_len;
const int gqa = kv_heads > 0 ? q_heads / kv_heads : 1;
fprintf(stderr, "[VERIFY attn_%s] START seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d bs=%d mb=%d kvs=%ld kvh_s=%ld\n",
is_decode ? "decode" : "prefill", num_seqs, q_len, total_q,
q_heads, kv_heads, hd, bs, max_blocks,
(long)r->kv_block_stride, (long)r->kv_head_stride);
std::vector<int> bt_h((size_t)num_seqs * (size_t)max_blocks);
hipMemcpy(bt_h.data(), r->block_table, bt_h.size() * 4, hipMemcpyDeviceToHost);
std::vector<int> su_h(num_seqs);
hipMemcpy(su_h.data(), r->seqused_k, su_h.size() * 4, hipMemcpyDeviceToHost);
std::vector<int> cu_h(num_seqs + 1);
if (ragged) hipMemcpy(cu_h.data(), r->cu_q, cu_h.size() * 4, hipMemcpyDeviceToHost);
else for (int s = 0; s <= num_seqs; ++s) cu_h[s] = s * q_len;
std::vector<float> kds_h(num_seqs * kv_heads), vds_h(num_seqs * kv_heads);
if (r->k_descale) hipMemcpy(kds_h.data(), r->k_descale, kds_h.size() * 4, hipMemcpyDeviceToHost);
if (r->v_descale) hipMemcpy(vds_h.data(), r->v_descale, vds_h.size() * 4, hipMemcpyDeviceToHost);
fprintf(stderr, "[VERIFY attn_%s] P1 small-copies done su0=%d\n", is_decode ? "decode" : "prefill", su_h[0]);
/* Only the blocks the block tables actually reference are read, so copy just those (a full
* cache can be gigabytes; a decode step touches one). */
std::vector<int> used;
for (int s = 0; s < num_seqs; ++s) {
int nb = (su_h[s] + bs - 1) / bs;
if (nb > max_blocks) nb = max_blocks;
for (int b = 0; b < nb; ++b) {
int blk = bt_h[(size_t)s * max_blocks + b];
if (blk < 0) continue;
bool seen = false;
for (int u : used) if (u == blk) { seen = true; break; }
if (!seen) used.push_back(blk);
}
}
fprintf(stderr, "[VERIFY attn_%s] P2 used_n=%zu used0=%d\n", is_decode ? "decode" : "prefill", used.size(), used.empty() ? -1 : used[0]);
/* The cache DtoH copy faults (host page table unmapped). Read the used blocks via a DEVICE copy
* kernel (the device page table IS mapped -- the store kernel wrote the cache fine) into a
* regular allocation, then DtoH that. TEMP (degenerate-output investigation). */
const size_t per_bytes = (size_t)r->kv_block_stride * (size_t)ew;
std::vector<uint8_t> kv_h(used.size() * per_bytes);
{
uint8_t* reg = nullptr;
if (hipMalloc(&reg, kv_h.size()) == hipSuccess && reg) {
for (size_t i = 0; i < used.size(); ++i)
r4d_copy8_kernel<<<(unsigned)((per_bytes + 255) / 256), 256>>>(
(const uint8_t*)r->kv + (size_t)used[i] * per_bytes, reg + i * per_bytes, per_bytes);
hipDeviceSynchronize();
hipMemcpy(kv_h.data(), reg, kv_h.size(), hipMemcpyDeviceToHost);
hipFree(reg);
}
}
fprintf(stderr, "[VERIFY attn_%s] P3 kv_h done bytes=%zu\n", is_decode ? "decode" : "prefill", kv_h.size());
auto blkidx = [&](int blk) -> int {
for (size_t i = 0; i < used.size(); ++i) if (used[i] == blk) return (int)i;
return -1;
};
std::vector<uint16_t> qh((size_t)total_q * (size_t)q_heads * (size_t)hd);
hipMemcpy(qh.data(), r->q, qh.size() * 2, hipMemcpyDeviceToHost);
fprintf(stderr, "[VERIFY attn_%s] P4 qh done bytes=%zu\n", is_decode ? "decode" : "prefill", qh.size() * 2);
std::vector<uint16_t> oh((size_t)total_q * (size_t)q_heads * (size_t)hd);
hipMemcpy(oh.data(), r->out, oh.size() * 2, hipMemcpyDeviceToHost);
fprintf(stderr, "[VERIFY attn_%s] P5 oh done bytes=%zu\n", is_decode ? "decode" : "prefill", oh.size() * 2);
float maxq = 0.0f;
for (size_t i = 0; i < qh.size(); ++i) { float a = fabsf(attn_verify_bf16(qh[i])); if (a > maxq) maxq = a; }
/* Cap the host recompute so a large prefill (total_q * ctx big) cannot stall the server; the
* decode band (total_q 1) is always well under it. */
int ctx_max = 0;
for (int s = 0; s < num_seqs; ++s) if (su_h[s] > ctx_max) ctx_max = su_h[s];
const long long work = (long long)total_q * (long long)q_heads * (long long)ctx_max * (long long)hd;
if (work > 200000000LL) {
fprintf(stderr, "[VERIFY attn_%s] SKIPPED (work=%lld>cap) seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d win=%d scale=%.3g maxq=%.6g\n",
is_decode ? "decode" : "prefill", work, num_seqs, q_len, total_q, q_heads, kv_heads,
hd, r->window, r->scale, maxq);
return;
}
float maxd = 0.0f; int bad = 0, ntot = 0;
for (int t = 0; t < total_q; ++t) {
int seq = 0, i = 0, ctx = 0, qlen_seq = 0;
if (ragged) {
for (int s = 0; s < num_seqs; ++s)
if (t >= cu_h[s] && t < cu_h[s + 1]) { seq = s; break; }
i = t - cu_h[seq];
ctx = su_h[seq];
qlen_seq = cu_h[seq + 1] - cu_h[seq];
} else {
seq = t / q_len;
i = t % q_len;
ctx = su_h[seq];
qlen_seq = q_len;
}
const int pos = ctx - qlen_seq + i;
for (int h = 0; h < q_heads; ++h) {
const int kh = h / gqa;
const float kds = r->k_descale ? kds_h[seq * kv_heads + kh] : 1.0f;
const float vds = r->v_descale ? vds_h[seq * kv_heads + kh] : 1.0f;
auto visible = [&](int j) -> bool {
if (r->causal) {
if (j > pos) return false;
if (r->window > 0 && (pos - j) >= r->window) return false;
} else {
if (j >= ctx) return false;
if (r->window > 0) { int d = pos - j; if (d >= r->window || d <= -r->window) return false; }
}
return true;
};
auto kdot = [&](int j, int idx) -> float {
float dot = 0.0f;
for (int d = 0; d < hd; ++d) {
const long off = (long)idx * r->kv_block_stride + (long)kh * r->kv_head_stride
+ (long)(j % bs) * 2 * hd + d;
const uint8_t* p = kv_h.data() + off * ew;
float k = kv_is_fp8 ? attn_verify_e4m3(p[0]) : attn_verify_bf16(*(const uint16_t*)p);
dot += attn_verify_bf16(qh[(size_t)t * q_heads * hd + (size_t)h * hd + d]) * (k * kds);
}
return dot * r->scale;
};
float mx = -INFINITY;
for (int j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / bs >= max_blocks) break;
int blk = bt_h[(size_t)seq * max_blocks + (j / bs)];
if (blk < 0) continue;
int idx = blkidx(blk);
if (idx < 0) continue;
float dot = kdot(j, idx);
if (dot > mx) mx = dot;
}
std::vector<float> ref(hd, 0.0f);
if (mx != -INFINITY) {
float sum = 0.0f;
for (int j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / bs >= max_blocks) break;
int blk = bt_h[(size_t)seq * max_blocks + (j / bs)];
if (blk < 0) continue;
int idx = blkidx(blk);
if (idx < 0) continue;
float dot = kdot(j, idx);
const float w = std::exp(dot - mx);
sum += w;
for (int d = 0; d < hd; ++d) {
const long off = (long)idx * r->kv_block_stride + (long)kh * r->kv_head_stride
+ (long)(j % bs) * 2 * hd + hd + d;
const uint8_t* p = kv_h.data() + off * ew;
float v = kv_is_fp8 ? attn_verify_e4m3(p[0]) : attn_verify_bf16(*(const uint16_t*)p);
ref[d] += w * (v * vds);
}
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int d = 0; d < hd; ++d) ref[d] *= inv;
}
for (int d = 0; d < hd; ++d) {
float dv = fabsf(attn_verify_bf16(oh[(size_t)t * q_heads * hd + (size_t)h * hd + d]) - ref[d]);
if (dv > maxd) maxd = dv;
if (dv > 1e-2f) bad++;
ntot++;
}
}
}
fprintf(stderr, "[VERIFY attn_%s] seqs=%d q_len=%d tot_q=%d qh=%d kvh=%d hd=%d bs=%d mb=%d win=%d caus=%d scale=%.3g maxd=%.6g bad=%d/%d maxq=%.6g\n",
is_decode ? "decode" : "prefill", num_seqs, q_len, total_q, q_heads, kv_heads, hd, bs,
max_blocks, r->window, r->causal, r->scale, maxd, bad, ntot, maxq);
if (*cnt == 1) {
fprintf(stderr, " q :"); for (int d = 0; d < 8 && d < hd; ++d) fprintf(stderr, " %g", attn_verify_bf16(qh[d]));
fprintf(stderr, " out:"); for (int d = 0; d < 8 && d < hd; ++d) fprintf(stderr, " %g", attn_verify_bf16(oh[d]));
fprintf(stderr, "\n");
}
}
namespace {
// DEBUG (env-gated, R4D_VERIFY_OFF=1): run the device kernel, then recompute the same op on the
// host (the libref formula, f32) from the bf16 input the kernel read, and report the max deviation.
// A deviation well above the bf16 rounding (~1e-3) means the device kernel is wrong for the real
// shape; a deviation at the bf16 rounding means it is correct. Only the first few calls are
// checked. OFF by default: the DtoH syncs inside perturb stream timing, which the KV-isolation
// investigation cannot afford.
int r4d_verify_on() {
static int on = -1;
if (on < 0) { const char* e = std::getenv("R4D_VERIFY_OFF"); on = (e && *e) ? 1 : 0; }
return on;
}
int g_rmsnorm_p_verify_n = 0;
int g_gelu_mul_verify_n = 0;
// The CORRECT bf16 -> f32 decode: the 16-bit pattern is the high half of the f32 bits. (Casting a
// uint16_t to float gives the integer value of the pattern, 0..65535, which is NOT the value.)
static float bf16_to_f32(uint16_t b) {
uint32_t u = (uint32_t)b << 16;
float f;
std::memcpy(&f, &u, 4);
return f;
}
void verify_rmsnorm_p(const uint16_t* x, const uint16_t* y, int M, int n, int x_ld, int y_ld,
float eps, long stream) {
if (!r4d_verify_on() || g_rmsnorm_p_verify_n >= 4) return;
g_rmsnorm_p_verify_n++;
/* SYNC BEFORE ANY DtoH COPY: the input `x` is the output of an earlier GEMM on `stream`, and a
* subsequent GEMM (launched after this verify returns) reuses the workspace and overwrites it.
* The DtoH copy below runs on the DEFAULT stream (concurrent with `stream`), so without this
* sync it can read `x` while the next GEMM is overwriting it -- a race that produced false
* O(1e37) "garbage" readings. Syncing `stream` first guarantees the producer GEMM + this kernel
* have completed and the consumer GEMM has not yet been launched. */
hipStreamSynchronize((hipStream_t)stream);
std::vector<uint16_t> xh((size_t)M * (size_t)x_ld);
hipMemcpy(xh.data(), x, (size_t)M * (size_t)x_ld * 2, hipMemcpyDeviceToHost);
std::vector<float> xf((size_t)M * (size_t)x_ld);
for (size_t i = 0; i < xf.size(); ++i) xf[i] = bf16_to_f32(xh[i]);
std::vector<float> ref((size_t)M * (size_t)y_ld);
for (int m = 0; m < M; ++m) {
float ss = 0.0f;
for (int i = 0; i < n; ++i) { float v = xf[(size_t)m * (size_t)x_ld + i]; ss += v * v; }
float s = 1.0f / sqrtf(ss / (float)n + eps);
for (int i = 0; i < n; ++i)
ref[(size_t)m * (size_t)y_ld + i] = xf[(size_t)m * (size_t)x_ld + i] * s;
}
std::vector<uint16_t> yh((size_t)M * (size_t)y_ld);
hipMemcpy(yh.data(), y, (size_t)M * (size_t)y_ld * 2, hipMemcpyDeviceToHost);
float maxd = 0.0f; int bad = 0;
float maxin = 0.0f;
for (size_t i = 0; i < xf.size(); ++i) { float a = fabsf(xf[i]); if (a > maxin) maxin = a; }
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
float d = fabsf(bf16_to_f32(yh[(size_t)m * (size_t)y_ld + i]) - ref[(size_t)m * (size_t)y_ld + i]);
if (d > maxd) maxd = d;
if (d > 1e-2f) bad++;
}
// sample: first 8 input, first 8 device-out, first 8 ref (all as f32); maxin = max-abs of the input (realistic ~O(1) vs GARBAGE ~O(1e37))
fprintf(stderr, "[VERIFY rmsnorm_p] M=%d n=%d x_ld=%d y_ld=%d eps=%.3g maxd=%.6g bad=%d/%d maxin=%.6g\n",
M, n, x_ld, y_ld, eps, maxd, bad, M * n, maxin);
if (g_rmsnorm_p_verify_n == 1) {
fprintf(stderr, " in :"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", xf[i]);
fprintf(stderr, " out:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(yh[i]));
fprintf(stderr, " ref:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", ref[i]);
fprintf(stderr, "\n");
}
}
void verify_gelu_mul(const uint16_t* gu, const uint16_t* y, int M, int n, int gu_ld, int y_ld,
long stream) {
if (!r4d_verify_on() || g_gelu_mul_verify_n >= 4) return;
g_gelu_mul_verify_n++;
/* SYNC BEFORE ANY DtoH COPY (see verify_rmsnorm_p): the input `gu` is the output of the
* gate_up GEMM on `stream`, and a subsequent GEMM reuses the workspace and overwrites it.
* The DtoH copy below runs on the DEFAULT stream (concurrent with `stream`), so without this
* sync it can read `gu` while the next GEMM is overwriting it -- a race that produced false
* O(1e37) "garbage" readings. Syncing `stream` first guarantees the gate_up GEMM + this kernel
* have completed and the consumer GEMM has not yet been launched. */
hipStreamSynchronize((hipStream_t)stream);
std::vector<uint16_t> guh((size_t)M * (size_t)gu_ld);
hipMemcpy(guh.data(), gu, (size_t)M * (size_t)gu_ld * 2, hipMemcpyDeviceToHost);
std::vector<float> ref((size_t)M * (size_t)y_ld);
const double k0 = 0.7978845608028654, k1 = 0.044715;
for (int m = 0; m < M; ++m)
for (int i = 0; i < n; ++i) {
double g = (double)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + i]);
double u = (double)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + n + i]);
ref[(size_t)m * (size_t)y_ld + i] = (float)(0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g))) * u);
}
std::vector<uint16_t> yh((size_t)M * (size_t)y_ld);
hipMemcpy(yh.data(), y, (size_t)M * (size_t)y_ld * 2, hipMemcpyDeviceToHost);
float maxd = 0.0f; int bad = 0;
float maxg = 0.0f;
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
float a = fabsf((float)bf16_to_f32(guh[(size_t)m * (size_t)gu_ld + i]));
if (a > maxg) maxg = a;
}
for (int m = 0; m < M; ++m) for (int i = 0; i < n; ++i) {
float d = fabsf(bf16_to_f32(yh[(size_t)m * (size_t)y_ld + i]) - ref[(size_t)m * (size_t)y_ld + i]);
if (d > maxd) maxd = d;
if (d > 1e-2f) bad++;
}
/* maxg = max-abs of the gate (first half of gu): realistic ~O(1) vs GARBAGE ~O(1e37). If maxg is
* now realistic after the sync-before-copy fix, the O(1e37) readings were a verify artifact
* (a race with a subsequent GEMM overwriting the workspace). If maxg is still ~O(1e37), the
* gate_up GEMM is genuinely producing garbage. */
fprintf(stderr, "[VERIFY gelu_mul] M=%d n=%d gu_ld=%d y_ld=%d maxd=%.6g bad=%d/%d maxg=%.6g\n",
M, n, gu_ld, y_ld, maxd, bad, M * n, maxg);
if (g_gelu_mul_verify_n == 1) {
fprintf(stderr, " g :"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(guh[i]));
fprintf(stderr, " out:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", bf16_to_f32(yh[i]));
fprintf(stderr, " ref:"); for (int i = 0; i < 8 && i < n; ++i) fprintf(stderr, " %g", ref[i]);
fprintf(stderr, "\n");
}
}
constexpr uint32_t kWave = 32;
constexpr uint32_t kThreads = 256;
constexpr uint32_t kWaves = kThreads / kWave;
@@ -152,7 +503,7 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
else dst[0] = 0;
return;
}
const float s = !sc ? 1.0f : sc_f32 ? *(const float*)sc : bf16_to_f32(*(const uint16_t*)sc);
const float s = !sc ? 1.0f : sc_f32 ? *(const float*)sc : bf2f(*(const uint16_t*)sc);
const size_t at = (size_t)id * n_embd + j;
float v[V];
if constexpr (Q && V == 4) {
@@ -163,10 +514,10 @@ __global__ __launch_bounds__(kThreads) void embed_lookup_q_kernel(
v[0] = r4d_fp8::e4m3(((const uint8_t*)wte)[at]);
} else if constexpr (V == 4) {
const uint2 b = *(const uint2*)((const uint16_t*)wte + at);
v[0] = bf16_to_f32((uint16_t)b.x); v[1] = bf16_to_f32((uint16_t)(b.x >> 16));
v[2] = bf16_to_f32((uint16_t)b.y); v[3] = bf16_to_f32((uint16_t)(b.y >> 16));
v[0] = bf2f((uint16_t)b.x); v[1] = bf2f((uint16_t)(b.x >> 16));
v[2] = bf2f((uint16_t)b.y); v[3] = bf2f((uint16_t)(b.y >> 16));
} else {
v[0] = bf16_to_f32(((const uint16_t*)wte)[at]);
v[0] = bf2f(((const uint16_t*)wte)[at]);
}
if constexpr (V == 4) {
*(uint2*)dst = make_uint2(
@@ -273,6 +624,29 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel(
}
}
// ---------------------------------------------------------------------------- rmsnorm_p
// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain.
// It is the weightless value normalisation Gemma's attention uses on V (llama.cpp's
// ggml_rms_norm(V, eps), no tensor); there is no checkpoint plane to feed a gain through, so an
// rmsnorm call would need a phantom all-zero weight. Two passes over the row, the sum of squares
// in f32; the second pass drops the gain multiply rmsnorm has. The mean accumulates in f32 in
// ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's
// gain happens to be one.
__global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) {
__shared__ float lds[kThreads / kWave];
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf2f(xr[i]); ss += v * v; }
ss = block_sum<kThreads / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(bf2f(xr[i]) * s);
}
// ---------------------------------------------------------------------------- add / mul
// ref_add / ref_mul, including THE ONE BROADCAST RULE: an operand carrying exactly n elements
// against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is
@@ -310,6 +684,53 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel(
yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i]))));
}
// ---------------------------------------------------------------------------- logit_softcap
// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output,
// and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n.
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel(
const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap));
}
/* The f32 leg: the 1.3.0 sampling chain carries the logits in f32 from the gemm, so the softcap
* is issued against f32 rows. The same row-with-pitch shape as the bf16 leg, and the math is the
* op's definition verbatim -- no rounding pass, the buffer already holds the arithmetic dtype. */
__global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32(
const float* __restrict__ x, float* __restrict__ y,
uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const float* __restrict__ xr = x + (size_t)m * x_ld;
float* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = cap * tanhf(xr[i] / cap);
}
// ---------------------------------------------------------------------------- scale
// ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH
// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at
// the end of every layer (the per-layer scalar), and the pitch form costs nothing on a contiguous
// buffer -- it is x_ld == n. The scalar is read once per block (a single load, cached), not per
// element: a per-element reload of a [1] tensor is the same value every time and costs a load per
// element. `s` is f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint); the branch is
// on its dtype, so the op is dtype-generic in the scalar and the bf16 kernel is the residual
// stream's, which is what a served Gemma 4 issues it against.
__global__ __launch_bounds__(kThreads) void scale_kernel(
const uint16_t* __restrict__ x, const void* __restrict__ s, uint32_t s_dt,
uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf2f(((const uint16_t*)s)[0]);
const uint16_t* __restrict__ xr = x + (size_t)m * x_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads)
yr[i] = f32_to_bf16(bf2f(xr[i]) * sv);
}
// ---------------------------------------------------------------------------- silu_mul
// ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is
// the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot
@@ -326,6 +747,26 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
}
}
// ---------------------------------------------------------------------------- gelu_mul
// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, the
// same order-lock as silu_mul. The tanh-approx GELU (gemma's gelu_pytorch_tanh), NOT the erf one:
// gated feed-forwards are trained with the tanh form, and the constants are the standard fit the
// gemm_nt_bias "gelu_tanh" epilogue uses (the identical function, so a GELU-gated FFN and a
// tanh-gelu epilogue agree to the last bit).
__global__ __launch_bounds__(kThreads) void gelu_mul_kernel(
const uint16_t* __restrict__ gu, uint16_t* __restrict__ y,
uint32_t n, uint32_t gu_ld, uint32_t y_ld) {
const uint32_t m = blockIdx.x;
const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld;
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
for (uint32_t i = threadIdx.x; i < n; i += kThreads) {
const float g = bf2f(gr[i]);
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g)));
yr[i] = f32_to_bf16(gelu * bf2f(gr[n + i]));
}
}
// ---------------------------------------------------------------------------- rope
// ref_rope, in place over a fused [n_head + 2*n_head_kv] head row -- the V heads at the end are
// left alone, which is the whole reason the op takes the fused projection rather than two tensors.
@@ -337,8 +778,10 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel(
// (rad_block_attn_gated.h says so and says what would have to change first), so the shim maps it.
//
// PARTIAL ROTARY. `rot` may be less than head_dim -- 64 of 256 on this target -- and the tail of
// the head is untouched. The frequency exponent divides by `rot`, not by head_dim: the rotated
// prefix is a complete rotary of its own width.
// the head is untouched. The base ladder's exponent divides by `den`, which `ladder` resolves:
// `rot` for `rotary` (the rotated prefix, a complete rotary of its own width) and `head_dim` for
// `head` (the proportional variant, a prefix of the full-width table). `den` = `rot` on the
// default path, so existing models are bit-for-bit unchanged.
//
// One thread a PAIR. The pair's two loads and two stores are the whole body, so there is no
// reduction and no LDS; the grid is (M, heads).
@@ -362,7 +805,7 @@ __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, i
__global__ __launch_bounds__(kThreads) void rope_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int den, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
const uint32_t m = blockIdx.x;
@@ -375,7 +818,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
t += kThreads * gridDim.y) {
const uint32_t h = t / half, i = t % half;
uint16_t* __restrict__ hd = qkv + (size_t)m * row_pitch + (size_t)h * head_dim;
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
float p = p0;
if (plane) {
uint32_t j = i;
@@ -621,6 +1064,13 @@ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, cons
return rc == RAD_OK ? 0 : -4;
}
extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd,
int n_vocab, int vocab_off, int x_ld, float scale,
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, scale, sk);
}
static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows,
int x_ld, int y_ld, const R4dSink& sk) {
if (!x || !idx || !y) return -1;
@@ -717,6 +1167,22 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps,
return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream);
}
// The weightless norm: rmsnorm without the gain multiply. It is not templated on a thread count
// the way rmsnorm is, because rmsnorm's width is pinned to the fused rmsnorm_quant_fp8 by their
// shared byte-identical requirement, and rmsnorm_p has no fused quantiser counterpart to match --
// kThreads is the same choice the other non-templated row kernels (binary, sigmoid, silu_mul) make.
extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps,
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;
hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// `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.
@@ -771,6 +1237,48 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap,
int x_ld, int y_ld, long stream) {
if (!x || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!(cap > 0.0f)) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const float*)x, (float*)y, (uint32_t)n, cap,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n,
int x_ld, int y_ld, long stream) {
if (!x || !s || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (s_dt != RAD_F32 && s_dt != RAD_BF16) return -3;
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(scale_kernel, dim3((uint32_t)M), dim3(kThreads), 0,
(hipStream_t)stream,
(const uint16_t*)x, (const void*)s, s_dt, (uint16_t*)y, (uint32_t)n,
(uint32_t)x_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
@@ -782,19 +1290,35 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// GELU-gated product, the gemma FFN activation. Same shape and order-lock as silu_mul (the gate
// is the first half of the fused [M, 2n] row); the only difference is the nonlinearity, which is
// the tanh approximation, not the erf one, to match ref_gelu_mul's act_gelu_tanh.
extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) {
if (!gu || !y) return -1;
if (M <= 0 || n <= 0) return -2;
if (!gu_ld) gu_ld = 2 * n;
if (!y_ld) y_ld = n;
hipLaunchKernelGGL(gelu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)gu, (uint16_t*)y, (uint32_t)n,
(uint32_t)gu_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// `n_rope_heads` is n_head + n_head_kv: the Q heads and the K heads of a fused projection, or just
// the one buffer's heads when q and k are separate tensors (which is what the gated block does).
extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
long stream) {
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale,
return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, rot, gptj, theta, rscale,
row_pitch, 0, nullptr, 0, 0, stream);
}
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
// below and the op without YaRN run the same arithmetic with the same arguments.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
// below and the op without YaRN run the same arithmetic with the same arguments. `den` is the
// ladder's width (`rot` for `rotary`, `head_dim` for `head`) -- the multi-component form passes
// the caller's, and the plain entry passes `rot`, as it always has.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
if (!qkv || !pos) return -1;
@@ -807,7 +1331,7 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0;
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
(uint32_t)n_rope_heads, (uint32_t)rot, (int)den, gptj, theta, rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -815,10 +1339,24 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
mode, sec, n_sec, plane, RadYarn{}, stream);
int rot, int den, int gptj, float theta, float rscale,
int row_pitch, int mode, const int* sec, int n_sec, int plane,
long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, den, gptj, theta, rscale,
row_pitch, mode, sec, n_sec, plane, RadYarn{}, stream);
}
// Copy n bf16 from a (possibly host-page-table-unmapped) device VA into a regular allocation.
// The device kernel reads via the DEVICE page table (mapped); a host DtoH copy on such a VA faults.
__global__ void r4d_kv_copy_kernel(const uint16_t* __restrict__ src, uint16_t* __restrict__ dst, size_t n) {
for (size_t i = blockIdx.x * (size_t)kThreads + threadIdx.x; i < n;
i += (size_t)gridDim.x * kThreads)
dst[i] = src[i];
}
__global__ void r4d_kv_copy8_kernel(const uint8_t* __restrict__ src, uint8_t* __restrict__ dst, size_t n) {
for (size_t i = blockIdx.x * (size_t)kThreads + threadIdx.x; i < n;
i += (size_t)gridDim.x * kThreads)
dst[i] = src[i];
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
@@ -840,6 +1378,57 @@ extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int
(const uint16_t*)k, (const uint16_t*)v, (const int32_t*)slot,
(uint16_t*)kv, (uint32_t)head_dim, (uint32_t)kv_heads,
(uint32_t)block_size, (uint32_t)n_blocks, (uint32_t)k_ld, (uint32_t)v_ld);
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): the store-populate check. ====
* Established: kv/k/v/slot are DEVICE pointers; the store kernel launches+completes clean;
* a DtoH copy from `slot` succeeds but a DtoH copy from `kv` FAULTS; kv is not a VMM allocation
* (hipMemRetainAllocationHandle=invalid). Coherent reading: the cache is mapped in the DEVICE
* page table (device kernels read/write it fine -> the model runs) and NOT in the HOST page
* table (host copies fault). So the model's cache is fine; the degenerate output is a forward
* bug. To confirm the store kernel POPULATED the cache, read it via a DEVICE copy kernel (the
* device page table is mapped -> succeeds) into a regular allocation, then DtoH that regular
* buffer. Compare the cached K against the store kernel's input k. Gated: R4D_DIAG=1. */
if (r4d_diag_on()) {
static int s_kvchk = 0;
if (s_kvchk < 2) {
++s_kvchk;
hipDeviceSynchronize();
const size_t blk_elems = (size_t)kv_heads * block_size * 2 * head_dim; // stride[0]
uint16_t* reg = nullptr;
hipError_t am = hipMalloc(&reg, blk_elems * 2);
fprintf(stderr, "[KVCHK] call=%d M=%d hd=%d kvh=%d bs=%d nb=%d kld=%d vld=%d malloc=%d reg=%p\n",
s_kvchk, M, head_dim, kv_heads, block_size, n_blocks, k_ld, v_ld, (int)am, (void*)reg);
fflush(stderr);
if (am == hipSuccess && reg) {
r4d_kv_copy_kernel<<<(unsigned)((blk_elems + kThreads - 1) / kThreads), kThreads>>>(
(const uint16_t*)kv, reg, blk_elems);
hipError_t cs = hipDeviceSynchronize();
std::vector<uint16_t> kv_h(blk_elems);
hipError_t kc = hipMemcpy(kv_h.data(), reg, blk_elems * 2, hipMemcpyDeviceToHost);
fprintf(stderr, "[KVCHK] call=%d devcopy_sync=%d kvcopy=%d\n", s_kvchk, (int)cs, (int)kc);
fflush(stderr);
if (cs == hipSuccess && kc == hipSuccess) {
std::vector<int32_t> slot_h(M);
hipMemcpy(slot_h.data(), (const int32_t*)(uintptr_t)slot, M * 4, hipMemcpyDeviceToHost);
std::vector<uint16_t> k_h((size_t)M * k_ld);
hipMemcpy(k_h.data(), (const uint16_t*)(uintptr_t)k, k_h.size() * 2, hipMemcpyDeviceToHost);
for (int t = 0; t < M && t < 6; ++t) {
int s = slot_h[t];
if (s < 0) continue;
const int blk = s / block_size, off = s % block_size;
const size_t base = ((size_t)blk * kv_heads * block_size + (size_t)off) * 2 * head_dim;
if (base + 2 * head_dim > kv_h.size()) break;
fprintf(stderr, "[KVCHK] call=%d t=%d slot=%d blk=%d off=%d cacheK[0..3]=", s_kvchk, t, s, blk, off);
for (int i = 0; i < 4; ++i) fprintf(stderr, " %.4f", attn_verify_bf16(kv_h[base + i]));
fprintf(stderr, " inputK[0..3]=");
for (int i = 0; i < 4; ++i) fprintf(stderr, " %.4f", attn_verify_bf16(k_h[(size_t)t * k_ld + i]));
fprintf(stderr, "\n");
}
fflush(stderr);
}
}
if (reg) hipFree(reg);
}
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -956,6 +1545,53 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N,
hipLaunchKernelGGL(logits_gemm_kernel, dim3((uint32_t)N), dim3(kThreads), 0,
(hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)w, (float*)c,
(uint32_t)M, (uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)c_ld);
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): is the final hidden state featureless? ====
* KV store + attention verified fine; the logits are near-flat (top-5 within a few points) ->
* a near-constant hidden state would make every logit the same. a is a regular device buffer
* (DtoH succeeds). Dump per-row mean/std over K + a few elements: std~0 = featureless (forward
* collapses); std large = hidden state varies and the flat logits come from elsewhere.
* Gated: R4D_DIAG=1. */
if (r4d_diag_on()) {
static int s_hidd = 0;
if (s_hidd < 2) {
++s_hidd;
hipDeviceSynchronize();
const int M1 = (M < 2) ? M : 2;
std::vector<uint16_t> a_h((size_t)M1 * a_ld);
hipMemcpy(a_h.data(), (const uint16_t*)a, a_h.size() * 2, hipMemcpyDeviceToHost);
for (int r = 0; r < M1; ++r) {
double s = 0, s2 = 0;
for (int d = 0; d < K; ++d) { double v = attn_verify_bf16(a_h[(size_t)r * a_ld + d]); s += v; s2 += v * v; }
const double mean = s / K, var = s2 / K - mean * mean;
fprintf(stderr, "[HIDD] call=%d M=%d K=%d r=%d mean=%.4f std=%.4f a[0..7]=", s_hidd, M, K, r, mean, sqrt(var));
for (int d = 0; d < 8 && d < K; ++d) fprintf(stderr, " %.4f", attn_verify_bf16(a_h[(size_t)r * a_ld + d]));
fprintf(stderr, "\n");
}
fflush(stderr);
}
}
/* ==== TEMP DIAGNOSTIC (degenerate-output investigation): the logits-GEMM output. ====
* Hidden state verified RICH (std~4.6). A rich hidden state + a correct logits GEMM => sharp
* logits; observed logits are near-flat (top-5 within a few points). Dump c (f32, regular
* buffer, DtoH succeeds): mean/std over the full vocab + max/argmax. std~0 => GEMM output flat
* (kernel bug); std large => GEMM fine and the sampler/softcap downstream is the suspect.
* Gated: R4D_DIAG=1. */
if (r4d_diag_on()) {
static int s_log = 0;
if (s_log < 2) {
++s_log;
hipDeviceSynchronize();
std::vector<float> c_h((size_t)N);
hipMemcpy(c_h.data(), (const float*)c, (size_t)N * 4, hipMemcpyDeviceToHost);
long double s = 0, s2 = 0; float mx = -1e30f; int mi = 0;
for (int j = 0; j < N; ++j) { const double v = c_h[j]; s += v; s2 += v * v; if (c_h[j] > mx) { mx = c_h[j]; mi = j; } }
const double mean = (double)(s / N), var = (double)(s2 / N) - mean * mean;
fprintf(stderr, "[LOGITS] call=%d c=%p N=%d ld=%d mean=%.4f std=%.4f max=%.4f argmax=%d c[0..7]=", s_log, (void*)(uintptr_t)c, N, c_ld, mean, sqrt(var), mx, mi);
for (int j = 0; j < 8 && j < N; ++j) fprintf(stderr, " %.4f", c_h[j]);
fprintf(stderr, "\n");
fflush(stderr);
}
}
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -1263,6 +1899,32 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) {
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ rmsnorm_p */
extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
const long long n = r4d_geti_or(a, "n", r4d_dim(x, (int)x->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
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);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const int rc = r4d_rmsnorm_p_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, eps,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
if (rc != 0) return RAD_E_DEVICE;
verify_rmsnorm_p((const uint16_t*)(uintptr_t)r4d_addr(x), (const uint16_t*)(uintptr_t)r4d_addr(y),
(int)M, (int)n, (int)x_ld, (int)y_ld, eps, (long)(uintptr_t)s);
return RAD_OK;
}
/* ------------------------------------------------------------------ add / mul */
enum { BI_A = 0, BI_B, BI_Y };
@@ -1375,6 +2037,76 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ logit_softcap */
extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!x || !y) return R4D_NO(RAD_E_INVAL);
/* Two legs, one op: bf16 (the logits buffer as the gemm writes it on the bf16 chain) and f32
* (the 1.3.0 sampling chain, where the gemm hands the sampler f32 rows). The dtype check
* moved from the entry to the call below because the legs differ, not the geometry. */
const bool leg_bf16 = (x->dtype == RAD_BF16) && (y->dtype == RAD_BF16);
const bool leg_f32 = (x->dtype == RAD_F32) && (y->dtype == RAD_F32);
if (!leg_bf16 && !leg_f32) return R4D_NO(RAD_E_DTYPE);
/* `cap` is where the model lives: Gemma 4 issues it at 30.0. The default exists for the same
* reason every other one here does (a direct call with no declare in front), and the `> 0`
* test is load-bearing: a zero cap is a division by zero in every lane, not a bad answer. */
const float cap = (float)r4d_getf(a, "cap", 30.0);
if (!(cap > 0.0f)) return R4D_NO(RAD_E_INVAL);
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against a column slice there is no contiguous
* extent to walk, and the contiguous case costs nothing. */
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, 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);
const int rc = leg_bf16
? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s)
: r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap,
(int)x_ld, (int)y_ld, (long)(uintptr_t)s);
return rc == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ scale */
extern "C" int r4d_rad_scale(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* sc = r4d_opt(a, 1);
const RadTensor* y = r4d_opt(a, 2);
if (!x || !sc || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(y));
/* `s` is a [1] weight, f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint). A
* scalar with no element is a shape error, not a broadcast of zero -- a zero scalar would be
* a plausible number, which is the thing the oracle rules out. Read on the device (the kernel
* reads s[0] once per block) rather than a host copy: a device-to-host copy of one element is
* a synchronisation on the step path, and the per-block read is cached. */
if (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
if (r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE);
/* ROW-WISE WITH A PITCH, same as sigmoid: issued against the residual stream at the end of a
* layer there is no contiguous extent to walk, and the contiguous case costs nothing. */
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, 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_scale_bf16(r4d_addr(x), r4d_addr(sc), sc->dtype, r4d_addr(y), (int)M, (int)n,
(int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ silu_mul */
extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
@@ -1396,6 +2128,31 @@ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) {
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ gelu_mul */
extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) {
const RadTensor* gu = r4d_opt(a, 0);
const RadTensor* y = r4d_opt(a, 1);
if (!gu || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(gu));
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, Mg = 0;
const long long y_ld = r4d_rows_pitch(y, n, &M);
const long long gu_ld = r4d_rows_pitch(gu, 2 * n, &Mg);
if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE);
const int rc = r4d_gelu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld,
(long)(uintptr_t)s);
if (rc != 0) return RAD_E_DEVICE;
verify_gelu_mul((const uint16_t*)(uintptr_t)r4d_addr(gu), (const uint16_t*)(uintptr_t)r4d_addr(y),
(int)M, (int)n, (int)gu_ld, (int)y_ld, (long)(uintptr_t)s);
return RAD_OK;
}
/* ------------------------------------------------------------------ rope */
enum { RP_QKV = 0, RP_POS };
@@ -1415,6 +2172,16 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
if (head_dim <= 0 || n_head <= 0) return R4D_NO(RAD_E_SHAPE);
if (rot <= 0 || rot > head_dim || (rot & 1)) return R4D_NO(RAD_E_SHAPE);
/* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the
* proportional variant. head_dim is already validated above, so `den = head_dim` is safe. */
const char* lad = r4d_gets(a, "ladder");
long long den = rot;
if (lad) {
if (!std::strcmp(lad, "head")) den = head_dim;
else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head"))
return R4D_NO(RAD_E_UNSUPPORTED);
}
/* THE MODE, and with it how many components a position has. With [M] positions -- one
* component a token -- mrope and imrope ARE neox: every frequency reads the same position and
* the ladder is the same. With [C, M] positions and `sections`, each frequency reads the
@@ -1465,9 +2232,10 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
* reason this op takes the fused projection rather than two tensors. */
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
(int)(n_head + n_head_kv), (int)rot, (int)den, gptj, theta, rscale,
(int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0
? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ kv_store */
+211 -6
View File
@@ -277,11 +277,13 @@ static const RadParamSpec pRopeTable[] = {
{ "rot", RAD_P_INT, RAD_REQUIRED },
P_F64("theta"),
P_F64("scale"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
{ "head_dim", RAD_P_INT, RAD_OPTIONAL }, /* needed only by the `head` ladder */
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
};
static const RadOperandSpec oRopeTable[] = {
{ "positions", RAD_OPD_IN, 0 },
@@ -1536,6 +1538,16 @@ static const RadParamSpec pMnDtype[] = {
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
/* `logit_softcap`'s, matched field for field to ref's `pMnCap` so the two plugins agree (spec
* §2.3). `cap` is required and must be > 0; a non-positive cap is a division by zero in every
* lane, so the op refuses it rather than answering with NaNs. */
static const RadParamSpec pMnCap[] = {
{ "M", RAD_P_INT, RAD_REQUIRED },
{ "n", RAD_P_INT, RAD_REQUIRED },
P_F64("cap"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
};
static const RadOperandSpec oBinary[] = {
{ "a", RAD_OPD_IN, 0 },
{ "b", RAD_OPD_IN, 0 },
@@ -1640,6 +1652,11 @@ static const RadParamSpec pFill[] = {
static const RadOperandSpec oFill[] = {
{ "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oScale[] = {
{ "x", RAD_OPD_IN, 0 },
{ "s", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
/* `cast`'s two dtype keys are STRINGS and not one `dtype`, because the whole point of the op is
* that the two ends differ. ref's spelling, matched field for field so the two plugins agree. */
static const RadParamSpec pCast[] = {
@@ -1674,6 +1691,7 @@ static const RadParamSpec pRope[] = {
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
{ "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */
};
/* ---------------------------------------------------------------------- the vision tower */
@@ -1738,7 +1756,7 @@ static const RadParamSpec pEmbed[] = {
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first GLOBAL row; vocab-parallel embedding */
/* The scale embed_lookup_q's layout quantises with. That op shares this parameter list and
* libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */
* libref fixes it for both, so it is spelled here to match. */
{ "wscale", RAD_P_F64, RAD_OPTIONAL },
};
/* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's
@@ -1944,6 +1962,11 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
"f32 after the load because forming it in bf16 first costs 0.3% per channel."),
SCHEMA("rmsnorm_p", pLayernorm, oUnary,
"y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. Gemma's "
"attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the "
"key with the k_norm gain in the same layer, which one op with a required gain cannot "
"express."),
SCHEMA("add", pMnDtype, oBinary,
"y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts "
"along rows, and nothing else broadcasts at all."),
@@ -1953,7 +1976,12 @@ static const RadOpSchema kSchemas[] = {
"(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."),
"which is the order rad-convert fuses gate_proj and up_proj in."),
SCHEMA("gelu_mul", pMnDtype, oGateUp,
"y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i], the tanh approximation "
"(gemma's gelu_pytorch_tanh), and the GATE IS THE FIRST HALF as in silu_mul. Its own "
"op, not gelu, because gated feed-forwards are trained with the tanh form and the "
"unary gelu is the exact erf one."),
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."),
@@ -1991,6 +2019,12 @@ static const RadOpSchema kSchemas[] = {
"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 "
"expects a defined buffer: a wire shared across layers cannot be zeroed once a step."),
SCHEMA("logit_softcap", pMnCap, oUnary,
"y = cap * tanh(x / cap); the final-logit softcap. `cap` is required and > 0."),
SCHEMA("scale", pMnDtype, oScale,
"y = x * s, s a [1] weight broadcast over every element; the per-tensor scalar "
"(per-layer scalar). `mul` broadcasts a row, `scale_rows` a column-per-row."),
SCHEMA("cast", pCast, oUnary,
"y = x, converted. `from` and `to` are for the selector; the bytes are described by the "
"tensors' own dtypes and those are what the kernel reads."),
@@ -2428,6 +2462,32 @@ static const RadConstraint cAttnDecodeH128Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense sliding window: head_dim 256, 2 queries per kv head, windowed decode
* (r4d_attn_paged_h256_gqa2.hip). window is a launch argument -- 1024 in the model, 0 = full
* attention -- so it is constrained on both sides like the drafter leg, not fixed. q_len <= 32 is
* the q_len*gqa <= 64 of the prose at gqa 2, and the bucket boundary that keeps prefill out. */
static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense sliding-window PREFILL (r4d_attn_paged_h256_gqa2.hip): the same geometry as the
* decode leg above, but no q_len bound -- it serves the prefill band (q_len > 32, the bucket the
* decode leg's C_LE leaves). window is a launch argument (1024 in the model) exactly as on the
* decode leg, so C_GE on both sides; the kernel's WIN bit masks the window and skips the below-
* window tiles. This was the band the decode-only leg left as a hole: a base-model prefill with no
* device kernel is fatal (spec §17 -- libref is an opt-in fallback the engine refuses by default). */
static const RadConstraint cAttnPrefillH256Gqa2Fp8[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = {
C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* EIGHT QUERIES PER KV HEAD, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is the
* `q_len * gqa <= 64` of the prose at gqa 8, and the difference from the gqa6 leg's 10 is the whole
* of what the ratio changes: a decode workgroup holds 64 rows and the verify width is how many of
@@ -2469,6 +2529,25 @@ static const RadConstraint cAttnDecodeH256G4Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* Gemma 4 dense GLOBAL layers: head_dim 512, 8 queries per KV head, full attention
* (r4d_attn_paged_h512_gqa8.hip). The `q_len <= 8` bound is the gqa verify width again; window
* stays 0, which is what separates this from the sliding leg and why it needs no windowed form. */
static const RadConstraint cAttnPrefillH512G8Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnPrefillH512G8Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cAttnDecodeH512G8Fp8[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
};
static const RadConstraint cAttnDecodeH512G8Bf16[] = {
C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16),
C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
};
/* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's
* QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two
* ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is
@@ -3381,6 +3460,7 @@ static const RadTunable tMv[] = {
* cannot match a query that forgot to say what it wanted -- the same reasoning cSampleChain gives.
* n_cand is bounded because the top-k's bitonic sort runs in LDS over a power-of-two padding. */
static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") };
static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") };
/* bf16 rows over the byte copy, which moves four bytes a thread: an even width. */
static const RadConstraint cBf16Row2[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
/* Opaque byte rows, four at a time. The width constraint is the vectorised copy's
@@ -3666,6 +3746,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr,
r4d_shape_rmsnorm },
{ "rmsnorm_p_bf16", "rmsnorm_p", "norm",
"weightless root-mean-square norm (no gain), two passes over the row",
"any n; the sum of squares accumulates in f32 and only the store narrows",
"bf16 x / y, fp32 reduction",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_rmsnorm_p, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "layernorm_bf16", "layernorm", "norm",
"layer norm with a gain and an optional bias, two passes over the row",
"any n; mean and variance accumulate in f32 and only the store narrows",
@@ -3739,6 +3828,33 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_sigmoid, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "logit_softcap_bf16", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"any extent; contiguous in and out",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "logit_softcap_f32", "logit_softcap", "elem",
"cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent",
"any extent; contiguous in and out",
"f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cF32Row), NOTUNE,
nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr,
r4d_shape_unary },
{ "scale_bf16", "scale", "elem",
"x * s, s a [1] weight broadcast over the whole extent, grid-strided",
"any extent; contiguous in and out",
"bf16 in and out, fp32 arithmetic, s f32 or bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
r4d_shape_scale },
{ "silu_mul_bf16", "silu_mul", "elem",
"silu-gated product over a fused [M, 2n] gate_up",
"any n; the gate is the first half",
@@ -3748,6 +3864,15 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_silu_mul, nullptr, nullptr, nullptr,
r4d_shape_silu_mul },
{ "gelu_mul_bf16", "gelu_mul", "elem",
"gelu-gated product over a fused [M, 2n] gate_up",
"any n; the gate is the first half",
"bf16 in and out, fp32 arithmetic",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_mul, nullptr, nullptr, nullptr,
r4d_shape_silu_mul },
{ "rope_bf16", "rope", "attn",
"rotary embedding in place, one thread a rotated pair",
"any head_dim; rotary_dim even and no wider than head_dim -- the frequency exponent divides by "
@@ -4021,6 +4146,48 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa2_fp8kv", "attn_paged", "attn",
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH256Gqa2Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa2_bf16kv", "attn_paged", "attn",
"paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)",
"head_dim 256, 2 queries per kv head, paged block 16, varlen, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH256Gqa2Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h256_gqa2_fp8kv", "attn_paged", "attn",
"paged causal attention with a sliding window, split-KV (decode / verify)",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_fp8, r4d_rad_attn_decode_h256_gqa2_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h256_gqa2_bf16kv", "attn_paged", "attn",
"paged causal attention with a sliding window, split-KV (decode / verify)",
"head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, "
"window taken from the launch argument (0 = full attention)",
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_bf16, r4d_rad_attn_decode_h256_gqa2_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 8 queries per kv head, paged block 16, varlen",
@@ -4097,6 +4264,44 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h512_gqa8_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH512G8Fp8), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_fp8, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h512_gqa8_bf16kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 512, 8 queries per kv head, paged block 16, varlen",
"bf16 query, bf16 kv cache, bf16 out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
ROW(cAttnPrefillH512G8Bf16), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_bf16, nullptr, nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h512_gqa8_fp8kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
"bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH512G8Fp8), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_fp8, r4d_rad_attn_decode_h512_gqa8_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_decode_h512_gqa8_bf16kv", "attn_paged", "attn",
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
"head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window",
"bf16 query, bf16 kv cache, bf16 out, f16 partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
ROW(cAttnDecodeH512G8Bf16), ROW(tAttnSplit), nullptr,
nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_bf16, r4d_rad_attn_decode_h512_gqa8_scratch,
nullptr, nullptr,
r4d_shape_attn_paged },
{ "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn",
"paged causal attention, query-tiled (prefill / chunked prefill)",
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
+35
View File
@@ -50,6 +50,9 @@
#include "r4d_common.h"
#include <cfloat>
#include <cstdio>
#include <cstdlib>
#include <vector>
// THE PARAMS ROW IS THE ENGINE'S STRUCT, not a restatement of it. Two independent declarations of
// one wire format drift, and the drift is silent: a sampler reading `top_p` out of `min_p`
@@ -1393,6 +1396,38 @@ extern "C" int r4d_rad_sample_argmax(const RadArgs* a, RadStream s) {
if (!tok) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_i32(tok));
if (!r4d_contig(tok) || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
/* DEBUG: dump the sampler's INPUT row 0 at the first two calls (prefill, then first decode),
* with the SAME fields as the [LOGITS] dump at the GEMM entry, plus the lg pointer + pitch, so
* the two dumps compare pointer-for-pointer and row-for-row in one run. Sync `s` first (the
* logits are produced by the logit_softcap op on `s`), then copy. Gated: R4D_DIAG=1.
* Findings: sampler input = the GEMM buffer (same pointer); softcap applied (43.02 -> 26.77 =
* 30*tanh(43.02/30)); true argmax 100 (prefill) / 45518 (decode) = the GEMM argmax. */
static const int r4d_sampin_on = std::getenv("R4D_DIAG") ? 1 : 0;
if (r4d_sampin_on) {
static int n = 0;
if (n < 2) {
n++;
hipStreamSynchronize((hipStream_t)(long)(uintptr_t)s);
const long lgp = r4d_addr(lg);
std::vector<float> lh((size_t)M * (size_t)ld);
hipMemcpy(lh.data(), (const void*)(uintptr_t)lgp, (size_t)M * (size_t)ld, hipMemcpyDeviceToHost);
long double s1 = 0, s2 = 0; float mx = -1e30f; int mi = 0;
for (long long v = 0; v < nv; ++v) { const double x = lh[v]; s1 += x; s2 += x * x; if (lh[v] > mx) { mx = lh[v]; mi = (int)v; } }
const double mean = (double)(s1 / nv), var = (double)(s2 / nv) - mean * mean;
int top[5] = {-1,-1,-1,-1,-1}; float tv[5] = {-1e30f,-1e30f,-1e30f,-1e30f,-1e30f};
for (long long v = 0; v < nv; ++v) {
float x = lh[v];
for (int i = 4; i >= 0; --i) { if (x > tv[i]) { if (i < 4) { tv[i+1] = tv[i]; top[i+1] = top[i]; } tv[i] = x; top[i] = (int)v; break; } }
}
fprintf(stderr, "[SAMPIN] call=%d lg=%p M=%lld nv=%lld ld=%lld row0 mean=%.4f std=%.4f max=%.4f argmax=%d top5:",
n, (void*)(uintptr_t)lgp, M, nv, ld, mean, sqrt(var), mx, mi);
for (int i = 0; i < 5; ++i) fprintf(stderr, " (%d,%.4f)", top[i], tv[i]);
fprintf(stderr, " row0[0..7]=");
for (long long v = 0; v < 8 && v < nv; ++v) fprintf(stderr, " %.4f", lh[v]);
fprintf(stderr, "\n");
fflush(stderr);
}
}
R4D_LAUNCH(r4d_sample_argmax_f32(r4d_addr(lg), r4d_addr(tok), (int)M, (int)nv, (int)ld,
(long)(uintptr_t)s));
}
+613 -2
View File
@@ -711,7 +711,7 @@ static const RadKernelInfo* find(const Plugin& pl, const char* name) {
/* ------------------------------------------------------------------ per-family smoke tests */
static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
int64_t q_len, const char* kv_dtype, int prefill) {
int64_t q_len, const char* kv_dtype, int prefill, int window = 0) {
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
@@ -743,7 +743,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6
absent(ts[6]);
std::vector<RadParam> ps = {
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
};
(void)prefill;
run_case(r, ts, ps);
@@ -824,6 +824,186 @@ static float h_e4m3(uint8_t b) {
return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7);
}
/* Two avalanche-random values for the numeric attention check: a bounded bf16 in [-1, 1] and an
* e4m3 code, each a function of its index so a wrong pitch or lane map reads unrelated numbers. */
static uint16_t st_rand_bf16(uint32_t i) {
const uint32_t x = st_mix32(i);
const float f = ((x & 0x00ffffffu) / 16777215.0f) * 2.0f - 1.0f;
return h_to_bf16(f);
}
static uint8_t st_rand_e4m3(uint32_t i) {
const uint32_t x = st_mix32(i + 0x9e3779b9u);
/* Bounded to [-1, 1] (the positive magnitudes below), mirroring st_rand_bf16. The full e4m3
* range (up to 448) makes the attention scores reach ~448*head_dim/sqrt(head_dim), so the
* softmax dominates by e^score and a 1-ulp difference between the device's v_cvt_f32_fp8 and
* this software h_e4m3 flips the max into a large output error; bounded, the scores stay ~22
* (the passing bf16 path) and the comparison is stable. */
static const uint8_t mag[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* subnormal, 0 .. 7/64 */
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, /* exp 4, 0.125 .. 0.234375 */
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, /* exp 5, 0.25 .. 0.46875 */
0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, /* exp 6, 0.5 .. 0.9375 */
0x38, /* exp 7, 1.0 */
};
const uint8_t m = mag[(x >> 1) % (sizeof mag / sizeof mag[0])];
return (uint8_t)(m | (((x >> 8) & 1u) << 7));
}
/* The inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the
* uniform batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales. The selftest does not link libref,
* so the reference the kbench byte-equality uses is carried here; the mask, the two-pass softmax
* and the k/v dequant are the same, so a wrong kernel fails the comparison. One (row, head) at a
* time: `i` is the query's position within its sequence's query, and `pos = ctx - qlen + i`. */
static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8,
int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh,
const int* block_table, int64_t max_blocks, int ctx,
float kds, float vds, int causal, int window, float scale,
int64_t qlen, int64_t i, float* out) {
const int ew = kv_is_fp8 ? 1 : 2;
const int64_t pos = ctx - qlen + i;
const int64_t sb = kv_heads * block_size * 2 * head_dim;
const int64_t sh = block_size * 2 * head_dim;
const int64_t so = 2 * head_dim;
const auto kslot = [&](int64_t blk, int64_t slot, int64_t d) {
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + d) * ew;
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
};
const auto vslot = [&](int64_t blk, int64_t slot, int64_t d) {
const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + head_dim + d) * ew;
return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p);
};
const auto visible = [&](int64_t j) {
if (causal ? (j > pos) : (j >= ctx)) return false;
if (window > 0) { const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return false; }
return true;
};
float mx = -INFINITY;
for (int64_t j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / block_size >= max_blocks) break;
int blk = block_table[j / block_size];
if (blk < 0) continue;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
dot *= scale;
if (dot > mx) mx = dot;
}
if (mx == -INFINITY) { for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f; return; }
float sum = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f;
for (int64_t j = 0; j < ctx; ++j) {
if (!visible(j)) continue;
if (j / block_size >= max_blocks) break;
int blk = block_table[j / block_size];
if (blk < 0) continue;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds);
const float w = std::exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d) out[d] += w * (vslot(blk, j % block_size, d) * vds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv;
}
/* The numeric attention check: fill q and the paged k/v with avalanche-random data, run the row,
* and compare the bf16 output against the inline oracle above. The launch smoke (attn_case) proves
* the kernel starts; this proves it computes. A negative control corrupts a share of the reference
* and requires the comparison to FAIL -- the proof the check has teeth. */
static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa,
int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) {
if (!sel(name)) return;
const RadKernelInfo* r = find(pl, name);
if (!r) { ok(name, false, "row absent"); return; }
const int64_t seqs = 1, kv_heads = 2, bs = 16;
const int64_t q_heads = kv_heads * gqa;
const int64_t max_blocks = ctx / bs;
const int64_t total_q = seqs * q_len;
const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0;
const uint32_t kvdt = kv_is_fp8 ? RAD_F8E4M3 : RAD_BF16;
const int ew = kv_is_fp8 ? 1 : 2;
const float scale = 1.0f / std::sqrt((float)head_dim);
std::vector<uint16_t> qh((size_t)total_q * q_heads * head_dim);
for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i);
const int64_t nelem = max_blocks * kv_heads * bs * 2 * head_dim;
std::vector<uint8_t> kv((size_t)nelem * ew);
for (int64_t e = 0; e < nelem; ++e) {
const size_t bo = (size_t)e * ew;
if (kv_is_fp8) kv[bo] = st_rand_e4m3(e);
else { const uint16_t h = st_rand_bf16(e); kv[bo] = (uint8_t)h; kv[bo + 1] = (uint8_t)(h >> 8); }
}
const std::vector<int32_t> bt = iota_i32(max_blocks);
void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2);
st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice);
void* d_kv = dalloc(kv.size());
st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice);
void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2);
std::vector<RadTensor> ts = {
T(d_q, RAD_BF16, { total_q, q_heads, head_dim }),
T(d_kv, kvdt, { max_blocks, kv_heads, bs, 2 * head_dim }),
TI32({ seqs, max_blocks }, bt),
TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)),
TF32({ seqs, kv_heads }, 1.0f),
TF32({ seqs, kv_heads }, 1.0f),
T(nullptr, RAD_I32, { seqs + 1 }),
T(d_out, RAD_BF16, { total_q, q_heads, head_dim }),
};
if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); }
absent(ts[6]);
std::vector<RadParam> ps = {
PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs),
PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype),
};
run_case(r, ts, ps);
std::vector<uint16_t> oh((size_t)total_q * q_heads * head_dim);
st_memcpy(oh.data(), d_out, oh.size() * 2, hipMemcpyDeviceToHost);
const float abs_tol = 1e-3f, rel_tol = 2e-2f;
std::vector<float> oref((size_t)total_q * q_heads * head_dim);
float max_err = 0.0f; int nbad = 0;
for (int64_t tok = 0; tok < total_q; ++tok)
for (int64_t h = 0; h < q_heads; ++h) {
const int64_t kh = h / gqa;
float o[512];
attn_oracle_one(&qh[(tok * q_heads + h) * head_dim], kv.data(), kv_is_fp8,
head_dim, kv_heads, bs, kh, bt.data(), max_blocks, ctx,
1.0f, 1.0f, 1, window, scale, q_len, tok, o);
for (int64_t d = 0; d < head_dim; ++d) {
const size_t idx = (size_t)(tok * q_heads + h) * head_dim + d;
oref[idx] = o[d];
const float got = h_bf16(oh[idx]);
const float diff = std::fabs(got - o[d]);
if (diff > abs_tol + rel_tol * std::fabs(o[d])) ++nbad;
if (diff > max_err) max_err = diff;
}
}
char nm[160];
std::snprintf(nm, sizeof nm, "%s numeric", name);
ok(nm, nbad == 0,
fmt("max_err=%.5g bad=%d/%d", max_err, nbad, (int)oref.size()));
/* Negative control: corrupt a share of the reference and require the comparison to FAIL -- the
* proof the check has teeth, since a broken (always-passing) comparison would flag nothing. */
for (size_t idx = 0; idx < oref.size(); ++idx)
if ((idx & 7) == 0) oref[idx] += 0.5f;
float nmax = 0.0f; int nbadc = 0;
for (size_t idx = 0; idx < oref.size(); ++idx) {
const float got = h_bf16(oh[idx]);
const float diff = std::fabs(got - oref[idx]);
if (diff > abs_tol + rel_tol * std::fabs(oref[idx])) ++nbadc;
if (diff > nmax) nmax = diff;
}
std::snprintf(nm, sizeof nm, "%s numeric-negctl", name);
ok(nm, nbadc > 0,
fmt("corrupted ref must fail: max_err=%.5g bad=%d", nmax, nbadc));
}
/* ================================================================== a weight's canonical planes
*
* A container holds a weight as the planes of its encoding, row-major (spec §4.1), and a kernel's
@@ -4107,6 +4287,375 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t
ok(nm, all, d);
}
/* logit_softcap, against an f64 evaluation of the same formula.
*
* THE CAP IS THE PARAMETER THE MODEL LIVES IN (Gemma 4's graph issues it at 30.0), so the case
* runs at two values: the model's, and a smaller one that moves every answer -- a kernel that
* hard-wires 30.0, or one that swaps `cap` with its inverse, passes one cap and fails the other.
*
* The inputs are 0, half, one, two and five TIMES THE CAP, signed: x/cap is then an exact small
* half-integer, the f64 oracle cap * tanh(x/cap) is five constants deep, and the only room for an
* error in the comparison is the kernel's own f32 arithmetic and its bf16 store. The tolerance is
* this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void logit_softcap_case(const Plugin& pl) {
const char* what = "logit_softcap vs an f64 evaluation of the same formula";
/* Both device legs run the case: bf16 (the gemm's own dtype) and f32 (the 1.3.0 sampling
* chain, where the logits reach the softcap as f32 rows). The f32 leg answers in the
* arithmetic dtype itself, so its oracle compare reads f32, not a bf16 round trip. */
for (const uint32_t dt : { (uint32_t)RAD_BF16, (uint32_t)RAD_F32 }) {
const char* row = dt == RAD_BF16 ? "logit_softcap_bf16" : "logit_softcap_f32";
const size_t es = dt == RAD_BF16 ? 2 : 4;
const RadKernelInfo* r = find(pl, row);
if (!r) { ok(what, false, std::string("row absent: ") + row); return; }
const int64_t M = 7, n = 128;
for (const double capd : { 30.0, 10.0 }) {
std::vector<uint16_t> xh((size_t)M * n);
std::vector<float> xf((size_t)M * n);
std::vector<double> want((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
const double xv = sgn * mag * capd;
xh[(size_t)i] = h_to_bf16((float)xv);
xf[(size_t)i] = (float)xv;
want[(size_t)i] = capd * std::tanh(xv / capd);
}
void* d_x = dalloc((size_t)(M * n) * es);
void* d_o = dalloc((size_t)(M * n) * es);
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, dt == RAD_BF16 ? (const void*)xh.data() : (const void*)xf.data(),
(size_t)(M * n) * es, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, dt, { M, n }),
T(d_o, dt, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n), PF("cap", capd) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " cap=" + std::to_string(capd));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
std::vector<float> gotf((size_t)(M * n));
st_memcpy(dt == RAD_BF16 ? (void*)got.data() : (void*)gotf.data(), d_o,
(size_t)(M * n) * es, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double v = dt == RAD_BF16 ? (double)h_bf16(got[(size_t)i])
: (double)gotf[(size_t)i];
const double e = v - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, std::string(row) + " cap=" + std::to_string(capd) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
}
/* rmsnorm_p, against an f64 evaluation of the weightless normalisation.
*
* THE EPS IS THE PARAMETER THE MODEL LIVES IN (Gemma 4 issues it at 1e-6), so the case runs at
* two values: the model's, and a larger one (1e-2) that moves every answer -- a kernel that hard-
* wires 1e-6, or one that drops the +eps and answers a bare 1/rms, passes the small one and fails
* the large.
*
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * rsqrt(mean(x^2) + eps)
* is exact and the only room for an error in the comparison is the kernel's own f32 accumulation
* and its bf16 store. The oracle is computed from the bf16 values the kernel actually reads. The
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void rmsnorm_p_case(const Plugin& pl) {
const char* what = "rmsnorm_p vs an f64 evaluation of the weightless normalisation";
const RadKernelInfo* r = find(pl, "rmsnorm_p_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 640;
for (const double epsd : { 1e-6, 1e-2 }) {
std::vector<uint16_t> xh((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
xh[(size_t)i] = h_to_bf16((float)(sgn * mag));
}
// f64 oracle from the bf16 values the kernel reads: y = x * rsqrt(mean(x^2) + eps).
std::vector<double> want((size_t)M * n);
for (int64_t m = 0; m < M; ++m) {
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) {
const double v = (double)h_bf16(xh[(size_t)m * n + i]);
ss += v * v;
}
const double s = 1.0 / std::sqrt(ss / (double)n + epsd);
for (int64_t i = 0; i < n; ++i)
want[(size_t)m * n + i] = (double)h_bf16(xh[(size_t)m * n + i]) * s;
}
void* d_x = dalloc(xh.size() * 2);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, RAD_BF16, { M, n }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n), PF("eps", epsd) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " eps=" + std::to_string(epsd));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "eps=" + std::to_string(epsd) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
/* gelu_mul, against an f64 evaluation of the tanh-approximation GELU.
*
* The inputs are a fixed set of magnitudes, signed, for both the gate and the up half, so the f64
* oracle 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u is exact and the only room for
* an error in the comparison is the kernel's own f32 tanhf and its bf16 store. The oracle is computed
* from the bf16 values the kernel reads; the gate is the first half of the [M, 2n] row. The
* tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */
static void gelu_mul_case(const Plugin& pl) {
const char* what = "gelu_mul vs an f64 evaluation of the tanh GELU";
const RadKernelInfo* r = find(pl, "gelu_mul_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 640;
std::vector<uint16_t> gh((size_t)M * 2 * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 };
for (int64_t i = 0; i < M * 2 * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
gh[(size_t)i] = h_to_bf16((float)(sgn * mag));
}
// f64 oracle from the bf16 values the kernel reads: y = gelu_tanh(gate) * up, gate the first half.
std::vector<double> want((size_t)M * n);
const double k0 = 0.7978845608028654, k1 = 0.044715;
for (int64_t m = 0; m < M; ++m) {
for (int64_t i = 0; i < n; ++i) {
const double g = (double)h_bf16(gh[(size_t)m * 2 * n + i]);
const double u = (double)h_bf16(gh[(size_t)m * 2 * n + n + i]);
const double gelu = 0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g)));
want[(size_t)m * n + i] = gelu * u;
}
}
void* d_g = dalloc(gh.size() * 2);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_g || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_g, gh.data(), gh.size() * 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_g, RAD_BF16, { M, 2 * n }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
/* scale, against an f64 evaluation of the same multiply.
*
* THE SCALAR IS THE [1] WEIGHT THE MODEL LIVES IN (Gemma 4's per-layer scalar, 0.03-0.99), so the
* case runs at three values: two positive of different magnitude (a kernel that hard-wires one of
* them, or one that squares the scalar, passes one and fails the other) and a negative (a kernel
* that drops the sign passes the positives and fails this).
*
* The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * s is five constants deep
* and the only room for an error in the comparison is the kernel's own f32 arithmetic and its bf16
* store. The tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). The scalar
* is stored as f32 (the kernel's branch reads it as such); a bf16 `s` takes the other branch and is
* not exercised here, which is fine -- the multiply is the same either way. */
static void scale_case(const Plugin& pl) {
const char* what = "scale vs an f64 evaluation of the same multiply";
const RadKernelInfo* r = find(pl, "scale_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 7, n = 128;
for (const double sv : { 2.0, 0.5, -1.5 }) {
std::vector<uint16_t> xh((size_t)M * n);
std::vector<double> want((size_t)M * n);
const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 3.0 };
for (int64_t i = 0; i < M * n; ++i) {
const double mag = mags[(int)((i * 31) % 5)];
const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0;
const double xv = sgn * mag;
xh[(size_t)i] = h_to_bf16((float)xv);
want[(size_t)i] = xv * sv;
}
void* d_x = dalloc(xh.size() * 2);
void* d_s = dalloc(4);
void* d_o = dalloc((size_t)(M * n) * 2);
if (!d_x || !d_s || !d_o) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
const float sf = (float)sv;
st_memcpy(d_s, &sf, 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = {
T(d_x, RAD_BF16, { M, n }),
T(d_s, RAD_F32, { 1 }),
T(d_o, RAD_BF16, { M, n }),
};
std::vector<RadParam> ps = { PI("n", n) };
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) {
ok(what, false, "launch rc=" + std::to_string(rc) + " s=" + std::to_string(sv));
return;
}
std::vector<uint16_t> got((size_t)(M * n));
st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost);
double worst = 0.0;
int64_t bad = 0;
for (int64_t i = 0; i < M * n; ++i) {
const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i];
if (std::fabs(e) > worst) worst = std::fabs(e);
if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad;
}
ok(what, bad == 0, "s=" + std::to_string(sv) +
" worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad));
}
}
/* rope_bf16, against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's
* width -- `rot` for `rotary`/absent and `head_dim` for `head` -- so the same kernel body is
* checked under both. The V head is untouched in every case; the absences there would be invisible
* in magnitude (the rotation preserves length) and rel_l2 is what sees the angle itself. */
static void rope_ladder_case(const Plugin& pl) {
const char* what = "rope ladder vs an f32 mirror of rope_kernel at each width";
const RadKernelInfo* r = find(pl, "rope_bf16");
if (!r) { ok(what, false, "row absent"); return; }
const int64_t M = 5, hd = 64, rot = 32, half = rot / 2;
const int64_t n_head = 2, nkv = 1, n_rope = n_head + nkv; /* 3 rotate, one V does not */
const int64_t row = (n_head + 2 * nkv) * hd;
const float theta = 10000.0f;
const int32_t pos[5] = { 0, 1, 7, 128, 4096 };
for (const char* lad : std::initializer_list<const char*>{ nullptr, "rotary", "head" }) {
const int64_t den = (lad && !std::strcmp(lad, "head")) ? hd : rot;
const char* tag = lad ? lad : "absent";
std::vector<uint16_t> saved((size_t)M * row);
for (int64_t i = 0; i < M * row; ++i) {
float v = (float)(((i * 5) % 17) - 8) / 9.0f;
if (i % 13 == 0) v *= 4.0f; /* a few big channels */
saved[(size_t)i] = h_to_bf16(v);
}
void* d_qkv = dalloc(saved.size() * 2);
void* d_pos = dalloc(M * 4);
if (!d_qkv || !d_pos) { ok(what, false, "hipMalloc failed"); return; }
st_memcpy(d_qkv, saved.data(), saved.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_pos, pos, M * 4, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = { T(d_qkv, RAD_BF16, { M, row }), T(d_pos, RAD_I32, { M }) };
std::vector<RadParam> ps = { PI("M", M), PI("head_dim", hd), PI("n_head", n_head),
PI("n_head_kv", nkv), PF("theta", (double)theta),
PF("scale", 1.0), PS("mode", "neox"),
PI("rotary_dim", rot) };
if (lad) ps.push_back(PS("ladder", lad));
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps.data(); a.n_p = (int)ps.size();
const int rc = r->launch(&a, nullptr);
st_stream_sync(nullptr);
if (rc != RAD_OK) { ok(what, false, std::string("ladder=") + tag + " rc=" + std::to_string(rc)); return; }
std::vector<uint16_t> got((size_t)M * row);
st_memcpy(got.data(), d_qkv, got.size() * 2, hipMemcpyDeviceToHost);
double num = 0.0, dnorm = 0.0;
int64_t untouched_bad = 0;
for (int64_t m = 0; m < M; ++m) {
const size_t base = (size_t)m * row;
for (int64_t h = 0; h < n_rope; ++h) {
for (int64_t i = 0; i < half; ++i) {
const size_t i0 = base + (size_t)h * hd + i;
const size_t i1 = i0 + half;
const float x0 = h_bf16(saved[(size_t)i0]), x1 = h_bf16(saved[(size_t)i1]);
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den);
float s, c;
sincosf((float)pos[(size_t)m] * inv, &s, &c);
const float w0 = x0 * c - x1 * s, w1 = x0 * s + x1 * c;
const float g0 = h_bf16(got[(size_t)i0]), g1 = h_bf16(got[(size_t)i1]);
num += (double)(g0 - w0) * (double)(g0 - w0) +
(double)(g1 - w1) * (double)(g1 - w1);
dnorm += (double)w0 * w0 + (double)w1 * w1;
}
}
for (int64_t e = 0; e < hd; ++e) /* the V head is untouched, so exact */
if (got[base + (size_t)n_rope * hd + e] != saved[base + (size_t)n_rope * hd + e])
++untouched_bad;
}
const double rel = dnorm > 0.0 ? std::sqrt(num / dnorm) : 0.0;
ok(what, rel < 2e-3 && untouched_bad == 0, std::string("ladder=") + tag + " rel_l2=" +
std::to_string(rel) + " vhead-moved=" + std::to_string(untouched_bad));
}
}
/* ---- the two fp8 fusions, against the pair each one replaces -------------------------------- */
//
// THE INVARIANT IS NOT "CLOSE", IT IS BYTE-IDENTICAL, which is why this compares against the
@@ -11246,6 +11795,43 @@ static void device_phase(const Plugin& pl) {
attn_case(pl, "attn_decode_h256_gqa6_bf16kv", 256, 6, 1, "bf16", 0);
attn_case(pl, "attn_decode_h128_gqa4_fp8kv", 128, 4, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0);
/* Gemma 4 dense sliding window: decode only, so the window is threaded through -- 1024 is the
* model's window. It exercises the windowed split law and the WIN=1 template the way the
* drafter leg does; max_ctx here is smaller than the window, so the span clamps to the context. */
attn_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 0, 1024);
attn_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 0, 1024);
/* Gemma 4 dense sliding window: the PREFILL leg (Path 2). The decode leg above was decode-only,
* leaving the prefill band (q_len > 32) with no device kernel -- fatal, since libref is an
* opt-in fallback the engine refuses by default (spec §17). This is the windowed query-tiled
* prefill kernel; window 1024 is the model's, threaded through to instantiate WIN=1 the way the
* decode leg does. max_ctx here (64) is smaller than the window, so the span clamps to the
* context and the launch is the full-attention form. */
attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024);
attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024);
/* Gemma 4 dense global: head_dim 512, full attention. The one head_dim with no fixture yet, so
* these launch-only cases are its box coverage -- the numeric byte-equality gate is the 3a GPU
* step, not here. Prefill at q_len 32, decode at 1, mirroring the gqa6 leg's pair. */
attn_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1);
attn_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1);
attn_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
/* The numeric attention check (Phase 3): the same rows, but with random data and a comparison
* against the inline oracle, plus a negative control. h512 is prefill + decode; h256/gqa2 is
* decode-only (the windowed sliding-window leg, window 1024). */
attn_numeric_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0);
attn_numeric_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0);
attn_numeric_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0);
/* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window
* clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for
* query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's
* wlo0 = 961 and tstart = 961/48 = 20 -- exercising both the window mask (keys below 961 are
* masked) and the below-window tile skip (tiles 0..19 are never walked). The oracle's
* visible() is the same bound, so the two agree. */
attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048);
attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048);
attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024);
attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024);
attn_gq_fold_case(pl, 3, false);
attn_gq_fold_case(pl, 24, false);
attn_gq_fold_case(pl, 3, true);
@@ -12529,6 +13115,31 @@ static void device_phase(const Plugin& pl) {
qsa_block_key_yarn_case(pl);
}
if (sel("logit_softcap_bf16")) {
if (!g_case) std::printf("\nthe final-logit softcap, against the formula it implements\n");
logit_softcap_case(pl);
}
if (sel("rmsnorm_p_bf16")) {
if (!g_case) std::printf("\nthe weightless RMS norm, against the formula it implements\n");
rmsnorm_p_case(pl);
}
if (sel("gelu_mul_bf16")) {
if (!g_case) std::printf("\nthe gelu-gated product, against the formula it implements\n");
gelu_mul_case(pl);
}
if (sel("scale_bf16")) {
if (!g_case) std::printf("\nthe per-tensor scalar scale, against the multiply it implements\n");
scale_case(pl);
}
if (sel("rope_bf16")) {
if (!g_case) std::printf("\nthe rotary ladder, against an f32 mirror of the kernel at each width\n");
rope_ladder_case(pl);
}
if (sel("moe_gemm_w4a8")) {
if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM, against a host decode\n");
/* One geometry; a gate/up pair whose odd experts are half as wide; a down projection
+11
View File
@@ -1272,6 +1272,17 @@ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, Rad
R4D_PICK(l);
}
/* The per-tensor scalar: one [1] weight broadcast over the whole [M, n] extent. `s` is the middle
* operand; its extent is 1, not M (that would be scale_rows) and not M*n (that would be a
* per-element mask). The scalar's dtype is the stream's, so a bf16 or f32 `s` both read. */
extern "C" int r4d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n");
if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) };
R4D_PICK(l);
}
extern "C" int r4d_shape_router_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = pi(p, n_p, "M");
const int64_t ne = pi(p, n_p, "n_expert");