radiance 1.7.0

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

No files matched your search

+502 -191
View File
@@ -1,24 +1,22 @@
/* ref_moe.cpp -- routing, the scatter/gather pair, the grouped GEMM, and the exact row top-k.
*
* ============================== WHAT sorted_tok CARRIES ==============================
* ============================== What sorted_tok carries ==============================
*
* docs/OPS.md names the operand and does not say what is in it, and the choice decides whether
* `moe_gather` can work at all. It holds the FLATTENED (token, slot) index -- token * top_k + slot
* -- grouped by expert, not the bare token id. With the bare id, gather would have no way to find
* which of a token's top_k routing weights applies to a row, and would have to search. This is
* also vLLM's `sorted_token_ids` convention, so a kernel lifted from there needs no translation.
* The flattened (token, slot) index, token * top_k + slot, grouped by expert; not the bare token
* id, with which moe_gather could not find which of a token's routing weights applies to a row.
* This is vLLM's `sorted_token_ids` convention.
*
* A slot whose expert id is outside [0, n_expert) is DROPPED: it is not counted, and the tail of
* sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A padded batch row has to
* be expressible, and a negative id is how it is said.
* A slot whose expert id is outside [0, n_expert) is dropped: not counted, and the tail of
* sorted_tok from expert_offset[n_expert] to M*top_k is filled with -1. A negative id marks a
* padded batch row.
*
* The histogram this produces is what rad_route_report hands the heat engine; it is read back
* asynchronously and consumed on the NEXT step, and nothing here blocks the compute stream
* (spec §5.5).
* The resulting histogram is what rad_route_report hands the heat engine; it is read back
* asynchronously and consumed on the next step, without blocking the compute stream (spec §5.5).
*/
#include "ref_common.h"
#include "ref_gemm.h"
#include "ref_ops.h"
#include "ref_planes.h"
#include <algorithm>
#include <cstdlib>
@@ -27,10 +25,9 @@
using namespace ref;
/* ------------------------------------------------------------------ router_topk */
/* softmax over ALL n_expert logits, then the top_k by probability, then -- if `norm` -- renormalise
* the kept weights to sum to one. Softmax first and select second is the order Mixtral, Qwen3 and
* every model in this engine's scope use; selecting first and normalising the raw logits would be
* a different router, so the order is part of the op rather than an implementation choice. */
/* Softmax over all n_expert logits, then the top_k by probability, then (with `norm`) renormalise
* the kept weights to sum to one. Softmax-then-select is the order Mixtral, Qwen3 and every model in
* scope use; selecting first would be a different router. */
int ref_router_topk(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *lg = &a->t[0], *ids = &a->t[1], *w = &a->t[2];
@@ -41,7 +38,7 @@ int ref_router_topk(const RadArgs* a, RadStream) {
const int64_t M = numel(lg) / n_expert;
if (M <= 0 || numel(ids) < M * top_k || numel(w) < M * top_k) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n_expert * (top_k + 2))
for (int64_t m = 0; m < M; ++m) {
const int64_t lb = rowoff(lg, m, n_expert), ls = laststride(lg);
float mx = -INFINITY;
@@ -53,8 +50,8 @@ int ref_router_topk(const RadArgs* a, RadStream) {
for (int64_t e = 0; e < n_expert; ++e) sum += ref_exp(ldt(lg, lb + e * ls) - mx);
const float inv = sum > 0.0f ? 1.0f / sum : 0.0f;
/* The selection runs on the LOGITS, not the probabilities: softmax is monotone, so the
* order is identical and the comparison is exact rather than through an exp. */
/* Select on the logits: softmax is monotone, so the order is the same and the comparison
* avoids an exp. */
float pv = INFINITY;
int64_t pi = -1, kept = 0;
float wsum = 0.0f;
@@ -78,9 +75,9 @@ int ref_router_topk(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ moe_scatter */
/* `protect`: local experts the sort places LAST, in the order listed, the rest closed up -- the
* layout a layer that serves a few experts with a second grouped GEMM needs (libr4d's sort_place).
* Returns false on a list that is not strictly ascending inside [0, n). */
/* `protect`: local experts the sort places last, in the order listed, the rest closed up; the
* layout a layer serving a few experts with a second grouped GEMM needs (libr4d's sort_place).
* Returns false unless the list is strictly ascending within [0, n). */
static bool sort_places(const char* s, int64_t n, std::vector<int64_t>* place) {
std::vector<int64_t> prot;
for (const char* c = s ? s : ""; *c;) {
@@ -100,17 +97,15 @@ static bool sort_places(const char* s, int64_t n, std::vector<int64_t>* place) {
return true;
}
/* A stable counting sort of the (token, slot) pairs by expert id. Serial on purpose: it is O(M) on
* a batch's worth of small integers, and a parallel version would need a per-thread histogram and
* a prefix pass to stay stable, which is more code than the work it saves. */
/* A stable counting sort of the (token, slot) pairs by expert id. Serial: a parallel stable version
* would need per-thread histograms and a prefix pass, more code than the work it saves. */
int ref_moe_scatter(const RadArgs* a, RadStream) {
if (!have(a, 4)) return RAD_E_INVAL;
const RadTensor *ids = &a->t[0], *sorted = &a->t[1], *off = &a->t[2], *cnt = &a->t[3];
const int64_t n_expert = p_int(a, "n_expert", 0);
const int64_t top_k = p_int(a, "top_k", 1);
/* THIS RANK'S FIRST EXPERT. Subtracted from every routed id, so the range test below is the
* one that was always here and the sort is over local indices -- which is what the weight
* table, the offsets and the GEMM downstream are indexed by. */
/* This rank's first expert, subtracted from every routed id so the sort runs over local
* indices, as the weight table, offsets and downstream GEMM expect. */
const int64_t base = p_int(a, "expert_base", 0);
if (n_expert <= 0 || top_k <= 0 || base < 0) return RAD_E_SHAPE;
const int64_t M = numel(ids) / top_k;
@@ -139,40 +134,247 @@ int ref_moe_scatter(const RadArgs* a, RadStream) {
}
st_int(off->dtype, off->data, offlin(off, n_expert), run);
/* A second cursor pass rather than mutating the offsets: the offsets are an output the caller
* reads, and rewinding them afterwards is one more place to be wrong. */
/* Each slot goes to its expert's cursor, in ascending slot order. The cursors are a copy, so
* the offsets (an output) are never mutated. */
for (int64_t i = run; i < T; ++i) st_int(sorted->dtype, sorted->data, offlin(sorted, i), -1);
for (int64_t e = 0, w = 0; e < n_expert; ++e) {
w = ld_int(off->dtype, off->data, offlin(off, e));
for (int64_t i = 0; i < T; ++i) {
if (at(i) != e) continue;
st_int(sorted->dtype, sorted->data, offlin(sorted, w), i);
++w;
}
std::vector<int64_t> cur((size_t)n_expert);
for (int64_t e = 0; e < n_expert; ++e)
cur[(size_t)e] = ld_int(off->dtype, off->data, offlin(off, e));
for (int64_t i = 0; i < T; ++i) {
const int64_t e = at(i);
if (e >= 0) st_int(sorted->dtype, sorted->data, offlin(sorted, cur[(size_t)e]++), i);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ moe_gemm, moe_gemm_q */
/* y[i, :] = a[row(i), :] @ w[e]^T, where e is the expert whose offset range contains i and
* `a_order` picks row(i) -- `sorted_tok[i] / top_k` when the activation has one row per TOKEN,
* and i itself when it already has one per (token, slot). The output is in SORTED order -- one
* row per (token, slot) pair, laid out the way moe_scatter grouped them -- because that is the
* layout that makes the expert loop contiguous, which is the entire point of the scatter.
* moe_gather puts it back.
/* y[i, :] = a[row(i), :] @ w[e]^T, e the expert whose offset range contains i. `a_order` picks
* row(i): `sorted_tok[i] / top_k` for one activation row per token, i itself for one per
* (token, slot). The output is in sorted order (one row per (token, slot), grouped as moe_scatter
* left them) so the expert loop is contiguous; moe_gather restores token order.
*
* THE WEIGHT OPERAND IS A TABLE (RAD_OPD_WTAB), not a plane, and ref_gemm.h's expert_entry() is
* where that is read. A layer's experts are separate movement units, so after placement one is in
* VRAM and the next is streamed over the link; `base + e*stride` describes only the case where
* nothing was offloaded. The stacked form is still accepted, because a caller with no engine
* behind it -- rad-kbench replaying a fixture -- has nowhere to put a pointer array.
* The weight operand is a table (RAD_OPD_WTAB), read through ref_gemm.h's expert_entry(): experts
* are separate movement units, so one may be in VRAM while the next is streamed. The stacked form
* is also accepted for callers without an engine (rad-kbench fixtures).
*
* The quantised arm is the same walk with ref_gemm.h's Scales over both operands, and the sub-sum
* is accumulated from the RAW CODES and scaled once per group exactly as `gemm_nt_q` does: the
* two references must agree in the last bits or rad-kbench blames a kernel for a choice made
* here. Only the WEIGHT scale grid is block-shaped -- one scale per 128x128 tile of an expert --
* while the activation's is per row per group of K, which is `rblk = 1`, which is what
* make_scales derives on its own from the two extents. */
* The quantised arm uses ref_gemm.h's Scales and quant_dot, accumulating raw codes and scaling once
* per group exactly as gemm_nt_q does. Only the weight scale grid is block-shaped (one scale per
* 128x128 tile); the activation's is per row per K group (rblk = 1), which make_scales derives from
* the extents. */
/* quant_tile with the loaders resolved at compile time for the grouped GEMM's dtype pairs (the
* same floats as Dyn, which serves the rest). */
typedef float* (*TileFn)(const Mat&, const Mat&, const Scales&, const Scales&, const int64_t*,
int64_t, int64_t, int64_t, int64_t, float*);
#define REF_TILE_ROW(DA) \
case DA: \
switch (db) { \
case RAD_F8E4M3: return &quant_tile<Fix<DA>, Fix<RAD_F8E4M3>>; \
case RAD_I4: return &quant_tile<Fix<DA>, Fix<RAD_I4>>; \
case RAD_I8: return &quant_tile<Fix<DA>, Fix<RAD_I8>>; \
case RAD_BF16: return &quant_tile<Fix<DA>, Fix<RAD_BF16>>; \
case RAD_F32: return &quant_tile<Fix<DA>, Fix<RAD_F32>>; \
default: return &quant_tile<Dyn, Dyn>; \
}
static TileFn pick_tile(uint32_t da, uint32_t db) {
switch (da) {
REF_TILE_ROW(RAD_F8E4M3)
REF_TILE_ROW(RAD_BF16)
REF_TILE_ROW(RAD_F32)
REF_TILE_ROW(RAD_I8)
default: return &quant_tile<Dyn, Dyn>;
}
}
#undef REF_TILE_ROW
/* ------------------------------------------------------------------ the codebook experts
*
* Qwen3.8-Flash-Next's experts (docs/MOE-W4.md) are u4 or u5 codes indexing a table of 16 or 32
* f32 levels, with a scale per (row, group of K): bf16 per 128 (`w4nla8h`), or E4M3 per 64 or 32
* times one fixed f32 (`w4nl64a8h`, `w4nl32a8h`, `w5nl64a8h`). Element (n, k) of an expert is
* table[code(n, k)] * scale(n, k / group), times `scale.1` where there is one. The codes view takes
* the planes `codes,table` and the two-level forms' scale view `scale,scale.1`; such a weight is
* stored in the joined form of abi/rad_planes.h, which these rows' layout hooks ask for. A view of
* one plane (w4nla8h's bf16 scale, every view of the other dtypes) is stored as it is.
*
* The arithmetic is quant_dot's: per weight group, the sub-sum of table values times activation
* codes, then `(sub * sa) * sb` with sb the scale times its level in f32. The logical form the
* oracle and rad-kbench pass (enc_selection_logical: table entries for codes, scale products for
* scales) goes through the same chain, so the two readings agree bit for bit wherever the logical
* operands hold the values exactly, as E4M3 and bf16 do for the shipped tables and scales. libr4d
* folds each 64- or 32-wide group's sum under its scale first and the activation's scale per 128
* after (`(sub0 * sb0 + sub1 * sb1) * sa`), which differs in the last bits. */
/* What a codebook `dtype` stores: the code width, the scale's group along K and dtype, and whether
* the scale view carries the level above it. `bits` is 0 for any other dtype. */
struct CbForm { int bits; int64_t group; uint32_t sdt; bool level; };
static CbForm cb_form(const RadParam* p, int n_p) {
const RadParam* d = rad_param_find(p, n_p, "dtype");
const char* s = d && d->kind == RAD_P_STR ? d->sval : nullptr;
if (s && !std::strcmp(s, "w4nla8h")) return CbForm{ 4, 128, RAD_BF16, false };
if (s && !std::strcmp(s, "w4nl64a8h")) return CbForm{ 4, 64, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w4nl32a8h")) return CbForm{ 4, 32, RAD_F8E4M3, true };
if (s && !std::strcmp(s, "w5nl64a8h")) return CbForm{ 5, 64, RAD_F8E4M3, true };
return CbForm{ 0, 0, 0, false };
}
/* Whether a selection of several planes for `operand` is what `dtype` names: the codes operands of
* both grouped GEMMs are 2, 6, 8 and 10 and their scales 3, 7, 9 and 11. RAD_E_DTYPE otherwise,
* which refuses the weight at declare by name. */
static int cb_check(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, int n_planes) {
const CbForm f = cb_form(p, n_p);
const bool codes = operand == 2 || operand == 6 || operand == 8 || operand == 10;
const bool scale = operand == 3 || operand == 7 || operand == 9 || operand == 11;
if (!f.bits || (!codes && !scale) || !enc || !sel || n_planes != 2 ||
std::strcmp(enc->transform, "fwht128") != 0)
return RAD_E_DTYPE;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_SHAPE;
const RadEncPlane& a = enc->plane[sel[0]];
const RadEncPlane& b = enc->plane[sel[1]];
if (codes)
return !std::strcmp(a.role, "codes") && a.kind == RAD_PLANE_TILED &&
a.dtype == (f.bits == 5 ? (uint32_t)RAD_U5 : (uint32_t)RAD_U4) &&
a.block[0] == 1 && a.block[1] == 1 && !std::strcmp(b.role, "table") &&
b.kind == RAD_PLANE_TABLE && b.dtype == RAD_F32 && b.extent[0] == 1 &&
b.extent[1] == ((int64_t)1 << f.bits)
? RAD_OK : RAD_E_DTYPE;
return f.level && !std::strcmp(a.role, "scale") && a.kind == RAD_PLANE_TILED &&
a.dtype == f.sdt && a.block[0] == 1 && a.block[1] == f.group &&
!std::strcmp(b.role, "scale.1") && b.kind == RAD_PLANE_TILED && b.dtype == RAD_F32 &&
b.block[0] == 0 && b.block[1] == 0
? RAD_OK : RAD_E_DTYPE;
}
extern "C" int ref_moe_cb_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n_planes,
RadLayout* out) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_layout(enc, sel, planes, n_planes, out);
}
extern "C" int ref_moe_cb_relayout(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* planes,
int n_planes, void* dst, int64_t dst_bytes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_relayout(enc, sel, planes, n_planes, dst, dst_bytes);
}
extern "C" int ref_moe_cb_unrelayout(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const void* src,
int64_t src_bytes, const RadTensor* planes, int n_planes) {
if (n_planes <= 1) return RAD_E_UNSUPPORTED;
const int rc = cb_check(p, n_p, operand, enc, sel, n_planes);
return rc < 0 ? rc : rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n_planes);
}
/* The joined form's header when weight entry `t` holds one. An entry smaller than a header is a
* plain plane, and is not read past its end. */
static const RadPlanesHeader* cb_joined(const RadTensor& t) {
int64_t n = 1;
for (uint32_t i = 0; i < t.rank; ++i) n *= t.shape[i];
if (!t.data || rad_dtype_bytes(t.dtype, n) < (int64_t)sizeof(RadPlanesHeader)) return nullptr;
return rad_planes_header(t.data);
}
/* A codebook expert's codes, which LdCb reads as table values. The RadTensor comes first, so a Mat
* over `t` reaches the rest: element i is (i / cols, i % cols) of a plane whose rows start
* `row_bytes` apart, the layout rad_planes.h keeps. */
struct CbTensor {
RadTensor t; /* `data`: the codes plane, from the tile's first weight row */
float tab[32];
int64_t cols = 0, row_bytes = 0;
int bits = 0;
};
struct LdCb {
static inline float ld(const RadTensor* t, int64_t i) {
const CbTensor* c = reinterpret_cast<const CbTensor*>(t);
const int64_t r = i / c->cols, k = i - r * c->cols;
return c->tab[rad_load_bits((const uint8_t*)c->t.data + r * c->row_bytes, c->bits, k)];
}
};
/* An expert's codes when its entry is the joined form: 1 with `out` filled, 0 for a plain plane
* (any dtype but u4 and u5), RAD_E_DTYPE for a form these kernels do not read and RAD_E_SHAPE for
* codes not covering [n, k]. A u4 or u5 entry is always joined: only its table says what a code
* means. */
static int cb_codes(const RadTensor& w, int64_t n, int64_t k, CbTensor* out) {
if (w.dtype != RAD_U4 && w.dtype != RAD_U5) return 0;
const RadPlanesHeader* h = rad_planes_header(w.data);
const RadPlanesEntry *ec = nullptr, *et = nullptr;
const void* codes = h ? rad_planes_find(w.data, "codes", &ec) : nullptr;
const void* tab = h ? rad_planes_find(w.data, "table", &et) : nullptr;
if (!codes || !tab || h->n_planes != 2) return RAD_E_DTYPE;
const int bits = ec->dtype == RAD_U4 ? 4 : ec->dtype == RAD_U5 ? 5 : 0;
if (!bits || ec->kind != RAD_PLANE_TILED || ec->block[0] != 1 || ec->block[1] != 1 ||
et->kind != RAD_PLANE_TABLE || et->dtype != RAD_F32 ||
et->rows * et->cols != ((int64_t)1 << bits))
return RAD_E_DTYPE;
if (ec->rows < n || ec->cols < k) return RAD_E_SHAPE;
out->t = w;
out->t.data = const_cast<void*>(codes);
std::memcpy(out->tab, tab, sizeof(float) << bits);
out->cols = ec->cols;
out->row_bytes = ec->row_bytes;
out->bits = bits;
return 1;
}
/* An expert's scales beside joined codes: the scale times the level above it. */
struct CbScale {
Scales s;
float mul = 1.0f;
inline float at(int64_t row, int64_t g) const { return (s.p ? s.grp(row, g) : 1.0f) * mul; }
};
/* From the joined `scale,scale.1` form when the entry holds one, else the plane as make_scales
* reads it (w4nla8h's bf16 scale, or none). RAD_E_DTYPE for a joined form of other planes. */
static int cb_scale(const RadTensor* ws, int64_t n, int64_t k, CbScale* out) {
out->mul = 1.0f;
const RadPlanesHeader* h = ws ? cb_joined(*ws) : nullptr;
if (!h) {
out->s = make_scales(ws, n, k, false);
return RAD_OK;
}
const RadPlanesEntry *es = nullptr, *e1 = nullptr;
const void* sp = rad_planes_find(ws->data, "scale", &es);
const void* lp = rad_planes_find(ws->data, "scale.1", &e1);
if (!sp || !lp || h->n_planes != 2) return RAD_E_DTYPE;
const uint32_t dt = es->dtype;
if (es->kind != RAD_PLANE_TILED || es->block[0] < 1 || es->block[1] < 1 ||
(dt != RAD_F8E4M3 && dt != RAD_BF16 && dt != RAD_F16 && dt != RAD_F32) ||
e1->kind != RAD_PLANE_TILED || e1->dtype != RAD_F32 || e1->block[0] != 0 ||
e1->block[1] != 0 || e1->rows != 1 || e1->cols != 1)
return RAD_E_DTYPE;
if ((n + es->block[0] - 1) / es->block[0] > es->rows ||
(k + es->block[1] - 1) / es->block[1] > es->cols)
return RAD_E_SHAPE;
Scales s{};
s.p = sp;
s.dt = dt;
s.rs = es->cols;
s.cs = 1;
s.group = es->block[1];
s.rblk = es->block[0];
s.e8m0 = false;
out->s = s;
std::memcpy(&out->mul, lp, sizeof out->mul);
return 1;
}
static TileFn pick_cb_tile(uint32_t da) {
switch (da) {
case RAD_F8E4M3: return &quant_tile<Fix<RAD_F8E4M3>, LdCb>;
case RAD_BF16: return &quant_tile<Fix<RAD_BF16>, LdCb>;
case RAD_F32: return &quant_tile<Fix<RAD_F32>, LdCb>;
default: return &quant_tile<Dyn, LdCb>;
}
}
static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int n_opd = quant ? (ncls == 4 ? 13 : 9) : 5;
if (!have(a, n_opd)) return RAD_E_INVAL;
@@ -183,9 +385,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const RadTensor* sorted = &a->t[quant ? 4 : 2];
const RadTensor* off = &a->t[quant ? 5 : 3];
const RadTensor* Y = &a->t[quant ? (ncls == 4 ? 12 : 8) : 4];
/* THE QUANTISED ARM'S EXPERTS ARE TWO TABLES BY PARITY -- see ref_registry.cpp -- or, for
* `moe_gemm_q_mod4`, four by the expert's number mod 4; the plain arm's are one, which is the
* same walk with every expert in the first class. */
/* The quantised arm's experts are two tables by parity (see ref_registry.cpp), or four by
* expert number mod 4 for `moe_gemm_q_mod4`; the plain arm has one, every expert in class 0. */
const RadTensor* W1 = quant ? &a->t[6] : W;
const RadTensor* ws1_ = quant ? t_in(a, 7) : nullptr;
const bool two = quant;
@@ -195,10 +396,9 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const RadTensor* wsq[4] = { ws_, ws1_, quant && nc == 4 ? t_in(a, 9) : nullptr,
quant && nc == 4 ? t_in(a, 11) : nullptr };
/* "sorted" means `a` already has one row per (token, slot) in the scatter's order, which is
* what the DOWN projection of a routed block reads -- its input is the first projection's
* output. "token" (the default, and the gate_up projection's case) means one row per token,
* gathered through sorted_tok. See ref_registry.cpp for why this is said and not derived. */
/* "sorted": `a` has one row per (token, slot) in scatter order (the down projection, reading
* the first projection's output). "token" (default, gate_up): one row per token, gathered
* through sorted_tok. See ref_registry.cpp for why this is stated, not derived. */
const char* ord = p_str(a, "a_order", "token");
const bool sorted_a = ord && std::strcmp(ord, "sorted") == 0;
if (ord && !sorted_a && std::strcmp(ord, "token") != 0) return RAD_E_UNSUPPORTED;
@@ -218,8 +418,8 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t n_expert = p_int(a, "n_expert", W->rank >= 3 ? W->shape[0] : 0);
const int64_t top_k = p_int(a, "top_k", 1);
if (parts <= 0 || n_expert <= 0 || top_k <= 0) return RAD_E_SHAPE;
/* The output is the widest class's width, the activation the longest class's K. Class q
* holds ceil((n - q) / nc) experts. */
/* The output is the widest class's N and the activation the longest class's K. Class q holds
* ceil((n - q) / nc) experts. */
int64_t N = 0, K = 0;
for (int q = 0; q < nc; ++q) {
if (Nq[q] <= 0 || Kq[q] <= 0 || Nq[q] % parts) return RAD_E_SHAPE;
@@ -231,16 +431,14 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t T = numel(Y) / N;
if (T <= 0 || numel(sorted) < T || numel(off) < n_expert + 1) return RAD_E_SHAPE;
/* `y` HAS ONE ROW PER (token, slot) AND `a` HAS WHATEVER `a_order` SAYS. The token count is
* recovered from T and top_k; the activation's row count is T under "sorted" and M under
* "token", and it is checked against THAT rather than against either extent on its own -- a
* sorted-order operand with only M rows is a caller that handed the down projection the
* gate_up projection's buffer. */
/* `y` has one row per (token, slot); `a` has T rows under "sorted" and M = T / top_k under
* "token", checked against the matching count (M rows under "sorted" means the down projection
* was handed gate_up's input buffer). */
const int64_t M = T / top_k;
const int64_t AR = sorted_a ? T : M;
if (M <= 0 || numel(A) < AR * K) return RAD_E_SHAPE;
const Mat ma = as_mat(A, AR, K);
const Mat ma = as_mat(A, K);
const Scales SA = make_scales(as_, AR, K, false);
const int64_t gp = p_int(a, "group", 0);
if (quant && gp > 0 && SA.p && SA.group != gp) return RAD_E_SHAPE;
@@ -248,14 +446,16 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
const int64_t y_rs = row_stride(Y, N);
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
/* Per-expert readings, built once outside the row loop: a table lookup and a Scales are cheap,
* and doing them per row would be T of them against n_expert. A null `data` means the operand
* could not be read as a table at all, which is refused before the loop because an OpenMP body
* cannot return. Expert e is entry e / nc of class e % nc. */
/* Per-expert views, built once outside the row loop (and validated there, since an OpenMP body
* cannot return). Expert e is entry e / nc of class e % nc. */
std::vector<RadTensor> we((size_t)n_expert), wse((size_t)n_expert);
std::vector<Mat> mw((size_t)n_expert);
std::vector<Scales> SW((size_t)n_expert);
std::vector<int64_t> en((size_t)n_expert), ek((size_t)n_expert);
/* Codebook experts (joined codes): every expert of the call, or none. */
std::vector<CbTensor> cbt;
std::vector<CbScale> cbs;
bool codebook = false;
for (int64_t e = 0; e < n_expert; ++e) {
const int q = (int)(e % nc);
const RadTensor* tw = Wq[q];
@@ -268,48 +468,161 @@ static int moe_gemm_impl(const RadArgs* a, bool quant, int ncls = 2) {
if (!we[(size_t)e].data) return RAD_E_STRIDE;
if (we[(size_t)e].rank < 2 || we[(size_t)e].shape[0] < n ||
we[(size_t)e].shape[1] < k) return RAD_E_SHAPE;
mw[(size_t)e] = as_mat(&we[(size_t)e], n, k);
if (quant && ts) {
wse[(size_t)e] = expert_entry(ts, ix);
if (!wse[(size_t)e].data) return RAD_E_STRIDE;
SW[(size_t)e] = make_scales(&wse[(size_t)e], n, k, false);
} else {
SW[(size_t)e] = make_scales(nullptr, n, k, false);
}
if (quant) {
CbTensor ct;
const int jc = cb_codes(we[(size_t)e], n, k, &ct);
if (jc < 0) return jc;
if (e == 0 && jc > 0) {
codebook = true;
cbt.resize((size_t)n_expert);
cbs.resize((size_t)n_expert);
}
if (codebook != (jc > 0)) return RAD_E_DTYPE;
if (codebook) {
cbt[(size_t)e] = ct;
const int js = cb_scale(ts ? &wse[(size_t)e] : nullptr, n, k, &cbs[(size_t)e]);
if (js < 0) return js;
continue;
}
/* A joined scale is read only beside joined codes. */
if (ts && cb_joined(wse[(size_t)e])) return RAD_E_DTYPE;
}
mw[(size_t)e] = as_mat(&we[(size_t)e], k);
SW[(size_t)e] = make_scales(quant && ts ? &wse[(size_t)e] : nullptr, n, k, false);
}
const int64_t fy = N / parts;
#pragma omp parallel for schedule(static)
/* Each row's expert (the binary search over the offsets) and activation row, or -1 for a row
* that is all zeros: a dropped slot, or a token past `a`. Zeros are written, never stale
* arena bytes, and so are each part's columns past a narrower class's width. */
std::vector<int64_t> ex((size_t)T, -1), tk((size_t)T, 0);
REF_PAR_FOR(T * N)
for (int64_t i = 0; i < T; ++i) {
const int64_t flat = ld_int(sorted->dtype, sorted->data, offlin(sorted, i));
if (flat < 0) { /* a dropped slot: a zero row, never stale arena bytes */
for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f);
continue;
int64_t e = -1;
if (flat >= 0) {
int64_t lo = 0, hi = n_expert;
while (lo + 1 < hi) {
const int64_t mid = (lo + hi) / 2;
if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid;
}
const int64_t tok = sorted_a ? i : flat / top_k;
if (tok < AR) { e = lo; tk[(size_t)i] = tok; }
}
/* Which expert owns row i: a binary search over the offsets, so a 256-expert model does
* not pay a linear scan per row. */
int64_t lo = 0, hi = n_expert;
while (lo + 1 < hi) {
const int64_t mid = (lo + hi) / 2;
if (ld_int(off->dtype, off->data, offlin(off, mid)) <= i) lo = mid; else hi = mid;
}
const int64_t e = lo;
const int64_t tok = sorted_a ? i : flat / top_k;
if (tok >= AR) { for (int64_t n = 0; n < N; ++n) stt(Y, i * y_rs + n * y_cs, 0.0f); continue; }
ex[(size_t)i] = e;
const int64_t fc = e >= 0 ? en[(size_t)e] / parts : 0;
for (int64_t n = 0; n < N; ++n)
if (n - (n / fy) * fy >= fc) stt(Y, i * y_rs + n * y_cs, 0.0f);
}
const Mat& B = mw[(size_t)e];
const Scales& SB = SW[(size_t)e];
/* The live rows grouped by expert, ascending within one, and the tiles over them: one per
* (expert, part, column block, row group). Output column pp * fy + j is weight row
* pp * fc + j of the expert's [N_e, K_e] plane. */
std::vector<int64_t> start((size_t)n_expert + 1, 0), order((size_t)T), arow((size_t)T);
for (int64_t i = 0; i < T; ++i)
if (ex[(size_t)i] >= 0) ++start[(size_t)ex[(size_t)i] + 1];
for (int64_t e = 0; e < n_expert; ++e) start[(size_t)e + 1] += start[(size_t)e];
{
std::vector<int64_t> cur(start.begin(), start.end() - 1);
for (int64_t i = 0; i < T; ++i) {
const int64_t e = ex[(size_t)i];
if (e < 0) continue;
const int64_t at = cur[(size_t)e]++;
order[(size_t)at] = i;
arow[(size_t)at] = tk[(size_t)i];
}
}
struct Item { int64_t e, pp, j0, r0, R; };
std::vector<Item> items;
int64_t rg_max = 1;
for (int64_t e = 0; e < n_expert; ++e) {
const int64_t cnt = start[(size_t)e + 1] - start[(size_t)e];
if (cnt <= 0) continue;
const int64_t fc = en[(size_t)e] / parts;
/* One product, and it is `quant_dot`'s: the same grouping and the same order the dense
* quantised GEMM folds its two scales in. A second copy of that arithmetic here would be a
* second place for it to be right by accident -- the expert GEMM and gemm_nt_q are the
* same function over different weights, and a reference that spelled them differently
* would put an ulp between them that no tolerance is meant to absorb. Output column n is
* weight row (n / fy) * fc + n % fy, and zero past a narrower class's part. */
for (int64_t n = 0; n < N; ++n) {
const int64_t pp = n / fy, j = n - pp * fy;
stt(Y, i * y_rs + n * y_cs,
j < fc ? quant_dot(ma, B, SA, SB, tok, pp * fc + j, ek[(size_t)e]) : 0.0f);
const TileGrid tg = tile_grid(cnt, fc * parts);
if (tg.rg > rg_max) rg_max = tg.rg;
for (int64_t pp = 0; pp < parts; ++pp)
for (int64_t j0 = 0; j0 < fc; j0 += REF_NB)
for (int64_t r0 = 0; r0 < cnt; r0 += tg.rg)
items.push_back({ e, pp, j0, r0, (r0 + tg.rg < cnt) ? tg.rg : cnt - r0 });
}
std::vector<TileFn> tile((size_t)n_expert);
for (int64_t e = 0; e < n_expert; ++e)
tile[(size_t)e] = codebook ? pick_cb_tile(A->dtype)
: pick_tile(A->dtype, we[(size_t)e].dtype);
REF_PAR_REGION(T * N * K)
{
/* A codebook tile's scales are its REF_NB weight rows' groups, at most K of them. */
const size_t wsf = tile_ws_floats(rg_max);
float* const ws = ws_get(wsf + (codebook ? (size_t)(REF_NB * K) : 0));
REF_FOR_DYN
for (int64_t it = 0; it < (int64_t)items.size(); ++it) {
const Item& w = items[(size_t)it];
const int64_t e = w.e, fc = en[(size_t)e] / parts, ke = ek[(size_t)e];
const int64_t nb = (w.j0 + REF_NB < fc) ? REF_NB : fc - w.j0;
const int64_t base = start[(size_t)e] + w.r0;
if (codebook) {
/* The tile's weight rows as their own [nb, ke] operand: codes from its first row,
* and its scales, each times its level, as an f32 [nb, ngrp] stream. */
const int64_t wr0 = w.pp * fc + w.j0;
CbTensor lt = cbt[(size_t)e];
lt.t.data = (uint8_t*)lt.t.data + wr0 * lt.row_bytes;
const Mat B{ &lt.t, lt.cols, 1 };
const CbScale& cs = cbs[(size_t)e];
const int64_t g = cs.s.p && cs.s.group > 0 ? cs.s.group : ke;
const int64_t ngrp = (ke + g - 1) / g;
float* const sb = ws + wsf;
for (int64_t j = 0; j < nb; ++j)
for (int64_t gi = 0; gi < ngrp; ++gi) sb[j * ngrp + gi] = cs.at(wr0 + j, gi);
Scales SB{};
SB.p = cs.s.p || cs.mul != 1.0f ? sb : nullptr;
SB.dt = RAD_F32;
SB.rs = ngrp;
SB.cs = 1;
SB.group = g;
SB.rblk = 1;
if (SA.p && SA.group < g) {
for (int64_t r = 0; r < w.R; ++r)
for (int64_t j = 0; j < nb; ++j)
stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs,
quant_dot<Dyn, LdCb>(ma, B, SA, SB, arow[(size_t)(base + r)], j,
ke));
continue;
}
const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R, 0, nb,
ke, ws);
for (int64_t r = 0; r < w.R; ++r) {
const int64_t i = order[(size_t)(base + r)];
for (int64_t j = 0; j < nb; ++j)
stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]);
}
continue;
}
const Mat& B = mw[(size_t)e];
const Scales& SB = SW[(size_t)e];
const int64_t g = SB.group > 0 ? SB.group : ke;
if (SA.p && SA.group < g) {
/* An activation grid finer than the weight's: quant_dot per element. */
for (int64_t r = 0; r < w.R; ++r)
for (int64_t j = 0; j < nb; ++j)
stt(Y, order[(size_t)(base + r)] * y_rs + (w.pp * fy + w.j0 + j) * y_cs,
quant_dot(ma, B, SA, SB, arow[(size_t)(base + r)],
w.pp * fc + w.j0 + j, ke));
continue;
}
const float* acc = tile[(size_t)e](ma, B, SA, SB, arow.data() + base, w.R,
w.pp * fc + w.j0, nb, ke, ws);
for (int64_t r = 0; r < w.R; ++r) {
const int64_t i = order[(size_t)(base + r)];
for (int64_t j = 0; j < nb; ++j)
stt(Y, i * y_rs + (w.pp * fy + w.j0 + j) * y_cs, acc[r * REF_NB + j]);
}
}
}
return RAD_OK;
@@ -322,16 +635,14 @@ int ref_moe_gemm_q_mod4(const RadArgs* a, RadStream) { return moe_gemm_impl(a, t
/* ------------------------------------------------------------------ moe_gather */
/* y[t] = sum over the token's slots of expert_w[t, j] * y_expert[position of (t, j)].
*
* THE SUMMATION ORDER IS ASCENDING SLOT j, which is what makes this reproducible: an
* implementation that walked the expert-sorted rows instead would sum a token's contributions in
* expert-id order, and the two differ in the last bits.
* Summation is in ascending slot j; walking the expert-sorted rows would sum in expert-id order and
* differ in the last bits.
*
* The inverse permutation is rebuilt in blocks rather than allocated: one pass over sorted_tok per
* block of tokens, into a fixed stack array. That costs (M / block) passes, which at the sizes an
* MoE layer runs is nothing, and it keeps the op free of both scratch and allocation. */
* The inverse permutation is rebuilt per block of tokens into a fixed stack array, one pass over
* sorted_tok per block, so the op needs no scratch or allocation. */
int ref_moe_gather(const RadArgs* a, RadStream) {
/* Operands are POSITIONAL, so an absent shared pair is two NULL SLOTS rather than a shorter
* array: `have` demands all six and would refuse every unfolded call. */
/* Operands are positional: an absent shared pair is two null slots, which `have` would
* refuse. */
if (a->n_t < 6) return RAD_E_INVAL;
const RadTensor *ye = &a->t[0], *ew = &a->t[1], *sorted = &a->t[2], *Y = &a->t[5];
if (!ye->data || !ew->data || !sorted->data || !Y->data) return RAD_E_INVAL;
@@ -357,7 +668,7 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
const int64_t y_rs = Y->rank >= 2 ? Y->stride[Y->rank - 2] : n;
const int64_t y_cs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(T * n)
for (int64_t b = 0; b < nblk; ++b) {
int32_t inv[INV_MAX];
const int64_t t0 = b * tb, t1 = (t0 + tb < M) ? t0 + tb : M;
@@ -383,9 +694,8 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
ldt(ye, (int64_t)i * ye_rs + c * ye_cs);
}
const int64_t yo = t * y_rs + c * y_cs;
/* THE NARROWS ARE THE UNFUSED PAIR'S, and the store is what performs them: the
* gather wrote a bf16 buffer and scale_rows narrowed its own product before the
* add, so both operands of the sum are rounded and the sum is rounded again. */
/* The stores round as the unfused pair does: the gather's result and scale_rows'
* product are each rounded, then their sum. */
stt(Y, yo, acc);
if (!sh) continue;
const float g = ldt(Y, yo);
@@ -397,16 +707,28 @@ int ref_moe_gather(const RadArgs* a, RadStream) {
return RAD_OK;
}
/* One step of a selection sort over `n` candidates: the unused one with the largest value, ties to
* the lower id, skipping pads (id < 0). Returns its index, or -1 when none is left. */
template <class Id, class Val>
static int64_t next_best(int64_t n, const Id& id, const Val& val,
const std::vector<unsigned char>& used) {
int64_t best = -1;
for (int64_t c = 0; c < n; ++c) {
if (used[(size_t)c] || id(c) < 0) continue;
if (best < 0 || val(c) > val(best) || (val(c) == val(best) && id(c) < id(best))) best = c;
}
return best;
}
/* ------------------------------------------------------------------ row_topk */
/* Exact per-row top-R, descending, ties to the lower column. The same selection the router uses,
* exposed as its own op because a drafter's candidate set and a speculative tree both want it
* without a softmax in front. */
/* Exact per-row top-R, descending, ties to the lower column: the router's selection without the
* softmax, for drafter candidate sets and speculative trees. */
int ref_row_topk(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
/* The vocab-parallel form. `off` shifts every column reported, so a rank's slice reports
* global ids; `pairs` is the [M, R, 2] plane an all_gather moves, an int32 id in the first
* float slot beside its value. Both absent is the ordinary single-rank top-R. */
/* Vocab-parallel form: `vocab_off` shifts reported columns to global ids; `pairs` is the
* [M, R, 2] plane an all_gather moves (int32 id bits in the first float slot, then the value).
* Both absent is the single-rank top-R. */
const RadTensor* pairs = t_in(a, 3);
const int64_t off = p_int(a, "vocab_off", 0);
const int64_t N = p_int(a, "N", x->rank >= 2 ? x->shape[x->rank - 1] : 0);
@@ -416,7 +738,7 @@ int ref_row_topk(const RadArgs* a, RadStream) {
if (M <= 0 || numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * N * R)
for (int64_t m = 0; m < M; ++m) {
const int64_t xb = rowoff(x, m, N), xs = laststride(x);
float pv = INFINITY;
@@ -438,68 +760,57 @@ int ref_row_topk(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ row_topk_merge */
/* The other half of the vocab-parallel top-R: the R largest of world_size all-gathered per-rank
* candidate sets, in the same descending (idx, val) form the single-rank path produces, so
* everything downstream is handed the answer it would have had from an unsharded plane.
/* The other half of the vocab-parallel top-R: the R largest of world_size gathered per-rank
* candidate sets, in the single-rank path's descending (idx, val) form.
*
* TIES BREAK ON THE LOWER ID, which is what makes that equality true rather than approximate: a
* dense top-R over the whole vocabulary breaks ties on the lower column, so a merge that broke
* them on rank order would disagree with it exactly when two shards hold the same logit.
* Ties break on the lower id, matching a dense top-R over the whole vocabulary; rank order would
* disagree when two shards hold the same logit.
*
* A slot the producing rank could not fill carries id -1 and is DROPPED -- a sentinel rather than
* a -INFINITY value, because -inf is a value a masked logit legitimately takes. */
* An unfilled slot carries id -1 and is dropped; -inf cannot be the sentinel, since masked logits
* legitimately take it. */
int ref_row_topk_merge(const RadArgs* a, RadStream) {
if (!have(a, 3)) return RAD_E_INVAL;
const RadTensor *g = &a->t[0], *idx = &a->t[1], *val = &a->t[2];
const int64_t R = p_int(a, "R", 1);
const int64_t W = p_int(a, "world_size", 1);
if (R <= 0 || W <= 0) return RAD_E_SHAPE;
/* The rows are the OPERAND'S, not the parameter's: `M` is declared as a band ceiling and the
* gathered plane is narrowed to the rows this step actually has. */
/* Rows come from the operand; `M` is a band ceiling (see band_rows). */
const int64_t M = numel(g) / (W * R * 2);
if (M <= 0) return RAD_E_SHAPE;
if (g->dtype != RAD_F32 || numel(g) < M * W * R * 2) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * W * R * R)
for (int64_t m = 0; m < M; ++m) {
const float* const row = (const float*)g->data + m * W * R * 2;
/* A selection sort over W*R entries: 32 of them at world 2 and R 16, so the quadratic
* form is cheaper than anything with an allocation in it, and it is the reference. */
auto id = [&](int64_t c) {
int32_t v;
std::memcpy(&v, row + c * 2, sizeof v);
return v;
};
auto value = [&](int64_t c) { return row[c * 2 + 1]; };
/* Selection sort over W*R entries (32 at world 2, R 16). */
std::vector<unsigned char> used((size_t)(W * R), 0);
for (int64_t r = 0; r < R; ++r) {
int64_t best = -1;
float bv = 0.0f;
int32_t bid = 0;
for (int64_t c = 0; c < W * R; ++c) {
if (used[(size_t)c]) continue;
int32_t id;
std::memcpy(&id, row + c * 2, sizeof id);
if (id < 0) continue; /* a pad, not a candidate */
const float v = row[c * 2 + 1];
if (best < 0 || v > bv || (v == bv && id < bid)) { best = c; bv = v; bid = id; }
}
const int64_t best = next_best(W * R, id, value, used);
if (best >= 0) used[(size_t)best] = 1;
st_int(idx->dtype, idx->data, rowoff(idx, m, R) + r * laststride(idx),
best >= 0 ? (int64_t)bid : -1);
stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? bv : -INFINITY);
best >= 0 ? (int64_t)id(best) : -1);
stt(val, rowoff(val, m, R) + r * laststride(val), best >= 0 ? value(best) : -INFINITY);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pair_argmax */
/* row_topk_merge at R = 1, for a caller that wants the winner's id as a PROPOSAL rather than as
* a candidate list: one element a row, at the output's own pitch, so a block drafter's per-position
* picks land contiguous in the token buffer it verifies. `pairs` is the same gathered plane --
* `n` (int32 id, f32 value) pairs a row, a negative id a pad -- and the rule is the same: the
* largest value, ties to the LOWER id, so the pick equals an argmax over the unsharded row.
/* The top-1 of a gathered pair plane as a proposal: one id per row at the output's pitch, so a block
* drafter's per-position picks land contiguous in the token buffer it verifies. `pairs` holds `n`
* (int32 id, f32 value) pairs per row, a negative id being a pad; largest value wins, ties to the
* lower id, matching an argmax over the unsharded row.
*
* Its own op rather than row_topk_merge with R = 1 because the shapes differ where it matters:
* row_topk_merge's `gathered` is world_size * R pairs a row, and a rank that sends R = 1 sends 8
* bytes, which a row-interleaved all_gather moving whole 16-byte words cannot carry. So a rank
* sends R >= 2 and this takes the top-1 of all of them, whatever `n` that makes. A row with no
* valid pair writes -1 and -inf, as the merge does for a slot it cannot fill. `val` is optional. */
* Not row_topk_merge with R = 1: a rank sending R = 1 sends 8 bytes, which a row-interleaved
* all_gather of 16-byte words cannot carry, so ranks send R >= 2 and this takes the top-1 of all
* `n`. A row with no valid pair writes -1 and -inf. `val` is optional. */
int ref_pair_argmax(const RadArgs* a, RadStream) {
if (!have(a, 2)) return RAD_E_INVAL;
const RadTensor *p = &a->t[0], *idx = &a->t[1];
@@ -507,12 +818,12 @@ int ref_pair_argmax(const RadArgs* a, RadStream) {
const int64_t n = p_int(a, "n", 0);
if (n <= 0) return RAD_E_SHAPE;
if (p->dtype != RAD_F32) return RAD_E_DTYPE; /* the id is carried by bit pattern */
/* The rows are the operand's, as on row_topk_merge: `M` is a band ceiling. */
/* Rows come from the operand; `M` is a band ceiling. */
const int64_t M = numel(p) / (n * 2);
if (M <= 0 || numel(idx) < M || (val && numel(val) < M)) return RAD_E_SHAPE;
const float* const pf = (const float*)p->data;
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * n)
for (int64_t m = 0; m < M; ++m) {
int32_t bid = -1;
float bv = -INFINITY;
@@ -530,27 +841,18 @@ int ref_pair_argmax(const RadArgs* a, RadStream) {
}
/* ------------------------------------------------------------------ logit_rerank */
/* EXACTLY RESCORE R CANDIDATES A ROW AGAINST THE FULL-PRECISION HEAD.
/* Rescore R candidates per row exactly against the full-precision head.
*
* A speculative step can afford a COARSE draft head -- the target verifies every proposal, so a
* worse draft costs acceptance and never a token -- but it cannot afford to be wrong about which
* candidate the coarse head liked best. A heavily quantised head disagrees with the exact one
* about the top-1 on a noticeable fraction of rows, and rescoring its top few candidates against
* the exact weight recovers nearly all of that disagreement.
* A speculative draft head may be coarse (the target verifies every proposal, so a worse draft
* costs only acceptance), but a heavily quantised head often disagrees with the exact one on the
* top-1. Rescoring its top few candidates against the exact weight recovers most of that, reading
* R rows of the head instead of all of it.
*
* So this is the second half of a coarse top-R: the coarse head proposes R, the exact weight
* scores those R and only those R, and the answer is re-sorted on the exact values. R rows of the
* head against the whole of it is the entire point -- a few hundred KB against a few hundred MB.
* `vocab_off` is the shard's first column; ids are global, as row_topk reports and row_topk_merge
* consumes them. A candidate outside this rank's rows becomes a pad.
*
* `vocab_off` IS THE SHARD'S FIRST COLUMN, and the ids are GLOBAL, because that is the form
* `row_topk` reports and `row_topk_merge` consumes. A candidate outside this rank's rows is not
* this rank's to score and becomes a pad: under vocab-parallel drafting `row_topk` picked from
* this rank's plane, so every id it reports is local and the guard is for a caller that mixes
* them.
*
* ORDER, AND WHY IT IS THE SAME ORDER row_topk USES: descending by value, ties to the LOWER id.
* The merge downstream breaks ties that way and the two have to agree, or a tie between shards
* resolves differently from a tie inside one. A pad sorts last and keeps id -1. */
* Output order matches row_topk: descending value, ties to the lower id, so the downstream merge
* resolves ties consistently. Pads sort last with id -1. */
int ref_logit_rerank(const RadArgs* a, RadStream) {
if (!have(a, 5)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *w = &a->t[1], *in = &a->t[2];
@@ -561,35 +863,44 @@ int ref_logit_rerank(const RadArgs* a, RadStream) {
const int64_t NV = p_int(a, "n_vocab", 0);
const int64_t voff = p_int(a, "vocab_off", 0);
if (R <= 0 || K <= 0 || NV <= 0) return RAD_E_SHAPE;
/* The rows are the OPERAND'S: `M` is a band ceiling and a step narrows it. */
/* Rows come from the operand; `M` is a band ceiling. */
const int64_t M = numel(x) / K;
if (M <= 0 || numel(in) < M * R) return RAD_E_SHAPE;
if (numel(idx) < M * R || numel(val) < M * R) return RAD_E_SHAPE;
if (numel(w) < NV * K) return RAD_E_SHAPE;
/* A head of codes and scale (ref_planes.h) is read element by element as the core's decoder
* gives it, so its scores are those of the decoded f32 head. */
ScaledRows sr;
const bool joined = is_joined(w);
if (joined) RAD_REF_TRY(scaled_rows(w, NV, K, &sr));
else if (numel(w) < NV * K) return RAD_E_SHAPE;
/* The pair plane is f32 words, ids carried by bit pattern, as row_topk writes it. */
if (pairs && (pairs->dtype != RAD_F32 || numel(pairs) < M * R * 2)) return RAD_E_SHAPE;
const int64_t ws = laststride(w);
#pragma omp parallel for schedule(static)
REF_PAR_FOR(M * R * K)
for (int64_t m = 0; m < M; ++m) {
std::vector<int32_t> id((size_t)R);
std::vector<float> sc((size_t)R);
for (int64_t r = 0; r < R; ++r) {
const int64_t g = ld_int(in->dtype, in->data, rowoff(in, m, R) + r * laststride(in));
const int64_t local = g - voff;
if (g < 0 || local < 0 || local >= NV) { id[(size_t)r] = -1; sc[(size_t)r] = -INFINITY; continue; }
double acc = 0.0; /* the reference sums wide and in order */
if (g < 0 || local < 0 || local >= NV) {
id[(size_t)r] = -1;
sc[(size_t)r] = -INFINITY;
continue;
}
double acc = 0.0; /* summed in double, in k order */
const int64_t wb = joined ? 0 : rowoff(w, local, K);
for (int64_t k = 0; k < K; ++k)
acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x))
* (double)ldt(w, local * K + k);
acc += (double)ldt(x, rowoff(x, m, K) + k * laststride(x)) *
(double)(joined ? sr.at(local, k) : ldt(w, wb + k * ws));
id[(size_t)r] = (int32_t)g;
sc[(size_t)r] = (float)acc;
}
std::vector<unsigned char> used((size_t)R, 0);
for (int64_t o = 0; o < R; ++o) {
int64_t best = -1;
for (int64_t c = 0; c < R; ++c) {
if (used[(size_t)c] || id[(size_t)c] < 0) continue;
if (best < 0 || sc[(size_t)c] > sc[(size_t)best] ||
(sc[(size_t)c] == sc[(size_t)best] && id[(size_t)c] < id[(size_t)best])) best = c;
}
const int64_t best = next_best(R, [&](int64_t c) { return id[(size_t)c]; },
[&](int64_t c) { return sc[(size_t)c]; }, used);
const int32_t oid = best >= 0 ? id[(size_t)best] : -1;
const float ov = best >= 0 ? sc[(size_t)best] : -INFINITY;
if (best >= 0) used[(size_t)best] = 1;