radiance 1.6.0

- Qwen-Image 2.1 and 2.1 Turbo: text to image and image edits over OpenAI's images API,
  /v1/images/generations and /v1/images/edits. An edit takes up to ten pictures and an optional
  mask, outside which the picture comes back exactly as it was; `background: transparent`, png,
  jpeg and webp output, `n` pictures from one prompt, streamed previews (`partial_images`), and
  vLLM-Omni's seed, negative_prompt with true_cfg_scale, num_inference_steps, width and height.
  arch/qwenimage21 serves the diffusers pipeline directory, converted with
  data/recipes/qwen-image-2.1-fp8.recipe (block fp8) or qwen-image-2.1-bf16.recipe.
  deploy/compose/qwen-image-2.1.yaml and qwen-image-2.1-turbo.yaml serve the fp8 containers on
  two cards. Two R9700s make a 2048x2048 picture in 61 s at the base model's 40 steps and in
  13 s with Turbo (56 and 12 s with --tp-wire wht6), a 1024x1024 one in 6.0 and 2.6 s. The
  models are under Qwen's research license, which is non-commercial
- an image generator is a program kind of its own (core/gen): an architecture declares its
  conditioning, denoising and decoding passes, and the driver runs the schedule, the pictures of
  a batch and the conditioning cache. An image model's /v1/models entry is its generator's name
  (qwen-image-2.1, qwen-image-2.1-turbo), and its capabilities and startup banner list only the
  images endpoints
- the tiled prefill GEMMs run their tiles in groups of activation bands, 16 for fp8 and 8 for
  bf16, so an operand larger than the 64 MB cache is read once a group instead of once a band. A
  bf16 GEMM with more than 64 MB of weight runs up to twice as fast
- fixed: a second lane opened in the middle of a step started beside work lane 0 had not
  finished. Gemma 4 26B-A4B opens its lane that way, so its first step after startup could read
  rows not yet written
- startup no longer warns about --checkpoint-slots when it was not passed, nor about an expert
  floor on a model with no experts
- the image's FFmpeg writes png, jpeg and webp (libwebp)
- for out-of-tree plugins: RAD_ABI_VERSION is 16. The op vocabulary gains the image generator's
  ops (conv2d_nhwc, ln_mod, ln_mod_quant_fp8, flow_euler, attn_prefix_self and others; docs/OPS.md,
  "Image generation"), and all_reduce takes an optional `overlap`. Plugins built against 1.5.0
  must be rebuilt
This commit is contained in:
Deadcode committed 2026-10-14 14:03:59 +02:00
1 parent b93b531f63
commit b068190326
66 files changed
+9035 -87

No files matched your search

+5
View File
@@ -81,6 +81,11 @@ set(R4D_UNITS
# the small ops around it: act_mul, seg_mean, qk_norm_rope with a v norm, the f32 widening.
"r4d_attn_dense_bf16|"
"r4d_encoder_bf16|"
# The image generator: attention over a paged prefix and the pass's own rows, the causal
# head_dim-128 dense form and the 1152-wide decoder head; and the sampler, adaptive norm,
# implicit-GEMM convolution and pixel ops around them.
"r4d_attn_gen|"
"r4d_gen|"
# The vision tower's own small ops: layer norm, the learned-grid position embedding, and the
# biased GEMM with a linear layer's activation and residual in its store.
"r4d_vit_bf16|"
+770
View File
@@ -0,0 +1,770 @@
// R4D attention over a paged prefix and the pass's own rows (attn_prefix_self), and the causal
// dense attention a text encoder's prompt pass needs (attn_dense, causal 1, head_dim 128).
//
// THE KERNEL IS THE DENSE ONE (r4d_attn_dense_bf16.hip) WITH A SECOND KEY SOURCE. S^T = K.Q^T, so a
// lane owns one query row and its softmax state, the C fragment of S^T is the B fragment the P.V
// matmul wants, and P never goes through LDS. A workgroup owns one KV head and every query head
// that reads it. What is new:
//
// THE PREFIX. A sequence's first `used[s]` keys are in the paged cache -- [blocks, kv_heads, 16,
// 2 * HD], K then V in a slot -- and its own rows' keys are dense, beside the queries. The key
// loop walks the prefix tiles first and then the own tiles; a tile is one source or the other,
// and its rows are fetched through that source's address rule. Every prefix key is visible.
//
// CAUSAL OWN KEYS. With `causal` a query sees its own rows up to itself: a text segment of a
// conditioning sequence, and the text encoder's prompt. A tile wholly below every query of the
// workgroup pays no test.
//
// bf16 operands (DT16<0>): a diffusion transformer's values carry outliers an f16 operand could
// overflow, and the reference takes P to bf16 for its P.V product too (rounded there, truncated
// here -- see the softmax).
//
// THE INT8 Q.K FORM (`I8`, the op's `k_i8` operand present). The score product runs on
// v_wmma_i32_16x16x16_iu8, which issues in half the cycles of the bf16 one; P.V stays bf16. Every
// code is quant_act_i8g's: a scale per (row, head) of amax / 127 (1 for an all-zero row) and a code
// rint(x * (1 / scale)) clamped to +-127. The own rows' keys arrive quantised that way (k_i8 and
// k_scale, one op ahead of this one), the query is quantised here once a workgroup, and a prefix
// tile is quantised as it is staged -- the prefix is a picture's conditioning, a few hundred rows
// against the thousands of own rows. A score is (q . k) * qs * ks, the integer dot product exact.
// At a DiT's 16384 rows this takes the kernel from 38 to about 32 ms; against the bf16 form the
// picture moves by less than swapping between exact attention implementations moves it.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_dt16.h"
#include <cmath>
#include <type_traits>
typedef int v2i_ps __attribute__((ext_vector_type(2)));
typedef int v8i_ps __attribute__((ext_vector_type(8)));
/* quant_act_i8g's scale and codes for eight values against `inv` = 1 / scale. */
__device__ __forceinline__ uint32_t ps_q8x4(float a, float b, float c, float d, float inv) {
auto q = [inv](float x) {
return (uint32_t)((int)rintf(fminf(fmaxf(x * inv, -127.0f), 127.0f)) & 0xff);
};
return q(a) | (q(b) << 8) | (q(c) << 16) | (q(d) << 24);
}
__device__ __forceinline__ float ps_lo(uint32_t w) { return __builtin_bit_cast(float, w << 16); }
__device__ __forceinline__ float ps_hi(uint32_t w) { return __builtin_bit_cast(float, w & 0xffff0000u); }
__device__ __forceinline__ float ps_amax8(uint4 u) {
return fmaxf(fmaxf(fmaxf(fabsf(ps_lo(u.x)), fabsf(ps_hi(u.x))),
fmaxf(fabsf(ps_lo(u.y)), fabsf(ps_hi(u.y)))),
fmaxf(fmaxf(fabsf(ps_lo(u.z)), fabsf(ps_hi(u.z))),
fmaxf(fabsf(ps_lo(u.w)), fabsf(ps_hi(u.w)))));
}
__device__ __forceinline__ uint2 ps_q8x8(uint4 u, float inv) {
return make_uint2(ps_q8x4(ps_lo(u.x), ps_hi(u.x), ps_lo(u.y), ps_hi(u.y), inv),
ps_q8x4(ps_lo(u.z), ps_hi(u.z), ps_lo(u.w), ps_hi(u.w), inv));
}
template<int HD, int GQA, int NQB, int TILE, bool I8>
__global__ __launch_bounds__(NQB * GQA * 32)
void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const int8_t* __restrict__ gk8, const float* __restrict__ gks,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, int num_seqs, const int* __restrict__ used,
const int* __restrict__ bt, int bt_pitch,
const uint16_t* __restrict__ kvc, int kv_heads,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
int v_ld, int o_ld)
{
typedef DT16<0> D;
typedef D::frag frag16;
typedef typename std::conditional<I8, v2i_ps, frag16>::type qfrag;
constexpr int NWARPS = NQB * GQA;
constexpr int NTHR = NWARPS * 32;
constexpr int BQ = NQB * 16;
constexpr int NKS = HD / 16;
constexpr int MT = TILE / 16;
constexpr int KSTR = HD + 8;
constexpr int VSTR = TILE + 8;
constexpr int DG = HD / 8;
constexpr int KGRP = TILE / 8;
constexpr int KITEMS = TILE * DG;
constexpr int KP = (KITEMS + NTHR - 1) / NTHR;
constexpr int NTR = KGRP * DG;
constexpr int LGRP = NTHR / 8;
constexpr int VP = (NTR + LGRP - 1) / LGRP;
constexpr float GROW = D::GROW;
constexpr int BS = 16; // the paged block, libr4d's (block_size == 16)
static_assert(HD % 16 == 0 && TILE % 16 == 0, "geometry");
// THE INT8 KEY TILE: a key's row is HD bytes, padded by 8 so the sixteen rows a fragment read
// touches land on distinct bank pairs (34 dwords a row), and written as 8-byte halves because
// the padding leaves odd rows 8-byte aligned. A prefix tile's key is DG lanes of 8 dims each,
// which is why those lanes must sit in one half-wave for the row's absolute maximum.
constexpr int KSTR8 = HD + 8;
constexpr int K8G = HD / 16; // 16-byte pieces of an own key's row
constexpr int K8P = (TILE * K8G + NTHR - 1) / NTHR;
static_assert(!I8 || (DG == 16 && NTHR % 32 == 0), "an int8 prefix key is one half-wave");
__shared__ __align__(16) uint16_t sK[I8 ? 8 : TILE * KSTR];
__shared__ __align__(16) int8_t sK8[I8 ? TILE * KSTR8 : 16];
__shared__ __align__(16) float sKs[I8 ? TILE : 4];
__shared__ __align__(16) uint16_t sV[HD * VSTR];
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5;
const int c = lane & 15, h = lane >> 4;
const int g = warp % GQA;
const int qbi = warp / GQA;
const int kvh = blockIdx.y;
const int hq = kvh * GQA + g;
// THE GRID IS FLAT OVER THE SEQUENCES' QUERY BLOCKS: block b is the b-th BQ-row block counting
// through every sequence in order, so a pass of many equal sequences launches what it needs
// rather than (longest sequence) x (sequences). A handful of sequences, so a walk.
int seq = -1, q0 = 0;
for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) {
const int nb = (cu[s + 1] - cu[s] + BQ - 1) / BQ;
if (b < nb) { seq = s; q0 = b * BQ; break; }
b -= nb;
}
if (seq < 0) return;
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
if (slen <= 0 || q0 >= slen) return;
const int qlast = min(q0 + BQ, slen) - 1;
const int P = used ? used[seq] : 0;
const int ke = causal ? qlast + 1 : slen; // own keys any query here can see
const float mul = scale * 1.44269504089f;
const int qpos = q0 + qbi * 16 + c;
const bool live = qpos < slen;
// The query: bf16 fragments pre-multiplied by the softmax scale, or int8 codes against its
// row's absolute maximum -- a lane holds half the head's dims, the lane 16 away the other half
// -- with the scale carried in `qs` and applied to the integer score.
qfrag qf[NKS];
float qs = mul;
{
const int qrow = live ? qpos : slen - 1;
const uint16_t* qp = gq + (long)(s0 + qrow) * q_ld + (long)hq * HD;
if constexpr (I8) {
uint4 qu[NKS];
float am = 0.0f;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
qu[t] = *(const uint4*)(qp + 16 * t + 8 * h);
am = fmaxf(am, ps_amax8(qu[t]));
}
am = fmaxf(am, swap16(am));
const float sq = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
const float inv = 1.0f / sq;
qs = sq * mul;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
const uint2 w = ps_q8x8(qu[t], inv);
qf[t] = (v2i_ps){ (int)w.x, (int)w.y };
}
} else {
#pragma unroll
for (int t = 0; t < NKS; ++t) {
const uint4 u = *(const uint4*)(qp + 16 * t + 8 * h);
auto cv = [&](uint32_t w) {
return D::pk(__builtin_bit_cast(float, w << 16) * mul,
__builtin_bit_cast(float, w & 0xffff0000u) * mul);
};
qf[t] = D::mk(make_uint2(cv(u.x), cv(u.y)), make_uint2(cv(u.z), cv(u.w)));
}
}
}
float m_ref = -3.0e38f, soff = 3.0e38f, 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 vj = tid & 7, lgi = tid >> 3;
const uint16_t* kbase = gk + (long)kvh * HD;
const uint16_t* vbase = gv + (long)kvh * HD;
const int* btrow = bt ? bt + (long)seq * bt_pitch : nullptr;
// The K row of key `kk` of the current source; its V row is `vrow`.
auto krow = [&](bool pre, int kk) -> const uint16_t* {
if (!pre) return kbase + (long)(s0 + kk) * k_ld;
const int blk = btrow[kk / BS];
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD);
};
auto vrow = [&](bool pre, int kk) -> const uint16_t* {
if (!pre) return vbase + (long)(s0 + kk) * v_ld;
const int blk = btrow[kk / BS];
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD;
};
const int ntp = (P + TILE - 1) / TILE, nts = (ke + TILE - 1) / TILE;
for (int ti = 0; ti < ntp + nts; ++ti) {
const bool pre = ti < ntp;
const int k0 = pre ? ti * TILE : (ti - ntp) * TILE;
const int klim = pre ? P : ke;
const bool mask = (k0 + TILE > klim) || (!pre && causal && k0 + TILE - 1 > q0);
// An own tile in the int8 form is K8P 16-byte pieces a thread and a scale for the first
// TILE threads; anything else is the bf16 rows (a prefix tile quantised below).
const bool own8 = I8 && !pre;
uint4 kr[KP], vr[VP];
float ksr = 0.0f;
if (own8) {
#pragma unroll
for (int p = 0; p < K8P; ++p) {
const int i = tid + p * NTHR;
if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) {
const int key = i / K8G, gg = i % K8G;
const int kk = (k0 + key < klim) ? k0 + key : klim - 1;
kr[p] = *(const uint4*)(gk8 + (long)(s0 + kk) * k8_ld + (long)kvh * HD + gg * 16);
}
}
if (tid < TILE) {
const int kk = (k0 + tid < klim) ? k0 + tid : klim - 1;
ksr = gks[(long)(s0 + kk) * ks_ld + kvh];
}
} else {
#pragma unroll
for (int p = 0; p < KP; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
const int key = i / DG, gg = i % DG;
const int kk = (k0 + key < klim) ? k0 + key : klim - 1;
kr[p] = *(const uint4*)(krow(pre, kk) + gg * 8);
}
}
}
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
const int kk0 = k0 + kg * 8 + vj;
const int kk = (kk0 < klim) ? kk0 : klim - 1;
vr[r] = __builtin_bit_cast(uint4, load_tr_b128(vrow(pre, kk) + dg * 8));
}
}
// A prefix key in the int8 form: its row's maximum across the DG lanes that hold it (one
// half-wave, so a DPP butterfly), then its eight codes a lane.
uint2 kq[KP];
float kqs[KP];
if (I8 && pre) {
#pragma unroll
for (int p = 0; p < KP; ++p) {
float am = ps_amax8(kr[p]);
am = fmaxf(am, r4d_xor_lane<8>(am));
am = fmaxf(am, r4d_xor_lane<4>(am));
am = fmaxf(am, r4d_xor_lane<2>(am));
am = fmaxf(am, r4d_xor_lane<1>(am));
kqs[p] = am > 0.0f ? am * (1.0f / 127.0f) : 1.0f;
kq[p] = ps_q8x8(kr[p], 1.0f / kqs[p]);
}
}
lds_barrier();
#pragma unroll
for (int r = 0; r < VP; ++r) {
const int u = lgi + r * LGRP;
if (NTR % LGRP == 0 || u < NTR) {
const int kg = u % KGRP, dg = u / KGRP;
*(uint4*)&sV[(dg * 8 + vj) * VSTR + kg * 8] = vr[r];
}
}
if constexpr (I8) {
if (!pre) {
#pragma unroll
for (int p = 0; p < K8P; ++p) {
const int i = tid + p * NTHR;
if ((TILE * K8G) % NTHR == 0 || i < TILE * K8G) {
int8_t* d = &sK8[(i / K8G) * KSTR8 + (i % K8G) * 16];
*(uint2*)d = make_uint2(kr[p].x, kr[p].y);
*(uint2*)(d + 8) = make_uint2(kr[p].z, kr[p].w);
}
}
if (tid < TILE) sKs[tid] = ksr;
} else {
#pragma unroll
for (int p = 0; p < KP; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS) {
*(uint2*)&sK8[(i / DG) * KSTR8 + (i % DG) * 8] = kq[p];
if (i % DG == 0) sKs[i / DG] = kqs[p];
}
}
}
} else {
#pragma unroll
for (int p = 0; p < KP; ++p) {
const int i = tid + p * NTHR;
if (KITEMS % NTHR == 0 || i < KITEMS)
*(uint4*)&sK[(i / DG) * KSTR + (i % DG) * 8] = kr[p];
}
}
lds_barrier();
#pragma unroll 1
for (int mt = 0; mt < MT; ++mt) {
// The scores of 16 keys, in log2 units once times `qs` (a no-op 1 for bf16, whose
// query carries the scale already).
float sc[8];
if constexpr (I8) {
v8i_ps si = (v8i_ps){0, 0, 0, 0, 0, 0, 0, 0};
const int8_t* kr2 = &sK8[(mt * 16 + c) * KSTR8] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
v2i_ps kf[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) {
const uint2 u = *(const uint2*)(kr2 + 16 * (t0 + j));
kf[j] = (v2i_ps){ (int)u.x, (int)u.y };
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS)
si = __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(true, kf[j], true,
qf[t0 + j], si, false);
}
const float4 ka = *(const float4*)&sKs[mt * 16 + 8 * h];
const float4 kb = *(const float4*)&sKs[mt * 16 + 8 * h + 4];
const float ks[8] = { ka.x, ka.y, ka.z, ka.w, kb.x, kb.y, kb.z, kb.w };
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = (float)si[e] * ks[e];
} else {
v8f s = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
const uint16_t* kr2 = &sK[(mt * 16 + c) * KSTR] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
frag16 kf[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) {
const uint4 u = *(const uint4*)(kr2 + 16 * (t0 + j));
kf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) s = D::wmma(kf[j], qf[t0 + j], s);
}
#pragma unroll
for (int e = 0; e < 8; ++e) sc[e] = s[e];
}
if (mask) {
const int kq0 = k0 + mt * 16 + 8 * h;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int key = kq0 + e;
const bool ok = key < klim && (pre || !causal || key <= qpos);
sc[e] = ok ? sc[e] : -INFINITY;
}
}
// `qs` is positive, so the maximum of the scaled scores is the scaled maximum.
float smax = sc[0];
#pragma unroll
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
if (I8) smax *= qs;
if (wave_any(smax > m_ref + GROW)) {
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 t = 0; t < NKS; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[t][e] *= alpha;
l_i *= alpha;
m_ref = mnew;
soff = -mnew;
}
// P TO BF16 BY TRUNCATION: one v_perm a pair where gfx1201's software round-to-nearest
// is about six VALU a value, on a path where the WMMA and the VALU share the SIMD
// (4-7% of the kernel at a DiT's 16384 rows). Its error is the rounding's in size, and
// its downward bias cancels: the row sum below is taken off the same truncated values.
uint32_t pw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2) {
const float a0 = I8 ? __builtin_fmaf(sc[e], qs, soff) : sc[e] + soff;
const float a1 = I8 ? __builtin_fmaf(sc[e + 1], qs, soff) : sc[e + 1] + soff;
const uint32_t lo = __builtin_bit_cast(uint32_t, ex2(a0));
const uint32_t hi = __builtin_bit_cast(uint32_t, ex2(a1));
pw[e >> 1] = __builtin_amdgcn_perm(hi, lo, 0x07060302u);
}
// The row sum off the packed P, so the denominator is the values P.V used.
#pragma unroll
for (int e = 0; e < 4; ++e)
l_i += __builtin_bit_cast(float, pw[e] << 16) +
__builtin_bit_cast(float, pw[e] & 0xffff0000u);
const frag16 p16 = D::mk(make_uint2(pw[0], pw[1]), make_uint2(pw[2], pw[3]));
{
const uint16_t* vr2 = &sV[c * VSTR + mt * 16] + 8 * h;
#pragma unroll
for (int t0 = 0; t0 < NKS; t0 += 4) {
frag16 vf[4];
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) {
const uint4 u = *(const uint4*)(vr2 + (t0 + j) * 16 * VSTR);
vf[j] = D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w));
}
sched_barrier();
#pragma unroll
for (int j = 0; j < 4; ++j)
if (t0 + j < NKS) acc[t0 + j] = D::wmma(vf[j], p16, acc[t0 + j]);
}
}
}
}
if (!live) return;
const float ls = l_i + swap16(l_i);
const float inv = (ls > 0.0f) ? (1.0f / ls) : 0.0f;
uint16_t* op = go + (long)(s0 + qpos) * o_ld + (long)hq * HD;
#pragma unroll
for (int t = 0; t < NKS; ++t) {
uint32_t tw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2)
tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv)
| ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16);
*(uint4*)(op + t * 16 + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]);
}
}
template<int HD, int GQA, int NQB, int TILE, bool I8>
static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, const float* ks,
const void* v, void* o, const int* cu,
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head_kv, float scale, int causal,
int q_ld, int k_ld, int k8_ld, int ks_ld, int v_ld, int o_ld,
hipStream_t s)
{
constexpr int BQ = NQB * 16;
// Every sequence's blocks: at most total / BQ, plus one partial block a sequence.
dim3 grid((max_q + BQ - 1) / BQ + num_seqs, n_head_kv, 1);
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8>), grid, dim3(NQB * GQA * 32), 0, s,
(const uint16_t*)q, (const uint16_t*)k, (const int8_t*)k8, ks,
(const uint16_t*)v, (uint16_t*)o, cu, num_seqs, used, bt, bt_pitch,
(const uint16_t*)kvc, n_head_kv, scale, causal, q_ld, k_ld, k8_ld, ks_ld,
v_ld, o_ld);
const hipError_t e = hipGetLastError();
return e == hipSuccess ? 0 : -100 - (int)e;
}
/* head_dim 128 at gqa 1, 2, 4 and 8. `used`/`bt`/`kvc` null is no prefix: the dense form. `max_q`
* is the query rows of every sequence together, which bounds the flat grid. `k8` non-null is the
* int8 Q.K form -- the own keys as int8 codes (`k8_ld` bytes a row) with a scale per (row, head)
* in `ks` (`ks_ld` floats a row) -- at gqa 1, the only ratio a DiT has. */
static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float* ks,
const void* v, void* o, const int* cu,
const int* used, const int* bt, int bt_pitch, const void* kvc,
int num_seqs, int max_q, int n_head, int n_head_kv, int head_dim,
float scale, int causal, int q_ld, int k_ld, int k8_ld, int ks_ld,
int v_ld, int o_ld, hipStream_t s)
{
if (n_head <= 0 || n_head_kv <= 0 || n_head % n_head_kv) return -2;
if ((q_ld | k_ld | v_ld | o_ld) & 7) return -3;
if (k8 && ((k8_ld & 15) || ((uintptr_t)k8 & 15) || !ks)) return -3;
if (num_seqs <= 0 || max_q <= 0) return 0;
const int gqa = n_head / n_head_kv;
if (head_dim != 128) return -1;
#define R4D_PS(G, NQB, T, I8) \
return r4d_attn_ps_launch<128, G, NQB, T, I8>(q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, \
num_seqs, max_q, n_head_kv, scale, causal, \
q_ld, k_ld, k8_ld, ks_ld, v_ld, o_ld, s)
/* SIXTEEN QUERY TILES A WORKGROUP at gqa 1: a workgroup streams its head's whole K and V once,
* so the rows it serves divide that traffic. At a DiT's 16384 rows a head's K and V are 8 MB
* and fall out of L2; 128 rows a workgroup ran at 66 TFLOP/s, 256 at 111, 512 at 102. */
if (k8) {
if (gqa != 1) return -1;
R4D_PS(1, 16, 64, true);
}
switch (gqa) {
case 1: R4D_PS(1, 16, 64, false);
case 2: R4D_PS(2, 4, 64, false);
case 4: R4D_PS(4, 2, 64, false);
case 8: R4D_PS(8, 1, 64, false);
default: return -1;
}
#undef R4D_PS
}
// ============================================================== the plugin ABI entry points
/* [tokens, heads * head_dim] (or rank 3) at the operand's own row pitch. */
static bool ps_rows(const RadTensor* t, long long head_dim, long long* n_tok, long long* n_head,
long long* ld) {
long long width = 1;
for (uint32_t i = 1; i < t->rank; ++i) width *= t->shape[i];
if (t->rank < 2 || width % head_dim) return false;
*n_head = width / head_dim;
*ld = r4d_rows_pitch(t, width, n_tok);
return *ld >= 0;
}
enum { PS_Q = 0, PS_K, PS_V, PS_KV, PS_BT, PS_USED, PS_CU, PS_KDES, PS_VDES, PS_K8, PS_KS,
PS_OUT };
extern "C" int r4d_rad_attn_prefix_self(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, PS_Q);
const RadTensor* k = r4d_opt(a, PS_K);
const RadTensor* v = r4d_opt(a, PS_V);
const RadTensor* kv = r4d_opt(a, PS_KV);
const RadTensor* bt = r4d_opt(a, PS_BT);
const RadTensor* su = r4d_opt(a, PS_USED);
const RadTensor* cu = r4d_opt(a, PS_CU);
const RadTensor* o = r4d_opt(a, PS_OUT);
if (!q || !k || !v || !kv || !bt || !su || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (r4d_opt(a, PS_KDES) || r4d_opt(a, PS_VDES)) return R4D_NO(RAD_E_UNSUPPORTED);
if (kv->dtype != RAD_BF16 || q->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
if (kv->rank != 4 || kv->shape[2] != 16 || kv->shape[3] != 2 * hd) return R4D_NO(RAD_E_SHAPE);
if (!r4d_contig(cu) || !r4d_contig(su) || cu->rank != 1 || cu->shape[0] < 2)
return R4D_NO(RAD_E_SHAPE);
const int num_seqs = (int)(cu->shape[0] - 1);
if (r4d_numel(su) < num_seqs) return R4D_NO(RAD_E_SHAPE);
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
long long to = 0, ho = 0, o_ld = 0;
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != hv || ho != nh || hk * gqa != nh || hk != kv->shape[1]) return R4D_NO(RAD_E_SHAPE);
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
const long long bt_pitch = bt->rank >= 2 ? bt->shape[1] : r4d_numel(bt) / num_seqs;
if (bt->rank >= 2 && bt->stride[1] != 1) return R4D_NO(RAD_E_STRIDE);
const long long mq = total;
/* THE INT8 Q.K FORM (`qk` "i8"): the own keys' codes [tokens, kv_heads * head_dim] and their
* scales [tokens, kv_heads], as quant_act_i8g writes them at group head_dim. */
const RadTensor* k8 = r4d_opt(a, PS_K8);
const RadTensor* ks = r4d_opt(a, PS_KS);
const char* qk = r4d_gets(a, "qk");
const bool i8 = qk && !std::strcmp(qk, "i8");
if (qk && !i8 && std::strcmp(qk, "bf16")) return R4D_NO(RAD_E_INVAL);
if (i8 != (k8 != nullptr) || i8 != (ks != nullptr)) return R4D_NO(RAD_E_INVAL);
long long k8_ld = 0, ks_ld = 0;
if (k8) {
if (k8->dtype != RAD_I8 || ks->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
long long t8 = 0, h8 = 0, ts = 0;
if (!ps_rows(k8, hd, &t8, &h8, &k8_ld)) return R4D_NO(RAD_E_STRIDE);
ks_ld = r4d_rows_pitch(ks, hk, &ts);
if (ks_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (h8 != hk || t8 < total || ts < total) return R4D_NO(RAD_E_SHAPE);
}
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
const int e = r4d_attn_ps(q->data, k->data, k8 ? k8->data : nullptr,
ks ? (const float*)ks->data : nullptr, v->data, o->data,
(const int*)cu->data, (const int*)su->data, (const int*)bt->data,
(int)bt_pitch, kv->data, num_seqs, (int)mq, (int)nh, (int)hk, (int)hd,
scale, (int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld,
(int)k8_ld, (int)ks_ld, (int)v_ld, (int)o_ld, (hipStream_t)s);
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
/* attn_dense at head_dim 128, causal or not: the same kernel with no prefix. */
extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, 0);
const RadTensor* k = r4d_opt(a, 1);
const RadTensor* v = r4d_opt(a, 2);
const RadTensor* cu = r4d_opt(a, 3);
const RadTensor* o = r4d_opt(a, 4);
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
const long long hd = r4d_geti_or(a, "head_dim", 0), gqa = r4d_geti_or(a, "gqa", 1);
if (hd != 128 || gqa <= 0) return R4D_NO(RAD_E_SHAPE);
if (r4d_geti_or(a, "window", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED);
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
long long to = 0, ho = 0, o_ld = 0;
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != hv || ho != nh || hk * gqa != nh) return R4D_NO(RAD_E_SHAPE);
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
const int num_seqs = (int)(cu->shape[0] - 1);
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
const int e = r4d_attn_ps(q->data, k->data, nullptr, nullptr, v->data, o->data,
(const int*)cu->data, nullptr, nullptr, 0, nullptr, num_seqs,
(int)total, (int)nh, (int)hk, (int)hd, scale,
(int)r4d_geti_or(a, "causal", 0), (int)q_ld, (int)k_ld, 0, 0,
(int)v_ld, (int)o_ld, (hipStream_t)s);
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
return e == 0 ? RAD_OK : R4D_NO(e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE);
}
// ============================================================== wide heads (attn_dense, h768 / h1152)
// AN IMAGE DECODER'S MID-BLOCK ATTENTION: one head 1152 wide over every latent pixel -- 16384 rows
// at 2048 x 2048. A lane cannot hold a 1152-wide output row (576 accumulator registers), so the
// head is split across the workgroup's eight waves instead of its rows: a wave owns HD/8 of the
// dims for the whole 16-query block.
//
// S = Q.K^T is contracted in eight pieces, a wave's dims each, and the partial score tiles are
// summed through LDS in wave order -- a fixed order, so the sum is the same every run.
// P is formed once, by sixteen threads (a query row each), rounded to bf16, and its row sum is
// taken off the rounded values, the denominator P.V uses.
// O += P.V is a wave's own dims: V^T fragments straight from global with the transposing load
// (no LDS), P^T from LDS.
//
// S^T = K.Q^T as in the dense kernel above, so a partial tile's C layout is (query = lane % 16,
// key = 8 (lane / 16) + e) and both the reduction and the P^T fragment index it the same way.
template<int HD>
__global__ __launch_bounds__(256)
void r4d_attn_wide_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
const int* __restrict__ cu, int num_seqs, float scale, int q_ld,
int k_ld, int v_ld, int o_ld)
{
typedef DT16<0> D;
constexpr int DW = HD / 8; // dims a wave
constexpr int NS = DW / 16; // its 16-wide steps
constexpr int KT = 64; // keys a tile
constexpr int PP = KT + 8; // P's LDS row pitch, in bf16
static_assert(HD % 128 == 0, "eight waves of whole 16-wide steps");
__shared__ float sPart[8 * KT * 16];
__shared__ float sS[KT * 16];
__shared__ __align__(16) uint16_t sP[16 * PP];
__shared__ float sAlpha[16], sL[16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
const int c = lane & 15, h = lane >> 4;
const int head = blockIdx.y;
int seq = -1, q0 = 0;
for (int s = 0, b = blockIdx.x; s < num_seqs; ++s) {
const int nb = (cu[s + 1] - cu[s] + 15) / 16;
if (b < nb) { seq = s; q0 = b * 16; break; }
b -= nb;
}
if (seq < 0) return;
const int s0 = cu[seq], slen = cu[seq + 1] - s0;
if (slen <= 0 || q0 >= slen) return;
const int d0 = wave * DW;
const uint16_t* qb = gq + (long)head * HD + d0;
const uint16_t* kb = gk + (long)head * HD + d0;
const uint16_t* vb = gv + (long)head * HD + d0;
const float mul = scale * 1.44269504089f;
D::frag qf[NS];
{
const int qr = min(q0 + c, slen - 1);
const uint16_t* p = qb + (long)(s0 + qr) * q_ld + 4 * h;
#pragma unroll
for (int t = 0; t < NS; ++t) {
const uint2 lo = *(const uint2*)(p + 16 * t), hi = *(const uint2*)(p + 16 * t + 8);
qf[t] = D::mk(lo, hi);
}
}
v8f acc[NS];
#pragma unroll
for (int t = 0; t < NS; ++t) acc[t] = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
float m_run = -INFINITY, l_run = 0.0f;
for (int k0 = 0; k0 < slen; k0 += KT) {
// ---- this wave's share of S^T for the tile's four 16-key blocks
#pragma unroll
for (int j = 0; j < KT / 16; ++j) {
v8f sp = (v8f){0, 0, 0, 0, 0, 0, 0, 0};
const int kr = min(k0 + 16 * j + c, slen - 1);
const uint16_t* p = kb + (long)(s0 + kr) * k_ld + 4 * h;
#pragma unroll
for (int t = 0; t < NS; ++t) {
const uint2 lo = *(const uint2*)(p + 16 * t), hi = *(const uint2*)(p + 16 * t + 8);
sp = D::wmma(D::mk(lo, hi), qf[t], sp);
}
#pragma unroll
for (int e = 0; e < 8; ++e) sPart[wave * KT * 16 + (16 * j + 8 * h + e) * 16 + c] = sp[e];
}
__syncthreads();
for (int u = tid; u < KT * 16; u += 256) {
float t = 0.0f;
#pragma unroll
for (int w = 0; w < 8; ++w) t += sPart[w * KT * 16 + u];
sS[u] = t;
}
__syncthreads();
// ---- the softmax, a thread a query row
if (tid < 16) {
const int nk = min(KT, slen - k0);
float mx = m_run;
for (int key = 0; key < nk; ++key) mx = fmaxf(mx, sS[key * 16 + tid] * mul);
const float alpha = ex2(m_run - mx);
float lsum = 0.0f;
for (int key = 0; key < KT; ++key) {
const uint16_t pb = key < nk ? f32_to_bf16(ex2(sS[key * 16 + tid] * mul - mx)) : 0;
sP[tid * PP + key] = pb;
lsum += __builtin_bit_cast(float, (uint32_t)pb << 16);
}
l_run = l_run * alpha + lsum;
m_run = mx;
sAlpha[tid] = alpha;
}
__syncthreads();
// ---- O^T += V^T . P^T over the wave's dims
const float al = sAlpha[c];
#pragma unroll
for (int t = 0; t < NS; ++t)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[t][e] *= al;
#pragma unroll
for (int ks = 0; ks < KT / 16; ++ks) {
const uint4 pu = *(const uint4*)&sP[c * PP + 16 * ks + 8 * h];
const D::frag pf = D::mk(make_uint2(pu.x, pu.y), make_uint2(pu.z, pu.w));
const int kr = min(k0 + 16 * ks + 8 * h + (lane & 7), slen - 1);
const uint16_t* vp = vb + (long)(s0 + kr) * v_ld + 8 * ((lane >> 3) & 1);
#pragma unroll
for (int t = 0; t < NS; ++t) {
const uint4 u = __builtin_bit_cast(uint4, load_tr_b128(vp + 16 * t));
acc[t] = D::wmma(D::mk(make_uint2(u.x, u.y), make_uint2(u.z, u.w)), pf, acc[t]);
}
}
}
if (tid < 16) sL[tid] = l_run;
__syncthreads();
if (q0 + c >= slen) return;
const float inv = sL[c] > 0.0f ? 1.0f / sL[c] : 0.0f;
uint16_t* op = go + (long)(s0 + q0 + c) * o_ld + (long)head * HD + d0;
#pragma unroll
for (int t = 0; t < NS; ++t) {
uint32_t tw[4];
#pragma unroll
for (int e = 0; e < 8; e += 2)
tw[e >> 1] = (uint32_t)f32_to_bf16(acc[t][e] * inv)
| ((uint32_t)f32_to_bf16(acc[t][e + 1] * inv) << 16);
*(uint4*)(op + 16 * t + 8 * h) = make_uint4(tw[0], tw[1], tw[2], tw[3]);
}
}
/* attn_dense at head_dim 768 or 1152 (an image encoder's and decoder's mid block), one query head a
* KV head, bidirectional. */
extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
const RadTensor* q = r4d_opt(a, 0);
const RadTensor* k = r4d_opt(a, 1);
const RadTensor* v = r4d_opt(a, 2);
const RadTensor* cu = r4d_opt(a, 3);
const RadTensor* o = r4d_opt(a, 4);
if (!q || !k || !v || !cu || !o) return R4D_NO(RAD_E_INVAL);
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2) return R4D_NO(RAD_E_SHAPE);
const long long hd = r4d_geti_or(a, "head_dim", 0);
if ((hd != 768 && hd != 1152) || r4d_geti_or(a, "gqa", 1) != 1 || r4d_geti_or(a, "causal", 0) != 0 ||
r4d_geti_or(a, "window", 0) != 0)
return R4D_NO(RAD_E_UNSUPPORTED);
long long total = 0, nh = 0, q_ld = 0, tk = 0, hk = 0, k_ld = 0, tv = 0, hv = 0, v_ld = 0;
long long to = 0, ho = 0, o_ld = 0;
if (!ps_rows(q, hd, &total, &nh, &q_ld) || !ps_rows(k, hd, &tk, &hk, &k_ld) ||
!ps_rows(v, hd, &tv, &hv, &v_ld) || !ps_rows(o, hd, &to, &ho, &o_ld))
return R4D_NO(RAD_E_STRIDE);
if (hk != nh || hv != nh || ho != nh) return R4D_NO(RAD_E_SHAPE);
if (tk < total || tv < total || to < total) return R4D_NO(RAD_E_SHAPE);
if ((q_ld | k_ld | v_ld | o_ld) & 7) return R4D_NO(RAD_E_STRIDE);
const int num_seqs = (int)(cu->shape[0] - 1);
const float scale = (float)r4d_getf(a, "scale", 1.0 / std::sqrt((double)hd));
dim3 grid((unsigned)((total + 15) / 16 + num_seqs), (unsigned)nh);
#define R4D_WIDE(HD) \
hipLaunchKernelGGL((r4d_attn_wide_kernel<HD>), grid, dim3(256), 0, (hipStream_t)s, \
(const uint16_t*)q->data, (const uint16_t*)k->data, \
(const uint16_t*)v->data, (uint16_t*)o->data, (const int*)cu->data, \
num_seqs, scale, (int)q_ld, (int)k_ld, (int)v_ld, (int)o_ld)
if (hd == 768) R4D_WIDE(768);
else R4D_WIDE(1152);
#undef R4D_WIDE
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+61 -9
View File
@@ -222,11 +222,19 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel(
// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains,
// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot`
// are normed only; a v head (v_norm) is normed at unit gain.
//
// `pm` picks the pairing, which is all that separates three rotaries over the same table:
// 0 blocks a section's pairs are (start + j, start + sec + j), its own ladder
// 1 gptj_blocks a section's pairs are ADJACENT, (start + 2j, start + 2j + 1), its own ladder:
// the complex-number form of a 3-axis image rotary (Qwen-Image)
// 2 imrope NeoX pairs (i, i + rot/2) on one ladder theta^(-2i/rot), the position
// component interleaved: 1 where i % 3 == 1 and i < 3 * sec[1], 2 where
// i % 3 == 2 and i < 3 * sec[2], 0 elsewhere (Qwen3-VL's text attention)
__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw,
const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv,
uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld,
QkBlocks blk, uint32_t pplane) {
QkBlocks blk, uint32_t pplane, int pm) {
__shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf];
__shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf];
const uint32_t m = blockIdx.x;
@@ -236,13 +244,29 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel(
uint16_t* row = qkv + (size_t)m * ld;
const float div = rscale != 0.0f ? rscale : 1.0f;
for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) {
if (pm == 2) {
int c = 0;
if (i % 3 == 1 && (int)i < 3 * blk.sec[1]) c = 1;
else if (i % 3 == 2 && (int)i < 3 * blk.sec[2]) c = 2;
const float p = (float)pos[(size_t)c * pplane + m] / div;
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
pa_s[i] = (int)i;
pb_s[i] = (int)(i + half);
continue;
}
int c = 0, s0 = 0;
while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; }
const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div;
const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]);
sincosf(p * inv, &sn_s[i], &cs_s[i]);
pa_s[i] = 2 * s0 + ((int)i - s0);
pb_s[i] = pa_s[i] + blk.sec[c];
if (pm == 1) {
pa_s[i] = 2 * (int)i;
pb_s[i] = 2 * (int)i + 1;
} else {
pa_s[i] = 2 * s0 + ((int)i - s0);
pb_s[i] = pa_s[i] + blk.sec[c];
}
}
__syncthreads();
const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5;
@@ -589,15 +613,34 @@ extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// mode: 0 neox, 1 gptj, 2 blocks (`blk` and the position plane stride `pplane` used only there).
// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope (`blk` and the position plane stride
// `pplane` used only by the last three).
extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M, int head_dim,
int n_head, int n_head_kv, int rot, int mode, int v_norm,
float theta, float eps, float rscale, float wadd, int ld,
const QkBlocks* blk, int pplane, long stream) {
if (!qkv || !pos || !qw || !kw) return -1;
if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim ||
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 2)
(rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 4)
return -2;
if (mode >= 3) {
/* The two forms only the general kernel takes: its pair table is built per mode. */
if (!blk || blk->n <= 0 || blk->n > 8) return -2;
int total = 0;
for (int c = 0; c < blk->n; ++c) {
if (blk->sec[c] <= 0) return -2;
total += blk->sec[c];
}
if (mode == 3 && 2 * total != rot) return -2;
if (mode == 4 && (blk->n < 3 || 2 * total != rot)) return -2;
hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0,
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos,
(const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta,
eps, rscale, wadd, (uint32_t)ld, *blk, (uint32_t)pplane,
mode == 3 ? 1 : 2);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
if (mode != 2 && head_dim % 32) return -2;
if (mode == 1 && head_dim % 64) return -2;
if (mode == 0 && (rot / 2) % 32) return -2;
@@ -620,7 +663,7 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M
(hipStream_t)stream, (uint16_t*)qkv, (const int*)pos,
(const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim,
(uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta,
eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane);
eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane, 0);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
#define R4D_QN(MD) \
@@ -837,12 +880,21 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) {
int md = 0;
if (mode && !std::strcmp(mode, "gptj")) md = 1;
else if (mode && !std::strcmp(mode, "blocks")) md = 2;
else if (mode && !std::strcmp(mode, "gptj_blocks")) md = 3;
else if (mode && !std::strcmp(mode, "imrope")) md = 4;
else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED);
/* Any head_dim in the blocks mode (qk_norm_rope_any_kernel); the others need multiples of 32. */
if (md != 2 && hd % 32) return R4D_NO(RAD_E_SHAPE);
/* Any head_dim in the section modes (qk_norm_rope_any_kernel); the others need multiples of 32. */
if (md < 2 && hd % 32) return R4D_NO(RAD_E_SHAPE);
QkBlocks blk{};
long long M = 0, pplane = 0;
if (md == 2) {
if (md == 4) {
/* Interleaved M-RoPE reads three position planes, its sections only bound the
* interleave. */
blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8);
if (blk.n < 3 || pos->rank != 2 || pos->shape[0] < 3) return R4D_NO(RAD_E_SHAPE);
M = pos->shape[1];
pplane = pos->stride[0];
} else if (md >= 2) {
blk.n = parse_ints(r4d_gets(a, "sections"), blk.sec, 8);
if (blk.n <= 0) return R4D_NO(RAD_E_SHAPE);
for (int c = 0; c < blk.n; ++c) blk.comp[c] = c;
+12 -1
View File
@@ -58,7 +58,18 @@ __global__ __launch_bounds__(256) void r4d_gemm_bf16_nt_tiled_kernel(
const int tid = threadIdx.x, wave = tid >> 5, lane = tid & 31;
const int wm = wave / BT_WN, wn = wave % BT_WN;
const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN;
// THE GRID RUNS IN GROUPS OF 8 ACTIVATION BANDS, M fastest inside a group. Blocks are
// dispatched in flattened-id order, and the launch's x-fastest grid swept every weight band for
// each activation band, reading the whole weight once per 128 rows: free while it sits in the
// 64 MB MALL, and half the rate once it does not (N 12288 x K 4096, 96 MB, ran at 68 TFLOP/s
// where N 8192 ran at 118). A group keeps its bands' weight tiles shared by the blocks in
// flight and reads the weight once a group. Small grids take it too: with fewer bands than a
// group the order is plain M-fastest, which is what reads the weight once.
constexpr unsigned kGroupM = 8;
const unsigned per = kGroupM * gridDim.x, lin = blockIdx.y * gridDim.x + blockIdx.x;
const unsigned first = lin / per * kGroupM, r = lin % per;
const unsigned gm = min(gridDim.y - first, kGroupM);
const int m0 = (int)(first + r % gm) * BM, n0 = (int)(r / gm) * BN;
// Staging: chunk c = tid + 256 i is row c / CPR, elements (c % CPR) * 8 of it. Eight threads
// cover a row's 128 bytes, so a warp's loads are four whole lines.
+21 -2
View File
@@ -98,6 +98,8 @@ constexpr uint32_t kFN = 128, kFK = 64; // kFK is BYTES per LDS row
// alone.
constexpr uint32_t kFKNarrow = 256;
constexpr uint32_t kFWaves = 8;
// Activation bands a raster group of the prefill tile holds in cache -- see the kernel's grouping.
constexpr uint32_t kGroupM = 16;
// 1 M tile x 8 N tiles a wave, so the 8 waves cover 8 DISTINCT row tiles.
//
// The register tile is the two of these together and it is a genuine knob -- the body takes it as a
@@ -415,8 +417,25 @@ void gemm_fp8a8_kernel(
const uint32_t kend = ck ? min(cols, kbeg + ck) : cols;
if (kbeg >= kend) return;
const uint32_t m0 = blockIdx.x * FM;
const uint32_t n0 = blockIdx.y * FN;
// THE PREFILL TILE RUNS IN GROUPS OF kGroupM ACTIVATION BANDS. Blocks are dispatched in
// flattened-id order, so with the plain x-fastest grid every weight band sweeps ALL of the
// activation, and the activation is read once per 128 weight rows. That is free while it sits
// in the 64 MB MALL and is the whole cost once it does not: at M = 16384 x K = 4096 (64 MB)
// gate_up's 192 bands read 12 GB and ran at half the rate of M = 4096. Within a group the
// kGroupM bands stay cached across the full N sweep, and the weight is read once a group.
// With kGroupM bands or fewer the order is the plain one, and skipping the division keeps a
// short prefill chunk at its old rate (2% at M = 512).
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (!AW && gridDim.x > kGroupM) {
const uint32_t per = kGroupM * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kGroupM, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kGroupM);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * FM;
const uint32_t n0 = bn * FN;
// Wave grid MW(M) x 1(N): a wave owns MT*16 A rows and all FN B rows. A 4x2 grid at the same
// 128x128 tile -- 2x4 a wave, so 6 fragment reads per 8 WMMA rather than 9 -- is a WASH, which
// says the fragment reads, which do not bank-conflict, are not the wall. There is no
+1049
View File
File diff suppressed because it is too large. Load diff
+77
View File
@@ -1232,3 +1232,80 @@ extern "C" int r4d_rad_layout_moe_fp8_mod4(const RadParam* p, int n_p, int opera
return rc != RAD_OK ? rc : r4d_rad_layout_fp8_rowmajor(v.p, v.n, v.operand, enc, sel, pl,
n, out);
}
/* ---- conv2d_nhwc: PyTorch's [cout][cin][k][k] stored TAP-MAJOR, [cout][k][k][cin].
*
* The implicit-GEMM convolution (r4d_gen.hip) contracts over K = (tap, channel) with the channel
* innermost, so that eight consecutive K are eight channels of one input pixel -- one 16-byte read
* of an NHWC row. The weight's K has to run the same way, and PyTorch's runs channel-major. A
* permutation of a bf16 plane, so the inverse is the same loop backwards. Operand 1 of
* conv2d_nhwc; the bias is read as it is. */
namespace {
constexpr int CONV_W_OPERAND = 1;
int conv_geom(const RadParam* p, int n_p, const RadTensor* pl, int n, long long* cout,
long long* cin, long long* k) {
*cout = r4d_pgeti_or(p, n_p, "cout", 0);
*cin = r4d_pgeti_or(p, n_p, "cin", 0);
*k = r4d_pgeti_or(p, n_p, "k", 0);
if (n != 1 || !pl || *cout <= 0 || *cin <= 0 || *k <= 0) return RAD_E_SHAPE;
if (pl[0].dtype != RAD_BF16 || pl[0].rank != 2 ||
pl[0].shape[0] * pl[0].shape[1] != *cout * *cin * *k * *k)
return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_conv_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* pl,
int n, RadLayout* out) {
(void)sel;
if (!out) return RAD_E_INVAL;
if (operand != CONV_W_OPERAND) return RAD_E_UNSUPPORTED;
if (!enc || !rad_enc_is(enc, "plain")) return RAD_E_DTYPE;
long long co, ci, k;
const int rc = conv_geom(p, n_p, pl, n, &co, &ci, &k);
if (rc != RAD_OK) return rc;
fill(out, "r4d.conv.tap_major", RAD_BF16, co, k * k * ci, co * k * k * ci * 2);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_conv_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
RadLayout L;
const int rc = r4d_rad_layout_conv_tap(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (dst_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
long long co, ci, k;
conv_geom(p, n_p, pl, n, &co, &ci, &k);
const uint16_t* s = (const uint16_t*)pl[0].data;
uint16_t* d = (uint16_t*)dst;
const long long kk = k * k;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < kk; ++t)
d[(o * kk + t) * ci + c] = s[(o * ci + c) * kk + t];
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_conv_tap(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
RadLayout L;
const int rc = r4d_rad_layout_conv_tap(p, n_p, operand, enc, sel, pl, n, &L);
if (rc != RAD_OK) return rc;
if (src_bytes != L.bytes || !pl[0].data) return RAD_E_SHAPE;
long long co, ci, k;
conv_geom(p, n_p, pl, n, &co, &ci, &k);
const uint16_t* s = (const uint16_t*)src;
uint16_t* d = (uint16_t*)pl[0].data;
const long long kk = k * k;
for (long long o = 0; o < co; ++o)
for (long long c = 0; c < ci; ++c)
for (long long t = 0; t < kk; ++t)
d[(o * ci + c) * kk + t] = s[(o * kk + t) * ci + c];
return RAD_OK;
}
+32
View File
@@ -138,6 +138,30 @@ int r4d_rad_join_add_scale_bf16 (const RadArgs*, RadStream);
int r4d_rad_expert_scale_bf16 (const RadArgs*, RadStream);
int r4d_rad_attn_vit (const RadArgs*, RadStream);
int r4d_rad_attn_dense (const RadArgs*, RadStream);
/* The image generator's attention (r4d_attn_gen.hip): a paged prefix and the pass's own rows, the
* causal-capable dense form at head_dim 128 (a text encoder's prompt), and one 1152-wide head
* (an image decoder's mid block). */
int r4d_rad_attn_prefix_self (const RadArgs*, RadStream);
int r4d_rad_attn_dense_h128 (const RadArgs*, RadStream);
int r4d_rad_attn_dense_wide (const RadArgs*, RadStream);
/* The image generator's other ops (r4d_gen.hip). */
int r4d_rad_ln_mod (const RadArgs*, RadStream);
int r4d_rad_ln_mod_quant_fp8 (const RadArgs*, RadStream);
int r4d_rad_gate_add (const RadArgs*, RadStream);
int r4d_rad_timestep_embed (const RadArgs*, RadStream);
int r4d_rad_gather_rows2 (const RadArgs*, RadStream);
int r4d_rad_lane_gather (const RadArgs*, RadStream);
int r4d_rad_lane_store (const RadArgs*, RadStream);
int r4d_rad_randn_lanes (const RadArgs*, RadStream);
int r4d_rad_flow_euler (const RadArgs*, RadStream);
int r4d_rad_chan_affine (const RadArgs*, RadStream);
int r4d_rad_conv2d_nhwc (const RadArgs*, RadStream);
int r4d_rad_l2norm_chan (const RadArgs*, RadStream);
int r4d_rad_d2s_add (const RadArgs*, RadStream);
int r4d_rad_s2d_avg_add (const RadArgs*, RadStream);
int r4d_rad_to_rgba8 (const RadArgs*, RadStream);
int r4d_rad_gelu_tanh (const RadArgs*, RadStream);
int r4d_rad_scatter_add_rows (const RadArgs*, RadStream);
/* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256
* and MiniCPM5-2B at 128. A decode workgroup holds 64 rows of q_len*gqa, so the verify
* width is 8 here against the gqa6 leg's 10 -- which is the row's constraint value. */
@@ -460,6 +484,14 @@ int r4d_rad_layout_gdense(const RadParam*, int, int, const RadEncoding*, const i
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_gdense(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
/* conv2d_nhwc's weight, PyTorch's [cout][cin][k][k] stored tap-major [cout][k][k][cin]
* (r4d_layout.cpp). */
int r4d_rad_layout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_unrelayout_conv_tap(const RadParam*, int, int, const RadEncoding*, const int*,
const void*, int64_t, const RadTensor*, int);
int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
+372
View File
@@ -660,6 +660,10 @@ static const RadParamSpec pAllReduce[] = {
* plugin reads it, because the message size picks the two-shot (the all-reduce constraints
* below). */
{ "hops", RAD_P_INT, RAD_OPTIONAL },
/* 1 when the caller issues this collective on its second lane, beside compute (rad_lane). It
* picks the rows whose launch is narrow -- see tArLane -- and changes nothing the kernel
* computes. */
{ "overlap", RAD_P_INT, RAD_OPTIONAL },
};
/* docs/OPS.md has `x` -> `x` (inout). Every kernel here is safe in place -- the thread that
* overwrites a word of the input is the one that read it (r4d_ar_entry.hip says so per kernel) --
@@ -2186,6 +2190,82 @@ static const RadOperandSpec oExpertScale[] = {
#define SCHEMA(op, p, o, doc) { (op), ROW(p), ROW(o), (doc) }
/* ---- image generation (r4d_gen.hip, r4d_attn_gen.hip) -------------------------------------
* ref's spellings (libref/ref_registry.cpp), field for field: the first plugin to declare an op
* fixes its schema and the second is refused if it disagrees. */
static const RadParamSpec pGenMn[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
static const RadParamSpec pLnMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype") };
static const RadOperandSpec oLnMod[] = {
{ "x", RAD_OPD_IN, 0 }, { "s", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pLnModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
P_INT("gated"), P_STR("dtype") };
static const RadOperandSpec oLnModQ[] = {
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 }, { "q", RAD_OPD_OUT, 0 },
{ "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 },
};
static const RadOperandSpec oGateAdd[] = {
{ "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "x", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pTimestep[] = { P_INT("M"), P_INT("n"), P_F64("scale"),
P_F64("max_period"), P_INTO("round"), P_STR("dtype") };
static const RadOperandSpec oTimestep[] = { { "t", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
static const RadOperandSpec oGather2[] = {
{ "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pLane[] = { P_INT("M"), P_INT("n"), P_INT("stride"), P_STR("dtype") };
static const RadOperandSpec oLaneGather[] = {
{ "src", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadOperandSpec oLaneStore[] = {
{ "src", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "dst", RAD_OPD_INOUT, 0 },
};
static const RadOperandSpec oRandnLanes[] = {
{ "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 }, { "dst", RAD_OPD_INOUT, 0 },
};
static const RadOperandSpec oFlowEuler[] = {
{ "v", RAD_OPD_IN, 0 }, { "sigma", RAD_OPD_IN, 0 }, { "sigma_next", RAD_OPD_IN, 0 },
{ "cfg", RAD_OPD_IN, 0 }, { "pair", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
{ "flags", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
{ "inp_lat", RAD_OPD_IN, 1 }, { "inp_mask", RAD_OPD_IN, 1 }, { "state", RAD_OPD_INOUT, 0 },
{ "preview", RAD_OPD_INOUT, 1 },
};
static const RadParamSpec pChanAffine[] = { P_INT("M"), P_INT("n"), P_STR("mul"), P_STR("add"),
P_STR("mode"), P_STR("dtype") };
static const RadOperandSpec oGenUnary[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
static const RadParamSpec pConvNhwc[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
P_INT("stride"), P_STR("pad"), P_INT("up"),
P_STR("dtype") };
static const RadOperandSpec oConvNhwc[] = {
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pL2Norm[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") };
static const RadOperandSpec oL2Norm[] = {
{ "x", RAD_OPD_IN, 0 }, { "gamma", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pSpaceDepth[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("ft"),
P_STR("dtype") };
static const RadOperandSpec oSpaceDepth[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_INOUT, 0 } };
static const RadOperandSpec oScatterAdd[] = {
{ "v", RAD_OPD_IN, 0 }, { "idx", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
};
static const RadParamSpec pAttnPS[] = { P_INT("q_len"), P_INT("head_dim"), P_INT("gqa"),
P_INTD("block_size"), P_INT("causal"), P_STR("q_dtype"),
P_STR("kv_dtype"), P_F64O("scale"), P_INTO("max_ctx"),
P_INTO("n_head"), P_INTO("max_seqs"), P_STRO("qk") };
static const RadOperandSpec oAttnPS[] = {
{ "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 }, { "v", RAD_OPD_IN, 0 },
{ "kv_cache", RAD_OPD_IN, 0 }, { "block_table", RAD_OPD_IN, 0 }, { "seqused", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 }, { "k_descale", RAD_OPD_IN, 1 }, { "v_descale", RAD_OPD_IN, 1 },
{ "k_i8", RAD_OPD_IN, 1 }, { "k_scale", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 },
};
static const RadOpSchema kSchemas[] = {
SCHEMA("rmsnorm", pRmsNorm, oRmsNorm,
"y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in "
@@ -2718,6 +2798,40 @@ static const RadOpSchema kSchemas[] = {
"ew[t, k] = ew[t, k] * w_e[ids[t, k]] over [M, top_k], w_e an [n_expert] table, an id "
"outside it reading 0; one product rounded once, so the embed_lookup + mul pair's value "
"bit for bit. Gemma 4's per_expert_scale on the renormalised routing weights."),
SCHEMA("ln_mod", pLnMod, oLnMod,
"y = bf16(bf16(LN(x)) * bf16(1 + s[seq])): a layer norm with no gain or bias, then the "
"row's sequence's modulation row of `s`."),
SCHEMA("ln_mod_quant_fp8", pLnModQ, oLnModQ,
"gated 1: x = bf16(x + bf16(bf16(tanh(g[seq])) * y)) first; then z = ln_mod(x) and "
"(q, scale) = quant_act_fp8(z, group), z written when bound."),
SCHEMA("gate_add", pGenMn, oGateAdd,
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate."),
SCHEMA("timestep_embed", pTimestep, oTimestep,
"the sinusoidal timestep embedding, [cos | sin] of t' * exp(-ln(max_period) * i / (n/2))."),
SCHEMA("gather_rows2", pGenMn, oGather2,
"y[i] = idx[i] >= 0 ? a[idx[i]] : b[-1 - idx[i]]."),
SCHEMA("lane_gather", pLane, oLaneGather, "y[cu[e] + k] = src[lane[e] * stride + k]."),
SCHEMA("lane_store", pLane, oLaneStore, "dst[l * stride + k] = src[k] for every lane listed."),
SCHEMA("randn_lanes", pLane, oRandnLanes,
"an image's first step: its lane's rows become its seed's normal stream."),
SCHEMA("flow_euler", pLane, oFlowEuler,
"one Euler step of a flow-matching sampler per entry that moves a lane."),
SCHEMA("chan_affine", pChanAffine, oGenUnary,
"a per-channel affine from two parameter lists of n values."),
SCHEMA("conv2d_nhwc", pConvNhwc, oConvNhwc,
"an image convolution, channels innermost, the sizes read off the operands."),
SCHEMA("l2norm_chan", pL2Norm, oL2Norm,
"unit-L2 per row, times sqrt(n), times gamma, then `act`: an image decoder's norm."),
SCHEMA("d2s_add", pSpaceDepth, oSpaceDepth, "an upsampling shortcut added in."),
SCHEMA("s2d_avg_add", pSpaceDepth, oSpaceDepth, "a downsampling shortcut added in."),
SCHEMA("to_rgba8", pGenMn, oGenUnary, "decoded pixels in [-1, 1] to bytes."),
SCHEMA("gelu_tanh", pGenMn, oGenUnary, "the tanh approximation of gelu."),
SCHEMA("scatter_add_rows", pGenMn, oScatterAdd, "x[idx[i]] += v[i]; a negative index adds nothing."),
SCHEMA("attn_prefix_self", pAttnPS, oAttnPS,
"attention over a paged prefix and the step's own rows, causal over the own rows or not. "
"`qk` \"i8\" with `k_i8` and `k_scale` selects the INT8 Q.K form: the own keys as quant_act_i8g "
"codes and scales at group head_dim, the query and the prefix keys quantised the same "
"way inside the op, the score product exact in integers and P.V as in the bf16 form."),
};
/* ================================================================================ constraints
@@ -3119,6 +3233,15 @@ static const RadConstraint cArWht6[] = {
C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64),
C_P2P,
};
/* The same two at `overlap` 1: the rows below whose launch defaults leave the CUs to compute. */
static const RadConstraint cArExactLane[] = {
C_EQ("world_size", 2), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"), C_EQ("overlap", 1),
C_P2P,
};
static const RadConstraint cArWht6Lane[] = {
C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64),
C_EQ("overlap", 1), C_P2P,
};
/* DIV 32, not 96: the three-rank split is uneven in whole groups (r4d_rad_ar_twoshot_3rank_ti8). */
static const RadConstraint cArTi8Ts3[] = {
C_EQ("world_size", 3), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 32),
@@ -3783,6 +3906,19 @@ static const RadTunable tAr[] = {
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
};
/* THE SAME AXES WITH NARROW DEFAULTS, for a collective issued beside compute (`overlap` 1). The
* wide launch -- up to 24 blocks of 1024 threads, 768 waves pushing over the link and then
* spinning on peer flags -- is right when the all-reduce has the card to itself and wrong when a
* GEMM shares it: on Qwen-Image's two-rank pass the GEMMs that ran beside it took 1.45 to 2.1x
* their time alone, which ate the whole overlap. Eight blocks of 256 threads still keep the link
* busy, and the same picture went 13.8 -> 13.0 s at 2048^2, bit for bit the same; 8 x 512 and
* 24 x 256 were 13.4 and 13.5. */
static const RadTunable tArLane[] = {
{ "nblocks", kArNblocks, NELEM(kArNblocks), 8, "blocks in the grid. 0 = scale with the message and clamp" },
{ "nthreads", kArNthreads, NELEM(kArNthreads), 256, "threads per block" },
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
};
/* --------------------------------------------------------------------------------- row top-k
* NCH is a REQUEST -- libr4d rounds the chunk width up to a multiple of eight columns -- so the
@@ -3892,6 +4028,33 @@ static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtyp
* reads no tuned key. */
#define NOTUNE nullptr, 0, nullptr
/* ---- image generation ------------------------------------------------------------------- */
/* Rows read 16 bytes at a time, so the widths are whole eights. */
static const RadConstraint cGenRows8[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) };
static const RadConstraint cGenBf16[] = { C_IN("dtype", "bf16") };
static const RadConstraint cLnModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192),
C_EQ("group", 128) };
/* The lane copies move 32-bit words, so any row of whole words: bf16 latents and an f32 mask. */
static const RadConstraint cGenLanes[] = { C_IN("dtype", "bf16 f32") };
/* The two lists are kernel arguments, 64 floats each at most (r4d_gen.hip). */
static const RadConstraint cGenAffine[] = { C_IN("dtype", "bf16"), C_LE("n", 64) };
static const RadConstraint cGenTimestep[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) };
/* The paged prefix at libr4d's block of 16, both caches bf16, up to eight query heads a KV head
* (the shim takes 1, 2, 4 and 8). */
static const RadConstraint cAttnPrefixSelf[] = {
C_EQ("head_dim", 128), C_LE("gqa", 8), C_EQ("block_size", 16), C_IN("q_dtype", "bf16"),
C_IN("kv_dtype", "bf16"),
};
static const RadConstraint cAttnDenseH128[] = {
C_EQ("head_dim", 128), C_LE("gqa", 8), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH768[] = {
C_EQ("head_dim", 768), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
static const RadConstraint cAttnDenseH1152[] = {
C_EQ("head_dim", 1152), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
};
static const RadKernelInfo kKernels[] = {
/* ---------------------------------- the small model ops (r4d_model_bf16.hip) ----------------
*
@@ -5137,6 +5300,27 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_wht6, nullptr, nullptr, nullptr,
r4d_shape_all_reduce },
/* The two above at `overlap` 1: the same entry points and the same arithmetic, a launch that
* leaves the CUs to the compute running beside it (tArLane). */
{ "ar_oneshot_2rank_exact_lane", "all_reduce", "ar",
"all-reduce (sum), one-shot push over P2P IPC scratch, narrow launch beside compute",
"exactly 2 ranks, peer-accessible, overlap 1; scratch sized by the full message; cudagraph-safe",
"bf16 / fp16 / fp32 payload, fp32 accumulate, bit-identical across ranks and to the wide row",
RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1,
ROW(cArExactLane), ROW(tArLane), nullptr,
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_exact, nullptr, nullptr, nullptr,
r4d_shape_all_reduce },
{ "ar_oneshot_2rank_wht6_lane", "all_reduce", "ar",
"all-reduce (sum) with a Walsh-Hadamard-rotated 6-bit wire payload -- lossy; narrow launch "
"beside compute",
"exactly 2 ranks, peer-accessible, overlap 1; groups of 64 elements; cudagraph-safe",
"bf16 / fp16 payload, 6 bits + bf16 scale per group on the wire, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1,
ROW(cArWht6Lane), ROW(tArLane), nullptr,
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_oneshot_2rank_wht6, nullptr, nullptr, nullptr,
r4d_shape_all_reduce },
{ "ar_gather_3rank", "all_gather", "ar",
"all-gather, one-shot push over P2P IPC scratch, the wide family's per-block handshake",
"exactly 3 ranks, all peer-accessible; y is [3 * numel] with rank r's input at r * numel, or "
@@ -6325,6 +6509,194 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
ROW(cExpertScale), NOTUNE,
nullptr, nullptr, r4d_rad_expert_scale_bf16, nullptr, nullptr, nullptr,
nullptr },
{ "attn_prefix_self_h128_bf16", "attn_prefix_self", "attn",
"attention over a paged prefix and the pass's own rows, causal over the own rows or not",
"head_dim 128, 1/2/4/8 query heads a KV head, a flat grid over the sequences' query blocks; "
"the int8 Q.K form (k_i8 / k_scale) at 1 only",
"bf16 q/k/v/out and cache, bf16 operands, fp32 accumulate; or i8 Q.K codes, i32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnPrefixSelf), NOTUNE,
nullptr, nullptr, r4d_rad_attn_prefix_self, nullptr, nullptr, nullptr,
nullptr },
{ "attn_dense_h128_bf16", "attn_dense", "attn",
"dense varlen attention over cu_seqlens, causal or bidirectional",
"head_dim 128, 1/2/4/8 query heads a KV head",
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH128), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense_h128, nullptr, nullptr, nullptr,
nullptr },
{ "attn_dense_h768_bf16", "attn_dense", "attn",
"one 768-wide head over every row of a segment: an image encoder's mid-block attention",
"head_dim 768 split across eight waves, 16 queries a workgroup",
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH768), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr,
nullptr },
{ "attn_dense_h1152_bf16", "attn_dense", "attn",
"one 1152-wide head over every row of a segment: an image decoder's mid-block attention",
"head_dim 1152 split across eight waves, 16 queries a workgroup",
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cAttnDenseH1152), NOTUNE,
nullptr, nullptr, r4d_rad_attn_dense_wide, nullptr, nullptr, nullptr,
nullptr },
{ "ln_mod_quant_fp8_bf16", "ln_mod_quant_fp8", "norm",
"gate_add, ln_mod and quant_act_fp8 in one pass: a workgroup a row",
"any M, n a multiple of 128 up to 8192, group 128",
"bf16 in, E4M3 codes with f32 scales out",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cLnModQ), NOTUNE,
nullptr, nullptr, r4d_rad_ln_mod_quant_fp8, nullptr, nullptr, nullptr,
nullptr },
{ "ln_mod_bf16", "ln_mod", "norm",
"gainless layer norm times (1 + a sequence's scale row): a workgroup a row",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_ln_mod, nullptr, nullptr, nullptr,
nullptr },
{ "gate_add_bf16", "gate_add", "elem",
"x += tanh(gate row) * y, the reference's three roundings",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_gate_add, nullptr, nullptr, nullptr,
nullptr },
{ "timestep_embed_bf16", "timestep_embed", "elem",
"sinusoidal timestep embedding, f32 angles",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenTimestep), NOTUNE,
nullptr, nullptr, r4d_rad_timestep_embed, nullptr, nullptr, nullptr,
nullptr },
{ "gather_rows2_bf16", "gather_rows2", "elem",
"rows from two sources by a signed index",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_gather_rows2, nullptr, nullptr, nullptr,
nullptr },
{ "lane_gather_w32", "lane_gather", "elem",
"each entry's rows out of its lane",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenLanes), NOTUNE,
nullptr, nullptr, r4d_rad_lane_gather, nullptr, nullptr, nullptr,
nullptr },
{ "lane_store_w32", "lane_store", "elem",
"one source's rows into several lanes",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenLanes), NOTUNE,
nullptr, nullptr, r4d_rad_lane_store, nullptr, nullptr, nullptr,
nullptr },
{ "randn_lanes_bf16", "randn_lanes", "elem",
"a lane's rows from its seed's Philox normal stream",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_randn_lanes, nullptr, nullptr, nullptr,
nullptr },
{ "flow_euler_bf16", "flow_euler", "elem",
"a flow-matching Euler step with guidance, preview and repaint",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_flow_euler, nullptr, nullptr, nullptr,
nullptr },
{ "chan_affine_bf16", "chan_affine", "elem",
"a per-channel affine from parameter lists",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenAffine), NOTUNE,
nullptr, nullptr, r4d_rad_chan_affine, nullptr, nullptr, nullptr,
nullptr },
{ "l2norm_chan_bf16", "l2norm_chan", "norm",
"unit-L2 channel norm, scaled, optional silu: a wave a pixel",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_l2norm_chan, nullptr, nullptr, nullptr,
nullptr },
{ "d2s_add_bf16", "d2s_add", "elem",
"an upsampling shortcut added in",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_d2s_add, nullptr, nullptr, nullptr,
nullptr },
{ "s2d_avg_add_bf16", "s2d_avg_add", "elem",
"a downsampling shortcut added in",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_s2d_avg_add, nullptr, nullptr, nullptr,
nullptr },
{ "to_rgba8_bf16", "to_rgba8", "elem",
"decoded pixels to bytes",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_to_rgba8, nullptr, nullptr, nullptr,
nullptr },
{ "gelu_tanh_bf16", "gelu_tanh", "elem",
"tanh gelu",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_gelu_tanh, nullptr, nullptr, nullptr,
nullptr },
{ "scatter_add_rows_bf16", "scatter_add_rows", "elem",
"x[idx[i]] += v[i]",
"any M, row pitches honoured",
"bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenRows8), NOTUNE,
nullptr, nullptr, r4d_rad_scatter_add_rows, nullptr, nullptr, nullptr,
nullptr },
{ "conv2d_nhwc_bf16", "conv2d_nhwc", "conv",
"an image convolution as an implicit GEMM over (tap, cin), the weight stored tap-major",
"128 pixels x 64 or 128 output channels a block, 64 K a stage; cin % 8 != 0 takes a direct kernel",
"bf16 image, weight and bias, fp32 accumulate, one rounding",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cGenBf16), NOTUNE,
nullptr, nullptr, r4d_rad_conv2d_nhwc, nullptr, r4d_rad_layout_conv_tap, r4d_rad_relayout_conv_tap,
nullptr, r4d_rad_unrelayout_conv_tap },
};
/* ================================================================================== the exports */