Archived
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:
1 parent
b068190326
commit
1e968f6e1d
739 files changed
+128447
-84632
No files matched your search
+232
-319
@@ -1,59 +1,78 @@
|
||||
/* ref_quant.cpp -- activation quantisation, the Walsh-Hadamard rotation, and the fused forms.
|
||||
*
|
||||
* Activations in this engine are ROTATED INT8, not fp8: several times better error at the same
|
||||
* width, and the rotation is what makes a single scale per row viable at all (docs/OPS.md).
|
||||
* ============================== What `group` means ==============================
|
||||
*
|
||||
* ============================== WHAT `group` MEANS ==============================
|
||||
* docs/OPS.md gives these ops one parameter `group` with different meanings; ref fixes them to
|
||||
* match the fast kernels:
|
||||
*
|
||||
* docs/OPS.md gives all five ops one parameter called `group` and it does not mean the same thing
|
||||
* in all five. Ref fixes the reading, because a fallback that guessed differently from the fast
|
||||
* kernel would produce plausible wrong numbers:
|
||||
* quant_act_i8 one scale per row; `group` is the width of the code sums `asum` holds.
|
||||
* quant_act_i8g contiguous elements sharing one f32 scale, so `scale` is [M, ceil(n/group)].
|
||||
* dequant the same, inverted: the scale stream's extent gives the group count and
|
||||
* `group` each group's width.
|
||||
* had_* the Walsh-Hadamard rotation width (libr4d's `had`); the int8 scale is per row
|
||||
* and carries the 1/sqrt(group) normalisation, as r4d_had_quant_act_i8 does. A
|
||||
* rotation block may not cross a tensor-parallel shard, so the width must divide
|
||||
* the per-rank n.
|
||||
*
|
||||
* quant_act_i8 `group` is the number of contiguous elements sharing one f32 scale, so `scale`
|
||||
* is [M, ceil(n/group)]. group <= 0 or group >= n is one scale per ROW, which is
|
||||
* what every int8 GEMM in libr4d consumes.
|
||||
* dequant the same reading, inverted: the scale stream's extent says how many groups
|
||||
* there are and `group` says how wide each is.
|
||||
* had_* `group` is the WALSH-HADAMARD ROTATION WIDTH (libr4d calls it `had`) and the
|
||||
* int8 scale is per ROW, carrying the 1/sqrt(group) normalisation. That is the
|
||||
* reading docs/OPS.md's own prose forces -- "the rotation (a per-group
|
||||
* Walsh-Hadamard) is what makes a single scale per row viable" -- and it is what
|
||||
* r4d_had_quant_act_i8 does. A rotation block may not cross a tensor-parallel
|
||||
* shard boundary, so the width has to divide the PER-RANK n.
|
||||
*
|
||||
* ============================== THE ROTATION ==============================
|
||||
* ============================== The rotation ==============================
|
||||
*
|
||||
* Unnormalised butterflies at ascending strides 1, 2, 4, ... group/2, pairing i with i+h where
|
||||
* (i & h) == 0 -- the same order and the same pairing as r4d_fwht.h, so the two agree bit for bit
|
||||
* on the same input. The 1/sqrt(group) is folded into the scale rather than applied to the values,
|
||||
* again because that is what the fast kernel does: dividing every element by a constant cannot
|
||||
* change which int8 code it rounds to, and folding it costs nothing.
|
||||
* (i & h) == 0: the order and pairing of r4d_fwht.h, so the two agree bit for bit. The 1/sqrt(group)
|
||||
* is folded into the scale, as the fast kernel does; scaling every element by a constant cannot
|
||||
* change its int8 code here.
|
||||
*/
|
||||
#include "ref_common.h"
|
||||
#include "ref_gemm.h" /* Mat and Scales: gemm_nt_q_gated reads a quantised operand the same way */
|
||||
#include "ref_gemm.h" /* Mat and Scales, for gemm_nt_q_gated */
|
||||
#include "ref_ops.h"
|
||||
|
||||
using namespace ref;
|
||||
|
||||
/* Symmetric int8 everywhere below: q = round(x * 127 / amax), scale = amax / 127, with the store
|
||||
* rounding to nearest and saturating (ref_common.h). An all-zero row gets scale 0 and codes 0,
|
||||
* which dequantises back to zero -- the alternative, a tiny epsilon scale, turns a zero row into
|
||||
* denormal noise in the GEMM that reads it. */
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8 */
|
||||
/* The activation of the w4a8, w8a8 and w2a8 GEMMs, with libr4d's arithmetic: one scale per row,
|
||||
* max(amax, 1e-8) / 127, and codes x * (1 / scale) rounded to nearest even, stored in the step
|
||||
* order (i8_step_pos). `asum`, when passed, receives each row's code sums per `group` columns,
|
||||
* group-major [n/group][Mpad] with Mpad = ceil(M/16)*16 (the asymmetric GEMMs read whole 16-row
|
||||
* tiles); rows M..Mpad-1 are not written. */
|
||||
int ref_quant_act_i8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
/* THE ASUM FORM IS A DIFFERENT CONTRACT, AND THIS DECLINES IT BY NAME. `asum` present selects
|
||||
* libr4d's asymmetric form, of which the extra output is only the visible half: that kernel
|
||||
* writes ONE SCALE PER ROW over the whole of `n` -- `group` is the asum grouping width there,
|
||||
* not the scale granularity -- and it stores `q` in fragment order rather than row-major. Run
|
||||
* beside it, the symmetric quantiser below compares neither plane against what it means.
|
||||
*
|
||||
* The name matters more than the declining. Without it the per-group scale plane this code
|
||||
* writes is simply wider than the per-row one the caller allocated, the size check refuses,
|
||||
* and a sweep reports the ENGINE'S operands as the fault -- the production 2-bit draft head's
|
||||
* quantiser among them. */
|
||||
if (a->n_t > 3 && a->t[3].data) return RAD_E_UNSUPPORTED;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const RadTensor* as = t_in(a, 3);
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0 || n % 16) return RAD_E_SHAPE; /* whole steps */
|
||||
if (q->dtype != RAD_I8) return RAD_E_DTYPE;
|
||||
if (laststride(q) != 1) return RAD_E_STRIDE;
|
||||
const int64_t rows = numel(x) / n;
|
||||
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
|
||||
const int64_t g = as ? p_int(a, "group", 0) : 0;
|
||||
const int64_t mpad = (rows + 15) / 16 * 16;
|
||||
if (as && (g <= 0 || n % g || numel(as) < n / g * mpad)) return RAD_E_SHAPE;
|
||||
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
|
||||
int8_t* qr = (int8_t*)q->data + rowoff(q, r, n);
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) amax = std::max(amax, std::fabs(ldt(x, xb + i * xs)));
|
||||
const float scale = std::max(amax, 1e-8f) / 127.0f;
|
||||
const float inv = 1.0f / scale;
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
st_dt(RAD_I8, qr, i8_step_pos(i), ldt(x, xb + i * xs) * inv);
|
||||
stt(s, rowoff(s, r, 1), scale);
|
||||
for (int64_t gi = 0; as && gi < n / g; ++gi) {
|
||||
int64_t sum = 0;
|
||||
for (int64_t i = gi * g; i < (gi + 1) * g; ++i) sum += qr[i8_step_pos(i)];
|
||||
stt(as, gi * mpad + r, (float)sum);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8g */
|
||||
/* quant_act_fp8 at int8 codes, libr4d's arithmetic: per `group` contiguous elements a scale
|
||||
* amax / 127 (1 for an all-zero group) and codes rounded to nearest even, row-major. What the
|
||||
* i8a8 GEMMs read. */
|
||||
int ref_quant_act_i8g(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
@@ -65,27 +84,48 @@ int ref_quant_act_i8(const RadArgs* a, RadStream) {
|
||||
const int64_t ngrp = (n + g - 1) / g;
|
||||
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
|
||||
const int64_t xs = laststride(x), qs = laststride(q);
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = k0; i < k1; ++i) {
|
||||
float m = std::fabs(ldt(x, xb + i * xs));
|
||||
if (m > amax) amax = m;
|
||||
}
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
for (int64_t i = k0; i < k1; ++i)
|
||||
st_dt(q->dtype, q->data, qb + i * qs, ldt(x, xb + i * xs) * inv);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
|
||||
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
|
||||
k1 - k0, 127.0f, q, qb + k0 * qs, qs);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The rotated forms below are symmetric int8 with one scale per row: q = round(x * 127 / amax),
|
||||
* scale = amax / 127, the store rounding to nearest and saturating (ref_common.h). An all-zero row
|
||||
* gets scale 0 and codes 0. */
|
||||
|
||||
/* ------------------------------------------------------------------ had_quant_act_i8 */
|
||||
/* The rotated int8 row of the had_*_i8 ops: `v(i)` for i < n rotated in blocks of `g`, its codes
|
||||
* stored at q[qb + i * qs] against one scale for the whole row (the amax is over the whole rotated
|
||||
* row). The rotation is computed twice, for the amax and then for the codes, rather than held.
|
||||
* Returns the row's scale, amax / 127 / sqrt(g). */
|
||||
template <class V>
|
||||
static float had_i8_row(const V& v, int64_t n, int64_t g, const RadTensor* q, int64_t qb,
|
||||
int64_t qs) {
|
||||
float buf[REF_HAD_MAX];
|
||||
float amax = 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
|
||||
}
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = v(b + i);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i) st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
|
||||
}
|
||||
return amax / 127.0f * (1.0f / std::sqrt((float)g));
|
||||
}
|
||||
|
||||
int ref_had_quant_act_i8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
@@ -95,47 +135,27 @@ int ref_had_quant_act_i8(const RadArgs* a, RadStream) {
|
||||
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t rows = numel(x) / n;
|
||||
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
|
||||
const float norm = 1.0f / std::sqrt((float)g);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n * 8)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float buf[REF_HAD_MAX];
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
|
||||
const int64_t xs = laststride(x), qs = laststride(q);
|
||||
/* amax is over the WHOLE rotated row, because the scale is per row. */
|
||||
float amax = 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
|
||||
}
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (b + i) * xs);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i)
|
||||
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
|
||||
}
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
|
||||
stt(s, r * laststride(s), had_i8_row([&](int64_t i) { return ldt(x, xb + i * xs); }, n, g,
|
||||
q, rowoff(q, r, n), laststride(q)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */
|
||||
/* The fused form of rmsnorm + hadamard + quant_act_i8, which is what a w4a8 layer wants where a
|
||||
* bf16 layer wants a plain rmsnorm (spec §2.3). A plugin asks for this first and emits the three
|
||||
* unfused ops when it does not resolve; ref resolves it, so the fallback path is one launch.
|
||||
/* Fused rmsnorm + hadamard + quant_act_i8, what a w4a8 layer uses in place of a plain rmsnorm
|
||||
* (spec §2.3). A plugin asks for this first and falls back to the three unfused ops.
|
||||
*
|
||||
* `residual` PRESENT IS THE fused_add_rms_norm FORM: the add happens first, the sum is written
|
||||
* back into `residual` (that is what makes it INOUT and what the next layer's shortcut reads), and
|
||||
* the norm is taken over the sum. The variance comes from the f32 sum and the rotation reads the
|
||||
* sum back AFTER it has been narrowed to the residual tensor's own dtype, which is what the pair
|
||||
* of kernels this replaces does -- matching it is what makes the fused form substitutable for
|
||||
* that pair.
|
||||
* With `residual` it is the fused_add_rms_norm form: the sum is written back to `residual` (INOUT;
|
||||
* the next layer's shortcut reads it) and the norm is over the sum. The variance comes from the f32
|
||||
* sum, but the rotation reads the sum back after narrowing to the residual's dtype, as the unfused
|
||||
* pair does.
|
||||
*
|
||||
* `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer of
|
||||
* it. Pre-rotation because the rotation is an artefact of the int8 path; a bf16 consumer wants the
|
||||
* normalised activation, not a Walsh-Hadamard of it. */
|
||||
* `out_bf16` is the post-norm, pre-rotation tensor for a bf16 consumer; the rotation belongs only
|
||||
* to the int8 path. */
|
||||
int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 5) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *w = &a->t[2], *q = &a->t[3], *s = &a->t[4];
|
||||
@@ -152,28 +172,25 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows || numel(w) < n) return RAD_E_SHAPE;
|
||||
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
|
||||
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
|
||||
const float norm = 1.0f / std::sqrt((float)g);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n * 8)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float buf[REF_HAD_MAX];
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
|
||||
const int64_t xs = laststride(x), qs = laststride(q), ws = laststride(w);
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w);
|
||||
|
||||
/* The residual add, written back before anything reads it, so what follows reads the
|
||||
* narrowed sum rather than the f32 one. */
|
||||
/* The variance is taken from the f32 sum as it is written back; everything after reads
|
||||
* the narrowed sum. */
|
||||
const int64_t rb = res ? rowoff(res, r, n) : 0;
|
||||
const int64_t rst = res ? laststride(res) : 1;
|
||||
if (res)
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
stt(res, rb + i * rst, ldt(x, xb + i * xs) + ldt(res, rb + i * rst));
|
||||
|
||||
auto src = [&](int64_t i) {
|
||||
return res ? ldt(res, rb + i * rst) : ldt(x, xb + i * xs);
|
||||
};
|
||||
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) { const float v = src(i); ss += v * v; }
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float v = res ? ldt(x, xb + i * xs) + ldt(res, rb + i * rst) : src(i);
|
||||
if (res) stt(res, rb + i * rst, v);
|
||||
ss += v * v;
|
||||
}
|
||||
const float sc = 1.0f / std::sqrt(ss / (float)n + eps);
|
||||
|
||||
if (ob) {
|
||||
@@ -182,37 +199,20 @@ int ref_rmsnorm_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
stt(ob, obb + i * obs, src(i) * sc * (ldt(w, i * ws) + wadd));
|
||||
}
|
||||
|
||||
float amax = 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i)
|
||||
buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
|
||||
}
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i)
|
||||
buf[i] = src(b + i) * sc * (ldt(w, (b + i) * ws) + wadd);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i)
|
||||
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
|
||||
}
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
auto normed = [&](int64_t i) { return src(i) * sc * (ldt(w, i * ws) + wadd); };
|
||||
stt(s, r * laststride(s), had_i8_row(normed, n, g, q, rowoff(q, r, n), laststride(q)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gated_had_quant_i8 */
|
||||
/* An elementwise gated product, then the rotation and the quantiser. Two of the four rotated sites
|
||||
* in a w4a8 model have this shape and differ by one multiply, so `act` picks between them:
|
||||
* silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a gated-attention layer
|
||||
* (Qwen3_5Attention computes attn_output * sigmoid(gate)). It defaults to silu, which is the form
|
||||
* docs/OPS.md's `silu_mul` names. `mode` is libr4d's integer spelling of the same choice and is
|
||||
* accepted where `act` is absent, so a caller written against either name works.
|
||||
/* An elementwise gated product, then the rotation and the quantiser. Two of a w4a8 model's four
|
||||
* rotated sites have this shape: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a
|
||||
* gated-attention layer (Qwen3_5Attention's attn_output * sigmoid(gate)). `act` picks, default silu
|
||||
* (docs/OPS.md's `silu_mul`); libr4d's integer `mode` is accepted where `act` is absent.
|
||||
*
|
||||
* `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], the gate is its first half and the up its second.
|
||||
* That is vLLM's layout and the one a fused gate_up projection produces, so both readings have to
|
||||
* exist; two operands with the second optional is the only shape that expresses both. */
|
||||
* With `b` absent, `a` is the packed [M, 2n] form (gate first half, up second), vLLM's layout and
|
||||
* what a fused gate_up projection produces. */
|
||||
int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 4) return RAD_E_INVAL;
|
||||
const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3];
|
||||
@@ -229,13 +229,10 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
if (rows <= 0 || numel(s) < rows) return RAD_E_SHAPE;
|
||||
if (numel(ga) < rows * (up ? n : 2 * n)) return RAD_E_SHAPE;
|
||||
if (up && numel(up) < rows * n) return RAD_E_SHAPE;
|
||||
const float norm = 1.0f / std::sqrt((float)g);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n * 8)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float buf[REF_HAD_MAX];
|
||||
const int64_t gb = rowoff(ga, r, up ? n : 2 * n), qb = rowoff(q, r, n);
|
||||
const int64_t gs = laststride(ga), qs = laststride(q);
|
||||
const int64_t gb = rowoff(ga, r, up ? n : 2 * n), gs = laststride(ga);
|
||||
const int64_t ub = up ? rowoff(up, r, n) : 0;
|
||||
const int64_t us = up ? laststride(up) : 0;
|
||||
auto gated = [&](int64_t i) {
|
||||
@@ -243,29 +240,14 @@ int ref_gated_had_quant_i8(const RadArgs* a, RadStream) {
|
||||
const float x = up ? ldt(up, ub + i * us) : ldt(ga, gb + (n + i) * gs);
|
||||
return (act == 1 ? act_sigmoid(gate) : act_silu(gate)) * x;
|
||||
};
|
||||
float amax = 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i) { float m = std::fabs(buf[i]); if (m > amax) amax = m; }
|
||||
}
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
for (int64_t b = 0; b < n; b += g) {
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = gated(b + i);
|
||||
fwht(buf, g);
|
||||
for (int64_t i = 0; i < g; ++i)
|
||||
st_dt(q->dtype, q->data, qb + (b + i) * qs, buf[i] * inv);
|
||||
}
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
stt(s, r * laststride(s), had_i8_row(gated, n, g, q, rowoff(q, r, n), laststride(q)));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ dequant */
|
||||
/* q * scale, with the scale stream's own extent deciding how many groups there are. The inverse of
|
||||
* quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op
|
||||
* that silently did one would make `dequant(had_quant(x)) == x` look true when the two have
|
||||
* different meanings. A caller that wants the rotation undone asks for it. */
|
||||
/* q * scale, the scale stream's extent giving the group count. The inverse of quant_act_i8g only,
|
||||
* not of the rotated forms: undoing a rotation is a separate Hadamard the caller must request. */
|
||||
int ref_dequant(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2];
|
||||
@@ -278,7 +260,7 @@ int ref_dequant(const RadArgs* a, RadStream) {
|
||||
if (g <= 0) g = (n + ngrp - 1) / ngrp;
|
||||
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t qb = rowoff(q, r, n), yb = rowoff(y, r, n), sb = rowoff(s, r, ngrp);
|
||||
const int64_t qs = laststride(q), ys = laststride(y), ss = laststride(s);
|
||||
@@ -293,27 +275,19 @@ int ref_dequant(const RadArgs* a, RadStream) {
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_fp8
|
||||
*
|
||||
* The oracle for the block-scaled FP8 family. Without a reference for `quant_act_fp8` the one
|
||||
* activation format the production checkpoints ship in is the one format rad-kbench cannot
|
||||
* measure (spec §17).
|
||||
* The oracle for the block-scaled FP8 family, the activation format the production checkpoints
|
||||
* use (spec §17). The arithmetic is r4d_quant_act_fp8.hip's, agreeing on three choices:
|
||||
*
|
||||
* The arithmetic is r4d_quant_act_fp8.hip's, restated rather than approximated, because the two
|
||||
* have to agree on three choices that are all defensible and none of which are derivable:
|
||||
* 448 E4M3's largest finite value; the scale is `amax / 448`, a dequant multiplier like
|
||||
* the checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales.
|
||||
* scale 1 for an all-zero group (amax / 448 would have an infinite reciprocal): the GEMM
|
||||
* multiplies the two block scales, and a zero would erase the weight's.
|
||||
* the clamp `amax * (1/scale)` is 448 exactly but can round an ulp above once the reciprocal is
|
||||
* rounded, which would encode as NaN.
|
||||
*
|
||||
* 448 E4M3's largest finite value, and the scale is `amax / 448` -- a DEQUANT multiplier,
|
||||
* the same sense as the checkpoint's `weight_scale_inv`, so the GEMM's fold
|
||||
* multiplies the two scales together and nothing has to be inverted.
|
||||
* scale 1 for an all-zero group, where `amax / 448` is zero and its reciprocal infinite. NOT
|
||||
* the zero scale ref_quant_act_i8 uses: that kernel's consumers read a per-row int8
|
||||
* scale and a zero row is a zero row, while here the GEMM multiplies the two block
|
||||
* scales and a zero would erase the weight's.
|
||||
* the clamp is not defensive. `amax * (1/scale)` is 448 in exact arithmetic and can land an ulp
|
||||
* above it once the reciprocal is rounded, which encodes as a NaN rather than as the
|
||||
* largest finite.
|
||||
*
|
||||
* `M` and `n` are the ROW COUNT and the ROW WIDTH, and rows are dim 0 -- so a rank-3 activation
|
||||
* ([tokens, heads, width], which is what a GDN block hands its out-projection) is one row per
|
||||
* token, not one per head. That is the reading the consuming GEMM forces: `n` is its K.
|
||||
* `M` and `n` are the row count and width with rows along dim 0, so a rank-3 activation
|
||||
* ([tokens, heads, width], a GDN block's out-projection input) is one row per token: `n` is the
|
||||
* consuming GEMM's K.
|
||||
*/
|
||||
int ref_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
@@ -328,25 +302,14 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
const int64_t ngrp = (n + g - 1) / g;
|
||||
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
|
||||
const int64_t xs = laststride(x), qs = laststride(q);
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = k0; i < k1; ++i) {
|
||||
const float m = std::fabs(ldt(x, xb + i * xs));
|
||||
if (m > amax) amax = m;
|
||||
}
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
for (int64_t i = k0; i < k1; ++i) {
|
||||
float v = ldt(x, xb + i * xs) * inv;
|
||||
if (v > 448.0f) v = 448.0f;
|
||||
if (v < -448.0f) v = -448.0f;
|
||||
st_dt(q->dtype, q->data, qb + i * qs, v);
|
||||
}
|
||||
const float sc = q8_group([&](int64_t i) { return ldt(x, xb + (k0 + i) * xs); },
|
||||
k1 - k0, 448.0f, q, qb + k0 * qs, qs);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
}
|
||||
@@ -354,27 +317,23 @@ int ref_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- had_quant_act_fp8 */
|
||||
/* The same quantiser with a `group`-wide Hadamard in front of the absmax, which is the only place
|
||||
* a rotation can go: the whole benefit is that the maximum the grid is scaled by gets smaller.
|
||||
/* The same quantiser with a `group`-wide Hadamard before the absmax, which lowers the maximum the
|
||||
* grid is scaled by.
|
||||
*
|
||||
* THE sqrt(g) IS NOT UNDONE HERE, and that is a DELIBERATE difference from ref_had_quant_act_i8
|
||||
* above, which folds 1/sqrt(g) into its own scale. H is symmetric, so
|
||||
* <Hw, Ha> = g <w, a>, and the residual g has to be divided out exactly once between the two
|
||||
* sides. The int8 op splits it; this one gives the WHOLE factor to the weight, where dividing a
|
||||
* bf16 scale by a power of two is an exponent shift and therefore exact. Splitting it would make
|
||||
* the stored weight scale bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g -- and the codes were
|
||||
* chosen against amax/7, so that rounding lands as a ~0.2% multiplicative error on every group,
|
||||
* which is a fifth of the int4 grid's own error bought for nothing.
|
||||
* Unlike ref_had_quant_act_i8, the sqrt(g) is not undone here. H is symmetric, so
|
||||
* <Hw, Ha> = g <w, a>, and g must be divided out once between the two sides. This op gives the
|
||||
* whole factor to the weight, where dividing a bf16 scale by a power of two is exact. Splitting it
|
||||
* would store bf16(amax/7/sqrt(g)) instead of bf16(amax/7)/g against codes chosen for amax/7, a
|
||||
* ~0.2% error per group (a fifth of the int4 grid's own error).
|
||||
*
|
||||
* So this op's output is NOT interchangeable with quant_act_fp8's, and its consumer is not free
|
||||
* either: only a weight plane stored as w4a8h carries the matching rotation and the matching /g. */
|
||||
* The output is not interchangeable with quant_act_fp8's: only a weight plane stored as w4a8h
|
||||
* carries the matching rotation and /g. */
|
||||
int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
const int64_t g = p_int(a, "group", 0);
|
||||
/* n % g != 0 is refused rather than rounded: a rotation block that straddled the end of the
|
||||
* row would mix real values with padding, and no weight block was rotated that way. */
|
||||
/* n % g != 0 is refused: no weight block was rotated across the row's end. */
|
||||
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
|
||||
if (g > REF_HAD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t rows = numel(x) / n;
|
||||
@@ -382,7 +341,7 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
if (rows <= 0 || numel(q) < rows * n) return RAD_E_SHAPE;
|
||||
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n * 8)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float buf[REF_HAD_MAX];
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, n);
|
||||
@@ -391,19 +350,8 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
const int64_t k0 = gi * g;
|
||||
for (int64_t i = 0; i < g; ++i) buf[i] = ldt(x, xb + (k0 + i) * xs);
|
||||
fwht(buf, g);
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = 0; i < g; ++i) {
|
||||
const float m = std::fabs(buf[i]);
|
||||
if (m > amax) amax = m;
|
||||
}
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
for (int64_t i = 0; i < g; ++i) {
|
||||
float v = buf[i] * inv;
|
||||
if (v > 448.0f) v = 448.0f;
|
||||
if (v < -448.0f) v = -448.0f;
|
||||
st_dt(q->dtype, q->data, qb + (k0 + i) * qs, v);
|
||||
}
|
||||
const float sc = q8_group([&](int64_t i) { return buf[i]; }, g, 448.0f, q,
|
||||
qb + k0 * qs, qs);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
}
|
||||
@@ -411,20 +359,19 @@ int ref_had_quant_act_fp8(const RadArgs* a, RadStream) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- givens_rotate */
|
||||
/* ParoQuant's activation side: every row scaled by its channel factors and rotated by `stages` rounds of
|
||||
* disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
|
||||
* (abi/rad_encoding.h, "givens") meets the activation x . D^-1 . G_1 ... G_S, because
|
||||
* <v, x D^-1 G_1..G_S> = <w, x> and each G is orthogonal. For a weight whose GEMM reads a 16-bit
|
||||
* activation (w5a16); the quantising form is givens_dense_quant, over the composed matrices.
|
||||
/* ParoQuant's activation side: each row divided by its channel factors and rotated by `stages`
|
||||
* rounds of disjoint Givens pairs, written in y's dtype. A weight stored as v = w . D . G_1 ... G_S
|
||||
* (abi/rad_encoding.h, "givens") meets x . D^-1 . G_1 ... G_S, since each G is orthogonal and so
|
||||
* <v, x D^-1 G_1..G_S> = <w, x>. For GEMMs reading a 16-bit activation (w5a16); the quantising
|
||||
* form is givens_dense_quant.
|
||||
*
|
||||
* PARTS. A fused projection (gate|up, q|k|v) was rotated per piece, so a row has `parts` rotated
|
||||
* copies, written side by side: y is [rows, parts * n], part p at columns [p*n, (p+1)*n). The tables
|
||||
* stack the parts: pairs and angle `stages` rows each, scale one row, per part. A part's pairs address
|
||||
* columns of the row and stay inside one group of `group` (the checkpoint's are within groups of 128).
|
||||
* Parts: a fused projection (gate|up, q|k|v) was rotated per piece, so y is [rows, parts * n] with
|
||||
* part p at columns [p*n, (p+1)*n). The tables stack per part: `stages` rows of pairs and angles,
|
||||
* one row of scales. A part's pairs stay within one `group` (128 in the checkpoints).
|
||||
*
|
||||
* The arithmetic is the device kernel's, restated: the divide by the channel scale, then for each
|
||||
* stage a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical to the device on the
|
||||
* angle: cos and sin of an f32 differ by an ulp between libm and the GPU's. */
|
||||
* The device kernel's arithmetic: divide by the channel scale, then per stage
|
||||
* a' = a cos t + b sin t, b' = b cos t - a sin t in f32. Not bit-identical: libm's and the GPU's
|
||||
* cos and sin differ by an ulp. */
|
||||
int ref_givens_rotate(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *pr = &a->t[1], *an = &a->t[2], *sc = &a->t[3], *q = &a->t[4];
|
||||
@@ -442,7 +389,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
|
||||
if (c < 0 || c >= n) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * P * n * S)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
std::vector<float> buf((size_t)n);
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
|
||||
@@ -454,7 +401,7 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
|
||||
for (int64_t j = 0; j < n / 2; ++j) {
|
||||
const int64_t ia = ld_int(pr->dtype, pr->data, t0 + 2 * j);
|
||||
const int64_t ib = ld_int(pr->dtype, pr->data, t0 + 2 * j + 1);
|
||||
const float th = ldt(an, a0 + j), c = std::cos(th), sn = std::sin(th);
|
||||
const float th = ldt(an, a0 + j), c = ref_cos(th), sn = ref_sin(th);
|
||||
const float va = buf[(size_t)ia], vb = buf[(size_t)ib];
|
||||
buf[(size_t)ia] = va * c + vb * sn;
|
||||
buf[(size_t)ib] = vb * c - va * sn;
|
||||
@@ -466,9 +413,9 @@ int ref_givens_rotate(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ParoQuant's activation quantiser: the rotation applied as the dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i] over
|
||||
* each (part, 128-column group), then the quantiser `q`'s dtype names. T is the weight, f16, one [128, 128]
|
||||
* matrix a (part, group) -- what rad-convert composes from the givens tables and stores as "t.dense". */
|
||||
/* ParoQuant's activation quantiser: the rotation as a dense matrix, y[j] = sum_i T[j][i] * x[i] / D[i]
|
||||
* per (part, 128-column group), then the quantiser named by `q`'s dtype. T is an f16 weight, one
|
||||
* [128, 128] matrix per (part, group), composed by rad-convert from the givens tables ("t.dense"). */
|
||||
int ref_givens_dense_quant(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *tm = &a->t[1], *sc = &a->t[2], *q = &a->t[3], *s = &a->t[4];
|
||||
@@ -481,7 +428,7 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) {
|
||||
if (rows <= 0 || numel(tm) < P * n * g || numel(sc) < P * n || numel(q) < rows * P * n ||
|
||||
numel(s) < rows * P * ngrp) return RAD_E_SHAPE;
|
||||
const float qmax = i8 ? 127.0f : 448.0f;
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * P * n * g)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), qb = rowoff(q, r, P * n);
|
||||
const int64_t xs = laststride(x), qs = laststride(q);
|
||||
@@ -516,22 +463,17 @@ int ref_givens_dense_quant(const RadArgs* a, RadStream) {
|
||||
|
||||
/* ---------------------------------------------------------------- the Gram accumulator
|
||||
*
|
||||
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], where x is the DEQUANTISED E4M3 input, or
|
||||
* a bf16 input as it stands when no scale is passed -- the second moment GPTQ's error feedback
|
||||
* needs, over exactly the operand the expert GEMM contracts. libr4d's kernel is the device half;
|
||||
* this is the oracle for it.
|
||||
* h[k1][k2] += sum over rows of x[m][k1] * x[m][k2], x being the dequantised E4M3 input (or a bf16
|
||||
* input as is when no scale is passed): the second moment GPTQ needs, over exactly the operand the
|
||||
* expert GEMM contracts. Oracle for libr4d's device kernel.
|
||||
*
|
||||
* THE ACCUMULATOR IS READ AS WELL AS WRITTEN, which is the one thing a reader coming from every
|
||||
* other op in this file has to hold: `h` is INOUT, the caller zeroes it once, and each call adds
|
||||
* its own block. An oracle that stored instead of added would agree with the kernel on a single
|
||||
* call and disagree on a corpus.
|
||||
* `h` is INOUT and accumulates: the caller zeroes it once and each call adds its block.
|
||||
*
|
||||
* Rows are dequantised once into a scratch plane rather than inside the k2 loop: the triple loop
|
||||
* is O(n^2 * rows) and a per-element dtype dispatch inside it is the difference between an oracle
|
||||
* that finishes and one that does not. The accumulation is f64 here and f32 on the device on
|
||||
* purpose -- an oracle should be tighter than the thing it checks, not bit-identical to it. */
|
||||
* Rows are dequantised once into a scratch plane, keeping the dtype dispatch out of the
|
||||
* O(n^2 * rows) loop. Accumulation is deliberately f64 here (f32 on the device): this oracle is
|
||||
* meant to be tighter than the kernel, not bit-identical. */
|
||||
int ref_gram_accum(const RadArgs* a, RadStream) {
|
||||
/* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */
|
||||
/* `a_scale` is optional; absent, `a` is read as is (the bf16 form). */
|
||||
if (a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor *x = t_in(a, 0), *s = t_in(a, 1), *h = t_in(a, 2);
|
||||
if (!x || !h) return RAD_E_INVAL;
|
||||
@@ -544,7 +486,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
|
||||
if (h->rank != 2 || h->shape[0] != n || h->shape[1] != n) return RAD_E_SHAPE;
|
||||
|
||||
std::vector<float> xs((size_t)rows * (size_t)n);
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), xst = laststride(x);
|
||||
const int64_t sb = s ? rowoff(s, r, ngrp) : 0, sst = s ? laststride(s) : 0;
|
||||
@@ -554,7 +496,7 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
|
||||
}
|
||||
|
||||
const int64_t hst = laststride(h);
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(n * n * rows)
|
||||
for (int64_t k1 = 0; k1 < n; ++k1) {
|
||||
const int64_t hb = rowoff(h, k1, n);
|
||||
for (int64_t k2 = 0; k2 < n; ++k2) {
|
||||
@@ -571,42 +513,29 @@ int ref_gram_accum(const RadArgs* a, RadStream) {
|
||||
|
||||
/* ======================================================================== the fp8 fusions
|
||||
*
|
||||
* THREE OPS THAT EXIST SO THAT A HOST RUN IS POSSIBLE AT ALL. libr4d fuses the fp8 activation
|
||||
* quantiser into whichever kernel already has the row in registers, and declares the fused form as
|
||||
* its own op. Without a host kernel for those names, a host-backend run -- the only thing that
|
||||
* can answer "is the GRAPH right", because the per-op oracle reads the same graph both sides --
|
||||
* cannot start on an fp8 model ("site 'host' is unavailable for this band").
|
||||
* libr4d fuses the fp8 activation quantiser into whichever kernel already has the row in
|
||||
* registers and declares the fused form as its own op. These host kernels for those names let a
|
||||
* host-backend run start on an fp8 model; that run is the only check of the graph itself, since the
|
||||
* per-op oracle reads the same graph on both sides.
|
||||
*
|
||||
* These are the unfused arithmetic written out in one pass, which is what a reference is for. They
|
||||
* are NOT required to be bit-identical to libr4d's kernels the way those kernels are required to be
|
||||
* bit-identical to the pair they replace: the oracle compares within a tolerance, and a reference
|
||||
* that chased the device's rounding would stop being a statement of what the op MEANS.
|
||||
*
|
||||
* WHAT THEY DO FOLLOW is the bf16 round-trip, because that is meaning and not rounding. The unfused
|
||||
* pair writes a bf16 intermediate and the quantiser reads those bytes back, so the codes are taken
|
||||
* over a bf16-narrowed value; a reference that quantised the f32 would be a different function, and
|
||||
* `out_bf16` -- which the caller may ask for precisely so the fused and unfused forms leave the same
|
||||
* buffers behind -- would not hold the value the codes were taken over.
|
||||
* Each is the unfused arithmetic in one pass. They need not be bit-identical to libr4d's kernels;
|
||||
* the oracle compares within a tolerance. They do follow the bf16 round-trip, which changes the
|
||||
* function: the unfused pair writes a bf16 intermediate and quantises those bytes, so codes are
|
||||
* taken over the narrowed value and `out_bf16` holds exactly the value the codes came from.
|
||||
*/
|
||||
|
||||
/* One group-scaled fp8 row, from values already in `v`. The scale layout is quant_act_fp8's and
|
||||
* the reason for each constant is written there. */
|
||||
/* One group-scaled fp8 row from the values in `v`; constants and scale layout as quant_act_fp8.
|
||||
* An int8 `q` (an int8 linear's input, ActFP8::q8_fed) takes quant_act_i8g's codes instead, scale
|
||||
* amax / 127, as libr4d's fused quantisers write them. */
|
||||
static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor* q,
|
||||
const RadTensor* s, int64_t r) {
|
||||
const int64_t ngrp = (n + g - 1) / g;
|
||||
const int64_t qb = rowoff(q, r, n), qs = laststride(q);
|
||||
const float top = q->dtype == RAD_I8 ? 127.0f : 448.0f;
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
|
||||
float amax = 0.0f;
|
||||
for (int64_t i = k0; i < k1; ++i) { const float m = std::fabs(v[i]); if (m > amax) amax = m; }
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
for (int64_t i = k0; i < k1; ++i) {
|
||||
float c = v[i] * inv;
|
||||
if (c > 448.0f) c = 448.0f;
|
||||
if (c < -448.0f) c = -448.0f;
|
||||
st_dt(q->dtype, q->data, qb + i * qs, c);
|
||||
}
|
||||
const float sc = q8_group([&](int64_t i) { return v[k0 + i]; }, k1 - k0, top, q,
|
||||
qb + k0 * qs, qs);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
}
|
||||
@@ -614,11 +543,10 @@ static inline void fp8_row(const float* v, int64_t n, int64_t g, const RadTensor
|
||||
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
|
||||
/* `x`, `residual`:inout?, `w`w -> `q`, `scale`, `out_bf16`?
|
||||
*
|
||||
* residual present is the fused_add_rms_norm form, and the add is STORED BEFORE THE VARIANCE READS
|
||||
* IT -- the sum the norm is taken over is the bf16-narrowed one, not the f32 one. libr4d's kernel
|
||||
* makes the same choice and says at length why: the pair it replaces writes a bf16 residual and
|
||||
* reads those bytes back, and half a ULP per channel is the difference between the same text and
|
||||
* very nearly the same text. `wadd` is added to every gain in f32 for the reason ref_rmsnorm gives.
|
||||
* With `residual` it is the fused_add_rms_norm form, and the sum is stored before the variance
|
||||
* reads it, so the norm is over the bf16-narrowed sum (as libr4d's kernel and the unfused pair do).
|
||||
* Unlike ref_rmsnorm_add, the variance also uses the narrowed sum. `wadd` is added to each gain in
|
||||
* f32, as in ref_rmsnorm.
|
||||
*/
|
||||
int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 5) return RAD_E_INVAL;
|
||||
@@ -639,7 +567,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
|
||||
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
|
||||
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
std::vector<float> v((size_t)n);
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x), ws = laststride(w);
|
||||
@@ -654,8 +582,7 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
|
||||
for (int64_t i = 0; i < n; ++i) { const float t = src(i); ss += t * t; }
|
||||
const float rs = 1.0f / std::sqrt(ss / (float)n + eps);
|
||||
|
||||
/* NARROWED TO BF16 AND THEN QUANTISED, and written out where asked. The codes belong to
|
||||
* the value `out_bf16` holds; taking them over the f32 would make the two disagree. */
|
||||
/* Narrow to bf16, write `out_bf16` if asked, then quantise those values. */
|
||||
const int64_t obb = ob ? rowoff(ob, r, n) : 0;
|
||||
const int64_t obs = ob ? laststride(ob) : 1;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
@@ -671,9 +598,8 @@ int ref_rmsnorm_quant_fp8(const RadArgs* a, RadStream) {
|
||||
/* ------------------------------------------------------------- gated_quant_fp8 */
|
||||
/* `gate_up` -> `q`, `scale`, `out_bf16`?
|
||||
*
|
||||
* The packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's
|
||||
* input) from sigmoid(gate)*up (a gated attention o_proj's), the same two ref_gated_had_quant_i8
|
||||
* takes and under the same two names. */
|
||||
* Packed form only: `gate_up` is [M, 2n], gate first. `act` picks silu(gate)*up (down_proj's input)
|
||||
* or sigmoid(gate)*up (a gated-attention o_proj's), as in ref_gated_had_quant_i8. */
|
||||
int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
@@ -690,7 +616,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
|
||||
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(rows * n)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
std::vector<float> v((size_t)n);
|
||||
const int64_t gb = rowoff(gu, r, 2 * n), gs = laststride(gu);
|
||||
@@ -699,7 +625,7 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float gt = ldt(gu, gb + i * gs);
|
||||
const float up = ldt(gu, gb + (n + i) * gs);
|
||||
const float sg = 1.0f / (1.0f + std::exp(-gt));
|
||||
const float sg = act_sigmoid(gt);
|
||||
const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up);
|
||||
if (ob) stt(ob, obb + i * obs, bf16_to_f32(h));
|
||||
v[(size_t)i] = bf16_to_f32(h);
|
||||
@@ -712,32 +638,21 @@ int ref_gated_quant_fp8(const RadArgs* a, RadStream) {
|
||||
/* ------------------------------------------------------------- gemm_nt_q_gated */
|
||||
/* `a`, `a_scale`, `b`w, `b_scale`w -> `q`, `scale`, `out_bf16`?
|
||||
*
|
||||
* gemm_nt_q over a [N, K] gate_up plane -- N is the WEIGHT's rows, twice the fused width, gate half
|
||||
* first -- with gated_quant_fp8's pass in the epilogue, so the [M, N] bf16 tensor between them is
|
||||
* never written. `act` is REQUIRED here and optional on the quantiser, for the reason docs/OPS.md
|
||||
* gives: an implementation is free to compile one gate, and an optional parameter would let it
|
||||
* resolve for another.
|
||||
* gemm_nt_q over an [N, K] gate_up plane (N the weight's rows, twice the fused width, gate half
|
||||
* first) with gated_quant_fp8 in the epilogue, so the [M, N] bf16 intermediate is never written.
|
||||
* `act` is required here, unlike on the quantiser (docs/OPS.md): an implementation may compile one
|
||||
* gate, and an optional parameter would let it resolve for the other.
|
||||
*
|
||||
* BYTE-IDENTICAL TO THE PAIR IT REPLACES, which is a requirement and not a hope -- the libr4d row
|
||||
* that serves this op makes the same claim, and a fold that is a slightly different function from
|
||||
* gemm_nt_q followed by gated_quant_fp8 is a different model. Two things earn it here: the product
|
||||
* comes from `quant_dot`, which is also what gemm_nt_q's plane comes from and is the one place the
|
||||
* grouping and the scale order are written down; and both halves are narrowed to bf16 BEFORE the
|
||||
* gate, because the unfused form writes a bf16 [M, N] tensor and gated_quant_fp8 reads those bytes
|
||||
* back. Taking either half off the f32 accumulator is a different function. ref_test holds both.
|
||||
* Byte-identical to gemm_nt_q followed by gated_quant_fp8 (ref_test checks it): the product comes
|
||||
* from `quant_dot` as gemm_nt_q's does, and both halves are narrowed to bf16 before the gate, as the
|
||||
* unfused pair writes and re-reads a bf16 [M, N] tensor.
|
||||
*
|
||||
* A NOTE FOR ANYONE COMPARING THIS AGAINST A DEVICE KERNEL ON THE ENGINE'S OWN OPERANDS. It will
|
||||
* disagree, completely, and the kernel is not wrong: libr4d stores an fp8a8 weight in WMMA FRAGMENT
|
||||
* ORDER (r4d.fp8.w.frag64), the same bytes in a different arrangement, and libref reads [N, K]
|
||||
* row-major. Two readings of one permuted plane are uncorrelated tensors, which shows up as a
|
||||
* relative error around 1.35 on every operand from element zero. The per-op oracle inverts the
|
||||
* layout through the row's own RadUnrelayoutFn, back to the encoding's canonical planes, before it
|
||||
* compares, and says so when a row publishes no inverse; a comparison that skips that step is
|
||||
* measuring the permutation.
|
||||
* Comparing against a device kernel on the engine's own operands needs the layout inverted first:
|
||||
* libr4d stores fp8a8 weights in WMMA fragment order (r4d.fp8.w.frag64) while libref reads [N, K]
|
||||
* row-major, and the two readings are uncorrelated (relative error around 1.35). The per-op oracle
|
||||
* applies the row's RadUnrelayoutFn before comparing and says so when a row has none.
|
||||
*
|
||||
* The product is formed a row at a time rather than all at once. A reference may be slow and may
|
||||
* not be surprising about memory: [M, N] at a prefill M is hundreds of megabytes for a value the
|
||||
* op exists to avoid materialising. */
|
||||
* The product is formed one row at a time; [M, N] at a prefill M would be hundreds of MB. */
|
||||
int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 6) return RAD_E_INVAL;
|
||||
const RadTensor *A = &a->t[0], *B = &a->t[2], *q = &a->t[4], *s = &a->t[5];
|
||||
@@ -764,19 +679,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
|
||||
const bool mx = B->dtype == RAD_FP4E2M1;
|
||||
const Scales SA = make_scales(as_, M, K, false);
|
||||
const Scales SB = make_scales(bs_, N, K, mx);
|
||||
const Mat ma = as_mat(A, M, K), mb = as_mat(B, N, K);
|
||||
const Mat ma = as_mat(A, K), mb = as_mat(B, K);
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(M * N * K)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
std::vector<float> row((size_t)N), v((size_t)n);
|
||||
for (int64_t j = 0; j < N; ++j) row[(size_t)j] = quant_dot(ma, mb, SA, SB, m, j, K);
|
||||
const int64_t obb = ob ? rowoff(ob, m, n) : 0;
|
||||
const int64_t obs = ob ? laststride(ob) : 1;
|
||||
/* Both halves narrowed to bf16 before the gate; the header says why. */
|
||||
/* Both halves narrowed to bf16 before the gate (see above). */
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float gt = bf16_to_f32(f32_to_bf16(row[(size_t)i]));
|
||||
const float up = bf16_to_f32(f32_to_bf16(row[(size_t)(n + i)]));
|
||||
const float sg = 1.0f / (1.0f + std::exp(-gt));
|
||||
const float gt = round_dt(RAD_BF16, row[(size_t)i]);
|
||||
const float up = round_dt(RAD_BF16, row[(size_t)(n + i)]);
|
||||
const float sg = act_sigmoid(gt);
|
||||
const uint16_t h = f32_to_bf16((act == 0 ? gt * sg : sg) * up);
|
||||
if (ob) stt(ob, obb + i * obs, bf16_to_f32(h));
|
||||
v[(size_t)i] = bf16_to_f32(h);
|
||||
@@ -790,19 +705,19 @@ int ref_gemm_nt_q_gated(const RadArgs* a, RadStream) {
|
||||
/* `cand`, `unary`, `hp`?, `anchor`, `pred`w, `succ`w -> `tokens`
|
||||
*
|
||||
* DFlash2's greedy walk over the candidate lattice. A block-diffusion drafter proposes every
|
||||
* position of a block in ONE backbone pass, so it cannot condition position l+1 on what it chose at
|
||||
* l; this puts that dependence back.
|
||||
* position of a block in one backbone pass, so it cannot condition position l+1 on its choice at
|
||||
* l; this restores that dependence.
|
||||
*
|
||||
* score[l, c] = unary[l, c] + sum_r pred[pid(l)][r] * hp[l][r] * succ[cand[l, c]][r]
|
||||
* pid(0) = anchor[s * anchor_stride] the token the target just committed
|
||||
* pid(l) = cand[l - 1, chosen(l - 1)] the walk's own previous pick
|
||||
*
|
||||
* `hp` ABSENT IS A PLANE OF ONES, which drops the trilinear form to a plain low-rank bigram and is
|
||||
* DSpark's Markov head rather than a degenerate case.
|
||||
* `hp` absent is a plane of ones, reducing the trilinear form to a low-rank bigram (DSpark's Markov
|
||||
* head).
|
||||
*
|
||||
* THE WALK IS SERIAL IN l, which is why it is an op and not a GEMM and an argmax: scoring the full
|
||||
* [steps, K, K] edge tensor computes K times the edges that are ever read, because the predecessor
|
||||
* is not known until the previous step has been decided. The parallelism here is over sequences. */
|
||||
* The walk is serial in l, so it is an op rather than a GEMM plus argmax: scoring the full
|
||||
* [steps, K, K] edge tensor computes K times the edges ever read, since each predecessor is known
|
||||
* only after the previous step. Parallel over sequences. */
|
||||
int ref_dflash_select(const RadArgs* a, RadStream) {
|
||||
if (a->n_t < 7) return RAD_E_INVAL;
|
||||
const RadTensor *cand = &a->t[0], *un = &a->t[1], *anc = &a->t[3];
|
||||
@@ -813,7 +728,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
|
||||
|
||||
const int64_t steps = p_int(a, "steps", 0);
|
||||
const int64_t K = p_int(a, "top_k", 0);
|
||||
/* `cand` is [M * steps, K] and it is the call; `M` is the band. See ref_common.h. */
|
||||
/* Rows come from `cand` [M * steps, K]; `M` is the band (see band_rows in ref_common.h). */
|
||||
const int64_t M = steps > 0 && K > 0
|
||||
? band_rows(numel(cand) / (steps * K), p_int(a, "M", 0)) : 0;
|
||||
const int64_t R = p_int(a, "rank", pred->rank >= 2 ? pred->shape[pred->rank - 1] : 0);
|
||||
@@ -829,7 +744,7 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
|
||||
const int64_t ps = laststride(pred), sxs = laststride(succ);
|
||||
const int64_t hs = hp ? laststride(hp) : 1;
|
||||
|
||||
#pragma omp parallel for schedule(static)
|
||||
REF_PAR_FOR(M * steps * K * R)
|
||||
for (int64_t m = 0; m < M; ++m) {
|
||||
std::vector<float> ax((size_t)R);
|
||||
int64_t pid = ld_int(anc->dtype, anc->data, offlin(anc, m * astr));
|
||||
@@ -837,10 +752,8 @@ int ref_dflash_select(const RadArgs* a, RadStream) {
|
||||
const int64_t r = m * steps + l;
|
||||
const int64_t cb = rowoff(cand, r, K), ub = rowoff(un, r, K);
|
||||
const int64_t hb = hp ? rowoff(hp, r, R) : 0;
|
||||
/* The half of the form that does not depend on the candidate, computed once and read
|
||||
* K times -- which is the shape the kernel is built around too. A predecessor outside
|
||||
* the vocabulary contributes nothing rather than reading past the codebook: at step 0
|
||||
* it is whatever the target committed, and a padding row's is not a token. */
|
||||
/* The candidate-independent half of the form, computed once and read K times. A
|
||||
* predecessor outside the vocabulary (a padding row's anchor) contributes nothing. */
|
||||
const bool ok = pid >= 0 && pid < nv;
|
||||
for (int64_t i = 0; i < R; ++i)
|
||||
ax[(size_t)i] = (ok ? ldt(pred, rowoff(pred, pid, R) + i * ps) : 0.0f) *
|
||||
|
||||
Reference in new issue
Block a user