radiance 1.7.0

- every model serves without a GPU: libavx covers every op, so `--kernels libavx` alone serves
  every shipped container
- Qwen3-ASR (zivius): speech to text on /v1/audio/transcriptions and live over /v1/realtime
- /v1/messages works with Claude Code as it ships (gearwave00001)
- a long agent conversation keeps its cached history when the client rewrites its last turn
  (manueloverride)
- a stream's first event goes out with the first token, so llama-benchy measures prefill right
- opt-in --prefill-interleave (Smellyyyy, baKon) and --prefill-span (keptn42)
- four-rank TP releases the link early; four-rank selftests and docs/TP4.md (goodman-b)
- NVFP4 and FP8 compressed-tensors imports (devmilan); tools/rad-export for finetunes and LoRA
  adapters (baKon)
- many fixes, among them lost tokens on stop strings under concurrency, keep-alive, MiniCPM5 tool
  arguments and the CPU's vision and audio encoders
- plugin ABI 17 and changed op schemas: out-of-tree plugins must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-16 18:25:18 +02:00
1 parent b068190326
commit 1e968f6e1d
739 files changed
+128447 -84632

No files matched your search

+10 -18
View File
@@ -1,15 +1,10 @@
# libref -- every op in the conventional vocabulary, naively and generically (spec §17).
#
# It links radiance::abi AND NOTHING ELSE. A kernel plugin does not link the core: abi/ is the
# whole contract, and a plugin that reached into core/ would stop being substitutable, which is the
# one property the plugin boundary exists to have. What it shares with the engine -- the dtype
# conversions, the parameter readers -- it takes from the ABI headers, which define them inline.
#
# The glob is CONFIGURE_DEPENDS, so a new translation unit in this directory is picked up by the
# next build with no edit here.
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
# radiance (`cmake -S libref -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the same
# rad_add_plugin either way (cmake/RadAddPlugin.cmake).
# Links radiance::abi and nothing else: abi/ is the whole plugin contract, so the plugin stays
# substitutable. Shared helpers (dtype conversions, parameter readers) come inline from the ABI
# headers.
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S libref -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); see cmake/RadAddPlugin.cmake.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libref LANGUAGES CXX)
@@ -21,16 +16,13 @@ file(GLOB REF_SRC CONFIGURE_DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
rad_add_plugin(libref kernels SOURCES ${REF_SRC})
# -ffp-contract=off IS A CORRECTNESS FLAG HERE, not a tuning one. rad-kbench compares resolved
# kernels against this plugin to a tolerance, so `a*b + c` has to round twice: a reference that
# contracts into an FMA disagrees with itself between two compilers, and one that reassociates
# cannot be trusted to a tolerance at all (libref/ref_common.h).
# -ffp-contract=off is a correctness flag: rad-kbench compares kernels against this reference to a
# tolerance, so `a*b + c` must round twice and give the same result under any compiler
# (libref/ref_common.h).
target_compile_options(libref PRIVATE -ffp-contract=off)
# OpenMP over the outer dimension only -- one thread owns whole output elements, and there is not
# one reduction() clause in the plugin, so two runs at different thread counts are bit-identical.
# Optional: without it the pragmas are ignored and the plugin is correct and slower, which is the
# right failure mode for a fallback.
# Optional OpenMP over the outer dimension only. One thread owns whole output elements and there is
# no reduction() clause, so results are bit-identical at any thread count.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(libref PRIVATE OpenMP::OpenMP_CXX)
+266 -249
View File
@@ -1,25 +1,21 @@
/* ref_attn.cpp -- paged attention, dense attention, the KV write, and the two rotary forms.
*
* These are the ops most likely to be subtly wrong in any implementation, so they are written for
* legibility over everything else: the mask is an explicit predicate per key, the softmax is two
* plain passes with the max subtracted, and nothing is fused.
* These ops are the easiest to get subtly wrong, so they favour legibility: the mask is an explicit
* predicate per key, the softmax is two plain passes with the max subtracted, and nothing is fused.
*
* ============================== THE PAGED LAYOUT ==============================
* ============================== The paged layout ==============================
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim] K then V inside a slot
*
* This is the layout every kernel in the project has to match (libr4d's `R4DArgs::kv` names the
* same one), so it is stated in ref_ops.h and obeyed here. A flat slot index
* s decomposes as block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the
* block id of the sequence's i-th block and `slot_mapping[token]` holds the flat slot a token's KV
* goes to.
* The layout every kernel must match (ref_ops.h; libr4d's `R4DArgs::kv`). A flat slot index s is
* block = s / block_size, offset = s % block_size; `block_table[seq, i]` holds the block id of the
* sequence's i-th block and `slot_mapping[token]` the flat slot a token's KV goes to.
*
* ============================== THE MASK ==============================
* ============================== The mask ==============================
*
* `seqused[s]` is the sequence's TOTAL key count INCLUDING this step's query tokens, so query row
* i of a q_len-row step sits at absolute position seqused[s] - q_len + i. That is what makes one
* kernel serve a decode (q_len 1), a speculative verify (q_len <= 64) and a prefill chunk
* (q_len in the thousands) without the caller passing a second length.
* `seqused[s]` is the sequence's total key count including this step's query tokens, so query row
* i of a q_len-row step sits at absolute position seqused[s] - q_len + i. One kernel thus serves
* decode (q_len 1), speculative verify (q_len <= 64) and prefill chunks (q_len in the thousands).
*
* causal = 1 key j is visible when j <= pos
* causal = 0 key j is visible when j < seqused[s]
@@ -28,9 +24,8 @@
*/
#include "ref_common.h"
#include "rad_yarn.h"
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
* in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols`
* -- the comment above kv_store shows where that shortcut is wrong. */
/* `row_stride`: every q/k/v/out row stride below goes through it rather than a rank-based
* shortcut; see kv_store for where the shortcut is wrong. */
#include "ref_gemm.h"
#include "ref_ops.h"
@@ -40,9 +35,9 @@ using namespace ref;
namespace {
/* The largest head this reference accumulates in one stack frame. The widest in circulation is an
* image VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1), so 2048 is headroom; above
* it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */
/* The largest head this reference accumulates in one stack frame. The widest in use is an image
* VAE's single-head mid-block attention at 1152 (Qwen-Image 2.1); above 2048 the op returns
* RAD_E_UNSUPPORTED instead of overflowing the frame. */
enum { REF_HD_MAX = 2048 };
struct KVView {
@@ -67,6 +62,16 @@ static inline KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block
return v;
}
/* Cache element loaders with the dtype resolved once per launch: the same floats as ldt, and the
* per-element switch out of the inner loops. */
template <uint32_t DT> struct KvFix {
float operator()(const void* p, int64_t i) const { return Cvt<DT>::ld(p, i); }
};
struct KvDyn {
uint32_t dt;
float operator()(const void* p, int64_t i) const { return ld_dt(dt, p, i); }
};
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
@@ -80,10 +85,8 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
/* `block_size` is RAD_DERIVED on this op (docs/OPS.md), so a caller who did not pin it and
* resolved to a kernel that declares no RAD_C_EQ for it -- ref's own row -- arrives here
* without the key. The cache tensor says what the block size is; ref reads it off the operand,
* which is this plugin's rule anyway, and cross-checks it below where the caller did name one. */
/* `block_size` is RAD_DERIVED here (docs/OPS.md), so a call resolved to ref's row may arrive
* without it. Read it off the cache tensor, and cross-check below when the caller names one. */
const int64_t block_size = p_int(a, "block_size", kv->rank == 4 ? kv->shape[2] : 0);
const int causal = (int)p_int(a, "causal", 1);
const int64_t window = p_int(a, "window", 0);
@@ -93,18 +96,16 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = gqa * kv_heads;
/* gqa and the cache's head count decide the query head count, so a rank-3 query that disagrees
* is a caller bug that would otherwise stride through the wrong rows and return plausible
* numbers. */
/* gqa and the cache's head count fix the query head count; a rank-3 query that disagrees would
* stride through the wrong rows. */
if (q->rank >= 3 && q->shape[q->rank - 2] != q_heads) return RAD_E_SHAPE;
const int64_t n_seq = numel(su);
const int64_t rows = numel(q) / (q_heads * head_dim);
if (n_seq <= 0 || rows <= 0) return RAD_E_SHAPE;
/* RAGGED BATCHES. cu_seqlens is optional and absent means every sequence presents the same
* query length, the uniform case. Present, it
* is [n_seq + 1] with cu[0] == 0 and cu[n_seq] == rows, and sequence s owns query rows
* [cu[s], cu[s+1]). A serving scheduler mixes one sequence prefill chunk with other single
* decode rows in the same step, so the ragged case is the ordinary one. */
/* Ragged batches. cu_seqlens is optional; absent, every sequence has the same query length.
* Present, it is [n_seq + 1] with cu[0] == 0 and cu[n_seq] == rows, and sequence s owns query
* rows [cu[s], cu[s+1]). Serving mixes a prefill chunk with decode rows in one step, so ragged
* is the ordinary case. */
if (!cus && rows % n_seq != 0) return RAD_E_SHAPE;
if (cus && numel(cus) != n_seq + 1) return RAD_E_SHAPE;
const int64_t q_len = cus ? 0 : rows / n_seq;
@@ -127,96 +128,129 @@ int ref_attn_paged(const RadArgs* a, RadStream) {
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
const int64_t total = rows * q_heads;
const int64_t jcap = max_blocks * block_size;
#pragma omp parallel for schedule(static)
for (int64_t idx = 0; idx < total; ++idx) {
const int64_t h = idx % q_heads;
const int64_t tok = idx / q_heads; /* the dense query row */
/* Which sequence owns it, and where inside that sequence's query it sits. Linear rather than a
* binary search: n_seq is a handful and this is the reference. */
int64_t s = 0, qlen = q_len, i = 0;
if (cus) {
while (s + 1 < n_seq && ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) <= tok) ++s;
const int64_t beg = ld_int(cus->dtype, cus->data, offlin(cus, s));
qlen = ld_int(cus->dtype, cus->data, offlin(cus, s + 1)) - beg;
i = tok - beg;
} else {
s = tok / q_len;
i = tok - s * q_len;
}
if (qlen <= 0) continue;
const int64_t kh = h / gqa;
/* Every (query row, head) is one output row, computed as below in a fixed order: per visible
* key, dot = sum over d of q[d] * (k[d] * k_descale), score = dot * scale; then the max over the
* scores in key order; then sum and acc[d] accumulate exp(score - max) and
* exp(...) * (v[d] * v_descale) in key order. The query row is widened once, each score is kept
* for the second pass instead of recomputed, and four keys' dot chains run side by side; none
* of that changes a value. */
REF_PAR_REGION(total * head_dim * 64)
{
float* const sc = ws_get((size_t)std::max<int64_t>(jcap, 1));
REF_FOR_DYN
for (int64_t idx = 0; idx < total; ++idx) {
auto unit = [&](auto kl) {
const int64_t h = idx % q_heads;
const int64_t tok = idx / q_heads; /* the dense query row */
/* The owning sequence and the row's index within its query. */
int64_t s = 0, qlen = q_len, i = 0;
if (cus) {
s = seq_of(cus, n_seq, tok);
qlen = cu_at(cus, s + 1) - cu_at(cus, s);
i = tok - cu_at(cus, s);
} else {
s = tok / q_len;
i = tok - s * q_len;
}
if (qlen <= 0) return;
const int64_t kh = h / gqa;
const int64_t ctx = ld_int(su->dtype, su->data, offlin(su, s));
const int64_t pos = ctx - qlen + i;
const int64_t qb = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
const int64_t ctx = ld_int(su->dtype, su->data, offlin(su, s));
const int64_t pos = ctx - qlen + i;
const int64_t qb = tok * q_rs + h * q_hs;
const int64_t ob = tok * o_rs + h * o_hs;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
const float kds = kdes ? ldt(kdes, s * kv_heads + kh) : 1.0f;
const float vds = vdes ? ldt(vdes, s * kv_heads + kh) : 1.0f;
/* Pass one: the maximum score, so the exponent below cannot overflow. */
float mx = -INFINITY;
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
/* Keys past the block table's width are never read. */
const int64_t jend = std::min(ctx, jcap);
/* Key j's slot in the cache, or -1 when the mask hides it or its block is
* unmapped. */
auto key_at = [&](int64_t j) -> int64_t {
if (causal && j > pos) return -1;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) return -1;
}
const int64_t blk =
ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
return blk < 0 ? -1 : blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
};
float qf[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) qf[d] = ldt(q, qb + d * q_ds);
/* Pass one: every visible key's score, four keys at a time, and the maximum. */
float mx = -INFINITY;
for (int64_t j0 = 0; j0 < jend; j0 += 4) {
int64_t kb[4];
float dot[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
const int nk = (int)std::min<int64_t>(4, jend - j0);
for (int u = 0; u < 4; ++u) kb[u] = u < nk ? key_at(j0 + u) : -1;
if (kb[0] >= 0 && kb[1] >= 0 && kb[2] >= 0 && kb[3] >= 0) {
for (int64_t d = 0; d < head_dim; ++d) {
const float qd = qf[d];
dot[0] += qd * (kl(kv->data, kb[0] + d * kvv.sd) * kds);
dot[1] += qd * (kl(kv->data, kb[1] + d * kvv.sd) * kds);
dot[2] += qd * (kl(kv->data, kb[2] + d * kvv.sd) * kds);
dot[3] += qd * (kl(kv->data, kb[3] + d * kvv.sd) * kds);
}
} else {
for (int u = 0; u < nk; ++u) {
if (kb[u] < 0) continue;
for (int64_t d = 0; d < head_dim; ++d)
dot[u] += qf[d] * (kl(kv->data, kb[u] + d * kvv.sd) * kds);
}
}
for (int u = 0; u < nk; ++u) {
if (kb[u] < 0) continue;
const float sj = dot[u] * scale;
sc[j0 + u] = sj;
if (sj > mx) mx = sj;
}
}
/* No visible key (an empty sliding window) gives a zero row, not NaN, matching
* every kernel in the project. */
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
return;
}
/* Pass two: exponentiate and accumulate in ascending key order. */
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float sum = 0.0f;
for (int64_t j = 0; j < jend; ++j) {
const int64_t kb = key_at(j);
if (kb < 0) continue;
const float w = ref_exp(sc[j] - mx);
sum += w;
const int64_t vb = kb + head_dim * kvv.sd;
for (int64_t d = 0; d < head_dim; ++d)
acc[d] += w * (kl(kv->data, vb + d * kvv.sd) * vds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
};
switch (kv->dtype) {
case RAD_F32: unit(KvFix<RAD_F32>{}); break;
case RAD_BF16: unit(KvFix<RAD_BF16>{}); break;
case RAD_F8E4M3: unit(KvFix<RAD_F8E4M3>{}); break;
default: unit(KvDyn{ kv->dtype }); break;
}
if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue;
const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds);
dot *= scale;
if (dot > mx) mx = dot;
}
float acc[REF_HD_MAX];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
/* No visible key at all -- an empty sliding window on the first token of a sequence -- is a
* zero row, not a NaN. A softmax over nothing has no defined answer and zero is the one
* every kernel in this project produces. */
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
/* Pass two: the scores again, exponentiated and accumulated in ascending key order. The
* dot product is recomputed rather than kept, because keeping it would need a buffer the
* size of the context and the reference has time it does not have memory. */
float sum = 0.0f;
for (int64_t j = 0; j < ctx; ++j) {
if (causal ? (j > pos) : (j >= ctx)) continue;
if (window > 0) {
const int64_t d = pos - j;
if (causal ? (d >= window) : (d >= window || d <= -window)) continue;
}
if (j / block_size >= max_blocks) break; /* bounds first: the table is only this wide */
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) continue;
const int64_t kb = blk * kvv.sb + kh * kvv.sh + (j % block_size) * kvv.so;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * (ldt(kv, kb + d * kvv.sd) * kds);
const float w = ref_exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d)
acc[d] += w * (ldt(kv, kb + (head_dim + d) * kvv.sd) * vds);
}
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, acc[d] * inv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ attn_dense */
/* The vision tower's: nothing paged, nothing quantised, `cu_seqlens` bounding one image (or one
* attention window) per entry so a whole batch is ONE launch rather than a per-segment loop and a
* concatenate. Causal is a parameter because a dense decoder-only prefill wants the same kernel. */
/* For the vision tower: unpaged, unquantised, `cu_seqlens` bounding one image (or attention window)
* per entry so a whole batch is one launch. Causal is a parameter so a dense decoder-only prefill
* can use the same kernel. */
int ref_attn_dense(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *cu = &a->t[3], *o = &a->t[4];
@@ -224,14 +258,19 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
/* `window` is attn_paged's rule over a segment's own positions: causal, key j is visible to
* query i when i - j < window; non-causal, when |i - j| < window. 0 is no window. */
/* `window` follows attn_paged's rule over a segment's own positions: causal, key j is visible
* to query i when i - j < window; non-causal, when |i - j| < window. 0 is no window. `block`
* cuts a segment into blocks of that many rows from its start, each attending only within
* itself (a chunked encoder's windows). `cu_div` reads cu_seqlens in units of that many rows:
* a segment is rows [cu[s] / cu_div, cu[s+1] / cu_div). */
const int64_t window = p_int(a, "window", 0);
if (head_dim <= 0 || gqa <= 0 || window < 0) return RAD_E_SHAPE;
const int64_t block = p_int(a, "block", 0);
const int64_t cdiv = p_int(a, "cu_div", 1);
if (head_dim <= 0 || gqa <= 0 || window < 0 || block < 0 || cdiv <= 0) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) return RAD_E_UNSUPPORTED;
/* [tokens, heads, head_dim], or [tokens, heads * head_dim] -- a column slice of a fused
* projection, whose row pitch is the projection's. */
/* [tokens, heads, head_dim], or [tokens, heads * head_dim] as a column slice of a fused
* projection with the projection's row pitch. */
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
const int64_t kv_heads = q_heads / gqa;
@@ -239,6 +278,7 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t total_q = numel(q) / (q_heads * head_dim);
if (total_q <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
if (numel(o) < total_q * q_heads * head_dim) return RAD_E_SHAPE;
if (numel(k) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
if (numel(v) < total_q * kv_heads * head_dim) return RAD_E_SHAPE;
@@ -258,11 +298,11 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(total_q * q_heads * head_dim * 64)
for (int64_t sh = 0; sh < n_seq * q_heads; ++sh) {
const int64_t s = sh / q_heads, h = sh % q_heads, kh = h / gqa;
const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
const int64_t b0 = cu_at(cu, s) / cdiv;
const int64_t b1 = cu_at(cu, s + 1) / cdiv;
for (int64_t i = b0; i < b1; ++i) {
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
int64_t jbeg = b0, jend = causal ? (i + 1) : b1;
@@ -270,6 +310,11 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
jbeg = std::max<int64_t>(b0, i - window + 1);
if (!causal) jend = std::min<int64_t>(b1, i + window);
}
if (block > 0) {
const int64_t blk = b0 + (i - b0) / block * block;
jbeg = std::max<int64_t>(jbeg, blk);
jend = std::min<int64_t>(jend, blk + block);
}
float mx = -INFINITY;
for (int64_t j = jbeg; j < jend; ++j) {
const int64_t kb = j * k_rs + kh * k_hs;
@@ -303,23 +348,18 @@ int ref_attn_dense(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ kv_store */
/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache operand is
* INOUT and not OUT: this op touches only the mapped slots and every other slot in the pool must
* survive it, which is a liveness fact the buffer planner has to know (docs/OPS.md draws it as an
* output; that is the one role this plugin states differently, and deliberately).
/* Writes this step's keys and values into the paged cache at `slot_mapping`. The cache is INOUT,
* not OUT: only mapped slots are touched and every other slot must survive, which the buffer
* planner needs to know (docs/OPS.md draws it as an output; this plugin deliberately differs).
*
* A NEGATIVE slot is skipped. That is how a padded batch row says "this token has no cache slot",
* and it has to be a documented value rather than an accident: libr4d treats slot <= 0 as null
* because vLLM reserves block 0, but a generic reference must not steal a valid slot, so ref skips
* only the strictly negative.
* A negative slot is skipped: it marks a padded row with no cache slot. libr4d treats slot <= 0 as
* null because vLLM reserves block 0, but a generic reference must not steal a valid slot.
*
* `k` AND `v` ARRIVE RANK 2 FROM THE ENGINE AND THEIR ROWS ARE NOT DENSE. An architecture that
* de-interleaves the projection hands [tokens, kv_heads, head_dim]; one that does not hands a
* COLUMN SLICE of the fused QKV plane -- [tokens, kv_heads * head_dim] whose row stride is the
* whole projection's width, 2560 against 256 on a 16-head model with 2 kv heads. Deriving the row
* stride from the shape instead of from the tensor puts token 0 in the right slot and every token
* after it inside the previous token's QUERY rows, which is a cache that looks written and holds
* the wrong keys from the second token on. `row_stride` asks the operand instead. */
* `k` and `v` rows are not dense. A de-interleaved projection gives [tokens, kv_heads, head_dim];
* otherwise they are a column slice of the fused QKV plane, [tokens, kv_heads * head_dim] with the
* projection's row stride (2560 vs 256 for 16 heads and 2 kv heads). Deriving the stride from the
* shape would write every token after the first from the wrong rows, so `row_stride` reads the
* operand. */
int ref_kv_store(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *v = &a->t[1], *sm = &a->t[2], *kv = &a->t[3];
@@ -342,8 +382,8 @@ int ref_kv_store(const RadArgs* a, RadStream) {
const int64_t v_hs = v->rank >= 3 ? v->stride[v->rank - 2] : head_dim * v_ds;
const int64_t v_rs = row_stride(v, kv_heads * head_dim);
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* AN FP8 CACHE STORES k / k_scale: the scales are the descales the reader multiplies back by,
* 1.0 unless the call names them. A wider cache stores the value itself. */
/* An fp8 cache stores k / k_scale, where the scales are the reader's descales (default 1.0).
* A wider cache stores the value itself. */
const bool fp8 = kv->dtype == RAD_F8E4M3 || kv->dtype == RAD_F8E5M2;
const float ks = fp8 ? 1.0f / p_f32(a, "k_scale", 1.0f) : 1.0f;
const float vs = fp8 ? 1.0f / p_f32(a, "v_scale", 1.0f) : 1.0f;
@@ -353,7 +393,7 @@ int ref_kv_store(const RadArgs* a, RadStream) {
if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE;
}
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * kv_heads * head_dim * 2)
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (slot < 0) continue;
@@ -372,21 +412,20 @@ int ref_kv_store(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ rope */
namespace {
/* NeoX pairs element i with i + rotary_dim/2; GPT-J (the "interleaved" style) pairs 2i with 2i+1.
* Which one a checkpoint wants is a property of the checkpoint, so it is a parameter and not a
* guess -- and getting it wrong produces fluent text with a broken sense of position, which is the
* hardest kind of wrong to notice (spec §12 makes the same point about token boundaries).
/* NeoX pairs element i with i + rotary_dim/2; GPT-J ("interleaved") pairs 2i with 2i+1. The
* checkpoint decides, so it is a parameter: the wrong one yields fluent text with broken position
* sense, which is hard to notice.
*
* THE MULTI-COMPONENT MODES pair like NeoX and differ in which position component drives each
* The multi-component modes pair like NeoX and differ in which position component drives each
* frequency (i indexes the rot/2 frequencies):
* mrope contiguous sections: frequencies [0, s0) take component 0, the next s1 component 1...
* (Qwen2-VL), all on one ladder theta^(-2i/rot).
* imrope interleaved (Qwen3-VL): component 1 where i % 3 == 1 and i < 3*s1, component 2 where
* i % 3 == 2 and i < 3*s2, component 0 everywhere else; one ladder.
* axial contiguous sections, EACH ON ITS OWN LADDER theta^(-2j/(2*s_c)) for its j-th
* frequency -- a 2-D rotary embedding over (row, column), the vision tower's.
* With one position component a token -- a rank-1 `positions` -- every component is that one and
* mrope and imrope ARE neox. */
* axial contiguous sections, each on its own ladder theta^(-2j/(2*s_c)) for its j-th
* frequency: the vision tower's 2-D rotary embedding over (row, column).
* With one position component per token (rank-1 `positions`) every component is the same, and
* mrope and imrope reduce to neox. */
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
struct RopeFreq {
@@ -394,10 +433,10 @@ struct RopeFreq {
float inv[REF_HD_MAX / 2];
};
/* Which component and inverse frequency each of the rot/2 frequencies uses. */
/* `den` is the width the BASE ladder is measured in: `rot` for a `rotary` ladder (a partial rotary
* is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant. The
* loop count and the NeoX/GPT-J pairing still come from `rot`; `axial` overrides `inv` below. */
/* The component and inverse frequency of each of the rot/2 frequencies. `den` is the width the base
* ladder is measured in: `rot` for a `rotary` ladder (a partial rotary is a full rotation of its
* own width), `head_dim` for the proportional `head` variant. The loop count and pairing still come
* from `rot`; `axial` overrides `inv`. */
static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int64_t* sec,
int n_sec, RopeFreq* f) {
const int64_t half = rot / 2;
@@ -407,12 +446,12 @@ static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int
if ((mode == ROPE_MROPE || mode == ROPE_AXIAL) && n_sec > 0 && total != half) return RAD_E_SHAPE;
for (int64_t i = 0; i < half; ++i) {
int c = 0;
float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)den);
float inv = 1.0f / ref_pow(theta, (float)(2 * i) / (float)den);
if (n_sec > 0 && (mode == ROPE_MROPE || mode == ROPE_AXIAL)) {
while (c + 1 < n_sec && i >= start[c + 1]) ++c;
if (mode == ROPE_AXIAL) {
const int64_t j = i - start[c];
inv = 1.0f / std::pow(theta, (float)(2 * j) / (float)(2 * sec[c]));
inv = 1.0f / ref_pow(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
} else if (n_sec >= 3 && mode == ROPE_IMROPE) {
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
@@ -429,7 +468,7 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot,
const int64_t half = rot / 2;
for (int64_t i = 0; i < half; ++i) {
const float ang = pos[f.comp[i]] * f.inv[i];
const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude;
const float c = ref_cos(ang) * magnitude, s = ref_sin(ang) * magnitude;
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
@@ -453,9 +492,9 @@ static int rope_sections(const RadArgs* a, int64_t* sec) {
return n;
}
/* `ladder` names the width the base frequency ladder is measured in -- see rope_freqs. Absent and
* `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An
* unknown value is a schema error, not a silent default: a mistyped ladder is a silent wrong angle. */
/* `ladder` names the width the base frequency ladder is measured in (see rope_freqs): absent or
* `rotary` divides by `rot`, `head` by `head_dim`. An unknown value is refused, since a mistyped
* ladder would silently give wrong angles. */
static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) {
const char* lad = p_str(a, "ladder", nullptr);
if (!lad) { *den = rot; return RAD_OK; }
@@ -490,7 +529,7 @@ int ref_rope(const RadArgs* a, RadStream) {
int64_t sec[8] = {};
const int n_sec = rope_sections(a, sec);
if (n_sec < 0) return RAD_E_SHAPE;
/* POSITIONS: [M] is one component a token; [C, M] is C components, component-major. */
/* Positions: [M] is one component per token; [C, M] is C components, component-major. */
const bool multi = pos->rank >= 2;
const int64_t n_comp = multi ? pos->shape[0] : 1;
const int64_t M = multi ? pos->shape[1] : numel(pos);
@@ -499,9 +538,9 @@ int ref_rope(const RadArgs* a, RadStream) {
const int64_t need = mode == ROPE_IMROPE ? 3 : n_sec;
if (n_comp < need || n_comp > 8) return RAD_E_SHAPE;
}
/* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is
* (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero, so those pairs turn by
* nothing. A rotary of rotary_dim's own width, pairing (i, i + rot/2), turns other channels. */
/* The proportional ladder (`head`) is HF's: the rotation spans the whole head, pair i being
* (i, i + head_dim/2), and frequencies past rotary_dim/2 are zero so those pairs do not turn.
* A rotary of rotary_dim's own width, pairing (i, i + rot/2), would turn other channels. */
const int64_t nfreq = rot / 2;
if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim;
RopeFreq f;
@@ -514,14 +553,13 @@ int ref_rope(const RadArgs* a, RadStream) {
}
for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t rs = row_stride(qkv, stride_row);
const int64_t ds = laststride(qkv);
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * stride_row)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float div = rscale != 0.0f ? rscale : 1.0f;
@@ -533,8 +571,7 @@ int ref_rope(const RadArgs* a, RadStream) {
for (int c = 0; c < 8; ++c) p[c] = one;
}
const int64_t row = m * rs;
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
* this op takes the fused qkv rather than two tensors. */
/* Q heads then K heads; the V heads after them are left alone. */
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude);
}
@@ -542,16 +579,13 @@ int ref_rope(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ qk_norm_rope */
/* The QK-norm preamble and the rotation in one op: an RMS norm over each 128-wide (or whatever
* head_dim is) q and k head against its own gain vector, then RoPE. `v_norm` 1 also RMS-norms
* each v head with a UNIT gain and no rotation -- Gemma 4's value norm, which has no weight. The
* v heads are otherwise left alone.
/* QK-norm and rotation in one op: an RMS norm over each head_dim-wide q and k head against its own
* gain vector, then RoPE. `v_norm` 1 also RMS-norms each v head with unit gain and no rotation
* (Gemma 4's weightless value norm); otherwise v heads are untouched.
*
* THE NORM OUTPUT IS ROUNDED TO THE TENSOR'S DTYPE BEFORE THE ROTATION. That is not an accident of
* writing it back in place -- it is what the unfused pair does, because the norm stores a tensor
* and the rotation reads it, and libr4d's r4d_qk_norm_rope_gate matches the unfused reference for
* exactly this reason. A fused kernel that kept f32 across the seam would be half a ULP better and
* would fail a comparison against this. */
* The norm output is rounded to the tensor's dtype before the rotation, as the unfused pair does;
* libr4d's r4d_qk_norm_rope_gate matches this. A fused kernel keeping f32 across the seam would be
* half a ULP better and fail the comparison. */
int ref_qk_norm_rope(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1], *qw = &a->t[2], *kw = &a->t[3];
@@ -564,9 +598,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
const float rscale = p_f32(a, "scale", 1.0f);
const float wadd = p_f32(a, "wadd", 0.0f);
const int v_norm = (int)p_int(a, "v_norm", 0);
/* `gptj_blocks` is `blocks` with each section's pairs ADJACENT -- (start + 2j, start + 2j + 1),
* the complex-number form a 3-axis image rotary takes (Qwen-Image's). `imrope` is `rope`'s
* interleaved M-RoPE over NeoX pairs, after the norm (Qwen3-VL's text attention). */
/* `gptj_blocks` is `blocks` with each section's pairs adjacent, (start + 2j, start + 2j + 1):
* the complex-number form of Qwen-Image's 3-axis rotary. `imrope` is `rope`'s interleaved
* M-RoPE over NeoX pairs, after the norm (Qwen3-VL text attention). */
static const char* kModes[] = { "neox", "gptj", "blocks", "gptj_blocks", "imrope" };
const int mode = p_enum(a, "mode", kModes, 5, 0);
if (mode < 0) return RAD_E_UNSUPPORTED;
@@ -577,10 +611,10 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
/* BLOCKS: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired
/* Blocks: section c is `sec[c]` rotary pairs over its own run of 2 * sec[c] channels, paired
* (start + j, start + sec[c] + j) and turned by position component comps[c] at
* theta^(-j / sec[c]) -- each section a complete neox rotary of its own width. The sections
* fill the rotated prefix exactly. Positions are [C, M], component-major. */
* theta^(-j / sec[c]), i.e. a complete neox rotary of its own width. The sections fill the
* rotated prefix exactly. Positions are [C, M], component-major. */
int64_t sec[8] = {}, comp[8] = {};
int n_sec = 0;
if (im) {
@@ -616,15 +650,28 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t rs = row_stride(qkv, stride_row);
const int64_t ds = laststride(qkv);
RopeFreq f;
/* No `ladder` on this row yet: the fused norm+rope measures by `rot`, as it always has. */
/* No `ladder` parameter here: the fused norm+rope measures by `rot`. */
if (im) RAD_REF_TRY(rope_freqs(ROPE_IMROPE, rot, rot, theta, sec, multi ? n_sec : 0, &f));
else RAD_REF_TRY(rope_freqs(blocks ? 0 : mode, rot, rot, theta, nullptr, 0, &f));
/* RMS-norms one head in place, against gain `w` (+ wadd), or unit gain without one. */
auto norm_head = [&](int64_t base, const RadTensor* w) {
float ss = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) {
const float x = ldt(qkv, base + d * ds);
ss += x * x;
}
const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d) {
const float x = ldt(qkv, base + d * ds) * sc;
stt(qkv, base + d * ds, w ? x * (ldt(w, d * laststride(w)) + wadd) : x);
}
};
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * stride_row)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float div = rscale != 0.0f ? rscale : 1.0f;
@@ -637,16 +684,8 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
}
const int64_t row = m * rs;
for (int64_t h = 0; h < n_head + n_head_kv; ++h) {
const RadTensor* w = h < n_head ? qw : kw;
const int64_t base = row + h * head_dim * ds, ws = laststride(w);
float ss = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) {
float x = ldt(qkv, base + d * ds);
ss += x * x;
}
const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d)
stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc * (ldt(w, d * ws) + wadd));
const int64_t base = row + h * head_dim * ds;
norm_head(base, h < n_head ? qw : kw);
if (!blocks) {
rope_head(qkv, base, ds, rot, im ? ROPE_IMROPE : mode, f, p);
continue;
@@ -654,9 +693,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
int64_t start = 0;
for (int c = 0; c < n_sec; ++c) {
for (int64_t j = 0; j < sec[c]; ++j) {
const float inv = 1.0f / std::pow(theta, (float)j / (float)sec[c]);
const float inv = 1.0f / ref_pow(theta, (float)j / (float)sec[c]);
const float ang = p[comp[c]] * inv;
const float cs = std::cos(ang), sn = std::sin(ang);
const float cs = ref_cos(ang), sn = ref_sin(ang);
const int64_t i0 = adjacent ? start + 2 * j : start + j;
const int64_t i1 = adjacent ? start + 2 * j + 1 : start + sec[c] + j;
const float x0 = ldt(qkv, base + i0 * ds), x1 = ldt(qkv, base + i1 * ds);
@@ -666,29 +705,12 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) {
start += 2 * sec[c];
}
}
for (int64_t h = 0; v_norm && h < n_head_kv; ++h) {
const int64_t base = row + (n_head + n_head_kv + h) * head_dim * ds;
float ss = 0.0f;
for (int64_t d = 0; d < head_dim; ++d) {
float x = ldt(qkv, base + d * ds);
ss += x * x;
}
const float sc = 1.0f / std::sqrt(ss / (float)head_dim + eps);
for (int64_t d = 0; d < head_dim; ++d)
stt(qkv, base + d * ds, ldt(qkv, base + d * ds) * sc);
}
for (int64_t h = 0; v_norm && h < n_head_kv; ++h)
norm_head(row + (n_head + n_head_kv + h) * head_dim * ds, nullptr);
}
return RAD_OK;
}
/* A value as a tensor of `dt` holds it: rounded through the dtype's own store and load. */
static inline float round_dt(uint32_t dt, float v) {
uint64_t buf = 0;
st_dt(dt, &buf, 0, v);
return ld_dt(dt, &buf, 0);
}
static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; }
/* ------------------------------------------------------------------ attn_local_rel */
/* Local attention with a relative-position term: Gemma 4's audio (USM conformer) attention.
*
@@ -702,11 +724,10 @@ static inline int64_t rows_n(const RadTensor* t, int64_t n) { return n > 0 ? num
* then a softmax over those keys and the weighted sum of v, all in f32 and rounded once. `relk`
* is [left + 1, n_head * head_dim]: row d is the projected relative position for distance d.
*
* The reference computes this in 12-query blocks over 24-key context windows and shifts the
* relative term into place (Transformer-XL's rel_shift); every key outside 0 <= i - j <= left
* carries a -1e9 logit there and a zero weight after the softmax, so the sliding form below is
* the same function. softplus(pds) is rounded to the weight's dtype before use, as the reference
* evaluates it on the bf16 parameter. */
* The upstream model computes this in 12-query blocks over 24-key windows with Transformer-XL's
* rel_shift; keys outside 0 <= i - j <= left get a -1e9 logit and zero weight there, so this
* sliding form is the same function. softplus(pds) is rounded to the weight's dtype before use,
* as upstream evaluates it on the bf16 parameter. */
int ref_attn_local_rel(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *rk = &a->t[3];
@@ -722,7 +743,8 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) {
if (numel(pds) < D || numel(rk) < (L + 1) * W) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mq = rows_n(q, W), Mk = rows_n(k, W), Mv = rows_n(v, W), Mo = rows_n(o, W);
const int64_t Mq = rows_of(q, W), Mk = rows_of(k, W), Mv = rows_of(v, W), Mo = rows_of(o, W);
if (Mq <= 0 || Mo <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
const float qs = (float)(1.0 / std::sqrt((double)D) / std::log(2.0));
const float ks = (float)(std::log(1.0 + std::exp(1.0)) / std::log(2.0));
@@ -731,13 +753,13 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) {
spd[d] = round_dt(pds->dtype, act_softplus(ldt(pds, d * laststride(pds)), 20.0f));
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
const int64_t c0 = cu_at(cu, s);
const int64_t c1 = cu_at(cu, s + 1);
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
if (t1 > Mq || t1 > Mk || t1 > Mv || t1 > Mo) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR((t1 - t0) * H * D * (L + R + 1))
for (int64_t ih = 0; ih < (t1 - t0) * H; ++ih) {
const int64_t i = t0 + ih / H, h = ih % H;
float qf[REF_HD_MAX], lg[REF_HD_MAX], acc[REF_HD_MAX];
@@ -753,13 +775,13 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) {
ac += qf[d] * (ldt(k, kb + d * laststride(k)) * ks);
bd += qf[d] * ldt(rk, rb + d * laststride(rk));
}
const float x = cap * std::tanh((ac + bd) / cap);
const float x = cap * ref_tanh((ac + bd) / cap);
lg[j - j0] = x;
mx = x > mx ? x : mx;
}
float sum = 0.0f;
for (int64_t j = j0; j <= i; ++j) {
lg[j - j0] = std::exp(lg[j - j0] - mx);
lg[j - j0] = ref_exp(lg[j - j0] - mx);
sum += lg[j - j0];
}
for (int64_t d = 0; d < D; ++d) acc[d] = 0.0f;
@@ -776,14 +798,11 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ rope_table */
/* The cos/sin plane a fused prologue reads instead of theta, written at each position's OWN row of
* a [max_ctx, rot] table: `rot` values a row, cos for the first rot/2 and sin for the second.
/* The cos/sin plane a fused prologue reads instead of theta, written at each position's own row of
* a [max_ctx, rot] table: cos in the first rot/2 values of a row, sin in the second.
*
* THE ANGLES ARE `rope`'s, TO THE LAST OPERATION, and that is the whole contract: a fused rotation
* that read a table built any other way would be a different model, and the difference would be a
* fraction of a ULP per element -- fluent text, subtly wrong positions, exactly the failure class
* this file's rope_head comment is about. Only the rows `positions` names are written; a negative
* position is a padded row and writes nothing. */
* The angles must match `rope`'s to the last operation; any other construction gives subtly wrong
* positions. Only rows named by `positions` are written; a negative position writes nothing. */
int ref_rope_table(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *pos = &a->t[0], *cs = &a->t[1];
@@ -801,16 +820,16 @@ int ref_rope_table(const RadArgs* a, RadStream) {
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * rot)
for (int64_t m = 0; m < M; ++m) {
const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m));
if (pp < 0 || pp >= rows) continue;
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
for (int64_t i = 0; i < half; ++i) {
const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)den), (int)i);
const float inv = yarn.frequency(1.0f / ref_pow(theta, (float)(2 * i) / (float)den), (int)i);
const float ang = p * inv;
stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude);
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude);
stt(cs, offlin(cs, pp * rot + i), ref_cos(ang) * yarn.magnitude);
stt(cs, offlin(cs, pp * rot + half + i), ref_sin(ang) * yarn.magnitude);
}
}
return RAD_OK;
@@ -819,16 +838,16 @@ int ref_rope_table(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ qsa_block_key */
/* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks,
*
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and rounded to k's dtype
* normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w)
* out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest
* passed through, rounded once at the store
*
* The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is
* part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's
* components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio`
* without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The
* rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */
* The rounding after the mean is the upstream model's (`.float().mean(dim=1).to(dtype)`). The
* block's position is `pos[b]` (a [>= M, 1 or 3] list holds a block's components side by side,
* read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio` without one. `page[b]`, when
* given, is the output row; a negative entry writes nothing. The rotary is `rope`'s ladder, with
* YaRN's blend and magnitude when its coefficients are given. */
int ref_qsa_block_key(const RadArgs* a, RadStream) {
const RadTensor* k = t_in(a, 0);
const RadTensor* w = t_in(a, 1);
@@ -857,8 +876,8 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) {
int64_t sec[8] = {};
const int n_sec = rope_sections(a, sec);
if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE;
/* Several components only with a mode, its sections and three columns of `pos`; otherwise
* every frequency reads the block's one position, which every mode reads as NeoX. */
/* Multiple components need a mode, its sections and three columns of `pos`; otherwise every
* frequency reads the block's single position, which reduces every mode to NeoX. */
const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
@@ -867,7 +886,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) {
RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, rot, theta, sec, mc ? n_sec : 0, &f));
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n * ratio)
for (int64_t b = 0; b < M; ++b) {
const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b;
if (orow < 0) continue;
@@ -876,9 +895,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) {
for (int64_t t = 0; t < n; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
uint64_t tmp = 0;
st_dt(k->dtype, &tmp, 0, acc / (float)ratio);
x[t] = ld_dt(k->dtype, &tmp, 0);
x[t] = round_dt(k->dtype, acc / (float)ratio);
ss += (double)x[t] * x[t];
}
const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
@@ -893,7 +910,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) {
const int64_t half = rot / 2;
for (int64_t i = 0; i < half; ++i) {
const float ang = p[f.comp[i]] * f.inv[i];
const float c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude;
const float c = ref_cos(ang) * yarn.magnitude, s = ref_sin(ang) * yarn.magnitude;
const float x0 = y[i], x1 = y[half + i];
y[i] = x0 * c - x1 * s;
y[half + i] = x0 * s + x1 * c;
+94 -97
View File
@@ -1,33 +1,26 @@
/* ref_collective.cpp -- all_reduce and all_gather on the host backend.
*
* At world_size 1 both are the degenerate case: all_reduce is inout and already holds the answer,
* all_gather is a copy. Above 1 they are real, and they work because of how this engine is shaped:
* ONE PROCESS, ONE THREAD PER RANK, ONE ADDRESS SPACE (spec §1). There is no IPC to set up and no
* serialisation to do -- a peer's buffer is a pointer -- so the whole collective is a rendezvous, a
* read of every rank's pointer, and a second rendezvous before anyone overwrites theirs.
* At world_size 1 all_reduce is a no-op (inout) and all_gather a copy. Above 1 they rely on the
* engine's shape: one process, one thread per rank, one address space (spec §1). A peer's buffer is
* a pointer, so a collective is a rendezvous, a read of every rank's pointer, and a second
* rendezvous before anyone overwrites theirs.
*
* That makes the host backend a FAKE MULTI-DEVICE BACKEND, which is the point: tensor-parallel code
* paths -- the sharded declare, the collective placement, the distributed top-k -- can be exercised
* on a machine with no accelerator at all. What it does not test is a device all-reduce's numerics,
* and it does not pretend to.
* This makes the host backend a fake multi-device backend, so tensor-parallel paths (sharded
* declare, collective placement, distributed top-k) can run without an accelerator. It does not
* test a device all-reduce's numerics.
*
* REDUCTION ORDER IS ASCENDING RANK, in f32, on every rank. That is libr4d's rule ("fp32
* accumulate in ascending rank order, bit-identical across ranks") and it is a correctness
* requirement rather than a convention: tensor-parallel ranks hold replicated state that must stay
* bit-identical, and two ranks that summed in different orders would drift apart over a
* generation. The `-ffp-contract=off` this plugin builds with is part of the same rule
* (docs/OPS.md).
* Reduction order is ascending rank, in f32, on every rank (libr4d's rule). Tensor-parallel ranks
* hold replicated state that must stay bit-identical; different summation orders would drift apart
* over a generation. -ffp-contract=off is part of the same rule (docs/OPS.md).
*
* `exact` is honoured in one direction only. exact=1 gets the exact sum. exact=0 -- a caller that
* has declared it will accept a lossy quantised wire -- also gets the exact sum, because there is
* no wire here to quantise. Serving a lossy request with an exact answer is safe; the constraint
* exists so a caller who wanted exactness cannot be handed a lossy result by accident, not the
* reverse. `hops` is accepted and ignored: one-shot and two-shot are the same walk over an array
* when the peers are pointers.
* exact=0 (caller accepts a lossy quantised wire) also gets the exact sum, since there is no wire;
* the constraint only forbids handing a lossy result to a caller that asked for exact. `hops` is
* ignored: one-shot and two-shot are the same walk when peers are pointers.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <atomic>
#include <mutex>
#include <condition_variable>
#include <chrono>
@@ -39,15 +32,15 @@ namespace {
enum { REF_MAX_RANKS = 8 };
/* One group per process. There is exactly one world size in a radiance process and the rank
* threads run the same declared graph in lockstep against one batch, so the sequence of collective
* calls is identical on every rank and a single sense-reversing barrier is enough to pair them up.
* A per-op group would need a key the ABI does not carry -- init() is called once per rank per
* resolved instance and cannot tell two ops apart from two ranks of one op. */
/* One group per process. A process has one world size and the rank threads run the same graph in
* lockstep, so every rank issues the same sequence of collectives and one generation-counting
* barrier pairs them. A per-op group would need a key the ABI does not carry: init() cannot tell
* two ops apart from two ranks of one op. */
struct Group {
std::mutex m;
std::condition_variable cv;
int world = 0;
int members = 0; /* initialised instances not yet finalised (see join) */
int arrived = 0;
unsigned gen = 0;
const void* slot[REF_MAX_RANKS] = {};
@@ -57,11 +50,14 @@ struct Group {
static Group& group() { static Group g; return g; }
/* Returns false on timeout. A collective IS a synchronisation, so the no-blocking rule cannot
* apply to it -- but an unbounded wait would turn a mismatched call sequence into a wedged test
* run with no output, and this engine exits non-zero rather than serving from a wedged queue
* (spec §17). Thirty seconds is far longer than any correct step and far shorter than a CI
* timeout. */
/* How long a rank waits for its peers. A collective must block, but an unbounded wait would turn a
* mismatched call sequence into a silent hang; the engine exits non-zero instead (spec §17). 30 s is
* far longer than any correct step and shorter than a CI timeout. ref_collective_timeout_ms sets it
* for a test. */
static std::atomic<int> g_timeout_ms{ 30000 };
/* Returns false on timeout. A rank that gives up withdraws its arrival, so the group's count is
* again that of the ranks still waiting and the next collective pairs from a clean start. */
static bool barrier(Group& g) {
std::unique_lock<std::mutex> lk(g.m);
const unsigned mygen = g.gen;
@@ -71,23 +67,48 @@ static bool barrier(Group& g) {
g.cv.notify_all();
return true;
}
return g.cv.wait_for(lk, std::chrono::seconds(30), [&] { return g.gen != mygen; });
const bool met = g.cv.wait_for(lk, std::chrono::milliseconds(g_timeout_ms.load()),
[&] { return g.gen != mygen; });
if (!met) --g.arrived;
return met;
}
static int join(int rank, int world) {
/* The world size is fixed while it is in use: while an initialised instance is alive or a rank is
* mid-collective. Otherwise the next join may state another one, so a process can run one group
* after another (a re-initialised engine, a test). `member` counts an init, which fini releases. */
static int join(int rank, int world, bool member) {
if (world <= 0 || world > REF_MAX_RANKS) return RAD_E_UNSUPPORTED;
if (rank < 0 || rank >= world) return RAD_E_INVAL;
Group& g = group();
std::lock_guard<std::mutex> lk(g.m);
if (g.world == 0) g.world = world;
if (g.world == 0 || (g.members == 0 && g.arrived == 0)) g.world = world;
else if (g.world != world) return RAD_E_INVAL;
if (member) ++g.members;
return RAD_OK;
}
/* Staging, so a rank does not overwrite its own buffer while a peer is still reading it. The
* scratch the arena hands us is used when it is big enough -- that is what the scratch hook exists
* for -- and the per-thread workspace covers a caller that passed none (a test, or a tool calling
* the kernel directly). */
/* Publishes this rank's input and waits until every rank has published a matching one. Peers read
* each other's input as `nel` contiguous elements, since only the pointer is published. */
static int publish(int rank, int world, const RadTensor* x, int64_t nel) {
if (!rad_tensor_is_contiguous(x)) return RAD_E_STRIDE;
RAD_REF_TRY(join(rank, world, false));
Group& g = group();
{
std::lock_guard<std::mutex> lk(g.m);
g.slot[rank] = x->data;
g.nel [rank] = nel;
g.dt [rank] = x->dtype;
}
if (!barrier(g)) return RAD_E_DEVICE;
for (int r = 0; r < world; ++r) {
if (!g.slot[r] || g.nel[r] != nel) return RAD_E_SHAPE;
if (g.dt[r] != x->dtype) return RAD_E_DTYPE;
}
return RAD_OK;
}
/* Staging, so a rank does not overwrite its buffer while a peer still reads it. Uses the arena's
* scratch when large enough, else the per-thread workspace (for direct callers that pass none). */
static float* staging(const RadArgs* a, int64_t nel) {
if (a->scratch && a->scratch_bytes >= nel * (int64_t)sizeof(float))
return (float*)a->scratch;
@@ -98,18 +119,30 @@ static float* staging(const RadArgs* a, int64_t nel) {
int ref_collective_init(const RadParam* p, int n_p, int rank, int world_size,
void** out) {
/* The world size in the geometry wins: declare states it, and RadBuildCtx already divided the
* model by it (spec §9). */
/* The geometry's world size wins: declare states it and RadBuildCtx divided the model by it
* (spec §9). */
int ws = world_size;
for (int i = 0; i < n_p; ++i)
if (p[i].key && std::strcmp(p[i].key, "world_size") == 0 && p[i].kind == RAD_P_INT)
ws = (int)p[i].ival;
if (out) *out = nullptr;
if (ws <= 1) return RAD_OK;
return join(rank, ws);
RAD_REF_TRY(join(rank, ws, true));
if (out) *out = &group();
return RAD_OK;
}
void ref_collective_fini(void*) {}
/* Pairs with an init that joined (its instance is the group); one that did not has none. */
void ref_collective_fini(void* inst) {
if (!inst) return;
Group& g = group();
std::lock_guard<std::mutex> lk(g.m);
if (g.members > 0) --g.members;
}
/* Test hook, exported beside the ABI entry points: how long a rank waits for its peers before
* the collective returns RAD_E_DEVICE. A non-positive value restores the default. */
extern "C" void ref_collective_timeout_ms(int ms) { g_timeout_ms.store(ms > 0 ? ms : 30000); }
int64_t ref_all_reduce_scratch(const RadArgs* a) {
const int64_t ws = p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
@@ -119,10 +152,9 @@ int64_t ref_all_reduce_scratch(const RadArgs* a) {
}
/* ------------------------------------------------------------------ all_reduce */
/* `y` is optional and absent means IN PLACE, which is the form docs/OPS.md draws and the only one
* the one-shot kernels need. libr4d's two-shot rows are not safe in place -- a rank gathers into
* the output while its own input is still being read for the scatter -- so the destination has to
* be expressible, and here it costs one branch on the store. */
/* `y` is optional; absent means in place (docs/OPS.md's form, all the one-shot kernels need).
* libr4d's two-shot rows are not safe in place, since a rank gathers into the output while its
* input is still read for the scatter, so a separate destination must be expressible. */
int ref_all_reduce(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
@@ -135,26 +167,12 @@ int ref_all_reduce(const RadArgs* a, RadStream) {
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (world <= 1) {
/* inout: the answer is already there. With a separate destination it still has to be
* COPIED there, because a caller that passed one reads it and not x. */
/* x already holds the answer; copy it to a separate destination if one was given. */
if (y) for (int64_t i = 0; i < nel; ++i) stt(y, offlin(y, i), ldt(x, offlin(x, i)));
return RAD_OK;
}
const int rank = a->rank;
RAD_REF_TRY(join(rank, world));
RAD_REF_TRY(publish(a->rank, world, x, nel));
Group& g = group();
{
std::lock_guard<std::mutex> lk(g.m);
g.slot[rank] = x->data;
g.nel [rank] = nel;
g.dt [rank] = x->dtype;
}
if (!barrier(g)) return RAD_E_DEVICE;
for (int r = 0; r < world; ++r)
if (!g.slot[r] || g.nel[r] != nel || g.dt[r] != x->dtype) return RAD_E_SHAPE;
float* acc = staging(a, nel);
for (int64_t i = 0; i < nel; ++i) {
float s = 0.0f;
@@ -162,9 +180,8 @@ int ref_all_reduce(const RadArgs* a, RadStream) {
acc[i] = s;
}
/* Everyone has finished READING before anyone WRITES. Without this the rank that finishes
* first would overwrite an input a slower peer has not consumed yet, and the bug would show up
* as a rank-dependent answer under load and never in a small test. */
/* Every rank finishes reading before any writes; otherwise a fast rank overwrites input a
* slower peer has not consumed, giving rank-dependent answers under load. */
if (!barrier(g)) return RAD_E_DEVICE;
for (int64_t i = 0; i < nel; ++i) stt(dst, offlin(dst, i), acc[i]);
return RAD_OK;
@@ -173,14 +190,10 @@ int ref_all_reduce(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ all_gather */
/* y is [world_size * numel] with rank r's contribution at offset r * numel.
*
* A GATHER MOVES BYTES, NOT NUMBERS, and here the difference is not academic. The vocab-parallel
* candidate merge gathers (id, score) pairs as an opaque u32 payload -- the ids are i32 and the
* scores are f32 bit patterns, in one buffer. Carried through float, an id of -1 (0xFFFFFFFF, the
* empty-candidate marker) becomes 4294967296.0f, which is one past the largest u32, and storing
* that back is undefined; it lands as zero. A float-carrying reference therefore disagrees with a
* correct kernel on exactly the padding of every gathered candidate list, and rounds every id
* above 2^24 as well. Copying the stored representation is also simply what the operation IS: no
* arithmetic happens here. */
* A gather moves bytes, not numbers. The vocab-parallel candidate merge gathers (id, score) pairs
* as an opaque u32 payload of i32 ids and f32 bit patterns. Through float, the -1 empty-candidate
* id (0xFFFFFFFF) becomes 4294967296.0f, which stores back as zero (undefined), and ids above 2^24
* round. */
int ref_all_gather(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -188,9 +201,8 @@ int ref_all_gather(const RadArgs* a, RadStream) {
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (nel <= 0 || numel(y) < nel * world) return RAD_E_SHAPE;
/* One element has to have an address of its own for a byte copy to mean anything, which rules
* out the sub-byte codes -- and a gather of packed weights is not a thing any caller asks
* for, so refusing says more than a silent unpack would. */
/* A byte copy needs whole-byte elements; sub-byte codes are refused (no caller gathers packed
* weights). */
const int64_t esz = rad_dtype_bytes(x->dtype, 1);
if (esz <= 0 || y->dtype != x->dtype) return RAD_E_DTYPE;
@@ -201,25 +213,11 @@ int ref_all_gather(const RadArgs* a, RadStream) {
return RAD_OK;
}
const int rank = a->rank;
RAD_REF_TRY(join(rank, world));
RAD_REF_TRY(publish(a->rank, world, x, nel));
Group& g = group();
{
std::lock_guard<std::mutex> lk(g.m);
g.slot[rank] = x->data;
g.nel [rank] = nel;
g.dt [rank] = x->dtype;
}
if (!barrier(g)) return RAD_E_DEVICE;
for (int r = 0; r < world; ++r) {
if (!g.slot[r] || g.nel[r] != nel) return RAD_E_SHAPE;
if (g.dt[r] != x->dtype) return RAD_E_DTYPE;
}
/* WHERE A RANK'S ELEMENTS LAND. `row` absent (or the whole message) is the plain
* concatenation; present, the placement is row-interleaved -- x is [rows][row] and y is
* [rows][world][row] -- which is the form the vocab-parallel candidate merge reads, because it
* takes one row of gathered candidates per sampled position at a single row stride. */
/* Placement. `row` absent (or the whole message) is plain concatenation; present, it is
* row-interleaved, x [rows][row] into y [rows][world][row], the form the vocab-parallel
* candidate merge reads (one row of candidates per sampled position at one stride). */
const int64_t row = p_int(a, "row", 0);
if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE;
for (int r = 0; r < world; ++r)
@@ -231,9 +229,8 @@ int ref_all_gather(const RadArgs* a, RadStream) {
(const char*)g.slot[r] + i * esz, (size_t)esz);
}
/* y is a different buffer from x, so no second barrier is needed for correctness -- but the
* ranks must not race ahead into the NEXT collective while a peer still reads this one's
* input, and the pairing of barriers is what keeps the call sequences aligned. */
/* y is separate from x, but ranks must not start the next collective while a peer still reads
* this one's input; the barrier also keeps call sequences paired. */
if (!barrier(g)) return RAD_E_DEVICE;
return RAD_OK;
}
+295 -168
View File
@@ -1,43 +1,45 @@
/* ref_common.h -- libref's numeric bedrock: dtype conversion, strided element access, and
* the parameter readers every op shares.
/* ref_common.h -- libref's numeric core: dtype conversion, strided element access, and the
* parameter readers every op shares.
*
* ============================ THE NUMERICS ARE THE REFERENCE DEFINITION ============================
* The numerics are the reference definition. rad-kbench compares each resolved kernel against
* this plugin to a tolerance, so these rules are part of the contract:
*
* rad-kbench compares a resolved kernel against this plugin to a tolerance, so what this plugin
* computes is not "one correct answer" -- it is THE answer, and every rule below is part of the
* contract rather than an implementation detail:
* * Every accumulation is f32. Not double: device kernels accumulate in f32, and an oracle more
* accurate than what it certifies makes a tolerance ambiguous. Not the operand dtype either: a
* bf16 accumulator would be worse than every kernel it judges. The exceptions sum in double
* and are part of their op's definition (docs/OPS.md):
* - seg_mean's segment sums, which OPS.md states;
* - gram_accum's Gram matrix, a calibration statistic read once at convert time;
* - logit_rerank's dot products, an exact rescoring of a coarse head's candidates;
* - sample_logprobs' normaliser, the sum of exp over the whole vocabulary;
* - givens_dense_quant's dense rotation and ple_gate's key-query dot;
* - the sums of squares of hc_read's, mtp_enter's, ple_gate's and qsa_block_key's norms. An
* f32 sum of n squares differs by at most about n * 2^-24 relative, which at these widths
* (n <= 10240) stays below one bf16 rounding of the normed value.
* * IEEE round-to-nearest-even everywhere, including the f32 -> bf16 / f16 / fp8 rounders. The
* target has no bf16 convert instruction, so software RTNE is the right reference.
* * No fused multiply-add and no reassociation: `a*b + c` rounds twice. A contracting reference
* disagrees with itself across compilers. libref/CMakeLists.txt passes -ffp-contract=off.
* * Summation order is fixed and independent of thread count. OpenMP parallelism is only over
* whole output elements (a row, a column block, a head), with no `reduction()` clause anywhere,
* so runs at different thread counts are bit-identical.
*
* * EVERY accumulation is f32. Not double, because a device kernel accumulates in f32 and an
* oracle that is more accurate than the thing it certifies turns a tolerance into a guess
* about which of the two is drifting. Not the operand dtype either: a bf16 accumulator would
* make the reference worse than every kernel it judges.
* * IEEE round-to-nearest-even everywhere, including the hand-written f32 -> bf16 / f16 / fp8
* rounders below. There is no bf16 convert instruction anywhere on this project's target, so
* a software RTNE is the right reference and not a workaround.
* * NO FUSED MULTIPLY-ADD AND NO REASSOCIATION. `a*b + c` must round twice. A reference that
* contracts is a reference that disagrees with itself between two compilers, and one that
* reassociates cannot be trusted to a tolerance at all. The pragma below asks the compiler for
* this and libref/CMakeLists.txt passes -ffp-contract=off, because the pragma is advisory
* in C++ and the flag is not.
* * SUMMATION ORDER IS FIXED AND INDEPENDENT OF THREAD COUNT. OpenMP parallelism in this plugin
* is only ever over whole output elements -- one thread owns a row, a column block, a head --
* and there is not one `reduction()` clause in the plugin. Two runs at different thread counts
* are bit-identical, which is what makes a diff against a device kernel mean something.
* This plugin is deliberately simple: scalar loops with a per-element dtype switch outside the few
* hot paths (the GEMM tiles, ref_gemm.h, and the delta-net scans, ref_gdn.cpp, which run
* independent output chains side by side without changing any chain). Its jobs are to run an
* unsupported model at reduced speed instead of not at all, and to be what every fast kernel is
* checked against (spec §17).
*
* The cost of all of this is stated plainly: this plugin is slow. It is a nest of scalar loops
* with a per-element dtype switch outside the few paths that matter, and it is meant to be. Its
* jobs are to make an unsupported model run at reduced speed instead of not at all, and to be the
* thing every fast kernel is checked against (spec §17).
* An operand of a dtype these conversions cannot read or store is refused at launch
* (ref_registry.cpp), never read as zeros.
*/
#ifndef RAD_REF_COMMON_H
#define RAD_REF_COMMON_H
/* THE CONTRACTION RULE IS A BUILD FLAG, NOT A PRAGMA. `#pragma STDC FP_CONTRACT` is C, and g++
* ignores it with a warning on every translation unit that includes this header; clang's
* equivalent is spelled differently and is scoped. libref/CMakeLists.txt therefore passes
* -ffp-contract=off on the target, which every compiler this project builds with honours, and the
* top-level build already sets it for device code (docs/OPS.md). If you compile these sources by
* hand, pass it. */
/* The no-contraction rule is a build flag, not a pragma: `#pragma STDC FP_CONTRACT` is C and g++
* ignores it with a warning, and clang's equivalent is spelled differently and scoped. The target
* gets -ffp-contract=off from libref/CMakeLists.txt (the top-level build sets it for device code,
* docs/OPS.md). Pass it when compiling these sources by hand. */
#include "rad_abi.h"
#include "rad_plugin.h"
@@ -52,13 +54,9 @@ namespace ref {
/* ================================================================== narrowing conversions
*
* ONE DEFINITION, IN rad_plugin.h, and these are the names ref's kernels call it by.
*
* These conversions ARE the reference definition, which is why they belong in the header every
* plugin gets rather than in this file. This plugin's contract is f32 accumulation, IEEE
* round-to-nearest-ties-to-even, no FMA and no reassociation, and a plugin whose bf16 narrowing
* truncates instead of rounding to even cannot reproduce it and therefore cannot be checked
* against it. A convention every implementer has to rediscover is a convention that drifts. */
* Local names for rad_plugin.h's conversions. They are part of the reference definition, so they
* live in the header every plugin gets: a plugin whose bf16 narrowing truncates instead of rounding
* to even cannot be checked against this one. */
static inline float bf16_to_f32(uint16_t h) { return rad_bf16_to_f32(h); }
static inline uint16_t f32_to_bf16(float f) { return rad_f32_to_bf16(f); }
static inline float f16_to_f32(uint16_t h) { return rad_f16_to_f32(h); }
@@ -68,8 +66,17 @@ static inline uint8_t f32_to_fp8e4m3(float f) { return rad_f32_to_fp8e4m3(f);
static inline float fp8e5m2_to_f32(uint8_t b) { return rad_fp8e5m2_to_f32(b); }
static inline uint8_t f32_to_fp8e5m2(float f) { return rad_f32_to_fp8e5m2(f); }
/* OCP MXFP4 element (e2m1): sign in bit 3, exponent in 2:1, mantissa in bit 0. Eight magnitudes,
* and no infinity or NaN -- the format has no room for either. */
/* E4M3 decoded through a table of all 256 codes, filled by fp8e4m3_to_f32 itself: the same
* floats without the decode's branches, which otherwise dominate an fp8 GEMM or KV-cache read. */
struct Fp8Table {
float v[256];
Fp8Table() { for (int b = 0; b < 256; ++b) v[b] = fp8e4m3_to_f32((uint8_t)b); }
};
inline const Fp8Table kFp8Table;
static inline float fp8e4m3_lut(uint8_t b) { return kFp8Table.v[b]; }
/* OCP MXFP4 element (e2m1): sign in bit 3, exponent in 2:1, mantissa in bit 0. Eight magnitudes;
* no infinity or NaN. */
static inline float mxfp4_elem_to_f32(uint8_t nib) {
static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
float v = kMag[nib & 0x7u];
@@ -83,19 +90,21 @@ static inline float e8m0_to_f32(uint8_t e) {
}
/* ================================================================== packed weight codes
* The packing conventions are libr4d's, because a .rad file is specific to a kernel set (spec
* §4.2) and ref has to read the same bytes the fast kernel does:
* The canonical planes a container stores (abi/rad_encoding.h): sub-byte codes are a bit stream
* along the row, lowest bits first, and integer codes are two's complement (abi/rad_types.h).
* libref rearranges no plane (its relayouts only join whole planes, ref_planes.h), so it reads
* these bytes as stored; the op oracle compares a device kernel that relayouts a weight at load
* after RadUnrelayoutFn restores this form.
*
* RAD_I4 two nibbles per byte, element 2i in the LOW nibble; symmetric two's-complement code,
* value = (n ^ 8) - 8, so 0..15 maps to -8..7. This is what radiance_w4.pack writes and
* what r4d_dequant_w4_bf16's `twos=1` path reads.
* RAD_I2 four codes per byte, element 4i in the LOW two bits; value = (c ^ 2) - 2, the same
* construction one radix down, so 0..3 maps to -2..1.
* RAD_FP4E2M1 two e2m1 nibbles per byte, element 2i low, with one e8m0 scale per 32 elements
* carried in a separate stream (the `b_scale` operand).
* RAD_I4 two nibbles per byte, element 2i in the low nibble; two's-complement code,
* value = (n ^ 8) - 8, so 0..15 maps to -8..7.
* RAD_I2 four codes per byte, element 4i in the low two bits; value = (c ^ 2) - 2, so 0..3 maps
* to -2..1.
* RAD_FP4E2M1 two e2m1 nibbles per byte, element 2i low, with one e8m0 scale per 32 elements in a
* separate stream (the `b_scale` operand).
*
* All three return the RAW CODE's value. The group scale is applied by the caller, because only
* the caller knows where the scale stream is. */
* All three return the raw code's value; the caller applies the group scale, since only it knows
* where the scale stream is. */
static inline float w4_code(const void* p, int64_t i) {
uint8_t b = ((const uint8_t*)p)[i >> 1];
uint8_t n = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
@@ -112,29 +121,66 @@ static inline float mxfp4_code(const void* p, int64_t i) {
}
/* ================================================================== element access
* One switch per element, which is the price of being generic. The GEMM family lifts it out with
* the templated loaders below; nothing else runs often enough to care. */
* One switch per element, the price of being generic. The GEMM family hoists it with the templated
* loaders below; nothing else runs often enough to matter. */
static inline float ld_dt(uint32_t dt, const void* p, int64_t i) {
switch (dt) {
case RAD_F32: return ((const float*)p)[i];
case RAD_F16: return f16_to_f32(((const uint16_t*)p)[i]);
case RAD_BF16: return bf16_to_f32(((const uint16_t*)p)[i]);
case RAD_F8E4M3: return fp8e4m3_to_f32(((const uint8_t*)p)[i]);
case RAD_F8E4M3: return fp8e4m3_lut(((const uint8_t*)p)[i]);
case RAD_F8E5M2: return fp8e5m2_to_f32(((const uint8_t*)p)[i]);
case RAD_I8: return (float)((const int8_t*)p)[i];
case RAD_U8: return (float)((const uint8_t*)p)[i];
case RAD_BOOL: return ((const uint8_t*)p)[i] ? 1.0f : 0.0f;
case RAD_I16: return (float)((const int16_t*)p)[i];
case RAD_U16: return (float)((const uint16_t*)p)[i];
case RAD_I32: return (float)((const int32_t*)p)[i];
case RAD_U32: return (float)((const uint32_t*)p)[i];
case RAD_I64: return (float)((const int64_t*)p)[i];
case RAD_I4: return w4_code(p, i);
case RAD_I2: return w2_code(p, i);
case RAD_FP4E2M1: return mxfp4_code(p, i);
case RAD_E8M0: return e8m0_to_f32(((const uint8_t*)p)[i]);
/* Unreachable through a launch: the registry refuses an operand of any other dtype
* (ref_registry.cpp, ref_check_dtypes). */
default: return 0.0f;
}
}
/* A packed code's bits `c` (already masked to `bits`) into element `i` of a bit stream, lowest
* bits first. The two atomics touch only this element's bits, so rows written by different threads
* may share a byte. */
static inline void st_packed(void* p, int64_t i, int bits, unsigned c) {
const int per = 8 / bits;
uint8_t* b = (uint8_t*)p + i / per;
const int sh = (int)(i % per) * bits;
const uint8_t mask = (uint8_t)(((1u << bits) - 1u) << sh);
__atomic_fetch_and(b, (uint8_t)~mask, __ATOMIC_RELAXED);
__atomic_fetch_or(b, (uint8_t)((c << sh) & mask), __ATOMIC_RELAXED);
}
/* The e2m1 code nearest `v` (ties to the even code), saturating at 6; NaN is +0. */
static inline unsigned e2m1_code(float v) {
static const float kMag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
if (v != v) return 0u;
const unsigned sign = std::signbit(v) ? 8u : 0u;
const float a = std::fabs(v);
unsigned best = 0;
for (unsigned c = 1; c < 8; ++c) {
const float d = std::fabs(kMag[c] - a), db = std::fabs(kMag[best] - a);
if (d < db || (d == db && (c & 1u) == 0u)) best = c;
}
return sign | best;
}
/* `v` rounded to nearest even and clamped to [lo, hi]; NaN is 0. */
static inline float sat_round(float v, float lo, float hi) {
if (v != v) return 0.0f;
const float r = std::nearbyintf(v);
return r < lo ? lo : (r > hi ? hi : r);
}
static inline void st_dt(uint32_t dt, void* p, int64_t i, float v) {
switch (dt) {
case RAD_F32: ((float*)p)[i] = v; break;
@@ -142,25 +188,42 @@ static inline void st_dt(uint32_t dt, void* p, int64_t i, float v) {
case RAD_BF16: ((uint16_t*)p)[i] = f32_to_bf16(v); break;
case RAD_F8E4M3: ((uint8_t*)p)[i] = f32_to_fp8e4m3(v); break;
case RAD_F8E5M2: ((uint8_t*)p)[i] = f32_to_fp8e5m2(v); break;
/* Integer stores round-to-nearest and saturate. A reference that wrapped would turn one
* overflowing activation into a plausible small number, which is the failure this plugin
* exists to catch rather than to commit. */
case RAD_I8: { float r = std::nearbyintf(v); r = r < -128.f ? -128.f : (r > 127.f ? 127.f : r);
((int8_t*)p)[i] = (int8_t)r; break; }
case RAD_U8: { float r = std::nearbyintf(v); r = r < 0.f ? 0.f : (r > 255.f ? 255.f : r);
((uint8_t*)p)[i] = (uint8_t)r; break; }
/* Integer stores round to nearest even, saturate to the type's range and store NaN as 0.
* Wrapping would turn an overflowing activation into a plausible small number, the kind
* of failure this plugin must catch. */
case RAD_I8: ((int8_t*)p)[i] = (int8_t)sat_round(v, -128.0f, 127.0f); break;
case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)sat_round(v, 0.0f, 255.0f); break;
case RAD_BOOL: ((uint8_t*)p)[i] = v != 0.0f ? 1u : 0u; break;
case RAD_I16: { float r = std::nearbyintf(v); r = r < -32768.f ? -32768.f : (r > 32767.f ? 32767.f : r);
((int16_t*)p)[i] = (int16_t)r; break; }
case RAD_I32: ((int32_t*)p)[i] = (int32_t)std::nearbyintf(v); break;
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)std::nearbyintf(v); break;
case RAD_I64: ((int64_t*)p)[i] = (int64_t)std::nearbyintf(v); break;
default: break;
case RAD_I16: ((int16_t*)p)[i] = (int16_t)sat_round(v, -32768.0f, 32767.0f); break;
case RAD_U16: ((uint16_t*)p)[i] = (uint16_t)sat_round(v, 0.0f, 65535.0f); break;
/* Bounds that are powers of two, exact in f32: at and past 2^31 (2^32, 2^63) the store
* saturates to the largest value, which f32 cannot hold. */
case RAD_I32: {
const float r = sat_round(v, -0x1p31f, 0x1p31f);
((int32_t*)p)[i] = r >= 0x1p31f ? INT32_MAX : (int32_t)r;
break;
}
case RAD_U32: {
const float r = sat_round(v, 0.0f, 0x1p32f);
((uint32_t*)p)[i] = r >= 0x1p32f ? UINT32_MAX : (uint32_t)r;
break;
}
case RAD_I64: {
const float r = sat_round(v, -0x1p63f, 0x1p63f);
((int64_t*)p)[i] = r >= 0x1p63f ? INT64_MAX : (int64_t)r;
break;
}
/* Packed codes: the nearest code, saturated, so a code read by ld_dt stores back as
* itself (a gather or scatter of packed rows moves them exactly). */
case RAD_I4: st_packed(p, i, 4, (unsigned)(int)sat_round(v, -8.0f, 7.0f) & 0xFu); break;
case RAD_I2: st_packed(p, i, 2, (unsigned)(int)sat_round(v, -2.0f, 1.0f) & 0x3u); break;
case RAD_FP4E2M1: st_packed(p, i, 4, e2m1_code(v)); break;
default: break; /* refused at launch, as in ld_dt */
}
}
/* Integer reads that must NOT go through f32: a token id, a slot index or a block id above 2^24
* would come back rounded. Index tensors are read with this and never with ld_dt. */
/* Integer reads that must not go through f32, where an id above 2^24 (token, slot, block) would
* be rounded. Index tensors are read with this, never with ld_dt. */
static inline int64_t ld_int(uint32_t dt, const void* p, int64_t i) {
switch (dt) {
case RAD_I32: return (int64_t)((const int32_t*)p)[i];
@@ -188,13 +251,13 @@ static inline void st_int(uint32_t dt, void* p, int64_t i, int64_t v) {
}
/* ================================================================== templated loaders
* The GEMM family reads one element per FLOP, so the switch above would be most of its cost. These
* let a caller hoist the decision to the top of the op and pay it once. */
* The GEMM family reads one element per FLOP, so the switch above would dominate its cost. These
* let a caller resolve the dtype once at the top of the op. */
template <uint32_t DT> struct Cvt;
template <> struct Cvt<RAD_F32> { static inline float ld(const void* p, int64_t i) { return ((const float*)p)[i]; } };
template <> struct Cvt<RAD_F16> { static inline float ld(const void* p, int64_t i) { return f16_to_f32(((const uint16_t*)p)[i]); } };
template <> struct Cvt<RAD_BF16> { static inline float ld(const void* p, int64_t i) { return bf16_to_f32(((const uint16_t*)p)[i]); } };
template <> struct Cvt<RAD_F8E4M3> { static inline float ld(const void* p, int64_t i) { return fp8e4m3_to_f32(((const uint8_t*)p)[i]); } };
template <> struct Cvt<RAD_F8E4M3> { static inline float ld(const void* p, int64_t i) { return fp8e4m3_lut(((const uint8_t*)p)[i]); } };
template <> struct Cvt<RAD_I8> { static inline float ld(const void* p, int64_t i) { return (float)((const int8_t*)p)[i]; } };
template <> struct Cvt<RAD_I32> { static inline float ld(const void* p, int64_t i) { return (float)((const int32_t*)p)[i]; } };
template <> struct Cvt<RAD_I4> { static inline float ld(const void* p, int64_t i) { return w4_code(p, i); } };
@@ -203,23 +266,19 @@ template <> struct Cvt<RAD_FP4E2M1> { static inline float ld(const void* p, int
/* ------------------------------------------------------------------ the ranged key
*
* A RANGED PARAMETER NAMES THE BAND AND THE OPERAND NAMES THE CALL, and every kernel below that
* wants a row count asks the operand.
* A ranged parameter names the band; the operand names the call. Every kernel that wants a row
* count reads it from the operand.
*
* `M`, `numel` and `q_len` are declared RAD_RANGE by the architectures, and the core freezes the
* band's UPPER BOUND into the geometry a kernel reads -- max_tok, max_seqs, the whole residual
* stream. It is what the selector matched on and what a kernel sizes a persistent buffer from;
* it is not this issue's extent. A decode step presents a few rows of a max_tok buffer, so a
* reference that reads the parameter as the length either REFUSES the call outright or, where the
* buffers are large enough to survive it, walks rows nobody wrote and reports a mismatch against
* a kernel that is right.
* `M`, `numel` and `q_len` are declared RAD_RANGE, and the core freezes the band's upper bound
* (max_tok, max_seqs, the whole residual stream) into the geometry. That is what the selector
* matched and what persistent buffers are sized from, not this issue's extent: a decode step
* presents a few rows of a max_tok buffer. Reading the parameter as the length would refuse the
* call or walk unwritten rows and report a false mismatch. The engine binds every operand with its
* real shape at issue, and libr4d reads the operand too (its all-reduce uses `numel` only to size
* peer scratch at init).
*
* libr4d reads the operand for the same reason -- the all-reduce shim takes r4d_numel(x) and uses
* its `numel` parameter only to size the peer scratch at init -- and the engine binds every
* operand with its real shape at issue, which is what makes the operand the honest source.
*
* The parameter is kept as a CEILING where one is stated: a call above the band was resolved
* against constraints it does not satisfy, and that is a caller bug worth refusing. */
* The parameter stays a ceiling where one is stated: a call above the band was resolved against
* constraints it does not satisfy, a caller bug worth refusing. */
static inline int64_t band_rows(int64_t from_operand, int64_t band) {
if (from_operand <= 0) return 0;
return (band > 0 && from_operand > band) ? 0 : from_operand;
@@ -233,12 +292,9 @@ static inline int64_t numel(const RadTensor* t) {
return n;
}
static inline bool contig(const RadTensor* t) { return rad_tensor_is_contiguous(t) != 0; }
/* Element offset of the `lin`-th element in row-major logical order. Contiguous is the norm and
* costs nothing; a strided view -- a slice of a wider projection, which the GDN block hands its
* conv in every real model -- costs a decomposition, and is supported rather than refused because
* "no geometry constraints" has to mean strides too. */
/* Element offset of the `lin`-th element in row-major logical order. Contiguous costs nothing; a
* strided view (a slice of a wider projection, as the GDN block passes its conv) costs a
* decomposition. Strides are supported because the reference has no geometry constraints. */
static inline int64_t offlin(const RadTensor* t, int64_t lin) {
if (t->rank == 0) return lin;
int64_t acc = 1;
@@ -258,12 +314,12 @@ static inline int64_t offlin(const RadTensor* t, int64_t lin) {
return off;
}
/* The element offset of logical row `r` when a tensor is read as [rows, cols]: rows is everything
* but the last dimension and cols is the last. This is the shape almost every op here wants. */
/* Element offset of logical row `r` when a tensor is read as [rows, cols], cols being the last
* dimension and rows everything before it. Most ops here use this view. */
static inline int64_t rowoff(const RadTensor* t, int64_t r, int64_t cols) {
if (t->rank >= 2 && t->shape[t->rank - 1] == cols) {
/* Walk the leading dimensions with their own strides, so a [T,H,V] tensor read as
* [T*H, V] lands correctly even when H's stride is not V. */
* [T*H, V] is correct even when H's stride is not V. */
int64_t off = 0;
for (int i = (int)t->rank - 2; i >= 0; --i) {
int64_t s = t->shape[i];
@@ -283,18 +339,40 @@ static inline int64_t laststride(const RadTensor* t) {
static inline float ldt(const RadTensor* t, int64_t off) { return ld_dt(t->dtype, t->data, off); }
static inline void stt(const RadTensor* t, int64_t off, float v) { st_dt(t->dtype, t->data, off, v); }
/* `v` rounded through a store and load of dtype `dt`, as an unfused pair rounds the tensor between
* them. Whole-byte dtypes only. */
static inline float round_dt(uint32_t dt, float v) {
uint64_t buf = 0;
st_dt(dt, &buf, 0, v);
return ld_dt(dt, &buf, 0);
}
/* Rows of a tensor read as [rows, n]: `n` is a parameter, the row count comes from the operand
* (ref_ops.h). */
static inline int64_t rows_of(const RadTensor* t, int64_t n) { return n > 0 ? numel(t) / n : 0; }
/* Entry `i` of a cu_seqlens operand. */
static inline int64_t cu_at(const RadTensor* cu, int64_t i) {
return ld_int(cu->dtype, cu->data, offlin(cu, i));
}
/* The sequence that owns dense row `r`; a linear scan, since there are few. */
static inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) {
int64_t s = 0;
while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s;
return s;
}
/* ================================================================== parameters
*
* p_find FORWARDS to the ABI's own lookup, and the property that makes that safe is that
* rad_args_geti/gets and the rest are `static inline` in the headers: this .so carries its own
* copy and has no undefined symbol from rad_abi.h. That matters because a kernel plugin links only
* the ABI (spec 18) -- a plugin referencing a symbol defined inside the engine would fail to
* dlopen unless the host exported its whole static core dynamically, which is a build coupling
* this side of the boundary must not have.
* p_find forwards to the ABI's lookup. That is safe because the rad_args_* helpers are `static
* inline` in the headers, so this .so has no undefined symbol from rad_abi.h. A kernel plugin links
* only the ABI (spec 18); referencing an engine symbol would break dlopen unless the host exported
* its static core.
*
* The getters below stay ref's own, because they are deliberately LAXER than the ABI's: they
* accept a RANGE and a string spelling of an int, since a tool or a test may call a kernel
* directly with no declare in front of it to enforce the type. */
* The getters are ref's own and deliberately laxer than the ABI's: they accept a RANGE and a string
* spelling of an int, since a tool or test may call a kernel directly with no declare to enforce
* the type. */
static inline const RadParam* p_find(const RadArgs* a, const char* k) {
return a ? rad_param_find(a->p, a->n_p, k) : nullptr;
}
@@ -303,7 +381,7 @@ static inline long long p_int(const RadArgs* a, const char* k, long long dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_INT) return p->ival;
if (p->kind == RAD_P_RANGE) return p->ihi; /* see p_range_note below */
if (p->kind == RAD_P_RANGE) return p->ihi; /* the band's ceiling; see band_rows */
if (p->kind == RAD_P_STR && p->sval) return std::strtoll(p->sval, nullptr, 10);
return dflt;
}
@@ -315,10 +393,9 @@ static inline const char* p_str(const RadArgs* a, const char* k, const char* dfl
return dflt;
}
/* A real-valued parameter. These are RAD_P_F64 in the schema (docs/OPS.md), and the core refuses
* any other spelling for a float key at declare -- so `dval` is what arrives. The other kinds are
* still read here because a tool or a test may call a kernel directly, with no declare in front of
* it to enforce the type, and failing such a caller over a spelling would tell it nothing useful. */
/* A real-valued parameter. The schema types these RAD_P_F64 (docs/OPS.md) and declare refuses any
* other spelling, so `dval` is what normally arrives. Other kinds are still accepted for direct
* callers (tools, tests) with no declare in front. */
static inline float p_f32(const RadArgs* a, const char* k, float dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
@@ -329,8 +406,8 @@ static inline float p_f32(const RadArgs* a, const char* k, float dflt) {
return dflt;
}
/* An enumerated parameter that a caller may spell either way: act="silu" or act=0. Names win;
* the integer form is libr4d's ordering. */
/* An enumerated parameter spelled either way, act="silu" or act=0. Names win; the integer form
* follows libr4d's ordering. An unknown name is -1, for the caller to refuse. */
static inline int p_enum(const RadArgs* a, const char* k, const char* const* names, int n,
int dflt) {
const RadParam* p = p_find(a, k);
@@ -338,35 +415,50 @@ static inline int p_enum(const RadArgs* a, const char* k, const char* const* nam
if (p->kind == RAD_P_STR && p->sval) {
for (int i = 0; i < n; ++i)
if (names[i] && std::strcmp(names[i], p->sval) == 0) return i;
return dflt;
return -1;
}
if (p->kind == RAD_P_INT) return (int)p->ival;
return dflt;
}
/* ================================================================== operand checks */
/* Errors are values (docs/IMPLEMENTATION.md). Nothing in this plugin throws, and nothing that did
* not do the work returns RAD_OK. */
/* Errors are values (docs/IMPLEMENTATION.md): nothing here throws, and nothing returns RAD_OK
* without doing the work. */
#define RAD_REF_TRY(expr) do { int _s = (expr); if (_s < 0) return _s; } while (0)
static inline const RadTensor* t_in(const RadArgs* a, int i) { return rad_arg_in(a, i); }
static inline bool have(const RadArgs* a, int n) { return rad_args_have(a, n) != 0; }
/* ================================================================== parallel loops
* OpenMP over whole outputs, with an if() clause: a loop with fewer than REF_PAR_MIN units of
* work (a unit is about one multiply-add or element access) runs on the calling thread, so a
* small op does not wake a thread team. Which thread computes an output never changes its value.
*
* REF_PAR_FOR(work) a parallel for, static schedule (REF_PAR_FOR_DYN: dynamic)
* REF_PAR_REGION(work) a parallel region, for a loop that wants per-thread setup (ws_get)
* REF_FOR / REF_FOR_DYN the for inside such a region, static or dynamic schedule */
#define REF_PRAGMA(x) _Pragma(#x)
#define REF_PAR_MIN ((int64_t)1 << 16)
#define REF_PAR_FOR(work) \
REF_PRAGMA(omp parallel for schedule(static) if((int64_t)(work) >= REF_PAR_MIN))
#define REF_PAR_FOR_DYN(work) \
REF_PRAGMA(omp parallel for schedule(dynamic) if((int64_t)(work) >= REF_PAR_MIN))
#define REF_PAR_REGION(work) REF_PRAGMA(omp parallel if((int64_t)(work) >= REF_PAR_MIN))
#define REF_FOR REF_PRAGMA(omp for schedule(static))
#define REF_FOR_DYN REF_PRAGMA(omp for schedule(dynamic))
/* ================================================================== per-thread workspace
* The gated-delta-net ops carry state that is too big for a stack frame -- a [128,128] fp32
* recurrent state alone is 64 KB, and the chunked scan wants three more matrices beside it. The
* fast kernel keeps all of that in WMMA accumulators; the reference cannot, so it needs somewhere
* to put it.
* The gated-delta-net ops carry state too big for a stack frame: a [128,128] fp32 recurrent state
* is 64 KB, and the chunked scan needs three more matrices. The fast kernel keeps that in WMMA
* accumulators; the reference needs memory.
*
* A per-thread vector that GROWS ONCE and is then reused. This is the one place in the plugin that
* allocates, and it is worth naming why it is allowed to: the engine's no-allocation rule is about
* the arena and the step path (docs/IMPLEMENTATION.md), and this allocates on the first launch of
* a shape and never again -- there is no per-step malloc. The honest alternative is a scratch hook,
* and it does not work here: scratch is sized at declare from the geometry, and the amount this
* needs depends on the OpenMP thread count, which declare does not know.
* A per-thread vector that grows once and is then reused, so it allocates only on a shape's first
* launch. A scratch hook cannot replace it: scratch is sized at declare, but this depends on the
* OpenMP thread count, which declare does not know. (This plugin is not the step path the engine's
* no-allocation rule covers, docs/IMPLEMENTATION.md; other ops allocate small per-row vectors.)
*
* ONE CALL PER LAUNCH. A second call may reallocate and invalidate the first pointer, so every op
* below asks for its whole workspace at once and carves it up itself. */
* One call per launch: a second call may reallocate and invalidate the first pointer, so each op
* requests its whole workspace at once and carves it up. */
inline float* ws_get(size_t n_floats) {
static thread_local std::vector<float> v;
if (v.size() < n_floats) v.resize(n_floats);
@@ -374,15 +466,12 @@ inline float* ws_get(size_t n_floats) {
}
/* ================================================================== exact top-k
* One step of an exact selection over a row, descending by value and, ON A TIE, by the LOWER
* index. That tie rule is libr4d's (r4d_rowtopk_bf16: "descending, ties to the lower column") and
* it has to be stated rather than left to a sort's stability, because a router that breaks ties
* differently from the kernel it is checked against routes a token to a different expert and the
* diff is a whole layer wide.
* One step of an exact selection over a row: descending by value, ties to the lower index. That is
* libr4d's rule (r4d_rowtopk_bf16) and it must be explicit, not left to sort stability: a router
* that breaks ties differently sends a token to a different expert and the whole layer diverges.
*
* `pv`/`pi` carry the previously selected (value, index); seed them with +infinity and -1. The
* cost is O(N) per selected element, i.e. O(N*R) for the whole row -- the straightforward
* definition, and the one that needs no scratch buffer to be exact. */
* `pv`/`pi` carry the previous pick (value, index); seed them with +infinity and -1. O(N) per
* selected element, O(N*R) per row, with no scratch buffer. */
static inline bool topk_next(const RadTensor* x, int64_t base, int64_t st, int64_t N,
float* pv, int64_t* pi) {
float best_v = 0.0f;
@@ -400,61 +489,99 @@ static inline bool topk_next(const RadTensor* x, int64_t base, int64_t st, int64
}
/* ================================================================== small maths
* Written out rather than taken from <cmath>'s fast paths, because the reference's exp is the one
* every softmax and every gate is checked against. std::expf is correctly rounded to well under a
* ULP on glibc, which is the accuracy an oracle wants; a device kernel's __expf is not, and the
* gap is what rad-kbench's tolerance is for. */
static inline float ref_exp(float x) { return std::exp(x); }
/* Used by locally-typical sampling, which is a threshold on |surprisal - entropy| and therefore
* needs both. Same reasoning as ref_exp: the oracle takes the correctly-rounded libm. */
static inline float ref_log(float x) { return std::log(x); }
static inline float ref_abs(float x) { return std::fabs(x); }
static inline float act_sigmoid(float x) { return 1.0f / (1.0f + std::exp(-x)); }
* Every transcendental is evaluated in double and rounded once to float. glibc's float routines
* are not the same function from one release to the next (2.41 made log1pf, tanhf, erff and
* others correctly rounded), so a float call answers differently on two hosts and an oracle held
* to its recordings exactly would fail on the one that did not record them. The double routines
* have been stable for many releases and are accurate to well under a ULP of double, so the
* rounded float is the same everywhere but for a double-rounding tie. A device kernel's __expf is
* further off; rad-kbench's tolerance covers that gap. */
static inline float ref_exp(float x) { return (float)std::exp((double)x); }
static inline float ref_log(float x) { return (float)std::log((double)x); }
static inline float ref_log1p(float x) { return (float)std::log1p((double)x); }
static inline float ref_erf(float x) { return (float)std::erf((double)x); }
static inline float ref_tanh(float x) { return (float)std::tanh((double)x); }
static inline float ref_sin(float x) { return (float)std::sin((double)x); }
static inline float ref_cos(float x) { return (float)std::cos((double)x); }
static inline float ref_pow(float b, float e) { return (float)std::pow((double)b, (double)e); }
static inline float ref_abs(float x) { return std::fabs(x); }
static inline float act_sigmoid(float x) { return 1.0f / (1.0f + ref_exp(-x)); }
static inline float act_silu(float x) { return x * act_sigmoid(x); }
/* The exact erf-based GELU, not tanh. A model trained with the tanh approximation should ask for
* it by name rather than have the reference guess; until an op says so, "gelu" is the real one. */
/* The exact erf-based GELU. "gelu" means this; the tanh approximation must be requested by name. */
static inline float act_gelu(float x) {
return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f));
return 0.5f * x * (1.0f + ref_erf(x * 0.70710678118654752f));
}
/* The tanh approximation (PyTorch's gelu_tanh / gemma's gelu_pytorch_tanh) -- the form gated
* feed-forwards are trained with. The constants are the standard fit and are the same two the
* gemm_nt_bias "gelu_tanh" epilogue uses (ref_gemm.cpp), which is a GEMM-local copy of this same
* formula; both compute the identical function, so a GELU-gated FFN and a tanh-gelu epilogue agree
* to the last bit. Kept here rather than `#include`d into ref_gemm.cpp so the elementwise header
* stays self-contained. */
/* The tanh approximation (PyTorch's gelu_tanh, Gemma's gelu_pytorch_tanh), which gated
* feed-forwards are trained with. */
static inline float act_gelu_tanh(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x)));
return 0.5f * x * (1.0f + ref_tanh(k0 * (x + k1 * x * x * x)));
}
/* softplus in the two-sided form, with the large-x cutoff FLA and libr4d both use: above the
* threshold log1p(e^x) IS x to every bit f32 holds, and evaluating it costs an overflow. */
/* softplus in the two-sided form, with FLA's and libr4d's large-x cutoff: above the threshold
* log1p(e^x) equals x in f32, and evaluating it would overflow. */
static inline float act_softplus(float x, float thr) {
if (x > thr) return x;
return x > 0.0f ? x + std::log1p(std::exp(-x)) : std::log1p(std::exp(x));
return x > 0.0f ? x + ref_log1p(ref_exp(-x)) : ref_log1p(ref_exp(x));
}
/* ================================================================== the Hadamard rotation
* The widest rotation this reference performs in one stack frame. libr4d caps `had` at 512 -- a
* power of two dividing the per-rank K, and 8704 admits no more -- so 4096 is four doublings of
* headroom. A wider request returns RAD_E_UNSUPPORTED by name rather than silently rotating a
* narrower block, because a half-applied rotation is numerically plausible and completely wrong. */
* The widest rotation this reference performs in one stack frame. libr4d caps `had` at 512 (a
* power of two dividing the per-rank K; 8704 admits no more), so 4096 leaves headroom. A wider
* request returns RAD_E_UNSUPPORTED rather than rotating a narrower block, since a half-applied
* rotation looks plausible and is wrong. */
enum { REF_HAD_MAX = 4096 };
/* The unnormalised in-place transform over `g` values, g a power of two. */
static inline void fwht(float* v, int64_t g) {
for (int64_t h = 1; h < g; h <<= 1)
for (int64_t i = 0; i < g; ++i)
if ((i & h) == 0) {
const float a = v[i], b = v[i + h];
v[i] = a + b;
v[i + h] = a - b;
for (int64_t i = 0; i < g; i += 2 * h)
for (int64_t j = i; j < i + h; ++j) {
const float a = v[j], b = v[j + h];
v[j] = a + b;
v[j + h] = a - b;
}
}
static inline bool pow2(int64_t v) { return v > 0 && (v & (v - 1)) == 0; }
/* ================================================================== the 8-bit group
* One group of the block-scaled 8-bit quantisers (constants explained at ref_quant.cpp's
* quant_act_fp8): `v(i)` for i < n is the group's values and `top` the largest code, 448 for E4M3
* and 127 for int8. The codes clamp(v(i) / scale, +-top) go to q[qb + i * qs] in q's dtype (int8
* rounded to nearest even), and the scale amax / top (1 for an all-zero group) is returned. */
template <class V>
static inline float q8_group(const V& v, int64_t n, float top, const RadTensor* q, int64_t qb,
int64_t qs) {
float amax = 0.0f;
for (int64_t i = 0; i < n; ++i) { const float m = std::fabs(v(i)); if (m > amax) amax = m; }
const float sc = amax > 0.0f ? amax * (1.0f / top) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = 0; i < n; ++i) {
float c = v(i) * inv;
if (c > top) c = top;
if (c < -top) c = -top;
st_dt(q->dtype, q->data, qb + i * qs, c);
}
return sc;
}
/* ================================================================== the int8 step order
* quant_act_i8 stores a row's codes in the order libr4d's int8 WMMA reads an A fragment: within
* each sixteen-byte step the middle two dwords are exchanged, so column c sits at byte
* i8_step_pos(c) (bits 2 and 3 of c swapped). The map is its own inverse. gemm_nt_q reads its
* activation in this order at the dtypes i8_steps_dtype names. */
static inline int64_t i8_step_pos(int64_t c) {
return (c & ~(int64_t)12) | ((c & 4) << 1) | ((c & 8) >> 1);
}
static inline bool i8_steps_dtype(const char* dt) {
static const char* const kDtypes[] = { "w4a8", "w4a8_asym", "w8a8", "w2a8" };
for (const char* d : kDtypes)
if (dt && std::strcmp(dt, d) == 0) return true;
return false;
}
} /* namespace ref */
#endif /* RAD_REF_COMMON_H */
+276 -240
View File
@@ -1,9 +1,8 @@
/* ref_elementwise.cpp -- the norms and the elementwise ops.
*
* Nothing here is interesting except where the fused forms round, and those places are the whole
* reason the ops exist: `rmsnorm_add` is one pass in every real implementation, so the reference
* has to say exactly which of its two intermediates is rounded and which is not, or a fused kernel
* checked against it fails on a tolerance nobody can explain.
* The subtle part is where fused forms round: `rmsnorm_add` is one pass in every real
* implementation, so the reference must state which intermediates are rounded, or a correct fused
* kernel fails its tolerance.
*/
#include "ref_common.h"
#include "ref_ops.h"
@@ -13,37 +12,20 @@
using namespace ref;
/* Rows of a tensor read as [rows, n]. `n` is a declared parameter and the row count is whatever
* the operand actually carries, which is the rule this plugin follows everywhere (ref_ops.h). */
static inline int64_t rows_of(const RadTensor* t, int64_t n) {
return n > 0 ? numel(t) / n : 0;
}
/* ------------------------------------------------------------------ rmsnorm */
/* y = x * rsqrt(mean(x^2) + eps) * (w + w_add)
*
* The mean is over the LAST n elements of a row and is accumulated in f32 in ascending index
* order. `w_add` is GemmaRMSNorm's `1 +`: Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain
* and use 1 + w, and forming that in the weight's dtype first loses 0.3% per channel (libr4d's
* r4d_rmsnorm_had_quant_i8 says the same). It defaults to 0, so a plain RMS norm is the plain
* call. */
int ref_rmsnorm(const RadArgs* a, RadStream) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[2];
/* An absent gain is one, and `wadd` belongs to a gain, so it is refused without one. */
const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr;
const int64_t n = p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
/* `mult` scales the normed row before its one rounding: a residual branch weighted by a
* constant (Gemma 4's audio feed-forward, a half) without a second pass over the row. */
const float mult = p_f32(a, "mult", 1.0f);
* The mean is over the last n elements of a row, accumulated in f32 in ascending index order.
* `w_add` is GemmaRMSNorm's `1 +`: Qwen3.5, Qwen3-Next and Gemma store a zero-centred gain and use
* 1 + w, and forming that in the weight's dtype first loses 0.3% per channel. Default 0. An absent
* gain `w` is 1. */
static int rms_rows(const RadTensor* x, const RadTensor* w, const RadTensor* y, int64_t n,
float eps, float wadd, float mult) {
if (n <= 0) return RAD_E_SHAPE;
if (!w && wadd != 0.0f) return RAD_E_INVAL;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || (w && numel(w) < n)) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y), ws = w ? laststride(w) : 0;
@@ -57,46 +39,35 @@ int ref_rmsnorm(const RadArgs* a, RadStream) {
return RAD_OK;
}
int ref_rmsnorm(const RadArgs* a, RadStream) {
if (!a || a->n_t < 3 || !a->t[0].data || !a->t[2].data) return RAD_E_INVAL;
const RadTensor* w = a->t[1].data ? &a->t[1] : nullptr;
const float wadd = p_f32(a, "wadd", 0.0f);
/* `wadd` without a gain is refused. */
if (!w && wadd != 0.0f) return RAD_E_INVAL;
/* `mult` scales the normed row before its single rounding, for a residual branch weighted by
* a constant (Gemma 4's audio feed-forward uses 0.5). */
return rms_rows(&a->t[0], w, &a->t[2], p_int(a, "n", w && w->rank ? w->shape[w->rank - 1] : 0),
p_f32(a, "eps", 1e-6f), wadd, p_f32(a, "mult", 1.0f));
}
/* ------------------------------------------------------------------ rmsnorm_p */
/* y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain at all. It is
* its own op rather than a zeroed gain on rmsnorm because the gain is a real, weightless thing:
* Gemma's attention normalises the VALUE with a bare RMS (llama.cpp's ggml_rms_norm(V, eps), no
* tensor) while normalising the KEY with the k_norm gain, and there is no checkpoint plane to feed
* a `wadd`/`w` through for the value -- so an rmsnorm call would need a phantom all-zero weight to
* express it, which is a name map to a tensor that does not exist. The mean is accumulated 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. */
/* y = x * rsqrt(mean(x^2) + eps): rmsnorm with no gain. A separate op because Gemma normalises the
* value with a bare RMS (llama.cpp's ggml_rms_norm(V, eps)) and the checkpoint has no plane for a
* gain; rmsnorm would need a phantom weight. */
int ref_rmsnorm_p(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y);
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); ss += v * v; }
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
for (int64_t i = 0; i < n; ++i)
stt(y, yb + i * ys, ldt(x, xb + i * xs) * s);
}
return RAD_OK;
return rms_rows(&a->t[0], nullptr, &a->t[1], p_int(a, "n", 0), p_f32(a, "eps", 1e-6f), 0.0f,
1.0f);
}
/* ------------------------------------------------------------------ rmsnorm_add */
/* residual_out = x + residual; y = rmsnorm(residual_out) * (w + w_add)
*
* THE ROUNDING IS THE CONTRACT. The sum is formed in f32 and the variance is taken from the
* UNROUNDED sum, but the multiply that produces y reads the sum back from residual_out AFTER it
* has been narrowed to that operand's dtype. That is what vLLM's fused_add_rms_norm does and what
* every fused kernel in this project will do, because the residual has to be stored anyway and
* re-reading it is free. A reference that kept f32 all the way through would be half a ULP better
* and would disagree with every kernel it certifies.
* The rounding is the contract: the variance comes from the unrounded f32 sum, but y reads the sum
* back from residual_out after it is narrowed to that dtype. vLLM's fused_add_rms_norm and every
* fused kernel here do the same, since the residual is stored anyway. Keeping f32 throughout would
* be half a ULP better and disagree with every kernel.
*/
int ref_rmsnorm_add(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
@@ -109,7 +80,7 @@ int ref_rmsnorm_add(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(y) < rows * n || numel(ro) < rows * n ||
numel(res) < rows * n || numel(w) < n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), rb = rowoff(res, r, n);
const int64_t yb = rowoff(y, r, n), ob = rowoff(ro, r, n);
@@ -129,9 +100,8 @@ int ref_rmsnorm_add(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ layernorm */
/* y = (x - mean) * rsqrt(var + eps) * w + b, with the BIASED variance (divide by n, not n-1),
* which is what every transformer implementation means by layer norm. `b` is optional: a ViT that
* dropped its bias passes a null operand rather than a zero tensor. */
/* y = (x - mean) * rsqrt(var + eps) * w + b, with the biased variance (divide by n, not n-1), as
* transformers use. `b` is optional: a bias-free ViT passes a null operand. */
int ref_layernorm(const RadArgs* a, RadStream) {
if (a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[3];
@@ -143,7 +113,7 @@ int ref_layernorm(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(y) < rows * n || numel(w) < n) return RAD_E_SHAPE;
if (b && numel(b) < n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y), ws = laststride(w);
@@ -163,19 +133,14 @@ int ref_layernorm(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ grid_embed */
/* A learned side x side table of position rows, resampled to a grid of its own size per row of x
* and added in: the vision tower's position embedding, which is trained at one grid and applied to
* images of any shape.
/* A learned side x side table of position rows, resampled per row of x to that row's grid size and
* added in: the vision tower's position embedding, trained at one grid and applied to any image
* shape.
*
* THE SAMPLING IS BILINEAR WITH THE CORNERS ALIGNED: grid row r of a grid of height g sits at table
* coordinate r * (side - 1) / max(g - 1, 1), in f32, and its two taps are the floor and the floor
* plus one, clamped to the table, weighted by distance. The four products are summed in f32 in the
* order (top-left, top-right, bottom-left, bottom-right) and rounded to x's dtype -- the position
* embedding as a tensor of its own -- and only then added to x, which is rounded again. */
static float round_to(uint32_t dt, float v) {
return dt == RAD_BF16 ? rad_bf16_to_f32(rad_f32_to_bf16(v)) : v;
}
* Bilinear with corners aligned: grid row r of height g sits at table coordinate
* r * (side - 1) / max(g - 1, 1) in f32, with taps at floor and floor + 1, clamped and weighted by
* distance. The four products are summed in f32 in the order (top-left, top-right, bottom-left,
* bottom-right), rounded to x's dtype as a tensor of its own, then added to x and rounded again. */
int ref_grid_embed(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2];
@@ -188,7 +153,7 @@ int ref_grid_embed(const RadArgs* a, RadStream) {
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 4)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gr = ld_int(crd->dtype, crd->data, 0 * cs + r * ms);
const int64_t gc = ld_int(crd->dtype, crd->data, 1 * cs + r * ms);
@@ -215,7 +180,7 @@ int ref_grid_embed(const RadArgs* a, RadStream) {
for (int kj = 0; kj < 2; ++kj)
acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) *
(wh[ki] * ww[kj]);
const float pe = round_to(x->dtype, acc);
const float pe = round_dt(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
@@ -223,10 +188,9 @@ int ref_grid_embed(const RadArgs* a, RadStream) {
}
/* grid_embed_aa: the table resampled as torch's F.interpolate(mode="bilinear", align_corners=False,
* antialias=True) does it -- SigLIP2's position embedding. Per axis a triangle filter on half-pixel
* centres, widened by the scale when shrinking, its taps inside the table normalised to sum to one.
* Separable, f32 throughout, rounded once before the add. A coordinate outside its grid is clamped
* into it, so every input is defined. */
* antialias=True), SigLIP2's position embedding. Per axis, a triangle filter on half-pixel centres,
* widened by the scale when shrinking, with in-table taps normalised to sum to one. Separable, f32
* throughout, rounded once before the add. Out-of-grid coordinates are clamped. */
static void aa_taps(int64_t at, int64_t size, int64_t side, float* w, int64_t* lo, int64_t* cnt) {
if (size < 1) size = 1;
at = at < 0 ? 0 : (at >= size ? size - 1 : at);
@@ -259,7 +223,7 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 16)
for (int64_t r = 0; r < rows; ++r) {
int64_t g[4];
for (int c = 0; c < 4; ++c) g[c] = ld_int(crd->dtype, crd->data, c * cs + r * ms);
@@ -277,7 +241,7 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
ww[(size_t)c];
acc += row * wh[(size_t)y];
}
const float pe = round_to(x->dtype, acc);
const float pe = round_dt(x->dtype, acc);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
@@ -285,10 +249,9 @@ int ref_grid_embed_aa(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ add / mul */
/* Elementwise over the output's extent. `b` may carry one row instead of all of them, so a bias
* add is this op rather than a second one: an operand with exactly `n` elements against an output
* of rows*n broadcasts along rows, and nothing else broadcasts at all. Silent broadcasting of an
* arbitrary shape is how a shape bug becomes a plausible number. */
/* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which
* broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a
* plausible number. */
static int elementwise2(const RadArgs* a, bool mul) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
@@ -299,7 +262,7 @@ static int elementwise2(const RadArgs* a, bool mul) {
const bool bcast = numel(B) == n && rows > 1;
if (!bcast && numel(B) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t ab = rowoff(A, r, n), yb = rowoff(Y, r, n);
const int64_t bb = bcast ? 0 : rowoff(B, r, n);
@@ -316,11 +279,10 @@ int ref_add(const RadArgs* a, RadStream) { return elementwise2(a, false); }
int ref_mul(const RadArgs* a, RadStream) { return elementwise2(a, true); }
/* ------------------------------------------------------------------ mul_weight */
/* y = x * w, `w` a WEIGHT of one element or of one row: a learned gain on an activation -- a
* per-layer scalar on the residual stream (Gemma 4's layer_scalar), or a per-channel one (a
* vision tower's layer scale). Its own op and not a form of `mul` because an op's operand is a
* weight or an activation by its schema, and `mul`'s `b` is an activation. The product is f32,
* rounded once to y's dtype. */
/* y = x * w, `w` a weight of one element or one row: a learned gain such as a per-layer residual
* scalar (Gemma 4's layer_scalar) or a per-channel layer scale (vision towers). Separate from `mul`
* because the schema fixes whether an operand is a weight or an activation, and `mul`'s `b` is an
* activation. The f32 product is rounded once to y's dtype. */
int ref_mul_weight(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *W = &a->t[1], *Y = &a->t[2];
@@ -332,7 +294,7 @@ int ref_mul_weight(const RadArgs* a, RadStream) {
if (!scalar && numel(W) != n) return RAD_E_SHAPE;
const int64_t ws = scalar ? 0 : laststride(W);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
@@ -343,26 +305,19 @@ int ref_mul_weight(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]) -- one scalar per ROW, broadcast across the row.
/* y[m, i] = x[m, i] * act(s[m]): one scalar per row, broadcast across it (a per-token gate).
* Separate from `mul`, which broadcasts one row down the rows; one op with both rules would be
* ambiguous when rows == n.
*
* IT IS NOT `mul`, AND THE DIFFERENCE IS WHICH AXIS BROADCASTS. `mul` lets `b` carry one ROW and
* broadcasts it down the rows, which is a bias's shape; this carries one COLUMN and broadcasts it
* across them, which is a per-token gate's. Giving `mul` both rules would make them ambiguous
* exactly when rows == n, and a silent choice between two broadcasts is how a shape bug becomes a
* plausible number -- which is the rule the comment above elementwise2 already states.
* The activation applies to the scalar, not the product: Qwen3.5-MoE's shared expert is scaled by
* `sigmoid(shared_expert_gate(x))`.
*
* The activation is applied to the SCALAR and not to the product, which is what a gate means:
* Qwen3.5-MoE's shared expert is scaled by `sigmoid(shared_expert_gate(x))`. */
/* `add` PRESENT IS THE FUSED GATE-AND-ADD FORM: y = narrow(x * act(s)) + add, and the NARROW is
* the whole of why this is expressible as one op rather than an approximation of two. The pair it
* stands in for writes the product into a bf16 buffer and then adds that buffer to `add`, so the
* product is rounded BEFORE the sum sees it; an f32 product carried into the add would differ in
* the last bit of every channel. Written here as the two stores it replaces, through `y` itself,
* because the oracle's job is to be obviously the same rather than to be quick.
*
* `add` is read before `y` is written so the two may alias without the sum reading its own output. */
* With `add` present it is the fused gate-and-add, y = narrow(x * act(s)) + add. The unfused pair
* stores the product to a bf16 buffer before adding, so the product is rounded first; this writes
* the same two stores through `y`. `add` is read before `y` is written so the two may alias. */
int ref_scale_rows(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
/* `add` (operand 2) is optional; the other three are required. */
if (a->n_t < 4 || !t_in(a, 0) || !t_in(a, 1) || !t_in(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *sc = &a->t[1], *y = &a->t[3];
const RadTensor *ad = t_in(a, 2);
const int64_t n = p_int(a, "n", numel(y));
@@ -375,7 +330,7 @@ int ref_scale_rows(const RadArgs* a, RadStream) {
if (act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t ss = laststride(sc);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const float v0 = ldt(sc, r * ss);
const float v = sig ? act_sigmoid(v0) : v0;
@@ -393,8 +348,8 @@ int ref_scale_rows(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ silu_mul */
/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the FIRST half, which is the
* order rad-convert fuses gate and up into one weight in, so the two conventions cannot drift. */
/* y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The gate is the first half, the order in
* which rad-convert fuses gate and up. */
int ref_silu_mul(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *y = &a->t[1];
@@ -403,7 +358,7 @@ int ref_silu_mul(const RadArgs* a, RadStream) {
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n);
const int64_t gs = laststride(gu), ys = laststride(y);
@@ -414,18 +369,11 @@ int ref_silu_mul(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ act_mul */
/* y = act(a) * b, the gated product with its two halves in two operands. `silu_mul` reads one
* fused gate_up row; this reads the gate and the multiplier from wherever they are, which covers
* a fused gate_up as two column slices of it AND a gate whose multiplier is some other tensor --
* Gemma's per-layer-input block multiplies gelu(gate(x)) by a per-layer embedding.
/* y = act(a) * b, the gated product with its halves in two operands: two column slices of a fused
* gate_up, or a gate whose multiplier is another tensor (Gemma's per-layer-input block multiplies
* gelu(gate(x)) by a per-layer embedding).
*
* THE ACTIVATION IS ROUNDED TO y's DTYPE BEFORE THE PRODUCT, which is what the unfused pair does:
* `act(gate)` is a tensor, and the product reads it back. */
static float gelu_tanh_f(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x)));
}
* The activation is rounded to y's dtype before the product, as the unfused pair stores it. */
int ref_act_mul(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[2];
@@ -437,38 +385,37 @@ int ref_act_mul(const RadArgs* a, RadStream) {
const int act = p_enum(a, "act", kActs, 4, -1);
if (act < 0) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t ab = rowoff(A, r, n), bb = rowoff(B, r, n), yb = rowoff(Y, r, n);
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
const float g = ldt(A, ab + i * as);
const float v = act == 0 ? act_silu(g) : act == 1 ? act_gelu(g)
: act == 2 ? gelu_tanh_f(g) : act_sigmoid(g);
stt(Y, yb + i * ys, round_to(Y->dtype, v) * ldt(B, bb + i * bs));
: act == 2 ? act_gelu_tanh(g) : act_sigmoid(g);
stt(Y, yb + i * ys, round_dt(Y->dtype, v) * ldt(B, bb + i * bs));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_mean */
/* y[s, :] = the mean of x's rows [cu[s], cu[s+1]): one row a segment, which is a sentence
* embedding's mean pooling over a ragged batch. The sum is taken in DOUBLE and divided once, so the
* pooled row does not depend on how many rows a segment has beyond the one rounding to y's dtype.
* An empty segment writes zeros. */
/* y[s, :] = mean of x's rows [cu[s], cu[s+1]): sentence-embedding mean pooling over a ragged
* batch. Summed in double and divided once, so only the final rounding to y's dtype depends on the
* segment length. An empty segment writes zeros. */
int ref_seg_mean(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = ld_int(cu->dtype, cu->data, offlin(cu, S));
if (total < 0 || numel(X) < total * n) return RAD_E_SHAPE;
const int64_t total = cu_at(cu, S);
if (total <= 0 || numel(X) < total * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR((total + S) * n)
for (int64_t s = 0; s < S; ++s) {
const int64_t b0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t b1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
const int64_t b0 = cu_at(cu, s);
const int64_t b1 = cu_at(cu, s + 1);
const int64_t yb = rowoff(Y, s, n), ys = laststride(Y), xs = laststride(X);
for (int64_t i = 0; i < n; ++i) {
double acc = 0.0;
@@ -481,8 +428,8 @@ int ref_seg_mean(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ pool_rows */
/* Row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to y's dtype, then
* multiplied by `mult` and rounded again -- the unfused pair, which stores the mean. A vision
* pooler whose processor lays each k-patch window out consecutively pools with this. */
* multiplied by `mult` and rounded again, as the unfused pair stores the mean. For vision poolers
* whose processor lays each k-patch window out consecutively. */
int ref_pool_rows(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Y = &a->t[1];
@@ -495,7 +442,7 @@ int ref_pool_rows(const RadArgs* a, RadStream) {
if (numel(Y) < rows * n) return RAD_E_SHAPE;
const float inv = 1.0f / (float)k;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows_in * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(Y, r, n), ys = laststride(Y), xs = laststride(X);
for (int64_t i = 0; i < n; ++i) {
@@ -518,7 +465,7 @@ int ref_relu(const RadArgs* a, RadStream) {
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
@@ -531,8 +478,8 @@ int ref_relu(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ clamp */
/* y = min(max(x, lo), hi), the bounds WEIGHTS of one element each: a clipped linear's input or
* output range (Gemma 4's audio tower), which the checkpoint states per projection. */
/* y = min(max(x, lo), hi), the bounds being one-element weights: a clipped linear's input or output
* range, stated per projection in the checkpoint (Gemma 4's audio tower). */
int ref_clamp(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *L = &a->t[1], *H = &a->t[2], *Y = &a->t[3];
@@ -542,7 +489,7 @@ int ref_clamp(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE;
const float lo = ldt(L, 0), hi = ldt(H, 0);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(X, r, n), yb = rowoff(Y, r, n);
const int64_t xs = laststride(X), ys = laststride(Y);
@@ -560,34 +507,49 @@ int ref_clamp(const RadArgs* a, RadStream) {
/* A 2-D convolution over (time, width) with channels innermost, segment by segment.
*
* x is [M, W * cin]: row t is time t, element (t, w, c) at column w * cin + c. Each cu_seqlens
* segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved ON ITS OWN, zero-padded by `pad` at its
* edges on both axes -- two clips in one pass must not see each other -- and its output rows start
* at cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw]. With the optional `valid`
* operand, input row t (pass-global) is read as zeros unless valid[t * valid_stride] != 0: the
* frame mask Gemma 4's subsampler multiplies in before each convolution. f32 accumulation, one
* rounding. */
* segment [cu[s] / cu_div, cu[s+1] / cu_div) is convolved separately, zero-padded by `pad` on both
* axes, so clips in one pass do not see each other; its output rows start at
* cu[s] / (cu_div * stride). `w` is PyTorch's [cout, cin, kh, kw], kh over time; with `t_last` it
* is [cout, cin, kw, kh], time last (a model that convolves a [mel, time] spectrogram, whose
* kernel's first spatial axis is the one this op calls width). With the optional `valid` operand,
* input row t (pass-global) reads as zeros unless valid[t * valid_stride] != 0: Gemma 4's
* subsampler frame mask, or the chunk boundary that keeps each second of Qwen3-ASR's audio apart.
* The optional `b` adds a bias per output channel before the one rounding; `act` (`none`, `gelu`)
* is then applied to the rounded value and rounded again, as gemm_nt_bias's epilogue does. f32
* accumulation. */
int ref_conv2d(const RadArgs* a, RadStream) {
if (!a || a->n_t < 5 || !a->t[0].data || !a->t[1].data || !a->t[2].data || !a->t[4].data)
return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *Wt = &a->t[1], *cu = &a->t[2], *Y = &a->t[4];
const RadTensor* V = a->t[3].data ? &a->t[3] : nullptr;
const RadTensor* B = a->n_t > 5 && a->t[5].data ? &a->t[5] : nullptr;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1);
const bool tlast = p_int(a, "t_last", 0) != 0;
const char* act = p_str(a, "act", "none");
const bool gelu = !std::strcmp(act, "gelu");
if (!gelu && std::strcmp(act, "none")) return RAD_E_UNSUPPORTED;
if (W <= 0 || cin <= 0 || cout <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 ||
vst <= 0)
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1;
if (Wo <= 0 || numel(Wt) < cout * cin * kh * kw) return RAD_E_SHAPE;
if (B && numel(B) < cout) return RAD_E_SHAPE;
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, rout = Wo * cout;
const int64_t Min = rows_of(X, rin), Mout = rows_of(Y, rout);
if (Min <= 0 || Mout <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
/* Kernel tap (i over time, j over width) of channel pair (co, ci). */
auto widx = [&](int64_t co, int64_t ci, int64_t i, int64_t j) {
return tlast ? ((co * cin + ci) * kw + j) * kh + i : ((co * cin + ci) * kh + i) * kw + j;
};
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
const int64_t c0 = cu_at(cu, s);
const int64_t c1 = cu_at(cu, s + 1);
if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0;
if (T <= 0) continue;
@@ -596,7 +558,7 @@ int ref_conv2d(const RadArgs* a, RadStream) {
if (t0 + T > Min || o0 + To > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(To * rout * cin * kh * kw)
for (int64_t to = 0; to < To; ++to) {
const int64_t yb = rowoff(Y, o0 + to, rout), ys = laststride(Y), xs = laststride(X);
for (int64_t wo = 0; wo < Wo; ++wo)
@@ -612,17 +574,82 @@ int ref_conv2d(const RadArgs* a, RadStream) {
const int64_t wi = wo * st - pad + j;
if (wi < 0 || wi >= W) continue;
for (int64_t ci = 0; ci < cin; ++ci)
acc += ldt(X, xb + (wi * cin + ci) * xs) *
ldt(Wt, ((co * cin + ci) * kh + i) * kw + j);
acc += ldt(X, xb + (wi * cin + ci) * xs) * ldt(Wt, widx(co, ci, i, j));
}
}
stt(Y, yb + (wo * cout + co) * ys, acc);
if (B) acc += ldt(B, offlin(B, co));
const int64_t yo = yb + (wo * cout + co) * ys;
stt(Y, yo, acc);
if (gelu) stt(Y, yo, act_gelu(ldt(Y, yo)));
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv2d_unfold */
/* conv2d's receptive fields as rows, so a GEMM against the weight is the convolution: row
* (o0 + to) * Wo + wo of y holds, for every input channel and kernel tap, the value conv2d would
* multiply that tap's weight by -- zero where the tap falls in the padding or on a row `valid`
* masks. Its columns are in the weight's order, (ci, i, j) for PyTorch's [cout, cin, kh, kw] and
* (ci, j, i) with t_last, so y times the weight viewed as [cout, cin * kh * kw] is conv2d's output
* with no relayout of either: row (to, wo) of the product is column block wo of conv2d's row to.
* Segments, cu_div and valid as conv2d's; rows no segment covers are left alone. */
int ref_conv2d_unfold(const RadArgs* a, RadStream) {
if (!a || a->n_t < 4 || !a->t[0].data || !a->t[1].data || !a->t[3].data) return RAD_E_INVAL;
const RadTensor *X = &a->t[0], *cu = &a->t[1], *Y = &a->t[3];
const RadTensor* V = a->t[2].data ? &a->t[2] : nullptr;
const int64_t W = p_int(a, "width", 0), cin = p_int(a, "cin", 0);
const int64_t kh = p_int(a, "kh", 0), kw = p_int(a, "kw", 0);
const int64_t st = p_int(a, "stride", 1), pad = p_int(a, "pad", 0);
const int64_t cdiv = p_int(a, "cu_div", 1), vst = p_int(a, "valid_stride", 1);
const bool tlast = p_int(a, "t_last", 0) != 0;
if (W <= 0 || cin <= 0 || kh <= 0 || kw <= 0 || st <= 0 || pad < 0 || cdiv <= 0 || vst <= 0)
return RAD_E_SHAPE;
const int64_t Wo = (W + 2 * pad - kw) / st + 1, K = cin * kh * kw;
const int64_t S = numel(cu) - 1;
if (Wo <= 0 || S <= 0) return RAD_E_SHAPE;
const int64_t rin = W * cin, Min = rows_of(X, rin), Mout = rows_of(Y, K);
if (Min <= 0 || Mout <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = cu_at(cu, s);
const int64_t c1 = cu_at(cu, s + 1);
if (c0 % cdiv || c1 % cdiv || (c0 / cdiv) % st || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, T = c1 / cdiv - t0;
if (T <= 0) continue;
const int64_t To = (T + 2 * pad - kh) / st + 1, o0 = t0 / st;
if (To <= 0) continue;
if (t0 + T > Min || (o0 + To) * Wo > Mout) return RAD_E_SHAPE;
if (V && numel(V) < (t0 + T - 1) * vst + 1) return RAD_E_SHAPE;
REF_PAR_FOR(To * Wo * K)
for (int64_t to = 0; to < To; ++to) {
const int64_t ys = laststride(Y), xs = laststride(X);
for (int64_t wo = 0; wo < Wo; ++wo) {
const int64_t yb = rowoff(Y, (o0 + to) * Wo + wo, K);
for (int64_t i = 0; i < kh; ++i) {
const int64_t ti = to * st - pad + i;
const int64_t tg = t0 + ti;
const bool row_ok = ti >= 0 && ti < T &&
!(V && ld_int(V->dtype, V->data, offlin(V, tg * vst)) == 0);
for (int64_t j = 0; j < kw; ++j) {
const int64_t wi = wo * st - pad + j;
const bool ok = row_ok && wi >= 0 && wi < W;
for (int64_t ci = 0; ci < cin; ++ci) {
const int64_t k = tlast ? (ci * kw + j) * kh + i : (ci * kh + i) * kw + j;
const float v = ok ? ldt(X, rowoff(X, tg, rin) + (wi * cin + ci) * xs)
: 0.0f;
stt(Y, yb + k * ys, v);
}
}
}
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ conv1d_dw */
/* A causal depthwise convolution over time: y[t, c] = sum_j w[c, j] * x[t - (k-1) + j, c], the
* rows before the segment's start (cu[s] / cu_div) read as zeros. `w` is PyTorch's depthwise
@@ -635,15 +662,16 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) {
const int64_t S = numel(cu) - 1;
if (S <= 0) return RAD_E_SHAPE;
const int64_t Mx = rows_of(X, C), My = rows_of(Y, C);
if (Mx <= 0 || My <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t c1 = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
const int64_t c0 = cu_at(cu, s);
const int64_t c1 = cu_at(cu, s + 1);
if (c0 % cdiv || c1 % cdiv || c1 < c0) return RAD_E_SHAPE;
const int64_t t0 = c0 / cdiv, t1 = c1 / cdiv;
if (t1 > Mx || t1 > My) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR((t1 - t0) * C * K)
for (int64_t t = t0; t < t1; ++t) {
const int64_t yb = rowoff(Y, t, C), ys = laststride(Y), xs = laststride(X);
for (int64_t c = 0; c < C; ++c) {
@@ -661,9 +689,9 @@ int ref_conv1d_dw(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ rel_sinusoid */
/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first
* half, cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)).
* Computed in f32 step by step the way the reference's torch expressions are, then rounded. */
/* The sinusoidal relative-position table, row d for distance d: sin(d * inv[i]) in the first half,
* cos(d * inv[i]) in the second, inv[i] = exp(i * -log(max_timescale) / max(n/2 - 1, 1)). Computed
* in f32 step by step as the upstream torch expressions are, then rounded. */
int ref_rel_sinusoid(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* Y = &a->t[0];
@@ -675,27 +703,24 @@ int ref_rel_sinusoid(const RadArgs* a, RadStream) {
const double mt = (double)p_f32(a, "max_timescale", 10000.0f);
const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t d = 0; d < rows; ++d) {
const int64_t yb = rowoff(Y, d, n), ys = laststride(Y);
for (int64_t i = 0; i < h; ++i) {
const float inv = std::exp((float)i * -inc);
const float inv = ref_exp((float)i * -inc);
const float ang = (float)d * inv;
stt(Y, yb + i * ys, std::sin(ang));
stt(Y, yb + (h + i) * ys, std::cos(ang));
stt(Y, yb + i * ys, ref_sin(ang));
stt(Y, yb + (h + i) * ys, ref_cos(ang));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu_mul */
/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i] -- the tanh GELU, and the gate is the
* FIRST half, for the same order-locking reason as silu_mul. This is Gemma's gated FFN
* (down(gelu_tanh(gate(x)) * up(x)), activation gelu_pytorch_tanh in the checkpoint). It is not
* `gemm_nt`'s "gelu_tanh" EPLOGUE, which applies the activation to a whole GEMM's output and has no
* gate to multiply; gating needs the product of two halves of one fused plane, which is silu_mul's
* shape. The exact-erf form is the unary `gelu` op; a GELU-gated feed-forward in this family is
* trained with the tanh approximation, so this op is the tanh one on purpose and says so. */
/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i], gate first as in silu_mul. Gemma's
* gated FFN, down(gelu_tanh(gate(x)) * up(x)) (gelu_pytorch_tanh in the checkpoint). Unlike
* gemm_nt's "gelu_tanh" epilogue it multiplies two halves of one fused plane. Deliberately the tanh
* form, which GELU-gated FFNs are trained with; the exact-erf form is the unary `gelu` op. */
int ref_gelu_mul(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *y = &a->t[1];
@@ -704,7 +729,7 @@ int ref_gelu_mul(const RadArgs* a, RadStream) {
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n);
const int64_t gs = laststride(gu), ys = laststride(y);
@@ -714,6 +739,43 @@ int ref_gelu_mul(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_sinusoid */
/* A Whisper-style absolute position table restarting every `period` rows of a segment: row r of
* segment s (rows [cu[s] / cu_div, cu[s+1] / cu_div)) takes position p = (r - cu[s] / cu_div) mod
* period, and is sin(p * inv[i]) then cos(p * inv[i]) over n/2 timescales, inv[i] as
* rel_sinusoid's, each step in f32 and rounded once. Qwen3-ASR's encoder adds it to every chunk's
* rows, which restart at position 0 with each second of audio. A row no segment covers is left
* untouched. */
int ref_seg_sinusoid(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *cu = &a->t[0], *Y = &a->t[1];
const int64_t n = p_int(a, "n", 0), period = p_int(a, "period", 0), cdiv = p_int(a, "cu_div", 1);
if (n <= 0 || n % 2 || period <= 0 || cdiv <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n), S = numel(cu) - 1;
if (rows <= 0 || S <= 0 || cu_at(cu, S) <= cu_at(cu, 0)) return RAD_E_SHAPE; /* zero rows */
const int64_t h = n / 2;
const double mt = (double)p_f32(a, "max_timescale", 10000.0f);
const float inc = (float)(std::log(mt / 1.0) / (double)(h - 1 > 1 ? h - 1 : 1));
for (int64_t s = 0; s < S; ++s) {
const int64_t c0 = cu_at(cu, s);
const int64_t c1 = cu_at(cu, s + 1);
if (c0 % cdiv || c1 % cdiv || c1 < c0 || c1 / cdiv > rows) return RAD_E_SHAPE;
REF_PAR_FOR((c1 / cdiv - c0 / cdiv) * n * 4)
for (int64_t r = c0 / cdiv; r < c1 / cdiv; ++r) {
const int64_t p = (r - c0 / cdiv) % period;
const int64_t yb = rowoff(Y, r, n), ys = laststride(Y);
for (int64_t i = 0; i < h; ++i) {
const float inv = ref_exp((float)i * -inc);
const float ang = (float)p * inv;
stt(Y, yb + i * ys, ref_sin(ang));
stt(Y, yb + (h + i) * ys, ref_cos(ang));
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu */
static int unary(const RadArgs* a, int which) {
if (!have(a, 2)) return RAD_E_INVAL;
@@ -721,7 +783,7 @@ static int unary(const RadArgs* a, int which) {
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(nel * 4)
for (int64_t i = 0; i < nel; ++i) {
float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), which == 0 ? act_gelu(v) : which == 1 ? act_silu(v) : act_sigmoid(v));
@@ -733,13 +795,12 @@ int ref_gelu(const RadArgs* a, RadStream) { return unary(a, 0); }
int ref_silu(const RadArgs* a, RadStream) { return unary(a, 1); }
/* ------------------------------------------------------------------ sigmoid */
/* Its own op rather than a `which` on gelu/silu, because a gated shared expert issues it against
* the router's output and the selector has to be able to name it (docs/OPS.md, "New ops"). Without
* it that expert runs ungated, which is a different model and not a slower one. */
/* Its own op so the selector can name it: a gated shared expert issues it on the router's output
* (docs/OPS.md, "Elementwise and norms"). */
int ref_sigmoid(const RadArgs* a, RadStream) { return unary(a, 2); }
/* ------------------------------------------------------------------ fill */
/* y = value over [M, n], at y's own row pitch. The value is rounded once, by the store. */
/* y = value over [M, n] at y's row pitch, rounded once by the store. */
int ref_fill(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
@@ -749,7 +810,7 @@ int ref_fill(const RadArgs* a, RadStream) {
if (rows <= 0) return RAD_E_SHAPE;
const float v = p_f32(a, "value", 0.0f);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, v);
@@ -758,10 +819,8 @@ int ref_fill(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ logit_softcap */
/* y = cap * tanh(x / cap), Gemma's final-logit softcap: the logits_gemm's output is a nearly
* unbounded row and the sampler wants it bounded, so this is issued against the LOGITS, not the
* hidden stream. Its own op for the same reason sigmoid is -- the selector has to be able to name
* it -- and `cap` is a parameter of the call, which the which-switch above cannot carry. */
/* y = cap * tanh(x / cap), Gemma's final-logit softcap, issued on the logits. Its own op so the
* selector can name it and so `cap` can be a call parameter. */
int ref_logit_softcap(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -770,51 +829,38 @@ int ref_logit_softcap(const RadArgs* a, RadStream) {
const float cap = p_f32(a, "cap", 30.0f);
if (!(cap > 0.0f)) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(nel * 4)
for (int64_t i = 0; i < nel; ++i) {
const float v = ldt(x, offlin(x, i));
stt(y, offlin(y, i), cap * std::tanh(v / cap));
stt(y, offlin(y, i), cap * ref_tanh(v / cap));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ scale */
/* y = x * s, where s is a [1] weight broadcast over every element of x.
*
* Gemma 4's per-layer scalar: the residual stream is scaled by a learned [1] value at the end of
* every layer (llama.cpp `out_scale`, `cur = cur * out_scale`). It is NOT `mul`, which broadcasts
* a single ROW down the rows (a bias's shape) -- this broadcasts a single SCALAR over the whole
* [M, n] tensor. `scale_rows` is the per-ROW version (one scalar a row); this is the per-TENSOR
* version (one scalar for all rows). Giving `mul` both rules would make them ambiguous exactly
* when rows == 1, so a silent choice between two broadcasts is how a shape bug becomes a
* plausible number -- the same reason `scale_rows` is its own op.
*
* `s` is a weight (a [1] tensor in the checkpoint), not a parameter: it varies per layer, so it
* is a declared weight the name map points at, not a call constant. Read once, outside the loop:
* a per-element reload of a [1] tensor is the same value every time and costs a load per element. */
/* y = x * s, s a [1] weight broadcast over all of x: Gemma 4's per-layer residual scalar (llama.cpp
* `out_scale`). `mul` broadcasts a row and `scale_rows` one scalar per row; this is one scalar per
* tensor, kept separate so the broadcasts are never ambiguous. `s` is a per-layer checkpoint weight,
* not a call constant. */
int ref_scale(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel || numel(s) < 1) return RAD_E_SHAPE;
const float sv = ldt(s, 0);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(nel)
for (int64_t i = 0; i < nel; ++i)
stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv);
return RAD_OK;
}
/* ------------------------------------------------------------------ gather_rows */
/* y[i, :] = x[idx[i], :]. The op that turns "correct" into "affordable": without it a plugin runs
* the lm_head GEMM over every token of a prefill chunk when the sampler wants one row per
* sequence -- n_tok/n_seq times the work, and at max_tok 8192 against a 248K vocab the logits
* buffer alone is 8 GiB (docs/OPS.md).
/* y[i, :] = x[idx[i], :]. Lets the lm_head GEMM run on one row per sequence instead of every
* prefill token: at max_tok 8192 and a 248K vocab the full logits buffer would be 8 GiB
* (docs/OPS.md).
*
* `M` is a RANGE parameter, so the number of rows actually gathered is the extent of `y` and not
* the declared worst case; `idx` is read for exactly that many entries. A negative index writes a
* zero row, matching embed_lookup's padding rule -- it is what a step with fewer sampled rows
* than the buffer's extent leaves behind, and zeros are the only answer that cannot be mistaken
* for a real logit row. An index at or past x's row count is RAD_E_INVAL: that is a caller bug,
* and reading it would be reading another sequence's hidden state. */
* `M` is a range parameter, so the row count is y's extent and `idx` is read for that many entries.
* A negative index writes a zero row (embed_lookup's padding rule; unsampled rows of a step). An
* index at or past x's row count is a caller bug and returns RAD_E_INVAL. */
int ref_gather_rows(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *idx = &a->t[1], *y = &a->t[2];
@@ -830,7 +876,7 @@ int ref_gather_rows(const RadArgs* a, RadStream) {
if (r >= src_rows) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
@@ -843,18 +889,14 @@ int ref_gather_rows(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ scatter_rows */
/* The mirror of gather_rows, and it exists for the same reason that one does: without it the only
* way to write M rows to M arbitrary destinations is M transfers, and at a few hundred bytes a row
* that is dispatch cost with the data as a rounding error.
/* The mirror of gather_rows: writes M rows to M arbitrary destinations in one launch instead of M
* small transfers.
*
* `x` IS INOUT AND THE WRITE IS PARTIAL. Rows no index names keep whatever they held -- which is
* the whole point when the destination is a pool other sequences are also using. An op that
* returned a fresh `x` would have to copy everything it was not asked to change.
* `x` is INOUT and the write is partial: unnamed rows keep their contents, since the destination
* is often a pool shared with other sequences.
*
* DUPLICATE INDICES ARE NOT LEGAL, and the schema says so with RAD_OPD_F_IDX_UNIQUE rather than
* leaving it to prose. Two rows landing on one destination has no defined winner on a parallel
* machine, so an op that permitted it would be one whose reference implementation and whose real
* kernel are allowed to disagree -- which is exactly what the oracle exists to rule out. */
* Duplicate indices are illegal (RAD_OPD_F_IDX_UNIQUE): two rows landing on one destination have no
* defined winner in parallel, so reference and kernel could legitimately disagree. */
int ref_scatter_rows(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2];
@@ -864,15 +906,14 @@ int ref_scatter_rows(const RadArgs* a, RadStream) {
const int64_t dst_rows = rows_of(x, n);
if (M <= 0 || dst_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
/* Validated before the loop, because an OpenMP body cannot return. A negative index is a
* skip, mirroring the zero row gather_rows writes for one: both mean "this slot has no
* counterpart", and on this side the honest response is to leave the destination alone. */
/* Validated before the loop, since an OpenMP body cannot return. A negative index is skipped,
* mirroring gather_rows' zero row: both mean the slot has no counterpart. */
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r >= dst_rows) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n)
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r < 0) continue;
@@ -883,24 +924,20 @@ int ref_scatter_rows(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ------------------------------------------------------------------ cast */
/* `from` and `to` are in the schema because the SELECTOR needs them -- a kernel that converts bf16
* to int8 is a different kernel from one that converts f32 to f16, and the constraint has to be
* expressible. Ref does not read them: the tensors carry their own dtypes and those are what the
* bytes actually are. A disagreement between the parameter and the tensor is a caller bug that
* ref cannot diagnose better than the caller can. */
/* `from` and `to` exist for the selector (each dtype pair is a different kernel). Ref ignores them
* and uses the tensors' own dtypes, which describe the bytes. */
int ref_cast(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t nel = numel(y);
if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE;
/* Integer targets and sources go through the integer path, so a token id or a block index
* survives a cast that f32 would round. */
/* Integer-to-integer casts bypass f32, so ids and indices above 2^24 survive. */
const bool int_pair = (x->dtype == RAD_I32 || x->dtype == RAD_I64 || x->dtype == RAD_U32 ||
x->dtype == RAD_I16) &&
(y->dtype == RAD_I32 || y->dtype == RAD_I64 || y->dtype == RAD_U32 ||
y->dtype == RAD_I16);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(nel)
for (int64_t i = 0; i < nel; ++i) {
if (int_pair) st_int(y->dtype, y->data, offlin(y, i), ld_int(x->dtype, x->data, offlin(x, i)));
else stt(y, offlin(y, i), ldt(x, offlin(x, i)));
@@ -909,9 +946,8 @@ int ref_cast(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ softmax */
/* Max-subtracted, f32, over the last n elements of a row. The max subtraction is not an
* optimisation: without it a 60-nat logit range overflows, and every kernel this is an oracle for
* does it, so the reference must too or the two differ by more than rounding. */
/* Max-subtracted, f32, over the last n elements of a row. Every kernel subtracts the max (a 60-nat
* logit range would otherwise overflow), so the reference must too. */
int ref_softmax(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -920,7 +956,7 @@ int ref_softmax(const RadArgs* a, RadStream) {
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 4)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y);
+414 -320
View File
File diff suppressed because it is too large. Load diff
+369 -239
View File
@@ -2,87 +2,84 @@
*
* nt: C[M,N] = A[M,K] @ B[N,K]^T
*
* B is stored TRANSPOSED because that is the layout every weight in a transformer already has, so
* both operands are k-contiguous and the inner loop is a dot product over k.
* B is stored transposed, the layout transformer weights already have, so both operands are
* k-contiguous and the inner loop is a dot product over k.
*
* This is the one family where the per-element dtype switch would BE the cost -- one element is
* read per FLOP -- so the inner loop is templated on the operand dtypes and selected once per
* launch through a function pointer. Everything else in this plugin pays the switch. The cost of
* not doing it is not marginal: a single prefill chunk is on the order of 10^11 element loads even
* for a small model, and a switch on each of them turns minutes of work into hours
* (docs/IMPLEMENTATION.md).
* This is the one family where the per-element dtype switch would dominate (one element read per
* FLOP; a prefill chunk is ~10^11 loads even for a small model), so the inner loop is templated on
* the operand dtypes and selected once per launch through a function pointer
* (docs/IMPLEMENTATION.md). Everything else pays the switch.
*
* Parallelism is over N, not M. A decode step is M=1 and a verify step is M<=64, so an M-major
* split would leave all but one core idle on exactly the shape the engine spends its life in; N is
* thousands in every GEMM a transformer issues. Each thread owns whole output elements, so the
* summation order does not depend on the thread count.
* Parallelism is over N, not M: decode is M=1 and verify M<=64, while N is thousands in every
* transformer GEMM. Each thread owns whole output elements, so summation order is independent of
* thread count.
*/
#include <algorithm>
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include "ref_planes.h"
using namespace ref;
namespace {
/* `Mat`, `as_mat`, `row_stride`, `Scales` and `make_scales` live in ref_gemm.h, because the
* mixture-of-experts GEMM reads its operands and scale streams exactly the same way. */
/* ------------------------------------------------------------------ the unquantised core */
template <uint32_t DA, uint32_t DB>
static void gemm_plain(const Mat& A, const Mat& B, const RadTensor* Y, const RadTensor* bias,
int64_t M, int64_t N, int64_t K, float alpha) {
/* ------------------------------------------------------------------ the tiled driver */
/* Y[m, n] = quant_dot(m, n) (+ bias[n]) over every output, in quant_tile's tiles (ref_gemm.h).
* Each tile is owned by one thread and every output's chain is fixed, so the result depends on
* neither the tiling nor the thread count. */
template <class LA, class LB>
static void gemm_tiles(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB,
const RadTensor* Y, const RadTensor* bias, int64_t M, int64_t N,
int64_t K) {
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
#pragma omp parallel for schedule(static)
for (int64_t n = 0; n < N; ++n) {
const void* bp = B.t->data;
const int64_t b0 = n * B.rs;
for (int64_t m = 0; m < M; ++m) {
const int64_t a0 = m * A.rs;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += Cvt<DA>::ld(A.t->data, a0 + k * A.cs) * Cvt<DB>::ld(bp, b0 + k * B.cs);
if (bias) acc += ldt(bias, n * laststride(bias));
stt(Y, m * ys_r + n * ys_c, acc * alpha);
const int64_t bs = bias ? laststride(bias) : 0;
const TileGrid tg = tile_grid(M, N);
std::vector<int64_t> rows((size_t)M);
for (int64_t m = 0; m < M; ++m) rows[(size_t)m] = m;
REF_PAR_REGION(M * N * K)
{
float* const ws = ws_get(tile_ws_floats(tg.rg));
REF_FOR
for (int64_t it = 0; it < tg.items(); ++it) {
const int64_t n0 = (it / tg.rgc) * REF_NB, r0 = (it % tg.rgc) * tg.rg;
const int64_t nb = (n0 + REF_NB < N) ? REF_NB : N - n0;
const int64_t R = (r0 + tg.rg < M) ? tg.rg : M - r0;
const float* acc = quant_tile<LA, LB>(A, B, SA, SB, rows.data() + r0, R, n0, nb, K,
ws);
for (int64_t r = 0; r < R; ++r)
for (int64_t j = 0; j < nb; ++j) {
float v = acc[r * REF_NB + j];
if (bias) v += ldt(bias, (n0 + j) * bs);
stt(Y, (r0 + r) * ys_r + (n0 + j) * ys_c, v);
}
}
}
}
/* The same loop with the switch left in. Anything the table below does not name lands here and is
* correct, just slow -- which is the deal this whole plugin makes. */
static void gemm_plain_generic(const Mat& A, const Mat& B, const RadTensor* Y,
const RadTensor* bias, int64_t M, int64_t N, int64_t K,
float alpha) {
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const uint32_t da = A.t->dtype, db = B.t->dtype;
#pragma omp parallel for schedule(static)
for (int64_t n = 0; n < N; ++n) {
const int64_t b0 = n * B.rs;
for (int64_t m = 0; m < M; ++m) {
const int64_t a0 = m * A.rs;
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k)
acc += ld_dt(da, A.t->data, a0 + k * A.cs) * ld_dt(db, B.t->data, b0 + k * B.cs);
if (bias) acc += ldt(bias, n * laststride(bias));
stt(Y, m * ys_r + n * ys_c, acc * alpha);
}
}
/* ------------------------------------------------------------------ the unquantised core */
/* The tiled driver with no scale streams: each output is acc += a * b over ascending k from
* zero, then the bias. */
template <class LA, class LB>
static void gemm_plain(const Mat& A, const Mat& B, const RadTensor* Y, const RadTensor* bias,
int64_t M, int64_t N, int64_t K) {
const Scales none = make_scales(nullptr, 0, K, false);
gemm_tiles<LA, LB>(A, B, none, none, Y, bias, M, N, K);
}
typedef void (*PlainFn)(const Mat&, const Mat&, const RadTensor*, const RadTensor*,
int64_t, int64_t, int64_t, float);
int64_t, int64_t, int64_t);
#define REF_PLAIN_ROW(DA) \
case DA: \
switch (db) { \
case RAD_F32: return &gemm_plain<DA, RAD_F32>; \
case RAD_F16: return &gemm_plain<DA, RAD_F16>; \
case RAD_BF16: return &gemm_plain<DA, RAD_BF16>; \
case RAD_I8: return &gemm_plain<DA, RAD_I8>; \
default: return nullptr; \
/* The dtype pairs with a compile-time loader; any other pair takes gemm_plain<Dyn, Dyn>. */
#define REF_PLAIN_ROW(DA) \
case DA: \
switch (db) { \
case RAD_F32: return &gemm_plain<Fix<DA>, Fix<RAD_F32>>; \
case RAD_F16: return &gemm_plain<Fix<DA>, Fix<RAD_F16>>; \
case RAD_BF16: return &gemm_plain<Fix<DA>, Fix<RAD_BF16>>; \
case RAD_I8: return &gemm_plain<Fix<DA>, Fix<RAD_I8>>; \
default: return &gemm_plain<Dyn, Dyn>; \
}
static PlainFn pick_plain(uint32_t da, uint32_t db) {
@@ -91,87 +88,49 @@ static PlainFn pick_plain(uint32_t da, uint32_t db) {
REF_PLAIN_ROW(RAD_F16)
REF_PLAIN_ROW(RAD_BF16)
REF_PLAIN_ROW(RAD_I8)
default: return nullptr;
default: return &gemm_plain<Dyn, Dyn>;
}
}
#undef REF_PLAIN_ROW
/* ------------------------------------------------------------------ the quantised core
* `quant_dot` in ref_gemm.h is the DEFINITION of one quantised product -- how the group sub-sum is
* formed from the raw codes and in what order the two scales fold onto it. This template is that
* function unrolled over a whole plane with the loads dispatched at COMPILE time, which is the only
* difference: `Cvt<DT>::ld` and `ld_dt(DT, ...)` return the same float for every dtype.
*
* SO THE TWO CAN DRIFT, and the thing that holds them together is a test rather than a comment:
* ref_test runs gemm_nt_q_gated -- which goes through `quant_dot` -- against gemm_nt_q followed by
* gated_quant_fp8, which comes through here, and requires the two byte-identical. */
template <uint32_t DA, uint32_t DB>
* `quant_dot` (ref_gemm.h) over a whole plane, with the loaders chosen at compile time where the
* pair is listed below. */
template <class LA, class LB>
static void gemm_quant(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB,
const RadTensor* Y, const RadTensor* bias,
int64_t M, int64_t N, int64_t K, float alpha) {
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
int64_t M, int64_t N, int64_t K) {
const int64_t g = SB.group > 0 ? SB.group : K;
const int64_t ngrp = (K + g - 1) / g;
const bool coarse_a = !SA.p || SA.group >= g;
#pragma omp parallel for schedule(static)
for (int64_t n = 0; n < N; ++n) {
const int64_t b0 = n * B.rs;
for (int64_t m = 0; m < M; ++m) {
const int64_t a0 = m * A.rs;
float acc = 0.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K;
const float sb = SB.p ? SB.grp(n, gi) : 1.0f;
float sub = 0.0f;
if (coarse_a) {
for (int64_t k = k0; k < k1; ++k)
sub += Cvt<DA>::ld(A.t->data, a0 + k * A.cs) *
Cvt<DB>::ld(B.t->data, b0 + k * B.cs);
acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb;
} else {
for (int64_t k = k0; k < k1; ++k)
sub += Cvt<DA>::ld(A.t->data, a0 + k * A.cs) * SA.at(m, k) *
Cvt<DB>::ld(B.t->data, b0 + k * B.cs);
acc += sub * sb;
}
}
if (bias) acc += ldt(bias, n * laststride(bias));
stt(Y, m * ys_r + n * ys_c, acc * alpha);
}
if (!SA.p || SA.group >= g) {
gemm_tiles<LA, LB>(A, B, SA, SB, Y, bias, M, N, K);
return;
}
}
static void gemm_quant_generic(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB,
const RadTensor* Y, const RadTensor* bias,
int64_t M, int64_t N, int64_t K, float alpha) {
/* An activation grid finer than the weight's, which quant_tile does not serve. */
const int64_t ys_r = row_stride(Y, N);
const int64_t ys_c = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(N * M * K)
for (int64_t n = 0; n < N; ++n)
for (int64_t m = 0; m < M; ++m) {
float acc = quant_dot(A, B, SA, SB, m, n, K);
float acc = quant_dot<LA, LB>(A, B, SA, SB, m, n, K);
if (bias) acc += ldt(bias, n * laststride(bias));
stt(Y, m * ys_r + n * ys_c, acc * alpha);
stt(Y, m * ys_r + n * ys_c, acc);
}
}
typedef void (*QuantFn)(const Mat&, const Mat&, const Scales&, const Scales&, const RadTensor*,
const RadTensor*, int64_t, int64_t, int64_t, float);
const RadTensor*, int64_t, int64_t, int64_t);
#define REF_QUANT_ROW(DA) \
case DA: \
switch (db) { \
case RAD_I4: return &gemm_quant<DA, RAD_I4>; \
case RAD_I2: return &gemm_quant<DA, RAD_I2>; \
case RAD_FP4E2M1: return &gemm_quant<DA, RAD_FP4E2M1>; \
case RAD_I8: return &gemm_quant<DA, RAD_I8>; \
case RAD_F8E4M3:return &gemm_quant<DA, RAD_F8E4M3>; \
case RAD_BF16: return &gemm_quant<DA, RAD_BF16>; \
case RAD_F32: return &gemm_quant<DA, RAD_F32>; \
default: return nullptr; \
#define REF_QUANT_ROW(DA) \
case DA: \
switch (db) { \
case RAD_I4: return &gemm_quant<Fix<DA>, Fix<RAD_I4>>; \
case RAD_I2: return &gemm_quant<Fix<DA>, Fix<RAD_I2>>; \
case RAD_FP4E2M1: return &gemm_quant<Fix<DA>, Fix<RAD_FP4E2M1>>; \
case RAD_I8: return &gemm_quant<Fix<DA>, Fix<RAD_I8>>; \
case RAD_F8E4M3: return &gemm_quant<Fix<DA>, Fix<RAD_F8E4M3>>; \
case RAD_BF16: return &gemm_quant<Fix<DA>, Fix<RAD_BF16>>; \
case RAD_F32: return &gemm_quant<Fix<DA>, Fix<RAD_F32>>; \
default: return &gemm_quant<Dyn, Dyn>; \
}
static QuantFn pick_quant(uint32_t da, uint32_t db) {
@@ -180,36 +139,101 @@ static QuantFn pick_quant(uint32_t da, uint32_t db) {
REF_QUANT_ROW(RAD_F8E4M3)
REF_QUANT_ROW(RAD_BF16)
REF_QUANT_ROW(RAD_F32)
default: return nullptr;
default: return &gemm_quant<Dyn, Dyn>;
}
}
#undef REF_QUANT_ROW
/* gemm_nt_bias's EPILOGUE, applied to what the GEMM stored: an activation, then a residual. Each
* step reads the stored value and stores its result, so every one of them is rounded to the
* output's dtype -- which is the unfused chain exactly: a linear layer's output, an activation of
* it, a residual sum, three tensors. `act` 0 none, 1 exact (erf) GELU, 2 tanh GELU. */
static float gelu_erf(float x) { return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f)); }
static float gelu_tanh(float x) {
const float k0 = 0.7978845608028654f, k1 = 0.044715f;
return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x)));
}
/* gemm_nt_bias's epilogue, applied to what the GEMM stored: an activation, then a residual. Each
* step reads and stores, so each rounds to the output dtype, exactly as the unfused chain of three
* tensors would. `act`: 0 none, 1 exact (erf) GELU, 2 tanh GELU. */
static void gemm_epilogue(const RadTensor* Y, const RadTensor* res, int act, int64_t M, int64_t N) {
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const int64_t rs_r = res ? row_stride(res, N) : 0, rs_c = res ? laststride(res) : 0;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * N)
for (int64_t m = 0; m < M; ++m)
for (int64_t n = 0; n < N; ++n) {
const int64_t o = m * ys_r + n * ys_c;
if (act == 1) stt(Y, o, gelu_erf(ldt(Y, o)));
else if (act == 2) stt(Y, o, gelu_tanh(ldt(Y, o)));
if (act == 1) stt(Y, o, act_gelu(ldt(Y, o)));
else if (act == 2) stt(Y, o, act_gelu_tanh(ldt(Y, o)));
if (res) stt(Y, o, ldt(res, m * rs_r + n * rs_c) + ldt(Y, o));
}
}
/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nk_from` names which parameters carry N
* and K, because logits_gemm spells them n_vocab and n_embd. */
/* ------------------------------------------------------------------ a joined head */
/* Y = A B^T for a B of codes and one scale (ref_planes.h: ScaledRows), decoded a block of rows at
* a time into f32 and multiplied by the plain core. Each decoded element is the f32 the core's
* affine decoder gives, so the result is bit-identical to the same product over that decoder's
* f32 head, which is what a tool hands this plugin as the logical form. */
static int gemm_scaled_rows(const Mat& ma, const RadTensor* Bt, const RadTensor* Y,
const RadTensor* bias, int64_t M, int64_t N, int64_t K) {
ScaledRows sr;
const int st = scaled_rows(Bt, N, K, &sr);
if (st != RAD_OK) return st;
/* Rows per block: about 16 MiB of f32, at least one tile. */
int64_t ch = ((int64_t)1 << 22) / K;
ch = std::max<int64_t>(REF_NB, ch / REF_NB * REF_NB);
std::vector<float> dec((size_t)(std::min(ch, N) * K));
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const PlainFn plain = pick_plain(ma.t->dtype, RAD_F32);
for (int64_t n0 = 0; n0 < N; n0 += ch) {
const int64_t nb = std::min(ch, N - n0);
REF_PAR_FOR(nb * K)
for (int64_t r = 0; r < nb; ++r)
for (int64_t k = 0; k < K; ++k) dec[(size_t)(r * K + k)] = sr.at(n0 + r, k);
RadTensor Bb{};
Bb.data = dec.data();
Bb.dtype = RAD_F32;
Bb.rank = 2; Bb.shape[0] = nb; Bb.shape[1] = K; Bb.stride[0] = K; Bb.stride[1] = 1;
RadTensor Yb = *Y;
Yb.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0 * ys_c);
Yb.rank = 2; Yb.shape[0] = M; Yb.shape[1] = nb; Yb.stride[0] = ys_r; Yb.stride[1] = ys_c;
RadTensor bb{};
if (bias) {
bb = *bias;
bb.data = (uint8_t*)bias->data + rad_dtype_bytes(bias->dtype, n0 * laststride(bias));
}
plain(ma, as_mat(&Bb, K), &Yb, bias ? &bb : nullptr, M, nb, K);
}
return RAD_OK;
}
/* Shared entry for gemm_nt / gemm_nt_bias / logits_gemm. `nkey`/`kkey` name the parameters that
* carry N and K, since logits_gemm spells them n_vocab and n_embd. */
/* Whether two operands' memory overlaps: from the first element to one past the last element
* their strides reach. A residual may be the output itself (an in-place residual add). */
static bool spans_overlap(const RadTensor* a, const RadTensor* b) {
auto span = [](const RadTensor* t, const char** lo, const char** hi) {
int64_t last = 0;
for (uint32_t i = 0; i < t->rank; ++i) last += (t->shape[i] - 1) * t->stride[i];
const int64_t eb = (rad_dtype_bits(t->dtype) + 7) / 8;
*lo = static_cast<const char*>(t->data);
*hi = *lo + (last + 1) * eb;
};
const char *alo, *ahi, *blo, *bhi;
span(a, &alo, &ahi);
span(b, &blo, &bhi);
return alo < bhi && blo < ahi;
}
/* The residual as f32 [M, N], read before the product overwrites it when it is the output's own
* memory. Widening is exact for every float dtype, so the epilogue's sum is unchanged. */
static RadTensor snapshot_res(const RadTensor* res, int64_t M, int64_t N, std::vector<float>* buf) {
const int64_t rs_r = row_stride(res, N), rs_c = laststride(res);
buf->resize((size_t)(M * N));
for (int64_t m = 0; m < M; ++m)
for (int64_t n = 0; n < N; ++n) (*buf)[(size_t)(m * N + n)] = ldt(res, m * rs_r + n * rs_c);
RadTensor t{};
t.dtype = RAD_F32;
t.rank = 2;
t.shape[0] = M;
t.shape[1] = N;
t.stride[0] = N;
t.stride[1] = 1;
t.data = buf->data();
return t;
}
static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, const char* kkey) {
/* gemm_nt_bias is a, b, bias, res?, y; the other two are a, b, y. */
const int nt = bias_operand ? 5 : 3;
@@ -219,25 +243,139 @@ static int gemm_nt_impl(const RadArgs* a, bool bias_operand, const char* nkey, c
const RadTensor* res = bias_operand ? t_in(a, 3) : nullptr;
static const char* kActs[] = { "none", "gelu", "gelu_tanh" };
const int act = bias_operand ? p_enum(a, "act", kActs, 3, 0) : 0;
if (act < 0 || act > 2) return RAD_E_INVAL;
const int64_t K = p_int(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = p_int(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0);
if (K <= 0 || N <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
/* A head of codes and scale, joined (ref_planes.h); its extents are its planes'. */
const bool joined = is_joined(B);
if (numel(A) < M * K || (!joined && numel(B) < N * K)) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
if (res && numel(res) < M * N) return RAD_E_SHAPE;
std::vector<float> res_buf;
RadTensor res_copy{};
if (res && spans_overlap(res, Y)) {
res_copy = snapshot_res(res, M, N, &res_buf);
res = &res_copy;
}
const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K);
PlainFn fn = pick_plain(A->dtype, B->dtype);
if (fn) fn(ma, mb, Y, bias, M, N, K, 1.0f);
else gemm_plain_generic(ma, mb, Y, bias, M, N, K, 1.0f);
const Mat ma = as_mat(A, K);
if (joined) {
const int st = gemm_scaled_rows(ma, B, Y, bias, M, N, K);
if (st != RAD_OK) return st;
if (act || res) gemm_epilogue(Y, res, act, M, N);
return RAD_OK;
}
const Mat mb = as_mat(B, K);
pick_plain(A->dtype, B->dtype)(ma, mb, Y, bias, M, N, K);
if (act || res) gemm_epilogue(Y, res, act, M, N);
return RAD_OK;
}
/* ------------------------------------------------------------------ the zero-point grids */
/* gemm_nt_q over an asymmetric grid (ref_planes.h, ZpGrid): weight element (n, k) is
* (code - zero) * scale with one f16 scale and one integer zero per (row, `group` of K), read from
* `b_scale`'s joined planes. Each group's sub-sum is formed on the integer grid and scaled once, as
* quant_dot does for the symmetric grids:
*
* ZP_I8_ROW sub = sum(a * code) - zero * a_sum[g][m] exact integers below 2^24
* acc += (sub * a_scale[m]) * scale
* ZP_I8_GROUP sub = sum(a * (code - zero)) exact
* acc += (sub * a_scale[m][g]) * scale
* ZP_F16 sub = sum over ascending k of a * (code - zero), each product exact in f32
* acc += sub * scale
*
* `a` is already in column order (the caller undoes the step order). `a_sum` is quant_act_i8's,
* group-major [K/group][Mpad], Mpad = ceil(M/16)*16; the grid's zero is removed through it, as
* libr4d's kernels do, so it is required. Parts (`pb1`, `pb2`, the ParoQuant grids only): weight
* rows [0, e1), [e1, e2), [e2, N) meet copies 0, 1, 2 of the activation, side by side in `a` and in
* `a_scale`. */
static int gemm_zp(const ZpGrid& zg, const RadTensor* A, const RadTensor* as_,
const RadTensor* B, const RadTensor* bs_, const RadTensor* asum,
const RadTensor* Y, int64_t M, int64_t N, int64_t K, int64_t group,
int64_t pb1, int64_t pb2) {
if (!is_joined(bs_)) return RAD_E_DTYPE;
const JPlane sc = jplane(bs_, "scale"), zp = jplane(bs_, "zero");
if (!sc || !zp || !float_scale_dt(sc.dt) || !zero_dt(zp.dt)) return RAD_E_DTYPE;
if (B->dtype != zg.codes) return RAD_E_DTYPE;
if (group <= 0 || K % group) return RAD_E_SHAPE;
const int64_t G = K / group;
if (sc.rows != N || sc.cols != G || zp.rows != N || zp.cols != G) return RAD_E_SHAPE;
if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE;
const int64_t brow = rad_enc_row_bytes(B->dtype, K);
const int cbits = rad_dtype_bits(B->dtype);
/* The parts' row bounds and the activation's width. */
const bool parted = pb1 > 0 || pb2 > 0;
if (parted && zg.act == ZP_I8_ROW) return RAD_E_UNSUPPORTED;
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE;
const int64_t acols = parts * K;
if (numel(A) < M * acols) return RAD_E_SHAPE;
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, acols), acs = laststride(A);
const bool i8 = zg.act != ZP_F16;
if (i8 && A->dtype != RAD_I8) return RAD_E_DTYPE;
if (!i8 && !float_scale_dt(A->dtype)) return RAD_E_DTYPE;
const int64_t mpad = (M + 15) / 16 * 16;
if (zg.act == ZP_I8_ROW) {
if (!as_ || numel(as_) < M) return RAD_E_INVAL;
if (!asum || numel(asum) < G * mpad) return RAD_E_INVAL;
}
if (zg.act == ZP_I8_GROUP && (!as_ || numel(as_) < M * parts * G)) return RAD_E_INVAL;
const int64_t sa_rs = as_ ? row_stride(as_, zg.act == ZP_I8_GROUP ? parts * G : 1) : 0;
const int64_t sa_cs = as_ ? laststride(as_) : 0;
const int64_t ys_r = row_stride(Y, N), ys_c = laststride(Y);
const int64_t asum_s = asum ? laststride(asum) : 0;
REF_PAR_FOR(N * M * K)
for (int64_t n = 0; n < N; ++n) {
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
const uint8_t* crow = (const uint8_t*)B->data + n * brow;
std::vector<int32_t> q((size_t)K);
for (int64_t k = 0; k < K; ++k) q[(size_t)k] = (int32_t)rad_load_bits(crow, cbits, k);
for (int64_t m = 0; m < M; ++m) {
const int64_t ab = m * ars + part * K * acs;
float acc = 0.0f;
for (int64_t g = 0; g < G; ++g) {
const float sb = sc.at(n, g);
const int32_t z = (int32_t)zp.at(n, g);
const int64_t k0 = g * group;
float sub;
if (zg.act == ZP_F16) {
sub = 0.0f;
for (int64_t k = k0; k < k0 + group; ++k)
sub += ldt(A, ab + k * acs) * (float)(q[(size_t)k] - z);
acc += sub * sb;
continue;
}
int64_t is = 0;
const int8_t* ar = (const int8_t*)A->data;
if (zg.act == ZP_I8_ROW) {
for (int64_t k = k0; k < k0 + group; ++k)
is += (int64_t)ar[ab + k * acs] * q[(size_t)k];
sub = (float)is - (float)z * ldt(asum, (g * mpad + m) * asum_s);
acc += sub * ldt(as_, m * sa_rs) * sb;
} else {
for (int64_t k = k0; k < k0 + group; ++k)
is += (int64_t)ar[ab + k * acs] * (q[(size_t)k] - z);
sub = (float)is;
acc += sub * ldt(as_, m * sa_rs + (part * G + g) * sa_cs) * sb;
}
}
stt(Y, m * ys_r + n * ys_c, acc);
}
}
return RAD_OK;
}
static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
const int nt = bias_operand ? 6 : 5;
if (a->n_t < nt || !a->t[0].data || !a->t[2].data || !a->t[nt - 1].data) return RAD_E_INVAL;
@@ -245,6 +383,18 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
const RadTensor* as_ = t_in(a, 1);
const RadTensor* bs_ = t_in(a, 3);
const RadTensor* bias = bias_operand ? t_in(a, 4) : nullptr;
/* The zero-point grids read `b_scale` joined and the w2a8 / w4a8_asym ones `a_sum` too
* (gemm_zp); they have no bias form. Elsewhere `a_sum` would remove a zero point the grid
* does not have, so a call passing it is refused rather than answered as if it were absent.
* `b_ref` is the per-row reference exponent an mxfp4 kernel folds its scales at; it is derived
* from `b_scale` and does not change the product, so it is accepted beside an e2m1 weight
* only. */
const ZpGrid* zg = zp_grid(p_str(a, "dtype", nullptr));
if (zg && bias_operand) return RAD_E_UNSUPPORTED;
if (!bias_operand) {
if (t_in(a, 5) && (!zg || zg->act != ZP_I8_ROW)) return RAD_E_UNSUPPORTED;
if (t_in(a, 6) && B->dtype != RAD_FP4E2M1) return RAD_E_UNSUPPORTED;
}
const int64_t K = p_int(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0);
const int64_t N = p_int(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0);
@@ -254,12 +404,33 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
if (numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
/* PARTS (`pb1`, `pb2`): the weight's rows are [0, pb1), [pb1, pb2) and [pb2, N), each against
* its own copy of the activation -- a fused projection whose pieces were rotated separately
* (ParoQuant). The copies sit side by side in a row of `a`, so `a` is [M, parts * K] and its
* scale [M, parts * K / 128]; a part is the plain product over its rows, which is how it is
* computed. 0 leaves a bound out: no `pb1` is one part, no `pb2` ends the second at N. */
/* quant_act_i8's codes arrive in the step order (ref_common.h); read them back into column
* order. */
std::vector<int8_t> a_cols;
RadTensor Ac;
if (A->dtype == RAD_I8 && i8_steps_dtype(p_str(a, "dtype", nullptr))) {
if (K % 16) return RAD_E_SHAPE;
if (laststride(A) != 1) return RAD_E_STRIDE;
a_cols.resize((size_t)(M * K));
for (int64_t m = 0; m < M; ++m) {
const int8_t* row = (const int8_t*)A->data + rowoff(A, m, K);
for (int64_t c = 0; c < K; ++c) a_cols[(size_t)(m * K + c)] = row[i8_step_pos(c)];
}
Ac = *A;
Ac.data = a_cols.data();
Ac.rank = 2; Ac.shape[0] = M; Ac.shape[1] = K; Ac.stride[0] = K; Ac.stride[1] = 1;
A = &Ac;
}
/* Parts (`pb1`, `pb2`): weight rows [0, pb1), [pb1, pb2) and [pb2, N) each multiply their own
* copy of the activation, for a fused projection whose pieces were rotated separately
* (ParoQuant). The copies sit side by side, so `a` is [M, parts * K] and its scale
* [M, parts * K / 128]; each part is computed as a plain product over its rows. 0 omits a
* bound: no `pb1` is one part, no `pb2` ends the second at N. */
const int64_t pb1 = p_int(a, "pb1", 0), pb2 = p_int(a, "pb2", 0);
if (zg)
return gemm_zp(*zg, A, as_, B, bs_, t_in(a, 5), Y, M, N, K, p_int(a, "group", 0), pb1,
pb2);
if (pb1 > 0 || pb2 > 0) {
if (bias_operand || B->dtype != RAD_FP4E2M1 || A->rank < 2) return RAD_E_UNSUPPORTED;
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
@@ -292,10 +463,8 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
Yp.data = (uint8_t*)Y->data + rad_dtype_bytes(Y->dtype, n0);
Yp.rank = 2; Yp.shape[0] = M; Yp.shape[1] = n1 - n0; Yp.stride[0] = ys; Yp.stride[1] = 1;
Scales SAp = make_scales(&Sp, M, K, false), SBp = make_scales(&Bsp, n1 - n0, K, true);
const Mat map_ = as_mat(&Ap, M, K), mbp = as_mat(&Bp, n1 - n0, K);
QuantFn fn = pick_quant(Ap.dtype, Bp.dtype);
if (fn) fn(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f);
else gemm_quant_generic(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K, 1.0f);
const Mat map_ = as_mat(&Ap, K), mbp = as_mat(&Bp, K);
pick_quant(Ap.dtype, Bp.dtype)(map_, mbp, SAp, SBp, &Yp, nullptr, M, n1 - n0, K);
}
return RAD_OK;
}
@@ -303,16 +472,13 @@ static int gemm_ntq_impl(const RadArgs* a, bool bias_operand) {
const bool mx = B->dtype == RAD_FP4E2M1;
Scales SA = make_scales(as_, M, K, false);
Scales SB = make_scales(bs_, N, K, mx);
/* `group` is in the schema and is what the SELECTOR matches on; the loop uses the group the
* scale stream actually implies. They agree in every well-formed call, and where they do not
* the stream is the one that describes the bytes. */
/* `group` is what the selector matches on; the loop uses the group the scale stream implies,
* which describes the bytes. A disagreement is refused. */
const int64_t gp = p_int(a, "group", 0);
if (gp > 0 && SB.p && SB.group != gp) return RAD_E_SHAPE;
const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K);
QuantFn fn = pick_quant(A->dtype, B->dtype);
if (fn) fn(ma, mb, SA, SB, Y, bias, M, N, K, 1.0f);
else gemm_quant_generic(ma, mb, SA, SB, Y, bias, M, N, K, 1.0f);
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
pick_quant(A->dtype, B->dtype)(ma, mb, SA, SB, Y, bias, M, N, K);
return RAD_OK;
}
@@ -332,113 +498,77 @@ int ref_gemm_nt_q_bias(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ logits_gemm */
/* The same arithmetic as gemm_nt, and a separate op anyway: lm_head is its own access class
* (RAD_ACCESS_VOCAB) and the sampler wants to fuse against it, so the two have to be selectable
* apart even when one kernel serves both (docs/OPS.md). N and K are spelled n_vocab and n_embd. */
/* gemm_nt's arithmetic as a separate op: lm_head is its own access class (RAD_ACCESS_VOCAB) and
* the sampler fuses against it, so the two must be selectable apart (docs/OPS.md). N and K are
* spelled n_vocab and n_embd. */
int ref_logits_gemm(const RadArgs* a, RadStream) {
return gemm_nt_impl(a, false, "n_vocab", "n_embd");
}
/* ------------------------------------------------------------------ embed_lookup */
/* A gather, not a GEMM, which is half of why it is its own op. A NEGATIVE token id writes a zero
* row -- that is the padding convention a batch with a short sequence needs.
/* A gather, not a GEMM. A negative token id writes a zero row (padding for short sequences).
*
* `vocab_offset` (optional, default 0) makes the table THIS RANK'S SLICE of a vocab-parallel
* embedding: it covers global ids [vocab_offset, vocab_offset + n_vocab), ids stay global, and one
* outside the slice writes a zero row so that summing the ranks reconstructs x. See the schema.
* `vocab_offset` (optional, default 0) makes the table this rank's slice of a vocab-parallel
* embedding, covering global ids [vocab_offset, vocab_offset + n_vocab). Ids stay global; one
* outside the slice writes a zero row, so summing the ranks reconstructs x.
*
* WITHOUT AN OFFSET AN ID AT OR ABOVE n_vocab STILL FAILS THE LAUNCH, because there it is a caller
* bug rather than another rank's token and a plausible embedding is the worst answer. With one,
* that check is not available to this kernel -- it cannot know the global vocabulary -- so it is
* the caller's, and the sampler and the tokeniser are both already bounded by it. */
int ref_embed_lookup(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *tok = &a->t[0], *wte = &a->t[1], *x = &a->t[2];
* When this rank holds the whole vocabulary, an id >= n_vocab fails the launch: it is a caller bug,
* and a plausible embedding is the worst answer. Under a split the kernel cannot know the global
* vocabulary, so the check is the caller's (the sampler and tokeniser are bounded by it).
*
* Every row read is multiplied by `factor`: embed_lookup's `mult`, embed_lookup_q's table scale. */
static int embed_gather(const RadArgs* a, const RadTensor* tok, const RadTensor* wte,
const RadTensor* x, float factor) {
const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0);
const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0);
const int64_t voff = p_int(a, "vocab_offset", 0);
const float mult = p_f32(a, "mult", 1.0f);
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / n_embd;
if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE;
/* Validated before the loop, because an OpenMP body cannot return.
*
* THE GUARD IS ABOUT HOLDING THE WHOLE VOCABULARY, NOT ABOUT THE OFFSET BEING ZERO. An id at
* or above n_vocab is a caller's mistake only where this rank holds every row; under a
* vocab-parallel split it is another rank's token, and the loop below writes it as a zero row
* exactly as it writes the padding id, which is what makes summing the ranks reconstruct x.
* Rank 0 of such a split has offset 0 -- so a guard keyed on the offset alone would refuse
* the engine's own operands on every step whose token belongs to the other half, where the
* device kernel correctly takes the zero-row path at any offset. */
/* Validated before the loop, since an OpenMP body cannot return. The guard keys on holding the
* whole vocabulary, not on a zero offset: rank 0 of a vocab-parallel split has offset 0, and
* its out-of-slice ids are other ranks' tokens that must become zero rows. */
if (voff == 0 && a->world_size <= 1) {
for (int64_t m = 0; m < M; ++m) {
int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m));
if (id >= n_vocab) return RAD_E_INVAL;
}
}
const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd;
const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m)) - voff;
const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x);
const bool have_row = id >= 0 && id < n_vocab;
for (int64_t i = 0; i < n_embd; ++i)
stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * mult : 0.0f);
}
return RAD_OK;
}
/* A gather from a QUANTISED table: one scale for the whole thing.
*
* WHY IT IS A SEPARATE OP AND NOT A `dtype` ON embed_lookup. The operand list differs -- there is a
* scale -- and operands are positional, so an op whose count depends on a string means different
* things to different kernels. That is the same argument `moe_gemm_q` and `gemm_nt_q` make against
* their unquantised twins, and adding the scale to embed_lookup as an OPTIONAL operand would have
* moved `x` from slot 2 to slot 3 for every caller in the tree.
*
* ONE SCALE FOR THE WHOLE TABLE, and that is the checkpoint's choice rather than a simplification.
* A hundreds-of-millions-of-rows n-gram embedding ships as E4M3 with a single bf16 `weight_scale`,
* and the reason that works is structural: E4M3 carries its own exponent, so a row spans very
* little dynamic range in units of the scale and the reconstruction is insensitive to the scale
* over octaves. A per-row scale buys a couple of percent there, which is why the format has none.
* (INT8 in the same byte WOULD gain substantially, because it spends all eight bits on resolution;
* that is a different format and not this one.)
*/
int ref_embed_lookup_q(const RadArgs* a, RadStream) {
/* `scale` (operand 2) is optional; the other three must be there. */
if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return RAD_E_INVAL;
const RadTensor *tok = &a->t[0], *wte = &a->t[1], *sc = &a->t[2], *x = &a->t[3];
const int64_t n_embd = p_int(a, "n_embd", wte->rank >= 2 ? wte->shape[wte->rank - 1] : 0);
const int64_t n_vocab = p_int(a, "n_vocab", wte->rank >= 2 ? wte->shape[wte->rank - 2] : 0);
const int64_t voff = p_int(a, "vocab_offset", 0);
if (n_embd <= 0 || n_vocab <= 0 || voff < 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / n_embd;
if (M <= 0 || numel(tok) < M || numel(wte) < n_vocab * n_embd) return RAD_E_SHAPE;
/* AN ABSENT SCALE IS ONE: a table stored as it ships -- a plain bf16 n-gram embedding read in
* place from a container -- takes the same op and the same host path as the quantised one,
* which is what keeps a table too large for any device pool on the mapped tier either way. */
const float scale = sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f;
/* Validated before the loop, because an OpenMP body cannot return. Same rule as the dense
* gather above: a negative id is padding and writes a zero row, an id past the table is a
* launch error rather than a read of whatever follows it. */
if (voff == 0) {
for (int64_t m = 0; m < M; ++m)
if (ld_int(tok->dtype, tok->data, offlin(tok, m)) >= n_vocab) return RAD_E_INVAL;
}
const int64_t ws = wte->rank >= 2 ? wte->stride[wte->rank - 2] : n_embd;
const int64_t wc = wte->rank >= 2 ? wte->stride[wte->rank - 1] : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_embd)
for (int64_t m = 0; m < M; ++m) {
const int64_t id = ld_int(tok->dtype, tok->data, offlin(tok, m)) - voff;
const int64_t xb = rowoff(x, m, n_embd), xs = laststride(x);
const bool have_row = id >= 0 && id < n_vocab;
for (int64_t i = 0; i < n_embd; ++i)
stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * scale : 0.0f);
stt(x, xb + i * xs, have_row ? ldt(wte, id * ws + i * wc) * factor : 0.0f);
}
return RAD_OK;
}
int ref_embed_lookup(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
return embed_gather(a, &a->t[0], &a->t[1], &a->t[2], p_f32(a, "mult", 1.0f));
}
/* A gather from a quantised table with one scale for the whole table.
*
* A separate op rather than a dtype on embed_lookup because operands are positional and this one
* adds a scale; an optional operand would have moved `x` from slot 2 to slot 3 for every caller
* (the same reason moe_gemm_q and gemm_nt_q are separate ops).
*
* One scale is the checkpoint's format: the n-gram embedding (hundreds of millions of rows) ships
* as E4M3 with a single bf16 `weight_scale`. E4M3 carries its own exponent, so reconstruction is
* insensitive to the scale over octaves and a per-row scale gains only a few percent. (INT8 would
* gain substantially, but that is a different format.)
*/
int ref_embed_lookup_q(const RadArgs* a, RadStream) {
/* `scale` (operand 2) is optional; the other three are required. */
if (a->n_t < 4 || !rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 3)) return RAD_E_INVAL;
const RadTensor* sc = &a->t[2];
/* An absent scale is 1, so a plain bf16 n-gram embedding read in place from a container takes
* the same op and host path, keeping a table too large for any device pool on the mapped tier. */
const float scale = sc->data && numel(sc) >= 1 ? ldt(sc, 0) : 1.0f;
return embed_gather(a, &a->t[0], &a->t[1], &a->t[3], scale);
}
+193 -95
View File
@@ -1,14 +1,10 @@
/* ref_gemm.h -- how libref reads a matrix operand and its scale stream.
*
* Shared by the dense GEMM and the mixture-of-experts GEMM, which need the same three answers:
* where row `r` of an operand begins, what the scale of a (row, k) pair is, and what a block-
* scaled grid looks like against the operand it scales. A grouped GEMM is a GEMM per row against
* a different weight, so it needs exactly the machinery the dense one has and nothing else; a
* second copy of `make_scales` in ref_moe.cpp would be a second place for the rblk rule to be
* wrong, and the rblk rule is what makes this reference usable as an oracle for a block-scaled
* fp8 checkpoint.
* Shared by the dense and mixture-of-experts GEMMs, which need the same answers: where row `r` of
* an operand begins, the scale of a (row, k) pair, and how a block-scaled grid maps onto its
* operand. Keeping one copy keeps one rblk rule, which block-scaled fp8 checkpoints depend on.
*
* Everything here is a pure reading of a RadTensor. No op, no dispatch, no allocation.
* Pure reads of a RadTensor: no op, no dispatch, no allocation.
*/
#ifndef REF_GEMM_H
#define REF_GEMM_H
@@ -17,24 +13,16 @@
namespace ref {
/* A tensor read as [rows, cols], which is what every GEMM here wants and is NOT the same as
* "dim 0 and dim 1".
/* Row stride of a tensor read as [rows, cols], which is not the same as dim 0 by dim 1.
*
* `stride[rank - 2]` is the row stride only when the LAST dimension is already `cols`. An
* activation that arrives rank 3 -- [tokens, heads, width], which is how the gated delta net's
* out-projection input is declared, because the scan kernels require that rank -- is read as
* [tokens, heads * width], and its row stride is the product of the trailing dimensions, not the
* head stride. Taking the head stride instead lands row 0 correctly and starts every row after it
* `width` elements in -- which reads as a correct implementation right up to the second row.
* `stride[rank - 2]` is the row stride only when the last dimension is already `cols`. A rank-3
* activation [tokens, heads, width] (the gated delta net's out-projection input, rank 3 because the
* scan kernels need it) is read as [tokens, heads * width], whose row stride spans the trailing
* dimensions. Using the head stride gets row 0 right and every later row wrong.
*
* THE OUTPUT SIDE IS THE WORSE HALF and has the same rule. A gated attention layer's q|gate
* projection is declared [tokens, heads, 2 * head_dim] -- rank 3, because the de-interleaving that
* follows needs the head axis -- and writing it at the HEAD stride does not merely write the wrong
* bytes, it leaves most of the buffer NEVER WRITTEN, so rows after the first carry a tail of exact
* zeros.
*
* This is libref, so it is the ORACLE: every tool that certifies a kernel against this arithmetic
* inherits whatever it gets wrong, which is why the rule is stated here once. */
* Outputs follow the same rule. A gated attention q|gate projection is [tokens, heads,
* 2 * head_dim]; writing it at the head stride leaves most of the buffer unwritten, so later rows
* end in exact zeros. */
static inline int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
/* Fold trailing dimensions until they span `cols`; the next one out carries the row. */
@@ -47,18 +35,16 @@ static inline int64_t row_stride(const RadTensor* t, int64_t cols) {
return t->stride[t->rank - 2]; /* the shapes disagree; fall back to the row axis */
}
/* The element offset of row `r` of a [rows, cols] operand, and the stride along cols. Weights
* arrive contiguous from the mapper; activations may be a slice of a wider arena buffer, so both
* are read through their strides. */
/* Row and column strides of a [rows, cols] operand. Weights arrive contiguous; activations may be
* a slice of a wider arena buffer, so both are read through their strides. */
struct Mat {
const RadTensor* t;
int64_t rs; /* elements between rows */
int64_t cs; /* elements between columns */
};
static inline Mat as_mat(const RadTensor* t, int64_t rows, int64_t cols) {
static inline Mat as_mat(const RadTensor* t, int64_t cols) {
Mat m{ t, cols, 1 };
(void)rows;
if (t->rank < 2) return m;
m.cs = t->stride[t->rank - 1];
m.rs = row_stride(t, cols);
@@ -66,48 +52,39 @@ static inline Mat as_mat(const RadTensor* t, int64_t rows, int64_t cols) {
}
/* ------------------------------------------------------------------ scale streams
* A quantised operand's scales are a separate SoA stream (spec §4.1), shaped [rows, groups] with
* the group index fastest, or [rows] for one scale per row. The group SIZE is derived from the
* stream's own extent rather than trusted from the parameter: a `group` that disagrees with the
* scale tensor is the kind of mismatch that produces plausible wrong numbers, and deriving it
* makes the disagreement structurally impossible.
* A quantised operand's scales are a separate SoA stream (spec §4.1), [rows, groups] with the
* group index fastest, or [rows] for one scale per row. The group size is derived from the
* stream's extent rather than the `group` parameter, so the two cannot disagree.
*
* A BLOCK-SCALED grid is the same stream with fewer rows than the operand. DeepSeek-style fp8 --
* which is what Qwen3.8-27B-FP8 and every other `weight_block_size: [128, 128]` checkpoint ships --
* stores one scale per 128x128 TILE, so `weight_scale_inv` is [ceil(N/128)][ceil(K/128)] against an
* [N][K] weight. `rblk` is how many operand rows share a scale row; it is 1 for every per-row grid,
* which is every other format in this project, so the division below costs those nothing.
*
* Without it this reference reads a 17408-row weight's 136-row scale plane as if it had 17408 rows
* and lands on `groups = 0`, which is not a diagnosable failure -- it is a plausible wrong number,
* and it makes ref useless as the oracle for exactly the format the production models are in. */
* A block-scaled grid is the same stream with fewer rows than the operand. DeepSeek-style fp8
* (Qwen3.8-27B-FP8 and any `weight_block_size: [128, 128]` checkpoint) stores one scale per
* 128x128 tile, so `weight_scale_inv` is [ceil(N/128)][ceil(K/128)] against an [N][K] weight.
* `rblk` is how many operand rows share a scale row; 1 for every per-row grid. Without it a
* 17408-row weight's 136-row scale plane would be read per row and give plausible wrong numbers. */
struct Scales {
const void* p;
uint32_t dt;
int64_t rs; /* elements between scale rows */
int64_t cs; /* elements between groups */
int64_t group; /* K elements per scale */
int64_t rblk; /* OPERAND rows per scale row; 1 unless the grid is block-scaled */
int64_t rblk; /* operand rows per scale row; 1 unless the grid is block-scaled */
bool e8m0; /* the scale stream is OCP e8m0 exponent bytes, not floats */
inline float at(int64_t row, int64_t k) const {
int64_t g = group > 0 ? k / group : 0;
int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i);
}
/* The scale of group `g` of `row`. */
inline float grp(int64_t row, int64_t g) const {
int64_t i = (rblk > 1 ? row / rblk : row) * rs + g * cs;
return e8m0 ? e8m0_to_f32(((const uint8_t*)p)[i]) : ld_dt(dt, p, i);
}
/* The scale of element `k` of `row`. */
inline float at(int64_t row, int64_t k) const { return grp(row, group > 0 ? k / group : 0); }
};
/* THE BLOCK A GRID OF `blocks` PIECES IMPLIES OVER `ext` ELEMENTS, and it is not ext / blocks.
* A grid's last block may be partial -- ceil(300 / 128) is 3 scales over 128, 128 and 44 -- so
* the quotient (100 there) assigns elements 100..127 to the second scale. The block is the POWER
* OF TWO whose ceiling division gives `blocks`, which is unique whenever there is more than one
* block, and every scale grid in this project is one (32, 64, 128). Where no power of two fits,
* the smallest block that yields `blocks` pieces is taken. Either way ceil(ext / block) is at
* most `blocks`, so an index derived from it never leaves the grid. */
/* The block size a grid of `blocks` pieces implies over `ext` elements; not ext / blocks, since
* the last block may be partial (300 over 128 is 3 scales covering 128, 128 and 44, but 300 / 3 =
* 100 would misassign 100..127). It is the power of two whose ceiling division gives `blocks`,
* unique for more than one block; every scale grid here is one (32, 64, 128). Otherwise the
* smallest block giving `blocks` pieces. Either way ceil(ext / block) <= `blocks`, so derived
* indices stay in the grid. */
static inline int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
@@ -125,15 +102,13 @@ static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bo
}
q.p = s->data;
q.dt = s->dtype;
/* A rank-2 stream states its own grid, and that statement is preferred: it is the only source
* that can distinguish "one scale per row over `groups` groups" from "one scale per row BLOCK".
* FEWER scale rows than operand rows is a block grid, whatever the remainder: [ceil(N/128)]
* rows against N = 129 is two blocks, the second of one row. As many or more is one scale row
* per operand row, read through the stream's own row stride.
/* A rank-2 stream states its own grid, the only way to tell per-row groups from per-row-block
* scales. Fewer scale rows than operand rows is a block grid whatever the remainder
* ([ceil(N/128)] rows against N = 129 is two blocks, the second one row); otherwise one scale
* row per operand row, through the stream's row stride.
*
* A rank-1 or flattened stream has no grid to state. With a scale for every row it is per row
* over nel / rows groups; with fewer it is one scale per BLOCK of rows. Reading it per row
* there walks off the end of the plane at the first row past its length. */
* A rank-1 or flattened stream states no grid. With a scale per row it is nel / rows groups per
* row; with fewer it is one scale per block of rows (reading it per row would run off the end). */
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
@@ -154,40 +129,44 @@ static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bo
q.cs = 1;
}
q.group = grid_block(K, groups);
/* mxfp4's block scale is an e8m0 exponent byte. When the stream arrives as u8 beside an mxfp4
* weight there is nothing else it could be; a float stream beside the same weight is read as
* a float, so a quantiser that chose to store the scale plainly still works. */
/* mxfp4's block scale is an e8m0 exponent byte: a u8 stream beside an mxfp4 weight is read as
* e8m0, while a float stream is read as floats, so plainly stored scales still work. */
q.e8m0 = mxfp4_weight && (s->dtype == RAD_U8);
return q;
}
/* ------------------------------------------------------------------ one quantised product
*
* ONE (m, n) dot of a quantised GEMM, and the ONE DEFINITION of how the scales fold into it.
* One (m, n) dot of a quantised GEMM, and the single definition of how scales fold into it.
*
* The group sub-sum is accumulated from the RAW CODES and scaled once at the end of the group,
* which is what an int8 or fp8 WMMA kernel does: it accumulates in the fragment's type and applies
* the block scales when the tile closes. Folding the scales into every product instead is the same
* value in exact arithmetic and a different one in the last bits, and rad-kbench would blame the
* kernel for the reference's choice.
* Each group's sub-sum is accumulated from the raw codes and scaled once at the group's end, as an
* int8 or fp8 WMMA kernel does when a tile closes. Scaling every product is equal in exact
* arithmetic but differs in the last bits.
*
* `sub * sa * sb` IS AN ORDER AND NOT AN EXPRESSION. Float multiplication is commutative and not
* associative, so (sub*sa)*sb and (sub*sb)*sa differ by an ulp on some operands -- which is enough
* to move one fp8 code, and a fused op being byte-identical to the pair it replaces is the whole
* claim such a fold rests on. Every caller goes through here so that there is one order.
* `sub * sa * sb` is an order: (sub*sa)*sb and (sub*sb)*sa can differ by an ulp, enough to move an
* fp8 code, and fused ops must be byte-identical to the pair they replace. Every caller uses this
* function so there is one order.
*
* The loads go through `ld_dt` rather than `Cvt<DT>` so that one function serves every dtype pair.
* The two return the same float for every dtype, so a caller that dispatches on the type at
* compile time for speed still computes these bits.
* LA and LB load A's and B's elements: `Dyn` switches on the dtype per element and serves every
* pair; `Fix<DT>` resolves it at compile time for the GEMM's hot pairs. Both return the same
* floats, so the result does not depend on which was used.
*/
struct Dyn {
static inline float ld(const RadTensor* t, int64_t i) { return ld_dt(t->dtype, t->data, i); }
};
template <uint32_t DT> struct Fix {
static inline float ld(const RadTensor* t, int64_t i) { return Cvt<DT>::ld(t->data, i); }
};
template <class LA = Dyn, class LB = Dyn>
static inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB,
int64_t m, int64_t n, int64_t K) {
const int64_t g = SB.group > 0 ? SB.group : K;
const int64_t ngrp = (K + g - 1) / g;
/* No format in this project gives the activation a finer group than the weight; where one
* appears the scale cannot be hoisted out of the group and the sub-sum is formed per element. */
/* No format here gives the activation a finer group than the weight; if one does, its scale
* cannot be hoisted and is applied per element. */
const bool coarse_a = !SA.p || SA.group >= g;
const uint32_t da = A.t->dtype, db = B.t->dtype;
const int64_t a0 = m * A.rs, b0 = n * B.rs;
float acc = 0.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
@@ -196,28 +175,147 @@ static inline float quant_dot(const Mat& A, const Mat& B, const Scales& SA, cons
float sub = 0.0f;
if (coarse_a) {
for (int64_t k = k0; k < k1; ++k)
sub += ld_dt(da, A.t->data, a0 + k * A.cs) * ld_dt(db, B.t->data, b0 + k * B.cs);
sub += LA::ld(A.t, a0 + k * A.cs) * LB::ld(B.t, b0 + k * B.cs);
acc += sub * (SA.p ? SA.at(m, k0) : 1.0f) * sb;
} else {
for (int64_t k = k0; k < k1; ++k)
sub += ld_dt(da, A.t->data, a0 + k * A.cs) * SA.at(m, k) *
ld_dt(db, B.t->data, b0 + k * B.cs);
sub += LA::ld(A.t, a0 + k * A.cs) * SA.at(m, k) * LB::ld(B.t, b0 + k * B.cs);
acc += sub * sb;
}
}
return acc;
}
/* ------------------------------------------------------------------ the blocked product
*
* quant_dot over a tile of outputs: A rows `arow[0..R)` against B rows [n0, n0 + nb). Every
* output is the chain quant_dot forms, per group a sub-sum from zero over ascending k and then
* `acc + (sub * sa) * sb`, so the result is bit-identical to calling it per element. What changes
* is that REF_NB outputs advance together: the chains are independent, so they run in vector lanes
* and their add latencies overlap, and B's codes are widened into an f32 panel once per K chunk
* and reused by every row of the tile (exact conversions, so the panel holds the same floats the
* loaders return).
*
* Only the coarse activation grid (no finer scale on A than on B) is tiled; quant_dot keeps the
* other, which no format uses. */
static constexpr int64_t REF_NB = 16, REF_KC = 256, REF_MB = 2;
typedef float RefV4 __attribute__((vector_size(16)));
/* Floats a tile of R rows needs: the panel, two A rows, and the sub-sums and accumulators of R
* rows rounded up to whole row pairs. One ws_get() carves all of it. */
static inline size_t tile_ws_floats(int64_t R) {
const int64_t rp = (R + REF_MB - 1) / REF_MB * REF_MB;
return (size_t)(REF_KC * REF_NB + REF_MB * REF_KC + 2 * rp * REF_NB);
}
/* sub[2][REF_NB] += abuf[i][k] * panel[k][*] over k < kl, one chain per output. */
static inline void tile_kernel(const float* abuf, const float* panel, float* sub, int64_t kl) {
static_assert(REF_NB == 16 && REF_MB == 2, "the kernel holds two rows of four vectors");
auto ld = [](const float* f) { RefV4 v; std::memcpy(&v, f, sizeof v); return v; };
auto st = [](float* f, RefV4 v) { std::memcpy(f, &v, sizeof v); };
RefV4 c00 = ld(sub), c01 = ld(sub + 4), c02 = ld(sub + 8), c03 = ld(sub + 12);
RefV4 c10 = ld(sub + 16), c11 = ld(sub + 20), c12 = ld(sub + 24), c13 = ld(sub + 28);
for (int64_t k = 0; k < kl; ++k) {
const float a0 = abuf[k], a1 = abuf[REF_KC + k];
const float* p = panel + k * REF_NB;
const RefV4 p0 = ld(p), p1 = ld(p + 4), p2 = ld(p + 8), p3 = ld(p + 12);
c00 += a0 * p0; c01 += a0 * p1; c02 += a0 * p2; c03 += a0 * p3;
c10 += a1 * p0; c11 += a1 * p1; c12 += a1 * p2; c13 += a1 * p3;
}
st(sub, c00); st(sub + 4, c01); st(sub + 8, c02); st(sub + 12, c03);
st(sub + 16, c10); st(sub + 20, c11); st(sub + 24, c12); st(sub + 28, c13);
}
/* The tile's results land in `ws`'s accumulator block, [R][REF_NB] row-major, which this returns;
* columns at and past `nb` are padding. Requires the coarse activation grid (see above). */
template <class LA, class LB>
static float* quant_tile(const Mat& A, const Mat& B, const Scales& SA, const Scales& SB,
const int64_t* arow, int64_t R, int64_t n0, int64_t nb, int64_t K,
float* ws) {
const int64_t rp = (R + REF_MB - 1) / REF_MB * REF_MB;
float* const panel = ws;
float* const abuf = panel + REF_KC * REF_NB;
float* const sub = abuf + REF_MB * REF_KC;
float* const acc = sub + rp * REF_NB;
const int64_t g = SB.group > 0 ? SB.group : K;
const int64_t ngrp = (K + g - 1) / g;
/* No scale on either side: quant_dot's acc is 0 + (sub * 1) * 1, which is sub exactly (a
* sub-sum started at +0 is never -0). */
const bool unscaled = !SA.p && !SB.p && ngrp == 1;
for (int64_t i = 0; i < rp * REF_NB; ++i) acc[i] = 0.0f;
float sb[REF_NB];
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < K) ? k0 + g : K;
for (int64_t j = 0; j < REF_NB; ++j) sb[j] = (j < nb && SB.p) ? SB.grp(n0 + j, gi) : 1.0f;
for (int64_t i = 0; i < rp * REF_NB; ++i) sub[i] = 0.0f;
for (int64_t kc0 = k0; kc0 < k1; kc0 += REF_KC) {
const int64_t kl = (kc0 + REF_KC < k1) ? REF_KC : k1 - kc0;
for (int64_t j = 0; j < REF_NB; ++j) {
if (j < nb) {
const int64_t b0 = (n0 + j) * B.rs + kc0 * B.cs;
for (int64_t k = 0; k < kl; ++k)
panel[k * REF_NB + j] = LB::ld(B.t, b0 + k * B.cs);
} else {
for (int64_t k = 0; k < kl; ++k) panel[k * REF_NB + j] = 0.0f;
}
}
for (int64_t r0 = 0; r0 < R; r0 += REF_MB) {
for (int64_t i = 0; i < REF_MB; ++i) {
float* const ar = abuf + i * REF_KC;
if (r0 + i < R) {
const int64_t a0 = arow[r0 + i] * A.rs + kc0 * A.cs;
for (int64_t k = 0; k < kl; ++k) ar[k] = LA::ld(A.t, a0 + k * A.cs);
} else {
for (int64_t k = 0; k < kl; ++k) ar[k] = 0.0f;
}
}
tile_kernel(abuf, panel, sub + r0 * REF_NB, kl);
}
}
if (unscaled) {
for (int64_t i = 0; i < rp * REF_NB; ++i) acc[i] = sub[i];
continue;
}
for (int64_t r = 0; r < R; ++r) {
const float sa = SA.p ? SA.at(arow[r], k0) : 1.0f;
for (int64_t j = 0; j < REF_NB; ++j)
acc[r * REF_NB + j] += sub[r * REF_NB + j] * sa * sb[j];
}
}
return acc;
}
/* How a grid of R rows by N outputs is cut into tiles for one parallel loop: `nblk` column blocks
* of REF_NB, each split into `rgc` row groups of `rg` rows. Rows are split only when there are too
* few column blocks to occupy the threads (a narrow projection at a prefill M); a row group then
* pays its own panel widening, which is cheap against rg rows of products. */
struct TileGrid {
int64_t nblk, rg, rgc;
int64_t items() const { return nblk * rgc; }
};
static inline TileGrid tile_grid(int64_t R, int64_t N) {
TileGrid t;
t.nblk = (N + REF_NB - 1) / REF_NB;
int64_t rg = R;
if (t.nblk < 128 && R > 8 * REF_MB) {
rg = (R * t.nblk + 127) / 128;
if (rg < 8 * REF_MB) rg = 8 * REF_MB;
rg = (rg + REF_MB - 1) / REF_MB * REF_MB;
}
t.rg = rg > 0 ? rg : 1;
t.rgc = R > 0 ? (R + t.rg - 1) / t.rg : 0;
return t;
}
/* ------------------------------------------------------------------ weight tables
*
* A RAD_OPD_WTAB operand: `data` is a device (here, host) array of `shape[0]` pointers, one per
* expert, and `stride[0]` is 0 to say so -- see RAD_WTAB in abi/rad_runtime.h. The STACKED form,
* a plain rank-3 [n_expert, N, K] tensor with an ordinary leading stride, is accepted too and is
* what a caller outside the engine hands over: rad-kbench draws one dense plane and the fixture
* has nowhere to put a pointer array. Both are one expert per call to this, so nothing downstream
* has to know which arrived.
* A RAD_OPD_WTAB operand: `data` is an array of `shape[0]` pointers, one per expert, marked by
* `stride[0]` == 0 (RAD_WTAB in abi/rad_runtime.h). The stacked form, a plain rank-3
* [n_expert, N, K] tensor, is also accepted; callers outside the engine such as rad-kbench pass
* that, having nowhere to put a pointer array.
*
* Returns entry `e` as a rank-(rank-1) tensor over the same dtype, or a null-data tensor when the
* Returns entry `e` as a rank-(rank-1) tensor of the same dtype, or a null-data tensor when the
* operand cannot be read that way. */
static inline RadTensor expert_entry(const RadTensor* w, int64_t e) {
RadTensor t{};
@@ -232,8 +330,8 @@ static inline RadTensor expert_entry(const RadTensor* w, int64_t e) {
void* const* tab = (void* const*)w->data;
t.data = tab[e];
} else {
/* An element offset in a packed dtype can be mid-byte; the stacked form is only ever
* whole planes, so the arithmetic is done in bytes off the leading stride. */
/* A packed-dtype element offset can be mid-byte; stacked planes are whole bytes, so
* compute in bits off the leading stride and refuse a fractional byte. */
const int64_t bits = rad_dtype_bits(w->dtype);
const int64_t nbits = (int64_t)bits * w->stride[0] * e;
if (bits <= 0 || (nbits & 7)) return t; /* data stays null: unreadable */
+108 -141
View File
@@ -1,13 +1,11 @@
/* ref_gen.cpp -- the image generator's ops (docs/OPS.md, "Image generation").
*
* WHERE A ROUNDING IS WRITTEN OUT, IT IS THE REFERENCE MODEL'S. A diffusion transformer and its
* decoder are run in bf16 by the reference implementation, so every tensor it materialises is
* rounded there: `LN(x) * (1 + scale)` is three bf16 tensors, not one f32 expression, and the
* oracle rounds where the reference does so a kernel that fuses the chain can be held to it.
* Every explicit rounding follows the upstream model, which runs the diffusion transformer and its
* decoder in bf16 and so rounds every tensor it materialises: `LN(x) * (1 + scale)` is three bf16
* tensors, not one f32 expression. Rounding at the same points lets a fused kernel be held to it.
*
* Geometry a step decides -- an image's height and width -- arrives in the OPERANDS, never in the
* parameters: a 2-D image operand is [height, width * channels], dense, and the op reads both off
* its shape. A parameter is fixed at declare and an image's size is a request's.
* Per-request geometry (an image's height and width) comes from the operands, never the
* parameters, which are fixed at declare: a 2-D image operand is [height, width * channels], dense.
*/
#include "ref_common.h"
#include "ref_gemm.h"
@@ -23,41 +21,12 @@ using namespace ref;
namespace {
/* An entry's flags (docs/OPS.md, flow_euler): RadGenBatch's RAD_GEN_F_* values, restated because a
* kernel library compiles against rad_abi.h and not the run phase's header. */
* kernel library compiles against rad_abi.h, not the run phase's header. */
enum { kFirst = 1, kInpaint = 2, kPreview = 4 };
inline float rnd(uint32_t dt, float v) {
uint16_t h;
switch (dt) {
case RAD_BF16: h = f32_to_bf16(v); return bf16_to_f32(h);
case RAD_F16: h = f32_to_f16(v); return f16_to_f32(h);
default: return v;
}
}
inline float rbf(float v) { return bf16_to_f32(f32_to_bf16(v)); }
inline float rbf(float v) { return round_dt(RAD_BF16, v); }
inline int64_t cu_at(const RadTensor* cu, int64_t i) {
return ld_int(cu->dtype, cu->data, offlin(cu, i));
}
/* The sequence that owns dense row `r`: linear, because there are a handful. */
inline int64_t seq_of(const RadTensor* cu, int64_t n_seq, int64_t r) {
int64_t s = 0;
while (s + 1 < n_seq && cu_at(cu, s + 1) <= r) ++s;
return s;
}
inline int64_t rows_n(const RadTensor* t, int64_t n) {
if (!t || n <= 0) return 0;
if (t->rank >= 2 && t->shape[t->rank - 1] == n) {
int64_t r = 1;
for (uint32_t i = 0; i + 1 < t->rank; ++i) r *= t->shape[i];
return r;
}
return numel(t) / n;
}
/* A space-separated list of floats, each rounded to bf16 as the reference's bf16 tensor of it is. */
/* A space-separated list of floats, each rounded to bf16 as the upstream bf16 tensor holds it. */
int parse_list(const char* s, std::vector<float>* out) {
out->clear();
while (s && *s) {
@@ -73,19 +42,19 @@ int parse_list(const char* s, std::vector<float>* out) {
} /* namespace */
/* ------------------------------------------------------------------ ln_mod */
/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ): a layer norm with no gain and no bias, then the
* modulation row of the row's sequence. `s` is [n_seq, >= n] at its own row pitch -- a column
* slice of the modulation projection. */
/* y = bf16( bf16(LN(x)) * bf16(1 + s[seq]) ): a layer norm with no gain or bias, then the row's
* sequence's modulation row. `s` is [n_seq, >= n] at its own row pitch (a column slice of the
* modulation projection). */
int ref_ln_mod(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *s = &a->t[1], *cu = &a->t[2], *y = &a->t[3];
const int64_t n = p_int(a, "n", 0);
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1;
if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1;
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
const int64_t s_rs = row_stride(s, n), s_cs = laststride(s);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
@@ -100,8 +69,8 @@ int ref_ln_mod(const RadArgs* a, RadStream) {
}
const float rs = 1.0f / std::sqrt(var / (float)n + eps);
for (int64_t i = 0; i < n; ++i) {
const float ln = rnd(y->dtype, (ldt(x, xb + i * xs) - mean) * rs);
const float sc = rnd(y->dtype, 1.0f + ldt(s, e * s_rs + i * s_cs));
const float ln = round_dt(y->dtype, (ldt(x, xb + i * xs) - mean) * rs);
const float sc = round_dt(y->dtype, 1.0f + ldt(s, e * s_rs + i * s_cs));
stt(y, yb + i * ys, ln * sc);
}
}
@@ -115,17 +84,17 @@ int ref_gate_add(const RadArgs* a, RadStream) {
const RadTensor *y = &a->t[0], *g = &a->t[1], *cu = &a->t[2], *x = &a->t[3];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n), n_seq = numel(cu) - 1;
if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n), n_seq = numel(cu) - 1;
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
const int64_t g_rs = row_stride(g, n), g_cs = laststride(g);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs)));
const float p = rnd(x->dtype, t * ldt(y, yb + i * ys));
const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs)));
const float p = round_dt(x->dtype, t * ldt(y, yb + i * ys));
stt(x, xb + i * xs, ldt(x, xb + i * xs) + p);
}
}
@@ -144,12 +113,12 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
const bool gated = p_int(a, "gated", 0) != 0;
const float eps = p_f32(a, "eps", 1e-6f);
if (n <= 0 || grp <= 0 || n % grp || (gated && (!y || !g))) return RAD_E_SHAPE;
const int64_t rows = rows_n(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
if (rows <= 0 || n_seq <= 0 || rows_n(x, n) < rows || numel(sc) < rows * ngrp)
const int64_t rows = rows_of(q, n), n_seq = numel(cu) - 1, ngrp = n / grp;
if (rows <= 0 || n_seq <= 0 || rows_of(x, n) < rows || numel(sc) < rows * ngrp)
return RAD_E_SHAPE;
const int64_t s_rs = row_stride(s, n), s_cs = laststride(s);
const int64_t g_rs = gated ? row_stride(g, n) : 0, g_cs = gated ? laststride(g) : 0;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t e = seq_of(cu, n_seq, r);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
@@ -157,9 +126,9 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
for (int64_t i = 0; i < n; ++i) {
float xv = ldt(x, xb + i * xs);
if (gated) {
const float t = rnd(x->dtype, std::tanh(ldt(g, e * g_rs + i * g_cs)));
const float t = round_dt(x->dtype, ref_tanh(ldt(g, e * g_rs + i * g_cs)));
const float d = ldt(y, rowoff(y, r, n) + i * laststride(y));
xv = rnd(x->dtype, xv + rnd(x->dtype, t * d));
xv = round_dt(x->dtype, xv + round_dt(x->dtype, t * d));
stt(x, xb + i * xs, xv);
}
v[(size_t)i] = xv;
@@ -171,24 +140,16 @@ int ref_ln_mod_quant_fp8(const RadArgs* a, RadStream) {
for (int64_t i = 0; i < n; ++i) { const float d = v[(size_t)i] - mean; var += d * d; }
const float rs = 1.0f / std::sqrt(var / (float)n + eps);
for (int64_t i = 0; i < n; ++i) {
const float ln = rnd(RAD_BF16, (v[(size_t)i] - mean) * rs);
const float sm = rnd(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs));
o[(size_t)i] = rnd(RAD_BF16, ln * sm);
const float ln = round_dt(RAD_BF16, (v[(size_t)i] - mean) * rs);
const float sm = round_dt(RAD_BF16, 1.0f + ldt(s, e * s_rs + i * s_cs));
o[(size_t)i] = round_dt(RAD_BF16, ln * sm);
if (z) stt(z, rowoff(z, r, n) + i * laststride(z), o[(size_t)i]);
}
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
float amax = 0.0f;
for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i)
amax = std::max(amax, std::fabs(o[(size_t)i]));
const float scl = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / scl;
for (int64_t i = gi * grp; i < (gi + 1) * grp; ++i) {
float w = o[(size_t)i] * inv;
if (w > 448.0f) w = 448.0f;
if (w < -448.0f) w = -448.0f;
st_dt(q->dtype, q->data, qb + i * qs, w);
}
const float* og = o.data() + gi * grp;
const float scl = q8_group([&](int64_t i) { return og[i]; }, grp, 448.0f, q,
qb + gi * grp * qs, qs);
stt(sc, rowoff(sc, r, ngrp) + gi * laststride(sc), scl);
}
}
@@ -208,7 +169,7 @@ int ref_timestep_embed(const RadArgs* a, RadStream) {
const double mp = p_f32(a, "max_period", 10000.0f);
const int round = (int)p_int(a, "round", 0);
if (n <= 0 || (n & 1)) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n);
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(t) < rows) return RAD_E_SHAPE;
const int64_t h = n / 2;
const float coef = (float)(-std::log(mp));
@@ -217,10 +178,10 @@ int ref_timestep_embed(const RadArgs* a, RadStream) {
const float tt = round ? scale * rbf(rbf(tv * scale) / scale) : scale * tv;
const int64_t yb = rowoff(y, m, n), ys = laststride(y);
for (int64_t i = 0; i < h; ++i) {
const float f = std::exp(coef * (float)i / (float)h);
const float f = ref_exp(coef * (float)i / (float)h);
const float arg = tt * f;
stt(y, yb + i * ys, std::cos(arg));
stt(y, yb + (h + i) * ys, std::sin(arg));
stt(y, yb + i * ys, ref_cos(arg));
stt(y, yb + (h + i) * ys, ref_sin(arg));
}
}
return RAD_OK;
@@ -233,10 +194,10 @@ int ref_gather_rows2(const RadArgs* a, RadStream) {
const RadTensor *A = &a->t[0], *B = &a->t[1], *idx = &a->t[2], *y = &a->t[3];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n);
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(idx) < rows) return RAD_E_SHAPE;
const int64_t ra = rows_n(A, n), rbn = rows_n(B, n);
#pragma omp parallel for schedule(static)
const int64_t ra = rows_of(A, n), rbn = rows_of(B, n);
REF_PAR_FOR(rows * n)
for (int64_t i = 0; i < rows; ++i) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, i));
const RadTensor* src = r >= 0 ? A : B;
@@ -259,8 +220,8 @@ int ref_lane_gather(const RadArgs* a, RadStream) {
const RadTensor *src = &a->t[0], *lane = &a->t[1], *cu = &a->t[2], *y = &a->t[3];
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, src_rows = rows_n(src, n);
if (n_seq <= 0 || numel(lane) < n_seq) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, src_rows = rows_of(src, n);
if (n_seq <= 0 || numel(lane) < n_seq || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
const int64_t b0 = cu_at(cu, e), b1 = cu_at(cu, e + 1);
@@ -280,7 +241,7 @@ int ref_lane_store(const RadArgs* a, RadStream) {
const RadTensor *src = &a->t[0], *lane = &a->t[1], *dst = &a->t[2];
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(src, n), dst_rows = rows_n(dst, n), nl = numel(lane);
const int64_t rows = rows_of(src, n), dst_rows = rows_of(dst, n), nl = numel(lane);
if (rows <= 0 || rows > stride) return RAD_E_SHAPE;
for (int64_t l = 0; l < nl; ++l) {
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, l));
@@ -304,9 +265,10 @@ int ref_randn_lanes(const RadArgs* a, RadStream) {
const RadTensor *dst = &a->t[4];
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, dst_rows = rows_n(dst, n);
const int64_t n_seq = numel(cu) - 1, dst_rows = rows_of(dst, n);
if (n_seq <= 0 || numel(fl) < n_seq || numel(lane) < n_seq || numel(seed) < 2 * n_seq)
return RAD_E_SHAPE;
if (cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
for (int64_t e = 0; e < n_seq; ++e) {
if (!(ld_int(fl->dtype, fl->data, offlin(fl, e)) & kFirst)) continue;
const int64_t L = ld_int(lane->dtype, lane->data, offlin(lane, e));
@@ -314,7 +276,7 @@ int ref_randn_lanes(const RadArgs* a, RadStream) {
if (L < 0 || len > stride || (L + 1) * stride > dst_rows) return RAD_E_SHAPE;
const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) |
((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(len * n * 8)
for (int64_t k = 0; k < len; ++k) {
const int64_t db = rowoff(dst, L * stride + k, n), ds = laststride(dst);
for (int64_t c = 0; c < n; ++c)
@@ -345,8 +307,8 @@ int ref_flow_euler(const RadArgs* a, RadStream) {
const RadTensor *pv = t_in(a, 12);
const int64_t n = p_int(a, "n", 0), stride = p_int(a, "stride", 0);
if (n <= 0 || stride <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_n(st, n);
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1, st_rows = rows_of(st, n);
if (n_seq <= 0 || cu_at(cu, n_seq) <= cu_at(cu, 0)) return RAD_E_SHAPE;
const uint32_t dt = st->dtype;
for (int64_t e = 0; e < n_seq; ++e) {
const int64_t pr = ld_int(pair->dtype, pair->data, offlin(pair, e));
@@ -361,10 +323,10 @@ int ref_flow_euler(const RadArgs* a, RadStream) {
const int64_t f = ld_int(fl->dtype, fl->data, offlin(fl, e));
const uint64_t sd = (uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e)) |
((uint64_t)(uint32_t)ld_int(seed->dtype, seed->data, offlin(seed, 2 * e + 1)) << 32);
const float dts = rnd(dt, sn - s);
const float dts = round_dt(dt, sn - s);
if ((f & kInpaint) && (!inp || !mask)) return RAD_E_INVAL;
if ((f & kPreview) && !pv) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(len * n * 8)
for (int64_t k = 0; k < len; ++k) {
const int64_t vb = rowoff(v, b0 + k, n), vs = laststride(v);
const int64_t nb = pr >= 0 ? rowoff(v, p0 + k, n) : 0;
@@ -373,20 +335,20 @@ int ref_flow_euler(const RadArgs* a, RadStream) {
float vv = ldt(v, vb + c * vs);
if (pr >= 0) {
const float vn = ldt(v, nb + c * vs);
vv = rnd(dt, vn + rnd(dt, w * rnd(dt, vv - vn)));
vv = round_dt(dt, vn + round_dt(dt, w * round_dt(dt, vv - vn)));
}
const float x = ldt(st, sb + c * ss);
if (f & kPreview) {
const int64_t pb = rowoff(pv, L * stride + k, n);
stt(pv, pb + c * laststride(pv), x - s * vv);
}
float xn = rnd(dt, x + rnd(dt, dts * vv));
float xn = round_dt(dt, x + round_dt(dt, dts * vv));
if (f & kInpaint) {
const float m = ldt(mask, offlin(mask, L * stride + k));
const float src = ldt(inp, rowoff(inp, L * stride + k, n) + c * laststride(inp));
const float nz = rad_philox_normal(sd, (uint64_t)(k * n + c));
const float kept = (1.0f - sn) * src + sn * nz;
xn = rnd(dt, m * xn + (1.0f - m) * kept);
xn = round_dt(dt, m * xn + (1.0f - m) * kept);
}
stt(st, sb + c * ss, xn);
}
@@ -396,9 +358,9 @@ int ref_flow_euler(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ chan_affine */
/* A per-channel affine from two lists the PARAMETERS carry (a latent's mean and deviation are
* configuration, not weights), each value rounded to bf16 as the reference's bf16 tensor of it:
* mode `fma` is bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */
/* A per-channel affine from two parameter lists (a latent's mean and deviation are configuration,
* not weights), each value rounded to bf16 as upstream holds it: mode `fma` is
* bf16(bf16(x * mul) + add), `inv` is bf16(bf16(x - add) / mul). */
int ref_chan_affine(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -410,16 +372,16 @@ int ref_chan_affine(const RadArgs* a, RadStream) {
const char* mode = p_str(a, "mode", "fma");
const bool inv = mode && !std::strcmp(mode, "inv");
if (!inv && mode && std::strcmp(mode, "fma")) return RAD_E_INVAL;
const int64_t rows = rows_n(y, n);
if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
const int64_t rows = rows_of(y, n);
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
for (int64_t c = 0; c < n; ++c) {
const float v = ldt(x, xb + c * xs);
stt(y, yb + c * ys, inv ? rnd(y->dtype, v - add[c]) / mul[c]
: rnd(y->dtype, v * mul[c]) + add[c]);
stt(y, yb + c * ys, inv ? round_dt(y->dtype, v - add[c]) / mul[c]
: round_dt(y->dtype, v * mul[c]) + add[c]);
}
}
return RAD_OK;
@@ -432,8 +394,8 @@ int ref_chan_affine(const RadArgs* a, RadStream) {
* up 2 the input is first upsampled 2x nearest-neighbour (`nearest-exact` at an exact
* factor of two is the same): the conv reads x[y / 2, x / 2]
* pad same k / 2 zeros on every side
* pad down no zeros above and left, one below and right -- ZeroPad2d((0, 1, 0, 1)) then the
* conv, a stride-2 downsample's
* pad down no zeros above and left, one below and right: ZeroPad2d((0, 1, 0, 1)) then the conv,
* as a stride-2 downsample does
*
* f32 accumulation over (kh, kw, cin), the bias added, one rounding. */
int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
@@ -447,13 +409,14 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE;
const int64_t Hin = x->shape[0], Win = x->shape[1] / cin;
const int64_t Ho = y->shape[0], Wo = y->shape[1] / cout;
if (Hin <= 0 || Win <= 0 || Ho <= 0 || Wo <= 0) return RAD_E_SHAPE;
const int64_t Hv = Hin * up, Wv = Win * up;
const int64_t pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
return RAD_E_SHAPE;
if (numel(w) < cout * cin * k * k || numel(b) < cout) return RAD_E_SHAPE;
const int64_t xr = x->stride[0], yr = y->stride[0];
#pragma omp parallel for schedule(static)
REF_PAR_FOR(Ho * Wo * cout * cin * k * k)
for (int64_t oy = 0; oy < Ho; ++oy)
for (int64_t ox = 0; ox < Wo; ++ox)
for (int64_t co = 0; co < cout; ++co) {
@@ -475,7 +438,7 @@ int ref_conv2d_nhwc(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ l2norm_chan */
/* An image norm over the channels of each pixel, the reference's three bf16 tensors:
/* An image norm over each pixel's channels, as upstream's three bf16 tensors:
* n1 = bf16(x / max(||x||, 1e-12)), n2 = bf16(n1 * sqrt(n)), y = bf16(n2 * gamma), then `act`
* (none, or silu: bf16(y * sigmoid(y))). */
int ref_l2norm_chan(const RadArgs* a, RadStream) {
@@ -486,11 +449,11 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) {
const char* act = p_str(a, "act", "none");
const bool silu = act && !std::strcmp(act, "silu");
if (!silu && act && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t rows = rows_n(y, n);
if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
const float sq = (float)std::sqrt((double)n);
const uint32_t dt = y->dtype;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
@@ -498,10 +461,10 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) {
for (int64_t c = 0; c < n; ++c) { const float v = ldt(x, xb + c * xs); ss += v * v; }
const float nrm = std::max(std::sqrt(ss), 1e-12f);
for (int64_t c = 0; c < n; ++c) {
const float n1 = rnd(dt, ldt(x, xb + c * xs) / nrm);
const float n2 = rnd(dt, n1 * sq);
float v = rnd(dt, n2 * ldt(g, c));
if (silu) v = v / (1.0f + std::exp(-v));
const float n1 = round_dt(dt, ldt(x, xb + c * xs) / nrm);
const float n2 = round_dt(dt, n1 * sq);
float v = round_dt(dt, n2 * ldt(g, c));
if (silu) v = v / (1.0f + ref_exp(-v));
stt(y, yb + c * ys, v);
}
}
@@ -512,7 +475,7 @@ int ref_l2norm_chan(const RadArgs* a, RadStream) {
/* d2s_add, the decoder's upsampling shortcut (Wan's DupUp3D on one frame): x [H, W * cin] repeated
* `rep = cout * F / cin` times per channel and dealt into a 2x larger y [2H, 2W * cout], added:
* y[2r+i, 2c+j, o] += x[r, c, (o * F + off + 2i + j) / rep], F = 4 * ft, off = 4 when ft is 2
* (the second of the two frames a temporal factor makes is the one a first chunk keeps). */
* (a first chunk keeps the second of the two frames a temporal factor makes). */
int ref_d2s_add(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -520,12 +483,13 @@ int ref_d2s_add(const RadArgs* a, RadStream) {
if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE;
if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE;
const int64_t H = x->shape[0], W = x->shape[1] / cin;
if (H <= 0 || W <= 0) return RAD_E_SHAPE;
if (y->shape[0] != 2 * H || y->shape[1] / cout != 2 * W) return RAD_E_SHAPE;
const int64_t F = 4 * ft, off = ft == 2 ? 4 : 0;
if ((cout * F) % cin) return RAD_E_SHAPE;
const int64_t rep = cout * F / cin;
const int64_t xr = x->stride[0], yr = y->stride[0];
#pragma omp parallel for schedule(static)
REF_PAR_FOR(4 * H * W * cout)
for (int64_t oy = 0; oy < 2 * H; ++oy)
for (int64_t ox = 0; ox < 2 * W; ++ox)
for (int64_t o = 0; o < cout; ++o) {
@@ -539,8 +503,8 @@ int ref_d2s_add(const RadArgs* a, RadStream) {
/* s2d_avg_add, the encoder's downsampling shortcut (Wan's AvgDown3D on one frame): each 2x2 block
* of x [2H, 2W * cin] dealt into channels and averaged in groups of gs = cin * F / cout into
* y [H, W * cout], added. A channel of the dealt row is (c, t, i, j) at c * F + 4t + 2i + j; with
* ft 2 the frame t == 0 is the zero frame the reference pads in front, which the mean still counts. */
* y [H, W * cout], added. A dealt channel (c, t, i, j) sits at c * F + 4t + 2i + j; with ft 2,
* frame t == 0 is upstream's zero padding frame, which the mean still counts. */
int ref_s2d_avg_add(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
@@ -548,12 +512,13 @@ int ref_s2d_avg_add(const RadArgs* a, RadStream) {
if (cin <= 0 || cout <= 0 || (ft != 1 && ft != 2)) return RAD_E_SHAPE;
if (x->rank != 2 || y->rank != 2 || x->shape[1] % cin || y->shape[1] % cout) return RAD_E_SHAPE;
const int64_t H = y->shape[0], W = y->shape[1] / cout;
if (H <= 0 || W <= 0) return RAD_E_SHAPE;
if (x->shape[0] != 2 * H || x->shape[1] / cin != 2 * W) return RAD_E_SHAPE;
const int64_t F = 4 * ft;
if ((cin * F) % cout) return RAD_E_SHAPE;
const int64_t gs = cin * F / cout;
const int64_t xr = x->stride[0], yr = y->stride[0];
#pragma omp parallel for schedule(static)
REF_PAR_FOR(H * W * cout * gs)
for (int64_t oy = 0; oy < H; ++oy)
for (int64_t ox = 0; ox < W; ++ox)
for (int64_t o = 0; o < cout; ++o) {
@@ -565,7 +530,7 @@ int ref_s2d_avg_add(const RadArgs* a, RadStream) {
acc += ldt(x, (2 * oy + i) * xr + (2 * ox + j) * cin + c);
}
const int64_t yo = oy * yr + ox * cout + o;
stt(y, yo, ldt(y, yo) + rnd(y->dtype, acc / (float)gs));
stt(y, yo, ldt(y, yo) + round_dt(y->dtype, acc / (float)gs));
}
return RAD_OK;
}
@@ -578,9 +543,9 @@ int ref_to_rgba8(const RadArgs* a, RadStream) {
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n);
if (rows <= 0 || rows_n(x, n) < rows || y->dtype != RAD_U8) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
const int64_t rows = rows_of(y, n);
if (rows <= 0 || rows_of(x, n) < rows || y->dtype != RAD_U8) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
@@ -601,17 +566,13 @@ int ref_gelu_tanh(const RadArgs* a, RadStream) {
const RadTensor *x = &a->t[0], *y = &a->t[1];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_n(y, n);
if (rows <= 0 || rows_n(x, n) < rows) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
const int64_t rows = rows_of(y, n);
if (rows <= 0 || rows_of(x, n) < rows) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
const int64_t yb = rowoff(y, r, n), ys = laststride(y);
for (int64_t c = 0; c < n; ++c) {
const float v = ldt(x, xb + c * xs);
const float t = std::tanh(0.7978845608028654f * (v + 0.044715f * v * v * v));
stt(y, yb + c * ys, 0.5f * v * (1.0f + t));
}
for (int64_t c = 0; c < n; ++c) stt(y, yb + c * ys, act_gelu_tanh(ldt(x, xb + c * xs)));
}
return RAD_OK;
}
@@ -622,7 +583,7 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) {
const RadTensor *v = &a->t[0], *idx = &a->t[1], *x = &a->t[2];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_n(v, n), dst_rows = rows_n(x, n);
const int64_t M = rows_of(v, n), dst_rows = rows_of(x, n);
if (M <= 0 || numel(idx) < M) return RAD_E_SHAPE;
for (int64_t m = 0; m < M; ++m)
if (ld_int(idx->dtype, idx->data, offlin(idx, m)) >= dst_rows) return RAD_E_INVAL;
@@ -637,13 +598,12 @@ int ref_scatter_add_rows(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ attn_prefix_self */
/* Attention over two key sources: the sequence's PREFIX, `seqused[s]` positions in the paged cache,
* and the step's OWN rows, `k` and `v` beside `q` and not in the cache. Self row i of a sequence
* sees every prefix key and, with `causal`, its own rows j <= i -- otherwise all of them.
/* Attention over two key sources: the sequence's prefix (`seqused[s]` positions in the paged cache)
* and the step's own rows (`k` and `v` beside `q`, not cached). Self row i sees every prefix key
* and its own rows j <= i with `causal`, all of them otherwise.
*
* It is the attention of a sequence whose rows are recomputed each step against a prefix that is
* not: an image's latent rows against the conditioning, or one segment of the conditioning against
* the segments before it. */
* For rows recomputed each step against a fixed prefix: an image's latent rows against the
* conditioning, or one conditioning segment against the segments before it. */
/* quant_act_i8g's rule for one row of `n`: the scale (amax/127, 1 for an all-zero row) and the
* codes rint(clamp(x * (1/scale), +-127)), in f32 as the device computes them. `code` may be `x`:
* each code is written after its value is read. */
@@ -662,7 +622,7 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *kv = &a->t[3];
const RadTensor *bt = &a->t[4], *su = &a->t[5], *cu = &a->t[6], *o = &a->t[11];
const RadTensor *kdes = t_in(a, 7), *vdes = t_in(a, 8);
/* THE INT8 Q.K FORM: the own keys' codes and scales given, everything else quantised here. */
/* The int8 Q.K form: own keys' codes and scales are given; everything else is quantised here. */
const RadTensor *k8 = t_in(a, 9), *ks = t_in(a, 10);
const char* qk = p_str(a, "qk", "bf16");
const bool i8 = std::strcmp(qk, "i8") == 0;
@@ -671,24 +631,31 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
const int64_t head_dim = p_int(a, "head_dim", 0), gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
const int64_t block_size = kv->rank == 4 ? kv->shape[2] : p_int(a, "block_size", 0);
/* The widest head held in the stack rows below. */
constexpr int64_t kHdMax = 1024;
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > 1024) return RAD_E_UNSUPPORTED;
if (head_dim > kHdMax) return RAD_E_UNSUPPORTED;
const int64_t kv_heads = kv->rank == 4 ? kv->shape[1] : 0;
if (kv_heads <= 0) return RAD_E_SHAPE;
const int64_t q_heads = kv_heads * gqa, n_seq = numel(cu) - 1;
if (n_seq <= 0 || numel(su) < n_seq) return RAD_E_SHAPE;
/* The rows are cu's own span, which need not start at 0: one segment of a longer sequence is
* passed as the two offsets that bound it. */
/* The rows are cu's span, which need not start at 0: a segment of a longer sequence is passed
* as its two bounding offsets. */
const int64_t r_first = cu_at(cu, 0), rows = cu_at(cu, n_seq) - r_first;
if (rows <= 0) return RAD_E_SHAPE;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[0] : max_blocks;
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[1] : 1;
/* Every prefix key must have a block-table entry. */
for (int64_t s = 0; s < n_seq; ++s)
if (ld_int(su->dtype, su->data, offlin(su, s)) > max_blocks * block_size) return RAD_E_SHAPE;
const int64_t q_rs = row_stride(q, q_heads * head_dim), k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_rs = row_stride(v, kv_heads * head_dim), o_rs = row_stride(o, q_heads * head_dim);
const int64_t k8_rs = i8 ? row_stride(k8, kv_heads * head_dim) : 0;
const int64_t ks_rs = i8 ? row_stride(ks, kv_heads) : 0;
const int64_t sb = kv->stride[0], sh = kv->stride[1], so = kv->stride[2];
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#pragma omp parallel for schedule(dynamic)
REF_PAR_FOR_DYN(rows * q_heads * head_dim * 64)
for (int64_t idx = 0; idx < rows * q_heads; ++idx) {
const int64_t h = idx % q_heads, r = r_first + idx / q_heads, kh = h / gqa;
const int64_t s = seq_of(cu, n_seq, r), b0 = cu_at(cu, s), b1 = cu_at(cu, s + 1);
@@ -698,12 +665,12 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
const int64_t qb = r * q_rs + h * head_dim;
const int64_t nself = causal ? i + 1 : b1 - b0;
auto pkey = [&](int64_t j, int64_t d, bool val) -> float {
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + j / block_size);
const int64_t blk = ld_int(bt->dtype, bt->data, s * bt_rs + (j / block_size) * bt_cs);
if (blk < 0) return 0.0f;
return ldt(kv, blk * sb + kh * sh + (j % block_size) * so + (val ? head_dim : 0) + d) *
(val ? vds : kds);
};
float xq[1024], cq[1024], ck[1024];
float xq[kHdMax], cq[kHdMax], ck[kHdMax];
float sq = 1.0f;
if (i8) {
for (int64_t d = 0; d < head_dim; ++d) xq[d] = ldt(q, qb + d);
@@ -738,7 +705,7 @@ int ref_attn_prefix_self(const RadArgs* a, RadStream) {
const int64_t nk = P + nself;
float mx = -INFINITY;
for (int64_t j = 0; j < nk; ++j) mx = std::max(mx, dot(j));
float acc[1024];
float acc[kHdMax];
for (int64_t d = 0; d < head_dim; ++d) acc[d] = 0.0f;
float sum = 0.0f;
for (int64_t j = 0; j < nk; ++j) {
+109 -145
View File
@@ -1,14 +1,12 @@
/* ref_hc.cpp -- the GATED RESIDUAL, which is Qwen4-Exp's replacement for a pre-norm and a
* residual add.
/* ref_hc.cpp -- the gated residual, Qwen4-Exp's replacement for a pre-norm and a residual add.
*
* ============================== WHAT IT IS ==============================
* ============================== What it is ==============================
*
* The residual stream is `hc` times as wide as the model: hidden_size 2560 at hc_count 4 is a
* 10240-wide stream carried through every layer, entered as four identical copies of the
* embedding and collapsed once at the end. Every block reads a 2560 mix of the four and writes
* its output back into all four, and BOTH the read's mix and the write's per-stream gain are
* data-dependent -- which is what "gated" means here and what makes this a pair of ops rather
* than a norm.
* 10240-wide stream through every layer, entered as four identical copies of the embedding and
* collapsed once at the end. Each block reads a 2560 mix of the four and writes its output back
* into all four; both the read's mix and the write's per-stream gain are data-dependent ("gated"),
* so this is a pair of ops rather than a norm.
*
* hc_read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one gain of
* 10240 over all four, `1 + w`
@@ -17,67 +15,40 @@
* inj[s] = 2 * sigmoid(W_inj[s] . N / hc) four scalars in (0, 2)
* hc_write h[s] += inj[s] * y for each stream s
*
* THE WRITE READS THE UNNORMED `h`, NOT `N`. The reference is `hyper_input + injection` where
* `hyper_input` is the argument the read received, so the normalisation is consumed entirely by
* the block input and the gate and never enters the stream. Writing back into `N` instead would
* re-normalise the residual on every one of the 96 connections, which diverges within a few
* layers and is the one mistake this pair can make that still produces fluent text.
* The write reads the unnormed `h`, not `N`: upstream computes `hyper_input + injection` with
* `hyper_input` the read's argument, so the normalisation feeds only the block input and the gates.
* Writing into `N` would re-normalise the residual at each of the 96 connections and diverge within
* a few layers while still producing fluent text.
*
* THE MIX IS A MEAN, NOT A SUM. `.mean(dim=-2)` over the hc dimension -- so the divide by hc
* happens here AND, separately, inside both gate arguments (`/ self.hc_count` before the silu and
* before the inject sigmoid). Three divisions by 4, all of them in the reference, none of them
* derivable from the others.
* The mix is a mean (`.mean(dim=-2)` over hc), and both gate arguments are separately divided by
* hc (`/ self.hc_count` before the silu and before the inject sigmoid): three independent
* divisions, all upstream's.
*
* ============================== WHY THE QUANTISER IS IN THE READ ==============================
* ============================== Why the quantiser is in the read ==============================
*
* `q` and `s` are OPTIONAL outputs. Present, the read also emits the fp8 block-scaled form of `x`
* that the following projection's GEMM wants, which is what keeps a gated-residual model at the
* same launch count as a pre-norm one: every launch costs a fixed floor whatever it computes, and a
* model with 96 connections cannot afford a separate quantise op at each. Absent, `x` is bf16 and the
* caller quantises it itself -- which is what the final mixer does, because its consumer is the
* lm_head and that is bf16.
* `q` and `s` are optional outputs. Present, the read also emits the fp8 block-scaled `x` the next
* projection's GEMM wants, keeping the launch count equal to a pre-norm model's (each launch has a
* fixed cost, and there are 96 connections). Absent, `x` is bf16 and the caller quantises it: the
* final mixer feeds the bf16 lm_head.
*
* IT QUANTISES WHAT WAS WRITTEN. `x` is narrowed to its own dtype first and the codes are taken
* from the narrowed value, not from the f32 accumulator, because that is what a fused kernel
* necessarily does and the two have to agree bit for bit -- the same epilogue-fold rule the GDN
* out-projection's quantiser follows (libref/ref_gdn.cpp).
* Codes are taken from `x` narrowed to its dtype, not from the f32 accumulator, as a fused kernel
* must (the GDN out-projection quantiser follows the same rule, libref/ref_gdn.cpp).
*
* `rq` and `rs` are the same argument one consumer further: had_quant_act_fp8 of the stored `x`,
* for an expert plane stored with a 128-wide Hadamard, whose block would otherwise run that
* quantiser as a launch of its own.
* `rq` and `rs` extend this one consumer further: had_quant_act_fp8 of the stored `x`, for expert
* planes stored with a 128-wide Hadamard.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include "ref_planes.h"
#include <cmath>
using namespace ref;
namespace {
/* A value narrowed to a tensor's own dtype and read back. The reference's arithmetic is f32
* throughout, but the REFERENCE MODEL's is not: torch's grouped norm returns `.type_as(x)`, so the
* two matrix products and the final multiply all read a bf16 `N`. Rounding once here is what makes
* a fused kernel able to match this to a tolerance that means something. */
inline float narrow(uint32_t dtype, float v) {
uint32_t buf[2] = {0, 0};
st_dt(dtype, buf, 0, v);
return ld_dt(dtype, buf, 0);
}
inline float sigmoidf(float v) { return 1.0f / (1.0f + std::exp(-v)); }
inline float siluf(float v) { return v * sigmoidf(v); }
} /* namespace */
/* ------------------------------------------------------------------ hc_enter */
/* THE WIDE STREAM'S FIRST VALUE: hc identical copies of the embedding.
*
* It is one launch for the whole step and it exists rather than being folded into the embedding
* lookup because the lookup's weight is [vocab, n] and its output width is n -- a wide output
* would be a different op with a different weight shape. The four streams are identical here and
* diverge at the first connection, because each block writes into all four with a DIFFERENT
* per-branch gain. */
/* The wide stream's initial value: hc identical copies of the embedding. Separate from the
* embedding lookup, whose output width is n. The streams diverge at the first connection, since
* each block writes into them with different per-stream gains. */
int ref_hc_enter(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
@@ -87,7 +58,7 @@ int ref_hc_enter(const RadArgs* a, RadStream) {
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(h) < rows * hc * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * hc * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), hb = rowoff(h, r, hc * n);
const int64_t xs = laststride(x), hs = laststride(h);
@@ -101,8 +72,8 @@ int ref_hc_enter(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ hc_read */
int ref_hc_read(const RadArgs* a, RadStream) {
/* NOT `have(a, 6)`: operand 4 is the OPTIONAL inject weight, and a prefix test would refuse
* the final mixer -- the one connection that has none. The required ones are 0..3 and 5. */
/* Not `have(a, 6)`: operand 4, the inject weight, is optional (the final mixer has none).
* Operands 0..3 and 5 are required. */
if (a->n_t < 6) return RAD_E_INVAL;
if (!rad_arg_in(a, 0) || !rad_arg_in(a, 1) || !rad_arg_in(a, 2) || !rad_arg_in(a, 3) ||
!rad_arg_in(a, 5)) return RAD_E_INVAL;
@@ -112,10 +83,10 @@ int ref_hc_read(const RadArgs* a, RadStream) {
const RadTensor* up = &a->t[3];
const RadTensor* injw = t_in(a, 4); /* absent on the final mixer */
const RadTensor* x = &a->t[5];
const RadTensor* inj = rad_arg_in(a, 6); /* an OUT, but the optional test is the same */
const RadTensor* inj = rad_arg_in(a, 6); /* an OUT; same optional test */
const RadTensor* q = rad_arg_in(a, 7);
const RadTensor* s = rad_arg_in(a, 8);
const RadTensor* rq = rad_arg_in(a, 9); /* the ROTATED fp8 form, for a w4a8h consumer */
const RadTensor* rq = rad_arg_in(a, 9); /* the rotated fp8 form, for a w4a8h consumer */
const RadTensor* rs = rad_arg_in(a, 10);
const int64_t n = p_int(a, "n", 0);
@@ -127,11 +98,19 @@ int ref_hc_read(const RadArgs* a, RadStream) {
const int64_t hn = hc * n;
const int64_t rows = numel(h) / hn;
if (rows <= 0 || numel(x) < rows * n || numel(w) < hn ||
numel(down) < lr * hn || numel(up) < hn * lr) return RAD_E_SHAPE;
if (rows <= 0 || numel(x) < rows * n || numel(w) < hn) return RAD_E_SHAPE;
/* The mixing matrices are plain, or codes and a scale plane joined (ref_planes.h; `mix`
* e4m3), read element by element as the core's decoder gives them. A plain matrix's dtype is
* what the gate it feeds is rounded to; a joined one's gates are rounded to h's. */
ScaledRows jd, ju;
const bool jdown = is_joined(down), jup = is_joined(up);
if (jdown) RAD_REF_TRY(scaled_rows(down, lr, hn, &jd));
else if (numel(down) < lr * hn) return RAD_E_SHAPE;
if (jup) RAD_REF_TRY(scaled_rows(up, hn, lr, &ju));
else if (numel(up) < hn * lr) return RAD_E_SHAPE;
const uint32_t ddt = jdown ? h->dtype : down->dtype, udt = jup ? h->dtype : up->dtype;
if (injw && numel(injw) < hc * hn) return RAD_E_SHAPE;
/* `inj` is what the paired hc_write consumes, so an inject WEIGHT with no inject OUTPUT is a
* caller that computed four scalars and threw them away -- refused rather than ignored. */
/* An inject weight without an inject output would compute scalars nobody reads; refused. */
if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE;
int64_t g = 0;
@@ -142,10 +121,9 @@ int ref_hc_read(const RadArgs* a, RadStream) {
ngrp = (n + g - 1) / g;
if (numel(q) < rows * n || !s || !s->data || numel(s) < rows * ngrp) return RAD_E_SHAPE;
}
/* The rotated form rotates each scale group whole, so the group must tile the row exactly and
* be a power of two: a block that straddled the end of the row would mix real values with
* padding, and no weight block was rotated that way. It is had_quant_act_fp8 of the stored `x`
* -- the operand's consumer cannot tell which op wrote it. */
/* The rotated form rotates each scale group whole, so the group must be a power of two that
* tiles the row; no weight block was rotated across padding. The result equals
* had_quant_act_fp8 of the stored `x`. */
int64_t rg = 0;
if (rq) {
rg = p_int(a, "group", 0);
@@ -154,12 +132,14 @@ int ref_hc_read(const RadArgs* a, RadStream) {
if (rg > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
}
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * hn * (2 * lr + hc))
for (int64_t r = 0; r < rows; ++r) {
const int64_t hb = rowoff(h, r, hn), xb = rowoff(x, r, n);
const int64_t hs = laststride(h), xs = laststride(x), ws = laststride(w);
/* ---- the grouped norm. One rsqrt per stream over its own n, then the full-width gain. */
/* ---- grouped norm: one rsqrt per stream over its n, then the full-width gain. N is
* rounded to h's dtype: upstream's norm returns `.type_as(x)`, so every product reads it
* rounded. */
std::vector<float> N((size_t)hn);
for (int64_t c = 0; c < hc; ++c) {
double ss = 0.0;
@@ -170,69 +150,60 @@ int ref_hc_read(const RadArgs* a, RadStream) {
const float sc = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
for (int64_t i = 0; i < n; ++i) {
const int64_t j = c * n + i;
N[(size_t)j] = narrow(h->dtype,
ldt(h, hb + j * hs) * sc * (ldt(w, j * ws) + wadd));
N[(size_t)j] = round_dt(h->dtype,
ldt(h, hb + j * hs) * sc * (ldt(w, j * ws) + wadd));
}
}
/* ---- the read gate: 10240 -> lowrank -> 10240, silu between and sigmoid after. */
/* ---- read gate: hc*n -> lowrank -> hc*n, silu between and sigmoid after. */
std::vector<float> d((size_t)lr);
for (int64_t j = 0; j < lr; ++j) {
float acc = 0.0f;
const int64_t db = rowoff(down, j, hn);
const int64_t db = jdown ? 0 : rowoff(down, j, hn);
const int64_t ds = laststride(down);
for (int64_t i = 0; i < hn; ++i) acc += N[(size_t)i] * ldt(down, db + i * ds);
d[(size_t)j] = narrow(down->dtype, siluf(acc / (float)hc));
for (int64_t i = 0; i < hn; ++i)
acc += N[(size_t)i] * (jdown ? jd.at(j, i) : ldt(down, db + i * ds));
d[(size_t)j] = round_dt(ddt, act_silu(acc / (float)hc));
}
/* ---- the mix, and the mean over the streams. */
/* ---- the gated mix, averaged over the streams. */
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int64_t c = 0; c < hc; ++c) {
const int64_t row = c * n + i;
const int64_t ub = rowoff(up, row, lr);
const int64_t ub = jup ? 0 : rowoff(up, row, lr);
const int64_t us = laststride(up);
float gv = 0.0f;
for (int64_t j = 0; j < lr; ++j) gv += d[(size_t)j] * ldt(up, ub + j * us);
acc += narrow(up->dtype, sigmoidf(gv)) * N[(size_t)row];
for (int64_t j = 0; j < lr; ++j)
gv += d[(size_t)j] * (jup ? ju.at(row, j) : ldt(up, ub + j * us));
acc += round_dt(udt, act_sigmoid(gv)) * N[(size_t)row];
}
stt(x, xb + i * xs, acc / (float)hc);
}
/* ---- the per-branch write gates. */
/* ---- per-stream write gates. */
if (injw && inj) {
const int64_t ib = rowoff(inj, r, hc), is = laststride(inj);
for (int64_t c = 0; c < hc; ++c) {
float acc = 0.0f;
const int64_t jb = rowoff(injw, c, hn), js = laststride(injw);
for (int64_t i = 0; i < hn; ++i) acc += N[(size_t)i] * ldt(injw, jb + i * js);
stt(inj, ib + c * is, 2.0f * sigmoidf(acc / (float)hc));
stt(inj, ib + c * is, 2.0f * act_sigmoid(acc / (float)hc));
}
}
/* ---- the optional fp8 form of x, read back from what was stored. */
/* ---- optional fp8 form of x, from the stored values. */
if (q && q->data) {
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float amax = 0.0f;
for (int64_t i = k0; i < k1; ++i) {
const float m = std::fabs(ldt(x, xb + i * xs));
if (m > amax) amax = m;
}
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float invs = 1.0f / sc;
for (int64_t i = k0; i < k1; ++i) {
float v = ldt(x, xb + i * xs) * invs;
if (v > 448.0f) v = 448.0f;
if (v < -448.0f) v = -448.0f;
st_dt(q->dtype, q->data, qb + i * qs, v);
}
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
k1 - k0, 448.0f, q, qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
/* ---- the optional ROTATED fp8 form of x, from the same stored values. */
/* ---- optional rotated fp8 form of x, from the same stored values. */
if (rq) {
float buf[REF_HAD_MAX];
const int64_t qb = rowoff(rq, r, n), qs = laststride(rq), rgrp = n / rg;
@@ -240,19 +211,8 @@ int ref_hc_read(const RadArgs* a, RadStream) {
const int64_t k0 = gi * rg;
for (int64_t i = 0; i < rg; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
fwht(buf, rg);
float amax = 0.0f;
for (int64_t i = 0; i < rg; ++i) {
const float m = std::fabs(buf[i]);
if (m > amax) amax = m;
}
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float invs = 1.0f / sc;
for (int64_t i = 0; i < rg; ++i) {
float v = buf[i] * invs;
if (v > 448.0f) v = 448.0f;
if (v < -448.0f) v = -448.0f;
st_dt(rq->dtype, rq->data, qb + (k0 + i) * qs, v);
}
const float sc = q8_group([&](int64_t i) { return buf[i]; }, rg, 448.0f, rq,
qb + k0 * qs, qs);
stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc);
}
}
@@ -261,8 +221,8 @@ int ref_hc_read(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ hc_write */
/* `h[s] += inj[s] * y` for each of the hc streams. In place: `h` is the only output and it is the
* stream the paired read was handed, unchanged by it. */
/* h[s] += inj[s] * y for each of the hc streams, in place on the stream the paired read was given
* (which the read left unchanged). */
int ref_hc_write(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
@@ -277,7 +237,7 @@ int ref_hc_write(const RadArgs* a, RadStream) {
const int64_t rows = numel(y) / n;
if (rows <= 0 || numel(h) < rows * hn || numel(inj) < rows * hc) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * hn)
for (int64_t r = 0; r < rows; ++r) {
const int64_t yb = rowoff(y, r, n), hb = rowoff(h, r, hn), ib = rowoff(inj, r, hc);
const int64_t ys = laststride(y), hs = laststride(h), is = laststride(inj);
@@ -294,20 +254,19 @@ int ref_hc_write(const RadArgs* a, RadStream) {
/* ================================================================== mtp_enter
*
* THE MULTI-TOKEN-PREDICTION HEAD'S ENTRY, for a model whose residual stream is `hc` wide.
* The multi-token-prediction head's entry for a model whose residual stream is `hc` wide.
*
* A pre-norm MTP head (Qwen3.5, Qwen3-Next, DeepSeek-V3) joins the trunk's hidden state and the
* next token's embedding with ONE `fc` over their concatenation, and arch/common/rad_block_mtp_fp8.h
* runs that as two rmsnorms into the two halves of one buffer and a single gemm_nt. Qwen4-Exp's
* head cannot: its hidden state is the WIDE stream and the checkpoint carries TWO square matrices,
* next token's embedding with one `fc` over their concatenation (arch/common/rad_block_mtp_fp8.h:
* two rmsnorms into one buffer, one gemm_nt). Qwen4-Exp's hidden state is the wide stream and the
* checkpoint carries two square matrices,
*
* mtp.fc_hidden.weight [n, n] mtp.pre_fc_norm_hidden.weight [hc * n]
* mtp.fc_embedding.weight [n, n] mtp.pre_fc_norm_embedding.weight [n]
*
* so the hidden half is `fc_h` applied to EACH of the hc sub-streams -- the reference's own
* `.unflatten(-1, (hc_count, hidden_size))` idiom, which is how every other 10240-wide tensor in
* this architecture is handled -- and the embedding half is one 2560-wide product added into all
* hc of them, which is the same broadcast the trunk enters the stream with (`hidden_states.repeat`).
* so the hidden half is `fc_h` applied to each of the hc sub-streams (upstream's
* `.unflatten(-1, (hc_count, hidden_size))` idiom) and the embedding half is one n-wide product
* added into all of them, the broadcast the trunk enters the stream with (`hidden_states.repeat`).
*
* rs_e = rsqrt(mean(e^2) + eps)
* ne[j] = e[j] * rs_e * (w_e[j] + wadd)
@@ -316,19 +275,15 @@ int ref_hc_write(const RadArgs* a, RadStream) {
* nh[k][j] = h[k*n+j] * rs[k] * (w_h[k*n+j] + wadd)
* x[k*n+i] = sum_j fc_h[i][j] * nh[k][j] + fe[i]
*
* IT IS ONE OP AND NOT SIX because every intermediate above is a DIFFERENT VIEW of the same bytes
* and this ABI has no reinterpreting view: `nh` is [M*hc, n] to the GEMM and [M, hc*n] to the norm,
* and core/runtime/issue.cpp narrows dim 0 or the last dimension with every stride left alone --
* which is the right rule and makes a row-pitch change inexpressible. Spelling the entry as one op
* is what lets the wide buffers stay wide. It is also six launches off a draft round, and a draft
* round is the latency this head exists to hide.
* One op rather than six because the intermediates are different views of the same bytes and the
* ABI has no reinterpreting view: `nh` is [M*hc, n] to the GEMM and [M, hc*n] to the norm, while
* core/runtime/issue.cpp only narrows dim 0 or the last dimension with strides unchanged, so a
* row-pitch change is inexpressible. It also saves launches in the latency-critical draft round.
*
* `ngroup` IS THE ONE THING THE CHECKPOINT DOES NOT SAY. A [hc * n] gain fits both a grouped norm
* (hc rsqrts, one per sub-stream -- what Qwen4ExpTextGatedResidual does at every one of its 97
* connections) and a flat one (a single rsqrt over the whole wide row). Both are self-consistent
* and no per-op oracle can tell them apart, exactly as rad_block_mtp_fp8.h's concat order cannot
* be told apart -- and it has the same cheap empirical answer, the draft acceptance rate. `ngroup`
* carries the choice so it is asked once, at declare, instead of being compiled in.
* `ngroup` is the one thing the checkpoint does not say: a [hc * n] gain fits both a grouped norm
* (hc rsqrts, one per sub-stream, as Qwen4ExpTextGatedResidual does) and a flat one (one rsqrt over
* the wide row). No per-op oracle can tell them apart; the draft acceptance rate can. `ngroup`
* makes it a declare-time choice.
*/
int ref_mtp_enter(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
@@ -352,15 +307,21 @@ int ref_mtp_enter(const RadArgs* a, RadStream) {
const int64_t rows = numel(h) / hn;
if (rows <= 0 || numel(e) < rows * n || numel(x) < rows * hn) return RAD_E_SHAPE;
if (numel(w_h) < hn || numel(w_e) < n) return RAD_E_SHAPE;
if (numel(fc_h) < n * n || numel(fc_e) < n * n) return RAD_E_SHAPE;
/* The fc matrices are plain, or codes and a scale plane joined (`fc` e4m3), as hc_read's. */
ScaledRows jh, je;
const bool jfh = is_joined(fc_h), jfe = is_joined(fc_e);
if (jfh) RAD_REF_TRY(scaled_rows(fc_h, n, n, &jh));
else if (numel(fc_h) < n * n) return RAD_E_SHAPE;
if (jfe) RAD_REF_TRY(scaled_rows(fc_e, n, n, &je));
else if (numel(fc_e) < n * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * hn * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t hb = rowoff(h, r, hn), eb = rowoff(e, r, n), xb = rowoff(x, r, hn);
const int64_t hs = laststride(h), es = laststride(e), xs = laststride(x);
const int64_t whs = laststride(w_h), wes = laststride(w_e);
/* ---- the embedding half: one norm and one 2560-wide product, shared by every stream. */
/* ---- embedding half: one norm and one n-wide product, shared by every stream. */
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(e, eb + i * es);
@@ -369,19 +330,21 @@ int ref_mtp_enter(const RadArgs* a, RadStream) {
const float rse = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
std::vector<float> ne((size_t)n);
for (int64_t i = 0; i < n; ++i)
ne[(size_t)i] = narrow(e->dtype, ldt(e, eb + i * es) * rse * (ldt(w_e, i * wes) + wadd));
ne[(size_t)i] = round_dt(e->dtype,
ldt(e, eb + i * es) * rse * (ldt(w_e, i * wes) + wadd));
std::vector<float> fe((size_t)n);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
const int64_t fb = rowoff(fc_e, i, n);
const int64_t fb = jfe ? 0 : rowoff(fc_e, i, n);
const int64_t fs = laststride(fc_e);
for (int64_t j = 0; j < n; ++j) acc += ne[(size_t)j] * ldt(fc_e, fb + j * fs);
for (int64_t j = 0; j < n; ++j)
acc += ne[(size_t)j] * (jfe ? je.at(i, j) : ldt(fc_e, fb + j * fs));
fe[(size_t)i] = acc;
}
/* ---- the hidden half: the grouped norm, then the SAME square matrix over each stream.
* The flat reading is one rsqrt over the whole wide row; `ngroup` says which. */
/* ---- hidden half: the norm (grouped, or flat per `ngroup`), then the same square matrix
* over each stream. */
float flat = 0.0f;
if (ngroup == 1) {
double sw = 0.0;
@@ -405,14 +368,15 @@ int ref_mtp_enter(const RadArgs* a, RadStream) {
}
for (int64_t i = 0; i < n; ++i) {
const int64_t j = c * n + i;
nh[(size_t)i] = narrow(h->dtype,
ldt(h, hb + j * hs) * sc * (ldt(w_h, j * whs) + wadd));
nh[(size_t)i] = round_dt(h->dtype,
ldt(h, hb + j * hs) * sc * (ldt(w_h, j * whs) + wadd));
}
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
const int64_t fb = rowoff(fc_h, i, n);
const int64_t fb = jfh ? 0 : rowoff(fc_h, i, n);
const int64_t fs = laststride(fc_h);
for (int64_t j = 0; j < n; ++j) acc += nh[(size_t)j] * ldt(fc_h, fb + j * fs);
for (int64_t j = 0; j < n; ++j)
acc += nh[(size_t)j] * (jfh ? jh.at(i, j) : ldt(fc_h, fb + j * fs));
stt(x, xb + (c * n + i) * xs, acc + fe[(size_t)i]);
}
}
+502 -191
View File
@@ -1,24 +1,22 @@
/* ref_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-k.
*
* ============================== WHAT sorted_tok CARRIES ==============================
* ============================== What sorted_tok carries ==============================
*
* docs/OPS.md names the operand and does not say what is in it, and the choice decides whether
* `moe_gather` can work at all. It holds the FLATTENED (token, slot) index -- token * top_k + slot
* -- grouped by expert, not the bare token id. With the bare id, gather would have no way to find
* which of a token's top_k routing weights applies to a row, and would have to search. This is
* also vLLM's `sorted_token_ids` convention, so a kernel lifted from there needs no translation.
* The flattened (token, slot) index, token * top_k + slot, grouped by expert; not the bare token
* id, with which moe_gather could not find which of a token's routing weights applies to a row.
* This is vLLM's `sorted_token_ids` convention.
*
* A slot whose expert id is outside [0, n_expert) is DROPPED: it is not counted, and the tail of
* sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A padded batch row has to
* be expressible, and a negative id is how it is said.
* A slot whose expert id is outside [0, n_expert) is dropped: not counted, and the tail of
* sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A negative id marks a
* padded batch row.
*
* The histogram this produces is what rad_route_report hands the heat engine; it is read back
* asynchronously and consumed on the NEXT step, and nothing here blocks the compute stream
* (spec §5.5).
* The resulting histogram is what rad_route_report hands the heat engine; it is read back
* asynchronously and consumed on the next step, without blocking the compute stream (spec §5.5).
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include "ref_planes.h"
#include <algorithm>
#include <cstdlib>
@@ -27,10 +25,9 @@
using namespace ref;
/* ------------------------------------------------------------------ router_topk */
/* softmax over ALL n_expert logits, then the top_k by probability, then -- if `norm` -- renormalise
* the kept weights to sum to one. Softmax first and select second is the order Mixtral, Qwen3 and
* every model in this engine's scope use; selecting first and normalising the raw logits would be
* a different router, so the order is part of the op rather than an implementation choice. */
/* Softmax over all n_expert logits, then the top_k by probability, then (with `norm`) renormalise
* the kept weights to sum to one. Softmax-then-select is the order Mixtral, Qwen3 and every model in
* scope use; selecting first would be a different router. */
int ref_router_topk(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *ids = &a->t[1], *w = &a->t[2];
@@ -41,7 +38,7 @@ int ref_router_topk(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_expert;
if (M <= 0 || numel(ids) < M * top_k || numel(w) < M * top_k) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_expert * (top_k + 2))
for (int64_t m = 0; m < M; ++m) {
const int64_t lb = rowoff(lg, m, n_expert), ls = laststride(lg);
float mx = -INFINITY;
@@ -53,8 +50,8 @@ int ref_router_topk(const RadArgs* a, RadStream) {
for (int64_t e = 0; e < n_expert; ++e) sum += ref_exp(ldt(lg, lb + e * ls) - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
/* The selection runs on the LOGITS, not the probabilities: softmax is monotone, so the
* order is identical and the comparison is exact rather than through an exp. */
/* Select on the logits: softmax is monotone, so the order is the same and the comparison
* avoids an exp. */
float pv = INFINITY;
int64_t pi = -1, kept = 0;
float wsum = 0.0f;
@@ -78,9 +75,9 @@ int ref_router_topk(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ moe_scatter */
/* `protect`: local experts the sort places LAST, in the order listed, the rest closed up -- the
* layout a layer that serves a few experts with a second grouped GEMM needs (libr4d's sort_place).
* Returns false on a list that is not strictly ascending inside [0, n). */
/* `protect`: local experts the sort places last, in the order listed, the rest closed up; the
* layout a layer serving a few experts with a second grouped GEMM needs (libr4d's sort_place).
* Returns false unless the list is strictly ascending within [0, n). */
static bool sort_places(const char* s, int64_t n, std::vector<int64_t>* place) {
std::vector<int64_t> prot;
for (const char* c = s ? s : ""; *c;) {
@@ -100,17 +97,15 @@ static bool sort_places(const char* s, int64_t n, std::vector<int64_t>* place) {
return true;
}
/* A stable counting sort of the (token, slot) pairs by expert id. Serial on purpose: it is O(M) on
* a batch's worth of small integers, and a parallel version would need a per-thread histogram and
* a prefix pass to stay stable, which is more code than the work it saves. */
/* A stable counting sort of the (token, slot) pairs by expert id. Serial: a parallel stable version
* would need per-thread histograms and a prefix pass, more code than the work it saves. */
int ref_moe_scatter(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *ids = &a->t[0], *sorted = &a->t[1], *off = &a->t[2], *cnt = &a->t[3];
const int64_t n_expert = p_int(a, "n_expert", 0);
const int64_t top_k = p_int(a, "top_k", 1);
/* THIS RANK'S FIRST EXPERT. Subtracted from every routed id, so the range test below is the
* one that was always here and the sort is over local indices -- which is what the weight
* table, the offsets and the GEMM downstream are indexed by. */
/* This rank's first expert, subtracted from every routed id so the sort runs over local
* indices, as the weight table, offsets and downstream GEMM expect. */
const int64_t base = p_int(a, "expert_base", 0);
if (n_expert <= 0 || top_k <= 0 || base < 0) return RAD_E_SHAPE;
const int64_t M = numel(ids) / top_k;
@@ -139,40 +134,247 @@ int ref_moe_scatter(const RadArgs* a, RadStream) {
}
st_int(off->dtype, off->data, offlin(off, n_expert), run);
/* A second cursor pass rather than mutating the offsets: the offsets are an output the caller
* reads, and rewinding them afterwards is one more place to be wrong. */
/* Each slot goes to its expert's cursor, in ascending slot order. The cursors are a copy, so
* the offsets (an output) are never mutated. */
for (int64_t i = run; i < T; ++i) st_int(sorted->dtype, sorted->data, offlin(sorted, i), -1);
for (int64_t e = 0, w = 0; e < n_expert; ++e) {
w = ld_int(off->dtype, off->data, offlin(off, e));
for (int64_t i = 0; i < T; ++i) {
if (at(i) != e) continue;
st_int(sorted->dtype, sorted->data, offlin(sorted, w), i);
++w;
}
std::vector<int64_t> cur((size_t)n_expert);
for (int64_t e = 0; e < n_expert; ++e)
cur[(size_t)e] = ld_int(off->dtype, off->data, offlin(off, e));
for (int64_t i = 0; i < T; ++i) {
const int64_t e = at(i);
if (e >= 0) st_int(sorted->dtype, sorted->data, offlin(sorted, cur[(size_t)e]++), i);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */
/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i and
* `a_order` picks row(i) -- `sorted_tok[i] / top_k` when the activation has one row per TOKEN,
* and i itself when it already has one per (token, slot). The output is in SORTED order -- one
* row per (token, slot) pair, laid out the way moe_scatter grouped them -- because that is the
* layout that makes the expert loop contiguous, which is the entire point of the scatter.
* moe_gather puts it back.
/* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks
* row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per
* (token, slot). The output is in sorted order (one row per (token, slot), grouped as moe_scatter
* left them) so the expert loop is contiguous; moe_gather restores token order.
*
* THE WEIGHT OPERAND IS A TABLE (RAD_OPD_WTAB), not a plane, and ref_gemm.h's expert_entry() is
* where that is read. A layer's experts are separate movement units, so after placement one is in
* VRAM and the next is streamed over the link; `base + e*stride` describes only the case where
* nothing was offloaded. The stacked form is still accepted, because a caller with no engine
* behind it -- rad-kbench replaying a fixture -- has nowhere to put a pointer array.
* The weight operand is a table (RAD_OPD_WTAB), read through ref_gemm.h's expert_entry(): experts
* are separate movement units, so one may be in VRAM while the next is streamed. The stacked form
* is also accepted for callers without an engine (rad-kbench fixtures).
*
* The quantised arm is the same walk with ref_gemm.h's Scales over both operands, and the sub-sum
* is accumulated from the RAW CODES and scaled once per group exactly as `gemm_nt_q` does: the
* two references must agree in the last bits or rad-kbench blames a kernel for a choice made
* here. Only the WEIGHT scale grid is block-shaped -- one scale per 128x128 tile of an expert --
* while the activation's is per row per group of K, which is `rblk = 1`, which is what
* make_scales derives on its own from the two extents. */
* The quantised arm uses ref_gemm.h's Scales and quant_dot, accumulating raw codes and scaling once
* per group exactly as gemm_nt_q does. Only the weight scale grid is block-shaped (one scale per
* 128x128 tile); the activation's is per row per K group (rblk = 1), which make_scales derives from
* the extents. */
/* quant_tile with the loaders resolved at compile time for the grouped GEMM's dtype pairs (the
* same floats as Dyn, which serves the rest). */
typedef float* (*TileFn)(const Mat&, const Mat&, const Scales&, const Scales&, const int64_t*,
int64_t, int64_t, int64_t, int64_t, float*);
#define REF_TILE_ROW(DA) \
case DA: \
switch (db) { \
case RAD_F8E4M3: return &quant_tile<Fix<DA>, Fix<RAD_F8E4M3>>; \
case RAD_I4: return &quant_tile<Fix<DA>, Fix<RAD_I4>>; \
case RAD_I8: return &quant_tile<Fix<DA>, Fix<RAD_I8>>; \
case RAD_BF16: return &quant_tile<Fix<DA>, Fix<RAD_BF16>>; \
case RAD_F32: return &quant_tile<Fix<DA>, Fix<RAD_F32>>; \
default: return &quant_tile<Dyn, Dyn>; \
}
static TileFn pick_tile(uint32_t da, uint32_t db) {
switch (da) {
REF_TILE_ROW(RAD_F8E4M3)
REF_TILE_ROW(RAD_BF16)
REF_TILE_ROW(RAD_F32)
REF_TILE_ROW(RAD_I8)
default: return &quant_tile<Dyn, Dyn>;
}
}
#undef REF_TILE_ROW
/* ------------------------------------------------------------------ the codebook experts
*
* Qwen3.8-Flash-Next's experts (docs/MOE-W4.md) are u4 or u5 codes indexing a table of 16 or 32
* f32 levels, with a scale per (row, group of K): bf16 per 128 (`w4nla8h`), or E4M3 per 64 or 32
* times one fixed f32 (`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`). Element (n, k) of an expert is
* table[code(n, k)] * scale(n, k / group), times `scale.1` where there is one. The codes view takes
* the planes `codes,table` and the two-level forms' scale view `scale,scale.1`; such a weight is
* stored in the joined form of abi/rad_planes.h, which these rows' layout hooks ask for. A view of
* one plane (w4nla8h's bf16 scale, every view of the other dtypes) is stored as it is.
*
* The arithmetic is quant_dot's: per weight group, the sub-sum of table values times activation
* codes, then `(sub * sa) * sb` with sb the scale times its level in f32. The logical form the
* oracle and rad-kbench pass (enc_selection_logical: table entries for codes, scale products for
* scales) goes through the same chain, so the two readings agree bit for bit wherever the logical
* operands hold the values exactly, as E4M3 and bf16 do for the shipped tables and scales. libr4d
* folds each 64- or 32-wide group's sum under its scale first and the activation's scale per 128
* after (`(sub0 * sb0 + sub1 * sb1) * sa`), which differs in the last bits. */
/* What a codebook `dtype` stores: the code width, the scale's group along K and dtype, and whether
* the scale view carries the level above it. `bits` is 0 for any other dtype. */
struct CbForm { int bits; int64_t group; uint32_t sdt; bool level; };
static CbForm cb_form(const RadParam* p, int n_p) {
const RadParam* d = rad_param_find(p, n_p, "dtype");
const char* s = d && d->kind == RAD_P_STR ? d->sval : nullptr;
if (s && !std::strcmp(s, "w4nla8h")) return CbForm{ 4, 128, RAD_BF16, false };
if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true };
return CbForm{ 0, 0, 0, false };
}
/* Whether a selection of several planes for `operand` is what `dtype` names: the codes operands of
* both grouped GEMMs are 2, 6, 8 and 10 and their scales 3, 7, 9 and 11. RAD_E_DTYPE otherwise,
* which refuses the weight at declare by name. */
static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, int n_planes) {
const CbForm f = cb_form(p, n_p);
const bool codes = operand == 2 || operand == 6 || operand == 8 || operand == 10;
const bool scale = operand == 3 || operand == 7 || operand == 9 || operand == 11;
if (!f.bits || (!codes && !scale) || !enc || !sel || n_planes != 2 ||
std::strcmp(enc->transform, "fwht128") != 0)
return RAD_E_DTYPE;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_SHAPE;
const RadEncPlane& a = enc->plane[sel[0]];
const RadEncPlane& b = enc->plane[sel[1]];
if (codes)
return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED &&
a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) &&
a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") &&
b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 &&
b.extent[1] == ((int64_t)1 << f.bits)
? RAD_OK : RAD_E_DTYPE;
return f.level && !std::strcmp(a.role, "scale") && a.kind == RAD_PLANE_TILED &&
a.dtype == f.sdt && a.block[0] == 1 && a.block[1] == f.group &&
!std::strcmp(b.role, "scale.1") && b.kind == RAD_PLANE_TILED && b.dtype == RAD_F32 &&
b.block[0] == 0 && b.block[1] == 0
? RAD_OK : RAD_E_DTYPE;
}
extern "C" int ref_moe_cb_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_layout(enc, sel, planes, n_planes, out);
}
extern "C" int ref_moe_cb_relayout(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* planes,
int n_planes, void* dst, int64_t dst_bytes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
extern "C" int ref_moe_cb_unrelayout(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const void* src,
int64_t src_bytes, const RadTensor* planes, int n_planes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n_planes);
}
/* The joined form's header when weight entry `t` holds one. An entry smaller than a header is a
* plain plane, and is not read past its end. */
static const RadPlanesHeader* cb_joined(const RadTensor& t) {
int64_t n = 1;
for (uint32_t i = 0; i < t.rank; ++i) n *= t.shape[i];
if (!t.data || rad_dtype_bytes(t.dtype, n) < (int64_t)sizeof(RadPlanesHeader)) return nullptr;
return rad_planes_header(t.data);
}
/* A codebook expert's codes, which LdCb reads as table values. The RadTensor comes first, so a Mat
* over `t` reaches the rest: element i is (i / cols, i % cols) of a plane whose rows start
* `row_bytes` apart, the layout rad_planes.h keeps. */
struct CbTensor {
RadTensor t; /* `data`: the codes plane, from the tile's first weight row */
float tab[32];
int64_t cols = 0, row_bytes = 0;
int bits = 0;
};
struct LdCb {
static inline float ld(const RadTensor* t, int64_t i) {
const CbTensor* c = reinterpret_cast<const CbTensor*>(t);
const int64_t r = i / c->cols, k = i - r * c->cols;
return c->tab[rad_load_bits((const uint8_t*)c->t.data + r * c->row_bytes, c->bits, k)];
}
};
/* An expert's codes when its entry is the joined form: 1 with `out` filled, 0 for a plain plane
* (any dtype but u4 and u5), RAD_E_DTYPE for a form these kernels do not read and RAD_E_SHAPE for
* codes not covering [n, k]. A u4 or u5 entry is always joined: only its table says what a code
* means. */
static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbTensor* out) {
if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0;
const RadPlanesHeader* h = rad_planes_header(w.data);
const RadPlanesEntry *ec = nullptr, *et = nullptr;
const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr;
const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr;
if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE;
const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0;
if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 ||
et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 ||
et->rows * et->cols != ((int64_t)1 << bits))
return RAD_E_DTYPE;
if (ec->rows < n || ec->cols < k) return RAD_E_SHAPE;
out->t = w;
out->t.data = const_cast<void*>(codes);
std::memcpy(out->tab, tab, sizeof(float) << bits);
out->cols = ec->cols;
out->row_bytes = ec->row_bytes;
out->bits = bits;
return 1;
}
/* An expert's scales beside joined codes: the scale times the level above it. */
struct CbScale {
Scales s;
float mul = 1.0f;
inline float at(int64_t row, int64_t g) const { return (s.p ? s.grp(row, g) : 1.0f) * mul; }
};
/* From the joined `scale,scale.1` form when the entry holds one, else the plane as make_scales
* reads it (w4nla8h's bf16 scale, or none). RAD_E_DTYPE for a joined form of other planes. */
static int cb_scale(const RadTensor* ws, int64_t n, int64_t k, CbScale* out) {
out->mul = 1.0f;
const RadPlanesHeader* h = ws ? cb_joined(*ws) : nullptr;
if (!h) {
out->s = make_scales(ws, n, k, false);
return RAD_OK;
}
const RadPlanesEntry *es = nullptr, *e1 = nullptr;
const void* sp = rad_planes_find(ws->data, "scale", &es);
const void* lp = rad_planes_find(ws->data, "scale.1", &e1);
if (!sp || !lp || h->n_planes != 2) return RAD_E_DTYPE;
const uint32_t dt = es->dtype;
if (es->kind != RAD_PLANE_TILED || es->block[0] < 1 || es->block[1] < 1 ||
(dt != RAD_F8E4M3 && dt != RAD_BF16 && dt != RAD_F16 && dt != RAD_F32) ||
e1->kind != RAD_PLANE_TILED || e1->dtype != RAD_F32 || e1->block[0] != 0 ||
e1->block[1] != 0 || e1->rows != 1 || e1->cols != 1)
return RAD_E_DTYPE;
if ((n + es->block[0] - 1) / es->block[0] > es->rows ||
(k + es->block[1] - 1) / es->block[1] > es->cols)
return RAD_E_SHAPE;
Scales s{};
s.p = sp;
s.dt = dt;
s.rs = es->cols;
s.cs = 1;
s.group = es->block[1];
s.rblk = es->block[0];
s.e8m0 = false;
out->s = s;
std::memcpy(&out->mul, lp, sizeof out->mul);
return 1;
}
static TileFn pick_cb_tile(uint32_t da) {
switch (da) {
case RAD_F8E4M3: return &quant_tile<Fix<RAD_F8E4M3>, LdCb>;
case RAD_BF16: return &quant_tile<Fix<RAD_BF16>, LdCb>;
case RAD_F32: return &quant_tile<Fix<RAD_F32>, LdCb>;
default: return &quant_tile<Dyn, LdCb>;
}
}
static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5;
if (!have(a, n_opd)) return RAD_E_INVAL;
@@ -183,9 +385,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const RadTensor* sorted = &a->t[quant ? 4 : 2];
const RadTensor* off = &a->t[quant ? 5 : 3];
const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4];
/* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- or, for
* `moe_gemm_q_mod4`, four by the expert's number mod 4; the plain arm's are one, which is the
* same walk with every expert in the first class. */
/* The quantised arm's experts are two tables by parity (see ref_registry.cpp), or four by
* expert number mod 4 for `moe_gemm_q_mod4`; the plain arm has one, every expert in class 0. */
const RadTensor* W1 = quant ? &a->t[6] : W;
const RadTensor* ws1_ = quant ? t_in(a, 7) : nullptr;
const bool two = quant;
@@ -195,10 +396,9 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const RadTensor* wsq[4] = { ws_, ws1_, quant && nc == 4 ? t_in(a, 9) : nullptr,
quant && nc == 4 ? t_in(a, 11) : nullptr };
/* "sorted" means `a` already has one row per (token, slot) in the scatter's order, which is
* what the DOWN projection of a routed block reads -- its input is the first projection's
* output. "token" (the default, and the gate_up projection's case) means one row per token,
* gathered through sorted_tok. See ref_registry.cpp for why this is said and not derived. */
/* "sorted": `a` has one row per (token, slot) in scatter order (the down projection, reading
* the first projection's output). "token" (default, gate_up): one row per token, gathered
* through sorted_tok. See ref_registry.cpp for why this is stated, not derived. */
const char* ord = p_str(a, "a_order", "token");
const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0;
if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED;
@@ -218,8 +418,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE;
/* The output is the widest class's width, the activation the longest class's K. Class q
* holds ceil((n - q) / nc) experts. */
/* The output is the widest class's N and the activation the longest class's K. Class q holds
* ceil((n - q) / nc) experts. */
int64_t N = 0, K = 0;
for (int q = 0; q < nc; ++q) {
if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE;
@@ -231,16 +431,14 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t T = numel(Y) / N;
if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE;
/* `y` HAS ONE ROW PER (token, slot) AND `a` HAS WHATEVER `a_order` SAYS. The token count is
* recovered from T and top_k; the activation's row count is T under "sorted" and M under
* "token", and it is checked against THAT rather than against either extent on its own -- a
* sorted-order operand with only M rows is a caller that handed the down projection the
* gate_up projection's buffer. */
/* `y` has one row per (token, slot); `a` has T rows under "sorted" and M = T / top_k under
* "token", checked against the matching count (M rows under "sorted" means the down projection
* was handed gate_up's input buffer). */
const int64_t M = T / top_k;
const int64_t AR = sorted_a ? T : M;
if (M <= 0 || numel(A) < AR * K) return RAD_E_SHAPE;
const Mat ma = as_mat(A, AR, K);
const Mat ma = as_mat(A, K);
const Scales SA = make_scales(as_, AR, K, false);
const int64_t gp = p_int(a, "group", 0);
if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE;
@@ -248,14 +446,16 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t y_rs = row_stride(Y, N);
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
/* Per-expert readings, built once outside the row loop: a table lookup and a Scales are cheap,
* and doing them per row would be T of them against n_expert. A null `data` means the operand
* could not be read as a table at all, which is refused before the loop because an OpenMP body
* cannot return. Expert e is entry e / nc of class e % nc. */
/* Per-expert views, built once outside the row loop (and validated there, since an OpenMP body
* cannot return). Expert e is entry e / nc of class e % nc. */
std::vector<RadTensor> we((size_t)n_expert), wse((size_t)n_expert);
std::vector<Mat> mw((size_t)n_expert);
std::vector<Scales> SW((size_t)n_expert);
std::vector<int64_t> en((size_t)n_expert), ek((size_t)n_expert);
/* Codebook experts (joined codes): every expert of the call, or none. */
std::vector<CbTensor> cbt;
std::vector<CbScale> cbs;
bool codebook = false;
for (int64_t e = 0; e < n_expert; ++e) {
const int q = (int)(e % nc);
const RadTensor* tw = Wq[q];
@@ -268,48 +468,161 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
if (!we[(size_t)e].data) return RAD_E_STRIDE;
if (we[(size_t)e].rank < 2 || we[(size_t)e].shape[0] < n ||
we[(size_t)e].shape[1] < k) return RAD_E_SHAPE;
mw[(size_t)e] = as_mat(&we[(size_t)e], n, k);
if (quant && ts) {
wse[(size_t)e] = expert_entry(ts, ix);
if (!wse[(size_t)e].data) return RAD_E_STRIDE;
SW[(size_t)e] = make_scales(&wse[(size_t)e], n, k, false);
} else {
SW[(size_t)e] = make_scales(nullptr, n, k, false);
}
if (quant) {
CbTensor ct;
const int jc = cb_codes(we[(size_t)e], n, k, &ct);
if (jc < 0) return jc;
if (e == 0 && jc > 0) {
codebook = true;
cbt.resize((size_t)n_expert);
cbs.resize((size_t)n_expert);
}
if (codebook != (jc > 0)) return RAD_E_DTYPE;
if (codebook) {
cbt[(size_t)e] = ct;
const int js = cb_scale(ts ? &wse[(size_t)e] : nullptr, n, k, &cbs[(size_t)e]);
if (js < 0) return js;
continue;
}
/* A joined scale is read only beside joined codes. */
if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE;
}
mw[(size_t)e] = as_mat(&we[(size_t)e], k);
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false);
}
const int64_t fy = N / parts;
#pragma omp parallel for schedule(static)
/* Each row's expert (the binary search over the offsets) and activation row, or -1 for a row
* that is all zeros: a dropped slot, or a token past `a`. Zeros are written, never stale
* arena bytes, and so are each part's columns past a narrower class's width. */
std::vector<int64_t> ex((size_t)T, -1), tk((size_t)T, 0);
REF_PAR_FOR(T * N)
for (int64_t i = 0; i < T; ++i) {
const int64_t flat = ld_int(sorted->dtype, sorted->data, offlin(sorted, i));
if (flat < 0) { /* a dropped slot: a zero row, never stale arena bytes */
for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f);
continue;
int64_t e = -1;
if (flat >= 0) {
int64_t lo = 0, hi = n_expert;
while (lo + 1 < hi) {
const int64_t mid = (lo + hi) / 2;
if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid;
}
const int64_t tok = sorted_a ? i : flat / top_k;
if (tok < AR) { e = lo; tk[(size_t)i] = tok; }
}
/* Which expert owns row i: a binary search over the offsets, so a 256-expert model does
* not pay a linear scan per row. */
int64_t lo = 0, hi = n_expert;
while (lo + 1 < hi) {
const int64_t mid = (lo + hi) / 2;
if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid;
}
const int64_t e = lo;
const int64_t tok = sorted_a ? i : flat / top_k;
if (tok >= AR) { for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f); continue; }
ex[(size_t)i] = e;
const int64_t fc = e >= 0 ? en[(size_t)e] / parts : 0;
for (int64_t n = 0; n < N; ++n)
if (n - (n / fy) * fy >= fc) stt(Y, i * y_rs + n * y_cs, 0.0f);
}
const Mat& B = mw[(size_t)e];
const Scales& SB = SW[(size_t)e];
/* The live rows grouped by expert, ascending within one, and the tiles over them: one per
* (expert, part, column block, row group). Output column pp * fy + j is weight row
* pp * fc + j of the expert's [N_e, K_e] plane. */
std::vector<int64_t> start((size_t)n_expert + 1, 0), order((size_t)T), arow((size_t)T);
for (int64_t i = 0; i < T; ++i)
if (ex[(size_t)i] >= 0) ++start[(size_t)ex[(size_t)i] + 1];
for (int64_t e = 0; e < n_expert; ++e) start[(size_t)e + 1] += start[(size_t)e];
{
std::vector<int64_t> cur(start.begin(), start.end() - 1);
for (int64_t i = 0; i < T; ++i) {
const int64_t e = ex[(size_t)i];
if (e < 0) continue;
const int64_t at = cur[(size_t)e]++;
order[(size_t)at] = i;
arow[(size_t)at] = tk[(size_t)i];
}
}
struct Item { int64_t e, pp, j0, r0, R; };
std::vector<Item> items;
int64_t rg_max = 1;
for (int64_t e = 0; e < n_expert; ++e) {
const int64_t cnt = start[(size_t)e + 1] - start[(size_t)e];
if (cnt <= 0) continue;
const int64_t fc = en[(size_t)e] / parts;
/* One product, and it is `quant_dot`'s: the same grouping and the same order the dense
* quantised GEMM folds its two scales in. A second copy of that arithmetic here would be a
* second place for it to be right by accident -- the expert GEMM and gemm_nt_q are the
* same function over different weights, and a reference that spelled them differently
* would put an ulp between them that no tolerance is meant to absorb. Output column n is
* weight row (n / fy) * fc + n % fy, and zero past a narrower class's part. */
for (int64_t n = 0; n < N; ++n) {
const int64_t pp = n / fy, j = n - pp * fy;
stt(Y, i * y_rs + n * y_cs,
j < fc ? quant_dot(ma, B, SA, SB, tok, pp * fc + j, ek[(size_t)e]) : 0.0f);
const TileGrid tg = tile_grid(cnt, fc * parts);
if (tg.rg > rg_max) rg_max = tg.rg;
for (int64_t pp = 0; pp < parts; ++pp)
for (int64_t j0 = 0; j0 < fc; j0 += REF_NB)
for (int64_t r0 = 0; r0 < cnt; r0 += tg.rg)
items.push_back({ e, pp, j0, r0, (r0 + tg.rg < cnt) ? tg.rg : cnt - r0 });
}
std::vector<TileFn> tile((size_t)n_expert);
for (int64_t e = 0; e < n_expert; ++e)
tile[(size_t)e] = codebook ? pick_cb_tile(A->dtype)
: pick_tile(A->dtype, we[(size_t)e].dtype);
REF_PAR_REGION(T * N * K)
{
/* A codebook tile's scales are its REF_NB weight rows' groups, at most K of them. */
const size_t wsf = tile_ws_floats(rg_max);
float* const ws = ws_get(wsf + (codebook ? (size_t)(REF_NB * K) : 0));
REF_FOR_DYN
for (int64_t it = 0; it < (int64_t)items.size(); ++it) {
const Item& w = items[(size_t)it];
const int64_t e = w.e, fc = en[(size_t)e] / parts, ke = ek[(size_t)e];
const int64_t nb = (w.j0 + REF_NB < fc) ? REF_NB : fc - w.j0;
const int64_t base = start[(size_t)e] + w.r0;
if (codebook) {
/* The tile's weight rows as their own [nb, ke] operand: codes from its first row,
* and its scales, each times its level, as an f32 [nb, ngrp] stream. */
const int64_t wr0 = w.pp * fc + w.j0;
CbTensor lt = cbt[(size_t)e];
lt.t.data = (uint8_t*)lt.t.data + wr0 * lt.row_bytes;
const Mat B{ &lt.t, lt.cols, 1 };
const CbScale& cs = cbs[(size_t)e];
const int64_t g = cs.s.p && cs.s.group > 0 ? cs.s.group : ke;
const int64_t ngrp = (ke + g - 1) / g;
float* const sb = ws + wsf;
for (int64_t j = 0; j < nb; ++j)
for (int64_t gi = 0; gi < ngrp; ++gi) sb[j * ngrp + gi] = cs.at(wr0 + j, gi);
Scales SB{};
SB.p = cs.s.p || cs.mul != 1.0f ? sb : nullptr;
SB.dt = RAD_F32;
SB.rs = ngrp;
SB.cs = 1;
SB.group = g;
SB.rblk = 1;
if (SA.p && SA.group < g) {
for (int64_t r = 0; r < w.R; ++r)
for (int64_t j = 0; j < nb; ++j)
stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs,
quant_dot<Dyn, LdCb>(ma, B, SA, SB, arow[(size_t)(base + r)], j,
ke));
continue;
}
const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R, 0, nb,
ke, ws);
for (int64_t r = 0; r < w.R; ++r) {
const int64_t i = order[(size_t)(base + r)];
for (int64_t j = 0; j < nb; ++j)
stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]);
}
continue;
}
const Mat& B = mw[(size_t)e];
const Scales& SB = SW[(size_t)e];
const int64_t g = SB.group > 0 ? SB.group : ke;
if (SA.p && SA.group < g) {
/* An activation grid finer than the weight's: quant_dot per element. */
for (int64_t r = 0; r < w.R; ++r)
for (int64_t j = 0; j < nb; ++j)
stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs,
quant_dot(ma, B, SA, SB, arow[(size_t)(base + r)],
w.pp * fc + w.j0 + j, ke));
continue;
}
const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R,
w.pp * fc + w.j0, nb, ke, ws);
for (int64_t r = 0; r < w.R; ++r) {
const int64_t i = order[(size_t)(base + r)];
for (int64_t j = 0; j < nb; ++j)
stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]);
}
}
}
return RAD_OK;
@@ -322,16 +635,14 @@ int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, t
/* ------------------------------------------------------------------ moe_gather */
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)].
*
* THE SUMMATION ORDER IS ASCENDING SLOT j, which is what makes this reproducible: an
* implementation that walked the expert-sorted rows instead would sum a token's contributions in
* expert-id order, and the two differ in the last bits.
* Summation is in ascending slot j; walking the expert-sorted rows would sum in expert-id order and
* differ in the last bits.
*
* The inverse permutation is rebuilt in blocks rather than allocated: one pass over sorted_tok per
* block of tokens, into a fixed stack array. That costs (M / block) passes, which at the sizes an
* MoE layer runs is nothing, and it keeps the op free of both scratch and allocation. */
* The inverse permutation is rebuilt per block of tokens into a fixed stack array, one pass over
* sorted_tok per block, so the op needs no scratch or allocation. */
int ref_moe_gather(const RadArgs* a, RadStream) {
/* Operands are POSITIONAL, so an absent shared pair is two NULL SLOTS rather than a shorter
* array: `have` demands all six and would refuse every unfolded call. */
/* Operands are positional: an absent shared pair is two null slots, which `have` would
* refuse. */
if (a->n_t < 6) return RAD_E_INVAL;
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
if (!ye->data || !ew->data || !sorted->data || !Y->data) return RAD_E_INVAL;
@@ -357,7 +668,7 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
const int64_t y_rs = Y->rank >= 2 ? Y->stride[Y->rank - 2] : n;
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(T * n)
for (int64_t b = 0; b < nblk; ++b) {
int32_t inv[INV_MAX];
const int64_t t0 = b * tb, t1 = (t0 + tb < M) ? t0 + tb : M;
@@ -383,9 +694,8 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
ldt(ye, (int64_t)i * ye_rs + c * ye_cs);
}
const int64_t yo = t * y_rs + c * y_cs;
/* THE NARROWS ARE THE UNFUSED PAIR'S, and the store is what performs them: the
* gather wrote a bf16 buffer and scale_rows narrowed its own product before the
* add, so both operands of the sum are rounded and the sum is rounded again. */
/* The stores round as the unfused pair does: the gather's result and scale_rows'
* product are each rounded, then their sum. */
stt(Y, yo, acc);
if (!sh) continue;
const float g = ldt(Y, yo);
@@ -397,16 +707,28 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* One step of a selection sort over `n` candidates: the unused one with the largest value, ties to
* the lower id, skipping pads (id < 0). Returns its index, or -1 when none is left. */
template <class Id, class Val>
static int64_t next_best(int64_t n, const Id& id, const Val& val,
const std::vector<unsigned char>& used) {
int64_t best = -1;
for (int64_t c = 0; c < n; ++c) {
if (used[(size_t)c] || id(c) < 0) continue;
if (best < 0 || val(c) > val(best) || (val(c) == val(best) && id(c) < id(best))) best = c;
}
return best;
}
/* ------------------------------------------------------------------ row_topk */
/* Exact per-row top-R, descending, ties to the lower column. The same selection the router uses,
* exposed as its own op because a drafter's candidate set and a speculative tree both want it
* without a softmax in front. */
/* Exact per-row top-R, descending, ties to the lower column: the router's selection without the
* softmax, for drafter candidate sets and speculative trees. */
int ref_row_topk(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
/* The vocab-parallel form. `off` shifts every column reported, so a rank's slice reports
* global ids; `pairs` is the [M, R, 2] plane an all_gather moves, an int32 id in the first
* float slot beside its value. Both absent is the ordinary single-rank top-R. */
/* Vocab-parallel form: `vocab_off` shifts reported columns to global ids; `pairs` is the
* [M, R, 2] plane an all_gather moves (int32 id bits in the first float slot, then the value).
* Both absent is the single-rank top-R. */
const RadTensor* pairs = t_in(a, 3);
const int64_t off = p_int(a, "vocab_off", 0);
const int64_t N = p_int(a, "N", x->rank >= 2 ? x->shape[x->rank - 1] : 0);
@@ -416,7 +738,7 @@ int ref_row_topk(const RadArgs* a, RadStream) {
if (M <= 0 || numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * N * R)
for (int64_t m = 0; m < M; ++m) {
const int64_t xb = rowoff(x, m, N), xs = laststride(x);
float pv = INFINITY;
@@ -438,68 +760,57 @@ int ref_row_topk(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ row_topk_merge */
/* The other half of the vocab-parallel top-R: the R largest of world_size all-gathered per-rank
* candidate sets, in the same descending (idx, val) form the single-rank path produces, so
* everything downstream is handed the answer it would have had from an unsharded plane.
/* The other half of the vocab-parallel top-R: the R largest of world_size gathered per-rank
* candidate sets, in the single-rank path's descending (idx, val) form.
*
* TIES BREAK ON THE LOWER ID, which is what makes that equality true rather than approximate: a
* dense top-R over the whole vocabulary breaks ties on the lower column, so a merge that broke
* them on rank order would disagree with it exactly when two shards hold the same logit.
* Ties break on the lower id, matching a dense top-R over the whole vocabulary; rank order would
* disagree when two shards hold the same logit.
*
* A slot the producing rank could not fill carries id -1 and is DROPPED -- a sentinel rather than
* a -INFINITY value, because -inf is a value a masked logit legitimately takes. */
* An unfilled slot carries id -1 and is dropped; -inf cannot be the sentinel, since masked logits
* legitimately take it. */
int ref_row_topk_merge(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *g = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
const int64_t R = p_int(a, "R", 1);
const int64_t W = p_int(a, "world_size", 1);
if (R <= 0 || W <= 0) return RAD_E_SHAPE;
/* The rows are the OPERAND'S, not the parameter's: `M` is declared as a band ceiling and the
* gathered plane is narrowed to the rows this step actually has. */
/* Rows come from the operand; `M` is a band ceiling (see band_rows). */
const int64_t M = numel(g) / (W * R * 2);
if (M <= 0) return RAD_E_SHAPE;
if (g->dtype != RAD_F32 || numel(g) < M * W * R * 2) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * W * R * R)
for (int64_t m = 0; m < M; ++m) {
const float* const row = (const float*)g->data + m * W * R * 2;
/* A selection sort over W*R entries: 32 of them at world 2 and R 16, so the quadratic
* form is cheaper than anything with an allocation in it, and it is the reference. */
auto id = [&](int64_t c) {
int32_t v;
std::memcpy(&v, row + c * 2, sizeof v);
return v;
};
auto value = [&](int64_t c) { return row[c * 2 + 1]; };
/* Selection sort over W*R entries (32 at world 2, R 16). */
std::vector<unsigned char> used((size_t)(W * R), 0);
for (int64_t r = 0; r < R; ++r) {
int64_t best = -1;
float bv = 0.0f;
int32_t bid = 0;
for (int64_t c = 0; c < W * R; ++c) {
if (used[(size_t)c]) continue;
int32_t id;
std::memcpy(&id, row + c * 2, sizeof id);
if (id < 0) continue; /* a pad, not a candidate */
const float v = row[c * 2 + 1];
if (best < 0 || v > bv || (v == bv && id < bid)) { best = c; bv = v; bid = id; }
}
const int64_t best = next_best(W * R, id, value, used);
if (best >= 0) used[(size_t)best] = 1;
st_int(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx),
best >= 0 ? (int64_t)bid : -1);
stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? bv : -INFINITY);
best >= 0 ? (int64_t)id(best) : -1);
stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? value(best) : -INFINITY);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pair_argmax */
/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as
* a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position
* picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane --
* `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the
* largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row.
/* The top-1 of a gathered pair plane as a proposal: one id per row at the output's pitch, so a block
* drafter's per-position picks land contiguous in the token buffer it verifies. `pairs` holds `n`
* (int32 id, f32 value) pairs per row, a negative id being a pad; largest value wins, ties to the
* lower id, matching an argmax over the unsharded row.
*
* Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters:
* row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8
* bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank
* sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no
* valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */
* Not row_topk_merge with R = 1: a rank sending R = 1 sends 8 bytes, which a row-interleaved
* all_gather of 16-byte words cannot carry, so ranks send R >= 2 and this takes the top-1 of all
* `n`. A row with no valid pair writes -1 and -inf. `val` is optional. */
int ref_pair_argmax(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *p = &a->t[0], *idx = &a->t[1];
@@ -507,12 +818,12 @@ int ref_pair_argmax(const RadArgs* a, RadStream) {
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */
/* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */
/* Rows come from the operand; `M` is a band ceiling. */
const int64_t M = numel(p) / (n * 2);
if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE;
const float* const pf = (const float*)p->data;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n)
for (int64_t m = 0; m < M; ++m) {
int32_t bid = -1;
float bv = -INFINITY;
@@ -530,27 +841,18 @@ int ref_pair_argmax(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ logit_rerank */
/* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD.
/* Rescore R candidates per row exactly against the full-precision head.
*
* A speculative step can afford a COARSE draft head -- the target verifies every proposal, so a
* worse draft costs acceptance and never a token -- but it cannot afford to be wrong about which
* candidate the coarse head liked best. A heavily quantised head disagrees with the exact one
* about the top-1 on a noticeable fraction of rows, and rescoring its top few candidates against
* the exact weight recovers nearly all of that disagreement.
* A speculative draft head may be coarse (the target verifies every proposal, so a worse draft
* costs only acceptance), but a heavily quantised head often disagrees with the exact one on the
* top-1. Rescoring its top few candidates against the exact weight recovers most of that, reading
* R rows of the head instead of all of it.
*
* So this is the second half of a coarse top-R: the coarse head proposes R, the exact weight
* scores those R and only those R, and the answer is re-sorted on the exact values. R rows of the
* head against the whole of it is the entire point -- a few hundred KB against a few hundred MB.
* `vocab_off` is the shard's first column; ids are global, as row_topk reports and row_topk_merge
* consumes them. A candidate outside this rank's rows becomes a pad.
*
* `vocab_off` IS THE SHARD'S FIRST COLUMN, and the ids are GLOBAL, because that is the form
* `row_topk` reports and `row_topk_merge` consumes. A candidate outside this rank's rows is not
* this rank's to score and becomes a pad: under vocab-parallel drafting `row_topk` picked from
* this rank's plane, so every id it reports is local and the guard is for a caller that mixes
* them.
*
* ORDER, AND WHY IT IS THE SAME ORDER row_topk USES: descending by value, ties to the LOWER id.
* The merge downstream breaks ties that way and the two have to agree, or a tie between shards
* resolves differently from a tie inside one. A pad sorts last and keeps id -1. */
* Output order matches row_topk: descending value, ties to the lower id, so the downstream merge
* resolves ties consistently. Pads sort last with id -1. */
int ref_logit_rerank(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *in = &a->t[2];
@@ -561,35 +863,44 @@ int ref_logit_rerank(const RadArgs* a, RadStream) {
const int64_t NV = p_int(a, "n_vocab", 0);
const int64_t voff = p_int(a, "vocab_off", 0);
if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE;
/* The rows are the OPERAND'S: `M` is a band ceiling and a step narrows it. */
/* Rows come from the operand; `M` is a band ceiling. */
const int64_t M = numel(x) / K;
if (M <= 0 || numel(in) < M * R) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (numel(w) < NV * K) return RAD_E_SHAPE;
/* A head of codes and scale (ref_planes.h) is read element by element as the core's decoder
* gives it, so its scores are those of the decoded f32 head. */
ScaledRows sr;
const bool joined = is_joined(w);
if (joined) RAD_REF_TRY(scaled_rows(w, NV, K, &sr));
else if (numel(w) < NV * K) return RAD_E_SHAPE;
/* The pair plane is f32 words, ids carried by bit pattern, as row_topk writes it. */
if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE;
const int64_t ws = laststride(w);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * R * K)
for (int64_t m = 0; m < M; ++m) {
std::vector<int32_t> id((size_t)R);
std::vector<float> sc((size_t)R);
for (int64_t r = 0; r < R; ++r) {
const int64_t g = ld_int(in->dtype, in->data, rowoff(in, m, R) + r * laststride(in));
const int64_t local = g - voff;
if (g < 0 || local < 0 || local >= NV) { id[(size_t)r] = -1; sc[(size_t)r] = -INFINITY; continue; }
double acc = 0.0; /* the reference sums wide and in order */
if (g < 0 || local < 0 || local >= NV) {
id[(size_t)r] = -1;
sc[(size_t)r] = -INFINITY;
continue;
}
double acc = 0.0; /* summed in double, in k order */
const int64_t wb = joined ? 0 : rowoff(w, local, K);
for (int64_t k = 0; k < K; ++k)
acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x))
* (double)ldt(w, local * K + k);
acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x)) *
(double)(joined ? sr.at(local, k) : ldt(w, wb + k * ws));
id[(size_t)r] = (int32_t)g;
sc[(size_t)r] = (float)acc;
}
std::vector<unsigned char> used((size_t)R, 0);
for (int64_t o = 0; o < R; ++o) {
int64_t best = -1;
for (int64_t c = 0; c < R; ++c) {
if (used[(size_t)c] || id[(size_t)c] < 0) continue;
if (best < 0 || sc[(size_t)c] > sc[(size_t)best] ||
(sc[(size_t)c] == sc[(size_t)best] && id[(size_t)c] < id[(size_t)best])) best = c;
}
const int64_t best = next_best(R, [&](int64_t c) { return id[(size_t)c]; },
[&](int64_t c) { return sc[(size_t)c]; }, used);
const int32_t oid = best >= 0 ? id[(size_t)best] : -1;
const float ov = best >= 0 ? sc[(size_t)best] : -INFINITY;
if (best >= 0) used[(size_t)best] = 1;
+67 -101
View File
@@ -1,73 +1,56 @@
/* ref_ngram.cpp -- the n-gram row ids of Qwen4-Exp's Per-Layer Embedding (PLE).
*
* ============================== WHAT IT IS ==============================
* ============================== What it is ==============================
*
* PLE gives ONE layer of the model a second embedding table, addressed not by the token but by a
* HASH of the last `ngram` tokens. Qwen3.8-Flash-Next's is 320,001,536 rows of 160 bf16 -- 102 GB,
* 51 of the model's 125 billion parameters, four fifths of the checkpoint -- read sixteen rows a
* token. This op computes those sixteen row ids. The gather itself is `gather_rows` over
* [M * heads] indices; there is no second op for it and there should not be.
* PLE gives one layer a second embedding table addressed by a hash of the last `ngram` tokens
* rather than the token. Qwen3.8-Flash-Next's has 320,001,536 rows of 160 bf16 (102 GB, 51 of the
* model's 125 billion parameters), read sixteen rows per token. This op computes those row ids; the
* gather itself is `gather_rows` over [M * heads] indices.
*
* mixed[2gram] = t0*m0 ^ t1*m1 heads 0..7
* mixed[3gram] = t0*m0 ^ t1*m1 ^ t2*m2 heads 8..15
* ids[h] = mixed[ngram(h)] % vocab[h] + offset[h]
*
* `m`, `vocab` and `offset` are all IN THE CHECKPOINT (`layer_multipliers`,
* `ngram_heads_vocab_sizes`, `ngram_heads_offsets`). The reference builds them from a splitmix64
* seed and a prime search at construction time; a served model reads them, and re-deriving them
* here would be a second source for sixteen numbers the container already carries.
* `m`, `vocab` and `offset` come from the checkpoint (`layer_multipliers`,
* `ngram_heads_vocab_sizes`, `ngram_heads_offsets`). Upstream derives them from a splitmix64 seed
* and a prime search; re-deriving them here would be a second source for numbers the container
* already carries.
*
* ============================== TWO THINGS THAT LOOK LIKE TRAPS AND ARE NOT ==================
* ============================== Two non-traps ==============================
*
* THE HASH IS NON-NEGATIVE BY CONSTRUCTION, so `%` is unambiguous. The reference uses
* `torch.remainder`, which FLOORS -- `remainder(-5, 3) == 1` where C gives -2 -- and the obvious
* worry is that an int64 multiply wraps into the sign bit and the two disagree. It cannot:
* `_build_layer_multipliers` bounds every multiplier by `(2^63-1) // vocab_size`, so each product
* of a real token id has its sign bit clear, and an XOR of values with a clear sign bit has a
* clear sign bit. `mixed` is always in [0, 2^63). The bound is not decoration -- it is what makes
* the hash well defined -- so this op REFUSES a multiplier or a token that would break it rather
* than producing a different answer from the reference in silence.
* The hash is non-negative, so `%` is unambiguous even though upstream's `torch.remainder` floors
* (remainder(-5, 3) == 1, C gives -2). `_build_layer_multipliers` bounds each multiplier by
* `(2^63-1) // vocab_size`, so a real token's product and any XOR of such products have the sign
* bit clear: `mixed` is in [0, 2^63).
*
* THE EOS RULE COLLAPSES TO TWO COMPARISONS. The reference shifts the token history right with
* `_shift_right_ignore_eos`, built out of a cummax over `where(ids == eos, positions, -1)`, a
* segment start, and `valid = (position_in_segment >= shift) & (p - shift >= 0)`. Expanded,
* `position_in_segment >= s` is exactly "no eos in [p-s, p-1]" -- and wherever the rule would
* substitute eos because `tok[p-s]` is ITSELF an eos, the substituted value is the value already
* there. So the whole construction is:
* The EOS rule collapses to two comparisons. Upstream's `_shift_right_ignore_eos` (a cummax over
* `where(ids == eos, positions, -1)`, a segment start, and
* `valid = (position_in_segment >= shift) & (p - shift >= 0)`) reduces to "no eos in [p-s, p-1]";
* where it would substitute eos because `tok[p-s]` is itself eos, the value is unchanged. So:
*
* t0 = tok[p]
* t1 = p >= 1 ? tok[p-1] : eos
* t2 = (p >= 2 && t1 != eos) ? tok[p-2] : eos
*
* and generally `t[s] = tok[p-s]` unless some earlier shift already fell back to eos, at which
* point every deeper shift is eos too. A serving engine needs no cummax and no segment
* bookkeeping: it needs the `ngram-1` COMMITTED ids in front of the step, and nothing deeper.
* and in general `t[s] = tok[p-s]` until a shift falls back to eos, after which all deeper shifts
* are eos. A serving engine needs only the `ngram-1` committed ids before the step.
*
* ============================== WHERE THOSE IDS COME FROM ====================================
* ============================== Where those ids come from ==============================
*
* They arrive in an INOUT STATE -- a rolling window of `ngram - 1 + n_spec` ids per slot, read at
* `num_accepted - 1`. That is `ple_conv`'s contract, operand for operand, including what the
* window holds afterwards (ref_ple.cpp): with `num_accepted` present the step is a decode step
* whose drafts a verify may reject, and the window is rewritten the way gdn_conv_update rewrites
* its own -- the old ids shifted down by one, then every id of the step -- so a next step that
* kept k of them reads at k - 1 and finds the `ngram - 1` ids ending at the k-th. Absent, every
* id commits and the last `ngram - 1` of them land at offset zero.
* An INOUT state: a rolling window of `ngram - 1 + n_spec` ids per slot, read at
* `num_accepted - 1`, with exactly `ple_conv`'s contract (ref_ple.cpp). With `num_accepted`
* present (a decode step whose drafts may be rejected) the window is rewritten as gdn_conv_update
* does: old ids shifted down by one, then every id of the step, so a next step that kept k reads
* at k - 1. Absent, every id commits and the last `ngram - 1` land at offset zero.
*
* THEY ARE A STATE AND NOT A PLAIN INPUT, even though nothing can invalidate them -- the
* predecessors of the step's first row are always committed, so no rejection reaches them. A plain
* input costs MORE than a state here, on two counts. It has to be filled by something, and nothing
* in the engine derives "the ids before this step": `DeriveInput` carries positions and cu_seqlens
* and no token ids at all, so a plain input means a new core derivation and a widened DeriveFn
* signature to serve one op. And the contract is already paid for by the layer -- the dilated
* convolution downstream carries a 9-timestep window with exactly this contract, so PLE passes
* `num_accepted`, `cache_idx` and `has_init` whether or not this op reads them.
* It is a state rather than a plain input although no rejection can reach the step's predecessors:
* nothing in the engine derives "the ids before this step" (`DeriveInput` carries positions and
* cu_seqlens, no token ids), and the layer's dilated convolution already passes `num_accepted`,
* `cache_idx` and `has_init` under the same contract. RAD_KV_CONV ("per-sequence, a rolling window
* of width-1 + num_spec entries") fits, and `conv_state_index` derives the read cursor.
*
* RAD_KV_CONV is already "per-sequence, a rolling window of width-1 + num_spec entries", which is
* this, and `conv_state_index` already derives the read cursor for it.
*
* THE COLD VALUE IS EOS AND NOT ZERO, which is the one place this differs from a conv window.
* Zero is a real token id, so a slot the manager has not written yet must be filled from `eos`
* explicitly -- `has_init` 0 means exactly that.
* The cold value is eos, not zero (zero is a real token id): `has_init` 0 fills the window with
* `eos`.
*/
#include "ref_common.h"
#include "ref_ops.h"
@@ -76,18 +59,10 @@ using namespace ref;
namespace {
/* THE TWO OPERATIONS TORCH WOULD DO, SPELLED SO THEY CANNOT BE UNDEFINED.
*
* A signed overflow is UB in C++ and wrapping in torch, so the multiply goes through uint64 and
* comes back -- two's complement, which is what an int64 tensor does on every machine this runs
* on. And `torch.remainder` FLOORS where C truncates, so the modulo is written out rather than
* left to `%`.
*
* On a real checkpoint NEITHER of these can fire: `_build_layer_multipliers` bounds every
* multiplier by `(2^63-1) // vocab_size`, so a real token's product has its sign bit clear, an XOR
* of such values has its sign bit clear, and truncating and flooring agree on a non-negative
* dividend. They are here so that a DRAWN case -- a harness index that no vocabulary bounds --
* gets torch's answer rather than a refusal or a platform's. */
/* Torch's int64 multiply and remainder without undefined behaviour: signed overflow is UB in C++
* but wraps in torch, so the multiply goes through uint64; `torch.remainder` floors where C
* truncates. On a real checkpoint neither case arises (see the file header); these give torch's
* answer for drawn test inputs that no vocabulary bounds. */
inline int64_t wrap_mul(int64_t a, int64_t b) {
return (int64_t)((uint64_t)a * (uint64_t)b);
}
@@ -109,20 +84,19 @@ inline int64_t floor_mod(int64_t a, int64_t b) { /* b > 0 */
* vocab_sizes [heads] i64 w
* offsets [heads] i64 w
* cache_idx [n_seq] i32 ? the state slot per sequence
* has_init [n_seq] i32 ? 0 = the window is EOS, not what the slot last held
* num_accepted [n_seq] i32 ? one-based; shifts the READ offset, and its presence
* has_init [n_seq] i32 ? 0 = the window is eos, not what the slot last held
* num_accepted [n_seq] i32 ? one-based; shifts the read offset, and its presence
* makes the write-back the decode layout. Absent reads
* at offset zero and leaves the prefill layout.
* ids [M][heads] i32 out
* ahead_ids [A][heads] i32 ? out: `tok` then holds A more tokens after the step's,
* continuing the LAST sequence, and these are their ids
* continuing the last sequence, and these are their ids
* as the step that runs them will compute them. The
* window is the step's own.
*/
int ref_ngram_ids(const RadArgs* a, RadStream) {
/* TEN POSITIONS AND AN ELEVENTH, four of them optional, so the count is checked and the
* optionals are tested one by one -- `have()` would refuse the op for an operand allowed to be
* absent. */
/* Eleven positions, four optional, so the optionals are tested one by one; `have()` would
* refuse an absent optional operand. */
if (a->n_t < 10) return RAD_E_INVAL;
const RadTensor* tok = t_in(a, 0);
const RadTensor* st = t_in(a, 1);
@@ -139,15 +113,15 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
const int64_t heads = p_int(a, "heads", 0);
if (heads <= 0) return RAD_E_SHAPE;
/* The token vector is the call and the prompt that follows it; `M` is the band. See band_rows
* in ref_common.h. */
/* The token vector holds the call's tokens plus the `ahead` tokens; `M` is the band (see
* band_rows in ref_common.h). */
const int64_t A = ahead ? numel(ahead) / heads : 0;
const int64_t M = band_rows(numel(tok) - A, p_int(a, "M", 0));
const int64_t ngram = p_int(a, "ngram", 0);
const int64_t eos = p_int(a, "eos", -1);
if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* heads are laid out as `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram,
* so the head count has to divide that way or the block a head belongs to is a guess. */
if (M <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* Heads are `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram, so the
* head count must divide evenly. */
if (heads % (ngram - 1)) return RAD_E_SHAPE;
const int64_t per = heads / (ngram - 1);
const int64_t ctx = ngram - 1;
@@ -155,47 +129,45 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE;
if (numel(ids) < M * heads) return RAD_E_SHAPE;
for (int64_t h = 0; h < heads; ++h)
if (ld_int(vsz->dtype, vsz->data, h) <= 0 || ld_int(off_->dtype, off_->data, h) < 0)
return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx;
if (W < ctx) return RAD_E_SHAPE;
/* Every sequence is checked before any state is written: the read window, and the window a
* decode step leaves behind, which is `ctx - 1` ids of history plus every id of the step. */
/* Check every sequence before writing any state: its rows, the read window, and the window a
* decode step leaves (`ctx - 1` ids of history plus every id of the step). */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t o = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0;
if (o < 0) return RAD_E_INVAL;
if (o + ctx > W) return RAD_E_SHAPE;
const int64_t T = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) -
ld_int(cu->dtype, cu->data, offlin(cu, s));
if (nacc && T > 0 && ctx - 1 + T > W) return RAD_E_SHAPE;
const int64_t bos = cu_at(cu, s), eot = cu_at(cu, s + 1);
if (bos < 0 || eot < bos || eot > M) return RAD_E_SHAPE;
if (nacc && eot > bos && ctx - 1 + (eot - bos) > W) return RAD_E_SHAPE;
}
const int64_t ids_ld = rowoff(ids, 1, heads);
const int64_t ahd_ld = ahead ? rowoff(ahead, 1, heads) : 0;
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t eot = ld_int(cu->dtype, cu->data, offlin(cu, s + 1));
if (bos < 0 || eot < bos || eot > M) return RAD_E_SHAPE;
const int64_t T = eot - bos;
const int64_t bos = cu_at(cu, s);
const int64_t T = cu_at(cu, s + 1) - bos;
if (T <= 0) continue;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s;
if (slot < 0) continue;
const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0;
const int64_t o = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0;
/* The `ctx` committed ids in front of this step. A COLD slot's window is EOS and not what
* the slot last held -- and not zero either, which is a real token. Without that a fresh
* sequence landing on a recycled slot hashes the previous sequence's tail into its first
* two rows, which is a wrong lookup in a 320-million-row table and nothing says so. */
/* The `ctx` committed ids before this step. A cold slot's window is eos, not a recycled
* slot's previous contents (and not zero, a real token). */
int64_t prev[8];
for (int64_t i = 0; i < ctx; ++i)
prev[i] = warm ? ld_int(st->dtype, st->data, rowoff(st, slot, W) + o + i) : eos;
/* The history this sequence reads: its `ctx` predecessors, then its own rows. Indexed by
* `p` in [0, ctx + T), so row `t` is history position `ctx + t` and every shift is in
* range without a bounds test in the inner loop. */
/* The sequence's history: `ctx` predecessors, then its own rows. Row `t` is history
* position `ctx + t`, so every shift is in range without a bounds test. */
auto hist = [&](int64_t p) -> int64_t {
return p < ctx ? prev[p] : ld_int(tok->dtype, tok->data, offlin(tok, bos + p - ctx));
};
@@ -205,9 +177,8 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
for (int64_t t = 0; t < reach; ++t) {
const int64_t p = ctx + t;
/* The shifted tokens, with the EOS rule in its collapsed form: once a shift falls back
* to eos every deeper one does too, because `position_in_segment >= s` is monotone in
* s and an eos at `p - s` makes the substituted value the value already there. */
/* The shifted tokens under the collapsed eos rule (file header): once a shift falls
* back to eos, every deeper one does too. */
int64_t sh[8];
sh[0] = hist(p);
bool cut = false;
@@ -217,8 +188,7 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
}
/* One mix per n-gram order, extended in place: the (b+2)-gram's mix is the
* (b+1)-gram's XOR'd with one more term, which is exactly the reference's inner loop
* and saves recomputing the shared prefix. */
* (b+1)-gram's XOR one more term, as in upstream's inner loop. */
int64_t mixed = 0;
int64_t blk = -1;
for (int64_t k = 0; k < ngram; ++k) {
@@ -230,7 +200,6 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
const int64_t h = blk * per + j;
const int64_t v = ld_int(vsz->dtype, vsz->data, h);
const int64_t ofh = ld_int(off_->dtype, off_->data, h);
if (v <= 0 || ofh < 0) return RAD_E_SHAPE;
if (t < T)
st_int(ids->dtype, ids->data, (bos + t) * ids_ld + h,
floor_mod(mixed, v) + ofh);
@@ -241,12 +210,9 @@ int ref_ngram_ids(const RadArgs* a, RadStream) {
}
}
/* The window this step leaves behind, written after every read of it is done. Same rule
* as ple_conv's, said again because the two states sit in the same layer and a reader
* will compare them: a decode step (`num_accepted` present) shifts the old ids down by
* one and appends every id it ran, so the next step's `num_accepted - 1` lands on the
* ids ending at the last one it kept; a step that commits everything leaves its last
* `ctx` ids at offset zero. */
/* Write the window back after all reads, by ple_conv's rule: a decode step (`num_accepted`
* present) shifts the old ids down by one and appends every id it ran; a step that
* commits everything leaves its last `ctx` ids at offset zero. */
const int64_t base = rowoff(st, slot, W);
if (nacc) {
for (int64_t i = 0; i + 1 < ctx; ++i)
+65 -54
View File
@@ -1,58 +1,51 @@
/* ref_ops.h -- the entry points ref_registry.cpp puts in the kernel table, and the layout
* conventions they share.
*
* ============================== SHAPES ARE READ OFF THE OPERANDS ==============================
* ============================== Shapes are read off the operands ==============================
*
* Every extent this plugin loops over comes from a RadTensor's shape, never from the op's
* parameters. That is a deliberate rule and not laziness:
* Every extent this plugin loops over comes from a RadTensor's shape, never from the parameters:
*
* * A RANGED parameter is collapsed to a BAND when the instance is resolved (spec §2.2), and
* `rad_issue` carries the actual value as an integer rather than by rewriting the param list.
* A loop bounded by `M` would therefore run to the band's upper bound -- 8192 rows of a
* single-row decode -- and read off the end of the arena. Ref takes M from the tensor.
* * Everything else the parameters name is either derivable from a shape (head_dim, N, K, n)
* or is genuinely not a shape at all (causal, window, block_size, eps, group, top_k). Ref
* uses the parameter for the second kind and cross-checks it against the shape for the
* first, refusing with RAD_E_SHAPE where a disagreement would mean an out-of-bounds read.
* * A ranged parameter is collapsed to a band when the instance is resolved (spec §2.2), and
* `rad_issue` carries the actual value separately. A loop bounded by `M` would run to the
* band's upper bound (8192 rows for a one-row decode) and read past the arena. Ref takes M
* from the tensor.
* * Other parameters are either derivable from a shape (head_dim, N, K, n) or not shapes at all
* (causal, window, block_size, eps, group, top_k). Ref uses the latter directly and
* cross-checks the former against the shape, refusing with RAD_E_SHAPE where a disagreement
* would read out of bounds.
*
* ============================== THE PAGED KV LAYOUT ==============================
* ============================== The paged KV layout ==============================
*
* This is libr4d's and every kernel in the project has to match it, so it is written here once:
* libr4d's layout, which every kernel must match:
*
* kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]
*
* K first and V second inside a slot: element d of the key is at [..., d] and element d of the
* value at [..., head_dim + d]. A flat slot index s decomposes as block = s / block_size and
* offset = s % block_size, which is what `slot_mapping` carries and what `block_table` indexes
* into. Nothing else in the file is allowed to invent a different one.
* K then V within a slot: key element d at [..., d], value element d at [..., head_dim + d]. A
* flat slot index s is block = s / block_size, offset = s % block_size; `slot_mapping` carries such
* indices and `block_table` maps to blocks.
*
* ============================== THE SPECULATIVE ROLLBACK CONTRACT ==============================
* ============================== The speculative rollback contract ==============================
*
* The linear-attention pair (gdn_conv_update, gdn_recurrent_update) must support rejection
* without recompute (spec §10), and the contract is part of the schema rather than an assumption:
* The linear-attention pair (gdn_conv_update, gdn_recurrent_update) supports rejection without
* recompute (spec §10); the contract is part of the schema:
*
* conv state [n_slots, conv_dim, state_len], state_len >= conv_width - 2 + q_len.
* A step READS its window at offset num_accepted[s] - 1 -- the slot the last
* accepted token left -- and REWRITES the buffer shifted down by one: slots
* 0 .. conv_width-3 take the tail of the old history, and this step's token t
* lands at slot t + conv_width - 2. The invariant that makes it work is that the
* last accepted token of a step always sits at the slot its own index implies, so
* the next step's read offset is the only thing that changes.
* A step reads its window at offset num_accepted[s] - 1 (the slot the last
* accepted token left) and rewrites the buffer shifted down by one: slots
* 0 .. conv_width-3 take the tail of the old history, and this step's token t lands
* at slot t + conv_width - 2. Invariant: a step's last accepted token always sits at
* the slot its index implies, so only the next step's read offset changes.
* linear state [n_slots, n_head_v, head_v, head_k], addressed through state_idx[s, 0..q_len).
* The initial state is read from state_idx[s, num_accepted[s] - 1] and EVERY
* candidate token t writes its own state to state_idx[s, t], because which of them
* survives verification is not known until after this layer has run.
* The initial state is read from state_idx[s, num_accepted[s] - 1], and every
* candidate token t writes its own state to state_idx[s, t], since which survives
* verification is unknown until after this layer.
*
* num_accepted counts the accepted tokens of the PREVIOUS step and is 1-based: 1 means "none of
* the drafts survived, only the token that was already committed". It is a REQUIRED operand on
* both ops -- an op that lets the caller omit it is an op whose rollback contract is optional --
* and a non-speculative decode passes all ones. Ref still reads a null as 1 rather than faulting,
* because a tool calling the launch directly has no declare in front of it to enforce the schema.
* num_accepted counts the previous step's accepted tokens, 1-based: 1 means no draft survived, only
* the committed token. It is a required operand on both ops; a non-speculative decode passes all
* ones. Ref still reads a null as 1, for direct callers with no declare to enforce the schema.
*
* BOTH OPS ALSO TAKE `cu`, and it is required. The two decode kernels run off the one cumulative-
* lengths tensor on the one step; the number of sequences is cu's length minus one and nothing
* else in either argument list carries it. The fast kernels read `cu[n]` before any null test, so
* a schema that omitted it would not make it optional -- it would make the launch fault.
* Both ops also require `cu`: the number of sequences is cu's length minus one and nothing else
* carries it. The fast kernels read `cu[n]` before any null test, so omitting it would fault.
*/
#ifndef RAD_REF_OPS_H
#define RAD_REF_OPS_H
@@ -83,8 +76,10 @@ int ref_pool_rows (const RadArgs*, RadStream);
int ref_relu (const RadArgs*, RadStream);
int ref_clamp (const RadArgs*, RadStream);
int ref_conv2d (const RadArgs*, RadStream);
int ref_conv2d_unfold (const RadArgs*, RadStream);
int ref_conv1d_dw (const RadArgs*, RadStream);
int ref_rel_sinusoid (const RadArgs*, RadStream);
int ref_seg_sinusoid (const RadArgs*, RadStream);
int ref_attn_local_rel (const RadArgs*, RadStream);
int ref_gelu (const RadArgs*, RadStream);
int ref_silu (const RadArgs*, RadStream);
@@ -103,6 +98,7 @@ int ref_softmax (const RadArgs*, RadStream);
/* ---- quantisation and rotation */
int ref_quant_act_i8 (const RadArgs*, RadStream);
int ref_quant_act_i8g (const RadArgs*, RadStream);
int ref_had_quant_act_i8 (const RadArgs*, RadStream);
int ref_quant_act_fp8 (const RadArgs*, RadStream);
int ref_had_quant_act_fp8 (const RadArgs*, RadStream);
@@ -153,6 +149,12 @@ int ref_gelu_tanh(const RadArgs*, RadStream);
int ref_scatter_add_rows(const RadArgs*, RadStream);
int ref_attn_prefix_self(const RadArgs*, RadStream);
int ref_qsa_block_key (const RadArgs*, RadStream);
/* the QSA indexer and DFlash2's convolution (ref_qsa.cpp) */
int ref_qsa_score (const RadArgs*, RadStream);
int ref_qsa_select (const RadArgs*, RadStream);
int ref_qsa_tail_store (const RadArgs*, RadStream);
int ref_qsa_work (const RadArgs*, RadStream);
int ref_dflash_conv (const RadArgs*, RadStream);
/* ---- mixture of experts */
int ref_router_topk (const RadArgs*, RadStream);
@@ -160,6 +162,14 @@ int ref_moe_scatter (const RadArgs*, RadStream);
int ref_moe_gemm (const RadArgs*, RadStream);
int ref_moe_gemm_q (const RadArgs*, RadStream);
int ref_moe_gemm_q_mod4 (const RadArgs*, RadStream);
/* The layout hooks of moe_gemm_q and moe_gemm_q_mod4: a codebook expert's views of several planes
* in the joined form of abi/rad_planes.h, checked against `dtype` (ref_moe.cpp). */
int ref_moe_cb_layout (const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int ref_moe_cb_relayout (const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int ref_moe_cb_unrelayout (const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
int ref_scale_rows (const RadArgs*, RadStream);
int ref_moe_gather (const RadArgs*, RadStream);
int ref_row_topk (const RadArgs*, RadStream);
@@ -198,24 +208,17 @@ int ref_sample_pick (const RadArgs*, RadStream);
int ref_sample_argmax (const RadArgs*, RadStream);
int ref_sample_logprobs (const RadArgs*, RadStream);
/* ============================== OPERAND DESCRIPTION ==============================
/* ============================== Operand description ==============================
*
* `RadKernelInfo::opd_shape` (rad_abi.h): how big is operand i of this op at this geometry, and
* what may legally be in it. libref/ref_shapes.cpp implements one for every entry point above,
* and the NAMING IS PART OF THE MECHANISM rather than a convention: the hook does not receive the
* op name, so a single shared function would have to recover it from a parameter and no op in this
* vocabulary carries its own name as one. Instead ref_registry.cpp's ROW() macro pastes the shape
* hook out of the launch it was already given -- `fn ## _shape` -- so every row gets its
* description without a row being edited, and an op added later that forgets to describe itself
* does not link.
* `RadKernelInfo::opd_shape` (rad_abi.h): the size of operand i at this geometry and what it may
* legally hold. libref/ref_shapes.cpp implements one per entry point above. The naming is
* load-bearing: the hook does not receive the op name, so ref_registry.cpp's ROW() macro pastes
* `fn ## _shape` from the launch function, and an op added without a description fails to link.
*
* The signature is spelled once here because it is the same for every entry point above, and the
* parameter names are what document it: `p`/`n_p` is the resolved parameter list exactly as
* `launch` would receive it, `operand` is the positional index into the op's schema, and the
* answer lands in `out`. RAD_OK, or RAD_E_UNSUPPORTED when the geometry
* does not carry what the description needs -- which a caller SKIPS AND COUNTS rather than
* guessing, because a tool that invents an extent tests the kernel's bounds handling and calls the
* result correctness. */
* `p`/`n_p` is the resolved parameter list as `launch` receives it, `operand` the positional index
* into the op's schema, and the result goes to `out`. Returns RAD_OK, or RAD_E_UNSUPPORTED when the
* geometry lacks what the description needs; callers skip and count those rather than guess, since
* an invented extent tests bounds handling, not correctness. */
#define REF_SHAPE_FN(fn) \
int fn##_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
@@ -240,8 +243,10 @@ REF_SHAPE_FN(ref_pool_rows);
REF_SHAPE_FN(ref_relu);
REF_SHAPE_FN(ref_clamp);
REF_SHAPE_FN(ref_conv2d);
REF_SHAPE_FN(ref_conv2d_unfold);
REF_SHAPE_FN(ref_conv1d_dw);
REF_SHAPE_FN(ref_rel_sinusoid);
REF_SHAPE_FN(ref_seg_sinusoid);
REF_SHAPE_FN(ref_attn_local_rel);
REF_SHAPE_FN(ref_gelu);
REF_SHAPE_FN(ref_silu);
@@ -259,6 +264,7 @@ REF_SHAPE_FN(ref_cast);
REF_SHAPE_FN(ref_softmax);
REF_SHAPE_FN(ref_quant_act_i8);
REF_SHAPE_FN(ref_quant_act_i8g);
REF_SHAPE_FN(ref_had_quant_act_i8);
REF_SHAPE_FN(ref_quant_act_fp8);
REF_SHAPE_FN(ref_had_quant_act_fp8);
@@ -306,6 +312,11 @@ REF_SHAPE_FN(ref_gelu_tanh);
REF_SHAPE_FN(ref_scatter_add_rows);
REF_SHAPE_FN(ref_attn_prefix_self);
REF_SHAPE_FN(ref_qsa_block_key);
REF_SHAPE_FN(ref_qsa_score);
REF_SHAPE_FN(ref_qsa_select);
REF_SHAPE_FN(ref_qsa_tail_store);
REF_SHAPE_FN(ref_qsa_work);
REF_SHAPE_FN(ref_dflash_conv);
REF_SHAPE_FN(ref_router_topk);
REF_SHAPE_FN(ref_moe_scatter);
+235
View File
@@ -0,0 +1,235 @@
/* ref_planes.h -- libref's reading of a weight operand joined over several planes
* (abi/rad_planes.h), and the layout hooks that ask for that form.
*
* A weight declared over several planes of one stored tensor reaches a kernel as one operand: an
* fp8 or int8 lm head's codes and scale, Flash-Next's E4M3 mixing rows with their f32 group
* scales, a zero-point grid's scale and zero. On the host it is stored joined: a header naming each
* plane, then the planes as the container holds them. A launch recognises the form by its header
* and reads the planes by role, so the bytes are the canonical ones and nothing is decoded at
* load.
*
* The hooks join only a selection of several planes; one plane is stored as it is (rad_planes.h
* declines it), so a row with these hooks still reads the plain forms a tool describes (the
* logical f32 head rad-kbench and the op oracle hand over). They refuse with RAD_E_DTYPE a joined
* selection the op does not compute, which keeps the row from being selected for it.
*
* libavx/avx_planes.h states the same rules for libavx; the two must accept the same encodings,
* since a selector may resolve either library for a band.
*/
#ifndef REF_PLANES_H
#define REF_PLANES_H
#include "ref_common.h"
#include "rad_planes.h"
namespace ref {
/* ================================================================== reading at launch */
/* One plane of a joined operand, as its entry describes it. */
struct JPlane {
const uint8_t* p = nullptr;
uint32_t dt = 0;
int64_t rows = 0, cols = 0, row_bytes = 0;
int64_t br = 0, bc = 0; /* logical rows x columns one element covers; 0 is all */
explicit operator bool() const { return p != nullptr; }
float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); }
/* The element of a TILED plane covering logical (r, c). */
float cover(int64_t r, int64_t c) const {
return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0);
}
};
static inline bool is_joined(const RadTensor* t) {
return t && t->data && rad_planes_header(t->data) != nullptr;
}
/* The plane of `t`'s joined form with this role; false when there is none. */
static inline JPlane jplane(const RadTensor* t, const char* role) {
JPlane v;
const RadPlanesEntry* e = nullptr;
const void* d = t && t->data ? rad_planes_find(t->data, role, &e) : nullptr;
if (!d) return v;
v.p = (const uint8_t*)d;
v.dt = e->dtype;
v.rows = e->rows;
v.cols = e->cols;
v.row_bytes = e->row_bytes;
v.br = e->block[0];
v.bc = e->block[1];
return v;
}
static inline int64_t cdiv_or_1(int64_t n, int64_t b) { return b > 0 ? (n + b - 1) / b : 1; }
static inline bool float_scale_dt(uint32_t dt) {
return dt == RAD_BF16 || dt == RAD_F16 || dt == RAD_F32;
}
/* Codes with one scale over [rows, cols], read element by element as the core's affine decoder
* gives it: the code times the scale covering it, one f32 rounding. An E4M3 lm head with a bf16
* scale per 128x128 block, an int8 one per (row, 128 of K), E4M3 rows with an f32 scale per group
* of their own. */
struct ScaledRows {
JPlane codes, scale;
float at(int64_t r, int64_t c) const { return codes.at(r, c) * scale.cover(r, c); }
};
/* RAD_OK and the view, RAD_E_DTYPE for a joined form other than codes and a scale, RAD_E_SHAPE
* for planes that do not cover [rows, cols]. */
static inline int scaled_rows(const RadTensor* t, int64_t rows, int64_t cols, ScaledRows* v) {
const RadPlanesHeader* h = t && t->data ? rad_planes_header(t->data) : nullptr;
if (!h) return RAD_E_INVAL;
v->codes = jplane(t, "codes");
v->scale = jplane(t, "scale");
if (h->n_planes != 2 || !v->codes || !v->scale) return RAD_E_DTYPE;
if ((v->codes.dt != RAD_F8E4M3 && v->codes.dt != RAD_I8) || !float_scale_dt(v->scale.dt) ||
v->codes.br != 1 || v->codes.bc != 1)
return RAD_E_DTYPE;
if (v->codes.rows != rows || v->codes.cols != cols ||
v->scale.rows != cdiv_or_1(rows, v->scale.br) ||
v->scale.cols != cdiv_or_1(cols, v->scale.bc))
return RAD_E_SHAPE;
return RAD_OK;
}
/* ================================================================== the zero-point grids
*
* gemm_nt_q's asymmetric grids (docs/OPS.md): unsigned codes read as (code - zero) * scale, an f16
* scale and an integer zero per (row, `group` of K), joined in `b_scale` from the weight's "scale"
* and "zero" planes; `b` is the codes plane. The activation side is one of three:
*
* ZP_I8_ROW quant_act_i8's codes in the step order, an f32 scale a row and the code sums
* `a_sum` the zero is removed with (w2a8, w4a8_asym)
* ZP_I8_GROUP row-major int8 codes with an f32 scale per (row, 128 of K), as givens_dense_quant
* writes them (w4a8i8_asym, w5a8i8)
* ZP_F16 a 16-bit activation, givens_rotate's (w4a16_asym, w5a16) */
enum ZpAct { ZP_I8_ROW = 0, ZP_I8_GROUP = 1, ZP_F16 = 2 };
struct ZpGrid {
const char* name;
uint32_t codes;
ZpAct act;
};
static inline const ZpGrid* zp_grid(const char* dtype) {
static const ZpGrid kGrids[] = {
{ "w2a8", RAD_U2, ZP_I8_ROW }, { "w4a8_asym", RAD_U4, ZP_I8_ROW },
{ "w4a16_asym", RAD_U4, ZP_F16 }, { "w5a16", RAD_U5, ZP_F16 },
{ "w4a8i8_asym", RAD_U4, ZP_I8_GROUP }, { "w5a8i8", RAD_U5, ZP_I8_GROUP },
};
if (!dtype) return nullptr;
for (const ZpGrid& g : kGrids)
if (std::strcmp(g.name, dtype) == 0) return &g;
return nullptr;
}
/* An unsigned integer zero point a code is compared against: the same width as the codes or
* wider, never signed. */
static inline bool zero_dt(uint32_t dt) {
return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5;
}
/* ================================================================== the layout hooks */
/* The encoding's planes `sel` names, in order: one role per name. */
static inline bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0,
const char* r1) {
if (!enc || !sel || n != 2) return false;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
}
/* Whether `enc` and its selection are codes and one scale, untransformed: what ScaledRows reads. */
static inline bool enc_scaled_rows(const RadEncoding* enc, const int* sel, int n) {
if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return false;
if (!sel_roles(enc, sel, n, "codes", "scale")) return false;
const RadEncPlane& c = enc->plane[sel[0]];
const RadEncPlane& s = enc->plane[sel[1]];
return c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 &&
(c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && s.kind == RAD_PLANE_TILED &&
float_scale_dt(s.dtype);
}
/* The joined form for a weight operand that takes codes and one scale (`rows_opd` and `rows_opd2`
* are the operands that may be one, -1 for none). Every other operand, and a single plane, is
* stored as it is. */
static inline int layout_scaled(int operand, int rows_opd, int rows_opd2, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || (operand != rows_opd && operand != rows_opd2)) return RAD_E_UNSUPPORTED;
if (!enc_scaled_rows(enc, sel, n)) return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
/* logits_gemm and logit_rerank: the head is operand 1 of both. */
static inline int ref_layout_head(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 1, -1, enc, sel, planes, n, out);
}
/* hc_read: mix_down and mix_up (operands 2 and 3). */
static inline int ref_layout_hc(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 2, 3, enc, sel, planes, n, out);
}
/* mtp_enter: fc_h and fc_e (operands 4 and 5). */
static inline int ref_layout_mtp(const RadParam*, int, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, RadLayout* out) {
return layout_scaled(operand, 4, 5, enc, sel, planes, n, out);
}
/* gemm_nt_q: `b_scale` (operand 3) as the scale and zero of the zero-point grid `dtype` names,
* one each per (row, `group` of K), over codes of that grid's width. The codes (operand 2) are one
* plane and stored as they are. A "givens" transform is the activation's (givens_rotate,
* givens_dense_quant), so the planes are read the same way under it. */
static inline int ref_layout_gemm_q(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED;
const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr));
const long long group = rad_param_geti(p, n_p, "group", 0);
if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE;
const RadEncPlane& c = enc->plane[0];
const RadEncPlane& s = enc->plane[sel[0]];
const RadEncPlane& z = enc->plane[sel[1]];
if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes ||
c.block[0] != 1 || c.block[1] != 1)
return RAD_E_DTYPE;
if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group ||
z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group)
return RAD_E_DTYPE;
return rad_planes_layout(enc, sel, planes, n, out);
}
/* RadRelayoutFn and RadUnrelayoutFn for any of the layout hooks above: the hook decides whether
* the planes are joined, and the copies are rad_planes.h's. */
template <RadLayoutFn L>
static int ref_relayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst,
int64_t dst_bytes) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
}
template <RadLayoutFn L>
static int ref_unrelayout_planes(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes,
const RadTensor* planes, int n) {
RadLayout lay{};
const int st = L(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
}
} /* namespace ref */
#endif /* REF_PLANES_H */
+100 -152
View File
@@ -1,42 +1,37 @@
/* ref_ple.cpp -- the gate of Qwen4-Exp's Per-Layer Embedding: everything between the n-gram
* lookup's two projections and the dilated convolution.
*
* ============================== WHAT IT IS ==============================
* ============================== What it is ==============================
*
* PLE mixes a hashed n-gram embedding into the residual stream, and the mixing coefficient is a
* DOT PRODUCT between the embedding and the stream -- one scalar per hyper-connection stream, per
* token. Written out, with `n` the model width and `hc` the number of streams:
* PLE mixes a hashed n-gram embedding into the residual stream with a mixing coefficient that is a
* dot product between the embedding and the stream: one scalar per hyper-connection stream per
* token. With `n` the model width and `hc` the number of streams:
*
* K[c] = grouped_rmsnorm(k)[c] * (w_key[c] + wadd) k is key_proj(embedding)
* Q[c] = grouped_rmsnorm(q)[c] * (w_query[c] + wadd) q is the INCOMING hc stream
* Q[c] = grouped_rmsnorm(q)[c] * (w_query[c] + wadd) q is the incoming hc stream
* s[c] = sum_d K[c][d] * Q[c][d] / sqrt(n)
* s[c] = sign(s[c]) * sqrt(max(|s[c]|, gate_eps)) <- the signed square root
* gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), ONE row
* gv[c] = sigmoid(s[c]) * v v is value_proj(embedding), one row
* gvn = grouped_rmsnorm(gv) * (w_conv + wadd)
*
* and the caller finishes with `out = gv + silu(dilated_conv(gvn))`. BOTH gv AND gvn leave this op
* because the convolution reads the NORMED copy and the residual add reads the UN-normed one --
* two different tensors, and recomputing either outside would be a second definition of the norm.
* and the caller finishes with `out = gv + silu(dilated_conv(gvn))`. Both gv and gvn are outputs:
* the convolution reads the normed copy and the residual add the un-normed one.
*
* ============================== THE SIGNED SQUARE ROOT ==============================
* ============================== The signed square root ==============================
*
* `gate.abs().clamp_min(1e-6).sqrt() * gate.sign()` is not a monotone rescaling of the dot product
* and it is not decoration: it compresses a score whose magnitude spans orders of magnitude into
* something sigmoid can resolve, and it KEEPS THE SIGN, so a stream whose embedding opposes the
* residual gets a gate below a half rather than a gate of zero.
* `gate.abs().clamp_min(1e-6).sqrt() * gate.sign()` compresses a score spanning orders of magnitude
* into a range sigmoid can resolve and keeps the sign, so a stream whose embedding opposes the
* residual gets a gate below a half.
*
* THE CLAMP IS ON THE MAGNITUDE AND THE SIGN IS TAKEN FROM THE ORIGINAL, which matters at exactly
* one value: torch's `sign(0)` is 0, so a dot product of exactly zero comes out as zero and not as
* sqrt(gate_eps). Clamping first and then re-signing the clamped value would give 1e-3 there.
* Zero is not a measure-zero curiosity in a quantised model -- an fp8 activation row can produce
* it -- so the order is written out rather than left to the arithmetic.
* The clamp applies to the magnitude and the sign comes from the original value. torch's `sign(0)`
* is 0, so an exactly-zero dot stays zero rather than becoming sqrt(gate_eps) = 1e-3; an fp8
* activation row can produce exact zero.
*
* ============================== ONE OP AND NOT SIX ==============================
* ============================== One op, not six ==============================
*
* Three grouped norms, a reduction, a scalar nonlinearity and a broadcast multiply would be six
* launches over tensors that are all [M, hc*n] -- 10240 wide at this model's shape. Every launch
* costs a fixed floor and every one of those ops is memory-bound, so the fused form is the only one
* worth writing. `hc_read` is the same argument at the same width.
* memory-bound launches over [M, hc*n] tensors (10240 wide at this model's shape). `hc_read` is
* fused for the same reason.
*/
#include "ref_common.h"
#include "ref_ops.h"
@@ -47,18 +42,8 @@ using namespace ref;
namespace {
/* A value narrowed to a tensor's own dtype and read back -- the same helper ref_hc.cpp carries and
* for the same reason. The reference model's arithmetic is NOT f32 throughout: torch's grouped norm
* returns `.type_as(x)`, so everything downstream of a norm reads a bf16 value. Rounding once, here,
* is what lets a fused kernel match this to a tolerance that means something. */
inline float narrow(uint32_t dtype, float v) {
uint32_t buf[2] = {0, 0};
st_dt(dtype, buf, 0, v);
return ld_dt(dtype, buf, 0);
}
/* One group's reciprocal RMS: the rsqrt is per `n`-wide stream while the gain below it spans all
* hc*n. That asymmetry is the whole of what `group_size` means on Qwen4ExpTextRMSNorm. */
/* One group's reciprocal RMS: the rsqrt is per `n`-wide stream while the gain spans all hc*n
* (what `group_size` means on Qwen4ExpTextRMSNorm). */
inline float group_rsqrt(const RadTensor* x, int64_t base, int64_t stride, int64_t n, float eps) {
double acc = 0;
for (int64_t d = 0; d < n; ++d) {
@@ -72,13 +57,13 @@ inline float group_rsqrt(const RadTensor* x, int64_t base, int64_t stride, int64
/* PLE's gate.
*
* k [M][hc*n] key_proj(embedding), UN-normed
* q [M][hc*n] the incoming hyper-connection stream, UN-normed
* v [M][n] value_proj(embedding) -- ONE row, gated differently per stream
* k [M][hc*n] key_proj(embedding), un-normed
* q [M][hc*n] the incoming hyper-connection stream, un-normed
* v [M][n] value_proj(embedding): one row, gated differently per stream
* w_key [hc*n] w
* w_query [hc*n] w
* w_conv [hc*n] w
* gv [M][hc*n] out, UN-normed: what the residual add reads
* gv [M][hc*n] out, un-normed: what the residual add reads
* gvn [M][hc*n] out, normed: what the convolution reads
*/
int ref_ple_gate(const RadArgs* a, RadStream) {
@@ -95,13 +80,11 @@ int ref_ple_gate(const RadArgs* a, RadStream) {
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
/* `v` is [M, n] and it is the call; `M` is the band. See band_rows in ref_common.h. */
/* Rows come from `v` [M, n]; `M` is the band (see band_rows in ref_common.h). */
const int64_t M = n > 0 ? band_rows(numel(v) / n, p_int(a, "M", 0)) : 0;
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
/* The floor the gate's magnitude is clamped to before the square root. Named rather than
* written into the expression: it is a model constant, and a constant a reader cannot see is
* one a kernel can disagree with in silence. */
/* The floor the gate's magnitude is clamped to before the square root; a model constant. */
const float geps = p_f32(a, "gate_eps", 1e-6f);
if (M <= 0 || n <= 0 || hc <= 0) return RAD_E_SHAPE;
const int64_t hn = hc * n;
@@ -113,49 +96,46 @@ int ref_ple_gate(const RadArgs* a, RadStream) {
const int64_t wks = laststride(wk), wqs = laststride(wq), wcs = laststride(wc);
const int64_t gls = laststride(gv), gnls = laststride(gvn);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * hn * 4)
for (int64_t m = 0; m < M; ++m) {
const int64_t kb = rowoff(k, m, hn), qb = rowoff(q, m, hn), vb = rowoff(v, m, n);
const int64_t gb = rowoff(gv, m, hn), nb = rowoff(gvn, m, hn);
for (int64_t c = 0; c < hc; ++c) {
/* The two normed streams, and the dot between them. Neither is materialised: every
* element is used exactly once here, and at 2560 wide per stream a buffer would be the
* only allocation in the op. */
/* The two normed streams and their dot, not materialised since each element is used
* once. Each norm is rounded to its input's dtype: upstream's grouped norm returns
* `.type_as(x)`. */
const float rk = group_rsqrt(k, kb + c * n * kls, kls, n, eps);
const float rq = group_rsqrt(q, qb + c * n * qls, qls, n, eps);
double dot = 0;
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
const float kk = narrow(k->dtype, ldt(k, kb + j * kls) * rk *
(ldt(wk, j * wks) + wadd));
const float qq = narrow(q->dtype, ldt(q, qb + j * qls) * rq *
(ldt(wq, j * wqs) + wadd));
const float kk = round_dt(k->dtype, ldt(k, kb + j * kls) * rk *
(ldt(wk, j * wks) + wadd));
const float qq = round_dt(q->dtype, ldt(q, qb + j * qls) * rq *
(ldt(wq, j * wqs) + wadd));
dot += (double)kk * (double)qq;
}
float s = (float)(dot / std::sqrt((double)n));
/* THE SIGNED SQUARE ROOT, in the reference's own order: the magnitude is clamped, the
* root is taken, and the SIGN COMES FROM THE ORIGINAL. torch's sign(0) is 0, so a dot
* of exactly zero stays zero instead of becoming sqrt(gate_eps). */
/* Signed square root in upstream's order: clamp the magnitude, take the root, sign
* from the original (sign(0) = 0). */
const float mag = std::sqrt(std::fabs(s) < geps ? geps : std::fabs(s));
s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f);
const float g = act_sigmoid(s);
for (int64_t d = 0; d < n; ++d)
stt(gv, gb + (c * n + d) * gls, narrow(gv->dtype, g * ldt(v, vb + d * vls)));
stt(gv, gb + (c * n + d) * gls, round_dt(gv->dtype, g * ldt(v, vb + d * vls)));
}
/* And the third norm, over what was just written -- READ BACK, not carried in registers,
* because `gv` has been narrowed to its own dtype and the convolution's input is a norm of
* THOSE bytes. A fused kernel that normed the f32 it still held would disagree in the last
* bits -- the same epilogue-fold rule the GDN out-projection follows. */
/* The third norm reads `gv` back after it was narrowed, since the convolution's input is a
* norm of the stored bytes (the GDN out-projection's epilogue-fold rule). */
for (int64_t c = 0; c < hc; ++c) {
const float r = group_rsqrt(gv, gb + c * n * gls, gls, n, eps);
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
stt(gvn, nb + j * gnls,
narrow(gvn->dtype, ldt(gv, gb + j * gls) * r * (ldt(wc, j * wcs) + wadd)));
round_dt(gvn->dtype, ldt(gv, gb + j * gls) * r * (ldt(wc, j * wcs) + wadd)));
}
}
}
@@ -163,65 +143,55 @@ int ref_ple_gate(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ ple_conv */
/* PLE's depthwise convolution: width 4 at DILATION 3, silu AFTER it, and the residual add folded
* in. That is the last piece of the layer -- `out = gv + silu(conv(gvn))`.
/* PLE's depthwise convolution: width 4 at dilation 3, silu after it, and the residual add folded
* in; the layer's last piece, `out = gv + silu(conv(gvn))`.
*
* ============================== THE DILATION IS THE WHOLE DIFFERENCE ==============================
* ============================== Dilation ==============================
*
* A dilated causal convolution reads `width` taps spaced `dilation` apart:
*
* y[t] = silu( sum_j w[c][j] * x[t - (width-1-j)*dilation] )
*
* so at Qwen4-Exp's width 4 and dilation 3 the taps are 9, 6, 3 and 0 timesteps back, and the
* history a sequence has to carry is (width-1)*dilation = NINE, not three. Every off-by-one in a
* convolution cache is a model that generates fluently from a slightly wrong context, so the
* indexing is written once here and mirrors gdn_conv_prep's exactly: state slot `i` holds the
* value at relative position `i - state_len`, and a read at `src < 0` becomes `cs[slot][c][src +
* state_len]`.
* so at Qwen4-Exp's width 4 and dilation 3 the taps are 9, 6, 3 and 0 timesteps back and the
* carried history is (width-1)*dilation = 9, not 3. The indexing mirrors gdn_conv_prep's: state
* slot `i` holds relative position `i - state_len`, and a read at `src < 0` becomes
* `cs[slot][c][src + state_len]`.
*
* The reference reaches the same place by a different route -- it pads by `state_len`, slices the
* last `state_len + seq_len`, and convolves with no padding -- and that pad-and-slice is a no-op
* on a warm cache. What it exists for is the COLD one, where the window in front of the first
* token must be zeros.
* Upstream pads by `state_len`, slices the last `state_len + seq_len` and convolves unpadded; on a
* warm cache that is a no-op, and on a cold one the window before the first token is zeros.
*
* ============================== ONE OP WHERE THE GDN HAS TWO ==============================
* ============================== One op where the GDN has two ==============================
*
* gdn_conv_prep and gdn_conv_update are separate because the work AROUND their convolutions
* differs -- one splits a fused projection and takes an l2 norm, the other does not. PLE's
* convolution is the same arithmetic at prefill and at decode, so it is one op, and it takes the
* union of the two contracts: `has_init` says whether the slot holds a history (prefill's
* question) and `num_accepted` shifts the read offset within a deeper window (decode's).
* gdn_conv_prep and gdn_conv_update differ in the work around the convolution. PLE's convolution is
* the same at prefill and decode, so one op takes both contracts: `has_init` says whether the slot
* holds history, and `num_accepted` shifts the read offset within a deeper window.
*
* `num_accepted` ABSENT MEANS EVERY TOKEN COMMITS, which is what a prefill chunk is: the read is at
* offset zero and nothing this step ran can be rejected. gdn_conv_update makes it required and
* argues that an optional rollback contract is not a contract; the difference here is that this op
* serves prefill too, where there is no previous step to have rejected anything. The state must
* still be sized (width-1)*dilation + n_spec by the manager, and a window too shallow for the
* offset asked for is refused by shape rather than clamped.
* `num_accepted` absent means every token commits (a prefill chunk): the read is at offset zero.
* Unlike gdn_conv_update it is optional because this op also serves prefill. The state must still
* be sized (width-1)*dilation + n_spec, and a window too shallow for the requested offset is
* refused, not clamped.
*
* ============================== WHAT THE WINDOW HOLDS AFTER A STEP ==============================
* ============================== The window after a step ==============================
*
* The next step reads at ITS `num_accepted - 1`, and what that offset must find is the `hist`
* values ending at the last token this step COMMITTED. Which token that is depends on the kind of
* step, so the presence of `num_accepted` picks the layout:
* The next step reads at its `num_accepted - 1` and must find the `hist` values ending at the last
* token this step committed. The presence of `num_accepted` picks the layout:
*
* PRESENT -- a decode step of `slen` tokens, any of which past the first a verify may reject.
* present -- a decode step of `slen` tokens, any past the first rejectable by verify.
* The window is rewritten the way gdn_conv_update rewrites its own: slot i holds position
* i + 1 of (the window this step read ++ this step's inputs), so the old history shifted down
* by one and then token t at slot hist - 1 + t. A next step that kept k of these tokens reads
* at k - 1 and finds the history ending at token k - 1. It needs hist - 1 + slen slots, which
* is the manager's hist + n_spec for a step of 1 + n_spec tokens.
*
* ABSENT -- every token commits, so the next step reads at offset zero (its `num_accepted` is
* 1) and the window is the last `hist` values of the step, there.
* absent -- every token commits, so the next step reads at offset zero (`num_accepted` 1) and
* the window is the step's last `hist` values.
*
* The two agree when the step has one token. Writing the tail at offset zero after a verify of
* several would hand a step that accepted only the first of them a history ending at a rejected
* draft, and one that accepted two a slot nothing wrote.
* The two agree for a one-token step. After a multi-token verify, the absent layout would give a
* step that accepted only the first token a history ending at a rejected draft.
*/
/* THE DEPTHWISE CAUSAL CONVOLUTION AND ITS ROLLING WINDOW, shared by `ple_conv` (dilated, silu,
* an optional residual) and `causal_conv1d` (LFM2's short convolution: undilated, no activation,
* no residual). One body, so the two ops cannot disagree about the window's layout. */
/* The depthwise causal convolution and its rolling window, shared by `ple_conv` (dilated, silu,
* optional residual) and `causal_conv1d` (LFM2's short convolution: undilated, no activation, no
* residual), so the two agree on the window layout. */
struct ConvArgs {
const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y;
bool silu;
@@ -234,13 +204,12 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
const int64_t n = p_int(a, "n", 0);
const int64_t wid = p_int(a, "width", 0);
/* `x` is [M, n] and it is the call; `M` is the band. See band_rows in ref_common.h. */
/* Rows come from `x` [M, n]; `M` is the band (see band_rows in ref_common.h). */
const int64_t M = n > 0 ? band_rows(numel(x) / n, p_int(a, "M", 0)) : 0;
const int64_t dil = p_int(a, "dilation", 1);
if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_SHAPE;
const int64_t hist_len = (wid - 1) * dil;
/* The read window lives in a stack frame. Nine at this model's shape; the bound is stated so a
* caller with a wider one is refused rather than overrunning it. */
/* The read window lives in a stack frame (9 at this model's shape); wider is refused. */
enum { kHistMax = 64 };
if (hist_len > kHistMax) return RAD_E_UNSUPPORTED;
@@ -252,15 +221,13 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len;
if (cs->data && state_len < hist_len) return RAD_E_SHAPE;
/* Checked for every sequence BEFORE any of them is written: a state too shallow for the offset
* asked for, or for the window a decode step leaves behind, is a caller bug whose symptom
* would otherwise be a silently truncated history. */
/* Check every sequence before writing any: a state too shallow for the requested offset or for
* a decode step's resulting window is a caller bug that would silently truncate history. */
for (int64_t s = 0; s < N; ++s) {
const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0;
if (off < 0) return RAD_E_INVAL;
if (off + hist_len > state_len) return RAD_E_SHAPE;
const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) -
ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t slen = cu_at(cu, s + 1) - cu_at(cu, s);
if (nacc && cs->data && hist_len > 0 && slen > 0 && hist_len - 1 + slen > state_len)
return RAD_E_SHAPE;
}
@@ -270,27 +237,31 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
const int64_t rrow = resid ? rowoff(resid, 1, n) : 0;
const int64_t rcol = resid ? laststride(resid) : 0;
const int64_t wrow = rowoff(w, 1, wid), wcol = laststride(w);
/* [n_slots, n, state_len], tight, the layout gdn's conv state already uses. */
const int64_t cs_slot = n * state_len, cs_ch = state_len;
/* [n_slots, n, state_len], as gdn's conv state; a flattened one is read as the tight layout. */
const bool cs3 = cs->rank >= 3;
const int64_t cs_slot = cs3 ? cs->stride[cs->rank - 3] : n * state_len;
const int64_t cs_ch = cs3 ? cs->stride[cs->rank - 2] : state_len;
const int64_t cs_t = cs3 ? cs->stride[cs->rank - 1] : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n * wid)
for (int64_t sc = 0; sc < N * n; ++sc) {
const int64_t s = sc / n, c = sc % n;
const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - bos;
const int64_t bos = cu_at(cu, s);
const int64_t slen = cu_at(cu, s + 1) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s;
if (slot < 0) continue;
/* A zero `has_init` means the slot holds no history: the window in front of the first
* token is ZEROS and not whatever the slot last held. Without it a fresh sequence landing
* on a recycled slot convolves the previous sequence's tail into its first nine tokens --
* fluent output with the wrong prefix. */
/* A zero `has_init` means the slot holds no history: the window before the first token
* is zeros, not a recycled slot's previous contents. */
const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0;
const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0;
const int64_t base = slot * cs_slot + c * cs_ch;
/* Read whole before anything is written back, since a step longer than the window
* overwrites history it still reads. */
float hist[kHistMax];
for (int64_t i = 0; i < hist_len; ++i)
hist[i] = (warm && cs->data) ? ldt(cs, slot * cs_slot + c * cs_ch + off + i) : 0.0f;
hist[i] = (warm && cs->data) ? ldt(cs, base + (off + i) * cs_t) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = 0.0f;
@@ -303,50 +274,27 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvArgs& o) {
const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f;
stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? act_silu(acc) : acc));
}
}
/* The window this step leaves behind, written after every read is done -- a sequence longer
* than the window overwrites history it was still reading otherwise. The layout is the one
* the header describes: shifted by one with every input of the step behind it when
* `num_accepted` is present, the last `hist` values at offset zero when it is not. */
if (cs->data && hist_len > 0) {
#pragma omp parallel for schedule(static)
for (int64_t sc = 0; sc < N * n; ++sc) {
const int64_t s = sc / n, c = sc % n;
const int64_t bos = ld_int(cu->dtype, cu->data, offlin(cu, s));
const int64_t slen = ld_int(cu->dtype, cu->data, offlin(cu, s + 1)) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, s)) : s;
if (slot < 0) continue;
const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, s)) != 0;
const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, s)) - 1 : 0;
const int64_t base = slot * cs_slot + c * cs_ch;
float win[kHistMax];
for (int64_t i = 0; i < hist_len; ++i)
win[i] = warm ? ldt(cs, base + off + i) : 0.0f;
if (nacc) {
for (int64_t i = 0; i + 1 < hist_len; ++i) stt(cs, base + i, win[i + 1]);
for (int64_t t = 0; t < slen; ++t)
stt(cs, base + hist_len - 1 + t, ldt(x, (bos + t) * xrow + c * xcol));
} else {
float keep[kHistMax];
for (int64_t i = 0; i < hist_len; ++i) {
const int64_t src = slen - hist_len + i;
keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: win[src + hist_len];
}
for (int64_t i = 0; i < hist_len; ++i) stt(cs, base + i, keep[i]);
/* The window after the step, in the layout described above ple_conv. */
if (!cs->data || hist_len == 0) continue;
if (nacc) {
for (int64_t i = 0; i + 1 < hist_len; ++i) stt(cs, base + i * cs_t, hist[i + 1]);
for (int64_t t = 0; t < slen; ++t)
stt(cs, base + (hist_len - 1 + t) * cs_t, ldt(x, (bos + t) * xrow + c * xcol));
} else {
float keep[kHistMax];
for (int64_t i = 0; i < hist_len; ++i) {
const int64_t src = slen - hist_len + i;
keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol) : hist[src + hist_len];
}
for (int64_t i = 0; i < hist_len; ++i) stt(cs, base + i * cs_t, keep[i]);
}
}
return RAD_OK;
}
int ref_ple_conv(const RadArgs* a, RadStream) {
/* NINE positions, four of them optional, so the count is checked and the optionals are tested
* one by one -- `have()` would refuse the op for an absent operand that is allowed to be. */
/* Nine positions, four optional; `have()` would refuse an absent optional operand. */
if (a->n_t < 9) return RAD_E_INVAL;
return depthwise_causal_conv(a, { t_in(a, 0), t_in(a, 1), t_in(a, 2), t_in(a, 3), t_in(a, 4),
t_in(a, 5), t_in(a, 6), t_in(a, 7), t_in(a, 8), true });
+356
View File
@@ -0,0 +1,356 @@
/* ref_qsa.cpp -- the QSA indexer's score, selection, tail store and work list, and DFlash2's
* grouped convolution (docs/OPS.md, "Sparse attention (QSA)" and "Draft heads").
*
* None of these is a fusion: an architecture that issues them has no chain to fall back to, so
* without a row here the host backend could not run the model and a device kernel would have no
* oracle. Each follows its libr4d kernel's contract (r4d_qsa_*_bf16.hip,
* r4d_dflash_conv_body.h), including which elements it leaves unwritten and the order of every
* output, with f32 sums in ascending order and no FMA (ref_common.h).
*
* `cu` holds absolute row indices: sequence s owns rows [cu[s], cu[s+1]) of every per-token
* operand, and cu[0] need not be 0.
*/
#include "ref_common.h"
#include "ref_gemm.h" /* row_stride */
#include "ref_ops.h"
#include <algorithm>
#include <vector>
using namespace ref;
namespace {
/* The sequence whose cu span holds row `m`, or `none`. */
int64_t seq_holding(const RadTensor* cu, int64_t n_seq, int64_t m, int64_t none) {
for (int64_t s = 0; s < n_seq; ++s)
if (m >= cu_at(cu, s) && m < cu_at(cu, s + 1)) return s;
return none;
}
/* Offset of entry `i` of a rank-1 operand, or of column 0 of row `i` of a rank-2 one (a state
* index row's committed slot). */
int64_t col0(const RadTensor* t, int64_t i) {
return t->rank >= 2 ? i * t->stride[0] : offlin(t, i);
}
int64_t ldi(const RadTensor* t, int64_t off) { return ld_int(t->dtype, t->data, off); }
/* Whether the trailing dimensions after the first are dense, so a row of a paged store is
* `numel / shape[0]` contiguous values from `row * stride[0]`. */
bool rows_dense(const RadTensor* t) {
int64_t acc = 1;
for (int i = (int)t->rank - 1; i >= 1; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) return false;
acc *= t->shape[i];
}
return true;
}
} /* namespace */
/* ------------------------------------------------------------------ qsa_score */
/* score[m][b] = (sum over heads h of relu(q[m][h] . bk[bt[seq(m)][b]])) / sqrt(n), for b below
* min(nc[seq], the table's width, the score plane's width); a negative page id scores -inf. Each
* dot is an f32 sum over the n lanes in order, the relus are summed over the heads in order.
* Columns past the bound, and rows no sequence of `cu` holds, are not written. */
int ref_qsa_score(const RadArgs* a, RadStream) {
if (!have(a, 6)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *bk = &a->t[1], *bt = &a->t[2], *cu = &a->t[3];
const RadTensor *nc = &a->t[4], *o = &a->t[5];
const int64_t n = p_int(a, "n", 0), heads = p_int(a, "heads", 0);
if (n <= 0 || heads <= 0) return RAD_E_SHAPE;
if (bt->rank != 2 || o->rank != 2 || bk->rank < 2) return RAD_E_SHAPE;
const int64_t M = o->shape[0], nb = std::min(bt->shape[1], o->shape[1]);
const int64_t n_seq = numel(cu) - 1, pages = bk->shape[0];
if (M <= 0 || nb <= 0 || n_seq <= 0 || pages <= 0) return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || numel(nc) < n_seq || rows_of(q, heads * n) < M) return RAD_E_SHAPE;
if (numel(bk) / pages != n) return RAD_E_SHAPE;
if (!rows_dense(bk)) return RAD_E_STRIDE;
const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1];
/* Every page id the loop will read must name a page of `bk`. */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb);
for (int64_t b = 0; b < nbs; ++b)
if (ldi(bt, s * bt_rs + b * bt_cs) >= pages) return RAD_E_INVAL;
}
const int64_t q_rs = row_stride(q, heads * n), q_cs = laststride(q);
const int64_t pg_rs = bk->stride[0], o_rs = o->stride[0], o_cs = o->stride[1];
const float rn = std::sqrt((float)n);
REF_PAR_FOR(M * nb * heads * n)
for (int64_t m = 0; m < M; ++m) {
const int64_t s = seq_holding(cu, n_seq, m, -1);
if (s < 0) continue;
const int64_t nbs = std::min(ldi(nc, offlin(nc, s)), nb);
for (int64_t b = 0; b < nbs; ++b) {
const int64_t pg = ldi(bt, s * bt_rs + b * bt_cs);
if (pg < 0) { stt(o, m * o_rs + b * o_cs, -INFINITY); continue; }
float sum = 0.0f;
for (int64_t h = 0; h < heads; ++h) {
float d = 0.0f;
for (int64_t i = 0; i < n; ++i)
d += ldt(q, m * q_rs + (h * n + i) * q_cs) * ldt(bk, pg * pg_rs + i);
sum += std::fmax(d, 0.0f);
}
stt(o, m * o_rs + b * o_cs, sum / rn);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_select */
/* The page-id table the sparse attention reads (docs/OPS.md): over the query's complete blocks
* n = min(nc[seq], (pos + 1) / ratio, width), the live ones (page id >= 0, score > -1e30) ranked
* by max(score, 0). At most `topk` are taken: all of them when that many or fewer are live, else
* every block above the topk-th largest value in block order, then the blocks equal to it in block
* order until topk are taken. The partial page bt[n] follows when (pos + 1) % ratio != 0 and
* n < width, and -1 pads the row to topk + 1. nsel counts the entries, seqused is
* (nsel - 1) * ratio + pos % ratio + 1 (0 for an empty table). A row no sequence holds reads
* sequence 0, as libr4d's does. */
int ref_qsa_select(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor *sc = &a->t[0], *bt = &a->t[1], *nc = &a->t[2], *po = &a->t[3];
const RadTensor *cu = &a->t[4], *se = &a->t[5], *ns = &a->t[6], *su = &a->t[7];
const int64_t topk = p_int(a, "topk", 0), ratio = p_int(a, "ratio", 0);
if (topk <= 0 || ratio <= 0) return RAD_E_SHAPE;
if (sc->rank != 2 || bt->rank != 2 || se->rank != 2) return RAD_E_SHAPE;
const int64_t M = sc->shape[0], nb = std::min(bt->shape[1], sc->shape[1]);
const int64_t n_seq = numel(cu) - 1;
if (M <= 0 || nb <= 0 || n_seq <= 0) return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || numel(nc) < n_seq) return RAD_E_SHAPE;
if (se->shape[0] < M || se->shape[1] < topk + 1) return RAD_E_SHAPE;
if (numel(ns) < M || numel(po) < M || numel(su) < M) return RAD_E_SHAPE;
for (int64_t s = 0; s < n_seq; ++s)
if (ldi(nc, offlin(nc, s)) < 0) return RAD_E_INVAL;
for (int64_t m = 0; m < M; ++m)
if (ldi(po, offlin(po, m)) < 0) return RAD_E_INVAL;
const int64_t s_rs = sc->stride[0], s_cs = sc->stride[1];
const int64_t bt_rs = bt->stride[0], bt_cs = bt->stride[1];
const int64_t o_rs = se->stride[0], o_cs = se->stride[1];
REF_PAR_FOR(M * nb * 4)
for (int64_t m = 0; m < M; ++m) {
const int64_t s = seq_holding(cu, n_seq, m, 0);
const int64_t p = ldi(po, offlin(po, m));
const int64_t n = std::min(std::min(ldi(nc, offlin(nc, s)), nb), (p + 1) / ratio);
std::vector<float> val((size_t)n);
std::vector<int64_t> live;
for (int64_t b = 0; b < n; ++b) {
const float v = ldt(sc, m * s_rs + b * s_cs);
if (ldi(bt, s * bt_rs + b * bt_cs) < 0 || !(v > -1e30f)) continue;
val[(size_t)b] = v > 0.0f ? v : 0.0f;
live.push_back(b);
}
std::vector<int64_t> take;
if ((int64_t)live.size() <= topk) {
take = live;
} else {
std::vector<float> ord;
for (int64_t b : live) ord.push_back(val[(size_t)b]);
std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), std::greater<float>());
const float thr = ord[(size_t)(topk - 1)];
for (int64_t b : live)
if (val[(size_t)b] > thr) take.push_back(b);
for (int64_t b : live)
if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b);
}
int64_t out = 0;
for (int64_t b : take) st_int(se->dtype, se->data, m * o_rs + (out++) * o_cs,
ldi(bt, s * bt_rs + b * bt_cs));
if (n < nb && (p + 1) % ratio != 0) {
const int64_t part = ldi(bt, s * bt_rs + n * bt_cs);
if (part >= 0) st_int(se->dtype, se->data, m * o_rs + (out++) * o_cs, part);
}
for (int64_t i = out; i <= topk; ++i) st_int(se->dtype, se->data, m * o_rs + i * o_cs, -1);
st_int(ns->dtype, ns->data, offlin(ns, m), out);
st_int(su->dtype, su->data, offlin(su, m), out == 0 ? 0 : (out - 1) * ratio + p % ratio + 1);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_tail_store */
/* state[sidx[s][0]][0][pos[t] % ring] = k[t] for the last `ring` rows of each sequence, rows in
* ascending order (a row whose slot is -1, or that no sequence holds, writes nothing). Every other
* row of `state` keeps its contents. */
int ref_qsa_tail_store(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *po = &a->t[1], *cu = &a->t[2], *st = &a->t[3];
const RadTensor *sx = &a->t[4];
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0);
if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL;
if (k->rank != 2 || st->rank != 4 || st->shape[1] != 1) return RAD_E_SHAPE;
const int64_t T = k->shape[0], slots = st->shape[0], n_seq = numel(cu) - 1;
if (T <= 0 || k->shape[1] != n || st->shape[2] < ring || st->shape[3] != n) return RAD_E_SHAPE;
if (n_seq <= 0 || numel(po) < T) return RAD_E_SHAPE;
if ((sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq) return RAD_E_SHAPE;
/* The rows that write, validated before any write. */
std::vector<std::pair<int64_t, int64_t>> w; /* (row, slot) */
for (int64_t t = 0; t < T; ++t) {
const int64_t s = seq_holding(cu, n_seq, t, -1);
if (s < 0 || t < cu_at(cu, s + 1) - ring) continue;
const int64_t si = ldi(sx, col0(sx, s));
if (si < 0) continue;
if (si >= slots || ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL;
w.push_back({ t, si });
}
for (const auto& [t, si] : w) {
const int64_t row = ldi(po, offlin(po, t)) % ring;
const int64_t db = si * st->stride[0] + row * st->stride[2];
for (int64_t d = 0; d < n; ++d)
stt(st, db + d * st->stride[3], ldt(k, t * k->stride[0] + d * k->stride[1]));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_work */
/* The blocks that complete in this batch, in sequence order and ascending within one: sequence s
* with positions p0 .. p1 completes blocks p0 / ratio .. (p1 + 1) / ratio - 1. Work item w gets its
* block's page bt[s][b] (-1 when the sequence has no tail slot), its first-token position b * ratio
* in bpos (or, with `rope`, three components: a first token in the batch reads its own, an earlier
* one its position plus the shift rope[0][cu[s]] - p0), and, when the slot exists, the block's
* `ratio` raw keys in stage rows w * ratio + i: key q from the batch row cu[s] + q - p0 when q >= p0,
* else from tail row q % ring. Items past the count get page -1 and position 0 and leave `stage`
* alone. nc[s] = (last position + 1) / ratio, 0 for an empty sequence. */
int ref_qsa_work(const RadArgs* a, RadStream) {
if (a->n_t < 11) return RAD_E_INVAL;
const RadTensor *k = t_in(a, 0), *po = t_in(a, 1), *cu = t_in(a, 2), *tl = t_in(a, 3);
const RadTensor *sx = t_in(a, 4), *bt = t_in(a, 5), *rp = t_in(a, 6), *stg = t_in(a, 7);
const RadTensor *pg = t_in(a, 8), *bp = t_in(a, 9), *nc = t_in(a, 10);
if (!k || !po || !cu || !tl || !sx || !bt || !stg || !pg || !bp || !nc) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0), ring = p_int(a, "ring", 0);
if (n <= 0 || ratio <= 0 || ring < ratio) return RAD_E_INVAL;
if (k->rank != 2 || bt->rank != 2 || stg->rank != 2) return RAD_E_SHAPE;
if (tl->rank != 4 || tl->shape[1] != 1 || tl->shape[2] < ring || tl->shape[3] != n)
return RAD_E_SHAPE;
const int64_t T = k->shape[0], n_seq = numel(cu) - 1, slots = tl->shape[0];
if (T <= 0 || n_seq <= 0 || numel(po) < T || k->shape[1] != n || stg->shape[1] != n)
return RAD_E_SHAPE;
if (bt->shape[0] < n_seq || (sx->rank >= 2 ? sx->shape[0] : numel(sx)) < n_seq)
return RAD_E_SHAPE;
const int64_t mw = numel(pg);
if (mw < n_seq || stg->shape[0] < mw * ratio || numel(nc) < n_seq) return RAD_E_SHAPE;
int64_t bstep = 1;
if (bp->rank == 2) {
if (bp->shape[0] < mw || bp->stride[1] != 1 || bp->stride[0] < bp->shape[1] ||
(rp && bp->shape[1] < 3))
return RAD_E_SHAPE;
bstep = bp->stride[0];
} else if (rp || numel(bp) < mw) {
return RAD_E_SHAPE;
}
if (rp && (rp->rank != 2 || rp->shape[0] < 3 || rp->shape[1] < T)) return RAD_E_SHAPE;
for (int64_t t = 0; t < T; ++t)
if (ldi(po, offlin(po, t)) < 0) return RAD_E_INVAL;
/* The work list, validated before any write. */
struct Item { int64_t s, b; };
std::vector<Item> items;
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1);
if (t1 <= t0) continue;
if (t0 < 0 || t1 > T) return RAD_E_SHAPE;
const int64_t p0 = ldi(po, offlin(po, t0)), p1 = ldi(po, offlin(po, t1 - 1));
for (int64_t b = p0 / ratio; b <= (p1 + 1) / ratio - 1; ++b) {
if ((int64_t)items.size() >= mw) break;
if (b >= bt->shape[1]) return RAD_E_SHAPE;
const int64_t si = ldi(sx, col0(sx, s));
if (si >= slots) return RAD_E_INVAL;
for (int64_t i = 0; si >= 0 && i < ratio; ++i) {
const int64_t q = b * ratio + i;
if (q >= p0 && t0 + (q - p0) >= T) return RAD_E_SHAPE;
}
items.push_back({ s, b });
}
}
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t t0 = cu_at(cu, s), t1 = cu_at(cu, s + 1);
st_int(nc->dtype, nc->data, offlin(nc, s),
t1 > t0 ? (ldi(po, offlin(po, t1 - 1)) + 1) / ratio : 0);
}
const int ncomp = rp ? 3 : 1;
auto bpos_at = [&](int64_t w, int c) { return bp->rank == 2 ? w * bstep + c : offlin(bp, w); };
for (int64_t w = 0; w < mw; ++w) {
if (w >= (int64_t)items.size()) {
st_int(pg->dtype, pg->data, offlin(pg, w), -1);
for (int c = 0; c < ncomp; ++c) st_int(bp->dtype, bp->data, bpos_at(w, c), 0);
continue;
}
const int64_t s = items[(size_t)w].s, b = items[(size_t)w].b;
const int64_t t0 = cu_at(cu, s), p0 = ldi(po, offlin(po, t0));
const int64_t si = ldi(sx, col0(sx, s));
st_int(pg->dtype, pg->data, offlin(pg, w),
si < 0 ? -1 : ldi(bt, s * bt->stride[0] + b * bt->stride[1]));
const int64_t f = b * ratio;
if (!rp) {
st_int(bp->dtype, bp->data, bpos_at(w, 0), f);
} else {
const int64_t rs = rp->stride[0], rc = rp->stride[1];
for (int c = 0; c < 3; ++c)
st_int(bp->dtype, bp->data, bpos_at(w, c),
f >= p0 ? ldi(rp, c * rs + (t0 + f - p0) * rc)
: f + (ldi(rp, t0 * rc) - p0));
}
if (si < 0) continue;
for (int64_t i = 0; i < ratio; ++i) {
const int64_t q = f + i;
const RadTensor* src = q >= p0 ? k : tl;
const int64_t sb = q >= p0 ? (t0 + q - p0) * k->stride[0]
: si * tl->stride[0] + (q % ring) * tl->stride[2];
const int64_t sc = q >= p0 ? k->stride[1] : tl->stride[3];
const int64_t db = (w * ratio + i) * stg->stride[0];
for (int64_t d = 0; d < n; ++d)
stt(stg, db + d * stg->stride[1], ldt(src, sb + d * sc));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ dflash_conv */
/* DFlash2's grouped dynamic depthwise convolution over the [T, H] rows of x, blocks of
* `block_size` rows starting at row 0:
*
* out[t][h] = sum over taps j with j == 0 or t % block_size >= j of
* (base[j][h] + delta[t][j][h / group_size]) * x[t - j][h]
*
* in tap order, each term `(base + delta) * x` rounded as written, rounded once to out's dtype.
* `delta` is [T, taps, NG], or [T, >= taps * NG] read at its own row pitch (a slice of the
* [T, 2, taps, NG] coefficient projection). `out` must not alias `x`: tap j reads row t - j. */
int ref_dflash_conv(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *dl = &a->t[1], *bs = &a->t[2], *o = &a->t[3];
const int64_t taps = p_int(a, "taps", 0), group = p_int(a, "group_size", 0);
const int64_t NG = p_int(a, "NG", 0), bsz = p_int(a, "block_size", 0);
if (taps <= 0 || group <= 0 || NG <= 0 || bsz <= 0) return RAD_E_INVAL;
if (x->data == o->data) return RAD_E_INVAL;
if (x->rank != 2 || o->rank != 2) return RAD_E_SHAPE;
const int64_t T = x->shape[0], H = x->shape[1];
if (T <= 0 || o->shape[0] != T || o->shape[1] != H || H != NG * group) return RAD_E_SHAPE;
if (numel(bs) < taps * H) return RAD_E_SHAPE;
int64_t d_rs = 0, d_ts = 0, d_gs = 0;
if (dl->rank == 3) {
if (dl->shape[0] < T || dl->shape[1] < taps || dl->shape[2] < NG) return RAD_E_SHAPE;
d_rs = dl->stride[0]; d_ts = dl->stride[1]; d_gs = dl->stride[2];
} else if (dl->rank == 2) {
if (dl->shape[0] < T || dl->shape[1] < taps * NG) return RAD_E_SHAPE;
d_rs = dl->stride[0]; d_gs = dl->stride[1]; d_ts = NG * d_gs;
} else {
return RAD_E_SHAPE;
}
const int64_t x_rs = x->stride[0], x_cs = x->stride[1];
const int64_t o_rs = o->stride[0], o_cs = o->stride[1];
REF_PAR_FOR(T * H * taps)
for (int64_t t = 0; t < T; ++t)
for (int64_t h = 0; h < H; ++h) {
const int64_t g = h / group;
float acc = 0.0f;
for (int64_t j = 0; j < taps; ++j) {
if (j > 0 && t % bsz < j) continue;
const float c = ldt(bs, rowoff(bs, j, H) + h * laststride(bs)) +
ldt(dl, t * d_rs + j * d_ts + g * d_gs);
const float term = c * ldt(x, (t - j) * x_rs + h * x_cs);
acc = j == 0 ? term : acc + term;
}
stt(o, t * o_rs + h * o_cs, acc);
}
return RAD_OK;
}
+232 -319
View File
@@ -1,59 +1,78 @@
/* ref_quant.cpp -- activation quantisation, the Walsh-Hadamard rotation, and the fused forms.
*
* Activations in this engine are ROTATED INT8, not fp8: several times better error at the same
* width, and the rotation is what makes a single scale per row viable at all (docs/OPS.md).
* ============================== What `group` means ==============================
*
* ============================== WHAT `group` MEANS ==============================
* docs/OPS.md gives these ops one parameter `group` with different meanings; ref fixes them to
* match the fast kernels:
*
* docs/OPS.md gives all five ops one parameter called `group` and it does not mean the same thing
* in all five. Ref fixes the reading, because a fallback that guessed differently from the fast
* kernel would produce plausible wrong numbers:
* quant_act_i8 one scale per row; `group` is the width of the code sums `asum` holds.
* quant_act_i8g contiguous elements sharing one f32 scale, so `scale` is [M, ceil(n/group)].
* dequant the same, inverted: the scale stream's extent gives the group count and
* `group` each group's width.
* had_* the Walsh-Hadamard rotation width (libr4d's `had`); the int8 scale is per row
* and carries the 1/sqrt(group) normalisation, as r4d_had_quant_act_i8 does. A
* rotation block may not cross a tensor-parallel shard, so the width must divide
* the per-rank n.
*
* quant_act_i8 `group` is the number of contiguous elements sharing one f32 scale, so `scale`
* is [M, ceil(n/group)]. group <= 0 or group >= n is one scale per ROW, which is
* what every int8 GEMM in libr4d consumes.
* dequant the same reading, inverted: the scale stream's extent says how many groups
* there are and `group` says how wide each is.
* had_* `group` is the WALSH-HADAMARD ROTATION WIDTH (libr4d calls it `had`) and the
* int8 scale is per ROW, carrying the 1/sqrt(group) normalisation. That is the
* reading docs/OPS.md's own prose forces -- "the rotation (a per-group
* Walsh-Hadamard) is what makes a single scale per row viable" -- and it is what
* r4d_had_quant_act_i8 does. A rotation block may not cross a tensor-parallel
* shard boundary, so the width has to divide the PER-RANK n.
*
* ============================== THE ROTATION ==============================
* ============================== The rotation ==============================
*
* Unnormalised butterflies at ascending strides 1, 2, 4, ... group/2, pairing i with i+h where
* (i & h) == 0 -- the same order and the same pairing as r4d_fwht.h, so the two agree bit for bit
* on the same input. The 1/sqrt(group) is folded into the scale rather than applied to the values,
* again because that is what the fast kernel does: dividing every element by a constant cannot
* change which int8 code it rounds to, and folding it costs nothing.
* (i & h) == 0: the order and pairing of r4d_fwht.h, so the two agree bit for bit. The 1/sqrt(group)
* is folded into the scale, as the fast kernel does; scaling every element by a constant cannot
* change its int8 code here.
*/
#include "ref_common.h"
#include "ref_gemm.h" /* Mat and Scales: gemm_nt_q_gated reads a quantised operand the same way */
#include "ref_gemm.h" /* Mat and Scales, for gemm_nt_q_gated */
#include "ref_ops.h"
using namespace ref;
/* Symmetric int8 everywhere below: q = round(x * 127 / amax), scale = amax / 127, with the store
* rounding to nearest and saturating (ref_common.h). An all-zero row gets scale 0 and codes 0,
* which dequantises back to zero -- the alternative, a tiny epsilon scale, turns a zero row into
* denormal noise in the GEMM that reads it. */
/* ------------------------------------------------------------------ quant_act_i8 */
/* The activation of the w4a8, w8a8 and w2a8 GEMMs, with libr4d's arithmetic: one scale per row,
* max(amax, 1e-8) / 127, and codes x * (1 / scale) rounded to nearest even, stored in the step
* order (i8_step_pos). `asum`, when passed, receives each row's code sums per `group` columns,
* group-major [n/group][Mpad] with Mpad = ceil(M/16)*16 (the asymmetric GEMMs read whole 16-row
* tiles); rows M..Mpad-1 are not written. */
int ref_quant_act_i8(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
/* THE ASUM FORM IS A DIFFERENT CONTRACT, AND THIS DECLINES IT BY NAME. `asum` present selects
* libr4d's asymmetric form, of which the extra output is only the visible half: that kernel
* writes ONE SCALE PER ROW over the whole of `n` -- `group` is the asum grouping width there,
* not the scale granularity -- and it stores `q` in fragment order rather than row-major. Run
* beside it, the symmetric quantiser below compares neither plane against what it means.
*
* The name matters more than the declining. Without it the per-group scale plane this code
* writes is simply wider than the per-row one the caller allocated, the size check refuses,
* and a sweep reports the ENGINE'S operands as the fault -- the production 2-bit draft head's
* quantiser among them. */
if (a->n_t > 3 && a->t[3].data) return RAD_E_UNSUPPORTED;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const RadTensor* as = t_in(a, 3);
const int64_t n = p_int(a, "n", 0);
if (n <= 0 || n % 16) return RAD_E_SHAPE; /* whole steps */
if (q->dtype != RAD_I8) return RAD_E_DTYPE;
if (laststride(q) != 1) return RAD_E_STRIDE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
const int64_t g = as ? p_int(a, "group", 0) : 0;
const int64_t mpad = (rows + 15) / 16 * 16;
if (as && (g <= 0 || n % g || numel(as) < n / g * mpad)) return RAD_E_SHAPE;
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
int8_t* qr = (int8_t*)q->data + rowoff(q, r, n);
float amax = 0.0f;
for (int64_t i = 0; i < n; ++i) amax = std::max(amax, std::fabs(ldt(x, xb + i * xs)));
const float scale = std::max(amax, 1e-8f) / 127.0f;
const float inv = 1.0f / scale;
for (int64_t i = 0; i < n; ++i)
st_dt(RAD_I8, qr, i8_step_pos(i), ldt(x, xb + i * xs) * inv);
stt(s, rowoff(s, r, 1), scale);
for (int64_t gi = 0; as && gi < n / g; ++gi) {
int64_t sum = 0;
for (int64_t i = gi * g; i < (gi + 1) * g; ++i) sum += qr[i8_step_pos(i)];
stt(as, gi * mpad + r, (float)sum);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ quant_act_i8g */
/* quant_act_fp8 at int8 codes, libr4d's arithmetic: per `group` contiguous elements a scale
* amax / 127 (1 for an all-zero group) and codes rounded to nearest even, row-major. What the
* i8a8 GEMMs read. */
int ref_quant_act_i8g(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
@@ -65,27 +84,48 @@ int ref_quant_act_i8(const RadArgs* a, RadStream) {
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
const int64_t xs = laststride(x), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float amax = 0.0f;
for (int64_t i = k0; i < k1; ++i) {
float m = std::fabs(ldt(x, xb + i * xs));
if (m > amax) amax = m;
}
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
for (int64_t i = k0; i < k1; ++i)
st_dt(q->dtype, q->data, qb + i * qs, ldt(x, xb + i * xs) * inv);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
k1 - k0, 127.0f, q, qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
return RAD_OK;
}
/* The rotated forms below are symmetric int8 with one scale per row: q = round(x * 127 / amax),
* scale = amax / 127, the store rounding to nearest and saturating (ref_common.h). An all-zero row
* gets scale 0 and codes 0. */
/* ------------------------------------------------------------------ had_quant_act_i8 */
/* The rotated int8 row of the had_*_i8 ops: `v(i)` for i < n rotated in blocks of `g`, its codes
* stored at q[qb + i * qs] against one scale for the whole row (the amax is over the whole rotated
* row). The rotation is computed twice, for the amax and then for the codes, rather than held.
* Returns the row's scale, amax / 127 / sqrt(g). */
template <class V>
static float had_i8_row(const V& v, int64_t n, int64_t g, const RadTensor* q, int64_t qb,
int64_t qs) {
float buf[REF_HAD_MAX];
float amax = 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
}
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i) st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
}
return amax / 127.0f * (1.0f / std::sqrt((float)g));
}
int ref_had_quant_act_i8(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
@@ -95,47 +135,27 @@ int ref_had_quant_act_i8(const RadArgs* a, RadStream) {
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 8)
for (int64_t r = 0; r < rows; ++r) {
float buf[REF_HAD_MAX];
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
const int64_t xs = laststride(x), qs = laststride(q);
/* amax is over the WHOLE rotated row, because the scale is per row. */
float amax = 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
}
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i)
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
}
stt(s, r * laststride(s), amax / 127.0f * norm);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
stt(s, r * laststride(s), had_i8_row([&](int64_t i) { return ldt(x, xb + i * xs); }, n, g,
q, rowoff(q, r, n), laststride(q)));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */
/* The fused form of rmsnorm + hadamard + quant_act_i8, which is what a w4a8 layer wants where a
* bf16 layer wants a plain rmsnorm (spec §2.3). A plugin asks for this first and emits the three
* unfused ops when it does not resolve; ref resolves it, so the fallback path is one launch.
/* Fused rmsnorm + hadamard + quant_act_i8, what a w4a8 layer uses in place of a plain rmsnorm
* (spec §2.3). A plugin asks for this first and falls back to the three unfused ops.
*
* `residual` PRESENT IS THE fused_add_rms_norm FORM: the add happens first, the sum is written
* back into `residual` (that is what makes it INOUT and what the next layer's shortcut reads), and
* the norm is taken over the sum. The variance comes from the f32 sum and the rotation reads the
* sum back AFTER it has been narrowed to the residual tensor's own dtype, which is what the pair
* of kernels this replaces does -- matching it is what makes the fused form substitutable for
* that pair.
* With `residual` it is the fused_add_rms_norm form: the sum is written back to `residual` (INOUT;
* the next layer's shortcut reads it) and the norm is over the sum. The variance comes from the f32
* sum, but the rotation reads the sum back after narrowing to the residual's dtype, as the unfused
* pair does.
*
* `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer of
* it. Pre-rotation because the rotation is an artefact of the int8 path; a bf16 consumer wants the
* normalised activation, not a Walsh-Hadamard of it. */
* `out_bf16` is the post-norm, pre-rotation tensor for a bf16 consumer; the rotation belongs only
* to the int8 path. */
int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
if (a->n_t < 5) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4];
@@ -152,28 +172,25 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows || numel(w) < n) return RAD_E_SHAPE;
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 8)
for (int64_t r = 0; r < rows; ++r) {
float buf[REF_HAD_MAX];
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
const int64_t xs = laststride(x), qs = laststride(q), ws = laststride(w);
const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w);
/* The residual add, written back before anything reads it, so what follows reads the
* narrowed sum rather than the f32 one. */
/* The variance is taken from the f32 sum as it is written back; everything after reads
* the narrowed sum. */
const int64_t rb = res ? rowoff(res, r, n) : 0;
const int64_t rst = res ? laststride(res) : 1;
if (res)
for (int64_t i = 0; i < n; ++i)
stt(res, rb + i * rst, ldt(x, xb + i * xs) + ldt(res, rb + i * rst));
auto src = [&](int64_t i) {
return res ? ldt(res, rb + i * rst) : ldt(x, xb + i * xs);
};
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { const float v = src(i); ss += v * v; }
for (int64_t i = 0; i < n; ++i) {
const float v = res ? ldt(x, xb + i * xs) + ldt(res, rb + i * rst) : src(i);
if (res) stt(res, rb + i * rst, v);
ss += v * v;
}
const float sc = 1.0f / std::sqrt(ss / (float)n + eps);
if (ob) {
@@ -182,37 +199,20 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
stt(ob, obb + i * obs, src(i) * sc * (ldt(w, i * ws) + wadd));
}
float amax = 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i)
buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
}
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i)
buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i)
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
}
stt(s, r * laststride(s), amax / 127.0f * norm);
auto normed = [&](int64_t i) { return src(i) * sc * (ldt(w, i * ws) + wadd); };
stt(s, r * laststride(s), had_i8_row(normed, n, g, q, rowoff(q, r, n), laststride(q)));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gated_had_quant_i8 */
/* An elementwise gated product, then the rotation and the quantiser. Two of the four rotated sites
* in a w4a8 model have this shape and differ by one multiply, so `act` picks between them:
* silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a gated-attention layer
* (Qwen3_5Attention computes attn_output * sigmoid(gate)). It defaults to silu, which is the form
* docs/OPS.md's `silu_mul` names. `mode` is libr4d's integer spelling of the same choice and is
* accepted where `act` is absent, so a caller written against either name works.
/* An elementwise gated product, then the rotation and the quantiser. Two of a w4a8 model's four
* rotated sites have this shape: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a
* gated-attention layer (Qwen3_5Attention's attn_output * sigmoid(gate)). `act` picks, default silu
* (docs/OPS.md's `silu_mul`); libr4d's integer `mode` is accepted where `act` is absent.
*
* `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], the gate is its first half and the up its second.
* That is vLLM's layout and the one a fused gate_up projection produces, so both readings have to
* exist; two operands with the second optional is the only shape that expresses both. */
* With `b` absent, `a` is the packed [M, 2n] form (gate first half, up second), vLLM's layout and
* what a fused gate_up projection produces. */
int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
if (a->n_t < 4) return RAD_E_INVAL;
const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3];
@@ -229,13 +229,10 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(s) < rows) return RAD_E_SHAPE;
if (numel(ga) < rows * (up ? n : 2 * n)) return RAD_E_SHAPE;
if (up && numel(up) < rows * n) return RAD_E_SHAPE;
const float norm = 1.0f / std::sqrt((float)g);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 8)
for (int64_t r = 0; r < rows; ++r) {
float buf[REF_HAD_MAX];
const int64_t gb = rowoff(ga, r, up ? n : 2 * n), qb = rowoff(q, r, n);
const int64_t gs = laststride(ga), qs = laststride(q);
const int64_t gb = rowoff(ga, r, up ? n : 2 * n), gs = laststride(ga);
const int64_t ub = up ? rowoff(up, r, n) : 0;
const int64_t us = up ? laststride(up) : 0;
auto gated = [&](int64_t i) {
@@ -243,29 +240,14 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
const float x = up ? ldt(up, ub + i * us) : ldt(ga, gb + (n + i) * gs);
return (act == 1 ? act_sigmoid(gate) : act_silu(gate)) * x;
};
float amax = 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
}
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
for (int64_t b = 0; b < n; b += g) {
for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i);
fwht(buf, g);
for (int64_t i = 0; i < g; ++i)
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
}
stt(s, r * laststride(s), amax / 127.0f * norm);
stt(s, r * laststride(s), had_i8_row(gated, n, g, q, rowoff(q, r, n), laststride(q)));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ dequant */
/* q * scale, with the scale stream's own extent deciding how many groups there are. The inverse of
* quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op
* that silently did one would make `dequant(had_quant(x)) == x` look true when the two have
* different meanings. A caller that wants the rotation undone asks for it. */
/* q * scale, the scale stream's extent giving the group count. The inverse of quant_act_i8g only,
* not of the rotated forms: undoing a rotation is a separate Hadamard the caller must request. */
int ref_dequant(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2];
@@ -278,7 +260,7 @@ int ref_dequant(const RadArgs* a, RadStream) {
if (g <= 0) g = (n + ngrp - 1) / ngrp;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t qb = rowoff(q, r, n), yb = rowoff(y, r, n), sb = rowoff(s, r, ngrp);
const int64_t qs = laststride(q), ys = laststride(y), ss = laststride(s);
@@ -293,27 +275,19 @@ int ref_dequant(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------------ quant_act_fp8
*
* The oracle for the block-scaled FP8 family. Without a reference for `quant_act_fp8` the one
* activation format the production checkpoints ship in is the one format rad-kbench cannot
* measure (spec §17).
* The oracle for the block-scaled FP8 family, the activation format the production checkpoints
* use (spec §17). The arithmetic is r4d_quant_act_fp8.hip's, agreeing on three choices:
*
* The arithmetic is r4d_quant_act_fp8.hip's, restated rather than approximated, because the two
* have to agree on three choices that are all defensible and none of which are derivable:
* 448 E4M3's largest finite value; the scale is `amax / 448`, a dequant multiplier like
* the checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales.
* scale 1 for an all-zero group (amax / 448 would have an infinite reciprocal): the GEMM
* multiplies the two block scales, and a zero would erase the weight's.
* the clamp `amax * (1/scale)` is 448 exactly but can round an ulp above once the reciprocal is
* rounded, which would encode as NaN.
*
* 448 E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier,
* the same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold
* multiplies the two scales together and nothing has to be inverted.
* scale 1 for an all-zero group, where `amax / 448` is zero and its reciprocal infinite. NOT
* the zero scale ref_quant_act_i8 uses: that kernel's consumers read a per-row int8
* scale and a zero row is a zero row, while here the GEMM multiplies the two block
* scales and a zero would erase the weight's.
* the clamp is not defensive. `amax * (1/scale)` is 448 in exact arithmetic and can land an ulp
* above it once the reciprocal is rounded, which encodes as a NaN rather than as the
* largest finite.
*
* `M` and `n` are the ROW COUNT and the ROW WIDTH, and rows are dim 0 -- so a rank-3 activation
* ([tokens, heads, width], which is what a GDN block hands its out-projection) is one row per
* token, not one per head. That is the reading the consuming GEMM forces: `n` is its K.
* `M` and `n` are the row count and width with rows along dim 0, so a rank-3 activation
* ([tokens, heads, width], a GDN block's out-projection input) is one row per token: `n` is the
* consuming GEMM's K.
*/
int ref_quant_act_fp8(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
@@ -328,25 +302,14 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) {
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
const int64_t xs = laststride(x), qs = laststride(q);
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float amax = 0.0f;
for (int64_t i = k0; i < k1; ++i) {
const float m = std::fabs(ldt(x, xb + i * xs));
if (m > amax) amax = m;
}
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = k0; i < k1; ++i) {
float v = ldt(x, xb + i * xs) * inv;
if (v > 448.0f) v = 448.0f;
if (v < -448.0f) v = -448.0f;
st_dt(q->dtype, q->data, qb + i * qs, v);
}
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
k1 - k0, 448.0f, q, qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
@@ -354,27 +317,23 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------- had_quant_act_fp8 */
/* The same quantiser with a `group`-wide Hadamard in front of the absmax, which is the only place
* a rotation can go: the whole benefit is that the maximum the grid is scaled by gets smaller.
/* The same quantiser with a `group`-wide Hadamard before the absmax, which lowers the maximum the
* grid is scaled by.
*
* THE sqrt(g) IS NOT UNDONE HERE, and that is a DELIBERATE difference from ref_had_quant_act_i8
* above, which folds 1/sqrt(g) into its own scale. H is symmetric, so
* <Hw, Ha> = g <w, a>, and the residual g has to be divided out exactly once between the two
* sides. The int8 op splits it; this one gives the WHOLE factor to the weight, where dividing a
* bf16 scale by a power of two is an exponent shift and therefore exact. Splitting it would make
* the stored weight scale bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g -- and the codes were
* chosen against amax/7, so that rounding lands as a ~0.2% multiplicative error on every group,
* which is a fifth of the int4 grid's own error bought for nothing.
* Unlike ref_had_quant_act_i8, the sqrt(g) is not undone here. H is symmetric, so
* <Hw, Ha> = g <w, a>, and g must be divided out once between the two sides. This op gives the
* whole factor to the weight, where dividing a bf16 scale by a power of two is exact. Splitting it
* would store bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g against codes chosen for amax/7, a
* ~0.2% error per group (a fifth of the int4 grid's own error).
*
* So this op's output is NOT interchangeable with quant_act_fp8's, and its consumer is not free
* either: only a weight plane stored as w4a8h carries the matching rotation and the matching /g. */
* The output is not interchangeable with quant_act_fp8's: only a weight plane stored as w4a8h
* carries the matching rotation and /g. */
int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
/* n % g != 0 is refused rather than rounded: a rotation block that straddled the end of the
* row would mix real values with padding, and no weight block was rotated that way. */
/* n % g != 0 is refused: no weight block was rotated across the row's end. */
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(x) / n;
@@ -382,7 +341,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n * 8)
for (int64_t r = 0; r < rows; ++r) {
float buf[REF_HAD_MAX];
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
@@ -391,19 +350,8 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
const int64_t k0 = gi * g;
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
fwht(buf, g);
float amax = 0.0f;
for (int64_t i = 0; i < g; ++i) {
const float m = std::fabs(buf[i]);
if (m > amax) amax = m;
}
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = 0; i < g; ++i) {
float v = buf[i] * inv;
if (v > 448.0f) v = 448.0f;
if (v < -448.0f) v = -448.0f;
st_dt(q->dtype, q->data, qb + (k0 + i) * qs, v);
}
const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, 448.0f, q,
qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
@@ -411,20 +359,19 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------- givens_rotate */
/* ParoQuant's activation side: every row scaled by its channel factors and rotated by `stages` rounds of
* disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
* (abi/rad_encoding.h, "givens") meets the activation x . D^-1 . G_1 ... G_S, because
* <v, x D^-1 G_1..G_S> = <w, x> and each G is orthogonal. For a weight whose GEMM reads a 16-bit
* activation (w5a16); the quantising form is givens_dense_quant, over the composed matrices.
/* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages`
* rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
* (abi/rad_encoding.h, "givens") meets x . D^-1 . G_1 ... G_S, since each G is orthogonal and so
* <v, x D^-1 G_1..G_S> = <w, x>. For GEMMs reading a 16-bit activation (w5a16); the quantising
* form is givens_dense_quant.
*
* PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated
* copies, written side by side: y is [rows, parts * n], part p at columns [p*n, (p+1)*n). The tables
* stack the parts: pairs and angle `stages` rows each, scale one row, per part. A part's pairs address
* columns of the row and stay inside one group of `group` (the checkpoint's are within groups of 128).
* Parts: a fused projection (gate|up, q|k|v) was rotated per piece, so y is [rows, parts * n] with
* part p at columns [p*n, (p+1)*n). The tables stack per part: `stages` rows of pairs and angles,
* one row of scales. A part's pairs stay within one `group` (128 in the checkpoints).
*
* The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each
* stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical to the device on the
* angle: cos and sin of an f32 differ by an ulp between libm and the GPU's. */
* The device kernel's arithmetic: divide by the channel scale, then per stage
* a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical: libm's and the GPU's
* cos and sin differ by an ulp. */
int ref_givens_rotate(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4];
@@ -442,7 +389,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
if (c < 0 || c >= n) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * P * n * S)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> buf((size_t)n);
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
@@ -454,7 +401,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
for (int64_t j = 0; j < n / 2; ++j) {
const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j);
const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1);
const float th = ldt(an, a0 + j), c = std::cos(th), sn = std::sin(th);
const float th = ldt(an, a0 + j), c = ref_cos(th), sn = ref_sin(th);
const float va = buf[(size_t)ia], vb = buf[(size_t)ib];
buf[(size_t)ia] = va * c + vb * sn;
buf[(size_t)ib] = vb * c - va * sn;
@@ -466,9 +413,9 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* ParoQuant's activation quantiser: the rotation applied as the dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] over
* each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128]
* matrix a (part, group) -- what rad-convert composes from the givens tables and stores as "t.dense". */
/* ParoQuant's activation quantiser: the rotation as a dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i]
* per (part, 128-column group), then the quantiser named by `q`'s dtype. T is an f16 weight, one
* [128, 128] matrix per (part, group), composed by rad-convert from the givens tables ("t.dense"). */
int ref_givens_dense_quant(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4];
@@ -481,7 +428,7 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n ||
numel(s) < rows * P * ngrp) return RAD_E_SHAPE;
const float qmax = i8 ? 127.0f : 448.0f;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * P * n * g)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
const int64_t xs = laststride(x), qs = laststride(q);
@@ -516,22 +463,17 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) {
/* ---------------------------------------------------------------- the Gram accumulator
*
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or
* a bf16 input as it stands when no scale is passed -- the second moment GPTQ's error feedback
* needs, over exactly the operand the expert GEMM contracts. libr4d's kernel is the device half;
* this is the oracle for it.
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], x being the dequantised E4M3 input (or a bf16
* input as is when no scale is passed): the second moment GPTQ needs, over exactly the operand the
* expert GEMM contracts. Oracle for libr4d's device kernel.
*
* THE ACCUMULATOR IS READ AS WELL AS WRITTEN, which is the one thing a reader coming from every
* other op in this file has to hold: `h` is INOUT, the caller zeroes it once, and each call adds
* its own block. An oracle that stored instead of added would agree with the kernel on a single
* call and disagree on a corpus.
* `h` is INOUT and accumulates: the caller zeroes it once and each call adds its block.
*
* Rows are dequantised once into a scratch plane rather than inside the k2 loop: the triple loop
* is O(n^2 * rows) and a per-element dtype dispatch inside it is the difference between an oracle
* that finishes and one that does not. The accumulation is f64 here and f32 on the device on
* purpose -- an oracle should be tighter than the thing it checks, not bit-identical to it. */
* Rows are dequantised once into a scratch plane, keeping the dtype dispatch out of the
* O(n^2 * rows) loop. Accumulation is deliberately f64 here (f32 on the device): this oracle is
* meant to be tighter than the kernel, not bit-identical. */
int ref_gram_accum(const RadArgs* a, RadStream) {
/* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */
/* `a_scale` is optional; absent, `a` is read as is (the bf16 form). */
if (a->n_t < 3) return RAD_E_INVAL;
const RadTensor *x = t_in(a, 0), *s = t_in(a, 1), *h = t_in(a, 2);
if (!x || !h) return RAD_E_INVAL;
@@ -544,7 +486,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
if (h->rank != 2 || h->shape[0] != n || h->shape[1] != n) return RAD_E_SHAPE;
std::vector<float> xs((size_t)rows * (size_t)n);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
const int64_t xb = rowoff(x, r, n), xst = laststride(x);
const int64_t sb = s ? rowoff(s, r, ngrp) : 0, sst = s ? laststride(s) : 0;
@@ -554,7 +496,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
}
const int64_t hst = laststride(h);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(n * n * rows)
for (int64_t k1 = 0; k1 < n; ++k1) {
const int64_t hb = rowoff(h, k1, n);
for (int64_t k2 = 0; k2 < n; ++k2) {
@@ -571,42 +513,29 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
/* ======================================================================== the fp8 fusions
*
* THREE OPS THAT EXIST SO THAT A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 activation
* quantiser into whichever kernel already has the row in registers, and declares the fused form as
* its own op. Without a host kernel for those names, a host-backend run -- the only thing that
* can answer "is the GRAPH right", because the per-op oracle reads the same graph both sides --
* cannot start on an fp8 model ("site 'host' is unavailable for this band").
* libr4d fuses the fp8 activation quantiser into whichever kernel already has the row in
* registers and declares the fused form as its own op. These host kernels for those names let a
* host-backend run start on an fp8 model; that run is the only check of the graph itself, since the
* per-op oracle reads the same graph on both sides.
*
* These are the unfused arithmetic written out in one pass, which is what a reference is for. They
* are NOT required to be bit-identical to libr4d's kernels the way those kernels are required to be
* bit-identical to the pair they replace: the oracle compares within a tolerance, and a reference
* that chased the device's rounding would stop being a statement of what the op MEANS.
*
* WHAT THEY DO FOLLOW is the bf16 round-trip, because that is meaning and not rounding. The unfused
* pair writes a bf16 intermediate and the quantiser reads those bytes back, so the codes are taken
* over a bf16-narrowed value; a reference that quantised the f32 would be a different function, and
* `out_bf16` -- which the caller may ask for precisely so the fused and unfused forms leave the same
* buffers behind -- would not hold the value the codes were taken over.
* Each is the unfused arithmetic in one pass. They need not be bit-identical to libr4d's kernels;
* the oracle compares within a tolerance. They do follow the bf16 round-trip, which changes the
* function: the unfused pair writes a bf16 intermediate and quantises those bytes, so codes are
* taken over the narrowed value and `out_bf16` holds exactly the value the codes came from.
*/
/* One group-scaled fp8 row, from values already in `v`. The scale layout is quant_act_fp8's and
* the reason for each constant is written there. */
/* One group-scaled fp8 row from the values in `v`; constants and scale layout as quant_act_fp8.
* An int8 `q` (an int8 linear's input, ActFP8::q8_fed) takes quant_act_i8g's codes instead, scale
* amax / 127, as libr4d's fused quantisers write them. */
static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor* q,
const RadTensor* s, int64_t r) {
const int64_t ngrp = (n + g - 1) / g;
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
const float top = q->dtype == RAD_I8 ? 127.0f : 448.0f;
for (int64_t gi = 0; gi < ngrp; ++gi) {
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
float amax = 0.0f;
for (int64_t i = k0; i < k1; ++i) { const float m = std::fabs(v[i]); if (m > amax) amax = m; }
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / sc;
for (int64_t i = k0; i < k1; ++i) {
float c = v[i] * inv;
if (c > 448.0f) c = 448.0f;
if (c < -448.0f) c = -448.0f;
st_dt(q->dtype, q->data, qb + i * qs, c);
}
const float sc = q8_group([&](int64_t i) { return v[k0 + i]; }, k1 - k0, top, q,
qb + k0 * qs, qs);
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
@@ -614,11 +543,10 @@ static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
/* `x`, `residual`:inout?, `w`w -> `q`, `scale`, `out_bf16`?
*
* residual present is the fused_add_rms_norm form, and the add is STORED BEFORE THE VARIANCE READS
* IT -- the sum the norm is taken over is the bf16-narrowed one, not the f32 one. libr4d's kernel
* makes the same choice and says at length why: the pair it replaces writes a bf16 residual and
* reads those bytes back, and half a ULP per channel is the difference between the same text and
* very nearly the same text. `wadd` is added to every gain in f32 for the reason ref_rmsnorm gives.
* With `residual` it is the fused_add_rms_norm form, and the sum is stored before the variance
* reads it, so the norm is over the bf16-narrowed sum (as libr4d's kernel and the unfused pair do).
* Unlike ref_rmsnorm_add, the variance also uses the narrowed sum. `wadd` is added to each gain in
* f32, as in ref_rmsnorm.
*/
int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
if (a->n_t < 5) return RAD_E_INVAL;
@@ -639,7 +567,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> v((size_t)n);
const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w);
@@ -654,8 +582,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
for (int64_t i = 0; i < n; ++i) { const float t = src(i); ss += t * t; }
const float rs = 1.0f / std::sqrt(ss / (float)n + eps);
/* NARROWED TO BF16 AND THEN QUANTISED, and written out where asked. The codes belong to
* the value `out_bf16` holds; taking them over the f32 would make the two disagree. */
/* Narrow to bf16, write `out_bf16` if asked, then quantise those values. */
const int64_t obb = ob ? rowoff(ob, r, n) : 0;
const int64_t obs = ob ? laststride(ob) : 1;
for (int64_t i = 0; i < n; ++i) {
@@ -671,9 +598,8 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------- gated_quant_fp8 */
/* `gate_up` -> `q`, `scale`, `out_bf16`?
*
* The packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's
* input) from sigmoid(gate)*up (a gated attention o_proj's), the same two ref_gated_had_quant_i8
* takes and under the same two names. */
* Packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's input)
* or sigmoid(gate)*up (a gated-attention o_proj's), as in ref_gated_had_quant_i8. */
int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2];
@@ -690,7 +616,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp) return RAD_E_SHAPE;
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(rows * n)
for (int64_t r = 0; r < rows; ++r) {
std::vector<float> v((size_t)n);
const int64_t gb = rowoff(gu, r, 2 * n), gs = laststride(gu);
@@ -699,7 +625,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
for (int64_t i = 0; i < n; ++i) {
const float gt = ldt(gu, gb + i * gs);
const float up = ldt(gu, gb + (n + i) * gs);
const float sg = 1.0f / (1.0f + std::exp(-gt));
const float sg = act_sigmoid(gt);
const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up);
if (ob) stt(ob, obb + i * obs, bf16_to_f32(h));
v[(size_t)i] = bf16_to_f32(h);
@@ -712,32 +638,21 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
/* ------------------------------------------------------------- gemm_nt_q_gated */
/* `a`, `a_scale`, `b`w, `b_scale`w -> `q`, `scale`, `out_bf16`?
*
* gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half
* first -- with gated_quant_fp8's pass in the epilogue, so the [M, N] bf16 tensor between them is
* never written. `act` is REQUIRED here and optional on the quantiser, for the reason docs/OPS.md
* gives: an implementation is free to compile one gate, and an optional parameter would let it
* resolve for another.
* gemm_nt_q over an [N, K] gate_up plane (N the weight's rows, twice the fused width, gate half
* first) with gated_quant_fp8 in the epilogue, so the [M, N] bf16 intermediate is never written.
* `act` is required here, unlike on the quantiser (docs/OPS.md): an implementation may compile one
* gate, and an optional parameter would let it resolve for the other.
*
* BYTE-IDENTICAL TO THE PAIR IT REPLACES, which is a requirement and not a hope -- the libr4d row
* that serves this op makes the same claim, and a fold that is a slightly different function from
* gemm_nt_q followed by gated_quant_fp8 is a different model. Two things earn it here: the product
* comes from `quant_dot`, which is also what gemm_nt_q's plane comes from and is the one place the
* grouping and the scale order are written down; and both halves are narrowed to bf16 BEFORE the
* gate, because the unfused form writes a bf16 [M, N] tensor and gated_quant_fp8 reads those bytes
* back. Taking either half off the f32 accumulator is a different function. ref_test holds both.
* Byte-identical to gemm_nt_q followed by gated_quant_fp8 (ref_test checks it): the product comes
* from `quant_dot` as gemm_nt_q's does, and both halves are narrowed to bf16 before the gate, as the
* unfused pair writes and re-reads a bf16 [M, N] tensor.
*
* A NOTE FOR ANYONE COMPARING THIS AGAINST A DEVICE KERNEL ON THE ENGINE'S OWN OPERANDS. It will
* disagree, completely, and the kernel is not wrong: libr4d stores an fp8a8 weight in WMMA FRAGMENT
* ORDER (r4d.fp8.w.frag64), the same bytes in a different arrangement, and libref reads [N, K]
* row-major. Two readings of one permuted plane are uncorrelated tensors, which shows up as a
* relative error around 1.35 on every operand from element zero. The per-op oracle inverts the
* layout through the row's own RadUnrelayoutFn, back to the encoding's canonical planes, before it
* compares, and says so when a row publishes no inverse; a comparison that skips that step is
* measuring the permutation.
* Comparing against a device kernel on the engine's own operands needs the layout inverted first:
* libr4d stores fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64) while libref reads [N, K]
* row-major, and the two readings are uncorrelated (relative error around 1.35). The per-op oracle
* applies the row's RadUnrelayoutFn before comparing and says so when a row has none.
*
* The product is formed a row at a time rather than all at once. A reference may be slow and may
* not be surprising about memory: [M, N] at a prefill M is hundreds of megabytes for a value the
* op exists to avoid materialising. */
* The product is formed one row at a time; [M, N] at a prefill M would be hundreds of MB. */
int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
if (a->n_t < 6) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5];
@@ -764,19 +679,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
const bool mx = B->dtype == RAD_FP4E2M1;
const Scales SA = make_scales(as_, M, K, false);
const Scales SB = make_scales(bs_, N, K, mx);
const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K);
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * N * K)
for (int64_t m = 0; m < M; ++m) {
std::vector<float> row((size_t)N), v((size_t)n);
for (int64_t j = 0; j < N; ++j) row[(size_t)j] = quant_dot(ma, mb, SA, SB, m, j, K);
const int64_t obb = ob ? rowoff(ob, m, n) : 0;
const int64_t obs = ob ? laststride(ob) : 1;
/* Both halves narrowed to bf16 before the gate; the header says why. */
/* Both halves narrowed to bf16 before the gate (see above). */
for (int64_t i = 0; i < n; ++i) {
const float gt = bf16_to_f32(f32_to_bf16(row[(size_t)i]));
const float up = bf16_to_f32(f32_to_bf16(row[(size_t)(n + i)]));
const float sg = 1.0f / (1.0f + std::exp(-gt));
const float gt = round_dt(RAD_BF16, row[(size_t)i]);
const float up = round_dt(RAD_BF16, row[(size_t)(n + i)]);
const float sg = act_sigmoid(gt);
const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up);
if (ob) stt(ob, obb + i * obs, bf16_to_f32(h));
v[(size_t)i] = bf16_to_f32(h);
@@ -790,19 +705,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`
*
* DFlash2's greedy walk over the candidate lattice. A block-diffusion drafter proposes every
* position of a block in ONE backbone pass, so it cannot condition position l+1 on what it chose at
* l; this puts that dependence back.
* position of a block in one backbone pass, so it cannot condition position l+1 on its choice at
* l; this restores that dependence.
*
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
* pid(0) = anchor[s * anchor_stride] the token the target just committed
* pid(l) = cand[l - 1, chosen(l - 1)] the walk's own previous pick
*
* `hp` ABSENT IS A PLANE OF ONES, which drops the trilinear form to a plain low-rank bigram and is
* DSpark's Markov head rather than a degenerate case.
* `hp` absent is a plane of ones, reducing the trilinear form to a low-rank bigram (DSpark's Markov
* head).
*
* THE WALK IS SERIAL IN l, which is why it is an op and not a GEMM and an argmax: scoring the full
* [steps, K, K] edge tensor computes K times the edges that are ever read, because the predecessor
* is not known until the previous step has been decided. The parallelism here is over sequences. */
* The walk is serial in l, so it is an op rather than a GEMM plus argmax: scoring the full
* [steps, K, K] edge tensor computes K times the edges ever read, since each predecessor is known
* only after the previous step. Parallel over sequences. */
int ref_dflash_select(const RadArgs* a, RadStream) {
if (a->n_t < 7) return RAD_E_INVAL;
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
@@ -813,7 +728,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
const int64_t steps = p_int(a, "steps", 0);
const int64_t K = p_int(a, "top_k", 0);
/* `cand` is [M * steps, K] and it is the call; `M` is the band. See ref_common.h. */
/* Rows come from `cand` [M * steps, K]; `M` is the band (see band_rows in ref_common.h). */
const int64_t M = steps > 0 && K > 0
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
@@ -829,7 +744,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
const int64_t ps = laststride(pred), sxs = laststride(succ);
const int64_t hs = hp ? laststride(hp) : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * steps * K * R)
for (int64_t m = 0; m < M; ++m) {
std::vector<float> ax((size_t)R);
int64_t pid = ld_int(anc->dtype, anc->data, offlin(anc, m * astr));
@@ -837,10 +752,8 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
const int64_t r = m * steps + l;
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
const int64_t hb = hp ? rowoff(hp, r, R) : 0;
/* The half of the form that does not depend on the candidate, computed once and read
* K times -- which is the shape the kernel is built around too. A predecessor outside
* the vocabulary contributes nothing rather than reading past the codebook: at step 0
* it is whatever the target committed, and a padding row's is not a token. */
/* The candidate-independent half of the form, computed once and read K times. A
* predecessor outside the vocabulary (a padding row's anchor) contributes nothing. */
const bool ok = pid >= 0 && pid < nv;
for (int64_t i = 0; i < R; ++i)
ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, pid, R) + i * ps) : 0.0f) *
+418 -282
View File
File diff suppressed because it is too large. Load diff
+134 -195
View File
@@ -1,45 +1,31 @@
/* ref_sample.cpp -- the sampler ops.
*
* Every sampler in this engine is a KERNEL and not a host lift: at a 151K vocab and batch 256 the
* logits are ~77 MiB a step, and moving that across the link to run a host chain costs both the
* bandwidth and a synchronisation, on the step path, at exactly the concurrency the engine exists
* to serve (spec §13). llama.cpp's chain is kept as a host reference in core/sample/, and THIS is
* the second implementation of the same arithmetic -- the two are deliberately independent, so
* that comparing them says something.
* Sampling runs as kernels, not on the host: at a 151K vocab and batch 256 the logits are ~77 MiB
* per step, and copying them for a host chain would cost bandwidth and a synchronisation on the step
* path (spec §13). core/sample/ keeps llama.cpp's chain as a host reference; this is an independent
* second implementation of the same arithmetic, so comparing the two is meaningful.
*
* ============================== EVERY SCALAR IS PER ROW ==============================
* ============================== Every scalar is per row ==============================
*
* `rep`, `freq`, `pres`, `k` and `p` cannot be op PARAMETERS. A parameter is geometry: the selector
* matches constraints against it and freezes it at declare (spec §2.2), so two requests in one
* batch with different top_p would be two different resolutions of one op. A deployment would have
* exactly one top_p, which is not a sampler.
* Sampling scalars (`rep`, `freq`, `pres`, `k`, `p`, `seed`, `pos`) arrive as data, in a `params`
* operand of RadSampleParams rows, one per sampled position, uploaded once per step
* (abi/rad_sample.h). As parameters they would be frozen at declare (see ref_registry.cpp).
*
* So they arrive as DATA, in a `params` operand of RadSampleParams rows -- one per sampled
* position, uploaded once a step (abi/rad_sample.h). That is the schema core/sample/sampler.h
* issues against, and the one every op below reads its scalars from.
* ============================== The candidate set ==============================
*
* `seed` and `pos` are fields of the row for the same reason, rather than two more operands of
* `sample_pick`.
* `sample_topk` produces a fixed-width candidate set and the narrowing stages work in place. A
* dropped candidate is index -1, value -infinity; kept candidates stay in place in descending
* order, so a later stage can stop at the first -1 or skip holes (`sample_pick` skips).
*
* ============================== THE CANDIDATE SET ==============================
* `cand_val` carries logits, not probabilities: each narrowing stage takes its own softmax over the
* set, as llama.cpp does, so stages compose in any order.
*
* `sample_topk` produces a fixed-width candidate set and the narrowing stages work IN PLACE. The
* tensors do not shrink, so a dropped candidate has to be expressible, and the convention is:
* index -1, value -infinity. Kept candidates stay where they are, in descending order, so a later
* stage can stop at the first -1 or skip the holes -- both work, and `sample_pick` skips.
* A row's top_k may be narrower than the buffer (a declare-time bound): top_k 40 in a 1024-wide
* buffer gives 40 candidates and 984 holes.
*
* `cand_val` carries LOGITS, not probabilities. Each narrowing stage takes its own softmax over
* the candidate set, which is what llama.cpp does and what keeps the stages composable in any
* order.
*
* A ROW'S OWN top_k MAY BE NARROWER THAN THE BUFFER. The candidate width is a deployment bound
* chosen at declare; a request asking for top_k 40 out of a 1024-wide buffer gets 40 candidates
* and 984 holes, which every later stage already knows how to skip.
*
* A GREEDY ROW (RAD_SP_GREEDY) HAS NO CANDIDATES. Its token is sample_argmax's, and in a batch
* that mixes greedy and sampled rows every stage runs over every row -- so top-k and the merge
* write it an empty set, the narrowing stages leave it alone, and the pick does not touch its
* token. A pick that ignored the flag would replace the argmax with a draw.
* A greedy row (RAD_SP_GREEDY) has no candidates; its token is sample_argmax's. In a mixed batch
* every stage runs over every row, so top-k and the merge write it an empty set, narrowing leaves it
* alone, and the pick must not overwrite its token with a draw.
*/
#include "ref_common.h"
#include "ref_ops.h"
@@ -54,22 +40,17 @@ using namespace ref;
namespace {
/* The params operand, checked once. A sampler op with no rows to act on is not an error -- it is
* a step in which nothing asked for that stage. */
/* The params operand, checked once. */
struct Rows {
const RadSampleParams* p;
int64_t n;
};
static inline int rows_of(const RadTensor* t, int64_t M, Rows* out) {
static inline int param_rows(const RadTensor* t, int64_t M, Rows* out) {
if (!t || !t->data) return RAD_E_INVAL;
/* The row array is a BYTE BLOB viewed through some 32-bit dtype -- the sampler declares it
* [rows, sizeof(RadSampleParams)/4] u32, which is the only way the builder can express "this
* many bytes a row". So the extent is checked in words, and the dtype is required to be a
* 32-bit one rather than run through rad_dtype_bytes -- not because that is out of reach (it
* is static inline in rad_types.h, and this file could call it), but because "any width, as
* long as the arithmetic works out" is the wrong contract here: the blob is addressed as
* 32-bit words and a 16-bit view of it would pass a byte count and then misread every row. */
/* The row array is a byte blob declared as [rows, sizeof(RadSampleParams)/4] u32, the only way
* the builder can express a per-row byte size. The dtype must be 32-bit: a 16-bit view could
* pass a byte-count check and then misread every row. */
if (t->dtype != RAD_U32 && t->dtype != RAD_I32 && t->dtype != RAD_F32) return RAD_E_DTYPE;
if (numel(t) * 4 < M * (int64_t)sizeof(RadSampleParams)) return RAD_E_SHAPE;
out->p = (const RadSampleParams*)t->data;
@@ -80,11 +61,10 @@ static inline int rows_of(const RadTensor* t, int64_t M, Rows* out) {
} /* namespace */
/* ------------------------------------------------------------------ the history window */
/* The window both history stages read, as the row states it: `hist_off` and `hist_len` address the
* row's OWN row of the history plane, clamped to it, and `last_n` then keeps the TAIL of that span
* -- the last n tokens, not the first, because a window applied at the wrong end penalises what
* the request has already forgotten. last_n 0 turns the stage off for the row (false), a negative
* one keeps the whole span: llama.cpp's meaning for repeat_last_n and dry_penalty_last_n. */
/* The window both history stages read: `hist_off` and `hist_len` address the row's own row of the
* history plane, clamped to it, and `last_n` keeps the tail of that span (the most recent tokens).
* last_n 0 disables the stage for the row (returns false); negative keeps the whole span, as
* llama.cpp's repeat_last_n and dry_penalty_last_n. */
static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_t hmax,
int64_t* ho_out, int64_t* hl_out) {
if (last_n == 0) return false;
@@ -104,16 +84,15 @@ static inline bool hist_window(const RadSampleParams& sp, int32_t last_n, int64_
/* ------------------------------------------------------------------ sample_penalties */
/* llama.cpp's ordering, in one pass over the row's history:
*
* repetition logit = logit > 0 ? logit / rep : logit * rep (once per DISTINCT token)
* repetition logit = logit > 0 ? logit / rep : logit * rep (once per distinct token)
* frequency logit -= count * freq
* presence logit -= pres (once per distinct token)
*
* The repetition penalty being multiplicative and sign-dependent is the part everyone gets wrong:
* dividing a negative logit would make it LARGER, so it is multiplied instead.
* The repetition penalty is sign-dependent: dividing a negative logit would raise it, so it is
* multiplied instead.
*
* The history holds GLOBAL token ids and the logits row is this rank's shard of the vocabulary,
* so a token's column is its id less `vocab_off`, and a token outside the shard is another rank's
* to penalise. */
* History ids are global and the logits row is this rank's vocabulary shard, so a token's column is
* its id less `vocab_off`; tokens outside the shard are other ranks'. */
int ref_sample_penalties(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *hist = &a->t[2];
@@ -122,12 +101,12 @@ int ref_sample_penalties(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
const int64_t hmax = numel(hist) / M;
if (hmax <= 0) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * (n_vocab + hmax))
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_PENALTY)) continue;
@@ -144,8 +123,8 @@ int ref_sample_penalties(const RadArgs* a, RadStream) {
const int64_t tok = ld_int(hist->dtype, hist->data, hb + i * hs);
const int64_t col = tok - voff;
if (tok < 0 || col < 0 || col >= n_vocab) continue;
/* First occurrence only: the penalties are per distinct token, and the count is what
* carries the multiplicity. O(hist^2) and the history is tens of tokens. */
/* First occurrence only: penalties are per distinct token, the count carries the
* multiplicity. O(hist^2) over a short history. */
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
@@ -166,26 +145,22 @@ int ref_sample_penalties(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ sample_dry */
/* DRY -- "don't repeat yourself". A penalty on the token that would EXTEND a suffix of the history
* that has occurred before, which is what stops a model looping on a phrase rather than on a
* token. llama.cpp's rule (llama_sampler_dry_apply):
/* DRY ("don't repeat yourself"): a penalty on a token that would extend a suffix of the history
* that occurred before, to stop phrase-level loops. llama.cpp's rule (llama_sampler_dry_apply):
*
* for every earlier position j, n_j is how long a suffix of the window also ends at j, capped
* at the breaker limit; the token after j would extend that repeat. Each such token is
* penalised ONCE, by multiplier * base^(L - allowed_length), where L is the LONGEST n_j among
* the positions it follows.
* penalised once, by multiplier * base^(L - allowed_length), L the longest n_j among the
* positions it follows.
*
* Only lengths at or above `allowed_length` count, so ordinary repetition of short n-grams is
* untouched, and a token that is itself a whole sequence breaker is never penalised -- it is what
* ends the repetition. Both breaker facts come from the host, which is the side with the
* vocabulary: the row's `dry_rep_limit` (0 for none) and the optional `breakers` plane, one byte
* per history position, nonzero where that position's token is a single-token breaker.
* Only lengths >= `allowed_length` count, and a token that is itself a whole sequence breaker is
* never penalised. Breaker facts come from the host, which has the vocabulary: the row's
* `dry_rep_limit` (0 for none) and the optional `breakers` plane, one byte per history position,
* nonzero for a single-token breaker.
*
* The penalty is multiplier * base^e by repeated multiplication, stopping short of overflow, so
* every implementation of this op computes the same float; llama.cpp clamps the exponent to the
* same end. History ids are GLOBAL and a column is an id less `vocab_off`, as for the penalties.
*
* Written the obvious quadratic way over the window: this is the oracle, not the fast path. */
* The penalty is computed by repeated multiplication, stopping short of overflow, so every
* implementation computes the same float (llama.cpp clamps the exponent likewise). Columns are
* global ids less `vocab_off`. Quadratic over the window. */
static inline float dry_penalty(float multiplier, float base, int64_t e) {
float pen = multiplier;
if (base == 1.0f) return pen;
@@ -206,14 +181,14 @@ int ref_sample_dry(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
const int64_t hmax = numel(hist) / M;
if (hmax <= 0) return RAD_E_SHAPE;
/* The breaker plane is the history's twin, position for position. */
/* The breaker plane matches the history position for position. */
if (brk && numel(brk) < M * hmax) return RAD_E_SHAPE;
const int64_t voff = p_int(a, "vocab_off", 0);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * (n_vocab + hmax * hmax))
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_DRY) || !(sp.dry_multiplier > 0.0f)) continue;
@@ -261,8 +236,7 @@ int ref_sample_dry(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ sample_temp */
/* temp <= 0 leaves the row untouched: greedy decoding is `sample_argmax`, and a temperature of
* zero silently meaning something else is how a sampler chain becomes unreadable. */
/* temp <= 0 leaves the row untouched; greedy decoding is `sample_argmax`. */
int ref_sample_temp(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1];
@@ -271,9 +245,9 @@ int ref_sample_temp(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_vocab)
for (int64_t m = 0; m < M; ++m) {
const float t = R.p[m].temp;
if (!(t > 0.0f) || t == 1.0f) continue;
@@ -293,25 +267,22 @@ int ref_sample_topk(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
/* The candidate WIDTH is the buffer's, not the request's: it is the deployment bound the
* arena was sized for, and every later stage reads it. */
RAD_REF_TRY(param_rows(pr, M, &R));
/* The candidate width is the buffer's (the declare-time bound), not the request's. */
const int64_t n_cand = ci->rank >= 2 ? ci->shape[ci->rank - 1] : numel(ci) / M;
if (n_cand <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
/* THE VOCAB-PARALLEL PAIR PLANE, optional. cand_idx stays LOCAL -- it indexes this rank's
* logits row and every stage after top-k reads it that way -- and `pairs` carries the same
* candidates with `vocab_off` added, as (u32 GLOBAL id, f32 logit), which is what the
* all-gather moves and what sample_merge_topk reads. Absent, and this is the single-rank
* top-k unchanged. */
/* Optional vocab-parallel pair plane. cand_idx stays local (it indexes this rank's logits
* row); `pairs` carries the same candidates as (u32 global id, f32 logit) with `vocab_off`
* added, for the all-gather and sample_merge_topk. */
const RadTensor* pp = a->n_t > 4 && a->t[4].data ? &a->t[4] : nullptr;
const int64_t voff = p_int(a, "vocab_off", 0);
if (pp && numel(pp) < M * 2 * n_cand) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_vocab * 4)
for (int64_t m = 0; m < M; ++m) {
/* A row's own top_k, clamped to the buffer. 0 or negative means "the whole candidate
* width", which is what a request that set no top_k asks for. A greedy row takes none. */
/* The row's top_k, clamped to the buffer; <= 0 means the whole width. A greedy row takes
* none. */
int64_t k = R.p[m].top_k;
if (k <= 0 || k > n_cand) k = n_cand;
if (R.p[m].flags & RAD_SP_GREEDY) k = 0;
@@ -327,8 +298,7 @@ int ref_sample_topk(const RadArgs* a, RadStream) {
st_int(ci->dtype, ci->data, ib + r * is, ok ? pi : -1);
stt(cv, vb + r * vs, ok ? pv : -INFINITY);
if (!pp) continue;
/* 0xffffffff is the hole, which the merge tests as a negative signed id -- the same
* convention cand_idx carries as -1. */
/* 0xffffffff is the hole (a negative signed id to the merge, -1 in cand_idx). */
uint32_t bits;
const float val = ok ? pv : -INFINITY;
std::memcpy(&bits, &val, 4);
@@ -353,9 +323,9 @@ static int narrow(const RadArgs* a, Narrow which) {
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_cand * 4)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (sp.flags & RAD_SP_GREEDY) continue;
@@ -378,9 +348,8 @@ static int narrow(const RadArgs* a, Narrow which) {
if (which == NR_MINP) {
const float p = sp.min_p;
if (!(p > 0.0f)) continue;
/* Keep everything within a factor p of the most likely candidate. Comparing
* exp(v - max) against p is the same test as prob >= p * max_prob without forming the
* normaliser, which is one fewer pass and one fewer rounding. */
/* Keep everything within a factor p of the most likely candidate: exp(v - max) >= p
* is prob >= p * max_prob without forming the normaliser. */
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float v = ldt(cv, vb + i * vs);
@@ -390,7 +359,7 @@ static int narrow(const RadArgs* a, Narrow which) {
continue;
}
/* The remaining three all need the normalised probabilities. */
/* The other three stages need normalised probabilities. */
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) sum += ref_exp(ldt(cv, vb + i * vs) - mx);
@@ -399,19 +368,15 @@ static int narrow(const RadArgs* a, Narrow which) {
if (which == NR_TOPP) {
const float p = sp.top_p;
if (!(p < 1.0f) || !(p > 0.0f)) continue;
/* The candidates arrive in DESCENDING order from sample_topk and this op does not
* re-sort them. Keep the shortest prefix whose cumulative probability reaches p, and
* always keep at least one -- a p small enough to select nothing still has to produce
* a token. */
/* Candidates arrive in descending order from sample_topk and are not re-sorted. Keep
* the shortest prefix whose cumulative probability reaches p, at least one. */
float cum = 0.0f;
bool done = false;
int64_t kept = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (done) { drop(i); continue; }
cum += ref_exp(ldt(cv, vb + i * vs) - mx) * inv;
++kept;
if (cum >= p && kept >= 1) done = true;
if (cum >= p) done = true;
}
continue;
}
@@ -420,51 +385,42 @@ static int narrow(const RadArgs* a, Narrow which) {
const float p = sp.typical_p;
if (!(p < 1.0f) || !(p > 0.0f)) continue;
/* Locally typical sampling: keep the candidates whose surprisal -log(prob) is closest
* to the distribution's entropy, until their mass reaches p. The candidate order is
* by probability and this order is by |surprisal - H|, so the two disagree and the
* selection is a threshold on the distance rather than a prefix.
*
* Two passes and no sort: find the distance at which the mass reaches p, then keep
* everything at or below it. Ties are kept, which can overshoot p slightly -- the
* alternative is an order that depends on the candidate index. */
* to the entropy until their mass reaches p. That order differs from the candidate
* order, so this is a threshold on |surprisal - H| rather than a prefix: find the
* smallest distance whose mass reaches p, keep everything at or below it. Ties are
* kept (may overshoot p) so the result does not depend on candidate index. */
/* q[i] is a live candidate's probability (0 for a dropped one), d[i] its distance. */
std::vector<float> q((size_t)n_cand, 0.0f), d((size_t)n_cand, 0.0f);
float H = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv;
if (q > 0.0f) H -= q * ref_log(q);
q[(size_t)i] = ref_exp(ldt(cv, vb + i * vs) - mx) * inv;
if (q[(size_t)i] > 0.0f) H -= q[(size_t)i] * ref_log(q[(size_t)i]);
}
/* The smallest distance threshold whose mass reaches p, found by scanning the
* distances that actually occur. n_cand is a thousand at most. */
for (int64_t i = 0; i < n_cand; ++i)
if (q[(size_t)i] > 0.0f) d[(size_t)i] = ref_abs(-ref_log(q[(size_t)i]) - H);
/* Scan the distances that occur (n_cand is at most about a thousand). */
float cut = 0.0f;
bool have_cut = false;
for (int64_t c = 0; c < n_cand; ++c) {
if (!live(c)) continue;
const float qc = ref_exp(ldt(cv, vb + c * vs) - mx) * inv;
if (!(qc > 0.0f)) continue;
const float dc = ref_abs(-ref_log(qc) - H);
if (!(q[(size_t)c] > 0.0f)) continue;
float mass = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv;
if (!(q > 0.0f)) continue;
if (ref_abs(-ref_log(q) - H) <= dc) mass += q;
for (int64_t i = 0; i < n_cand; ++i)
if (q[(size_t)i] > 0.0f && d[(size_t)i] <= d[(size_t)c]) mass += q[(size_t)i];
if (mass >= p && (!have_cut || d[(size_t)c] < cut)) {
cut = d[(size_t)c];
have_cut = true;
}
if (mass >= p && (!have_cut || dc < cut)) { cut = dc; have_cut = true; }
}
if (!have_cut) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float q = ref_exp(ldt(cv, vb + i * vs) - mx) * inv;
if (!(q > 0.0f) || ref_abs(-ref_log(q) - H) > cut) drop(i);
}
for (int64_t i = 0; i < n_cand; ++i)
if (live(i) && (!(q[(size_t)i] > 0.0f) || d[(size_t)i] > cut)) drop(i);
continue;
}
/* XTC -- "exclude top choices". With probability `xtc_probability`, DROP every candidate
* above `xtc_threshold` except the least likely of them, which is the opposite of every
* other stage here and is the point: it removes the obvious continuations and leaves the
* interesting one. The draw is per row and comes from the row's own stream, so it
* reproduces. */
/* XTC ("exclude top choices"): with probability `xtc_probability`, drop every candidate
* above `xtc_threshold` except the least likely of them, removing the obvious
* continuations. The draw comes from the row's own stream, so it reproduces. */
{
if (!(sp.xtc_probability > 0.0f) || !(sp.xtc_threshold > 0.0f)) continue;
if (rad_sample_uniform01(sp.seed ^ RAD_SAMPLE_KEY_XTC, sp.pos) >= sp.xtc_probability)
@@ -477,8 +433,7 @@ static int narrow(const RadArgs* a, Narrow which) {
++n_above;
}
}
/* Nothing to do unless at least two candidates clear the threshold: dropping the only
* one would leave the row without its own choice. */
/* Needs at least two candidates above the threshold. */
if (n_above < 2) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i) || i == last_above) continue;
@@ -497,15 +452,12 @@ int ref_sample_typical(const RadArgs* a, RadStream) { return narrow(a, NR_TYPICA
int ref_sample_xtc(const RadArgs* a, RadStream) { return narrow(a, NR_XTC); }
/* ------------------------------------------------------------------ sample_mask */
/* Where a GBNF grammar lands. The state machine stays on host and what crosses is a token bitmask
* per sequence -- 19 KiB at a 151K vocab, cheap enough to upload every step (spec §13).
/* GBNF grammar masking. The state machine stays on the host; a token bitmask per sequence (19 KiB
* at a 151K vocab) is uploaded every step (spec §13).
*
* A SET BIT MEANS ALLOWED. That polarity has to be stated: a grammar produces a set of admissible
* tokens, and the mask is that set rather than its complement. Word w bit b covers token
* 32*w + b, least significant bit first.
* A set bit means allowed. Word w bit b covers token 32*w + b, least significant bit first.
*
* The row says WHICH mask row it uses, because a constrained sequence and an unconstrained one
* share the plane and `mask_row` is -1 for the second. */
* Each row names its mask row; unconstrained rows share the plane with `mask_row` -1. */
int ref_sample_mask(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *bm = &a->t[2];
@@ -514,12 +466,12 @@ int ref_sample_mask(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
const int64_t words = (n_vocab + 31) / 32;
const int64_t mask_rows = numel(bm) / (words > 0 ? words : 1);
if (mask_rows <= 0) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_vocab)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_MASK)) continue;
@@ -544,9 +496,9 @@ int ref_sample_pick(const RadArgs* a, RadStream) {
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand || numel(tok) < M) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_cand * 4)
for (int64_t m = 0; m < M; ++m) {
/* A greedy row's token is the argmax's, already written. */
if (R.p[m].flags & RAD_SP_GREEDY) continue;
@@ -569,14 +521,10 @@ int ref_sample_pick(const RadArgs* a, RadStream) {
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
const float u = rad_sample_uniform01(R.p[m].seed ^ RAD_SAMPLE_KEY_PICK, R.p[m].pos);
/* The inverse CDF, walked in candidate order, accumulating in f32. The fallback is the
* last candidate whose logit is ABOVE -infinity: `u` is strictly below 1 and the
* probabilities sum to 1 in exact arithmetic, but they do not in f32, and a draw that
* falls through the last comparison must still produce a token -- one the distribution
* allows. top-k fills its width from a masked row, so the grammar's forbidden tokens sit
* at the tail of the set at -infinity, and falling through to one of them emits a token
* the grammar ruled out. Such a candidate adds nothing to `cum`, so the comparison never
* chooses one either. */
/* Inverse CDF in candidate order, accumulating in f32. The f32 probabilities may sum to
* less than u < 1, so a draw that falls through takes the last candidate above
* -infinity. Grammar-masked tokens sit at the set's tail at -infinity; they add nothing to
* `cum` and must never be the fallback. */
float cum = 0.0f;
int64_t chosen = -1, last = -1;
for (int64_t i = 0; i < n_cand; ++i) {
@@ -593,8 +541,7 @@ int ref_sample_pick(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ sample_argmax */
/* Greedy, ties to the LOWER token id -- the same tie rule the top-k selection uses, so a greedy
* step and a top-1 step cannot disagree. */
/* Greedy, ties to the lower token id, as in top-k selection, so greedy and top-1 agree. */
int ref_sample_argmax(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *tok = &a->t[2];
@@ -603,7 +550,7 @@ int ref_sample_argmax(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_vocab;
if (M <= 0 || numel(tok) < M) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_vocab)
for (int64_t m = 0; m < M; ++m) {
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
float best = -INFINITY;
@@ -618,13 +565,12 @@ int ref_sample_argmax(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ sample_logprobs */
/* THE RAW DISTRIBUTION'S SUMMARY, for a row that asks for logprobs (RAD_SP_LOGPROBS): the row's
* maximum, the sum of exp(l - max) over it, and its k largest as (id, logit) pairs, descending,
* ties to the lower id, ids as floats (exact below 2^24). Read off the logits before any sampling
* stage has touched them, which is the distribution OpenAI's and llama-server's logprobs report.
* A row without the flag is not written. Under a split vocabulary the ids are global
* (+ `vocab_off`) and the host merges the ranks' summaries; a slot past the row's width is id -1,
* logit -infinity. The sum is taken in double here: this is the oracle. */
/* A summary of the raw distribution for rows with RAD_SP_LOGPROBS: the max, the sum of
* exp(l - max), and the k largest as (id, logit) pairs, descending, ties to the lower id, ids as
* floats (exact below 2^24). Read before any sampling stage, as OpenAI's and llama-server's
* logprobs report. Rows without the flag are not written. Under a split vocabulary ids are global
* (+ `vocab_off`) and the host merges ranks; an unfilled slot is id -1, logit -infinity. The sum is
* in double. */
int ref_sample_logprobs(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *st = &a->t[2];
@@ -636,9 +582,9 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) {
const int64_t w = 2 + 2 * k;
if (M <= 0 || numel(st) < M * w) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
RAD_REF_TRY(param_rows(pr, M, &R));
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_vocab * (k + 2))
for (int64_t m = 0; m < M; ++m) {
if (!(R.p[m].flags & RAD_SP_LOGPROBS)) continue;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
@@ -670,15 +616,13 @@ int ref_sample_logprobs(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ sample_merge_topk */
/* THE VOCAB-PARALLEL MERGE. lm_head is vocab-sharded, so each rank runs top-k over ITS OWN shard
* and the candidate sets are all-gathered -- k * world_size pairs, 2 KiB at k=64 and world_size=4,
* against the ~77 MiB a full-logits gather would move (spec §9, §13).
/* The vocab-parallel merge. lm_head is vocab-sharded, so each rank runs top-k over its shard and
* the candidate sets are all-gathered: k * world_size pairs, 2 KiB at k=64 and world_size=4, versus
* ~77 MiB for a full-logits gather (spec §9, §13).
*
* `gathered` is [M, world_size * n_cand] pairs of (token id, logit) as raw u32 words: the token id
* is already GLOBAL, because each rank adds its own vocab offset before the gather -- a merge that
* had to know the offsets would need the shard layout, which is the caller's business and not a
* kernel's. The output is the same descending candidate set the single-rank path produces, so
* every stage after it is identical. */
* `gathered` is [M, world_size * n_cand] (token id, logit) pairs as raw u32 words, ids already
* global. The output is the single-rank path's descending candidate set, so later stages are
* unchanged. */
int ref_sample_merge_topk(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *gt = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3];
@@ -687,11 +631,9 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) {
const int64_t M = numel(ci) / n_cand;
if (M <= 0 || numel(cv) < M * n_cand) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
/* Each gathered entry is a (u32 id, f32 logit) PAIR IN ONE BUFFER, so the two halves have
* different types and the buffer's dtype can only be one of them. It is u32, and the logit is
* read by BIT PATTERN: `ldt` on a u32 buffer would convert 0x40800000 to 1.08e9 rather than
* to 4.0. A word-typed buffer is the only way the builder can express a packed pair. */
RAD_REF_TRY(param_rows(pr, M, &R));
/* Each entry packs a u32 id and an f32 logit in a u32 buffer, so the logit is read by bit
* pattern (`ldt` would convert 0x40800000 to 1.08e9, not 4.0). */
if (gt->dtype != RAD_U32 && gt->dtype != RAD_I32) return RAD_E_DTYPE;
const int64_t per_row = numel(gt) / M;
const int64_t n_in = per_row / 2;
@@ -703,22 +645,18 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) {
return f;
};
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_in * 4)
for (int64_t m = 0; m < M; ++m) {
const int64_t gb = rowoff(gt, m, per_row), gs = laststride(gt);
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
/* Selection sort over the gathered pairs, n_cand times. n_in is world_size * n_cand and
* n_cand is a thousand at most, so this is the same O(n*k) the single-rank top-k already
* pays and it needs no scratch. Ties to the lower token id, which is the tie rule every
* other selection here uses. */
/* THE ROW'S OWN top_k, RE-APPLIED. Every rank ran top-k over its own shard before the
* gather, so the merged set holds up to world_size * k candidates where the request asked
* for k, and no stage after this one narrows again. That is a different sampling support,
* and at k = 1 it is a different ANSWER: a greedy row is staged at top_k = 1 exactly so
* this chain returns the argmax, and with world_size candidates alive sample_pick draws
* among them against the request's seed. 0 or negative means the whole width. */
/* Selection sort over the gathered pairs, n_cand times, ties to the lower id: O(n*k) as
* in single-rank top-k, no scratch.
*
* The row's own top_k is re-applied: the gather holds up to world_size * k candidates and
* nothing later narrows them, which at top_k 1 would let sample_pick draw among several
* instead of returning the argmax. <= 0 means the whole width. */
const int32_t tk = R.p[m].top_k;
const int64_t keep = (R.p[m].flags & RAD_SP_GREEDY) ? 0
: (tk > 0 && (int64_t)tk < n_cand) ? (int64_t)tk : n_cand;
@@ -734,7 +672,8 @@ int ref_sample_merge_topk(const RadArgs* a, RadStream) {
float best = -INFINITY;
int64_t best_id = -1;
for (int64_t j = 0; j < n_in; ++j) {
const int64_t id = (int64_t)(uint32_t)ld_int(gt->dtype, gt->data, gb + 2 * j * gs);
/* As int32, so the 0xffffffff hole reads as -1 and is skipped. */
const int64_t id = (int32_t)ld_int(gt->dtype, gt->data, gb + 2 * j * gs);
const float v = bits_to_f32(ld_int(gt->dtype, gt->data, gb + (2 * j + 1) * gs));
if (id < 0) continue;
const bool after = v < taken_v || (v == taken_v && id > taken_i);
+599 -639
View File
File diff suppressed because it is too large. Load diff