/* xe2_gemm.cpp -- the unquantised GEMMs: gemm_nt (Y = A B^T) and logits_gemm, its lm_head twin. * * Correctness first (docs/SYCL_PORTING.md ยง4.8, Phase 3): one work-item an output, accumulating * a * b in f32 over ascending k from zero, no fused multiply-add, then one store: libref's * gemm_plain exactly. It reads each weight row once per output row, so it is slow; the XMX kernels * of Phase 4 are checked against it and against libref. * * A is read through its row and column strides (an activation may be a slice of a wider arena * buffer); B is the weight, [N, K]. A joined head (codes with a scale plane) and a non-float * weight are refused: those are gemm_nt_q's. */ #include "xe2_common.h" #include "xe2_ops.h" #include "rad_planes.h" #include #include namespace xe2 { namespace { /* libref's row_stride: fold trailing axes until they span `cols`. */ 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]; } bool is_float(uint32_t dt) { return dt == RAD_F32 || dt == RAD_F16 || dt == RAD_BF16 || dt == RAD_F8E4M3 || dt == RAD_F8E5M2; } /* A plane of a joined head, found on the card (the header lives in device memory). */ struct HPlane { const char* p = nullptr; uint32_t dt = 0; int64_t row_bytes = 0, br = 0, bc = 0; float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); } float cover(int64_t r, int64_t c) const { return at(br > 0 ? r / br : 0, bc > 0 ? c / bc : 0); } }; inline bool role_is(const char* r, const char* want) { for (int i = 0; i < RAD_ENC_STR; ++i) { if (r[i] != want[i]) return false; if (!want[i]) return true; } return true; } inline HPlane hplane(const char* base, const char* role) { HPlane v; const RadPlanesHeader* h = (const RadPlanesHeader*)base; if (h->magic != RAD_PLANES_MAGIC) return v; const RadPlanesEntry* e = (const RadPlanesEntry*)(base + sizeof(RadPlanesHeader)); for (int i = 0; i < h->n_planes && i < RAD_ENC_MAX_PLANES; ++i) if (role_is(e[i].role, role)) { v.p = base + e[i].offset; v.dt = e[i].dtype; v.row_bytes = e[i].row_bytes; v.br = e[i].block[0]; v.bc = e[i].block[1]; return v; } return v; } inline float gelu(float x) { return 0.5f * x * (1.0f + (float)sycl::erf((double)(x * 0.70710678118654752f))); } inline float gelu_tanh(float x) { const float k0 = 0.7978845608028654f, k1 = 0.044715f; return 0.5f * x * (1.0f + (float)sycl::tanh((double)(k0 * (x + k1 * x * x * x)))); } /* libref's gemm_nt_impl: acc += a * b over ascending k, then the bias, stored; then the activation * on the stored value and the residual added to it, each stored (gemm_epilogue). `joined`: B is a * head of E4M3 / int8 codes and a scale plane, each element decoded to code * scale in f32 first * (gemm_scaled_rows). */ int gemm_plain(const RadArgs* a, RadStream st, const char* nkey, const char* kkey, const char* op, bool bias_form = false, bool joined = false) { const int nt = bias_form ? 5 : 3; if (!a || a->n_t < nt || !a->t[0].data || !a->t[1].data || !a->t[nt - 1].data) return RAD_E_INVAL; const RadTensor *A = &a->t[0], *B = &a->t[1], *Y = &a->t[nt - 1]; const RadTensor* bias = bias_form ? rad_arg_in(a, 2) : nullptr; const RadTensor* res = bias_form ? rad_arg_in(a, 3) : nullptr; int act = 0; if (bias_form) { const char* as = rad_args_gets_or(a, "act", "none"); if (!std::strcmp(as, "none")) act = 0; else if (!std::strcmp(as, "gelu")) act = 1; else if (!std::strcmp(as, "gelu_tanh")) act = 2; else return RAD_E_INVAL; } const int64_t K = rad_args_geti_or(a, kkey, B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = rad_args_geti_or(a, nkey, B->rank >= 2 ? B->shape[B->rank - 2] : 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = rad_tensor_numel(Y) / N; if (M <= 0) return RAD_E_SHAPE; if (!is_float(A->dtype) || (!joined && !is_float(B->dtype))) return refuse("%s: dtype pair %u x %u is not served (a quantised weight is gemm_nt_q's)", op, A->dtype, B->dtype); if (rad_tensor_numel(A) < M * K || (!joined && rad_tensor_numel(B) < N * K)) return RAD_E_SHAPE; if (bias && rad_tensor_numel(bias) < N) return RAD_E_SHAPE; if (res && rad_tensor_numel(res) < M * N) return RAD_E_SHAPE; const int64_t ars = row_stride(A, K), acs = A->rank >= 2 ? A->stride[A->rank - 1] : 1; const int64_t brs = joined ? 0 : row_stride(B, K), bcs = !joined && B->rank >= 2 ? B->stride[B->rank - 1] : 1; const int64_t yrs = row_stride(Y, N), ycs = Y->rank >= 2 ? Y->stride[Y->rank - 1] : 1; const int64_t rrs = res ? row_stride(res, N) : 0, rcs = res && res->rank >= 2 ? res->stride[res->rank - 1] : 1; const int64_t bis = bias && bias->rank ? bias->stride[bias->rank - 1] : 1; if (res && res->data != Y->data) { /* libref snapshots an overlapping residual; here an element reads its residual before its * store, which is the same only when the residual is Y itself or apart from it. */ const char *rl = (const char*)res->data, *yl = (const char*)Y->data; const int64_t span = (M - 1) * std::max(yrs, rrs) + N * std::max(ycs, rcs); const int64_t eb = 4; if (rl < yl + span * eb && yl < rl + span * eb && (rrs != yrs || rcs != ycs || res->dtype != Y->dtype)) return refuse("%s: a residual overlapping y in another layout", op); } const char *ab = (const char*)A->data, *bb = (const char*)B->data; const char* bsb = bias ? (const char*)bias->data : nullptr; const char* rb = res ? (const char*)res->data : nullptr; char* yb = (char*)Y->data; const uint32_t adt = A->dtype, bdt = B->dtype, ydt = Y->dtype; const uint32_t bidt = bias ? bias->dtype : 0, rdt = res ? res->dtype : 0; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const size_t wn = 64; const size_t nn = (size_t)((N + (int64_t)wn - 1) / (int64_t)wn) * wn; return submit([&] { syclex::nd_launch(*q, sycl::nd_range<2>{{(size_t)M, nn}, {1, wn}}, [=](sycl::nd_item<2> it) { const int64_t m = (int64_t)it.get_global_id(0), n = (int64_t)it.get_global_id(1); if (n >= N) return; float acc = 0.0f; if (joined) { const HPlane cp = hplane(bb, "codes"), sp = hplane(bb, "scale"); if (!cp.p || !sp.p) return; /* the layout hook guarantees a joined head */ for (int64_t k = 0; k < K; ++k) acc += rad_load_f32(ab, adt, m * ars + k * acs) * (cp.at(n, k) * sp.cover(n, k)); } else { for (int64_t k = 0; k < K; ++k) acc += rad_load_f32(ab, adt, m * ars + k * acs) * rad_load_f32(bb, bdt, n * brs + k * bcs); } const int64_t o = m * yrs + n * ycs; const float rv = rb ? rad_load_f32(rb, rdt, m * rrs + n * rcs) : 0.0f; float v = acc; if (bsb) v += rad_load_f32(bsb, bidt, n * bis); rad_store_f32(yb, ydt, o, v); if (act || rb) { if (act == 1) rad_store_f32(yb, ydt, o, gelu(rad_load_f32(yb, ydt, o))); else if (act == 2) rad_store_f32(yb, ydt, o, gelu_tanh(rad_load_f32(yb, ydt, o))); if (rb) rad_store_f32(yb, ydt, o, rv + rad_load_f32(yb, ydt, o)); } }); }); } } // namespace int gemm_nt(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "N", "K", "gemm_nt"); } int gemm_nt_bias(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "N", "K", "gemm_nt_bias", true); } int logits_gemm(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "n_vocab", "n_embd", "logits_gemm"); } int logits_gemm_head(const RadArgs* a, RadStream s) { return gemm_plain(a, s, "n_vocab", "n_embd", "logits_gemm", false, true); } /* libref's ref_layout_head: operand 1 (the head) of codes and one scale, joined. */ int head_layout(const RadParam*, int, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n, RadLayout* out) { if (n < 2 || operand != 1) return RAD_E_UNSUPPORTED; if (!rad_enc_is(enc, "affine") || enc->transform[0] || enc->n_planes != 2) return RAD_E_DTYPE; if (!sel || n != 2 || sel[0] < 0 || sel[0] >= enc->n_planes || sel[1] < 0 || sel[1] >= enc->n_planes) return RAD_E_DTYPE; const RadEncPlane& c = enc->plane[sel[0]]; const RadEncPlane& sc = enc->plane[sel[1]]; if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || std::strncmp(sc.role, "scale", RAD_ENC_STR) != 0) return RAD_E_DTYPE; const bool fs = sc.dtype == RAD_F32 || sc.dtype == RAD_F16 || sc.dtype == RAD_BF16; if (!(c.kind == RAD_PLANE_TILED && c.block[0] == 1 && c.block[1] == 1 && (c.dtype == RAD_F8E4M3 || c.dtype == RAD_I8) && sc.kind == RAD_PLANE_TILED && fs)) return RAD_E_DTYPE; return rad_planes_layout(enc, sel, planes, n, out); } int head_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 = head_layout(p, n_p, operand, enc, sel, planes, n, &lay); if (st != RAD_OK) return st; return rad_planes_relayout(enc, sel, planes, n, dst, dst_bytes); } int head_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 = head_layout(p, n_p, operand, enc, sel, planes, n, &lay); if (st != RAD_OK) return st; return rad_planes_unrelayout(enc, sel, src, src_bytes, planes, n); } } // namespace xe2