radiance 1.0.0

This commit is contained in:
Deadcode committed 2026-10-04 12:02:41 +02:00
commit ae74a8aebf
616 files changed
+338692

No files matched your search

+39
View File
@@ -0,0 +1,39 @@
# 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).
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(libref LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
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).
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.
find_package(OpenMP QUIET)
if(OpenMP_CXX_FOUND)
target_link_libraries(libref PRIVATE OpenMP::OpenMP_CXX)
else()
message(STATUS "libref: no OpenMP -- the reference will run single-threaded")
endif()
+593
View File
@@ -0,0 +1,593 @@
/* 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.
*
* ============================== 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 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.
*
* causal = 1 key j is visible when j <= pos
* causal = 0 key j is visible when j < seqused[s]
* window > 0 causal: additionally pos - j < window; non-causal: |pos - j| < window, which is
* the two-sided reading libr4d's h128 kernel documents.
*/
#include "ref_common.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. */
#include "ref_gemm.h"
#include "ref_ops.h"
using namespace ref;
namespace {
/* The largest head this reference accumulates in one stack frame. MLA's 576 is the widest head in
* circulation and libr4d's widest is 256, so 1024 is headroom rather than a limit anyone will
* meet; above it the op says RAD_E_UNSUPPORTED by name instead of overflowing a frame. */
enum { REF_HD_MAX = 1024 };
struct KVView {
const RadTensor* t;
int64_t sb, sh, so, sd; /* strides: block, kv head, slot offset, element */
int64_t head_dim;
};
static inline KVView kv_view(const RadTensor* c, int64_t head_dim, int64_t block_size,
int64_t kv_heads) {
KVView v{};
v.t = c;
v.head_dim = head_dim;
if (c->rank == 4) {
v.sb = c->stride[0]; v.sh = c->stride[1]; v.so = c->stride[2]; v.sd = c->stride[3];
} else {
v.sd = 1;
v.so = 2 * head_dim;
v.sh = block_size * v.so;
v.sb = kv_heads * v.sh;
}
return v;
}
} /* namespace */
/* ------------------------------------------------------------------ attn_paged */
int ref_attn_paged(const RadArgs* a, RadStream) {
if (a->n_t < 8) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *kv = &a->t[1], *bt = &a->t[2], *su = &a->t[3], *o = &a->t[7];
const RadTensor* kdes = t_in(a, 4);
const RadTensor* vdes = t_in(a, 5);
const RadTensor* cus = t_in(a, 6);
if (!q->data || !kv->data || !bt->data || !su->data || !o->data) return RAD_E_INVAL;
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. */
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);
if (head_dim <= 0 || gqa <= 0 || block_size <= 0) return RAD_E_SHAPE;
if (head_dim > REF_HD_MAX) 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 = 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. */
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. */
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;
if (numel(o) < rows * q_heads * head_dim) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[2] != block_size) return RAD_E_SHAPE;
if (kv->rank == 4 && kv->shape[3] < 2 * head_dim) return RAD_E_SHAPE;
const int64_t max_blocks = bt->rank >= 2 ? bt->shape[bt->rank - 1] : numel(bt) / n_seq;
const int64_t bt_rs = bt->rank >= 2 ? bt->stride[bt->rank - 2] : max_blocks;
const int64_t bt_cs = bt->rank >= 2 ? bt->stride[bt->rank - 1] : 1;
const KVView kvv = kv_view(kv, head_dim, block_size, kv_heads);
/* Row strides of q and out read as [rows, q_heads, head_dim], at whatever rank they arrived. */
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
const int64_t total = rows * q_heads;
#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;
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;
/* 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;
}
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. */
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];
const int64_t head_dim = p_int(a, "head_dim", q->rank >= 3 ? q->shape[q->rank - 1] : 0);
const int64_t gqa = p_int(a, "gqa", 1);
const int causal = (int)p_int(a, "causal", 0);
if (head_dim <= 0 || gqa <= 0) return RAD_E_SHAPE;
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. */
const int64_t q_heads = q->rank >= 3 ? q->shape[q->rank - 2]
: (q->rank == 2 ? q->shape[1] / head_dim : 1);
const int64_t kv_heads = q_heads / gqa;
if (kv_heads <= 0 || q_heads % gqa != 0) return RAD_E_SHAPE;
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t total_q = numel(q) / (q_heads * head_dim);
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;
const int64_t q_ds = q->rank >= 2 ? q->stride[q->rank - 1] : 1;
const int64_t q_hs = q->rank >= 3 ? q->stride[q->rank - 2] : head_dim * q_ds;
const int64_t q_rs = row_stride(q, q_heads * head_dim);
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
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 int64_t o_ds = o->rank >= 2 ? o->stride[o->rank - 1] : 1;
const int64_t o_hs = o->rank >= 3 ? o->stride[o->rank - 2] : head_dim * o_ds;
const int64_t o_rs = row_stride(o, q_heads * head_dim);
const float scale = p_f32(a, "scale", 1.0f / std::sqrt((float)head_dim));
#pragma omp parallel for schedule(static)
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));
for (int64_t i = b0; i < b1; ++i) {
const int64_t qb = i * q_rs + h * q_hs, ob = i * o_rs + h * o_hs;
const int64_t jend = causal ? (i + 1) : b1;
float mx = -INFINITY;
for (int64_t j = b0; j < jend; ++j) {
const int64_t kb = j * k_rs + kh * k_hs;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
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;
if (mx == -INFINITY) {
for (int64_t d = 0; d < head_dim; ++d) stt(o, ob + d * o_ds, 0.0f);
continue;
}
float sum = 0.0f;
for (int64_t j = b0; j < jend; ++j) {
const int64_t kb = j * k_rs + kh * k_hs, vb = j * v_rs + kh * v_hs;
float dot = 0.0f;
for (int64_t d = 0; d < head_dim; ++d)
dot += ldt(q, qb + d * q_ds) * ldt(k, kb + d * k_ds);
const float w = ref_exp(dot * scale - mx);
sum += w;
for (int64_t d = 0; d < head_dim; ++d) acc[d] += w * ldt(v, vb + d * v_ds);
}
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;
}
/* ------------------------------------------------------------------ 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).
*
* 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.
*
* `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. */
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];
const int64_t head_dim = p_int(a, "head_dim", k->rank >= 3 ? k->shape[k->rank - 1] : 0);
const int64_t block_size = p_int(a, "block_size", 0);
int64_t kv_heads = p_int(a, "n_head_kv", kv->rank == 4 ? kv->shape[1] : 0);
if (head_dim <= 0 || block_size <= 0 || kv_heads <= 0) return RAD_E_SHAPE;
if (kv->rank == 4 && (kv->shape[1] != kv_heads || kv->shape[2] != block_size ||
kv->shape[3] < 2 * head_dim)) return RAD_E_SHAPE;
const int64_t M = numel(sm);
if (M <= 0 || numel(k) < M * kv_heads * head_dim) return RAD_E_SHAPE;
const int64_t n_blocks = kv->rank == 4 ? kv->shape[0] : 0;
const int64_t k_ds = k->rank >= 2 ? k->stride[k->rank - 1] : 1;
const int64_t k_hs = k->rank >= 3 ? k->stride[k->rank - 2] : head_dim * k_ds;
const int64_t k_rs = row_stride(k, kv_heads * head_dim);
const int64_t v_ds = v->rank >= 2 ? v->stride[v->rank - 1] : 1;
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. */
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;
for (int64_t t = 0; t < M; ++t) {
const int64_t slot = ld_int(sm->dtype, sm->data, offlin(sm, t));
if (slot >= 0 && n_blocks > 0 && slot / block_size >= n_blocks) return RAD_E_SHAPE;
}
#pragma omp parallel for schedule(static)
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;
const int64_t blk = slot / block_size, off = slot % block_size;
for (int64_t h = 0; h < kv_heads; ++h) {
const int64_t cb = blk * kvv.sb + h * kvv.sh + off * kvv.so;
for (int64_t d = 0; d < head_dim; ++d) {
stt(kv, cb + d * kvv.sd, ldt(k, t * k_rs + h * k_hs + d * k_ds) * ks);
stt(kv, cb + (head_dim + d) * kvv.sd, ldt(v, t * v_rs + h * v_hs + d * v_ds) * vs);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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).
*
* 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. */
enum { ROPE_NEOX = 0, ROPE_GPTJ = 1, ROPE_MROPE = 2, ROPE_IMROPE = 3, ROPE_AXIAL = 4 };
struct RopeFreq {
int comp[REF_HD_MAX / 2];
float inv[REF_HD_MAX / 2];
};
/* Which component and inverse frequency each of the rot/2 frequencies uses. */
static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, int n_sec,
RopeFreq* f) {
const int64_t half = rot / 2;
if (half > REF_HD_MAX / 2) return RAD_E_UNSUPPORTED;
int64_t start[8] = {}, total = 0;
for (int c = 0; c < n_sec; ++c) { start[c] = total; total += sec[c]; }
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)rot);
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]));
}
} else if (n_sec >= 3 && mode == ROPE_IMROPE) {
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
}
f->comp[i] = c;
f->inv[i] = inv;
}
return RAD_OK;
}
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
const RopeFreq& f, const float* pos) {
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), s = std::sin(ang);
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);
stt(t, base + i0 * ds, x0 * c - x1 * s);
stt(t, base + i1 * ds, x0 * s + x1 * c);
}
}
/* "11 11 10" -> {11, 11, 10}. Absent is no sections. */
static int rope_sections(const RadArgs* a, int64_t* sec) {
const char* v = p_str(a, "sections", nullptr);
int n = 0;
while (v && *v && n < 8) {
char* end = nullptr;
const long long x = std::strtoll(v, &end, 10);
if (end == v) break;
if (x <= 0) return -1;
sec[n++] = x;
v = end;
}
return n;
}
} /* namespace */
int ref_rope(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *qkv = &a->t[0], *pos = &a->t[1];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" };
const int mode = p_enum(a, "mode", kModes, 5, -1);
if (mode < 0) return RAD_E_UNSUPPORTED;
int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
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. */
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);
if (multi) {
if (mode == ROPE_NEOX || mode == ROPE_GPTJ || n_sec <= 0) return RAD_E_SHAPE;
const int64_t need = mode == ROPE_IMROPE ? 3 : n_sec;
if (n_comp < need || n_comp > 8) return RAD_E_SHAPE;
}
RopeFreq f;
RAD_REF_TRY(rope_freqs(mode, rot, theta, sec, multi ? n_sec : 0, &f));
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 ds = laststride(qkv);
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float div = rscale != 0.0f ? rscale : 1.0f;
if (multi) {
for (int64_t c = 0; c < n_comp; ++c)
p[c] = (float)ld_int(pos->dtype, pos->data, c * pcs + m * pms) / div;
} else {
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) / div;
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. */
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);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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.
*
* 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. */
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];
const int64_t head_dim = p_int(a, "head_dim", 0);
const int64_t n_head = p_int(a, "n_head", 0);
const int64_t n_head_kv = p_int(a, "n_head_kv", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float eps = p_f32(a, "eps", 1e-6f);
const float rscale = p_f32(a, "scale", 1.0f);
const float wadd = p_f32(a, "wadd", 0.0f);
static const char* kModes[] = { "neox", "gptj" };
const int mode = p_enum(a, "mode", kModes, 2, ROPE_NEOX);
int64_t rot = p_int(a, "rotary_dim", head_dim);
if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE;
if (numel(qw) < head_dim || numel(kw) < head_dim) return RAD_E_SHAPE;
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
const int64_t M = numel(pos);
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row;
const int64_t ds = laststride(qkv);
RopeFreq f;
RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f));
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
float p[8];
const float one = (float)ld_int(pos->dtype, pos->data, offlin(pos, m)) /
(rscale != 0.0f ? rscale : 1.0f);
for (int c = 0; c < 8; ++c) p[c] = one;
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));
rope_head(qkv, base, ds, rot, mode, f, p);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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 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. */
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];
const int64_t rot = p_int(a, "rot", 0);
const float theta = p_f32(a, "theta", 10000.0f);
const float rscale = p_f32(a, "scale", 1.0f);
if (rot < 2 || (rot & 1)) return RAD_E_SHAPE;
const int64_t M = numel(pos);
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
const int64_t rows = numel(cs) / rot;
const int64_t half = rot / 2;
#pragma omp parallel for schedule(static)
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 = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
const float ang = p * inv;
stt(cs, offlin(cs, pp * rot + i), std::cos(ang));
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang));
}
}
return RAD_OK;
}
+239
View File
@@ -0,0 +1,239 @@
/* 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.
*
* 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.
*
* 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).
*
* `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.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <cstring>
using namespace ref;
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. */
struct Group {
std::mutex m;
std::condition_variable cv;
int world = 0;
int arrived = 0;
unsigned gen = 0;
const void* slot[REF_MAX_RANKS] = {};
int64_t nel [REF_MAX_RANKS] = {};
uint32_t dt [REF_MAX_RANKS] = {};
};
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. */
static bool barrier(Group& g) {
std::unique_lock<std::mutex> lk(g.m);
const unsigned mygen = g.gen;
if (++g.arrived == g.world) {
g.arrived = 0;
++g.gen;
g.cv.notify_all();
return true;
}
return g.cv.wait_for(lk, std::chrono::seconds(30), [&] { return g.gen != mygen; });
}
static int join(int rank, int world) {
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;
else if (g.world != world) return RAD_E_INVAL;
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). */
static float* staging(const RadArgs* a, int64_t nel) {
if (a->scratch && a->scratch_bytes >= nel * (int64_t)sizeof(float))
return (float*)a->scratch;
return ws_get((size_t)nel);
}
} /* namespace */
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). */
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);
}
void ref_collective_fini(void*) {}
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);
if (ws <= 1) return 0;
const int64_t nel = p_int(a, "numel", a->n_t > 0 ? numel(&a->t[0]) : 0);
return nel * (int64_t)sizeof(float);
}
/* ------------------------------------------------------------------ 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. */
int ref_all_reduce(const RadArgs* a, RadStream) {
if (!have(a, 1)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
const RadTensor* y = t_in(a, 1);
/* The message is the operand; `numel` is the band. See band_rows in ref_common.h. */
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
if (nel <= 0) return RAD_E_SHAPE;
if (y && numel(y) < nel) return RAD_E_SHAPE;
const RadTensor* dst = y ? y : x;
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. */
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));
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;
for (int r = 0; r < world; ++r) s += ld_dt(g.dt[r], g.slot[r], i);
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. */
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;
}
/* ------------------------------------------------------------------ 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. */
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];
/* The contribution is the operand; `numel` is the band. See band_rows in ref_common.h. */
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. */
const int64_t esz = rad_dtype_bytes(x->dtype, 1);
if (esz <= 0 || y->dtype != x->dtype) return RAD_E_DTYPE;
if (world <= 1) {
for (int64_t i = 0; i < nel; ++i)
std::memcpy((char*)y->data + offlin(y, i) * esz,
(const char*)x->data + offlin(x, i) * esz, (size_t)esz);
return RAD_OK;
}
const int rank = a->rank;
RAD_REF_TRY(join(rank, world));
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. */
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)
for (int64_t i = 0; i < nel; ++i) {
const int64_t o = (row > 0 && row < nel)
? (i / row) * (world * row) + (int64_t)r * row + (i % row)
: (int64_t)r * nel + i;
std::memcpy((char*)y->data + offlin(y, o) * esz,
(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. */
if (!barrier(g)) return RAD_E_DEVICE;
return RAD_OK;
}
+449
View File
@@ -0,0 +1,449 @@
/* ref_common.h -- libref's numeric bedrock: dtype conversion, strided element access, and
* the parameter readers every op shares.
*
* ============================ THE NUMERICS ARE THE REFERENCE DEFINITION ============================
*
* 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, 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.
*
* 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).
*/
#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. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include <cstdint>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <vector>
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. */
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); }
static inline uint16_t f32_to_f16(float f) { return rad_f32_to_f16(f); }
static inline float fp8e4m3_to_f32(uint8_t b) { return rad_fp8e4m3_to_f32(b); }
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. */
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];
return (nib & 0x8u) ? -v : v;
}
/* OCP e8m0 block scale: a raw exponent byte, value 2^(e-127). 255 is NaN by definition. */
static inline float e8m0_to_f32(uint8_t e) {
if (e == 0xff) return std::nanf("");
return std::ldexp(1.0f, (int)e - 127);
}
/* ================================================================== 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:
*
* 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).
*
* 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. */
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);
return (float)((int)(n ^ 0x8u) - 8);
}
static inline float w2_code(const void* p, int64_t i) {
uint8_t b = ((const uint8_t*)p)[i >> 2];
uint8_t c = (uint8_t)((b >> (2 * (i & 3))) & 0x3u);
return (float)((int)(c ^ 0x2u) - 2);
}
static inline float mxfp4_code(const void* p, int64_t i) {
uint8_t b = ((const uint8_t*)p)[i >> 1];
return mxfp4_elem_to_f32((i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf));
}
/* ================================================================== 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. */
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_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_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);
default: return 0.0f;
}
}
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;
case RAD_F16: ((uint16_t*)p)[i] = f32_to_f16(v); break;
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; }
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;
}
}
/* 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. */
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];
case RAD_U32: return (int64_t)((const uint32_t*)p)[i];
case RAD_I64: return ((const int64_t*)p)[i];
case RAD_I16: return (int64_t)((const int16_t*)p)[i];
case RAD_I8: return (int64_t)((const int8_t*)p)[i];
case RAD_U8: return (int64_t)((const uint8_t*)p)[i];
case RAD_BOOL: return ((const uint8_t*)p)[i] ? 1 : 0;
case RAD_F32: return (int64_t)((const float*)p)[i];
default: return 0;
}
}
static inline void st_int(uint32_t dt, void* p, int64_t i, int64_t v) {
switch (dt) {
case RAD_I32: ((int32_t*)p)[i] = (int32_t)v; break;
case RAD_U32: ((uint32_t*)p)[i] = (uint32_t)v; break;
case RAD_I64: ((int64_t*)p)[i] = v; break;
case RAD_I16: ((int16_t*)p)[i] = (int16_t)v; break;
case RAD_I8: ((int8_t*)p)[i] = (int8_t)v; break;
case RAD_U8: ((uint8_t*)p)[i] = (uint8_t)v; break;
default: st_dt(dt, p, i, (float)v); break;
}
}
/* ================================================================== 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. */
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_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); } };
template <> struct Cvt<RAD_I2> { static inline float ld(const void* p, int64_t i) { return w2_code(p, i); } };
template <> struct Cvt<RAD_FP4E2M1> { static inline float ld(const void* p, int64_t i) { return mxfp4_code(p, i); } };
/* ------------------------------------------------------------------ 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.
*
* `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.
*
* 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. */
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;
}
/* ================================================================== tensors */
static inline int64_t numel(const RadTensor* t) {
if (!t || !t->data || t->rank == 0) return 0;
int64_t n = 1;
for (uint32_t i = 0; i < t->rank; ++i) n *= t->shape[i];
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. */
static inline int64_t offlin(const RadTensor* t, int64_t lin) {
if (t->rank == 0) return lin;
int64_t acc = 1;
bool c = true;
for (int i = (int)t->rank - 1; i >= 0; --i) {
if (t->shape[i] != 1 && t->stride[i] != acc) { c = false; break; }
acc *= t->shape[i];
}
if (c) return lin;
int64_t off = 0;
for (int i = (int)t->rank - 1; i >= 0; --i) {
int64_t s = t->shape[i];
if (s <= 0) return 0;
off += (lin % s) * t->stride[i];
lin /= s;
}
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. */
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. */
int64_t off = 0;
for (int i = (int)t->rank - 2; i >= 0; --i) {
int64_t s = t->shape[i];
if (s <= 0) return 0;
off += (r % s) * t->stride[i];
r /= s;
}
return off;
}
return r * cols;
}
static inline int64_t laststride(const RadTensor* t) {
return t->rank ? t->stride[t->rank - 1] : 1;
}
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); }
/* ================================================================== 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.
*
* 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. */
static inline const RadParam* p_find(const RadArgs* a, const char* k) {
return a ? rad_param_find(a->p, a->n_p, k) : nullptr;
}
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_STR && p->sval) return std::strtoll(p->sval, nullptr, 10);
return dflt;
}
static inline const char* p_str(const RadArgs* a, const char* k, const char* dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_STR && p->sval) return p->sval;
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. */
static inline float p_f32(const RadArgs* a, const char* k, float dflt) {
const RadParam* p = p_find(a, k);
if (!p) return dflt;
if (p->kind == RAD_P_F64) return (float)p->dval;
if (p->kind == RAD_P_STR && p->sval) return (float)std::strtod(p->sval, nullptr);
if (p->kind == RAD_P_INT) return (float)p->ival;
if (p->kind == RAD_P_RANGE) return (float)p->ihi;
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. */
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);
if (!p) return dflt;
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;
}
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. */
#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; }
/* ================================================================== 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.
*
* 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.
*
* 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. */
inline float* ws_get(size_t n_floats) {
static thread_local std::vector<float> v;
if (v.size() < n_floats) v.resize(n_floats);
return v.data();
}
/* ================================================================== 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.
*
* `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. */
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;
int64_t best_i = -1;
for (int64_t i = 0; i < N; ++i) {
const float v = ld_dt(x->dtype, x->data, base + i * st);
if (v > *pv) continue; /* strictly better than the last pick */
if (v == *pv && i <= *pi) continue; /* the last pick itself, or one before it */
if (best_i < 0 || v > best_v) { best_v = v; best_i = i; }
}
if (best_i < 0) return false;
*pv = best_v;
*pi = best_i;
return true;
}
/* ================================================================== 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)); }
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. */
static inline float act_gelu(float x) {
return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f));
}
/* 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. */
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));
}
/* ================================================================== 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. */
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;
}
}
static inline bool pow2(int64_t v) { return v > 0 && (v & (v - 1)) == 0; }
} /* namespace ref */
#endif /* RAD_REF_COMMON_H */
+443
View File
@@ -0,0 +1,443 @@
/* 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.
*/
#include "ref_common.h"
#include "ref_ops.h"
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 (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *y = &a->t[2];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || numel(y) < rows * n || numel(w) < 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), ws = laststride(w);
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 * (ldt(w, i * ws) + wadd));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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.
*/
int ref_rmsnorm_add(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *res = &a->t[1], *w = &a->t[2], *y = &a->t[3], *ro = &a->t[4];
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
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)
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);
const int64_t xs = laststride(x), rs = laststride(res);
const int64_t ys = laststride(y), os = laststride(ro), ws = laststride(w);
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) {
float v = ldt(x, xb + i * xs) + ldt(res, rb + i * rs);
ss += v * v;
stt(ro, ob + i * os, 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(ro, ob + i * os) * s * (ldt(w, i * ws) + wadd));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const RadTensor* b = t_in(a, 2);
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-5f);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
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)
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);
float sum = 0.0f;
for (int64_t i = 0; i < n; ++i) sum += ldt(x, xb + i * xs);
const float mean = sum / (float)n;
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) { float d = ldt(x, xb + i * xs) - mean; ss += d * d; }
const float s = 1.0f / std::sqrt(ss / (float)n + eps);
for (int64_t i = 0; i < n; ++i) {
float v = (ldt(x, xb + i * xs) - mean) * s * ldt(w, i * ws);
if (b) v += ldt(b, i * laststride(b));
stt(y, yb + i * ys, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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.
*
* 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;
}
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];
const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0);
const int64_t side = p_int(a, "side", 0);
if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE;
const int64_t rows = rows_of(x, n);
if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows)
return RAD_E_SHAPE;
const int64_t cs = crd->stride[0], ms = crd->stride[1];
const int64_t ts = laststride(tab);
#pragma omp parallel for schedule(static)
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);
const int64_t gh = ld_int(crd->dtype, crd->data, 2 * cs + r * ms);
const int64_t gw = ld_int(crd->dtype, crd->data, 3 * cs + r * ms);
int64_t th[2], tw[2];
float wh[2], ww[2];
auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) {
const float src = (float)idx * (float)(side - 1) / (float)(size - 1 > 1 ? size - 1 : 1);
const float fl = std::floor(src);
for (int k = 0; k < 2; ++k) {
int64_t tap = (int64_t)fl + k;
t[k] = tap < 0 ? 0 : (tap > side - 1 ? side - 1 : tap);
const float d = std::fabs(src - fl - (float)k);
w[k] = 1.0f - d > 0.0f ? 1.0f - d : 0.0f;
}
};
axis(gr, gh, th, wh);
axis(gc, gw, tw, ww);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
for (int ki = 0; ki < 2; ++ki)
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);
stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const int64_t n = p_int(a, "n", numel(Y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(Y, n);
if (rows <= 0 || numel(A) < rows * n) return RAD_E_SHAPE;
const bool bcast = numel(B) == n && rows > 1;
if (!bcast && numel(B) < rows * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
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);
const int64_t as = laststride(A), bs = laststride(B), ys = laststride(Y);
for (int64_t i = 0; i < n; ++i) {
float u = ldt(A, ab + i * as), v = ldt(B, bb + i * bs);
stt(Y, yb + i * ys, mul ? u * v : u + v);
}
}
return RAD_OK;
}
int ref_add(const RadArgs* a, RadStream) { return elementwise2(a, false); }
int ref_mul(const RadArgs* a, RadStream) { return elementwise2(a, true); }
/* ------------------------------------------------------------------ scale_rows */
/* y[m, i] = x[m, i] * act(s[m]) -- one scalar per ROW, broadcast across the row.
*
* 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 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. */
int ref_scale_rows(const RadArgs* a, RadStream) {
if (!have(a, 4)) 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));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n || numel(sc) < rows) return RAD_E_SHAPE;
if (ad && numel(ad) < rows * n) return RAD_E_SHAPE;
const char* act = p_str(a, "act", "none");
const bool sig = act && !std::strcmp(act, "sigmoid");
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)
for (int64_t r = 0; r < rows; ++r) {
const float v0 = ldt(sc, r * ss);
const float v = sig ? act_sigmoid(v0) : v0;
const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n);
const int64_t xs = laststride(x), ys = laststride(y);
const int64_t ab = ad ? rowoff(ad, r, n) : 0;
const int64_t as = ad ? laststride(ad) : 1;
for (int64_t i = 0; i < n; ++i) {
const float av = ad ? ldt(ad, ab + i * as) : 0.0f;
stt(y, yb + i * ys, ldt(x, xb + i * xs) * v);
if (ad) stt(y, yb + i * ys, ldt(y, yb + i * ys) + av);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
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);
for (int64_t i = 0; i < n; ++i)
stt(y, yb + i * ys, act_silu(ldt(gu, gb + i * gs)) * ldt(gu, gb + (n + i) * gs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gelu / silu */
static int unary(const RadArgs* a, int which) {
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;
#pragma omp parallel for schedule(static)
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));
}
return RAD_OK;
}
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. */
int ref_sigmoid(const RadArgs* a, RadStream) { return unary(a, 2); }
/* ------------------------------------------------------------------ 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).
*
* `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. */
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];
const int64_t n = p_int(a, "n", y->rank >= 1 ? y->shape[y->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(y, n);
const int64_t src_rows = rows_of(x, n);
if (M <= 0 || src_rows <= 0 || numel(idx) < M) return RAD_E_SHAPE;
/* Validated before the loop, because an OpenMP body cannot return. */
for (int64_t m = 0; m < M; ++m) {
const int64_t r = ld_int(idx->dtype, idx->data, offlin(idx, m));
if (r >= src_rows) return RAD_E_INVAL;
}
#pragma omp parallel for schedule(static)
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);
if (r < 0) { for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, 0.0f); continue; }
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, ldt(x, xb + i * xs));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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.
*
* `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.
*
* 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. */
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];
const int64_t n = p_int(a, "n", v->rank >= 1 ? v->shape[v->rank - 1] : 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t M = rows_of(v, n);
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. */
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)
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;
const int64_t vb = rowoff(v, m, n), vs = laststride(v);
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
for (int64_t i = 0; i < n; ++i) stt(x, xb + i * xs, ldt(v, vb + i * vs));
}
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. */
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. */
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)
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)));
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const int64_t n = p_int(a, "n", numel(y));
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = rows_of(y, n);
if (rows <= 0 || numel(x) < rows * n) return RAD_E_SHAPE;
#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 mx = -INFINITY;
for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); if (v > mx) mx = v; }
float sum = 0.0f;
for (int64_t i = 0; i < n; ++i) {
float e = ref_exp(ldt(x, xb + i * xs) - mx);
sum += e;
stt(y, yb + i * ys, e);
}
const float inv = 1.0f / sum;
for (int64_t i = 0; i < n; ++i) stt(y, yb + i * ys, ldt(y, yb + i * ys) * inv);
}
return RAD_OK;
}
+905
View File
@@ -0,0 +1,905 @@
/* ref_gdn.cpp -- the gated delta net: the conv preamble, the chunk preamble, the chunked scan, the
* recurrent update and the gated norm.
*
* The algorithm is libr4d's, stated in its own comments and reproduced here without any of the
* fusion. Where libr4d says the state lives in WMMA accumulators across a whole chunk, this keeps
* it in a per-thread workspace and writes every intermediate out; where libr4d recomputes the gram
* once per k head for three v heads, this recomputes it per v head. Both are the same arithmetic.
*
* ============================== THE ALGORITHM ==============================
*
* Per token, per v head, with q and k l2-normalised and the state S shaped [head_v, head_k]:
*
* g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b)
* S *= e^g
* u = beta . (v - S k) S += u k^T o = S q
*
* That is the recurrent form, which is what DECODE runs. Prefill runs the chunked form, which is
* the same recurrence blocked over `chunk` tokens with the intra-chunk dependencies solved in one
* triangular inverse (`gdn_kkt_solve`) instead of sequentially:
*
* ge[j] = e^{g_j} gs[j] = e^{g_last - g_j} (g is the INTRA-CHUNK CUMSUM of the gate)
* U = K S^T W = beta . (V - ge . U) V' = A W
* P = Q K^T sA = scale . e^{g_i - g_j} . tril(P)
* O = scale . ge . (Q S^T) + sA V'
* S = e^{g_last} S + V'^T (gs . K)
*
* EVERY DECAY FACTOR FORMED HERE IS <= 1, and that is a correctness requirement rather than a
* style. Intra-chunk gate spans on real prefill inputs reach several hundred nats, so
* any factorisation that puts half the exponent on its own -- e^{g_i - c} and e^{c - g_j} about
* some per-chunk reference c -- sends one half past fp32's e^88 while the other underflows to
* zero, whatever c is chosen. The pairs e^{g_i - g_j} (j <= i) and e^{g_last - g_j} never leave
* (0, 1]. A reference that took the convenient factorisation would produce infinities on inputs
* the fast kernel handles, which is the wrong way round for an oracle.
*
* ============================== THE LAYOUTS ==============================
*
* q, k [T, head_k_count, head_k] v, o [T, head_v_count, head_v]
* g, beta [T, head_v_count] A [T, head_v_count, chunk]
* h0, ht [N, head_v_count, head_v, head_k] cu [N+1]
* conv w [conv_dim, conv_width] conv b [conv_dim]
* conv_state [n_slots, conv_dim, state_len]
* state [n_slots, head_v_count, head_v, head_k]
*
* with conv_dim = 2 * head_k_count * head_k + head_v_count * head_v, and `x` the fused projection
* row [q | k | v | a | b] -- conv_dim convolved channels followed by one `a` and one `b` per v
* head. gdn_conv_prep takes `a` and `b_gate` as OPTIONAL operands: present, they are the layer's
* separate gate and beta projections; absent, they are the last 2 * head_v_count columns of `x`.
* gdn_recurrent_update always names them separately, and a caller with a fused row passes strided
* views of it.
*
* The speculative rollback contract for the two state caches is in ref_ops.h and is obeyed here.
*/
#include "ref_common.h"
#include "ref_ops.h"
using namespace ref;
namespace {
/* The deepest convolution history this reference holds in a stack frame. libr4d's width is 4 and
* no linear-attention model in circulation exceeds it by much; a wider request returns
* RAD_E_UNSUPPORTED by name rather than convolving a truncated window, which would be numerically
* plausible and completely wrong. */
enum { REF_CONV_HIST_MAX = 16 };
struct V3 { const RadTensor* t; int64_t s0, s1, s2; };
struct V2 { const RadTensor* t; int64_t s0, s1; };
static inline V3 v3(const RadTensor* t, int64_t d1, int64_t d2) {
V3 v{ t, d1 * d2, d2, 1 };
if (t->rank >= 3) {
v.s0 = t->stride[t->rank - 3];
v.s1 = t->stride[t->rank - 2];
v.s2 = t->stride[t->rank - 1];
}
return v;
}
/* The same [tokens, d1, d2] reading for an operand that may be a COLUMN VIEW of a wider row: the
* fp8 delta net's output gate is the tail of a fused [q|k|v|z] projection, so its token stride is
* its own rather than d1*d2. A rank-3 spelling already carries all three strides; a rank-2 one
* carries the token stride in stride[0] and v3() would have guessed d1*d2 for it. */
static inline V3 v3_rows(const RadTensor* t, int64_t d1, int64_t d2) {
if (t->rank != 2) return v3(t, d1, d2);
return V3{ t, t->stride[0], d2 * t->stride[1], t->stride[1] };
}
static inline V2 v2(const RadTensor* t, int64_t d1) {
V2 v{ t, d1, 1 };
if (t->rank >= 2) { v.s0 = t->stride[t->rank - 2]; v.s1 = t->stride[t->rank - 1]; }
return v;
}
static inline int64_t at3(const V3& v, int64_t i, int64_t j, int64_t k) {
return i * v.s0 + j * v.s1 + k * v.s2;
}
static inline int64_t at2(const V2& v, int64_t i, int64_t j) { return i * v.s0 + j * v.s1; }
/* [N, heads, head_v, head_k] -- the shape both the chunked scan's h0/ht and the paged recurrent
* state have. The slot and head strides are read off the tensor and NOT derived from the shape:
* a paged state cache is padded so its page matches the attention page, and a kernel that derived
* the stride would read every slot but the first at the wrong offset, which looks exactly like a
* correct kernel producing noise (libr4d makes the same point about vLLM's mamba page). */
struct V4 { const RadTensor* t; int64_t s0, s1, s2, s3; };
static inline V4 v4(const RadTensor* t, int64_t d1, int64_t d2, int64_t d3) {
V4 v{ t, d1 * d2 * d3, d2 * d3, d3, 1 };
if (t->rank >= 4) {
v.s0 = t->stride[t->rank - 4];
v.s1 = t->stride[t->rank - 3];
v.s2 = t->stride[t->rank - 2];
v.s3 = t->stride[t->rank - 1];
}
return v;
}
static inline int64_t at4(const V4& v, int64_t i, int64_t j, int64_t k, int64_t l) {
return i * v.s0 + j * v.s1 + k * v.s2 + l * v.s3;
}
static inline int64_t cu_at(const RadTensor* cu, int64_t i) {
return ld_int(cu->dtype, cu->data, offlin(cu, i));
}
/* The conv state is [n_slots, conv_dim, state_len]; a rank the caller flattened is read as the
* tight layout that shape implies. */
static inline V3 conv_state_view(const RadTensor* cs, int64_t conv_dim, int64_t width,
int64_t* state_len) {
*state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : (width > 1 ? width - 1 : 1);
return v3(cs, conv_dim, *state_len);
}
} /* namespace */
/* ------------------------------------------------------------------ gdn_conv_prep */
/* Everything between the qkv projection and the chunked scan: the width-`conv_width` depthwise
* causal convolution with silu and its state cache, the q/k/v split, the l2 norm over each q and k
* head, the gate with its per-chunk cumsum, and beta.
*
* THE CONV OUTPUT IS ROUNDED BEFORE THE NORM. A fused kernel rounds to bf16 there because the pair
* of kernels it replaces does -- the conv writes a bf16 tensor and the prep reads it back -- and
* matching that is what lets the fused form stand in for the unfused pair on real weights. The
* reference does the same by writing the conv result into its output tensor and reading it back
* for the norm.
*
* The l2 norm is rsqrt(sum(x^2) + l2_eps) with NO division by the head width -- it is a norm, not
* an RMS -- and l2_eps is 1e-6, which is FLA's and libr4d's L2NORM_EPS. */
int ref_gdn_conv_prep(const RadArgs* a, RadStream) {
if (a->n_t < 16) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[5], *cu = &a->t[6];
const RadTensor *q = &a->t[11], *k = &a->t[12], *v = &a->t[13];
const RadTensor *g = &a->t[14], *beta = &a->t[15];
const RadTensor* bias = t_in(a, 2);
const RadTensor* A_log = t_in(a, 3);
const RadTensor* dt_bias = t_in(a, 4);
/* The gate and beta projections, when the layer hands them separately from the qkv slice.
* Absent, they are the last 2*H columns of the fused `x` row, which is what a caller holding
* a single fused projection passes. */
const RadTensor* ta = t_in(a, 7);
const RadTensor* tb = t_in(a, 8);
const RadTensor* sidx = t_in(a, 9);
const RadTensor* hini = t_in(a, 10);
if (!x->data || !w->data || !cu->data || !q->data || !k->data || !v->data ||
!g->data || !beta->data) return RAD_E_INVAL;
/* One of the two, not one of each: a caller that names the gate has to name beta as well, or
* the second read silently falls back into a fused row that may not be there. */
if ((ta != nullptr) != (tb != nullptr)) return RAD_E_INVAL;
const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
/* `chunk` is RAD_DERIVED on this op, and NOTHING HERE CARRIES IT: the gate cumsum is cut at
* the chunk boundary and no operand's shape records where that is. Ref declares no RAD_C_EQ
* for it, so a caller who both omitted it and resolved to ref arrives with the key unset and
* gets RAD_E_SHAPE by name. The alternative -- treating the sequence as one chunk -- is a
* decay summed over the wrong span, which is numerically plausible and completely wrong. A
* caller pins `chunk` here (which is what the architecture plugins do) or resolves to a kernel
* that declares one. */
const int64_t chunk = p_int(a, "chunk", 0), width = p_int(a, "conv_width", 0);
const float l2eps = p_f32(a, "l2_eps", 1e-6f);
const float spthr = p_f32(a, "softplus_thr", 20.0f);
if (K <= 0 || V <= 0 || chunk <= 0 || width <= 0) return RAD_E_SHAPE;
if (width - 1 > REF_CONV_HIST_MAX) return RAD_E_UNSUPPORTED;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
const int64_t T = cu_at(cu, N);
if (T <= 0) return RAD_OK; /* an empty step is not an error */
const int64_t Hg = numel(q) / (T * K);
const int64_t H = numel(v) / (T * V);
if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE;
const int64_t conv_dim = 2 * Hg * K + H * V;
if (numel(w) < conv_dim * width) return RAD_E_SHAPE;
if (numel(g) < T * H || numel(beta) < T * H) return RAD_E_SHAPE;
const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : (conv_dim + (ta ? 0 : 2 * H));
const int64_t xcol = laststride(x);
/* THE BOUND IS THE VIEW'S AND NOT THE BUFFER'S. `x` may be a column slice of a wider row --
* the fp8 block hands the convolution the left-hand `conv_dim` of a fused [q|k|v|z]
* projection -- and a slice's numel counts only the elements it names, so the flat product
* refuses a call that is perfectly in range. Rank 2 or more spells the extent in the shape;
* only a flattened operand has to be bounded by numel. */
const int64_t xneed = conv_dim + (ta ? 0 : 2 * H);
if (x->rank >= 2) {
if (x->shape[x->rank - 1] < xneed || x->shape[x->rank - 2] < T) return RAD_E_SHAPE;
} else if (numel(x) < (T - 1) * xrow + xneed) {
return RAD_E_SHAPE;
}
if (ta && (numel(ta) < T * H || numel(tb) < T * H)) return RAD_E_SHAPE;
int64_t state_len = 0;
const V3 cvs = conv_state_view(cs, conv_dim, width, &state_len);
if (cs->data && state_len < width - 1) return RAD_E_SHAPE;
const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V);
const V2 wv = v2(w, width);
const V2 gv = v2(g, H), bv = v2(beta, H);
const V2 av = ta ? v2(ta, H) : V2{ nullptr, 0, 0 };
const V2 bgv = tb ? v2(tb, H) : V2{ nullptr, 0, 0 };
/* ---- phase 1: the convolution, straight into q / k / v ---------------------------------- */
#pragma omp parallel for schedule(static)
for (int64_t nc = 0; nc < N * conv_dim; ++nc) {
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, n)) : n;
/* A zero `has_init` means the slot holds no history: the window in front of the sequence's
* first token is ZEROS, 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
* conv_width-1 tokens, which is fluent output with the wrong prefix. */
const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, n)) != 0;
/* Which of the three outputs this channel belongs to. Channel groups are counted in HEADS,
* so a group never straddles the q/k/v boundaries at any tensor-parallel width. */
const RadTensor* out;
V3 ov;
int64_t oh, od;
if (c < Hg * K) { out = q; ov = qv; oh = c / K; od = c % K; }
else if (c < 2 * Hg * K) { out = k; ov = kv; oh = (c - Hg * K) / K; od = (c - Hg * K) % K; }
else { out = v; ov = vv; oh = (c - 2 * Hg * K) / V;
od = (c - 2 * Hg * K) % V; }
const float bs = bias ? ldt(bias, c * laststride(bias)) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = bs;
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
float val = 0.0f;
if (src >= 0) val = ldt(x, (bos + src) * xrow + c * xcol);
else if (warm && cs->data && slot >= 0)
val = ldt(cs, at3(cvs, slot, c, src + width - 1));
acc += val * ldt(w, at2(wv, c, j));
}
stt(out, at3(ov, bos + t, oh, od), act_silu(acc));
}
}
/* ---- phase 2: the l2 norm over each q and k head, reading the ROUNDED conv output -------- */
#pragma omp parallel for schedule(static)
for (int64_t th = 0; th < T * Hg * 2; ++th) {
const int64_t which = th / (T * Hg);
const int64_t rest = th % (T * Hg);
const int64_t t = rest / Hg, h = rest % Hg;
const RadTensor* z = which ? k : q;
const V3& zv = which ? kv : qv;
float ss = 0.0f;
for (int64_t d = 0; d < K; ++d) { float u = ldt(z, at3(zv, t, h, d)); ss += u * u; }
const float inv = 1.0f / std::sqrt(ss + l2eps);
for (int64_t d = 0; d < K; ++d)
stt(z, at3(zv, t, h, d), ldt(z, at3(zv, t, h, d)) * inv);
}
/* ---- phase 3: the gate, its per-chunk cumsum, and beta ----------------------------------- */
/* The cumsum is per CHUNK and per sequence, because that is what the scan consumes: g[j] is
* the decay from the start of j's chunk up to and including j. */
#pragma omp parallel for schedule(static)
for (int64_t nh = 0; nh < N * H; ++nh) {
const int64_t n = nh / H, h = nh % H;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
const float alog = A_log ? ldt(A_log, h * laststride(A_log)) : 0.0f;
const float dtb = dt_bias ? ldt(dt_bias, h * laststride(dt_bias)) : 0.0f;
float run = 0.0f;
for (int64_t t = 0; t < slen; ++t) {
if (t % chunk == 0) run = 0.0f;
const float av_ = ta ? ldt(ta, at2(av, bos + t, h))
: ldt(x, (bos + t) * xrow + (conv_dim + h) * xcol);
const float bvl = tb ? ldt(tb, at2(bgv, bos + t, h))
: ldt(x, (bos + t) * xrow + (conv_dim + H + h) * xcol);
run += -ref_exp(alog) * act_softplus(av_ + dtb, spthr);
stt(g, at2(gv, bos + t, h), run);
stt(beta, at2(bv, bos + t, h), act_sigmoid(bvl));
}
}
/* ---- phase 4: rewrite the conv state from the sequence's last width-1 tokens -------------- */
/* After phase 1, so the history it overwrites has already been read. A sequence shorter than
* width-1 keeps what the old state held in front of its tokens, which is what makes chunked
* prefill work: the second chunk of a sequence continues from the first. */
if (cs->data && width > 1) {
#pragma omp parallel for schedule(static)
for (int64_t nc = 0; nc < N * conv_dim; ++nc) {
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, n)) : n;
if (slen <= 0 || slot < 0) continue;
const bool warm = !hini || ld_int(hini->dtype, hini->data, offlin(hini, n)) != 0;
float keep[REF_CONV_HIST_MAX];
const int64_t st = width - 1;
for (int64_t i = 0; i < st; ++i) {
const int64_t src = slen - (width - 1) + i;
keep[i] = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: (warm ? ldt(cs, at3(cvs, slot, c, src + width - 1)) : 0.0f);
}
for (int64_t i = 0; i < st; ++i) stt(cs, at3(cvs, slot, c, i), keep[i]);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_conv_update */
/* The same convolution for a decode step, against the rolling window. See ref_ops.h for the
* contract; the two things that matter are that the READ starts at num_accepted-1 and that the
* rewrite shifts the buffer down by one so the next step can do the same. A rejection is a change
* of read offset, not a recompute (spec §10), and that is the whole reason this is a separate
* entry point rather than a flag on the prefill one.
*
* No l2 norm here: on the decode path the recurrent update does it, which is where libr4d puts it
* too. */
int ref_gdn_conv_update(const RadArgs* a, RadStream) {
if (a->n_t < 10) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *cs = &a->t[3], *cu = &a->t[6];
const RadTensor *q = &a->t[7], *k = &a->t[8], *v = &a->t[9];
const RadTensor* bias = t_in(a, 2);
const RadTensor* sidx = t_in(a, 4);
const RadTensor* nacc = t_in(a, 5);
if (!x->data || !w->data || !cs->data || !cu->data || !q->data || !k->data || !v->data)
return RAD_E_INVAL;
const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
const int64_t width = p_int(a, "conv_width", 0);
if (K <= 0 || V <= 0 || width <= 0) return RAD_E_SHAPE;
if (width - 1 > REF_CONV_HIST_MAX) return RAD_E_UNSUPPORTED;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
const int64_t T = cu_at(cu, N);
if (T <= 0) return RAD_OK;
const int64_t Hg = numel(q) / (T * K);
const int64_t H = numel(v) / (T * V);
if (Hg <= 0 || H <= 0 || H % Hg != 0) return RAD_E_SHAPE;
const int64_t conv_dim = 2 * Hg * K + H * V;
if (numel(w) < conv_dim * width) return RAD_E_SHAPE;
const int64_t xrow = x->rank >= 2 ? x->stride[x->rank - 2] : conv_dim;
const int64_t xcol = laststride(x);
int64_t state_len = 0;
const V3 cvs = conv_state_view(cs, conv_dim, width, &state_len);
/* The window this step needs: the largest read offset plus the history, and the largest write
* slot. Both are checked here rather than clamped, because a cache that is too shallow is a
* caller bug whose symptom would otherwise be a silently truncated history. */
for (int64_t n = 0; n < N; ++n) {
const int64_t slen = cu_at(cu, n + 1) - cu_at(cu, n);
const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) - 1 : 0;
if (off < 0) return RAD_E_INVAL;
if (off + width - 1 > state_len) return RAD_E_SHAPE;
if (width > 1 && (width - 2) + slen > state_len) return RAD_E_SHAPE;
}
const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V);
const V2 wv = v2(w, width);
#pragma omp parallel for schedule(static)
for (int64_t nc = 0; nc < N * conv_dim; ++nc) {
const int64_t n = nc / conv_dim, c = nc % conv_dim;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
if (slen <= 0) continue;
const int64_t slot = sidx ? ld_int(sidx->dtype, sidx->data, offlin(sidx, n)) : n;
if (slot < 0) continue;
const int64_t off = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) - 1 : 0;
float hist[REF_CONV_HIST_MAX];
const int64_t st = width - 1;
for (int64_t i = 0; i < st; ++i) hist[i] = ldt(cs, at3(cvs, slot, c, off + i));
const RadTensor* out;
V3 ov;
int64_t oh, od;
if (c < Hg * K) { out = q; ov = qv; oh = c / K; od = c % K; }
else if (c < 2 * Hg * K) { out = k; ov = kv; oh = (c - Hg * K) / K; od = (c - Hg * K) % K; }
else { out = v; ov = vv; oh = (c - 2 * Hg * K) / V;
od = (c - 2 * Hg * K) % V; }
const float bs = bias ? ldt(bias, c * laststride(bias)) : 0.0f;
for (int64_t t = 0; t < slen; ++t) {
float acc = bs;
for (int64_t j = 0; j < width; ++j) {
const int64_t src = t - (width - 1) + j;
const float val = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: hist[src + width - 1];
acc += val * ldt(w, at2(wv, c, j));
}
stt(out, at3(ov, bos + t, oh, od), act_silu(acc));
}
/* Shift down by one: the tail of the old history, then this step's tokens. Reading before
* writing is what makes the in-place update safe, and the history is already in registers. */
if (width > 1) {
for (int64_t i = 0; i + 1 < width - 1; ++i)
stt(cs, at3(cvs, slot, c, i), hist[i + 1]);
for (int64_t t = 0; t < slen; ++t)
stt(cs, at3(cvs, slot, c, t + width - 2),
ldt(x, (bos + t) * xrow + c * xcol));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_kkt_solve */
/* A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1}, per chunk, per v head.
*
* The decay is applied PER ELEMENT as e^{g_i - g_j} rather than split about a per-chunk reference.
* Only i > j is kept and g decreases along the chunk, so the difference is always <= 0 and the
* direct form cannot overflow at any span -- which the split form can, on its own, at spans this
* model actually reaches (libr4d's r4d_gdn_kkt_solve says the same at length).
*
* The inverse is a forward substitution rather than libr4d's blocked 16 -> 32 -> 64 WMMA merge.
* The two agree exactly: I + M is unit lower triangular, so its inverse is unique and the
* substitution computes it in fp32, which is what libr4d's diagonal blocks do too. */
int ref_gdn_kkt_solve(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *k = &a->t[0], *beta = &a->t[1], *g = &a->t[2], *cu = &a->t[3], *A = &a->t[4];
const int64_t K = p_int(a, "head_k", 0);
/* `chunk` is RAD_DERIVED, so a caller who did not pin it and resolved to ref (which declares
* no RAD_C_EQ for it) arrives without the key. Here the operand says: A is [T, heads, chunk]
* and the caller sized it, which is this plugin's rule for every other extent too. */
const int64_t chunk = p_int(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0);
if (K <= 0 || chunk <= 0) return RAD_E_SHAPE;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
const int64_t T = cu_at(cu, N);
if (T <= 0) return RAD_OK;
const int64_t H = numel(beta) / T;
const int64_t Hg = numel(k) / (T * K);
if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE;
if (numel(A) < T * H * chunk) return RAD_E_SHAPE;
const int64_t grp = H / Hg;
const V3 kv = v3(k, Hg, K), Av = v3(A, H, chunk);
const V2 gv = v2(g, H), bv = v2(beta, H);
#pragma omp parallel for schedule(static)
for (int64_t nh = 0; nh < N * H; ++nh) {
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
float* wsp = ws_get((size_t)(chunk * chunk + chunk));
float* Am = wsp; /* [chunk, chunk] the inverse, in fp32 */
float* row = wsp + chunk * chunk;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
const float bi = ldt(beta, at2(bv, ti, h));
const float gi = ldt(g, at2(gv, ti, h));
for (int64_t j = 0; j < i; ++j) {
const int64_t tj = bos + c0 + j;
float dot = 0.0f;
for (int64_t d = 0; d < K; ++d)
dot += ldt(k, at3(kv, ti, hk, d)) * ldt(k, at3(kv, tj, hk, d));
row[j] = bi * dot * ref_exp(gi - ldt(g, at2(gv, tj, h)));
}
/* (I + M) A = I, row by row: A[i][j] = delta - sum_{j<=l<i} M[i][l] A[l][j]. */
for (int64_t j = 0; j <= i; ++j) {
float s = (i == j) ? 1.0f : 0.0f;
for (int64_t l = j; l < i; ++l) s -= row[l] * Am[l * chunk + j];
Am[i * chunk + j] = s;
}
for (int64_t j = i + 1; j < chunk; ++j) Am[i * chunk + j] = 0.0f;
for (int64_t j = 0; j < chunk; ++j)
stt(A, at3(Av, ti, h, j), Am[i * chunk + j]);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_chunk_scan */
int ref_gdn_chunk_scan(const RadArgs* a, RadStream) {
if (a->n_t < 10) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *A = &a->t[3];
const RadTensor *g = &a->t[4], *beta = &a->t[5], *cu = &a->t[7];
const RadTensor *o = &a->t[8], *ht = &a->t[9];
const RadTensor* h0 = t_in(a, 6);
/* THE STATE SLOT, when the caller keeps its recurrent states in a pool the batch does not
* index positionally. Absent, a row owns slot n, which is correct only where slots are handed
* out in batch order. */
const RadTensor* sidx = t_in(a, 10);
if (!q->data || !k->data || !v->data || !A->data || !g->data || !beta->data ||
!cu->data || !o->data) return RAD_E_INVAL;
const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
/* RAD_DERIVED, and A is [T, heads, chunk] -- see gdn_kkt_solve, which writes the same tensor. */
const int64_t chunk = p_int(a, "chunk", A->rank >= 3 ? A->shape[A->rank - 1] : 0);
const float scale = p_f32(a, "scale", 1.0f);
if (K <= 0 || V <= 0 || chunk <= 0) return RAD_E_SHAPE;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
const int64_t T = cu_at(cu, N);
if (T <= 0) return RAD_OK;
const int64_t H = numel(beta) / T;
const int64_t Hg = numel(q) / (T * K);
if (H <= 0 || Hg <= 0 || H % Hg != 0) return RAD_E_SHAPE;
const int64_t grp = H / Hg;
if (numel(o) < T * H * V || numel(A) < T * H * chunk) return RAD_E_SHAPE;
if (!sidx) {
if (ht->data && numel(ht) < N * H * V * K) return RAD_E_SHAPE;
if (h0 && numel(h0) < N * H * V * K) return RAD_E_SHAPE;
} else if (sidx->rank < 1 || sidx->shape[0] < N) {
return RAD_E_SHAPE;
}
const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, H, V), ov = v3(o, H, V);
const V3 Av = v3(A, H, chunk);
const V2 gv = v2(g, H), bv = v2(beta, H);
const V4 h0v = h0 ? v4(h0, H, V, K) : V4{ nullptr, 0, 0, 0, 0 };
const V4 htv = ht->data ? v4(ht, H, V, K) : V4{ nullptr, 0, 0, 0, 0 };
#pragma omp parallel for schedule(static)
for (int64_t nh = 0; nh < N * H; ++nh) {
const int64_t n = nh / H, h = nh % H, hk = h / grp;
const int64_t bos = cu_at(cu, n), slen = cu_at(cu, n + 1) - bos;
/* COLUMN 0 IS THE STATE. A row may be wider -- a decode kernel serving speculation asks
* for scratch beside it -- and the scan writes the state and nothing else. */
const int64_t sw = sidx && sidx->rank >= 1 ? sidx->stride[0] : 1;
const int64_t sn = sidx ? ld_int(sidx->dtype, sidx->data, n * sw) : n;
if (sn < 0) continue; /* a padded row owns no state */
/* One workspace request, carved up by hand -- a second ws_get() may reallocate and
* invalidate the first pointer (ref_common.h). */
const size_t need = (size_t)(V * K + chunk * V + chunk * V + chunk);
float* wsp = ws_get(need);
float* S = wsp; /* [V, K] the recurrent state */
float* Wm = S + V * K; /* [chunk, V] */
float* Vp = Wm + chunk * V; /* [chunk, V] */
float* row = Vp + chunk * V; /* [chunk] one row of sA */
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d)
S[e * K + d] = h0 ? ldt(h0, at4(h0v, sn, h, e, d)) : 0.0f;
for (int64_t c0 = 0; c0 < slen; c0 += chunk) {
const int64_t L = (c0 + chunk < slen) ? chunk : slen - c0;
const float glast = ldt(g, at2(gv, bos + c0 + L - 1, h));
/* W = beta . (V - e^{g_j} . (K S^T)) */
for (int64_t j = 0; j < L; ++j) {
const int64_t tj = bos + c0 + j;
const float ge = ref_exp(ldt(g, at2(gv, tj, h)));
const float bt = ldt(beta, at2(bv, tj, h));
for (int64_t e = 0; e < V; ++e) {
float u = 0.0f;
for (int64_t d = 0; d < K; ++d)
u += ldt(k, at3(kv, tj, hk, d)) * S[e * K + d];
Wm[j * V + e] = bt * (ldt(v, at3(vv, tj, h, e)) - ge * u);
}
}
/* V' = A W, with A unit lower triangular so only j <= i contributes. */
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
for (int64_t e = 0; e < V; ++e) {
float s = 0.0f;
for (int64_t j = 0; j <= i; ++j)
s += ldt(A, at3(Av, ti, h, j)) * Wm[j * V + e];
Vp[i * V + e] = s;
}
}
/* O = scale . e^{g_i} . (Q S^T) + sA V' */
for (int64_t i = 0; i < L; ++i) {
const int64_t ti = bos + c0 + i;
const float gi = ldt(g, at2(gv, ti, h));
const float ge = ref_exp(gi);
for (int64_t j = 0; j <= i; ++j) {
const int64_t tj = bos + c0 + j;
float p = 0.0f;
for (int64_t d = 0; d < K; ++d)
p += ldt(q, at3(qv, ti, hk, d)) * ldt(k, at3(kv, tj, hk, d));
row[j] = scale * ref_exp(gi - ldt(g, at2(gv, tj, h))) * p;
}
for (int64_t e = 0; e < V; ++e) {
float inter = 0.0f;
for (int64_t d = 0; d < K; ++d)
inter += ldt(q, at3(qv, ti, hk, d)) * S[e * K + d];
float s = scale * ge * inter;
for (int64_t j = 0; j <= i; ++j) s += row[j] * Vp[j * V + e];
stt(o, at3(ov, ti, h, e), s);
}
}
/* S = e^{g_last} S + V'^T (e^{g_last - g_j} . K) */
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d) {
float s = ref_exp(glast) * S[e * K + d];
for (int64_t j = 0; j < L; ++j) {
const int64_t tj = bos + c0 + j;
const float gs = ref_exp(glast - ldt(g, at2(gv, tj, h)));
s += Vp[j * V + e] * (gs * ldt(k, at3(kv, tj, hk, d)));
}
S[e * K + d] = s;
}
}
if (ht->data)
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d)
stt(ht, at4(htv, sn, h, e, d), S[e * K + d]);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_recurrent_update */
/* What decode runs where prefill runs the chunked scan, against the PAGED state cache: the initial
* state comes from the slot the last accepted token wrote and every candidate token writes its own
* slot, because which of them survives verification is not known until after this layer has run
* (ref_ops.h). The gated RMS norm is folded into the epilogue, which is where libr4d puts it too --
* its workgroup owns the whole row. */
int ref_gdn_recurrent_update(const RadArgs* a, RadStream) {
if (a->n_t < 14) return RAD_E_INVAL;
const RadTensor *q = &a->t[0], *k = &a->t[1], *v = &a->t[2], *av = &a->t[3], *bvt = &a->t[4];
const RadTensor *state = &a->t[7], *o = &a->t[13];
const RadTensor* A_log = t_in(a, 5);
const RadTensor* dt_bias = t_in(a, 6);
const RadTensor* sidx = t_in(a, 8);
const RadTensor* nacc = t_in(a, 9);
const RadTensor* cu = t_in(a, 10);
const RadTensor* z = t_in(a, 11);
const RadTensor* nw = t_in(a, 12);
/* The out projection's quantiser, folded in. Optional and all-or-nothing; see the
* operand list in r4d_rows.cpp for why the group is the row. */
const RadTensor* oq = (a->n_t > 14 && a->t[14].data) ? &a->t[14] : nullptr;
const RadTensor* osc = (a->n_t > 15 && a->t[15].data) ? &a->t[15] : nullptr;
if (!q->data || !k->data || !v->data || !av->data || !bvt->data || !state->data || !o->data ||
!cu) return RAD_E_INVAL;
/* `cu` BOUNDS THE SEQUENCES, exactly as it does on the sibling gdn_conv_update, which runs off
* the same tensor on the same step. Carrying the sequence count in the state index instead
* works only for a rectangular batch, and leaves a fast kernel -- which reads `cu[n]` before
* any null test -- with a null pointer. Ref reads the token spans from cu and falls back to
* the rectangular reading only for a caller whose cu is degenerate. */
/* THE OTHER STATE CONTRACT IS DECLINED, NOT APPROXIMATED. Under "anchor" the cache holds one
* committed state a sequence plus a block of replay factors, and the accepted prefix is
* replayed onto it next step -- two slots whatever the draft depth. The `o` it produces is the
* same, so a comparison against this reference AGREES on every output and disagrees on the
* whole state, which reads as a broken kernel and is not one. A named refusal is the honest
* answer: RAD_E_UNSUPPORTED says "not this contract", where a number would say "wrong". */
const char* sf = p_str(a, "state_form", "per_candidate");
if (sf && std::strcmp(sf, "per_candidate") != 0) return RAD_E_UNSUPPORTED;
const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
const float scale = p_f32(a, "scale", 1.0f);
const float l2eps = p_f32(a, "l2_eps", 1e-6f);
const float neps = p_f32(a, "eps", 1e-6f);
const float spthr = p_f32(a, "softplus_thr", 20.0f);
static const char* kActs[] = { "silu", "sigmoid" };
const int nact = p_enum(a, "act", kActs, 2, 0);
if (K <= 0 || V <= 0) return RAD_E_SHAPE;
/* The head count and the token count come off the operands: v is [T, head_v_count, head_v],
* so a rank-3 value tensor names both. `n_head_v` overrides it for a caller that hands a
* flattened view. */
int64_t Hv = p_int(a, "n_head_v", 0);
if (Hv <= 0) Hv = v->rank >= 3 ? v->shape[v->rank - 2] : 0;
if (Hv <= 0) return RAD_E_SHAPE;
const int64_t Tk = numel(v) / (Hv * V);
if (Tk <= 0) return RAD_E_SHAPE;
const int64_t Hg = numel(q) / (Tk * K);
if (Hg <= 0 || Hv % Hg != 0) return RAD_E_SHAPE;
const int64_t grp = Hv / Hg;
/* N comes from cu and nothing else: cu is [N+1] and its length minus one IS the sequence
* count. Deriving N from state_idx and trusting cu to be at least as long is an off-by-one
* waiting to happen, because a state index may be wider than one column per sequence. */
const int64_t n_seq = numel(cu) - 1;
if (n_seq <= 0) return RAD_E_SHAPE;
if (cu_at(cu, n_seq) != Tk) return RAD_E_SHAPE;
const int64_t sw = sidx ? (sidx->rank >= 2 ? sidx->shape[sidx->rank - 1]
: (numel(sidx) / n_seq > 0 ? numel(sidx) / n_seq
: 1))
: 1;
const V3 qv = v3(q, Hg, K), kv = v3(k, Hg, K), vv = v3(v, Hv, V), ov = v3(o, Hv, V);
const V3 zv = z ? v3_rows(z, Hv, V) : vv;
const V2 a2 = v2(av, Hv), b2 = v2(bvt, Hv);
const V2 si = sidx ? v2(sidx, sw) : V2{ nullptr, 0, 0 };
#pragma omp parallel for schedule(static)
for (int64_t nh = 0; nh < n_seq * Hv; ++nh) {
const int64_t n = nh / Hv, h = nh % Hv, hk = h / grp;
const int64_t bos = cu_at(cu, n), q_len = cu_at(cu, n + 1) - bos;
if (q_len <= 0) continue;
const int64_t na = nacc ? ld_int(nacc->dtype, nacc->data, offlin(nacc, n)) : 1;
const int64_t rd = na > 0 ? na - 1 : 0;
const int64_t slot_in = sidx ? ld_int(sidx->dtype, sidx->data, at2(si, n, rd < sw ? rd : sw - 1))
: n;
if (slot_in < 0) continue;
const size_t need = (size_t)(V * K + 2 * K + 2 * V);
float* wsp = ws_get(need);
float* S = wsp;
float* qn = S + V * K;
float* kn = qn + K;
float* uu = kn + K;
float* orow = uu + V;
const int64_t sstride = state->rank >= 4 ? state->stride[0] : (int64_t)Hv * V * K;
const int64_t hstride = state->rank >= 4 ? state->stride[1] : (int64_t)V * K;
const int64_t vstride = state->rank >= 4 ? state->stride[2] : K;
const int64_t dstride = state->rank >= 4 ? state->stride[3] : 1;
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d)
S[e * K + d] = ldt(state, slot_in * sstride + h * hstride + e * vstride +
d * dstride);
const float alog = A_log ? ldt(A_log, h * laststride(A_log)) : 0.0f;
const float dtb = dt_bias ? ldt(dt_bias, h * laststride(dt_bias)) : 0.0f;
for (int64_t t = 0; t < q_len; ++t) {
const int64_t tok = bos + t;
const float gv = -ref_exp(alog) *
act_softplus(ldt(av, at2(a2, tok, h)) + dtb, spthr);
const float bt = act_sigmoid(ldt(bvt, at2(b2, tok, h)));
float sq = 0.0f, sk = 0.0f;
for (int64_t d = 0; d < K; ++d) {
const float u = ldt(q, at3(qv, tok, hk, d)), w = ldt(k, at3(kv, tok, hk, d));
sq += u * u;
sk += w * w;
}
const float qs = 1.0f / std::sqrt(sq + l2eps) * scale;
const float ks = 1.0f / std::sqrt(sk + l2eps);
for (int64_t d = 0; d < K; ++d) {
qn[d] = ldt(q, at3(qv, tok, hk, d)) * qs;
kn[d] = ldt(k, at3(kv, tok, hk, d)) * ks;
}
const float dec = ref_exp(gv);
for (int64_t e = 0; e < V; ++e) {
float sk2 = 0.0f;
for (int64_t d = 0; d < K; ++d) {
S[e * K + d] *= dec;
sk2 += S[e * K + d] * kn[d];
}
uu[e] = bt * (ldt(v, at3(vv, tok, h, e)) - sk2);
}
for (int64_t e = 0; e < V; ++e) {
float ss = 0.0f;
for (int64_t d = 0; d < K; ++d) {
S[e * K + d] += uu[e] * kn[d];
ss += S[e * K + d] * qn[d];
}
orow[e] = ss;
}
/* The gated RMS norm, over the head's V channels. */
float sq2 = 0.0f;
for (int64_t e = 0; e < V; ++e) sq2 += orow[e] * orow[e];
const float sc = 1.0f / std::sqrt(sq2 / (float)V + neps);
for (int64_t e = 0; e < V; ++e) {
float r = orow[e] * sc;
if (nw) r *= ldt(nw, e * laststride(nw));
if (z) {
const float zz = ldt(z, at3(zv, tok, h, e));
r *= (nact == 1 ? act_sigmoid(zz) : act_silu(zz));
}
stt(o, at3(ov, tok, h, e), r);
}
/* QUANTISE WHAT WAS WRITTEN, not what produced it: the standalone quant_act_fp8 this
* replaces read `o` back out of memory, so it saw the rounded store and not the f32.
* One group per (token, head), because head_v is the fp8 block width. */
if (oq && osc) {
float amax = 0.0f;
for (int64_t e = 0; e < V; ++e) {
const float m = std::fabs(ldt(o, at3(ov, tok, h, e)));
if (m > amax) amax = m;
}
const float qsc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
const float inv = 1.0f / qsc;
const int64_t qb = rowoff(oq, tok, Hv * V), qs = laststride(oq);
for (int64_t e = 0; e < V; ++e) {
float u = ldt(o, at3(ov, tok, h, e)) * inv;
if (u > 448.0f) u = 448.0f;
if (u < -448.0f) u = -448.0f;
st_dt(oq->dtype, oq->data, qb + (h * V + e) * qs, u);
}
stt(osc, rowoff(osc, tok, Hv) + h * laststride(osc), qsc);
}
const int64_t so = sidx ? ld_int(sidx->dtype, sidx->data, at2(si, n, t < sw ? t : sw - 1))
: n;
if (so >= 0)
for (int64_t e = 0; e < V; ++e)
for (int64_t d = 0; d < K; ++d)
stt(state, so * sstride + h * hstride + e * vstride + d * dstride,
S[e * K + d]);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_gated_rmsnorm */
/* out = x * rsqrt(mean_channels(x^2) + eps) * w * act(z), one row per (token, head). The prefill
* path's form of the epilogue the recurrent update folds in. */
/* The gate has a third spelling the shared rowoff() cannot see. [tokens, heads, ch] it walks, and
* a flat [rows, ch] projection is its product; but a COLUMN SLICE of a wider projection row -- the
* fp8 delta net fuses [q|k|v|z] into one GEMM -- has heads*ch as its last axis, so rowoff reads it
* as a dense row and lands in the next token. Spelled out here rather than generalised there,
* because it is a property of THIS operand and not of every one. */
static inline int64_t gate_rowoff(const RadTensor* t, int64_t r, int64_t ch) {
if (t->rank == 2 && ch > 0 && t->shape[1] != ch && t->shape[1] % ch == 0) {
const int64_t heads = t->shape[1] / ch;
return (r / heads) * t->stride[0] + (r % heads) * ch * t->stride[1];
}
return rowoff(t, r, ch);
}
int ref_gdn_gated_rmsnorm(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *z = &a->t[1], *w = &a->t[2], *o = &a->t[3];
const int64_t ch = p_int(a, "channels", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, 0);
if (ch <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / ch;
if (rows <= 0 || numel(o) < rows * ch || numel(z) < rows * ch || numel(w) < ch)
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, ch), zb = gate_rowoff(z, r, ch), ob = rowoff(o, r, ch);
const int64_t xs = laststride(x), zs = laststride(z), os = laststride(o);
const int64_t ws = laststride(w);
float ss = 0.0f;
for (int64_t i = 0; i < ch; ++i) { float u = ldt(x, xb + i * xs); ss += u * u; }
const float sc = 1.0f / std::sqrt(ss / (float)ch + eps);
for (int64_t i = 0; i < ch; ++i) {
const float zz = ldt(z, zb + i * zs);
stt(o, ob + i * os, ldt(x, xb + i * xs) * sc * ldt(w, i * ws) *
(act == 1 ? act_sigmoid(zz) : act_silu(zz)));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ gdn_conv_recurrent_update */
/* gdn_conv_update into a staging q, k and v, then gdn_recurrent_update over them: the fused op is
* DEFINED as the pair, so the reference is the pair and nothing is restated. The head geometry the
* staging needs comes off `o` ([T, Hv, head_v]) and `x` (2 Hg head_k + Hv head_v columns). */
int ref_gdn_conv_recurrent_update(const RadArgs* a, RadStream st) {
if (a->n_t < 16) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *o = &a->t[15];
if (!x->data || !o->data || o->rank != 3 || x->rank < 2) return RAD_E_SHAPE;
const int64_t K = p_int(a, "head_k", 0), V = p_int(a, "head_v", 0);
const int64_t T = o->shape[0], Hv = o->shape[1];
if (K <= 0 || V <= 0 || T <= 0 || Hv <= 0 || o->shape[2] != V) return RAD_E_SHAPE;
const int64_t conv_dim = x->shape[x->rank - 1];
if (conv_dim <= Hv * V || (conv_dim - Hv * V) % (2 * K)) return RAD_E_SHAPE;
const int64_t Hg = (conv_dim - Hv * V) / (2 * K);
std::vector<uint16_t> qb((size_t)(T * Hg * K)), kb((size_t)(T * Hg * K)), vb((size_t)(T * Hv * V));
auto stage = [&](uint16_t* d, int64_t h, int64_t w) {
RadTensor t{};
t.data = d; t.dtype = x->dtype; t.rank = 3;
t.shape[0] = T; t.shape[1] = h; t.shape[2] = w;
t.stride[0] = h * w; t.stride[1] = w; t.stride[2] = 1;
return t;
};
const RadTensor tq = stage(qb.data(), Hg, K), tk = stage(kb.data(), Hg, K),
tv = stage(vb.data(), Hv, V);
RadParam cp[4] = {};
const char* ck[4] = { "q_len", "head_k", "head_v", "conv_width" };
for (int i = 0; i < 4; ++i) {
const RadParam* f = rad_param_find(a->p, a->n_p, ck[i]);
if (!f) return RAD_E_INVAL;
cp[i] = *f;
}
/* x, w, b, conv_state, state_idx, num_accepted, cu, q, k, v */
RadTensor ct[10] = { a->t[0], a->t[1], a->t[2], a->t[3], a->t[4], a->t[11], a->t[12], tq, tk,
tv };
RadArgs ca = *a;
ca.t = ct; ca.n_t = 10; ca.p = cp; ca.n_p = 4;
int rc = ref_gdn_conv_update(&ca, st);
if (rc != RAD_OK) return rc;
std::vector<RadParam> rp;
for (int i = 0; i < a->n_p; ++i)
if (std::strcmp(a->p[i].key, "conv_width")) rp.push_back(a->p[i]);
/* q, k, v, a, b, A_log, dt_bias, state, state_idx, num_accepted, cu, z, norm_w, o, o_q,
* o_scale */
RadTensor rt[16] = { tq, tk, tv, a->t[5], a->t[6], a->t[7], a->t[8], a->t[9], a->t[10],
a->t[11], a->t[12], a->t[13], a->t[14], a->t[15],
a->n_t > 16 ? a->t[16] : RadTensor{}, a->n_t > 17 ? a->t[17] : RadTensor{} };
RadArgs ra = *a;
ra.t = rt; ra.n_t = 16; ra.p = rp.data(); ra.n_p = (int)rp.size();
return ref_gdn_recurrent_update(&ra, st);
}
+396
View File
@@ -0,0 +1,396 @@
/* ref_gemm.cpp -- the GEMM family and the two vocabulary edges.
*
* 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.
*
* 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).
*
* 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.
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.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) {
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);
}
}
}
/* 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);
}
}
}
typedef void (*PlainFn)(const Mat&, const Mat&, const RadTensor*, const RadTensor*,
int64_t, int64_t, int64_t, float);
#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; \
}
static PlainFn pick_plain(uint32_t da, uint32_t db) {
switch (da) {
REF_PLAIN_ROW(RAD_F32)
REF_PLAIN_ROW(RAD_F16)
REF_PLAIN_ROW(RAD_BF16)
REF_PLAIN_ROW(RAD_I8)
default: return nullptr;
}
}
#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>
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;
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);
}
}
}
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) {
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)
for (int64_t m = 0; m < M; ++m) {
float acc = quant_dot(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);
}
}
typedef void (*QuantFn)(const Mat&, const Mat&, const Scales&, const Scales&, const RadTensor*,
const RadTensor*, int64_t, int64_t, int64_t, float);
#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; \
}
static QuantFn pick_quant(uint32_t da, uint32_t db) {
switch (da) {
REF_QUANT_ROW(RAD_I8)
REF_QUANT_ROW(RAD_F8E4M3)
REF_QUANT_ROW(RAD_BF16)
REF_QUANT_ROW(RAD_F32)
default: return nullptr;
}
}
#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)));
}
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)
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 (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. */
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;
if (a->n_t < nt || !a->t[0].data || !a->t[1].data || !a->t[nt - 1].data) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[nt - 1];
const RadTensor* bias = bias_operand ? t_in(a, 2) : nullptr;
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;
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;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
if (res && numel(res) < M * N) return RAD_E_SHAPE;
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);
if (act || res) gemm_epilogue(Y, res, act, M, N);
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;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[nt - 1];
const RadTensor* as_ = t_in(a, 1);
const RadTensor* bs_ = t_in(a, 3);
const RadTensor* bias = bias_operand ? t_in(a, 4) : nullptr;
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);
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;
if (bias && numel(bias) < N) return RAD_E_SHAPE;
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. */
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);
return RAD_OK;
}
} /* namespace */
int ref_gemm_nt(const RadArgs* a, RadStream) {
return gemm_nt_impl(a, false, "N", "K");
}
int ref_gemm_nt_bias(const RadArgs* a, RadStream) {
return gemm_nt_impl(a, true, "N", "K");
}
int ref_gemm_nt_q(const RadArgs* a, RadStream) {
return gemm_ntq_impl(a, false);
}
int ref_gemm_nt_q_bias(const RadArgs* a, RadStream) {
return gemm_ntq_impl(a, true);
}
/* ------------------------------------------------------------------ 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. */
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.
*
* `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.
*
* 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];
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;
/* 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. */
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) : 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)
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);
}
return RAD_OK;
}
+247
View File
@@ -0,0 +1,247 @@
/* 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.
*
* Everything here is a pure reading of a RadTensor. No op, no dispatch, no allocation.
*/
#ifndef REF_GEMM_H
#define REF_GEMM_H
#include "ref_common.h"
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".
*
* `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.
*
* 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. */
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. */
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
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. */
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) {
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);
return m;
}
/* ------------------------------------------------------------------ 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 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. */
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 */
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);
}
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 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. */
static inline int64_t grid_block(int64_t ext, int64_t blocks) {
if (ext <= 0) return 1;
if (blocks <= 1) return ext;
const int64_t lo = (ext + blocks - 1) / blocks;
int64_t b = 1;
while (b < lo) b <<= 1;
return (ext + b - 1) / b == blocks ? b : lo;
}
static inline Scales make_scales(const RadTensor* s, int64_t rows, int64_t K, bool mxfp4_weight) {
Scales q{};
q.rblk = 1;
if (!s || !s->data || rows <= 0 || numel(s) <= 0) {
q.p = nullptr; q.group = K; q.dt = RAD_F32; return q;
}
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-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. */
int64_t groups = 0;
if (s->rank >= 2) {
const int64_t srows = s->shape[s->rank - 2];
q.rblk = srows >= rows ? 1 : grid_block(rows, srows);
groups = s->shape[s->rank - 1];
q.rs = s->stride[s->rank - 2];
q.cs = s->stride[s->rank - 1];
} else {
const int64_t nel = numel(s);
if (nel >= rows) {
groups = nel / rows;
q.rs = groups;
} else {
groups = 1;
q.rblk = grid_block(rows, nel);
q.rs = 1;
}
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. */
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.
*
* 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.
*
* `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.
*
* 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.
*/
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. */
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) {
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 += ld_dt(da, A.t->data, a0 + k * A.cs) * ld_dt(db, 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 += ld_dt(da, A.t->data, a0 + k * A.cs) * SA.at(m, k) *
ld_dt(db, B.t->data, b0 + k * B.cs);
acc += sub * sb;
}
}
return acc;
}
/* ------------------------------------------------------------------ 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.
*
* Returns entry `e` as a rank-(rank-1) tensor over 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{};
if (!w || !w->data || w->rank < 2 || e < 0 || e >= w->shape[0]) return t;
t.dtype = w->dtype;
t.rank = w->rank - 1;
for (uint32_t d = 0; d + 1 < w->rank; ++d) {
t.shape[d] = w->shape[d + 1];
t.stride[d] = w->stride[d + 1];
}
if (w->stride[0] == 0) {
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. */
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 */
t.data = (void*)((const char*)w->data + (nbits >> 3));
}
return t;
}
} /* namespace ref */
#endif /* REF_GEMM_H */
+421
View File
@@ -0,0 +1,421 @@
/* ref_hc.cpp -- the GATED RESIDUAL, which is Qwen4-Exp's replacement for a pre-norm and a
* residual add.
*
* ============================== 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.
*
* hc_read N = grouped_rmsnorm(h) one rsqrt per 2560 stream, one gain of
* 10240 over all four, `1 + w`
* g = sigmoid(W_up @ silu(W_down @ N / hc))
* x = mean_over_streams(g * N) the block's 2560 input
* 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 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.
*
* ============================== 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.
*
* 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).
*
* `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.
*/
#include "ref_common.h"
#include "ref_ops.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. */
int ref_hc_enter(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
const RadTensor* h = &a->t[1];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
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)
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);
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(x, xb + i * xs);
for (int64_t c = 0; c < hc; ++c) stt(h, hb + (c * n + i) * hs, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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;
const RadTensor* h = &a->t[0];
const RadTensor* w = &a->t[1];
const RadTensor* down = &a->t[2];
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* 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* rs = rad_arg_in(a, 10);
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
const int64_t lr = p_int(a, "lowrank", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0 || hc <= 1 || lr <= 0) return RAD_E_SHAPE;
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 (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. */
if (injw && (!inj || !inj->data || numel(inj) < rows * hc)) return RAD_E_SHAPE;
int64_t g = 0;
int64_t ngrp = 0;
if (q && q->data) {
g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
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. */
int64_t rg = 0;
if (rq) {
rg = p_int(a, "group", 0);
if (!pow2(rg) || n % rg != 0 || !rs || numel(rq) < rows * n || numel(rs) < rows * (n / rg))
return RAD_E_SHAPE;
if (rg > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
}
#pragma omp parallel for schedule(static)
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. */
std::vector<float> N((size_t)hn);
for (int64_t c = 0; c < hc; ++c) {
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(h, hb + (c * n + i) * hs);
ss += (double)v * (double)v;
}
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));
}
}
/* ---- the read gate: 10240 -> lowrank -> 10240, 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 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));
}
/* ---- the mix, and the mean 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 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];
}
stt(x, xb + i * xs, acc / (float)hc);
}
/* ---- the per-branch 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));
}
}
/* ---- the optional fp8 form of x, read back from what was stored. */
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);
}
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
/* ---- the 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;
for (int64_t gi = 0; gi < rgrp; ++gi) {
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);
}
stt(rs, rowoff(rs, r, rgrp) + gi * laststride(rs), sc);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
int ref_hc_write(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor* y = &a->t[0];
const RadTensor* inj = &a->t[1];
const RadTensor* h = &a->t[2];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
const int64_t hn = hc * n;
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)
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);
for (int64_t c = 0; c < hc; ++c) {
const float gain = ldt(inj, ib + c * is);
for (int64_t i = 0; i < n; ++i) {
const int64_t j = hb + (c * n + i) * hs;
stt(h, j, ldt(h, j) + gain * ldt(y, yb + i * ys));
}
}
}
return RAD_OK;
}
/* ================================================================== mtp_enter
*
* 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,
*
* 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`).
*
* rs_e = rsqrt(mean(e^2) + eps)
* ne[j] = e[j] * rs_e * (w_e[j] + wadd)
* fe[i] = sum_j fc_e[i][j] * ne[j]
* rs[k] = rsqrt(mean(h[k*n .. k*n+n)^2) + eps) -- `ngroup` == hc
* 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.
*
* `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.
*/
int ref_mtp_enter(const RadArgs* a, RadStream) {
if (!have(a, 7)) return RAD_E_INVAL;
const RadTensor* h = &a->t[0];
const RadTensor* e = &a->t[1];
const RadTensor* w_h = &a->t[2];
const RadTensor* w_e = &a->t[3];
const RadTensor* fc_h = &a->t[4];
const RadTensor* fc_e = &a->t[5];
const RadTensor* x = &a->t[6];
const int64_t n = p_int(a, "n", 0);
const int64_t hc = p_int(a, "hc", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
int64_t ngroup = p_int(a, "ngroup", hc);
if (n <= 0 || hc <= 1) return RAD_E_SHAPE;
if (ngroup != 1 && ngroup != hc) return RAD_E_SHAPE;
const int64_t hn = hc * n;
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;
#pragma omp parallel for schedule(static)
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. */
double ss = 0.0;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(e, eb + i * es);
ss += (double)v * (double)v;
}
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));
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 fs = laststride(fc_e);
for (int64_t j = 0; j < n; ++j) acc += ne[(size_t)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. */
float flat = 0.0f;
if (ngroup == 1) {
double sw = 0.0;
for (int64_t j = 0; j < hn; ++j) {
const float v = ldt(h, hb + j * hs);
sw += (double)v * (double)v;
}
flat = 1.0f / std::sqrt((float)(sw / (double)hn) + eps);
}
std::vector<float> nh((size_t)n);
for (int64_t c = 0; c < hc; ++c) {
float sc = flat;
if (ngroup != 1) {
double sk = 0.0;
for (int64_t i = 0; i < n; ++i) {
const float v = ldt(h, hb + (c * n + i) * hs);
sk += (double)v * (double)v;
}
sc = 1.0f / std::sqrt((float)(sk / (double)n) + eps);
}
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));
}
for (int64_t i = 0; i < n; ++i) {
float acc = 0.0f;
const int64_t fb = 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);
stt(x, xb + (c * n + i) * xs, acc + fe[(size_t)i]);
}
}
}
return RAD_OK;
}
+548
View File
@@ -0,0 +1,548 @@
/* ref_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-k.
*
* ============================== 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.
*
* 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.
*
* 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).
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include <algorithm>
#include <cstdlib>
#include <vector>
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. */
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];
const int64_t n_expert = p_int(a, "n_expert", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
const int64_t top_k = p_int(a, "top_k", 1);
const int norm = (int)p_int(a, "norm", 0);
if (n_expert <= 0 || top_k <= 0 || top_k > n_expert) return RAD_E_SHAPE;
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)
for (int64_t m = 0; m < M; ++m) {
const int64_t lb = rowoff(lg, m, n_expert), ls = laststride(lg);
float mx = -INFINITY;
for (int64_t e = 0; e < n_expert; ++e) {
float v = ldt(lg, lb + e * ls);
if (v > mx) mx = v;
}
float sum = 0.0f;
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. */
float pv = INFINITY;
int64_t pi = -1, kept = 0;
float wsum = 0.0f;
for (int64_t r = 0; r < top_k; ++r) {
if (!topk_next(lg, lb, ls, n_expert, &pv, &pi)) break;
const float p = ref_exp(pv - mx) * inv;
st_int(ids->dtype, ids->data, rowoff(ids, m, top_k) + r * laststride(ids), pi);
stt(w, rowoff(w, m, top_k) + r * laststride(w), p);
wsum += p;
++kept;
}
if (norm && wsum > 0.0f) {
const float n2 = 1.0f / wsum;
for (int64_t r = 0; r < kept; ++r) {
const int64_t off = rowoff(w, m, top_k) + r * laststride(w);
stt(w, off, ldt(w, off) * n2);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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). */
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;) {
char* end = nullptr;
const long long v = std::strtoll(c, &end, 10);
if (end == c || v < 0 || v >= n || (!prot.empty() && v <= prot.back())) return false;
prot.push_back(v);
c = end;
if (*c == ',') ++c;
else if (*c) return false;
}
place->assign((size_t)n, 0);
int64_t next = 0;
for (int64_t e = 0; e < n; ++e)
if (!std::binary_search(prot.begin(), prot.end(), e)) (*place)[(size_t)e] = next++;
for (size_t j = 0; j < prot.size(); ++j) (*place)[(size_t)prot[j]] = next++;
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. */
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. */
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;
const int64_t T = M * top_k;
if (M <= 0 || numel(sorted) < T) return RAD_E_SHAPE;
if (numel(off) < n_expert + 1 || numel(cnt) < n_expert) return RAD_E_SHAPE;
std::vector<int64_t> place;
if (!sort_places(p_str(a, "protect", nullptr), n_expert, &place)) return RAD_E_SHAPE;
/* A slot's place in the sort, or -1 for an expert outside this call's slice. */
auto at = [&](int64_t i) -> int64_t {
const int64_t e = ld_int(ids->dtype, ids->data, offlin(ids, i)) - base;
return (e < 0 || e >= n_expert) ? -1 : place[(size_t)e];
};
for (int64_t e = 0; e < n_expert; ++e) st_int(cnt->dtype, cnt->data, offlin(cnt, e), 0);
for (int64_t i = 0; i < T; ++i) {
const int64_t e = at(i);
if (e < 0) continue;
const int64_t o = offlin(cnt, e);
st_int(cnt->dtype, cnt->data, o, ld_int(cnt->dtype, cnt->data, o) + 1);
}
int64_t run = 0;
for (int64_t e = 0; e < n_expert; ++e) {
st_int(off->dtype, off->data, offlin(off, e), run);
run += ld_int(cnt->dtype, cnt->data, offlin(cnt, e));
}
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. */
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;
}
}
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.
*
* 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 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. */
static int moe_gemm_impl(const RadArgs* a, bool quant) {
const int n_opd = quant ? 9 : 5;
if (!have(a, n_opd)) return RAD_E_INVAL;
const RadTensor* A = &a->t[0];
const RadTensor* as_ = quant ? t_in(a, 1) : nullptr;
const RadTensor* W = &a->t[quant ? 2 : 1];
const RadTensor* ws_ = quant ? t_in(a, 3) : nullptr;
const RadTensor* sorted = &a->t[quant ? 4 : 2];
const RadTensor* off = &a->t[quant ? 5 : 3];
const RadTensor* Y = &a->t[quant ? 8 : 4];
/* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- and the
* plain arm's are one, which is the same walk with every expert in the first class. */
const RadTensor* W1 = quant ? &a->t[6] : W;
const RadTensor* ws1_ = quant ? t_in(a, 7) : nullptr;
const bool two = quant;
/* "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. */
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;
const int64_t N0 = p_int(a, "N", W->rank >= 3 ? W->shape[1] : 0);
const int64_t K0 = p_int(a, "K", W->rank >= 3 ? W->shape[2] : 0);
const int64_t N1 = two ? p_int(a, "N_odd", N0) : N0;
const int64_t K1 = two ? p_int(a, "K_odd", K0) : K0;
const int64_t parts = two ? p_int(a, "parts", 1) : 1;
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 (N0 <= 0 || K0 <= 0 || N1 <= 0 || K1 <= 0 || parts <= 0 || n_expert <= 0 || top_k <= 0)
return RAD_E_SHAPE;
if (N0 % parts || N1 % parts) return RAD_E_SHAPE;
/* The output is the wider class's width, the activation the longer class's K. */
const int64_t N = N0 > N1 ? N0 : N1, K = K0 > K1 ? K0 : K1;
const int64_t ne0 = two ? (n_expert + 1) / 2 : n_expert, ne1 = two ? n_expert / 2 : 0;
if (W->rank < 3 || W->shape[0] < ne0) return RAD_E_SHAPE;
if (two && (W1->rank < 3 || W1->shape[0] < ne1)) return RAD_E_SHAPE;
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. */
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 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;
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 / 2 of class e % 2 when there are two classes. */
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);
for (int64_t e = 0; e < n_expert; ++e) {
const bool odd = two && (e & 1);
const RadTensor* tw = odd ? W1 : W;
const RadTensor* ts = odd ? ws1_ : ws_;
const int64_t ix = two ? e / 2 : e;
const int64_t n = odd ? N1 : N0, k = odd ? K1 : K0;
en[(size_t)e] = n;
ek[(size_t)e] = k;
we[(size_t)e] = expert_entry(tw, ix);
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);
}
}
const int64_t fy = N / parts;
#pragma omp parallel for schedule(static)
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;
}
/* 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; }
const Mat& B = mw[(size_t)e];
const Scales& SB = SW[(size_t)e];
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);
}
}
return RAD_OK;
}
int ref_moe_gemm(const RadArgs* a, RadStream) { return moe_gemm_impl(a, false); }
int ref_moe_gemm_q(const RadArgs* a, RadStream) { return moe_gemm_impl(a, true); }
/* ------------------------------------------------------------------ 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.
*
* 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. */
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. */
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;
/* The shared arm, folded: y = bf16(shared * act(gate)) + bf16(gathered). A pair or neither. */
const RadTensor *sh = t_in(a, 3), *sg = t_in(a, 4);
if ((sh != nullptr) != (sg != nullptr)) return RAD_E_INVAL;
const char* const act = p_str(a, "act", "none");
const bool sig = act && !std::strcmp(act, "sigmoid");
if (sh && act && std::strcmp(act, "sigmoid") && std::strcmp(act, "none")) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (n <= 0 || top_k <= 0) return RAD_E_SHAPE;
const int64_t M = numel(Y) / n;
const int64_t T = M * top_k;
if (M <= 0 || numel(sorted) < T || numel(ew) < T || numel(ye) < T * n) return RAD_E_SHAPE;
enum { INV_MAX = 4096 };
const int64_t tb = INV_MAX / top_k > 0 ? INV_MAX / top_k : 1;
const int64_t nblk = (M + tb - 1) / tb;
const int64_t ye_rs = ye->rank >= 2 ? ye->stride[ye->rank - 2] : n;
const int64_t ye_cs = ye->rank >= 2 ? ye->stride[ye->rank - 1] : 1;
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)
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;
const int64_t span = (t1 - t0) * top_k;
for (int64_t i = 0; i < span; ++i) inv[i] = -1;
for (int64_t i = 0; i < T; ++i) {
const int64_t f = ld_int(sorted->dtype, sorted->data, offlin(sorted, i));
if (f < t0 * top_k || f >= t1 * top_k) continue;
inv[f - t0 * top_k] = (int32_t)i;
}
for (int64_t t = t0; t < t1; ++t) {
float gate = 0.0f;
if (sh) {
const float v0 = ldt(sg, rowoff(sg, t, 1));
gate = sig ? act_sigmoid(v0) : v0;
}
for (int64_t c = 0; c < n; ++c) {
float acc = 0.0f;
for (int64_t j = 0; j < top_k; ++j) {
const int32_t i = inv[(t - t0) * top_k + j];
if (i < 0) continue;
acc += ldt(ew, rowoff(ew, t, top_k) + j * laststride(ew)) *
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. */
stt(Y, yo, acc);
if (!sh) continue;
const float g = ldt(Y, yo);
stt(Y, yo, ldt(sh, rowoff(sh, t, n) + c * laststride(sh)) * gate);
stt(Y, yo, ldt(Y, yo) + g);
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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. */
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);
const int64_t R = p_int(a, "R", 1);
if (N <= 0 || R <= 0) return RAD_E_SHAPE;
const int64_t M = numel(x) / N;
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)
for (int64_t m = 0; m < M; ++m) {
const int64_t xb = rowoff(x, m, N), xs = laststride(x);
float pv = INFINITY;
int64_t pi = -1;
for (int64_t r = 0; r < R; ++r) {
const bool ok = topk_next(x, xb, xs, N, &pv, &pi);
const int64_t id = ok ? pi + off : -1;
st_int(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx), id);
stt(val, rowoff(val, m, R) + r * laststride(val), ok ? pv : -INFINITY);
if (pairs) {
float* const q = (float*)pairs->data + (m * R + r) * 2;
const int32_t i32 = (int32_t)id;
std::memcpy(q, &i32, sizeof i32);
q[1] = ok ? pv : -INFINITY;
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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.
*
* 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.
*
* 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. */
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. */
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)
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. */
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; }
}
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);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ logit_rerank */
/* EXACTLY RESCORE R CANDIDATES A ROW 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.
*
* 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, 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. */
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];
const RadTensor *idx = &a->t[3], *val = &a->t[4];
const RadTensor *pairs = (a->n_t > 5 && a->t[5].data) ? &a->t[5] : nullptr;
const int64_t R = p_int(a, "R", 1);
const int64_t K = p_int(a, "n_embd", 0);
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. */
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;
#pragma omp parallel for schedule(static)
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 */
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);
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 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;
st_int(idx->dtype, idx->data, rowoff(idx, m, R) + o * laststride(idx), (int64_t)oid);
stt(val, rowoff(val, m, R) + o * laststride(val), ov);
if (pairs) {
float* p = (float*)pairs->data + (m * R + o) * 2;
std::memcpy(p, &oid, sizeof oid);
p[1] = ov;
}
}
}
return RAD_OK;
}
+267
View File
@@ -0,0 +1,267 @@
/* ref_ngram.cpp -- the n-gram row ids of Qwen4-Exp's Per-Layer Embedding (PLE).
*
* ============================== 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.
*
* 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.
*
* ============================== TWO THINGS THAT LOOK LIKE TRAPS AND ARE NOT ==================
*
* 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 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:
*
* 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.
*
* ============================== 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.
*
* 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.
*
* 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.
*/
#include "ref_common.h"
#include "ref_ops.h"
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. */
inline int64_t wrap_mul(int64_t a, int64_t b) {
return (int64_t)((uint64_t)a * (uint64_t)b);
}
inline int64_t floor_mod(int64_t a, int64_t b) { /* b > 0 */
const int64_t r = a % b;
return r < 0 ? r + b : r;
}
} // namespace
/* ids[m][h] = (hash of the ngram ending at m) % vocab[h] + offset[h].
*
* tok [M] i32/i64 the step's token ids, sequences back to back
* state [n_slots][W] i32 inout: a rolling window of committed ids, W = ctx +
* n_spec, slot i holding the id at relative position
* i - ctx from the step's first row
* cu [n_seq+1] i32
* mult [ngram] i64 w
* 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
* 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
* 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. */
if (a->n_t < 10) return RAD_E_INVAL;
const RadTensor* tok = t_in(a, 0);
const RadTensor* st = t_in(a, 1);
const RadTensor* cu = t_in(a, 2);
const RadTensor* mult = t_in(a, 3);
const RadTensor* vsz = t_in(a, 4);
const RadTensor* off_ = t_in(a, 5);
const RadTensor* sidx = t_in(a, 6); /* optional */
const RadTensor* hini = t_in(a, 7); /* optional */
const RadTensor* nacc = t_in(a, 8); /* optional */
const RadTensor* ids = t_in(a, 9);
const RadTensor* ahead = a->n_t > 10 ? t_in(a, 10) : nullptr; /* optional */
if (!tok || !st || !cu || !mult || !vsz || !off_ || !ids) return RAD_E_INVAL;
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. */
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 (heads % (ngram - 1)) return RAD_E_SHAPE;
const int64_t per = heads / (ngram - 1);
const int64_t ctx = ngram - 1;
if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window lives in a stack frame */
if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE;
if (numel(ids) < M * heads) 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. */
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 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;
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. */
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. */
auto hist = [&](int64_t p) -> int64_t {
return p < ctx ? prev[p] : ld_int(tok->dtype, tok->data, offlin(tok, bos + p - ctx));
};
/* The last sequence runs on into the prompt that follows, whose ids land in `ahead`. */
const int64_t reach = T + (ahead && s + 1 == n_seq ? A : 0);
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. */
int64_t sh[8];
sh[0] = hist(p);
bool cut = false;
for (int64_t k = 1; k < ngram; ++k) {
if (cut || sh[k - 1] == eos) { cut = true; sh[k] = eos; continue; }
sh[k] = hist(p - k);
}
/* 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. */
int64_t mixed = 0;
int64_t blk = -1;
for (int64_t k = 0; k < ngram; ++k) {
const int64_t term = wrap_mul(sh[k], ld_int(mult->dtype, mult->data, k));
mixed = k == 0 ? term : (mixed ^ term);
if (k == 0) continue; /* a 1-gram addresses no head */
++blk; /* k = 1 is the 2-gram block, k = 2 the 3-gram */
for (int64_t j = 0; j < per; ++j) {
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);
else
st_int(ahead->dtype, ahead->data, (t - T) * ahd_ld + h,
floor_mod(mixed, v) + ofh);
}
}
}
/* 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. */
const int64_t base = rowoff(st, slot, W);
if (nacc) {
for (int64_t i = 0; i + 1 < ctx; ++i)
st_int(st->dtype, st->data, base + i, prev[i + 1]);
for (int64_t t = 0; t < T; ++t)
st_int(st->dtype, st->data, base + ctx - 1 + t,
ld_int(tok->dtype, tok->data, offlin(tok, bos + t)));
} else {
for (int64_t i = 0; i < ctx; ++i) {
const int64_t src = T - ctx + i;
const int64_t v = src >= 0 ? ld_int(tok->dtype, tok->data, offlin(tok, bos + src))
: prev[src + ctx];
st_int(st->dtype, st->data, base + i, v);
}
}
}
return RAD_OK;
}
+265
View File
@@ -0,0 +1,265 @@
/* 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 ==============================
*
* 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:
*
* * 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.
*
* ============================== THE PAGED KV LAYOUT ==============================
*
* This is libr4d's and every kernel in the project has to match it, so it is written here once:
*
* 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.
*
* ============================== 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:
*
* 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.
* 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.
*
* 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.
*
* 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.
*/
#ifndef RAD_REF_OPS_H
#define RAD_REF_OPS_H
#include "rad_abi.h"
extern "C" {
/* ---- elementwise and norms */
int ref_rmsnorm (const RadArgs*, RadStream);
int ref_rmsnorm_add (const RadArgs*, RadStream);
int ref_hc_enter (const RadArgs*, RadStream);
int ref_hc_read (const RadArgs*, RadStream);
int ref_hc_write (const RadArgs*, RadStream);
int ref_mtp_enter (const RadArgs*, RadStream);
int ref_layernorm (const RadArgs*, RadStream);
int ref_grid_embed (const RadArgs*, RadStream);
int ref_add (const RadArgs*, RadStream);
int ref_mul (const RadArgs*, RadStream);
int ref_silu_mul (const RadArgs*, RadStream);
int ref_gelu (const RadArgs*, RadStream);
int ref_silu (const RadArgs*, RadStream);
int ref_sigmoid (const RadArgs*, RadStream);
int ref_gather_rows (const RadArgs*, RadStream);
int ref_scatter_rows (const RadArgs*, RadStream);
int ref_ngram_ids (const RadArgs*, RadStream);
int ref_ple_gate (const RadArgs*, RadStream);
int ref_ple_conv (const RadArgs*, RadStream);
int ref_cast (const RadArgs*, RadStream);
int ref_softmax (const RadArgs*, RadStream);
/* ---- quantisation and rotation */
int ref_quant_act_i8 (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);
int ref_rmsnorm_quant_fp8 (const RadArgs*, RadStream);
int ref_gated_quant_fp8 (const RadArgs*, RadStream);
int ref_gemm_nt_q_gated (const RadArgs*, RadStream);
int ref_dflash_select (const RadArgs*, RadStream);
int ref_gram_accum (const RadArgs*, RadStream);
int ref_rmsnorm_had_quant_i8(const RadArgs*, RadStream);
int ref_gated_had_quant_i8 (const RadArgs*, RadStream);
int ref_dequant (const RadArgs*, RadStream);
/* ---- gemm and the vocabulary edges */
int ref_gemm_nt (const RadArgs*, RadStream);
int ref_gemm_nt_bias (const RadArgs*, RadStream);
int ref_gemm_nt_q (const RadArgs*, RadStream);
int ref_gemm_nt_q_bias (const RadArgs*, RadStream);
int ref_embed_lookup (const RadArgs*, RadStream);
int ref_embed_lookup_q (const RadArgs*, RadStream);
int ref_logits_gemm (const RadArgs*, RadStream);
/* ---- attention */
int ref_attn_paged (const RadArgs*, RadStream);
int ref_attn_dense (const RadArgs*, RadStream);
int ref_kv_store (const RadArgs*, RadStream);
int ref_rope (const RadArgs*, RadStream);
int ref_rope_table (const RadArgs*, RadStream);
int ref_qk_norm_rope (const RadArgs*, RadStream);
/* ---- mixture of experts */
int ref_router_topk (const RadArgs*, RadStream);
int ref_moe_scatter (const RadArgs*, RadStream);
int ref_moe_gemm (const RadArgs*, RadStream);
int ref_moe_gemm_q (const RadArgs*, RadStream);
int ref_scale_rows (const RadArgs*, RadStream);
int ref_moe_gather (const RadArgs*, RadStream);
int ref_row_topk (const RadArgs*, RadStream);
int ref_row_topk_merge (const RadArgs*, RadStream);
int ref_logit_rerank (const RadArgs*, RadStream);
/* ---- gated delta net */
int ref_gdn_conv_prep (const RadArgs*, RadStream);
int ref_gdn_conv_update (const RadArgs*, RadStream);
int ref_gdn_kkt_solve (const RadArgs*, RadStream);
int ref_gdn_chunk_scan (const RadArgs*, RadStream);
int ref_gdn_recurrent_update(const RadArgs*, RadStream);
int ref_gdn_conv_recurrent_update(const RadArgs*, RadStream);
int ref_gdn_gated_rmsnorm (const RadArgs*, RadStream);
/* ---- collectives */
int ref_all_reduce (const RadArgs*, RadStream);
int ref_all_gather (const RadArgs*, RadStream);
int64_t ref_all_reduce_scratch(const RadArgs*);
int ref_collective_init(const RadParam*, int, int, int, void**);
void ref_collective_fini(void*);
/* ---- sampling */
int ref_sample_penalties (const RadArgs*, RadStream);
int ref_sample_dry (const RadArgs*, RadStream);
int ref_sample_temp (const RadArgs*, RadStream);
int ref_sample_topk (const RadArgs*, RadStream);
int ref_sample_topp (const RadArgs*, RadStream);
int ref_sample_minp (const RadArgs*, RadStream);
int ref_sample_typical (const RadArgs*, RadStream);
int ref_sample_xtc (const RadArgs*, RadStream);
int ref_sample_merge_topk (const RadArgs*, RadStream);
int ref_sample_mask (const RadArgs*, RadStream);
int ref_sample_pick (const RadArgs*, RadStream);
int ref_sample_argmax (const RadArgs*, RadStream);
/* ============================== 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.
*
* 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. */
#define REF_SHAPE_FN(fn) \
int fn##_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out)
REF_SHAPE_FN(ref_rmsnorm);
REF_SHAPE_FN(ref_rmsnorm_add);
REF_SHAPE_FN(ref_hc_enter);
REF_SHAPE_FN(ref_hc_read);
REF_SHAPE_FN(ref_hc_write);
REF_SHAPE_FN(ref_mtp_enter);
REF_SHAPE_FN(ref_layernorm);
REF_SHAPE_FN(ref_grid_embed);
REF_SHAPE_FN(ref_add);
REF_SHAPE_FN(ref_mul);
REF_SHAPE_FN(ref_silu_mul);
REF_SHAPE_FN(ref_gelu);
REF_SHAPE_FN(ref_silu);
REF_SHAPE_FN(ref_sigmoid);
REF_SHAPE_FN(ref_gather_rows);
REF_SHAPE_FN(ref_scatter_rows);
REF_SHAPE_FN(ref_ngram_ids);
REF_SHAPE_FN(ref_ple_gate);
REF_SHAPE_FN(ref_ple_conv);
REF_SHAPE_FN(ref_cast);
REF_SHAPE_FN(ref_softmax);
REF_SHAPE_FN(ref_quant_act_i8);
REF_SHAPE_FN(ref_had_quant_act_i8);
REF_SHAPE_FN(ref_quant_act_fp8);
REF_SHAPE_FN(ref_had_quant_act_fp8);
REF_SHAPE_FN(ref_rmsnorm_quant_fp8);
REF_SHAPE_FN(ref_gated_quant_fp8);
REF_SHAPE_FN(ref_gemm_nt_q_gated);
REF_SHAPE_FN(ref_dflash_select);
REF_SHAPE_FN(ref_gram_accum);
REF_SHAPE_FN(ref_rmsnorm_had_quant_i8);
REF_SHAPE_FN(ref_gated_had_quant_i8);
REF_SHAPE_FN(ref_dequant);
REF_SHAPE_FN(ref_gemm_nt);
REF_SHAPE_FN(ref_gemm_nt_bias);
REF_SHAPE_FN(ref_gemm_nt_q);
REF_SHAPE_FN(ref_gemm_nt_q_bias);
REF_SHAPE_FN(ref_embed_lookup);
REF_SHAPE_FN(ref_embed_lookup_q);
REF_SHAPE_FN(ref_logits_gemm);
REF_SHAPE_FN(ref_attn_paged);
REF_SHAPE_FN(ref_attn_dense);
REF_SHAPE_FN(ref_kv_store);
REF_SHAPE_FN(ref_rope);
REF_SHAPE_FN(ref_rope_table);
REF_SHAPE_FN(ref_qk_norm_rope);
REF_SHAPE_FN(ref_router_topk);
REF_SHAPE_FN(ref_moe_scatter);
REF_SHAPE_FN(ref_moe_gemm);
REF_SHAPE_FN(ref_moe_gemm_q);
REF_SHAPE_FN(ref_scale_rows);
REF_SHAPE_FN(ref_moe_gather);
REF_SHAPE_FN(ref_row_topk);
REF_SHAPE_FN(ref_row_topk_merge);
REF_SHAPE_FN(ref_logit_rerank);
REF_SHAPE_FN(ref_gdn_conv_prep);
REF_SHAPE_FN(ref_gdn_conv_update);
REF_SHAPE_FN(ref_gdn_kkt_solve);
REF_SHAPE_FN(ref_gdn_chunk_scan);
REF_SHAPE_FN(ref_gdn_recurrent_update);
REF_SHAPE_FN(ref_gdn_conv_recurrent_update);
REF_SHAPE_FN(ref_gdn_gated_rmsnorm);
REF_SHAPE_FN(ref_all_reduce);
REF_SHAPE_FN(ref_all_gather);
REF_SHAPE_FN(ref_sample_penalties);
REF_SHAPE_FN(ref_sample_dry);
REF_SHAPE_FN(ref_sample_temp);
REF_SHAPE_FN(ref_sample_topk);
REF_SHAPE_FN(ref_sample_topp);
REF_SHAPE_FN(ref_sample_minp);
REF_SHAPE_FN(ref_sample_typical);
REF_SHAPE_FN(ref_sample_xtc);
REF_SHAPE_FN(ref_sample_merge_topk);
REF_SHAPE_FN(ref_sample_mask);
REF_SHAPE_FN(ref_sample_pick);
REF_SHAPE_FN(ref_sample_argmax);
} /* extern "C" */
#endif /* RAD_REF_OPS_H */
+347
View File
@@ -0,0 +1,347 @@
/* 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 ==============================
*
* 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:
*
* 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
* 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
* 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.
*
* ============================== 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.
*
* 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.
*
* ============================== ONE OP AND 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.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include <cmath>
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. */
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) {
const double v = ldt(x, base + d * stride);
acc += v * v;
}
return (float)(1.0 / std::sqrt(acc / (double)n + (double)eps));
}
} /* namespace */
/* 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
* 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
* gvn [M][hc*n] out, normed: what the convolution reads
*/
int ref_ple_gate(const RadArgs* a, RadStream) {
if (!have(a, 8)) return RAD_E_INVAL;
const RadTensor* k = t_in(a, 0);
const RadTensor* q = t_in(a, 1);
const RadTensor* v = t_in(a, 2);
const RadTensor* wk = t_in(a, 3);
const RadTensor* wq = t_in(a, 4);
const RadTensor* wc = t_in(a, 5);
const RadTensor* gv = t_in(a, 6);
const RadTensor* gvn = t_in(a, 7);
if (!k || !q || !v || !wk || !wq || !wc || !gv || !gvn) return RAD_E_INVAL;
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. */
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. */
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;
if (numel(k) < M * hn || numel(q) < M * hn || numel(v) < M * n) return RAD_E_SHAPE;
if (numel(wk) < hn || numel(wq) < hn || numel(wc) < hn) return RAD_E_SHAPE;
if (numel(gv) < M * hn || numel(gvn) < M * hn) return RAD_E_SHAPE;
const int64_t kls = laststride(k), qls = laststride(q), vls = laststride(v);
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)
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. */
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));
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). */
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)));
}
/* 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. */
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)));
}
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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))`.
*
* ============================== THE DILATION IS THE WHOLE DIFFERENCE ==============================
*
* 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]`.
*
* 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.
*
* ============================== 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).
*
* `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.
*
* ============================== WHAT THE WINDOW HOLDS 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:
*
* PRESENT -- a decode step of `slen` tokens, any of which past the first a verify may reject.
* 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.
*
* 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.
*/
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. */
if (a->n_t < 9) return RAD_E_INVAL;
const RadTensor* x = t_in(a, 0);
const RadTensor* w = t_in(a, 1);
const RadTensor* cs = t_in(a, 2);
const RadTensor* cu = t_in(a, 3);
const RadTensor* resid = t_in(a, 4); /* optional */
const RadTensor* sidx = t_in(a, 5); /* optional */
const RadTensor* hini = t_in(a, 6); /* optional */
const RadTensor* nacc = t_in(a, 7); /* optional */
const RadTensor* y = t_in(a, 8);
if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL;
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. */
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. */
enum { kHistMax = 64 };
if (hist_len > kHistMax) return RAD_E_UNSUPPORTED;
const int64_t N = numel(cu) - 1;
if (N <= 0) return RAD_E_SHAPE;
if (numel(x) < M * n || numel(y) < M * n || numel(w) < n * wid) return RAD_E_SHAPE;
if (resid && numel(resid) < M * n) return RAD_E_SHAPE;
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. */
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));
if (nacc && cs->data && hist_len > 0 && slen > 0 && hist_len - 1 + slen > state_len)
return RAD_E_SHAPE;
}
const int64_t xrow = rowoff(x, 1, n), xcol = laststride(x);
const int64_t yrow = rowoff(y, 1, n), ycol = laststride(y);
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;
#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;
/* 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. */
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;
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;
for (int64_t t = 0; t < slen; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < wid; ++j) {
const int64_t src = t - hist_len + j * dil;
const float v = src >= 0 ? ldt(x, (bos + src) * xrow + c * xcol)
: hist[src + hist_len];
acc += v * ldt(w, c * wrow + j * wcol);
}
const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f;
stt(y, (bos + t) * yrow + c * ycol, r + act_silu(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]);
}
}
}
return RAD_OK;
}
+761
View File
@@ -0,0 +1,761 @@
/* 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 ==============================
*
* 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 `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 ==============================
*
* 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.
*/
#include "ref_common.h"
#include "ref_gemm.h" /* Mat and Scales: gemm_nt_q_gated reads a quantised operand the same way */
#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 */
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 int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) 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), 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);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ had_quant_act_i8 */
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];
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
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;
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)
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);
}
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.
*
* `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.
*
* `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. */
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];
const RadTensor* res = t_in(a, 1);
const RadTensor* ob = t_in(a, 5);
if (!x->data || !w->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const int64_t g = p_int(a, "group", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
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;
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)
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);
/* The residual add, written back before anything reads it, so what follows reads the
* narrowed sum rather than the f32 one. */
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; }
const float sc = 1.0f / std::sqrt(ss / (float)n + eps);
if (ob) {
const int64_t obb = rowoff(ob, r, n), obs = laststride(ob);
for (int64_t i = 0; i < n; ++i)
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);
}
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.
*
* `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. */
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];
const RadTensor* up = t_in(a, 1);
if (!ga->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, (int)p_int(a, "mode", 0));
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
if (act != 0 && act != 1) return RAD_E_INVAL;
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
const int64_t rows = numel(q) / n;
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)
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 ub = up ? rowoff(up, r, n) : 0;
const int64_t us = up ? laststride(up) : 0;
auto gated = [&](int64_t i) {
const float gate = ldt(ga, gb + i * gs);
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);
}
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. */
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];
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(y) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
const int64_t ngrp = numel(s) / rows > 0 ? numel(s) / rows : 1;
int64_t g = p_int(a, "group", 0);
if (g <= 0) g = (n + ngrp - 1) / ngrp;
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
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);
for (int64_t i = 0; i < n; ++i) {
const int64_t gi = g > 0 ? i / g : 0;
const float sc = ldt(s, sb + (gi < ngrp ? gi : ngrp - 1) * ss);
stt(y, yb + i * ys, ldt(q, qb + i * qs) * sc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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 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, 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.
*/
int ref_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);
if (n <= 0) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
if (numel(s) < rows * ngrp) 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), 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);
}
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------- 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 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.
*
* 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. */
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. */
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;
const int64_t ngrp = n / g;
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)
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);
for (int64_t gi = 0; gi < ngrp; ++gi) {
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);
}
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
return RAD_OK;
}
/* ---------------------------------------------------------------- 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.
*
* 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.
*
* 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. */
int ref_gram_accum(const RadArgs* a, RadStream) {
/* `a_scale` is optional: absent, `a` is read as it stands, which 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;
const int64_t n = p_int(a, "n", 0);
const int64_t g = p_int(a, "group", 0);
if (n <= 0 || (s && g <= 0)) return RAD_E_SHAPE;
const int64_t rows = numel(x) / n;
const int64_t ngrp = s ? (n + g - 1) / g : 0;
if (rows <= 0 || (s && numel(s) < rows * ngrp)) return RAD_E_SHAPE;
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)
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;
for (int64_t k = 0; k < n; ++k)
xs[(size_t)r * (size_t)n + (size_t)k] =
ldt(x, xb + k * xst) * (s ? ldt(s, sb + (k / g) * sst) : 1.0f);
}
const int64_t hst = laststride(h);
#pragma omp parallel for schedule(static)
for (int64_t k1 = 0; k1 < n; ++k1) {
const int64_t hb = rowoff(h, k1, n);
for (int64_t k2 = 0; k2 < n; ++k2) {
double acc = 0.0;
for (int64_t r = 0; r < rows; ++r)
acc += (double)xs[(size_t)r * (size_t)n + (size_t)k1] *
(double)xs[(size_t)r * (size_t)n + (size_t)k2];
const int64_t off = hb + k2 * hst;
stt(h, off, (float)((double)ldt(h, off) + acc));
}
}
return RAD_OK;
}
/* ======================================================================== 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, `RADIANCE_HOST_DOMAIN` -- 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").
*
* 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.
*/
/* 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. */
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);
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);
}
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
}
}
/* ------------------------------------------------------------- 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.
*/
int ref_rmsnorm_quant_fp8(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];
const RadTensor* res = t_in(a, 1);
const RadTensor* ob = t_in(a, 5);
if (!x->data || !w->data || !q->data || !s->data) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", w->rank ? w->shape[w->rank - 1] : 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
if (n <= 0) return RAD_E_SHAPE;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t rows = numel(x) / n;
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp || 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;
#pragma omp parallel for schedule(static)
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);
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 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. */
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) {
const uint16_t h = f32_to_bf16(src(i) * rs * (ldt(w, i * ws) + wadd));
if (ob) stt(ob, obb + i * obs, bf16_to_f32(h));
v[(size_t)i] = bf16_to_f32(h);
}
fp8_row(v.data(), n, g, q, s, r);
}
return RAD_OK;
}
/* ------------------------------------------------------------- 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. */
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];
const RadTensor* ob = t_in(a, 3);
const int64_t n = p_int(a, "n", 0);
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, (int)p_int(a, "mode", 0));
if (n <= 0) return RAD_E_SHAPE;
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t rows = numel(gu) / (2 * n);
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)
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);
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) {
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 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);
}
fp8_row(v.data(), n, g, q, s, r);
}
return RAD_OK;
}
/* ------------------------------------------------------------- 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.
*
* 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.
*
* 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.
*
* 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. */
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];
const RadTensor* as_ = t_in(a, 1);
const RadTensor* bs_ = t_in(a, 3);
const RadTensor* ob = t_in(a, 6);
if (!A->data || !B->data || !q->data || !s->data) return RAD_E_INVAL;
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);
if (K <= 0 || N <= 0 || (N & 1)) return RAD_E_SHAPE;
const int64_t n = N / 2;
static const char* kActs[] = { "silu", "sigmoid" };
const int act = p_enum(a, "act", kActs, 2, -1);
if (act != 0 && act != 1) return RAD_E_INVAL;
int64_t g = p_int(a, "group", 0);
if (g <= 0 || g > n) g = n;
const int64_t ngrp = (n + g - 1) / g;
const int64_t M = numel(q) / n;
if (M <= 0 || numel(A) < M * K || numel(B) < N * K) return RAD_E_SHAPE;
if (numel(s) < M * ngrp) return RAD_E_SHAPE;
if (ob && numel(ob) < M * n) return RAD_E_SHAPE;
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);
#pragma omp parallel for schedule(static)
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. */
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 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);
}
fp8_row(v.data(), n, g, q, s, m);
}
return RAD_OK;
}
/* ------------------------------------------------------------- dflash_select */
/* `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.
*
* 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.
*
* 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. */
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];
const RadTensor *pred = &a->t[4], *succ = &a->t[5], *out = &a->t[6];
const RadTensor* hp = t_in(a, 2);
if (!cand->data || !un->data || !anc->data || !pred->data || !succ->data || !out->data)
return RAD_E_INVAL;
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. */
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);
const int64_t nv = p_int(a, "n_vocab", pred->rank >= 2 ? pred->shape[pred->rank - 2] : 0);
const int64_t astr = p_int(a, "anchor_stride", 1);
if (M <= 0 || steps <= 0 || K <= 0 || R <= 0 || nv <= 0 || astr <= 0) return RAD_E_SHAPE;
if (numel(un) < M * steps * K) return RAD_E_SHAPE;
if (numel(anc) < (M - 1) * astr + 1 || numel(out) < M * steps) return RAD_E_SHAPE;
if (numel(pred) < nv * R || numel(succ) < nv * R) return RAD_E_SHAPE;
if (hp && numel(hp) < M * steps * R) return RAD_E_SHAPE;
const int64_t cs = laststride(cand), us = laststride(un), os = laststride(out);
const int64_t ps = laststride(pred), sxs = laststride(succ);
const int64_t hs = hp ? laststride(hp) : 1;
#pragma omp parallel for schedule(static)
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));
for (int64_t l = 0; l < steps; ++l) {
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. */
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) *
(hp ? ldt(hp, hb + i * hs) : 1.0f);
int64_t best_c = 0;
float best_s = -INFINITY;
for (int64_t c = 0; c < K; ++c) {
const int64_t tok = ld_int(cand->dtype, cand->data, cb + c * cs);
float sc = ldt(un, ub + c * us);
if (tok >= 0 && tok < nv) {
const int64_t sb = rowoff(succ, tok, R);
for (int64_t i = 0; i < R; ++i) sc += ax[(size_t)i] * ldt(succ, sb + i * sxs);
}
if (sc > best_s) { best_s = sc; best_c = c; }
}
pid = ld_int(cand->dtype, cand->data, cb + best_c * cs);
st_int(out->dtype, out->data, rowoff(out, m, steps) + l * os, pid);
}
}
return RAD_OK;
}
File diff suppressed because it is too large. Load diff
+699
View File
@@ -0,0 +1,699 @@
/* 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.
*
* ============================== 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.
*
* 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.
*
* `seed` and `pos` are fields of the row for the same reason, rather than two more operands of
* `sample_pick`.
*
* ============================== THE CANDIDATE SET ==============================
*
* `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.
*
* `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.
*/
#include "ref_common.h"
#include "ref_ops.h"
#include "rad_sample.h"
#include <cfloat>
#include <unordered_map>
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. */
struct Rows {
const RadSampleParams* p;
int64_t n;
};
static inline int rows_of(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. */
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;
out->n = M;
return RAD_OK;
}
} /* 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. */
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;
int64_t hl = sp.hist_len;
int64_t ho = sp.hist_off < 0 ? 0 : sp.hist_off;
if (ho > hmax) ho = hmax;
if (hl > hmax - ho) hl = hmax - ho;
if (last_n > 0 && hl > last_n) {
ho += hl - last_n;
hl = last_n;
}
*ho_out = ho;
*hl_out = hl;
return hl > 0;
}
/* ------------------------------------------------------------------ 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)
* 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 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. */
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];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(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)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_PENALTY)) continue;
const float rep = sp.rep_penalty, freq = sp.freq_penalty, pres = sp.pres_penalty;
if (rep == 1.0f && freq == 0.0f && pres == 0.0f) continue;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.penalty_last_n, hmax, &ho, &hl)) continue;
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
for (int64_t i = 0; i < hl; ++i) {
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. */
bool first = true;
int64_t count = 0;
for (int64_t j = 0; j < hl; ++j) {
const int64_t t2 = ld_int(hist->dtype, hist->data, hb + j * hs);
if (t2 != tok) continue;
if (j < i) { first = false; break; }
++count;
}
if (!first) continue;
float v = ldt(lg, lb + col * ls);
v = v > 0.0f ? v / rep : v * rep;
v -= (float)count * freq;
v -= pres;
stt(lg, lb + col * ls, v);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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):
*
* 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.
*
* 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.
*
* 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. */
static inline float dry_penalty(float multiplier, float base, int64_t e) {
float pen = multiplier;
if (base == 1.0f) return pen;
const float lim = FLT_MAX / base;
for (int64_t i = 0; i < e; ++i) {
if (pen > lim) break;
pen *= base;
}
return pen;
}
int ref_sample_dry(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];
const RadTensor* brk = t_in(a, 3);
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(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. */
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)
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;
const int64_t allowed = sp.dry_allowed_length > 0 ? sp.dry_allowed_length : 2;
int64_t ho = 0, hl = 0;
if (!hist_window(sp, sp.dry_penalty_last_n, hmax, &ho, &hl)) continue;
if (hl <= allowed) continue;
const int64_t cap = sp.dry_rep_limit > 0 && sp.dry_rep_limit < hl ? sp.dry_rep_limit : hl;
if (cap < allowed) continue;
const int64_t hb = rowoff(hist, m, hmax) + ho * laststride(hist);
const int64_t hs = laststride(hist);
const int64_t bb = brk ? rowoff(brk, m, hmax) + ho * laststride(brk) : 0;
const int64_t bs = brk ? laststride(brk) : 0;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
auto tok_at = [&](int64_t i) {
return ld_int(hist->dtype, hist->data, hb + i * hs);
};
auto exempt = [&](int64_t i) {
return brk && ld_int(brk->dtype, brk->data, bb + i * bs) != 0;
};
/* The longest repeat each continuation token would extend. */
std::unordered_map<int64_t, int64_t> longest;
for (int64_t j = 0; j + 1 < hl; ++j) {
const int64_t lim = j + 1 < cap ? j + 1 : cap;
int64_t n = 0;
while (n < lim && tok_at(j - n) == tok_at(hl - 1 - n)) ++n;
if (n < allowed || exempt(j + 1)) continue;
const int64_t next = tok_at(j + 1);
const int64_t col = next - voff;
if (next < 0 || col < 0 || col >= n_vocab) continue;
int64_t& L = longest[next];
if (n > L) L = n;
}
const float base = sp.dry_base > 0.0f ? sp.dry_base : 1.75f;
for (const auto& e : longest) {
const int64_t off = lb + (e.first - voff) * ls;
stt(lg, off, ldt(lg, off) - dry_penalty(sp.dry_multiplier, base, e.second - allowed));
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(pr, M, &R));
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const float t = R.p[m].temp;
if (!(t > 0.0f) || t == 1.0f) continue;
const float inv = 1.0f / t;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
for (int64_t i = 0; i < n_vocab; ++i) stt(lg, lb + i * ls, ldt(lg, lb + i * ls) * inv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_topk */
int ref_sample_topk(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *pr = &a->t[1], *ci = &a->t[2], *cv = &a->t[3];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
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. */
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. */
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)
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. */
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;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
const int64_t pb = pp ? rowoff(pp, m, 2 * n_cand) : 0, ps = pp ? laststride(pp) : 0;
float pv = INFINITY;
int64_t pi = -1;
for (int64_t r = 0; r < n_cand; ++r) {
const bool ok = r < k && topk_next(lg, lb, ls, n_vocab, &pv, &pi);
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. */
uint32_t bits;
const float val = ok ? pv : -INFINITY;
std::memcpy(&bits, &val, 4);
st_int(pp->dtype, pp->data, pb + (2 * r) * ps,
ok ? (int64_t)(pi + voff) : (int64_t)0xffffffffu);
st_int(pp->dtype, pp->data, pb + (2 * r + 1) * ps, (int64_t)bits);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ the narrowing stages */
namespace {
enum Narrow { NR_TOPP, NR_MINP, NR_TYPICAL, NR_XTC };
static int narrow(const RadArgs* a, Narrow which) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *ci = &a->t[0], *cv = &a->t[1], *pr = &a->t[2];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
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));
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (sp.flags & RAD_SP_GREEDY) continue;
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
auto drop = [&](int64_t i) {
st_int(ci->dtype, ci->data, ib + i * is, -1);
stt(cv, vb + i * vs, -INFINITY);
};
auto live = [&](int64_t i) {
return ld_int(ci->dtype, ci->data, ib + i * is) >= 0;
};
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i)
if (live(i)) { const float v = ldt(cv, vb + i * vs); if (v > mx) mx = v; }
if (mx == -INFINITY) continue;
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. */
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
const float v = ldt(cv, vb + i * vs);
if (v == mx) continue; /* the max always survives */
if (ref_exp(v - mx) < p) drop(i);
}
continue;
}
/* The remaining three all need the 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);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
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. */
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;
}
continue;
}
if (which == NR_TYPICAL) {
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. */
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);
}
/* The smallest distance threshold whose mass reaches p, found by scanning the
* distances that actually occur. n_cand is a thousand at most. */
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);
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;
}
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);
}
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. */
{
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)
continue;
int64_t last_above = -1, n_above = 0;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i)) continue;
if (ref_exp(ldt(cv, vb + i * vs) - mx) * inv >= sp.xtc_threshold) {
last_above = i;
++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. */
if (n_above < 2) continue;
for (int64_t i = 0; i < n_cand; ++i) {
if (!live(i) || i == last_above) continue;
if (ref_exp(ldt(cv, vb + i * vs) - mx) * inv >= sp.xtc_threshold) drop(i);
}
}
}
return RAD_OK;
}
} /* namespace */
int ref_sample_topp(const RadArgs* a, RadStream) { return narrow(a, NR_TOPP); }
int ref_sample_minp(const RadArgs* a, RadStream) { return narrow(a, NR_MINP); }
int ref_sample_typical(const RadArgs* a, RadStream) { return narrow(a, NR_TYPICAL); }
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).
*
* 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.
*
* 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. */
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];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0) return RAD_E_SHAPE;
Rows R;
RAD_REF_TRY(rows_of(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)
for (int64_t m = 0; m < M; ++m) {
const RadSampleParams& sp = R.p[m];
if (!(sp.flags & RAD_SP_MASK)) continue;
const int64_t row = sp.mask_row;
if (row < 0 || row >= mask_rows) continue;
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
const int64_t bb = rowoff(bm, row, words), bs = laststride(bm);
for (int64_t i = 0; i < n_vocab; ++i) {
const uint32_t word = (uint32_t)ld_int(bm->dtype, bm->data, bb + (i / 32) * bs);
if (!((word >> (i % 32)) & 1u)) stt(lg, lb + i * ls, -INFINITY);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ sample_pick */
int ref_sample_pick(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *ci = &a->t[0], *cv = &a->t[1], *pr = &a->t[2], *tok = &a->t[3];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
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));
#pragma omp parallel for schedule(static)
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;
const int64_t ib = rowoff(ci, m, n_cand), is = laststride(ci);
const int64_t vb = rowoff(cv, m, n_cand), vs = laststride(cv);
float mx = -INFINITY;
for (int64_t i = 0; i < n_cand; ++i) {
if (ld_int(ci->dtype, ci->data, ib + i * is) < 0) continue;
const float v = ldt(cv, vb + i * vs);
if (v > mx) mx = v;
}
if (mx == -INFINITY) { st_int(tok->dtype, tok->data, offlin(tok, m), -1); continue; }
float sum = 0.0f;
for (int64_t i = 0; i < n_cand; ++i) {
if (ld_int(ci->dtype, ci->data, ib + i * is) < 0) continue;
sum += ref_exp(ldt(cv, vb + i * vs) - mx);
}
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. */
float cum = 0.0f;
int64_t chosen = -1, last = -1;
for (int64_t i = 0; i < n_cand; ++i) {
const int64_t id = ld_int(ci->dtype, ci->data, ib + i * is);
if (id < 0) continue;
const float v = ldt(cv, vb + i * vs);
if (v > -INFINITY) last = id;
cum += ref_exp(v - mx) * inv;
if (u < cum) { chosen = id; break; }
}
st_int(tok->dtype, tok->data, offlin(tok, m), chosen >= 0 ? chosen : last);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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. */
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];
const int64_t n_vocab = p_int(a, "n_vocab", lg->rank >= 2 ? lg->shape[lg->rank - 1] : 0);
if (n_vocab <= 0) return RAD_E_SHAPE;
const int64_t M = numel(lg) / n_vocab;
if (M <= 0 || numel(tok) < M) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t lb = rowoff(lg, m, n_vocab), ls = laststride(lg);
float best = -INFINITY;
int64_t bi = -1;
for (int64_t i = 0; i < n_vocab; ++i) {
const float v = ldt(lg, lb + i * ls);
if (bi < 0 || v > best) { best = v; bi = i; }
}
st_int(tok->dtype, tok->data, offlin(tok, m), bi);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ 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).
*
* `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. */
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];
const int64_t n_cand = p_int(a, "n_cand", ci->rank >= 2 ? ci->shape[ci->rank - 1] : 0);
if (n_cand <= 0) return RAD_E_SHAPE;
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. */
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;
if (n_in <= 0) return RAD_E_SHAPE;
auto bits_to_f32 = [](int64_t w) {
const uint32_t u = (uint32_t)w;
float f;
std::memcpy(&f, &u, 4);
return f;
};
#pragma omp parallel for schedule(static)
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. */
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;
float taken_v = INFINITY;
int64_t taken_i = -1;
for (int64_t r = 0; r < n_cand; ++r) {
if (r >= keep) {
st_int(ci->dtype, ci->data, ib + r * is, -1);
stt(cv, vb + r * vs, -INFINITY);
continue;
}
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);
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);
if (!after) continue;
if (best_id < 0 || v > best || (v == best && id < best_id)) { best = v; best_id = id; }
}
st_int(ci->dtype, ci->data, ib + r * is, best_id);
stt(cv, vb + r * vs, best_id >= 0 ? best : -INFINITY);
if (best_id < 0) continue;
taken_v = best;
taken_i = best_id;
}
}
return RAD_OK;
}
File diff suppressed because it is too large. Load diff