libr4d: logits_gemm_bf16_cols -- the bf16 head without a block per column at n_embd 4096

logits_gemm_bf16 runs a 256-thread block per vocabulary column. At n_embd 4096 a thread makes two
16-byte weight loads before the block-wide sum, and each row widens both operands for its own
product: GLM-5.3's TP8 slice (19360 columns) took 303 us at six rows and 1133 at 24, where a verify
pass of eight streams lands, against 235 at one.

The new row runs a wave per four columns: lane l takes, in turn, threads 32q + l of the old
block for q = 0..7 -- the same 8-wide k chunks summed from 0 and added in k order, the same lane
butterfly per q, the eight wave sums added in q order from 0 -- so each column gets the old row's
bytes. bf16 widens to f32 exactly, so each weight is widened once for every row and each
activation once for every column. It outranks the block row at n_embd 4096 only; the block row
is unchanged and serves every other width.

Measured at the TP8 slice (r4d_selftest --perflogits), us:

  rows                 1      6      8     16     24     48
  logits_gemm_bf16  239.1  303.2  378.2  741.4 1133.2 2354.5
  ..._cols          235.5  247.5  250.4  404.5  635.6 1220.1

Two columns a wave and 16 rows a pass measured slower. r4d_selftest compares both rows byte for
byte from one row to past one 8-row chunk, at a vocabulary off the column step and a pitched
activation with a NaN and a signed zero.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
NunzeandClaude Opus 5.5 committed 2026-10-21 15:26:57 +02:00
1 parent 1ff9abe2ba
commit f909576d09
5 files changed
+245

No files matched your search

+3
View File
@@ -965,6 +965,9 @@ int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
// that compares neighbouring probabilities. K must be a multiple of 8.
int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld,
long stream);
// The same bytes from a wave per four vocabulary columns; K must be 4096.
int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld, int c_ld,
long stream);
// Scatter into kv_cache[n_blocks, kv_heads, block_size, 2*head_dim]: K at [.., d], V at
// [.., head_dim + d], slot decomposing as block = slot / block_size, offset = slot % block_size.
int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, int kv_heads,
+136
View File
@@ -1240,6 +1240,99 @@ __global__ __launch_bounds__(kThreads) void logits_gemm_kernel(
}
}
// The same projection with each wave taking four whole vocabulary columns, for a head where the
// 256-thread block per column is the cost: at n_embd 4096 a thread of that kernel makes two 16-byte
// weight loads before the block-wide sum, and each row widens both operands for its own product.
//
// BYTE-IDENTICAL to logits_gemm_kernel: lane l of a wave runs, in turn, threads 32q + l of that
// kernel's block for q = 0..7 -- the same 8-wide k chunks, each summed from 0 and added to the
// thread's accumulator in k order -- reduces each q with the same lane butterfly, and adds the
// eight wave sums in q order from 0. Only where the threads run changes, and bf16 widens to f32
// exactly, so each weight is widened once for every row and each activation once for every
// column. A q's loads (four columns and up to kLgRows rows, two chunks each) are issued before its
// arithmetic.
constexpr uint32_t kLgCols = 4, kLgKi = 2; // columns a wave; 2048-wide chunks of n_embd 4096
__global__ __launch_bounds__(kThreads) void logits_gemm_cols_kernel(
const uint16_t* __restrict__ a, const uint16_t* __restrict__ w, float* __restrict__ c,
uint32_t M, uint32_t N, uint32_t a_ld, uint32_t c_ld) {
constexpr uint32_t C = kLgCols, KI = kLgKi, K = KI * kThreads * kLgVec, V = KI * kLgVec;
const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave;
const uint32_t j0 = (blockIdx.x * kWaves + wave) * C;
if (j0 >= N) return;
for (uint32_t r0 = 0; r0 < M; r0 += kLgRows) {
const uint32_t nr = (M - r0) < kLgRows ? (M - r0) : kLgRows;
float v[C][kLgRows];
#pragma unroll
for (uint32_t x = 0; x < C; ++x)
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) v[x][i] = 0.0f;
#pragma unroll 1
for (uint32_t q = 0; q < kWaves; ++q) {
const uint32_t k0 = (q * kWave + lane) * kLgVec;
uint4 wv[C][KI], av[kLgRows][KI];
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
const uint16_t* wr = w + (size_t)(j0 + x < N ? j0 + x : N - 1) * K + k0;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t)
wv[x][t] = *(const uint4*)(wr + t * kThreads * kLgVec);
}
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) {
if (i >= nr) break;
const uint16_t* ar = a + (size_t)(r0 + i) * a_ld + k0;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t)
av[i][t] = *(const uint4*)(ar + t * kThreads * kLgVec);
}
float wf[C][V];
#pragma unroll
for (uint32_t x = 0; x < C; ++x)
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
const uint32_t ww[4] = { wv[x][t].x, wv[x][t].y, wv[x][t].z, wv[x][t].w };
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
wf[x][t * kLgVec + p] = bf16_to_f32((uint16_t)(ww[p / 2] >> (16 * (p & 1))));
}
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i) {
if (i >= nr) break;
float af[V];
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
const uint32_t aw[4] = { av[i][t].x, av[i][t].y, av[i][t].z, av[i][t].w };
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
af[t * kLgVec + p] = bf16_to_f32((uint16_t)(aw[p / 2] >> (16 * (p & 1))));
}
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
float acc = 0.0f;
#pragma unroll
for (uint32_t t = 0; t < KI; ++t) {
float s = 0.0f;
#pragma unroll
for (uint32_t p = 0; p < kLgVec; ++p)
s += af[t * kLgVec + p] * wf[x][t * kLgVec + p];
acc += s;
}
v[x][i] += r4d_wave_sum(acc);
}
}
}
#pragma unroll
for (uint32_t x = 0; x < C; ++x) {
float out = 0.0f;
#pragma unroll
for (uint32_t i = 0; i < kLgRows; ++i)
if (i == lane) out = v[x][i];
if (lane < nr && j0 + x < N) c[(size_t)(r0 + lane) * c_ld + j0 + x] = out;
}
}
}
} // namespace
// a [M][K] bf16, `a_ld` elements a row (0 = K)
@@ -1258,6 +1351,21 @@ extern "C" int r4d_logits_gemm_bf16(long a, long w, long c, int M, int K, int N,
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// The column form; n_embd must be 4096 and an activation row whole 16 bytes.
extern "C" int r4d_logits_gemm_bf16_cols(long a, long w, long c, int M, int K, int N, int a_ld,
int c_ld, long stream) {
if (!a || !w || !c) return -1;
if (M <= 0 || N <= 0) return -2;
if (!a_ld) a_ld = K;
if (!c_ld) c_ld = N;
if (K != (int)(kLgKi * kThreads * kLgVec) || a_ld % (int)kLgVec) return -3;
const uint32_t per = kWaves * kLgCols;
hipLaunchKernelGGL(logits_gemm_cols_kernel, dim3(((uint32_t)N + per - 1) / per), dim3(kThreads),
0, (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)w, (float*)c,
(uint32_t)M, (uint32_t)N, (uint32_t)a_ld, (uint32_t)c_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// ============================================================== the plugin ABI entry points
//
// Unpacking RadArgs and deriving row pitches belongs to the kernel library (libr4d/r4d_args.h).
@@ -2148,3 +2256,31 @@ extern "C" int r4d_rad_logits_gemm(const RadArgs* a, RadStream s) {
(int)n_vocab, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
/* logits_gemm_bf16_cols: the operands and checks above, then the column form at the n_embd of its
* row's constraint, with the activation's rows whole 16 bytes. */
extern "C" int r4d_rad_logits_gemm_cols(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, LG_X);
const RadTensor* w = r4d_opt(a, LG_W);
const RadTensor* y = r4d_opt(a, LG_Y);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(x));
R4D_NEED(dt_bf16(w));
if (y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(w)) return R4D_NO(RAD_E_STRIDE);
const long long n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(w, 0));
const long long n_embd = r4d_geti_or(a, "n_embd", r4d_dim(w, 1));
if (n_vocab <= 0 || n_embd != 4096) return R4D_NO(RAD_E_SHAPE);
if (w->rank != 2 || w->shape[0] != n_vocab || w->shape[1] != n_embd)
return R4D_NO(RAD_E_SHAPE);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n_embd, &M);
const long long y_ld = r4d_rows_pitch(y, n_vocab, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 16) || x_ld % 8)
return R4D_NO(RAD_E_ALIGN);
return r4d_logits_gemm_bf16_cols(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd,
(int)n_vocab, (int)x_ld, (int)y_ld,
(long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE;
}
+4
View File
@@ -67,6 +67,9 @@ enum {
* these rows' layout hooks refuse a bf16 head, and the bf16 row has no hook for a scaled
* one. */
R4D_PRIO_LOGITS_FP8 = 60,
/* The bf16 head's column form, above the block-per-column row whose bytes it gives, at the
* n_embd it is built for. */
R4D_PRIO_LOGITS_COLS = 55,
/* Runtime LoRA: the tiled rows serve a subset of the scalar rows' dtypes at every M, so they
* must outrank them to be reached; the scalar rows keep f16 / f32 activations (no exact WMMA)
@@ -718,6 +721,7 @@ int r4d_rad_kv_store_fp8 (const RadArgs*, RadStream);
int r4d_rad_kv_store_fp8v4 (const RadArgs*, RadStream);
int r4d_rad_kv_store_k6v4 (const RadArgs*, RadStream);
int r4d_rad_logits_gemm (const RadArgs*, RadStream);
int r4d_rad_logits_gemm_cols(const RadArgs*, RadStream);
/* -- the decomposed sampler chain (r4d_sample_stages_f32.hip) --
*
+11
View File
@@ -4995,6 +4995,7 @@ static const RadConstraint cSampleCand[] = { C_GE("n_cand", 1), C_LE("n_cand", 4
static const RadConstraint cSampleLogprobs[] = { C_GE("n_vocab", 1), C_GE("k", 1), C_LE("k", 64) };
/* The activation width the column loop vectorises over; M is unbounded -- the kernel chunks rows. */
static const RadConstraint cLogitsGemm[] = { C_DIV("n_embd", 8), C_IN("dtype", "bf16") };
static const RadConstraint cLogitsGemmCols[] = { C_EQ("n_embd", 4096), C_IN("dtype", "bf16") };
/* The fp8 head: n_embd on the 128 scale block, and no cap on M. The row relayouts the weight, so
* it must cover the whole range; above a cap the bf16 projection would read the E4M3 codes as bf16.
* The kernel chunks above 32, and core/build/rad_builder.cpp refuses a capped arrangement.
@@ -5684,6 +5685,16 @@ static const RadKernelInfo kKernels[] = {
nullptr, nullptr, r4d_rad_logits_gemm, nullptr, nullptr, nullptr,
r4d_shape_logits_gemm },
{ "logits_gemm_bf16_cols", "logits_gemm", "vocab",
"logits_gemm_bf16 with a wave per four vocabulary columns: lane l runs that row's threads 32q + l "
"in turn, so each column keeps its k chunks, lane butterfly and wave order",
"any M and any vocabulary; n_embd 4096 exactly; the activation's row pitch whole 16 bytes",
"bf16 x and lm_head, F32 LOGITS OUT, fp32 accumulate. BYTE-IDENTICAL to logits_gemm_bf16",
RAD_DOMAIN_DEVICE, R4D_PRIO_LOGITS_COLS,
ROW(cLogitsGemmCols), NOTUNE,
nullptr, nullptr, r4d_rad_logits_gemm_cols, nullptr, nullptr, nullptr,
r4d_shape_logits_gemm },
{ "logits_gemm_fp8", "logits_gemm", "vocab",
"the lm_head projection over an fp8 head: C[M, n_vocab] f32 = x[M, n_embd] @ dequant(W)^T, "
"one wave a vocabulary row, the row's own scales in its tail",
+91
View File
@@ -14994,6 +14994,72 @@ static void mx_experts_check(const Plugin& pl, int M, int parts, bool pooled, co
dlclose(ref);
}
/* logits_gemm_bf16_cols against logits_gemm_bf16 on the same operands: the column form must give
* the block-per-column row's bytes. M from one row to past the 8-row chunk, a vocabulary not a
* multiple of the four columns a wave takes, an activation row pitch past n_embd, and a NaN and
* signed zeros in the activation, which the per-thread sums must carry the same way. With `iters`
* both rows are also timed at GLM-5.3's TP8 slice, where the weight is past the last-level cache
* and every launch reads it from memory. */
static void logits_cols_check(const Plugin& pl, int64_t M, int64_t N, int iters = 0) {
const RadKernelInfo* ref = find(pl, "logits_gemm_bf16");
const RadKernelInfo* cols = find(pl, "logits_gemm_bf16_cols");
if (!ref || !cols) {
ok("logits_gemm_bf16_cols", false, "row absent");
return;
}
const int64_t K = 4096, xp = K + 8;
std::vector<uint16_t> hx((size_t)(M * xp), 0), hw((size_t)(N * K));
for (int64_t r = 0; r < M; ++r)
for (int64_t k = 0; k < K; ++k)
hx[(size_t)(r * xp + k)] = st_rand_bf16((uint32_t)(r * K + k));
hx[3] = 0x8000;
if (M > 1) hx[(size_t)(xp + 7)] = 0x7fc0;
for (size_t i = 0; i < hw.size(); ++i) hw[i] = st_rand_bf16((uint32_t)i + 0x51ed27u);
void* dx = dalloc(hx.size() * 2);
void* dw = dalloc(hw.size() * 2);
void* dy = dalloc((size_t)(M * N) * 4);
if (!dx || !dw || !dy) {
ok("logits_gemm_bf16_cols allocation", false);
dfree_all();
return;
}
st_memcpy(dx, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
st_memcpy(dw, hw.data(), hw.size() * 2, hipMemcpyHostToDevice);
std::vector<RadTensor> ts = { T(dx, RAD_BF16, { M, K }), T(dw, RAD_BF16, { N, K }),
T(dy, RAD_F32, { M, N }) };
ts[0].stride[0] = xp;
std::vector<RadParam> ps = { PI("M", M), PI("n_vocab", N), PI("n_embd", K),
PS("dtype", "bf16") };
std::vector<uint8_t> want((size_t)(M * N) * 4), got(want.size());
st_memset(dy, 0xa5, want.size());
run_case(ref, ts, ps);
st_memcpy(want.data(), dy, want.size(), hipMemcpyDeviceToHost);
st_memset(dy, 0x5a, got.size());
run_case(cols, ts, ps);
st_memcpy(got.data(), dy, got.size(), hipMemcpyDeviceToHost);
ok(fmt("logits_gemm_bf16_cols M=%lld N=%lld: the bytes of logits_gemm_bf16", (long long)M,
(long long)N)
.c_str(),
got == want);
if (iters > 0) {
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = ts.data();
a.n_t = (int)ts.size();
a.p = ps.data();
a.n_p = (int)ps.size();
a.world_size = 1;
const double bytes = (double)(N * K * 2);
for (const RadKernelInfo* r : { ref, cols }) {
for (int i = 0; i < 3; ++i) r->launch(&a, nullptr);
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
std::printf(" %-22s M=%-3lld %9.1f us %6.1f GB/s of weight\n", r->name, (long long)M,
us, bytes / (us * 1e3));
}
}
dfree_all();
}
/* The MXFP4 expert GEMM at GLM's TP8 slices (mx_experts_check's model shapes 3 and 4): gate_up
* 512 x 4096 over token rows (parts 2), down 4096 x 256 over sorted rows, over an M-token chunk.
*
@@ -26705,6 +26771,13 @@ static void device_phase(const Plugin& pl) {
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33 })
fp8_logits_numeric(pl, 2560, 2560, M);
}
/* The bf16 head's column form against the block-per-column row, to past one 8-row chunk. */
if (sel("logits_gemm_bf16_cols")) {
for (const int64_t M : { (int64_t)1, (int64_t)2, (int64_t)6, (int64_t)8, (int64_t)9,
(int64_t)17 })
logits_cols_check(pl, M, 2051);
logits_cols_check(pl, 6, 19360);
}
/* The int8 head over the same stored row: both forms, and the padded K = 2560 row. */
if (sel("logits_gemm_i8") || sel("logit_rerank_i8")) {
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33, (int64_t)64 })
@@ -27008,6 +27081,8 @@ static void usage(void) {
" --perfkda M [iters]: kda_update at GLM's TP8 shape: prefill of M tokens (one\n"
" sequence, and three anchored) and the 8x6 verify step, timed.\n"
" --perfproject M [iters]: mla_project at GLM's TP8 shape, both modes, timed.\n"
" --perflogits M [iters]: logits_gemm_bf16 and logits_gemm_bf16_cols at\n"
" GLM-5.3's TP8 head slice (19360 x 4096), M rows, bytes compared.\n"
" --perfmx M [iters] [experts] [top_k] [skew]: the MXFP4 expert GEMM at GLM's\n"
" TP8 slices (gate_up 512 x 4096, down 4096 x 256) over a routing of an\n"
" M-token chunk (288 experts, top 8 by default; uniform, or `skew` a Gamma\n"
@@ -27072,6 +27147,8 @@ int main(int argc, char** argv) {
long long ar8_n = -1;
int ar8_it = 200;
const char* ar8_dt = "bf16";
long long lg_m = 0;
int lg_it = 200;
long long mx_m = 0, mx_e = 288, mx_k = 8;
const char* mx_skew = nullptr;
bool mx_f8 = false;
@@ -27238,6 +27315,11 @@ int main(int argc, char** argv) {
if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_e = std::strtoll(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_k = std::strtoll(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != 0x2d) mx_skew = argv[++i];
} else if (!std::strcmp(argv[i], "--perflogits")) {
/* Both bf16 head rows at GLM-5.3's TP8 slice over M rows. */
if (i + 1 >= argc) { usage(); return 2; }
lg_m = std::strtoll(argv[++i], nullptr, 0);
if (i + 1 < argc && argv[i + 1][0] != 0x2d) lg_it = (int)std::strtol(argv[++i], nullptr, 0);
} else if (!std::strcmp(argv[i], "--perfhc")) {
/* The gated residual's read at M rows. */
if (i + 1 >= argc) { usage(); return 2; }
@@ -27411,6 +27493,15 @@ int main(int argc, char** argv) {
dfree_all();
#else
skip("kda_update and mla_project timing", "built without HIP");
#endif
return 0;
}
if (lg_m) {
if (!load(&pl, path)) return 1;
#ifdef RAD_HAVE_HIP
logits_cols_check(pl, lg_m, 19360, lg_it);
#else
skip("bf16 head timing", "built without HIP");
#endif
return 0;
}