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

+93 -150
View File
@@ -1,41 +1,26 @@
/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives.
/* avx_misc.cpp -- the PLE pair, the hashed n-gram ids, and the two collectives. Mostly scalar:
*
* Grouped because none of them is a vector kernel and the reason differs in each case, which is
* worth saying rather than leaving as an absence:
* ple_gate vectorises the per-stream norms and the gated broadcast of `v`. The dot between the
* two normed streams is accumulated in f64, as in libref: it feeds a signed square root, whose
* relative sensitivity is unbounded near zero, so an f32 reduction over a 10240-wide product
* would move the gate past tolerance on rows near the hinge.
*
* ple_gate IS vectorised, in the two places that carry the work -- the per-stream norms and the
* gated broadcast of `v`. What is not is the dot between the two normed streams, which is
* accumulated in f64 because libref accumulates it in f64 and this is the one op where that
* choice is visible: the dot feeds a SIGNED SQUARE ROOT, which has unbounded relative sensitivity
* near zero, so an f32 reduction of a 10240-wide product would move the gate by more than the
* tolerance on exactly the rows where the gate is near its hinge.
* ple_conv is a width-4 depthwise convolution with taps `dilation` apart; channels are the
* parallel axis and the four-term inner loop has nothing to vectorise.
*
* ple_conv is a depthwise convolution of width 4 over a channel, which is 4 multiplies per
* output element with the taps `dilation` apart. The channel loop is the parallel axis and the
* inner one is four terms; there is no vector work in it that the outer parallelism does not
* already have. What it gets instead is the rolling-window rule written out exactly.
* ngram_ids is integer hashing with a data-dependent early cut, using torch's arithmetic (a
* wrapping 64-bit multiply and a flooring modulo).
*
* ngram_ids is INTEGER HASHING with a data-dependent early cut, and its arithmetic is defined by
* torch's -- a wrapping 64-bit multiply and a FLOORING modulo, neither of which is C's. There is
* nothing here to vectorise and a great deal to get exactly right.
*
* all_reduce / all_gather serve WORLD SIZE 1 and refuse anything wider by name. See the note on
* the collectives below; it is a deliberate limit, not an omission.
* all_reduce / all_gather serve world size 1 only and refuse wider worlds (see below).
*/
#include "avx_vec.h"
#include "avx_common.h"
using namespace avx;
static inline float narrow1(uint32_t dt, float v) {
uint32_t buf[2] = { 0, 0 };
rad_store_f32(buf, dt, 0, v);
return rad_load_f32(buf, dt, 0);
}
/* One group's reciprocal RMS over `n` contiguous f32. f64 accumulation, matching libref's
* `group_rsqrt`: the rsqrt is per n-wide stream while the gain below it spans all hc*n, and that
* asymmetry is the whole of what `group_size` means on Qwen4ExpTextRMSNorm. */
/* Reciprocal RMS of one n-wide stream, accumulated in f64 as libref's `group_rsqrt`. The rsqrt is
* per stream while the gain spans all hc*n; that is what `group_size` means on
* Qwen4ExpTextRMSNorm. */
static float group_rsqrt_f64(const float* v, int64_t n, float eps) {
double acc = 0;
for (int64_t d = 0; d < n; ++d) acc += (double)v[d] * (double)v[d];
@@ -43,21 +28,18 @@ static float group_rsqrt_f64(const float* v, int64_t n, float eps) {
}
/* ------------------------------------------------------------------ ple_gate */
/* k [M][hc*n] key_proj(embedding), UN-normed
* q [M][hc*n] the incoming hyper-connection stream, UN-normed
* v [M][n] value_proj(embedding) -- ONE row, gated differently per stream
/* k [M][hc*n] key_proj(embedding), unnormed
* q [M][hc*n] the incoming hyper-connection stream, unnormed
* v [M][n] value_proj(embedding): one row, gated differently per stream
* w_key / w_query / w_conv [hc*n] gains
* gv [M][hc*n] out, UN-normed: what the residual add reads
* gvn [M][hc*n] out, normed: what the convolution reads
* gv [M][hc*n] out, unnormed: read by the residual add
* gvn [M][hc*n] out, normed: read by the convolution
*
* THE THIRD NORM IS TAKEN OVER WHAT THIS OP ITSELF WROTE, and it is READ BACK rather than carried
* in registers -- which is why the op owns all three norms instead of the graph owning the last
* one. Splitting it would make two definitions of the same rounding.
* The third norm is taken over gv as stored (rounded through its dtype), which is why this op owns
* all three norms.
*
* THE SIGNED SQUARE ROOT IS IN THE REFERENCE'S ORDER: the magnitude is clamped to `gate_eps`, the
* root is taken of the clamped magnitude, and the sign is reapplied afterwards. Clamping after the
* root, or taking the root of the signed value, are both different functions near zero and the
* gate spends its life near zero. */
* Signed square root in the reference's order: clamp the magnitude to `gate_eps`, take the root,
* reapply the sign. Other orders differ near zero, where the gate usually sits. */
AVX_KERNEL(ple_gate) {
if (!rad_args_have(a, 8)) return RAD_E_INVAL;
const RadTensor* k = &a->t[0];
@@ -70,12 +52,12 @@ AVX_KERNEL(ple_gate) {
const RadTensor* gvn = &a->t[7];
const int64_t n = p_int(a, "n", 0);
/* `v` is [M, n] and it is the call; `M` is the band. */
/* Rows come from `v` ([M, n]); the `M` parameter is the band's upper bound. */
const int64_t M = n > 0 ? band_rows(numel(v) / n, p_int(a, "M", 0)) : 0;
const int64_t hc = p_int(a, "hc", 0);
const float eps = p_f32(a, "eps", 1e-6f);
const float wadd = p_f32(a, "wadd", 0.0f);
/* The floor the gate's magnitude is clamped to before the square root. */
/* Floor for the gate's magnitude before the square root. */
const float geps = p_f32(a, "gate_eps", 1e-6f);
if (M <= 0 || n <= 0 || hc <= 0) return RAD_E_SHAPE;
const int64_t hn = hc * n;
@@ -83,8 +65,8 @@ AVX_KERNEL(ple_gate) {
if (numel(wk) < hn || numel(wq) < hn || numel(wc) < hn) return RAD_E_SHAPE;
if (numel(gv) < M * hn || numel(gvn) < M * hn) return RAD_E_SHAPE;
/* The three gains, widened once with `wadd` folded in. One allocation -- the arena grows, so a
* second scratch_raw would free this one under the worker threads. */
/* The three gains, widened once with `wadd` folded in, in one allocation: a second
* scratch_raw call could free this one under the worker threads. */
float* gains = (float*)scratch_raw((size_t)(3 * hn) * sizeof(float) + 64);
float* gk = gains;
float* gq = gains + hn;
@@ -98,7 +80,6 @@ AVX_KERNEL(ple_gate) {
}
}
const int64_t gls = laststride(gv), gnls = laststride(gvn);
AVX_PARALLEL_FOR_IF(M >= 2)
for (int64_t m = 0; m < M; ++m) {
@@ -116,8 +97,7 @@ AVX_KERNEL(ple_gate) {
for (int64_t c = 0; c < hc; ++c) {
const float rk = group_rsqrt_f64(kk + c * n, n, eps);
const float rq = group_rsqrt_f64(qq + c * n, n, eps);
/* f64, and see the file header: the dot feeds a signed square root whose relative
* sensitivity is unbounded near zero. */
/* f64: the dot feeds the signed square root (see the file header). */
double dot = 0;
for (int64_t d = 0; d < n; ++d) {
const int64_t j = c * n + d;
@@ -128,7 +108,7 @@ AVX_KERNEL(ple_gate) {
float s = (float)(dot / std::sqrt((double)n));
const float mag = std::sqrt(std::fabs(s) < geps ? geps : std::fabs(s));
s = s > 0.0f ? mag : (s < 0.0f ? -mag : 0.0f);
const float g = 1.0f / (1.0f + std::exp(-s));
const float g = 1.0f / (1.0f + sc_exp(-s));
const vf vg = vf_set1(g);
int64_t d = 0;
@@ -136,12 +116,9 @@ AVX_KERNEL(ple_gate) {
vf_storeu(out + c * n + d, vf_mul(vg, vf_loadu(vv + d)));
for (; d < n; ++d) out[c * n + d] = g * vv[d];
}
if (gls == 1) out_row(gv, gb, hn, out);
else for (int64_t j = 0; j < hn; ++j) stt(gv, gb + j * gls, out[j]);
out_row(gv, gb, hn, out);
/* The third norm, over what was just written -- read BACK through gv's dtype, not carried
* in registers. The round trip is done here rather than by re-reading the operand: same
* arithmetic, and it does not depend on the store having retired. */
/* Third norm over gv as stored: round `out` through gv's dtype in scratch. */
if (gv->dtype != RAD_F32) {
row_from_f32(gv->dtype, out, kv, hn);
row_to_f32(gv->dtype, kv, out, hn);
@@ -153,31 +130,30 @@ AVX_KERNEL(ple_gate) {
qv[j] = narrow1(gvn->dtype, out[j] * r * gc[j]);
}
}
if (gnls == 1) out_row(gvn, nb, hn, qv);
else for (int64_t j = 0; j < hn; ++j) stt(gvn, nb + j * gnls, qv[j]);
out_row(gvn, nb, hn, qv);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ ple_conv */
/* PLE's dilated depthwise convolution, silu AFTER it, and the residual add folded in.
/* PLE's dilated depthwise convolution, then silu, with the residual add folded in. Two rules,
* both silent when broken:
*
* TWO RULES THAT ARE NOT DERIVABLE AND ARE BOTH SILENT WHEN WRONG:
* `has_init` zero means the slot holds no history: the window before the first token is zeros.
* Otherwise a new sequence on a recycled slot convolves the previous sequence's tail into its
* first (width-1)*dilation tokens.
*
* A ZERO `has_init` MEANS THE SLOT HOLDS NO HISTORY -- the window in front of the first token is
* ZEROS, not whatever the slot last held. Without it a fresh sequence landing on a recycled slot
* convolves the previous sequence's tail into its first `(width-1)*dilation` tokens: fluent
* output with the wrong prefix.
* `num_accepted` shifts the read and selects the window left behind (full contract: libref's
* ref_ple.cpp). Present, this is a decode step whose drafts may be rejected: the history read is
* offset by num_accepted - 1 and the state keeps the shifted history followed by every input of
* the step, so a next step that kept k tokens reads at k - 1. Absent, every token commits and the
* last (width-1)*dilation inputs land at offset zero.
*
* `num_accepted` SHIFTS THE READ AND ITS PRESENCE PICKS THE WINDOW LEFT BEHIND -- libref's
* ref_ple.cpp states the contract in full. Present, the step is a decode step whose drafts a
* verify may reject: the history read is shifted down by one and every input of the step follows
* it, so a next step that kept k tokens reads at k - 1 and finds the history ending at the k-th.
* Absent, every token commits and the last (width-1)*dilation inputs land at offset zero. The
* write happens in a SECOND pass after every read is done, because a sequence longer than the
* window would otherwise overwrite history it is still reading. */
/* ONE BODY FOR ple_conv AND causal_conv1d (LFM2's short convolution: undilated, no activation, no
* residual), as in libref, so the two cannot disagree about the window's layout. */
* The state is written in a second pass after all reads, since a sequence longer than the window
* would otherwise overwrite history it still reads.
*
* One body serves ple_conv and causal_conv1d (LFM2's short convolution: undilated, no activation,
* no residual), as in libref, so both use the same window layout. */
struct ConvOps {
const RadTensor *x, *w, *cs, *cu, *resid, *sidx, *hini, *nacc, *y;
bool silu;
@@ -189,14 +165,14 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
if (!x || !w || !cs || !cu || !y) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0);
/* `x` is [M, n] and it is the call; `M` is the band. */
/* Rows come from `x` ([M, n]); the `M` parameter is the band's upper bound. */
const int64_t M = n > 0 ? band_rows(numel(x) / n, p_int(a, "M", 0)) : 0;
const int64_t wid = p_int(a, "width", 0);
const int64_t dil = p_int(a, "dilation", 1);
if (M <= 0 || n <= 0 || wid <= 0 || dil <= 0) return RAD_E_SHAPE;
const int64_t hist_len = (wid - 1) * dil;
/* The read window lives in a stack frame. Nine at this model's shape; the bound is stated so a
* wider one is refused by name rather than overflowing. Same number as libref's. */
/* The read window is a stack array (9 at PLE's shape); wider windows are refused rather than
* overflowing. Same bound as libref. */
enum { kHistMax = 64 };
if (hist_len > kHistMax) return RAD_E_UNSUPPORTED;
@@ -208,9 +184,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
const int64_t state_len = cs->rank >= 3 ? cs->shape[cs->rank - 1] : hist_len;
if (cs->data && state_len < hist_len) return RAD_E_SHAPE;
/* Checked for every sequence BEFORE any of them is written: a state too shallow for the offset,
* or for the window a decode step leaves behind, is a caller error, and an OpenMP body cannot
* return. */
/* Validate every sequence before writing any (an OpenMP body cannot return): the state must
* be deep enough for the offset and for the window a decode step leaves behind. */
for (int64_t s = 0; s < N; ++s) {
const int64_t off = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
if (off < 0) return RAD_E_INVAL;
@@ -225,7 +200,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
const int64_t rrow = resid ? rowoff(resid, 1, n) : 0;
const int64_t rcol = resid ? laststride(resid) : 0;
const int64_t wrow = rowoff(w, 1, wid), wcol = laststride(w);
/* [n_slots, n, state_len], tight -- the layout gdn's conv state already uses. */
/* [n_slots, n, state_len], dense, the same layout as gdn's conv state. */
const int64_t cs_slot = n * state_len, cs_ch = state_len;
AVX_PARALLEL_FOR_IF(N * n >= 64)
@@ -243,10 +218,8 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
for (int64_t i = 0; i < hist_len; ++i)
hist[i] = (warm && cs->data) ? ldt(cs, slot * cs_slot + c * cs_ch + off + i) : 0.0f;
/* The taps, read once per channel rather than per output element -- libref reads them
* through `ldt` inside the t loop, which is `slen * width` dtype switches for `width`
* distinct values. In scratch rather than a stack array so `width` carries no bound of its
* own: the only limit this op has is the read window's, stated above. */
/* Taps read once per channel (libref reads them per output element). Kept in scratch, not
* on the stack, so `width` needs no bound of its own. */
float* tap = scratch_f32((size_t)wid);
for (int64_t j = 0; j < wid; ++j) tap[j] = ldt(w, c * wrow + j * wcol);
@@ -259,7 +232,7 @@ static int depthwise_causal_conv(const RadArgs* a, const ConvOps& o) {
acc += vv * tap[j];
}
const float r = resid ? ldt(resid, (bos + t) * rrow + c * rcol) : 0.0f;
stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + std::exp(-acc)) : acc));
stt(y, (bos + t) * yrow + c * ycol, r + (o.silu ? acc / (1.0f + sc_exp(-acc)) : acc));
}
}
@@ -304,7 +277,7 @@ AVX_KERNEL(ple_conv) {
rad_arg_in(a, 6), rad_arg_in(a, 7), rad_arg_in(a, 8), true });
}
/* ple_conv's operands without `resid`, at dilation one and with no activation. */
/* ple_conv's operands without `resid`, dilation 1, no activation. */
AVX_KERNEL(causal_conv1d) {
if (a->n_t < 8) return RAD_E_INVAL;
if (p_int(a, "dilation", 1) != 1) return RAD_E_INVAL;
@@ -315,25 +288,16 @@ AVX_KERNEL(causal_conv1d) {
/* ------------------------------------------------------------------ ngram_ids
*
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h].
* ids[m][h] = (hash of the n-gram ending at m) % vocab[h] + offset[h], in torch's arithmetic:
*
* THE ARITHMETIC IS TORCH'S, NOT C's, and both differences bite:
* Signed overflow is UB in C++ but wraps in torch, so the multiply goes through uint64.
* `torch.remainder` floors where C's `%` truncates, so the modulo is written out.
*
* A SIGNED OVERFLOW IS UB IN C++ AND WRAPPING IN TORCH, so the multiply goes through uint64 and
* comes back -- two's complement, which is what an int64 tensor does on every machine this runs
* on.
* Neither matters on a real checkpoint (multipliers are bounded by (2^63-1)//vocab_size, so real
* products are non-negative); they make random test inputs match torch.
*
* `torch.remainder` FLOORS WHERE C TRUNCATES, so the modulo is written out rather than left to
* `%`.
*
* On a real checkpoint neither can fire -- the multiplier build bounds every multiplier by
* (2^63-1)//vocab_size, so a real token's product has its sign bit clear and truncating and
* flooring agree on a non-negative dividend. They are here so that a DRAWN case, whose indices no
* vocabulary bounds, gets torch's answer rather than a platform's.
*
* THE EOS RULE IS COLLAPSED: once a shift falls off the front of the sequence, every longer shift
* is EOS too, so the cut is carried rather than re-tested. A COLD slot's window is EOS and not
* zero, because zero is a real token. */
* Once a shift reaches EOS, every longer shift is EOS too, so the cut is carried. A cold slot's
* window is EOS, not zero, because zero is a real token. */
static inline int64_t wrap_mul(int64_t x, int64_t y) {
return (int64_t)((uint64_t)x * (uint64_t)y);
}
@@ -354,24 +318,24 @@ AVX_KERNEL(ngram_ids) {
const RadTensor* hini = rad_arg_in(a, 7);
const RadTensor* nacc = rad_arg_in(a, 8);
const RadTensor* ids = rad_arg_in(a, 9);
/* THE PROMPT THAT FOLLOWS, optional: `tok` holds its row count more tokens after the step's,
* continuing the LAST sequence, and their ids go here. The window is the step's own. */
/* Optional ids for the prompt that follows: `tok` holds that many more tokens after the
* step's, continuing the last sequence. The state window is still the step's own. */
const RadTensor* ahead = a->n_t > 10 ? rad_arg_in(a, 10) : nullptr;
if (!tok || !st || !cu || !mult || !vsz || !off_ || !ids) return RAD_E_INVAL;
const int64_t heads = p_int(a, "heads", 0);
if (heads <= 0) return RAD_E_SHAPE;
/* The token vector is the call and the prompt that follows it; `M` is the band. */
/* Rows come from `tok` minus the prompt ahead; the `M` parameter is the band's upper bound. */
const int64_t A = ahead ? numel(ahead) / heads : 0;
const int64_t M = band_rows(numel(tok) - A, p_int(a, "M", 0));
const int64_t ngram = p_int(a, "ngram", 0);
const int64_t eos = p_int(a, "eos", -1);
if (M <= 0 || heads <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* Heads are `ngram - 1` blocks of `heads_per_ngram`, block b using the (b+2)-gram. */
if (M <= 0 || ngram < 2 || eos < 0) return RAD_E_SHAPE;
/* Heads form `ngram - 1` blocks of `heads_per_ngram`; block b uses the (b+2)-gram. */
if (heads % (ngram - 1)) return RAD_E_SHAPE;
const int64_t per = heads / (ngram - 1);
const int64_t ctx = ngram - 1;
if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window lives in a stack frame */
if (ngram > 8) return RAD_E_UNSUPPORTED; /* the shift window is a stack array */
if (numel(mult) < ngram || numel(vsz) < heads || numel(off_) < heads) return RAD_E_SHAPE;
if (numel(tok) < M + A || numel(ids) < M * heads) return RAD_E_SHAPE;
@@ -380,8 +344,8 @@ AVX_KERNEL(ngram_ids) {
if (n_seq <= 0) return RAD_E_SHAPE;
const int64_t W = st->rank >= 2 ? st->shape[st->rank - 1] : ctx;
if (W < ctx) return RAD_E_SHAPE;
/* The read window, and the window a decode step leaves behind: `ctx - 1` ids of history plus
* every id of the step. */
/* The state must hold the read window and the window a decode step leaves behind (`ctx - 1`
* ids of history plus every id of the step). */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t o = nacc ? ldi(nacc, offlin(nacc, s)) - 1 : 0;
if (o < 0) return RAD_E_INVAL;
@@ -393,8 +357,7 @@ AVX_KERNEL(ngram_ids) {
const int64_t ids_ld = rowoff(ids, 1, heads);
const int64_t ahd_ld = ahead ? rowoff(ahead, 1, heads) : 0;
/* The per-head tables, read once. libref reads `vocab_sizes` and `offsets` through ld_int
* inside the innermost loop, which is `M * heads` dtype switches for `heads` distinct values. */
/* Per-head tables read once (libref reads them in the innermost loop). */
int64_t* tab = (int64_t*)scratch_raw((size_t)(2 * heads + ngram) * sizeof(int64_t) + 64);
int64_t* vtab = tab;
int64_t* otab = tab + heads;
@@ -406,9 +369,8 @@ AVX_KERNEL(ngram_ids) {
}
for (int64_t k = 0; k < ngram; ++k) mtab[k] = ldi(mult, k);
/* Serial over sequences, as libref is: each writes its own state slot, the work per sequence is
* a token loop with a handful of integer ops, and a parallel region over a handful of
* sequences would cost more than it saves. */
/* Serial over sequences, as in libref: the per-sequence work is a short integer loop, too
* little to pay for a parallel region. */
for (int64_t s = 0; s < n_seq; ++s) {
const int64_t bos = ldi(cu, offlin(cu, s));
const int64_t eot = ldi(cu, offlin(cu, s + 1));
@@ -439,8 +401,8 @@ AVX_KERNEL(ngram_ids) {
sh[k] = hist(p - k);
}
/* One mix per n-gram order, EXTENDED IN PLACE: the (b+2)-gram's mix is the
* (b+1)-gram's XOR'd with one more term, which saves recomputing the shared prefix. */
/* Mixes are extended in place: the (b+2)-gram's is the (b+1)-gram's XOR one more
* term. */
int64_t mixed = 0;
int64_t blk = -1;
for (int64_t k = 0; k < ngram; ++k) {
@@ -460,9 +422,9 @@ AVX_KERNEL(ngram_ids) {
}
}
/* The window this step leaves behind, written after every read of it is done, in the
* layout ple_conv's state follows: shifted by one with every id of the step behind it when
* `num_accepted` is present, the last `ctx` ids at offset zero when it is not. */
/* State window, written after all reads, in ple_conv's layout: with `num_accepted`, the
* history shifted by one followed by every id of the step; without, the last `ctx` ids at
* offset zero. */
const int64_t base = rowoff(st, slot, W);
if (nacc) {
for (int64_t i = 0; i + 1 < ctx; ++i)
@@ -482,37 +444,21 @@ AVX_KERNEL(ngram_ids) {
/* ================================================================== the collectives
*
* WORLD SIZE 1 ONLY, AND THAT IS A DELIBERATE LIMIT RATHER THAN AN OMISSION.
* World size 1 only, by design. libref implements real host collectives (one process, one thread
* per rank, a shared address space: a rendezvous, read every rank's pointer, rendezvous again),
* which lets the host backend exercise tensor-parallel graphs without a second card. That state (a
* barrier, a generation counter, a timeout) must exist once per process: a second copy in this
* plugin would form a separate rendezvous group, and ranks would deadlock whenever selection put
* them in different plugins. So above world 1 these return RAD_E_UNSUPPORTED and the selector
* falls through to libref.
*
* libref implements the real thing, and it can because of how this engine is shaped: one process,
* one thread per rank, one address space, so a peer's buffer is a POINTER and the whole collective
* is a rendezvous, a read of every rank's pointer, and a second rendezvous before anyone
* overwrites theirs. That makes the host backend a fake multi-device backend, which is genuinely
* useful -- the sharded declare, the collective placement and the distributed top-k can all be
* exercised on a box with no second card.
*
* It is also a piece of SHARED MUTABLE STATE with a barrier, a generation counter and a timeout,
* and there is exactly one of it per process. Two kernel plugins each carrying their own would be
* two rendezvous groups for one world, and which one a rank joined would depend on which plugin
* won selection for that op -- a deadlock that appears only when the hierarchy changes. A CPU
* kernel library has no business owning the wire; libref already owns it and sits below this
* plugin in the hierarchy, so a tensor-parallel host deployment resolves the collectives there and
* everything else here.
*
* So: at world 1 both are the degenerate case and are served exactly. Above 1 this refuses by name
* with RAD_E_UNSUPPORTED, which makes the selector fall through to libref's row rather than
* producing a wrong sum.
*
* `exact` IS HONOURED IN ONE DIRECTION ONLY, as libref does: exact=1 gets the exact sum, and
* exact=0 -- a caller that has declared it will accept a lossy quantised wire -- ALSO gets the
* exact sum, because there is no wire here to quantise. Serving a lossy request exactly is safe;
* the constraint exists so a caller who wanted exactness cannot be handed a lossy result by
* accident, not the reverse. */
* `exact` is honoured one way, as in libref: exact=0 permits a lossy wire but there is none here,
* so both settings get the exact result. */
AVX_KERNEL(all_reduce) {
if (!rad_args_have(a, 1)) return RAD_E_INVAL;
const RadTensor* x = &a->t[0];
const RadTensor* y = rad_arg_in(a, 1);
/* The message is the operand; `numel` is the band. */
/* The element count comes from the operand; the `numel` parameter is the band. */
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
if (nel <= 0) return RAD_E_SHAPE;
if (y && numel(y) < nel) return RAD_E_SHAPE;
@@ -520,8 +466,7 @@ AVX_KERNEL(all_reduce) {
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (world > 1) return RAD_E_UNSUPPORTED;
/* In place: the answer is already there. With a separate destination it still has to be COPIED
* there, because a caller that passed one reads it and not x. */
/* In place: nothing to do. With a separate destination, copy x into it. */
if (!y) return RAD_OK;
if (rad_tensor_is_contiguous(x) && rad_tensor_is_contiguous(y)) {
const int64_t TILE = 8192;
@@ -539,16 +484,14 @@ AVX_KERNEL(all_reduce) {
AVX_KERNEL(all_gather) {
if (!rad_args_have(a, 2)) return RAD_E_INVAL;
const RadTensor *x = &a->t[0], *y = &a->t[1];
/* The contribution is the operand; `numel` is the band. */
/* The element count comes from the operand; the `numel` parameter is the band. */
const int64_t nel = band_rows(numel(x), p_int(a, "numel", 0));
const int world = (int)p_int(a, "world_size", a->world_size > 0 ? a->world_size : 1);
if (nel <= 0 || numel(y) < nel * world) return RAD_E_SHAPE;
if (world > 1) return RAD_E_UNSUPPORTED;
/* THE `row` PLACEMENT DOES NOT MATTER AT WORLD 1 and is still checked, because a caller that
* passes an illegal one at world 1 would get a silent pass here and a refusal at world 2 --
* and the whole value of running a tensor-parallel graph at world 1 is that it is the same
* graph. */
/* `row` has no effect at world 1 but is still validated, so an invalid graph fails the same
* way at world 1 as at world 2. */
const int64_t row = p_int(a, "row", 0);
if (row < 0 || (row > 0 && nel % row)) return RAD_E_SHAPE;