This repository has been archived on 2026-11-24. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
radiance-sycl/libxe2/xe2_gemv_m2.cpp
T
pascallinxweilerandClaude Opus 5.5 55a350f0c6 libxe2: the DFlash2 path fast -- exact draft head, DPAS verify GEMV, parallel rerank
- gemm_nt_q over the zero-point grids at M <= 16 (the drafter's 2-bit vocabulary head, N=248320):
  a sub-group a column, the group sums exact integers in f32, libref's group terms added in group
  order through lane broadcasts -- bit-identical to the exact kernel on the live head (checked in
  the engine: 0 differing bytes of 3.5 MB, every round). 252 ms -> well under 1 ms a call.
- m2xfp4 at 2 <= M <= 16 (the verify width) on XMX: a lane a column decodes its codes a 64-byte line
  at a time into its sub-group's VNNI slice of local memory (subnormal-bit fp16 pairs times
  (1 + k/4) * 2^(e - e_max + 14)), eight K16 DPAS a step against the permuted fp16 activation,
  K split for narrow N, partials added in order. On the vector ALUs M = 8 cost five times M = 1;
  gate_up at M = 8 1159 -> ~490 us. rad-kbench on the 27B: 50/50, rel_l2 ~8.5e-4 (tol 4e-2).
- logit_rerank: a work-group a row, a sub-group a candidate along K, libref's double sum as a float
  pair (two-product, two-sum, a fixed lane tree), libref's selection; 136 ms -> negligible a call.
- the gated delta net's gate, beta and decay (libref's double exp / log1p) once a (token, head)
  in a prepass instead of once a column block; still bit-identical (10/10 at rel_l2 0).
- profile_decode.sh: KEEP=DIR keeps the per-geometry tables.

27B on the B65, greedy: 12.1 tok/s plain, 13.2 tok/s with the drafter (device time a token
217 -> 76 ms under speculation). The drafter's text now departs from plain decoding at a
near-tie (byte 246 of 256 tokens): the verify forward runs the M = 8 DPAS path and plain decoding
the M = 1 GEMV, whose roundings differ (~1e-3); with the exact kernels the two were identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018EpFgqQidSnH8zo7boVZC1
2026-10-24 04:37:16 +02:00

458 lines
26 KiB
C++

/* xe2_gemv_m2.cpp -- the fast gemm_nt_q at m2xfp4 for M <= 16: decode and the speculative verify,
* bandwidth-bound by construction (a 27B step reads ~14 GB of these weights).
*
* One 16-lane sub-group an output column. Lane l walks the 32-column groups l, l + 16, ...: per
* group one 16-byte load of codes (32 e2m1 nibbles), the group's E8M0 exponent and meta byte, and
* 32 bytes of each activation row's E4M3 codes. A group's four 8-column subgroups are summed as
* sum(a * e2m1(code)) and scaled once by a_scale[m][k/128] * 2^(e-127) * (1 + k_s/4); the lane's
* groups add up in order and the sub-group reduces them as a tree. So the result is libref's
* product (each weight is e2m1 * 2^e * (1 + k/4), exact in f32) summed in another order: checked
* against libref at rad-kbench's gemm tolerance and the KL bound (docs/SYCL_PROGRESS.md D13), as
* the bf16 GEMV is. XE2_EXACT=1 sends every launch to the correctness-first kernel.
*
* Parts (pb1/pb2): a column reads the activation copy its part names, as xe2_gemm_m2.cpp does.
* Takes K a multiple of 32, a dense activation row and codes rows of K/2 bytes 16-byte aligned;
* anything else falls back to the exact kernel.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include <algorithm>
namespace xe2 {
namespace {
using half = sycl::half;
constexpr int kMaxM = 16;
constexpr int kColsM1 = 4; /* output columns a sub-group at M = 1 */
constexpr size_t kWg = 256; /* 16 sub-groups */
int64_t row_stride(const RadTensor* t, int64_t cols) {
if (!t || t->rank < 2) return cols;
int64_t span = 1;
for (int i = (int)t->rank - 1; i >= 0; --i) {
span *= t->shape[i];
if (span == cols) return (i > 0) ? t->stride[i - 1] : cols;
if (span > cols) break;
}
return t->stride[t->rank - 2];
}
/* E4M3 to f32: sign, 4 exponent bits (bias 7), 3 mantissa bits; 0x7F / 0xFF are NaN. */
inline float e4m3(uint8_t b) {
const uint32_t s = (uint32_t)(b & 0x80) << 24;
const uint32_t e = (b >> 3) & 0xF, m = b & 7;
if ((b & 0x7F) == 0x7F) return sycl::bit_cast<float>(s | 0x7FC00000u);
if (e == 0) {
const float v = (float)m * (1.0f / 512.0f); /* 2^-6 * m / 8 */
return s ? -v : v;
}
return sycl::bit_cast<float>(s | ((e + 120) << 23) | (m << 20));
}
/* The weights as fp16 by bits alone: for a code (s, m2 m1 m0) the half with magnitude bits
* m2 m1 m0 << 9 and sign bit 15 is exactly e2m1(code) * 2^-14 -- 0.5 * 2^-14 is the subnormal
* 0x0200 -- so a pair of codes is two shifts, two masks and an or (the card's fp16 keeps
* subnormals; m2bench in scratch measured it). Pairs are the codes (u, u + 4) of a 32-bit word,
* so the activation is laid out with K permuted alike within each 8. The activation carries the
* 2^14: a16 = fp16(a * a_scale / R * 2^14), R = 224 * the row's largest scale, so |a16| <= 2^15.
* A subgroup's four pairs accumulate in half2, times (1 + k/4) into the group's half2, which is
* widened and scaled by 2^(e-127) into the f32 sum: fp16 sums of at most 32 products. */
template <int MM, int NC>
int launch(sycl::queue& q, const half* a16, const float* rr, const uint8_t* codes0,
const uint8_t* meta0, const uint8_t* expe0, char* yb, uint32_t ydt, int64_t N, int64_t K,
int64_t acols, int64_t brs, int64_t yrs, int64_t ycs, int mm, int64_t e1, int64_t e2) {
const int64_t per_wg = 16 * NC;
const size_t groups = (size_t)((N + per_wg - 1) / per_wg);
const int64_t kg = K / 32;
return submit([&] {
syclex::nd_launch(q, sycl::nd_range<1>{groups * kWg, kWg},
[=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
const sycl::sub_group sg = it.get_sub_group();
const int64_t n0 = ((int64_t)it.get_group(0) * 16 + (int64_t)sg.get_group_linear_id()) * NC;
if (n0 >= N) return; /* uniform across the sub-group */
const int lane = (int)sg.get_local_linear_id();
/* The columns of one sub-group share a part: the part bounds are multiples of 16 and
* NC divides 16, so n0 .. n0 + NC - 1 never straddle one. */
const int nc = (int)sycl::min((int64_t)NC, N - n0);
const int64_t part = n0 < e1 ? 0 : (n0 < e2 ? 1 : 2);
const half* arow0 = a16 + part * K;
using H2 = sycl::vec<half, 2>;
float acc[NC][MM];
for (int c = 0; c < NC; ++c)
for (int r = 0; r < MM; ++r) acc[c][r] = 0.0f;
for (int64_t g = lane; g < kg; g += kSub) {
for (int c = 0; c < NC; ++c) {
const int64_t n = n0 + (c < nc ? c : 0);
const sycl::vec<uint32_t, 4> cw = *(const sycl::vec<uint32_t, 4>*)(codes0 + n * (K / 2) + g * 16);
const float ev = sycl::ldexp(1.0f, (int)expe0[n * brs + g] - 127);
const uint32_t mt = meta0[n * kg + g];
H2 w2[16];
H2 kmh[4];
for (int j = 0; j < 4; ++j) {
const uint32_t word = cw[j];
for (int u = 0; u < 4; ++u) {
const uint32_t mb = u < 3 ? (word << (9 - 4 * u)) & 0x0E000E00u : (word >> 3) & 0x0E000E00u;
const uint32_t sb = (word << (12 - 4 * u)) & 0x80008000u;
w2[j * 4 + u] = sycl::bit_cast<H2>(mb | sb);
}
const half k1 = (half)(1.0f + 0.25f * (float)((mt >> (2 * j)) & 3));
kmh[j] = H2(k1, k1);
}
for (int r = 0; r < MM; ++r) {
if (r >= mm) break;
const sycl::vec<uint32_t, 16> aw = *(const sycl::vec<uint32_t, 16>*)(arow0 + r * acols + g * 32);
H2 pg(0.0f, 0.0f);
for (int j = 0; j < 4; ++j) {
H2 p2(0.0f, 0.0f);
for (int u = 0; u < 4; ++u) p2 = sycl::fma(sycl::bit_cast<H2>(aw[j * 4 + u]), w2[j * 4 + u], p2);
pg = sycl::fma(p2, kmh[j], pg);
}
acc[c][r] += ((float)pg[0] + (float)pg[1]) * ev;
}
}
}
for (int c = 0; c < NC; ++c) {
if (c >= nc) break;
for (int r = 0; r < MM; ++r) {
if (r >= mm) break;
const float v = sycl::reduce_over_group(sg, acc[c][r], sycl::plus<float>());
if (lane == 0) rad_store_f32(yb, ydt, r * yrs + (n0 + c) * ycs, v * rr[r]);
}
}
});
});
}
/* The verify band (2 <= M <= 16) on XMX. A lane per output column: it reads its column's codes a
* 64-byte line (four 32-groups) at a time and writes the decoded fp16 pairs -- (u, u + 4) of each
* word, the subnormal-bits form times (1 + k/4) * 2^(e - e_max + 14) by one half2 multiply,
* exactly e2m1 * (1 + k/4) * 2^(e - e_max) -- into its sub-group's VNNI slice of local memory,
* consecutive words across the lanes; then the sub-group runs eight K16 DPAS against the fp16
* activation fp16(a * a_scale / R) laid out in the same permuted order. The vector ALUs keep the
* decode, DPAS takes the rows: on the ALUs alone M = 8 costs five times M = 1 (m2bench in scratch).
* K is split when the columns alone give too few work-groups; the partials are added in split
* order, then y = acc * R_m * 2^(e_max - 127). Products in f32 (DPAS), the activation rounded once
* to fp16: held to the gemm tolerance and the KL bound like the rest. */
namespace jm = sycl::ext::oneapi::experimental::matrix;
constexpr int kKs = 4; /* 32-groups a step: one 64-byte line of a column's codes */
template <int MT>
int launch_dpas(sycl::queue& q, const half* a16, int64_t lda, const int32_t* emax,
const uint8_t* codes0, const uint8_t* meta0, const uint8_t* expe0, int64_t brs,
float* pbuf, int64_t N, int64_t K, int64_t e1, int64_t e2, int64_t mpad, int splits) {
const int64_t ntile = (N + 127) / 128;
const size_t groups = (size_t)(ntile * splits);
const int64_t kg = K / 32;
const int64_t per = ((kg + splits - 1) / splits + kKs - 1) / kKs * kKs;
const int64_t ldp = ntile * 128;
return submit([&] {
q.submit([&](sycl::handler& h) {
sycl::local_accessor<uint32_t, 1> bt(sycl::range<1>((size_t)8 * kKs * 16 * 16), h);
h.parallel_for(sycl::nd_range<1>{groups * 128, 128}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] {
using H2 = sycl::vec<half, 2>;
const sycl::sub_group sg = it.get_sub_group();
const int s = (int)sg.get_group_linear_id(), lane = (int)sg.get_local_linear_id();
const int64_t tile = (int64_t)it.get_group(0) % ntile, sp = (int64_t)it.get_group(0) / ntile;
const int64_t g0s = sp * per, g1s = sycl::min(kg, g0s + per);
const int64_t n0 = tile * 128 + s * 16;
if (n0 >= N) return; /* uniform */
const int64_t n = sycl::min(n0 + lane, N - 1);
const int64_t part = n0 < e1 ? 0 : (n0 < e2 ? 1 : 2);
const half* abase = a16 + part * K;
const uint8_t* crow = codes0 + n * (K / 2);
const int emx = emax[n];
uint32_t* mine = &bt[(size_t)s * kKs * 16 * 16];
jm::joint_matrix<sycl::sub_group, half, jm::use::a, 8, 16, jm::layout::row_major> ma;
jm::joint_matrix<sycl::sub_group, half, jm::use::b, 16, 16, jm::layout::ext_intel_packed> mb;
jm::joint_matrix<sycl::sub_group, float, jm::use::accumulator, 8, 16> mc[MT];
for (int i = 0; i < MT; ++i) jm::joint_matrix_fill(sg, mc[i], 0.0f);
for (int64_t g0 = g0s; g0 < g1s; g0 += kKs) {
const sycl::vec<uint32_t, 16> line = *(const sycl::vec<uint32_t, 16>*)(crow + g0 * 16);
const uint32_t e4 = *(const uint32_t*)(expe0 + n * brs + g0);
const uint32_t m4 = *(const uint32_t*)(meta0 + n * kg + g0);
for (int gg = 0; gg < kKs; ++gg) {
const int d = (int)((e4 >> (8 * gg)) & 0xFF) - emx;
const float sc = d < -30 ? 0.0f : sycl::ldexp(16384.0f, d);
const uint32_t mt = (m4 >> (8 * gg)) & 0xFF;
for (int j = 0; j < 4; ++j) {
const uint32_t word = line[gg * 4 + j];
const half kh = (half)((1.0f + 0.25f * (float)((mt >> (2 * j)) & 3)) * sc);
const H2 k2(kh, kh);
for (int u = 0; u < 4; ++u) {
const uint32_t mb2 = u < 3 ? (word << (9 - 4 * u)) & 0x0E000E00u : (word >> 3) & 0x0E000E00u;
const uint32_t sb2 = (word << (12 - 4 * u)) & 0x80008000u;
mine[(gg * 16 + j * 4 + u) * 16 + lane] = sycl::bit_cast<uint32_t>(sycl::bit_cast<H2>(mb2 | sb2) * k2);
}
}
}
sycl::group_barrier(sg);
for (int kk = 0; kk < kKs * 32; kk += 16) {
auto lb = sycl::address_space_cast<sycl::access::address_space::local_space,
sycl::access::decorated::no>((half*)mine + (size_t)(kk / 2) * 32);
jm::joint_matrix_load(sg, mb, lb, 32);
for (int i = 0; i < MT; ++i) {
auto ga = sycl::address_space_cast<sycl::access::address_space::global_space,
sycl::access::decorated::no>(abase + (int64_t)i * 8 * lda + g0 * 32 + kk);
jm::joint_matrix_load(sg, ma, ga, (size_t)lda);
jm::joint_matrix_mad(sg, mc[i], ma, mb, mc[i]);
}
}
sycl::group_barrier(sg);
}
for (int i = 0; i < MT; ++i) {
auto gp = sycl::address_space_cast<sycl::access::address_space::global_space,
sycl::access::decorated::no>(pbuf + (sp * mpad + (int64_t)i * 8) * ldp + n0);
jm::joint_matrix_store(sg, mc[i], gp, (size_t)ldp, jm::layout::row_major);
}
});
});
});
}
int m2_dpas(sycl::queue& q, const RadTensor* A, const RadTensor* AS, const uint8_t* codes0,
const uint8_t* meta0, const uint8_t* expe0, int64_t brs, const RadTensor* Y, int64_t M,
int64_t N, int64_t K, int64_t acols, int64_t scols, int64_t ars, int64_t srs, int64_t yrs,
int64_t ycs, int64_t e1, int64_t e2) {
const int mt = (int)((M + 7) / 8);
const int64_t mpad = (int64_t)mt * 8, kg = K / 32, kb = kg;
const int64_t ntile = (N + 127) / 128, ldp = ntile * 128;
constexpr int64_t kFill = 160;
const int splits = (int)std::min<int64_t>(std::max<int64_t>(1, (kFill + ntile - 1) / ntile), std::max<int64_t>(1, kg / kKs));
const int64_t abytes = (mpad * acols * 2 + 255) / 256 * 256, rbytes = (mpad * 4 + 255) / 256 * 256;
float* ws = workspace(q, (size_t)((abytes + rbytes + N * 4) / 4 + 64));
float* pbuf = workspace(q, (size_t)(splits * mpad * ldp), 2);
if (!ws || !pbuf) return RAD_E_DEVICE;
half* a16 = (half*)ws;
float* rr = (float*)((char*)ws + abytes);
int32_t* emax = (int32_t*)((char*)ws + abytes + rbytes);
const uint8_t* ab = (const uint8_t*)A->data;
const char* sab = (const char*)AS->data;
const uint32_t sadt = AS->dtype;
int rc = submit([&] {
q.parallel_for(sycl::nd_range<1>{(size_t)mpad * 256, 256}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0), t = (int64_t)it.get_local_id(0);
float mx = 0.0f;
if (m < M)
for (int64_t c = t; c < scols; c += 256) mx = sycl::fmax(mx, rad_load_f32(sab, sadt, m * srs + c));
mx = sycl::reduce_over_group(it.get_group(), mx, sycl::maximum<float>());
const float R = mx > 0.0f ? 224.0f * mx : 1.0f;
if (t == 0) rr[m] = R;
const float f = 1.0f / R;
for (int64_t c = t; c < acols; c += 256) {
const int64_t p = c & 7, src = (c & ~(int64_t)7) + (p >> 1) + 4 * (p & 1);
a16[m * acols + c] = m < M ? (half)(e4m3(ab[m * ars + src]) * rad_load_f32(sab, sadt, m * srs + src / 128) * f)
: (half)0.0f;
}
});
q.parallel_for(sycl::range<1>((size_t)N), [=](sycl::id<1> i) {
const uint8_t* er = expe0 + (int64_t)i[0] * brs;
int32_t mx = 0;
int64_t g = 0;
if ((kb & 15) == 0 && ((uintptr_t)er & 15) == 0)
for (; g < kb; g += 16) {
const sycl::vec<uint8_t, 16> ev = *(const sycl::vec<uint8_t, 16>*)(er + g);
for (int u = 0; u < 16; ++u) mx = sycl::max(mx, (int32_t)ev[u]);
}
for (; g < kb; ++g) mx = sycl::max(mx, (int32_t)er[g]);
emax[i[0]] = mx;
});
});
if (rc < 0) return rc;
rc = mt == 1 ? launch_dpas<1>(q, a16, acols, emax, codes0, meta0, expe0, brs, pbuf, N, K, e1, e2, mpad, splits)
: launch_dpas<2>(q, a16, acols, emax, codes0, meta0, expe0, brs, pbuf, N, K, e1, e2, mpad, splits);
if (rc < 0) return rc;
char* yb = (char*)Y->data;
const uint32_t ydt = Y->dtype;
return submit([&] {
q.parallel_for(sycl::range<1>((size_t)(M * N)), [=](sycl::id<1> i) {
const int64_t m = (int64_t)i[0] / N, c = (int64_t)i[0] % N;
float acc = 0.0f;
for (int sp = 0; sp < splits; ++sp) acc += pbuf[(sp * mpad + m) * ldp + c];
rad_store_f32(yb, ydt, m * yrs + c * ycs, acc * rr[m] * sycl::ldexp(1.0f, emax[c] - 127));
});
});
}
} // namespace
int gemm_nt_q_m2_gemv(const RadArgs* a, RadStream st) {
if (exact_only()) return gemm_nt_q_m2(a, st);
if (!a || a->n_t < 5) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor *AS = rad_arg_in(a, 1), *BS = rad_arg_in(a, 3);
if (!A->data || !B->data || !Y->data || !AS || !BS || !AS->data || !BS->data) return RAD_E_INVAL;
const int64_t K = rad_args_geti_or(a, "K", 0), N = rad_args_geti_or(a, "N", 0);
if (K <= 0 || K % 32 || N <= 0) return gemm_nt_q_m2(a, st);
const int64_t M = rad_tensor_numel(Y) / N;
if (M < 1 || M > kMaxM || rad_arg_in(a, 5)) return gemm_nt_q_m2(a, st);
const int64_t pb1 = rad_args_geti_or(a, "pb1", 0), pb2 = rad_args_geti_or(a, "pb2", 0);
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
const int64_t kb = K / 32, akb = (K + 127) / 128;
const int64_t acols = parts * K, scols = parts * akb;
const bool blob = (B->rank == 1 && rad_tensor_numel(B) == N * (K / 2 + kb)) ||
(B->rank == 2 && B->shape[0] == N && B->shape[1] == K);
const int64_t ars = row_stride(A, acols), srs = row_stride(AS, scols), brs = row_stride(BS, kb);
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const bool ok = blob && A->dtype == RAD_F8E4M3 && B->dtype == RAD_U8 && BS->dtype == RAD_E8M0 &&
(A->rank < 2 || A->stride[A->rank - 1] == 1) &&
(AS->rank < 2 || AS->stride[AS->rank - 1] == 1) && ars % 16 == 0 &&
rad_ptr_aligned(A->data, 16) && rad_ptr_aligned(B->data, 16) &&
(K / 2) % 16 == 0 && rad_tensor_numel(A) >= M * acols &&
rad_tensor_numel(AS) >= M * scols && rad_tensor_numel(BS) >= N * kb &&
(!(pb1 > 0 || pb2 > 0) || ((e1 % 16) == 0 && (e2 % 16) == 0 && !(e1 == e2 && e2 < N)));
if (!ok) return gemm_nt_q_m2(a, st);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const uint8_t* codes0 = (const uint8_t*)B->data;
const uint8_t* meta0 = codes0 + N * (K / 2);
const int mm = (int)M;
/* the verify band on XMX, where its line loads fit: K a multiple of 128, aligned rows */
if (mm >= 2 && K % 128 == 0 && brs % 4 == 0 && rad_ptr_aligned(BS->data, 4) &&
((uintptr_t)meta0 & 3) == 0 && (K / 2) % 64 == 0 && rad_ptr_aligned(B->data, 64))
return m2_dpas(*q, A, AS, codes0, meta0, (const uint8_t*)BS->data, brs, Y, M, N, K, acols, scols,
ars, srs, yrs, ycs, e1, e2);
/* The activation once as fp16 in the weight pairs' order, with its row factor R. */
const int64_t abytes = (M * acols * 2 + 255) / 256 * 256;
float* ws = workspace(*q, (size_t)(abytes / 4 + M + 64));
if (!ws) return RAD_E_DEVICE;
half* a16 = (half*)ws;
float* rr = (float*)((char*)ws + abytes);
{
const uint8_t* ab = (const uint8_t*)A->data;
const char* sab = (const char*)AS->data;
const uint32_t sadt = AS->dtype;
const int rc = submit([&] {
q->parallel_for(sycl::nd_range<1>{(size_t)M * 256, 256}, [=](sycl::nd_item<1> it) {
const int64_t m = (int64_t)it.get_group(0);
const int64_t t = (int64_t)it.get_local_id(0);
float mx = 0.0f;
for (int64_t c = t; c < scols; c += 256) mx = sycl::fmax(mx, rad_load_f32(sab, sadt, m * srs + c));
mx = sycl::reduce_over_group(it.get_group(), mx, sycl::maximum<float>());
const float R = mx > 0.0f ? 224.0f * mx : 1.0f;
if (t == 0) rr[m] = R;
const float f = 16384.0f / R;
for (int64_t c = t; c < acols; c += 256) {
const int64_t p = c & 7, src = (c & ~(int64_t)7) + (p >> 1) + 4 * (p & 1);
a16[m * acols + c] = (half)(e4m3(ab[m * ars + src]) * rad_load_f32(sab, sadt, m * srs + src / 128) * f);
}
});
});
if (rc < 0) return rc;
}
auto go = [&](auto tag, auto cols) {
constexpr int MM = decltype(tag)::value, NC = decltype(cols)::value;
return launch<MM, NC>(*q, a16, rr, codes0, meta0, (const uint8_t*)BS->data, (char*)Y->data, Y->dtype,
N, K, acols, brs, yrs, ycs, mm, e1, e2);
};
/* Columns a sub-group: four at decode (the activation read once for four weight rows), fewer
* as the rows' accumulators grow. */
using I = std::integral_constant<int, 1>;
if (mm == 1) return go(I{}, std::integral_constant<int, kColsM1>{});
if (mm <= 4) return go(std::integral_constant<int, 4>{}, std::integral_constant<int, 2>{});
if (mm <= 8) return go(std::integral_constant<int, 8>{}, std::integral_constant<int, 2>{});
return go(std::integral_constant<int, 16>{}, I{});
}
} // namespace xe2
/* ------------------------------------------------------------------ prefill: through bf16 XMX */
/* For M > 16 the m2xfp4 weight is decoded to bf16 -- exact: e2m1 * (1 + k/4) has at most four
* significant bits and 2^(e-127) is within bf16's exponent -- and the activation rescaled to
* bf16(e4m3 * a_scale), one rounding of 2^-9 beside the activation's own E4M3 step of 2^-4. Then
* each part is gemm_nt_xmx over its column slice, which takes M8 tiles on XMX and the tail rows on
* the bf16 GEMV. The products differ from libref's by that one rounding and the summation order:
* held to rad-kbench's gemm tolerance and the KL bound. */
namespace xe2 {
int gemm_nt_q_m2_xmx(const RadArgs* a, RadStream st) {
if (exact_only()) return gemm_nt_q_m2(a, st);
if (!a || a->n_t < 5) return RAD_E_INVAL;
const RadTensor *A = &a->t[0], *B = &a->t[2], *Y = &a->t[4];
const RadTensor *AS = rad_arg_in(a, 1), *BS = rad_arg_in(a, 3);
if (!A->data || !B->data || !Y->data || !AS || !BS || !AS->data || !BS->data) return RAD_E_INVAL;
const int64_t K = rad_args_geti_or(a, "K", 0), N = rad_args_geti_or(a, "N", 0);
if (K <= 0 || K % 32 || N <= 0 || rad_arg_in(a, 5)) return gemm_nt_q_m2(a, st);
const int64_t M = rad_tensor_numel(Y) / N;
if (M < 1) return RAD_E_SHAPE;
const int64_t pb1 = rad_args_geti_or(a, "pb1", 0), pb2 = rad_args_geti_or(a, "pb2", 0);
const int64_t e1 = pb1 > 0 ? std::min<int64_t>(pb1, N) : N;
const int64_t e2 = pb2 > 0 ? std::max<int64_t>(e1, std::min<int64_t>(pb2, N)) : N;
const int64_t parts = e2 < N ? 3 : (e1 < N ? 2 : 1);
const int64_t kb = K / 32, akb = (K + 127) / 128;
const int64_t acols = parts * K, scols = parts * akb;
const bool blob = (B->rank == 1 && rad_tensor_numel(B) == N * (K / 2 + kb)) ||
(B->rank == 2 && B->shape[0] == N && B->shape[1] == K);
const int64_t ars = row_stride(A, acols), srs = row_stride(AS, scols), brs = row_stride(BS, kb);
const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1;
const bool ok = blob && A->dtype == RAD_F8E4M3 && B->dtype == RAD_U8 && BS->dtype == RAD_E8M0 &&
(A->rank < 2 || A->stride[A->rank - 1] == 1) &&
(AS->rank < 2 || AS->stride[AS->rank - 1] == 1) &&
rad_tensor_numel(A) >= M * acols && rad_tensor_numel(AS) >= M * scols &&
rad_tensor_numel(BS) >= N * kb &&
(!(pb1 > 0 || pb2 > 0) || ((e1 % 16) == 0 && (e2 % 16) == 0 && !(e1 == e2 && e2 < N)));
if (!ok) return gemm_nt_q_m2(a, st);
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
/* The workspace: the bf16 activation [M, parts * K], then the bf16 weight [N, K]. */
const int64_t abytes = (M * acols * 2 + 255) / 256 * 256;
float* ws = workspace(*q, (size_t)((abytes + N * K * 2) / 4 + 64));
if (!ws) return RAD_E_DEVICE;
uint16_t* a16 = (uint16_t*)ws;
uint16_t* w16 = (uint16_t*)((char*)ws + abytes);
const uint8_t* ab = (const uint8_t*)A->data;
const char* sab = (const char*)AS->data;
const uint32_t sadt = AS->dtype;
const uint8_t* codes0 = (const uint8_t*)B->data;
const uint8_t* meta0 = codes0 + N * (K / 2);
const uint8_t* expe0 = (const uint8_t*)BS->data;
int rc = submit([&] {
const int64_t na = M * acols;
q->parallel_for(sycl::range<1>((size_t)na), [=](sycl::id<1> i) {
const int64_t m = (int64_t)i[0] / acols, c = (int64_t)i[0] % acols;
const float v = e4m3(ab[m * ars + c]) * rad_load_f32(sab, sadt, m * srs + c / 128);
a16[m * acols + c] = rad_f32_to_bf16(v);
});
const int64_t nw = N * (K / 2); /* a work-item a code byte: two weights */
q->parallel_for(sycl::range<1>((size_t)nw), [=](sycl::id<1> i) {
const int64_t n = (int64_t)i[0] / (K / 2), j = (int64_t)i[0] % (K / 2);
const uint8_t byte = codes0[n * (K / 2) + j];
constexpr float lut[16] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,
-0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f };
for (int h = 0; h < 2; ++h) {
const int64_t k = 2 * j + h;
const float ev = sycl::ldexp(1.0f, (int)expe0[n * brs + (k >> 5)] - 127);
const float km = 1.0f + 0.25f * (float)((meta0[n * kb + (k >> 5)] >> (2 * ((k & 31) >> 3))) & 3);
w16[n * K + k] = rad_f32_to_bf16(lut[(byte >> (4 * h)) & 0xF] * ev * km);
}
});
});
if (rc < 0) return rc;
const int64_t bound[4] = { 0, e1, e2, N };
for (int p = 0; p < 3 && rc >= 0; ++p) {
const int64_t n0 = bound[p], n1 = bound[p + 1];
if (n1 <= n0) continue;
const int64_t pi = p == 0 ? 0 : (p == 1 ? 1 : (parts == 3 ? 2 : 1));
RadTensor t[3] = {};
t[0].data = a16 + pi * K; t[0].dtype = RAD_BF16; t[0].rank = 2;
t[0].shape[0] = M; t[0].shape[1] = K; t[0].stride[0] = acols; t[0].stride[1] = 1;
t[1].data = w16 + n0 * K; t[1].dtype = RAD_BF16; t[1].rank = 2;
t[1].shape[0] = n1 - n0; t[1].shape[1] = K; t[1].stride[0] = K; t[1].stride[1] = 1;
t[2].data = (char*)Y->data + (n0 * ycs) * ((rad_dtype_bits(Y->dtype) + 7) / 8);
t[2].dtype = Y->dtype; t[2].rank = 2;
t[2].shape[0] = M; t[2].shape[1] = n1 - n0; t[2].stride[0] = yrs; t[2].stride[1] = ycs;
RadParam pr[2] = { RAD_INT("N", n1 - n0), RAD_INT("K", K) };
RadArgs b = *a;
b.t = t; b.n_t = 3; b.p = pr; b.n_p = 2;
rc = gemm_nt_xmx(&b, st);
}
return rc;
}
} // namespace xe2