This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libr4d/r4d_attn_prefill_h256_gqa6.hip
T
Deadcode 1e968f6e1d 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
2026-10-16 18:25:18 +02:00

442 lines
21 KiB
Plaintext

// R4D prefill. Transposed core: S^T = K.Q^T, one lane owns one query row, ROWS = 16*NWARPS,
// 128-VGPR accumulator. The query is bf16 and the KV cache is fp8 or bf16; the 16-bit operand
// format for both matmuls is f16 (see r4d_dt16.h for why).
//
// Two families: all-16-bit (bf16 KV) and 16/8 mixed (bf16 query, fp8 KV). No fp8-P variant.
//
// Each option below can be turned off on its own after a geometry change:
//
// LAZY (always on) Softmax against a reference max instead of a running one:
// p = 2^(s - m_ref + SHIFT), with m_ref updated and the 128-VGPR accumulator rescaled only
// when a row max exceeds m_ref by more than the P format absorbs (DT16::GROW octaves),
// instead of on every m-tile. Same relative weighting in an f32 accumulator.
// F16 f16 as the 16-bit operand format. gfx1201 has no bf16 convert (software RTNE is ~6 VALU);
// v_cvt_pkrtz_f16_f32 converts two values in one. Exact for these operands (fp8 has 3
// mantissa bits, bf16 7, f16 10).
// MSKIP Causal masking only on m-tiles that straddle the limit.
// FOLDQ scale * k_descale * log2(e) folded into the query once at load.
// CONTIG The WMMA k axis is only contracted, so relabelling it on both operands is free. Reading
// eight contiguous elements at 8*h gives one aligned ds_read_b128 per fragment, removes 16
// address adds and makes the P fragment lane-local.
// PF/SGB Load PF fragments before the matching PF WMMAs, with a scheduling barrier between the
// groups. Without the barrier PF has no effect.
// DOT2 v_dot2_f32_f16 row sum from the packed f16 P: 4 instructions instead of 8, and the
// denominator uses the p values the PV matmul used.
// BTS/KWIDE/GPREV tile staging; see each define.
#include "r4d.h"
#include "r4d_common.h"
#include "r4d_dt16.h"
#define O_F16 1
#define O_MSKIP 2
#define O_FOLDQ 8
#define O_CONTIG 512
#define O_PF2 1024
#define O_PF4 2048
#define O_PF8 3072
#define O_SGB 4096
#define O_DOT2 16384
// BTS: a tile's TILE/BS block-table entries are at a wave-uniform index, so load them into SGPRs
// once per tile. Otherwise each staging pass does two serialised memory round trips (block table,
// then KV) inside a barrier-bounded phase with nothing else to run.
#define O_BTS 262144
// KWIDE: one 16-byte K fetch per thread instead of two 8-byte ones. 768 threads x 16 B is exactly
// a 48-key fp8 tile, so staging is straight-line with half the loads and block-table lookups.
// key = tid/16 would make a warp write one row at a 32-byte stride (4-way LDS bank conflict, since
// 8*ch mod 32 takes four values). key = 2*warp + (lane&1), ch = (lane&31)>>1 interleaves two keys
// so the writes cover all 32 banks, while global reads stay two contiguous 256-byte runs.
#define O_KWIDE 524288
// GPREV: fetch tile ti+1's V into registers right after the second barrier, so its latency is
// hidden by tile ti's 96 WMMAs and only the LDS stores remain between barriers. V only: at
// 240 VGPRs a K prefetch would be spilled, and a spilled prefetch is waited on immediately.
#define O_GPREV 1048576
// LDSB: an LDS-scoped barrier instead of __syncthreads() (lds_barrier() in r4d_common.h). The
// default fence invalidates the vector cache twice per tile, though only LDS needs ordering.
#define O_LDSB 2097152
// bf16 dword -> 16-bit dword in the target format, optionally scaled. Used once per kernel on Q.
template<class D, int FOLDQ, int F16>
__device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) {
if (!FOLDQ) return F16 ? D::from_bf16w(w) : w;
return D::pk(__builtin_bit_cast(float, w << 16) * s,
__builtin_bit_cast(float, w & 0xffff0000u) * s);
}
// WIN enables a sliding window (a.window positions ending at each row's causal limit), as in the
// decode kernel. Keys below the window are masked, and the KV walk starts at the tile holding the
// workgroup's earliest window token. window <= 0 (or WIN off) is full attention.
template<int NWARPS, int TILE, int HEAD_DIM, int GQA, int BS, int KVP, int OPT, int WIN = 0>
__global__ __launch_bounds__(NWARPS * 32)
void r4d_attn_prefill_kernel(const R4DArgs a)
{
constexpr int F16 = (OPT & O_F16) ? 1 : 0;
constexpr int MSKIP = (OPT & O_MSKIP) ? 1 : 0;
constexpr int FOLDQ = (OPT & O_FOLDQ) ? 1 : 0;
constexpr int CTG = (OPT & O_CONTIG) ? 1 : 0;
constexpr int PF = 1 << ((OPT >> 10) & 3);
constexpr int SGB = (OPT & O_SGB) ? 1 : 0;
constexpr int DOT2 = ((OPT & O_DOT2) && (OPT & O_F16)) ? 1 : 0;
constexpr int BTS = (OPT & O_BTS) ? 1 : 0;
constexpr int GPREV = (OPT & O_GPREV) ? 1 : 0;
constexpr int LDSB = (OPT & O_LDSB) ? 1 : 0;
constexpr int KWIDE = (OPT & O_KWIDE) ? 1 : 0;
typedef DT16<F16> D;
typedef typename D::frag frag16;
constexpr int ROWS = NWARPS * 16;
constexpr int BLOCK_Q = ROWS / GQA;
constexpr int NKS = HEAD_DIM / 16;
constexpr int MT = TILE / 16;
constexpr int KSTR = HEAD_DIM + (CTG ? 8 : 4);
constexpr int VSTR = TILE + (CTG ? 8 : 4);
constexpr int NTHR = NWARPS * 32;
constexpr int NB = TILE / BS; // block-table entries per tile
constexpr int KEL = KWIDE ? 16 : 8; // K elements fetched per thread-pass
constexpr int KITEMS = TILE * (HEAD_DIM / KEL); // K passes needed for one tile
constexpr int KPASS = (KITEMS + NTHR - 1) / NTHR; // passes per thread
constexpr int KREGS = KPASS * (KVP ? 2 : 1); // uint4 of raw K per thread
constexpr int NTR = (TILE / 8) * (HEAD_DIM / (KVP ? 32 : 64));
constexpr int VREGS = (NTR + NWARPS - 1) / NWARPS; // uint4 of raw V per thread
constexpr float PSHIFT = D::SHIFT;
constexpr float PGROW = D::GROW;
static_assert(!KWIDE || KPASS == 1, "the wide K fetch is one straight-line pass");
__shared__ uint16_t sK[TILE * KSTR];
__shared__ uint16_t sV16[HEAD_DIM * VSTR];
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int c = lane & 15, h = lane >> 4;
const int qb = blockIdx.x, kvh = blockIdx.y, seq = blockIdx.z;
const int ctx = a.seqused_k[seq];
if (ctx <= 0) return;
// Ragged batches: this sequence owns rows [qoff, qoff+qlen) of q and out. grid.x is sized from
// the batch maximum q_len, so blocks past a shorter sequence's end exit here.
const int qoff = r4d_q_off(a.cu_q, seq, a.q_len);
const int qlen = r4d_q_len(a.cu_q, seq, a.q_len);
if (qb * BLOCK_Q >= qlen) return;
const int row = warp * 16 + c;
const int qi = row / GQA, hi = row - qi * GQA;
const int qpos = qb * BLOCK_Q + qi;
const bool live = (qpos < qlen);
const int qrow = live ? qpos : (qlen - 1);
const int qhead = kvh * GQA + hi;
const int* __restrict__ bt = a.block_table + (size_t)seq * a.max_blocks;
const float kdesc = a.k_descale ? a.k_descale[seq * a.kv_heads + kvh] : 1.0f;
const float vdesc = a.v_descale ? a.v_descale[seq * a.kv_heads + kvh] : 1.0f;
const float mul = a.scale * kdesc * 1.44269504089f;
frag16 qf[NKS];
{
const uint16_t* qp = (const uint16_t*)a.q
+ ((size_t)(qoff + qrow) * a.q_heads + qhead) * HEAD_DIM;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
// CONTIG reads the 8 dims as one run; the split map takes them 4+4.
const uint2 l0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h : 4 * h));
const uint2 h0 = *(const uint2*)(qp + 16 * t + (CTG ? 8 * h + 4 : 8 + 4 * h));
qf[t] = D::mk(make_uint2(r4d_qcvt<D, FOLDQ, F16>(l0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(l0.y, mul)),
make_uint2(r4d_qcvt<D, FOLDQ, F16>(h0.x, mul),
r4d_qcvt<D, FOLDQ, F16>(h0.y, mul)));
}
}
const int klimit = ctx - qlen + qpos;
// First key in this row's window, floored at zero. Same formula as r4d_attn_wlo, which is
// defined in the decode unit, included after this one.
int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0;
if (WIN && a.window > 0 && wlo < 0) wlo = 0;
float m_ref = -3.0e38f;
float off = PSHIFT + 3.0e38f;
float l_i = 0.0f;
v8f acc[NKS];
#pragma unroll
for (int t = 0; t < NKS; ++t) acc[t] = (v8f){0,0,0,0,0,0,0,0};
const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1);
const int klimit_cta = ctx - qlen + qmax_cta;
const int ntiles = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE;
// First window tile, taken at this workgroup's first query row (the one reaching furthest
// back), not the chunk's row 0, so fully masked tiles are never walked. Starts at 0 without a
// window.
const int wlo0 = (WIN && a.window > 0) ? (ctx - qlen + qb * BLOCK_Q - a.window + 1) : 0;
const int tstart = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0;
// ---- staging, split into a global fetch (registers) and an LDS store ------------------------
// The split lets GPREV move the fetch out from between the barriers.
const int vg = lane >> 3, vj = lane & 7;
uint4 kreg[KREGS], vreg[VREGS];
auto fetchK = [&](int k0, const int* blks) {
#pragma unroll
for (int p = 0; p < KPASS; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL));
const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL));
if (KWIDE && key >= TILE) continue;
const int kk = min(k0 + key, ctx - 1);
const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const size_t o = (size_t)blk * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride + (size_t)(kk % BS) * (2 * HEAD_DIM);
if (KVP) {
const uint16_t* g = (const uint16_t*)a.kv + o + ch * KEL;
#pragma unroll
for (int q = 0; q < (KVP ? (KEL / 8) : 1); ++q)
kreg[p * (KEL / 8) + q] = *(const uint4*)(g + 8 * q);
} else if (KWIDE) {
kreg[p] = *(const uint4*)((const uint8_t*)a.kv + o + ch * 16);
} else {
const uint2 r = *(const uint2*)((const uint8_t*)a.kv + o + ch * 8);
kreg[p] = make_uint4(r.x, r.y, 0, 0);
}
}
}
};
auto fetchV = [&](int k0, const int* blks) {
#pragma unroll
for (int r = 0; r < VREGS; ++r) {
const int idx = warp + r * NWARPS;
if (NTR % NWARPS == 0 || idx < NTR) {
constexpr int DG = HEAD_DIM / (KVP ? 32 : 64);
const int kg = idx / DG, dg = idx - kg * DG;
const int kk = min(k0 + kg * 8 + vj, ctx - 1);
const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16);
const int blk = BTS ? blks[(kk - k0) / BS] : bt[kk / BS];
const size_t o = (size_t)blk * a.kv_block_stride
+ (size_t)kvh * a.kv_head_stride
+ (size_t)(kk % BS) * (2 * HEAD_DIM) + HEAD_DIM + d0;
const void* p = KVP ? (const void*)((const uint16_t*)a.kv + o)
: (const void*)((const uint8_t*)a.kv + o);
vreg[r] = __builtin_bit_cast(uint4, load_tr_b128(p));
}
}
};
auto storeK = [&]() {
#pragma unroll
for (int p = 0; p < KPASS; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
const int key = KWIDE ? (2 * (i >> 5) + (i & 1)) : (i / (HEAD_DIM / KEL));
const int ch = KWIDE ? ((i & 31) >> 1) : (i - key * (HEAD_DIM / KEL));
if (KWIDE && key >= TILE) continue;
uint16_t* kd = &sK[key * KSTR + ch * KEL];
#pragma unroll
for (int q = 0; q < KEL / 8; ++q) {
uint32_t w4[4];
if (KVP) {
const uint4 r = kreg[p * (KEL / 8) + q];
w4[0] = D::from_bf16w(r.x); w4[1] = D::from_bf16w(r.y);
w4[2] = D::from_bf16w(r.z); w4[3] = D::from_bf16w(r.w);
} else {
const uint4 r = kreg[p];
fp8x8_to_16x4w<D>(q ? make_uint2(r.z, r.w) : make_uint2(r.x, r.y), w4);
}
*(uint2*)(kd + 8 * q) = make_uint2(w4[0], w4[1]);
*(uint2*)(kd + 8 * q + 4) = make_uint2(w4[2], w4[3]);
}
}
}
};
auto storeV = [&]() {
#pragma unroll
for (int r = 0; r < VREGS; ++r) {
const int idx = warp + r * NWARPS;
if (NTR % NWARPS == 0 || idx < NTR) {
constexpr int DG = HEAD_DIM / (KVP ? 32 : 64);
const int kg = idx / DG, dg = idx - kg * DG;
const int d0 = dg * (KVP ? 32 : 64) + vg * (KVP ? 8 : 16);
const uint4 v = vreg[r];
if (KVP) {
uint16_t* dst = &sV16[(d0 + vj) * VSTR + kg * 8];
*(uint2*)(dst) = make_uint2(D::from_bf16w(v.x), D::from_bf16w(v.y));
*(uint2*)(dst + 4) = make_uint2(D::from_bf16w(v.z), D::from_bf16w(v.w));
} else {
// tr_b128 transposes 16-bit lanes, so each short holds two fp8 from adjacent
// dims; v_perm_b32 splits them into two dim rows.
const uint32_t lo0 = byte_gather(v.x, v.y, 0), lo1 = byte_gather(v.z, v.w, 0);
const uint32_t hi0 = byte_gather(v.x, v.y, 1), hi1 = byte_gather(v.z, v.w, 1);
uint32_t wl[4], wh[4];
fp8x8_to_16x4w<D>(make_uint2(lo0, lo1), wl);
fp8x8_to_16x4w<D>(make_uint2(hi0, hi1), wh);
uint16_t* a0 = &sV16[(d0 + 2 * vj) * VSTR + kg * 8];
uint16_t* a1 = &sV16[(d0 + 2 * vj + 1) * VSTR + kg * 8];
*(uint2*)(a0) = make_uint2(wl[0], wl[1]);
*(uint2*)(a0 + 4) = make_uint2(wl[2], wl[3]);
*(uint2*)(a1) = make_uint2(wh[0], wh[1]);
*(uint2*)(a1 + 4) = make_uint2(wh[2], wh[3]);
}
}
}
};
// Tile ti's block-table entries are loaded during tile ti-1, off the KV address chain.
// A multi-block tile can run past the sequence's last block (on the last row, past the end of
// the table). Keys are clamped to ctx - 1, so entries past lastb are never used; only tiles
// reaching past lastb take the clamped load. With NB == 1 the test folds away.
const int lastb = (ctx - 1) / BS;
auto load_bt = [&](int t0, int* out) {
if (NB > 1 && t0 + NB - 1 > lastb) {
#pragma unroll
for (int i = 0; i < NB; ++i) out[i] = bt[min(t0 + i, lastb)];
} else {
#pragma unroll
for (int i = 0; i < NB; ++i) out[i] = bt[t0 + i];
}
};
int blk[NB];
if (BTS) load_bt(tstart * NB, blk);
if (GPREV) fetchV(tstart * TILE, blk);
for (int ti = tstart; ti < ntiles; ++ti) {
const int k0 = ti * TILE;
int blkn[NB];
if (BTS && ti + 1 < ntiles) {
load_bt((ti + 1) * NB, blkn);
}
if (LDSB) lds_barrier(); else __syncthreads();
fetchK(k0, blk);
if (!GPREV) fetchV(k0, blk);
storeV(); // V first: already in registers, so it covers K's load latency
storeK();
if (LDSB) lds_barrier(); else __syncthreads();
// Issue the next tile's V loads before the WMMAs below; they are consumed after the next
// barrier.
if (GPREV && ti + 1 < ntiles) fetchV(k0 + TILE, blkn);
#pragma unroll 1
for (int mt = 0; mt < MT; ++mt) {
v8f s = (v8f){0,0,0,0,0,0,0,0};
{
const uint16_t* krow = &sK[(mt * 16 + c) * KSTR] + (CTG ? 8 * h : 0);
// Load PF fragments before issuing their WMMAs, so each WMMA waits on
// s_wait_dscnt PF-1 instead of a full drain.
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
frag16 kb[PF];
#pragma unroll
for (int j = 0; j < PF; ++j) {
const uint16_t* kp = krow + 16 * (g + j);
if (CTG) {
const uint4 u = *(const uint4*)kp;
kb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
} else {
kb[j] = D::mk(*(const uint2*)(kp + 4 * h),
*(const uint2*)(kp + 8 + 4 * h));
}
}
if (SGB) sched_barrier();
#pragma unroll
for (int j = 0; j < PF; ++j) s = D::wmma(kb[j], qf[g + j], s);
}
}
float sc[8];
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul;
const int kbase = k0 + mt * 16 + 8 * h;
// Mask keys past klimit and, with WIN, before wlo. MSKIP skips tiles straddling neither.
if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) {
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo))
? sc[e] : -INFINITY;
}
float smax = sc[0];
#pragma unroll
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
if (wave_any(smax > m_ref + PGROW)) {
const float rmax = fmaxf(smax, swap16(smax));
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
const float alpha = ex2(m_ref - mnew);
#pragma unroll
for (int dt = 0; dt < NKS; ++dt)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[dt][e] *= alpha;
l_i *= alpha;
m_ref = mnew;
off = PSHIFT - mnew;
}
float pf[8], lsum = 0.0f;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const float p = ex2(sc[e] + off);
pf[e] = p;
if (!DOT2) lsum += p;
}
if (!DOT2) l_i += lsum;
{
uint32_t pw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2) pw[e >> 1] = D::pk(pf[e], pf[e + 1]);
if (DOT2) {
const v2hf one = {(__fp16)1.0f, (__fp16)1.0f};
#pragma unroll
for (int e = 0; e < 4; ++e)
l_i = __builtin_amdgcn_fdot2(__builtin_bit_cast(v2hf, pw[e]), one, l_i, false);
}
const uint2 lo = make_uint2(pw[0], pw[1]);
const uint2 hi2 = make_uint2(pw[2], pw[3]);
// QK leaves lane (c,h) holding keys 8h+e. Under CONTIG that is already the B
// fragment; the split map needs a cross-half exchange.
frag16 p16;
if (CTG) {
p16 = D::mk(lo, hi2);
} else {
const uint2 y = swap16_u2p((h == 0) ? hi2 : lo);
p16 = (h == 0) ? D::mk(lo, y) : D::mk(y, hi2);
}
const uint16_t* vbase = &sV16[c * VSTR + mt * 16] + (CTG ? 8 * h : 0);
#pragma unroll
for (int g = 0; g < NKS; g += PF) {
frag16 vb[PF];
#pragma unroll
for (int j = 0; j < PF; ++j) {
const uint16_t* vp = vbase + (g + j) * 16 * VSTR;
if (CTG) {
const uint4 u = *(const uint4*)vp;
vb[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
} else {
vb[j] = D::mk(*(const uint2*)(vp + 4 * h),
*(const uint2*)(vp + 8 + 4 * h));
}
}
if (SGB) sched_barrier();
#pragma unroll
for (int j = 0; j < PF; ++j) acc[g + j] = D::wmma(vb[j], p16, acc[g + j]);
}
}
}
if (BTS) {
#pragma unroll
for (int i = 0; i < NB; ++i) blk[i] = blkn[i];
}
}
if (!live) return;
l_i += swap16(l_i);
const float inv = (l_i > 0.0f) ? (vdesc / l_i) : 0.0f;
uint16_t* op = (uint16_t*)a.out
+ ((size_t)(qoff + qpos) * a.q_heads + qhead) * HEAD_DIM;
#pragma unroll
for (int dt = 0; dt < NKS; ++dt) {
uint32_t tw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2)
tw[e >> 1] = (uint32_t)f32_to_bf16(acc[dt][e] * inv)
| ((uint32_t)f32_to_bf16(acc[dt][e + 1] * inv) << 16);
*(uint4*)(op + dt * 16 + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]);
}
}