radiance 1.15.0

New models and formats:
- IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column
  (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in
  VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight
  (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md)
- libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d
- Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral
  tower, on the card and on the CPU
- Nemotron 3.5 Rerank 8B
- /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside
  LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass
- LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe
- DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags

Weights on the drive:
- The file tier reads only the experts the pass routes rows to; the draft head's weights stay in
  the host pool
- A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host
  pool slots, and copyless evictions; the file tier's counters are now ssd_*
- GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive
- The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's
  own completion fence

Quantisation tooling:
- --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside
  --kld-record the reference's own run records them
- --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass)
- GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks
  with coordinate descent, and rad-convert --reuse repeated, each container supplying what the
  earlier ones lack

Speculation:
- Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its
  n-grams, and a proposal is verified only when its measured step cost says it pays;
  --draft-window adaptive follows it

Speed:
- IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K
  block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's
  time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms
  before and FP8's 27.3
- Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8
- libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and
  rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores

Features:
- /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced
  nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356)
- --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344)
- The startup report lists only the options not at their default, with a count; -v lists all
  (#250)
- --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room
- --placement layer_offload spills dense layers so one --max-model-len sequence fits
- Startup refuses amdgpu with CWSR off and says how to fix it;
  --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner

Fixes:
- The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row
  cache holds, and pauses while decode reads: about one drive read a row instead of two (#355)
- A file-tier window reads each of its runs once, not once a run per run
- The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer
  declares 64x the scratch (#342)
- A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a
  prefill stage copies only the blocks its own tables name (#343)
- The split-KV row sum is read with fetch-inactive (#328)
- LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348)
- The preempted-prefill gate skips a KV group that holds no blocks (#352)
- Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes
  in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id
  outside the vocabulary refused at admission; --api-key "" refused at startup
- The telemetry the HTTP thread reads is atomic
- An RMS norm row no longer depends on how many rows its launch carries; prefill attention's
  rescale is decided by live rows only
- A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model
- A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step
  hang)

Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader
refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt.
Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and
plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
This commit is contained in:
Deadcode committed 2026-10-30 22:01:01 +01:00
commit 9ed3ef7a7b
452 files changed
+167762 -1346

No files matched your search

+16
View File
@@ -65,6 +65,7 @@ std::vector<Case> build_cases() {
add("mul_weight", { HI("M", 9), HI("n", 645), HS("dtype", dt), HI("scalar", 1) },
EB(9, 645, w, 2));
add("seg_mean", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 1));
add("seg_softmax_pool", { HI("M", 23), HI("n", 645), HS("dtype", dt) }, EB(23, 645, w, 2));
if (!std::strcmp(dt, "bf16"))
add("seg_mean_bf16_sum", { HI("M", 23), HI("n", 645), HS("dtype", dt) },
EB(23, 645, w, 1));
@@ -1223,6 +1224,21 @@ std::vector<Case> build_cases() {
add("sub_i32", { HI("M", 1) });
add("sub_i32", { HI("M", 37) });
/* The row-form names: every case of the base op again under the name. */
{
const char* const forms[][2] = { { "rmsnorm", "rmsnorm_rows" }, { "rope", "rope_rows" },
{ "gemm_nt_q", "gemm_nt_q_short" },
{ "gemm_nt_q_gated", "gemm_nt_q_gated_wide" } };
const size_t n = c.size();
for (size_t i = 0; i < n; ++i)
for (const auto& f : forms)
if (std::strcmp(c[i].op, f[0]) == 0) {
Case x = c[i];
x.op = f[1];
c.push_back(x);
}
}
/* ================================================================== speed-only, at model size
*
* Timed by rad-avx-bench, skipped by rad-avx-check. The cases above are sized to break kernels;
+1
View File
@@ -815,6 +815,7 @@ int main(int argc, char** argv) {
/* And in TMPDIR, usually tmpfs: since Linux 6.6 tmpfs does direct reads but reports
* no alignment (like btrfs), so the gather uses the block size. Only the read differs
* there, so it runs once. */
if (lvl == top && !row_ahead_case(lib, at, ck.verbose)) rc = 1;
if (lvl == top) {
const char* tmp = std::getenv("TMPDIR");
if (!row_gather_case(lib, tmp && *tmp ? tmp : "/tmp", calls, seed, ck.verbose,
+3
View File
@@ -58,6 +58,9 @@ bool hand_cases(const Check& ck);
* per process and kept mapped, so later calls reuse it. */
bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint64_t seed,
bool verbose, bool bf16);
/* embed_lookup_q over a prefill whose following chunks are passed ahead, as the engine passes
* them: every row read about once, every row exact (avx_check_rows.cpp). */
bool row_ahead_case(const Lib& lib, const std::string& dir, bool verbose);
/* embed_lookup_q's init with io_uring refused, and in this process (avx_check_rows.cpp). */
bool ngram_init_case(const Lib& lib);
+104
View File
@@ -355,3 +355,107 @@ bool row_gather_case(const Lib& lib, const std::string& dir, int64_t calls, uint
granule, (long long)calls);
return pass;
}
/* A prefill's read-ahead, as the engine drives it (#355): each call gathers one chunk of 65,536
* rows (4096 tokens of 16 heads) and passes the following eight chunks as `ahead`, the window
* moving on by one chunk a call, with both ranks passing the same lists. Each row the calls gather
* must be read from the file about once: each window adds one chunk to what the reader was handed,
* and what is read ahead must still be in the cache when its chunk is gathered. Handing each window
* over whole queued every chunk eight times and read ahead the cache's whole 2^19 rows, so rows
* were evicted before their chunk came and read again, and the reader went on reading after the
* last call. avx_ngram_reads counts the rows read from table files once the reader is idle; the
* table is row_gather_case's, so some rows are already cached and read less than once. */
bool row_ahead_case(const Lib& lib, const std::string& dir, bool verbose) {
const char* what = "embed_lookup_q's read-ahead over a prefill";
const RadKernelInfo* r = lib.row("embed_lookup_q");
auto reads = (uint64_t (*)())dlsym(lib.h, "avx_ngram_reads");
if (!r || !r->launch || !reads) {
std::printf(" %s: %s\n", what, !reads ? "no avx_ngram_reads export" : "no row");
return false;
}
if (const int e = ring_probe()) {
std::printf(" %s: SKIPPED -- %s\n", what,
e == ENOMEM ? kRingMemory
: (std::string("io_uring is unavailable here (") +
std::strerror(e) + ")").c_str());
return true;
}
const int64_t n = 40, V = int64_t(1) << 21, M = 65536, chunks = 12, window = 8;
RowTable* rt = row_table(dir, false, V, n);
if (rt->state == RowTable::SKIP) {
std::printf(" %s: SKIPPED -- %s\n", what, rt->note.c_str());
return true;
}
if (rt->state != RowTable::OK) {
std::printf(" %s: %s\n", what, rt->note.c_str());
return false;
}
const uint8_t* tab = rt->tab;
const float scale = 0.375f;
uint64_t x = 0x2545f4914f6cdd1dull;
auto rnd = [&x]() { x ^= x << 13; x ^= x >> 7; x ^= x << 17; return x; };
std::vector<int32_t> ids((size_t)(chunks * M));
for (auto& id : ids) id = (int32_t)(rnd() % (uint64_t)V);
std::vector<int32_t> distinct(ids);
std::sort(distinct.begin(), distinct.end());
const int64_t U = std::unique(distinct.begin(), distinct.end()) - distinct.begin();
uint16_t lut[256];
for (int b = 0; b < 256; ++b) lut[b] = rad_f32_to_bf16(rad_fp8e4m3_to_f32((uint8_t)b) * scale);
auto tensor = [](void* p, uint32_t dt, std::initializer_list<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int i = 0;
for (int64_t s : shape) t.shape[i++] = s;
int64_t st = 1;
for (int k = (int)t.rank - 1; k >= 0; --k) { t.stride[k] = st; st *= t.shape[k]; }
return t;
};
const uint64_t before = reads();
std::barrier<> go(2);
int64_t bad[2] = {0, 0}, refused[2] = {0, 0};
auto rank = [&](int rk) {
uint16_t sc = rad_f32_to_bf16(scale);
std::vector<uint16_t> out((size_t)(M * n));
RadParam ps[3] = {};
ps[0].key = "M"; ps[0].kind = RAD_P_INT; ps[0].ival = M;
ps[1].key = "n_embd"; ps[1].kind = RAD_P_INT; ps[1].ival = n;
ps[2].key = "n_vocab"; ps[2].kind = RAD_P_INT; ps[2].ival = V;
for (int64_t c = 0; c < chunks; ++c) {
const int64_t na = std::min(window, chunks - 1 - c) * M;
std::vector<RadTensor> ts = {
tensor(&ids[(size_t)(c * M)], RAD_I32, {M}),
tensor(const_cast<uint8_t*>(tab), RAD_F8E4M3, {V, n}),
tensor(&sc, RAD_BF16, {1}), tensor(out.data(), RAD_BF16, {M, n}),
tensor(na ? &ids[(size_t)((c + 1) * M)] : nullptr, RAD_I32, {na}) };
RadArgs a{};
a.t = ts.data(); a.n_t = (int)ts.size();
a.p = ps; a.n_p = 3;
a.rank = rk; a.world_size = 2;
go.arrive_and_wait();
if (r->launch(&a, nullptr) != RAD_OK) { ++refused[rk]; continue; }
for (int64_t m = 0; m < M; ++m) {
const uint8_t* row = tab + (int64_t)ids[(size_t)(c * M + m)] * n;
for (int64_t i = 0; i < n; ++i)
if (out[(size_t)(m * n + i)] != lut[row[i]]) { ++bad[rk]; break; }
}
}
};
std::thread t0(rank, 0), t1(rank, 1);
t0.join();
t1.join();
const uint64_t read = reads() - before;
const bool exact = bad[0] + bad[1] + refused[0] + refused[1] == 0;
const bool once = (int64_t)read <= U + U / 10;
const bool pass = exact && once;
std::printf(" %s in %s: %lld chunks of %lld rows x 2 ranks, %llu rows read for %lld distinct "
"(%.2f each)%s%s\n", what, dir.c_str(), (long long)chunks, (long long)M,
(unsigned long long)read, (long long)U, (double)read / (double)U,
exact ? ", every row exact" : "", pass ? "" : " FAIL");
if (!exact || verbose)
std::printf(" rows wrong %lld/%lld, calls refused %lld/%lld\n", (long long)bad[0],
(long long)bad[1], (long long)refused[0], (long long)refused[1]);
return pass;
}
+37
View File
@@ -20,6 +20,9 @@
#include "avx_vec.h"
#include "avx_common.h"
#include <algorithm>
#include <cmath>
using namespace avx;
/* Round a row through an operand's storage dtype and back, as an unfused store-and-reload would.
@@ -534,6 +537,40 @@ AVX_KERNEL(seg_mean) {
return RAD_OK;
}
/* ------------------------------------------------------------------ seg_softmax_pool */
/* One output row per cu_seqlens segment: its rows summed with the softmax of their scores as
* weights, the softmax in f32 with the maximum subtracted, the sum in f32, rounded once, as in
* libref. A segment is a question's few options, so the scores are read plainly. */
AVX_KERNEL(seg_softmax_pool) {
if (!rad_args_have(a, 4)) return RAD_E_INVAL;
const RadTensor *Sc = &a->t[0], *V = &a->t[1], *cu = &a->t[2], *Y = &a->t[3];
const int64_t n = p_int(a, "n", 0);
const int64_t S = numel(cu) - 1;
if (n <= 0 || S <= 0 || numel(Y) < S * n) return RAD_E_SHAPE;
const int64_t total = ldi(cu, offlin(cu, S));
if (total <= 0 || numel(V) < total * n || numel(Sc) < total) return RAD_E_SHAPE;
AVX_PARALLEL_FOR_IF(S >= 2)
for (int64_t s = 0; s < S; ++s) {
const int64_t b0 = ldi(cu, offlin(cu, s)), b1 = ldi(cu, offlin(cu, s + 1));
float* acc = scratch_f32_b((size_t)n);
float* sy = scratch_f32_c((size_t)n);
float one = 0.0f;
float m = -INFINITY, z = 0.0f;
for (int64_t r = b0; r < b1; ++r) m = std::max(m, in_row(Sc, rowoff(Sc, r, 1), 1, &one)[0]);
for (int64_t r = b0; r < b1; ++r) z += std::exp(in_row(Sc, rowoff(Sc, r, 1), 1, &one)[0] - m);
for (int64_t i = 0; i < n; ++i) acc[i] = 0.0f;
for (int64_t r = b0; r < b1; ++r) {
const float w = std::exp(in_row(Sc, rowoff(Sc, r, 1), 1, &one)[0] - m) / z;
const float* x = in_row(V, rowoff(V, r, n), n, sy);
for (int64_t i = 0; i < n; ++i) acc[i] += w * x[i];
}
for (int64_t i = 0; i < n; ++i) sy[i] = b1 > b0 ? acc[i] : 0.0f;
out_row(Y, rowoff(Y, s, n), n, sy);
}
return RAD_OK;
}
/* ------------------------------------------------------------------ pool_rows */
/* As libref: the mean of each k consecutive rows, summed in f32 and rounded to y's dtype, then the
* multiplier and a second rounding (the unfused pair). Parallel over output rows. */
+1
View File
@@ -89,6 +89,7 @@ int avx_par_force(int threads);
X(scale_rows) X(scale) X(fill) X(act_mul) \
X(seg_mean_bf16_sum) \
X(seg_mean) X(mul_weight) X(pool_rows) X(pool_cols) \
X(seg_softmax_pool) \
X(relu) X(clamp) X(conv2d) X(conv1d_dw) \
X(rel_sinusoid) X(seg_sinusoid) X(conv2d_unfold) \
X(position_scale) \
+161 -44
View File
@@ -39,6 +39,7 @@
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <atomic>
#include <condition_variable>
#include <deque>
@@ -571,15 +572,17 @@ int ring_errno() {
return e;
}
/* Reads `reads` through the ring in batches: rows with a slot are copied into the cache and
* published READY; rows without one are decoded directly into their output rows. On a failed read,
* every unpublished claim is released (word back to EMPTY) so no thread waits on it. */
/* Rows read from table files by this process, every thread together (avx_ngram_reads). */
std::atomic<uint64_t> g_rows_read{0};
/* Reads `reads[0, total)` through the ring in batches: rows with a slot are copied into the cache
* and published READY; rows without one are decoded directly into their output rows. On a failed
* read, every unpublished claim is released (word back to EMPTY) so no thread waits on it. */
int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
const std::vector<SpanRead>& reads, long long n, long long ne,
const SpanRead* reads, size_t total, long long n, long long ne,
avx::RowDecode decode, const uint16_t* lut, uint16_t* out, long long x_ld) {
const long long A = tf.align;
const long long stride = ((n + A - 1) / A + 1) * A;
const size_t total = reads.size();
for (size_t b = 0; b < total;) {
const unsigned cnt = (unsigned)(total - b < rr.entries ? total - b : rr.entries);
uint8_t* bounce = g.bounce_for((size_t)cnt * (size_t)stride, (size_t)A);
@@ -592,6 +595,7 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
rc.published.notify_all();
return rs;
}
g_rows_read.fetch_add(cnt, std::memory_order_relaxed);
g.bsrc.clear();
g.bdst.clear();
for (unsigned i = 0; i < cnt; ++i) {
@@ -622,6 +626,17 @@ int read_and_publish(const TableFile& tf, RowCache& rc, ReadRing& rr, Gather& g,
* output row. */
constexpr long long kOnDemandMaxRows = 4096;
/* Decode-sized gathers reading now. The reader thread starts no batch while any is (see the reader
* below); such a gather never waits on another thread's claim, so the pause cannot close a cycle. */
std::atomic<int> g_urgent_reads{0};
struct UrgentReads {
UrgentReads() { g_urgent_reads.fetch_add(1, std::memory_order_acq_rel); }
~UrgentReads() {
if (g_urgent_reads.fetch_sub(1, std::memory_order_acq_rel) == 1) g_urgent_reads.notify_all();
}
};
int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowGather& q,
avx::RowDecode decode, const uint16_t* lut) {
Gather& g = gather_state();
@@ -657,8 +672,10 @@ int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::
g.reads.push_back({m, key, f == RowCache::CLAIMED ? s : -1});
}
}
const UrgentReads urgent;
if (!g.reads.empty()) {
const int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
const int rs = read_and_publish(tf, rc, rr, g, g.reads.data(), g.reads.size(), n, ne,
decode, lut, q.out, x_ld);
if (rs != RAD_OK) return rs;
/* The claimed rows were published into the cache, not decoded: decode them from it. */
for (const SpanRead& r : g.reads) {
@@ -680,7 +697,8 @@ int gather_ondemand(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::
if (g.again.empty()) return RAD_OK;
g.reads.clear();
for (long long m : g.again) g.reads.push_back({m, key_of(m), -1});
return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
return read_and_publish(tf, rc, rr, g, g.reads.data(), g.reads.size(), n, ne, decode, lut,
q.out, x_ld);
}
/* out[m] = decoded row ids[m] - voff for every m < M, through the cache: find or claim each row
@@ -725,7 +743,8 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
else if (f == RowCache::THEIRS) g.waits.push_back(m);
}
int rs = read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
int rs = read_and_publish(tf, rc, rr, g, g.reads.data(), g.reads.size(), n, ne, decode, lut,
q.out, x_ld);
if (rs != RAD_OK) return rs;
/* Wait for rows other threads claimed to turn READY. `published` is read before the words, so
@@ -774,7 +793,8 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
if (g.again.empty()) return RAD_OK;
g.reads.clear();
for (long long m : g.again) g.reads.push_back({m, key_of(m), -1});
return read_and_publish(tf, rc, rr, g, g.reads, n, ne, decode, lut, q.out, x_ld);
return read_and_publish(tf, rc, rr, g, g.reads.data(), g.reads.size(), n, ne, decode, lut,
q.out, x_ld);
}
/* ============================== the reader that runs a step ahead ==============================
@@ -790,26 +810,74 @@ int gather_rows(const TableFile& tf, RowCache& rc, ReadRing& rr, const avx::RowG
* list order. A claim is a promise a gather may wait on, so jobs stay small: a gather that outruns
* the reader finds unclaimed rows and reads them itself.
*
* Both ranks hand over the same ids; a repeated list is dropped. A failed read releases its claims
* and the next call reads those rows itself. The reader is detached and never destroyed. */
struct AheadJob {
const TableFile* tf = nullptr;
RowCache* rc = nullptr;
long long n = 0;
std::vector<uint64_t> keys;
bool retry = false; /* the keys a full set refused once already */
};
* Each id is handed over once, and only as far ahead as the cache can hold it. A call hands over
* at most kAheadRows ids, a quarter of the cache, so a row read ahead is still there when its chunk
* gathers it. Each step's list is the previous one moved on by the chunk just gathered, so only the
* ids past the end of the previous list are new; both ranks hand over the same list, and a repeated
* list adds nothing. A list that does not continue the previous one (another request's prompt)
* drops the jobs still queued for the previous one.
*
* The reader reads in batches of kReaderBatch rows and starts none while a decode-sized gather is
* reading (g_urgent_reads), so a decode step's few reads do not queue in the drive behind a
* prefetch's thousands. A failed read releases its claims and the next call reads those rows
* itself. The reader is detached and never destroyed. */
/* Ids of the following prompt a call hands over, at most: a quarter of the cache. */
constexpr long long kAheadRows = (long long)(RowCache::kRows / 4);
/* Keys per reader job, about two ring batches: a job's claims are promises a consuming gather may
* wait on, so it stays short. */
constexpr size_t kJobRows = 8192;
/* Reads the reader has in the drive at once. A drive serves a batch in arrival order, so this is
* the most a decode step's reads can find ahead of them; 128 still keeps an NVMe queue busy. */
constexpr size_t kReaderBatch = 128;
/* Tries at matching a list against the previous one (read_ahead) before it counts as new. */
constexpr int kShiftTries = 64;
/* One table's following ids as last handed over: the table's cache and offset in the file, and
* the list, clamped to kAheadRows. */
struct AheadStream {
const RowCache* rc = nullptr;
long long base = 0;
std::vector<int32_t> ids;
};
struct AheadJob {
const TableFile* tf = nullptr;
RowCache* rc = nullptr;
long long n = 0;
std::vector<uint64_t> keys;
bool retry = false; /* the keys a full set refused once already */
const AheadStream* stream = nullptr;
};
struct AheadReader {
std::mutex mu;
std::condition_variable cv;
std::condition_variable idle; /* the queues are empty and no job runs */
std::deque<AheadJob> urgent; /* keys a full set refused, tried once more first */
std::deque<AheadJob> q; /* the read-ahead queue: future chunks, in order */
uint64_t last = 0; /* hash of the last id list accepted */
std::vector<std::unique_ptr<AheadStream>> streams;
bool running = false;
/* Called with `mu` held. */
AheadStream* stream(const RowCache* rc, long long base) {
for (const auto& st : streams)
if (st->rc == rc && st->base == base) return st.get();
streams.push_back(std::make_unique<AheadStream>());
streams.back()->rc = rc;
streams.back()->base = base;
return streams.back().get();
}
/* Drops the queued jobs of `st`. Called with `mu` held. */
void drop(const AheadStream* st) {
for (std::deque<AheadJob>* d : { &urgent, &q })
for (auto it = d->begin(); it != d->end();)
it = it->stream == st ? d->erase(it) : it + 1;
}
void run() {
Gather& g = gather_state();
@@ -819,9 +887,12 @@ struct AheadReader {
AheadJob j;
{
std::unique_lock<std::mutex> lk(mu);
running = false;
if (urgent.empty() && q.empty()) idle.notify_all();
cv.wait(lk, [&] { return !urgent.empty() || !q.empty(); });
if (!urgent.empty()) { j = std::move(urgent.front()); urgent.pop_front(); }
else { j = std::move(q.front()); q.pop_front(); }
running = true;
}
if (!rr || !me) continue;
g.reads.clear();
@@ -837,12 +908,25 @@ struct AheadReader {
retry.push_back(j.keys[i]);
}
/* Every read has a slot, so nothing is decoded and there is no output. */
(void)read_and_publish(*j.tf, *j.rc, *rr, g, g.reads, j.n, 0, nullptr, nullptr,
nullptr, 0);
for (size_t b = 0; b < g.reads.size(); b += kReaderBatch) {
for (int u; (u = g_urgent_reads.load(std::memory_order_acquire)) > 0;)
g_urgent_reads.wait(u, std::memory_order_acquire);
const size_t cnt = std::min(kReaderBatch, g.reads.size() - b);
if (read_and_publish(*j.tf, *j.rc, *rr, g, &g.reads[b], cnt, j.n, 0, nullptr,
nullptr, nullptr, 0) == RAD_OK)
continue;
/* The failed batch released its own claims; the later batches' go too. */
for (size_t i = b + cnt; i < g.reads.size(); ++i)
j.rc->word[g.reads[i].slot].store(RowCache::EMPTY, std::memory_order_release);
j.rc->published.fetch_add(1, std::memory_order_release);
j.rc->published.notify_all();
break;
}
if (!retry.empty()) {
std::lock_guard<std::mutex> lk(mu);
AheadJob r;
r.tf = j.tf; r.rc = j.rc; r.n = j.n; r.keys = std::move(retry); r.retry = true;
r.stream = j.stream;
urgent.push_front(std::move(r));
cv.notify_one();
}
@@ -850,49 +934,68 @@ struct AheadReader {
}
};
/* The reader, started by the first call that hands it rows; null before. */
std::atomic<AheadReader*> g_reader{nullptr};
AheadReader* ahead_reader() {
static AheadReader* const r = [] {
AheadReader* a = new AheadReader();
std::thread([a] { a->run(); }).detach();
g_reader.store(a, std::memory_order_release);
return a;
}();
return r;
}
/* Hands the rows of `q.ahead` (gathered by later calls) to the reader as kJobRows-key jobs in list
* order, so the nearest chunk's rows come first. */
/* Hands the ids of `q.ahead` (gathered by later calls) that the previous list did not hold to the
* reader, as kJobRows-key jobs in list order, so the nearest chunk's rows come first. */
void read_ahead(const TableFile& tf, RowCache& rc, const avx::RowGather& q) {
uint64_t h = 1469598103934665603ull ^ (uint64_t)(uintptr_t)&rc;
for (long long m = 0; m < q.n_ahead; ++m) { h ^= (uint32_t)q.ahead[m]; h *= 1099511628211ull; }
AheadReader* r = ahead_reader();
{
std::lock_guard<std::mutex> lk(r->mu);
if (h == r->last) return;
r->last = h;
}
const long long base = tf.off + (long long)(q.tab - tf.lo);
const long long na = q.n_ahead < kAheadRows ? q.n_ahead : kAheadRows;
const int32_t* w = q.ahead;
/* Keys before the lock; a padding id has none. */
constexpr uint64_t kPad = ~0ull;
std::vector<uint64_t> keys((size_t)na);
for (long long m = 0; m < na; ++m) {
const long long id = (long long)w[m] - q.voff;
keys[(size_t)m] = id < 0 || id >= q.n_vocab ? kPad : (uint64_t)(base + id * q.row_bytes);
}
AheadReader* r = ahead_reader();
std::lock_guard<std::mutex> lk(r->mu);
AheadStream* st = r->stream(&rc, base);
const std::vector<int32_t>& p = st->ids;
const long long np = (long long)p.size();
if (np == na && std::equal(w, w + na, p.data())) return; /* the other rank's, or a repeat */
/* The list continues the previous one moved on by `s` ids if w[0, np - s) == p[s, np); the
* smallest such s leaves the fewest ids to hand over. An id repeats only where the text does,
* so few shifts pass the first comparison; kShiftTries bounds a text that repeats a lot. */
long long from = -1;
for (long long s = 1, tries = 0; s < np && tries < kShiftTries; ++s) {
if (p[(size_t)s] != w[0]) continue;
++tries;
const long long k = std::min(np - s, na);
if (std::equal(w, w + k, p.data() + s)) { from = k; break; }
}
if (from < 0) {
r->drop(st);
from = 0;
}
st->ids.assign(w, w + na);
AheadJob j;
j.tf = &tf;
j.rc = &rc;
j.n = q.row_bytes;
j.stream = st;
j.keys.reserve(kJobRows);
for (long long m = 0; m < q.n_ahead; ++m) {
const long long id = (long long)q.ahead[m] - q.voff;
if (id < 0 || id >= q.n_vocab) continue;
j.keys.push_back((uint64_t)(base + id * q.row_bytes));
for (long long m = from; m < na; ++m) {
if (keys[(size_t)m] == kPad) continue;
j.keys.push_back(keys[(size_t)m]);
if (j.keys.size() == kJobRows) {
{
std::lock_guard<std::mutex> lk(r->mu);
r->q.push_back(j);
}
r->cv.notify_one();
r->q.push_back(j);
j.keys.clear();
}
}
if (!j.keys.empty()) {
std::lock_guard<std::mutex> lk(r->mu);
r->q.push_back(std::move(j));
}
if (!j.keys.empty()) r->q.push_back(std::move(j));
r->cv.notify_one();
}
@@ -903,6 +1006,20 @@ inline const TableFile* table_file(const uint8_t*, long long, int*) { static Tab
} // namespace
/* Rows read from table files by this process, once the reader thread has nothing queued or
* running: rad-avx-check counts what a prefill reads with it (avx_check_rows.cpp). */
extern "C" uint64_t avx_ngram_reads(void) {
#if defined(__linux__)
if (AheadReader* r = g_reader.load(std::memory_order_acquire)) {
std::unique_lock<std::mutex> lk(r->mu);
r->idle.wait(lk, [&] { return !r->running && r->q.empty() && r->urgent.empty(); });
}
return g_rows_read.load(std::memory_order_relaxed);
#else
return 0;
#endif
}
int avx::row_gather(const RowGather& q, RowDecode decode) {
if (!decode || !q.ids || !q.tab || !q.out || q.M <= 0 || q.n_embd <= 0 || q.n_vocab <= 0 ||
q.row_bytes < q.n_embd)
+4 -2
View File
@@ -740,7 +740,9 @@ 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. */
* the two sums are the same bits. Rows of the triangle shrink, hence the dynamic schedule.
* `upper` 1 leaves (k2, k1) as it was. */
const bool upper = p_int(a, "upper", 0) != 0;
const int64_t hst = laststride(h);
#ifdef _OPENMP
AVX_PRAGMA(omp parallel for schedule(dynamic, 8) if(n * n >= 1024 || avx_par_forced())
@@ -753,7 +755,7 @@ AVX_KERNEL(gram_accum) {
acc += (double)xs[r * n + k1] * (double)xs[r * n + k2];
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));
if (k2 != k1 && !upper) stt(h, o21, (float)((double)ldt(h, o21) + acc));
}
}
return RAD_OK;
+36 -3
View File
@@ -22,6 +22,7 @@
#include "rad_abi.h"
#include "rad_planes.h"
#include "rad_plugin.h"
#include "rad_abi_layout.h"
#include <cstring>
@@ -161,6 +162,8 @@ static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") };
static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadParamSpec pSegMean[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oSegMean[] = { OPD("x"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pSegPool[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadOperandSpec oSegPool[] = { OPD("score"), OPD("v"), OPD("cu_seqlens"), OUT("y") };
static const RadParamSpec pPoolRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_F64O("mult"),
P_STR("dtype") };
static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") };
@@ -207,6 +210,9 @@ static const RadParamSpec pCast[] = { P_INT("M"), P_INT("n"), P_STR("from"), P_S
/* ---- quantisation and rotation ------------------------------------------------------------ */
static const RadParamSpec pQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"),
P_STR("dtype") };
/* gram_accum's: `upper` 1 accumulates only k2 >= k1, the half a reader of a symmetric H needs. */
static const RadParamSpec pGram[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"),
P_INTO("upper") };
static const RadOperandSpec oQuant[] = { OPD("x"), OUT("q"), OUT("scale"), OUT_O("asum") };
static const RadOperandSpec oHadQuant[] = { OPD("x"), OUT("q"), OUT("scale") };
static const RadOperandSpec oQuantFp8[] = { OPD("x"), OUT("q"), OUT("scale") };
@@ -258,10 +264,10 @@ static const RadParamSpec pGemmBias[] = { P_INT("M"), P_INT("N"), P_INT("K"),
static const RadOperandSpec oGemmBias[] = { OPD("a"), WGT("b"), WGT("bias"), OPD_O("res"),
OUT("y") };
/* `split_n` is libr4d's (docs/OPS.md); accepted and ignored here. */
/* `split_n` and `w_rb` are libr4d's (docs/OPS.md); accepted and ignored here. */
static const RadParamSpec pGemmQ[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype"), P_INTO("pb1"), P_INTO("pb2"),
P_INTO("split_n") };
P_INTO("split_n"), P_INTO("w_rb") };
static const RadParamSpec pGemmQBias[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_INT("group"),
P_STR("dtype") };
static const RadOperandSpec oGemmQ[] = { OPD("a"), OPD_O("a_scale"), WGT("b"), WGT("b_scale"),
@@ -965,6 +971,9 @@ static const RadOpSchema kSchemas[] = {
"BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output." },
{ "seg_mean", ARR(pSegMean), ARR(oSegMean),
"y[s] = the mean of x's rows in cu_seqlens segment s, summed in double, rounded once." },
{ "seg_softmax_pool", ARR(pSegPool), ARR(oSegPool),
"y[s] = v's rows in cu_seqlens segment s summed with the softmax of their scores as weights, "
"in f32, rounded once." },
{ "relu", ARR(pMnD), ARR(oUnary), "y = max(x, 0)." },
{ "clamp", ARR(pMnD), ARR(oClamp), "y = min(max(x, lo), hi), lo and hi one-element weights." },
{ "conv2d", ARR(pConv2d), ARR(oConv2d),
@@ -1035,7 +1044,7 @@ static const RadOpSchema kSchemas[] = {
{ "had_quant_act_i8g", ARR(pQuant), ARR(oQuantFp8),
"width-`group` Hadamard, then quant_act_i8g's symmetric int8 per group. No normalisation: the "
"1/group is the i8a8h weight's stored scale (docs/OPS.md)." },
{ "gram_accum", ARR(pQuant), ARR(oGram),
{ "gram_accum", ARR(pGram), ARR(oGram),
"h += x^T x over a dequantised E4M3 activation. `h` is [n, n] and INOUT." },
{ "givens_dense_quant", ARR(pGivensDense), ARR(oGivensDense),
"ParoQuant's activation quantiser with the rotation as a dense per-group matrix: y = T (x / "
@@ -1436,6 +1445,16 @@ static const RadOpSchema kSchemas[] = {
"children are the valid candidates at the next position with log probability parent + "
"log_softmax(score / temp); each round takes the largest untaken child, ties to the first "
"pushed. tokens and parents list the taken nodes in order, a parent as its node index." },
/* Row forms libr4d declares under names of their own, so a model can ask for the form: the same op, the same
* arithmetic and the same schema as the op named in each string. */
{ "rmsnorm_rows", ARR(pRmsnorm), ARR(oRmsnorm),
"rmsnorm, for rows a model declares in thousands (the head norms over head_dim)." },
{ "rope_rows", ARR(pRope), ARR(oRope),
"rope, for a model that wants the per-(token, pair) angles form at prefill row counts." },
{ "gemm_nt_q_short", ARR(pGemmQ), ARR(oGemmQ),
"gemm_nt_q, for the short-prompt split rule's rows." },
{ "gemm_nt_q_gated_wide", ARR(pGemmQGated), ARR(oGemmQGated),
"gemm_nt_q_gated at any M." },
};
/* ================================================================== the kernel table
@@ -1586,6 +1605,9 @@ SIMPLE("avx_seg_mean_bf16_sum", "seg_mean_bf16_sum", "elem", "BF16 sum/division
"bf16 in and out; f32 sum, BF16 sum and quotient", L(seg_mean_bf16_sum)),
SIMPLE("avx_seg_mean", "seg_mean", "elem", "mean of each cu_seqlens segment's rows", DT_FLOAT,
L(seg_mean)),
SIMPLE("avx_seg_softmax_pool", "seg_softmax_pool", "elem",
"each cu_seqlens segment's rows summed with the softmax of their scores", DT_FLOAT,
L(seg_softmax_pool)),
SIMPLE("avx_pool_rows", "pool_rows", "elem", "mean of every k consecutive rows, then a multiplier",
DT_FLOAT, L(pool_rows)),
SIMPLE("avx_pool_cols", "pool_cols", "elem", "mean of every k consecutive columns, then a "
@@ -2034,6 +2056,16 @@ SIMPLE("avx_dflash_select", "dflash_select", "draft",
SIMPLE("avx_dflash_tree", "dflash_tree", "draft",
"DFlash2's candidate lattice grown best-first into a tree",
"i32 candidates, tokens and parents, float unary and codebooks", L(dflash_tree)),
/* The row-form names (see the schema table): each the base op's row. */
SIMPLE("avx_rmsnorm_rows", "rmsnorm_rows", "norm", "rmsnorm under its row-form name", DT_FLOAT,
L(rmsnorm)),
SIMPLE("avx_rope_rows", "rope_rows", "attn", "rope under its row-form name", DT_FLOAT, L(rope)),
ROWL("avx_gemm_nt_q_short", "gemm_nt_q_short", "gemm", "gemm_nt_q under its row-form name",
"as avx_gemm_nt_q", L(gemm_nt_q), avx_layout_gemm_q),
SIMPLE("avx_gemm_nt_q_gated_wide", "gemm_nt_q_gated_wide", "gemm",
"gemm_nt_q_gated under its row-form name",
"i8 / fp8 / float A; w4, w2, mxfp4, i8 or float B; fp8_e4m3 out, f32 scale",
L(gemm_nt_q_gated)),
};
/* ================================================================== plugin exports */
@@ -2049,6 +2081,7 @@ static const RadPluginInfo kInfo = {
};
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
extern "C" int rad_kernel_schema_count(void) {