Archived
radiance 1.9.0
New models: - LTX-2.5 (base and distilled): video with a stereo soundtrack from text or from text and a first frame, on one card, with its duration head, tiled VAE decoding, the diffusion decoder and the x2 latent upsampler - Krea 2 Raw and Turbo, and FLUX.3 [klein] and its base: text to image, and for FLUX.3 edits from up to ten reference pictures, on one card - GLM-5.3-Flash from AMD's Quark MXFP4 export, on eight cards (John McDonough, Nunze) - Gemma 3 / TranslateGemma 27B with an optional DFlash2 drafter (mici81) Engine: - --kv-cache-dtype fp8_v4 and k6_v4 for Gemma 3 and Qwen3.8-Flash-Next (mici81) - the rotated int8 trunk (i8a8h) for Qwen3.8-27B (eddie168168) - eight-rank all-reduce bands, weighted shards and pieces (Nunze); --host-headroom-mib (sfjes) - the dashboard shows the single-stream decode floor and its most recent window (Memoria) Fixes: prefix-cache reservations kept until their save lands (baKon), tool calls in Responses namespaces (#119), system messages merged when a template refuses several (#137), a prefill continued with no open step (#127), calibration of a Gram accumulation (#122), JSON Schema patterns read unanchored (davetha), GLM-style tool calls, the KV floor counting every sequence's state. Plugin ABI 24.
This commit is contained in:
1 parent
778cbf315e
commit
685ec5bd85
136 files changed
+18917
-3821
No files matched your search
@@ -81,6 +81,7 @@ set(R4D_UNITS
|
||||
# decoder's patch unfold, tiles, stitch and rotary positions, and the soundtrack decoder's
|
||||
# alias-free SnakeBeta.
|
||||
"r4d_video|"
|
||||
"r4d_ltx|"
|
||||
# A video latent upscaler: the 3x3x3 convolution as an implicit GEMM over voxel rows, the group
|
||||
# norm, the temporal depthwise convolution, the per-frame bilinear resize, the patch fold and the
|
||||
# re-noise.
|
||||
|
||||
@@ -869,6 +869,7 @@ int r4d_binary_bf16(long a, long b, long y, int M, int n, int op,
|
||||
int a_ld, int b_ld, int y_ld, long stream);
|
||||
int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld, long stream);
|
||||
int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream);
|
||||
int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream);
|
||||
// y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The gate is the first half, the order rad-convert
|
||||
// fuses gate_proj and up_proj in.
|
||||
int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream);
|
||||
|
||||
@@ -362,9 +362,10 @@ int build(ArInst* in, int rank, int world, long long max_numel, int dtype_code,
|
||||
* fill a card while their twins wait behind the other engine's kernel on the peer card, which
|
||||
* waits for a slot on the full card. Not capped: the hyper-connection gathers of the MoE paths
|
||||
* (r4d_ar_gather_hc_write without its inverse scratch, r4d_ar_hc_write_wht6), whose LDS table
|
||||
* needs a minimum block count, which may exceed the ceiling (dense models do not use them). Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B)
|
||||
* hung within a minute of concurrent prefill; MES then failed to evict the queues and the
|
||||
* failed reset froze the host. Capped in both engines so that their spinners together cannot
|
||||
* needs a minimum block count, which may exceed the ceiling (dense models do not use them).
|
||||
* Two TP2 engines on two R9700s (Qwen3.8-27B and Gemma 3 27B) hung within a minute of
|
||||
* concurrent prefill; MES then failed to evict the queues and the failed reset froze the
|
||||
* host. Capped in both engines so that their spinners together cannot
|
||||
* fill a card, the cycle cannot close. The flag and counter arrays keep their full size (maxb);
|
||||
* only the launch counts shrink, and each element's sum is the same. Unset, nothing changes. */
|
||||
if (const char* e = std::getenv("R4D_AR_MAX_BLOCKS")) {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
// R4D dense attention, varlen over cu_seqlens segments, grouped-query: an encoder's, non-causal with
|
||||
// an optional two-sided window, i - j < window behind and j - i < wright ahead (wright is
|
||||
// `window_right`, or `window` for the symmetric |i - j| < window), or causal with an optional
|
||||
// window behind (a codec's sliding layers). bf16 in and out, f16 operands, f32 accumulate. Head
|
||||
// widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair is a row.
|
||||
// window behind (a codec's sliding layers, a text encoder's prompt). bf16 in and out, f16
|
||||
// operands, f32 accumulate. Head widths 64, 256 and 512 are compiled; each (head_dim, gqa) pair
|
||||
// is a row.
|
||||
//
|
||||
// Core from the vision kernel (r4d_attn_vit_h72_bf16.hip): S^T = K.Q^T, so the wave32
|
||||
// column-distributed accumulator gives each lane one query row, softmax state is lane-private, and
|
||||
@@ -39,7 +40,8 @@ __global__ __launch_bounds__(NQB * GQA * DSPLIT * 32)
|
||||
void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restrict__ gk,
|
||||
const uint16_t* __restrict__ gv, uint16_t* __restrict__ go,
|
||||
const int* __restrict__ cu, float scale, int window, int wright,
|
||||
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld)
|
||||
int block, int cdiv, int causal, int q_ld, int k_ld, int v_ld, int o_ld,
|
||||
int krep)
|
||||
{
|
||||
typedef DT16<1> D;
|
||||
typedef D::frag frag16;
|
||||
@@ -73,8 +75,9 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
const int dp = warp % DSPLIT;
|
||||
const int g = (warp / DSPLIT) % GQA;
|
||||
const int qbi = warp / (DSPLIT * GQA);
|
||||
const int kvh = blockIdx.y, seq = blockIdx.z;
|
||||
const int hq = kvh * GQA + g;
|
||||
// blockIdx.y is a group of GQA query heads; krep groups read one KV head.
|
||||
const int kvh = blockIdx.y / krep, seq = blockIdx.z;
|
||||
const int hq = blockIdx.y * GQA + g;
|
||||
|
||||
const int s0 = cu[seq] / cdiv, slen = cu[seq + 1] / cdiv - s0;
|
||||
const int q0 = blockIdx.x * BQ;
|
||||
@@ -301,21 +304,25 @@ void r4d_attn_dense_kernel(const uint16_t* __restrict__ gq, const uint16_t* __re
|
||||
// ---- launch ----------------------------------------------------------------------------------
|
||||
// One instantiation per (head_dim, gqa), at a workgroup shape picked for it:
|
||||
// h64 gqa1: 8 query blocks of 16, K/V tiles of 64 keys (the vision towers' heads)
|
||||
// h256 gqa2: 8 query blocks x 2 heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h256 gqa4: 4 query blocks x 4 heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa4: 2 query blocks x 4 heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// h256 gqa2, 4, 8: 8, 4, 2 query blocks x the heads, tiles of 32 (LDS: 37 KiB)
|
||||
// h512 gqa2, 4, 8: 4, 2, 1 query blocks x the heads x 2 head halves, tiles of 16 (LDS: 57 KiB)
|
||||
// The LDS holds one K/V tile, so the query heads a workgroup carries change its waves, not it.
|
||||
// A wider group (16 query heads a KV head and up, any multiple of 8) runs as krep workgroups of
|
||||
// eight heads each over the same KV head: 16 heads in one would need 32 waves and, at h512, more
|
||||
// than 64 KiB of LDS.
|
||||
template<int HD, int GQA, int NQB, int DSPLIT, int TILE>
|
||||
static int r4d_attn_dense_launch(const void* q, const void* k, const void* v, void* o,
|
||||
const void* cu, int num_seqs, int max_seqlen, int n_head_kv,
|
||||
float scale, int window, int wright, int block, int cdiv,
|
||||
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s)
|
||||
int causal, int q_ld, int k_ld, int v_ld, int o_ld, hipStream_t s,
|
||||
int krep = 1)
|
||||
{
|
||||
constexpr int BQ = NQB * 16;
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv, num_seqs);
|
||||
dim3 grid((max_seqlen + BQ - 1) / BQ, n_head_kv * krep, num_seqs);
|
||||
hipLaunchKernelGGL((r4d_attn_dense_kernel<HD, GQA, NQB, DSPLIT, TILE>), grid,
|
||||
dim3(NQB * GQA * DSPLIT * 32), 0, s, (const uint16_t*)q, (const uint16_t*)k,
|
||||
(const uint16_t*)v, (uint16_t*)o, (const int*)cu, scale, window, wright,
|
||||
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld);
|
||||
block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, krep);
|
||||
const hipError_t e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
@@ -338,27 +345,34 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v,
|
||||
return -4;
|
||||
if (num_seqs <= 0 || max_seqlen <= 0) return 0;
|
||||
if (wright == 0) wright = window;
|
||||
const int gqa = n_head / n_head_kv;
|
||||
int gqa = n_head / n_head_kv, krep = 1;
|
||||
if (gqa > 8 && gqa % 8 == 0) krep = gqa / 8, gqa = 8;
|
||||
hipStream_t s = (hipStream_t)stream;
|
||||
if (head_dim == 64 && gqa == 1)
|
||||
return r4d_attn_dense_launch<64, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen,
|
||||
n_head_kv, scale, window, wright, block,
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s);
|
||||
if (head_dim == 256 && gqa == 2)
|
||||
return r4d_attn_dense_launch<256, 2, 8, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
if (head_dim == 256 && gqa == 4)
|
||||
return r4d_attn_dense_launch<256, 4, 4, 1, 32>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
if (head_dim == 512 && gqa == 4)
|
||||
return r4d_attn_dense_launch<512, 4, 2, 2, 16>(q, k, v, o, cu_seqlens, num_seqs,
|
||||
max_seqlen, n_head_kv, scale, window,
|
||||
wright, block, cdiv, causal, q_ld, k_ld,
|
||||
v_ld, o_ld, s);
|
||||
#define R4D_DENSE(HD, G, NQB, DS, T) \
|
||||
return r4d_attn_dense_launch<HD, G, NQB, DS, T>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \
|
||||
n_head_kv, scale, window, wright, block, \
|
||||
cdiv, causal, q_ld, k_ld, v_ld, o_ld, s, krep)
|
||||
if (head_dim == 256) {
|
||||
switch (gqa) {
|
||||
case 2: R4D_DENSE(256, 2, 8, 1, 32);
|
||||
case 4: R4D_DENSE(256, 4, 4, 1, 32);
|
||||
case 8: R4D_DENSE(256, 8, 2, 1, 32);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
if (head_dim == 512) {
|
||||
switch (gqa) {
|
||||
case 2: R4D_DENSE(512, 2, 4, 2, 16);
|
||||
case 4: R4D_DENSE(512, 4, 2, 2, 16);
|
||||
case 8: R4D_DENSE(512, 8, 1, 2, 16);
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
#undef R4D_DENSE
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
+81
-19
@@ -69,7 +69,8 @@ __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__ cu, const int* __restrict__ cuk, 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,
|
||||
@@ -137,7 +138,10 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
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
|
||||
// Own keys: beside the queries, or (`cuk`, attn_cross) a run of their own; a query sees key j
|
||||
// of its run, counted from the run's start, when j <= its own row with `causal`.
|
||||
const int ks0 = cuk ? cuk[seq] : s0, klen = cuk ? cuk[seq + 1] - ks0 : slen;
|
||||
const int ke = causal ? min(qlast + 1, klen) : klen; // own keys any query here can see
|
||||
|
||||
const float mul = scale * 1.44269504089f;
|
||||
const int qpos = q0 + qbi * 16 + c;
|
||||
@@ -193,12 +197,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
|
||||
// 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;
|
||||
if (!pre) return kbase + (long)(ks0 + 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;
|
||||
if (!pre) return vbase + (long)(ks0 + kk) * v_ld;
|
||||
const int blk = btrow[kk / BS];
|
||||
return kvc + ((long)(blk * kv_heads + kvh) * BS + (kk % BS)) * (2 * HD) + HD;
|
||||
};
|
||||
@@ -222,12 +226,12 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
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);
|
||||
kr[p] = *(const uint4*)(gk8 + (long)(ks0 + 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];
|
||||
ksr = gks[(long)(ks0 + kk) * ks_ld + kvh];
|
||||
}
|
||||
} else {
|
||||
#pragma unroll
|
||||
@@ -243,7 +247,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
if constexpr (PV8) {
|
||||
const int kk0 = k0 + (lgi / DG8) * 8 + vj;
|
||||
const int kk = (kk0 < klim) ? kk0 : klim - 1;
|
||||
const uint8_t* v8 = (const uint8_t*)gv + (long)(s0 + kk) * v_ld + (long)kvh * HD;
|
||||
const uint8_t* v8 = (const uint8_t*)gv + (long)(ks0 + kk) * v_ld + (long)kvh * HD;
|
||||
vr[0] = __builtin_bit_cast(uint4, load_tr_b128(v8 + (lgi % DG8) * 16));
|
||||
} else {
|
||||
#pragma unroll
|
||||
@@ -597,7 +601,7 @@ void r4d_attn_ps_kernel(const uint16_t* __restrict__ gq, const uint16_t* __restr
|
||||
|
||||
template<int HD, int GQA, int NQB, int TILE, bool I8, bool PV8>
|
||||
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 void* v, void* o, const int* cu, const int* cuk,
|
||||
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,
|
||||
@@ -609,14 +613,15 @@ static int r4d_attn_ps_launch(const void* q, const void* k, const void* k8, cons
|
||||
hipLaunchKernelGGL((r4d_attn_ps_kernel<HD, GQA, NQB, TILE, I8, PV8>), 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*)v, (uint16_t*)o, cu, cuk, 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, vs);
|
||||
const hipError_t e = hipGetLastError();
|
||||
return e == hipSuccess ? 0 : -100 - (int)e;
|
||||
}
|
||||
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8. Null `used`/`bt`/`kvc` means no prefix (the dense form).
|
||||
/* head_dim 128 at gqa 1, 2, 4 and 8, and 64 (an audio stream's heads) without a prefix or the
|
||||
* int8 and fp8 forms. Null `used`/`bt`/`kvc` means no prefix (the dense form).
|
||||
* `max_q` is the total query rows over all sequences and bounds the flat grid. Non-null `k8`
|
||||
* selects the int8 Q.K form (own-key codes, `k8_ld` bytes per row; a scale per (row, head) in
|
||||
* `ks`, `ks_ld` floats per row), gqa 1 only. Non-null `vs` selects the fp8 P.V form (`v` as E4M3
|
||||
@@ -626,16 +631,34 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
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, const float* vs = nullptr)
|
||||
int v_ld, int o_ld, hipStream_t s, const float* vs = nullptr,
|
||||
const int* cuk = nullptr)
|
||||
{
|
||||
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 == 64) {
|
||||
if (k8 || vs || used || bt || kvc) return -1;
|
||||
#define R4D_PS64(G, NQB) \
|
||||
return r4d_attn_ps_launch<64, G, NQB, 64, false, false>(q, k, k8, ks, v, o, cu, cuk, 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, nullptr, s)
|
||||
switch (gqa) {
|
||||
case 1: R4D_PS64(1, 16);
|
||||
case 2: R4D_PS64(2, 4);
|
||||
case 4: R4D_PS64(4, 2);
|
||||
case 8: R4D_PS64(8, 1);
|
||||
default: return -1;
|
||||
}
|
||||
#undef R4D_PS64
|
||||
}
|
||||
if (head_dim != 128) return -1;
|
||||
#define R4D_PS(G, NQB, T, I8) \
|
||||
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, used, bt, \
|
||||
return r4d_attn_ps_launch<128, G, NQB, T, I8, false>(q, k, k8, ks, v, o, cu, cuk, 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, nullptr, s)
|
||||
@@ -646,10 +669,10 @@ static int r4d_attn_ps(const void* q, const void* k, const void* k8, const float
|
||||
if (gqa != 1 || used || bt || kvc || (v_ld & 15) || ((uintptr_t)v & 15)) return -1;
|
||||
if (k8)
|
||||
return r4d_attn_ps_launch<128, 1, 16, 64, true, true>(
|
||||
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv,
|
||||
q, k, k8, ks, v, o, cu, cuk, 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, vs, s);
|
||||
return r4d_attn_ps_launch<128, 1, 16, 64, false, true>(
|
||||
q, k, k8, ks, v, o, cu, used, bt, bt_pitch, kvc, num_seqs, max_q, n_head_kv, scale,
|
||||
q, k, k8, ks, v, o, cu, cuk, 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, vs, s);
|
||||
}
|
||||
if (k8) {
|
||||
@@ -791,8 +814,44 @@ extern "C" int r4d_rad_attn_dense_h128(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
// ============================================================== wide heads (attn_dense, h768 / h1152)
|
||||
// Image decoder mid-block attention: one head up to 1152 wide over every latent pixel (16384 rows
|
||||
/* attn_cross at head_dim 64 or 128: the dense kernel with each entry's keys a run of their own
|
||||
* (`cu_k`), causal counting from each run's start. */
|
||||
extern "C" int r4d_rad_attn_cross(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* ck = r4d_opt(a, 4);
|
||||
const RadTensor* o = r4d_opt(a, 5);
|
||||
if (!q || !k || !v || !cu || !ck || !o) return R4D_NO(RAD_E_INVAL);
|
||||
if (!r4d_contig(cu) || cu->rank != 1 || cu->shape[0] < 2 || !r4d_contig(ck) ||
|
||||
r4d_numel(ck) < cu->shape[0])
|
||||
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 != 64 && hd != 128) || gqa <= 0) 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 (!r4d_head_rows(q, hd, &total, &nh, &q_ld) ||
|
||||
!r4d_head_rows(k, hd, &tk, &hk, &k_ld) ||
|
||||
!r4d_head_rows(v, hd, &tv, &hv, &v_ld) ||
|
||||
!r4d_head_rows(o, hd, &to, &ho, &o_ld))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (hk != hv || ho != nh || hk * gqa != nh || tk != tv || 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, nullptr,
|
||||
(const int*)ck->data);
|
||||
if (e == -1 || e == -2) return R4D_NO(RAD_E_SHAPE);
|
||||
if (e == 0) return RAD_OK;
|
||||
return R4D_NO(e == -3 ? RAD_E_STRIDE : e <= -100 ? RAD_E_DEVICE : RAD_E_SHAPE);
|
||||
}
|
||||
|
||||
// ============================================================== wide heads (attn_dense, h384 .. h1152)
|
||||
// Image decoder mid-block attention: one head 384 to 1152 wide over every latent pixel (16384 rows
|
||||
// at 2048 x 2048). A lane cannot hold a 1152-wide output row (576 accumulator VGPRs), so the head
|
||||
// is split across the workgroup's eight waves: a wave owns HD/8 dims of the 16-query block.
|
||||
//
|
||||
@@ -945,7 +1004,8 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream s) {
|
||||
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 ||
|
||||
if ((hd != 384 && hd != 512 && 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 || r4d_geti_or(a, "block", 0) != 0 ||
|
||||
r4d_geti_or(a, "cu_div", 1) != 1)
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
@@ -967,8 +1027,10 @@ extern "C" int r4d_rad_attn_dense_wide(const RadArgs* a, RadStream 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);
|
||||
if (hd == 384) R4D_WIDE(384);
|
||||
else if (hd == 512) R4D_WIDE(512);
|
||||
else if (hd == 768) R4D_WIDE(768);
|
||||
else R4D_WIDE(1152);
|
||||
#undef R4D_WIDE
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -54,6 +54,12 @@ using std::max;
|
||||
#ifndef R4D_ATTN_H256
|
||||
#define R4D_ATTN_H256 1
|
||||
#endif
|
||||
/* The fp8_v4 and k6_v4 caches at head_dim 256 (RadBuildCtx::kv_quant), off unless the including
|
||||
* unit serves a model whose plugin offers them: Qwen3.8-Flash-Next's QSA layers (gqa12, and gqa6
|
||||
* at four ranks). The kernels are the h256/gqa6 templates' O_V4 / O_K6 forms. */
|
||||
#ifndef R4D_ATTN_V4
|
||||
#define R4D_ATTN_V4 0
|
||||
#endif
|
||||
#define GQ_JOIN_(a, b, c) a##b##c
|
||||
#define GQ_JOIN(a, b, c) GQ_JOIN_(a, b, c)
|
||||
#define GQ_SYM(pre, suf) GQ_JOIN(pre, R4D_ATTN_GQA, suf)
|
||||
@@ -99,10 +105,11 @@ extern "C" long GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(const R4DArgs* a) {
|
||||
return r4d_decode_scratch(a, r4d_decode_splits(a, G8_D_TILE), G8_D_OPT);
|
||||
}
|
||||
|
||||
template <int HEAD_DIM, int KVP>
|
||||
template <int HEAD_DIM, int KVP, int XOPT = 0>
|
||||
/* Two dispatches: the attention kernel and the split-KV combine. R4DArgs is passed by value (168
|
||||
* bytes) like any other kernel argument. Non-null `gq` adds the output gate and quantiser to the
|
||||
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). */
|
||||
* combine (attn_paged_gate_quant; R4DGateQuant in r4d_attn_decode_h256_gqa6.hip). `XOPT` adds
|
||||
* option bits to the attention kernel's (O_V4, O_K6: the cache layout). */
|
||||
static int g8_decode_launch(const R4DArgs* a, RadStream stream,
|
||||
const R4DGateQuant* gq = nullptr) {
|
||||
int emit_rc = RAD_OK;
|
||||
@@ -115,12 +122,14 @@ static int g8_decode_launch(const R4DArgs* a, RadStream stream,
|
||||
|
||||
#define G8_LAUNCH(NW) \
|
||||
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<NW, G8_D_TILE, HEAD_DIM, G8_GQA, \
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT>), \
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT | XOPT>), \
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, *a, splits)
|
||||
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. */
|
||||
/* One-wave workgroups stage V as codes (O_V8): same conversion count, half the LDS. A v4
|
||||
* cache stages V widened (the kernel drops O_V8 under O_V4). */
|
||||
if (nw == 1)
|
||||
emit_rc = R4D_EMIT(stream, (r4d_attn_decode_kernel<1, G8_D_TILE, HEAD_DIM, G8_GQA,
|
||||
G8_BLOCK_SIZE, KVP, G8_D_OPT | O_V8>),
|
||||
G8_BLOCK_SIZE, KVP,
|
||||
G8_D_OPT | O_V8 | XOPT>),
|
||||
dim3(splits, a->kv_heads, a->num_seqs), dim3(32), 0, *a, splits);
|
||||
else if (nw == 2) G8_LAUNCH(2);
|
||||
else if (nw == 3) G8_LAUNCH(3);
|
||||
@@ -227,7 +236,9 @@ extern "C" int GQ_SYM(r4d_rad_attn_prefill_h64_gqa, _bf16)(const RadArgs* a, Rad
|
||||
* parameters and no tensors, so parameters come first and tensors are the fallback (see the
|
||||
* h256/gqa6 dispatch). The size is the maximum over every sequence count up to max_seqs, because
|
||||
* S * floor(128 / (kv_heads * S)) is not monotone in S. */
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
/* `row` is a token's bytes in a (block, head) page, 0 for the 16-bit and E4M3 caches' 2 * head_dim
|
||||
* (fill_paged_row). */
|
||||
static int64_t g8_decode_scratch(const RadArgs* a, int head_dim, long long row = 0) {
|
||||
const int sp = split_of(a);
|
||||
if (sp < 0) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
@@ -254,7 +265,7 @@ static int64_t g8_decode_scratch(const RadArgs* a, int head_dim) {
|
||||
}
|
||||
return worst;
|
||||
}
|
||||
const int rc = fill_paged(a, &r, head_dim);
|
||||
const int rc = fill_paged_row(a, &r, head_dim, row > 0 ? row : 2LL * head_dim);
|
||||
if (rc != RAD_OK) return rc;
|
||||
r.splits = sp;
|
||||
return GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(&r);
|
||||
@@ -271,10 +282,10 @@ extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h128_gqa, _scratch)(const RadArgs*
|
||||
}
|
||||
#endif
|
||||
|
||||
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim) {
|
||||
static int g8_decode_common(const RadArgs* a, R4DArgs* r, int head_dim, long long row = 0) {
|
||||
const int sp = split_of(a);
|
||||
if (sp < 0) return R4D_NO(RAD_E_INVAL);
|
||||
const int rc = fill_paged(a, r, head_dim);
|
||||
const int rc = fill_paged_row(a, r, head_dim, row > 0 ? row : 2LL * head_dim);
|
||||
if (rc != RAD_OK) return rc;
|
||||
r->splits = sp;
|
||||
const int64_t need = GQ_SYM(r4d_attn_decode_gqa, _scratch_bytes)(r);
|
||||
@@ -380,3 +391,39 @@ extern "C" int GQ_SYM(r4d_rad_attn_decode_h128_gqa, _bf16)(const RadArgs* a, Rad
|
||||
return g8_decode_launch<128, 1>(&r, s);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if R4D_ATTN_H256 && R4D_ATTN_V4
|
||||
/* ---- the fp8_v4 cache (a token's row 25 * 256 / 16 = 400 bytes: E4M3 K, int4 V, f16 scales) and
|
||||
* the k6_v4 cache (352 bytes: int6 K, int4 V), prefill, decode and decode with the gate and
|
||||
* quantiser in the merge. */
|
||||
#define G8_V4_ENTRIES(TAG, ROWB, XOPT) \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_prefill_h256_gqa, _##TAG)(const RadArgs* a, RadStream s) { \
|
||||
R4DArgs r; \
|
||||
const int rc = fill_paged_row(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
return g8_prefill_launch<256, G8_P_OPT_256 | (XOPT), 0>(&r, (hipStream_t)s); \
|
||||
} \
|
||||
extern "C" int64_t GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG##_scratch)(const RadArgs* a) { \
|
||||
return g8_decode_scratch(a, 256, ROWB); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_h256_gqa, _##TAG)(const RadArgs* a, \
|
||||
RadStream stream) { \
|
||||
R4DArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, stream); \
|
||||
} \
|
||||
extern "C" int GQ_SYM(r4d_rad_attn_decode_gq_h256_gqa, _##TAG)(const RadArgs* a, \
|
||||
RadStream stream) { \
|
||||
R4DArgs r; \
|
||||
const int rc = g8_decode_common(a, &r, 256, ROWB); \
|
||||
if (rc != RAD_OK) return rc; \
|
||||
R4DGateQuant gq{}; \
|
||||
const int gc = g8_gate_quant_args(a, r, &gq); \
|
||||
if (gc != RAD_OK) return gc; \
|
||||
return g8_decode_launch<256, 0, (XOPT)>(&r, stream, &gq); \
|
||||
}
|
||||
G8_V4_ENTRIES(fp8v4, 400, O_V4)
|
||||
G8_V4_ENTRIES(k6v4, 352, O_V4 | O_K6)
|
||||
#undef G8_V4_ENTRIES
|
||||
#endif
|
||||
@@ -17,5 +17,7 @@
|
||||
// pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16 here
|
||||
// would refuse at issue rather than at declare.
|
||||
#define G8_BLOCK_SIZE 4
|
||||
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
|
||||
#define R4D_ATTN_V4 1
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -19,5 +19,7 @@
|
||||
// the pages at 4 (RadKVGroupDecl takes the block size from the resolved kernel). A row saying 16
|
||||
// here would refuse at issue rather than at declare.
|
||||
#define G8_BLOCK_SIZE 4
|
||||
// The fp8_v4 and k6_v4 caches (--kv-cache-dtype), which qwen4exp_fp8 offers for these layers.
|
||||
#define R4D_ATTN_V4 1
|
||||
|
||||
#include "r4d_attn_paged_gqa8.hip"
|
||||
@@ -16,6 +16,7 @@
|
||||
#include "rad_philox.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
@@ -970,6 +971,17 @@ __global__ __launch_bounds__(kT) void iota_kernel(int* __restrict__ y, int n, in
|
||||
if (i < n) y[i] = start + (period > 0 ? i % period : i) * step;
|
||||
}
|
||||
|
||||
// y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j], the lists by value.
|
||||
constexpr int kAffMax = 16;
|
||||
struct IntAffine { int src[kAffMax], mul[kAffMax], add[kAffMax]; };
|
||||
|
||||
__global__ __launch_bounds__(kAffMax) void int_affine_kernel(const int* __restrict__ x,
|
||||
int* __restrict__ y, IntAffine p,
|
||||
int n) {
|
||||
const int j = threadIdx.x;
|
||||
if (j < n) y[j] = (p.src[j] < 0 ? 0 : x[p.src[j]]) * p.mul[j] + p.add[j];
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(kT) void cu_repeat_kernel(const int* __restrict__ len,
|
||||
int* __restrict__ y, int n, int mult) {
|
||||
const int j = blockIdx.x * kT + threadIdx.x;
|
||||
@@ -1597,6 +1609,38 @@ extern "C" int r4d_rad_iota(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
namespace {
|
||||
int parse_ints(const char* s, int* v, int cap) {
|
||||
int n = 0;
|
||||
while (s && *s) {
|
||||
char* e = nullptr;
|
||||
const long x = std::strtol(s, &e, 10);
|
||||
if (e == s) break;
|
||||
if (n == cap) return -1;
|
||||
v[n++] = (int)x;
|
||||
s = e;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_rad_int_affine(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_i32(x) || !is_i32(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
if (!r4d_contig(x) || !r4d_contig(y)) return R4D_NO(RAD_E_STRIDE);
|
||||
IntAffine p{};
|
||||
const int n = parse_ints(r4d_gets(a, "src"), p.src, kAffMax);
|
||||
if (n <= 0 || parse_ints(r4d_gets(a, "mul"), p.mul, kAffMax) != n ||
|
||||
parse_ints(r4d_gets(a, "add"), p.add, kAffMax) != n || r4d_numel(y) < n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
for (int j = 0; j < n; ++j)
|
||||
if (p.src[j] >= r4d_numel(x)) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(int_affine_kernel, dim3(1), dim3(kAffMax), 0, (hipStream_t)s,
|
||||
(const int*)x->data, (int*)y->data, p, n);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_cu_repeat(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *len = r4d_opt(a, 0), *y = r4d_opt(a, 1);
|
||||
if (!len || !y) return R4D_NO(RAD_E_INVAL);
|
||||
|
||||
+99
-205
@@ -1,6 +1,7 @@
|
||||
/* Canonical E4M3 weights with exact F32 block scales: native FP8 WMMA and F32 scale folding, no
|
||||
* checkpoint scale narrowing. The grouped form and the legacy dense form compute one 16x64 output
|
||||
* tile a block; the dense decode and prefill forms below them produce the same bytes faster. */
|
||||
* checkpoint scale narrowing. The legacy dense form computes one 16x64 output tile a block; the
|
||||
* dense decode and prefill forms below it produce the same bytes faster, and the grouped form runs
|
||||
* expert-major over the same per-element sequence. */
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
@@ -8,108 +9,75 @@
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_launch.h"
|
||||
#include <climits>
|
||||
#include <cstdio>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
struct Meta {
|
||||
long ar, asr, yr, wr, sr, wstep[2], sstep[2];
|
||||
int T, N, K, experts, topk, sorted_a, tile;
|
||||
int T, N, K, experts, topk, sorted_a;
|
||||
};
|
||||
__device__ const uint8_t* entry(const void* p, long step, int e) {
|
||||
return step ? (const uint8_t*)p + step * e : ((const uint8_t* const*)p)[e];
|
||||
}
|
||||
template <bool Grouped>
|
||||
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const void* w0, const void* s0,
|
||||
const void* w1, const void* s1, const int* sorted, const int* offsets,
|
||||
/* The legacy dense form: a block per 16 rows by 64 columns, the operands staged through LDS a
|
||||
* dword at a time, so it serves any row pitch and alignment. */
|
||||
__global__ void fp8_f32scale(const uint8_t* a, const float* as, const uint8_t* w, const float* ws,
|
||||
uint16_t* y, Meta m) {
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, n0 = blockIdx.x * 64;
|
||||
__shared__ uint8_t qa[16 * 136], wb[64 * 136];
|
||||
__shared__ int source[16];
|
||||
int first = (int)blockIdx.y * (Grouped ? m.tile : 16);
|
||||
const int limit = min(first + (Grouped ? m.tile : 16), m.T);
|
||||
while (first < limit) {
|
||||
int expert = 0, end = limit;
|
||||
if constexpr (Grouped) {
|
||||
// Tile sorted rows rather than launching every expert, most of which are empty
|
||||
// during native MTP decode. Split a tile at each expert boundary.
|
||||
if (sorted[first] < 0 || offsets[m.experts] <= first) {
|
||||
for (int c = tid; c < 64; c += 128)
|
||||
if (n0 + c < m.N) y[(long)first * m.yr + n0 + c] = 0;
|
||||
++first;
|
||||
continue;
|
||||
const int first = (int)blockIdx.y * 16, end = min(first + 16, m.T);
|
||||
if (tid < 16) {
|
||||
const int r = first + tid;
|
||||
source[tid] = r < end ? r : -1;
|
||||
}
|
||||
__syncthreads();
|
||||
auto acc = r4d_fp8::acc_zero();
|
||||
for (int k0 = 0; k0 < m.K; k0 += 128) {
|
||||
for (int j = tid; j < 16 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4, src = source[r];
|
||||
uint32_t v = 0;
|
||||
if (src >= 0) {
|
||||
const auto* p = a + (long)src * m.ar + k0 + c;
|
||||
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
|
||||
((uint32_t)p[3] << 24);
|
||||
}
|
||||
int lo = 0, hi = m.experts;
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offsets[mid] <= first)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
expert = lo;
|
||||
end = min(limit, offsets[expert + 1]);
|
||||
if (end <= first) return;
|
||||
*(uint32_t*)(qa + r * 136 + c) = v;
|
||||
}
|
||||
const int parity = Grouped ? expert & 1 : 0, e = Grouped ? expert / 2 : 0;
|
||||
const auto* w = entry(parity ? w1 : w0, m.wstep[parity], e);
|
||||
const auto* ws = (const float*)entry(parity ? s1 : s0, m.sstep[parity], e);
|
||||
if (tid < 16) {
|
||||
const int r = first + tid;
|
||||
const int flat = Grouped && r < end ? sorted[r] : r;
|
||||
source[tid] = r < end && flat >= 0 ? (Grouped && !m.sorted_a ? flat / m.topk : r) : -1;
|
||||
for (int j = tid; j < 64 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4;
|
||||
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
|
||||
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
__syncthreads();
|
||||
auto acc = r4d_fp8::acc_zero();
|
||||
for (int k0 = 0; k0 < m.K; k0 += 128) {
|
||||
for (int j = tid; j < 16 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4, src = source[r];
|
||||
uint32_t v = 0;
|
||||
if (src >= 0) {
|
||||
const auto* p = a + (long)src * m.ar + k0 + c;
|
||||
v = (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) |
|
||||
((uint32_t)p[3] << 24);
|
||||
}
|
||||
*(uint32_t*)(qa + r * 136 + c) = v;
|
||||
}
|
||||
for (int j = tid; j < 64 * 32; j += 128) {
|
||||
const int r = j / 32, c = (j % 32) * 4;
|
||||
const auto* p = w + (long)(n0 + r) * m.wr + k0 + c;
|
||||
*(uint32_t*)(wb + r * 136 + c) = (uint32_t)p[0] | ((uint32_t)p[1] << 8) |
|
||||
((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
__syncthreads();
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
#pragma unroll
|
||||
for (int k = 0; k < 128; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
|
||||
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int src = source[(lane >> 4) * 8 + j];
|
||||
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
|
||||
acc[j] += raw[j] * scale;
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
for (int k = 0; k < 128; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(qa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(wb, wave * 16, k, lane), raw);
|
||||
const float weight_scale = ws[(long)(n0 / 128) * m.sr + k0 / 128];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
|
||||
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
|
||||
const int src = source[(lane >> 4) * 8 + j];
|
||||
const float scale = src >= 0 ? as[(long)src * m.asr + k0 / 128] * weight_scale : 0;
|
||||
acc[j] += raw[j] * scale;
|
||||
}
|
||||
__syncthreads();
|
||||
first = end;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const int r = first + (lane >> 4) * 8 + j, c = n0 + wave * 16 + (lane & 15);
|
||||
if (r < end) y[(long)r * m.yr + c] = f32_to_bf16(acc[j]);
|
||||
}
|
||||
}
|
||||
/* The grouped form expert-major: a block per (column span, expert) takes every row of its
|
||||
* expert in 16-row tiles, so an expert slice is read from memory once however its rows fall in
|
||||
* the sorted order (the row tiles above re-read it once per tile its run spans). Each element
|
||||
* keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as raw *
|
||||
* (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K in
|
||||
* stages of StageK, as one stage sequence with the next stage loaded into registers while the
|
||||
* the sorted order (16-row tiles of the sorted order read it once per tile its run spans). Each
|
||||
* element keeps the sequence above: per 128 of K in order a fresh chain of eight WMMAs, folded as
|
||||
* raw * (activation scale * weight scale). A block walks ColTiles column tiles of 64, each over K
|
||||
* in stages of StageK, as one stage sequence with the next stage loaded into registers while the
|
||||
* current one computes from LDS. Block row `experts` zeroes the dropped rows past
|
||||
* offsets[experts]. */
|
||||
typedef unsigned f8_u4 __attribute__((ext_vector_type(4)));
|
||||
@@ -237,15 +205,15 @@ __global__ __launch_bounds__(128) void fp8_f32scale_experts(const uint8_t* a, co
|
||||
}
|
||||
// Both forms below keep fp8_f32scale's arithmetic for every output: per 128-K block the same
|
||||
// eight-mma chain from zero over the same fragments (the bytes at k + 8*(lane/16) of the block's
|
||||
// row segment, which the old kernel copied through LDS unchanged), then acc += raw * (a_scale *
|
||||
// row segment, which the legacy form copies through LDS unchanged), then acc += raw * (a_scale *
|
||||
// w_scale) in ascending block order. A WMMA output depends only on its own A row, B column and
|
||||
// C, so which rows and columns share a tile does not change it.
|
||||
|
||||
// Decode: one wave C adjacent 16-column tiles, S waves of a block on S consecutive K blocks at
|
||||
// once, the fragments loaded straight from global memory; R row tiles share each weight fragment
|
||||
// and C column tiles each activation fragment. Each wave scales its own partial products (the
|
||||
// a_scale x w_scale product and the multiply are the old fold's own two roundings) into LDS; then
|
||||
// every wave folds a share of the outputs, adding the round's products in block order to the
|
||||
// a_scale x w_scale product and the multiply are the legacy fold's own two roundings) into LDS;
|
||||
// then every wave folds a share of the outputs, adding the round's products in block order to the
|
||||
// output's running sum, which lives in LDS between rounds. The block's activation scales are
|
||||
// staged in LDS when they fit (`stage`).
|
||||
template <int R, int C>
|
||||
@@ -338,7 +306,7 @@ __global__ void fp8_f32scale_decode(const uint8_t* a, const float* as, const uin
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill: the old kernel's 64-column block and LDS layout over R row tiles, so a staged weight
|
||||
// Prefill: the legacy form's 64-column block and LDS layout over R row tiles, so a staged weight
|
||||
// block serves R*16 rows instead of 16, staged with 16-byte loads and the next K block loaded
|
||||
// into registers while the current one is multiplied.
|
||||
template <int R>
|
||||
@@ -413,54 +381,18 @@ __global__ void __launch_bounds__(128)
|
||||
}
|
||||
}
|
||||
|
||||
// The dense form. RADIANCE_FP8F32_FORM names "legacy", "rows1"/"rows2"/"rows4" (row tiles a
|
||||
// block) or "decode", optionally "decodeRxS" or "decodeRxSxC" (R row tiles, S waves a block, C
|
||||
// column tiles a wave); otherwise the rule at the end of dense_form. The forms are byte-identical;
|
||||
// the choice is speed only.
|
||||
// The dense form: a decode form (`decode`, C column tiles a wave, S waves a block) or the row
|
||||
// tiles (R of 16 rows a block), by the rule at the end of dense_form. The forms are
|
||||
// byte-identical; the choice is speed only.
|
||||
struct Form {
|
||||
int kind = 0, r = 0, s = 0, c = 1;
|
||||
}; // kind 0 legacy, 1 decode, 2 rows
|
||||
bool decode = false;
|
||||
int r = 1, s = 1, c = 1;
|
||||
};
|
||||
constexpr int kLdsCap = 64 * 1024;
|
||||
long decode_lds(int R, int S, int C, long KB, bool stage) {
|
||||
return ((long)S * R * C * 8 * 32 + (long)R * C * 8 * 32 + (stage ? (long)R * 16 * KB : 0)) * 4;
|
||||
}
|
||||
// Row tiles a decode block shares a weight fragment over (at most three: four need 192 registers
|
||||
// and spill), then waves a block: doubled while the grid stays under 1024 waves, the K blocks last
|
||||
// and the exchange fits the LDS.
|
||||
Form decode_plan(long N, long K, long T) {
|
||||
Form f;
|
||||
f.kind = 1;
|
||||
const long tiles = (T + 15) / 16, kb = K / 128;
|
||||
f.r = (int)(tiles >= 3 ? 3 : tiles);
|
||||
const long blocks = (N / 16) * ((tiles + f.r - 1) / f.r);
|
||||
f.s = 1;
|
||||
while (f.s < 32 && f.s * 2 <= kb && blocks * f.s < 1024 &&
|
||||
decode_lds(f.r, f.s * 2, 1, kb, false) <= kLdsCap)
|
||||
f.s *= 2;
|
||||
return f;
|
||||
}
|
||||
Form dense_form(long N, long K, long T) {
|
||||
if (const char* e = std::getenv("RADIANCE_FP8F32_FORM")) {
|
||||
if (!std::strcmp(e, "legacy")) return Form{};
|
||||
if (!std::strncmp(e, "rows", 4)) {
|
||||
Form f;
|
||||
f.kind = 2;
|
||||
f.r = e[4] == '1' ? 1 : e[4] == '2' ? 2 : 4;
|
||||
return f;
|
||||
}
|
||||
if (!std::strncmp(e, "decode", 6)) {
|
||||
Form f = decode_plan(N, K, T);
|
||||
int r = 0, s = 0, c = 1;
|
||||
const int n = std::sscanf(e + 6, "%dx%dx%d", &r, &s, &c);
|
||||
if (n >= 2 && r >= 1 && r <= 3 && s >= 1 && s <= 32 && (s & (s - 1)) == 0 &&
|
||||
(c == 1 || c == 2 || c == 4) && !(r == 3 && c == 4)) {
|
||||
f.r = r;
|
||||
f.s = s;
|
||||
f.c = c;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
}
|
||||
// Measured on gfx1201 (r4d_selftest --perfq, cold) at GLM's six shapes: decode1x8 up to 16
|
||||
// rows; from 17 to 64 two column tiles a wave (decode1x8x2) lead by 5 to 15 %, except at N 512
|
||||
// (too few column tiles, 1x8 stays) and N 4096 over K 1536, where the 16-row tile wins; from 65
|
||||
@@ -472,14 +404,12 @@ Form dense_form(long N, long K, long T) {
|
||||
const bool rows =
|
||||
T > 128 || (T > 64 && K <= 2048) || (T > 16 && T <= 64 && K <= 1536 && N >= 4096);
|
||||
if (!rows) {
|
||||
f.kind = 1;
|
||||
f.r = 1;
|
||||
f.decode = true;
|
||||
f.c = T > 16 && T <= 64 && N > 512 ? 2 : 1;
|
||||
f.s = 8;
|
||||
while (f.s > 1 && f.s > kb) f.s /= 2;
|
||||
return f;
|
||||
}
|
||||
f.kind = 2;
|
||||
f.r = T > 64 && N >= 4096 ? 2 : 1;
|
||||
return f;
|
||||
}
|
||||
@@ -494,35 +424,28 @@ int dense_fast(RadStream stream, const RadTensor& x, const RadTensor& xs, const
|
||||
const RadTensor& ws, const RadTensor& y, const Meta& m, bool* done) {
|
||||
*done = false;
|
||||
const Form f = dense_form(m.N, m.K, m.T);
|
||||
if (!f.kind || m.wr % 16 || m.ar % 16 ||
|
||||
if (m.wr % 16 || m.ar % 16 ||
|
||||
(reinterpret_cast<uintptr_t>(x.data) | reinterpret_cast<uintptr_t>(w.data)) % 16)
|
||||
return RAD_OK;
|
||||
const uint8_t *xa = (const uint8_t*)x.data, *wa = (const uint8_t*)w.data;
|
||||
const float *xsa = (const float*)xs.data, *wsa = (const float*)ws.data;
|
||||
uint16_t* ya = (uint16_t*)y.data;
|
||||
if (f.kind == 1) {
|
||||
if (f.decode) {
|
||||
const long kb = m.K / 128;
|
||||
const int stage = decode_lds(f.r, f.s, f.c, kb, true) <= kLdsCap;
|
||||
const long lds = decode_lds(f.r, f.s, f.c, kb, stage);
|
||||
const int stage = decode_lds(1, f.s, f.c, kb, true) <= kLdsCap;
|
||||
const long lds = decode_lds(1, f.s, f.c, kb, stage);
|
||||
if (lds > kLdsCap || m.N % (16 * f.c)) return RAD_OK;
|
||||
*done = true;
|
||||
const dim3 grid(m.N / (16 * f.c), (unsigned)(((m.T + 15) / 16 + f.r - 1) / f.r)),
|
||||
block(32 * f.s);
|
||||
#define F32S_DECODE(R_, C_) \
|
||||
if (f.r == R_ && f.c == C_) \
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<R_, C_>), grid, block, (uint32_t)lds, xa, \
|
||||
xsa, wa, wsa, ya, m, stage);
|
||||
F32S_DECODE(1, 1)
|
||||
F32S_DECODE(2, 1) F32S_DECODE(3, 1) F32S_DECODE(1, 2) F32S_DECODE(2, 2) F32S_DECODE(3, 2)
|
||||
F32S_DECODE(1, 4) F32S_DECODE(2, 4)
|
||||
#undef F32S_DECODE
|
||||
* done = false;
|
||||
return RAD_OK;
|
||||
const dim3 grid(m.N / (16 * f.c), (unsigned)((m.T + 15) / 16)), block(32 * f.s);
|
||||
if (f.c == 2)
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 2>), grid, block, (uint32_t)lds, xa,
|
||||
xsa, wa, wsa, ya, m, stage);
|
||||
return R4D_EMIT(stream, (fp8_f32scale_decode<1, 1>), grid, block, (uint32_t)lds, xa, xsa,
|
||||
wa, wsa, ya, m, stage);
|
||||
}
|
||||
*done = true;
|
||||
if (f.r == 1) return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
if (f.r == 2) return emit_rows<2>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
return emit_rows<4>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
return emit_rows<1>(stream, xa, xsa, wa, wsa, ya, m);
|
||||
}
|
||||
int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
if (!a || !a->t || a->n_t < (grouped ? 9 : 5)) return RAD_E_INVAL;
|
||||
@@ -539,7 +462,7 @@ int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
y.shape[1] != N || x.stride[1] != 1 || xs.stride[1] != 1 || y.stride[1] != 1 ||
|
||||
y.shape[0] < 1 || y.shape[0] > INT_MAX)
|
||||
return RAD_E_SHAPE;
|
||||
const int rank = grouped ? 3 : 2;
|
||||
const uint32_t rank = grouped ? 3 : 2;
|
||||
if (w.rank != rank || ws.rank != rank || w.shape[rank - 2] != N || w.shape[rank - 1] != K ||
|
||||
ws.shape[rank - 2] != N / 128 || ws.shape[rank - 1] != K / 128 || w.stride[rank - 1] != 1 ||
|
||||
ws.stride[rank - 1] != 1)
|
||||
@@ -553,75 +476,46 @@ int body(const RadArgs* a, RadStream stream, bool grouped) {
|
||||
m.T = (int)y.shape[0];
|
||||
m.N = N;
|
||||
m.K = K;
|
||||
const void *w1 = nullptr, *s1 = nullptr;
|
||||
const int *sorted = nullptr, *offsets = nullptr;
|
||||
if (grouped) {
|
||||
m.experts = r4d_geti_or(a, "n_expert", 0);
|
||||
m.topk = r4d_geti_or(a, "top_k", 0);
|
||||
const char* order = r4d_gets(a, "a_order");
|
||||
m.sorted_a = order && !std::strcmp(order, "sorted");
|
||||
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
|
||||
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
|
||||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
|
||||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
|
||||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
|
||||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
|
||||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
|
||||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
|
||||
!so.data || !st.data || !off.data)
|
||||
return RAD_E_SHAPE;
|
||||
m.wstep[0] = w.stride[0];
|
||||
m.wstep[1] = wo.stride[0];
|
||||
m.sstep[0] = ws.stride[0] * 4;
|
||||
m.sstep[1] = so.stride[0] * 4;
|
||||
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
|
||||
w1 = wo.data;
|
||||
s1 = so.data;
|
||||
sorted = (const int*)st.data;
|
||||
offsets = (const int*)off.data;
|
||||
} else {
|
||||
if (!grouped) {
|
||||
if (x.shape[0] != m.T) return RAD_E_SHAPE;
|
||||
m.wstep[0] = N * m.wr;
|
||||
m.sstep[0] = (N / 128) * m.sr * 4;
|
||||
bool done = false;
|
||||
const int rc = dense_fast(stream, x, xs, w, ws, y, m, &done);
|
||||
if (done || rc < 0) return rc;
|
||||
return R4D_EMIT(stream, fp8_f32scale, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, (const uint8_t*)w.data,
|
||||
(const float*)ws.data, (uint16_t*)y.data, m);
|
||||
}
|
||||
m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16;
|
||||
if (grouped) {
|
||||
/* The expert-major form at every routed-row count unless the environment bounds or
|
||||
* refuses it (RADIANCE_FP8F32_DECODE_EXPERTS 0 or 1, ..._MAX_T). Measured at GLM's TP8
|
||||
* slices: a long K (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and
|
||||
* under 128 routed rows four tiles a block on top; at down's K of 256 every variant
|
||||
* reads within a few percent of the bandwidth, so it keeps 128 over four tiles. Stage
|
||||
* and tiles can be pinned, for the microbenchmark. */
|
||||
auto env_long = [](const char* name, long dflt) {
|
||||
const char* v = std::getenv(name);
|
||||
return v && *v ? std::strtol(v, nullptr, 10) : dflt;
|
||||
};
|
||||
const char* force = std::getenv("RADIANCE_FP8F32_DECODE_EXPERTS");
|
||||
const long max_t = env_long("RADIANCE_FP8F32_DECODE_EXPERTS_MAX_T", -1);
|
||||
if (force ? force[0] == '1' : max_t < 0 || m.T <= max_t) {
|
||||
const long stage = env_long("RADIANCE_FP8F32_EXPERTS_STAGE_K", K <= 256 ? 128 : 256);
|
||||
const long tiles =
|
||||
env_long("RADIANCE_FP8F32_EXPERTS_COLTILES", K <= 256 || m.T < 128 ? 4 : 1);
|
||||
m.experts = r4d_geti_or(a, "n_expert", 0);
|
||||
m.topk = r4d_geti_or(a, "top_k", 0);
|
||||
const char* order = r4d_gets(a, "a_order");
|
||||
m.sorted_a = order && !std::strcmp(order, "sorted");
|
||||
const auto &wo = a->t[6], &so = a->t[7], &st = a->t[4], &off = a->t[5];
|
||||
if (m.experts < 2 || m.topk < 1 || r4d_geti_or(a, "N_odd", N) != N ||
|
||||
r4d_geti_or(a, "K_odd", K) != K || wo.dtype != RAD_F8E4M3 || so.dtype != RAD_F32 ||
|
||||
wo.rank != 3 || so.rank != 3 || wo.shape[1] != N || wo.shape[2] != K ||
|
||||
so.shape[1] != N / 128 || so.shape[2] != K / 128 || wo.stride[1] != m.wr ||
|
||||
so.stride[1] != m.sr || wo.stride[2] != 1 || so.stride[2] != 1 || st.dtype != RAD_I32 ||
|
||||
off.dtype != RAD_I32 || st.rank != 1 || off.rank != 1 || st.stride[0] != 1 ||
|
||||
off.stride[0] != 1 || st.shape[0] < m.T || off.shape[0] < m.experts + 1 || !wo.data ||
|
||||
!so.data || !st.data || !off.data)
|
||||
return RAD_E_SHAPE;
|
||||
m.wstep[0] = w.stride[0];
|
||||
m.wstep[1] = wo.stride[0];
|
||||
m.sstep[0] = ws.stride[0] * 4;
|
||||
m.sstep[1] = so.stride[0] * 4;
|
||||
if (w.shape[0] < (m.experts + 1) / 2 || wo.shape[0] < m.experts / 2) return RAD_E_SHAPE;
|
||||
/* The expert-major form at every routed-row count. Measured at GLM's TP8 slices: a long K
|
||||
* (gate_up's 4096) wants the 256 stage, 25 to 40 % ahead of 128, and under 128 routed rows
|
||||
* four tiles a block on top; at down's K of 256 every variant reads within a few percent of
|
||||
* the bandwidth, so it keeps 128 over four tiles. */
|
||||
#define F8_EXPERTS(SK, C) \
|
||||
R4D_EMIT(stream, (fp8_f32scale_experts<SK, C>), \
|
||||
dim3((N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), 0, \
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted, \
|
||||
offsets, (uint16_t*)y.data, m)
|
||||
if (stage == 256) return tiles == 4 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
|
||||
return tiles == 4 ? F8_EXPERTS(128, 4) : F8_EXPERTS(128, 1);
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, wo.data, so.data, \
|
||||
(const int*)st.data, (const int*)off.data, (uint16_t*)y.data, m)
|
||||
if (K > 256) return m.T < 128 ? F8_EXPERTS(256, 4) : F8_EXPERTS(256, 1);
|
||||
return F8_EXPERTS(128, 4);
|
||||
#undef F8_EXPERTS
|
||||
}
|
||||
}
|
||||
if (grouped)
|
||||
return R4D_EMIT(stream, fp8_f32scale<true>, dim3(N / 64, (m.T + m.tile - 1) / m.tile),
|
||||
dim3(128), 0, (const uint8_t*)x.data, (const float*)xs.data, w.data,
|
||||
ws.data, w1, s1, sorted, offsets, (uint16_t*)y.data, m);
|
||||
return R4D_EMIT(stream, fp8_f32scale<false>, dim3(N / 64, (m.T + 15) / 16), dim3(128), 0,
|
||||
(const uint8_t*)x.data, (const float*)xs.data, w.data, ws.data, w1, s1, sorted,
|
||||
offsets, (uint16_t*)y.data, m);
|
||||
}
|
||||
int dense(const RadArgs* a, RadStream stream) { return body(a, stream, false); }
|
||||
int grouped(const RadArgs* a, RadStream stream) { return body(a, stream, true); }
|
||||
|
||||
+177
-13
@@ -116,6 +116,62 @@ __global__ __launch_bounds__(kT) void gate_add_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- table_add
|
||||
// y[r, l n + c] = x[r, c] + t[l, c], f32 sum rounded once: one workgroup a (row, table row).
|
||||
__global__ __launch_bounds__(kT) void table_add_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ t, uint16_t* __restrict__ y,
|
||||
int n, int L, int x_ld, int y_ld) {
|
||||
const int r = blockIdx.x / L, l = blockIdx.x % L;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float a[8], b[8];
|
||||
ld8(x + (size_t)r * x_ld + i, a);
|
||||
ld8(t + (size_t)l * n + i, b);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) a[j] += b[j];
|
||||
st8(y + (size_t)r * y_ld + (size_t)l * n + i, a);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- mix_rows
|
||||
// y[r, c] = sum_i w[i] x[r k + i, c], f32 in ascending i, rounded once: one workgroup a row.
|
||||
__global__ __launch_bounds__(kT) void mix_rows_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, uint16_t* __restrict__ y,
|
||||
int n, int k, int x_ld, int y_ld) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float acc[8] = {0, 0, 0, 0, 0, 0, 0, 0}, v[8];
|
||||
for (int q = 0; q < k; ++q) {
|
||||
const float wq = bf2f(w[q]);
|
||||
ld8(x + (size_t)(r * k + q) * x_ld + i, v);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) acc[j] += wq * v[j];
|
||||
}
|
||||
st8(y + (size_t)r * y_ld + i, acc);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- chan_stats
|
||||
// The statistics are rounded on the host side of each thread (cheap: n reads), every step as
|
||||
// libref rounds it.
|
||||
__global__ __launch_bounds__(kT) void chan_stats_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ mean,
|
||||
const uint16_t* __restrict__ sv, uint16_t* __restrict__ y, int n, int x_ld, int y_ld,
|
||||
int var, float eps, int norm) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x * 8; i < n; i += kT * 8) {
|
||||
float a[8], mu[8], sd[8];
|
||||
ld8(x + (size_t)r * x_ld + i, a);
|
||||
ld8(mean + i, mu);
|
||||
ld8(sv + i, sd);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const float s = var ? bfr(sqrtf(sd[j] + eps)) : sd[j];
|
||||
a[j] = norm ? bfr(bfr(a[j] - mu[j]) / s) : bfr(bfr(a[j] * s) + mu[j]);
|
||||
}
|
||||
st8(y + (size_t)r * y_ld + i, a);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- ln_mod_quant_fp8
|
||||
// gate_add, ln_mod and quant_act_fp8 in one pass over the row: the DiT block's norm in front of
|
||||
// every quantised linear, with the previous branch's gated residual folded in. Three passes over a
|
||||
@@ -207,7 +263,8 @@ __global__ __launch_bounds__(kT) void timestep_kernel(
|
||||
int round, int y_ld) {
|
||||
const int m = blockIdx.x;
|
||||
const float tv = t[m];
|
||||
const float tt = round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
|
||||
const float tt = round == 3 ? bfr(scale * bfr(tv)) : round == 2 ? scale * bfr(tv)
|
||||
: round ? scale * bfr(bfr(tv * scale) / scale) : scale * tv;
|
||||
for (int i = threadIdx.x; i < h; i += kT) {
|
||||
const float f = expf(coef * (float)i / (float)h);
|
||||
const float arg = tt * f;
|
||||
@@ -339,6 +396,25 @@ __device__ __forceinline__ float ca_rd(const float*, float v) { return v; }
|
||||
__device__ __forceinline__ void ca_st(uint16_t* p, int64_t i, float v) { p[i] = f32_to_bf16(v); }
|
||||
__device__ __forceinline__ void ca_st(float* p, int64_t i, float v) { p[i] = v; }
|
||||
|
||||
// The element-wise form, any of x, the statistics (TW) and y in bf16 or f32: a latent kept in
|
||||
// f32, or rows whose pitch the 8-wide kernel cannot take (an encoder's mean channels beside its
|
||||
// log-variance). Each step rounds to y's dtype as the reference stores it; the explicit _rn
|
||||
// intrinsics keep the compiler from contracting x s + mean into one fused multiply-add.
|
||||
template <typename TX, typename TW, typename TY>
|
||||
__global__ __launch_bounds__(kT) void chan_stats_any_kernel(
|
||||
const TX* __restrict__ x, const TW* __restrict__ mean, const TW* __restrict__ sv,
|
||||
TY* __restrict__ y, int n, int x_ld, int y_ld, int var, float eps, int norm) {
|
||||
const int r = blockIdx.x;
|
||||
for (int i = threadIdx.x; i < n; i += kT) {
|
||||
const float mu = ca_rd(y, ca_ld(mean, (size_t)i)), v = ca_ld(sv, (size_t)i);
|
||||
const float sd = ca_rd(y, var ? __fsqrt_rn(__fadd_rn(v, eps)) : v);
|
||||
const float a = ca_ld(x, (size_t)r * x_ld + i);
|
||||
ca_st(y, (int64_t)r * y_ld + i,
|
||||
norm ? ca_rd(y, __fdiv_rn(ca_rd(y, __fsub_rn(a, mu)), sd))
|
||||
: ca_rd(y, __fadd_rn(ca_rd(y, __fmul_rn(a, sd)), mu)));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
__global__ __launch_bounds__(kT) void chan_affine_kernel(
|
||||
const T* __restrict__ x, T* __restrict__ y, int64_t total, int n, int x_ld, int inv, int rnd,
|
||||
@@ -467,7 +543,7 @@ template <int TP, int TC, int KS, int UP>
|
||||
__global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int Mpx, int K) {
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int Mpx, int K) {
|
||||
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
|
||||
constexpr int CPR = CV_BK / 8;
|
||||
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
|
||||
@@ -512,7 +588,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
auto loadA = [&](int i) -> r4d_u32x4 {
|
||||
if (!a_ok[i] || a_t[i] >= kk2) return zero;
|
||||
const int kh = a_t[i] / kq, kw = a_t[i] - kh * kq;
|
||||
const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pt;
|
||||
const int iy = a_oy[i] * stride + kh - pt, ix = a_ox[i] * stride + kw - pl;
|
||||
if (iy < 0 || iy >= Hv || ix < 0 || ix >= Wv) return zero;
|
||||
/* Both are non-negative here, so a halving is a shift. */
|
||||
const int sy = UP == 1 ? iy : UP == 2 ? (iy >> 1) : iy / up;
|
||||
@@ -600,7 +676,7 @@ __global__ __launch_bounds__(256) void conv_igemm_kernel(
|
||||
__global__ __launch_bounds__(kT) void conv_direct_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, uint16_t* __restrict__ y, int Hv, int Wv, int cin, int Wo,
|
||||
int cout, int k, int stride, int up, int pt, int x_ld, int y_ld, int64_t total) {
|
||||
int cout, int k, int stride, int up, int pt, int pl, int x_ld, int y_ld, int64_t total) {
|
||||
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
if (t >= total) return;
|
||||
const int co = (int)(t % cout);
|
||||
@@ -612,7 +688,7 @@ __global__ __launch_bounds__(kT) void conv_direct_kernel(
|
||||
const int iy = oy * stride + kh - pt;
|
||||
if (iy < 0 || iy >= Hv) continue;
|
||||
for (int kw = 0; kw < k; ++kw) {
|
||||
const int ix = ox * stride + kw - pt;
|
||||
const int ix = ox * stride + kw - pl;
|
||||
if (ix < 0 || ix >= Wv) continue;
|
||||
const uint16_t* xp = x + (size_t)(iy / up) * x_ld + (size_t)(ix / up) * cin;
|
||||
const uint16_t* wp = w + (size_t)co * K + (size_t)(kh * k + kw) * cin;
|
||||
@@ -637,9 +713,10 @@ inline bool rows8(const RadTensor* t, long long n, long long* rows, long long* l
|
||||
}
|
||||
|
||||
// A dense [H, W * c] image operand.
|
||||
inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W) {
|
||||
inline bool image_of(const RadTensor* t, long long c, long long* H, long long* W,
|
||||
bool pitched = false) {
|
||||
if (!t || t->rank != 2 || c <= 0 || t->shape[1] % c || t->stride[1] != 1 ||
|
||||
t->stride[0] != t->shape[1])
|
||||
(pitched ? t->stride[0] < t->shape[1] : t->stride[0] != t->shape[1]))
|
||||
return false;
|
||||
*H = t->shape[0];
|
||||
*W = t->shape[1] / c;
|
||||
@@ -752,6 +829,87 @@ extern "C" int r4d_rad_gate_add(const RadArgs* a, RadStream s) {
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_table_add(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *t = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !t || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(t) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), L = r4d_geti_or(a, "L", 0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (L <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n * L, &ry, &yl) || !r4d_contig(t) ||
|
||||
((uintptr_t)t->data & 15))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry || r4d_numel(t) < L * n) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(table_add_kernel, dim3((unsigned)(ry * L)), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)t->data, (uint16_t*)y->data,
|
||||
(int)n, (int)L, (int)xl, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_mix_rows(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *y = r4d_opt(a, 2);
|
||||
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(w) || !is_bf16(y)) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), k = r4d_geti_or(a, "k", 0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (k <= 0 || !rows8(x, n, &rx, &xl) || !rows8(y, n, &ry, &yl) || !r4d_contig(w))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry * k || r4d_numel(w) < k) return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(mix_rows_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)w->data, (uint16_t*)y->data,
|
||||
(int)n, (int)k, (int)xl, (int)yl);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
template <typename TX, typename TW, typename TY>
|
||||
static int chan_stats_any(const RadTensor* x, const RadTensor* mn, const RadTensor* sv,
|
||||
const RadTensor* y, long long rows, long long n, long long xl,
|
||||
long long yl, int var, float eps, int norm, RadStream s) {
|
||||
hipLaunchKernelGGL((chan_stats_any_kernel<TX, TW, TY>), dim3((unsigned)rows), dim3(kT), 0,
|
||||
(hipStream_t)s, (const TX*)x->data, (const TW*)mn->data,
|
||||
(const TW*)sv->data, (TY*)y->data, (int)n, (int)xl, (int)yl, var, eps,
|
||||
norm);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
/* Both rows: bf16 (chan_stats_bf16, eight channels a thread when every row and statistic is
|
||||
* 16-byte aligned, element-wise otherwise) and f32 (chan_stats_f32: x and y f32 over bf16 or f32
|
||||
* statistics, a latent kept in f32 before a bf16 network reads it). */
|
||||
extern "C" int r4d_rad_chan_stats(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *mn = r4d_opt(a, 1), *sv = r4d_opt(a, 2), *y = r4d_opt(a, 3);
|
||||
if (!x || !mn || !sv || !y) return R4D_NO(RAD_E_INVAL);
|
||||
const long long n = r4d_geti_or(a, "n", 0);
|
||||
const char* mode = r4d_gets(a, "mode");
|
||||
const int norm = mode && !std::strcmp(mode, "norm");
|
||||
if (!mode || (!norm && std::strcmp(mode, "denorm"))) return R4D_NO(RAD_E_INVAL);
|
||||
auto bf_f32 = [](const RadTensor* t) { return is_bf16(t) || t->dtype == RAD_F32; };
|
||||
if (!bf_f32(x) || !bf_f32(y) || !bf_f32(mn) || mn->dtype != sv->dtype || x->dtype != y->dtype)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const int var = (int)r4d_geti_or(a, "var", 0);
|
||||
const float eps = (float)r4d_getf(a, "eps", 0.0);
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0;
|
||||
if (is_bf16(x) && is_bf16(mn) && rows8(x, n, &rx, &xl) && rows8(y, n, &ry, &yl) &&
|
||||
r4d_contig(mn) && r4d_contig(sv) && !((uintptr_t)mn->data & 15) &&
|
||||
!((uintptr_t)sv->data & 15)) {
|
||||
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(chan_stats_kernel, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s,
|
||||
(const uint16_t*)x->data, (const uint16_t*)mn->data,
|
||||
(const uint16_t*)sv->data, (uint16_t*)y->data, (int)n, (int)xl, (int)yl,
|
||||
var, eps, norm);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
xl = r4d_rows_pitch(x, n, &rx);
|
||||
yl = r4d_rows_pitch(y, n, &ry);
|
||||
if (xl < 0 || yl < 0 || !r4d_contig(mn) || !r4d_contig(sv)) return R4D_NO(RAD_E_STRIDE);
|
||||
if (ry <= 0 || rx < ry || r4d_numel(mn) < n || r4d_numel(sv) < n) return R4D_NO(RAD_E_SHAPE);
|
||||
const bool f = x->dtype == RAD_F32, wf = mn->dtype == RAD_F32;
|
||||
#define R4D_CS(TX, TW) chan_stats_any<TX, TW, TX>(x, mn, sv, y, ry, n, xl, yl, var, eps, norm, s)
|
||||
if (f) return wf ? R4D_CS(float, float) : R4D_CS(float, uint16_t);
|
||||
return wf ? R4D_CS(uint16_t, float) : R4D_CS(uint16_t, uint16_t);
|
||||
#undef R4D_CS
|
||||
}
|
||||
|
||||
/* Both rows: a bf16 embedding (timestep_embed_bf16) or an f32 one (timestep_embed_f32, a timestep
|
||||
* MLP kept in f32). */
|
||||
extern "C" int r4d_rad_timestep_embed(const RadArgs* a, RadStream s) {
|
||||
@@ -957,13 +1115,19 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
const long long up = r4d_geti_or(a, "up", 1);
|
||||
const char* pad = r4d_gets(a, "pad");
|
||||
const bool down = pad && !std::strcmp(pad, "down");
|
||||
if (pad && !down && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
|
||||
const bool causal = pad && !std::strcmp(pad, "causal");
|
||||
if (pad && !down && !causal && std::strcmp(pad, "same")) return R4D_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || stride <= 0 || up <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long Hin = 0, Win = 0, Ho = 0, Wo = 0;
|
||||
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo)) return R4D_NO(RAD_E_SHAPE);
|
||||
/* y may be a column slice of wider rows (a channel written into its own columns): both kernels
|
||||
* store at its row pitch. */
|
||||
if (!image_of(x, cin, &Hin, &Win) || !image_of(y, cout, &Ho, &Wo, true))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long Hv = Hin * up, Wv = Win * up;
|
||||
const long long pt = down ? 0 : k / 2, pb = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pt + pb - k) / stride + 1 != Wo)
|
||||
/* Rows padded above `pt` and below `pb`, columns `pl` left and `pr` right. */
|
||||
const long long pt = down ? 0 : causal ? k - 1 : k / 2, pb = down ? 1 : causal ? 0 : k / 2;
|
||||
const long long pl = down ? 0 : k / 2, pr = down ? 1 : k / 2;
|
||||
if ((Hv + pt + pb - k) / stride + 1 != Ho || (Wv + pl + pr - k) / stride + 1 != Wo)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const long long K = k * k * cin;
|
||||
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -977,7 +1141,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
(const uint16_t*)x->data, (const uint16_t*)w->data,
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv,
|
||||
(int)cin, (int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt,
|
||||
(int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
(int)pl, (int)x->stride[0], (int)y->stride[0], (int64_t)total);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
// 128 pixels a block, and the widest channel tile (192, 128, then 64) that leaves under a third
|
||||
@@ -995,7 +1159,7 @@ extern "C" int r4d_rad_conv2d_nhwc(const RadArgs* a, RadStream s) {
|
||||
(unsigned)((cout + 4 * TC * 16 - 1) / (4 * TC * 16))), \
|
||||
dim3(256), 0, st, (const uint16_t*)x->data, (const uint16_t*)w->data, \
|
||||
(const uint16_t*)b->data, (uint16_t*)y->data, (int)Hv, (int)Wv, (int)cin, \
|
||||
(int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, \
|
||||
(int)Wo, (int)cout, (int)k, (int)stride, (int)up, (int)pt, (int)pl, \
|
||||
(int)x->stride[0], (int)y->stride[0], (int)Mpx, (int)K)
|
||||
/* The decoder's two kernel sizes at its two sampling rates, and the generic form for the rest. */
|
||||
#define R4D_CONV_K(TP, TC) \
|
||||
|
||||
+21
-79
@@ -5,9 +5,6 @@
|
||||
#include "r4d_moe_sort.h"
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
__global__ void gemm_nt_f32_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp,
|
||||
@@ -71,31 +68,6 @@ __global__ void __launch_bounds__(128)
|
||||
if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c];
|
||||
}
|
||||
|
||||
// The tile forms, by rows x columns per wave. RADIANCE_F32_GEMM_TILE names one ("8x4") or
|
||||
// "legacy"; unset or unknown picks by M. All forms are byte-identical, so the choice is speed only.
|
||||
struct F32Tile {
|
||||
int r, c;
|
||||
};
|
||||
constexpr F32Tile kF32Tiles[] = { { 1, 1 }, { 2, 1 }, { 4, 1 }, { 8, 1 }, { 4, 2 },
|
||||
{ 8, 2 }, { 4, 4 }, { 8, 4 }, { 16, 2 }, { 16, 4 } };
|
||||
F32Tile f32_tile(long rows, long n) {
|
||||
if (const char* e = std::getenv("RADIANCE_F32_GEMM_TILE")) {
|
||||
if (!std::strcmp(e, "legacy")) return { 0, 0 };
|
||||
int r = 0, c = 0;
|
||||
if (std::sscanf(e, "%dx%d", &r, &c) == 2)
|
||||
for (const F32Tile& t : kF32Tiles)
|
||||
if (t.r == r && t.c == c) return t;
|
||||
}
|
||||
// Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096. 16x4 gains
|
||||
// 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every width. A
|
||||
// projection of a few columns has too few waves for wide tiles at any M.
|
||||
if (n <= 8) return { 4, 1 };
|
||||
if (rows <= 1) return { 0, 0 };
|
||||
if (rows <= 2) return { 2, 1 };
|
||||
if (rows < 16) return { 4, 1 };
|
||||
if (rows < 64) return { 4, 4 };
|
||||
return { 8, 4 };
|
||||
}
|
||||
template <int R, int C>
|
||||
int gemm_f32_tile(RadStream stream, const RadTensor& x, const RadTensor& w, const RadTensor& y,
|
||||
long n, long k) {
|
||||
@@ -117,52 +89,28 @@ int gemm_f32_body(const RadArgs* a, RadStream stream) {
|
||||
w.stride[1] != 1 || y.stride[1] != 1 || x.stride[0] < k || w.stride[0] < k ||
|
||||
y.stride[0] < n)
|
||||
return RAD_E_SHAPE;
|
||||
const F32Tile t = f32_tile(x.shape[0], n);
|
||||
#define R4D_F32_TILE(R, C) \
|
||||
if (t.r == R && t.c == C) return gemm_f32_tile<R, C>(stream, x, w, y, n, k);
|
||||
R4D_F32_TILE(1, 1)
|
||||
R4D_F32_TILE(2, 1) R4D_F32_TILE(4, 1) R4D_F32_TILE(8, 1) R4D_F32_TILE(4, 2) R4D_F32_TILE(8, 2)
|
||||
R4D_F32_TILE(4, 4) R4D_F32_TILE(8, 4) R4D_F32_TILE(16, 2) R4D_F32_TILE(16, 4)
|
||||
#undef R4D_F32_TILE
|
||||
return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0,
|
||||
(const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
|
||||
x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k);
|
||||
/* The tile form, rows x columns per wave, by M; all forms are byte-identical, so the choice is
|
||||
* speed only. Measured on gfx1201 (r4d_selftest --perff32, cold) at N 4/32/36/288, K 4096.
|
||||
* 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; 8x4 holds at every
|
||||
* width. A projection of a few columns has too few waves for wide tiles at any M. */
|
||||
const long rows = x.shape[0];
|
||||
if (n <= 8) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
|
||||
if (rows <= 1)
|
||||
return R4D_EMIT(stream, gemm_nt_f32_kernel, dim3((n + 3) / 4, x.shape[0]), dim3(128), 0,
|
||||
(const uint16_t*)x.data, (const float*)w.data, (float*)y.data,
|
||||
x.stride[0], w.stride[0], y.stride[0], (int)n, (int)k);
|
||||
if (rows <= 2) return gemm_f32_tile<2, 1>(stream, x, w, y, n, k);
|
||||
if (rows < 16) return gemm_f32_tile<4, 1>(stream, x, w, y, n, k);
|
||||
if (rows < 64) return gemm_f32_tile<4, 4>(stream, x, w, y, n, k);
|
||||
return gemm_f32_tile<8, 4>(stream, x, w, y, n, k);
|
||||
}
|
||||
__global__ void router_sigmoid_kernel(const float* logits, const float* bias, int* ids,
|
||||
float* weights, long lp, long bp, long ip, long wp, int ne,
|
||||
int k, int norm, float factor) {
|
||||
__shared__ float probabilities[512], ranking[512];
|
||||
const int r = blockIdx.x;
|
||||
for (int e = threadIdx.x; e < ne; e += 256) {
|
||||
const float p = 1.0f / (1.0f + expf(-logits[(long)r * lp + e]));
|
||||
probabilities[e] = p;
|
||||
ranking[e] = p + bias[(long)e * bp];
|
||||
}
|
||||
__syncthreads();
|
||||
if (threadIdx.x) return;
|
||||
int index[32];
|
||||
float chosen[32], total = 0;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
int best = 0;
|
||||
for (int e = 1; e < ne; ++e)
|
||||
if (ranking[e] > ranking[best]) best = e;
|
||||
index[j] = best;
|
||||
chosen[j] = probabilities[best];
|
||||
total += chosen[j];
|
||||
ranking[best] = -INFINITY;
|
||||
}
|
||||
const float mult = norm ? factor / (total + 1e-20f) : factor;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
ids[(long)r * ip + j] = index[j];
|
||||
weights[(long)r * wp + j] = chosen[j] * mult;
|
||||
}
|
||||
}
|
||||
// The scan above in one wave per row. Lane l holds experts l, l+32, ... as 64-bit keys: the
|
||||
// rank's order-preserving bits (-0 folded to +0) over ~e, so equal ranks order as the scan's strict
|
||||
// `>` does, to the lower expert. Round j takes the largest key below round j-1's winner and parks
|
||||
// it on lane j (top_k <= 32). Probabilities, `total` in round order, `mult` and the weights are
|
||||
// the scan's expressions, so a finite row gives the same bytes. A NaN rank is never selected here,
|
||||
// while the scan takes expert 0 first when its rank is NaN.
|
||||
// router_sigmoid_topk in one wave per row: p = sigmoid(logit), the top_k largest ranks p + bias
|
||||
// in descending order, equal ranks to the lower expert, as a serial scan with a strict `>` takes
|
||||
// them. Lane l holds experts l, l+32, ... as 64-bit keys: the rank's order-preserving bits (-0
|
||||
// folded to +0) over ~e, so equal ranks order to the lower expert. Round j takes the largest key
|
||||
// below round j-1's winner and parks it on lane j (top_k <= 32). `total` sums the selected p in
|
||||
// round order, mult = norm ? factor / (total + 1e-20) : factor, and a weight is p * mult. A NaN
|
||||
// rank is never selected.
|
||||
// OWN is a template bound because the keys are registers; a lane-derived trip count would index
|
||||
// them divergently, which gfx12 lowers to a v_movrels loop.
|
||||
__device__ __forceinline__ unsigned long long router_rank_key(float rank, int e) {
|
||||
@@ -283,12 +231,6 @@ int router_body(const RadArgs* a, RadStream stream) {
|
||||
bias.stride[0] < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int norm = (int)(r4d_geti_or(a, "norm", 0) != 0);
|
||||
const char* select = std::getenv("RADIANCE_ROUTER_SELECT");
|
||||
if (select && !std::strcmp(select, "old"))
|
||||
return R4D_EMIT(stream, router_sigmoid_kernel, dim3(lg.shape[0]), dim3(256), 0,
|
||||
(const float*)lg.data, (const float*)bias.data, (int*)ids.data,
|
||||
(float*)w.data, lg.stride[0], bias.stride[0], ids.stride[0], w.stride[0],
|
||||
(int)ne, (int)k, norm, factor);
|
||||
const dim3 grid((unsigned)((lg.shape[0] + 3) / 4));
|
||||
if (ne <= 9 * 32)
|
||||
return R4D_EMIT(stream, router_sigmoid_wave_kernel<9>, grid, dim3(128), 0,
|
||||
|
||||
+20
-169
@@ -1,6 +1,5 @@
|
||||
/* Exact recurrent baseline for GLM KDA, including speculative candidate snapshots.
|
||||
* One wave owns one, two or four value rows and keeps each row's 128-wide state in four
|
||||
* registers per lane.
|
||||
* One wave owns four value rows and keeps each row's 128-wide state in four registers per lane.
|
||||
* Prefill uses the same recurrence and commits only its final state. */
|
||||
#include <hip/hip_runtime.h>
|
||||
#include "r4d_args.h"
|
||||
@@ -26,29 +25,16 @@ struct KdaJob : KdaMeta {
|
||||
const int *idx, *cu, *accepted, *init;
|
||||
};
|
||||
|
||||
__device__ float sum(float v) {
|
||||
for (int d = 16; d; d >>= 1) v += __shfl_down(v, d, 32);
|
||||
return __shfl(v, 0, 32);
|
||||
}
|
||||
/* r4d_wave_sum adds the same partners in the same order as sum() does for lane 0, and every
|
||||
* other lane forms the same additions with the operands swapped, so all lanes hold lane 0's bits
|
||||
* without the broadcast. */
|
||||
template <bool Dpp>
|
||||
__device__ __forceinline__ float wave_total(float v) {
|
||||
if constexpr (Dpp)
|
||||
return r4d_wave_sum(v);
|
||||
else
|
||||
return sum(v);
|
||||
}
|
||||
__device__ long factor_offset(long base, int logical, long pitch) {
|
||||
return base + (logical / 128) * pitch + (logical % 128);
|
||||
}
|
||||
/* Separate dispatch: all old factor reads finish before the next window overwrites them. */
|
||||
template <bool Dpp>
|
||||
__global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, const int* accepted,
|
||||
const int* init, KdaMeta m) {
|
||||
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
|
||||
seq = blockIdx.z;
|
||||
/* A sequence without tokens this step leaves its slots as they are. */
|
||||
if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return;
|
||||
const int anchor = idx[(long)seq * m.is0],
|
||||
scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1];
|
||||
if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch)
|
||||
@@ -80,123 +66,17 @@ __global__ void kda_replay_kernel(float* state, const int* idx, const int* cu, c
|
||||
}
|
||||
const float delta =
|
||||
state[factor_offset(fb, f + 384, m.ss2)] *
|
||||
(state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_total<Dpp>(prediction));
|
||||
(state[factor_offset(fb, f + 128 + e, m.ss2)] - r4d_wave_sum(prediction));
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) s[d] += delta * k[d];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d];
|
||||
}
|
||||
__global__ void kda_update_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
|
||||
const uint16_t* g, const uint16_t* beta, const float* alog,
|
||||
const float* bias, float* state_ptr, uint16_t* out,
|
||||
const int* idx, const int* cu, const int* accepted_ptr,
|
||||
const int* init, KdaMeta meta) {
|
||||
KdaJob j{};
|
||||
static_cast<KdaMeta&>(j) = meta;
|
||||
j.input[0] = q;
|
||||
j.input[1] = k;
|
||||
j.input[2] = v;
|
||||
j.input[3] = g;
|
||||
j.input[4] = beta;
|
||||
j.alog = alog;
|
||||
j.bias = bias;
|
||||
j.state = state_ptr;
|
||||
j.out = out;
|
||||
j.idx = idx;
|
||||
j.cu = cu;
|
||||
j.accepted = accepted_ptr;
|
||||
j.init = init;
|
||||
const int lane = threadIdx.x & 31, e = blockIdx.x * 4 + (threadIdx.x >> 5);
|
||||
const int head = blockIdx.y, seq = blockIdx.z;
|
||||
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
|
||||
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
|
||||
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
|
||||
accepted > (j.anchor ? 32 : j.width) ||
|
||||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
|
||||
return;
|
||||
const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1];
|
||||
if (read >= j.slots) return;
|
||||
if (read < 0) {
|
||||
if (!lane)
|
||||
for (int t = begin; t < end; ++t) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = 0;
|
||||
return;
|
||||
}
|
||||
const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0;
|
||||
const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0;
|
||||
if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return;
|
||||
const long fb = (long)scratch * j.ss0 + (long)head * j.ss1;
|
||||
const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
|
||||
float state[4];
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) state[d] = initialized ? j.state[initial + lane + 32 * d] : 0;
|
||||
const float gain = expf(j.alog[head]);
|
||||
for (int t = begin; t < end; ++t) {
|
||||
float q[4], k[4], decay[4], sq = 0, sk = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const int channel = lane + d * 32;
|
||||
q[d] = bf16_to_f32(j.input[0][(long)t * j.row[0] + (long)head * j.head[0] + channel]);
|
||||
k[d] = bf16_to_f32(j.input[1][(long)t * j.row[1] + (long)head * j.head[1] + channel]);
|
||||
sq += q[d] * q[d];
|
||||
sk += k[d] * k[d];
|
||||
const float raw =
|
||||
bf16_to_f32(j.input[3][(long)t * j.row[3] + (long)head * j.head[3] + channel]);
|
||||
decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + j.bias[head * 128 + channel]))));
|
||||
}
|
||||
const float qi = j.scale * rsqrtf(sum(sq) + j.eps), ki = rsqrtf(sum(sk) + j.eps);
|
||||
const float beta =
|
||||
1.0f /
|
||||
(1.0f + expf(-bf16_to_f32(j.input[4][(long)t * j.row[4] + (long)head * j.head[4]])));
|
||||
float predicted = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
q[d] *= qi;
|
||||
k[d] *= ki;
|
||||
state[d] *= decay[d];
|
||||
predicted += state[d] * k[d];
|
||||
}
|
||||
predicted = sum(predicted);
|
||||
const float value =
|
||||
bf16_to_f32(j.input[2][(long)t * j.row[2] + (long)head * j.head[2] + e]);
|
||||
if (j.anchor && j.verify) {
|
||||
const int f = 1 + (t - begin) * 385;
|
||||
if (e == 0) {
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
const int c = lane + 32 * d;
|
||||
j.state[factor_offset(fb, f + c, j.ss2)] = k[d];
|
||||
j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d];
|
||||
}
|
||||
if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = beta;
|
||||
}
|
||||
if (!lane) j.state[factor_offset(fb, f + 128 + e, j.ss2)] = value;
|
||||
}
|
||||
const float delta = beta * (value - predicted);
|
||||
float result = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
state[d] += delta * k[d];
|
||||
result += state[d] * q[d];
|
||||
}
|
||||
result = sum(result);
|
||||
if (!lane) j.out[(long)t * j.os0 + (long)head * j.os1 + e] = f32_to_bf16(result);
|
||||
if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) {
|
||||
const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1];
|
||||
if (write >= 0 && write < j.slots) {
|
||||
const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e * j.ss2;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) j.state[target + lane + 32 * d] = state[d];
|
||||
}
|
||||
}
|
||||
}
|
||||
if (j.anchor && e == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
|
||||
}
|
||||
/* kda_update_kernel with R value rows a wave: the loads, norms and decay exponentials, which do
|
||||
* not depend on the state, are formed once for R rows, and the rows' reductions interleave. Each
|
||||
* row's arithmetic is kda_update_kernel's in its order, so the bytes match (selftest --perfkda).
|
||||
* With Prefetch the next token's operands are loaded while this one is reduced. */
|
||||
template <int R, bool Prefetch>
|
||||
/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state,
|
||||
* are formed once for R rows, and the rows' reductions interleave. The next token's operands are
|
||||
* loaded while this one is reduced. */
|
||||
template <int R>
|
||||
__global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint16_t* v,
|
||||
const uint16_t* g, const uint16_t* beta, const float* alog,
|
||||
const float* bias, float* state_ptr, uint16_t* out, const int* idx,
|
||||
@@ -222,7 +102,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
const int head = blockIdx.y, seq = blockIdx.z;
|
||||
const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0];
|
||||
const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1;
|
||||
if (begin < 0 || end < begin || end > j.tokens || accepted < 1 ||
|
||||
if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 ||
|
||||
accepted > (j.anchor ? 32 : j.width) ||
|
||||
(j.verify && end - begin > (j.anchor ? 32 : j.width)))
|
||||
return;
|
||||
@@ -269,14 +149,11 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r);
|
||||
};
|
||||
Token cur;
|
||||
if (Prefetch && begin < end) fetch(begin, cur);
|
||||
if (begin < end) fetch(begin, cur);
|
||||
for (int t = begin; t < end; ++t) {
|
||||
[[maybe_unused]] Token next;
|
||||
Token next;
|
||||
/* The last token loads itself again rather than a row past `end`. */
|
||||
if constexpr (Prefetch)
|
||||
fetch(t + 1 < end ? t + 1 : t, next);
|
||||
else
|
||||
fetch(t, cur);
|
||||
fetch(t + 1 < end ? t + 1 : t, next);
|
||||
float qv[4], kv[4], decay[4], sq = 0, sk = 0;
|
||||
#pragma unroll
|
||||
for (int d = 0; d < 4; ++d) {
|
||||
@@ -355,7 +232,7 @@ __global__ void kda_rows_kernel(const uint16_t* q, const uint16_t* k, const uint
|
||||
j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d];
|
||||
}
|
||||
}
|
||||
if constexpr (Prefetch) cur = next;
|
||||
cur = next;
|
||||
}
|
||||
if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f;
|
||||
}
|
||||
@@ -448,44 +325,18 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
j.init = (const int*)init->data;
|
||||
j.hs0 = init->stride[0];
|
||||
}
|
||||
/* RADIANCE_KDA_FORM=old is the one-row kernel on shuffle sums, the reference the selftest
|
||||
* holds every form to byte for byte; RADIANCE_KDA_ROWS (1, 2 or 4 value rows a wave) and
|
||||
* RADIANCE_KDA_PREFETCH=0 pin the other form's variants for the microbenchmark. */
|
||||
const char* kform = std::getenv("RADIANCE_KDA_FORM");
|
||||
const bool old = kform && !std::strcmp(kform, "old");
|
||||
const unsigned seqs = (unsigned)(cu.shape[0] - 1);
|
||||
if (j.anchor && j.verify) {
|
||||
const int rc =
|
||||
old ? R4D_EMIT(stream, kda_replay_kernel<false>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j))
|
||||
: R4D_EMIT(stream, kda_replay_kernel<true>, dim3(32, (unsigned)H, seqs), dim3(128),
|
||||
0, j.state, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
R4D_EMIT(stream, kda_replay_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0, j.state,
|
||||
j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
if (rc != RAD_OK) return rc;
|
||||
}
|
||||
if (old)
|
||||
return R4D_EMIT(stream, kda_update_kernel, dim3(32, (unsigned)H, seqs), dim3(128), 0,
|
||||
j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias,
|
||||
j.state, j.out, j.idx, j.cu, j.accepted, j.init, static_cast<KdaMeta>(j));
|
||||
const char* rows_env = std::getenv("RADIANCE_KDA_ROWS");
|
||||
const long rows = rows_env && *rows_env ? std::strtol(rows_env, nullptr, 10) : 4;
|
||||
const char* prefetch_env = std::getenv("RADIANCE_KDA_PREFETCH");
|
||||
const bool prefetch = !prefetch_env || prefetch_env[0] != '0';
|
||||
#define KDA_ROWS(RR, PF) \
|
||||
return R4D_EMIT(stream, (kda_rows_kernel<RR, PF>), dim3(32 / RR, (unsigned)H, seqs), \
|
||||
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4], \
|
||||
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init, \
|
||||
static_cast<KdaMeta>(j))
|
||||
if (rows == 1) {
|
||||
if (prefetch) KDA_ROWS(1, true);
|
||||
KDA_ROWS(1, false);
|
||||
}
|
||||
if (rows == 2) {
|
||||
if (prefetch) KDA_ROWS(2, true);
|
||||
KDA_ROWS(2, false);
|
||||
}
|
||||
if (prefetch) KDA_ROWS(4, true);
|
||||
KDA_ROWS(4, false);
|
||||
#undef KDA_ROWS
|
||||
constexpr int kRows = 4;
|
||||
return R4D_EMIT(stream, (kda_rows_kernel<kRows>), dim3(32 / kRows, (unsigned)H, seqs),
|
||||
dim3(128), 0, j.input[0], j.input[1], j.input[2], j.input[3], j.input[4],
|
||||
j.alog, j.bias, j.state, j.out, j.idx, j.cu, j.accepted, j.init,
|
||||
static_cast<KdaMeta>(j));
|
||||
}
|
||||
}
|
||||
extern "C" int r4d_rad_kda_update(const RadArgs* a, RadStream stream) { return body(a, stream); }
|
||||
+1091
File diff suppressed because it is too large.
Load diff
+31
-127
@@ -67,41 +67,8 @@ __global__ void mhc_partial_kernel(const uint16_t* h, const float* fn, Out out,
|
||||
}
|
||||
}
|
||||
|
||||
// Prefill reuses each F32 mixing weight across four BF16 token rows.
|
||||
// Each row keeps the same accumulation and reduction order as the scalar-row path.
|
||||
template <class Out>
|
||||
__global__ void mhc_partial_rows4_kernel(const uint16_t* h, const float* fn, Out out, int width,
|
||||
int mix, int chunk0, long hp, long fp, long rows) {
|
||||
__shared__ float sums[4][4];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int j = blockIdx.y, chunk = chunk0 + blockIdx.x;
|
||||
const long first = (long)blockIdx.z * 4;
|
||||
float sum[4] = { 0, 0, 0, 0 };
|
||||
for (int i = chunk * 2048 + tid; i < min(width, (chunk + 1) * 2048); i += 128) {
|
||||
const float weight = j == mix ? 0 : fn[(long)j * fp + i];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < 4; ++r)
|
||||
if (first + r < rows) {
|
||||
const float v = bf16_to_f32(h[(first + r) * hp + i]);
|
||||
sum[r] += v * (j == mix ? v : weight);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int r = 0; r < 4; ++r) {
|
||||
sum[r] = warp_sum(sum[r]);
|
||||
if (!lane) sums[r][wave] = sum[r];
|
||||
}
|
||||
__syncthreads();
|
||||
if (!tid)
|
||||
for (int r = 0; r < 4; ++r)
|
||||
if (first + r < rows) {
|
||||
*out.at(first + r, j, chunk) = sums[r][0] + sums[r][1] + sums[r][2] + sums[r][3];
|
||||
if (j == mix) out.pad(first + r, mix, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
// Reuse each input across four coefficients and each weight across four rows.
|
||||
// All per-output K accumulation and reduction orders match the rows4 path.
|
||||
// Prefill reuses each input across four coefficients and each F32 mixing weight across four BF16
|
||||
// token rows. Every output keeps mhc_partial_kernel's accumulation and reduction order.
|
||||
template <class Out>
|
||||
__global__ void mhc_partial_rows4_coeff4_kernel(const uint16_t* h, const float* fn, Out out,
|
||||
int width, int mix, int chunk0, long hp, long fp,
|
||||
@@ -246,17 +213,18 @@ __global__ __launch_bounds__(128) void mhc_partial_vec_kernel(const uint16_t* h,
|
||||
}
|
||||
}
|
||||
|
||||
template <class In, bool VecX>
|
||||
// The geometries without the chunk split: one workgroup a row projects the residual itself from
|
||||
// `fn`, then mixes and collapses it.
|
||||
__global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float* scale,
|
||||
const float* base, uint16_t* x, float* post, float* comb, int n,
|
||||
int hc, int iterations, float eps, float heps, long hp, long fp,
|
||||
long xp, long pp, long cp, int chunks, In in) {
|
||||
long xp, long pp, long cp) {
|
||||
__shared__ float sums[8], inverse, coefficients[80], pre[8], c[64];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const long r = blockIdx.x;
|
||||
const int width = hc * n, mix = hc * (hc + 2);
|
||||
float ss = 0;
|
||||
for (int i = tid; !chunks && i < width; i += 256) {
|
||||
for (int i = tid; i < width; i += 256) {
|
||||
const float v = bf16_to_f32(h[r * hp + i]);
|
||||
ss += v * v;
|
||||
}
|
||||
@@ -265,20 +233,14 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float*
|
||||
__syncthreads();
|
||||
if (!tid) {
|
||||
float s = 0;
|
||||
if (chunks)
|
||||
for (int i = 0; i < chunks; ++i) s += *in.at(r, mix, i);
|
||||
else
|
||||
for (int i = 0; i < 8; ++i) s += sums[i];
|
||||
for (int i = 0; i < 8; ++i) s += sums[i];
|
||||
inverse = rsqrtf(s / (float)width + eps);
|
||||
}
|
||||
__syncthreads();
|
||||
for (int j = wave; j < mix; j += 8) {
|
||||
float dot = 0;
|
||||
if (chunks)
|
||||
for (int i = lane; i < chunks; i += 32) dot += *in.at(r, j, i);
|
||||
else
|
||||
for (int i = lane; i < width; i += 32)
|
||||
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
|
||||
for (int i = lane; i < width; i += 32)
|
||||
dot += bf16_to_f32(h[r * hp + i]) * fn[(long)j * fp + i];
|
||||
dot = warp_sum(dot);
|
||||
if (!lane) coefficients[j] = dot * inverse;
|
||||
}
|
||||
@@ -319,7 +281,7 @@ __global__ void mhc_pre_kernel(const uint16_t* h, const float* fn, const float*
|
||||
for (int j = 0; j < hc * hc; ++j) comb[r * cp + j] = c[j];
|
||||
}
|
||||
__syncthreads();
|
||||
if (VecX && mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
|
||||
if (mix_rows_vec(h + r * hp, x + r * xp, pre, n, hc, tid, 256)) return;
|
||||
for (int i = tid; i < n; i += 256) {
|
||||
float v = 0;
|
||||
for (int j = 0; j < hc; ++j) v += pre[j] * bf16_to_f32(h[r * hp + j * n + i]);
|
||||
@@ -383,29 +345,8 @@ __device__ __forceinline__ float glm_warp_mix(int lane, long row, const float* s
|
||||
if (lane < 16) comb[row * cp + lane] = value;
|
||||
return pre;
|
||||
}
|
||||
template <class In>
|
||||
__global__ void mhc_pre_glm_warp_kernel(const uint16_t* h, const float* scale, const float* base,
|
||||
uint16_t* x, float* post, float* comb, int iterations,
|
||||
float eps, float heps, long hp, long xp, long pp, long cp,
|
||||
In in) {
|
||||
const int lane = threadIdx.x;
|
||||
const long row = blockIdx.x;
|
||||
const float pre =
|
||||
glm_warp_mix(lane, row, scale, base, post, comb, iterations, eps, heps, pp, cp, in);
|
||||
const float p0 = __shfl(pre, 0, 32), p1 = __shfl(pre, 1, 32), p2 = __shfl(pre, 2, 32),
|
||||
p3 = __shfl(pre, 3, 32);
|
||||
for (int i = lane; i < 4096; i += 32) {
|
||||
float v = 0;
|
||||
v += p0 * bf16_to_f32(h[row * hp + i]);
|
||||
v += p1 * bf16_to_f32(h[row * hp + 4096 + i]);
|
||||
v += p2 * bf16_to_f32(h[row * hp + 8192 + i]);
|
||||
v += p3 * bf16_to_f32(h[row * hp + 12288 + i]);
|
||||
x[row * xp + i] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
|
||||
// The warp kernel's mix on wave 0, then the collapsed read over the whole block: one wave writing
|
||||
// 4096 columns a row was most of a decode step's mhc_pre.
|
||||
// glm_warp_mix on wave 0, then the collapsed read over the whole block: one wave writing 4096
|
||||
// columns a row would be most of a decode step's mhc_pre.
|
||||
template <class In>
|
||||
__global__ __launch_bounds__(256) void mhc_pre_glm_wide_kernel(
|
||||
const uint16_t* h, const float* scale, const float* base, uint16_t* x, float* post, float* comb,
|
||||
@@ -516,23 +457,15 @@ constexpr int kChunkCols = 2048, kPartStride = 28;
|
||||
template <class Out>
|
||||
int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out out, int n, int hc,
|
||||
int chunk0, int count, long rows) {
|
||||
const char* rows4 = std::getenv("RADIANCE_MHC_PREFILL_ROWS4");
|
||||
const char* coeff4 = std::getenv("RADIANCE_MHC_PREFILL_COEFF4");
|
||||
/* From 2 rows the four-slot form (RADIANCE_MHC_PARTIAL_VEC 0 off, 1 at every row count;
|
||||
* RADIANCE_MHC_PARTIAL_ROWS 1, 2 or 4 pins its rows a wave), on 16-byte weight and 8-byte
|
||||
* residual rows; GLM's 2048-column chunks only. Measured cold on gfx1201 at GLM's shape:
|
||||
* one row a wave leads up to 16 rows (13 us against the old 20 to 36), two rows from 48
|
||||
* (20 against 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave
|
||||
* trail two at every count. */
|
||||
const char* vec = std::getenv("RADIANCE_MHC_PARTIAL_VEC");
|
||||
/* From 2 rows the four-slot form, on 16-byte weight and 8-byte residual rows; GLM's
|
||||
* 2048-column chunks only. Measured cold on gfx1201 at GLM's shape: one row a wave leads up
|
||||
* to 16 rows (13 us against 20 to 36 for the one-slot kernels), two rows from 48 (20 against
|
||||
* 22 us, at 128 rows 34 against 39, at 2048 391 against 500); four rows a wave trail two at
|
||||
* every count. */
|
||||
const bool vec_aligned = ((uintptr_t)fn.data & 15) == 0 && fn.stride[0] % 4 == 0 &&
|
||||
((uintptr_t)h.data & 7) == 0 && h.stride[0] % 4 == 0 &&
|
||||
hc * n % kChunkCols == 0;
|
||||
if (vec_aligned && (vec ? vec[0] == '1' : rows >= 2)) {
|
||||
const char* pin_rows = std::getenv("RADIANCE_MHC_PARTIAL_ROWS");
|
||||
const long R = pin_rows && *pin_rows ? std::strtol(pin_rows, nullptr, 10)
|
||||
: rows >= 32 ? 2
|
||||
: 1;
|
||||
if (vec_aligned && rows >= 2) {
|
||||
const int mix = hc * (hc + 2), groups = (mix + 4) / 4;
|
||||
#define MHC_VEC(RR) \
|
||||
do { \
|
||||
@@ -542,25 +475,18 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out
|
||||
(const float*)fn.data, out, mix, chunk0, count, (long)h.stride[0], \
|
||||
(long)fn.stride[0], rows, items); \
|
||||
} while (0)
|
||||
if (R == 4) MHC_VEC(4);
|
||||
if (R == 2) MHC_VEC(2);
|
||||
if (rows >= 32) MHC_VEC(2);
|
||||
MHC_VEC(1);
|
||||
#undef MHC_VEC
|
||||
}
|
||||
const char* rows4_min = std::getenv("RADIANCE_MHC_ROWS4_MIN");
|
||||
const bool use_rows4 =
|
||||
(!rows4 || rows4[0] == '1') &&
|
||||
rows >= (rows4_min && *rows4_min ? std::strtol(rows4_min, nullptr, 10) : 32);
|
||||
if (use_rows4 && (!coeff4 || coeff4[0] == '1'))
|
||||
/* Otherwise four rows and four coefficients a block from 32 rows, one row and one coefficient
|
||||
* below. */
|
||||
constexpr long kRows4Min = 32;
|
||||
if (rows >= kRows4Min)
|
||||
return R4D_EMIT(stream, (mhc_partial_rows4_coeff4_kernel<Out>),
|
||||
dim3(count, (hc * (hc + 2) + 4) / 4, (unsigned)((rows + 3) / 4)), dim3(128),
|
||||
0, (const uint16_t*)h.data, (const float*)fn.data, out, hc * n,
|
||||
hc * (hc + 2), chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
|
||||
if (use_rows4)
|
||||
return R4D_EMIT(stream, (mhc_partial_rows4_kernel<Out>),
|
||||
dim3(count, hc * (hc + 2) + 1, (unsigned)((rows + 3) / 4)), dim3(128), 0,
|
||||
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
|
||||
chunk0, (long)h.stride[0], (long)fn.stride[0], rows);
|
||||
return R4D_EMIT(stream, (mhc_partial_kernel<Out>),
|
||||
dim3(count, hc * (hc + 2) + 1, (unsigned)rows), dim3(128), 0,
|
||||
(const uint16_t*)h.data, (const float*)fn.data, out, hc * n, hc * (hc + 2),
|
||||
@@ -571,39 +497,19 @@ int emit_partials(RadStream stream, const RadTensor& h, const RadTensor& fn, Out
|
||||
template <class In>
|
||||
int emit_finish(RadStream stream, const RadTensor& h, const float* fn, long fp, const RadTensor& s,
|
||||
const RadTensor& b, const RadTensor& x, const RadTensor& p, const RadTensor& c,
|
||||
int n, int hc, int iters, float eps, float heps, long rows, int chunks, bool split,
|
||||
In in) {
|
||||
const char* warp = std::getenv("RADIANCE_MHC_PREFILL_WARP");
|
||||
int n, int hc, int iters, float eps, float heps, long rows, bool split, In in) {
|
||||
/* The warp mix at every row count: byte-identical to the scalar one and a quarter of its time
|
||||
* at one to six rows. RADIANCE_MHC_FINISH, for the microbenchmark: `old` the one-wave finish
|
||||
* from 32 rows and the scalar mix and read below, `scalar` that mix with the wide read. */
|
||||
const char* form = std::getenv("RADIANCE_MHC_FINISH");
|
||||
const bool old = form && !std::strcmp(form, "old");
|
||||
const bool warp_mix = split && (warp ? warp[0] == '1' : true) &&
|
||||
(old ? rows >= 32 : !(form && !std::strcmp(form, "scalar")));
|
||||
if (warp_mix && old)
|
||||
return R4D_EMIT(stream, (mhc_pre_glm_warp_kernel<In>), dim3((unsigned)rows), dim3(32), 0,
|
||||
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
|
||||
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
in);
|
||||
if (warp_mix)
|
||||
* at one to six rows. */
|
||||
if (split)
|
||||
return R4D_EMIT(stream, (mhc_pre_glm_wide_kernel<In>), dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, iters, eps, heps,
|
||||
(long)h.stride[0], (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
in);
|
||||
if (old)
|
||||
return R4D_EMIT(stream, (mhc_pre_kernel<In, false>), dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0],
|
||||
(long)c.stride[0], split ? chunks : 0, in);
|
||||
return R4D_EMIT(stream, (mhc_pre_kernel<In, true>), dim3((unsigned)rows), dim3(256), 0,
|
||||
return R4D_EMIT(stream, mhc_pre_kernel, dim3((unsigned)rows), dim3(256), 0,
|
||||
(const uint16_t*)h.data, fn, (const float*)s.data, (const float*)b.data,
|
||||
(uint16_t*)x.data, (float*)p.data, (float*)c.data, n, hc, iters, eps, heps,
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0],
|
||||
split ? chunks : 0, in);
|
||||
(long)h.stride[0], fp, (long)x.stride[0], (long)p.stride[0], (long)c.stride[0]);
|
||||
}
|
||||
bool coefficients(const RadArgs* a, long* iters, float* eps, float* heps) {
|
||||
*iters = r4d_geti_or(a, "iterations", 0);
|
||||
@@ -640,7 +546,7 @@ int pre_body(const RadArgs* a, RadStream stream) {
|
||||
if (rc < 0) return rc;
|
||||
}
|
||||
return emit_finish(stream, h, (const float*)fn.data, (long)fn.stride[0], s, b, x, p, c, n, hc,
|
||||
(int)iters, eps, heps, rows, chunks, split, in);
|
||||
(int)iters, eps, heps, rows, split, in);
|
||||
}
|
||||
int partial_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
@@ -676,7 +582,7 @@ int finish_body(const RadArgs* a, RadStream stream) {
|
||||
return RAD_E_SHAPE;
|
||||
const Dense in{ (float*)part.data, (long)part.stride[0], kPartStride, 0 };
|
||||
return emit_finish(stream, h, nullptr, 0, s, b, x, p, c, n, hc, (int)iters, eps, heps, rows,
|
||||
chunks, true, in);
|
||||
true, in);
|
||||
}
|
||||
int post_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 5) return RAD_E_INVAL;
|
||||
@@ -689,12 +595,10 @@ int post_body(const RadArgs* a, RadStream stream) {
|
||||
!matrix(p, RAD_F32, rows, hc) || !matrix(c, RAD_F32, rows, hc * hc) ||
|
||||
!matrix(o, RAD_BF16, rows, hc * n) || o.data == h.data)
|
||||
return RAD_E_SHAPE;
|
||||
/* RADIANCE_MHC_POST_VEC=0 keeps the per-output kernel, for the microbenchmark. */
|
||||
const char* vec = std::getenv("RADIANCE_MHC_POST_VEC");
|
||||
const auto aligned = [](const RadTensor& t) {
|
||||
return ((uintptr_t)t.data & 15) == 0 && t.stride[0] % 8 == 0;
|
||||
};
|
||||
if ((!vec || vec[0] == '1') && hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
|
||||
if (hc == 4 && n % 8 == 0 && aligned(x) && aligned(h) && aligned(o))
|
||||
return R4D_EMIT(stream, mhc_post_vec_kernel, dim3((n / 8 + 255) / 256, (unsigned)rows),
|
||||
dim3(256), 0, (const uint16_t*)x.data, (const uint16_t*)h.data,
|
||||
(const float*)p.data, (const float*)c.data, (uint16_t*)o.data, n,
|
||||
|
||||
+10
-44
@@ -19,31 +19,11 @@ struct ProjectMeta {
|
||||
long xr, xh, wp, yr, yh;
|
||||
int rows, heads;
|
||||
};
|
||||
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. */
|
||||
__global__ void project_absorb(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
|
||||
const int col = blockIdx.x * 128 + threadIdx.x, head = blockIdx.y, r = blockIdx.z;
|
||||
if (col >= 512) return;
|
||||
float sum = 0;
|
||||
for (int j = 0; j < 256; ++j)
|
||||
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
|
||||
bf16_to_f32(w[((long)head * 512 + j) * m.wp + col]), sum);
|
||||
y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
|
||||
}
|
||||
__global__ void project_expand(const uint16_t* x, const uint16_t* w, uint16_t* y, ProjectMeta m) {
|
||||
const int lane = threadIdx.x & 31, col = blockIdx.x * 4 + (threadIdx.x >> 5), head = blockIdx.y,
|
||||
r = blockIdx.z;
|
||||
float sum = 0;
|
||||
for (int j = lane; j < 512; j += 32)
|
||||
sum = fmaf(bf16_to_f32(x[(long)r * m.xr + head * m.xh + j]),
|
||||
bf16_to_f32(w[((long)head * 512 + 256 + col) * m.wp + j]), sum);
|
||||
#pragma unroll
|
||||
for (int mask = 16; mask; mask >>= 1) sum += __shfl_xor(sum, mask, 32);
|
||||
if (!lane) y[(long)r * m.yr + head * m.yh + col] = f32_to_bf16(sum);
|
||||
}
|
||||
/* project_absorb and project_expand with R rows a thread (absorb) or a wave (expand): each weight
|
||||
* element is loaded once for R rows. Every row's sum runs over j in the same order, and
|
||||
* r4d_xor_sum<32> exchanges as the shuffle loop does, so the bytes match the one-row kernels.
|
||||
* A tail group past the last row reads that row again and stores nothing for it. */
|
||||
/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows
|
||||
* a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's
|
||||
* sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then
|
||||
* r4d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the
|
||||
* last row reads that row again and stores nothing for it. */
|
||||
template <int R>
|
||||
__global__ void project_absorb_rows(const uint16_t* x, const uint16_t* w, uint16_t* y,
|
||||
ProjectMeta m) {
|
||||
@@ -122,24 +102,11 @@ int project_body(const RadArgs* a, RadStream stream) {
|
||||
return RAD_E_SHAPE;
|
||||
const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0],
|
||||
y.stride[1], (int)x.shape[0], (int)h };
|
||||
/* RADIANCE_MLA_PROJECT: `old` the one-row kernels on shuffle sums, the reference the selftest
|
||||
* holds the row forms to byte for byte; 1, 2, 4 or 8 pins the rows a thread (absorb) or a
|
||||
* wave (expand). */
|
||||
const char* form = std::getenv("RADIANCE_MLA_PROJECT");
|
||||
const auto* xp = (const uint16_t*)x.data;
|
||||
const auto* wp = (const uint16_t*)w.data;
|
||||
auto* yp = (uint16_t*)y.data;
|
||||
if (form && !std::strcmp(form, "old")) {
|
||||
if (absorb)
|
||||
return R4D_EMIT(stream, project_absorb, dim3(4, h, m.rows), dim3(128), 0, xp, wp, yp,
|
||||
m);
|
||||
return R4D_EMIT(stream, project_expand, dim3(64, h, m.rows), dim3(128), 0, xp, wp, yp, m);
|
||||
}
|
||||
const long R = form && *form ? std::strtol(form, nullptr, 10)
|
||||
: m.rows >= 8 ? 8
|
||||
: m.rows >= 4 ? 4
|
||||
: m.rows >= 2 ? 2
|
||||
: 1;
|
||||
/* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */
|
||||
const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1;
|
||||
#define MLA_PROJECT_ROWS(RR) \
|
||||
do { \
|
||||
const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \
|
||||
@@ -639,10 +606,9 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
// Vectors need every cache row on a sixteen-byte boundary.
|
||||
const bool wide = g_mla_matrix_form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
|
||||
!(kv.stride[2] % 8);
|
||||
/* RADIANCE_MLA_PAIR=pos keeps the positional pairing, for comparison; the union's LDS lists
|
||||
* hold a table of at most kUnionBlocks entries. */
|
||||
const char* pairing = std::getenv("RADIANCE_MLA_PAIR");
|
||||
const bool by_page = !(pairing && !std::strcmp(pairing, "pos")) && bt.shape[1] <= kUnionBlocks;
|
||||
/* The union's LDS lists hold a table of at most kUnionBlocks entries; a wider table takes the
|
||||
* positional pairing. */
|
||||
const bool by_page = bt.shape[1] <= kUnionBlocks;
|
||||
const bool stats = MATRIX && env_on("RADIANCE_MLA_CONFLICT_STATS");
|
||||
Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2],
|
||||
bt.stride[0], bt.stride[1], len.stride[0], o.stride[0],
|
||||
|
||||
+28
-11
@@ -837,9 +837,11 @@ extern "C" int r4d_sigmoid_bf16(long x, long y, int M, int n, int x_ld, int y_ld
|
||||
// y[m, i] = v over an [M, n] extent with a row pitch, for a rank with nothing to compute whose
|
||||
// downstream reader (an all-reduce, a residual) still needs a defined buffer. A memset cannot
|
||||
// handle the pitch or a two-byte value.
|
||||
__global__ __launch_bounds__(kThreads) void fill_kernel(uint16_t* __restrict__ y, uint32_t n,
|
||||
uint32_t y_ld, uint16_t v) {
|
||||
uint16_t* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
|
||||
// T is the element's bits: uint16_t for bf16, uint32_t for f32.
|
||||
template<typename T>
|
||||
__global__ __launch_bounds__(kThreads) void fill_kernel(T* __restrict__ y, uint32_t n,
|
||||
uint32_t y_ld, T v) {
|
||||
T* __restrict__ yr = y + (size_t)blockIdx.x * y_ld;
|
||||
for (uint32_t i = threadIdx.x; i < n; i += kThreads) yr[i] = v;
|
||||
}
|
||||
|
||||
@@ -854,8 +856,20 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s
|
||||
if (!y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!y_ld) y_ld = n;
|
||||
hipLaunchKernelGGL(fill_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream,
|
||||
(uint16_t*)y, (uint32_t)n, (uint32_t)y_ld, f32_to_bf16_host(value));
|
||||
hipLaunchKernelGGL(fill_kernel<uint16_t>, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (uint16_t*)y, (uint32_t)n, (uint32_t)y_ld,
|
||||
f32_to_bf16_host(value));
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
extern "C" int r4d_fill_f32(long y, int M, int n, int y_ld, float value, long stream) {
|
||||
if (!y) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (!y_ld) y_ld = n;
|
||||
uint32_t bits;
|
||||
std::memcpy(&bits, &value, sizeof bits);
|
||||
hipLaunchKernelGGL(fill_kernel<uint32_t>, dim3((uint32_t)M), dim3(kThreads), 0,
|
||||
(hipStream_t)stream, (uint32_t*)y, (uint32_t)n, (uint32_t)y_ld, bits);
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
|
||||
@@ -1306,8 +1320,10 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* x = r4d_opt(a, CS_X);
|
||||
const RadTensor* y = r4d_opt(a, CS_Y);
|
||||
if (!x || !y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(x));
|
||||
R4D_NEED(dt_bf16(y));
|
||||
/* A copy at the dtype both sides share: bf16, or f32 (a latent kept aside and put back). */
|
||||
if (x->dtype != y->dtype || (x->dtype != RAD_BF16 && x->dtype != RAD_F32))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long es = x->dtype == RAD_F32 ? 4 : 2;
|
||||
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1319,7 +1335,7 @@ extern "C" int r4d_rad_cast(const RadArgs* a, RadStream s) {
|
||||
* while the source holds the live rows, so the source need only have at least as many. */
|
||||
if (M <= 0 || Mx < M) return R4D_NO(RAD_E_SHAPE);
|
||||
|
||||
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * 2, x_ld * 2, n * 2, M,
|
||||
return r4d_p2p_copy2d(r4d_addr(y), r4d_addr(x), y_ld * es, x_ld * es, n * es, M,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
@@ -1566,7 +1582,7 @@ extern "C" int r4d_rad_sigmoid(const RadArgs* a, RadStream s) {
|
||||
extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* y = r4d_opt(a, 0);
|
||||
if (!y) return R4D_NO(RAD_E_INVAL);
|
||||
R4D_NEED(dt_bf16(y));
|
||||
if (y->dtype != RAD_BF16 && y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1));
|
||||
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long M = 0;
|
||||
@@ -1574,8 +1590,9 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) {
|
||||
if (y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (M <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
const double v = r4d_getf(a, "value", 0.0);
|
||||
return r4d_fill_bf16(r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v,
|
||||
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
const int e = (y->dtype == RAD_F32 ? r4d_fill_f32 : r4d_fill_bf16)(
|
||||
r4d_addr(y), (int)M, (int)n, (int)y_ld, (float)v, (long)(uintptr_t)s);
|
||||
return e == 0 ? RAD_OK : RAD_E_DEVICE;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ logit_softcap */
|
||||
|
||||
+121
-308
@@ -10,14 +10,14 @@
|
||||
#include "r4d_mxfp4.h"
|
||||
#include <climits>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
struct MxMeta {
|
||||
long wstep[2], sstep[2];
|
||||
int wrow[2], srow[2], n[2], k[2];
|
||||
long ar, asr, yr;
|
||||
int T, Arows, N, K, experts, topk, sorted_a, tile, parts, aligned_jobs;
|
||||
int T, Arows, N, K, experts, topk, sorted_a, parts;
|
||||
int stage_out, out16;
|
||||
};
|
||||
__device__ const uint8_t* entry(const void* base, long step, int e) {
|
||||
@@ -26,96 +26,43 @@ __device__ const uint8_t* entry(const void* base, long step, int e) {
|
||||
/* E2M1 values are exactly representable in E4M3. Stage those codes directly,
|
||||
* use FP8 WMMA, and fold each 32-wide E8M0 scale into the F32 accumulator.
|
||||
* No persistent expansion or checkpoint relayout is needed. */
|
||||
// Four independent bytes: magnitudes >=2 map to (m+12)*4; 0/1 map to 0/48.
|
||||
// Expand each magnitude-test bit into a byte mask without cross-byte carries.
|
||||
__device__ __forceinline__ uint32_t fp4x4(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return ((((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4));
|
||||
}
|
||||
/* Eight codes of a packed word to their E4M3 bytes in k order. The table form (r4d_mxfp4.h, v_perm
|
||||
* on the magnitude) gives the same bytes in about a third of the instructions; the arithmetic form
|
||||
* stays reachable (RADIANCE_MXFP4_LUT=0) as the bytewise reference. */
|
||||
template <bool Lut>
|
||||
/* Eight codes of a packed word to their E4M3 bytes in k order, by table (r4d_mxfp4.h, v_perm on
|
||||
* the magnitude): the bytes of the bytewise arithmetic decode in about a third of the
|
||||
* instructions. */
|
||||
__device__ __forceinline__ uint2 mx_codes8(uint32_t packed) {
|
||||
if constexpr (Lut) {
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact(packed, &lo, &hi);
|
||||
return uint2{ lo, hi };
|
||||
} else {
|
||||
const uint32_t low = fp4x4(packed & 0x0f0f0f0fu), high = fp4x4((packed >> 4) & 0x0f0f0f0fu);
|
||||
return uint2{ __byte_perm(low, high, 0x5140), __byte_perm(low, high, 0x7362) };
|
||||
}
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact(packed, &lo, &hi);
|
||||
return uint2{ lo, hi };
|
||||
}
|
||||
template <int ColTiles, int RowTiles, bool CachedRows, bool Lut>
|
||||
/* The row-group form: a one-wave block per (16 columns, 16 sorted rows), the rows split at each
|
||||
* expert boundary. */
|
||||
__global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const void* w0,
|
||||
const void* s0, const void* w1, const void* s1,
|
||||
const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
__shared__ __align__(16) uint8_t aa[16 * RowTiles * 136], bb[16 * ColTiles * 136];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5,
|
||||
col0 = blockIdx.x * (16 * ColTiles);
|
||||
constexpr int JobRows = 16 * RowTiles, Threads = 32 * ColTiles * RowTiles;
|
||||
const int wave_col = ColTiles == 1 ? 0 : wave % ColTiles,
|
||||
wave_row = RowTiles == 1 ? 0 : wave / ColTiles;
|
||||
int first = blockIdx.y * m.tile;
|
||||
int group_end = min((int)(blockIdx.y + 1) * m.tile, m.T), job_expert = 0;
|
||||
if (m.aligned_jobs) {
|
||||
// Expert e begins at job floor(offset[e]/JobRows)+e. The extra job per expert
|
||||
// bounds padding without a prefix-sum pass; every live job owns one row tile
|
||||
// of one expert, so hot experts still spread across independent CTAs.
|
||||
const int job = blockIdx.y, tail = offset[m.experts] / JobRows + m.experts;
|
||||
if (job >= tail) {
|
||||
const int r0 = offset[m.experts] + (job - tail) * JobRows;
|
||||
for (int r = r0; r < min(r0 + JobRows, m.T); ++r)
|
||||
if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)r * m.yr + col0 + tid] = 0;
|
||||
return;
|
||||
__shared__ __align__(16) uint8_t aa[16 * 136], bb[16 * 136];
|
||||
const int tid = threadIdx.x, lane = tid & 31, col0 = blockIdx.x * 16;
|
||||
const int first = blockIdx.y * 16, group_end = min((int)(blockIdx.y + 1) * 16, m.T);
|
||||
for (int start = first; start < group_end;) {
|
||||
if (sorted[start] < 0 || offset[m.experts] <= start) {
|
||||
if (tid < 16 && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0;
|
||||
++start;
|
||||
continue;
|
||||
}
|
||||
int lo = 0, hi = m.experts;
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offset[mid] / JobRows + mid <= job)
|
||||
if (offset[mid] <= start)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
job_expert = lo;
|
||||
first = offset[lo] + (job - (offset[lo] / JobRows + lo)) * JobRows;
|
||||
group_end = min(first + JobRows, offset[lo + 1]);
|
||||
}
|
||||
for (int start = first; start < group_end;) {
|
||||
if (sorted[start] < 0 || offset[m.experts] <= start) {
|
||||
if (tid < 16 * ColTiles && col0 + tid < m.N) y[(long)start * m.yr + col0 + tid] = 0;
|
||||
++start;
|
||||
continue;
|
||||
}
|
||||
int lo = m.aligned_jobs ? job_expert : 0, hi = m.experts;
|
||||
if (!m.aligned_jobs)
|
||||
while (lo + 1 < hi) {
|
||||
const int mid = (lo + hi) / 2;
|
||||
if (offset[mid] <= start)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
const int cls = lo & 1, end = min(group_end, offset[lo + 1]);
|
||||
if (end <= start) return;
|
||||
const auto* w = entry(cls ? w1 : w0, m.wstep[cls], lo / 2);
|
||||
const auto* ws = entry(cls ? s1 : s0, m.sstep[cls], lo / 2);
|
||||
auto total = r4d_fp8::acc_zero();
|
||||
// Routing is invariant across K; each activation scale covers all four groups.
|
||||
int sources[8];
|
||||
if constexpr (CachedRows) {
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row;
|
||||
const int flat = r < end ? sorted[r] : -1;
|
||||
const int ar = flat < 0 ? -1 : m.sorted_a ? r : flat / m.topk;
|
||||
sources[row] = ar >= 0 && ar < m.Arows ? ar : -1;
|
||||
}
|
||||
}
|
||||
for (int kb = 0; kb < m.k[cls]; kb += 128) {
|
||||
for (int j = tid; j < 16 * RowTiles * 16; j += Threads) {
|
||||
for (int j = tid; j < 16 * 16; j += 32) {
|
||||
const int r = j / 16, d = (j % 16) * 8;
|
||||
const int ar = start + r < end && sorted[start + r] >= 0
|
||||
? (m.sorted_a ? start + r : sorted[start + r] / m.topk)
|
||||
@@ -124,56 +71,40 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo
|
||||
if (ar >= 0 && ar < m.Arows) __builtin_memcpy(&av, a + (long)ar * m.ar + kb + d, 8);
|
||||
*reinterpret_cast<uint2*>(aa + r * 136 + d) = av;
|
||||
}
|
||||
for (int j = tid; j < 16 * ColTiles * 16; j += Threads) {
|
||||
for (int j = tid; j < 16 * 16; j += 32) {
|
||||
const int r = j / 16, d = (j % 16) * 8;
|
||||
const int n = col0 + r, part = n / (m.N / m.parts), within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
uint32_t packed = 0;
|
||||
if (n < m.N && within < m.n[cls] / m.parts)
|
||||
__builtin_memcpy(&packed, w + (long)wn * m.wrow[cls] + (kb + d) / 2, 4);
|
||||
*reinterpret_cast<uint2*>(bb + r * 136 + d) = mx_codes8<Lut>(packed);
|
||||
*reinterpret_cast<uint2*>(bb + r * 136 + d) = mx_codes8(packed);
|
||||
}
|
||||
__syncthreads();
|
||||
if (start + wave_row * 16 < end) {
|
||||
const int n = col0 + wave_col * 16 + (lane & 15), part = n / (m.N / m.parts),
|
||||
within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
const bool valid = n < m.N && within < m.n[cls] / m.parts;
|
||||
float activation[8];
|
||||
if constexpr (CachedRows) {
|
||||
const int n = col0 + (lane & 15), part = n / (m.N / m.parts),
|
||||
within = n % (m.N / m.parts);
|
||||
const int wn = part * (m.n[cls] / m.parts) + within;
|
||||
const bool valid = n < m.N && within < m.n[cls] / m.parts;
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row)
|
||||
activation[row] =
|
||||
sources[row] >= 0 ? as[(long)sources[row] * m.asr + kb / 128] : 0;
|
||||
}
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127;
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
#pragma unroll
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const int exp = valid ? ws[(long)wn * m.srow[cls] + kb / 32 + group] : 127;
|
||||
auto raw = r4d_fp8::acc_zero();
|
||||
for (int k = group * 32; k < (group + 1) * 32; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, 0, k, lane),
|
||||
r4d_fp8::frag<128>(bb, 0, k, lane), raw);
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127,
|
||||
// a representable subnormal, and code 255 is NaN.
|
||||
const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? ((uint32_t)exp << 23)
|
||||
: 0x00400000u);
|
||||
#pragma unroll
|
||||
for (int k = group * 32; k < (group + 1) * 32; k += 16)
|
||||
raw = r4d_fp8::mma(r4d_fp8::frag<128>(aa, wave_row * 16, k, lane),
|
||||
r4d_fp8::frag<128>(bb, wave_col * 16, k, lane), raw);
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127,
|
||||
// a representable subnormal, and code 255 is NaN.
|
||||
const float scale = __uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? ((uint32_t)exp << 23)
|
||||
: 0x00400000u);
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
if constexpr (CachedRows) {
|
||||
if (sources[row] >= 0) total[row] += raw[row] * activation[row] * scale;
|
||||
} else {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row;
|
||||
if (r < end) {
|
||||
const int ar = sorted[r] < 0 ? -1
|
||||
: m.sorted_a ? r
|
||||
: sorted[r] / m.topk;
|
||||
if (ar >= 0 && ar < m.Arows)
|
||||
total[row] +=
|
||||
raw[row] * as[(long)ar * m.asr + kb / 128] * scale;
|
||||
}
|
||||
}
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + (lane >> 4) * 8 + row;
|
||||
if (r < end) {
|
||||
const int ar = sorted[r] < 0 ? -1 : m.sorted_a ? r : sorted[r] / m.topk;
|
||||
if (ar >= 0 && ar < m.Arows)
|
||||
total[row] += raw[row] * as[(long)ar * m.asr + kb / 128] * scale;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -181,8 +112,7 @@ __global__ void moe_mxfp4_fp8_kernel(const uint8_t* a, const float* as, const vo
|
||||
}
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) {
|
||||
const int r = start + wave_row * 16 + (lane >> 4) * 8 + row,
|
||||
n = col0 + wave_col * 16 + (lane & 15);
|
||||
const int r = start + (lane >> 4) * 8 + row, n = col0 + (lane & 15);
|
||||
if (r < end && n < m.N) y[(long)r * m.yr + n] = f32_to_bf16(total[row]);
|
||||
}
|
||||
start = end;
|
||||
@@ -201,18 +131,20 @@ __device__ __forceinline__ r4d_u32x4 mx_ldg16(const uint8_t* p) {
|
||||
__device__ __forceinline__ uint32_t mx_ldg4(const uint8_t* p) {
|
||||
return *(const __attribute__((address_space(1))) mx_g4*)p;
|
||||
}
|
||||
/* The TP8 prefill form (M32N64, aligned jobs, cached rows) with its loads a stage ahead. A job's
|
||||
* row table resolves into LDS once; the next 128 of K (activation bytes, weight codes, an exponent
|
||||
* dword a column, the activation scales) is loaded into registers while the current stage computes
|
||||
* from LDS. The form above waits on three dependent latencies a stage: the routing entry, the
|
||||
* activation row it names, and the exponent bytes it reads after the barrier. A job begins at its
|
||||
* first row even when that slot is dropped; rows are independent, so the bytes are the same.
|
||||
/* The GLM prefill form: jobs of 32 rows of one expert by 64 columns, eight waves, with its loads a
|
||||
* stage ahead. Expert e begins at job floor(offset[e]/32)+e: the extra job per expert bounds the
|
||||
* padding without a prefix-sum pass, and every live job owns one row tile of one expert, so hot
|
||||
* experts still spread across independent blocks. A job's row table resolves into LDS once; the
|
||||
* next 128 of K (activation bytes, weight codes, an exponent dword a column, the activation
|
||||
* scales) is loaded into registers while the current stage computes from LDS, where a form that
|
||||
* loads after the barrier waits on three dependent latencies a stage: the routing entry, the
|
||||
* activation row it names, and the exponent bytes. A job begins at its first row even when that
|
||||
* slot is dropped; rows are independent, so the bytes are the same.
|
||||
* The exponents are decoded once, at staging; the fold carries no row predicate, the epilogue
|
||||
* writes a dropped row's zero instead.
|
||||
* One stage ahead only: a deeper prefetch measured slower on the expert-major forms. The barriers
|
||||
* order LDS only (lds_barrier), so the prefetch stays in flight across them and L0 keeps the
|
||||
* activation rows the next column block reads. */
|
||||
template <bool Lut>
|
||||
__global__ __launch_bounds__(256)
|
||||
R4D_WAVES(16) void moe_mxfp4_prefill_kernel(const uint8_t* a, const float* as, const void* w0,
|
||||
const void* s0, const void* w1, const void* s1,
|
||||
@@ -285,7 +217,7 @@ __global__ __launch_bounds__(256)
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + arow * P + ad) = ra;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8<Lut>(rw[t]);
|
||||
*reinterpret_cast<uint2*>(bb + wcol * P + 2 * wd + 8 * t) = mx_codes8(rw[t]);
|
||||
if (tid < BN) {
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable
|
||||
// subnormal, and code 255 is NaN.
|
||||
@@ -351,13 +283,8 @@ __global__ __launch_bounds__(256)
|
||||
* fresh WMMA pair from zero, folded as (raw * activation scale) * E8M0 scale and added, two
|
||||
* roundings and an add (the unit is built -ffp-contract=off). The tiles of a wave are separate
|
||||
* accumulators, so no element sees another order. `stage_out` writes the output through LDS in
|
||||
* 16-byte rows instead of a lane's 2-byte column stores.
|
||||
*
|
||||
* DB (streamed A only): two LDS stages, one barrier a stage. The next stage is stored into the
|
||||
* other buffer after the current one computes, which every wave last read before the previous
|
||||
* barrier; the single-buffer order needs a second barrier before it may overwrite the stage it
|
||||
* computes from. Same bytes in LDS, same per-element sequence. */
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident, bool DB = false>
|
||||
* 16-byte rows instead of a lane's 2-byte column stores. */
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident>
|
||||
struct MxP64 {
|
||||
static constexpr int Threads = 256, WR = BM / 16, WC = 8 / WR, TC = BN / (16 * WC),
|
||||
KB = StageK / 128;
|
||||
@@ -366,28 +293,27 @@ struct MxP64 {
|
||||
static constexpr int TPA = Threads / BM, ACh = StageK / 16 / TPA, RCh = KR / 16 / TPA;
|
||||
static constexpr int TPW = Threads / BN, WCh = StageK / 32 / TPW,
|
||||
SAK = Resident ? KR / 128 : KB;
|
||||
static constexpr int NB = DB ? 2 : 1, BB = NB * BN * PB > BM *PO ? NB * BN * PB : BM * PO;
|
||||
static constexpr int Lds = NB * (BM * PA + 16 * KB * BN + 4 * SAK * BM) + BB + 4 * BM;
|
||||
static constexpr int BB = BN * PB > BM * PO ? BN * PB : BM * PO;
|
||||
static constexpr int Lds = BM * PA + 16 * KB * BN + 4 * SAK * BM + BB + 4 * BM;
|
||||
// The waves a SIMD the LDS admits (128 KiB a WGP, a block's eight waves over four SIMDs):
|
||||
// stating it keeps the compiler from trading the stage registers for waves it cannot get.
|
||||
static constexpr int Waves = 2 * (131072 / Lds > 8 ? 8 : 131072 / Lds);
|
||||
};
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident, bool DB = false>
|
||||
template <int BM, int BN, int StageK, int CT, bool Resident>
|
||||
__global__ __launch_bounds__(256)
|
||||
R4D_WAVES((MxP64<BM, BN, StageK, CT, Resident, DB>::Waves)) void moe_mxfp4_p64_kernel(
|
||||
R4D_WAVES((MxP64<BM, BN, StageK, CT, Resident>::Waves)) void moe_mxfp4_p64_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
using G = MxP64<BM, BN, StageK, CT, Resident, DB>;
|
||||
using G = MxP64<BM, BN, StageK, CT, Resident>;
|
||||
constexpr int Threads = G::Threads, WC = G::WC, TC = G::TC, KB = G::KB, AK = G::AK, PA = G::PA,
|
||||
PB = G::PB;
|
||||
constexpr int PO = G::PO, TPA = G::TPA, TPW = G::TPW, SAK = G::SAK;
|
||||
static_assert(BM % 16 == 0 && 8 % G::WR == 0 && TC >= 1 && TC * 16 * WC == BN &&
|
||||
(Resident || CT == 1) && G::ACh >= 1 && G::WCh >= 1 && BN * KB <= Threads &&
|
||||
BM * SAK <= Threads && !(DB && Resident) && G::Lds <= 65536,
|
||||
BM * SAK <= Threads && G::Lds <= 65536,
|
||||
"stage chunks must divide evenly over the block, in 64 KiB of LDS");
|
||||
constexpr int NB = G::NB;
|
||||
__shared__ __align__(16) uint8_t aa[NB * BM * PA], bb[G::BB];
|
||||
__shared__ __align__(16) float ss[NB * 4 * KB * BN], sa[NB * SAK * BM];
|
||||
__shared__ __align__(16) uint8_t aa[BM * PA], bb[G::BB];
|
||||
__shared__ __align__(16) float ss[4 * KB * BN], sa[SAK * BM];
|
||||
__shared__ int src[BM];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, wave_row = wave / WC,
|
||||
wave_col = wave % WC;
|
||||
@@ -479,20 +405,19 @@ __global__ __launch_bounds__(256)
|
||||
re = 0x7f7f7f7fu;
|
||||
if (evalid && k0 + ekb * 128 < kc) re = mx_ldg4(ep + (k0 + ekb * 128) / 32);
|
||||
};
|
||||
auto store = [&](int b) {
|
||||
auto store = [&]() {
|
||||
if constexpr (!Resident) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < G::ACh; ++i)
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + b * BM * PA + arow * PA + (a0 + i * TPA) * 16) =
|
||||
ra[i];
|
||||
if (tid < BM * KB) sa[b * SAK * BM + tid] = rsa;
|
||||
*reinterpret_cast<r4d_u32x4*>(aa + arow * PA + (a0 + i * TPA) * 16) = ra[i];
|
||||
if (tid < BM * KB) sa[tid] = rsa;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < G::WCh; ++i) {
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + b * BN * PB + wcol * PB + (w0c + i * TPW) * 32 +
|
||||
8 * t) = mx_codes8<true>(rw[i][t]);
|
||||
*reinterpret_cast<uint2*>(bb + wcol * PB + (w0c + i * TPW) * 32 + 8 * t) =
|
||||
mx_codes8(rw[i][t]);
|
||||
}
|
||||
if (tid < BN * KB) {
|
||||
// E8M0 maps directly to the F32 exponent field; code zero is 2^-127, a representable
|
||||
@@ -500,7 +425,7 @@ __global__ __launch_bounds__(256)
|
||||
#pragma unroll
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
const uint32_t exp = (re >> (8 * g)) & 0xffu;
|
||||
ss[b * 4 * KB * BN + (ekb * 4 + g) * BN + ecol] =
|
||||
ss[(ekb * 4 + g) * BN + ecol] =
|
||||
__uint_as_float(exp == 255 ? 0x7fc00000u
|
||||
: exp ? (exp << 23)
|
||||
: 0x00400000u);
|
||||
@@ -510,32 +435,30 @@ __global__ __launch_bounds__(256)
|
||||
r4d_fp8::f8v total[TC];
|
||||
#pragma unroll
|
||||
for (int t = 0; t < TC; ++t) total[t] = r4d_fp8::acc_zero();
|
||||
auto compute = [&](int s, int b) {
|
||||
auto compute = [&](int s) {
|
||||
const int k0 = (s % ksn) * StageK;
|
||||
const uint8_t *ab = aa + b * BM * PA, *bp = bb + b * BN * PB;
|
||||
const float* sp = ss + b * 4 * KB * BN;
|
||||
#pragma unroll
|
||||
for (int kb = 0; kb < KB; ++kb) {
|
||||
if (k0 + kb * 128 >= kc) break;
|
||||
const float* sar = sa + b * SAK * BM + (Resident ? k0 / 128 + kb : kb) * BM + rowbase;
|
||||
const float* sar = sa + (Resident ? k0 / 128 + kb : kb) * BM + rowbase;
|
||||
float activation[8];
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row) activation[row] = sar[row];
|
||||
const int ka = (Resident ? k0 : 0) + kb * 128;
|
||||
#pragma unroll
|
||||
for (int group = 0; group < 4; ++group) {
|
||||
const auto fa0 = r4d_fp8::frag<AK>(ab, wave_row * 16, ka + group * 32, lane);
|
||||
const auto fa1 = r4d_fp8::frag<AK>(ab, wave_row * 16, ka + group * 32 + 16, lane);
|
||||
const auto fa0 = r4d_fp8::frag<AK>(aa, wave_row * 16, ka + group * 32, lane);
|
||||
const auto fa1 = r4d_fp8::frag<AK>(aa, wave_row * 16, ka + group * 32 + 16, lane);
|
||||
#pragma unroll
|
||||
for (int t = 0; t < TC; ++t) {
|
||||
auto raw = r4d_fp8::mma(
|
||||
fa0, r4d_fp8::frag<StageK>(bp, colw + t * 16, kb * 128 + group * 32, lane),
|
||||
fa0, r4d_fp8::frag<StageK>(bb, colw + t * 16, kb * 128 + group * 32, lane),
|
||||
r4d_fp8::acc_zero());
|
||||
raw = r4d_fp8::mma(
|
||||
fa1,
|
||||
r4d_fp8::frag<StageK>(bp, colw + t * 16, kb * 128 + group * 32 + 16, lane),
|
||||
r4d_fp8::frag<StageK>(bb, colw + t * 16, kb * 128 + group * 32 + 16, lane),
|
||||
raw);
|
||||
const float scale = sp[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)];
|
||||
const float scale = ss[(kb * 4 + group) * BN + colw + t * 16 + (lane & 15)];
|
||||
// A dropped row folds zeros (or NaN under a code-255 scale) and is written as 0.
|
||||
#pragma unroll
|
||||
for (int row = 0; row < 8; ++row)
|
||||
@@ -586,21 +509,11 @@ __global__ __launch_bounds__(256)
|
||||
}
|
||||
};
|
||||
load(0);
|
||||
if constexpr (DB) {
|
||||
store(0);
|
||||
lds_barrier();
|
||||
}
|
||||
for (int s = 0; s < S; ++s) {
|
||||
if constexpr (DB) {
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s, s & 1);
|
||||
if (s + 1 < S) store((s + 1) & 1);
|
||||
} else {
|
||||
store(0);
|
||||
lds_barrier();
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s, 0);
|
||||
}
|
||||
store();
|
||||
lds_barrier();
|
||||
if (s + 1 < S) load(s + 1);
|
||||
if (live) compute(s);
|
||||
lds_barrier();
|
||||
if (s % ksn == ksn - 1) {
|
||||
epilogue(colb + (s / ksn) * BN);
|
||||
@@ -620,7 +533,7 @@ __global__ __launch_bounds__(256)
|
||||
* A stage of StageK of K is loaded into registers while the previous one computes from LDS; at
|
||||
* gate_up's K of 4096 the 256 stage measured fastest. Block row `experts` zeroes the dropped rows
|
||||
* past offset[experts]. */
|
||||
template <int Waves, int StageK, bool Lut>
|
||||
template <int Waves, int StageK>
|
||||
__global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
@@ -715,7 +628,7 @@ __global__ __launch_bounds__(32 * Waves) void moe_mxfp4_expert_kernel(
|
||||
const uint32_t q[4] = { rw[i].x, rw[i].y, rw[i].z, rw[i].w };
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8<Lut>(q[t]);
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8(q[t]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < SChunks; ++i) {
|
||||
@@ -777,7 +690,7 @@ struct MxStage {
|
||||
uint32_t s[SChunks];
|
||||
float sa;
|
||||
};
|
||||
template <int StageK, int ColTiles, bool Lut>
|
||||
template <int StageK, int ColTiles>
|
||||
__global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel(
|
||||
const uint8_t* a, const float* as, const void* w0, const void* s0, const void* w1,
|
||||
const void* s1, const int* sorted, const int* offset, uint16_t* y, MxMeta m) {
|
||||
@@ -870,8 +783,7 @@ __global__ __launch_bounds__(128) void moe_mxfp4_expert_staged_kernel(
|
||||
d = (j % (StageK / 32)) * 16;
|
||||
#pragma unroll
|
||||
for (int t = 0; t < 4; ++t)
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) =
|
||||
mx_codes8<Lut>(R.w[i][t]);
|
||||
*reinterpret_cast<uint2*>(bb + c * P + 2 * d + 8 * t) = mx_codes8(R.w[i][t]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int i = 0; i < St::SChunks; ++i) {
|
||||
@@ -993,78 +905,24 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
m.ar = aq->stride[0];
|
||||
m.asr = as->stride[0];
|
||||
m.yr = y->stride[0];
|
||||
m.tile = m.T < 32 ? 1 : m.T < 128 ? 4 : 16;
|
||||
// Validated GLM projections at TP4 and TP8: retain the small/decode path and other models.
|
||||
const bool glm_prefill = ne == 288 && top == 8 && nn[0] == nn[1] && kk[0] == kk[1] &&
|
||||
((parts == 2 && (nn[0] == 1024 || nn[0] == 512) && kk[0] == 4096) ||
|
||||
(parts == 1 && nn[0] == 4096 && (kk[0] == 512 || kk[0] == 256)));
|
||||
auto enabled = [&](const char* name) {
|
||||
const char* v = std::getenv(name);
|
||||
return v ? v[0] == '1' : glm_prefill;
|
||||
};
|
||||
/* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted
|
||||
* rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form
|
||||
* overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice
|
||||
* 2.2 times less often and wins by a quarter). Other shapes keep the decode band. The environment
|
||||
* moves the bounds, forces either side (RADIANCE_MXFP4_DECODE_EXPERTS 0 or 1) and pins stage
|
||||
* and tiles, for the microbenchmark. */
|
||||
const char* lut_env = std::getenv("RADIANCE_MXFP4_LUT");
|
||||
const bool lut = lut_env ? lut_env[0] == '1' : true;
|
||||
auto env_long = [](const char* name, long dflt) {
|
||||
const char* v = std::getenv(name);
|
||||
return v && *v ? std::strtol(v, nullptr, 10) : dflt;
|
||||
};
|
||||
const long max_t =
|
||||
env_long(m.sorted_a ? "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_DOWN"
|
||||
: "RADIANCE_MXFP4_DECODE_EXPERTS_MAX_T_GATE_UP",
|
||||
glm_prefill && (nn[0] == 512 || kk[0] == 256) ? (m.sorted_a ? 6143 : 768) : 511);
|
||||
const char* experts_env = std::getenv("RADIANCE_MXFP4_DECODE_EXPERTS");
|
||||
const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256);
|
||||
/* The P64 form from a routed-row bound per projection, ahead of the expert-major band (its
|
||||
* down bound overlaps it): gate_up from 769 rows, where the prefill forms begin, down from
|
||||
* 20 rows an expert at GLM's 288. Default at GLM's TP8 slices only, the measured ones
|
||||
* (RADIANCE_MXFP4_PREFILL_P64=0 keeps the TP8 prefill form of stage 1, which also takes a grid
|
||||
* P64 cannot address). The
|
||||
* tile follows the rows an expert, measured at the TP8 slices (perfmx, cold): down BM32 BN64
|
||||
* K128 over four column tiles up to 3072 tokens (2048: 647 against 831 us), above BM64 BN128
|
||||
* K128 x4 with the LDS output (4096: 1101 against 1607); gate_up BM32 BN64 K256 up to 1536
|
||||
* tokens (768: 563 against 660), BM64 BN64 K256 up to 3072 (2048: 941 against 995), above
|
||||
* BM64 BN128 K128 with the LDS output (4096: 1715 against 1915). BM, BN, stage, column tiles,
|
||||
* the LDS output, the double buffer and the three row bounds move with the environment, and a
|
||||
* forced expert-major form (DECODE_EXPERTS=1) keeps precedence. */
|
||||
const char* p64_env = std::getenv("RADIANCE_MXFP4_PREFILL_P64");
|
||||
const bool resident = m.K <= 256;
|
||||
long dbm = 32, dbn = 64, dsk = 128, dout = 0;
|
||||
if (resident) {
|
||||
if (m.T >= env_long("RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE", 24576)) {
|
||||
dbm = 64;
|
||||
dbn = 128;
|
||||
dout = 1;
|
||||
}
|
||||
} else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BM64", 12288))
|
||||
dsk = 256;
|
||||
else if (m.T < env_long("RADIANCE_MXFP4_PREFILL_P64_T_BN128", 24576)) {
|
||||
dbm = 64;
|
||||
dsk = 256;
|
||||
} else {
|
||||
dbm = 64;
|
||||
dbn = 128;
|
||||
dout = 1;
|
||||
}
|
||||
const long bm = env_long("RADIANCE_MXFP4_PREFILL_P64_BM", dbm) == 32 ? 32 : 64;
|
||||
const bool tp8 = glm_prefill && (nn[0] == 512 || kk[0] == 256);
|
||||
if ((p64_env ? p64_env[0] == '1' : tp8) && !(experts_env && experts_env[0] == '1') &&
|
||||
m.T >= env_long(m.sorted_a ? "RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN"
|
||||
: "RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP",
|
||||
m.sorted_a ? 5760 : 769) &&
|
||||
(m.T + bm - 1) / bm + m.experts <= 65535) {
|
||||
const long bn = env_long("RADIANCE_MXFP4_PREFILL_P64_BN", dbn) == 64 ? 64 : 128;
|
||||
const long sk = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_K", dsk) == 256 ? 256 : 128;
|
||||
const long ct = resident && env_long("RADIANCE_MXFP4_PREFILL_P64_COLTILES", 4) != 1 ? 4 : 1;
|
||||
m.stage_out = env_long("RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT", dout) == 1;
|
||||
// The double buffer exists where two stages fit in 64 KiB of LDS: every 128 stage, and
|
||||
// the 256 stage at BM32 BN64.
|
||||
const bool db = !resident && env_long("RADIANCE_MXFP4_PREFILL_P64_DB", 0) == 1 &&
|
||||
(sk == 128 || (bm == 32 && bn == 64));
|
||||
* 20 rows an expert at GLM's 288. At GLM's TP8 slices only, the measured ones; a grid P64
|
||||
* cannot address takes the forms below. The tile follows the rows an expert, measured at the
|
||||
* TP8 slices (perfmx, cold): down BM32 BN64 K128 over four column tiles up to 3072 tokens
|
||||
* (2048: 647 against 831 us), above BM64 BN128 K128 x4 with the LDS output (4096: 1101
|
||||
* against 1607); gate_up BM32 BN64 K256 up to 1536 tokens (768: 563 against 660), BM64 BN64
|
||||
* K256 up to 3072 (2048: 941 against 995), above BM64 BN128 K128 with the LDS output (4096:
|
||||
* 1715 against 1915). */
|
||||
const bool resident = m.K <= 256, wide = m.T >= 24576;
|
||||
const long bm = wide || (!resident && m.T >= 12288) ? 64 : 32;
|
||||
if (tp8 && m.T >= (m.sorted_a ? 5760 : 769) && (m.T + bm - 1) / bm + m.experts <= 65535) {
|
||||
m.stage_out = wide;
|
||||
m.out16 = (reinterpret_cast<uintptr_t>(y->data) & 15) == 0 && m.yr % 8 == 0;
|
||||
const long jobs = (m.T + bm - 1) / bm + m.experts;
|
||||
#define MX_P64(BM, BN, SK, CT, R) \
|
||||
@@ -1072,85 +930,40 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
dim3(((long)m.N + BN * CT - 1) / (BN * CT), jobs), dim3(256), 0, \
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \
|
||||
s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
#define MX_P64D(BM, BN, SK) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_p64_kernel<BM, BN, SK, 1, false, true>), \
|
||||
dim3(((long)m.N + BN - 1) / BN, jobs), dim3(256), 0, (const uint8_t*)aq->data, \
|
||||
(const float*)as->data, w[0]->data, s[0]->data, w[1]->data, s[1]->data, \
|
||||
(const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
if (db) {
|
||||
if (sk == 256) return MX_P64D(32, 64, 256);
|
||||
if (bm == 32) return bn == 64 ? MX_P64D(32, 64, 128) : MX_P64D(32, 128, 128);
|
||||
return bn == 64 ? MX_P64D(64, 64, 128) : MX_P64D(64, 128, 128);
|
||||
}
|
||||
#undef MX_P64D
|
||||
#define MX_P64_SK(BM, BN, CT, R) \
|
||||
return sk == 256 ? MX_P64(BM, BN, 256, CT, R) : MX_P64(BM, BN, 128, CT, R);
|
||||
#define MX_P64_BN(BM, CT, R) \
|
||||
if (bn == 64) { MX_P64_SK(BM, 64, CT, R) } \
|
||||
MX_P64_SK(BM, 128, CT, R)
|
||||
#define MX_P64_BM(CT, R) \
|
||||
if (bm == 32) { MX_P64_BN(32, CT, R) } \
|
||||
MX_P64_BN(64, CT, R)
|
||||
if (!resident) { MX_P64_BM(1, false) }
|
||||
if (ct == 1) { MX_P64_BM(1, true) }
|
||||
MX_P64_BM(4, true)
|
||||
#undef MX_P64_BM
|
||||
#undef MX_P64_BN
|
||||
#undef MX_P64_SK
|
||||
if (resident) return wide ? MX_P64(64, 128, 128, 4, true) : MX_P64(32, 64, 128, 4, true);
|
||||
if (wide) return MX_P64(64, 128, 128, 1, false);
|
||||
return bm == 64 ? MX_P64(64, 64, 256, 1, false) : MX_P64(32, 64, 256, 1, false);
|
||||
#undef MX_P64
|
||||
}
|
||||
if (experts_env ? experts_env[0] == '1' : max_t < 0 || m.T <= max_t) {
|
||||
const long stage = env_long("RADIANCE_MXFP4_EXPERTS_STAGE_K", m.K <= 256 ? 128 : 256);
|
||||
const long tiles = env_long("RADIANCE_MXFP4_EXPERTS_COLTILES", m.K <= 256 ? 4 : 1);
|
||||
/* The expert-major form up to a routed-row bound per projection (token rows: gate_up, sorted
|
||||
* rows: down), measured at GLM's TP8 slices: gate_up up to 768 rows, where the prefill form
|
||||
* overtakes it, down up to 6143 rows (at 8192 the pipelined prefill form reads the slice
|
||||
* 2.2 times less often and wins by a quarter). Other shapes keep the decode band. A K of 256
|
||||
* takes 128 stages over four column tiles, a longer K the 256 stage over one. */
|
||||
if (m.T <= (tp8 ? (m.sorted_a ? 6143 : 768) : 511)) {
|
||||
#define MX_EXPERTS(KERNEL, C) \
|
||||
R4D_EMIT(stream, KERNEL, dim3(((long)m.N + 64 * C - 1) / (64 * C), m.experts + 1), dim3(128), \
|
||||
0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \
|
||||
(uint16_t*)y->data, m)
|
||||
#define MX_EXPERTS_LUT(L) \
|
||||
if (stage == 128) \
|
||||
return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4, L>), 4) \
|
||||
: MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 1, L>), 1); \
|
||||
return tiles == 4 ? MX_EXPERTS((moe_mxfp4_expert_staged_kernel<256, 4, L>), 4) \
|
||||
: MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256, L>), 1);
|
||||
if (lut) { MX_EXPERTS_LUT(true) }
|
||||
MX_EXPERTS_LUT(false)
|
||||
#undef MX_EXPERTS_LUT
|
||||
if (m.K <= 256) return MX_EXPERTS((moe_mxfp4_expert_staged_kernel<128, 4>), 4);
|
||||
return MX_EXPERTS((moe_mxfp4_expert_kernel<4, 256>), 1);
|
||||
#undef MX_EXPERTS
|
||||
}
|
||||
m.aligned_jobs = enabled("RADIANCE_MXFP4_ALIGNED_JOBS") && m.T >= 512;
|
||||
const bool wide = enabled("RADIANCE_MXFP4_PREFILL_N32") && m.T >= 512;
|
||||
const bool tall = wide && m.aligned_jobs && enabled("RADIANCE_MXFP4_PREFILL_M32");
|
||||
const int job_rows = tall ? 32 : 16;
|
||||
const int jobs =
|
||||
m.aligned_jobs ? (m.T + job_rows - 1) / job_rows + m.experts : (m.T + m.tile - 1) / m.tile;
|
||||
/* From 512 routed rows (past the expert-major band) the GLM prefill form at GLM's slices, in
|
||||
* jobs of 32 rows of one expert; elsewhere the row groups, 16 sorted rows a block. */
|
||||
const bool pipe = glm_prefill && m.T >= 512;
|
||||
const int jobs = pipe ? (m.T + 31) / 32 + m.experts : (m.T + 15) / 16;
|
||||
if (jobs > 65535) return RAD_E_SHAPE;
|
||||
#define MX_EMIT(CT, RT, CACHE, L) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_fp8_kernel<CT, RT, CACHE, L>), \
|
||||
dim3(((long)m.N + 16 * CT - 1) / (16 * CT), jobs), dim3(32 * CT * RT), 0, \
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, w[1]->data, \
|
||||
s[1]->data, (const int*)sorted->data, (const int*)off->data, (uint16_t*)y->data, m)
|
||||
#define MX_PIPE(L) \
|
||||
R4D_EMIT(stream, (moe_mxfp4_prefill_kernel<L>), dim3(((long)m.N + 63) / 64, jobs), dim3(256), \
|
||||
0, (const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data, \
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data, \
|
||||
(uint16_t*)y->data, m)
|
||||
const char* cached = std::getenv("RADIANCE_MXFP4_PREFILL_CACHE_ROWS");
|
||||
const bool pipe = enabled("RADIANCE_MXFP4_PREFILL_PIPE");
|
||||
#define MX_EMIT_LUT(L) \
|
||||
if (tall && enabled("RADIANCE_MXFP4_PREFILL_N64")) { \
|
||||
if (cached ? cached[0] == '1' : glm_prefill) \
|
||||
return pipe ? MX_PIPE(L) : MX_EMIT(4, 2, true, L); \
|
||||
return MX_EMIT(4, 2, false, L); \
|
||||
} \
|
||||
if (tall) return MX_EMIT(2, 2, false, L); \
|
||||
if (wide) return MX_EMIT(2, 1, false, L); \
|
||||
return MX_EMIT(1, 1, false, L);
|
||||
if (lut) { MX_EMIT_LUT(true) }
|
||||
MX_EMIT_LUT(false)
|
||||
#undef MX_EMIT_LUT
|
||||
#undef MX_PIPE
|
||||
#undef MX_EMIT
|
||||
if (pipe)
|
||||
return R4D_EMIT(stream, moe_mxfp4_prefill_kernel, dim3(((long)m.N + 63) / 64, jobs),
|
||||
dim3(256), 0, (const uint8_t*)aq->data, (const float*)as->data,
|
||||
w[0]->data, s[0]->data, w[1]->data, s[1]->data, (const int*)sorted->data,
|
||||
(const int*)off->data, (uint16_t*)y->data, m);
|
||||
return R4D_EMIT(stream, moe_mxfp4_fp8_kernel, dim3(((long)m.N + 15) / 16, jobs), dim3(32), 0,
|
||||
(const uint8_t*)aq->data, (const float*)as->data, w[0]->data, s[0]->data,
|
||||
w[1]->data, s[1]->data, (const int*)sorted->data, (const int*)off->data,
|
||||
(uint16_t*)y->data, m);
|
||||
}
|
||||
}
|
||||
extern "C" int r4d_rad_moe_mxfp4(const RadArgs* a, RadStream stream) { return body(a, stream); }
|
||||
@@ -164,6 +164,10 @@ int r4d_rad_seg_sinusoid (const RadArgs*, RadStream);
|
||||
* (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_cross (const RadArgs*, RadStream);
|
||||
int r4d_rad_table_add (const RadArgs*, RadStream);
|
||||
int r4d_rad_mix_rows (const RadArgs*, RadStream);
|
||||
int r4d_rad_chan_stats (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);
|
||||
@@ -204,6 +208,7 @@ int r4d_rad_interleave2 (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_dense_small_h256 (const RadArgs*, RadStream);
|
||||
int r4d_rad_iota (const RadArgs*, RadStream);
|
||||
int r4d_rad_cu_repeat (const RadArgs*, RadStream);
|
||||
int r4d_rad_int_affine (const RadArgs*, RadStream);
|
||||
/* r4d_video.hip */
|
||||
int r4d_rad_rms_mod (const RadArgs*, RadStream);
|
||||
int r4d_rad_rms_mod_quant_fp8 (const RadArgs*, RadStream);
|
||||
@@ -221,6 +226,21 @@ int r4d_rad_tconv_dw (const RadArgs*, RadStream);
|
||||
int r4d_rad_resize_bilinear (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_fold (const RadArgs*, RadStream);
|
||||
int r4d_rad_flow_renoise (const RadArgs*, RadStream);
|
||||
int r4d_rad_rope_split (const RadArgs*, RadStream);
|
||||
int r4d_rad_head_gate (const RadArgs*, RadStream);
|
||||
int r4d_rad_ltx_guide (const RadArgs*, RadStream);
|
||||
int r4d_rad_pixel_norm (const RadArgs*, RadStream);
|
||||
int r4d_rad_d2s3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_s2d3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_pix_patch (const RadArgs*, RadStream);
|
||||
int r4d_rad_patch_pix8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_vol_index (const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_na3d (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_grid (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_crop (const RadArgs*, RadStream);
|
||||
int r4d_rad_tile_stitch (const RadArgs*, RadStream);
|
||||
int r4d_rad_stft_logmel (const RadArgs*, RadStream);
|
||||
int r4d_rad_bwe_up (const RadArgs*, RadStream);
|
||||
/* r4d_vsa.hip: video sparse attention's selection (scratch for the tile means) and attention. */
|
||||
int r4d_rad_vsa_select (const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_vsa_select_scratch (const RadArgs*);
|
||||
@@ -280,6 +300,24 @@ int64_t r4d_rad_attn_decode_h256_gqa6_scratch(const RadArgs*);
|
||||
* kernel; see attn_decode_gq_h256_gqa6_fp8kv. */
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_fp8(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_bf16(const RadArgs*, RadStream);
|
||||
/* The fp8_v4 and k6_v4 caches on both: prefill, decode, and decode with the gate and quantiser in
|
||||
* the merge (R4D_ATTN_V4 in r4d_attn_paged_gqa8.hip). */
|
||||
int r4d_rad_attn_prefill_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa12_fp8v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa12_k6v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa12_k6v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_fp8v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch(const RadArgs*);
|
||||
int r4d_rad_attn_prefill_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int r4d_rad_attn_decode_gq_h256_gqa6_k6v4(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_attn_decode_h256_gqa6_k6v4_scratch(const RadArgs*);
|
||||
|
||||
/* -- gated delta net (r4d_gdn_*.hip) -- */
|
||||
int r4d_rad_gdn_chunk_scan (const RadArgs*, RadStream);
|
||||
|
||||
+589
-22
@@ -188,6 +188,23 @@ static const RadOperandSpec oAttnDense[] = {
|
||||
{ "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pAttnCross[] = {
|
||||
P_INT("M"), P_INT("head_dim"), P_INT("gqa"), P_INT("causal"), P_STR("dtype"),
|
||||
P_F64O("scale"),
|
||||
};
|
||||
static const RadOperandSpec oAttnCross[] = {
|
||||
{ "q", RAD_OPD_IN, 0 },
|
||||
{ "k", RAD_OPD_IN, 0 },
|
||||
{ "v", RAD_OPD_IN, 0 },
|
||||
{ "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "cu_k", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pAttnNa3d[] = { P_INT("M"), P_INT("head_dim"), P_INT("kt"), P_INT("kh"),
|
||||
P_INT("kw"), P_STR("dtype"), P_F64O("scale") };
|
||||
static const RadOperandSpec oAttnNa3d[] = { { "q", RAD_OPD_IN, 0 }, { "k", RAD_OPD_IN, 0 },
|
||||
{ "v", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "out", RAD_OPD_OUT, 0 } };
|
||||
|
||||
/* Not docs/OPS.md's `qk_norm_rope` (qkv in place, `theta`): this kernel splits a packed [q|gate]
|
||||
* projection per head, writes q, k and the gate to three destinations, and takes a precomputed
|
||||
@@ -2257,6 +2274,20 @@ static const RadOperandSpec oLnModQ[] = {
|
||||
{ "scale", RAD_OPD_OUT, 0 }, { "z", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
/* `act` is the gate's activation, "tanh" (the default) or "none". */
|
||||
static const RadParamSpec pTableAdd[] = { P_INT("M"), P_INT("n"), P_INT("L"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTableAdd[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "t", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pMixRows[] = { P_INT("M"), P_INT("n"), P_INT("k"), P_STR("dtype") };
|
||||
static const RadParamSpec pChanStats[] = { P_INT("M"), P_INT("n"), P_STR("mode"), P_INTO("var"),
|
||||
P_F64O("eps"), P_STR("dtype") };
|
||||
static const RadOperandSpec oChanStats[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "mean", RAD_OPD_WEIGHT, 0 }, { "s", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadOperandSpec oMixRows[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pGateAdd[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_STRO("act") };
|
||||
static const RadOperandSpec oGateAdd[] = {
|
||||
{ "y", RAD_OPD_IN, 0 }, { "g", RAD_OPD_IN, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
@@ -2408,6 +2439,8 @@ static const RadParamSpec pIota[] = { P_INT("M"), P_INT("start"), P_INT("step"),
|
||||
static const RadOperandSpec oIota[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadOperandSpec oCuRepeat[] = { { "len", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pSnakeAa[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_INT("k"),
|
||||
P_INTO("log"), P_STR("dtype") };
|
||||
static const RadOperandSpec oSnakeAa[] = {
|
||||
@@ -2419,17 +2452,19 @@ static const RadOperandSpec oSnakeAa[] = {
|
||||
/* ---- video generation (r4d_video.hip); the same specs as libref's (ref_registry.cpp). `geom` is
|
||||
* the request's latent geometry, i32 on the device. */
|
||||
static const RadParamSpec pRmsMod[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INTO("gated"),
|
||||
P_STR("dtype") };
|
||||
P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsMod[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "z", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pRmsModQ[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_INT("group"),
|
||||
P_INT("gated"), P_STR("dtype") };
|
||||
P_INT("gated"), P_STR("dtype"), P_F64O("wadd"),
|
||||
P_INTO("norm_once"), P_STRO("norm") };
|
||||
static const RadOperandSpec oRmsModQ[] = {
|
||||
{ "y", RAD_OPD_IN, 1 }, { "g", RAD_OPD_IN, 1 }, { "s", RAD_OPD_IN, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
{ "w", RAD_OPD_WEIGHT, 1 }, { "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 oFlowX0[] = {
|
||||
@@ -2464,7 +2499,8 @@ static const RadOperandSpec oGridPos3[] = { { "y", RAD_OPD_OUT, 0 } };
|
||||
/* ---- a video latent upscaler (r4d_upscaler.hip); the same specs as libref's. `geom` is the
|
||||
* request's volume, i32 on the device; patch_fold takes patch_unfold's specs. */
|
||||
static const RadParamSpec pConv3d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("kt"), P_STR("dtype") };
|
||||
P_INT("kt"), P_STR("dtype"), P_STRO("tpad"),
|
||||
P_INTO("tpre") };
|
||||
static const RadOperandSpec oConv3d[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "b", RAD_OPD_WEIGHT, 0 },
|
||||
{ "geom", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 },
|
||||
@@ -2489,6 +2525,64 @@ static const RadOperandSpec oFlowRenoise[] = {
|
||||
{ "sigma", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
/* ---- LTX-2 (r4d_ltx.hip); the same specs as libref's. */
|
||||
static const RadParamSpec pRopeSplit[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_INT("dim"), P_INT("n_dims"), P_F64("theta"),
|
||||
P_STR("max"), P_INTO("head0"), P_STR("dtype") };
|
||||
static const RadOperandSpec oRopeSplit[] = {
|
||||
{ "x", RAD_OPD_INOUT, 0 }, { "positions", RAD_OPD_IN, 0 },
|
||||
};
|
||||
static const RadParamSpec pHeadGate[] = { P_INT("M"), P_INT("n_head"), P_INT("head_dim"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oHeadGate[] = { { "g", RAD_OPD_IN, 0 }, { "x", RAD_OPD_INOUT, 0 } };
|
||||
static const RadParamSpec pLtxGuide[] = { P_INT("M"), P_INT("n"), P_STR("dtype") };
|
||||
static const RadOperandSpec oLtxGuide[] = {
|
||||
{ "vc", RAD_OPD_IN, 0 }, { "vu", RAD_OPD_IN, 1 }, { "vs", RAD_OPD_IN, 1 },
|
||||
{ "vm", RAD_OPD_IN, 1 }, { "scales", RAD_OPD_IN, 0 }, { "sched", RAD_OPD_IN, 0 },
|
||||
{ "stats", RAD_OPD_INOUT, 0 }, { "x", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
/* LTX-2's VAE, audio VAE and vocoder (r4d_ltx.hip); `geom` is x's volume, i32 on the device. */
|
||||
static const RadParamSpec pPixelNorm[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("form"),
|
||||
P_STRO("act"), P_INTO("ileave"), P_STR("dtype"),
|
||||
P_F64O("mult") };
|
||||
static const RadOperandSpec oPixelNorm[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pD2s3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"),
|
||||
P_INT("sw"), P_INTO("drop"), P_STR("dtype") };
|
||||
static const RadOperandSpec oD2s3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pS2d3d[] = { P_INT("M"), P_INT("C"), P_INT("st"), P_INT("sh"),
|
||||
P_INT("sw"), P_INTO("tpre"), P_INTO("group"),
|
||||
P_STR("mode"), P_INTO("add"), P_STR("dtype") };
|
||||
static const RadOperandSpec oS2d3d[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_INOUT, 0 } };
|
||||
static const RadParamSpec pPixPatch[] = { P_INT("M"), P_INT("p"), P_INT("C"), P_STRO("order"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oPixPatch[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pVolIndex[] = { P_INT("M") };
|
||||
static const RadOperandSpec oVolIndex[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileGrid[] = { P_INT("M"), P_INT("tile"), P_INT("stride"), P_STRO("rule"),
|
||||
P_INTO("min"), P_INTO("tile_t"), P_INTO("stride_t"),
|
||||
P_INTO("min_t"), P_INTO("tail") };
|
||||
static const RadOperandSpec oTileGrid[] = { { "geom", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileCrop[] = { P_INT("M"), P_INT("C"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileCrop[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "box", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pTileStitch[] = { P_INT("M"), P_INT("tile"), P_INT("stride"),
|
||||
P_STRO("rule"), P_INTO("min"), P_INTO("tile_t"),
|
||||
P_INTO("stride_t"), P_INTO("min_t"), P_INT("scale"),
|
||||
P_INTO("scale_t"), P_INT("p"), P_INT("C"),
|
||||
P_STRO("order"), P_STR("dtype") };
|
||||
static const RadOperandSpec oTileStitch[] = { { "x", RAD_OPD_IN, 0 }, { "geom", RAD_OPD_IN, 0 },
|
||||
{ "first", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pStftMel[] = { P_INT("M"), P_INT("hop"), P_INT("nfft"), P_INT("n_mel"),
|
||||
P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oStftMel[] = { { "x", RAD_OPD_IN, 0 }, { "basis", RAD_OPD_WEIGHT, 0 },
|
||||
{ "mel", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } };
|
||||
static const RadParamSpec pBweUp[] = { P_INT("M"), P_INT("ratio"), P_INT("ch"), P_STR("dtype") };
|
||||
static const RadOperandSpec oBweUp[] = { { "x", RAD_OPD_IN, 0 }, { "res", RAD_OPD_IN, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 } };
|
||||
|
||||
/* ---- video sparse attention (r4d_vsa.hip); the same specs as libref's. `segs` cuts the packed
|
||||
* rows into dense segments and the video grid, `geom` is the request's latent geometry; `sel` is
|
||||
* vsa_select's output and attn_vsa's input. `v` of vsa_select is read only for `coarse`. */
|
||||
@@ -2761,6 +2855,12 @@ static const RadOpSchema kSchemas[] = {
|
||||
"dense attention over cu_seqlens segments (rows cu/cu_div), with attn_paged's window "
|
||||
"rule over a segment's positions and optional blocks of `block` rows that attend "
|
||||
"within themselves."),
|
||||
SCHEMA("attn_cross", pAttnCross, oAttnCross,
|
||||
"attn_dense with each entry's keys a run of their own: queries rows [cu[s], cu[s+1]), "
|
||||
"keys and values rows [cu_k[s], cu_k[s+1]); `causal` counts from each run's start."),
|
||||
SCHEMA("attn_na3d", pAttnNa3d, oAttnNa3d,
|
||||
"3-D neighborhood attention over the voxels of geom = (T, H, W): each query sees the "
|
||||
"kt x kh x kw window centred on it, shifted inward at the border."),
|
||||
SCHEMA("qk_norm_rope_gate", pQkNormRopeGate, oQkNormRopeGate,
|
||||
"split [q|gate] per head, QK RMS norm over the head, partial NeoX RoPE and the gate "
|
||||
"copy, in one pass. Not docs/OPS.md's qk_norm_rope: different operands, and a "
|
||||
@@ -3137,6 +3237,14 @@ static const RadOpSchema kSchemas[] = {
|
||||
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("table_add", pTableAdd, oTableAdd,
|
||||
"y[r, l n + c] = x[r, c] + t[l, c]: a shared modulation row plus each of L learned rows, "
|
||||
"f32 sum rounded once."),
|
||||
SCHEMA("chan_stats", pChanStats, oChanStats,
|
||||
"a latent through per-channel statistics held as weights: denorm rd(rd(x std) + mean), "
|
||||
"norm rd(rd(x - mean) / std); std is s, or sqrt(s + eps) with var 1."),
|
||||
SCHEMA("mix_rows", pMixRows, oMixRows,
|
||||
"y[r, c] = sum_i w[i] x[r k + i, c], i < k: a Linear(k, 1) across k consecutive rows."),
|
||||
SCHEMA("gate_add", pGateAdd, oGateAdd,
|
||||
"x = bf16(x + bf16(bf16(tanh(g[seq])) * y)): a residual through its sequence's gate; "
|
||||
"with `act` none the gate is g itself, x = bf16(x + bf16(g[seq] * y))."),
|
||||
@@ -3205,6 +3313,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("interleave2", pInterleave, oInterleave2, "two streams interleaved."),
|
||||
SCHEMA("iota", pIota, oIota, "y[i] = start + i * step."),
|
||||
SCHEMA("cu_repeat", pCuRepeat, oCuRepeat, "bounds of equal sequences, y[j] = j * len[0] * mult."),
|
||||
SCHEMA("int_affine", pIntAffine, oIntAffine,
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists."),
|
||||
SCHEMA("snake_aa", pSnakeAa, oSnakeAa,
|
||||
"BigVGAN's alias-free SnakeBeta over each sequence, f32: replicate-padded, upsampled "
|
||||
"`ratio` times by `f_up`, SnakeBeta, filtered by `f_down` at stride `ratio`."),
|
||||
@@ -3247,6 +3357,44 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("flow_renoise", pFlowRenoise, oFlowRenoise,
|
||||
"x = (1 - sigma) x + sigma z, z the (seed, stream) normal stream at element k n + c, "
|
||||
"each step one f32 rounding."),
|
||||
SCHEMA("rope_split", pRopeSplit, oRopeSplit,
|
||||
"LTX-2's split rotary over fractional coordinates: the pairs of all heads on one "
|
||||
"ladder, the first `pad` unrotated, the axes interleaved; each head's halves turned "
|
||||
"against each other in f32."),
|
||||
SCHEMA("head_gate", pHeadGate, oHeadGate,
|
||||
"x = rd(x rd(2 rd(sigmoid(g)))) for each head's values."),
|
||||
SCHEMA("ltx_guide", pLtxGuide, oLtxGuide,
|
||||
"LTX-2's sampler step: the passes' clean estimates combined (CFG, STG, modality), an "
|
||||
"optional rescale by the deviations' ratio, the velocity back and the Euler step, f32."),
|
||||
SCHEMA("pixel_norm", pPixelNorm, oPixelNorm,
|
||||
"an RMS norm over each row's n values as bf16 tensors compute it, every step rounded "
|
||||
"to y's dtype; rsqrt or div form, optionally silu; `ileave` L writes x's row t L + l "
|
||||
"to columns c L + l of y's row t."),
|
||||
SCHEMA("d2s3d", pD2s3d, oD2s3d,
|
||||
"depth to space over voxel rows, the first st - 1 frames dropped."),
|
||||
SCHEMA("s2d3d", pS2d3d, oS2d3d,
|
||||
"space to depth over voxel rows, `tpre` leading frames prepended: a packed row each "
|
||||
"box (copy) or each `group` packed channels averaged (mean); `add` adds into y."),
|
||||
SCHEMA("pix_patch", pPixPatch, oPixPatch,
|
||||
"an image [H, W C] to patch rows [H/p, (W/p) C p p], order wh or hw."),
|
||||
SCHEMA("patch_pix8", pPixPatch, oPixPatch,
|
||||
"patch rows [R, w C p p] to RGB bytes [R p, w p C] by to_rgba8's rule."),
|
||||
SCHEMA("vol_index", pVolIndex, oVolIndex,
|
||||
"a volume's voxel coordinates (t, i, j), component-major."),
|
||||
SCHEMA("tile_grid", pTileGrid, oTileGrid,
|
||||
"the tiles of a grid as diffusers cuts them (rule stride or intervals), in space and "
|
||||
"optionally time, one row (t, h, w, t0, y0, x0, k, count) a tile."),
|
||||
SCHEMA("tile_crop", pTileCrop, oTileCrop,
|
||||
"one tile's voxels out of a volume, box (t, h, w, t0, y0, x0)."),
|
||||
SCHEMA("tile_stitch", pTileStitch, oTileStitch,
|
||||
"decoded tiles to RGB bytes: diffusers' in-place blend_v then blend_h, then blend_t "
|
||||
"across time bands, each tile kept to its stride, patch_pix8's bytes."),
|
||||
SCHEMA("stft_logmel", pStftMel, oStftMel,
|
||||
"each channel's causal log-mel spectrogram from a windowed DFT basis and a mel "
|
||||
"filterbank, every stored tensor rounded to y's dtype."),
|
||||
SCHEMA("bwe_up", pBweUp, oBweUp,
|
||||
"y = clamp(rd(res + up(x)), -1, 1), x raised `ratio` times by a Hann-windowed sinc "
|
||||
"resampler."),
|
||||
SCHEMA("vsa_select", pVsa, oVsaSelect,
|
||||
"video sparse attention's selection over tiles of at most 64 rows (dense segments in "
|
||||
"chunks, the video grid in tile_t x tile_h x tile_w boxes): f32 tile means of q and k, "
|
||||
@@ -3504,6 +3652,60 @@ static const RadConstraint cAttnDecodeGqH256G6Bs4Bf16[] = {
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
/* The fp8_v4 and k6_v4 caches on the QSA layers' two ratios (r4d_attn_paged_gqa8.hip's
|
||||
* R4D_ATTN_V4): the fp8 rows' constraints at those kv_dtype values. */
|
||||
static const RadConstraint cAttnPrefillH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G12Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G12K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 12), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 5), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G6Bs4Fp8v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
};
|
||||
static const RadConstraint cAttnDecodeGqH256G6Bs4K6v4[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 6), C_EQ("block_size", 4),
|
||||
C_GE("causal", 0), C_LE("q_len", 10), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "k6_v4"),
|
||||
C_EQ("group", 128), C_IN("act", "sigmoid"),
|
||||
};
|
||||
static const RadConstraint cAttnPrefillH128G8Fp8[] = {
|
||||
C_EQ("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 8), C_EQ("block_size", 16),
|
||||
C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"),
|
||||
@@ -3571,6 +3773,9 @@ static const RadConstraint cAttnLocalRel[] = {
|
||||
};
|
||||
/* `cast` widening bf16 -> f32: an exact conversion, the form a pooled embedding leaves the
|
||||
* device in. */
|
||||
static const RadConstraint cCastF32[] = {
|
||||
C_IN("from", "f32"), C_IN("to", "f32"),
|
||||
};
|
||||
static const RadConstraint cCastWiden[] = {
|
||||
C_IN("from", "bf16"), C_IN("to", "f32"),
|
||||
};
|
||||
@@ -3584,20 +3789,30 @@ static const RadConstraint cCastF16[] = {
|
||||
static const RadConstraint cCastNarrow[] = {
|
||||
C_IN("from", "f32"), C_IN("to", "bf16"),
|
||||
};
|
||||
/* The encoder's dense attention: bidirectional, any window, at the (head_dim, gqa) pairs
|
||||
* r4d_attn_dense_bf16.hip compiles. */
|
||||
/* Dense attention at the (head_dim, gqa) pairs r4d_attn_dense_bf16.hip compiles: an encoder's,
|
||||
* bidirectional with any window, or a text encoder's causal prompt. gqa 1 at 256 and 512 is
|
||||
* attn_dense_small_h256's and the wide kernel's. */
|
||||
/* Causal or not at head_dim 64: a vision tower's heads, and a codec's sliding causal layers. */
|
||||
static const RadConstraint cAttnDenseH64[] = {
|
||||
C_EQ("head_dim", 64), C_EQ("gqa", 1), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G2[] = {
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 2), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G4[] = {
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 256), C_EQ("gqa", 4), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH256G8[] = {
|
||||
C_EQ("head_dim", 256), C_DIV("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G2[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 2), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G4[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 4), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 4), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512G8[] = {
|
||||
C_EQ("head_dim", 512), C_DIV("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
/* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to
|
||||
* 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */
|
||||
@@ -3871,16 +4086,9 @@ static const RadConstraint cMlaProject[] = { C_GE("M", 1),
|
||||
/* The matrix row outranks the wave row (mla_attn_bf16) at every M, the pairing walking the union
|
||||
* of both rows' pages: measured cold on gfx1201 (r4d_selftest --perfmla), a 2048-row chunk
|
||||
* with DSA tables (fill topk:16) takes 7.1 ms against 12.4 ms on the wave row and 13.0 ms on the
|
||||
* positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms.
|
||||
* RADIANCE_MLA_MATRIX_MAX_M lowers the bound, read once as the table loads; 0 is never. */
|
||||
static long long mla_matrix_max_m() {
|
||||
const char* e = std::getenv("RADIANCE_MLA_MATRIX_MAX_M");
|
||||
char* end = nullptr;
|
||||
const long long v = e && *e ? std::strtoll(e, &end, 10) : -1;
|
||||
return end && !*end && v >= 0 ? (v < 65535 ? v : 65535) : 65535;
|
||||
}
|
||||
* positional pairing, fresh 3.8 against 6.3 ms, a decode step of 8x6 rows 0.23 against 0.82 ms. */
|
||||
static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
|
||||
C_LE("M", mla_matrix_max_m()),
|
||||
C_LE("M", 65535),
|
||||
C_EQ("latent_dim", 512),
|
||||
C_GE("heads", 8),
|
||||
C_LE("heads", 64),
|
||||
@@ -4605,6 +4813,16 @@ static const RadConstraint cAttnPrefixSelf[] = {
|
||||
static const RadConstraint cAttnDenseH128[] = {
|
||||
C_EQ("head_dim", 128), C_LE("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnCrossH64[] = {
|
||||
C_EQ("head_dim", 64), C_LE("gqa", 8), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnNa3d[] = { C_EQ("head_dim", 64), C_IN("dtype", "bf16 f32") };
|
||||
static const RadConstraint cAttnDenseH384[] = {
|
||||
C_EQ("head_dim", 384), C_EQ("gqa", 1), C_EQ("causal", 0), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cAttnDenseH512[] = {
|
||||
C_EQ("head_dim", 512), C_EQ("gqa", 1), C_EQ("causal", 0), 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"),
|
||||
};
|
||||
@@ -4729,6 +4947,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr,
|
||||
r4d_shape_cast },
|
||||
|
||||
{ "cast_f32_f32", "cast", "elem",
|
||||
"y = x, f32 to f32 -- a strided row copy through libr4d's 2D copy",
|
||||
"any M and n; both row pitches are read off the operands",
|
||||
"f32 in, f32 out, byte-for-byte",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cCastF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_cast, nullptr, nullptr, nullptr,
|
||||
r4d_shape_cast },
|
||||
|
||||
{ "cast_bf16_f32", "cast", "elem",
|
||||
"y = x, bf16 widened to f32",
|
||||
"any M and n; both row pitches are read off the operands",
|
||||
@@ -5013,6 +5240,15 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr,
|
||||
r4d_shape_fill },
|
||||
|
||||
{ "fill_f32", "fill", "elem",
|
||||
"constant fill, a row a workgroup",
|
||||
"any M, n; a row pitch is honoured",
|
||||
"f32 out, the value exactly",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cF32Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_fill, nullptr, nullptr, nullptr,
|
||||
r4d_shape_fill },
|
||||
|
||||
{ "sigmoid_bf16", "sigmoid", "elem",
|
||||
"logistic sigmoid, grid-strided over the whole extent",
|
||||
"any extent; contiguous in and out",
|
||||
@@ -5791,6 +6027,129 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr,
|
||||
r4d_shape_attn_paged_gate_quant, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
/* The fp8_v4 and k6_v4 caches on Flash-Next's QSA layers: gqa12 at one and two ranks, gqa6 with
|
||||
* 4-token pages at four. A token's row is 400 bytes (E4M3 K, int4 V, f16 group scales) or 352
|
||||
* (int6 K, int4 V); the layouts are RAD_KVQ_*'s (abi/rad_builder.h). */
|
||||
{ "attn_prefill_h256_gqa12_fp8v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G12Fp8v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_fp8v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa12_fp8v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G12Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa12_fp8v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa12_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G12Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_fp8v4, r4d_rad_attn_decode_h256_gqa12_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa12_k6v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G12K6v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa12_k6v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa12_k6v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 12 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G12K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa12_k6v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa12_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G12K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa12_k6v4, r4d_rad_attn_decode_h256_gqa12_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa6_bs4_fp8v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G6Bs4Fp8v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_fp8v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa6_bs4_fp8v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa6_bs4_fp8v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa6_bs4_fp8v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, fp8_v4 kv cache (E4M3 K, int4 V in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G6Bs4Fp8v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_fp8v4, r4d_rad_attn_decode_h256_gqa6_fp8v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h256_gqa6_bs4_k6v4", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, varlen",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL,
|
||||
ROW(cAttnPrefillH256G6Bs4K6v4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa6_k6v4, nullptr, nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_h256_gqa6_bs4_k6v4", "attn_paged", "attn",
|
||||
"paged attention, causal or not, split-KV (decode / speculative verify / draft block)",
|
||||
"head_dim 256, 6 queries per kv head, paged block 4, q_len*gqa <= 64, no window",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 out, f16 partials",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeH256G6Bs4K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr },
|
||||
|
||||
{ "attn_decode_gq_h256_gqa6_bs4_k6v4", "attn_paged_gate_quant", "attn",
|
||||
"paged split-KV decode attention with the output gate and the fp8 quantiser in the merge",
|
||||
"attn_decode_h256_gqa6_bs4_k6v4's geometry; gate_quant_fp8 over the merged (token, head) rows: "
|
||||
"sigmoid only, group 128, the gate 16-byte aligned with a pitch of 8, the codes 8-byte aligned",
|
||||
"bf16 query, k6_v4 kv cache (int6 K, int4 V, each in groups of 32 with f16 scales), bf16 gated out, E4M3 codes with an f32 scale per 128 columns",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE,
|
||||
ROW(cAttnDecodeGqH256G6Bs4K6v4), ROW(tAttnSplit), nullptr,
|
||||
nullptr, nullptr, r4d_rad_attn_decode_gq_h256_gqa6_k6v4, r4d_rad_attn_decode_h256_gqa6_k6v4_scratch,
|
||||
nullptr, nullptr,
|
||||
nullptr, nullptr, r4d_fuse_attn_paged_gate_quant },
|
||||
|
||||
{ "attn_prefill_h128_gqa8_fp8kv", "attn_paged", "attn",
|
||||
"paged causal attention, query-tiled (prefill / chunked prefill)",
|
||||
"head_dim 128, 8 queries per kv head, paged block 16, varlen",
|
||||
@@ -5887,7 +6246,8 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa2_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, two query heads a KV head in one workgroup, the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
@@ -5895,21 +6255,52 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa4_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, four query heads a KV head in one workgroup, the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH256G4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h256_gqa8_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 256, eight query heads a KV head in one workgroup (a multiple of eight as several), "
|
||||
"the key range cut to the window",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH256G8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa2_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, two query heads a KV head in one workgroup",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G2), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa4_bf16", "attn_dense", "attn",
|
||||
"dense bidirectional encoder attention, varlen over cu_seqlens, optional two-sided window",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, four query heads a KV head in one workgroup",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G4), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
{ "attn_dense_h512_gqa8_bf16", "attn_dense", "attn",
|
||||
"dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window, or "
|
||||
"causal with an optional window behind",
|
||||
"head_dim 512 split across two waves, eight query heads a KV head in one workgroup (a "
|
||||
"multiple of eight as several workgroups)",
|
||||
"bf16 query / key / value / out, f16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512G8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense },
|
||||
|
||||
/* -------------------------------------------------------------------------- gated delta net */
|
||||
{ "gdn_chunk_scan_k128_v128_c64_bf16", "gdn_chunk_scan", "gdn",
|
||||
"gated delta net chunked scan: WY recompute, state recurrence and output in one kernel",
|
||||
@@ -7496,6 +7887,46 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cAttnDenseH128), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_h128 },
|
||||
|
||||
{ "attn_cross_h128_bf16", "attn_cross", "attn",
|
||||
"dense varlen attention with the keys bounded apart from the queries (cross attention)",
|
||||
"head_dim 128, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH128), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_cross },
|
||||
|
||||
{ "attn_cross_h64_bf16", "attn_cross", "attn",
|
||||
"dense varlen attention with the keys bounded apart from the queries (cross attention)",
|
||||
"head_dim 64, 1/2/4/8 query heads a KV head; attn_dense_h128's kernel at 64",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnCrossH64), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_cross },
|
||||
|
||||
{ "attn_na3d_h64", "attn_na3d", "attn",
|
||||
"3-D neighborhood attention: a thread a (query, head), the window's keys streamed through the "
|
||||
"caches, libref's two passes",
|
||||
"head_dim 64, any window, row pitches honoured", "bf16 or f32 q / k / v / out, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnNa3d), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_na3d },
|
||||
|
||||
{ "attn_dense_h384_bf16", "attn_dense", "attn",
|
||||
"one 384-wide head over every row of a segment: an image encoder's mid-block attention",
|
||||
"head_dim 384 split across eight waves, 16 queries a workgroup",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH384), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_wide },
|
||||
|
||||
{ "attn_dense_h512_bf16", "attn_dense", "attn",
|
||||
"one 512-wide head over every row of a segment: an image encoder's mid-block attention",
|
||||
"head_dim 512 split across eight waves, 16 queries a workgroup",
|
||||
"bf16 query / key / value / out, bf16 operands, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cAttnDenseH512), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_attn_dense_wide },
|
||||
|
||||
{ "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",
|
||||
@@ -7527,6 +7958,38 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_ln_mod },
|
||||
|
||||
{ "table_add_bf16", "table_add", "elem",
|
||||
"a shared modulation row plus each block's learned table row, every block in one launch",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_table_add },
|
||||
|
||||
{ "chan_stats_bf16", "chan_stats", "elem",
|
||||
"a VAE latent through its per-channel statistics (running mean and variance, or mean and std)",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_chan_stats },
|
||||
|
||||
{ "chan_stats_f32", "chan_stats", "elem",
|
||||
"a latent kept in f32 through its VAE's per-channel statistics",
|
||||
"any M, row pitches honoured",
|
||||
"f32 x and y, bf16 or f32 statistics, every step rounded to f32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cF32Row), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_chan_stats },
|
||||
|
||||
{ "mix_rows_bf16", "mix_rows", "elem",
|
||||
"a learned weighted sum of k consecutive rows (a Linear(k, 1) over a stacked axis)",
|
||||
"any M, row pitches honoured; n a multiple of 8",
|
||||
"bf16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenRows8), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_mix_rows },
|
||||
|
||||
{ "gate_add_bf16", "gate_add", "elem",
|
||||
"x += tanh(gate row) * y, the reference's three roundings; with `act` none the gate as it is",
|
||||
"any M, row pitches honoured",
|
||||
@@ -7809,6 +8272,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_cu_repeat },
|
||||
|
||||
{ "int_affine", "int_affine", "elem",
|
||||
"integers derived from device geometry: one wave, the lists by value", "up to 16 values",
|
||||
"i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_int_affine },
|
||||
|
||||
{ "attn_dense_small_h256_bf16", "attn_dense", "attn",
|
||||
"dense attention over short sequences, causal or not: a depth decoder's frame positions",
|
||||
"head_dim 256, one query head a key head, sequences of at most 32 rows, a workgroup a (sequence, "
|
||||
@@ -7958,6 +8428,103 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenF32), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_flow_renoise },
|
||||
|
||||
{ "rope_split", "rope_split", "elem",
|
||||
"LTX-2's rotary: a workgroup a (head, 64 rows), the head's ladder in LDS, sincosf a pair",
|
||||
"any M, row pitches honoured; head_dim / 2 dividing 256; up to four axes",
|
||||
"bf16 or f32 x, f32 or i32 positions",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rope_split },
|
||||
|
||||
{ "head_gate", "head_gate", "elem",
|
||||
"each head times 2 sigmoid of its logit: a thread a value",
|
||||
"any M, row pitches honoured", "bf16 logits, bf16 or f32 x",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_head_gate },
|
||||
|
||||
{ "ltx_guide", "ltx_guide", "elem",
|
||||
"LTX-2's guided step: f64 deviation sums in up to 1024 parts, then the step in place",
|
||||
"any M and n, row pitches honoured", "f32 latent, bf16 or f32 velocities",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_ltx_guide },
|
||||
|
||||
{ "pixel_norm", "pixel_norm", "norm",
|
||||
"an RMS norm as bf16 tensors compute it: a wave a row, its sum of squares a wave reduction",
|
||||
"any M and n, row pitches honoured", "bf16 or f32 x and y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pixel_norm },
|
||||
|
||||
{ "d2s3d", "d2s3d", "elem",
|
||||
"depth to space over voxel rows: a thread a value, the volume off the device",
|
||||
"any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_d2s3d },
|
||||
|
||||
{ "s2d3d", "s2d3d", "elem",
|
||||
"space to depth over voxel rows, copy or group mean, optionally added: a thread a value",
|
||||
"any C and factors, row pitches honoured", "bf16 or f32 x and y, i32 geom",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_s2d3d },
|
||||
|
||||
{ "pix_patch", "pix_patch", "elem",
|
||||
"an image to patch rows: a thread a value",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x and y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_pix_patch },
|
||||
|
||||
{ "patch_pix8", "patch_pix8", "elem",
|
||||
"patch rows to RGB bytes: a thread a byte",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_patch_pix8 },
|
||||
|
||||
{ "vol_index", "vol_index", "elem",
|
||||
"a volume's voxel coordinates: a thread a voxel", "i32, a dense [3, n]", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vol_index },
|
||||
|
||||
{ "tile_grid", "tile_grid", "elem",
|
||||
"a tiled decode's boxes off a device volume: a thread a row", "contiguous i32", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_grid },
|
||||
|
||||
{ "tile_crop", "tile_crop", "elem",
|
||||
"a tile's voxels out of a volume: a thread a value, the box read on the device",
|
||||
"row pitches honoured", "bf16 or f32 x and y, i32 geom and box",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_crop },
|
||||
|
||||
{ "tile_stitch", "tile_stitch", "elem",
|
||||
"decoded tiles blended to RGB bytes: a thread a byte, up to four tiles read",
|
||||
"dense 2-D operands, row pitches honoured", "bf16 or f32 x, u8 y, i32 geom and first",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_tile_stitch },
|
||||
|
||||
{ "stft_logmel", "stft_logmel", "elem",
|
||||
"a causal log-mel spectrogram: a workgroup a (frame, channel), the frame in LDS",
|
||||
"nfft up to 4096, row pitches honoured", "bf16 or f32 operands",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_stft_logmel },
|
||||
|
||||
{ "bwe_up", "bwe_up", "elem",
|
||||
"a sinc-resampled waveform plus a residual, clamped: a thread a value, the taps by value",
|
||||
"ratio up to 9, row pitches honoured", "bf16 or f32 operands",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGenAnyFloat), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_bwe_up },
|
||||
};
|
||||
|
||||
/* ================================================================================== the exports */
|
||||
|
||||
+1738
-877
File diff suppressed because it is too large.
Load diff
@@ -316,11 +316,11 @@ extern "C" int r4d_shape_cast(const RadParam* p, int n_p, int operand,
|
||||
|
||||
const int64_t M = pi(p, n_p, "M");
|
||||
const int64_t n = pi(p, n_p, "n");
|
||||
/* Three rows serve the op, bf16 -> bf16 (a strided row copy), bf16 -> f32 and bf16 -> f16,
|
||||
* and the shims refuse any other pair, so another pair is declined here. */
|
||||
/* The rows serve bf16 -> bf16 and f32 -> f32 (strided row copies), bf16 -> f32, bf16 -> f16
|
||||
* and f32 -> bf16, and the shims refuse any other pair, so another pair is declined here. */
|
||||
const uint32_t f = dt_par(p, n_p, "from"), t = dt_par(p, n_p, "to");
|
||||
if (f != (uint32_t)RAD_BF16 ||
|
||||
(t != (uint32_t)RAD_BF16 && t != (uint32_t)RAD_F32 && t != (uint32_t)RAD_F16))
|
||||
const uint32_t bf = (uint32_t)RAD_BF16, f32 = (uint32_t)RAD_F32, f16 = (uint32_t)RAD_F16;
|
||||
if (!(f == bf && (t == bf || t == f32 || t == f16)) && !(f == f32 && (t == bf || t == f32)))
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const RadOpdDesc l[] = { opd(f, M, n), opd(t, M, n) };
|
||||
R4D_PICK(l);
|
||||
|
||||
+115
-46
@@ -51,10 +51,49 @@ __device__ __forceinline__ void st8(float* p, const float* f) {
|
||||
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
|
||||
*(float4*)(p + 4) = make_float4(f[4], f[5], f[6], f[7]);
|
||||
}
|
||||
// Eight per-channel values of an f32 or bf16 vector, its dtype known only at run time.
|
||||
__device__ __forceinline__ void ld8w(const void* p, bool f32, int c, float* f) {
|
||||
if (f32) ld8((const float*)p + c, f);
|
||||
else ld8((const uint16_t*)p + c, f);
|
||||
// Four- and two-channel forms of the above, and a chunk of CW (8, 4 or 2) channels through them.
|
||||
__device__ __forceinline__ void ld4(const uint16_t* p, float* f) {
|
||||
const uint2 u = *(const uint2*)p;
|
||||
f[0] = bf16w_lo(u.x); f[1] = bf16w_hi(u.x); f[2] = bf16w_lo(u.y); f[3] = bf16w_hi(u.y);
|
||||
}
|
||||
__device__ __forceinline__ void ld4(const float* p, float* f) {
|
||||
const float4 a = *(const float4*)p;
|
||||
f[0] = a.x; f[1] = a.y; f[2] = a.z; f[3] = a.w;
|
||||
}
|
||||
__device__ __forceinline__ void st4(uint16_t* p, const float* f) {
|
||||
*(uint2*)p = make_uint2(bf16x2_rne(f[0], f[1]), bf16x2_rne(f[2], f[3]));
|
||||
}
|
||||
__device__ __forceinline__ void st4(float* p, const float* f) {
|
||||
*(float4*)p = make_float4(f[0], f[1], f[2], f[3]);
|
||||
}
|
||||
__device__ __forceinline__ void ld2(const uint16_t* p, float* f) {
|
||||
const uint32_t u = *(const uint32_t*)p;
|
||||
f[0] = bf16w_lo(u); f[1] = bf16w_hi(u);
|
||||
}
|
||||
__device__ __forceinline__ void ld2(const float* p, float* f) {
|
||||
const float2 a = *(const float2*)p;
|
||||
f[0] = a.x; f[1] = a.y;
|
||||
}
|
||||
__device__ __forceinline__ void st2(uint16_t* p, const float* f) {
|
||||
*(uint32_t*)p = bf16x2_rne(f[0], f[1]);
|
||||
}
|
||||
__device__ __forceinline__ void st2(float* p, const float* f) {
|
||||
*(float2*)p = make_float2(f[0], f[1]);
|
||||
}
|
||||
template <int CW, typename T> __device__ __forceinline__ void ldc(const T* p, float* f) {
|
||||
if constexpr (CW == 8) ld8(p, f);
|
||||
else if constexpr (CW == 4) ld4(p, f);
|
||||
else ld2(p, f);
|
||||
}
|
||||
template <int CW, typename T> __device__ __forceinline__ void stc(T* p, const float* f) {
|
||||
if constexpr (CW == 8) st8(p, f);
|
||||
else if constexpr (CW == 4) st4(p, f);
|
||||
else st2(p, f);
|
||||
}
|
||||
// CW per-channel values of an f32 or bf16 vector, its dtype known only at run time.
|
||||
template <int CW> __device__ __forceinline__ void ldcw(const void* p, bool f32, int c, float* f) {
|
||||
if (f32) ldc<CW>((const float*)p + c, f);
|
||||
else ldc<CW>((const uint16_t*)p + c, f);
|
||||
}
|
||||
|
||||
// The volume a request runs at: (T, H, W) and its row count, or false for a geometry the operands
|
||||
@@ -101,6 +140,11 @@ __device__ __forceinline__ bool volume_of(const int* geom, long long rows, int*
|
||||
// guarded load instead, its last tile running past K), so neither operand's addresses cost vector
|
||||
// arithmetic per tile.
|
||||
//
|
||||
// `tpad` pads the frames other than with zeros (LTX-2's VAE): 1 replicate, the frame clamped into
|
||||
// the volume; 2 causal, output frame t's tap dt reading frame max(t + dt - 1 - tpre, 0), so the
|
||||
// output has tpre more frames than the input. A neighbour's frame is resolved when its offset is,
|
||||
// once a tap.
|
||||
//
|
||||
// Measured on the R9700 at 300 W, warm, against gemm_nt_bias at bf16 at the same M, N and K = 27
|
||||
// cin: 512 -> 512 at 84 x 48 x 37 148 TFLOP/s (the GEMM 146), at 42 x 24 x 37 149 (145). The
|
||||
// select-and-pointer form of the gather this replaces ran 136 and 134: its loop issued twice the
|
||||
@@ -133,13 +177,13 @@ __device__ __forceinline__ unsigned short conv_finish(float acc, float bv, unsig
|
||||
|
||||
/* `vec` (host-checked): y, res and the bias take 16-byte accesses at every eight-column boundary.
|
||||
* `xrows` bounds the volume the device geometry may name, `xbytes` is x's extent (at most kOob)
|
||||
* and `Mcap` bounds the rows written. */
|
||||
* and `Mcap` bounds the rows written; `tpad` and `tpre` as above. */
|
||||
template <bool C64, bool RES, bool BF32>
|
||||
__global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
const unsigned short* __restrict__ X, const unsigned short* __restrict__ Wt,
|
||||
const void* __restrict__ bias, const unsigned short* R, unsigned short* C,
|
||||
const int* __restrict__ geom, unsigned ldx, unsigned ldr, unsigned ldc, int Mcap, int xrows,
|
||||
unsigned xbytes, int cin, int N, unsigned vec) {
|
||||
unsigned xbytes, int cin, int N, unsigned vec, int tpad, int tpre) {
|
||||
typedef r4d_u32x4 U4;
|
||||
__shared__ __attribute__((aligned(16))) unsigned char s_a[2][kCBM * kCPB];
|
||||
|
||||
@@ -147,7 +191,8 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
long long vol;
|
||||
if (!volume_of(geom, xrows, &gT, &gH, &gW, &vol)) return;
|
||||
const int HW = gH * gW;
|
||||
const int Mv = vol < (long long)Mcap ? (int)vol : Mcap;
|
||||
const long long ovol = vol + (long long)tpre * HW;
|
||||
const int Mv = ovol < (long long)Mcap ? (int)ovol : Mcap;
|
||||
|
||||
const uint32_t tid = threadIdx.x, lane = tid & 31u;
|
||||
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid >> 5);
|
||||
@@ -197,10 +242,14 @@ __global__ __launch_bounds__(kCThreads) R4D_WAVES(6) void conv3d_kernel(
|
||||
const int delta = dt * HW + dy * gW + dx;
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < kCSPT; ++i) {
|
||||
const bool ok = tap < kTaps && (unsigned)(vt[i] + dt) < (unsigned)gT &&
|
||||
int ft = vt[i] + dt;
|
||||
if (tpad == 1) ft = min(max(ft, 0), gT - 1);
|
||||
else if (tpad == 2) ft = max(ft - 1 - tpre, 0);
|
||||
const bool ok = tap < kTaps && vt[i] >= 0 && (unsigned)ft < (unsigned)gT &&
|
||||
(unsigned)(vy[i] + dy) < (unsigned)gH &&
|
||||
(unsigned)(vx[i] + dx) < (unsigned)gW;
|
||||
off[i] = ok ? (uint32_t)(vm[i] + delta) * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
|
||||
const int src = tpad ? (ft * gH + vy[i] + dy) * gW + vx[i] + dx : vm[i] + delta;
|
||||
off[i] = ok ? (uint32_t)src * ldx * 2u + (C64 ? ch * 16u : 0u) : kOob;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -387,9 +436,9 @@ __device__ __forceinline__ void chan_merge(float& n, float& mean, float& m2, flo
|
||||
n = nab;
|
||||
}
|
||||
|
||||
/* `cpr_log`: log2 of the chunks a row (n / 8, a power of two dividing the block); `gs8` the chunks
|
||||
* a group. */
|
||||
template <typename TX>
|
||||
/* `cpr_log`: log2 of the chunks a row (n / CW, a power of two dividing the block); `gs8` the
|
||||
* chunks a group. A chunk is CW channels: 8, or 4 for groups of 4 channels. */
|
||||
template <typename TX, int CW>
|
||||
__global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
|
||||
float* __restrict__ stats, int M, int groups,
|
||||
int cpr_log, int gs8, int ldx, int rpp) {
|
||||
@@ -401,16 +450,16 @@ __global__ __launch_bounds__(kT) void gn_part_kernel(const TX* __restrict__ x,
|
||||
const int r0 = p * rpp, r1 = min(M, r0 + rpp);
|
||||
float cnt = 0.0f, s1 = 0.0f, s2 = 0.0f, shift = 0.0f;
|
||||
for (int r = r0 + slot; r < r1; r += slots) {
|
||||
float v[8];
|
||||
ld8(x + (size_t)r * ldx + c * 8, v);
|
||||
float v[CW];
|
||||
ldc<CW>(x + (size_t)r * ldx + c * CW, v);
|
||||
if (cnt == 0.0f) shift = v[0];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
for (int j = 0; j < CW; ++j) {
|
||||
const float d = v[j] - shift;
|
||||
s1 += d;
|
||||
s2 += d * d;
|
||||
}
|
||||
cnt += 8.0f;
|
||||
cnt += (float)CW;
|
||||
}
|
||||
float mean = 0.0f, m2 = 0.0f;
|
||||
if (cnt > 0.0f) {
|
||||
@@ -466,7 +515,7 @@ __global__ __launch_bounds__(kT) void gn_final_kernel(float* __restrict__ stats,
|
||||
|
||||
/* `wf`, `bf`: the gain's and bias's dtype is f32; `modk` 0 no modulation, 1 a bf16 row, 2 an f32
|
||||
* one. x and y may be the same memory: a thread reads its chunk before it writes it. */
|
||||
template <typename TX, typename TY>
|
||||
template <typename TX, typename TY, int CW>
|
||||
__global__ __launch_bounds__(kT) void gn_apply_kernel(
|
||||
const TX* x, TY* y, const void* __restrict__ w, const void* __restrict__ b,
|
||||
const void* __restrict__ mod, const float* __restrict__ stats, int M, int n, int cpr_log,
|
||||
@@ -475,27 +524,27 @@ __global__ __launch_bounds__(kT) void gn_apply_kernel(
|
||||
const int tid = threadIdx.x;
|
||||
const int r = blockIdx.x * slots + (tid >> cpr_log);
|
||||
if (r >= M) return;
|
||||
const int ck = tid & ((1 << cpr_log) - 1), c = ck * 8;
|
||||
const int ck = tid & ((1 << cpr_log) - 1), c = ck * CW;
|
||||
const int g = ck / gs8;
|
||||
const float mean = stats[2 * g], rstd = stats[2 * g + 1];
|
||||
float v[8], wv[8], bv[8];
|
||||
ld8(x + (size_t)r * ldx + c, v);
|
||||
ld8w(w, wf != 0, c, wv);
|
||||
ld8w(b, bf != 0, c, bv);
|
||||
float v[CW], wv[CW], bv[CW];
|
||||
ldc<CW>(x + (size_t)r * ldx + c, v);
|
||||
ldcw<CW>(w, wf != 0, c, wv);
|
||||
ldcw<CW>(b, bf != 0, c, bv);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
|
||||
for (int j = 0; j < CW; ++j) v[j] = (v[j] - mean) * rstd * wv[j] + bv[j];
|
||||
if (modk) {
|
||||
float sc[8], sf[8];
|
||||
ld8w(mod, modk == 2, c, sc);
|
||||
ld8w(mod, modk == 2, n + c, sf);
|
||||
float sc[CW], sf[CW];
|
||||
ldcw<CW>(mod, modk == 2, c, sc);
|
||||
ldcw<CW>(mod, modk == 2, n + c, sf);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
|
||||
for (int j = 0; j < CW; ++j) v[j] = v[j] * (1.0f + sc[j]) + sf[j];
|
||||
}
|
||||
if (silu) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
|
||||
for (int j = 0; j < CW; ++j) v[j] = v[j] / (1.0f + expf(-v[j]));
|
||||
}
|
||||
st8(y + (size_t)r * ldy + c, v);
|
||||
stc<CW>(y + (size_t)r * ldy + c, v);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------- tconv_dw
|
||||
@@ -720,6 +769,15 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
|
||||
if (r4d_numel(w) < cout * K || r4d_numel(b) < cout || r4d_numel(geom) < 3)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_contig(w) || !r4d_contig(b) || !r4d_contig(geom)) return R4D_NO(RAD_E_STRIDE);
|
||||
const char* tp = r4d_gets(a, "tpad");
|
||||
int tpad = 0;
|
||||
if (tp && *tp) {
|
||||
if (!std::strcmp(tp, "replicate")) tpad = 1;
|
||||
else if (!std::strcmp(tp, "causal")) tpad = 2;
|
||||
else if (std::strcmp(tp, "zero")) return R4D_NO(RAD_E_INVAL);
|
||||
}
|
||||
const long long tpre = r4d_geti_or(a, "tpre", 0);
|
||||
if (tpre < 0 || tpre > 64 || (tpre && tpad != 2)) return R4D_NO(RAD_E_INVAL);
|
||||
long long rx = 0, ldx = 0, ry = 0, rr = 0;
|
||||
if (!rows8(x, cin, &rx, &ldx) || !r4d_aligned(r4d_p(w), 16)) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long ldy = r4d_rows_pitch(y, cout, &ry);
|
||||
@@ -747,7 +805,8 @@ extern "C" int r4d_rad_conv3d_ndhwc(const RadArgs* a, RadStream stream) {
|
||||
#define C3_L(C6, RS, BF) \
|
||||
return R4D_EMIT(stream, (conv3d_kernel<C6, RS, BF>), grid, dim3(kCThreads), 0, Xp, Wp, Bp, Rp, \
|
||||
Cp, (const int*)r4d_p(geom), (unsigned)ldx, (unsigned)ldr, (unsigned)ldy, \
|
||||
(int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec)
|
||||
(int)Mcap, (int)rx, (unsigned)xbytes, (int)cin, (int)cout, vec, tpad, \
|
||||
(int)tpre)
|
||||
#define C3_RES(C6, BF) do { if (res) C3_L(C6, true, BF); C3_L(C6, false, BF); } while (0)
|
||||
#define C3_BF(C6) do { if (bf32) C3_RES(C6, true); C3_RES(C6, false); } while (0)
|
||||
if (c64) C3_BF(true);
|
||||
@@ -774,12 +833,14 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
|
||||
if (!std::strcmp(act, "silu")) silu = 1;
|
||||
else if (std::strcmp(act, "none")) return R4D_NO(RAD_E_INVAL);
|
||||
}
|
||||
/* A thread an 8-channel chunk inside one group, a row's chunks a power of two dividing the
|
||||
* 256-thread block. */
|
||||
const int cpr_log = (n > 0 && !(n & 7)) ? log2_exact(n / 8) : -1;
|
||||
if (cpr_log < 0 || n / 8 > kT || groups <= 0 || groups > kT || n % groups ||
|
||||
(n / groups) % 8)
|
||||
/* A thread a chunk of CW channels inside one group (8; 4 for groups of 4 channels, the
|
||||
* FLUX.2 VAE's 128 channels in 32 groups; 2 for groups of 2), a row's chunks a power of two
|
||||
* dividing the 256-thread block. */
|
||||
if (groups <= 0 || groups > kT || n <= 0 || n % groups || (n / groups) % 2)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const int CW = (n / groups) % 8 == 0 ? 8 : (n / groups) % 4 == 0 ? 4 : 2;
|
||||
const int cpr_log = log2_exact(n / CW);
|
||||
if (cpr_log < 0 || n / CW > kT) return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_numel(w) < n || r4d_numel(b) < n || (mod && r4d_numel(mod) < 2 * n) ||
|
||||
r4d_numel(st) < groups * (2 + 3 * kGnParts))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -797,29 +858,36 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
|
||||
long long rpp = (M + kGnParts - 1) / kGnParts;
|
||||
rpp = (rpp + slots - 1) / slots * slots;
|
||||
const int parts = (int)((M + rpp - 1) / rpp);
|
||||
const int gs8 = (int)(n / groups / 8);
|
||||
const int gs8 = (int)(n / groups / CW);
|
||||
float* S = (float*)r4d_wp(st);
|
||||
const float eps = (float)r4d_getf(a, "eps", 1e-5);
|
||||
int rc;
|
||||
if (is_f32(x))
|
||||
rc = R4D_EMIT(stream, gn_part_kernel<float>, dim3((unsigned)parts), dim3(kT), 0,
|
||||
(const float*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
|
||||
(int)rpp);
|
||||
else
|
||||
rc = R4D_EMIT(stream, gn_part_kernel<uint16_t>, dim3((unsigned)parts), dim3(kT), 0,
|
||||
(const uint16_t*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx,
|
||||
(int)rpp);
|
||||
#define GN_P(TX, C4) \
|
||||
rc = R4D_EMIT(stream, (gn_part_kernel<TX, C4>), dim3((unsigned)parts), dim3(kT), 0, \
|
||||
(const TX*)r4d_p(x), S, (int)M, (int)groups, cpr_log, gs8, (int)ldx, (int)rpp)
|
||||
if (is_f32(x)) {
|
||||
if (CW == 8) GN_P(float, 8);
|
||||
else if (CW == 4) GN_P(float, 4);
|
||||
else GN_P(float, 2);
|
||||
} else {
|
||||
if (CW == 8) GN_P(uint16_t, 8);
|
||||
else if (CW == 4) GN_P(uint16_t, 4);
|
||||
else GN_P(uint16_t, 2);
|
||||
}
|
||||
#undef GN_P
|
||||
if (rc != RAD_OK) return R4D_NO(rc);
|
||||
rc = R4D_EMIT(stream, gn_final_kernel, dim3((unsigned)groups), dim3(kT), 0, S, (int)groups,
|
||||
parts, eps);
|
||||
if (rc != RAD_OK) return R4D_NO(rc);
|
||||
const int modk = !mod ? 0 : is_f32(mod) ? 2 : 1;
|
||||
const dim3 grid((unsigned)((M + slots - 1) / slots));
|
||||
#define GN_A(TX, TY) \
|
||||
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY>), grid, dim3(kT), 0, (const TX*)r4d_p(x), \
|
||||
#define GN_A2(TX, TY, C4) \
|
||||
return R4D_EMIT(stream, (gn_apply_kernel<TX, TY, C4>), grid, dim3(kT), 0, (const TX*)r4d_p(x),\
|
||||
(TY*)r4d_wp(y), r4d_p(w), r4d_p(b), r4d_p(mod), (const float*)S, (int)M, \
|
||||
(int)n, cpr_log, gs8, (int)ldx, (int)ldy, (int)is_f32(w), (int)is_f32(b), \
|
||||
modk, silu)
|
||||
#define GN_A(TX, TY) \
|
||||
do { if (CW == 8) GN_A2(TX, TY, 8); if (CW == 4) GN_A2(TX, TY, 4); GN_A2(TX, TY, 2); } while (0)
|
||||
if (is_f32(x)) {
|
||||
if (is_f32(y)) GN_A(float, float);
|
||||
GN_A(float, uint16_t);
|
||||
@@ -827,6 +895,7 @@ extern "C" int r4d_rad_group_norm(const RadArgs* a, RadStream stream) {
|
||||
if (is_f32(y)) GN_A(uint16_t, float);
|
||||
GN_A(uint16_t, uint16_t);
|
||||
#undef GN_A
|
||||
#undef GN_A2
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ tconv_dw */
|
||||
|
||||
+45
-10
@@ -82,7 +82,8 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
const uint16_t* __restrict__ yd, const uint16_t* __restrict__ g, const uint16_t* __restrict__ s,
|
||||
const uint16_t* __restrict__ w, const int* __restrict__ cu, uint16_t* __restrict__ x,
|
||||
uint8_t* __restrict__ q, float* __restrict__ qs, uint16_t* __restrict__ z, int n, int n_seq,
|
||||
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld) {
|
||||
float eps, int y_ld, int g_ld, int s_ld, int x_ld, int q_ld, int qs_ld, int z_ld, float wadd,
|
||||
int once, int layer, int none) {
|
||||
__shared__ float sh[kT / 32];
|
||||
const int r = blockIdx.x;
|
||||
const int e = seq_of(cu, n_seq, r);
|
||||
@@ -109,7 +110,32 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
for (int j = 0; j < 8; ++j) { v[k][j] = f[j]; ss += f[j] * f[j]; }
|
||||
}
|
||||
}
|
||||
const float rs = 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps);
|
||||
/* A LayerNorm centres first: the mean's block sum, then the centred squares'. */
|
||||
float mu = 0.0f;
|
||||
if (layer) {
|
||||
float sm = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kRmChunks; ++k) {
|
||||
const int i = ((int)threadIdx.x + k * kT) * 8;
|
||||
if (i < n) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) sm += v[k][j];
|
||||
}
|
||||
}
|
||||
mu = block_sum(sm, sh) / (float)n;
|
||||
__syncthreads();
|
||||
ss = 0.0f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kRmChunks; ++k) {
|
||||
const int i = ((int)threadIdx.x + k * kT) * 8;
|
||||
if (i < n) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) { v[k][j] -= mu; ss += v[k][j] * v[k][j]; }
|
||||
}
|
||||
}
|
||||
}
|
||||
/* `none`: no norm (libref's n2 = x); the flag is the same for the whole workgroup. */
|
||||
const float rs = none ? 1.0f : 1.0f / sqrtf(block_sum(ss, sh) / (float)n + eps);
|
||||
const uint16_t* sr = s + (size_t)e * s_ld;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < kRmChunks; ++k) {
|
||||
@@ -118,10 +144,11 @@ __global__ __launch_bounds__(kT) void rms_mod_kernel(
|
||||
float shf[8], scf[8], wf[8], o[8];
|
||||
ld8(sr + i, shf);
|
||||
ld8(sr + n + i, scf);
|
||||
ld8(w + i, wf);
|
||||
if (w) ld8(w + i, wf);
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
const float n2 = bfr(bfr(v[k][j] * rs) * wf[j]);
|
||||
const float n1 = once ? v[k][j] * rs : bfr(v[k][j] * rs);
|
||||
const float n2 = w ? bfr(n1 * (wf[j] + wadd)) : bfr(v[k][j] * rs);
|
||||
o[j] = bfr(bfr(n2 * bfr(1.0f + scf[j])) + shf[j]);
|
||||
}
|
||||
if (z) st8(z + (size_t)r * z_ld + i, o);
|
||||
@@ -431,10 +458,10 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
const RadTensor* q = quant ? r4d_opt(a, 6) : nullptr;
|
||||
const RadTensor* qs = quant ? r4d_opt(a, 7) : nullptr;
|
||||
const RadTensor* z = r4d_opt(a, quant ? 8 : 6);
|
||||
if (!sc || !w || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
|
||||
if (!sc || !cu || !x || (quant ? (!q || !qs) : !z)) return R4D_NO(RAD_E_INVAL);
|
||||
const bool gated = r4d_geti_or(a, "gated", 0) != 0;
|
||||
if (gated && (!y || !g)) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_bf16(x) || !is_bf16(sc) || !is_bf16(w) || !is_i32(cu) ||
|
||||
if (!is_bf16(x) || !is_bf16(sc) || (w && !is_bf16(w)) || !is_i32(cu) ||
|
||||
(gated && (!is_bf16(y) || !is_bf16(g))) || (z && !is_bf16(z)) ||
|
||||
(quant && (q->dtype != RAD_F8E4M3 || qs->dtype != RAD_F32)))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
@@ -445,7 +472,7 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
long long rx = 0, xl = 0, ry = 0, yl = 0, rg = 0, gl = 0, rs = 0, sl = 0, rz = 0, zl = 0;
|
||||
long long rq = 0, rqs = 0, ql = 0, qsl = 0;
|
||||
if (!rows8(x, n, &rx, &xl) || !rows8(sc, 2 * n, &rs, &sl) || !r4d_contig(cu) ||
|
||||
!r4d_contig(w) || ((uintptr_t)w->data & 15) ||
|
||||
(w && (!r4d_contig(w) || ((uintptr_t)w->data & 15))) ||
|
||||
(gated && (!rows8(y, n, &ry, &yl) || !rows8(g, n, &rg, &gl))) ||
|
||||
(z && !rows8(z, n, &rz, &zl)))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
@@ -455,18 +482,26 @@ static int rms_mod_launch(const RadArgs* a, RadStream st, bool quant) {
|
||||
if (ql < 0 || (ql & 7) || ((uintptr_t)q->data & 7) || qsl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
}
|
||||
const long long n_seq = r4d_numel(cu) - 1, rows = quant ? rq : rz;
|
||||
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || r4d_numel(w) < n ||
|
||||
if (rows <= 0 || n_seq <= 0 || rx < rows || rs < n_seq || (w && r4d_numel(w) < n) ||
|
||||
(quant && rqs < rows) || (gated && (ry < rows || rg < n_seq)) || (z && rz < rows))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const float eps = (float)r4d_getf(a, "eps", 1e-6);
|
||||
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
|
||||
const int once = (int)r4d_geti_or(a, "norm_once", 0);
|
||||
const char* nk = r4d_gets(a, "norm");
|
||||
const int layer = nk && !std::strcmp(nk, "layer");
|
||||
const int none = nk && !std::strcmp(nk, "none");
|
||||
if ((nk && !layer && !none && std::strcmp(nk, "rms")) || (none && w)) return R4D_NO(RAD_E_INVAL);
|
||||
#define R4D_RMQ(G, Q) \
|
||||
hipLaunchKernelGGL((rms_mod_kernel<G, Q>), dim3((unsigned)rows), dim3(kT), 0, \
|
||||
(hipStream_t)st, G ? (const uint16_t*)y->data : nullptr, \
|
||||
G ? (const uint16_t*)g->data : nullptr, (const uint16_t*)sc->data, \
|
||||
(const uint16_t*)w->data, (const int*)cu->data, (uint16_t*)x->data, \
|
||||
w ? (const uint16_t*)w->data : nullptr, (const int*)cu->data, \
|
||||
(uint16_t*)x->data, \
|
||||
Q ? (uint8_t*)q->data : nullptr, Q ? (float*)qs->data : nullptr, \
|
||||
z ? (uint16_t*)z->data : nullptr, (int)n, (int)n_seq, eps, (int)yl, \
|
||||
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl)
|
||||
(int)gl, (int)sl, (int)xl, (int)ql, (int)qsl, (int)zl, wadd, once, layer, \
|
||||
none)
|
||||
if (quant) {
|
||||
if (gated) R4D_RMQ(true, true);
|
||||
else R4D_RMQ(false, true);
|
||||
|
||||
Reference in new issue
Block a user