/* xe2_gemm_zp.cpp -- gemm_nt_q over the zero-point grids whose activation is quant_act_i8's * (w2a8, w4a8_asym): the DSpark drafter's 2-bit vocabulary head. Correctness first: libref's * gemm_zp (ref_gemm.cpp) per output -- * * per group g of K: is = sum over ascending k of a[k] * code[n][k] (exact integers) * sub = (float)is - (float)zero[n][g] * a_sum[g][m] * acc = acc + (sub * a_scale[m]) * scale[n][g] * * -- with `a` read back from quant_act_i8's step order into column order, as libref does. * * `b_scale` reaches the kernel in libref's joined form (abi/rad_planes.h): a header, an entry per * plane, then the "scale" and "zero" planes. The layout hook below is libref's * (ref_layout_gemm_q), so both libraries ask for the same stored bytes and the builder can resolve * either for a band. The header lives in device memory, so the kernel finds its planes itself: a * launch must not read device memory from the host. */ #include "xe2_common.h" #include "xe2_ops.h" #include "rad_planes.h" #include #include namespace xe2 { namespace { struct ZpGrid { const char* name; uint32_t codes; bool i8_row; /* the activation is quant_act_i8's (served here) */ }; const ZpGrid* zp_grid(const char* dtype) { static const ZpGrid kGrids[] = { { "w2a8", RAD_U2, true }, { "w4a8_asym", RAD_U4, true }, { "w4a16_asym", RAD_U4, false }, { "w5a16", RAD_U5, false }, { "w4a8i8_asym", RAD_U4, false }, { "w5a8i8", RAD_U5, false }, }; if (!dtype) return nullptr; for (const ZpGrid& g : kGrids) if (std::strcmp(g.name, dtype) == 0) return &g; return nullptr; } bool zero_dt(uint32_t dt) { return dt == RAD_U8 || dt == RAD_U2 || dt == RAD_U4 || dt == RAD_U5; } 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; } /* One plane of the joined operand, found on the device. */ struct DPlane { const char* p = nullptr; uint32_t dt = 0; int64_t row_bytes = 0; float at(int64_t i, int64_t j) const { return rad_load_f32(p + i * row_bytes, dt, j); } }; inline bool role_is(const char* role, const char* want) { for (int i = 0; i < RAD_ENC_STR; ++i) { if (role[i] != want[i]) return false; if (!want[i]) return true; } return true; } inline DPlane find_plane(const char* base, const char* role) { DPlane 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; return v; } return v; } 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]; } } // namespace /* ------------------------------------------------------------------ the layout hooks */ /* libref's ref_layout_gemm_q, line for line: `b_scale` (operand 3) joined as "scale" and "zero", * one each per (row, `group` of K), over codes of the grid's width. */ int gemm_zp_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel, const RadTensor* planes, int n, RadLayout* out) { if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED; const ZpGrid* zg = zp_grid(rad_param_gets(p, n_p, "dtype", nullptr)); const long long group = rad_param_geti(p, n_p, "group", 0); if (!zg || group <= 0 || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return RAD_E_DTYPE; if (!sel_roles(enc, sel, n, "scale", "zero") || enc->n_planes < 3) return RAD_E_DTYPE; const RadEncPlane& c = enc->plane[0]; const RadEncPlane& s = enc->plane[sel[0]]; const RadEncPlane& z = enc->plane[sel[1]]; if (std::strncmp(c.role, "codes", RAD_ENC_STR) != 0 || c.dtype != zg->codes || c.block[0] != 1 || c.block[1] != 1) return RAD_E_DTYPE; if (s.kind != RAD_PLANE_TILED || s.dtype != RAD_F16 || s.block[0] != 1 || s.block[1] != group || z.kind != RAD_PLANE_TILED || !zero_dt(z.dtype) || z.block[0] != 1 || z.block[1] != group) return RAD_E_DTYPE; return rad_planes_layout(enc, sel, planes, n, out); } int gemm_zp_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_zp_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 gemm_zp_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_zp_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); } /* ------------------------------------------------------------------ the launch */ int gemm_nt_q_zp(const RadArgs* a, RadStream st) { if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) 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); const RadTensor* BS = rad_arg_in(a, 3); const RadTensor* ASUM = rad_arg_in(a, 5); if (rad_arg_in(a, 6)) return refuse("gemm_nt_q (zero-point): b_ref is mxfp4's"); const ZpGrid* zg = zp_grid(rad_args_gets_or(a, "dtype", nullptr)); if (!zg || !zg->i8_row) return refuse("gemm_nt_q (zero-point): dtype '%s' is not served (w2a8, w4a8_asym are)", rad_args_gets_or(a, "dtype", "")); if (rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0) return RAD_E_UNSUPPORTED; const int64_t K = rad_args_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); const int64_t group = rad_args_geti_or(a, "group", 0); if (K <= 0 || N <= 0) return RAD_E_SHAPE; const int64_t M = rad_tensor_numel(Y) / N; if (M <= 0 || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE; if (!BS) return RAD_E_INVAL; if (B->dtype != zg->codes) return RAD_E_DTYPE; if (group <= 0 || K % group || K % 16) return RAD_E_SHAPE; if (!rad_tensor_is_contiguous(B)) return RAD_E_STRIDE; if (A->dtype != RAD_I8) return RAD_E_DTYPE; if (A->rank && A->stride[A->rank - 1] != 1) return RAD_E_STRIDE; const int64_t G = K / group, mpad = (M + 15) / 16 * 16; if (!AS || rad_tensor_numel(AS) < M) return RAD_E_INVAL; if (!ASUM || rad_tensor_numel(ASUM) < G * mpad) return RAD_E_INVAL; const int64_t brow = rad_dtype_bytes(B->dtype, K); const int cbits = rad_dtype_bits(B->dtype); const int64_t ars = row_stride(A, K); const int64_t sa_rs = row_stride(AS, 1); const int64_t asum_s = ASUM->rank ? ASUM->stride[ASUM->rank - 1] : 1; const int64_t ys_r = row_stride(Y, N), ys_c = Y->rank ? Y->stride[Y->rank - 1] : 1; const char *ab = (const char*)A->data, *bb = (const char*)B->data, *bsb = (const char*)BS->data; const char *sab = (const char*)AS->data, *sumb = (const char*)ASUM->data; const uint32_t sadt = AS->dtype, sumdt = ASUM->dtype, ydt = Y->dtype; char* yb = (char*)Y->data; 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; const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero"); if (!sc.p || !zp.p) return; /* not a joined b_scale: the layout hook guarantees one */ const uint8_t* crow = (const uint8_t*)bb + n * brow; const int8_t* ar = (const int8_t*)ab + m * ars; const float sa = rad_load_f32(sab, sadt, m * sa_rs); float acc = 0.0f; for (int64_t g = 0; g < G; ++g) { const float sb = sc.at(n, g); const int32_t z = (int32_t)zp.at(n, g); int64_t is = 0; for (int64_t k = g * group; k < (g + 1) * group; ++k) { const int64_t pos = (k & ~(int64_t)12) | ((k & 4) << 1) | ((k & 8) >> 1); is += (int64_t)ar[pos] * (int32_t)rad_load_bits(crow, cbits, k); } const float sub = (float)is - (float)z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s); acc += sub * sa * sb; } rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc); }); }); } } // namespace xe2 /* ------------------------------------------------------------------ the fast form */ /* The same products and order, spread: a 16-lane sub-group an output column, lane l the groups * l, l + 16, ... Within a group the sum of a * code is an exact integer (|a| <= 127, code <= 15, * a group of <= 512: under 2^24), formed in f32 in any order; each group's term * ((is - zero * a_sum) * a_scale) * scale is libref's; and the terms are added in group order by * every lane from the lanes' registers (select_from_group), libref's chain. So the result is * libref's bit for bit, at the cost of a read of the weight rather than one per output row. For * the DFlash2 drafter's 2-bit head: N = 248320, 252 ms a call in the per-output form. */ namespace xe2 { namespace { constexpr int kZpMaxM = 16; constexpr int kZpMaxPer = 4; /* groups a lane: G <= 64 */ template int zp_gemv(sycl::queue& q, const int8_t* ab, int64_t ars, const char* sab, uint32_t sadt, int64_t sa_rs, const char* sumb, uint32_t sumdt, int64_t asum_s, int64_t mpad, const uint8_t* bb, int64_t brow, int cbits, const char* bsb, char* yb, uint32_t ydt, int64_t ys_r, int64_t ys_c, int64_t N, int64_t K, int64_t group, int mm) { const int64_t G = K / group; const size_t groups = (size_t)((N + 15) / 16); return submit([&] { syclex::nd_launch(q, sycl::nd_range<1>{groups * 256, 256}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { const sycl::sub_group sg = it.get_sub_group(); const int64_t n = (int64_t)it.get_group(0) * 16 + (int64_t)sg.get_group_linear_id(); if (n >= N) return; const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero"); if (!sc.p || !zp.p) return; const int lane = (int)sg.get_local_linear_id(); const uint8_t* crow = bb + n * brow; float term[MM][kZpMaxPer]; for (int m = 0; m < MM; ++m) for (int i = 0; i < kZpMaxPer; ++i) term[m][i] = 0.0f; for (int i = 0; i < kZpMaxPer; ++i) { const int64_t g = lane + (int64_t)i * kSub; if (g >= G) break; float is[MM]; for (int m = 0; m < MM; ++m) is[m] = 0.0f; for (int64_t k0 = g * group; k0 < (g + 1) * group; k0 += 16) { float cf[16]; for (int j = 0; j < 16; ++j) cf[j] = (float)rad_load_bits(crow, cbits, k0 + j); for (int m = 0; m < MM; ++m) { if (m >= mm) break; /* the step order: logical column j of the step sits at byte * (j & ~12) | ((j & 4) << 1) | ((j & 8) >> 1) */ const sycl::vec av = *(const sycl::vec*)(ab + m * ars + k0); float p = 0.0f; for (int j = 0; j < 16; ++j) { const int pos = (j & ~12) | ((j & 4) << 1) | ((j & 8) >> 1); p += (float)av[pos] * cf[j]; } is[m] += p; } } const float sb = sc.at(n, g); const float z = (float)(int32_t)zp.at(n, g); for (int m = 0; m < MM; ++m) { if (m >= mm) break; const float sa = rad_load_f32(sab, sadt, m * sa_rs); const float sub = is[m] - z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s); term[m][i] = sub * sa * sb; } } for (int m = 0; m < MM; ++m) { if (m >= mm) break; float acc = 0.0f; for (int i = 0; i < kZpMaxPer; ++i) for (int l = 0; l < kSub; ++l) { const int64_t g = (int64_t)i * kSub + l; if (g < G) acc += sycl::select_from_group(sg, term[m][i], l); } if (lane == 0) rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc); } }); }); } /* The same group terms with the integer sums on XMX: an int8 DPAS (8 x 32 by 32 x 16) forms each * group's sum of a * code exactly in int32 for up to 8 rows and 16 columns at once. The codes * unpack straight into the packed B operand: four codes along k are one dword, and the step * order's swap of bits 2 and 3 of k moves whole dwords, so the activation is used as stored. * A sub-group owns 16 columns and walks the groups in order, each lane adding its column's terms * as the per-output form does -- libref's chain, at one read of the weight. */ constexpr int kZpDpasSgs = 16; template inline uint32_t zp_dword(const uint8_t* crow, int64_t d) { /* the 4 codes of logical dword d */ if constexpr (CBITS == 2) { const uint32_t b = crow[d]; return (b & 3u) | ((b >> 2) & 3u) << 8 | ((b >> 4) & 3u) << 16 | ((b >> 6) & 3u) << 24; } else { const uint32_t h = (uint32_t)crow[2 * d] | (uint32_t)crow[2 * d + 1] << 8; return (h & 15u) | ((h >> 4) & 15u) << 8 | ((h >> 8) & 15u) << 16 | ((h >> 12) & 15u) << 24; } } template int zp_dpas(sycl::queue& q, const int8_t* ab, int64_t ars, const char* sab, uint32_t sadt, int64_t sa_rs, const char* sumb, uint32_t sumdt, int64_t asum_s, int64_t mpad, const uint8_t* bb, int64_t brow, const char* bsb, char* yb, uint32_t ydt, int64_t ys_r, int64_t ys_c, int64_t N, int64_t K, int64_t group, int mm) { namespace jm = sycl::ext::oneapi::experimental::matrix; const int64_t G = K / group; const size_t wgs = (size_t)((N + 16 * kZpDpasSgs - 1) / (16 * kZpDpasSgs)); return submit([&] { q.submit([&](sycl::handler& h) { sycl::local_accessor As(sycl::range<1>((size_t)(8 * K)), h); sycl::local_accessor Bs(sycl::range<1>((size_t)kZpDpasSgs * 8 * 16), h); sycl::local_accessor Cs(sycl::range<1>((size_t)kZpDpasSgs * 8 * 16), h); h.parallel_for(sycl::nd_range<1>{wgs * kZpDpasSgs * kSub, (size_t)kZpDpasSgs * kSub}, [=](sycl::nd_item<1> it) [[sycl::reqd_sub_group_size(kSub)]] { 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 int t = (int)it.get_local_id(0); for (int64_t i = t; i < 2 * K; i += kZpDpasSgs * kSub) { /* 8 rows, 4 bytes at a time */ const int64_t m = i / (K / 4), c = (i % (K / 4)) * 4; uint32_t v = 0u; if (m < mm) v = *(const uint32_t*)(ab + m * ars + c); *(uint32_t*)&As[m * K + c] = v; } sycl::group_barrier(it.get_group()); const int64_t n0 = ((int64_t)it.get_group(0) * kZpDpasSgs + s) * 16; if (n0 >= N) return; const DPlane sc = find_plane(bsb, "scale"), zp = find_plane(bsb, "zero"); if (!sc.p || !zp.p) return; const int64_t n = n0 + lane; const bool live = n < N; const uint8_t* crow = bb + (live ? n : n0) * brow; float sa[8], acc[8]; for (int m = 0; m < 8; ++m) { sa[m] = m < mm ? rad_load_f32(sab, sadt, m * sa_rs) : 0.0f; acc[m] = 0.0f; } uint32_t* bt = &Bs[s * 8 * 16]; int32_t* ct = &Cs[s * 8 * 16]; auto lb = sycl::address_space_cast((int8_t*)bt); auto lc = sycl::address_space_cast(ct); jm::joint_matrix ma; jm::joint_matrix mb; jm::joint_matrix mc; for (int64_t g = 0; g < G; ++g) { jm::joint_matrix_fill(sg, mc, 0); for (int64_t k0 = g * group; k0 < (g + 1) * group; k0 += 32) { /* stored dword r of this step holds logical dword (r & ~3) | swap(r & 3) */ for (int r = 0; r < 8; ++r) { const int ld = (r & ~3) | ((r & 1) << 1) | ((r & 2) >> 1); bt[r * 16 + lane] = zp_dword(crow, k0 / 4 + ld); } sycl::group_barrier(sg); auto la = sycl::address_space_cast(&As[k0]); jm::joint_matrix_load(sg, ma, la, (size_t)K); jm::joint_matrix_load(sg, mb, lb, 64); jm::joint_matrix_mad(sg, mc, ma, mb, mc); sycl::group_barrier(sg); } jm::joint_matrix_store(sg, mc, lc, 16, jm::layout::row_major); sycl::group_barrier(sg); if (live) { const float sb = sc.at(n, g); const float z = (float)(int32_t)zp.at(n, g); for (int m = 0; m < 8; ++m) { if (m >= mm) break; const float sub = (float)ct[m * 16 + lane] - z * rad_load_f32(sumb, sumdt, (g * mpad + m) * asum_s); const float term = sub * sa[m] * sb; acc[m] += term; } } sycl::group_barrier(sg); } if (live) for (int m = 0; m < 8; ++m) { if (m >= mm) break; rad_store_f32(yb, ydt, m * ys_r + n * ys_c, acc[m]); } }); }); }); } } // namespace int gemm_nt_q_zp_gemv(const RadArgs* a, RadStream st) { if (exact_only()) return gemm_nt_q_zp(a, st); if (!a || a->n_t < 5 || !a->t[0].data || !a->t[2].data || !a->t[4].data) 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); const RadTensor* BS = rad_arg_in(a, 3); const RadTensor* ASUM = rad_arg_in(a, 5); const ZpGrid* zg = zp_grid(rad_args_gets_or(a, "dtype", nullptr)); if (!zg || !zg->i8_row || rad_arg_in(a, 6) || rad_args_geti_or(a, "pb1", 0) > 0 || rad_args_geti_or(a, "pb2", 0) > 0) return gemm_nt_q_zp(a, st); const int64_t K = rad_args_geti_or(a, "K", B->rank >= 2 ? B->shape[B->rank - 1] : 0); const int64_t N = rad_args_geti_or(a, "N", B->rank >= 2 ? B->shape[B->rank - 2] : 0); const int64_t group = rad_args_geti_or(a, "group", 0); if (K <= 0 || N <= 0 || group <= 0 || group % 16 || group > 512 || K % group) return gemm_nt_q_zp(a, st); const int64_t M = rad_tensor_numel(Y) / N, G = K / group; if (M < 1 || M > kZpMaxM || G > kZpMaxPer * kSub || !BS || !AS || !ASUM || A->dtype != RAD_I8 || B->dtype != zg->codes || !rad_tensor_is_contiguous(B) || (A->rank && A->stride[A->rank - 1] != 1)) return gemm_nt_q_zp(a, st); const int64_t ars = row_stride(A, K); if (ars % 16 || !rad_ptr_aligned(A->data, 16)) return gemm_nt_q_zp(a, st); const int64_t mpad = (M + 15) / 16 * 16; if (rad_tensor_numel(AS) < M || rad_tensor_numel(ASUM) < G * mpad || rad_tensor_numel(A) < M * K || rad_tensor_numel(B) < N * K) return RAD_E_SHAPE; sycl::queue* q = queue_of(st); if (!q) return RAD_E_DEVICE; const int64_t brow = rad_dtype_bytes(B->dtype, K); const int cbits = rad_dtype_bits(B->dtype); const int64_t sa_rs = row_stride(AS, 1); const int64_t asum_s = ASUM->rank ? ASUM->stride[ASUM->rank - 1] : 1; const int64_t ys_r = row_stride(Y, N), ys_c = Y->rank ? Y->stride[Y->rank - 1] : 1; if (M <= 8 && (cbits == 2 || cbits == 4) && group % 32 == 0 && K * 8 <= 64 * 1024 && ars % 4 == 0 && !std::getenv("XE2_ZP_GEMV")) { auto dp = cbits == 2 ? zp_dpas<2> : zp_dpas<4>; int rc = dp(*q, (const int8_t*)A->data, ars, (const char*)AS->data, AS->dtype, sa_rs, (const char*)ASUM->data, ASUM->dtype, asum_s, mpad, (const uint8_t*)B->data, brow, (const char*)BS->data, (char*)Y->data, Y->dtype, ys_r, ys_c, N, K, group, (int)M); return rc; } auto go = [&](auto tag) { constexpr int MM = decltype(tag)::value; return zp_gemv(*q, (const int8_t*)A->data, ars, (const char*)AS->data, AS->dtype, sa_rs, (const char*)ASUM->data, ASUM->dtype, asum_s, mpad, (const uint8_t*)B->data, brow, cbits, (const char*)BS->data, (char*)Y->data, Y->dtype, ys_r, ys_c, N, K, group, (int)M); }; if (M == 1) return go(std::integral_constant{}); if (M <= 8) return go(std::integral_constant{}); return go(std::integral_constant{}); } } // namespace xe2