libr4d: mla_attn_rows_bf16 -- one key load for all 64 heads of a query row

A third mla_attn row, at 64 heads. A workgroup takes one query row and all its heads, four waves
to each group of sixteen, and loads each 16-token key chunk once for all of them, where the
matrix row loads it once a tile of sixteen. The scores are K Q^T, tokens as the tile's rows and
heads as its columns, so a head's running maximum and denominator stay in its lane; the waves of
a group each take a quarter of the latent's dot products and add the four partials in one order,
and the probabilities reach the value product through a permlanex16 swap instead of LDS. The
next chunk's keys are fetched into registers while the current one is multiplied, two barriers a
chunk. A row's bytes do not depend on the other rows of the batch. Under 32 rows the launcher
runs the matrix row's kernel; r4d_mla_rows_pin_form, a test hook, pins the element-wise key load,
32 heads a workgroup, the rows kernel at any row count, or the matrix row's kernel at every row
count (the form a KL measurement needs to tell this kernel's share of a row split's difference).

Measured on gfx1201 (r4d_selftest --perfmla, one sequence past the DSA budget at 16k of
context, 513 blocks): 512 rows x 64 heads take 3.9 ms, 35 TFLOP/s, against 12.3 ms on the
matrix row, and the 4096 rows x 8 heads they stand for in a TP8 prefill chunk 14.0 ms on the
paired union tile. Against the wave row the output stays within the matrix row's tolerance
(max abs 2.4e-4 at 513 blocks).

r4d_selftest checks it against libref at 1 to 33 rows, 32 and 64 heads, every fill and both key
loads, and times it against the matrix row (--case mla_attn_rows_bf16, --perfmla at 64 heads).
r4d_emu_mla runs it on the host against an f64 softmax, its forms bit for bit against each
other, a run of rows against the same rows of the whole batch, and a mixed TP step (decodes, a
verify window, a prefill past the budget, a fresh chunk) split by heads over the matrix row and
by rows over this one, at runs that do and do not divide the step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NunzeandClaude Opus 5.5 committed 2026-10-22 09:58:07 +00:00
1 parent 123c439684
commit 87701cb6b8
8 files changed
+645 -66

No files matched your search

+13 -1
View File
@@ -2836,7 +2836,7 @@ contributes nothing, and a row with no visible key outputs zero. The softmax 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).
libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
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
heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter
it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of
@@ -2848,6 +2848,18 @@ by table position, with a second pass where the two differ. Other head counts ta
workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks
reserve; without scratch they compute unsplit.
At exactly 64 heads the rows row, `mla_attn_rows_bf16`, ranks above both. A workgroup takes one
query row and all its heads, four waves to each group of sixteen, and loads each 16-token key chunk
once for all of them, where the matrix row loads it once a tile of sixteen. The scores are
`K Q^T`, tokens as the tile's rows and heads as its columns, so a head's running maximum and
denominator stay in its lane; the four waves of a group each take a quarter of the latent's dot
products and add the four partials in one order, and the probabilities reach the value product
through a lane swap instead of LDS. The next chunk's keys are fetched while the current one is
multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives
the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher
runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a
workgroup), which no constraint routes to it.
`mla_project` moves a query into the latent and a latent result out of it, through the bf16
weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows.
`mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored,
+4
View File
@@ -688,6 +688,10 @@ void r4d_hc_read_pin_prefill(int form);
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
// Bit-identical; r4d_selftest compares them and --perfmla times both.
void r4d_mla_matrix_pin_form(int form);
// Test hook: pins the MLA rows row's form. 0 is the launcher's rule (64 heads a workgroup, vector
// key loads where aligned; the matrix row's kernel under 32 rows), 1 the element-wise key load
// (bit-identical to 3), 2 32 heads a workgroup, 3 the rows kernel of the rule at any row count.
void r4d_mla_rows_pin_form(int form);
// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the
// next call, and returns how many launches the previous recording saw (which may exceed its cap).
// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel
+240
View File
@@ -537,6 +537,178 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16);
}
}
/* ROWS gives a workgroup one query row and HG groups of sixteen heads, four waves a group, so a
* key chunk is loaded once for 16*HG heads instead of the head-tiled row's sixteen. GLM's prefill
* splits attention by rows, one rank holding all 64 heads of its rows; that is what this serves.
*
* Scores are S^T = K Q^T: tokens are the matrix rows and heads the columns, so a head is a lane
* and its running maximum and denominator stay in registers. Each wave of a group takes a quarter
* of the latent dimension; the four partial dot products meet in LDS and every wave of the group
* adds them in the same order, so all four hold identical scores and statistics. The
* probabilities become the second product's B operand with one permlanex16 swap, and each wave
* accumulates O^T for its quarter of the latent columns, the keys read transposed from the tile.
* 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,
const int* bt, const int* len,
uint16_t* out, float* scratch, Meta m) {
constexpr int NT = HG * 128, LOADS = 16 * 64 / NT;
static_assert(LOADS * NT == 16 * 64 && LOADS <= 32, "a chunk's 16-byte pieces over the group");
__shared__ __align__(16) uint16_t keys[2][16 * kRowsPitch];
__shared__ __align__(32) float partial[HG * 4][32 * 8];
__shared__ int visible[2][16];
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, quarter = wave & 3,
group = wave >> 2, r = blockIdx.x, split = blockIdx.z;
const int head = blockIdx.y * 16 * HG + group * 16 + (lane & 15);
const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs);
const int begin = (int)((long)live * split / m.splits),
end = (int)((long)live * (split + 1) / m.splits);
v8bf query[8];
{
const uint16_t* qp =
q + (long)r * m.qr + (long)head * m.qh + quarter * 128 + 4 * (lane >> 4);
#pragma unroll
for (int s = 0; s < 8; ++s) {
union {
uint16_t h[8];
v8bf f;
} u;
#pragma unroll
for (int e = 0; e < 4; ++e) {
u.h[e] = qp[s * 16 + e];
u.h[4 + e] = qp[s * 16 + 8 + e];
}
query[s] = u.f;
}
}
uint4 staged[LOADS];
unsigned staged_ok = 0;
auto fetch = [&](int start) {
#pragma unroll
for (int j = 0; j < LOADS; ++j) {
const int flat = tid + j * NT, token = start + (flat >> 6), piece = flat & 63;
const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1;
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);
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;
staged[j] = make_uint4(w[0], w[1], w[2], w[3]);
}
staged_ok = ok ? staged_ok | 1u << j : staged_ok & ~(1u << j);
}
};
auto stash = [&](int b) {
#pragma unroll
for (int j = 0; j < LOADS; ++j) {
const int flat = tid + j * NT, token = flat >> 6, piece = flat & 63;
*(uint4*)(keys[b] + token * kRowsPitch + piece * 8) = staged[j];
if (!piece) visible[b][token] = (int)(staged_ok >> j & 1u);
}
};
v8f value[8];
#pragma unroll
for (int mt = 0; mt < 8; ++mt) value[mt] = (v8f){ 0 };
float run_max = -INFINITY, run_den = 0;
fetch(begin);
stash(0);
__syncthreads();
int buf = 0;
for (int start = begin; start < end; start += 16) {
const bool more = start + 16 < end;
if (more) fetch(start + 16);
const uint16_t* tile = keys[buf];
v8f dot = { 0 };
#pragma unroll
for (int s = 0; s < 8; ++s)
dot = mma(frag(tile, kRowsPitch, 0, quarter * 128 + s * 16, lane), query[s], dot);
*(v8f*)&partial[wave][lane * 8] = dot;
__syncthreads();
v8f score = *(const v8f*)&partial[group * 4][lane * 8];
#pragma unroll
for (int k = 1; k < 4; ++k) score += *(const v8f*)&partial[group * 4 + k][lane * 8];
float chunk_max = -INFINITY;
#pragma unroll
for (int e = 0; e < 8; ++e) {
score[e] = visible[buf][8 * (lane >> 4) + e] ? score[e] * m.scale : -INFINITY;
chunk_max = fmaxf(chunk_max, score[e]);
}
chunk_max = fmaxf(chunk_max, swap16(chunk_max));
const float next_max = fmaxf(run_max, chunk_max);
const float alpha = isfinite(next_max) ? expf(run_max - next_max) : 1;
float p[8], sum = 0;
#pragma unroll
for (int e = 0; e < 8; ++e) {
p[e] = isfinite(score[e]) ? expf(score[e] - next_max) : 0;
sum += p[e];
}
/* Both halves add tokens 0-7 before 8-15, so the sixteen lanes of a head agree. */
const float other = swap16(sum);
run_den = run_den * alpha + (lane < 16 ? sum + other : other + sum);
run_max = next_max;
/* A B fragment's lane holds its head's tokens 0-3 and 8-11 (lanes 0-15) or 4-7 and 12-15
* (16-31); a score lane holds 0-7 or 8-15. Each half sends the other the four it needs. */
uint32_t hi[4], lo[4];
#pragma unroll
for (int i = 0; i < 4; ++i) {
const uint16_t h0 = f32_to_bf16(p[2 * i]), h1 = f32_to_bf16(p[2 * i + 1]);
hi[i] = (uint32_t)h0 | (uint32_t)h1 << 16;
lo[i] = (uint32_t)f32_to_bf16(p[2 * i] - bf16_to_f32(h0)) |
(uint32_t)f32_to_bf16(p[2 * i + 1] - bf16_to_f32(h1)) << 16;
}
const bool low = lane < 16;
const uint32_t hx0 = r4d_xor_lane_u32<16>(low ? hi[2] : hi[0]),
hx1 = r4d_xor_lane_u32<16>(low ? hi[3] : hi[1]),
lx0 = r4d_xor_lane_u32<16>(low ? lo[2] : lo[0]),
lx1 = r4d_xor_lane_u32<16>(low ? lo[3] : lo[1]);
union {
uint32_t w[4];
v8bf f;
} ph, pl;
ph.w[0] = low ? hi[0] : hx0;
ph.w[1] = low ? hi[1] : hx1;
ph.w[2] = low ? hx0 : hi[2];
ph.w[3] = low ? hx1 : hi[3];
pl.w[0] = low ? lo[0] : lx0;
pl.w[1] = low ? lo[1] : lx1;
pl.w[2] = low ? lx0 : lo[2];
pl.w[3] = low ? lx1 : lo[3];
#pragma unroll
for (int mt = 0; mt < 8; ++mt) {
const auto v = fragT(tile, kRowsPitch, quarter * 128 + mt * 16, 0, lane);
value[mt] *= alpha;
value[mt] = mma(v, ph.f, value[mt]);
value[mt] = mma(v, pl.f, value[mt]);
}
if (more) stash(buf ^ 1);
__syncthreads();
buf ^= 1;
}
#pragma unroll
for (int mt = 0; mt < 8; ++mt)
#pragma unroll
for (int e = 0; e < 8; ++e) {
const int col = quarter * 128 + mt * 16 + 8 * (lane >> 4) + e;
if (m.splits == 1)
out[(long)r * m.orr + (long)head * m.oh + col] =
f32_to_bf16(run_den > 0 ? value[mt][e] / run_den : 0);
else
scratch[(((long)r * m.heads + head) * m.splits + split) * PART + col] =
value[mt][e];
}
if (m.splits > 1 && !quarter && lane < 16) {
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
dst[D] = run_max;
dst[D + 1] = run_den;
}
}
bool env_on(const char* name) {
const char* e = std::getenv(name);
return e && *e && *e != '0';
@@ -643,6 +815,70 @@ int body(const RadArgs* a, RadStream stream) {
if (rc == RAD_OK && stats) report_stats(stream);
return rc;
}
/* r4d_mla_rows_pin_form: 0 is the launcher's rule (64 heads a workgroup, vector key loads where
* the cache is aligned, the matrix row's kernel under kRowsMin rows), 1 the element-wise key load,
* 2 thirty-two heads a workgroup, 3 the rule's rows kernel at any row count, 4 the matrix row's
* kernel at every row count. The pin is a test hook (r4d_selftest, r4d_emu); nothing else sets
* it. */
int g_mla_rows_form = 0;
/* Under it, a decode step's rows at one rank, a workgroup a row leaves the card mostly idle, and
* 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;
int rows_body(const RadArgs* a, RadStream stream) {
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 ||
len.dtype != RAD_I32)
return RAD_E_DTYPE;
for (int i = 0; i < 5; ++i)
if (!a->t[i].data) return RAD_E_INVAL;
const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0);
const float scale = (float)r4d_getf(a, "scale", 0);
if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 ||
!std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 ||
q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 ||
q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 ||
kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D ||
kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 ||
bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs ||
bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 ||
len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 ||
o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 ||
o.stride[1] < D || o.stride[0] < heads * o.stride[1])
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);
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
* WGPs, as far as 16-token chunks and the scratch's 2048 partials allow. */
int splits = (int)std::min(64l, (64 + jobs - 1) / jobs);
splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + 15) / 16));
splits = (int)std::max(1l, std::min((long)splits, 2048 / (rows * heads)));
if (!a->scratch || a->scratch_bytes < matrix_scratch_bytes) splits = 1;
const bool wide = form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
!(kv.stride[2] % 8);
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],
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, \
(const int*)bt.data, (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
int rc;
if (group_heads == 64)
rc = wide ? ROWS_EMIT(4, true) : ROWS_EMIT(4, false);
else
rc = wide ? ROWS_EMIT(2, true) : ROWS_EMIT(2, false);
#undef ROWS_EMIT
if (rc == RAD_OK && splits > 1)
rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0,
(const float*)a->scratch, (uint16_t*)o.data, m);
return rc;
}
}
extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
return body<false>(a, stream);
@@ -650,12 +886,16 @@ extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
return body<true>(a, stream);
}
extern "C" int r4d_rad_mla_attn_rows(const RadArgs* a, RadStream stream) {
return rows_body(a, stream);
}
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
return project_body(a, stream);
}
extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; }
extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; }
extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; }
extern "C" void r4d_mla_rows_pin_form(int form) { g_mla_rows_form = form; }
/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes,
* second passes, raster chunks), then zeroed. */
extern "C" void r4d_mla_matrix_stats(unsigned long long* out) {
+1
View File
@@ -698,6 +698,7 @@ int r4d_rad_mla_attn(const RadArgs*, RadStream);
int64_t r4d_rad_mla_attn_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_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*);
int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream);
int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*);
+16
View File
@@ -4266,6 +4266,16 @@ static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
C_GE("blocks", 1),
C_EQ("block_size", 4),
C_IN("dtype", "bf16") };
/* GLM's prefill splits MLA by rows, a rank holding every head of its rows: the rows row loads a
* key chunk once for a workgroup of 64 heads and outranks the matrix row there. Measured on gfx1201
* (r4d_selftest --perfmla 512 513 64 20 topk:16:16000), a rank's run of 512 rows takes 3.9 ms
* against 12.3 ms on the matrix row, and the 4096 rows x 8 heads it replaces 14.0 ms on the paired
* matrix row. Under 32 rows its launcher runs the matrix row's kernel (r4d_mla.hip); a bound on M
* here would cut every mla_attn band at 32, the eight-head ones too. */
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") };
/* `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[] = {
@@ -5541,6 +5551,12 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
r4d_shape_scale },
{ "mla_attn_rows_bf16", "mla_attn", "attn", "row-tiled WMMA latent attention, one key load for 64 heads",
"latent_dim=512, heads=64, block_size=4",
"bf16 operands; FP32 probabilities via high/low BF16",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 2, ROW(cMlaRows), NOTUNE,
nullptr, nullptr, r4d_rad_mla_attn_rows, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr,
r4d_shape_mla_attn },
{ "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax",
"latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4",
"bf16 operands; FP32 probabilities via high/low BF16",
+45 -13
View File
@@ -144,6 +144,7 @@ struct Plugin {
void (*pin_qsel)(int) = nullptr;
void (*pin_mla)(int) = nullptr;
void (*mla_stats)(unsigned long long*) = nullptr;
void (*pin_mla_rows)(int) = nullptr;
int (*record)(const void**, int) = nullptr;
};
@@ -181,6 +182,7 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel);
okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla);
okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats);
okall &= sym(pl->h, "r4d_mla_rows_pin_form", &pl->pin_mla_rows);
okall &= sym(pl->h, "r4d_record_dispatches", &pl->record);
return okall;
}
@@ -14008,25 +14010,28 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo
const int rc = oracle->launch(&args, nullptr);
ok("MLA host oracle", rc == RAD_OK);
args.t = device.data();
/* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix);
* other head counts must be refused rather than computed. */
if (std::strstr(name, "matrix") && heads % 8) {
/* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix),
* the rows row groups of 32 or 64 heads; other head counts must be refused rather than
* computed. */
const bool by_rows = std::strstr(name, "rows") != nullptr;
auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla;
if ((std::strstr(name, "matrix") && heads % 8) || (by_rows && heads % 32)) {
args.scratch = nullptr;
args.scratch_bytes = 0;
const int grc = row->launch(&args, nullptr);
st_stream_sync(nullptr);
ok(fmt("MLA %s refuses heads=%lld (not a multiple of 8) with RAD_E_UNSUPPORTED, no launch",
name, (long long)heads)
ok(fmt("MLA %s refuses heads=%lld (not a multiple of %d) with RAD_E_UNSUPPORTED, no launch",
name, (long long)heads, by_rows ? 32 : 8)
.c_str(),
grc == RAD_E_UNSUPPORTED);
dlclose(ref);
return;
}
if (form && pl.pin_mla) pl.pin_mla(form);
if (form && pin) pin(form);
const int64_t need = row->scratch ? row->scratch(&args) : 0;
void* scratch = need > 0 ? dalloc((size_t)need + 256) : nullptr;
if (need <= 0 || !scratch) {
if (form && pl.pin_mla) pl.pin_mla(0);
if (form && pin) pin(0);
ok("MLA scratch allocation", false);
dlclose(ref);
return;
@@ -14095,7 +14100,7 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo
versus, base, name, base / us, shape);
}
}
if (form && pl.pin_mla) pl.pin_mla(0);
if (form && pin) pin(0);
dlclose(ref);
}
@@ -14205,17 +14210,19 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
PS("dtype", "bf16") };
std::vector<uint16_t> base, rule;
auto run = [&](const char* name, int form, const char* label) {
const bool by_rows = std::strstr(name, "rows") != nullptr;
auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla;
const RadKernelInfo* r = find(pl, name);
if (!r) {
std::printf(" %-34s row absent\n", label);
return;
}
if (form >= 0) {
if (!pl.pin_mla) {
if (!pin) {
std::printf(" %-34s no pin hook\n", label);
return;
}
pl.pin_mla(form);
pin(form);
}
RadArgs a;
std::memset(&a, 0, sizeof(a));
@@ -14232,7 +14239,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
const int rc = r->launch(&a, nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
std::printf(" %-34s rc=%d (shape not served)\n", label, rc);
if (form >= 0) pl.pin_mla(0);
if (form >= 0) pin(0);
return;
}
std::vector<uint16_t> got(qh.size());
@@ -14253,7 +14260,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
st_ev_destroy(w1);
}
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
if (form >= 0) pl.pin_mla(0);
if (form >= 0) pin(0);
char diff[192] = "reference";
if (base.empty())
base = got;
@@ -14279,7 +14286,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
}
if (form == 0) rule = got;
std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff);
if (form >= 0 && pl.mla_stats) {
if (form >= 0 && !by_rows && pl.mla_stats) {
/* One more launch with the conflict counters on, outside the timing. */
ScopedEnv counting("RADIANCE_MLA_CONFLICT_STATS", "1");
unsigned long long v[3];
@@ -14308,6 +14315,11 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load");
run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load");
}
if (heads == 64) {
run("mla_attn_rows_bf16", 0, "rows 64 heads, vector load");
run("mla_attn_rows_bf16", 1, "rows 64 heads, element load");
run("mla_attn_rows_bf16", 2, "rows 32 heads, vector load");
}
}
static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepted_count,
@@ -26663,6 +26675,26 @@ static void device_phase(const Plugin& pl) {
for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true);
}
}
if (sel("mla_attn_rows_bf16")) {
/* A rank's run of rows with all 64 heads (GLM's prefill split by rows), against the matrix
* row on the same operands. Under 32 rows the rule runs the matrix kernel, so the rows
* kernel is pinned there (form 3). */
for (int requests : { 1, 2, 7, 33 })
for (int64_t blocks : { 17, 513 })
mla_check(pl, requests, 64, blocks, "mla_attn_rows_bf16", MlaFill::ragged,
"mla_attn_matrix_bf16", requests < 32 ? 3 : 0);
mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::full, "mla_attn_matrix_bf16", 3);
mla_check(pl, 2, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16", 3);
mla_check(pl, 33, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16");
for (int64_t swaps : { 0, 4, 16, 64 })
mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16",
0, swaps);
mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, nullptr, 1);
mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, nullptr, 2, 16);
mla_check(pl, 7, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16", 0, 4);
mla_check(pl, 7, 32, 65, "mla_attn_rows_bf16", MlaFill::ragged, nullptr, 3);
mla_check(pl, 4, 40, 17, "mla_attn_rows_bf16");
}
if (sel("mla_attn_matrix_bf16")) {
mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16");
mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16");
+7 -1
View File
@@ -996,7 +996,8 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) {
}
/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves
* every M up to its bound, a decode step's rows and a prefill chunk alike. */
* every M up to its bound, a decode step's rows and a prefill chunk alike. At 64 heads the rows
* row ranks above both. */
TEST(libr4d_resolves_the_mla_attention_by_rows) {
const std::string so = libr4d();
if (so.empty()) return;
@@ -1010,6 +1011,11 @@ TEST(libr4d_resolves_the_mla_attention_by_rows) {
g.set_s("dtype", "bf16");
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 ");
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 ");
// All 64 heads of a row, as GLM's prefill split by rows runs it: the rows row.
g.set_i("heads", 64);
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_rows_bf16 ");
g.set_i("heads", 16);
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 512, g)), "512:mla_attn_matrix_bf16 ");
}
/* ================================================================== constraints that are not intervals */
+319 -51
View File
@@ -5,7 +5,9 @@
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the
* same operands: the union at the case's table width, the positional pairing on the table
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches. */
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches.
* The rows row (attend_rows, 64 heads of one row a workgroup) runs on its own cases, and a mixed
* TP step runs both ways, split by heads over the matrix row and by rows over the rows row. */
#include "rad_abi.h"
#include "rad_plugin.h"
#include "r4d_plugin.h"
@@ -21,6 +23,7 @@
extern "C" void r4d_mla_matrix_pin_form(int form);
extern "C" void r4d_mla_matrix_stats(unsigned long long* out);
extern "C" void r4d_mla_rows_pin_form(int form);
namespace {
@@ -106,9 +109,9 @@ void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng
}
}
int run(const Case& c, std::mt19937& rng) {
const int M = c.rows, H = c.heads, B = c.blocks;
std::vector<int> bt, len;
/* The case's page tables and visible lengths; returns the pages the cache holds. */
int fill_tables(const Case& c, std::mt19937& rng, std::vector<int>& bt, std::vector<int>& len) {
const int M = c.rows, B = c.blocks;
int pages = 0;
if (c.fill == Fill::topk) {
topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages);
@@ -144,25 +147,73 @@ int run(const Case& c, std::mt19937& rng) {
len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7;
}
}
return pages;
}
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
t.shape[i] = shape[i];
t.stride[i] = st;
st *= shape[i];
}
return t;
}
/* An f64 softmax over each row's own table. */
std::vector<double> reference(int M, int H, int B, int pages, const std::vector<int>& bt,
const std::vector<int>& len, const std::vector<uint16_t>& qb,
const std::vector<uint16_t>& kvb, double scale) {
std::vector<double> want((size_t)M * H * D);
std::vector<double> sc;
for (int r = 0; r < M; ++r)
for (int h = 0; h < H; ++h) {
const int live = std::min(std::max(len[r], 0), B * BS);
sc.assign(live, -INFINITY);
double mx = -INFINITY;
auto row_of = [&](int j) -> const uint16_t* {
const int pg = bt[(size_t)r * B + j / BS];
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
};
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
for (int j = 0; j < live; ++j) {
const uint16_t* k = row_of(j);
if (!k) continue;
double dot = 0;
for (int d = 0; d < D; ++d)
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
sc[j] = dot * scale;
mx = std::max(mx, sc[j]);
}
std::vector<double> acc(D, 0.0);
double sum = 0;
for (int j = 0; j < live; ++j) {
if (sc[j] == -INFINITY) continue;
const double w = std::exp(sc[j] - mx);
sum += w;
const uint16_t* k = row_of(j);
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
}
for (int d = 0; d < D; ++d)
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
}
return want;
}
int run(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);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
auto tens = [](void* p, uint32_t dt, std::vector<int64_t> shape) {
RadTensor t{};
t.data = p;
t.dtype = dt;
t.rank = (uint32_t)shape.size();
int64_t st = 1;
for (int i = (int)shape.size() - 1; i >= 0; --i) {
t.shape[i] = shape[i];
t.stride[i] = st;
st *= shape[i];
}
return t;
};
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
@@ -202,40 +253,7 @@ int run(const Case& c, std::mt19937& rng) {
a.scratch_bytes = need;
}
/* the f64 reference */
std::vector<double> want((size_t)M * H * D);
std::vector<double> sc;
for (int r = 0; r < M; ++r)
for (int h = 0; h < H; ++h) {
const int live = std::min(std::max(len[r], 0), B * BS);
sc.assign(live, -INFINITY);
double mx = -INFINITY;
auto row_of = [&](int j) -> const uint16_t* {
const int pg = bt[(size_t)r * B + j / BS];
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
};
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
for (int j = 0; j < live; ++j) {
const uint16_t* k = row_of(j);
if (!k) continue;
double dot = 0;
for (int d = 0; d < D; ++d)
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
sc[j] = dot * scale;
mx = std::max(mx, sc[j]);
}
std::vector<double> acc(D, 0.0);
double sum = 0;
for (int j = 0; j < live; ++j) {
if (sc[j] == -INFINITY) continue;
const double w = std::exp(sc[j] - mx);
sum += w;
const uint16_t* k = row_of(j);
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
}
for (int d = 0; d < D; ++d)
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
}
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
/* Both pairings on the same operands: the positional one, on the table widened past the
* union's lists, and at the case's own width the launcher's choice, the union, which must
@@ -326,6 +344,227 @@ int run(const Case& c, std::mt19937& rng) {
return fails;
}
/* The rows row (attend_rows): one query row and 64 heads a workgroup, as GLM's prefill runs MLA
* split by rows. Each form against the f64 softmax and the forms bit for bit against each other
* (the element-wise key load; 32 heads a workgroup, whose heads sum alike); unsplit, a run of the
* rows against the same rows of the whole batch, since a rank computing its run must produce the
* bytes the batch would. */
int run_rows(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);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
const double scale = 0.0625;
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
std::vector<char> scratch;
auto launch = [&](int first, int rows, int form, std::vector<uint16_t>& out) {
const size_t q0 = (size_t)first * H * D;
RadTensor t[5] = { tens(qb.data() + q0, RAD_BF16, { rows, H, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
tens(len.data() + first, RAD_I32, { rows }),
tens(out.data() + q0, RAD_BF16, { rows, H, D }) };
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { rows, 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 = scale;
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;
}
if (form < 0) return r4d_rad_mla_attn_matrix(&a, nullptr);
r4d_mla_rows_pin_form(form);
const int rc = r4d_rad_mla_attn_rows(&a, nullptr);
r4d_mla_rows_pin_form(0);
return rc;
};
int fails = 0;
std::vector<uint16_t> rule;
for (int form : { 3, 1, 2, 0 }) {
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
const int rc = launch(0, M, form, out);
if (rc != RAD_OK) {
std::printf("%-40s form %d launch returned %d FAIL\n", c.name.c_str(), form, rc);
++fails;
continue;
}
double max_err = 0;
long bad = 0;
for (size_t i = 0; i < out.size(); ++i) {
const float got = rad_bf16_to_f32(out[i]);
const double e = std::fabs(got - want[i]);
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
if (std::isfinite(got)) max_err = std::max(max_err, e);
}
bool ok = bad == 0;
std::string note;
/* A split follows the workgroup count, which 32 heads a workgroup doubles; under 32 rows
* the rule is the matrix row's kernel. */
if (form == 3)
rule = out;
else if (form == 0 && M < 32) {
std::vector<uint16_t> matrix((size_t)M * H * D, 0xffff);
const int mrc = launch(0, M, -1, matrix);
if (mrc != RAD_OK || matrix != out) {
note = " (the rule under 32 rows is not the matrix row)";
ok = false;
}
} else if ((form == 1 || !c.scratch) && out != rule) {
note = " (differs from form 3)";
ok = false;
}
std::printf("%-40s form %d M %3d H %2d blocks %3d max_abs %.2e bad %ld%s %s\n",
c.name.c_str(), form, M, H, B, max_err, bad, note.c_str(), ok ? "PASS" : "FAIL");
fails += !ok;
}
if (!c.scratch && M >= 3 && !rule.empty()) {
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
const int rc = launch(1, M - 2, 3, out);
bool same = rc == RAD_OK, untouched = true;
for (int r = 0; r < M; ++r)
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
if (r == 0 || r == M - 1)
untouched = untouched && out[i] == 0xffff;
else
same = same && out[i] == rule[i];
}
std::printf("%-40s rows 1..%d alone: %s, rows outside %s %s\n", c.name.c_str(), M - 2,
same ? "bit-identical to the batch" : "DIFFER from the batch",
untouched ? "untouched" : "WRITTEN", same && untouched ? "PASS" : "FAIL");
fails += !(same && untouched);
}
return fails;
}
/* A TP step's attention both ways on one operand set: by heads, each of `world` ranks running
* the matrix row on its heads of every row (views into the whole [T, 64, 512]), and by rows, each
* rank the rows row on its run of ceil(T / world) rows with every head, the last run short. The
* step mixes what a step batch carries, decode rows first: single-row decodes on scattered tables,
* a verify window of four rows on one table, then a prefill continuing past the DSA budget and a
* fresh prompt's first chunk. Both forms against the f64 softmax; how far apart they are is
* printed. */
int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) {
constexpr int H = 64, B = 65;
std::vector<int> bt, len;
int pages = 0;
auto append = [&](const std::vector<int>& t, const std::vector<int>& l, int segment_pages) {
for (int v : t) bt.push_back(v >= 0 ? v + pages : v);
len.insert(len.end(), l.begin(), l.end());
pages += segment_pages;
};
{ /* three decodes, each its own table with holes */
std::vector<int> t((size_t)3 * B), l(3);
for (int r = 0; r < 3; ++r) {
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = b % 13 == 5 ? -1 : (b * 5 + r * 17) % (3 * B);
l[r] = B * BS - 1 - 3 * r;
}
append(t, l, 3 * B);
}
{ /* a verify window: four rows of one sequence on one table */
std::vector<int> t((size_t)4 * B), l(4);
for (int r = 0; r < 4; ++r) {
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = (b * 3 + 1) % B;
l[r] = B * BS - 4 + r + 1;
}
append(t, l, B);
}
{ /* a prefill past the DSA budget: every row its own top blocks */
std::vector<int> t, l;
int segment = 0;
topk_tables(23, B, 1200, 4, rng, t, l, segment);
append(t, l, segment);
}
{ /* a fresh prompt's chunk: causal on one table, rows starting at position 0 */
std::vector<int> t((size_t)fresh_rows * B, -1), l(fresh_rows);
for (int r = 0; r < fresh_rows; ++r) {
for (int b = 0; b <= r / BS && b < B; ++b) t[(size_t)r * B + b] = b;
l[r] = r + 1;
}
append(t, l, B);
}
const int T = (int)len.size();
std::normal_distribution<float> nrm(0.f, 1.f);
std::vector<uint16_t> qb((size_t)T * H * D), kvb((size_t)pages * BS * D);
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
const double scale = 0.0625;
const std::vector<double> want = reference(T, H, B, pages, bt, len, qb, kvb, scale);
auto launch = [&](bool by_rows, int first, int rows, int h0, int heads,
std::vector<uint16_t>& out) {
const size_t at = ((size_t)first * H + h0) * D;
RadTensor t[5] = { tens(qb.data() + at, RAD_BF16, { rows, heads, D }),
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
tens(len.data() + first, RAD_I32, { rows }),
tens(out.data() + at, RAD_BF16, { rows, heads, D }) };
t[0].stride[0] = t[4].stride[0] = (int64_t)H * D;
RadParam p[6]{};
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
const long long vals[5] = { rows, D, heads, 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 = scale;
RadArgs a{};
a.t = t;
a.n_t = 5;
a.p = p;
a.n_p = 6;
if (!by_rows) return r4d_rad_mla_attn_matrix(&a, nullptr);
/* Runs this short take the matrix kernel by rule; the rows kernel is what is under test. */
r4d_mla_rows_pin_form(3);
const int rc = r4d_rad_mla_attn_rows(&a, nullptr);
r4d_mla_rows_pin_form(0);
return rc;
};
std::vector<uint16_t> heads_out((size_t)T * H * D, 0xffff), rows_out((size_t)T * H * D, 0xffff);
const int per_heads = H / world, run = (T + world - 1) / world;
int fails = 0;
for (int rank = 0; rank < world; ++rank) {
fails += launch(false, 0, T, rank * per_heads, per_heads, heads_out) != RAD_OK;
const int first = rank * run, n = std::min(run, T - first);
if (n > 0) fails += launch(true, first, n, 0, H, rows_out) != RAD_OK;
}
long bad[2] = { 0, 0 };
double max_err[2] = { 0, 0 }, apart = 0;
for (size_t i = 0; i < want.size(); ++i) {
const float got[2] = { rad_bf16_to_f32(heads_out[i]), rad_bf16_to_f32(rows_out[i]) };
for (int f = 0; f < 2; ++f) {
const double e = std::fabs(got[f] - want[i]);
if (!std::isfinite(got[f]) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad[f];
if (std::isfinite(got[f])) max_err[f] = std::max(max_err[f], e);
}
apart = std::max(apart, (double)std::fabs(got[0] - got[1]));
}
const bool ok = !fails && !bad[0] && !bad[1];
std::printf("%-40s T %3d world %d run %2d last %2d heads max_abs %.2e bad %ld rows max_abs "
"%.2e bad %ld apart %.2e %s\n",
name, T, world, run, T - (world - 1) * run, max_err[0], bad[0], max_err[1], bad[1],
apart, ok ? "PASS" : "FAIL");
return !ok;
}
/* The launcher prints the running totals every 1024th counted launch and must leave them
* standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */
int periodic_report() {
@@ -406,6 +645,18 @@ int main(int argc, char** argv) {
{ "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 },
{ "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false },
};
/* The rows row at 64 heads, and at 32, which it serves with two groups a workgroup. */
std::vector<Case> rows_cases = {
{ "rows: prefill, one table", 8, 64, 65, Fill::prefill },
{ "rows: topk d=4", 8, 64, 65, Fill::topk, 4, 600 },
{ "rows: topk d=16, 513 blocks", 3, 64, 513, Fill::topk, 16, 8192 },
{ "rows: repeated pages", 6, 64, 33, Fill::repeat },
{ "rows: ragged, holes and bad pages", 7, 64, 17, Fill::ragged },
{ "rows: ragged, split", 3, 64, 17, Fill::ragged, 0, 0, true },
{ "rows: prefill, one row, split", 1, 64, 65, Fill::prefill, 0, 0, true },
{ "rows: 32 heads", 5, 32, 33, Fill::prefill },
{ "rows: 32 heads, topk d=4, split", 2, 32, 33, Fill::topk, 4, 400, true },
};
const char* filter = argc > 1 ? argv[1] : nullptr;
int fails = 0;
for (size_t i = 0; i < cases.size(); ++i) {
@@ -413,6 +664,23 @@ int main(int argc, char** argv) {
std::mt19937 rng(20261018u + (unsigned)i);
fails += run(cases[i], rng);
}
for (size_t i = 0; i < rows_cases.size(); ++i) {
if (filter && rows_cases[i].name.find(filter) == std::string::npos) continue;
std::mt19937 rng(20261020u + (unsigned)i);
fails += run_rows(rows_cases[i], rng);
}
/* T 45 over eight ranks: runs of 6, the last of 3; 37 over four: 10 and 7; 48: whole runs. */
const struct {
const char* name;
int world, fresh;
} splits[] = { { "split: heads vs rows, 8 ranks", 8, 15 },
{ "split: heads vs rows, 4 ranks", 4, 7 },
{ "split: heads vs rows, whole runs", 8, 18 } };
for (size_t i = 0; i < sizeof splits / sizeof splits[0]; ++i) {
if (filter && !std::strstr(splits[i].name, filter)) continue;
std::mt19937 rng(20261021u + (unsigned)i);
fails += run_split(splits[i].name, splits[i].world, splits[i].fresh, rng);
}
if (!filter) fails += periodic_report();
std::printf("%d failure(s)\n", fails);
return fails ? 1 : 0;