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_gemm_m2.cpp
T
pascallinxweilerandClaude Opus 5.5 4921641578 libxe2: every op Qwen3.8-27B-PARO-M2XFP4 needs, correctness first -- the 27B serves on the B65
Kernels, each libref's arithmetic in libref's order:
- gemm_nt_q at m2xfp4 (xe2_gemm_m2.cpp) with libref's m2 layout hooks, and givens_dense_quant
  (xe2_givens.cpp, the rotation in double as libref's)
- the gated delta net (xe2_gdn.cpp): gdn_conv_prep, gdn_conv_update, gdn_kkt_solve, gdn_chunk_scan,
  gdn_recurrent_update (per-candidate and anchor state forms), gdn_gated_rmsnorm,
  gdn_conv_recurrent_update; each work-item one iteration of libref's parallel loop, the
  per-(sequence, head) workspaces in a shared device workspace (xe2_common: workspace())
- rope's multi-component modes (mrope, imrope, axial) and rope_table
- logits_gemm over an fp8 128x128 joined head, gemm_nt_bias with its epilogue
- mul, sigmoid, scatter_rows, layernorm, grid_embed, attn_dense (the vision tower)
- dflash_conv and logit_rerank (plain and joined head) for the DFlash2 drafter

libref's gemm_m2 gains the parts (pb1/pb2) every other ParoQuant grid and libr4d's mx_parts
already define -- weight rows [0, e1), [e1, e2), [e2, N) read activation copies 0, 1, 2 side by
side -- since this model's fused projections are rotated per piece and the oracle declined them;
its shape hook widens a and a_scale by the part count. Both m2 arms now take the stored
codes-then-meta blob as the engine describes it, u8 [N, K], beside the shape hook's rank-1 form
(libref refused the engine's launch; only libr4d had been run on it).

rad-kbench on the fixture: every new row at rel_l2 0 (90 gdn/givens cases, 108 rope, 80
elementwise, 20 attn_dense, the drafter's and the heads'). On the B65 the model starts with every
op on the card and answers "The capital of France is" -> " Paris.\nThe capital of Germany is
Berlin.\nThe capital of Italy is" (greedy), at 0.1 tok/s: the correctness-first kernels.

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

211 lines
10 KiB
C++

/* xe2_gemm_m2.cpp -- gemm_nt_q at dtype m2xfp4 (the M2XFP4 grid of Qwen3.8-27B-PARO-M2XFP4).
* Correctness first: libref's gemm_m2 (ref_gemm.cpp) per output --
*
* w[k] = (e2m1(code[n][k]) * 2^(e[n][k/32] - 127)) * (1 + meta field / 4)
* acc = acc + (a[m][k] * a_scale[m][k/128]) * w[k] for ascending k, f32
*
* -- the meta byte's two-bit field [2s, 2s+2) over subgroups s of eight columns. The activation is
* givens_dense_quant's E4M3 with a scale per 128 columns; the weight's Givens rotation is the
* activation's, so the planes are read as they are stored. Parts (`pb1`, `pb2`, a fused projection
* rotated per piece): weight rows [0, e1), [e1, e2), [e2, N) read copies 0, 1, 2 of the activation
* and its scale, side by side, as libref's gemm_m2 and libr4d's mx_parts do.
*
* `b` reaches the kernel as the weight's codes rows, then its meta rows ("m2.codes.meta"), `b_scale`
* as the E8M0 plane [N, K/32]. The layout hooks are libref's m2 arm (ref_layout_gemm_q,
* ref_planes.h) line for line, so both libraries ask for the same stored bytes.
*/
#include "xe2_common.h"
#include "xe2_ops.h"
#include "rad_planes.h"
#include <algorithm>
#include <cstring>
namespace xe2 {
namespace {
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];
}
int64_t last_stride(const RadTensor* t) { return t->rank ? t->stride[t->rank - 1] : 1; }
bool sel_roles(const RadEncoding* enc, const int* sel, int n, const char* r0, const char* r1) {
if (!enc || !sel || n != 2) return false;
for (int i = 0; i < 2; ++i)
if (sel[i] < 0 || sel[i] >= enc->n_planes) return false;
return std::strncmp(enc->plane[sel[0]].role, r0, RAD_ENC_STR) == 0 &&
std::strncmp(enc->plane[sel[1]].role, r1, RAD_ENC_STR) == 0;
}
/* libref's m2_enc_planes: three tiled planes over 32-column groups, untransformed or under a
* "givens" transform with its tables beside them. */
bool m2_enc_planes(const RadEncoding* enc) {
if (!rad_enc_is(enc, "m2xfp4")) return false;
if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* mt = rad_enc_plane(enc, "meta");
const bool planes = enc->plane[0].kind == RAD_PLANE_TILED &&
enc->plane[0].dtype == RAD_FP4E2M1 && enc->plane[0].block[0] == 1 &&
enc->plane[0].block[1] == 1 && sc && mt && sc->kind == RAD_PLANE_TILED &&
sc->dtype == RAD_E8M0 && sc->block[0] == 1 && sc->block[1] == 32 &&
mt->kind == RAD_PLANE_TILED && mt->dtype == RAD_U8 && mt->block[0] == 1 &&
mt->block[1] == 32;
if (!planes) return false;
if (!enc->transform[0]) return enc->n_planes == 3;
return enc->n_planes >= 6 && rad_enc_plane(enc, "t.pairs") &&
rad_enc_plane(enc, "t.angle") && rad_enc_plane(enc, "t.scale");
}
constexpr const char* kTag = "m2.codes.meta";
} // namespace
/* ------------------------------------------------------------------ the layout hooks */
int gemm_m2_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* planes, int n, RadLayout* out) {
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
if (!dt || std::strcmp(dt, "m2xfp4") != 0) return RAD_E_DTYPE;
const long long group = rad_param_geti(p, n_p, "group", 0);
const long long N = rad_param_geti(p, n_p, "N", 0), K = rad_param_geti(p, n_p, "K", 0);
if (!m2_enc_planes(enc) || group != 32 || N <= 0 || K <= 0 || K % 32) return RAD_E_DTYPE;
if (operand == 2) {
if (!sel_roles(enc, sel, n, "codes", "meta")) return RAD_E_DTYPE;
if (planes[0].shape[0] != N || planes[0].shape[1] != K || planes[1].shape[0] != N ||
planes[1].shape[1] != K / 32)
return RAD_E_SHAPE;
out->tag = kTag;
out->dtype = RAD_U8;
out->rank = 1;
out->shape[0] = N * (K / 2 + K / 32);
out->align = 0;
out->bytes = out->shape[0];
return RAD_OK;
}
if (operand == 3 || operand == 6) {
if (n != 1 || sel[0] < 0 || sel[0] >= enc->n_planes ||
std::strncmp(enc->plane[sel[0]].role, "scale", RAD_ENC_STR) != 0)
return RAD_E_DTYPE;
return RAD_E_UNSUPPORTED; /* one plane, stored as it is */
}
return RAD_E_UNSUPPORTED;
}
int gemm_m2_relayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* planes, int n, void* dst, int64_t dst_bytes) {
RadLayout lay{};
const int st = gemm_m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (!lay.tag || std::strcmp(lay.tag, kTag) != 0)
return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes);
if (dst_bytes != lay.bytes) return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
for (int i = 0; i < n; ++i) {
const int64_t b = planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
std::memcpy(d, planes[i].data, (size_t)b);
d += b;
}
return RAD_OK;
}
int gemm_m2_unrelayout(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const void* src, int64_t src_bytes, const RadTensor* planes,
int n) {
RadLayout lay{};
const int st = gemm_m2_layout(p, n_p, operand, enc, sel, planes, n, &lay);
if (st != RAD_OK) return st;
if (!lay.tag || std::strcmp(lay.tag, kTag) != 0)
return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n);
if (src_bytes != lay.bytes) return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
for (int i = 0; i < n; ++i) {
const int64_t b = planes[i].shape[0] * rad_enc_row_bytes(planes[i].dtype, planes[i].shape[1]);
std::memcpy(planes[i].data, s, (size_t)b);
s += b;
}
return RAD_OK;
}
/* ------------------------------------------------------------------ the kernel */
int gemm_nt_q_m2(const RadArgs* a, RadStream 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) return RAD_E_INVAL;
if (rad_arg_in(a, 5)) return RAD_E_UNSUPPORTED; /* a_sum belongs to the asym grids */
if (A->dtype != RAD_F8E4M3 || B->dtype != RAD_U8 || !AS || !BS || !AS->data || !BS->data ||
BS->dtype != RAD_E8M0 || BS->rank < 2)
return RAD_E_DTYPE;
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 RAD_E_SHAPE;
const int64_t M = rad_tensor_numel(Y) / N;
if (M <= 0) return RAD_E_SHAPE;
const int64_t kb = K / 32, akb = (K + 127) / 128;
const int64_t pb1 = rad_args_geti_or(a, "pb1", 0), pb2 = rad_args_geti_or(a, "pb2", 0);
const bool parted = pb1 > 0 || 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);
if (parted && ((e1 % 16) || (e2 % 16))) return RAD_E_SHAPE;
if (parted && e1 == e2 && e2 < N) return RAD_E_SHAPE;
const int64_t acols = parts * K, scols = parts * akb;
/* `b` is the stored codes-then-meta blob: a rank-1 u8 of its bytes (the shape hook's
* description), or the weight's logical [N, K] u8 view of the same bytes (the engine's). */
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);
if (!blob) return RAD_E_SHAPE;
if (rad_tensor_numel(A) < M * acols ||
rad_tensor_numel(BS) < N * kb || rad_tensor_numel(AS) < M * scols)
return RAD_E_SHAPE;
if (A->rank >= 2 && A->shape[A->rank - 1] != acols) return RAD_E_SHAPE;
const int64_t ars = row_stride(A, acols), acs = last_stride(A);
const int64_t srs = row_stride(AS, scols), scs = last_stride(AS);
const int64_t brs = row_stride(BS, kb);
const int64_t yrs = row_stride(Y, N), ycs = last_stride(Y);
const char *ab = (const char*)A->data, *sb = (const char*)AS->data;
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;
char* yb = (char*)Y->data;
const uint32_t adt = A->dtype, sdt = AS->dtype, ydt = Y->dtype;
sycl::queue* q = queue_of(st);
if (!q) return RAD_E_DEVICE;
const int64_t total = M * N;
constexpr size_t wg = 128;
const size_t groups = (size_t)((total + (int64_t)wg - 1) / (int64_t)wg);
return submit([&] {
syclex::nd_launch(*q, sycl::nd_range<1>{groups * wg, wg}, [=](sycl::nd_item<1> it) {
const int64_t g = (int64_t)it.get_global_id(0);
if (g >= total) return;
const int64_t n = g % N, m = g / N;
const int64_t part = n < e1 ? 0 : (n < e2 ? 1 : 2);
const int64_t a0 = m * ars + part * K * acs, s0 = m * srs + part * akb * scs;
const uint8_t* codes = codes0 + n * (K / 2);
const uint8_t* meta = meta0 + n * kb;
const uint8_t* expe = expe0 + n * brs;
constexpr float e2m1[8] = { 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f };
float acc = 0.0f;
for (int64_t k = 0; k < K; ++k) {
const uint8_t c = (uint8_t)((codes[k >> 1] >> (4 * (k & 1))) & 0xF);
const float cv = (c & 8) ? -e2m1[c & 7] : e2m1[c & 7];
const float ev = sycl::ldexp(1.0f, (int)expe[k >> 5] - 127);
const float km = 1.0f + 0.25f * (float)((meta[k >> 5] >> (2 * ((k & 31) >> 3))) & 3);
const float w = cv * ev * km;
acc += rad_load_f32(ab, adt, a0 + k * acs) * rad_load_f32(sb, sdt, s0 + (k >> 7) * scs) * w;
}
rad_store_f32(yb, ydt, m * yrs + n * ycs, acc);
});
});
}
} // namespace xe2