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

+110 -31
View File
@@ -2,6 +2,9 @@
#include "rad_plugin.h"
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <sys/mman.h>
#include <unistd.h>
/* ---- the context switch: callee-saved registers and the stack pointer (x86-64 SysV) */
extern "C" void emu_switch(void** save_sp, void* new_sp);
@@ -31,7 +34,9 @@ namespace {
constexpr size_t kStack = 512 * 1024;
struct Fiber {
void* sp = nullptr;
std::vector<char> stack;
/* left uninitialised so the OS commits only the pages a fiber touches: a 1024-thread block
* would otherwise zero half a GiB */
std::unique_ptr<char[]> stack;
EmuIdx tid{};
bool done = false;
unsigned bar_gen = 0; /* block barrier generation this fiber waits on */
@@ -50,6 +55,7 @@ struct Sched {
/* wave barriers and exchange slots, double-buffered by parity */
int warrive[64] = {}; unsigned wgen[64] = {};
int slot[64][2][32] = {};
int tag[64][2][32] = {}; /* which op, and its uniform operand, each lane posted */
unsigned xparity[1024] = {};
} S;
@@ -95,74 +101,148 @@ static void wave_barrier(int w) {
me.waiting = 0;
}
int emu_bpermute(int addr, int v) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
/* Every lane posts `v` to the wave's exchange slots and passes the wave barrier; the slots of this
* exchange are returned for the caller to read. `tag` names the op and its wave-uniform operand:
* lanes that met at different ops (a cross-lane op called under divergence, each side reaching
* one) are reported, not combined. */
enum { kOpBpermute = 1 << 24, kOpReadlane = 2 << 24, kOpBallot = 3 << 24, kOpDpp = 4 << 24,
kOpPermlanex16 = 5 << 24 };
static const int* exchange(int v, int* lane, int tag) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5;
const unsigned par = S.xparity[t]++ & 1u;
S.slot[w][par][l] = v;
*lane = t & 31;
S.slot[w][par][*lane] = v;
S.tag[w][par][*lane] = tag;
wave_barrier(w);
return S.slot[w][par][(addr >> 2) & 31];
for (int i = 0; i < 32; ++i)
if (S.tag[w][par][i] != tag) {
std::fprintf(stderr, "emu: DIVERGENCE in block (%u,%u,%u), wave %d: lanes %d and %d met at different "
"cross-lane ops (0x%x, 0x%x)\n", S.bid.x, S.bid.y, S.bid.z, w, *lane, i, tag,
S.tag[w][par][i]);
std::abort();
}
return S.slot[w][par];
}
int emu_bpermute(int addr, int v) {
int l;
return exchange(v, &l, kOpBpermute)[(addr >> 2) & 31];
}
/* v_readlane_b32 takes a wave-uniform lane, so a lane-varying one is reported */
int emu_readlane(int v, int lane) {
int l;
return exchange(v, &l, kOpReadlane | (lane & 31))[lane & 31];
}
int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); }
int emu_cvt_pk_fp8(float a, float b, int old, bool hi) {
const unsigned pk = (unsigned)rad_f32_to_fp8e4m3(a) | ((unsigned)rad_f32_to_fp8e4m3(b) << 8);
const unsigned o = (unsigned)old;
return (int)(hi ? ((o & 0xffffu) | (pk << 16)) : ((o & 0xffff0000u) | pk));
}
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
/* One 16x16x16 WMMA: each lane posts its A and B elements, then reads the whole tile back. `ga`
* and `gb` are the exchange slots of one element type, [wave][parity][lane][element]. */
template <class T, class V, class Cvt>
static emu_v8f emu_wmma(T (&ga)[64][2][32][8], T (&gb)[64][2][32][8], V a, V b, emu_v8f c,
Cvt cvt) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
const unsigned par = S.xparity[t]++ & 1u;
for (int e = 0; e < 8; ++e) { g_wa[w][par][l][e] = a[e]; g_wb[w][par][l][e] = b[e]; }
for (int e = 0; e < 8; ++e) { ga[w][par][l][e] = a[e]; gb[w][par][l][e] = b[e]; }
wave_barrier(w);
auto bf = [](short v) { unsigned u = (unsigned)(unsigned short)v << 16; float f; std::memcpy(&f, &u, 4); return f; };
const int N = l & 15, h = l >> 4;
emu_v8f d;
for (int e = 0; e < 8; ++e) {
const int M = 8 * h + e;
float acc = c[e];
for (int k = 0; k < 16; ++k)
acc += bf(g_wa[w][par][M + 16 * (k >> 3)][k & 7]) * bf(g_wb[w][par][N + 16 * (k >> 3)][k & 7]);
acc += cvt(ga[w][par][M + 16 * (k >> 3)][k & 7]) * cvt(gb[w][par][N + 16 * (k >> 3)][k & 7]);
d[e] = acc;
}
return d;
}
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
return emu_wmma(g_wa, g_wb, a, b, c, [](short v) { return rad_bf16_to_f32((uint16_t)v); });
}
static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
const unsigned par = S.xparity[t]++ & 1u;
for (int e = 0; e < 8; ++e) { g_ha[w][par][l][e] = a[e]; g_hb[w][par][l][e] = b[e]; }
wave_barrier(w);
const int N = l & 15, h = l >> 4;
emu_v8f d;
for (int e = 0; e < 8; ++e) {
const int M = 8 * h + e;
float acc = c[e];
for (int k = 0; k < 16; ++k)
acc += (float)g_ha[w][par][M + 16 * (k >> 3)][k & 7] * (float)g_hb[w][par][N + 16 * (k >> 3)][k & 7];
d[e] = acc;
}
return d;
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; });
}
unsigned emu_ballot(bool p) {
int l;
const int* s = exchange(p ? 1 : 0, &l, kOpBallot);
unsigned m = 0;
for (int l = 0; l < 32; ++l) m |= (unsigned)(emu_readlane(p ? 1 : 0, l) & 1) << l;
for (int i = 0; i < 32; ++i) m |= (unsigned)(s[i] & 1) << i;
return m;
}
int emu_update_dpp(int old, int src, int ctrl, int row_mask, int bank_mask, bool bound_ctrl) {
int l;
const int* s = exchange(src, &l, kOpDpp | (ctrl & 0xffff));
const int r = l & 15, k = ctrl & 15;
int from;
if (ctrl > 0x100 && ctrl < 0x110) from = r + k < 16 ? l + k : -1; /* row_shl */
else if (ctrl > 0x110 && ctrl < 0x120) from = r - k >= 0 ? l - k : -1; /* row_shr */
else if (ctrl >= 0x160 && ctrl < 0x170) from = (l & 16) | (r ^ k); /* row_xmask */
else { std::fprintf(stderr, "emu: dpp_ctrl 0x%x is not emulated\n", ctrl); std::abort(); }
if ((row_mask & 3) != 3 || (bank_mask & 15) != 15) {
std::fprintf(stderr, "emu: dpp row/bank masks 0x%x/0x%x are not emulated\n", row_mask, bank_mask);
std::abort();
}
return from < 0 ? (bound_ctrl ? 0 : old) : s[from];
}
int emu_permlanex16(int, int src, unsigned sel_lo, unsigned sel_hi, bool, bool) {
int l;
const int* s = exchange(src, &l, kOpPermlanex16);
const int r = l & 15;
const unsigned sel = (r < 8 ? sel_lo >> (4 * r) : sel_hi >> (4 * (r - 8))) & 15u;
return s[(16 - (l & 16)) | (int)sel];
}
emu_v8s emu_load_tr_b128(const void*) {
std::fprintf(stderr, "emu: global_load_tr_b128 is not emulated\n");
std::abort();
}
/* Dynamic LDS: a mapping whose last page is inaccessible, the buffer placed against it with its
* start 16-byte aligned, refilled with a poison pattern for every block. */
static char* g_lds_map = nullptr;
static size_t g_lds_map_len = 0;
static char* g_lds = nullptr;
void* emu_dyn_lds() { return g_lds; }
static void lds_reserve(size_t bytes) {
const size_t page = (size_t)sysconf(_SC_PAGESIZE);
const size_t len = (bytes + 15 + page - 1) / page * page + page;
if (len > g_lds_map_len) {
if (g_lds_map) munmap(g_lds_map, g_lds_map_len);
void* m = mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (m == MAP_FAILED || mprotect((char*)m + len - page, page, PROT_NONE) != 0) {
std::fprintf(stderr, "emu: no dynamic LDS mapping\n");
std::abort();
}
g_lds_map = (char*)m;
g_lds_map_len = len;
}
const uintptr_t end = (uintptr_t)(g_lds_map + g_lds_map_len - page);
g_lds = (char*)((end - bytes) & ~(uintptr_t)15);
}
int emu_grids = 0;
int emu_last_block = 0;
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) {
const char* emu_last_kernel = "";
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds) {
++emu_grids;
const int n = (int)(block.x * block.y * block.z);
emu_last_block = n;
if (block.y != 1 || block.z != 1 || n % 32 || n > 1024) { std::fprintf(stderr, "emu: block shape\n"); std::abort(); }
if (dyn_lds > 64 * 1024) {
std::fprintf(stderr, "emu: %zu bytes of dynamic LDS, past the 64 KiB a workgroup has\n", dyn_lds);
std::abort();
}
lds_reserve(dyn_lds);
S.body = body; S.ctx = ctx; S.nthreads = n;
S.f.resize(n);
for (auto& f : S.f) if (f.stack.size() != kStack) f.stack.assign(kStack, 0);
for (auto& f : S.f) if (!f.stack) f.stack.reset(new char[kStack]);
for (unsigned bz = 0; bz < grid.z; ++bz)
for (unsigned by = 0; by < grid.y; ++by)
for (unsigned bx = 0; bx < grid.x; ++bx) {
S.bid = EmuIdx{bx, by, bz};
std::memset(g_lds, 0xA5, dyn_lds);
S.arrive = 0; S.gen = 0;
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; }
for (int t = 0; t < n; ++t) {
@@ -170,14 +250,13 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) {
f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0};
S.xparity[t] = 0;
/* a fresh stack: six callee-saved slots, then the entry as the return address */
void** top = (void**)(f.stack.data() + kStack - 64);
void** top = (void**)(f.stack.get() + kStack - 64);
*--top = (void*)&emu_entry;
for (int r = 0; r < 6; ++r) *--top = nullptr;
f.sp = top;
}
int live = n;
while (live > 0) {
int progressed = 0;
const int live_before = live;
const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w];
int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w];
@@ -189,7 +268,7 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) {
S.cur = -1;
if (!S.f[t].done) ++live;
}
progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
bool progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]);
if (live > 0 && !progressed) {
int done = 0, wb = 0, bb = 0;
+81 -8
View File
@@ -1,11 +1,13 @@
/* tests/r4d_emu: SIMT EMULATOR SHIM -- runs libr4d kernel source on the host. Every GPU thread is a fiber on
* one OS thread; __syncthreads and every cross-lane op are barriers the scheduler enforces, and a
* barrier some threads never reach is reported as a deadlock rather than hung. Test-only. */
/* tests/r4d_emu: SIMT emulator shim that runs libr4d kernel source on the host. Each GPU thread
* is a fiber on one OS thread; __syncthreads and cross-lane ops are barriers the scheduler
* enforces, a barrier some threads never reach is reported as a deadlock, and lanes of a wave
* that meet at different cross-lane ops as a divergence. Test-only. */
#pragma once
#include <cmath>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <tuple>
#include <vector>
#define __global__
@@ -23,6 +25,14 @@ typedef void* hipStream_t;
typedef int hipError_t;
enum { hipSuccess = 0 };
inline hipError_t hipGetLastError() { return 0; }
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
struct hipDeviceProp_t { size_t sharedMemPerBlock; };
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
*p = hipDeviceProp_t{};
p->sharedMemPerBlock = 64 * 1024;
return hipSuccess;
}
struct EmuIdx { unsigned x, y, z; };
EmuIdx& emu_thread_idx();
@@ -36,6 +46,40 @@ int emu_readlane(int v, int lane);
#define __builtin_amdgcn_readlane(v, l) emu_readlane((v), (l))
unsigned emu_ballot(bool p);
#define __builtin_amdgcn_ballot_w32(p) emu_ballot((p))
/* HIP's __ballot: the wave32 mask, zero-extended */
inline unsigned long long __ballot(int p) { return emu_ballot(p != 0); }
inline int __popcll(unsigned long long v) { return __builtin_popcountll(v); }
/* v_readfirstlane_b32: a cross-lane op is a wave barrier here, so every lane is active, lane 0 first */
#define __builtin_amdgcn_readfirstlane(v) emu_readlane((v), 0)
/* DPP16 row_shl, row_shr and row_xmask with every row and bank written; a source outside the row
* reads 0 under bound_ctrl, else leaves `old`. Other controls and masks are reported. */
int emu_update_dpp(int old, int src, int ctrl, int row_mask, int bank_mask, bool bound_ctrl);
#define __builtin_amdgcn_update_dpp(o, s, c, rm, bm, bc) emu_update_dpp((o), (s), (c), (rm), (bm), (bc))
/* v_permlanex16_b32: lane L reads the lane of the other row of sixteen that L's selector names */
int emu_permlanex16(int old, int src, unsigned sel_lo, unsigned sel_hi, bool fi, bool bc);
#define __builtin_amdgcn_permlanex16(o, s, lo, hi, fi, bc) emu_permlanex16((o), (s), (lo), (hi), (fi), (bc))
/* v_perm_b32: result byte i is the byte of {a, b} (b low) that selector byte i names; 8-11 a sign
* byte (bit 15 or 31 of b, then of a), 12 zero, 13 and up 0xff */
inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
const unsigned long long d = ((unsigned long long)a << 32) | b;
unsigned r = 0;
for (int i = 0; i < 4; ++i) {
const unsigned s = (sel >> (8 * i)) & 0xffu;
unsigned v = s >= 13 ? 0xffu : s == 12 ? 0u : s >= 8 ? ((d >> (16 * (s - 8) + 15)) & 1u) * 0xffu
: (unsigned)(d >> (8 * s)) & 0xffu;
r |= v << (8 * i);
}
return r;
}
#define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s))
/* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a
* fence or a scheduling barrier orders nothing more. */
#define __builtin_amdgcn_s_barrier() __syncthreads()
#define __builtin_amdgcn_fence(...) ((void)0)
#define __builtin_amdgcn_sched_barrier(m) ((void)0)
/* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */
template <class T>
inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; }
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
typedef short emu_v8s __attribute__((ext_vector_type(8)));
@@ -45,15 +89,19 @@ emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): a and b as two codes into the low half of `old` (hi false)
* or its high half, the other half kept; round to nearest even. The project's saturating encoder,
* rad_f32_to_fp8e4m3, is the same function on the +-448 a kernel clamps to first. */
/* global_load_tr_b128: not emulated; reported when reached */
emu_v8s emu_load_tr_b128(const void* p);
#define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p))
/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): converts a and b into the low half of `old` (hi false) or
* its high half, keeping the other half; round to nearest even. Matches the saturating encoder
* rad_f32_to_fp8e4m3 on inputs a kernel has already clamped to +-448. */
int emu_cvt_pk_fp8(float a, float b, int old, bool hi);
#define __builtin_amdgcn_cvt_pk_fp8_f32(a, b, old, hi) emu_cvt_pk_fp8((a), (b), (old), (hi))
extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */
struct alignas(8) uint2 { unsigned x, y; };
struct alignas(16) uint4 { unsigned x, y, z, w; };
struct alignas(16) int4 { int x, y, z, w; };
struct alignas(16) float4 { float x, y, z, w; };
inline uint4 make_uint4(unsigned a, unsigned b, unsigned c, unsigned d) { return uint4{a, b, c, d}; }
inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; }
@@ -64,8 +112,8 @@ inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); r
inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; }
inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; }
/* one block at a time, every thread a fiber */
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx);
/* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0);
template <typename K, typename A>
struct EmuCall { K k; A a; static void run(void* p) { auto* c = (EmuCall*)p; c->k(c->a); } };
template <typename A>
@@ -74,3 +122,28 @@ void emu_launch(void (*k)(A), dim3 g, dim3 b, A a) {
emu_run_grid(g, b, &EmuCall<void (*)(A), A>::run, &c);
}
#define R4D_KLAUNCH(kernel, grid, block, stream, ...) emu_launch(&kernel, grid, block, __VA_ARGS__)
/* R4D_EMIT (r4d_emit.h): every argument converted to its parameter's type, as r4d_emit does, and
* `lds` bytes of dynamic LDS; the kernel's name is kept in emu_last_kernel. Returns RAD_OK. */
extern const char* emu_last_kernel;
template <class... P, class... A>
int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, const A&... a) {
static_assert(sizeof...(P) == sizeof...(A),
"a kernel argument list must match the kernel's parameter list");
struct Call {
void (*k)(P...);
std::tuple<P...> v;
static void run(void* p) { Call* c = (Call*)p; std::apply(c->k, c->v); }
};
Call c{k, std::tuple<P...>(static_cast<P>(a)...)};
emu_last_kernel = name;
emu_run_grid(g, b, &Call::run, &c, lds);
return 0;
}
#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \
emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)
/* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending
* at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one
* past the end faults */
void* emu_dyn_lds();
#define R4D_DYN_LDS(type, name) type* const name = (type*)emu_dyn_lds()
+27 -38
View File
@@ -26,8 +26,8 @@ int host_pair_argmax(const RadArgs* a) {
}
const int64_t rows = p->shape[0];
if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE;
const int64_t prs = p->stride[0], trs = t->rank >= 2 ? t->stride[0] : 1;
const int64_t vrs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0;
/* A row's element is stride[0] apart at any rank, as in the kernel. */
const int64_t prs = p->stride[0], trs = t->stride[0], vrs = v ? v->stride[0] : 0;
for (int64_t r = 0; r < rows; ++r) {
const float* row = (const float*)p->data + r * prs;
int32_t bid = -1;
@@ -45,31 +45,14 @@ int host_pair_argmax(const RadArgs* a) {
return RAD_OK;
}
/* The joins: each value the unfused chain stores is rounded to bf16 where it stores it. Summed in
* index order, so a ULP from the device's block order. */
static float hb2f(uint16_t h) { const uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
static uint16_t hf2b(float f) {
uint32_t u; std::memcpy(&u, &f, 4);
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
}
static float hrbf(float f) { return hb2f(hf2b(f)); }
/* The joins round each value to bf16 where the unfused chain stores it. Sums run in index order,
* so a result may differ from the device's block order by a ULP. */
static float hnorm(const float* v, int64_t n, double eps) {
float ss = 0.0f;
for (int64_t i = 0; i < n; ++i) ss += v[i] * v[i];
return 1.0f / std::sqrt(ss / (float)n + (float)eps);
}
static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) {
if (!t || t->dtype != RAD_BF16 || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
if (t->stride[t->rank - 1] != 1) return false;
*rows = rad_tensor_rows(t);
*ld = rad_tensor_row_pitch(t);
return true;
}
static bool hgain(const RadTensor* w, int64_t n) {
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
}
/* [rows..., n] of `dt`, dense last axis, for the route form's fp8 codes and f32 scales */
/* [rows..., n] of `dt` (bf16 unless named), dense last axis */
static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) {
if (!t || t->dtype != dt || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
if (t->stride[t->rank - 1] != 1) return false;
@@ -77,6 +60,12 @@ static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows,
*ld = rad_tensor_row_pitch(t);
return true;
}
static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) {
return hrows_as(t, RAD_BF16, n, rows, ld);
}
static bool hgain(const RadTensor* w, int64_t n) {
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
}
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */
static int nan_host(const RadArgs* a, bool route) {
@@ -105,15 +94,15 @@ static int nan_host(const RadArgs* a, bool route) {
const uint16_t* ar = (const uint16_t*)A_->data + m * la;
uint16_t* xr = (uint16_t*)X->data + m * lx;
uint16_t* yr = (uint16_t*)Y->data + m * ly;
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = hb2f(ar[i]);
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = b2f(ar[i]);
const float sa = hnorm(v.data(), n, eps);
for (int64_t i = 0; i < n; ++i) {
const float t = hrbf((v[(size_t)i] * sa) * wa[i]);
xv[(size_t)i] = hrbf(hb2f(xr[i]) + t);
xr[i] = hf2b(xv[(size_t)i]);
const float t = rb((v[(size_t)i] * sa) * wa[i]);
xv[(size_t)i] = rb(b2f(xr[i]) + t);
xr[i] = f2b(xv[(size_t)i]);
}
const float sx = hnorm(xv.data(), n, eps);
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]);
for (int64_t i = 0; i < n; ++i) yr[i] = f2b((xv[(size_t)i] * sx) * wy[i]);
if (!route) continue;
/* the router's row, and the experts' as rmsnorm_quant_fp8 writes it (v holds it) */
const float *wr = (const float*)Wr->data, *we = (const float*)We->data;
@@ -121,8 +110,8 @@ static int nan_host(const RadArgs* a, bool route) {
uint8_t* qrow = (uint8_t*)Q->data + m * lq;
float* srow = (float*)S->data + m * ls;
for (int64_t i = 0; i < n; ++i) {
rrow[i] = hf2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
v[(size_t)i] = hrbf((xv[(size_t)i] * sx) * we[i]);
rrow[i] = f2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
v[(size_t)i] = rb((xv[(size_t)i] * sx) * we[i]);
}
for (int64_t g = 0; g < n / 128; ++g) {
float am = 0.0f;
@@ -161,27 +150,27 @@ int host_join_add_scale(const RadArgs* a) {
if (Y && !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
if (rd < rx || rr < rx || (Y && ry < rx)) return RAD_E_SHAPE;
const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data;
const float sc = hb2f(*(const uint16_t*)Sc->data);
const float sc = b2f(*(const uint16_t*)Sc->data);
std::vector<float> dv((size_t)n), rv((size_t)n);
for (int64_t m = 0; m < rx; ++m) {
const uint16_t* dr = (const uint16_t*)D->data + m * ld;
const uint16_t* rrw = (const uint16_t*)R->data + m * lr;
uint16_t* xr = (uint16_t*)X->data + m * lx;
for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = hb2f(dr[i]); rv[(size_t)i] = hb2f(rrw[i]); }
for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = b2f(dr[i]); rv[(size_t)i] = b2f(rrw[i]); }
const float sd = hnorm(dv.data(), n, eps), sr = hnorm(rv.data(), n, eps);
for (int64_t i = 0; i < n; ++i)
dv[(size_t)i] = hrbf(hrbf((dv[(size_t)i] * sd) * wd[i]) + hrbf((rv[(size_t)i] * sr) * wr[i]));
dv[(size_t)i] = rb(rb((dv[(size_t)i] * sd) * wd[i]) + rb((rv[(size_t)i] * sr) * wr[i]));
const float sj = hnorm(dv.data(), n, eps);
for (int64_t i = 0; i < n; ++i) {
const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i]));
xr[i] = hf2b(x1 * sc);
rv[(size_t)i] = hb2f(xr[i]);
const float x1 = rb(b2f(xr[i]) + rb((dv[(size_t)i] * sj) * wj[i]));
xr[i] = f2b(x1 * sc);
rv[(size_t)i] = b2f(xr[i]);
}
if (Y) {
const float* wn = (const float*)Wn->data;
uint16_t* yr = (uint16_t*)Y->data + m * ly;
const float sn = hnorm(rv.data(), n, eps);
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((rv[(size_t)i] * sn) * wn[i]);
for (int64_t i = 0; i < n; ++i) yr[i] = f2b((rv[(size_t)i] * sn) * wn[i]);
}
}
return RAD_OK;
@@ -205,9 +194,9 @@ int host_expert_scale(const RadArgs* a) {
for (int64_t r = 0; r < rows; ++r)
for (int64_t c = 0; c < k; ++c) {
const int32_t id = ((const int32_t*)I->data)[r * li + c];
const float s = (id >= 0 && id < ne) ? hb2f(sc[id]) : 0.0f;
const float s = (id >= 0 && id < ne) ? b2f(sc[id]) : 0.0f;
uint16_t* w = (uint16_t*)W->data + r * lw + c;
*w = hf2b(hb2f(*w) * s);
*w = f2b(b2f(*w) * s);
}
return RAD_OK;
}
+11 -4
View File
@@ -1,11 +1,18 @@
/* ref_host.h -- what the four libr4d units r4d_emu runs compute, in plain C++ on the host.
/* ref_host.h -- host C++ versions of the libr4d units r4d_emu runs.
*
* The device kernels' arithmetic restated, each a RadArgs in and RAD_OK or an error out: the
* reference the emulated kernels are held to beside the unfused chain each test builds itself
* (the joins, expert_scale) or a brute force (pair_argmax). No HIP, no libr4d header. */
* Each restates a device kernel's arithmetic, RadArgs in and RAD_OK or an error out. Tests hold
* the emulated kernels to these, beside the unfused chain each test builds (the joins,
* expert_scale) or a brute force (pair_argmax). No HIP, no libr4d header. */
#pragma once
#include "rad_abi.h"
#include "rad_plugin.h"
/* bf16 as libr4d converts it: exact widening, round-to-nearest-even narrowing. rb() is a value
* stored to bf16 and read back. */
inline float b2f(uint16_t h) { return rad_bf16_to_f32(h); }
inline uint16_t f2b(float f) { return rad_f32_to_bf16(f); }
inline float rb(float f) { return b2f(f2b(f)); }
int host_pair_argmax(const RadArgs* a);
int host_norm_add_norm(const RadArgs* a);
-30
View File
@@ -1,30 +0,0 @@
#!/bin/sh
# tests/r4d_emu/run.sh -- build and run r4d_emu with a clang that is not the build's C++ compiler.
#
# A build whose C++ compiler is clang builds these as ordinary targets (tests/CMakeLists.txt). The
# docker image compiles host C++ with g++, which has no ext_vector_type; its HIP compiler is ROCm's
# own clang++, and with `-x c++` that compiles the kernel sources as the host code this test needs.
#
# run.sh <clang++> <abi dir> <libr4d dir> <work dir> [sweep cases]
set -e
CXX=${1:?usage: run.sh <clang++> <abi dir> <libr4d dir> <work dir> [sweep cases]}
ABI=$2; G=$3; B=$4; N=${5:-40}
HERE=$(cd "$(dirname "$0")" && pwd)
mkdir -p "$B"
F="-std=c++20 -O2 -ffp-contract=off -Wno-psabi -I$HERE/emu -I$HERE -I$ABI -I$G"
$CXX $F -x c++ -c "$G/r4d_attn_paged_window.hip" -o "$B/k_attn.o"
$CXX $F -x c++ -c "$G/r4d_pair_argmax_f32.hip" -o "$B/k_pick.o"
$CXX $F -x c++ -c "$G/r4d_norm_join_bf16.hip" -o "$B/k_norm.o"
$CXX $F -x c++ -c "$G/r4d_expert_scale_bf16.hip" -o "$B/k_escale.o"
$CXX $F -c "$HERE/ref_host.cpp" -o "$B/ref.o"
$CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o"
for t in attn pick norm escale; do
$CXX $F -c "$HERE/test_$t.cpp" -o "$B/test_$t.o"
$CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/k_escale.o" "$B/ref.o" \
"$B/emu.o" -o "$B/test_$t"
done
"$B/test_attn"
"$B/test_attn" sweep "$N"
"$B/test_pick"
"$B/test_norm"
"$B/test_escale"
+20 -3
View File
@@ -192,7 +192,7 @@ int main(int argc, char** argv) {
{"h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {5}, {21}, -1, 0, 0, 512},
/* no scratch where a split was wanted: falls back to the unsplit kernel */
{"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}},
/* PREFILL-SHAPED: the WMMA kernel (a 64-row query, or longer) */
/* Prefill-shaped: the WMMA kernel (a 64-row query, or longer) */
{"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
{"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
{"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
@@ -240,9 +240,26 @@ int main(int argc, char** argv) {
wmmas, fails);
return fails ? 1 : 0;
}
/* [--shard k/n] [name filter]: --shard runs every n-th case from the k-th, so ctest can split
* the run into parallel entries. */
int shard = 0, shards = 1;
const char* filter = nullptr;
for (int i = 1; i < argc; ++i) {
if (std::string(argv[i]) == "--shard" && i + 1 < argc) {
if (std::sscanf(argv[++i], "%d/%d", &shard, &shards) != 2 || shards < 1 || shard < 0 ||
shard >= shards) {
std::fprintf(stderr, "--shard takes k/n with 0 <= k < n\n");
return 2;
}
} else {
filter = argv[i];
}
}
int fails = 0;
for (auto& c : cases) {
if (argc > 1 && c.name.find(argv[1]) == std::string::npos) continue;
for (size_t i = 0; i < cases.size(); ++i) {
const Case& c = cases[i];
if ((int)(i % (size_t)shards) != shard) continue;
if (filter && c.name.find(filter) == std::string::npos) continue;
fails += run(c);
}
std::printf("%d failure(s)\n", fails);
+5 -8
View File
@@ -1,8 +1,8 @@
/* tests/r4d_emu: expert_scale (r4d_expert_scale_bf16.hip) on the host SIMT emulator, against the chain it
* replaces -- embed_lookup of the [n_expert, 1] scale table by the ids, then mul into the weights --
* and against ref_host.cpp, bit for bit: one product rounded once has no other answer. Ids outside
* the table (a negative pad, one past the end) read a zero scale; rows past M and the pitch's
* padding stay untouched. */
/* tests/r4d_emu: expert_scale (r4d_expert_scale_bf16.hip) on the host SIMT emulator, checked bit
* for bit against the chain it replaces (embed_lookup of the [n_expert, 1] scale table by the
* ids, then mul into the weights) and against ref_host.cpp; one product rounded once has a single
* correct result. Ids outside the table (a negative pad, one past the end) read a zero scale;
* rows past M and the pitch's padding stay untouched. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -13,9 +13,6 @@
#include <random>
#include <vector>
static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
int main() {
std::mt19937 rng(5);
std::normal_distribution<float> nd(0.f, 1.f);
+16 -18
View File
@@ -1,14 +1,16 @@
/* tests/r4d_emu: the sandwich-norm joins (r4d_norm_join_bf16.hip) on the host SIMT emulator.
*
* Two references. The CHAIN is the unfused sequence the arch plugin would otherwise issue -- rmsnorm,
* add, rmsnorm (or rmsnorm x2, add, rmsnorm, add, mul_weight) -- in libr4d's per-element arithmetic,
* its sums of squares added in this kernel's block order: the fused kernel must match it BIT FOR
* BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in
* index order -- what a different libr4d block width does too -- and may differ by a flipped
* rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be
* left alone. The route form's chain adds the router's rmsnorm (with its mult) and libr4d's
* rmsnorm_quant_fp8 of the experts' norm -- amax * (1 / 448) a group, the clamped value encoded by
* the emulator's v_cvt_pk_fp8_f32, the saturating encoder every fp8 cast here uses. */
* Two references:
* Chain: the unfused sequence the arch plugin would otherwise issue (rmsnorm, add, rmsnorm; or
* rmsnorm x2, add, rmsnorm, add, mul_weight) in libr4d's per-element arithmetic, with sums of
* squares in this kernel's block order. The fused kernel must match it bit for bit: fusing
* changes only the launch count.
* Host arm: sums in index order (as a different libr4d block width would) and may differ by a
* flipped rounding, measured against the row's scale (see cmp).
* Padding columns and rows past M must be left alone. The route form's chain adds the router's
* rmsnorm (with its mult) and libr4d's rmsnorm_quant_fp8 of the experts' norm: scale amax / 448
* per group, the clamped value encoded by the emulator's v_cvt_pk_fp8_f32, the saturating
* encoder every fp8 cast here uses. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -21,9 +23,6 @@
#include <vector>
static std::mt19937 rng(11);
static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
static float rb(float f) { return b2f(f2b(f)); }
/* the kernel's sum of squares: 256 threads strided over the row, a butterfly a wave, waves in order */
static float block_factor(const std::vector<float>& v, int n, float eps) {
@@ -73,10 +72,9 @@ static std::vector<float> gains(int n) {
for (auto& x : g) x = d(rng);
return g;
}
/* vs the host arm, the difference in units of the row's RMS: a different summation order moves the
* norm factor by an f32 ulp, which flips a bf16 rounding here and there -- and where the residual
* add cancels, a flipped ulp of the addend is many ulps of a small sum, so ulps of the OUTPUT are
* the wrong yardstick and the row's scale is the right one. */
/* Difference from the host arm in units of the row's RMS. A different summation order moves the
* norm factor by an f32 ulp, which flips the odd bf16 rounding; where the residual add cancels,
* one ulp of the addend is many ulps of the small sum, so output ulps are the wrong yardstick. */
struct Tally { long chain_bad = 0, host_diff = 0, host_bad = 0, pad = 0; double worst = 0.0; };
static void cmp(const uint16_t* got, const uint16_t* chain, const uint16_t* host, int n, Tally& t) {
double ss = 0.0;
@@ -195,8 +193,8 @@ static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = f
for (int j = 0; j < 128; ++j) {
const int i = g * 128 + j;
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
/* vs the host arm: one code step is an eighth of its value at most, which is no
* more than an eighth of the group's amax; a scale an ulp off moves less */
/* vs the host arm: one code step is at most an eighth of its value, so at most an
* eighth of the group's amax; a scale an ulp off moves less */
const double dv = std::fabs((double)rad_fp8e4m3_to_f32(qd[oq + i]) * sd[os + g] -
(double)rad_fp8e4m3_to_f32(qh[oq + i]) * sh[os + g]);
if (dv > (double)am / 8 + 1e-30) ++q_host_bad;
+604
View File
@@ -0,0 +1,604 @@
/* tests/r4d_emu: the QSA block selection (r4d_qsa_select_bf16.hip) on the host SIMT emulator, each
* of its four kernels against a port of libref's ref_qsa_select, byte for byte: the page-id table
* (sentinel-filled before every launch, the row pitch's padding and a row past M included), nsel
* and seqused.
*
* Every fixture runs three ways: pinned to the single-workgroup kernel and pinned to the wide one,
* both without scratch, and the launcher's own choice with the split path's scratch given (the
* local + merge pair for a decode-shaped launch over several chunks, the wide kernel above 64 rows,
* else the single-workgroup one). The kernel that ran is checked by name.
*
* The fixtures follow r4d_selftest's qsa_select cases at sizes the emulator runs in seconds, plus a
* seeded sweep of small odd shapes (NaN, +-inf, -0.0, denormal and -1e30 scores, pitches, a table
* narrower than the scores, rows no sequence holds, topk 1, ratio 1). Which branch a row takes
* inside the kernels is predicted from their constants, restated in `Path`; the run fails when the
* fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <functional>
#include <map>
#include <random>
#include <string>
#include <vector>
extern "C" void r4d_qsa_select_pin_form(int form);
extern int emu_grids;
extern const char* emu_last_kernel;
namespace {
constexpr int32_t kSentinel = 0x55555555;
struct Fix {
std::string name;
int S = 1, M = 1, nb_s = 1, nb_t = 1; /* sequences, query rows, score and table widths */
int s_ld = 0, t_ld = 0, o_ld = 0; /* row pitches; 0 = tight */
int topk = 1, ratio = 1;
std::vector<float> sc; /* [M][s_ld] */
std::vector<int32_t> bt; /* [S][t_ld] */
std::vector<int32_t> nc, pos, cu; /* [S], [M], [S + 1] */
void shape(int s, int m, int nbs, int nbt, int tk, int r, int spad = 0, int tpad = 0, int opad = 0) {
S = s; M = m; nb_s = nbs; nb_t = nbt; topk = tk; ratio = r;
s_ld = nbs + spad; t_ld = nbt + tpad; o_ld = tk + 1 + opad;
sc.assign((size_t)M * s_ld, -INFINITY);
bt.assign((size_t)S * t_ld, -1);
nc.assign((size_t)S, 0); pos.assign((size_t)M, 0); cu.assign((size_t)S + 1, 0);
}
float& score(int m, int b) { return sc[(size_t)m * s_ld + b]; }
int32_t& page(int s, int b) { return bt[(size_t)s * t_ld + b]; }
int nb() const { return std::min(nb_s, nb_t); }
int seq_of(int m) const {
for (int s = 0; s < S; ++s) if (m >= cu[s] && m < cu[s + 1]) return s;
return 0;
}
int n_of(int m) const {
const int s = seq_of(m);
return (int)std::min<int64_t>(std::min<int64_t>(nc[s], nb()), ((int64_t)pos[m] + 1) / ratio);
}
};
/* ---- libref's ref_qsa_select (libref/ref_qsa.cpp), restated over the fixture's arrays: the same
* steps in the same order. */
void ref_select(const Fix& f, std::vector<int32_t>& se, std::vector<int32_t>& ns, std::vector<int32_t>& su) {
const int64_t topk = f.topk, ratio = f.ratio;
se.assign((size_t)f.M * (topk + 1), 0); ns.assign((size_t)f.M, 0); su.assign((size_t)f.M, 0);
for (int64_t m = 0; m < f.M; ++m) {
const int64_t s = f.seq_of((int)m), p = f.pos[m];
const int64_t n = std::min(std::min<int64_t>(f.nc[s], f.nb()), (p + 1) / ratio);
std::vector<float> val((size_t)n);
std::vector<int64_t> live;
for (int64_t b = 0; b < n; ++b) {
const float v = f.sc[(size_t)(m * f.s_ld + b)];
if (f.bt[(size_t)(s * f.t_ld + b)] < 0 || !(v > -1e30f)) continue;
val[(size_t)b] = v > 0.0f ? v : 0.0f;
live.push_back(b);
}
std::vector<int64_t> take;
if ((int64_t)live.size() <= topk) {
take = live;
} else {
std::vector<float> ord;
for (int64_t b : live) ord.push_back(val[(size_t)b]);
std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), std::greater<float>());
const float thr = ord[(size_t)(topk - 1)];
for (int64_t b : live)
if (val[(size_t)b] > thr) take.push_back(b);
for (int64_t b : live)
if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b);
}
int32_t* row = &se[(size_t)(m * (topk + 1))];
int64_t out = 0;
for (int64_t b : take) row[out++] = f.bt[(size_t)(s * f.t_ld + b)];
if (n < f.nb() && (p + 1) % ratio != 0) {
const int32_t part = f.bt[(size_t)(s * f.t_ld + n)];
if (part >= 0) row[out++] = part;
}
for (int64_t i = out; i <= topk; ++i) row[i] = -1;
ns[(size_t)m] = (int32_t)out;
su[(size_t)m] = (int32_t)(out == 0 ? 0 : (out - 1) * ratio + p % ratio + 1);
}
}
/* ---- Which branch a row takes inside the kernels: the launcher's and kernels' constants
* (r4d_qsa_select_bf16.hip) on a 64 KiB-LDS device, and their branch conditions. Coverage only: the
* tables are checked against the port above whatever the prediction says. */
namespace Path {
constexpr int kCacheCap = 8192, kCacheMaxM = 64; /* the key cache */
constexpr int kSamp = 2048, kSampRun = 32, kSampRuns = 64, kSampMinN = 3 * kSamp, kSampCap = 1920;
constexpr int kWideShift = 19, kWideCand = 3840, kMergeAbove = 512, kMergeCand = 1664;
constexpr int kParM = 32, kParWMax = 16, kParCap = 8192; /* the split path */
int par_chunks(int nb) { return std::max(1, std::min(kParWMax, (nb + 4095) / 4096)); }
}
uint32_t keyof(float v, int32_t page) {
if (page < 0 || !(v > -1e30f)) return 0u;
const float c = v > 0.0f ? v : 0.0f;
uint32_t u;
std::memcpy(&u, &c, 4);
return u + 1u;
}
enum Form { kSingle, kWide, kAuto };
const char* const kFormName[] = { "single", "wide", "auto" };
bool split_applies(const Fix& f) {
const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch;
return f.M <= Path::kParM && nch > 1 && chunk <= Path::kParCap && nch * f.topk <= Path::kParCap;
}
std::map<std::string, int> g_paths;
/* The branches row m reaches under `form`. */
void note_paths(const Fix& f, int m, Form form, bool split) {
const int s = f.seq_of(m), n = f.n_of(m), topk = f.topk;
std::vector<uint32_t> k((size_t)std::max(n, 0));
for (int b = 0; b < n; ++b) k[(size_t)b] = keyof(f.sc[(size_t)m * f.s_ld + b], f.bt[(size_t)s * f.t_ld + b]);
std::vector<uint32_t> live;
for (uint32_t x : k) if (x) live.push_back(x);
std::sort(live.begin(), live.end(), std::greater<uint32_t>());
const int L = (int)live.size();
auto hit = [](const char* p) { ++g_paths[p]; };
if (n <= topk) hit("rows of at most topk blocks");
else if (L == topk) hit("exactly topk live over more blocks");
else if (L < topk) hit("fewer than topk live over more blocks");
else {
hit("a threshold");
const uint32_t T = live[(size_t)topk - 1];
int above = 0, eq = 0;
for (uint32_t x : live) { above += x > T; eq += x == T; }
if (eq > topk - above) hit("a threshold whose ties are cut short");
}
if (split) {
const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch;
int tot = 0;
bool over = false;
for (int c = 0; c < nch && c * chunk < n; ++c) {
const int lo = c * chunk, hi = std::min(lo + chunk, n);
int lc = 0;
for (int b = lo; b < hi; ++b) lc += k[(size_t)b] != 0;
over |= hi - lo > topk && lc > topk;
tot += std::min(lc, topk);
}
if (n <= topk || (!over && tot <= topk)) hit("split: topk or fewer live, every one taken");
else if (!over) hit("split: no chunk over topk, more than topk live");
else if (tot == topk) hit("split: exactly topk candidates, from a chunk over topk");
else hit("split: a chunk over topk");
return;
}
if (form == kSingle || (form == kAuto && f.M <= Path::kCacheMaxM)) {
const int cap = f.M <= Path::kCacheMaxM ? std::min(Path::kCacheCap, f.nb()) : 0;
hit(n <= cap ? "single: keys cached in LDS" : "single: keys read from global memory");
return;
}
if (n <= topk) return;
if (n >= Path::kSampMinN && topk <= Path::kMergeAbove) {
std::vector<uint32_t> smp;
for (int i = 0; i < Path::kSamp; ++i) {
const long b = (long)(i / Path::kSampRun) * (n - Path::kSampRun) / (Path::kSampRuns - 1) + i % Path::kSampRun;
if (k[(size_t)b]) smp.push_back(k[(size_t)b]);
}
std::sort(smp.begin(), smp.end(), std::greater<uint32_t>());
const uint32_t ms = std::min<uint32_t>(
(uint32_t)(((uint64_t)topk * 2u * Path::kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u, Path::kSamp);
const uint32_t lo = smp.size() > ms ? smp[ms - 1] : 0u;
int cnt = 0;
for (uint32_t x : live) cnt += x >= lo;
const bool vec = (((uintptr_t)&f.sc[(size_t)m * f.s_ld] | (uintptr_t)&f.bt[(size_t)s * f.t_ld]) & 15u) == 0;
hit(vec ? "wide: the sampled pass, rows 16-byte aligned" : "wide: the sampled pass, rows not 16-byte aligned");
if (cnt > topk && cnt <= Path::kSampCap) {
hit(lo ? "wide: the sampled list" : "wide: the sampled list, holding every live key");
return;
}
hit("wide: a sample that fell back");
}
if (L <= topk) return;
const uint32_t B = live[(size_t)topk - 1] >> Path::kWideShift;
int in = 0;
for (uint32_t x : live) in += (x >> Path::kWideShift) == B;
hit(in <= Path::kMergeCand && topk <= Path::kMergeAbove ? "wide: merged lists"
: in <= Path::kWideCand ? "wide: the threshold's bin in LDS" : "wide: the threshold's bin over global memory");
}
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape, int64_t ld = 0) {
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) { t.shape[i] = shape[i]; t.stride[i] = st; st *= shape[i]; }
if (ld && t.rank == 2) t.stride[0] = ld;
return t;
}
/* One launch of `form` against the port. Returns the failures (0 or 1). */
int run(Fix& f, Form form) {
std::vector<int32_t> want, want_n, want_su;
ref_select(f, want, want_n, want_su);
const int M = f.M, W = f.topk + 1;
std::vector<int32_t> se((size_t)(M + 1) * f.o_ld, kSentinel), ns((size_t)M + 1, kSentinel), su((size_t)M + 1, kSentinel);
RadTensor t[8] = {
tens(f.sc.data(), RAD_F32, {M, f.nb_s}, f.s_ld), tens(f.bt.data(), RAD_I32, {f.S, f.nb_t}, f.t_ld),
tens(f.nc.data(), RAD_I32, {f.S}), tens(f.pos.data(), RAD_I32, {M}),
tens(f.cu.data(), RAD_I32, {f.S + 1}), tens(se.data(), RAD_I32, {M, W}, f.o_ld),
tens(ns.data(), RAD_I32, {M}), tens(su.data(), RAD_I32, {M}),
};
RadParam p[5]{};
p[0] = {"M", RAD_P_INT, M}; p[1] = {"blocks", RAD_P_INT, f.nb()}; p[2] = {"topk", RAD_P_INT, f.topk};
p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S};
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = 5;
const int64_t need = r4d_rad_qsa_select_scratch(&a);
std::vector<uint32_t> scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u);
if (form == kAuto) { a.scratch = scratch.data(); a.scratch_bytes = need; }
r4d_qsa_select_pin_form(form == kSingle ? 1 : form == kWide ? 2 : 0);
const int g0 = emu_grids;
const int rc = r4d_rad_qsa_select(&a, nullptr);
r4d_qsa_select_pin_form(0);
const int grids = emu_grids - g0;
const bool split = form == kAuto && split_applies(f);
const char* expect = split ? "qsa_merge_kernel"
: form == kWide || (form == kAuto && f.M > Path::kCacheMaxM) ? "qsa_select_wide_kernel"
: "qsa_select_kernel";
const char* fn = kFormName[form];
if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; }
if (std::strcmp(emu_last_kernel, expect) != 0 || grids != (split ? 2 : 1)) {
std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn,
emu_last_kernel, grids, expect, split ? 2 : 1);
return 1;
}
int bad_rows = 0;
for (int m = 0; m <= M; ++m) {
if (m < M) note_paths(f, m, form, split);
int diff = 0, first = -1;
for (int i = 0; i < f.o_ld; ++i) {
const int32_t w = m < M && i < W ? want[(size_t)m * W + i] : kSentinel;
if (se[(size_t)m * f.o_ld + i] != w) { ++diff; if (first < 0) first = i; }
}
const int32_t wn = m < M ? want_n[(size_t)m] : kSentinel, wsu = m < M ? want_su[(size_t)m] : kSentinel;
if (!diff && ns[(size_t)m] == wn && su[(size_t)m] == wsu) continue;
if (++bad_rows > 4) continue;
std::printf("FAIL %-48s %-6s row %d (n %d): nsel %d want %d, seqused %d want %d", f.name.c_str(), fn, m,
m < M ? f.n_of(m) : -1, ns[(size_t)m], wn, su[(size_t)m], wsu);
if (diff) {
const int32_t w = m < M && first < W ? want[(size_t)m * W + first] : kSentinel;
std::printf(", %d slot(s) differ, first slot %d: %d want %d", diff, first, se[(size_t)m * f.o_ld + first], w);
}
std::printf("\n");
}
return bad_rows ? 1 : 0;
}
uint64_t g_x = 0;
uint64_t rnd() { g_x ^= g_x << 13; g_x ^= g_x >> 7; g_x ^= g_x << 17; return g_x; }
/* r4d_selftest's qsa_select_case: decode rows, ties on a coarse grid, a dead page with a winning
* score, a tail on alternate rows; rows 0 and 1 have at most topk live. */
Fix fix_decode() {
Fix f; f.name = "decode: ties, a tail and a dead page";
const int M = 6, nb = 900, topk = 64, pages = 4096, ratio = 4;
f.shape(M, M, nb, nb, topk, ratio);
std::fill(f.sc.begin(), f.sc.end(), 0.0f);
for (int m = 0; m < M; ++m) {
const int live = m == 0 ? 9 : m == 1 ? topk : 100 + m * 137;
f.nc[m] = live; f.cu[m + 1] = m + 1;
for (int b = 0; b < nb; ++b) {
if (b < live) {
f.score(m, b) = (float)((b * 17 + m * 7) % 40) * 0.25f;
f.page(m, b) = (b * 31 + m * 11) % pages;
if (b == live / 3) { f.score(m, b) = 1e6f; f.page(m, b) = -1; }
} else if (b == live) {
f.page(m, b) = m % 2 == 0 ? (m * 97 + 5) % pages : -1;
}
}
f.pos[m] = f.page(m, live) >= 0 ? live * ratio + m % 3 : live * ratio - 1;
}
return f;
}
/* r4d_selftest's qsa_select_prefill_case: two chunks over two histories, each query bounded by
* its own position, the partial page present exactly when (pos + 1) % ratio != 0. */
Fix fix_prefill() {
Fix f; f.name = "prefill: per-query bound and the partial page";
const int S = 2, nb = 96, topk = 5, pages = 512, ratio = 4, q0 = 9, q1 = 14, M = q0 + q1;
const int base[2] = { 137, 4 };
f.shape(S, M, nb, nb, topk, ratio);
f.cu = { 0, q0, M };
for (int i = 0; i < q0; ++i) f.pos[i] = base[0] + i;
for (int i = 0; i < q1; ++i) f.pos[q0 + i] = base[1] + i;
f.nc = { (base[0] + q0) / ratio, (base[1] + q1) / ratio };
for (int s = 0; s < S; ++s)
for (int b = 0; b < nb; ++b)
f.page(s, b) = b <= (base[s] + (s == 0 ? q0 : q1) - 1) / ratio ? (b * 29 + s * 7) % pages : -1;
for (int m = 0; m < M; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 23 + m * 5) % 37) * 0.5f;
return f;
}
/* r4d_selftest's qsa_select_wide_case at emulator size: the first sequence's rows see about 3000,
* 5000, 7000 and 8800 blocks (the two-pass form below the sample's 6144, the sampled form above,
* the key cache's 8192 crossed), the second's fewer than topk; dead pages and -inf scattered; five
* score distributions. Over 4096 blocks at six rows, the automatic choice is the split path. */
Fix fix_wide(int dist) {
static const char* const kDist[] = { "continuous", "coarse, heavy ties", "an eighth in one first-digit bin",
"all in one first-digit bin", "fine ties at the threshold" };
Fix f; f.name = std::string("wide: ") + kDist[dist];
const int S = 2, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20;
f.shape(S, 6, nb, nb, topk, ratio);
f.cu = { 0, 4, 6 };
f.pos = { 4 * 3000 + 1, 4 * 5000 + 2, 4 * 7000 + 3, 4 * 8800 + 1, 4 * 300, 4 * 337 + 2 };
f.nc = { 8900, 340 };
g_x = 0x243F6A8885A308D3ull + (uint64_t)dist;
for (auto& v : f.bt) v = rnd() % 97 == 0 ? -1 : (int32_t)(rnd() % pages);
for (auto& v : f.sc) {
const uint64_t u = rnd();
if (u % 211 == 0) { v = -INFINITY; continue; }
switch (dist) {
case 0: v = (float)(u % 1000003) / 1000.0f; break;
case 1: v = (float)(u % 23) * 0.25f; break;
case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break;
case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break;
default: v = (float)(u % 4999) * 0.01f; break;
}
}
return f;
}
/* r4d_selftest's qsa_select_split_one at emulator size: three chunks, 96 distinct scores so the
* tie rule decides, one page in 64 dead, `per` draft rows a sequence. */
Fix fix_split(int S, int per) {
Fix f; f.name = "split: " + std::to_string(S) + " seq x " + std::to_string(per) + " rows, 96 scores";
const int M = S * per, nb = 12001, topk = 512, ratio = 4, pages = 8192, n = 11000;
f.shape(S, M, nb, nb, topk, ratio);
for (int s = 0; s < S; ++s) {
const int ns = n - s * 1300;
f.nc[s] = ns; f.cu[s] = s * per;
for (int b = 0; b < nb; ++b)
f.page(s, b) = b >= ns ? -1 : b % 64 == 37 ? -1 : (b * 4099 + 11 + s * 71) % pages;
for (int j = 0; j < per; ++j) f.pos[s * per + j] = ns * ratio + j - 2;
}
f.cu[S] = M;
for (int m = 0; m < M; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 31 + m * 17) % 96) * 0.125f;
return f;
}
/* Three chunks, none with more than topk live: the merge's candidates are every live key, more
* than topk in the first row (its threshold the list's own, coarse scores tied at it), topk or
* fewer in the second. The first row's sample holds fewer live keys than its bound, so the wide
* kernel's list is every live key. */
Fix fix_split_sparse() {
Fix f; f.name = "split: no chunk over topk";
const int nb = 9000, topk = 512, ratio = 4;
f.shape(2, 2, nb, nb, topk, ratio);
f.cu = { 0, 1, 2 }; f.nc = { 8990, 8990 }; f.pos = { 4 * 8990 + 1, 4 * 8990 + 3 };
for (int s = 0; s < 2; ++s)
for (int b = 0; b < nb; ++b) f.page(s, b) = b % (s ? 20 : 9) == 3 ? (b * 131 + s) % 65536 : -1;
for (int m = 0; m < 2; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 7 + m) % 13) * 0.5f;
return f;
}
/* r4d_selftest's qsa_select_few_live_case: over more than topk blocks with topk or fewer live.
* 0 few live pages, continuous scores 1 few live, most of them scoring zero or less
* 2 live pages, most scores -inf 3 exactly topk live, a third tied at zero
* 4 all live keys in the first chunk, more than topk, ties at the threshold
* 5 nothing live 6 at most topk blocks (control)
* 7 everything live (control) */
Fix fix_few_live() {
Fix f; f.name = "few live: topk or fewer live, in every way";
const int S = 8, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20;
const int nrow[S] = { 8000, 8000, 8000, 8000, 2000, 8000, 300, 8000 };
f.shape(S, S, nb, nb, topk, ratio);
g_x = 0x9E3779B97F4A7C15ull;
for (int s = 0; s < S; ++s) {
const int n = nrow[s];
f.nc[s] = n; f.cu[s] = s; f.pos[s] = n * ratio + s % 3;
for (int b = 0; b < n; ++b) {
float& v = f.score(s, b);
int32_t& pg = f.page(s, b);
const uint64_t u = rnd();
const float cont = (float)(u % 1000003) / 1000.0f + 0.001f;
pg = (int32_t)(u % pages);
switch (s) {
case 0: if (b % 80 != 3) pg = -1; v = cont; break;
case 1: if (b % 20 != 7) pg = -1;
v = (b / 20) % 4 == 0 ? cont : (b / 20) % 3 == 0 ? -2.5f : (b / 20) % 3 == 1 ? -0.0f : 0.0f;
break;
case 2: v = b % 40 == 1 ? cont : -INFINITY; break;
case 3: if (b % 15 != 2 || b >= 15 * 512) pg = -1;
v = b % 45 == 2 ? 0.0f : cont; break;
case 4: v = b % 7 == 0 ? cont : (b % 2 ? 0.0f : -0.0f); break;
case 5: pg = -1; v = cont; break;
case 6: if (b % 9 == 4) pg = -1; v = (float)(u % 13) * 0.5f; break;
default: v = cont; break;
}
}
f.page(s, n) = s % 2 == 0 ? (int32_t)(rnd() % pages) : -1;
}
f.cu[S] = S;
return f;
}
/* A 70-row prefill chunk: wider than the key cache's gate, so the automatic choice is the wide
* kernel and the pinned single-workgroup kernel reads its keys from global memory. */
Fix fix_wide_launch() {
Fix f; f.name = "a 70-row chunk: the wide kernel by default";
const int M = 70, nb = 160, topk = 16, ratio = 4;
f.shape(1, M, nb, nb, topk, ratio);
f.cu = { 0, M }; f.nc = { 110 };
for (int m = 0; m < M; ++m) f.pos[m] = 4 * 90 + m;
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 11 == 5 ? -1 : (b * 37 + 3) % 4096;
for (int m = 0; m < M; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 13 + m * 3) % 9) * 0.5f;
return f;
}
/* topk above the merged form's 512: the wide kernel's threshold bin goes to LDS alone, and the
* split path still applies (two chunks of 2500, two lists of up to 1000 keys). */
Fix fix_big_topk() {
Fix f; f.name = "topk 1000: above the merged form";
const int nb = 5000, topk = 1000, ratio = 4;
f.shape(1, 3, nb, nb, topk, ratio);
f.cu = { 0, 3 }; f.nc = { 4990 }; f.pos = { 4 * 4990 + 2, 4 * 3000 - 1, 4 * 900 + 1 };
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 13 == 6 ? -1 : (b * 211 + 7) % 100000;
for (int m = 0; m < 3; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 11 + m * 5) % 50) * 0.125f;
return f;
}
/* Where the launcher leaves the split path: 33 query rows (one past its 32), and topk 3000, whose
* three chunk lists overflow its 8192 keys. Both take the single-workgroup kernel. */
Fix fix_no_split(bool rows) {
Fix f; f.name = rows ? "33 rows: past the split path's 32" : "topk 3000: past the split path's lists";
const int M = rows ? 33 : 2, nb = rows ? 4500 : 9000, topk = rows ? 64 : 3000, ratio = 4;
f.shape(1, M, nb, nb, topk, ratio);
f.cu = { 0, M }; f.nc = { nb - 10 };
for (int m = 0; m < M; ++m) f.pos[m] = 4 * (nb - 10 - 97 * m) + m % 4;
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 17 == 1 ? -1 : (b * 389 + 1) % 200000;
for (int m = 0; m < M; ++m)
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 29 + m * 3) % 211) * 0.0625f;
return f;
}
/* A seeded small fixture: odd values, pitches, widths and row-to-sequence maps. */
Fix fix_sweep(int it) {
g_x = 0xD1B54A32D192ED03ull ^ ((uint64_t)(it + 1) * 0x9E3779B97F4A7C15ull);
for (int i = 0; i < 4; ++i) rnd();
static const int kTopk[] = { 1, 2, 3, 5, 8, 17, 33, 64 }, kRatio[] = { 1, 2, 3, 4, 7 };
const int topk = kTopk[rnd() % 8], ratio = kRatio[rnd() % 5], S = 1 + (int)(rnd() % 3);
const int nb_t = 1 + (int)(rnd() % 300), nb_s = rnd() % 3 ? nb_t : 1 + (int)(rnd() % 300);
std::vector<int> rows((size_t)S);
int M = 0;
for (auto& r : rows) { r = (int)(rnd() % 5); M += r; }
const int lead = rnd() % 4 == 0 ? 1 : 0, trail = rnd() % 4 == 0 ? 1 : 0; /* rows no sequence holds */
M += lead + trail;
if (M == 0) { rows[0] = 1; M = 1; }
Fix f; f.name = "sweep " + std::to_string(it);
f.shape(S, M, nb_s, nb_t, topk, ratio, (int)(rnd() % 4), (int)(rnd() % 4), (int)(rnd() % 3));
f.cu[0] = lead;
for (int s = 0; s < S; ++s) f.cu[s + 1] = f.cu[s] + rows[(size_t)s];
const int nb = f.nb();
for (int s = 0; s < S; ++s) f.nc[s] = (int)(rnd() % (uint64_t)(nb + 6));
for (int m = 0; m < M; ++m) f.pos[m] = (int)(rnd() % (uint64_t)(ratio * (nb + 3)));
const unsigned dead = (unsigned)(rnd() % 4); /* none, a tenth, half, nearly all */
for (auto& v : f.bt) {
const uint64_t u = rnd();
v = (dead == 1 && u % 10 == 0) || (dead == 2 && u % 2) || (dead == 3 && u % 20) ? -1 : (int32_t)(u % 100000);
}
const unsigned grid = 1 + (unsigned)(rnd() % 12); /* distinct values: ties when small */
for (auto& v : f.sc) {
const uint64_t u = rnd();
switch (u % 23) {
case 0: v = NAN; break;
case 1: v = INFINITY; break;
case 2: v = -INFINITY; break;
case 3: v = -0.0f; break;
case 4: v = 0.0f; break;
case 5: v = 1e-40f * (float)(1 + (u >> 8) % 4); break; /* denormal */
case 6: v = -1e30f; break; /* not live: the bound is strict */
case 7: v = -9e29f; break; /* live, ranked as zero */
case 8: v = -(float)((u >> 8) % 100); break;
default: v = (float)((u >> 8) % grid) * 0.75f; break;
}
}
return f;
}
/* A seeded fixture at serving sizes for `sweep`: 500 to 14500 blocks, topk on both sides of the
* merged form's 512 and of the split path's list budget, one to three sequences of a few draft
* rows or of a prefill chunk past 64 rows, and dead pages, -inf, NaN and ties in varying amounts. */
Fix fix_random(int it) {
g_x = 0xA0761D6478BD642Full ^ ((uint64_t)(it + 7) * 0xE7037ED1A0B428DBull);
for (int i = 0; i < 4; ++i) rnd();
static const int kTopk[] = { 1, 16, 64, 200, 511, 512, 513, 700, 1500, 2600 }, kRatio[] = { 1, 4, 4, 8 };
const int topk = kTopk[rnd() % 10], ratio = kRatio[rnd() % 4], S = 1 + (int)(rnd() % 3);
const int nb = 500 + (int)(rnd() % 14000);
const bool chunk = rnd() % 6 == 0;
std::vector<int> rows((size_t)S);
int M = 0;
for (auto& r : rows) { r = chunk ? 20 + (int)(rnd() % 30) : 1 + (int)(rnd() % 5); M += r; }
Fix f; f.name = "sweep " + std::to_string(it) + ": " + std::to_string(M) + " rows, " + std::to_string(nb) +
" blocks, topk " + std::to_string(topk);
f.shape(S, M, nb, nb + (int)(rnd() % 3), topk, ratio, (int)(rnd() % 5), (int)(rnd() % 5), (int)(rnd() % 3));
for (int s = 0; s < S; ++s) f.cu[s + 1] = f.cu[s] + rows[(size_t)s];
for (int s = 0; s < S; ++s) f.nc[s] = nb - (int)(rnd() % (uint64_t)(nb / 2 + 1)) + (int)(rnd() % 3);
for (int m = 0; m < M; ++m)
f.pos[m] = std::max(0, ratio * f.nc[f.seq_of(m)] - (int)(rnd() % (uint64_t)(ratio * nb / 3 + 1)) + (int)(rnd() % 7));
const unsigned dead = (unsigned)(rnd() % 6), dist = (unsigned)(rnd() % 6), grid = 1 + (unsigned)(rnd() % 400);
for (auto& v : f.bt) {
const uint64_t u = rnd();
const bool d = dead == 1 ? u % 50 == 0 : dead == 2 ? u % 2 == 0 : dead == 3 ? u % 16 != 0
: dead == 4 ? u % 100 != 0 : false;
v = d ? -1 : (int32_t)(u % 1000000);
}
for (auto& v : f.sc) {
const uint64_t u = rnd();
if (u % 97 == 0) { v = -INFINITY; continue; }
if (u % 389 == 0) { v = NAN; continue; }
switch (dist) {
case 0: v = (float)(u % 1000003) / 1000.0f; break;
case 1: v = (float)((u >> 8) % grid) * 0.25f; break;
case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break;
case 3: v = 1.0f + (float)((u >> 8) % 60000) * 1e-6f; break;
case 4: v = (u >> 8) % 3 == 0 ? 0.0f : (u >> 8) % 3 == 1 ? -0.0f : -1.0f; break;
default: v = (float)((u >> 8) % 4999) * 0.01f; break;
}
}
return f;
}
} // namespace
/* No argument: the fixtures above and the branch check. `sweep N`: N fix_random fixtures, about
* 0.15 s each. */
int main(int argc, char** argv) {
const auto t0 = std::chrono::steady_clock::now();
const bool sweep = argc > 1 && std::string(argv[1]) == "sweep";
std::vector<std::function<Fix()>> fixtures;
if (sweep) {
const int n = argc > 2 ? std::atoi(argv[2]) : 100;
for (int i = 0; i < n; ++i) fixtures.push_back([i] { return fix_random(i); });
} else {
fixtures = { fix_decode, fix_prefill, fix_few_live, fix_wide_launch,
[] { return fix_split(1, 4); }, [] { return fix_split(2, 4); }, fix_split_sparse, fix_big_topk,
[] { return fix_no_split(true); }, [] { return fix_no_split(false); } };
for (int d = 0; d < 5; ++d) fixtures.push_back([d] { return fix_wide(d); });
for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return fix_sweep(i); });
}
int fails = 0, launches = 0;
for (auto& make : fixtures) {
Fix f = make();
for (Form form : { kSingle, kWide, kAuto }) { fails += run(f, form); ++launches; }
}
if (sweep) {
for (const auto& [p, c] : g_paths) std::printf(" %5d row(s): %s\n", c, p.c_str());
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
std::printf("qsa_select sweep: %zu fixtures, %d launches, %d failure(s), %.1f s\n", fixtures.size(),
launches, fails, sec);
return fails ? 1 : 0;
}
/* Every branch the fixtures are built to reach. */
static const char* const kRequired[] = {
"rows of at most topk blocks", "exactly topk live over more blocks", "fewer than topk live over more blocks",
"a threshold", "a threshold whose ties are cut short",
"single: keys cached in LDS", "single: keys read from global memory",
"wide: the sampled pass, rows 16-byte aligned", "wide: the sampled pass, rows not 16-byte aligned",
"wide: the sampled list", "wide: the sampled list, holding every live key",
"wide: a sample that fell back", "wide: merged lists",
"wide: the threshold's bin in LDS", "wide: the threshold's bin over global memory",
"split: topk or fewer live, every one taken", "split: no chunk over topk, more than topk live",
"split: a chunk over topk", "split: exactly topk candidates, from a chunk over topk",
};
int missing = 0;
for (const char* p : kRequired)
if (!g_paths.count(p)) { std::printf("FAIL no row reaches: %s\n", p); ++missing; }
for (const auto& [p, c] : g_paths) std::printf(" %5d row(s): %s\n", c, p.c_str());
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
std::printf("qsa_select: %zu fixtures, %d launches, %d failure(s), %d branch(es) unreached, %.1f s\n",
fixtures.size(), launches, fails, missing, sec);
return fails || missing ? 1 : 0;
}