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
+170
-196
@@ -1,55 +1,32 @@
|
||||
/* avx_quant.cpp -- the quantisers, the rotation, and the Gram accumulator.
|
||||
*
|
||||
* ============================== THE WALSH-HADAMARD IS BIT-IDENTICAL, ON PURPOSE ==============================
|
||||
* Walsh-Hadamard, bit-identical to libref. The rotation is butterflies at strides 1, 2, 4, ... g/2,
|
||||
* pairing i with i + h where (i & h) == 0. The stride matrices commute in exact arithmetic but not
|
||||
* in f32, so libref's ascending order is kept: each butterfly is the same add and subtract on the
|
||||
* same two floats, the rotated block is bit-identical, and the rotated-int8 family holds at the
|
||||
* quantiser tolerance (1e-6). Only the lane mapping is vectorised (avx_had.h):
|
||||
*
|
||||
* The rotation is a sequence of butterflies at ascending strides 1, 2, 4, ... g/2, pairing i with
|
||||
* i + h where (i & h) == 0. The butterfly matrices for different strides COMMUTE -- H is a tensor
|
||||
* power of the 2x2 Hadamard -- so any order of `h` gives the same transform in exact arithmetic,
|
||||
* and it is tempting to reorder them for the vectoriser.
|
||||
* h >= VF_N the pair (i, i+h) is two whole vectors: one add, one sub, two stores.
|
||||
* h < VF_N the partner is a swizzle within one vector (adjacent lanes, lane pairs, 128-bit
|
||||
* lanes, 256-bit halves), results selected by a lane mask. Four such strides at
|
||||
* AVX-512, three at AVX2; left scalar they would dominate at g = 128.
|
||||
*
|
||||
* That temptation is refused here and the order is libref's exactly, ASCENDING, because commuting
|
||||
* in exact arithmetic is not the same as commuting in f32: the intermediate values differ and the
|
||||
* roundings land in different places. Keeping the order means every butterfly is the same add and
|
||||
* the same subtract on the same two floats as the reference performs, so the rotated block is
|
||||
* BIT-IDENTICAL and not merely close -- which is what lets the whole rotated-int8 family be held
|
||||
* at the quantiser tolerance (1e-6) instead of a loosened one. What is vectorised is WHICH LANES a
|
||||
* butterfly runs on, not the arithmetic:
|
||||
* The rotation runs once per row. libref rotates each block twice (once for amax, once for the
|
||||
* codes) because it has no row-sized scratch; here the row is rotated into scratch once.
|
||||
*
|
||||
* h >= VF_N the pair (i, i+h) is two whole vectors. One load, one add, one sub, two stores.
|
||||
* h < VF_N the pair is inside one vector, so the partner is a SWIZZLE of it -- swap adjacent
|
||||
* lanes, pairs of lanes, 128-bit lanes, 256-bit halves -- and the two results are
|
||||
* selected by a lane mask. Four such steps at AVX-512, three at AVX2.
|
||||
* `group` has three meanings (docs/OPS.md); reading the wrong one gives plausible numbers:
|
||||
*
|
||||
* Doing the small strides scalar was the obvious first implementation and it is the wrong one: at
|
||||
* g = 128 and VF_N = 16 that is four scalar passes over 128 elements against three vector passes,
|
||||
* so the part that was left scalar would be most of the cost.
|
||||
*
|
||||
* ============================== THE ROTATION IS PERFORMED ONCE, NOT TWICE ==============================
|
||||
*
|
||||
* libref rotates each block twice -- once to find the absolute maximum and once to write the codes
|
||||
* -- because it has a 4096-float stack frame and no row-sized scratch. That is a factor of two on
|
||||
* every rotated op and it is pure recomputation: the rotated row is deterministic. Here the whole
|
||||
* row is rotated once into scratch, the maximum is taken over it, and the codes are written from
|
||||
* it. Identical arithmetic, half the butterflies.
|
||||
*
|
||||
* ============================== THE TWO `group` READINGS, AND THE TWO sqrt(g) CONVENTIONS ==============================
|
||||
*
|
||||
* docs/OPS.md is explicit that `group` means two different things in this table and that a kernel
|
||||
* reading it the other way is WRONG rather than slow:
|
||||
*
|
||||
* quant_act_i8, quant_act_fp8, dequant `group` is the number of contiguous elements sharing
|
||||
* and the fp8 fusions one scale. `scale` is [M, ceil(n/group)].
|
||||
* every had_* INT8 form `group` is the ROTATION WIDTH and the scale is per ROW,
|
||||
* carrying the 1/sqrt(group).
|
||||
* the had_* FP8 forms `group` is BOTH, and there is NO normalisation at all:
|
||||
* <Hw, Ha> = g <w, a> and the whole factor g is folded
|
||||
* into the stored weight scale at convert, where dividing
|
||||
* a bf16 by a power of two is exact. Splitting it as the
|
||||
* int8 forms do would round amax/7/sqrt(g) into bf16 and
|
||||
* land ~0.2% of multiplicative error on every group.
|
||||
*
|
||||
* Three readings of one parameter name is not a pleasant fact, and it is the vocabulary's rather
|
||||
* than this plugin's. It is restated here because getting it wrong produces a plausible number.
|
||||
* quant_act_i8 one scale per row; `group` is the width of the code
|
||||
* sums `asum` holds.
|
||||
* quant_act_i8g, quant_act_fp8, dequant contiguous elements sharing one scale; `scale` is
|
||||
* and the fp8 fusions [M, ceil(n/group)].
|
||||
* had_* int8 forms the rotation width; one scale per row, carrying
|
||||
* 1/sqrt(group).
|
||||
* had_* fp8 forms both, with no normalisation: <Hw, Ha> = g <w, a>, and
|
||||
* the whole g is folded into the stored weight scale at
|
||||
* convert, where dividing a bf16 by a power of two is
|
||||
* exact. Splitting it as int8 does would round
|
||||
* amax/7/sqrt(g) into bf16 (~0.2% error per group).
|
||||
*/
|
||||
#include "avx_vec.h"
|
||||
#include "avx_common.h"
|
||||
@@ -58,14 +35,8 @@ using namespace avx;
|
||||
|
||||
#include "avx_had.h"
|
||||
|
||||
/* ================================================================== int8 store
|
||||
* `q` is almost always RAD_I8, in which case the row store is the vectorised cvtps/packs path
|
||||
* (avx_vec.h) whose rounding is MXCSR round-to-nearest-even and whose saturation is the pack
|
||||
* instruction's -- exactly libref's nearbyintf-and-clamp, bit for bit. Anything else falls back to
|
||||
* the generic row store, which is correct and slower. */
|
||||
static inline void store_codes(const RadTensor* q, int64_t base, int64_t n, const float* v) {
|
||||
out_row(q, base, n, v);
|
||||
}
|
||||
/* Codes are stored with out_row; for RAD_I8 that is the vectorised clamp + cvtps/packs path
|
||||
* (avx_vec.h), bit-exact with libref's nearbyintf-and-clamp. */
|
||||
|
||||
/* Scale a row by a scalar, in place. */
|
||||
static inline void scale_row(float* v, int64_t n, float s) {
|
||||
@@ -76,10 +47,52 @@ static inline void scale_row(float* v, int64_t n, float s) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8 */
|
||||
/* q = round(x * 127 / amax), scale = amax / 127, per `group` contiguous elements. An all-zero
|
||||
* group 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. */
|
||||
/* libref's arithmetic (ref_quant.cpp): one scale per row, max(amax, 1e-8) / 127, codes rounded to
|
||||
* nearest even and stored in the step order, the middle two dwords of every 16-byte step
|
||||
* exchanged. `asum` gets the per-`group` code sums, group-major [n/group][ceil(M/16)*16], taken
|
||||
* from the row-major codes before the exchange. */
|
||||
AVX_KERNEL(quant_act_i8) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
const RadTensor* as = rad_arg_in(a, 3);
|
||||
const int64_t n = p_int(a, "n", 0);
|
||||
if (n <= 0 || n % 16) return RAD_E_SHAPE;
|
||||
if (q->dtype != RAD_I8) return RAD_E_DTYPE;
|
||||
if (!dense_row(q)) 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;
|
||||
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
int8_t* qb = (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n));
|
||||
const float scale = std::max(row_amax(v, n), 1e-8f) / 127.0f;
|
||||
cvt_scaled_f32_to_i8(v, 1.0f / scale, qb, n);
|
||||
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 += qb[i];
|
||||
stt(as, gi * mpad + r, (float)sum);
|
||||
}
|
||||
for (int64_t k = 0; k < n; k += 16) {
|
||||
uint32_t d1, d2;
|
||||
std::memcpy(&d1, qb + k + 4, 4);
|
||||
std::memcpy(&d2, qb + k + 8, 4);
|
||||
std::memcpy(qb + k + 4, &d2, 4);
|
||||
std::memcpy(qb + k + 8, &d1, 4);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_i8g */
|
||||
/* libr4d's quant_act_i8g: per `group` contiguous elements a scale amax * (1/127) (1 for an
|
||||
* all-zero group), codes x * (1/scale) rounded to nearest even, row-major. */
|
||||
AVX_KERNEL(quant_act_i8g) {
|
||||
if (!rad_args_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);
|
||||
@@ -92,48 +105,36 @@ AVX_KERNEL(quant_act_i8) {
|
||||
const int64_t ngrp = (n + g - 1) / g;
|
||||
if (numel(s) < rows * ngrp) return RAD_E_SHAPE;
|
||||
|
||||
/* DENSE-i8 FAST PATH: the per-group scale feeds the int8 encoder directly, with no f32
|
||||
* scratch round trip between them. */
|
||||
if (q->dtype == RAD_I8 && dense_row(q)) {
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
int8_t* qb = (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n));
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
|
||||
const float amax = row_amax(v + k0, k1 - k0);
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0);
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const bool dense_i8 = q->dtype == RAD_I8 && dense_row(q);
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
float* w = scratch_f32_b((size_t)n);
|
||||
int8_t* qb = dense_i8 ? (int8_t*)byte_at(q->data, q->dtype, rowoff(q, r, n)) : nullptr;
|
||||
float* w = dense_i8 ? nullptr : scratch_f32_b((size_t)n);
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g, k1 = (k0 + g < n) ? k0 + g : n;
|
||||
const float amax = row_amax(v + k0, k1 - k0);
|
||||
const float inv = amax > 0.0f ? 127.0f / amax : 0.0f;
|
||||
const vf vi = vf_set1(inv);
|
||||
int64_t i = k0;
|
||||
for (; i + VF_N <= k1; i += VF_N) vf_storeu(w + i, vf_mul(vf_loadu(v + i), vi));
|
||||
for (; i < k1; ++i) w[i] = v[i] * inv;
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), amax / 127.0f);
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 127.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
if (dense_i8) {
|
||||
cvt_scaled_f32_to_i8(v + k0, inv, qb + k0, k1 - k0);
|
||||
} else {
|
||||
const vf vi = vf_set1(inv);
|
||||
int64_t i = k0;
|
||||
for (; i + VF_N <= k1; i += VF_N) vf_storeu(w + i, vf_mul(vf_loadu(v + i), vi));
|
||||
for (; i < k1; ++i) w[i] = v[i] * inv;
|
||||
}
|
||||
stt(s, rowoff(s, r, ngrp) + gi * laststride(s), sc);
|
||||
}
|
||||
store_codes(q, rowoff(q, r, n), n, w);
|
||||
if (!dense_i8) out_row(q, rowoff(q, r, n), n, w);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ had_quant_act_i8 */
|
||||
/* Rotation at width `group`, then symmetric int8 with ONE scale per ROW carrying the
|
||||
* 1/sqrt(group). The absolute maximum is over the WHOLE rotated row, because the scale is per row. */
|
||||
/* Rotation at width `group`, then symmetric int8 with one scale per row carrying the
|
||||
* 1/sqrt(group); amax is over the whole rotated row. */
|
||||
AVX_KERNEL(had_quant_act_i8) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
@@ -145,9 +146,7 @@ AVX_KERNEL(had_quant_act_i8) {
|
||||
if (rows <= 0 || numel(q) < rows * n || numel(s) < rows) return RAD_E_SHAPE;
|
||||
const float norm = 1.0f / std::sqrt((float)g);
|
||||
|
||||
/* Same dense-i8 fusion as quant_act_i8: the rotation stays, but its output is scaled +
|
||||
* encoded straight to bytes. The amax here is whole-row (one scale per row), so the fusion
|
||||
* is a single call rather than per group. */
|
||||
/* Dense i8: one fused scale+encode call per row. */
|
||||
if (q->dtype == RAD_I8 && dense_row(q)) {
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
@@ -166,34 +165,27 @@ AVX_KERNEL(had_quant_act_i8) {
|
||||
AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
float* buf = scratch_f32((size_t)n);
|
||||
/* in_row may hand back the operand's own pointer for a dense f32 input, and the rotation
|
||||
* is IN PLACE -- so the row is copied into scratch whenever that happened. Rotating the
|
||||
* caller's activation would be a kernel that destroys its own input. */
|
||||
/* in_row may return the operand itself for dense f32; copy before the in-place rotation
|
||||
* so the input is not modified. */
|
||||
const float* v = in_row(x, rowoff(x, r, n), n, buf);
|
||||
if (v != buf) std::memcpy(buf, v, (size_t)n * sizeof(float));
|
||||
fwht_row(buf, n, g);
|
||||
const float amax = row_amax(buf, n);
|
||||
scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f);
|
||||
store_codes(q, rowoff(q, r, n), n, buf);
|
||||
out_row(q, rowoff(q, r, n), n, buf);
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ rmsnorm_had_quant_i8 */
|
||||
/* The fused rmsnorm + hadamard + quant_act_i8 a w4a8 layer wants where a bf16 layer wants a plain
|
||||
* rmsnorm.
|
||||
/* Fused rmsnorm + Hadamard + quant_act_i8, the w4a8 counterpart of a plain rmsnorm.
|
||||
*
|
||||
* `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, and matching it is what makes the fused form substitutable for
|
||||
* that pair.
|
||||
* With `residual` (the fused_add_rms_norm form) the sum is written back into `residual` (INOUT;
|
||||
* the next layer's shortcut reads it). As in libref, the variance comes from the f32 sum and the
|
||||
* rotation reads the sum narrowed to the residual's dtype.
|
||||
*
|
||||
* `out_bf16` is the post-norm, PRE-ROTATION tensor for a layer that also has a bf16 consumer: the
|
||||
* rotation is an artefact of the int8 path, and a bf16 consumer wants the normalised activation
|
||||
* rather than a Walsh-Hadamard of it. */
|
||||
* `out_bf16` receives the post-norm, pre-rotation row for a layer that also has a bf16 consumer. */
|
||||
AVX_KERNEL(rmsnorm_had_quant_i8) {
|
||||
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];
|
||||
@@ -212,8 +204,7 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
|
||||
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
|
||||
const float norm = 1.0f / std::sqrt((float)g);
|
||||
|
||||
/* The gain, widened once per launch with `wadd` already folded in -- see avx_norm.cpp on why
|
||||
* this cannot live in the per-thread scratch. */
|
||||
/* Gain with `wadd` folded in, widened once per launch (as in avx_norm.cpp). */
|
||||
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
|
||||
{
|
||||
const int64_t ws = laststride(w);
|
||||
@@ -228,14 +219,15 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
|
||||
float* buf = scratch_f32_b((size_t)n);
|
||||
float* tmp = scratch_f32_c((size_t)n);
|
||||
|
||||
float ss;
|
||||
if (res) {
|
||||
/* x + residual, stored back, then READ BACK NARROWED -- the round trip is the
|
||||
* contract. Done through a hot buffer rather than by re-reading the operand: same
|
||||
* arithmetic, and it does not depend on the store having retired. */
|
||||
/* x + residual, stored, its variance taken, then narrowed through the residual's
|
||||
* dtype in scratch. */
|
||||
const float* xv = in_row(x, rowoff(x, r, n), n, src);
|
||||
const float* rv = in_row(res, rowoff(res, r, n), n, tmp);
|
||||
for (int64_t i = 0; i < n; ++i) buf[i] = xv[i] + rv[i];
|
||||
out_row(res, rowoff(res, r, n), n, buf);
|
||||
ss = row_sumsq(buf, n);
|
||||
if (res->dtype != RAD_F32) {
|
||||
row_from_f32(res->dtype, buf, tmp, n);
|
||||
row_to_f32(res->dtype, tmp, buf, n);
|
||||
@@ -244,34 +236,33 @@ AVX_KERNEL(rmsnorm_had_quant_i8) {
|
||||
} else {
|
||||
const float* xv = in_row(x, rowoff(x, r, n), n, src);
|
||||
if (xv != src) std::memcpy(src, xv, (size_t)n * sizeof(float));
|
||||
ss = row_sumsq(src, n);
|
||||
}
|
||||
|
||||
const float sc = 1.0f / std::sqrt(row_sumsq(src, n) / (float)n + eps);
|
||||
const float sc = 1.0f / std::sqrt(ss / (float)n + eps);
|
||||
const vf vsc = vf_set1(sc);
|
||||
int64_t i = 0;
|
||||
for (; i + VF_N <= n; i += VF_N)
|
||||
vf_storeu(buf + i, vf_mul(vf_mul(vf_loadu(src + i), vsc), vf_loadu(gain + i)));
|
||||
for (; i < n; ++i) buf[i] = src[i] * sc * gain[i];
|
||||
|
||||
if (ob) out_row(ob, rowoff(ob, r, n), n, buf); /* post-norm, PRE-rotation */
|
||||
if (ob) out_row(ob, rowoff(ob, r, n), n, buf); /* post-norm, pre-rotation */
|
||||
|
||||
fwht_row(buf, n, g);
|
||||
const float amax = row_amax(buf, n);
|
||||
scale_row(buf, n, amax > 0.0f ? 127.0f / amax : 0.0f);
|
||||
store_codes(q, rowoff(q, r, n), n, buf);
|
||||
out_row(q, rowoff(q, r, n), n, buf);
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ gated_had_quant_i8 */
|
||||
/* An elementwise gated product, then the rotation and the quantiser. `act` picks between the two
|
||||
* rotated sites a w4a8 model has: silu(a)*b is down_proj's input, sigmoid(a)*b is o_proj's on a
|
||||
* gated-attention layer. `mode` is libr4d's integer spelling of the same choice.
|
||||
/* Gated product, then the rotation and the quantiser. `act` selects the w4a8 site: silu(a)*b is
|
||||
* down_proj's input, sigmoid(a)*b is o_proj's on a gated-attention layer. `mode` is libr4d's
|
||||
* integer spelling of the same choice.
|
||||
*
|
||||
* `b` ABSENT IS THE PACKED FORM: `a` is [M, 2n], gate first half, up second -- which is what a
|
||||
* fused gate_up projection produces. Two operands with the second optional is the only shape that
|
||||
* expresses both readings. */
|
||||
* With `b` absent, `a` is a packed [M, 2n] gate_up plane, gate first. */
|
||||
AVX_KERNEL(gated_had_quant_i8) {
|
||||
if (a->n_t < 4) return RAD_E_INVAL;
|
||||
const RadTensor *ga = &a->t[0], *q = &a->t[2], *s = &a->t[3];
|
||||
@@ -307,24 +298,22 @@ AVX_KERNEL(gated_had_quant_i8) {
|
||||
}
|
||||
for (; i < n; ++i) {
|
||||
const float gt = gv[i];
|
||||
const float sg = 1.0f / (1.0f + std::exp(-gt));
|
||||
const float sg = 1.0f / (1.0f + sc_exp(-gt));
|
||||
out[i] = (act == 1 ? sg : gt * sg) * uv[i];
|
||||
}
|
||||
|
||||
fwht_row(out, n, g);
|
||||
const float amax = row_amax(out, n);
|
||||
scale_row(out, n, amax > 0.0f ? 127.0f / amax : 0.0f);
|
||||
store_codes(q, rowoff(q, r, n), n, out);
|
||||
out_row(q, rowoff(q, r, n), n, out);
|
||||
stt(s, r * laststride(s), amax / 127.0f * norm);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ dequant */
|
||||
/* q * scale, with the SCALE STREAM'S OWN EXTENT deciding how many groups there are. The inverse of
|
||||
* quant_act_i8 and NOT of the rotated forms: undoing a rotation is a second Hadamard, and an op
|
||||
* that silently did one would make `dequant(had_quant(x)) == x` look true when the two have
|
||||
* different meanings. */
|
||||
/* q * scale, with the scale tensor's extent giving the group count. The inverse of quant_act_i8
|
||||
* only; it does not undo a rotation. */
|
||||
AVX_KERNEL(dequant) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *q = &a->t[0], *s = &a->t[1], *y = &a->t[2];
|
||||
@@ -343,9 +332,8 @@ AVX_KERNEL(dequant) {
|
||||
float* out = scratch_f32_b((size_t)n);
|
||||
const float* v = in_row(q, rowoff(q, r, n), n, buf);
|
||||
const int64_t sb = rowoff(s, r, ngrp), ss = laststride(s);
|
||||
/* GROUP BY GROUP, with the scale hoisted out of the element loop. libref reads the scale
|
||||
* per element through a divide; the group edge is known here, so the divide happens once
|
||||
* per group and the body is a vector multiply. Same product, same order. */
|
||||
/* Per group, with the scale hoisted (libref divides per element to find it). Same
|
||||
* product. */
|
||||
for (int64_t gi = 0; gi < ngrp; ++gi) {
|
||||
const int64_t k0 = gi * g;
|
||||
if (k0 >= n) break;
|
||||
@@ -356,8 +344,8 @@ AVX_KERNEL(dequant) {
|
||||
for (; i + VF_N <= k1; i += VF_N) vf_storeu(out + i, vf_mul(vf_loadu(v + i), vs));
|
||||
for (; i < k1; ++i) out[i] = v[i] * sc;
|
||||
}
|
||||
/* A row longer than the groups describe takes the LAST group's scale, which is libref's
|
||||
* clamp (`gi < ngrp ? gi : ngrp - 1`) and is what a ragged final group means. */
|
||||
/* Elements past the described groups use the last group's scale, as libref clamps
|
||||
* (`gi < ngrp ? gi : ngrp - 1`). */
|
||||
if (ngrp * g < n) {
|
||||
const float sc = ldt(s, sb + (ngrp - 1) * ss);
|
||||
for (int64_t i = ngrp * g; i < n; ++i) out[i] = v[i] * sc;
|
||||
@@ -368,18 +356,14 @@ AVX_KERNEL(dequant) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ quant_act_fp8 */
|
||||
/* The three choices this shares with libr4d's kernel, none of them derivable:
|
||||
/* Conventions shared with libr4d's kernel:
|
||||
*
|
||||
* 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 quant_act_i8 uses: that kernel's consumer reads 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. */
|
||||
* 448 E4M3's largest finite value. scale = amax / 448 is a dequant multiplier, the same
|
||||
* sense as a checkpoint's `weight_scale_inv`, so the GEMM multiplies the two scales.
|
||||
* scale 1 for an all-zero group (amax/448 = 0 has no reciprocal), because the GEMM
|
||||
* multiplies the block scales and 0 would erase the weight's.
|
||||
* the clamp amax * (1/scale) can land an ulp above 448 after rounding the reciprocal, which
|
||||
* would encode as NaN. */
|
||||
AVX_KERNEL(quant_act_fp8) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
@@ -410,13 +394,12 @@ AVX_KERNEL(quant_act_fp8) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- rmsnorm_quant_fp8 */
|
||||
/* RMS norm, an optional residual add, and quant_act_fp8, in one pass.
|
||||
/* RMS norm, optional residual add, and quant_act_fp8 in one pass.
|
||||
*
|
||||
* `residual` PRESENT IS THE fused_add_rms_norm FORM and the add is STORED BEFORE THE VARIANCE READS
|
||||
* IT: the sum goes back into `residual`, narrowed to that tensor's dtype, and the norm -- variance
|
||||
* included -- is taken over the narrowed sum. That is the `add` + `rmsnorm` pair, and not
|
||||
* rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is then narrowed
|
||||
* to bf16 and the codes taken over it (avx_had.h). */
|
||||
* With `residual`, the sum is written back narrowed to that tensor's dtype and the whole norm,
|
||||
* variance included, is taken over the narrowed sum: the `add` + `rmsnorm` pair, unlike
|
||||
* rmsnorm_add, which takes its variance from the unrounded sum. The normalised row is narrowed to
|
||||
* bf16 before the codes are taken (avx_had.h). */
|
||||
AVX_KERNEL(rmsnorm_quant_fp8) {
|
||||
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];
|
||||
@@ -436,8 +419,7 @@ AVX_KERNEL(rmsnorm_quant_fp8) {
|
||||
if (res && numel(res) < rows * n) return RAD_E_SHAPE;
|
||||
if (ob && numel(ob) < rows * n) return RAD_E_SHAPE;
|
||||
|
||||
/* The gain with `wadd` folded in, widened once on the calling thread -- see avx_norm.cpp on
|
||||
* why it cannot live in the per-thread scratch. */
|
||||
/* Gain with `wadd` folded in, widened once on the calling thread (as in avx_norm.cpp). */
|
||||
float* gain = (float*)scratch_raw((size_t)n * sizeof(float));
|
||||
{
|
||||
const int64_t ws = laststride(w);
|
||||
@@ -480,9 +462,9 @@ AVX_KERNEL(rmsnorm_quant_fp8) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- gated_quant_fp8 */
|
||||
/* act(gate) * up over a PACKED [M, 2n] gate_up plane, gate half first, then quant_act_fp8 over the
|
||||
* bf16-narrowed product. `act` is silu or sigmoid, `mode` libr4d's integer spelling of the same
|
||||
* choice, silu when neither is given. */
|
||||
/* act(gate) * up over a packed [M, 2n] gate_up plane (gate first), then quant_act_fp8 over the
|
||||
* bf16-narrowed product. `act` is silu or sigmoid (`mode` is libr4d's integer form); default
|
||||
* silu. */
|
||||
AVX_KERNEL(gated_quant_fp8) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *gu = &a->t[0], *q = &a->t[1], *s = &a->t[2];
|
||||
@@ -512,21 +494,18 @@ AVX_KERNEL(gated_quant_fp8) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- 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.
|
||||
/* quant_act_fp8 with a `group`-wide Hadamard before the absmax, which shrinks the maximum the grid
|
||||
* is scaled by.
|
||||
*
|
||||
* THE sqrt(g) IS NOT UNDONE HERE, and that is a deliberate difference from 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. */
|
||||
* Unlike had_quant_act_i8, 1/sqrt(g) is not applied here. <Hw, Ha> = g <w, a>, and the whole g is
|
||||
* divided out of the weight scale instead, where dividing a bf16 by a power of two is exact. */
|
||||
AVX_KERNEL(had_quant_act_fp8) {
|
||||
if (!rad_args_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: a block straddling the row end would mix in padding, unlike any
|
||||
* rotated weight block. */
|
||||
if (n <= 0 || !pow2(g) || n % g != 0) return RAD_E_SHAPE;
|
||||
if (g > AVX_HAD_MAX) return RAD_E_UNSUPPORTED;
|
||||
const int64_t rows = numel(x) / n;
|
||||
@@ -552,12 +531,11 @@ AVX_KERNEL(had_quant_act_fp8) {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- givens_rotate */
|
||||
/* ParoQuant's activation side for a 16-bit GEMM: each row divided by its channel scales and rotated
|
||||
* by `stages` rounds of disjoint Givens pairs, once a part, the parts side by side in y. libref's
|
||||
* arithmetic (ref_quant.cpp) in its order: the divide, then a' = a cos t + b sin t,
|
||||
* b' = b cos t - a sin t in f32, stage by stage. A pair walk is a gather and a scatter with nothing
|
||||
* to vectorise; what is hoisted is the cos and sin of every angle, a property of the weight and the
|
||||
* same for every row, so they are taken once a call rather than once a row. */
|
||||
/* ParoQuant's activation side for a 16-bit GEMM: each row is divided by its channel scales and
|
||||
* rotated by `stages` rounds of disjoint Givens pairs, once per part, parts side by side in y.
|
||||
* libref's arithmetic and order (ref_quant.cpp): the divide, then a' = a cos t + b sin t,
|
||||
* b' = b cos t - a sin t in f32, stage by stage. The pair walk is a gather/scatter and stays
|
||||
* scalar; the cos and sin of each angle are computed once per call. */
|
||||
AVX_KERNEL(givens_rotate) {
|
||||
if (!rad_args_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], *y = &a->t[4];
|
||||
@@ -582,8 +560,8 @@ AVX_KERNEL(givens_rotate) {
|
||||
}
|
||||
for (int64_t j = 0; j < NP; ++j) {
|
||||
const float th = ldt(an, j);
|
||||
cs[j] = std::cos(th);
|
||||
sn[j] = std::sin(th);
|
||||
cs[j] = sc_cos(th);
|
||||
sn[j] = sc_sin(th);
|
||||
}
|
||||
for (int64_t k = 0; k < P * n; ++k) rs[k] = ldt(sc, k);
|
||||
|
||||
@@ -612,12 +590,12 @@ AVX_KERNEL(givens_rotate) {
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- givens_dense_quant */
|
||||
/* The quantising form: the rotation as one dense 128 x 128 f16 matrix a (part, group) -- `tdense`,
|
||||
* which rad-convert composes from the pairs and angles and stores as the weight's "t.dense" table --
|
||||
* then the block-scaled quantiser `out` names: "fp8" E4M3 with scale amax / 448, "i8" scale
|
||||
* amax / 127 rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened
|
||||
* to f32 once a call; a row is then a matrix-vector product a group, in f32 where libref sums in
|
||||
* f64, so a code can differ from libref's where the value sits on a rounding edge. */
|
||||
/* Quantising form: the rotation as one dense 128 x 128 f16 matrix per (part, group) (`tdense`,
|
||||
* which rad-convert composes from the pairs and angles as the weight's "t.dense" table), then the
|
||||
* block-scaled quantiser named by `out`: "fp8" E4M3 with scale amax / 448, or "i8" with scale
|
||||
* amax / 127, rounded to nearest; scale 1 for an all-zero group, as libref. The matrices are widened
|
||||
* to f32 once per call. Each group is a matrix-vector product summed in f32 (libref uses f64), so a
|
||||
* code on a rounding edge can differ from libref's. */
|
||||
AVX_KERNEL(givens_dense_quant) {
|
||||
if (!rad_args_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];
|
||||
@@ -673,26 +651,17 @@ AVX_KERNEL(givens_dense_quant) {
|
||||
|
||||
/* ---------------------------------------------------------------- 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.
|
||||
* 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 is when no scale is passed: the second moment GPTQ's error feedback needs, over the
|
||||
* operand the expert GEMM contracts.
|
||||
*
|
||||
* `h` IS READ AS WELL AS WRITTEN and that is the op: the caller zeroes it once and drives a whole
|
||||
* calibration corpus through the graph, so each launch adds its own block. An implementation that
|
||||
* stored instead of added would agree on one call and disagree on a corpus.
|
||||
* `h` accumulates across launches: the caller zeroes it once and runs a calibration corpus through.
|
||||
*
|
||||
* THE ACCUMULATION IS f64 HERE AND f32 ON THE DEVICE, and that is libref's choice reproduced
|
||||
* rather than an accident: this is the one op in the vocabulary whose result is consumed OFFLINE,
|
||||
* by the packer, through a file -- so being tighter than the kernel is the right trade, and the
|
||||
* kbench tolerance covers the gap. It also means the inner reduction is NOT the f32 vector path
|
||||
* the rest of this file uses; there is nothing to vectorise about an f64 accumulation of an f32
|
||||
* product that would not change the answer.
|
||||
*
|
||||
* What IS vectorised is the dequantisation: rows are widened and scaled once into a scratch plane
|
||||
* rather than inside the k2 loop, which is O(n^2 * rows) with a per-element dtype dispatch in it
|
||||
* otherwise. */
|
||||
* Accumulation is f64 here (f32 on the device), as in libref: the result is consumed offline by
|
||||
* the packer, and the kbench tolerance covers the gap. The f64 inner reduction stays scalar; only
|
||||
* the dequantisation is vectorised, once per row into a scratch plane rather than in the k2 loop. */
|
||||
AVX_KERNEL(gram_accum) {
|
||||
/* `a_scale` is optional: absent, `a` is read as it stands, which is the bf16 form. */
|
||||
/* `a_scale` is optional; without it `a` is read as is (the bf16 form). */
|
||||
if (a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor *x = rad_arg_in(a, 0), *s = rad_arg_in(a, 1), *h = rad_arg_in(a, 2);
|
||||
if (!x || !h) return RAD_E_INVAL;
|
||||
@@ -721,16 +690,21 @@ AVX_KERNEL(gram_accum) {
|
||||
}
|
||||
}
|
||||
|
||||
/* The upper triangle, each sum added to both (k1, k2) and (k2, k1): the products commute, so
|
||||
* the two sums are the same bits. Rows of the triangle shrink, hence the dynamic schedule. */
|
||||
const int64_t hst = laststride(h);
|
||||
AVX_PARALLEL_FOR_IF(n * n >= 1024)
|
||||
#ifdef _OPENMP
|
||||
AVX_PRAGMA(omp parallel for schedule(dynamic, 8) if(n * n >= 1024 || avx_par_forced())
|
||||
num_threads(avx_team_size()))
|
||||
#endif
|
||||
for (int64_t k1 = 0; k1 < n; ++k1) {
|
||||
const int64_t hb = rowoff(h, k1, n);
|
||||
for (int64_t k2 = 0; k2 < n; ++k2) {
|
||||
for (int64_t k2 = k1; k2 < n; ++k2) {
|
||||
double acc = 0.0;
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
acc += (double)xs[r * n + k1] * (double)xs[r * n + k2];
|
||||
const int64_t off = hb + k2 * hst;
|
||||
stt(h, off, (float)((double)ldt(h, off) + acc));
|
||||
const int64_t o12 = rowoff(h, k1, n) + k2 * hst, o21 = rowoff(h, k2, n) + k1 * hst;
|
||||
stt(h, o12, (float)((double)ldt(h, o12) + acc));
|
||||
if (k2 != k1) stt(h, o21, (float)((double)ldt(h, o21) + acc));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
|
||||
Reference in new issue
Block a user