radiance 1.7.0

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

No files matched your search

+108 -140
View File
@@ -1,18 +1,12 @@
/* avx_support.cpp -- the dtype-generic row and the row reductions, compiled once per ISA level.
/* avx_support.cpp -- dtype-generic row conversion and row reductions, compiled once per ISA level.
*
* WHY THESE ARE OUT OF LINE AND NOT IN THE HEADER. They are called from every kernel with a
* runtime dtype, so inlining them would paste a fifteen-way switch into sixty-eight call sites and
* the switch is the thing being hoisted out of the loop in the first place. Out of line, the
* branch is taken ONCE PER ROW and the body it lands in is a straight vector loop the hardware
* prefetcher can see through.
* Out of line rather than in the header: every kernel calls these with a runtime dtype, so inlining
* would paste the dtype switch into every call site. Out of line, the switch is taken once per row
* and lands in a straight vector loop.
*
* The conversion rates per level are measured by `rad-avx-bench --cvt` and recorded in
* libavx/README.md rather than here, because they are a property of the machine the bench last ran
* on and a number typed into a comment outlives the machine that produced it.
*
* The two fp8 decodes take different paths and avx_vec.h says why: e4m3 is a branchless bit
* reconstruction, e5m2 a table gather, and the scalar level and every tail element read the table
* in both cases.
* Conversion rates per level come from `rad-avx-bench --cvt` (libavx/README.md). The two fp8
* decodes differ (avx_vec.h explains): e4m3 is a branchless bit reconstruction, e5m2 a table
* gather; the scalar level and tail elements use the table for both.
*/
#include "avx_vec.h"
#include "avx_common.h"
@@ -21,18 +15,14 @@ namespace avx {
inline namespace AVX_SUFFIX {
/* ================================================================== packed weight codes
* The conventions are libr4d's, because a .rad is specific to a kernel set (spec §4.2) and this
* plugin has to read the same bytes: W4 is two nibbles a byte with element 2i LOW and a symmetric
* two's-complement code ((n ^ 8) - 8), W2 four codes a byte with the same construction one radix
* down, MXFP4 two e2m1 nibbles with the magnitude table below. libref/ref_common.h is the written
* definition and this is the vectorised reading of it.
* The canonical planes a container stores (abi/rad_encoding.h), read as stored: libavx rearranges
* no plane, its relayouts only join whole planes (avx_planes.h). Definition: libref/ref_common.h.
* W4: two nibbles a byte, element 2i in the low nibble, code (n ^ 8) - 8. W2: four codes a byte,
* code (c ^ 2) - 2. MXFP4: two e2m1 nibbles, as avx_common.h: ld_elem decodes them.
*
* THE W4 UNPACK IS A SHUFFLE, NOT A SHIFT PER ELEMENT. Sixteen nibble pairs are one 128-bit load;
* the low nibbles are an AND and the high ones a shift, and the two interleave back with a
* punpcklbw -- four instructions for 32 elements against 32 shifts and 32 masks scalar. W2 and
* MXFP4 are left scalar: W2 appears only in the draft head's lm_head and MXFP4 only in an expert
* grid this plugin does not serve at speed, so neither is on a path worth the code. */
static const float kMxfp4Mag[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
* W4 unpacks 32 elements from one 128-bit load: AND for the low nibbles, shift for the high, then
* interleave with punpcklbw; MXFP4 takes the same unpack and a register table. W2 stays scalar: no
* plain W2 weight is served. */
static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
@@ -59,28 +49,46 @@ static void w4_to_f32(const uint8_t* src, float* dst, int64_t n) {
#endif
}
#endif
for (; i < n; ++i) {
uint8_t b = src[i >> 1];
uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
dst[i] = (float)((int)(nb ^ 0x8u) - 8);
}
for (; i < n; ++i) dst[i] = ld_elem(src, RAD_I4, i);
}
static void w2_to_f32(const uint8_t* src, float* dst, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
uint8_t b = src[i >> 2];
uint8_t c = (uint8_t)((b >> (2 * (i & 3))) & 0x3u);
dst[i] = (float)((int)(c ^ 0x2u) - 2);
}
}
static void mxfp4_to_f32(const uint8_t* src, float* dst, int64_t n) {
for (int64_t i = 0; i < n; ++i) {
uint8_t b = src[i >> 1];
uint8_t nb = (i & 1) ? (uint8_t)(b >> 4) : (uint8_t)(b & 0xf);
float v = kMxfp4Mag[nb & 7u];
dst[i] = (nb & 8u) ? -v : v;
/* MXFP4: the same nibble unpack, then the e2m1 value of each code from a register table. AVX-512
* looks all sixteen up in one vpermps; AVX2's vpermps indexes eight, so it takes the magnitude by
* the low three bits and ors in the sign (bit 3). Code 8 is -0, as ld_elem gives it. */
static void fp4_to_f32(const uint8_t* src, float* dst, int64_t n) {
int64_t i = 0;
#if AVX_LEVEL >= 2
const __m128i lomask = _mm_set1_epi8(0x0f);
#if AVX_LEVEL >= 3
const __m512 tab = _mm512_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f, -0.0f,
-0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f);
#else
const __m256 mag = _mm256_setr_ps(0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f);
auto emit8 = [&](__m128i codes8, float* d) {
const __m256i ix = _mm256_cvtepu8_epi32(codes8);
const __m256 m = _mm256_permutevar8x32_ps(mag, ix);
const __m256i sg = _mm256_slli_epi32(_mm256_and_si256(ix, _mm256_set1_epi32(8)), 28);
_mm256_storeu_ps(d, _mm256_or_ps(m, _mm256_castsi256_ps(sg)));
};
#endif
for (; i + 32 <= n; i += 32) {
const __m128i b = _mm_loadu_si128((const __m128i*)(src + (i >> 1)));
const __m128i lo = _mm_and_si128(b, lomask);
const __m128i hi = _mm_and_si128(_mm_srli_epi16(b, 4), lomask);
const __m128i e0 = _mm_unpacklo_epi8(lo, hi); /* codes 0..15 */
const __m128i e1 = _mm_unpackhi_epi8(lo, hi); /* codes 16..31 */
#if AVX_LEVEL >= 3
_mm512_storeu_ps(dst + i, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e0), tab));
_mm512_storeu_ps(dst + i + 16, _mm512_permutexvar_ps(_mm512_cvtepu8_epi32(e1), tab));
#else
emit8(e0, dst + i);
emit8(_mm_srli_si128(e0, 8), dst + i + 8);
emit8(e1, dst + i + 16);
emit8(_mm_srli_si128(e1, 8), dst + i + 24);
#endif
}
#endif
for (; i < n; ++i) dst[i] = ld_elem(src, RAD_FP4E2M1, i);
}
/* ================================================================== the generic row */
@@ -93,11 +101,10 @@ void row_to_f32(uint32_t dt, const void* src, float* dst, int64_t n) {
case RAD_F8E5M2: cvt_fp8e5m2_to_f32((const uint8_t*)src, dst, n); break;
case RAD_I8: cvt_i8_to_f32((const int8_t*)src, dst, n); break;
case RAD_I4: w4_to_f32((const uint8_t*)src, dst, n); break;
case RAD_I2: w2_to_f32((const uint8_t*)src, dst, n); break;
case RAD_FP4E2M1: mxfp4_to_f32((const uint8_t*)src, dst, n); break;
case RAD_I2: for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, RAD_I2, i); break;
case RAD_FP4E2M1: fp4_to_f32((const uint8_t*)src, dst, n); break;
default:
/* Everything left is an integer or a bool, none of them hot. The ABI's own accessor is
* the definition and there is nothing to vectorise about a u8 widen nobody runs. */
/* Remaining integer and bool dtypes are not hot; use the ABI accessor. */
for (int64_t i = 0; i < n; ++i) dst[i] = rad_load_f32(src, dt, i);
break;
}
@@ -120,19 +127,17 @@ void row_from_f32(uint32_t dt, const float* src, void* dst, int64_t n) {
void row_to_f32_strided(uint32_t dt, const void* src, int64_t stride, float* dst, int64_t n) {
if (stride == 1) { row_to_f32(dt, src, dst, n); return; }
/* A GATHER, AND IT IS LEFT SCALAR. vpgatherdd issues one cache line per lane where the scalar
* loop's loads coalesce in the load queue, and every strided operand in this plugin is a
* column slice of a fused projection (docs/OPS.md on `z`) -- a handful of rows per launch. Not
* a hot path, and not worth a second code path that would need its own check. */
/* Scalar gather. vpgatherdd issues one cache line per lane, while scalar loads coalesce in
* the load queue; and strided operands here are only column slices of a fused projection
* (docs/OPS.md on `z`), a few rows per launch. */
for (int64_t i = 0; i < n; ++i) dst[i] = ld_elem(src, dt, i * stride);
}
/* ================================================================== row reductions
* FIXED TREES. The accumulator count is written out rather than left to the unroller, because the
* summation order has to be a property of the source and not of the optimiser: a rebuild that
* moved the answer in the last ulp would show up in the checker as a tolerance move and be read as
* whatever change was under test. Four accumulators is what it takes to cover the FMA latency on a modern core
* -- the sweep that says so is `rad-avx-bench --reduce`. */
* Fixed summation trees. The accumulators are written out rather than left to the unroller so the
* summation order is fixed by the source, not the optimiser, and results do not move by an ulp
* between builds. Four accumulators cover the FMA latency on current cores (`rad-avx-bench
* --reduce`). */
float row_sumsq(const float* x, int64_t n) {
vf a0 = vf_zero(), a1 = vf_zero(), a2 = vf_zero(), a3 = vf_zero();
int64_t i = 0;
@@ -193,75 +198,57 @@ float row_max(const float* x, int64_t n) {
}
/* ================================================================== an operand's row, as f32 */
/* Whether a dense row starting at element `base` can be addressed by a byte pointer. A sub-byte
* dtype starting mid-byte cannot (`byte_at` maps elements 2i and 2i+1 to the same byte), so it
* takes the element path rather than reading the row shifted by a nibble. Real W4 rows start on a
* group boundary. */
static inline bool byte_aligned(const RadTensor* t, int64_t base) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
return (base & sub) == 0;
}
const float* in_row(const RadTensor* t, int64_t base, int64_t n, float* scr) {
const int64_t st = laststride(t);
if (st == 1) {
/* SUB-BYTE DTYPES AT AN ODD ELEMENT OFFSET are the one case a byte pointer cannot express,
* and they take the slow path rather than being silently truncated: `byte_at` maps element
* 2i and 2i+1 to the same byte, so a W4 row starting at an odd element would read the whole
* row shifted by one nibble -- a permutation, and the kind that produces plausible numbers.
* Every real W4 row starts on a group boundary, so this costs nothing. */
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
const void* p = byte_at(t->data, t->dtype, base);
return row_f32_in(t->dtype, p, scr, n);
}
}
if (st == 1 && byte_aligned(t, base))
return row_f32_in(t->dtype, byte_at(t->data, t->dtype, base), scr, n);
for (int64_t i = 0; i < n; ++i) scr[i] = ldt(t, base + i * st);
return scr;
}
void out_row(const RadTensor* t, int64_t base, int64_t n, const float* src) {
const int64_t st = laststride(t);
if (st == 1) {
const int sub = (t->dtype == RAD_I4 || t->dtype == RAD_FP4E2M1) ? 1
: (t->dtype == RAD_I2) ? 3 : 0;
if (!sub || (base & sub) == 0) {
row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n);
return;
}
if (st == 1 && byte_aligned(t, base)) {
row_from_f32(t->dtype, src, (void*)byte_at(t->data, t->dtype, base), n);
return;
}
for (int64_t i = 0; i < n; ++i) stt(t, base + i * st, src[i]);
}
/* ================================================================== exact top-R
*
* ONE STEP OF AN EXACT SELECTION, descending by value and on a tie by the LOWER index. libref's
* `topk_next` is the definition and this is the vectorised reading of it.
* One step of an exact selection: the next element in descending value order, ties to the lower
* index (libref's `topk_next`).
*
* THE ELIGIBILITY TEST SPLITS AT THE PREVIOUS PICK, and that is what makes it vectorisable at all.
* The rule is "skip anything above the last pick, and skip the last pick itself and everything
* before it that equals it" -- which reads as an index comparison and is not a lane predicate. But
* it is equivalent to two PURE VALUE tests over two ranges:
* Eligibility ("not above the last pick, and not the last pick or an equal element before it")
* splits at the previous pick into two value-only tests, which vectorise as compare + blend + max:
*
* i <= pi eligible iff !(v > pv) and v != pv
* i > pi eligible iff !(v > pv)
*
* so each range is one compare and one blend, and the maximum over them is a vector max. Recovering
* WHICH index held that maximum is a second pass that early-exits at the first match -- on real
* data it reads a fraction of the row. libref does one scalar pass with two unpredictable branches
* per element; at a 248K vocabulary and R = 16 that is eight million of them.
* A second pass finds the index of the maximum and exits at the first match.
*
* `!(v > pv)` RATHER THAN `v <= pv` IS DELIBERATE and is why the comparisons below are the
* unordered NGT form: for a NaN both are different answers, and libref's `if (v > *pv) continue;`
* treats a NaN as eligible. Matching it costs nothing here.
*
* WHAT DOES NOT MATCH, stated rather than hidden: libref seeds its running best with the FIRST
* eligible element and only replaces it on a strict `>`, so an eligible NaN encountered first stays
* the winner for the whole row. A vector max cannot reproduce that, and this returns the largest
* non-NaN instead. Both are arbitrary -- a NaN logit has no correct selection -- and no path in
* this project produces one (a masked logit is -inf, which IS ordered and IS handled). */
* `!(v > pv)` (the unordered NGT compare) rather than `v <= pv` matches libref, which treats a NaN
* as eligible. One known difference: libref keeps an eligible NaN that it meets first as the
* winner, while the vector max returns the largest non-NaN. No path produces NaN logits (a masked
* logit is -inf, which is handled). */
bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
const float prev = *pv;
const int64_t pidx = *pi;
#if AVX_LEVEL == 0
/* ONE PASS AT THE SCALAR LEVEL, WHICH IS libref's LOOP. The two-pass form below -- a vector
* maximum and then a scan for the index that held it -- pays only because the first pass is
* vector work; with a vector of one float it is strictly two passes where libref does one, and
* it measures slower than the reference it is meant to replace. A fallback that loses to the
* thing it falls back from is not a fallback, so the scalar level gets its own loop. */
/* Scalar level: libref's single pass. The two-pass form below only pays when the first pass
* is vector work; scalar, it is slower than one pass. */
float best = 0.0f;
int64_t bi = -1;
for (int64_t j = 0; j < n; ++j) {
@@ -276,7 +263,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
return true;
#else
const float NEG = -INFINITY;
/* The split point: indices at or below `pidx` must also differ from `prev`. */
/* Indices below `split` (at or below `pidx`) must also differ from `prev`. */
const int64_t split = (pidx + 1 > 0) ? (pidx + 1 < n ? pidx + 1 : n) : 0;
float best = NEG;
int64_t i = 0;
@@ -284,7 +271,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
{
const vf vprev = vf_set1(prev), vneg = vf_set1(NEG);
vf acc = vf_set1(NEG);
/* Range one: below or at the previous pick -- equality is excluded here. */
/* At or below the previous pick: equality excluded. */
for (; i + VF_N <= split; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
@@ -302,7 +289,7 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
if (x > prev || x == prev) continue;
if (x > best) best = x;
}
/* Range two: past the previous pick -- equality is allowed. */
/* Past the previous pick: equality allowed. */
for (; i + VF_N <= n; i += VF_N) {
const vf x = vf_loadu(v + i);
#if AVX_LEVEL == 3
@@ -323,25 +310,16 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
if (x > best) best = x;
}
/* THE LOWEST INDEX HOLDING THAT MAXIMUM -- "ties to the lower column" -- AND THIS PASS IS
* VECTORISED TOO, because it costs as much as the maximum does when it is not.
/* Lowest index holding the maximum (ties to the lower column). Vectorised as well: a scalar
* scan reads n/2 elements on average and would dominate `sample_argmax`.
*
* The maximum can sit anywhere in the row, so a scalar scan for it reads n/2 elements on
* average: over a 32000-logit row that is sixteen thousand unpredictable compares, and it
* dominates `sample_argmax`. Comparing a whole vector against `best` and taking the lowest set
* bit of the mask turns that into n/2/VF_N iterations.
* The range below the previous pick must be scanned first, since the lowest index over the
* whole row wins. Scanning the vector range first returns the wrong index when the maximum
* occurs on both sides, which is common at bf16.
*
* THE LOW RANGE IS SCANNED FIRST AND THAT IS NOT A DETAIL. "Lowest index" means lowest over the
* WHOLE row, so a match below the previous pick beats one above it -- and scanning the long
* vector range first and only then the short scalar one returns the wrong index exactly when
* the maximum occurs twice, once on each side. That failure only bites on ties: it does not
* show at f32 or at the scalar level, and it shows at bf16, where a narrow row quantised to a
* handful of distinct values makes a repeated maximum common.
*
* Below the previous pick the extra `x != prev` test applies, and that range is at most pidx+1
* long -- zero for an argmax, R-1 for the R-th selection -- so it stays scalar. Past it,
* eligibility is exactly `!(x > prev)` and `x == best` already implies it, since `best` was
* drawn from eligible lanes and is therefore <= prev. */
* That low range needs the extra `x != prev` test and is at most pidx+1 long (0 for an argmax,
* R-1 for the R-th pick), so it stays scalar. Past it, `x == best` implies eligibility, since
* best <= prev. */
for (int64_t j = 0; j < split; ++j) {
const float x = v[j];
if (x != best || x == prev) continue;
@@ -374,28 +352,18 @@ bool topk_next_f32(const float* v, int64_t n, float* pv, int64_t* pi) {
/* ================================================================== the machine's FMA ceiling
*
* THE CEILING HAS TO BE MEASURED WITH THE FLAGS THE KERNELS ARE COMPILED WITH, which is why this
* lives here -- in a file compiled once per ISA level -- and not in rad-avx-bench, which is
* baseline-compiled like the dispatcher and can only ever emit SSE2. A bench that reported the
* scalar chain as "the machine's peak" would be reporting something ten times below what a GEMM
* at this level is up against, and every kernel would look like it was doing well.
* Measured here, with the kernels' per-level flags, because rad-avx-bench is baseline-compiled
* and could only measure a scalar chain far below what a GEMM at this level faces.
*
* WHAT IT MEASURES: a dependency-free chain of independent FMA accumulators, all in registers,
* nothing touching memory. What comes out is what the machine RETIRES, including whatever clock it
* actually holds under a sustained vector load -- which on a part with an AVX-512 frequency offset
* is not the advertised boost, and is exactly the number a kernel is competing with.
* Independent FMA accumulators in registers, no memory traffic. The result is what the core
* retires at the clock it holds under sustained vector load (below advertised boost on parts with
* an AVX-512 frequency offset).
*
* THE ACCUMULATOR COUNT IS THE REGISTER FILE, and getting it wrong understates the ceiling rather
* than overstating it -- which is worse, because every kernel then looks good against it. Sixteen
* accumulators plus the two constants is EIGHTEEN live vectors, which fits AVX-512's 32 registers
* and spills on AVX2's and AVX's 16. With sixteen everywhere the AVX2 peak comes out barely above
* the AVX one -- a step of a few percent for turning two instructions into one, where the ports
* say 2x -- because the spill is inside the loop. Ten accumulators covers a 4-5 cycle FMA latency
* against 2 FMA ports with room to spare and leaves six registers free.
* The accumulator count must fit the register file; a spill inside the loop understates the
* ceiling. 16 accumulators plus 2 constants fit AVX-512's 32 registers but spill on AVX/AVX2's 16.
* 10 covers a 4-5 cycle FMA latency on 2 FMA ports and leaves six registers free.
*
* `volatile` on the sink, so the whole loop is not deleted. The accumulators are read out through
* it; without that the compiler is entirely within its rights to remove the work and report an
* infinite ceiling, which is the classic way this measurement is wrong. */
* The `volatile` sink keeps the compiler from deleting the loop. */
extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) {
using namespace avx;
#if AVX_LEVEL == 1 || AVX_LEVEL == 2
@@ -412,6 +380,6 @@ extern "C" double AVX_FN(avx_peak_fma)(int64_t iters) {
for (int i = 0; i < NACC; ++i) sink += vf_hsum(acc[i]);
volatile float keep = sink;
(void)keep;
/* 2 flops an FMA, NACC of them an iteration, VF_N lanes each. */
/* 2 flops per FMA, NACC FMAs per iteration, VF_N lanes each. */
return 2.0 * (double)iters * (double)NACC * (double)VF_N;
}