r4d mla_attn: E4M3 latent cache twins of the three rows

mla_attn takes an optional `kv_dtype`; at fp8_e4m3 the cache is E4M3 as kv_store_fp8 writes it at its
default descale of 1. mla_attn_fp8kv, mla_attn_matrix_fp8kv and mla_attn_rows_fp8kv are the bf16
rows' kernels with the cache element as a template parameter: the key load decodes E4M3 to bf16
(v_cvt_pk_f32_fp8, then the high half), which is exact since every E4M3 value is a bf16, so the
tiles and all arithmetic past the load are the bf16 instance's. The twins carry the bf16 rows'
constraints plus kv_dtype fp8_e4m3 and rank above all three bf16 rows, in their order. At uint16_t
the loads are the plain loads the bf16 kernels made; their launchers still refuse any cache that
is not bf16.

r4d_emu test_mla runs every kernel form (wave, matrix and its element load, rows forms 0-3) on E4M3
codes against its bf16 instance on the decoded cache: bit-identical on all 23 form/case pairs, and
each launcher refuses the other cache dtype.
This commit is contained in:
AnimusNull authored and AnimusNull committed 2026-11-05 14:09:13 +00:00
1 parent b632c72f5d
commit 17f0eae420
6 files changed
+249 -24

No files matched your search

+9 -2
View File
@@ -3027,7 +3027,7 @@ order, not a slow one.
| `dsa_pool` | `M`(range) `n` `ratio` `dtype` `block_size`/opt | `kg`, `ape`w → `q`, `scale`; `page`?, `cache`:inout? |
| `dsa_query` | `M`(range) `n` `dtype` | `x` → `q`, `scale` |
| `dsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` `row_part`/opt | `q`, `q_scale`, `gate`, `k`, `k_scale`?, `bt`, `cu`, `nc` → `score`, `cu_part`? |
| `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` | `q`, `kv`, `bt`, `length` → `out` |
| `mla_attn` | `M`(range) `latent_dim` `heads` `blocks` `block_size` `scale`:f64 `dtype` `kv_dtype`/opt | `q`, `kv`, `bt`, `length` → `out` |
| `mla_attn_paged` | `M`(range) `heads` `latent_dim` `rope_dim` `block_size` `scale`:f64 `dtype` | `q`, `q_rope`?, `kv`, `block_table`, `seqused`, `cu_seqlens`, `gate`? → `out` |
| `mla_project` | `M`(range) `heads` `head_dim` `latent_dim` `mode` `dtype` | `a`, `b`w → `y` |
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
@@ -3353,7 +3353,9 @@ fold only after each head's ReLU.
the tail) and is the causal bound: no slot at or past it is read. A missing or out-of-range page
contributes nothing, and a row with no visible key outputs zero. The softmax is f32 and `out` is
rounded once. `scale` is positive and finite and comes from the original query/key head width,
not the latent width (GLM: `1/sqrt(256)` against a latent of 512).
not the latent width (GLM: `1/sqrt(256)` against a latent of 512). `kv_dtype`, when given, is the
cache's dtype and may differ from `dtype`: `fp8_e4m3` is a cache `kv_store` wrote at its default
descale of 1, so each code is read as the value itself.
libr4d has three `mla_attn` rows, all at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the
@@ -3380,6 +3382,11 @@ runs the matrix row's kernel instead. It also takes multiples of 32 heads (two g
workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor
parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`).
Each of the three has an E4M3-cache twin (`mla_attn_fp8kv`, `mla_attn_matrix_fp8kv`,
`mla_attn_rows_fp8kv`) on the same constraints plus `kv_dtype` `fp8_e4m3`, ranked above all three
bf16 rows and in their order. The kernels are the bf16 rows' with the key load decoding E4M3:
every E4M3 value is a bf16, so the decoded tile is exact and the rest of the arithmetic is the bf16
instance's. The bf16 rows state no `kv_dtype` and their launchers refuse an E4M3 cache.
`mla_attn_paged` is the dense, causal form for a model whose MLA keeps a rotary part beside the
latent (Ling-3.0: latent 512, rotary 64, every key visible). A token's cache row is the normed
latent followed by the rotated key part, `latent_dim + rope_dim` wide; it is stored as one KV head
+81 -20
View File
@@ -5,6 +5,7 @@
#include "r4d_args.h"
#include "r4d_common.h"
#include "r4d_emit.h"
#include "r4d_fp8_wmma.h"
#include "r4d_gdn_wmma.h"
#include <algorithm>
#include <climits>
@@ -155,7 +156,49 @@ __device__ void load_latent(const uint16_t* p, float (&v)[16]) {
for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32(p[j]);
}
}
__global__ __launch_bounds__(128) void attend(const uint16_t* q, const uint16_t* kv, const int* bt,
/* The latent cache is bf16, or E4M3 as kv_store_fp8 writes it at its default descale of 1, so a
* code is the value itself. Every E4M3 value is a bf16 (three mantissa bits against seven, an
* exponent range bf16 contains), so an fp8 key decodes exactly to the bf16 the tiles hold and every
* kernel's arithmetic past the load is its bf16 instance's. The loads below are overloaded on the
* cache's element type; at uint16_t each is the plain load the bf16 kernels always made. */
template <bool HI>
__device__ __forceinline__ uint32_t e4m3x2_bf16(uint32_t w) {
const v2f f = r4d_fp8::e4m3_pk<HI>(w);
return (__float_as_uint(f.x) >> 16) | (__float_as_uint(f.y) & 0xffff0000u);
}
__device__ __forceinline__ void load_latent(const uint8_t* p, float (&v)[16]) {
if (!((uintptr_t)p & 15)) {
const uint4 a = *(const uint4*)p;
const uint32_t packed[4] = { a.x, a.y, a.z, a.w };
#pragma unroll
for (int j = 0; j < 4; ++j) {
const v2f lo = r4d_fp8::e4m3_pk<false>(packed[j]),
hi = r4d_fp8::e4m3_pk<true>(packed[j]);
v[4 * j] = lo.x;
v[4 * j + 1] = lo.y;
v[4 * j + 2] = hi.x;
v[4 * j + 3] = hi.y;
}
} else {
#pragma unroll
for (int j = 0; j < 16; ++j) v[j] = r4d_fp8::e4m3(p[j]);
}
}
/* Eight consecutive cache elements as four bf16 pairs: one 16-byte load at bf16, one 8-byte load
* at E4M3. The caller keeps the 16-byte alignment the bf16 load needs, which covers the E4M3 one. */
__device__ __forceinline__ uint4 load8(const uint16_t* p) { return *(const uint4*)p; }
__device__ __forceinline__ uint4 load8(const uint8_t* p) {
const uint2 raw = *(const uint2*)p;
return make_uint4(e4m3x2_bf16<false>(raw.x), e4m3x2_bf16<true>(raw.x),
e4m3x2_bf16<false>(raw.y), e4m3x2_bf16<true>(raw.y));
}
/* One cache element as bf16 bits. */
__device__ __forceinline__ uint16_t elem(const uint16_t* p) { return *p; }
__device__ __forceinline__ uint16_t elem(const uint8_t* p) {
return (uint16_t)(__float_as_uint(r4d_fp8::e4m3(*p)) >> 16);
}
template <typename K>
__global__ __launch_bounds__(128) void attend(const uint16_t* q, const K* kv, const int* bt,
const int* len, uint16_t* out, float* scratch,
Meta m) {
const int lane = threadIdx.x & 31, head = blockIdx.y * 4 + (threadIdx.x >> 5), r = blockIdx.x,
@@ -424,9 +467,10 @@ constexpr int kUnionBlocks = 520, kUnionSlots = 1024;
__device__ __forceinline__ unsigned union_slot(int page) {
return ((unsigned)page * 2654435761u) >> 22;
}
/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. */
template <bool PAIR, bool WIDE, bool UNION, bool STATS>
__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const uint16_t* kv,
/* STATS is its own instance: counting inside the loop costs the paired tile spilled VGPRs. K is
* the cache's element (uint16_t bf16, uint8_t E4M3). */
template <typename K, bool PAIR, bool WIDE, bool UNION, bool STATS>
__global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const K* kv,
const int* bt, const int* len, uint16_t* out,
float* scratch, Meta m) {
static_assert(PAIR || !UNION, "the union pairs two requests");
@@ -614,7 +658,7 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
for (int j = 0; j < 8; ++j) {
const int flat = tid + j * 128;
const long at = source[flat >> 6];
part[j] = *(const uint4*)(kv + (at >= 0 ? at : 0) + (flat & 63) * 8);
part[j] = load8(kv + (at >= 0 ? at : 0) + (flat & 63) * 8);
if (at < 0) part[j] = make_uint4(0, 0, 0, 0);
}
#pragma unroll
@@ -625,7 +669,8 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
} else {
for (int j = tid; j < 16 * 512; j += 128) {
const int token = j / 512, col = j % 512;
keys[token * 520 + col] = source[token] >= 0 ? kv[source[token] + col] : 0;
keys[token * 520 + col] =
source[token] >= 0 ? elem(kv + source[token] + col) : 0;
}
}
__syncthreads();
@@ -734,8 +779,8 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
* The next chunk's keys are fetched into registers while the current one is multiplied, so a
* chunk costs two barriers. */
constexpr int kRowsPitch = 520;
template <int HG, bool WIDE>
__global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const uint16_t* kv,
template <typename K, int HG, bool WIDE>
__global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const K* kv,
const int* bt, const int* len,
uint16_t* out, float* scratch, Meta m) {
constexpr int NT = HG * 128, LOADS = 16 * 64 / NT;
@@ -777,13 +822,15 @@ __global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const
const bool ok = page >= 0 && page < m.pages;
const long at = ok ? (long)page * m.kp + (token % m.bs) * m.kt + piece * 8 : 0;
if constexpr (WIDE) {
staged[j] = *(const uint4*)(kv + at);
staged[j] = load8(kv + at);
if (!ok) staged[j] = make_uint4(0, 0, 0, 0);
} else {
uint32_t w[4];
#pragma unroll
for (int i = 0; i < 4; ++i)
w[i] = ok ? (uint32_t)kv[at + 2 * i] | (uint32_t)kv[at + 2 * i + 1] << 16 : 0u;
w[i] = ok ? (uint32_t)elem(kv + at + 2 * i) |
(uint32_t)elem(kv + at + 2 * i + 1) << 16
: 0u;
staged[j] = make_uint4(w[0], w[1], w[2], w[3]);
}
staged_ok = ok ? staged_ok | 1u << j : staged_ok & ~(1u << j);
@@ -931,11 +978,13 @@ void report_stats(RadStream stream) {
"%llu second passes (%.3fx)\n",
device, v[0], v[2], v[1], (double)v[0] / (double)v[2]);
}
template <bool MATRIX>
/* K is the cache's element: uint16_t for a bf16 cache, uint8_t for an E4M3 one. */
template <bool MATRIX, typename K = uint16_t>
int body(const RadArgs* a, RadStream stream) {
constexpr uint32_t KV = sizeof(K) == 1 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
if (!a || a->n_t < 5) return RAD_E_INVAL;
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4];
if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
if (q.dtype != RAD_BF16 || kv.dtype != KV || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
len.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 5; ++i)
@@ -977,8 +1026,8 @@ int body(const RadArgs* a, RadStream stream) {
int rc;
if constexpr (MATRIX) {
#define MATRIX_EMIT(P, W, U, S, X, Y) \
R4D_EMIT(stream, (attend_matrix<P, W, U, S>), dim3(X, Y, m.splits), dim3(128), 0, \
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data, \
R4D_EMIT(stream, (attend_matrix<K, P, W, U, S>), dim3(X, Y, m.splits), dim3(128), 0, \
(const uint16_t*)q.data, (const K*)kv.data, (const int*)bt.data, \
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
#define MATRIX_LAUNCH(P, W, U, X, Y) \
(stats ? MATRIX_EMIT(P, W, U, true, X, Y) : MATRIX_EMIT(P, W, U, false, X, Y))
@@ -994,8 +1043,8 @@ int body(const RadArgs* a, RadStream stream) {
#undef MATRIX_LAUNCH
#undef MATRIX_EMIT
} else
rc = R4D_EMIT(stream, attend, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0,
(const uint16_t*)q.data, (const uint16_t*)kv.data, (const int*)bt.data,
rc = R4D_EMIT(stream, attend<K>, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), 0,
(const uint16_t*)q.data, (const K*)kv.data, (const int*)bt.data,
(const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m);
if (rc == RAD_OK && splits > 1)
rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0,
@@ -1013,10 +1062,12 @@ int g_mla_rows_form = 0;
* the matrix row's four tiles a row and its splits are faster (r4d_selftest --case
* mla_attn_rows_bf16, M 7: 0.5x). */
constexpr long kRowsMin = 32;
template <typename K = uint16_t>
int rows_body(const RadArgs* a, RadStream stream) {
constexpr uint32_t KV = sizeof(K) == 1 ? (uint32_t)RAD_F8E4M3 : (uint32_t)RAD_BF16;
if (!a || a->n_t < 5) return RAD_E_INVAL;
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4];
if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
if (q.dtype != RAD_BF16 || kv.dtype != KV || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
len.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 5; ++i)
@@ -1037,7 +1088,7 @@ int rows_body(const RadArgs* a, RadStream stream) {
return RAD_E_SHAPE;
if (heads % 32) return RAD_E_UNSUPPORTED;
const int form = g_mla_rows_form;
if (form == 4 || (!form && q.shape[0] < kRowsMin)) return body<true>(a, stream);
if (form == 4 || (!form && q.shape[0] < kRowsMin)) return body<true, K>(a, stream);
const int group_heads = heads % 64 || form == 2 ? 32 : 64;
const long rows = q.shape[0], groups = heads / group_heads, jobs = rows * groups;
/* Short batches split the history until 64 workgroups run, two to each of the R9700's 32
@@ -1053,8 +1104,8 @@ int rows_body(const RadArgs* a, RadStream stream) {
o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1],
(int)bs, (int)kv.shape[0], splits, scale };
#define ROWS_EMIT(HG, W) \
R4D_EMIT(stream, (attend_rows<HG, W>), dim3(m.rows, (unsigned)groups, m.splits), \
dim3(HG * 128), 0, (const uint16_t*)q.data, (const uint16_t*)kv.data, \
R4D_EMIT(stream, (attend_rows<K, HG, W>), dim3(m.rows, (unsigned)groups, m.splits), \
dim3(HG * 128), 0, (const uint16_t*)q.data, (const K*)kv.data, \
(const int*)bt.data, (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
int rc;
if (group_heads == 64)
@@ -1077,6 +1128,16 @@ extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
extern "C" int r4d_rad_mla_attn_rows(const RadArgs* a, RadStream stream) {
return rows_body(a, stream);
}
/* The same three rows over an E4M3 latent cache (kv_dtype fp8_e4m3). */
extern "C" int r4d_rad_mla_attn_fp8kv(const RadArgs* a, RadStream stream) {
return body<false, uint8_t>(a, stream);
}
extern "C" int r4d_rad_mla_attn_matrix_fp8kv(const RadArgs* a, RadStream stream) {
return body<true, uint8_t>(a, stream);
}
extern "C" int r4d_rad_mla_attn_rows_fp8kv(const RadArgs* a, RadStream stream) {
return rows_body<uint8_t>(a, stream);
}
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
return project_body(a, stream);
}
+3
View File
@@ -883,6 +883,9 @@ int64_t r4d_rad_mla_attn_paged_scratch(const RadArgs*);
int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*);
int r4d_rad_mla_attn_rows(const RadArgs*, RadStream);
int r4d_rad_mla_attn_fp8kv(const RadArgs*, RadStream);
int r4d_rad_mla_attn_matrix_fp8kv(const RadArgs*, RadStream);
int r4d_rad_mla_attn_rows_fp8kv(const RadArgs*, RadStream);
int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream);
int r4d_rad_router_sigmoid_group_topk(const RadArgs*, RadStream);
+46 -1
View File
@@ -1932,9 +1932,10 @@ static const RadParamSpec pSwigluClampedQuant[] = { P_INT("M"), P_INT("n"), P_F6
P_INT("group"), P_STR("dtype") };
static const RadParamSpec pDsaPool[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), P_STR("dtype"),
P_INTO("block_size") };
/* `kv_dtype` is the latent cache's: absent or bf16, or fp8_e4m3 (kv_store_fp8 at descale 1). */
static const RadParamSpec pMlaAttn[] = { P_INT("M"), P_INT("latent_dim"), P_INT("heads"),
P_INT("blocks"), P_INT("block_size"), P_F64("scale"),
P_STR("dtype") };
P_STR("dtype"), P_STRO("kv_dtype") };
static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"),
P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") };
static const RadParamSpec pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"),
@@ -5054,6 +5055,29 @@ static const RadConstraint cMlaRows[] = { C_GE("M", 1), C_LE("M", 65535)
C_EQ("latent_dim", 512), C_EQ("heads", 64),
C_GE("blocks", 1), C_EQ("block_size", 4),
C_IN("dtype", "bf16") };
/* The three rows over an E4M3 latent cache: each bf16 row's constraints and kv_dtype fp8_e4m3,
* ranked above all three bf16 rows (which state no kv_dtype and would otherwise also match), in
* the bf16 rows' order among themselves. The kernels are the bf16 rows' with the key load
* decoding E4M3 (r4d_mla.hip). */
static const RadConstraint cMlaAttnFp8[] = {
C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_GE("heads", 1),
C_LE("heads", 64), C_GE("blocks", 1), C_EQ("block_size", 4), C_IN("dtype", "bf16"),
C_IN("kv_dtype", "fp8_e4m3")
};
static const RadConstraint cMlaMatrixFp8[] = { C_GE("M", 1),
C_LE("M", 65535),
C_EQ("latent_dim", 512),
C_GE("heads", 8),
C_LE("heads", 64),
C_DIV("heads", 8),
C_GE("blocks", 1),
C_EQ("block_size", 4),
C_IN("dtype", "bf16"),
C_IN("kv_dtype", "fp8_e4m3") };
static const RadConstraint cMlaRowsFp8[] = { C_GE("M", 1), C_LE("M", 65535),
C_EQ("latent_dim", 512), C_EQ("heads", 64),
C_GE("blocks", 1), C_EQ("block_size", 4),
C_IN("dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3") };
/* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase;
* 28672 elements is that budget at hc 4. */
static const RadConstraint cMtpEnter[] = {
@@ -6598,6 +6622,27 @@ static const RadKernelInfo kKernels[] = {
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cMlaAttn), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn, r4d_rad_mla_attn_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "mla_attn_rows_fp8kv", "mla_attn", "attn",
"mla_attn_rows_bf16 over an E4M3 latent cache, each key decoded exactly to bf16 at the load",
"latent_dim=512, heads=64, block_size=4",
"bf16 Q/output, fp8-e4m3 cache at descale 1; FP32 probabilities via high/low BF16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 5, ROW(cMlaRowsFp8), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_rows_fp8kv, r4d_rad_mla_attn_matrix_scratch, nullptr,
nullptr, r4d_shape_mla_attn },
{ "mla_attn_matrix_fp8kv", "mla_attn", "attn",
"mla_attn_matrix_bf16 over an E4M3 latent cache, each key decoded exactly to bf16 at the load",
"latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4",
"bf16 Q/output, fp8-e4m3 cache at descale 1; FP32 probabilities via high/low BF16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 4, ROW(cMlaMatrixFp8), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_matrix_fp8kv, r4d_rad_mla_attn_matrix_scratch, nullptr,
nullptr, r4d_shape_mla_attn },
{ "mla_attn_fp8kv", "mla_attn", "attn",
"mla_attn_bf16 over an E4M3 latent cache, each key decoded exactly at the load",
"latent_dim=512, heads<=64, block_size=4",
"bf16 Q/output, fp8-e4m3 cache at descale 1, f32 softmax and partials",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 3, ROW(cMlaAttnFp8), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_fp8kv, r4d_rad_mla_attn_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "gemm_fp8a8_f32scale", "gemm_nt_q", "gemm", "FP8 WMMA with canonical F32 block scales",
"N and K multiples of 128; pitched activations and row-major weights", "E4M3 codes, F32 scales, BF16 output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cFp8F32Scale), NOTUNE,
+3 -1
View File
@@ -743,7 +743,9 @@ extern "C" int r4d_shape_mla_attn(const RadParam* p, int n_p, int operand, RadOp
const int64_t B = pi(p, n_p, "blocks"), bs = pi(p, n_p, "block_size"),
pages = std::max((int64_t)2, B * M);
const uint32_t dt = dt_act(p, n_p, "dtype");
const RadOpdDesc l[] = { opd(dt, M, H, D), opd(dt, pages, 1, bs, D), opd_idx(M, B, pages),
/* The cache is the query's dtype unless `kv_dtype` names another (fp8_e4m3). */
const uint32_t kv = r4d_pgets(p, n_p, "kv_dtype") ? dt_act(p, n_p, "kv_dtype") : dt;
const RadOpdDesc l[] = { opd(dt, M, H, D), opd(kv, pages, 1, bs, D), opd_idx(M, B, pages),
opd_idx(M, 0, 0, B * bs), opd(dt, M, H, D) };
R4D_PICK(l);
}
+107
View File
@@ -14,6 +14,7 @@
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -787,6 +788,99 @@ int run_paged_verify(int heads, int context, std::mt19937& rng) {
return fails;
}
/* The E4M3-cache twins (r4d_rad_mla_attn*_fp8kv): every E4M3 value is a bf16, so each kernel form
* on a cache of codes must give the bytes its bf16 instance gives on the same cache decoded to
* bf16. Each launcher also refuses the other cache dtype. */
int run_fp8kv(const Case& c, std::mt19937& rng) {
const int M = c.rows, H = c.heads, B = c.blocks;
std::vector<int> bt, len;
const int pages = fill_tables(c, rng, bt, len);
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
std::vector<uint8_t> kv8(kvb.size());
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (size_t i = 0; i < kv8.size(); ++i) {
/* Codes over most exponents, subnormals included. */
const float x = nrm(rng);
kv8[i] = rad_f32_to_fp8e4m3(x * x * x * 4.0f);
kvb[i] = rad_f32_to_bf16(rad_fp8e4m3_to_f32(kv8[i]));
if (rad_bf16_to_f32(kvb[i]) != rad_fp8e4m3_to_f32(kv8[i])) {
std::printf("%-40s E4M3 code %u is not a bf16 FAIL\n", c.name.c_str(), kv8[i]);
return 1;
}
}
std::vector<char> scratch;
typedef int (*Launch)(const RadArgs*, RadStream);
auto launch = [&](Launch fn, bool fp8, std::vector<uint16_t>& out) {
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
fp8 ? tens(kv8.data(), RAD_F8E4M3, { pages, 1, BS, D })
: tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
tens(out.data(), RAD_BF16, { M, H, D }) };
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { M, D, H, B, BS };
for (int i = 0; i < 5; ++i) {
p[i].key = keys[i];
p[i].kind = RAD_P_INT;
p[i].ival = vals[i];
}
p[5].key = "scale";
p[5].kind = RAD_P_F64;
p[5].dval = 0.0625;
RadArgs a{};
a.t = t;
a.n_t = 5;
a.p = p;
a.n_p = 6;
if (c.scratch) {
const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a);
scratch.assign((size_t)need + 16, 0);
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
a.scratch_bytes = need;
}
return fn(&a, nullptr);
};
struct Form {
const char* name;
Launch bf16, fp8;
void (*pin)(int);
int form;
};
std::vector<Form> forms = { { "wave", r4d_rad_mla_attn, r4d_rad_mla_attn_fp8kv, nullptr, 0 } };
if (H % 8 == 0) {
forms.push_back({ "matrix", r4d_rad_mla_attn_matrix, r4d_rad_mla_attn_matrix_fp8kv,
r4d_mla_matrix_pin_form, 0 });
forms.push_back({ "matrix, element load", r4d_rad_mla_attn_matrix,
r4d_rad_mla_attn_matrix_fp8kv, r4d_mla_matrix_pin_form, 1 });
}
if (H % 32 == 0)
for (int form : { 0, 3, 1, 2 })
forms.push_back({ "rows", r4d_rad_mla_attn_rows, r4d_rad_mla_attn_rows_fp8kv,
r4d_mla_rows_pin_form, form });
int fails = 0;
for (const Form& f : forms) {
std::vector<uint16_t> want((size_t)M * H * D, 0xffff), got(want.size(), 0xffff);
if (f.pin) f.pin(f.form);
const int rb = launch(f.bf16, false, want), rf = launch(f.fp8, true, got);
std::vector<uint16_t> spare(want.size(), 0xffff);
const int refuse_b = launch(f.bf16, true, spare), refuse_f = launch(f.fp8, false, spare);
if (f.pin) f.pin(0);
size_t differ = 0;
for (size_t i = 0; i < got.size(); ++i) differ += got[i] != want[i];
const bool untouched = std::all_of(spare.begin(), spare.end(),
[](uint16_t v) { return v == 0xffff; });
const bool ok = rb == RAD_OK && rf == RAD_OK && !differ && refuse_b == RAD_E_DTYPE &&
refuse_f == RAD_E_DTYPE && untouched;
std::printf("%-40s fp8kv %-20s form %d rc %d/%d %zu differ from bf16, refusals %d/%d "
"%s\n",
c.name.c_str(), f.name, f.form, rb, rf, differ, refuse_b, refuse_f,
ok ? "PASS" : "FAIL");
fails += !ok;
}
return fails;
}
} // namespace
int main(int argc, char** argv) {
@@ -839,6 +933,19 @@ int main(int argc, char** argv) {
std::mt19937 rng(20261020u + (unsigned)i);
fails += run_rows(rows_cases[i], rng);
}
/* The E4M3-cache twins against their bf16 instances. */
std::vector<Case> fp8_cases = {
{ "fp8kv: ragged, holes and bad pages", 7, 8, 17, Fill::ragged },
{ "fp8kv: prefill, 16 heads, split", 4, 16, 33, Fill::prefill, 0, 0, true },
{ "fp8kv: topk d=4, 8 heads", 6, 8, 33, Fill::topk, 4, 400 },
{ "fp8kv: rows, ragged", 3, 64, 17, Fill::ragged },
{ "fp8kv: rows, topk d=4, split", 2, 64, 33, Fill::topk, 4, 400, true },
};
for (size_t i = 0; i < fp8_cases.size(); ++i) {
if (filter && fp8_cases[i].name.find(filter) == std::string::npos) continue;
std::mt19937 rng(20261028u + (unsigned)i);
fails += run_fp8kv(fp8_cases[i], rng);
}
if (!filter || std::strstr("rowwise", filter)) {
std::mt19937 rng(20261022u);
fails += run_rowwise(rng);