Archived
M2XFP4 (MXFP4v2): quantiser, gfx1201 WMMA kernels, host rows, df2 wiring, .rad packer (Import::ParoM2), stability fixes (counters-in-scratch x3, aql publish fences), kbench rows, runbook (REMAINING.md)
This commit is contained in:
1 parent
9eaf10da6e
commit
ea0908596b
60 files changed
+4619
-193
No files matched your search
@@ -148,6 +148,10 @@ set(R4D_UNITS
|
||||
"r4d_gemm_mxfp4a8_nt_m64|"
|
||||
"r4d_gemm_mxfp4a8_tiled|"
|
||||
"r4d_gemm_mxfp4a8_decode|"
|
||||
# M2XFP4 (arXiv 2601.19213 §4.4.2): the decode and tiled rows at the m2xfp4 encoding, one meta
|
||||
# plane more. Same bands and fold as the OCP rows; the meta multipliers ride r4d_m2xfp4.h's table.
|
||||
"r4d_gemm_m2xfp4a8_tiled|"
|
||||
"r4d_gemm_m2xfp4a8_decode|"
|
||||
# Block-scaled FP8 (the format Qwen3.8-27B-FP8 ships in). The 128x128 block is fixed by the
|
||||
# checkpoint, and the entry points reject a mismatch.
|
||||
"r4d_gemm_fp8a16_nt_m1|"
|
||||
|
||||
+26
-2
@@ -598,6 +598,30 @@ int r4d_gemm_mxfp4a8_tiled_group(void);
|
||||
// scratch, which only the plugin ABI provides.
|
||||
int r4d_gemm_mxfp4a8_decode_max_m(void);
|
||||
|
||||
// M2XFP4 weight, fp8 activation: the MXFP4 rows at the paper's weight-side Sg-EM (arXiv 2601.19213
|
||||
// §4.4.2). Beside each E8M0 exponent per 32 K (whose adaptive bias the quantiser already folded
|
||||
// in) the weight carries one meta byte per (row, 32 of K): four two-bit subgroup multipliers, the
|
||||
// subgroup s covering columns [8s, 8s+8) of the group, value k_s in 0..3. The exact weight is
|
||||
// e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds it into the same e4m3
|
||||
// staging bytes through a second table index, so the fold, the Wref epilogue and the activation
|
||||
// scale grids are the MXFP4 kernels'. `wm` is the [K/32][N] meta plane, `ldws` its row pitch (0 =
|
||||
// N); the k=3 multipliers on odd-mantissa codes round as r4d_m2xfp4.h documents, <= 2^-4 relative.
|
||||
void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref, long c,
|
||||
int M, int K, int N, int TN, int as_group, int as_rs, long stream,
|
||||
int ldws = 0, int ldc = 0);
|
||||
void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda = 0);
|
||||
long r4d_m2xfp4a8_tile_a_bytes(int M, int K);
|
||||
int r4d_gemm_m2xfp4a8_tiled_group(void);
|
||||
// The decode band (M <= 128) is r4d_rad_gemm_m2xfp4a8_decode only, as for mxfp4a8: the split
|
||||
// partial and the arrival counters are the plugin ABI's. The raw entry takes the scratch that
|
||||
// carries both: the fp32 split partial with the counters in its tail (m2d_partial_bytes; null
|
||||
// runs unsplit only at KS 1).
|
||||
void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref, long c,
|
||||
int M, int K, int N, int KS, int BK, int NT, int as_group,
|
||||
int as_rs, long scratch, long scratch_bytes, long stream,
|
||||
int lda = 0, int ldws = 0, int ldc = 0);
|
||||
int r4d_gemm_m2xfp4a8_decode_max_m(void);
|
||||
|
||||
// ---- Block-scaled FP8, as checkpoints ship it -------------------------------------------------
|
||||
//
|
||||
// Reads the weight as safetensors stores it: `<linear>.weight` F8_E4M3 row-major [N][K] and
|
||||
@@ -633,8 +657,8 @@ int r4d_gemm_fp8a16_nt_m1_block(void);
|
||||
int r4d_gemm_fp8a16_nt_m1_max_m(void);
|
||||
|
||||
// `a` is E4M3 [M][K] with `ascale` f32 [M][ceil(K/128)], r4d_quant_act_fp8's output. `scratch` is
|
||||
// the split-K partial plane; 0 runs the launch unsplit (correct, slower). Size it with the query,
|
||||
// which returns 0 when this shape will not split.
|
||||
// the split-K partial planes with the finisher's arrival counters in the tail; 0 runs the launch
|
||||
// unsplit (correct, slower). Size it with the query, which always includes the counters.
|
||||
//
|
||||
// Split-K is not bit-comparable across settings: ksplit repartitions K, so the accumulation order
|
||||
// differs. Two runs of the same binary still agree.
|
||||
|
||||
+46
-6
@@ -257,7 +257,10 @@ enum {
|
||||
/* The same GEMM's 5-bit expert weight: per row, R4D_DT_MOEW4's nibble plane of the codes' low
|
||||
* four bits (the magnitude), then the sign bits, one dword per 32 elements in the order the
|
||||
* kernel merges them (r4d_layout.cpp, moew5_row). A row is 5K/8 bytes. */
|
||||
R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8
|
||||
R4D_DT_MOEW5 = RAD_DT_PLUGIN_BASE + 8,
|
||||
/* The M2XFP4 GEMMs' stored weight: R4D_DT_MXFP4_FRAG's fragment-order e2m1 codes, then the
|
||||
* [K/32][N] meta plane the kernel reads beside the E8M0 exponents (r4d_layout.cpp, m2xfp4). */
|
||||
R4D_DT_M2XFP4_FRAG = RAD_DT_PLUGIN_BASE + 9
|
||||
};
|
||||
|
||||
/* The grouped MoE GEMM's code tables, as the four dwords w4_e4m3's byte permutes read
|
||||
@@ -343,18 +346,55 @@ struct R4dMvCfg { int rb; };
|
||||
|
||||
|
||||
|
||||
/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from
|
||||
* M >= 2048), which needs M. */
|
||||
static const int64_t kMxTn[] = { 0, 2, 4 };
|
||||
static const RadTunable tGemmMxfp4Tiled[] = {
|
||||
{ "tn", kMxTn, (int)(sizeof kMxTn / sizeof kMxTn[0]), 0,
|
||||
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
|
||||
};
|
||||
|
||||
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
|
||||
* `nt` 1 streams the weight past the caches, 2 loads it plainly. The M2XFP4 rows declare the same
|
||||
* axes (r4d_rows.cpp) and resolve them through the same readers below, which sit in this header so
|
||||
* a kernel unit links without the declaration side -- the r4d_emu build compiles the units alone. */
|
||||
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
|
||||
static const int64_t kMxDecBk[] = { 0, 64, 128 };
|
||||
static const int64_t kMxDecNt[] = { 0, 1, 2 };
|
||||
static const RadTunable tGemmMxfp4Decode[] = {
|
||||
{ "ks", kMxDecKs, (int)(sizeof kMxDecKs / sizeof kMxDecKs[0]), 0, "split-K workgroups a column block. 0 = the fill rule" },
|
||||
{ "bk", kMxDecBk, (int)(sizeof kMxDecBk / sizeof kMxDecBk[0]), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
|
||||
{ "nt", kMxDecNt, (int)(sizeof kMxDecNt / sizeof kMxDecNt[0]), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
|
||||
};
|
||||
|
||||
/* The tuned configuration (r4d_rows.cpp's TUNE), inline so the kernel units carry it: the core
|
||||
* appends the row's tuned point to RadArgs::p; a key absent falls to the axis default above. */
|
||||
static inline int64_t r4d_tune_i(const RadArgs* a, const RadTunable* tab, int n, const char* key) {
|
||||
long long v = 0;
|
||||
if (rad_args_geti(a, key, &v)) return v;
|
||||
for (int i = 0; i < n; ++i)
|
||||
if (!std::strcmp(tab[i].key, key)) return tab[i].deflt;
|
||||
return 0;
|
||||
}
|
||||
|
||||
extern "C" {
|
||||
/* -- the tuned configuration (r4d_rows.cpp) --
|
||||
*
|
||||
* The core picked a point in the space the row declared and appended it to RadArgs::p. These read
|
||||
* it back, falling to the axis's default (defined once, in the RadTunable table) when a caller
|
||||
* supplied none, so a checker with no tuned key runs what an untuned install runs. They cannot
|
||||
* fail: the loader refuses a plugin whose default is not one of the axis's values. */
|
||||
* it back, falling to the axis's default (defined once, above) when a caller supplied none, so a
|
||||
* checker with no tuned key runs what an untuned install runs. They cannot fail: the loader
|
||||
* refuses a plugin whose default is not one of the axis's values. */
|
||||
void r4d_cfg_gemm (const RadArgs*, struct R4dGemmCfg*);
|
||||
void r4d_cfg_tiled (const RadArgs*, struct R4dTileCfg*);
|
||||
void r4d_cfg_prefill(const RadArgs*, struct R4dTileCfg*);
|
||||
void r4d_cfg_mxfp4_tiled(const RadArgs*, struct R4dMxTileCfg*);
|
||||
void r4d_cfg_mxfp4_decode(const RadArgs*, struct R4dMxDecCfg*);
|
||||
inline void r4d_cfg_mxfp4_tiled(const RadArgs* a, struct R4dMxTileCfg* out) {
|
||||
out->tn = (int)r4d_tune_i(a, tGemmMxfp4Tiled, (int)(sizeof tGemmMxfp4Tiled / sizeof tGemmMxfp4Tiled[0]), "tn");
|
||||
}
|
||||
inline void r4d_cfg_mxfp4_decode(const RadArgs* a, struct R4dMxDecCfg* out) {
|
||||
out->ks = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "ks");
|
||||
out->bk = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "bk");
|
||||
out->nt = (int)r4d_tune_i(a, tGemmMxfp4Decode, (int)(sizeof tGemmMxfp4Decode / sizeof tGemmMxfp4Decode[0]), "nt");
|
||||
}
|
||||
void r4d_cfg_split (const RadArgs*, struct R4dSplitCfg*);
|
||||
void r4d_cfg_ar (const RadArgs*, struct R4dArCfg*);
|
||||
/* Whether the four-rank fused junction takes its tail form from 5 rows (the row's `tail` axis). */
|
||||
|
||||
+32
-41
@@ -15,7 +15,8 @@
|
||||
// 2. The weight is the WMMA A operand on both tiles, so D is C^T of `C[M,N] = A[M,K] @ W[N,K]^T`
|
||||
// and a lane's eight accumulator slots are eight weight rows of one activation row.
|
||||
// 3. Split-K uses the caller's scratch (nothing on a launch path allocates), sized by
|
||||
// r4d_gemm_fp8a8_nt_m16_scratch(). The summation order is fixed.
|
||||
// r4d_gemm_fp8a8_nt_m16_scratch(): the split partial planes with the finisher's arrival
|
||||
// counters in the tail. The summation order is fixed.
|
||||
// 4. C is bf16, like every GEMM in this library.
|
||||
//
|
||||
// Load-bearing: the padded LDS row pitch (r4d_fp8_wmma.h `lds_pitch`), the one-K-tile-ahead
|
||||
@@ -35,7 +36,6 @@
|
||||
#include <atomic>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <type_traits>
|
||||
|
||||
@@ -560,9 +560,9 @@ __device__ __forceinline__ void gemm_fp8a8_body(
|
||||
// The z loop runs in fixed ascending order with no atomic on an accumulator, so the result is
|
||||
// bit-identical to the separate reduce and deterministic.
|
||||
//
|
||||
// The counters are a small allocation keyed on (stream, output) (`split_ctr`), not the caller's
|
||||
// scratch, which other ops overwrite. The self-reset keeps them zero, which is sound only while
|
||||
// launches sharing a counter block never overlap; see split_ctr.
|
||||
// The counters are the caller's scratch tail past the split partials (see kMaxCtr), zeroed
|
||||
// beside each launch: the engine hands the op a scratch slice no unordered launch shares, and
|
||||
// the self-reset keeps them zero through the launch.
|
||||
if (ck && Ctr) {
|
||||
// Every thread's stores must be visible device-wide before the arrival is published: a
|
||||
// per-thread fence, then the barrier.
|
||||
@@ -844,36 +844,15 @@ void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restr
|
||||
// Double-buffering the narrow tile is ~10% slower even where it fits (MW = 2): the tile is short
|
||||
// of LDS, not waiting on the barrier.
|
||||
|
||||
// The finisher's arrival counters, one per grid.x column (see the finisher). Zeroed once and kept
|
||||
// zero by the finisher. If allocation fails, the caller falls back to the separate reduce kernel,
|
||||
// which computes the same bytes.
|
||||
// The finisher's arrival counters, one per grid.x column (see the finisher). They ride the op's
|
||||
// scratch tail past the split partials, as the mxfp4 decode's counters do (mxd_partial_bytes): the
|
||||
// scratch is a declared op buffer a recorded pass relocates with the other operands, where the
|
||||
// per-(stream, output) library allocation this replaced (`split_ctr`) was a pointer baked into
|
||||
// the recorded kernarg that a replaying pass could not relocate. Beyond kMaxCtr columns, a short
|
||||
// scratch, or a failed zero, the separate reduce kernel computes the same bytes.
|
||||
constexpr uint32_t kMaxCtr = 8192;
|
||||
|
||||
/* One counter block per (stream, output), so concurrent launches never share one (sharing would
|
||||
* mean a hang or a wrong answer). Launches overlap across streams (`rad_lane`) or on one stream
|
||||
* (rad_kernel_concurrent); overlapping launches on one stream write disjoint outputs, and launches
|
||||
* sharing an output on one stream are ordered by their dependency. A step has a few dozen distinct
|
||||
* outputs at fixed arena addresses, so this is a few dozen 32 KiB blocks, allocated once. A block
|
||||
* is never freed: a recorded pass replays the pointer. */
|
||||
unsigned int* split_ctr(RadStream s, const void* out) {
|
||||
static std::mutex m;
|
||||
static std::map<std::pair<RadStream, const void*>, unsigned int*> blocks;
|
||||
std::lock_guard<std::mutex> lk(m);
|
||||
const auto key = std::make_pair(s, out);
|
||||
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
|
||||
void* p = nullptr;
|
||||
if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
|
||||
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
|
||||
* finished when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it
|
||||
* runs on the null stream, which a non-blocking stream does not wait for, so wait here. */
|
||||
if (hipMemset(p, 0, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess ||
|
||||
hipDeviceSynchronize() != hipSuccess) {
|
||||
(void)hipFree(p);
|
||||
return nullptr;
|
||||
}
|
||||
blocks.emplace(key, (unsigned int*)p);
|
||||
return (unsigned int*)p;
|
||||
}
|
||||
|
||||
// The narrow tile's wave count MW, which is its M tile: the wave grid is MW x 1, so a block covers
|
||||
// MW*16 weight rows and the grid over N is N/(MW*16). The rule is fitted together with
|
||||
// kSplitTarget (which shapes split decides whether narrow or wide blocks win) on the shapes the
|
||||
@@ -998,9 +977,12 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) {
|
||||
g_nt_force.store(v, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
// Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split. The
|
||||
// caller may pass more, or none (the launch then runs unsplit: correct but slow, and unreported).
|
||||
// The bound is max_m() so the query and the band cannot drift apart.
|
||||
// Bytes of f32 scratch one r4d_gemm_fp8a8_nt_m16 call needs, or 0 when it will not split, plus
|
||||
// the arrival counters (kMaxCtr words) in the tail, as the mxfp4 decode's mxd_partial_bytes.
|
||||
// The caller may pass more, or none (the launch then runs unsplit: correct but slow, and
|
||||
// unreported). The bound is max_m() so the query and the band cannot drift apart. The counters
|
||||
// are reserved whether or not this bound splits: the launch decides its own split at its own M,
|
||||
// and the counters must fit the arena this query sized.
|
||||
//
|
||||
// `split_n` (0: N) is the width the split is chosen for. The split depends on N alone, and it
|
||||
// fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a
|
||||
@@ -1011,7 +993,8 @@ static long m16_scratch(int M, int K, int N, int split_n) {
|
||||
uint32_t ck = 0;
|
||||
const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K,
|
||||
(uint32_t)M, &ck);
|
||||
return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0;
|
||||
return (k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0) +
|
||||
(long)kMaxCtr * (long)sizeof(unsigned int);
|
||||
}
|
||||
extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) {
|
||||
return m16_scratch(M, K, N, 0);
|
||||
@@ -1068,10 +1051,18 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c,
|
||||
* the arrival counter, and the finisher hangs. */
|
||||
const bool full = ((uint32_t)N % fm == 0) && ((uint32_t)M % (nt * 16u) == 0) &&
|
||||
(K % (int)kBlock == 0);
|
||||
// The finisher needs one counter per column; beyond kMaxCtr or on allocation failure, the
|
||||
// separate reduce kernel computes the same bytes.
|
||||
unsigned int* const ctr =
|
||||
(ksplit > 1 && gx <= kMaxCtr) ? split_ctr(stream, (const void*)c) : nullptr;
|
||||
// The finisher's counters ride the scratch tail past the split partials and are zeroed here,
|
||||
// so every launch enters with them zero however the last launch left them or whatever else
|
||||
// wrote the arena. Beyond kMaxCtr columns, a short scratch, or a failed zero, the separate
|
||||
// reduce kernel computes the same bytes.
|
||||
unsigned int* ctr = nullptr;
|
||||
const long ctr_bytes = (long)kMaxCtr * (long)sizeof(unsigned int);
|
||||
if (ksplit > 1 && gx <= kMaxCtr && scratch && scratch_bytes >= need + ctr_bytes) {
|
||||
ctr = (unsigned int*)(scratch + need);
|
||||
if (hipMemsetAsync(ctr, 0, (size_t)gx * sizeof(unsigned int),
|
||||
(hipStream_t)stream) != hipSuccess)
|
||||
ctr = nullptr;
|
||||
}
|
||||
|
||||
#define R4D_F8D(f, mw_, nt_, fk_, i8_) \
|
||||
emit_rc = R4D_EMIT(stream, \
|
||||
|
||||
@@ -0,0 +1,651 @@
|
||||
// r4d_gemm_m2xfp4a8_decode.hip - r4d_gemm_m2xfp4a8_decode: the M2XFP4 x fp8 GEMM for the decode
|
||||
// band, M <= 128, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout,
|
||||
// fold and split of r4d_gemm_mxfp4a8_decode, and the paper's weight-side Sg-EM (arXiv 2601.19213
|
||||
// §4.4.2) on top: per group of 32 K the weight carries, beside its E8M0 exponent (whose adaptive
|
||||
// bias is already folded in), one meta byte of four two-bit subgroup multipliers k_s. The exact
|
||||
// weight is e2m1mag[c&7] * sign(c) * 2^(scale-127) * (1 + k_s/4); r4d_m2xfp4.h folds the
|
||||
// (1 + k_s/4) * 2^-d into the e4m3 byte through a second table index, so the WMMA sees the same
|
||||
// bytes it would for MXFP4 and everything downstream of the fold -- the Wref epilogue, the
|
||||
// activation scale grids, the split -- is the mxfp4 kernel's unchanged.
|
||||
//
|
||||
// The meta byte is staged beside the exponent byte: one byte per (row, 32 of K), in the scale
|
||||
// plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
|
||||
// appends it after the fragment-order codes, r4d_layout.cpp), so the staging reads it with the
|
||||
// codes' and exponents' own geometry and the weight stream grows by one byte per sixteen -- the
|
||||
// traffic the row gives up for the extra half stop of precision.
|
||||
//
|
||||
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
|
||||
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
|
||||
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). Nothing else moves: the split, slab and load
|
||||
// rule, the fused last-arriver reduction and its counters, the scratch contract and the
|
||||
// concurrency promise are the mxfp4 decode row's, with this row's own state (its counters are
|
||||
// keyed on the output, like the original's).
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_m2xfp4.h"
|
||||
|
||||
// bf16 output as uint16 pairs, the emulator-compatible spelling the MoE units use: the OCP rows
|
||||
// read __hip_bfloat16 from hip_bf16.h, which the emulator's shim does not carry, and the bytes are
|
||||
// the same -- bf16x2_rne_nan and f32_to_bf16 round as it does (r4d_common.h).
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_M2D_DWN 8 // waves per block; the N tile is DWN*16 = 128 wide
|
||||
#define R4D_M2D_MTILE 16
|
||||
#define R4D_M2D_MAX_TM 8 // M <= 128
|
||||
#define R4D_M2D_PAD 8
|
||||
#define R4D_M2D_MAX_KS 16
|
||||
#define R4D_M2D_MAX_N 36864 // the counter block's width; a 27B gate_up at TP=1 is 34816
|
||||
|
||||
typedef int m2d_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned m2d_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned m2d_u4 __attribute__((ext_vector_type(4)));
|
||||
typedef float m2d_f4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
template <bool NT, typename T>
|
||||
static __device__ __forceinline__ T m2d_ld(const T* p) {
|
||||
if constexpr (NT) return __builtin_nontemporal_load(p);
|
||||
else return *p;
|
||||
}
|
||||
|
||||
// ---- shared by both kernels: the scale grid at a 128 boundary, and the epilogue.
|
||||
//
|
||||
// The accumulator is C transposed: the WMMA takes the weight fragment as A and the activation as B
|
||||
// (same register layout), so a lane's accumulator for M fragment i holds one row, m = 16i + col,
|
||||
// and eight consecutive columns n0 + 16*wave + kb8 + e. A lane needs one activation scale per row,
|
||||
// and writes its eight outputs as one 16-byte store (one 32-byte store of partials).
|
||||
|
||||
// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a
|
||||
// boundary early and writes s_prev / s_next to LDS at the boundary (published by the staging
|
||||
// barrier). A zero next block keeps the carried scale; after a zero block the carried scale is
|
||||
// looked up from the grid.
|
||||
static __device__ __forceinline__ float m2d_ratio(float ns, float np, const float* __restrict__ row,
|
||||
int kb) {
|
||||
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
|
||||
}
|
||||
|
||||
template <int DTM>
|
||||
static __device__ __forceinline__ void m2d_rescale(v8f (&acc)[DTM], const float* sR, int col) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const float r = sR[i * 16 + col];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[i][e] *= r;
|
||||
}
|
||||
}
|
||||
|
||||
// The split's result: written to C when the accumulator covers all of K, else as an fp32 partial
|
||||
// that the last block to arrive on this column block sums. `kb_end` is the block the split's last
|
||||
// slab ends in (ABLK: the scale the accumulators are carried in).
|
||||
template <int DTM, int DKS, bool ABLK>
|
||||
static __device__ __forceinline__ void m2d_epilogue(
|
||||
const v8f (&acc)[DTM], const float* __restrict__ As, int as_rs,
|
||||
const unsigned char* __restrict__ Wref, float* __restrict__ P, unsigned* __restrict__ cnt,
|
||||
uint16_t* __restrict__ C, int M, int N, int ldc, int n0, int wave, int col, int kb8,
|
||||
int ks, int kb_end, unsigned* s_last, float* sR) {
|
||||
constexpr int NTHR = R4D_M2D_DWN * 32, BND = R4D_M2D_DWN * 16;
|
||||
constexpr int ROWS = R4D_M2D_MTILE * DTM;
|
||||
const int tid = threadIdx.x;
|
||||
const int nb = n0 + wave * 16 + kb8; // this lane's eight columns; N % 16 == 0 keeps all or none
|
||||
// Each row's final scale: the one the split's accumulators end in (ABLK), or the row's own. The
|
||||
// K loop's closing barrier retired the last ratio reads.
|
||||
if (tid < ROWS) {
|
||||
const int m = tid < M ? tid : M - 1;
|
||||
sR[tid] = ABLK ? r4d_mxfp4_carried(As + (size_t)m * as_rs, kb_end) : As[(size_t)m * as_rs];
|
||||
}
|
||||
__syncthreads();
|
||||
float sc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) sc[i] = sR[i * 16 + col];
|
||||
if constexpr (DKS == 1) {
|
||||
if (nb < N) {
|
||||
const m2d_u2 rb = *(const m2d_u2*)(Wref + nb);
|
||||
float rf[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) rf[e] = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const int m = i * 16 + col;
|
||||
if (m < M) {
|
||||
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
|
||||
float v[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e)
|
||||
v[e] = ABLK ? acc[i][e] * sc[i] * rf[e] : acc[i][e] * rf[e] * sc[i];
|
||||
m2d_u4 o;
|
||||
o.x = bf16x2_rne_nan(v[0], v[1]);
|
||||
o.y = bf16x2_rne_nan(v[2], v[3]);
|
||||
o.z = bf16x2_rne_nan(v[4], v[5]);
|
||||
o.w = bf16x2_rne_nan(v[6], v[7]);
|
||||
*(m2d_u4*)(C + (size_t)m * ldc + nb) = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (nb < N) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const int m = i * 16 + col;
|
||||
if (m < M) {
|
||||
m2d_f4 lo, hi;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
lo[e] = ABLK ? acc[i][e] * sc[i] : acc[i][e];
|
||||
hi[e] = ABLK ? acc[i][e + 4] * sc[i] : acc[i][e + 4];
|
||||
}
|
||||
m2d_f4* dst = (m2d_f4*)(P + ((size_t)ks * M + m) * N + nb);
|
||||
dst[0] = lo;
|
||||
dst[1] = hi;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Every thread's partial stores are ordered before the counter; then the last arriver reduces.
|
||||
__threadfence();
|
||||
__syncthreads();
|
||||
if (tid == 0)
|
||||
*s_last = __hip_atomic_fetch_add(&cnt[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
|
||||
__HIP_MEMORY_SCOPE_AGENT);
|
||||
__syncthreads();
|
||||
if (*s_last != (unsigned)(DKS - 1)) return;
|
||||
if (tid == 0) cnt[blockIdx.x] = 0u; // reset for the next launch
|
||||
__threadfence(); // acquire, before reading the other partials
|
||||
const int nhi = min(n0 + BND, N);
|
||||
for (int nn = n0 + tid; nn < nhi; nn += NTHR) {
|
||||
const float rf = __int_as_float((int)Wref[nn] << 23);
|
||||
for (int m = 0; m < M; ++m) {
|
||||
float sum = 0.f;
|
||||
#pragma unroll
|
||||
for (int k = 0; k < DKS; ++k) sum += P[((size_t)k * M + m) * N + nn];
|
||||
C[(size_t)m * ldc + nn] = f32_to_bf16(sum * rf * (ABLK ? 1.f : As[(size_t)m * as_rs]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Waves per SIMD for each tile shape (R4D_WAVES), by K block, M fragments and scale form: pins
|
||||
* the register budget the tile was tuned at so a compiler release cannot change occupancy (LLVM 24
|
||||
* would drop the DBK 64, three-fragment form from 16 waves to 12). Where a shape spilled at 256
|
||||
* VGPRs, the budget is the one it reaches without spilling. The meta adds one global byte per
|
||||
* staged pair to the fold's inputs and no register to the WMMA chain, so the budgets are the
|
||||
* mxfp4 decode kernel's; the fold is a second table index, not a multiply. */
|
||||
constexpr int m2d_waves(int dbk, int dtm, bool ablk) {
|
||||
if (dbk == 64)
|
||||
return dtm <= 3 ? 16 : dtm == 4 ? 12 : dtm == 5 ? 10 : dtm == 6 ? (ablk ? 9 : 10)
|
||||
: dtm == 7 ? 9 : (ablk ? 8 : 9);
|
||||
return dtm <= 3 ? 10 : dtm == 4 ? 8 : dtm == 5 ? (ablk ? 8 : 7) : dtm == 6 ? (ablk ? 8 : 6)
|
||||
: 6;
|
||||
}
|
||||
|
||||
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(m2d_waves(DBK, DTM, ABLK))
|
||||
void r4d_gemm_m2xfp4a8_decode_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
|
||||
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
|
||||
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_M2D_MTILE * DTM;
|
||||
constexpr int STR = DBK + R4D_M2D_PAD;
|
||||
__shared__ unsigned char sA[ROWS * STR];
|
||||
__shared__ unsigned char sW[BND * STR];
|
||||
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
|
||||
__shared__ unsigned s_last;
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int n0 = blockIdx.x * BND;
|
||||
const int ks = blockIdx.z;
|
||||
|
||||
const int slabs = (K + DBK - 1) / DBK;
|
||||
const int spb = (slabs + DKS - 1) / DKS;
|
||||
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
|
||||
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
|
||||
|
||||
v8f acc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
|
||||
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
if constexpr (ABLK) {
|
||||
// a split that starts mid-block meets its first boundary one slab in
|
||||
const int kb = ((s_lo * DBK) >> 7) + 1;
|
||||
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
|
||||
}
|
||||
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps_g = K / 16;
|
||||
|
||||
for (int s = s_lo; s < s_hi; ++s) {
|
||||
const int k0 = s * DBK;
|
||||
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
|
||||
}
|
||||
// ---- A: ROWS x DBK bytes, clamped rows, 16 B a thread
|
||||
#pragma unroll
|
||||
for (int off = 0; off < ROWS * DBK; off += NTHR * 16) {
|
||||
const int idx = off + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1; // clamp, never predicate
|
||||
*(m2d_u4*)(&sA[r * STR + c]) = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
|
||||
}
|
||||
}
|
||||
// ---- W: fragment-order slots, two adjacent rows a thread (an 8 B request), folded to e4m3.
|
||||
// The k offset of the eight elements a lane stages is a multiple of 8 and DBK of 32, so one
|
||||
// meta byte's two-bit field per row covers it whole (r4d_m2xfp4.h).
|
||||
{
|
||||
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int off = 0; off < NTILES_T * KSTEPS_T * 32; off += NTHR * 2) {
|
||||
const int sl = off + tid * 2;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
|
||||
const int r = ntl * 16 + (lane_ & 15), kloc = kst * 16 + (lane_ >> 4) * 8;
|
||||
const int ksh = r4d_m2xfp4_kshift(kloc);
|
||||
const int gn = n0 + r;
|
||||
// gn is even and N % 16 == 0, so clamping to N - 2 keeps the 8 B read aligned and gc + 1 in
|
||||
// bounds; the slot address is recomputed from the clamped row.
|
||||
const int gc = gn < N - 2 ? gn : N - 2;
|
||||
const int lanec = (lane_ & 16) | (gc & 15);
|
||||
const m2d_u2 wv =
|
||||
m2d_ld<NT>((const m2d_u2*)&Wp[((size_t)(gc >> 4) * ksteps_g + kstep0 + kst) * 32 +
|
||||
lanec]);
|
||||
const int blk = (k0 + kst * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d(Wref[gc + q], Ws[(size_t)blk * ldws + gc + q]);
|
||||
const int k = (Wm[(size_t)blk * ldws + gc + q] >> ksh) & 3;
|
||||
unsigned int lo, hi;
|
||||
r4d_m2xfp4_unpack8(q ? wv[1] : wv[0], d, k, &lo, &hi);
|
||||
*(m2d_u2*)(&sW[(r + q) * STR + kloc]) = m2d_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
if constexpr (ABLK) {
|
||||
if (bnd) m2d_rescale(acc, sR, col);
|
||||
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int step = 0; step < DBK / 16; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
m2d_v2i af[DTM], wf;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
|
||||
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
|
||||
}
|
||||
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
|
||||
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i)
|
||||
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as
|
||||
// above, plus: the next slab's A, codes, exponents and meta bytes are loaded into registers while
|
||||
// this slab computes, keeping loads in flight across barriers; a thread takes four adjacent slots
|
||||
// (one 16 B load); and each row's reference exponent is read once. Bit-identical to the kernel
|
||||
// above.
|
||||
template <int DBK, int DKS, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_M2D_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
|
||||
void r4d_gemm_m2xfp4a8_decode1_kernel(
|
||||
const unsigned char* __restrict__ A, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
|
||||
float* __restrict__ P, unsigned* __restrict__ cnt, uint16_t* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int lda, int ldws, int ldc) {
|
||||
constexpr int DTM = 1, VEC = 4;
|
||||
constexpr int DWN = R4D_M2D_DWN, BND = DWN * 16, NTHR = DWN * 32;
|
||||
constexpr int ROWS = R4D_M2D_MTILE * DTM;
|
||||
constexpr int STR = DBK + R4D_M2D_PAD;
|
||||
constexpr int KSTEPS_T = DBK / 16, NTILES_T = BND / 16;
|
||||
constexpr int W_IT = NTILES_T * KSTEPS_T * 32 / (NTHR * VEC);
|
||||
constexpr int A_IT = (ROWS * DBK + NTHR * 16 - 1) / (NTHR * 16);
|
||||
__shared__ unsigned char sA[ROWS * STR];
|
||||
__shared__ unsigned char sW[BND * STR];
|
||||
__shared__ float sR[ROWS]; // ABLK: a boundary's ratio a row; then every row's final scale
|
||||
__shared__ unsigned s_last;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int n0 = blockIdx.x * BND;
|
||||
const int ks = blockIdx.z;
|
||||
const int slabs = (K + DBK - 1) / DBK;
|
||||
const int spb = (slabs + DKS - 1) / DKS;
|
||||
const int s_lo = ks * spb, s_hi = min(slabs, s_lo + spb);
|
||||
const int k_hi = (s_hi * DBK < K ? s_hi * DBK : K);
|
||||
|
||||
v8f acc[DTM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) acc[i] = (v8f)(0.f);
|
||||
const float* __restrict__ asrow = As + (size_t)(tid < M ? tid : M - 1) * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
if constexpr (ABLK) {
|
||||
const int kb = ((s_lo * DBK) >> 7) + 1;
|
||||
if (tid < ROWS && ((s_lo * DBK) & 127) && kb * 128 < k_hi) { ns = asrow[kb]; np = asrow[kb - 1]; }
|
||||
}
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
const int ksteps_g = K / 16;
|
||||
|
||||
// per-thread slot geometry, fixed across slabs; the meta shift with it, since an eight-element
|
||||
// slot's offset inside its 32-column group does not move
|
||||
int s_r[W_IT], s_kst[W_IT], s_kloc[W_IT], s_gc[W_IT], s_lanec[W_IT], s_ksh[W_IT][VEC];
|
||||
int s_ref[W_IT][VEC];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
const int sl = it * NTHR * VEC + tid * VEC;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % KSTEPS_T, ntl = rest / KSTEPS_T;
|
||||
const int r = ntl * 16 + (lane_ & 15);
|
||||
const int gn = n0 + r;
|
||||
const int gc = gn < N - VEC ? gn : N - VEC;
|
||||
s_r[it] = r; s_kst[it] = kst; s_kloc[it] = kst * 16 + (lane_ >> 4) * 8;
|
||||
s_gc[it] = gc; s_lanec[it] = (lane_ & 16) | (gc & 15);
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) {
|
||||
s_ref[it][q] = (int)Wref[gc + q];
|
||||
s_ksh[it][q] = r4d_m2xfp4_kshift(s_kloc[it]);
|
||||
}
|
||||
}
|
||||
typedef unsigned wv_t __attribute__((ext_vector_type(VEC)));
|
||||
wv_t rw[W_IT];
|
||||
int rd[W_IT][VEC], rk[W_IT][VEC];
|
||||
m2d_u4 ra[A_IT];
|
||||
|
||||
auto load = [&](int s) {
|
||||
const int k0 = s * DBK;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < A_IT; ++j) {
|
||||
const int idx = j * NTHR * 16 + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
const int rc = r < M - 1 ? r : M - 1;
|
||||
ra[j] = *(const m2d_u4*)(A + (size_t)rc * lda + k0 + c);
|
||||
}
|
||||
}
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
const size_t slot =
|
||||
((size_t)(s_gc[it] >> 4) * ksteps_g + kstep0 + s_kst[it]) * 32 + s_lanec[it];
|
||||
rw[it] = m2d_ld<NT>((const wv_t*)&Wp[slot]);
|
||||
const int blk = (k0 + s_kst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) {
|
||||
rd[it][q] = (int)Ws[(size_t)blk * ldws + s_gc[it] + q];
|
||||
rk[it][q] = (int)Wm[(size_t)blk * ldws + s_gc[it] + q];
|
||||
}
|
||||
}
|
||||
};
|
||||
auto store = [&]() {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < A_IT; ++j) {
|
||||
const int idx = j * NTHR * 16 + tid * 16;
|
||||
if (idx < ROWS * DBK) {
|
||||
const int r = idx / DBK, c = idx % DBK;
|
||||
*(m2d_u4*)(&sA[r * STR + c]) = ra[j];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int it = 0; it < W_IT; ++it) {
|
||||
#pragma unroll
|
||||
for (int q = 0; q < VEC; ++q) {
|
||||
unsigned int lo, hi;
|
||||
r4d_m2xfp4_unpack8(rw[it][q], r4d_mxfp4_fold_d(s_ref[it][q], rd[it][q]),
|
||||
(rk[it][q] >> s_ksh[it][q]) & 3, &lo, &hi);
|
||||
*(m2d_u2*)(&sW[(s_r[it] + q) * STR + s_kloc[it]]) = m2d_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if (s_lo < s_hi) load(s_lo);
|
||||
for (int s = s_lo; s < s_hi; ++s) {
|
||||
const int k0 = s * DBK;
|
||||
const bool bnd = ABLK && s > s_lo && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd && tid < ROWS) sR[tid] = m2d_ratio(ns, np, asrow, k0 >> 7);
|
||||
}
|
||||
store();
|
||||
__syncthreads();
|
||||
if (s + 1 < s_hi) load(s + 1); // the next slab's loads fly across this slab's WMMAs
|
||||
if constexpr (ABLK) {
|
||||
if (bnd) m2d_rescale(acc, sR, col);
|
||||
if (tid < ROWS && (k0 & 127) == 0 && k0 + 128 < k_hi) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int step = 0; step < DBK / 16; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
m2d_v2i af[DTM], wf;
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i) {
|
||||
const unsigned char* pa = &sA[(i * 16 + col) * STR + kk];
|
||||
af[i][0] = *(const int*)pa; af[i][1] = *(const int*)(pa + 4);
|
||||
}
|
||||
const unsigned char* pw = &sW[(wave * 16 + col) * STR + kk];
|
||||
wf[0] = *(const int*)pw; wf[1] = *(const int*)(pw + 4);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < DTM; ++i)
|
||||
acc[i] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf, af[i], acc[i]);
|
||||
}
|
||||
__syncthreads();
|
||||
}
|
||||
const int kb_end = s_hi > s_lo ? (k_hi - 1) >> 7 : 0;
|
||||
m2d_epilogue<DTM, DKS, ABLK>(acc, As, as_rs, Wref, P, cnt, C, M, N, ldc, n0, wave, col, kb8, ks,
|
||||
kb_end, &s_last, sR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The arrival counters now ride the op's scratch (m2d_partial_bytes); the per-output library
|
||||
// allocation this replaced was a pointer a recorded pass could not relocate.
|
||||
|
||||
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule).
|
||||
// The mxfp4 decode kernel's rule: the meta byte adds weight-stream traffic, not work at any of the
|
||||
// points the rule trades, so the rule itself carries over. Shared by the launch and the scratch
|
||||
// hook so the sized partial is the one written.
|
||||
struct M2dPlan { int ks, bk; bool nt; };
|
||||
M2dPlan m2d_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
|
||||
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
|
||||
M2dPlan p;
|
||||
int ks = 1;
|
||||
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
|
||||
while (ks < R4D_M2D_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
|
||||
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
|
||||
while (ks < R4D_M2D_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
|
||||
p.ks = KS > 0 ? KS : ks;
|
||||
// 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column
|
||||
// blocks, and DTM 8 on those or at a split of 4 or more.
|
||||
const bool slab64 = (tm == 4 && p.ks == 1 && nblk >= 110) || (tm == 8 && (nblk >= 110 || p.ks >= 4));
|
||||
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
|
||||
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
|
||||
if (K % p.bk) { // a slab may not run past K
|
||||
p.bk = 64;
|
||||
if (p.ks == 2) p.ks = 4;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The scratch: the split partial when ks > 1, then the arrival counters. The counters live in
|
||||
* the scratch rather than in a library-owned allocation because the scratch is a declared op
|
||||
* buffer: a recorded pass relocates it with the other operands, while a pointer the library
|
||||
* allocated itself is baked into the recorded kernarg and cannot be relocated. */
|
||||
constexpr size_t m2d_ctr_count() { return R4D_M2D_MAX_N / (R4D_M2D_DWN * 16); }
|
||||
|
||||
long m2d_partial_bytes(int M, int N, int ks) {
|
||||
return (ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0) +
|
||||
(long)m2d_ctr_count() * (long)sizeof(unsigned);
|
||||
}
|
||||
|
||||
void m2d_launch(long a, long ascale, long wq, long ws, long wm, long wref, long c, int M, int K,
|
||||
int N, int KS, int BK, int NT, int as_group, int as_rs, long stream, long scratch,
|
||||
long scratch_bytes, int lda, int ldws, int ldc) {
|
||||
// A part of a partitioned weight reads windows of larger planes; 0 means the plane's own width,
|
||||
// as r4d_gemm_mxfp4a8_nt_m64's launcher spells it.
|
||||
if (!lda) lda = K;
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1 || M > R4D_M2D_MTILE * R4D_M2D_MAX_TM)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: M must be 1..128");
|
||||
if (N < 16 || N % 16 || N > R4D_M2D_MAX_N)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: N must be a multiple of 16 up to 36864");
|
||||
if (K < 64 || K % 64)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: K must be a multiple of 64");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the activation scale is per row or per "
|
||||
"128 of K");
|
||||
const M2dPlan pl = m2d_plan(M, K, N, KS, BK, NT);
|
||||
const int ks = pl.ks, bk = pl.bk;
|
||||
if (ks != 1 && ks != 2 && ks != 4 && ks != 8 && ks != 16)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
|
||||
if (bk != 64 && bk != 128)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: BK must be 64 or 128");
|
||||
if (!scratch || scratch_bytes < m2d_partial_bytes(M, N, ks))
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: the op's scratch is shorter than the split "
|
||||
"partial and the arrival counters; the scratch hook sizes it");
|
||||
float* P = (float*)scratch;
|
||||
unsigned* cnt = (unsigned*)((unsigned char*)P +
|
||||
(ks > 1 ? (size_t)ks * (size_t)M * (size_t)N * sizeof(float) : 0));
|
||||
/* Every launch enters with the counters zero: the scratch is shared across ops, and a replayed
|
||||
* pass writes the same slots. One 1.1 KiB memset beside the launch is not measurable. */
|
||||
if (hipMemsetAsync(cnt, 0, m2d_ctr_count() * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_decode: zeroing the arrival counters failed");
|
||||
const bool ablk = as_group == 128, nt = pl.nt;
|
||||
const int nblk = (N + R4D_M2D_DWN * 16 - 1) / (R4D_M2D_DWN * 16);
|
||||
const int tm = (M + R4D_M2D_MTILE - 1) / R4D_M2D_MTILE;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
dim3 grid(nblk, 1, ks), block(R4D_M2D_DWN * 32);
|
||||
auto Ap = (const unsigned char*)a;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Mp = (const unsigned char*)wm;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (uint16_t*)c;
|
||||
#define M2D_L(BK_, KS_, TM_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode_kernel<BK_, KS_, TM_, NT_, AB_>), grid, block, 0, \
|
||||
st, Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
|
||||
#define M2D_L1(BK_, KS_, NT_, AB_) \
|
||||
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_decode1_kernel<BK_, KS_, NT_, AB_>), grid, block, 0, st, \
|
||||
Ap, Sp, Wp, Zp, Mp, Rp, P, cnt, Cp, M, K, N, as_rs, lda, ldws, ldc)
|
||||
#define M2D_AB(BK_, KS_, TM_, NT_) \
|
||||
{ if (ablk) M2D_L(BK_, KS_, TM_, NT_, true); else M2D_L(BK_, KS_, TM_, NT_, false); }
|
||||
#define M2D_NT(BK_, KS_, TM_) \
|
||||
{ if (nt) M2D_AB(BK_, KS_, TM_, true) else M2D_AB(BK_, KS_, TM_, false) }
|
||||
#define M2D_AB1(BK_, KS_, NT_) \
|
||||
{ if (ablk) M2D_L1(BK_, KS_, NT_, true); else M2D_L1(BK_, KS_, NT_, false); }
|
||||
#define M2D_NT1(BK_, KS_) { if (nt) M2D_AB1(BK_, KS_, true) else M2D_AB1(BK_, KS_, false) }
|
||||
#define M2D_TM(BK_, KS_) \
|
||||
{ switch (tm) { case 1: M2D_NT1(BK_, KS_) break; case 2: M2D_NT(BK_, KS_, 2) break; \
|
||||
case 3: M2D_NT(BK_, KS_, 3) break; case 4: M2D_NT(BK_, KS_, 4) break; \
|
||||
case 5: M2D_NT(BK_, KS_, 5) break; case 6: M2D_NT(BK_, KS_, 6) break; \
|
||||
case 7: M2D_NT(BK_, KS_, 7) break; default: M2D_NT(BK_, KS_, 8) break; } }
|
||||
#define M2D_KS(BK_) \
|
||||
{ switch (ks) { case 1: M2D_TM(BK_, 1) break; case 2: M2D_TM(BK_, 2) break; \
|
||||
case 4: M2D_TM(BK_, 4) break; case 8: M2D_TM(BK_, 8) break; \
|
||||
default: M2D_TM(BK_, 16) break; } }
|
||||
if (bk == 64) M2D_KS(64) else M2D_KS(128)
|
||||
#undef M2D_KS
|
||||
#undef M2D_TM
|
||||
#undef M2D_NT1
|
||||
#undef M2D_AB1
|
||||
#undef M2D_NT
|
||||
#undef M2D_AB
|
||||
#undef M2D_L1
|
||||
#undef M2D_L
|
||||
}
|
||||
} // namespace
|
||||
|
||||
extern "C" int r4d_gemm_m2xfp4a8_decode_max_m(void) { return R4D_M2D_MTILE * R4D_M2D_MAX_TM; }
|
||||
|
||||
// The raw entry, as r4d_gemm_fp8a8_nt_m16: plain C ABI for a caller that sizes the split itself.
|
||||
// The scratch is the split partial m2d_partial_bytes(M, N, KS) long; `scratch` null runs unsplit
|
||||
// only when KS is 1.
|
||||
extern "C" void r4d_gemm_m2xfp4a8_decode(long a, long ascale, long wq, long ws, long wm, long wref,
|
||||
long c, int M, int K, int N, int KS, int BK, int NT,
|
||||
int as_group, int as_rs, long scratch,
|
||||
long scratch_bytes, long stream, int lda, int ldws,
|
||||
int ldc) {
|
||||
m2d_launch(a, ascale, wq, ws, wm, wref, c, M, K, N, KS, BK, NT, as_group, as_rs, stream, scratch,
|
||||
scratch_bytes, lda, ldws, ldc);
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
extern "C" int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale || !g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % 64) return R4D_NO(RAD_E_SHAPE);
|
||||
if (g.M > r4d_gemm_m2xfp4a8_decode_max_m() || g.N > R4D_M2D_MAX_N) return R4D_NO(RAD_E_SHAPE);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
const long long kb = (g.K + 127) / 128;
|
||||
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order: the part
|
||||
// window opens at n0 of it as of the exponent plane, at n0 * K / 2 of the codes.
|
||||
const long meta0 = (long)g.N * g.K / 2;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
R4D_TRY("gemm_m2xfp4a8_decode",
|
||||
m2d_launch(r4d_addr(g.a) + p * g.K, r4d_addr(g.ascale) + (long)(p * kb * 4),
|
||||
r4d_addr(g.b) + n0 * g.K / 2, r4d_addr(g.bscale) + n0,
|
||||
r4d_addr(g.b) + meta0 + n0, r4d_addr(g.bref) + n0,
|
||||
r4d_addr(g.y) + n0 * 2,
|
||||
(int)g.M, (int)g.K, (int)np, t.ks, t.bk, t.nt, as_group, as_rs,
|
||||
(long)(uintptr_t)s, (long)(uintptr_t)a->scratch, (long)a->scratch_bytes,
|
||||
(int)(mp.lda ? mp.lda : g.K), (int)g.N, (int)g.N));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The op's scratch size. A narrower M can split wider than the band's widest M, so the size is the
|
||||
* widest split over the band times the widest M, an upper bound for every launch. Parts of a
|
||||
* partitioned weight split at their own N and run in turn sharing the scratch, so the bound is the
|
||||
* largest part's. */
|
||||
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
|
||||
const long long K = r4d_geti_or(a, "K", 0);
|
||||
if (M < 1 || N < 16 || K < 64 || M > r4d_gemm_m2xfp4a8_decode_max_m()) return 0;
|
||||
R4dMxDecCfg t;
|
||||
r4d_cfg_mxfp4_decode(a, &t);
|
||||
long long bound[4];
|
||||
mx_part_bounds(N, r4d_geti_or(a, "pb1", 0), r4d_geti_or(a, "pb2", 0), bound);
|
||||
int64_t worst = 0;
|
||||
for (int i = 0; i < 3; ++i) {
|
||||
const long long np = bound[i + 1] - bound[i];
|
||||
if (np < 16) continue;
|
||||
int ks = 1;
|
||||
for (int m = 1; m <= (int)M; ++m) {
|
||||
const int k = m2d_plan(m, (int)K, (int)np, t.ks, t.bk, t.nt).ks;
|
||||
if (k > ks) ks = k;
|
||||
}
|
||||
const int64_t b = (int64_t)m2d_partial_bytes((int)M, (int)np, ks);
|
||||
if (b > worst) worst = b;
|
||||
}
|
||||
const int64_t ctr = (int64_t)m2d_ctr_count() * (int64_t)sizeof(unsigned);
|
||||
return worst > ctr ? worst : ctr;
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
// r4d_gemm_m2xfp4a8_tiled.hip - r4d_gemm_m2xfp4a8_tiled: the M2XFP4 x fp8 GEMM for prefill row
|
||||
// counts, gfx1201. C[M,N] = A[M,K] @ dequant(Wq)[N,K]^T with the operands, weight layout, fold and
|
||||
// tile of r4d_gemm_mxfp4a8_tiled, plus the weight-side Sg-EM (arXiv 2601.19213 §4.4.2) the decode
|
||||
// row decodes: per group of 32 K a meta byte of four two-bit subgroup multipliers, folded into the
|
||||
// e4m3 staging bytes through r4d_m2xfp4.h's second table index, so the WMMA chain, the Wref
|
||||
// epilogue and the activation scale grids are the mxfp4 kernel's unchanged.
|
||||
//
|
||||
// The meta byte is staged beside the exponent byte: one byte per (weight row, 32 of K), in the
|
||||
// scale plane's [K/32][N] order and row pitch, in the tail of the same stored weight (the relayout
|
||||
// appends it after the fragment-order codes, r4d_layout.cpp). A staged slot's eight elements sit at
|
||||
// an offset that is a multiple of 8 inside their 32-column group, so one two-bit field per slot
|
||||
// covers it whole; the shift is fixed per slot across slabs and read with the geometry the scale
|
||||
// dword already uses.
|
||||
//
|
||||
// The fold's bound: Wref[n] is the row's largest exponent byte as for MXFP4, so d >= 0 holds for
|
||||
// every block, and the largest element any table cell then holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d
|
||||
// -- an e4m3 normal at every d >= 0 (r4d_m2xfp4.h). The table is four times the mxfp4 one, 512
|
||||
// bytes, still nothing against sW; the LDS copy widens with it.
|
||||
#include "r4d.h"
|
||||
#include "r4d_gemm_args.h"
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_m2xfp4.h"
|
||||
|
||||
// bf16 output as uint16 pairs (the emulator-compatible spelling, r4d_common.h): the OCP
|
||||
// rows read __hip_bfloat16 from hip_bf16.h, whose bytes these are.
|
||||
#include <cstdint>
|
||||
#include <stdexcept>
|
||||
|
||||
#define R4D_M2T_TM 4 // 16-row fragments per wave
|
||||
#define R4D_M2T_WM 4 // waves along M
|
||||
#define R4D_M2T_WN 2 // waves along N
|
||||
#define R4D_M2T_PAD 8 // LDS row pad: 16 lanes reading rows 64 B apart collide 8 ways
|
||||
#define R4D_M2T_NTHR (R4D_M2T_WM * R4D_M2T_WN * 32)
|
||||
#define R4D_M2T_BMF (R4D_M2T_WM * R4D_M2T_TM * 16)
|
||||
#define R4D_M2T_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
|
||||
#define R4D_M2T_TN4_MIN_M 2048 // tn=0's crossover, see r4d_gemm_mxfp4a8_tiled.hip
|
||||
|
||||
typedef int m2t_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned m2t_u2 __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned m2t_u4 __attribute__((ext_vector_type(4)));
|
||||
|
||||
// The re-tile: one thread per 8-byte slot of the fragment-ordered plane; writes are contiguous.
|
||||
// (r4d_mxfp4a8_tile_a_kernel, shared work; this row runs its own copy so the two units stay
|
||||
// independent.)
|
||||
__global__ __launch_bounds__(256) void r4d_m2xfp4a8_tile_a_kernel(
|
||||
const unsigned char* __restrict__ A, unsigned char* __restrict__ AT, int M, int K,
|
||||
long long slots, int lda) {
|
||||
const long long o = (long long)blockIdx.x * 256 + threadIdx.x;
|
||||
if (o >= slots) return;
|
||||
const int ks = K / 16;
|
||||
const int lane = (int)(o & 31);
|
||||
const long long f = o >> 5;
|
||||
const int mt = (int)(f / ks), kst = (int)(f % ks);
|
||||
const int r = mt * 16 + (lane & 15), k = kst * 16 + (lane >> 4) * 8;
|
||||
m2t_u2 v = { 0u, 0u };
|
||||
if (r < M) v = *(const m2t_u2*)(A + (size_t)r * lda + k);
|
||||
*(m2t_u2*)(AT + o * 8) = v;
|
||||
}
|
||||
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_M2T_NTHR) void r4d_gemm_m2xfp4a8_tiled_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wm, const unsigned char* __restrict__ Wref,
|
||||
uint16_t* __restrict__ C, int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
constexpr int TM = R4D_M2T_TM, WN = R4D_M2T_WN, NTHR = R4D_M2T_NTHR, BMF = R4D_M2T_BMF;
|
||||
constexpr int NS = LBK / 16, STR = LBK + R4D_M2T_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
// 4 weight slots (one 16 B read) wherever the tile has enough of them, else 2 (8 B), else 1.
|
||||
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
|
||||
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
|
||||
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
|
||||
__shared__ unsigned char sW[BNF * STR];
|
||||
__shared__ unsigned int sMag[128]; // kM2xfp4Mag: [16][4][2] words
|
||||
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
|
||||
const int ksteps = K / 16, Mt = (M + 15) >> 4;
|
||||
|
||||
if (tid < 128) sMag[tid] = (&kM2xfp4Mag[0][0][0])[tid];
|
||||
|
||||
// One A base per M fragment, wave-uniform: readfirstlane keeps it in an SGPR so loads take the
|
||||
// SADDR form with a 32-bit lane offset. A tile past M reads the last real one.
|
||||
const unsigned char* abase[TM];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
int mt = (m0 >> 4) + wm * TM + i;
|
||||
mt = mt < Mt - 1 ? mt : Mt - 1;
|
||||
abase[i] = AT + (size_t)__builtin_amdgcn_readfirstlane(mt * ksteps * 256);
|
||||
}
|
||||
const unsigned int aoff = (unsigned int)lane * 8;
|
||||
|
||||
// The W slots this thread stages, fixed across slabs: WSLOTS adjacent rows of one (n-tile,
|
||||
// k-step), so the wave reads contiguous bytes; the clamp keeps the vector read aligned. The meta
|
||||
// shift moves with the slot: its eight elements' offset inside their 32-column group is
|
||||
// kst*16 + (lane>>4)*8, a multiple of 8 (r4d_m2xfp4.h).
|
||||
int wrow[NW], wkloc[NW], wrc[NW], wkst[NW], wlanec[NW], wksh[NW];
|
||||
unsigned int wref[NW];
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const int sl = it * NTHR * WSLOTS + tid * WSLOTS;
|
||||
const int lane_ = sl & 31, rest = sl >> 5;
|
||||
const int kst = rest % NS, ntl = rest / NS;
|
||||
wrow[it] = ntl * 16 + (lane_ & 15);
|
||||
wkloc[it] = kst * 16 + (lane_ >> 4) * 8;
|
||||
wksh[it] = r4d_m2xfp4_kshift(wkloc[it]);
|
||||
const int gn = n0 + wrow[it];
|
||||
wrc[it] = gn < N - WSLOTS ? gn : N - WSLOTS;
|
||||
wlanec[it] = (lane_ & 16) | (wrc[it] & 15);
|
||||
wkst[it] = kst;
|
||||
wref[it] = WSLOTS == 4 ? *(const unsigned int*)(Wref + wrc[it])
|
||||
: WSLOTS == 2 ? *(const unsigned short*)(Wref + wrc[it])
|
||||
: Wref[wrc[it]];
|
||||
}
|
||||
|
||||
v8f acc[TM][TN];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) acc[i][j] = (v8f)(0.f);
|
||||
|
||||
// ABLK: thread t owns row m0 + t (BMF == NTHR) and loads the next 128 boundary's two scales (the
|
||||
// block starting there and the one before it) a boundary early.
|
||||
const int trow = m0 + tid < M ? m0 + tid : M - 1;
|
||||
const float* __restrict__ asrow = As + (size_t)trow * as_rs;
|
||||
float ns = 0.f, np = 0.f;
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
lds_barrier(); // sMag
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += LBK) {
|
||||
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
|
||||
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
|
||||
// the carried scale; after a zero block the carried scale is looked up from the grid.
|
||||
const bool bnd = ABLK && k0 && (k0 & 127) == 0;
|
||||
if constexpr (ABLK) {
|
||||
if (bnd)
|
||||
sR[tid] = ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(asrow, (k0 >> 7) - 2)) / ns : 1.f;
|
||||
}
|
||||
// A fragments for the whole slab, one clause, consumed only at the WMMAs.
|
||||
m2t_v2i af[TM][NS];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int st = 0; st < NS; ++st)
|
||||
af[i][st] = *(const m2t_v2i*)(abase[i] +
|
||||
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
|
||||
// W slab -> LDS, folded to e4m3. The meta bytes ride the same dword reads as the exponents.
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const unsigned int* src =
|
||||
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
|
||||
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
unsigned int wq[WSLOTS], wsw, wmw;
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const m2t_u4 v = *(const m2t_u4*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
|
||||
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
wmw = *(const unsigned int*)(Wm + (size_t)blk * ldws + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const m2t_u2 v = *(const m2t_u2*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1];
|
||||
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
wmw = *(const unsigned short*)(Wm + (size_t)blk * ldws + wrc[it]);
|
||||
} else {
|
||||
wq[0] = *src;
|
||||
wsw = Ws[(size_t)blk * ldws + wrc[it]];
|
||||
wmw = Wm[(size_t)blk * ldws + wrc[it]];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int q = 0; q < WSLOTS; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
|
||||
(int)((wsw >> (8 * q)) & 0xFF));
|
||||
const int k = (int)((wmw >> (8 * q + wksh[it])) & 3);
|
||||
const int ti = (d * 4 + k) * 2;
|
||||
unsigned int lo, hi;
|
||||
r4d_m2xfp4_unpack8_t(wq[q], sMag[ti], sMag[ti + 1], &lo, &hi);
|
||||
*(m2t_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = m2t_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
|
||||
if constexpr (ABLK) {
|
||||
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
|
||||
if (bnd) {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const float r = sR[wm * TM * 16 + i * 16 + col];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) acc[i][j][e] *= r;
|
||||
}
|
||||
}
|
||||
// The next boundary's scales, issued behind this slab's loads and needed a boundary later.
|
||||
if ((k0 & 127) == 0 && k0 + 128 < K) {
|
||||
ns = asrow[(k0 >> 7) + 1];
|
||||
np = asrow[k0 >> 7];
|
||||
}
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (int step = 0; step < NS; ++step) {
|
||||
const int kk = step * 16 + kb8;
|
||||
m2t_v2i wf[TN];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const unsigned char* p = &sW[(wn * TN * 16 + j * 16 + col) * STR + kk];
|
||||
wf[j][0] = *(const int*)p; wf[j][1] = *(const int*)(p + 4);
|
||||
}
|
||||
// Keep one step's W fragments live at a time; otherwise the compiler hoists every step's
|
||||
// loads above the first WMMA.
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
|
||||
acc[i][j]);
|
||||
}
|
||||
lds_barrier();
|
||||
}
|
||||
|
||||
// Epilogue. A lane holds row m0 + 64*wm + 16i + col of M fragment i and eight consecutive columns
|
||||
// of N fragment j, one 16-byte store per (i, j). 2^(Wref[n]-127) is the float whose exponent
|
||||
// field is Wref[n]; N % 16 == 0 keeps a lane's eight columns all inside or all outside N.
|
||||
float sc[TM];
|
||||
if constexpr (ABLK) {
|
||||
// the scale each row ends in, once a row; the K loop's closing barrier retired the ratio reads
|
||||
sR[tid] = r4d_mxfp4_carried(asrow, (K - 1) >> 7);
|
||||
lds_barrier();
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) sc[i] = sR[wm * TM * 16 + i * 16 + col];
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const int m = m0 + wm * TM * 16 + i * 16 + col;
|
||||
sc[i] = As[(size_t)(m < M ? m : M - 1) * as_rs];
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j) {
|
||||
const int nb = n0 + wn * TN * 16 + j * 16 + kb8;
|
||||
if (nb >= N) continue;
|
||||
const m2t_u2 rb = *(const m2t_u2*)(Wref + nb);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
const int m = m0 + wm * TM * 16 + i * 16 + col;
|
||||
if (m >= M) continue;
|
||||
// rounded as the bf16 store rounds, packed in whole registers (see bf16x2_rne_nan)
|
||||
float v[8];
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const float rf = __int_as_float((int)((rb[e >> 2] >> (8 * (e & 3))) & 0xFF) << 23);
|
||||
v[e] = acc[i][j][e] * rf * sc[i];
|
||||
}
|
||||
m2t_u4 o;
|
||||
o.x = bf16x2_rne_nan(v[0], v[1]);
|
||||
o.y = bf16x2_rne_nan(v[2], v[3]);
|
||||
o.z = bf16x2_rne_nan(v[4], v[5]);
|
||||
o.w = bf16x2_rne_nan(v[6], v[7]);
|
||||
*(m2t_u4*)(C + (size_t)m * ldc + nb) = o;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int r4d_gemm_m2xfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
|
||||
|
||||
extern "C" long r4d_m2xfp4a8_tile_a_bytes(int M, int K) {
|
||||
return M < 1 || K < 16 ? 0 : (long)((M + 15) / 16) * 16 * K;
|
||||
}
|
||||
|
||||
extern "C" void r4d_m2xfp4a8_tile_a(long a, long at, int M, int K, long stream, int lda) {
|
||||
if (!lda) lda = K;
|
||||
if (M < 1) throw std::runtime_error("r4d m2xfp4a8_tile_a: M must be >= 1");
|
||||
if (K < 16 || K % 16) throw std::runtime_error("r4d m2xfp4a8_tile_a: K must be a multiple of 16");
|
||||
const long long slots = (long long)((M + 15) / 16) * (K / 16) * 32;
|
||||
hipLaunchKernelGGL(r4d_m2xfp4a8_tile_a_kernel, dim3((unsigned)((slots + 255) / 256)), dim3(256),
|
||||
0, (hipStream_t)stream, (const unsigned char*)a, (unsigned char*)at, M, K,
|
||||
slots, lda);
|
||||
}
|
||||
|
||||
extern "C" void r4d_gemm_m2xfp4a8_tiled(long at, long ascale, long wq, long ws, long wm, long wref,
|
||||
long c, int M, int K, int N, int TN, int as_group,
|
||||
int as_rs, long stream, int ldws, int ldc) {
|
||||
if (!ldws) ldws = N;
|
||||
if (!ldc) ldc = N;
|
||||
if (M < 1) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: M must be >= 1");
|
||||
if (N < 16 || N % 16) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: N must be a multiple of 16");
|
||||
if (K < R4D_M2T_KUNIT || K % R4D_M2T_KUNIT)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: K must be a multiple of 64");
|
||||
// tn=0: TN=4 from the M crossover on, unless its 128-wide tile leaves fewer than 128 blocks
|
||||
// (narrow N), where TN=2's extra blocks win.
|
||||
if (TN == 0)
|
||||
TN = M >= R4D_M2T_TN4_MIN_M && (long)((N + 127) / 128) * ((M + R4D_M2T_BMF - 1) / R4D_M2T_BMF) >= 128
|
||||
? 4 : 2;
|
||||
if (TN != 2 && TN != 4) throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: TN must be 2 or 4");
|
||||
if (as_group != 0 && as_group != 128)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: the activation scale is per row or per 128 of K");
|
||||
const bool ablk = as_group == 128;
|
||||
if (ablk && as_rs < (K + 127) / 128)
|
||||
throw std::runtime_error("r4d gemm_m2xfp4a8_tiled: activation scale rows shorter than ceil(K/128)");
|
||||
const bool wide_slab = TN == 2 && K % 128 == 0;
|
||||
const int bnf = R4D_M2T_WN * TN * 16;
|
||||
dim3 grid((N + bnf - 1) / bnf, (M + R4D_M2T_BMF - 1) / R4D_M2T_BMF), block(R4D_M2T_NTHR);
|
||||
auto Ap = (const unsigned char*)at;
|
||||
auto Sp = (const float*)ascale;
|
||||
auto Wp = (const unsigned char*)wq;
|
||||
auto Zp = (const unsigned char*)ws;
|
||||
auto Mp = (const unsigned char*)wm;
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (uint16_t*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define M2T_LAUNCH(TNv, LBKv, ABv) \
|
||||
hipLaunchKernelGGL((r4d_gemm_m2xfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
|
||||
Wp, Zp, Mp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
|
||||
if (TN == 4) { if (ablk) M2T_LAUNCH(4, 64, true); else M2T_LAUNCH(4, 64, false); }
|
||||
else if (wide_slab) { if (ablk) M2T_LAUNCH(2, 128, true); else M2T_LAUNCH(2, 128, false); }
|
||||
else { if (ablk) M2T_LAUNCH(2, 64, true); else M2T_LAUNCH(2, 64, false); }
|
||||
#undef M2T_LAUNCH
|
||||
}
|
||||
|
||||
// ============================================================== the plugin ABI entry point
|
||||
// The row-major activation is re-tiled into the op's scratch and the GEMM reads it there. For a
|
||||
// partitioned weight (mx_parts), each part's activation copy is re-tiled and multiplied in turn.
|
||||
extern "C" int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs* a, RadStream s) {
|
||||
GemmOps g;
|
||||
int rc = gemm_ops(a, &g, 1, /*parts=*/1);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.N < 16 || g.N % 16) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!g.ascale) return R4D_NO(RAD_E_INVAL);
|
||||
/* The per-row reference exponent is required, as in r4d_rad_gemm_mxfp4a8_m64. */
|
||||
if (!g.bref) return R4D_NO(RAD_E_INVAL);
|
||||
MxParts mp;
|
||||
rc = mx_parts(a, &g, &mp);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.K % R4D_M2T_KUNIT) return R4D_NO(RAD_E_SHAPE);
|
||||
int as_group = 0, as_rs = 1;
|
||||
rc = mx_ascale_grid(g, &as_group, &as_rs, mp.n);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const long long slab = r4d_m2xfp4a8_tile_a_bytes((int)g.M, (int)g.K);
|
||||
if (!a->scratch || a->scratch_bytes < slab) return R4D_NO(RAD_E_INVAL);
|
||||
R4dMxTileCfg t;
|
||||
r4d_cfg_mxfp4_tiled(a, &t);
|
||||
const long kb = (long)((g.K + 127) / 128);
|
||||
const long at = (long)(uintptr_t)a->scratch;
|
||||
// The meta plane rides the weight blob's tail, in the scale plane's [K/32][N] order; a part
|
||||
// windows it at n0 of the plane, as of the exponents.
|
||||
const long meta0 = (long)g.N * g.K / 2;
|
||||
for (int p = 0; p < mp.n; ++p) {
|
||||
const long long n0 = mp.n0[p], np = mp.n1[p] - mp.n0[p];
|
||||
R4D_TRY("gemm_m2xfp4a8_tiled",
|
||||
r4d_m2xfp4a8_tile_a(r4d_addr(g.a) + p * g.K, at, (int)g.M, (int)g.K,
|
||||
(long)(uintptr_t)s, (int)(mp.lda ? mp.lda : g.K));
|
||||
r4d_gemm_m2xfp4a8_tiled(at, r4d_addr(g.ascale) + p * kb * 4, r4d_addr(g.b) + n0 * g.K / 2,
|
||||
r4d_addr(g.bscale) + n0, r4d_addr(g.b) + meta0 + n0,
|
||||
r4d_addr(g.bref) + n0,
|
||||
r4d_addr(g.y) + n0 * 2, (int)g.M, (int)g.K, (int)np, t.tn,
|
||||
as_group, as_rs, (long)(uintptr_t)s, (int)g.N, (int)g.N));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The op's scratch, sized at the band's widest M: the fragment-tiled activation in whole 16-row
|
||||
* fragments. One copy serves every part: parts run in order on the op's stream, so a re-tile
|
||||
* cannot overtake the previous part's GEMM. */
|
||||
extern "C" int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "K", 0);
|
||||
return (int64_t)r4d_m2xfp4a8_tile_a_bytes((int)M, (int)K);
|
||||
}
|
||||
@@ -27,7 +27,7 @@
|
||||
//
|
||||
// No state is keyed on the stream, since a recorded pass may replay on another stream. The split
|
||||
// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get
|
||||
// disjoint slices); the arrival counters are keyed on the output buffer (mxd_out_ctr), zero at
|
||||
// disjoint slices); the arrival counters ride the scratch's tail, zero at
|
||||
// entry and reset by the reducer. Launches writing the same output are ordered; overlapping ones
|
||||
// write different outputs. The row is therefore concurrent (rad_kernel_concurrent), like
|
||||
// gemm_fp8a8_nt_m16. A scratch shorter than the split needs is refused.
|
||||
@@ -457,31 +457,8 @@ void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
}
|
||||
|
||||
namespace {
|
||||
// The arrival counters, one block per output buffer (see the header). They cannot live in the
|
||||
// scratch, which other ops overwrite, because they must be zero at entry. One allocation per
|
||||
// (device, output), kept zero by the reducer and never freed (a recorded pass replays the
|
||||
// pointer), as gemm_fp8a8_nt_m16's split_ctr.
|
||||
unsigned* mxd_out_ctr(const void* out) {
|
||||
static std::mutex mu;
|
||||
static std::map<std::pair<int, const void*>, unsigned*> blocks;
|
||||
int dev = 0;
|
||||
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
|
||||
std::lock_guard<std::mutex> lk(mu);
|
||||
const auto key = std::make_pair(dev, out);
|
||||
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
|
||||
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
|
||||
unsigned* p = nullptr;
|
||||
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
|
||||
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
|
||||
// when it returns (core/device/aql.cpp); under HIP's own runtime (r4d_selftest) it runs on the
|
||||
// null stream, which a non-blocking stream does not wait for, so wait here.
|
||||
if (hipMemset(p, 0, n * sizeof(unsigned)) != hipSuccess || hipDeviceSynchronize() != hipSuccess) {
|
||||
(void)hipFree(p);
|
||||
return nullptr;
|
||||
}
|
||||
blocks.emplace(key, p);
|
||||
return p;
|
||||
}
|
||||
// The arrival counters now ride the op's scratch (mxd_partial_bytes); the per-output library
|
||||
// allocation this replaced was a pointer a recorded pass could not relocate.
|
||||
|
||||
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see
|
||||
// the header). Shared by the launch and the scratch hook so the sized partial is the one written.
|
||||
@@ -508,8 +485,15 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* The scratch: the split partial when ks > 1, then the arrival counters. The counters live in the
|
||||
* scratch rather than in a library-owned allocation because the scratch is a declared op buffer:
|
||||
* a recorded pass relocates it with the other operands, while a pointer the library allocated
|
||||
* itself is baked into the recorded kernarg and cannot be relocated. */
|
||||
constexpr size_t mxd_ctr_count() { return R4D_MXD_MAX_N / (R4D_MXD_DWN * 16); }
|
||||
|
||||
long mxd_partial_bytes(int M, int N, int ks) {
|
||||
return ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0;
|
||||
return (ks > 1 ? (long)ks * M * N * (long)sizeof(float) : 0) +
|
||||
(long)mxd_ctr_count() * (long)sizeof(unsigned);
|
||||
}
|
||||
|
||||
void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M, int K, int N,
|
||||
@@ -530,12 +514,16 @@ void mxd_launch(long a, long ascale, long wq, long ws, long wref, long c, int M,
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: KS must be 1, 2, 4, 8 or 16");
|
||||
if (bk != 64 && bk != 128)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: BK must be 64 or 128");
|
||||
if (scratch_bytes < mxd_partial_bytes(M, N, ks) || (ks > 1 && !scratch))
|
||||
if (!scratch || scratch_bytes < mxd_partial_bytes(M, N, ks))
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: the op's scratch is shorter than the split "
|
||||
"partial; the scratch hook sizes it");
|
||||
"partial and the arrival counters; the scratch hook sizes it");
|
||||
float* P = (float*)scratch;
|
||||
unsigned* cnt = mxd_out_ctr((const void*)c);
|
||||
if (!cnt) throw std::runtime_error("r4d gemm_mxfp4a8_decode: split counter alloc failed");
|
||||
unsigned* cnt = (unsigned*)((unsigned char*)P +
|
||||
(ks > 1 ? (size_t)ks * (size_t)M * (size_t)N * sizeof(float) : 0));
|
||||
/* Every launch enters with the counters zero: the scratch is shared across ops, and a replayed
|
||||
* pass writes the same slots. One 1.1 KiB memset beside the launch is not measurable. */
|
||||
if (hipMemsetAsync(cnt, 0, mxd_ctr_count() * sizeof(unsigned), (hipStream_t)stream) != hipSuccess)
|
||||
throw std::runtime_error("r4d gemm_mxfp4a8_decode: zeroing the arrival counters failed");
|
||||
const bool ablk = as_group == 128, nt = pl.nt;
|
||||
const int nblk = (N + R4D_MXD_DWN * 16 - 1) / (R4D_MXD_DWN * 16);
|
||||
const int tm = (M + R4D_MXD_MTILE - 1) / R4D_MXD_MTILE;
|
||||
@@ -638,5 +626,6 @@ extern "C" int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs* a) {
|
||||
const int64_t b = (int64_t)mxd_partial_bytes((int)M, (int)np, ks);
|
||||
if (b > worst) worst = b;
|
||||
}
|
||||
return worst;
|
||||
const int64_t ctr = (int64_t)mxd_ctr_count() * (int64_t)sizeof(unsigned);
|
||||
return worst > ctr ? worst : ctr;
|
||||
}
|
||||
@@ -939,6 +939,140 @@ extern "C" int r4d_rad_relayout_mxfp4(const RadParam* p, int n_p, int operand,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- M2XFP4: the M2 analogue of MXFP4 above, the paper's weight-side Sg-EM (arXiv 2601.19213
|
||||
* §4.4.2). The quantiser's own scheme "m2xfp4", three TILED planes over the same 32-column groups:
|
||||
*
|
||||
* codes u4 [1 x 1] e2m1, element 2j in bits 0-3 of byte j -- radiance MXFP4's codes
|
||||
* scale u8 [1 x 32] e8m0 per group, the adaptive bias already folded into the stored byte
|
||||
* meta u8 [1 x 32] one byte a group: subgroup s = columns [8s, 8s+8) in bits [2s, 2s+2)
|
||||
*
|
||||
* The exact element is e2m1mag[c&7] . sign(c) . 2^(scale-127) . (1 + k_s/4). What the kernels read
|
||||
* is the mxfp4 arrangement with the meta plane riding the stored weight's tail, in the scale
|
||||
* plane's [K/32][N] order: codes in fragment order, then K/32 rows of N meta bytes, so both GEMM
|
||||
* rows read it with the exponents' own geometry (r4d_gemm_m2xfp4a8_*.hip). b_ref stays each row's
|
||||
* largest exponent byte, the same derivation a reader of the plane could compute -- and it is what
|
||||
* bounds the fold: d >= 0 for every block, so the largest e4m3 a table cell holds is the x1.75
|
||||
* magnitude 10.5 scaled by 2^-d, a normal at every d >= 0.
|
||||
*
|
||||
* Anything else is refused: this kernel library decodes one scheme, and a weight whose meta plane
|
||||
* said something else would decode to other numbers.
|
||||
*
|
||||
* A rotated weight (ParoQuant's M2XFP4) carries the same three planes in the basis its "givens"
|
||||
* transform names, with the rotation's tables beside them -- the rotated MXFP4 weight's shape plus
|
||||
* the metadata plane. The GEMM reads the planes as for an unrotated weight; the rotation is
|
||||
* applied to the activation (givens_dense_quant), whose tables are separate weight operands. */
|
||||
namespace {
|
||||
/* The scheme's three planes, whichever kind of weight carries them. */
|
||||
bool m2_planes(const RadEncoding* enc) {
|
||||
if (!enc || !rad_enc_is(enc, "m2xfp4")) return false;
|
||||
if (enc->plane[0].dtype != RAD_FP4E2M1 || enc->plane[0].block[0] != 1 ||
|
||||
enc->plane[0].block[1] != 1)
|
||||
return false;
|
||||
const int s = rad_enc_find(enc, "scale"), m = rad_enc_find(enc, "meta");
|
||||
if (s < 0 || m < 0) return false;
|
||||
if (enc->plane[s].dtype != RAD_E8M0 || enc->plane[s].kind != RAD_PLANE_TILED ||
|
||||
enc->plane[s].block[0] != 1 || enc->plane[s].block[1] != R4D_MXFP4_GROUP)
|
||||
return false;
|
||||
if (enc->plane[m].dtype != RAD_U8 || enc->plane[m].kind != RAD_PLANE_TILED ||
|
||||
enc->plane[m].block[0] != 1 || enc->plane[m].block[1] != R4D_MXFP4_GROUP)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* A rotated one: the three planes in the basis of a "givens" transform, whose tables are views of
|
||||
* the weight's planes. Only the presence and the dtype of the tables is checked here (the arch
|
||||
* declares them as operands the rotation op reads); any other transform would decode to other
|
||||
* numbers, so it is refused. */
|
||||
bool m2_paro_enc(const RadEncoding* enc, long long K) {
|
||||
if (!enc || std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) return false;
|
||||
if (enc->n_planes < 6 || !rad_enc_valid(enc) || !m2_planes(enc)) return false;
|
||||
const int p = rad_enc_find(enc, "t.pairs"), an = rad_enc_find(enc, "t.angle"),
|
||||
sc = rad_enc_find(enc, "t.scale");
|
||||
if (p < 0 || an < 0 || sc < 0) return false;
|
||||
if (enc->plane[p].dtype != RAD_I32 || enc->plane[an].dtype != RAD_F32 ||
|
||||
enc->plane[sc].dtype != RAD_F32)
|
||||
return false;
|
||||
/* The quantiser rotates whole groups of 128 columns, one scale per group. */
|
||||
return K % 128 == 0 && enc->plane[p].extent[1] == K;
|
||||
}
|
||||
|
||||
int m2_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out, WGeom* gout) {
|
||||
if (!out || !pl) return RAD_E_INVAL;
|
||||
WGeom g;
|
||||
int rc = wgeom(p, n_p, R4D_MXFP4_GROUP, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (g.group != R4D_MXFP4_GROUP || g.K % 16) return RAD_E_SHAPE;
|
||||
if (!m2_planes(enc)) return RAD_E_DTYPE;
|
||||
const bool plain = !enc->transform[0] && enc->n_planes == 3;
|
||||
if (!plain && !m2_paro_enc(enc, g.K)) return RAD_E_DTYPE;
|
||||
if (gout) *gout = g;
|
||||
const long long nblk = g.K / R4D_MXFP4_GROUP;
|
||||
if (operand == Q_BSCALE || operand == Q_BREF) {
|
||||
if (!selects(enc, sel, n, "scale") || !dims(pl[0], g.N, nblk)) return RAD_E_SHAPE;
|
||||
if (operand == Q_BSCALE) fill(out, "r4d.mxfp4.e8m0", R4D_DT_E8M0, nblk, g.N, nblk * g.N);
|
||||
else fill(out, "r4d.mxfp4.wref", R4D_DT_E8M0, g.N, 1, g.N);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (operand != Q_B) return RAD_E_UNSUPPORTED;
|
||||
/* The weight operand takes codes and meta: the codes go to fragment order, the meta to the
|
||||
* stored blob's tail (rad_arch's decl_view names both planes). */
|
||||
if (!selects(enc, sel, n, "codes", "meta") || !dims(pl[0], g.N, g.K) ||
|
||||
!dims(pl[1], g.N, nblk))
|
||||
return RAD_E_SHAPE;
|
||||
fill(out, "r4d.m2xfp4.frag.g32.meta", R4D_DT_M2XFP4_FRAG, g.N, g.K,
|
||||
g.N * g.K / 2 + nblk * g.N);
|
||||
return RAD_OK;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int r4d_rad_layout_m2xfp4(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel,
|
||||
const RadTensor* pl, int n, RadLayout* out) {
|
||||
return m2_enc_layout(p, n_p, operand, enc, sel, pl, n, out, nullptr);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_relayout_m2xfp4(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel, const RadTensor* pl,
|
||||
int n, void* dst, int64_t dst_bytes) {
|
||||
RadLayout L;
|
||||
WGeom g;
|
||||
const int rc = m2_enc_layout(p, n_p, operand, enc, sel, pl, n, &L, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (dst_bytes != L.bytes) return RAD_E_SHAPE;
|
||||
std::memset(dst, 0, (size_t)dst_bytes);
|
||||
const long long nblk = g.K / R4D_MXFP4_GROUP;
|
||||
uint8_t* d = (uint8_t*)dst;
|
||||
if (operand == Q_BSCALE || operand == Q_BREF) {
|
||||
const uint8_t* e = pdata(pl[0]);
|
||||
for (long long nn = 0; nn < g.N; ++nn) {
|
||||
uint8_t mx = 0;
|
||||
for (long long b = 0; b < nblk; ++b) {
|
||||
const uint8_t v = e[nn * nblk + b];
|
||||
if (operand == Q_BSCALE) d[b * g.N + nn] = v;
|
||||
if (v > mx) mx = v;
|
||||
}
|
||||
if (operand == Q_BREF) d[nn] = mx;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* Codes to fragment order (mx_slot, as r4d_rad_relayout_mxfp4), then the meta plane appended:
|
||||
* canonical [N][K/32] read into stored [K/32][N]. */
|
||||
const uint8_t* meta = pdata(pl[1]);
|
||||
uint8_t* md = d + g.N * g.K / 2;
|
||||
for (long long nn = 0; nn < g.N; ++nn) {
|
||||
const uint8_t* row = pdata(pl[0]) + nn * (g.K / 2);
|
||||
for (long long k = 0; k < g.K; ++k) {
|
||||
const uint8_t code = (uint8_t)((row[k >> 1] >> (4 * (k & 1))) & 0xF);
|
||||
const long long idx = mx_slot(g, nn, k);
|
||||
if (k & 1) d[idx] = (uint8_t)((d[idx] & 0x0Fu) | (uint32_t)(code << 4));
|
||||
else d[idx] = (uint8_t)((d[idx] & 0xF0u) | code);
|
||||
}
|
||||
for (long long b = 0; b < nblk; ++b) md[b * g.N + nn] = meta[nn * nblk + b];
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ---- the MoE experts. The weight is staged through LDS, so it is not permuted: the int4 plane is
|
||||
* the canonical one with each dword's nibbles reordered for the expansion (byte b holds element b
|
||||
* low and element b+4 high), and the fp8 plane is the canonical one unchanged. `w4a8h` is the same
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// Shared device code for the M2XFP4 GEMMs (r4d_gemm_m2xfp4a8_decode, r4d_gemm_m2xfp4a8_tiled):
|
||||
// the folded-magnitude table and the eight-element unpack that reads it. The M2 analogue of
|
||||
// r4d_mxfp4.h: the same e2m1 codes and E8M0 exponents, plus one more per-group byte of weight-side
|
||||
// Sg-EM metadata (arXiv 2601.19213 §4.4.2), which folds the same way -- through a table, with a
|
||||
// v_perm_b32 per half-word.
|
||||
//
|
||||
// The container ("m2xfp4", the quantiser's scheme) stores, per group of 32 K, an E8M0 exponent byte
|
||||
// whose adaptive bias b in {-1,0,1} is already folded in, and a meta byte holding one two-bit
|
||||
// subgroup multiplier k_s per eight columns, s = columns [8s, 8s+8) of the group: the stored byte's
|
||||
// bits [2s, 2s+2). The exact weight is
|
||||
//
|
||||
// w = e2m1mag[c & 7] * sign(c) * 2^(scale - 127) * (1 + k_s / 4)
|
||||
//
|
||||
// with e2m1mag = {0, .5, 1, 1.5, 2, 3, 4, 6} and k -> {1.0, 1.25, 1.5, 1.75}. The fold of
|
||||
// r4d_gemm_mxfp4a8_nt_m64.hip applies to it unchanged: d = Wref[n] - E8M0[n][blk] goes through the
|
||||
// table, 2^(Wref[n]-127) once in the epilogue. Wref[n] is still the row's largest exponent byte,
|
||||
// so d >= 0 holds for every block; what the meta adds is bounded the same way -- the largest
|
||||
// element a table cell holds is 6 * 1.75 * 2^-d = 10.5 * 2^-d, an E4M3 normal for every d >= 0, so
|
||||
// no cell saturates and the fold is exact in its exponent at every block.
|
||||
#pragma once
|
||||
|
||||
#include "r4d_mxfp4.h" // the fold clamp r4d_mxfp4_fold_d, the carried-scale reader, GROUP
|
||||
|
||||
#define R4D_M2XFP4_SUBGROUP 8 // K per two-bit meta multiplier: four of them per 32-column group
|
||||
|
||||
// kM2xfp4Mag[d][k] is the eight e2m1 magnitudes {0, .5, 1, 1.5, 2, 3, 4, 6} scaled by
|
||||
// (1 + k/4) * 2^-d, as packed e4m3 bytes (low word, high word), indexed by the 3-bit magnitude
|
||||
// through v_perm_b32 -- kMxfp4Mag's table with a second index. Entries are the round-to-nearest-even
|
||||
// e4m3 of the product, matching the hardware conversion.
|
||||
//
|
||||
// Exactness, per magnitude and k, in the normal range of e4m3 (every entry here down to its
|
||||
// subnormal floor behaves exactly like r4d_mxfp4.h's table one binade earlier, where the 2^-9 step
|
||||
// is coarse; the entries flush the same way and the sums they miss are invisible next to the
|
||||
// accumulator):
|
||||
// - k = 0 is r4d_mxfp4.h's kMxfp4Mag row, byte for byte.
|
||||
// - k = 1, 2: exact. The products' mantissas (1.25, 1.5 and 1.75 times a magnitude whose own
|
||||
// mantissa is 1.0 or 1.1) take at most the three e4m3 mantissa bits, at every d while the
|
||||
// value is normal.
|
||||
// - k = 3 (x1.75): the even-mantissa magnitudes {0, .5, 1, 2, 4} stay exact (1.11 x 1.0); the odd
|
||||
// ones {1.5, 3, 6} land on 1.0101, four mantissa bits, and round to the tie's even side -- 2.5,
|
||||
// 5 and 10 scaled by 2^-d. That is 2^-4.4 relative error on those elements and nothing on the
|
||||
// rest, accepted here: the CPU decode (and the reference) stay exact, and 6 * 1.75 = 10.5 at
|
||||
// d = 0 is what the row-maximum bound above has to fit, which it does.
|
||||
//
|
||||
// Static: each kernel's code object carries its own copy.
|
||||
static __device__ __constant__ unsigned int kM2xfp4Mag[16][4][2] = {
|
||||
{{0x3c383000u, 0x4c484440u}, {0x3f3a3200u, 0x4f4a4742u}, {0x413c3400u, 0x514c4944u},
|
||||
{0x423e3600u, 0x524e4a46u}},
|
||||
{{0x34302800u, 0x44403c38u}, {0x37322a00u, 0x47423f3au}, {0x39342c00u, 0x4944413cu},
|
||||
{0x3a362e00u, 0x4a46423eu}},
|
||||
{{0x2c282000u, 0x3c383430u}, {0x2f2a2200u, 0x3f3a3732u}, {0x312c2400u, 0x413c3934u},
|
||||
{0x322e2600u, 0x423e3a36u}},
|
||||
{{0x24201800u, 0x34302c28u}, {0x27221a00u, 0x37322f2au}, {0x29241c00u, 0x3934312cu},
|
||||
{0x2a261e00u, 0x3a36322eu}},
|
||||
{{0x1c181000u, 0x2c282420u}, {0x1f1a1200u, 0x2f2a2722u}, {0x211c1400u, 0x312c2924u},
|
||||
{0x221e1600u, 0x322e2a26u}},
|
||||
{{0x14100800u, 0x24201c18u}, {0x17120a00u, 0x27221f1au}, {0x19140c00u, 0x2924211cu},
|
||||
{0x1a160e00u, 0x2a26221eu}},
|
||||
{{0x0c080400u, 0x1c181410u}, {0x0f0a0500u, 0x1f1a1712u}, {0x110c0600u, 0x211c1914u},
|
||||
{0x120e0700u, 0x221e1a16u}},
|
||||
{{0x06040200u, 0x14100c08u}, {0x08050200u, 0x17120f0au}, {0x09060300u, 0x1914110cu},
|
||||
{0x0a070400u, 0x1a16120eu}},
|
||||
{{0x03020100u, 0x0c080604u}, {0x04020100u, 0x0f0a0805u}, {0x04030200u, 0x110c0906u},
|
||||
{0x05040200u, 0x120e0a07u}},
|
||||
{{0x02010000u, 0x06040302u}, {0x02010100u, 0x08050402u}, {0x02020100u, 0x09060403u},
|
||||
{0x03020100u, 0x0a070504u}},
|
||||
{{0x01000000u, 0x03020201u}, {0x01010000u, 0x04020201u}, {0x01010000u, 0x04030202u},
|
||||
{0x01010000u, 0x05040302u}},
|
||||
{{0x00000000u, 0x02010100u}, {0x00000000u, 0x02010101u}, {0x01000000u, 0x02020101u},
|
||||
{0x01000000u, 0x03020101u}},
|
||||
{{0x00000000u, 0x01000000u}, {0x00000000u, 0x01010000u}, {0x00000000u, 0x01010100u},
|
||||
{0x00000000u, 0x01010100u}},
|
||||
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x01000000u},
|
||||
{0x00000000u, 0x01000000u}},
|
||||
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u}},
|
||||
{{0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u}, {0x00000000u, 0x00000000u},
|
||||
{0x00000000u, 0x00000000u}},
|
||||
};
|
||||
|
||||
// The two-bit field of a meta byte that covers `koff`, an element offset inside a 32-column group
|
||||
// that is a multiple of R4D_M2XFP4_SUBGROUP (which the kernels' staging offsets all are): the
|
||||
// subgroup s = koff / 8, bits [2s, 2s+2). A thread whose eight elements start at koff takes this
|
||||
// shift once and one meta byte per (row, block) alongside the exponent byte.
|
||||
static __device__ __forceinline__ int r4d_m2xfp4_kshift(int koff) {
|
||||
return 2 * ((koff >> 3) & 3);
|
||||
}
|
||||
|
||||
// Eight e2m1 codes (four packed bytes, element 2j in the low nibble of byte j) -> eight e4m3 bytes
|
||||
// in k order (word 0 = elements 0..3, word 1 = 4..7), with the exponent difference `d` and the
|
||||
// subgroup multiplier `k` folded in. r4d_mxfp4_unpack8_t with the [d][k] table row; see there.
|
||||
//
|
||||
// `_t` takes a table row (t0, t1) the caller already holds, e.g. from an LDS copy (the tiled
|
||||
// kernel's sMag), which keeps the lookup off the global load counter the weight and activation
|
||||
// loads wait on.
|
||||
static __device__ __forceinline__ void r4d_m2xfp4_unpack8_t(unsigned int wv, unsigned int t0,
|
||||
unsigned int t1, unsigned int* lo,
|
||||
unsigned int* hi) {
|
||||
r4d_mxfp4_unpack8_t(wv, t0, t1, lo, hi);
|
||||
}
|
||||
static __device__ __forceinline__ void r4d_m2xfp4_unpack8(unsigned int wv, int d, int k,
|
||||
unsigned int* lo, unsigned int* hi) {
|
||||
r4d_mxfp4_unpack8_t(wv, kM2xfp4Mag[d][k][0], kM2xfp4Mag[d][k][1], lo, hi);
|
||||
}
|
||||
@@ -450,6 +450,12 @@ int r4d_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_mxfp4a8_tiled_scratch(const RadArgs*);
|
||||
int r4d_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
|
||||
/* M2XFP4 (the paper's weight-side Sg-EM): the same GEMM bands at the m2xfp4 encoding, one meta
|
||||
* plane more (r4d_layout.cpp, m2xfp4). */
|
||||
int r4d_rad_gemm_m2xfp4a8_tiled(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_m2xfp4a8_tiled_scratch(const RadArgs*);
|
||||
int r4d_rad_gemm_m2xfp4a8_decode(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_m2xfp4a8_decode_scratch(const RadArgs*);
|
||||
int r4d_rad_dequant_w4 (const RadArgs*, RadStream);
|
||||
int r4d_rad_rowtopk (const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_rowtopk_scratch(const RadArgs*);
|
||||
@@ -652,6 +658,10 @@ int r4d_rad_layout_mxfp4(const RadParam*, int, int, const RadEncoding*, const in
|
||||
const RadTensor*, int, RadLayout*);
|
||||
int r4d_rad_relayout_mxfp4(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_layout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
int r4d_rad_relayout_m2xfp4(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, void*, int64_t);
|
||||
int r4d_rad_layout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
const RadTensor*, int, RadLayout*);
|
||||
int r4d_rad_relayout_givens_pairs(const RadParam*, int, int, const RadEncoding*, const int*,
|
||||
|
||||
+56
-30
@@ -4808,6 +4808,16 @@ static const RadConstraint cGemmMxfp4A8Decode[] = {
|
||||
static const RadConstraint cGemmMxfp4A8Tiled[] = {
|
||||
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
|
||||
};
|
||||
/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): the same bands at the m2xfp4 encoding, whose dtype
|
||||
* string alone separates them -- no skinny M2 row exists, so the decode row owns M <= 128 outright
|
||||
* and the tiled row everything above, with no priority question between them (MXDEC outranks TILED
|
||||
* wherever both match, as for mxfp4a8). */
|
||||
static const RadConstraint cGemmM2xfp4A8Decode[] = {
|
||||
C_LE("M", 128), C_LE("N", 36864), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"),
|
||||
};
|
||||
static const RadConstraint cGemmM2xfp4A8Tiled[] = {
|
||||
C_GE("M", 1), C_DIV("K", 64), C_DIV("N", 16), C_IN("dtype", "m2xfp4"),
|
||||
};
|
||||
/* r4d_gemm_w8a8_tiled: the same kernel at radix 8. Its asym arm is not declared in r4d.h, so
|
||||
* `w8a8_asym` is absent from the dtype set. */
|
||||
static const RadConstraint cGemmW8A8Tiled[] = {
|
||||
@@ -4903,24 +4913,9 @@ static const RadTunable tGemmPrefill[] = {
|
||||
"compiled tile arm; 0 is BM 128 x BN 256, libr4d's own default" },
|
||||
};
|
||||
|
||||
/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from
|
||||
* M >= 2048), which needs M. */
|
||||
static const int64_t kMxTn[] = { 0, 2, 4 };
|
||||
static const RadTunable tGemmMxfp4Tiled[] = {
|
||||
{ "tn", kMxTn, NELEM(kMxTn), 0,
|
||||
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
|
||||
};
|
||||
|
||||
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
|
||||
* `nt` 1 streams the weight past the caches, 2 loads it plainly. */
|
||||
static const int64_t kMxDecKs[] = { 0, 1, 2, 4, 8, 16 };
|
||||
static const int64_t kMxDecBk[] = { 0, 64, 128 };
|
||||
static const int64_t kMxDecNt[] = { 0, 1, 2 };
|
||||
static const RadTunable tGemmMxfp4Decode[] = {
|
||||
{ "ks", kMxDecKs, NELEM(kMxDecKs), 0, "split-K workgroups a column block. 0 = the fill rule" },
|
||||
{ "bk", kMxDecBk, NELEM(kMxDecBk), 0, "K slab in bytes. 0 = 128, or 64 for a wide unsplit DTM 4" },
|
||||
{ "nt", kMxDecNt, NELEM(kMxDecNt), 0, "weight loads: 1 non-temporal, 2 plain. 0 = by weight size" },
|
||||
};
|
||||
/* The MXFP4 tiled GEMM's one axis and the MXFP4 decode GEMM's axes (with the M2XFP4 rows
|
||||
* declaring the decode set) live in r4d_args.h now, beside the cfg readers that resolve them, so
|
||||
* a kernel unit links without this declaration side. */
|
||||
|
||||
/* ------------------------------------------------------------------------ split-KV attention
|
||||
* 0 is libr4d's split law (table in r4d_attn_paged_h256_gqa6.hip), which reads num_seqs and
|
||||
@@ -7530,6 +7525,42 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, nullptr, r4d_rad_gemm_mxfp4a8_tiled, r4d_rad_gemm_mxfp4a8_tiled_scratch,
|
||||
r4d_rad_layout_mxfp4, r4d_rad_relayout_mxfp4 },
|
||||
|
||||
/* M2XFP4: the mxfp4a8 rows at the paper's weight-side Sg-EM (arXiv 2601.19213 §4.4.2) -- per 32 K
|
||||
* one more byte of weight, four two-bit subgroup multipliers, folded into the same e4m3 staging
|
||||
* bytes through r4d_m2xfp4.h's table. The bands, tunables (ks/bk/nt and tn resolve through the
|
||||
* same cfg readers) and relayout contract are the OCP rows', with the meta plane in the stored
|
||||
* weight's tail (r4d_layout.cpp, m2xfp4) and no skinny row: at these row counts the decode kernel
|
||||
* covers the whole M <= 128 band, the tiled one prefill. */
|
||||
{ "gemm_m2xfp4a8_decode", "gemm_nt_q", "gemm",
|
||||
"the M2XFP4 GEMM for the DECODE band: the mxfp4a8 decode kernel's split-K across workgroups with "
|
||||
"a fused last-arriver reduction, the weight unpacked through LDS with its per-subgroup meta "
|
||||
"multiplier, streaming weight loads",
|
||||
"M <= 128; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
|
||||
"[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the "
|
||||
"stored weight's tail; the split partial in the op's scratch",
|
||||
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias "
|
||||
"folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, "
|
||||
"bf16 C, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_MXDEC,
|
||||
ROW(cGemmM2xfp4A8Decode), ROW(tGemmMxfp4Decode), nullptr,
|
||||
nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_decode, r4d_rad_gemm_m2xfp4a8_decode_scratch,
|
||||
r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 },
|
||||
|
||||
{ "gemm_m2xfp4a8_tiled", "gemm_nt_q", "gemm",
|
||||
"the M2XFP4 GEMM tiled for PREFILL row counts: the mxfp4a8 tiled kernel's 256-row block, the "
|
||||
"activation re-tiled into the op's scratch, the weight with its meta multipliers unpacked once "
|
||||
"per K slab into LDS",
|
||||
"any M; N a multiple of 16; K a multiple of 64; the skinny kernel's fragment-order weight, "
|
||||
"[K/32][N] E8M0 exponents and per-row reference exponent, and the [K/32][N] meta plane in the "
|
||||
"stored weight's tail; the re-tiled activation in the op's scratch",
|
||||
"e4m3 A with an f32 scale per row or per (row, 128), e2m1 W with an E8M0 scale per 32 K (bias "
|
||||
"folded) and a two-bit multiplier per 8 K folded into the element against a per-row reference, "
|
||||
"bf16 C, fp32 accumulate",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_TILED,
|
||||
ROW(cGemmM2xfp4A8Tiled), ROW(tGemmMxfp4Tiled), nullptr,
|
||||
nullptr, nullptr, r4d_rad_gemm_m2xfp4a8_tiled, r4d_rad_gemm_m2xfp4a8_tiled_scratch,
|
||||
r4d_rad_layout_m2xfp4, r4d_rad_relayout_m2xfp4 },
|
||||
|
||||
/* Band read off the entry point's own rejection tests. */
|
||||
{ "gemm_w4a8_prefill", "gemm_nt_q", "gemm",
|
||||
"the 4-bit GEMM for PREFILL row counts, where the matrix pipe rather than the weight stream is "
|
||||
@@ -9389,10 +9420,11 @@ extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
* every collective the peer flags and exchange buffers the all-reduces own
|
||||
*
|
||||
* gemm_fp8a8_nt_m16's finisher counters are keyed on the stream and the output;
|
||||
* gemm_mxfp4a8_decode's split partial is the op's scratch and its arrival counters are keyed on the
|
||||
* output alone; router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken
|
||||
* at init, one per declared op and band). Concurrent launches never share these, so those three
|
||||
* rows are concurrent. A new row with stream-ordered state belongs in the list above.
|
||||
* gemm_mxfp4a8_decode's and gemm_m2xfp4a8_decode's split partial is the op's scratch and their
|
||||
* arrival counters are keyed on the output alone (the M2 row keeps its own counter blocks,
|
||||
* m2d_out_ctr); router_gemm_topk_scatter_bf16's arrival counter belongs to its op instance (taken
|
||||
* at init, one per declared op and band). Concurrent launches never share these, so those rows are
|
||||
* concurrent. A new row with stream-ordered state belongs in the list above.
|
||||
*
|
||||
* lora_* ordered on purpose: the core appends them behind the GEMM whose `y` they
|
||||
* update and refills the pools they read between steps with its own copies,
|
||||
@@ -9545,14 +9577,8 @@ extern "C" void r4d_cfg_tiled(const RadArgs* a, R4dTileCfg* out) {
|
||||
extern "C" void r4d_cfg_prefill(const RadArgs* a, R4dTileCfg* out) {
|
||||
tile_bmbn(TUNE(a, tGemmPrefill, "tile"), 1, out);
|
||||
}
|
||||
extern "C" void r4d_cfg_mxfp4_decode(const RadArgs* a, R4dMxDecCfg* out) {
|
||||
out->ks = TUNE(a, tGemmMxfp4Decode, "ks");
|
||||
out->bk = TUNE(a, tGemmMxfp4Decode, "bk");
|
||||
out->nt = TUNE(a, tGemmMxfp4Decode, "nt");
|
||||
}
|
||||
extern "C" void r4d_cfg_mxfp4_tiled(const RadArgs* a, R4dMxTileCfg* out) {
|
||||
out->tn = TUNE(a, tGemmMxfp4Tiled, "tn");
|
||||
}
|
||||
/* r4d_cfg_mxfp4_decode and r4d_cfg_mxfp4_tiled are inline in r4d_args.h, beside their tables and
|
||||
* the tune reader, so the kernel units carry them without this declaration side. */
|
||||
extern "C" void r4d_cfg_split(const RadArgs* a, R4dSplitCfg* out) {
|
||||
out->splits = TUNE(a, tAttnSplit, "splits");
|
||||
}
|
||||
|
||||
@@ -4386,6 +4386,147 @@ static void mxfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_
|
||||
}
|
||||
|
||||
|
||||
/* The M2XFP4 rows (r4d_gemm_m2xfp4a8_*.hip): mxfp4a8_numeric's shape checks at the m2xfp4
|
||||
* encoding -- a third plane of per-subgroup multipliers, whose every byte value is valid, drawn
|
||||
* full range so k = 3 is in regular rotation, beside the bias-folded exponents. The bound is the
|
||||
* mxfp4 row's plus the table's accepted k = 3 rounding: a quarter of the weights at up to 2^-4.4
|
||||
* each is about 1.2% of a whole dot, so 4e-2 holds the same margin the 1e-2 does there. The
|
||||
* relayout is exercised for real: the weight operand takes codes and meta, and the stored blob the
|
||||
* launch reads is this hook's output. */
|
||||
static void m2xfp4a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
|
||||
int tn, bool ablk = false, std::vector<RadParam> extra = {},
|
||||
int64_t pb1 = 0, int64_t pb2 = 0) {
|
||||
if (!sel(row)) return;
|
||||
const PartCut cut(N, pb1, pb2);
|
||||
const int parts = cut.parts;
|
||||
char nm[160];
|
||||
std::string ex;
|
||||
for (const RadParam& p : extra) ex += std::string(" ") + p.key + "=" + std::to_string(p.ival);
|
||||
if (parts > 1) ex += " parts=" + std::to_string(parts);
|
||||
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld tn=%d%s%s", row, (long long)M,
|
||||
(long long)N, (long long)K, tn, ablk ? " ascale=row x 128" : "", ex.c_str());
|
||||
const RadKernelInfo* r = find(pl, row);
|
||||
if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; }
|
||||
const int64_t nblk = K / 32;
|
||||
|
||||
Planes p;
|
||||
rad_enc_clear(&p.enc);
|
||||
rad_enc_copy_str(p.enc.scheme, "m2xfp4");
|
||||
rad_enc_add_plane(&p.enc, "codes", RAD_FP4E2M1, 1, 1);
|
||||
rad_enc_add_plane(&p.enc, "scale", RAD_E8M0, 1, 32);
|
||||
rad_enc_add_plane(&p.enc, "meta", RAD_U8, 1, 32);
|
||||
p.size(N, K);
|
||||
const int ic = p.find("codes"), is = p.find("scale"), im = p.find("meta");
|
||||
if (ic < 0 || is < 0 || im < 0) { ok(nm, false, "encoding has no m2xfp4 planes"); return; }
|
||||
/* codes and exponents as mxfp4_fill draws them (deep: exponents the fold's subnormal floor
|
||||
* reaches), the meta full range so every multiplier and every subgroup phase appears */
|
||||
mxfp4_fill(p, ic, is, N, K, 0x71u, true);
|
||||
for (int64_t i = 0; i < (int64_t)p.data[(size_t)im].size(); ++i)
|
||||
p.data[(size_t)im][(size_t)i] = (uint8_t)st_mix32((uint32_t)i ^ 0x4d2eu);
|
||||
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 32) };
|
||||
std::vector<uint8_t> wq, ws, wr;
|
||||
const int rw = stored(r, lp, 2, p, { "codes", "meta" }, &wq);
|
||||
const int rs = stored(r, lp, 3, p, { "scale" }, &ws);
|
||||
const int rr = stored(r, lp, 6, p, { "scale" }, &wr);
|
||||
if (rw != RAD_OK || rs != RAD_OK || rr != RAD_OK) {
|
||||
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs) + "/" +
|
||||
std::to_string(rr));
|
||||
return;
|
||||
}
|
||||
|
||||
const int64_t nkb = (K + 127) / 128, asc = ablk ? nkb : 1;
|
||||
const int64_t PK = parts * K, PA = parts * asc; /* a row of `a`, and of its scale */
|
||||
std::vector<uint8_t> ha((size_t)(M * PK));
|
||||
std::vector<float> av((size_t)(M * PK)), as((size_t)(M * PA));
|
||||
for (int64_t i = 0; i < M; ++i) {
|
||||
for (int64_t c = 0; c < PA; ++c) {
|
||||
const uint32_t h = st_mix32((uint32_t)(i * PA + c) ^ 0xa5u);
|
||||
as[(size_t)(i * PA + c)] =
|
||||
ablk ? ((i + c) % 11 == 5 ? 0.0f : 0.002f * (float)(1 + h % 97))
|
||||
: 0.0125f * (float)(1 + h % 5);
|
||||
}
|
||||
for (int64_t k = 0; k < PK; ++k) {
|
||||
const bool zero = ablk && as[(size_t)(i * PA + (k / K) * asc + (k % K) / 128)] == 0.0f;
|
||||
const float v = zero ? 0.0f : mxfp4_act(i, k, 0x3cu);
|
||||
rad_store_f32(ha.data(), RAD_F8E4M3, i * PK + k, v);
|
||||
av[(size_t)(i * PK + k)] = rad_load_f32(ha.data(), RAD_F8E4M3, i * PK + k);
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> hy((size_t)(M * N), 0);
|
||||
void* d_a = dalloc(ha.size());
|
||||
void* d_s = dalloc(as.size() * 4);
|
||||
void* d_w = dalloc(wq.size());
|
||||
void* d_e = dalloc(ws.size());
|
||||
void* d_r = dalloc(wr.size());
|
||||
void* d_y = dalloc(hy.size() * 2);
|
||||
if (!d_a || !d_s || !d_w || !d_e || !d_r || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_s, as.data(), as.size() * 4, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_e, ws.data(), ws.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_r, wr.data(), wr.size(), hipMemcpyHostToDevice);
|
||||
std::vector<RadTensor> ts = {
|
||||
T(d_a, RAD_F8E4M3, { M, PK }),
|
||||
ablk ? T(d_s, RAD_F32, { M, PA }) : T(d_s, RAD_F32, { M }),
|
||||
T(d_w, RAD_U8, { (int64_t)wq.size() }), T(d_e, RAD_U8, { (int64_t)ws.size() }),
|
||||
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(d_r, RAD_U8, { (int64_t)wr.size() }),
|
||||
};
|
||||
absent(ts[5]);
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32),
|
||||
PS("dtype", "m2xfp4") };
|
||||
if (tn) ps.push_back(PI("tn", tn));
|
||||
if (pb1) ps.push_back(PI("pb1", pb1));
|
||||
if (pb2) ps.push_back(PI("pb2", pb2));
|
||||
for (const RadParam& p : extra) ps.push_back(p);
|
||||
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;
|
||||
if (r->scratch) {
|
||||
const int64_t sb = r->scratch(&a);
|
||||
if (sb > 0) {
|
||||
a.scratch = dalloc((size_t)sb);
|
||||
a.scratch_bytes = sb;
|
||||
if (!a.scratch) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
}
|
||||
}
|
||||
const int rc = r->launch(&a, (RadStream) nullptr);
|
||||
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
|
||||
ok(nm, false, "rc=" + std::to_string(rc));
|
||||
return;
|
||||
}
|
||||
st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost);
|
||||
|
||||
/* Every column for small N, a stride otherwise, always including the last column. The exact
|
||||
* decode: the e2m1 code, the subgroup's stored multiplier, and the folded exponent. */
|
||||
const int64_t nstep = N > 96 ? N / 96 : 1;
|
||||
double num = 0, den = 0;
|
||||
for (int64_t i = 0; i < M; ++i)
|
||||
for (int64_t n = 0; n < N; n = (n + 1 == N) ? N : std::min(n + nstep, N - 1)) {
|
||||
double acc = 0;
|
||||
const int pt = cut.part_of(n);
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
const uint8_t meta = p.data[(size_t)im][(size_t)(n * nblk + k / 32)];
|
||||
const int kk = (int)(((meta >> (2 * ((k % 32) / 8))) & 3));
|
||||
const double w =
|
||||
(double)rad_load_f32(p.data[(size_t)ic].data(), RAD_FP4E2M1, n * K + k) *
|
||||
(1.0 + kk / 4.0) *
|
||||
(double)rad_load_f32(p.data[(size_t)is].data(), RAD_E8M0, n * nblk + k / 32);
|
||||
acc += (double)av[(size_t)(i * PK + pt * K + k)] * w *
|
||||
(ablk ? (double)as[(size_t)(i * PA + pt * asc + k / 128)] : 1.0);
|
||||
}
|
||||
if (!ablk) acc *= (double)as[(size_t)i];
|
||||
const double d = (double)h_bf16(hy[(size_t)(i * N + n)]) - acc;
|
||||
num += d * d;
|
||||
den += acc * acc;
|
||||
}
|
||||
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
|
||||
char d[96];
|
||||
std::snprintf(d, sizeof d, "rel_l2 %.3e", rel);
|
||||
ok(nm, rel < 4e-2, d);
|
||||
}
|
||||
|
||||
/* What givens_numeric runs: the sequential rotation to f16, or the dense rotation with either
|
||||
* quantiser. */
|
||||
enum class GvCase { Rotate, DenseFp8, DenseI8 };
|
||||
@@ -26820,6 +26961,23 @@ static void device_phase(const Plugin& pl) {
|
||||
for (int bk : { 64, 128 })
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 96, 400, 2560, 0, true,
|
||||
{ PI("ks", ks), PI("bk", bk), PI("nt", 1) });
|
||||
/* The M2XFP4 rows: the decode band's rule and band edges, the tiled row at both widths and
|
||||
* past the tn crossover, both activation grids, and parts -- the same spread the OCP rows
|
||||
* get, at the three-plane encoding. */
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, false);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 272, 640, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 400, 2560, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 128, 512, 2560, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 5, 1040, 576, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 96, 14336, 640, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 8, 400, 2560, 0, true, {}, 128);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_decode", 40, 512, 2560, 0, true, {}, 128, 384);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 40, 272, 640, 2, false);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 4, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 2100, 512, 2560, 0, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 272, 576, 2, true);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 400, 640, 2, true, {}, 192);
|
||||
m2xfp4a8_numeric(pl, "gemm_m2xfp4a8_tiled", 300, 34816, 5120, 0, true, {}, 17408);
|
||||
for (int ks : { 1, 2, 4, 8, 16 })
|
||||
for (int bk : { 64, 128 })
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_decode", 24, 400, 2560, 0, true,
|
||||
|
||||
Reference in new issue
Block a user