Archived
libr4d: GLM-5.3's kernels -- mHC, KDA, the DSA indexer, MLA, f32-scaled FP8, MXFP4 experts
The device rows for GLM-5.3-Flash's ops, at its geometry and at TP4 and TP8 slices: - mhc_pre / mhc_post / mhc_contract, and mhc_pre_partial / mhc_pre_finish, which run mhc_pre's own projection and finishing kernels with its chunk-sum order, so the pair is byte-identical to mhc_pre at n 4096, hc 4, chunk 2048. - kda_update_k128_v128_bf16, one, two or four value rows a wave, both state forms. - dsa_pool_fp8, dsa_query_fp8 and dsa_score_fp8 (fp8 WMMA, 32 heads of 128). - mla_attn: a matrix row whose WMMA tile holds a query's heads, or pairs eight heads of two neighbouring queries over the union of their page tables, above the wave row; mla_project with up to eight rows a thread or wave. - gemm_nt_f32 and router_sigmoid_topk in tiled and one-wave-a-row forms; gemm_fp8a8_f32scale and moe_gemm_fp8a8_f32scale read f32 block scales in place; moe_gemm_mxfp4a8 decodes e2m1 into exact E4M3 bytes for fp8 WMMA, with an expert-major decode form and a wide prefill form. - swiglu_clamped, and the device-only fusions of GLM's MoE block: swiglu_clamped_quant_fp8, router_sigmoid_topk_scatter, and moe_scatter_inv / moe_gather_inv, which pass the gather's slot table from the sort instead of rebuilding it. moe_gather takes f32 routing weights in its column-per-thread kernel. The sort and the gather kernels move from r4d_moe.hip into r4d_moe_sort.h and r4d_moe_gather.h, so the fused router and gather instantiate the same code. Every form that replaces another gives its bytes: tests/r4d_emu runs the kernels on the host (test_f32, test_fp8f32, test_kda, test_mhc, test_mla, test_moefuse, test_moemx), r4d_selftest compares them on a card against libref and against each other, and plugin_test pins the mla_attn band. docs/OPS.md states what libr4d serves. Co-Authored-By: John McDonough <18016200+JohnCMcDonough@users.noreply.github.com>
This commit is contained in:
1 parent
da77f86332
commit
78c58841bf
31 files changed
+12371
-302
No files matched your search
+20
-13
@@ -357,14 +357,16 @@ endif()
|
||||
# ================================================================== libr4d's kernels, on the host
|
||||
#
|
||||
# Some libr4d ops (the sandwich-norm joins, expert_scale) have no libref oracle by design
|
||||
# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of six units written
|
||||
# against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins,
|
||||
# expert_scale, the QSA block selection, whose four kernels a card-less build otherwise never
|
||||
# runs, and the runtime-LoRA pair. emu/hip/hip_runtime.h supplies the HIP names, each GPU thread
|
||||
# is a fiber, and __syncthreads and cross-lane ops are barriers (one not reached uniformly is
|
||||
# reported as a deadlock). Checked against ports of libref's ref_attn_paged and ref_qsa_select,
|
||||
# the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit, and for the
|
||||
# LoRA pair libref itself when the test can load it.
|
||||
# (docs/OPS.md), so rad-kbench never checks them. r4d_emu runs the source of thirteen units
|
||||
# written against r4d_launch.h on the host: the windowed paged attention, pair_argmax, the joins,
|
||||
# expert_scale, the QSA block selection, the runtime-LoRA pair, the F32 routing projection's tile
|
||||
# forms, GLM's mHC read with its chunk split, the F32-scale E4M3 GEMM's forms, GLM's KDA
|
||||
# recurrence, the MXFP4 expert GEMM's forms, the MLA matrix row's pairings and GLM's MoE decode
|
||||
# fusions, whose kernels a card-less build otherwise never runs. emu/hip/hip_runtime.h supplies the
|
||||
# HIP names, each GPU thread is a fiber, and __syncthreads and cross-lane ops are barriers (one not
|
||||
# reached uniformly is reported as a deadlock). Checked against ports of libref's ref_attn_paged and
|
||||
# ref_qsa_select, the host arithmetic in ref_host.cpp, for the joins the unfused chain bit for bit,
|
||||
# and for the LoRA pair libref itself when the test can load it.
|
||||
#
|
||||
# Requires clang (ext_vector_type) and x86-64 (SysV fiber switch in inline assembly). With a clang
|
||||
# C++ compiler the .hip files build here as C++ (`-x c++`; the property is per directory, so
|
||||
@@ -376,8 +378,10 @@ set(R4D_DIR ${CMAKE_SOURCE_DIR}/libr4d)
|
||||
set(R4D_EMU ${CMAKE_CURRENT_SOURCE_DIR}/r4d_emu)
|
||||
set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_f32.hip
|
||||
${R4D_DIR}/r4d_norm_join_bf16.hip ${R4D_DIR}/r4d_expert_scale_bf16.hip
|
||||
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora)
|
||||
${R4D_DIR}/r4d_qsa_select_bf16.hip ${R4D_DIR}/r4d_lora_bf16.hip ${R4D_DIR}/r4d_glm.hip
|
||||
${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_fp8_f32scale.hip ${R4D_DIR}/r4d_kda.hip
|
||||
${R4D_DIR}/r4d_moe_mxfp4.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip)
|
||||
set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse)
|
||||
set(R4D_EMU_BUILT OFF)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# No fiber switch for this ISA.
|
||||
@@ -413,7 +417,10 @@ else()
|
||||
set(objs "")
|
||||
foreach(src ${R4D_EMU_HIP} ${R4D_EMU}/ref_host.cpp ${R4D_EMU}/emu/emu.cpp
|
||||
${R4D_EMU}/test_attn.cpp ${R4D_EMU}/test_pick.cpp ${R4D_EMU}/test_norm.cpp
|
||||
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp)
|
||||
${R4D_EMU}/test_escale.cpp ${R4D_EMU}/test_qsa.cpp ${R4D_EMU}/test_lora.cpp
|
||||
${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_fp8f32.cpp
|
||||
${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_moemx.cpp ${R4D_EMU}/test_mla.cpp
|
||||
${R4D_EMU}/test_moefuse.cpp)
|
||||
get_filename_component(stem ${src} NAME_WE)
|
||||
set(lang "")
|
||||
if(src MATCHES "\\.hip$")
|
||||
@@ -450,7 +457,7 @@ else()
|
||||
endif()
|
||||
endif()
|
||||
if(R4D_EMU_BUILT)
|
||||
foreach(t pick norm escale qsa lora)
|
||||
foreach(t pick norm escale qsa lora f32 mhc fp8f32 kda moemx mla moefuse)
|
||||
add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t})
|
||||
endforeach()
|
||||
# The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel,
|
||||
@@ -460,7 +467,7 @@ if(R4D_EMU_BUILT)
|
||||
COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_attn --shard ${k}/3)
|
||||
endforeach()
|
||||
set_tests_properties(r4d_emu_attn_shard0 r4d_emu_attn_shard1 r4d_emu_attn_shard2 r4d_emu_pick
|
||||
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora
|
||||
r4d_emu_norm r4d_emu_escale r4d_emu_qsa r4d_emu_lora r4d_emu_mla r4d_emu_moefuse
|
||||
PROPERTIES LABELS "r4d_emu" TIMEOUT ${RAD_TEST_TIMEOUT})
|
||||
# The LoRA pair has a libref oracle, and the test holds the emulated kernels to it when it can
|
||||
# load one -- expand bit for bit, shrink to its bound.
|
||||
|
||||
@@ -995,6 +995,25 @@ TEST(libr4d_resolves_the_vision_attention_without_a_window) {
|
||||
for (const Band& x : b) CHECK_EQ(picked(x.dom[RAD_DOMAIN_DEVICE].row), "attn_vit_h72_bf16");
|
||||
}
|
||||
|
||||
/* GLM-5.3-Flash's MLA at eight heads a rank: the matrix row ranks above the wave row and serves
|
||||
* every M up to its bound, a decode step's rows and a prefill chunk alike. RADIANCE_MLA_MATRIX_MAX_M
|
||||
* lowers that bound, which this case does not cover. */
|
||||
TEST(libr4d_resolves_the_mla_attention_by_rows) {
|
||||
const std::string so = libr4d();
|
||||
if (so.empty()) return;
|
||||
if (std::getenv("RADIANCE_MLA_MATRIX_MAX_M")) return;
|
||||
Registry r;
|
||||
CHECK(r.load_plugin(so, 0) >= 0);
|
||||
Geometry g;
|
||||
g.set_i("latent_dim", 512);
|
||||
g.set_i("heads", 8);
|
||||
g.set_i("blocks", 513);
|
||||
g.set_i("block_size", 4);
|
||||
g.set_s("dtype", "bf16");
|
||||
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 2048, g)), "2048:mla_attn_matrix_bf16 ");
|
||||
CHECK_EQ(band_names(r.build_bands("mla_attn", "M", 1, 48, g)), "48:mla_attn_matrix_bf16 ");
|
||||
}
|
||||
|
||||
/* ================================================================== constraints that are not intervals */
|
||||
namespace {
|
||||
std::string extra_dir() { return home() + "/testkernels/extra"; }
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
#include "rad_plugin.h"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
@@ -47,11 +48,12 @@ struct Sched {
|
||||
std::vector<Fiber> f;
|
||||
void* main_sp = nullptr;
|
||||
int cur = -1, nthreads = 0;
|
||||
EmuIdx bid{};
|
||||
EmuIdx bid{}, bdim{}, gdim{};
|
||||
void (*body)(void*) = nullptr;
|
||||
void* ctx = nullptr;
|
||||
/* block barrier */
|
||||
/* block barrier; or_acc[g % 3] collects __syncthreads_or's predicates at generation g */
|
||||
int arrive = 0; unsigned gen = 0;
|
||||
int or_acc[3] = {};
|
||||
/* wave barriers and exchange slots, double-buffered by parity */
|
||||
int warrive[64] = {}; unsigned wgen[64] = {};
|
||||
int slot[64][2][32] = {};
|
||||
@@ -82,15 +84,26 @@ extern "C" void emu_entry();
|
||||
|
||||
EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; }
|
||||
EmuIdx& emu_block_idx() { return S.bid; }
|
||||
EmuIdx& emu_block_dim() { return S.bdim; }
|
||||
EmuIdx& emu_grid_dim() { return S.gdim; }
|
||||
|
||||
void __syncthreads() {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.gen;
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; }
|
||||
/* Clearing the next generation's slot here, as the barrier completes, keeps it ahead of every
|
||||
* write to it (threads arrive at g + 1 only after g completes) and behind every read of the
|
||||
* slot it shares a residue with (g - 2's, read before arriving at g - 1). */
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; S.or_acc[(g + 1) % 3] = 0; ++S.gen; return; }
|
||||
me.waiting = 1;
|
||||
while (S.gen == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
int __syncthreads_or(int p) {
|
||||
const unsigned g = S.gen;
|
||||
if (p) S.or_acc[g % 3] = 1;
|
||||
__syncthreads();
|
||||
return S.or_acc[g % 3];
|
||||
}
|
||||
|
||||
static void wave_barrier(int w) {
|
||||
Fiber& me = S.f[S.cur];
|
||||
@@ -165,6 +178,23 @@ static _Float16 g_ha[64][2][32][8], g_hb[64][2][32][8];
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c) {
|
||||
return emu_wmma(g_ha, g_hb, a, b, c, [](_Float16 v) { return (float)v; });
|
||||
}
|
||||
namespace {
|
||||
struct Bytes8 {
|
||||
uint8_t v[8];
|
||||
uint8_t operator[](int e) const { return v[e]; }
|
||||
};
|
||||
}
|
||||
static uint8_t g_qa[64][2][32][8], g_qb[64][2][32][8];
|
||||
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c) {
|
||||
Bytes8 pa, pb;
|
||||
std::memcpy(pa.v, &a, 8);
|
||||
std::memcpy(pb.v, &b, 8);
|
||||
return emu_wmma(g_qa, g_qb, pa, pb, c, [](uint8_t v) { return rad_fp8e4m3_to_f32(v); });
|
||||
}
|
||||
emu_v8i emu_wmma_iu8(bool, emu_v2i, bool, emu_v2i, emu_v8i, bool) {
|
||||
std::fprintf(stderr, "emu: v_wmma_i32_16x16x16_iu8 is not emulated\n");
|
||||
std::abort();
|
||||
}
|
||||
unsigned emu_ballot(bool p) {
|
||||
int l;
|
||||
const int* s = exchange(p ? 1 : 0, &l, kOpBallot);
|
||||
@@ -236,6 +266,8 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
}
|
||||
lds_reserve(dyn_lds);
|
||||
S.body = body; S.ctx = ctx; S.nthreads = n;
|
||||
S.bdim = EmuIdx{block.x, block.y, block.z};
|
||||
S.gdim = EmuIdx{grid.x, grid.y, grid.z};
|
||||
S.f.resize(n);
|
||||
for (auto& f : S.f) if (!f.stack) f.stack.reset(new char[kStack]);
|
||||
for (unsigned bz = 0; bz < grid.z; ++bz)
|
||||
@@ -244,6 +276,7 @@ void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t
|
||||
S.bid = EmuIdx{bx, by, bz};
|
||||
std::memset(g_lds, 0xA5, dyn_lds);
|
||||
S.arrive = 0; S.gen = 0;
|
||||
for (int& a : S.or_acc) a = 0;
|
||||
for (int w = 0; w < 64; ++w) { S.warrive[w] = 0; S.wgen[w] = 0; }
|
||||
for (int t = 0; t < n; ++t) {
|
||||
Fiber& f = S.f[t];
|
||||
|
||||
@@ -15,8 +15,12 @@
|
||||
#define __device__
|
||||
#define __host__
|
||||
#define __shared__ static
|
||||
#define __constant__
|
||||
#define __forceinline__ inline
|
||||
#define __launch_bounds__(n)
|
||||
/* R4D_WAVES (r4d_common.h) names a kernel attribute; on the host it becomes an empty attribute */
|
||||
#define amdgpu_waves_per_eu(lo, hi)
|
||||
#define __align__(n) __attribute__((aligned(n)))
|
||||
|
||||
struct dim3 {
|
||||
unsigned x, y, z;
|
||||
@@ -29,6 +33,25 @@ inline hipError_t hipGetLastError() { return 0; }
|
||||
/* one device, with the R9700's 64 KiB of LDS a workgroup, which launchers size dynamic LDS by */
|
||||
struct hipDeviceProp_t { size_t sharedMemPerBlock; };
|
||||
inline hipError_t hipGetDevice(int* d) { *d = 0; return hipSuccess; }
|
||||
/* no graphs: a stream never captures */
|
||||
enum hipStreamCaptureStatus { hipStreamCaptureStatusNone = 0 };
|
||||
inline hipError_t hipStreamIsCapturing(hipStream_t, hipStreamCaptureStatus* s) {
|
||||
*s = hipStreamCaptureStatusNone;
|
||||
return hipSuccess;
|
||||
}
|
||||
/* every launch runs to completion before it returns */
|
||||
inline hipError_t hipDeviceSynchronize() { return hipSuccess; }
|
||||
/* __device__ variables are host globals, so a symbol copy is a memcpy */
|
||||
enum hipMemcpyKind { hipMemcpyHostToDevice = 1, hipMemcpyDeviceToHost = 2 };
|
||||
#define HIP_SYMBOL(s) (&(s))
|
||||
inline hipError_t hipMemcpyFromSymbol(void* dst, const void* sym, size_t n, size_t off, hipMemcpyKind) {
|
||||
std::memcpy(dst, (const char*)sym + off, n);
|
||||
return hipSuccess;
|
||||
}
|
||||
inline hipError_t hipMemcpyToSymbol(const void* sym, const void* src, size_t n, size_t off, hipMemcpyKind) {
|
||||
std::memcpy((char*)sym + off, src, n);
|
||||
return hipSuccess;
|
||||
}
|
||||
inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
|
||||
*p = hipDeviceProp_t{};
|
||||
p->sharedMemPerBlock = 64 * 1024;
|
||||
@@ -38,9 +61,15 @@ inline hipError_t hipGetDeviceProperties(hipDeviceProp_t* p, int) {
|
||||
struct EmuIdx { unsigned x, y, z; };
|
||||
EmuIdx& emu_thread_idx();
|
||||
EmuIdx& emu_block_idx();
|
||||
EmuIdx& emu_block_dim();
|
||||
EmuIdx& emu_grid_dim();
|
||||
#define threadIdx (emu_thread_idx())
|
||||
#define blockIdx (emu_block_idx())
|
||||
#define blockDim (emu_block_dim())
|
||||
#define gridDim (emu_grid_dim())
|
||||
void __syncthreads();
|
||||
/* the block barrier, returning whether any thread passed a nonzero predicate */
|
||||
int __syncthreads_or(int p);
|
||||
int emu_bpermute(int addr, int v);
|
||||
int emu_readlane(int v, int lane);
|
||||
#define __builtin_amdgcn_ds_bpermute(a, v) emu_bpermute((a), (v))
|
||||
@@ -73,6 +102,14 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
|
||||
return r;
|
||||
}
|
||||
#define __builtin_amdgcn_perm(a, b, s) emu_perm((a), (b), (s))
|
||||
/* HIP's __byte_perm: result byte i is the byte of {y, x} (x low) that the low three bits of
|
||||
* nibble i of s name; only the low four nibbles are read */
|
||||
inline unsigned __byte_perm(unsigned x, unsigned y, unsigned s) {
|
||||
const unsigned long long d = ((unsigned long long)y << 32) | x;
|
||||
unsigned r = 0;
|
||||
for (int i = 0; i < 4; ++i) r |= (unsigned)((d >> (8 * ((s >> (4 * i)) & 7u))) & 0xffu) << (8 * i);
|
||||
return r;
|
||||
}
|
||||
/* s_barrier is the workgroup barrier. Fibers share one memory and switch only at barriers, so a
|
||||
* fence or a scheduling barrier orders nothing more. */
|
||||
#define __builtin_amdgcn_s_barrier() __syncthreads()
|
||||
@@ -81,15 +118,38 @@ inline unsigned emu_perm(unsigned a, unsigned b, unsigned sel) {
|
||||
/* LDS atomics: fibers switch only at barriers, so a plain read-modify-write is indivisible */
|
||||
template <class T>
|
||||
inline T atomicAdd(T* p, T v) { const T o = *p; *p = o + v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMin(T* p, T v) { const T o = *p; if (v < o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicMax(T* p, T v) { const T o = *p; if (v > o) *p = v; return o; }
|
||||
template <class T>
|
||||
inline T atomicCAS(T* p, T expect, T v) { const T o = *p; if (o == expect) *p = v; return o; }
|
||||
/* v_wmma_f32_16x16x16_bf16 (gfx12, wave32): A[M][K] lane M + 16 * (K / 8) element K % 8; B[K][N]
|
||||
* lane N + 16 * (K / 8) element K % 8; D[M][N] lane N + 16 * (M / 8) element M % 8 */
|
||||
typedef short emu_v8s __attribute__((ext_vector_type(8)));
|
||||
typedef float emu_v8f __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c);
|
||||
/* the __bf16 fragments of r4d_gdn_wmma.h, the same bits */
|
||||
typedef __bf16 emu_v8bf __attribute__((ext_vector_type(8)));
|
||||
inline emu_v8f emu_wmma_bf16(emu_v8bf a, emu_v8bf b, emu_v8f c) {
|
||||
return emu_wmma_bf16(__builtin_bit_cast(emu_v8s, a), __builtin_bit_cast(emu_v8s, b), c);
|
||||
}
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32_gfx12(a, b, c) emu_wmma_bf16((a), (b), (c))
|
||||
typedef _Float16 emu_v8h __attribute__((ext_vector_type(8)));
|
||||
emu_v8f emu_wmma_f16(emu_v8h a, emu_v8h b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_f16_w32_gfx12(a, b, c) emu_wmma_f16((a), (b), (c))
|
||||
/* v_wmma_f32_16x16x16_fp8_fp8 (gfx12, wave32): the bf16 form's layout with eight E4M3 bytes a
|
||||
* lane, element e in byte e. Each output is c plus its 16 products in k order: not the hardware's
|
||||
* internal order, but a function of the output's own row, column and c alone, as the hardware's
|
||||
* is, which is what a comparison of two kernels over the same fragments relies on. */
|
||||
typedef int emu_v2i __attribute__((ext_vector_type(2)));
|
||||
emu_v8f emu_wmma_fp8(emu_v2i a, emu_v2i b, emu_v8f c);
|
||||
#define __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(a, b, c) emu_wmma_fp8((a), (b), (c))
|
||||
/* v_wmma_i32_16x16x16_iu8: not emulated; reported when reached */
|
||||
typedef int emu_v8i __attribute__((ext_vector_type(8)));
|
||||
emu_v8i emu_wmma_iu8(bool sa, emu_v2i a, bool sb, emu_v2i b, emu_v8i c, bool clamp);
|
||||
#define __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32_gfx12(sa, a, sb, b, c, cl) \
|
||||
emu_wmma_iu8((sa), (a), (sb), (b), (c), (cl))
|
||||
/* global_load_tr_b128: not emulated; reported when reached */
|
||||
emu_v8s emu_load_tr_b128(const void* p);
|
||||
#define __builtin_amdgcn_global_load_tr_b128_v8i16(p) emu_load_tr_b128((const void*)(p))
|
||||
@@ -120,9 +180,34 @@ inline uint2 make_uint2(unsigned a, unsigned b) { return uint2{a, b}; }
|
||||
inline float4 make_float4(float a, float b, float c, float d) { return float4{a, b, c, d}; }
|
||||
inline float __uint_as_float(unsigned u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline float rsqrtf(float x) { return 1.0f / std::sqrt(x); } /* v_rsq_f32 is within an ulp of it */
|
||||
/* The device's fast exponential is not bit-exact to expf; here it is expf, so a test compares two
|
||||
* kernels that both take it, never a kernel against a host value of it. */
|
||||
inline float __expf(float x) { return std::exp(x); }
|
||||
inline unsigned __float_as_uint(float f) { unsigned u; std::memcpy(&u, &f, 4); return u; }
|
||||
inline float __int_as_float(int u) { float f; std::memcpy(&f, &u, 4); return f; }
|
||||
inline int __float_as_int(float f) { int u; std::memcpy(&u, &f, 4); return u; }
|
||||
/* The float shuffles over ds_bpermute, for one-dimensional blocks, within groups of `width`
|
||||
* lanes: __shfl_xor reads lane L ^ mask, __shfl lane `src`, __shfl_down lane L + delta (its own
|
||||
* value past the group's end) */
|
||||
inline float emu_shfl_from(float v, int src) {
|
||||
return __int_as_float(emu_bpermute(src << 2, __float_as_int(v)));
|
||||
}
|
||||
inline float __shfl_xor(float v, int mask, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31;
|
||||
return emu_shfl_from(v, (lane & ~(width - 1)) | ((lane ^ mask) & (width - 1)));
|
||||
}
|
||||
inline float __shfl(float v, int src, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31;
|
||||
return emu_shfl_from(v, (lane & ~(width - 1)) | (src & (width - 1)));
|
||||
}
|
||||
inline float __shfl_down(float v, unsigned delta, int width = 32) {
|
||||
const int lane = (int)threadIdx.x & 31, in_group = lane & (width - 1);
|
||||
return emu_shfl_from(v, in_group + (int)delta < width ? lane + (int)delta : lane);
|
||||
}
|
||||
/* HIP declares the classification functions in the global namespace */
|
||||
using std::isfinite;
|
||||
inline int min(int a, int b) { return a < b ? a : b; }
|
||||
inline int max(int a, int b) { return a > b ? a : b; }
|
||||
|
||||
/* one block at a time, every thread a fiber; `dyn_lds` bytes of dynamic LDS */
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx, size_t dyn_lds = 0);
|
||||
@@ -154,6 +239,9 @@ int emu_emit(const char* name, void (*k)(P...), dim3 g, dim3 b, size_t lds, cons
|
||||
}
|
||||
#define R4D_EMIT(stream, kernel, grid, block, lds, ...) \
|
||||
emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__)
|
||||
/* hipLaunchKernelGGL, for units that launch with it directly: the same call as R4D_EMIT. */
|
||||
#define hipLaunchKernelGGL(kernel, grid, block, lds, stream, ...) \
|
||||
((void)(stream), (void)emu_emit(#kernel, (kernel), (grid), (block), (size_t)(lds), __VA_ARGS__))
|
||||
/* R4D_DYN_LDS (r4d_launch.h): the launch's dynamic LDS, poisoned at each block's start and ending
|
||||
* at an inaccessible page (its start 16-byte aligned), so a read before any write shows and one
|
||||
* past the end faults */
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
/* tests/r4d_emu: gemm_nt_f32 (r4d_glm.hip) on the host SIMT emulator. Every tile form
|
||||
* (RADIANCE_F32_GEMM_TILE) must match the one-wave-per-output legacy kernel bit for bit, and the
|
||||
* legacy kernel must match its arithmetic written out here: lane l folds k = l, l+32, ... with
|
||||
* fmaf, then the xor butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding
|
||||
* stay untouched.
|
||||
*
|
||||
* router_sigmoid_topk from the same unit: the wave-per-row select must match the serial scan
|
||||
* (RADIANCE_ROUTER_SELECT=old) bit for bit, and the scan its arithmetic written out here, on
|
||||
* random and on tied ranks, with the outputs' pitch padding untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static float legacy_model(const uint16_t* x, const float* w, int k) {
|
||||
float lane[32];
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
float s = 0;
|
||||
for (int j = l; j < k; j += 32) s = std::fmaf(b2f(x[j]), w[j], s);
|
||||
lane[l] = s;
|
||||
}
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
float next[32];
|
||||
for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask];
|
||||
std::memcpy(lane, next, sizeof lane);
|
||||
}
|
||||
return lane[0];
|
||||
}
|
||||
|
||||
static void router_model(const float* lg, const float* bias, int bp, int ne, int k, int norm,
|
||||
float factor, int* ids, float* w) {
|
||||
float prob[512], rank[512], chosen[32], total = 0;
|
||||
int index[32];
|
||||
for (int e = 0; e < ne; ++e) {
|
||||
prob[e] = 1.0f / (1.0f + expf(-lg[e]));
|
||||
rank[e] = prob[e] + bias[(size_t)e * bp];
|
||||
}
|
||||
for (int j = 0; j < k; ++j) {
|
||||
int best = 0;
|
||||
for (int e = 1; e < ne; ++e)
|
||||
if (rank[e] > rank[best]) best = e;
|
||||
index[j] = best;
|
||||
chosen[j] = prob[best];
|
||||
total += chosen[j];
|
||||
rank[best] = -INFINITY;
|
||||
}
|
||||
const float mult = norm ? factor / (total + 1e-20f) : factor;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
ids[j] = index[j];
|
||||
w[j] = chosen[j] * mult;
|
||||
}
|
||||
}
|
||||
|
||||
static void router_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
struct Shape {
|
||||
int M, ne, k, norm;
|
||||
bool ties;
|
||||
};
|
||||
const Shape shapes[] = { { 1, 288, 8, 1, false }, { 6, 288, 8, 1, false },
|
||||
{ 20, 288, 8, 1, true }, { 48, 288, 8, 1, false },
|
||||
{ 6, 288, 8, 1, true }, { 5, 8, 8, 0, true },
|
||||
{ 5, 32, 32, 0, true }, { 7, 300, 8, 1, false },
|
||||
{ 3, 512, 32, 1, true } };
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.ties ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias) v = sh.ties ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
RadTensor t[4]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 4;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
auto run = [&](const char* form, std::vector<int>& ids, std::vector<float>& w) {
|
||||
ids.assign((size_t)M * ip, -77);
|
||||
w.assign((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids.data();
|
||||
t[3].data = w.data();
|
||||
if (form)
|
||||
setenv("RADIANCE_ROUTER_SELECT", form, 1);
|
||||
else
|
||||
unsetenv("RADIANCE_ROUTER_SELECT");
|
||||
return r4d_rad_router_sigmoid_topk(&a, nullptr);
|
||||
};
|
||||
std::vector<int> ids_old, ids_new;
|
||||
std::vector<float> w_old, w_new;
|
||||
++cases;
|
||||
if (run("old", ids_old, w_old) != RAD_OK) {
|
||||
std::printf("FAIL router scan launch M=%d ne=%d\n", M, ne);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M; ++r) {
|
||||
int mi[32];
|
||||
float mw[32];
|
||||
router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw);
|
||||
bad += std::memcmp(mi, &ids_old[(size_t)r * ip], (size_t)k * 4) != 0;
|
||||
bad += std::memcmp(mw, &w_old[(size_t)r * wp], (size_t)k * 4) != 0;
|
||||
for (int c = k; c < ip; ++c) bad += ids_old[(size_t)r * ip + c] != -77;
|
||||
for (int c = k; c < wp; ++c) bad += w_old[(size_t)r * wp + c] != -7.25f;
|
||||
}
|
||||
if (bad) {
|
||||
std::printf("FAIL router scan against its model at M=%d ne=%d k=%d: %d\n", M, ne, k,
|
||||
bad);
|
||||
++fails;
|
||||
}
|
||||
++cases;
|
||||
const int rc = run(nullptr, ids_new, w_new);
|
||||
if (rc != RAD_OK || ids_new != ids_old ||
|
||||
std::memcmp(w_new.data(), w_old.data(), w_new.size() * 4) != 0) {
|
||||
std::printf("FAIL router wave select at M=%d ne=%d k=%d%s (rc %d)\n", M, ne, k,
|
||||
sh.ties ? " tied" : "", rc);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
unsetenv("RADIANCE_ROUTER_SELECT");
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(17);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
const char* forms[] = { "1x1", "2x1", "4x1", "8x1", "4x2", "8x2",
|
||||
"4x4", "8x4", "16x2", "16x4", nullptr };
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
};
|
||||
const Shape shapes[] = { { 1, 288, 512 }, { 3, 36, 129 }, { 8, 288, 129 }, { 33, 32, 512 },
|
||||
{ 70, 36, 129 }, { 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3;
|
||||
std::vector<uint16_t> x((size_t)M * xp);
|
||||
std::vector<float> w((size_t)N * K);
|
||||
for (auto& v : x) v = f2b(nd(rng));
|
||||
for (auto& v : w) v = nd(rng) * 0.03f;
|
||||
RadTensor t[3]{};
|
||||
t[0].data = x.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = K;
|
||||
t[0].stride[0] = xp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = w.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 2;
|
||||
t[1].shape[0] = N;
|
||||
t[1].shape[1] = K;
|
||||
t[1].stride[0] = K;
|
||||
t[1].stride[1] = 1;
|
||||
t[2].dtype = RAD_F32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = N;
|
||||
t[2].stride[0] = yp;
|
||||
t[2].stride[1] = 1;
|
||||
RadParam p[4]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3].key = "dtype";
|
||||
p[3].kind = RAD_P_STR;
|
||||
p[3].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 3;
|
||||
a.p = p;
|
||||
a.n_p = 4;
|
||||
auto run = [&](const char* form, std::vector<float>& y) {
|
||||
y.assign((size_t)M * yp, -7.25f);
|
||||
t[2].data = y.data();
|
||||
if (form)
|
||||
setenv("RADIANCE_F32_GEMM_TILE", form, 1);
|
||||
else
|
||||
unsetenv("RADIANCE_F32_GEMM_TILE");
|
||||
return r4d_rad_gemm_nt_f32(&a, nullptr);
|
||||
};
|
||||
std::vector<float> legacy, got;
|
||||
++cases;
|
||||
if (run("legacy", legacy) != RAD_OK) {
|
||||
std::printf("FAIL legacy launch M=%d N=%d K=%d\n", M, N, K);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int c = 0; c < N; ++c) {
|
||||
const float e = legacy_model(&x[(size_t)r * xp], &w[(size_t)c * K], K);
|
||||
bad += std::memcmp(&e, &legacy[(size_t)r * yp + c], 4) != 0;
|
||||
}
|
||||
for (int c = N; c < yp; ++c) bad += legacy[(size_t)r * yp + c] != -7.25f;
|
||||
}
|
||||
if (bad) {
|
||||
std::printf("FAIL legacy kernel against its model at M=%d N=%d K=%d: %d words\n", M, N,
|
||||
K, bad);
|
||||
++fails;
|
||||
}
|
||||
for (const char* const* f = forms;; ++f) {
|
||||
++cases;
|
||||
const int rc = run(*f, got);
|
||||
const bool same =
|
||||
rc == RAD_OK && std::memcmp(got.data(), legacy.data(), got.size() * 4) == 0;
|
||||
if (!same) {
|
||||
std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d)\n", *f ? *f : "default", M, N,
|
||||
K, rc);
|
||||
++fails;
|
||||
}
|
||||
if (!*f) break;
|
||||
}
|
||||
}
|
||||
unsetenv("RADIANCE_F32_GEMM_TILE");
|
||||
router_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
/* tests/r4d_emu: the dense E4M3 GEMM with F32 block scales (r4d_fp8_f32scale.hip) on the host SIMT
|
||||
* emulator. The decode and row-tile forms (RADIANCE_FP8F32_FORM, each R x S x C and row count) must
|
||||
* match the legacy 16x64 tile
|
||||
* bit for bit: the same fragments, the same mma chain per 128-K block and the same fold order.
|
||||
* Ragged row counts, pitched rows and a K that leaves the decode form's last wave group partly
|
||||
* idle are covered; the output's pitch padding stays untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(31);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
};
|
||||
const Shape shapes[] = { { 1, 256, 512 }, { 6, 128, 1536 }, { 17, 256, 512 },
|
||||
{ 48, 128, 512 }, { 70, 128, 384 }, { 130, 128, 256 },
|
||||
{ 3, 128, 4096 } };
|
||||
const char* forms[] = { "decode", "decode1x4", "decode1x32", "decode2x8",
|
||||
"decode3x16", "decode1x8x2", "decode1x4x4", "decode2x8x2",
|
||||
"decode3x4x2", "decode2x4x4", "rows1", "rows2",
|
||||
"rows4", nullptr };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)M * ap), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
|
||||
// summation order shows through the bf16 output.
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap),
|
||||
mat(as.data(), RAD_F32, M, kb, kb),
|
||||
mat(w.data(), RAD_F8E4M3, N, K, K),
|
||||
mat(ws.data(), RAD_F32, N / 128, kb, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
auto run = [&](const char* form, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * yp, 0x7777);
|
||||
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
|
||||
setenv("RADIANCE_FP8F32_FORM", form, 1);
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return r4d_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> legacy, got;
|
||||
++cases;
|
||||
if (run("legacy", legacy) != RAD_OK) {
|
||||
std::printf("FAIL legacy M=%d N=%d K=%d\n", M, N, K);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int nonzero = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0;
|
||||
if (nonzero < M * N / 2) {
|
||||
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
|
||||
++fails;
|
||||
}
|
||||
for (const char* const* f = forms; *f; ++f) {
|
||||
++cases;
|
||||
const int rc = run(*f, got);
|
||||
if (rc != RAD_OK || got != legacy) {
|
||||
size_t i = 0;
|
||||
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
|
||||
std::printf("FAIL form %s at M=%d N=%d K=%d (rc %d, first word %zu)\n", *f, M, N, K,
|
||||
rc, i);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
unsetenv("RADIANCE_FP8F32_FORM");
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
/* tests/r4d_emu: kda_update (r4d_kda.hip) on the host SIMT emulator. Every row and prefetch form
|
||||
* must give the old one-row kernel's output and whole state buffer bit for bit, in all four modes:
|
||||
* prefill per candidate and anchored, verify per candidate and anchored (after the replay of the
|
||||
* accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten slot
|
||||
* are mixed in. The GPU check of the same claim is r4d_selftest's kda_forms. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
static uint16_t f2b(float f) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
const char* mode;
|
||||
bool anchor;
|
||||
int64_t width;
|
||||
std::vector<int> cu, idx, accepted, init;
|
||||
std::vector<std::pair<int64_t, float>> counts;
|
||||
};
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(41);
|
||||
std::uniform_real_distribution<float> u(-1.f, 1.f);
|
||||
const int64_t H = 2, D = 128, slots = 16, tokens = 9;
|
||||
std::vector<float> state0((size_t)(slots * H * D * D)), alog((size_t)H), bias((size_t)(H * D));
|
||||
for (auto& v : state0) v = u(rng);
|
||||
for (auto& v : alog) v = 0.5f * u(rng);
|
||||
for (auto& v : bias) v = u(rng);
|
||||
std::vector<uint16_t> in[5];
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D)));
|
||||
for (auto& v : in[i]) v = f2b((i >= 3 ? 2.f : 1.f) * u(rng));
|
||||
}
|
||||
const std::vector<Case> cases = {
|
||||
{ "prefill, per candidate",
|
||||
"prefill",
|
||||
false,
|
||||
1,
|
||||
{ 0, 4, 4, 9 },
|
||||
{ 3, 4, -1 },
|
||||
{ 1, 1, 1 },
|
||||
{ 0, 1, 1 },
|
||||
{} },
|
||||
{ "prefill, anchored",
|
||||
"prefill",
|
||||
true,
|
||||
2,
|
||||
{ 0, 5, 9 },
|
||||
{ 1, 2, 3, 4 },
|
||||
{ 1, 1 },
|
||||
{ 1, 0 },
|
||||
{} },
|
||||
{ "verify, per candidate",
|
||||
"verify",
|
||||
false,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 0, 1 },
|
||||
{} },
|
||||
{ "verify, anchored",
|
||||
"verify",
|
||||
true,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 1, 9, 5, 9, 2, 9, 6, 9, 3, 9, 7, 9 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 1, 0 },
|
||||
{ { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } },
|
||||
};
|
||||
struct Form {
|
||||
const char* rows;
|
||||
const char* prefetch;
|
||||
};
|
||||
const Form forms[] = { { "1", "1" }, { "2", "1" }, { "4", "1" },
|
||||
{ "1", "0" }, { "2", "0" }, { "4", "0" } };
|
||||
int fails = 0, checks = 0;
|
||||
for (const Case& c : cases) {
|
||||
std::vector<float> start = state0;
|
||||
for (const auto& sc : c.counts)
|
||||
for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second;
|
||||
const int64_t seqs = (int64_t)c.cu.size() - 1;
|
||||
std::vector<int> idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init;
|
||||
auto run = [&](std::vector<uint16_t>& out, std::vector<float>& state) {
|
||||
out.assign((size_t)(tokens * H * D), 0x7777);
|
||||
state = start;
|
||||
RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[1].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[2].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[3].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[4].data(), RAD_BF16, { tokens, H }),
|
||||
tens(alog.data(), RAD_F32, { H }),
|
||||
tens(bias.data(), RAD_F32, { H * D }),
|
||||
tens(state.data(), RAD_F32, { slots, H, D, D }),
|
||||
tens(idx.data(), RAD_I32, { seqs, c.width }),
|
||||
tens(cu.data(), RAD_I32, { seqs + 1 }),
|
||||
tens(acc.data(), RAD_I32, { seqs }),
|
||||
tens(init.data(), RAD_I32, { seqs }),
|
||||
tens(out.data(), RAD_BF16, { tokens, H, D }) };
|
||||
RadParam p[10]{};
|
||||
p[0] = { "heads", RAD_P_INT, H };
|
||||
p[1] = { "head_k", RAD_P_INT, D };
|
||||
p[2] = { "head_v", RAD_P_INT, D };
|
||||
p[3].key = "lower_bound";
|
||||
p[3].kind = RAD_P_F64;
|
||||
p[3].dval = -5;
|
||||
p[4].key = "scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 1.0 / std::sqrt(128.0);
|
||||
p[5].key = "l2_eps";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 1e-6;
|
||||
p[6].key = "mode";
|
||||
p[6].kind = RAD_P_STR;
|
||||
p[6].sval = c.mode;
|
||||
p[7].key = "state_form";
|
||||
p[7].kind = RAD_P_STR;
|
||||
p[7].sval = c.anchor ? "anchor" : "per_candidate";
|
||||
p[8].key = "dtype";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 13;
|
||||
a.p = p;
|
||||
a.n_p = 9;
|
||||
return r4d_rad_kda_update(&a, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> ref_out, out;
|
||||
std::vector<float> ref_state, state;
|
||||
setenv("RADIANCE_KDA_FORM", "old", 1);
|
||||
if (run(ref_out, ref_state) != RAD_OK) {
|
||||
std::printf("FAIL %s: old form refused\n", c.name);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
unsetenv("RADIANCE_KDA_FORM");
|
||||
bool written = false;
|
||||
for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777;
|
||||
if (!written) {
|
||||
std::printf("FAIL %s: the old form wrote no output\n", c.name);
|
||||
++fails;
|
||||
}
|
||||
for (const Form& f : forms) {
|
||||
setenv("RADIANCE_KDA_ROWS", f.rows, 1);
|
||||
setenv("RADIANCE_KDA_PREFETCH", f.prefetch, 1);
|
||||
++checks;
|
||||
const bool same = run(out, state) == RAD_OK && out == ref_out &&
|
||||
std::memcmp(state.data(), ref_state.data(), state.size() * 4) == 0;
|
||||
if (!same) {
|
||||
++fails;
|
||||
std::printf("FAIL %s, %s rows a wave, prefetch %s: differs from the old form\n",
|
||||
c.name, f.rows, f.prefetch);
|
||||
}
|
||||
}
|
||||
unsetenv("RADIANCE_KDA_ROWS");
|
||||
unsetenv("RADIANCE_KDA_PREFETCH");
|
||||
}
|
||||
std::printf("kda_update forms against the old kernel: %d of %d bit-identical\n", checks - fails,
|
||||
checks);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
/* tests/r4d_emu: GLM's mHC read split by residual chunks (r4d_mhc.hip) on the host SIMT emulator.
|
||||
* Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the
|
||||
* row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and
|
||||
* comb bit for bit, under each of mhc_pre's kernel switches; the partial matrix's padding slots
|
||||
* are zero. Every form is also held to the old dispatch, bit for bit. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, int64_t n) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = RAD_F32;
|
||||
t.rank = 1;
|
||||
t.shape[0] = n;
|
||||
t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8;
|
||||
std::vector<float> fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix);
|
||||
for (auto& v : fn) v = nd(rng) * 0.01f;
|
||||
for (auto& v : base) v = nd(rng) * 0.5f;
|
||||
struct Form {
|
||||
const char* env;
|
||||
const char* value;
|
||||
};
|
||||
const Form forms[] = { { nullptr, nullptr },
|
||||
{ "RADIANCE_MHC_PREFILL_COEFF4", "0" },
|
||||
{ "RADIANCE_MHC_PREFILL_ROWS4", "0" },
|
||||
{ "RADIANCE_MHC_PREFILL_WARP", "0" } };
|
||||
int fails = 0, cases = 0;
|
||||
for (int64_t rows : { 1, 5, 37 }) {
|
||||
const int64_t hp = W + 6, xp = n + 2;
|
||||
std::vector<uint16_t> h((size_t)(rows * hp));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
for (const Form& f : forms) {
|
||||
if (f.env) setenv(f.env, f.value, 1);
|
||||
RadParam coef[8]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-5;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
std::vector<uint16_t> x((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc));
|
||||
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(x.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
if (r4d_rad_mhc_pre(&a, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL mhc_pre M=%lld\n", (long long)rows);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
++cases;
|
||||
const int64_t mine = total / world;
|
||||
std::vector<float> gathered((size_t)(rows * total * S));
|
||||
bool padded = true, launched = true;
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
std::vector<float> part((size_t)(rows * mine * S), 7.0f);
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(part.data(), RAD_F32, rows, mine * S, mine * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, rank * mine };
|
||||
pp[5] = { "chunks", RAD_P_INT, mine };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
launched = launched && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t c = 0; c < mine; ++c)
|
||||
for (int64_t j = mix + 1; j < S; ++j)
|
||||
padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f;
|
||||
std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)],
|
||||
&part[(size_t)(r * mine * S)], (size_t)(mine * S * 4));
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> x2((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post2(post.size()), comb2(comb.size());
|
||||
RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S),
|
||||
t[0],
|
||||
t[2],
|
||||
t[3],
|
||||
mat(x2.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post2.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadParam fp[8];
|
||||
std::memcpy(fp, coef, sizeof coef);
|
||||
fp[6] = { "chunk", RAD_P_INT, 2048 };
|
||||
fp[7].key = "dtype";
|
||||
fp[7].kind = RAD_P_STR;
|
||||
fp[7].sval = "bf16";
|
||||
RadArgs fa{};
|
||||
fa.t = ft;
|
||||
fa.n_t = 7;
|
||||
fa.p = fp;
|
||||
fa.n_p = 8;
|
||||
launched = launched && r4d_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK;
|
||||
const bool same = launched && x2 == x &&
|
||||
std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 &&
|
||||
std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0;
|
||||
if (!same || !padded) {
|
||||
std::printf("FAIL M=%lld world %d %s%s%s: %s\n", (long long)rows, world,
|
||||
f.env ? f.env : "default", f.env ? "=" : "", f.env ? f.value : "",
|
||||
!launched ? "launch"
|
||||
: !padded ? "padding"
|
||||
: "differs");
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
if (f.env) unsetenv(f.env);
|
||||
}
|
||||
}
|
||||
/* Every form against the old dispatch (one-wave finish from 32 rows, scalar mix and read
|
||||
* below, scalar-row and rows4 partials, the per-output mhc_post) on 16-byte rows, where the
|
||||
* vector paths run: mhc_pre's x, post and comb, mhc_pre_partial's matrix and mhc_post's
|
||||
* output, bit for bit. */
|
||||
struct Pin {
|
||||
const char* what;
|
||||
const char* finish;
|
||||
const char* vec;
|
||||
const char* prow;
|
||||
};
|
||||
const Pin pins[] = { { "rule", nullptr, nullptr, nullptr },
|
||||
{ "finish scalar", "scalar", nullptr, nullptr },
|
||||
{ "partials four-slot, 1 row a wave", nullptr, "1", "1" },
|
||||
{ "partials four-slot, 2 rows a wave", nullptr, "1", "2" },
|
||||
{ "partials four-slot, 4 rows a wave", nullptr, "1", "4" } };
|
||||
auto pin = [](const char* k, const char* v) {
|
||||
if (v)
|
||||
setenv(k, v, 1);
|
||||
else
|
||||
unsetenv(k);
|
||||
};
|
||||
for (int64_t rows : { 1, 5, 16, 37, 64 }) {
|
||||
std::vector<uint16_t> h((size_t)(rows * W)), y((size_t)(rows * n));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
for (auto& v : y) v = f2b(nd(rng));
|
||||
RadParam coef[7]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-6;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
struct Out {
|
||||
std::vector<uint16_t> x, o;
|
||||
std::vector<float> p, c, part;
|
||||
};
|
||||
auto run = [&](Out* r) {
|
||||
r->x.assign((size_t)(rows * n), 0x7777);
|
||||
r->o.assign((size_t)(rows * W), 0x7777);
|
||||
r->p.assign((size_t)(rows * hc), 0);
|
||||
r->c.assign((size_t)(rows * hc * hc), 0);
|
||||
r->part.assign((size_t)(rows * total * S), 7.0f);
|
||||
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, W),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(r->x.data(), RAD_BF16, rows, n, n),
|
||||
mat(r->p.data(), RAD_F32, rows, hc, hc),
|
||||
mat(r->c.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
bool okay = r4d_rad_mhc_pre(&a, nullptr) == RAD_OK;
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(r->part.data(), RAD_F32, rows, total * S, total * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, 0 };
|
||||
pp[5] = { "chunks", RAD_P_INT, total };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
okay = okay && r4d_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
RadTensor ot[5] = { mat(y.data(), RAD_BF16, rows, n, n), t[0], t[5], t[6],
|
||||
mat(r->o.data(), RAD_BF16, rows, W, W) };
|
||||
RadArgs oa{};
|
||||
oa.t = ot;
|
||||
oa.n_t = 5;
|
||||
oa.p = coef;
|
||||
oa.n_p = 7;
|
||||
return okay && r4d_rad_mhc_post(&oa, nullptr) == RAD_OK;
|
||||
};
|
||||
Out ref, got;
|
||||
pin("RADIANCE_MHC_FINISH", "old");
|
||||
pin("RADIANCE_MHC_PARTIAL_VEC", "0");
|
||||
pin("RADIANCE_MHC_POST_VEC", "0");
|
||||
const bool ref_ok = run(&ref);
|
||||
pin("RADIANCE_MHC_POST_VEC", nullptr);
|
||||
for (const Pin& f : pins) {
|
||||
++cases;
|
||||
pin("RADIANCE_MHC_FINISH", f.finish);
|
||||
pin("RADIANCE_MHC_PARTIAL_VEC", f.vec);
|
||||
pin("RADIANCE_MHC_PARTIAL_ROWS", f.prow);
|
||||
const bool launched = ref_ok && run(&got);
|
||||
const char* bad = !launched ? "launch"
|
||||
: got.x != ref.x ? "x"
|
||||
: std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post"
|
||||
: std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb"
|
||||
: std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4)
|
||||
? "partials"
|
||||
: got.o != ref.o ? "mhc_post"
|
||||
: nullptr;
|
||||
if (bad) {
|
||||
std::printf("FAIL M=%lld %s against the old dispatch: %s differs\n",
|
||||
(long long)rows, f.what, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
for (const char* k :
|
||||
{ "RADIANCE_MHC_FINISH", "RADIANCE_MHC_PARTIAL_VEC", "RADIANCE_MHC_PARTIAL_ROWS" })
|
||||
unsetenv(k);
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,408 @@
|
||||
/* Drives libr4d's MLA matrix row (r4d_mla.hip, attend_matrix) through the SIMT emulator and checks
|
||||
* every output element against an f64 softmax over each row's own table. The cases put the paired
|
||||
* tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk
|
||||
* whose rows share one table, and rows past the DSA budget, where each row selects its own top
|
||||
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
|
||||
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" void r4d_mla_matrix_pin_form(int form);
|
||||
extern "C" void r4d_mla_matrix_stats(unsigned long long* out);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int D = 512, BS = 4;
|
||||
|
||||
enum class Fill { prefill, topk, ragged, repeat };
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
int rows, heads, blocks;
|
||||
Fill fill;
|
||||
int swaps = 0; /* topk: blocks exchanged between neighbouring rows */
|
||||
int context = 0; /* topk: tokens of the sequence the rows end */
|
||||
bool scratch = false; /* lets the launcher split the history */
|
||||
int form = 0; /* r4d_mla_matrix_pin_form */
|
||||
int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */
|
||||
bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */
|
||||
bool bitwise_all = false; /* both requests do (the tables agree position by position) */
|
||||
bool union_falls_back = false; /* the table is wider than the union's lists */
|
||||
};
|
||||
|
||||
/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows ..
|
||||
* context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher
|
||||
* ones in block order and a short tie run after them, then the partial page. Row r's choice is row
|
||||
* r-1's with `swaps` members exchanged for non-members. Pages are a fixed shuffle of the blocks. */
|
||||
void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng,
|
||||
std::vector<int>& bt, std::vector<int>& len, int& pages) {
|
||||
const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk);
|
||||
pages = universe;
|
||||
std::vector<int> page(universe);
|
||||
for (int i = 0; i < universe; ++i) page[i] = i;
|
||||
std::shuffle(page.begin(), page.end(), rng);
|
||||
std::vector<char> in(universe, 0);
|
||||
std::vector<int> members;
|
||||
auto tie_rank = [](int b) { return (uint32_t)b * 2654435761u ^ 0x9e3779b9u; };
|
||||
bt.assign((size_t)rows * blocks, -1);
|
||||
len.assign(rows, 0);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const int p = context - rows + r, n = (p + 1) / BS;
|
||||
if (n <= topk) {
|
||||
for (int b = 0; b < n; ++b)
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
} else {
|
||||
while ((int)members.size() < topk) {
|
||||
const int b = (int)(rng() % (unsigned)n);
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
}
|
||||
for (int s = 0; s < swaps; ++s) {
|
||||
int add;
|
||||
do add = (int)(rng() % (unsigned)n);
|
||||
while (in[add]);
|
||||
const size_t drop = rng() % members.size();
|
||||
in[members[drop]] = 0;
|
||||
members[drop] = add;
|
||||
in[add] = 1;
|
||||
}
|
||||
}
|
||||
std::vector<int> order(members);
|
||||
std::sort(order.begin(), order.end());
|
||||
if (n > topk) {
|
||||
std::vector<int> tied(order);
|
||||
std::sort(tied.begin(), tied.end(),
|
||||
[&](int a, int b) { return tie_rank(a) < tie_rank(b); });
|
||||
tied.resize(ties);
|
||||
std::sort(tied.begin(), tied.end());
|
||||
order.erase(std::remove_if(
|
||||
order.begin(), order.end(),
|
||||
[&](int b) { return std::binary_search(tied.begin(), tied.end(), b); }),
|
||||
order.end());
|
||||
order.insert(order.end(), tied.begin(), tied.end());
|
||||
}
|
||||
int out = 0;
|
||||
for (int b : order) bt[(size_t)r * blocks + out++] = page[b];
|
||||
if ((p + 1) % BS) bt[(size_t)r * blocks + out++] = page[n];
|
||||
len[r] = out ? (out - 1) * BS + p % BS + 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
int run(const Case& c, std::mt19937& rng) {
|
||||
const int M = c.rows, H = c.heads, B = c.blocks;
|
||||
std::vector<int> bt, len;
|
||||
int pages = 0;
|
||||
if (c.fill == Fill::topk) {
|
||||
topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages);
|
||||
} else if (c.fill == Fill::prefill) {
|
||||
/* one sequence, its rows the last M positions of the capacity, one table */
|
||||
pages = B + 1;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = (b * 7 + 3) % pages;
|
||||
len[r] = B * BS - M + r + 1;
|
||||
}
|
||||
} else if (c.fill == Fill::repeat) {
|
||||
/* every page twice in a row's table and shifted by one entry from row to row, so a page
|
||||
* repeats within a table and between the pair */
|
||||
pages = M + B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = ((b + r) / 2 * 5) % pages;
|
||||
len[r] = B * BS - r % 3;
|
||||
}
|
||||
} else {
|
||||
/* every row its own scattered table, with holes and out-of-range pages */
|
||||
pages = M * B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b)
|
||||
bt[(size_t)r * B + b] = b % 17 == 3 ? -1
|
||||
: b % 19 == 5 ? pages + 3
|
||||
: (b * 7 + r * 11) % pages;
|
||||
len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7;
|
||||
}
|
||||
}
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
|
||||
auto tens = [](void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
return t;
|
||||
};
|
||||
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
|
||||
tens(out.data(), RAD_BF16, { M, H, D }) };
|
||||
std::vector<RadParam> p;
|
||||
auto pi = [&](const char* k, long long v) {
|
||||
RadParam x{};
|
||||
x.key = k;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
p.push_back(x);
|
||||
};
|
||||
auto pf = [&](const char* k, double v) {
|
||||
RadParam x{};
|
||||
x.key = k;
|
||||
x.kind = RAD_P_F64;
|
||||
x.dval = v;
|
||||
p.push_back(x);
|
||||
};
|
||||
pi("M", M);
|
||||
pi("latent_dim", D);
|
||||
pi("heads", H);
|
||||
pi("blocks", B);
|
||||
pi("block_size", BS);
|
||||
const double scale = 0.0625;
|
||||
pf("scale", scale);
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p.data();
|
||||
a.n_p = (int)p.size();
|
||||
std::vector<char> scratch;
|
||||
if (c.scratch) {
|
||||
const int64_t need = r4d_rad_mla_attn_matrix_scratch(&a);
|
||||
scratch.assign((size_t)need + 16, 0);
|
||||
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
}
|
||||
|
||||
/* the f64 reference */
|
||||
std::vector<double> want((size_t)M * H * D);
|
||||
std::vector<double> sc;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int h = 0; h < H; ++h) {
|
||||
const int live = std::min(std::max(len[r], 0), B * BS);
|
||||
sc.assign(live, -INFINITY);
|
||||
double mx = -INFINITY;
|
||||
auto row_of = [&](int j) -> const uint16_t* {
|
||||
const int pg = bt[(size_t)r * B + j / BS];
|
||||
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
|
||||
};
|
||||
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
|
||||
for (int j = 0; j < live; ++j) {
|
||||
const uint16_t* k = row_of(j);
|
||||
if (!k) continue;
|
||||
double dot = 0;
|
||||
for (int d = 0; d < D; ++d)
|
||||
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
|
||||
sc[j] = dot * scale;
|
||||
mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(D, 0.0);
|
||||
double sum = 0;
|
||||
for (int j = 0; j < live; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx);
|
||||
sum += w;
|
||||
const uint16_t* k = row_of(j);
|
||||
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
|
||||
}
|
||||
for (int d = 0; d < D; ++d)
|
||||
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
|
||||
}
|
||||
|
||||
/* Both pairings on the same operands: the positional one (RADIANCE_MLA_PAIR=pos) and the
|
||||
* union, which must never take a second pass. */
|
||||
const bool paired = H % 16 == 8;
|
||||
std::vector<uint16_t> by_pos;
|
||||
int fails = 0;
|
||||
for (const char* pairing : { "pos", "union" }) {
|
||||
if (!paired && !std::strcmp(pairing, "union")) break;
|
||||
setenv("RADIANCE_MLA_PAIR", pairing, 1);
|
||||
std::fill(out.begin(), out.end(), 0xffff);
|
||||
unsigned long long stats[3];
|
||||
r4d_mla_matrix_stats(stats);
|
||||
r4d_mla_matrix_pin_form(c.form);
|
||||
const int rc = r4d_rad_mla_attn_matrix(&a, nullptr);
|
||||
r4d_mla_matrix_pin_form(0);
|
||||
r4d_mla_matrix_stats(stats);
|
||||
unsetenv("RADIANCE_MLA_PAIR");
|
||||
if (rc != RAD_OK) {
|
||||
std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
double max_err = 0;
|
||||
long bad = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
const float got = rad_bf16_to_f32(out[i]);
|
||||
const double e = std::fabs(got - want[i]);
|
||||
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
|
||||
if (std::isfinite(got)) max_err = std::max(max_err, e);
|
||||
}
|
||||
bool ok = bad == 0;
|
||||
std::string note;
|
||||
const bool by_page = !std::strcmp(pairing, "union");
|
||||
if (!by_page) {
|
||||
by_pos = out;
|
||||
if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) {
|
||||
note +=
|
||||
c.expect_second ? " (expected a second pass)" : " (expected no second pass)";
|
||||
ok = false;
|
||||
}
|
||||
} else {
|
||||
if ((stats[1] > 0) != c.union_falls_back) {
|
||||
note += c.union_falls_back ? " (expected the positional fallback)"
|
||||
: " (the union took a second pass)";
|
||||
ok = false;
|
||||
}
|
||||
/* Request r of each pair walks its own table in its own order, as the positional
|
||||
* pairing does, so at one split it must agree to the bit; r+1 sums in another order. */
|
||||
size_t first_diff_a = 0, diff_b = 0;
|
||||
double max_ab = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
|
||||
if (out[i] == by_pos[i]) continue;
|
||||
if (r % 2 == 0)
|
||||
++first_diff_a;
|
||||
else
|
||||
++diff_b;
|
||||
max_ab = std::max(max_ab, (double)std::fabs(rad_bf16_to_f32(out[i]) -
|
||||
rad_bf16_to_f32(by_pos[i])));
|
||||
}
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e",
|
||||
first_diff_a, diff_b, max_ab);
|
||||
note += buf;
|
||||
if (c.bitwise_a && first_diff_a) {
|
||||
note += " (request r differs)";
|
||||
ok = false;
|
||||
}
|
||||
if (c.bitwise_all && diff_b) {
|
||||
note += " (request r+1 differs)";
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
std::printf("%-40s %-5s M %3d H %2d blocks %3d passes %5llu raster %5llu second %5llu "
|
||||
"max_abs %.2e bad %ld%s %s\n",
|
||||
c.name.c_str(), pairing, M, H, B, stats[0], stats[2], stats[1], max_err, bad,
|
||||
note.c_str(), ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The launcher prints the running totals every 1024th counted launch and must leave them
|
||||
* standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */
|
||||
int periodic_report() {
|
||||
std::vector<uint16_t> q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D);
|
||||
std::vector<int> bt = { 0, 1 }, len = { 4, 3 };
|
||||
RadTensor t[5]{};
|
||||
auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
x.data = p;
|
||||
x.dtype = dt;
|
||||
x.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
x.shape[i] = shape[i];
|
||||
x.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
};
|
||||
set(t[0], q.data(), RAD_BF16, { 2, 8, D });
|
||||
set(t[1], kv.data(), RAD_BF16, { 4, 1, BS, D });
|
||||
set(t[2], bt.data(), RAD_I32, { 2, 1 });
|
||||
set(t[3], len.data(), RAD_I32, { 2 });
|
||||
set(t[4], out.data(), RAD_BF16, { 2, 8, D });
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { 2, D, 8, 1, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 0.0625;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
unsigned long long stats[3];
|
||||
r4d_mla_matrix_stats(stats);
|
||||
for (int i = 0; i < 1024; ++i)
|
||||
if (r4d_rad_mla_attn_matrix(&a, nullptr) != RAD_OK) {
|
||||
std::printf("periodic report: launch failed\n");
|
||||
return 1;
|
||||
}
|
||||
r4d_mla_matrix_stats(stats);
|
||||
const bool ok = stats[0] == 1024 && stats[2] == 1024 && stats[1] == 0;
|
||||
std::printf("periodic report: %llu passes over %llu raster chunks after 1024 launches %s\n",
|
||||
stats[0], stats[2], ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setenv("RADIANCE_MLA_CONFLICT_STATS", "1", 1);
|
||||
/* name, rows, heads, blocks, fill, swaps, context, scratch, form, expect_second, bitwise_a,
|
||||
* bitwise_all, union_falls_back */
|
||||
std::vector<Case> cases = {
|
||||
{ "prefill, one table", 8, 8, 65, Fill::prefill, 0, 0, false, 0, 0, true, true },
|
||||
{ "prefill, odd rows, split", 7, 8, 33, Fill::prefill, 0, 0, true, 0, 0, true, true },
|
||||
{ "prefill, 16 heads", 4, 16, 33, Fill::prefill, 0, 0, false, 0, 0 },
|
||||
{ "prefill, 24 heads (three pairs)", 5, 24, 17, Fill::prefill, 0, 0, false, 0, 0, true,
|
||||
true },
|
||||
{ "topk d=0", 8, 8, 65, Fill::topk, 0, 600, false, 0, 0, true, true },
|
||||
{ "topk d=4", 8, 8, 65, Fill::topk, 4, 600, false, 0, 1 },
|
||||
{ "topk d=16", 8, 8, 65, Fill::topk, 16, 600, false, 0, 1 },
|
||||
{ "topk d=64 (disjoint neighbours)", 6, 8, 65, Fill::topk, 64, 600, false, 0, 1 },
|
||||
{ "topk d=16, 513 blocks", 4, 8, 513, Fill::topk, 16, 8192, false, 0, 1 },
|
||||
/* a split cuts the union's walk elsewhere than the positional raster */
|
||||
{ "topk d=4, odd rows, split", 5, 8, 33, Fill::topk, 4, 400, true, 0, 1, false },
|
||||
{ "topk d=4, element load", 4, 8, 33, Fill::topk, 4, 400, false, 1, 1 },
|
||||
{ "topk d=4, 16 heads", 4, 16, 33, Fill::topk, 4, 400, false, 0, 0 },
|
||||
{ "topk, table past the union's lists", 4, 8, 600, Fill::topk, 16, 4000, false, 0, 1, true,
|
||||
true, true },
|
||||
{ "repeated pages", 6, 8, 33, Fill::repeat, 0, 0, false, 0, -1 },
|
||||
{ "repeated pages, split", 3, 8, 33, Fill::repeat, 0, 0, true, 0, -1, false },
|
||||
{ "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 },
|
||||
{ "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false },
|
||||
};
|
||||
const char* filter = argc > 1 ? argv[1] : nullptr;
|
||||
int fails = 0;
|
||||
for (size_t i = 0; i < cases.size(); ++i) {
|
||||
if (filter && cases[i].name.find(filter) == std::string::npos) continue;
|
||||
std::mt19937 rng(20261018u + (unsigned)i);
|
||||
fails += run(cases[i], rng);
|
||||
}
|
||||
if (!filter) fails += periodic_report();
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
/* tests/r4d_emu: GLM's decode fusions of the MoE block (r4d_glm.hip) on the host SIMT emulator,
|
||||
* each byte for byte against the separate launches it replaces.
|
||||
*
|
||||
* router_sigmoid_topk_scatter against router_sigmoid_topk (the emulated kernel), then moe_scatter's
|
||||
* stable counting sort over its ids written out here, then the `fill` of the shared gate with 1:
|
||||
* random, tied and NaN ranks (a row with fewer finite ranks than top_k selects expert 0 for its
|
||||
* empty slots, and the sort takes those as written), slices and protected experts, rows past 64
|
||||
* wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past
|
||||
* every output and the gate's untouched rows show an overrun.
|
||||
*
|
||||
* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes,
|
||||
* scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the
|
||||
* clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the
|
||||
* sigmoid underflows, and NaN and infinite inputs.
|
||||
*
|
||||
* moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself
|
||||
* without, and the inverse against the table the gather builds from `sorted`; then moe_gather's
|
||||
* kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at
|
||||
* GLM's f32 routing weights and bf16 ones, with the ungated shared arm, a sigmoid-gated one and
|
||||
* none, and slices that drop slots. moe_scatter's three-pass form (T > 1024) is not here: its
|
||||
* kernels take dynamic LDS through `extern __shared__`, which the emulator cannot give; the card
|
||||
* checks it (r4d_selftest --case moe_scatter_inv_i32). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include "r4d_moe_sort.h"
|
||||
#include "r4d_moe_gather.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int32_t kPoison = -77;
|
||||
constexpr uint16_t kGatePoison = 0x7e57;
|
||||
|
||||
/* moe_scatter's contract: slot i = token * top_k + slot goes to its expert's run in ascending i;
|
||||
* an expert outside the slice drops the slot; protected experts are placed last in list order;
|
||||
* sorted rows past the live count are -1. */
|
||||
struct SortModel {
|
||||
std::vector<int32_t> sorted, off, cnt;
|
||||
};
|
||||
int32_t place_of(int32_t e, int nl, const std::vector<int>& prot) {
|
||||
int32_t below = 0;
|
||||
for (size_t j = 0; j < prot.size(); ++j) {
|
||||
if (prot[j] == e) return nl - (int32_t)prot.size() + (int32_t)j;
|
||||
below += prot[j] < e;
|
||||
}
|
||||
return e - below;
|
||||
}
|
||||
SortModel sort_model(const std::vector<int32_t>& ids, int M, int k, int ip, int nl, int base,
|
||||
const std::vector<int>& prot) {
|
||||
const int T = M * k;
|
||||
std::vector<int32_t> place((size_t)T);
|
||||
SortModel s;
|
||||
s.cnt.assign((size_t)nl, 0);
|
||||
s.off.assign((size_t)nl + 1, 0);
|
||||
s.sorted.assign((size_t)T, -1);
|
||||
for (int i = 0; i < T; ++i) {
|
||||
const int32_t e = ids[(size_t)(i / k) * ip + i % k] - base;
|
||||
place[(size_t)i] = e >= 0 && e < nl ? place_of(e, nl, prot) : -1;
|
||||
if (place[(size_t)i] >= 0) ++s.cnt[(size_t)place[(size_t)i]];
|
||||
}
|
||||
for (int e = 0; e < nl; ++e) s.off[(size_t)e + 1] = s.off[(size_t)e] + s.cnt[(size_t)e];
|
||||
std::vector<int32_t> seen((size_t)nl, 0);
|
||||
for (int i = 0; i < T; ++i)
|
||||
if (place[(size_t)i] >= 0) {
|
||||
const int32_t e = place[(size_t)i];
|
||||
s.sorted[(size_t)(s.off[(size_t)e] + seen[(size_t)e]++)] = i;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The table the gather builds from `sorted` (gather_kernel's self-scan, or its prepass): slot
|
||||
* sorted[p] at row p, every other slot -1. */
|
||||
std::vector<int32_t> inverse_of(const std::vector<int32_t>& sorted) {
|
||||
std::vector<int32_t> inv(sorted.size(), -1);
|
||||
for (size_t p = 0; p < sorted.size(); ++p)
|
||||
if (sorted[p] >= 0) inv[(size_t)sorted[p]] = (int32_t)p;
|
||||
return inv;
|
||||
}
|
||||
|
||||
/* moe_scatter's small-form kernel (r4d_moe_sort.h) over contiguous ids, with or without the
|
||||
* inverse. */
|
||||
struct Scatter {
|
||||
int rc = RAD_OK;
|
||||
std::vector<int32_t> sorted, off, cnt, inv;
|
||||
};
|
||||
Scatter scatter_kernel(const std::vector<int32_t>& ids, int nl, int base, const char* protect,
|
||||
bool with_inv) {
|
||||
const int T = (int)ids.size();
|
||||
Scatter s;
|
||||
s.sorted.assign((size_t)T, kPoison);
|
||||
s.off.assign((size_t)nl + 1, kPoison);
|
||||
s.cnt.assign((size_t)nl, kPoison);
|
||||
s.inv.assign((size_t)T, kPoison);
|
||||
RadParam pp{};
|
||||
pp.key = "protect";
|
||||
pp.kind = RAD_P_STR;
|
||||
pp.sval = protect;
|
||||
RadArgs pa{};
|
||||
pa.p = &pp;
|
||||
pa.n_p = protect ? 1 : 0;
|
||||
r4d_moesort::Protect prot;
|
||||
s.rc = r4d_moesort::protect_of(&pa, nl, &prot);
|
||||
if (s.rc != RAD_OK) return s;
|
||||
if (with_inv)
|
||||
R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel<true>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, s.inv.data());
|
||||
else
|
||||
R4D_EMIT(nullptr, (r4d_moesort::scatter_small_kernel<false>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, (int32_t*)nullptr);
|
||||
return s;
|
||||
}
|
||||
|
||||
struct RouterShape {
|
||||
int M, ne, k, norm;
|
||||
int mode; /* 0 random, 1 tied ranks, 2 NaN rows */
|
||||
int nl, base; /* the slice: nl 0 is the whole router */
|
||||
const char* protect;
|
||||
bool gate;
|
||||
};
|
||||
|
||||
void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const RouterShape shapes[] = {
|
||||
{ 1, 288, 8, 1, 0, 0, 0, nullptr, true }, { 2, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 6, 288, 8, 1, 0, 0, 0, nullptr, true }, { 8, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 9, 288, 8, 1, 0, 0, 0, nullptr, false }, { 16, 288, 8, 1, 2, 0, 0, nullptr, true },
|
||||
{ 17, 288, 8, 1, 0, 0, 0, nullptr, true }, { 24, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 33, 288, 8, 1, 0, 0, 0, nullptr, true }, { 48, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 48, 288, 8, 1, 2, 0, 0, nullptr, true }, { 65, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 100, 288, 8, 0, 0, 0, 0, nullptr, true }, { 128, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 24, 288, 8, 1, 0, 144, 144, nullptr, true }, { 24, 288, 8, 1, 1, 96, 32, "3,7,90", true },
|
||||
{ 48, 512, 8, 1, 0, 0, 0, nullptr, true }, { 32, 32, 32, 0, 1, 0, 0, nullptr, true },
|
||||
{ 5, 300, 10, 1, 2, 0, 0, "0,299", true },
|
||||
};
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const RouterShape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, T = M * k;
|
||||
const int nl = sh.nl ? sh.nl : ne, base = sh.base;
|
||||
const int lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1, gp = 3;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.mode == 1 ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias)
|
||||
v = sh.mode == 1 ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
if (sh.mode == 2)
|
||||
for (int r = 0; r < M; r += 2) {
|
||||
/* every other row keeps (r % 5) finite ranks, fewer than top_k */
|
||||
for (int e = 0; e < ne; ++e) lg[(size_t)r * lp + e] = NAN;
|
||||
for (int j = 0; j < r % 5; ++j)
|
||||
lg[(size_t)r * lp + (size_t)(ud(rng) + 1000) % ne] = 0.25f * (float)j;
|
||||
}
|
||||
std::vector<int> prot;
|
||||
if (sh.protect)
|
||||
for (const char* p = sh.protect; *p;) {
|
||||
char* end = nullptr;
|
||||
prot.push_back((int)std::strtol(p, &end, 10));
|
||||
p = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
|
||||
RadTensor t[8]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = nl + 1;
|
||||
t[5].stride[0] = 1;
|
||||
t[6].dtype = RAD_I32;
|
||||
t[6].rank = 1;
|
||||
t[6].shape[0] = nl;
|
||||
t[6].stride[0] = 1;
|
||||
t[7].dtype = RAD_BF16;
|
||||
t[7].rank = 2;
|
||||
t[7].shape[0] = M;
|
||||
t[7].shape[1] = 1;
|
||||
t[7].stride[0] = gp;
|
||||
t[7].stride[1] = 1;
|
||||
std::vector<RadParam> p(9);
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
p[6] = { "n_local", RAD_P_INT, nl };
|
||||
p[7] = { "expert_base", RAD_P_INT, base };
|
||||
p[8].key = "protect";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = sh.protect;
|
||||
const int n_p = sh.protect ? 9 : 8;
|
||||
|
||||
/* the separate launches: the selection, then the sort and fill modelled */
|
||||
std::vector<int32_t> ids_ref((size_t)M * ip, kPoison);
|
||||
std::vector<float> w_ref((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids_ref.data();
|
||||
t[3].data = w_ref.data();
|
||||
RadArgs sel{};
|
||||
sel.t = t;
|
||||
sel.n_t = 4;
|
||||
sel.p = p.data();
|
||||
sel.n_p = 6;
|
||||
++cases;
|
||||
if (r4d_rad_router_sigmoid_topk(&sel, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL router_sigmoid_topk launch M=%d ne=%d\n", M, ne);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const SortModel ref = sort_model(ids_ref, M, k, ip, nl, base, prot);
|
||||
/* moe_scatter's own kernel over the ids, contiguous as it reads them, held to the model;
|
||||
* with the inverse, which must be the table the gather builds from `sorted`. */
|
||||
std::vector<int32_t> flat((size_t)T);
|
||||
for (int i = 0; i < T; ++i) flat[(size_t)i] = ids_ref[(size_t)(i / k) * ip + i % k];
|
||||
Scatter ks = scatter_kernel(flat, nl, base, sh.protect, true);
|
||||
++cases;
|
||||
if (ks.rc != RAD_OK || ks.sorted != ref.sorted || ks.off != ref.off || ks.cnt != ref.cnt ||
|
||||
ks.inv != inverse_of(ref.sorted)) {
|
||||
std::printf("FAIL moe_scatter kernel against its model at M=%d ne=%d slice %d+%d\n", M,
|
||||
ne, base, nl);
|
||||
++fails;
|
||||
}
|
||||
|
||||
for (int with_inv = 0; with_inv < 2; ++with_inv) {
|
||||
std::vector<int32_t> ids((size_t)M * ip, kPoison), sorted((size_t)T + 4, kPoison),
|
||||
off((size_t)nl + 5, kPoison), cnt((size_t)nl + 4, kPoison),
|
||||
inv((size_t)T + 4, kPoison);
|
||||
std::vector<float> w((size_t)M * wp, -7.25f);
|
||||
std::vector<uint16_t> gate((size_t)(M + 2) * gp, kGatePoison);
|
||||
RadTensor tf[9];
|
||||
std::memcpy(tf, t, sizeof t);
|
||||
tf[2].data = ids.data();
|
||||
tf[3].data = w.data();
|
||||
tf[4].data = sorted.data();
|
||||
tf[5].data = off.data();
|
||||
tf[6].data = cnt.data();
|
||||
tf[7].data = sh.gate ? gate.data() : nullptr;
|
||||
tf[8] = tf[4];
|
||||
tf[8].data = inv.data();
|
||||
RadArgs a{};
|
||||
a.t = tf;
|
||||
a.n_t = with_inv ? 9 : 8;
|
||||
a.p = p.data();
|
||||
a.n_p = n_p;
|
||||
++cases;
|
||||
const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
int bad = 0;
|
||||
bad += ids != ids_ref;
|
||||
bad += std::memcmp(w.data(), w_ref.data(), w.size() * 4) != 0;
|
||||
bad += std::memcmp(sorted.data(), ks.sorted.data(), (size_t)T * 4) != 0;
|
||||
bad += std::memcmp(off.data(), ks.off.data(), (size_t)(nl + 1) * 4) != 0;
|
||||
bad += std::memcmp(cnt.data(), ks.cnt.data(), (size_t)nl * 4) != 0;
|
||||
if (with_inv) bad += std::memcmp(inv.data(), ks.inv.data(), (size_t)T * 4) != 0;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
bad += sorted[(size_t)T + i] != kPoison || off[(size_t)nl + 1 + i] != kPoison ||
|
||||
cnt[(size_t)nl + i] != kPoison || inv[(size_t)T + i] != kPoison;
|
||||
if (!with_inv)
|
||||
for (int i = 0; i < T; ++i) bad += inv[(size_t)i] != kPoison;
|
||||
for (int r = 0; r < M + 2; ++r)
|
||||
for (int c = 0; c < gp; ++c) {
|
||||
const uint16_t want = sh.gate && r < M && c == 0 ? 0x3f80 : kGatePoison;
|
||||
bad += gate[(size_t)r * gp + c] != want;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf(
|
||||
"FAIL router_sigmoid_topk_scatter at M=%d ne=%d k=%d mode %d slice %d+%d%s%s%s "
|
||||
"(rc %d, %d mismatching outputs)\n",
|
||||
M, ne, k, sh.mode, base, nl, sh.protect ? " protect " : "",
|
||||
sh.protect ? sh.protect : "", with_inv ? " with inverse" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Past the sort's one workgroup: refused, nothing written. */
|
||||
{
|
||||
const int M = 129, ne = 288, k = 8;
|
||||
std::vector<float> lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f),
|
||||
w((size_t)M * k, -7.25f);
|
||||
std::vector<int32_t> ids((size_t)M * k, kPoison), sorted((size_t)M * k, kPoison),
|
||||
off((size_t)ne + 1, kPoison), cnt((size_t)ne, kPoison);
|
||||
RadTensor t[7]{};
|
||||
auto mat = [](RadTensor& x, void* d, uint32_t dt, int r, int c) {
|
||||
x.data = d;
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = c;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
auto vec = [](RadTensor& x, void* d, int n) {
|
||||
x.data = d;
|
||||
x.dtype = RAD_I32;
|
||||
x.rank = 1;
|
||||
x.shape[0] = n;
|
||||
x.stride[0] = 1;
|
||||
};
|
||||
mat(t[0], lg.data(), RAD_F32, M, ne);
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = 1;
|
||||
mat(t[2], ids.data(), RAD_I32, M, k);
|
||||
mat(t[3], w.data(), RAD_F32, M, k);
|
||||
vec(t[4], sorted.data(), M * k);
|
||||
vec(t[5], off.data(), ne + 1);
|
||||
vec(t[6], cnt.data(), ne);
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, 1 };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 2.5;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
++cases;
|
||||
const int rc = r4d_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
if (rc == RAD_OK || ids[0] != kPoison || sorted[0] != kPoison) {
|
||||
std::printf("FAIL router_sigmoid_topk_scatter served M*top_k=%d past the sort's bound "
|
||||
"(rc %d)\n",
|
||||
M * k, rc);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QuantShape {
|
||||
int M, n;
|
||||
float limit;
|
||||
int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */
|
||||
bool y; /* the fused op also writes the bf16 product */
|
||||
};
|
||||
|
||||
void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const QuantShape shapes[] = {
|
||||
{ 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false },
|
||||
{ 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true },
|
||||
{ 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true },
|
||||
{ 2, 260, 0.5f, 2, false },
|
||||
};
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> ud(0, 15);
|
||||
for (const QuantShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, nkb = (n + 127) / 128;
|
||||
const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3;
|
||||
std::vector<uint16_t> gu((size_t)M * gp, f2b(-3.f));
|
||||
const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < 2 * n; ++c) {
|
||||
float v = nd(rng) * 6.f;
|
||||
uint16_t h = f2b(v);
|
||||
if (sh.mode == 1) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = lim;
|
||||
else if (pick == 1)
|
||||
h = past;
|
||||
else if (pick == 2)
|
||||
h = (uint16_t)(lim | 0x8000u);
|
||||
else if (pick == 3)
|
||||
h = (uint16_t)(past | 0x8000u);
|
||||
else if (pick == 4)
|
||||
h = f2b(-200.f);
|
||||
/* rows divisible by 3 hold an all-zero first group */
|
||||
if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0;
|
||||
} else if (sh.mode == 2) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = 0x7fc0; /* NaN */
|
||||
else if (pick == 1)
|
||||
h = 0x7f80; /* +inf */
|
||||
else if (pick == 2)
|
||||
h = 0xff80; /* -inf */
|
||||
}
|
||||
gu[(size_t)r * gp + c] = h;
|
||||
}
|
||||
RadTensor t[4]{};
|
||||
t[0].data = gu.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = 2 * n;
|
||||
t[0].stride[0] = gp;
|
||||
t[0].stride[1] = 1;
|
||||
auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) {
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = pitch;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
RadParam pc[4]{};
|
||||
pc[0] = { "M", RAD_P_INT, M };
|
||||
pc[1] = { "n", RAD_P_INT, n };
|
||||
pc[2].key = "limit";
|
||||
pc[2].kind = RAD_P_F64;
|
||||
pc[2].dval = sh.limit;
|
||||
pc[3].key = "dtype";
|
||||
pc[3].kind = RAD_P_STR;
|
||||
pc[3].sval = "bf16";
|
||||
RadParam pq[4]{};
|
||||
pq[0] = { "M", RAD_P_INT, M };
|
||||
pq[1] = { "n", RAD_P_INT, n };
|
||||
pq[2] = { "group", RAD_P_INT, 128 };
|
||||
pq[3].key = "dtype";
|
||||
pq[3].kind = RAD_P_STR;
|
||||
pq[3].sval = "bf16";
|
||||
RadParam pf[5]{};
|
||||
pf[0] = pc[0];
|
||||
pf[1] = pc[1];
|
||||
pf[2] = pc[2];
|
||||
pf[3] = pq[2];
|
||||
pf[4] = pc[3];
|
||||
|
||||
std::vector<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
|
||||
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
|
||||
std::vector<float> s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f);
|
||||
RadTensor tc[2] = { t[0], {} };
|
||||
mat(tc[1], RAD_BF16, M, n, yp);
|
||||
tc[1].data = y_ref.data();
|
||||
RadArgs ac{};
|
||||
ac.t = tc;
|
||||
ac.n_t = 2;
|
||||
ac.p = pc;
|
||||
ac.n_p = 4;
|
||||
RadTensor tq[3] = { tc[1], {}, {} };
|
||||
mat(tq[1], RAD_F8E4M3, M, n, qp);
|
||||
tq[1].data = q_ref.data();
|
||||
mat(tq[2], RAD_F32, M, nkb, sp);
|
||||
tq[2].data = s_ref.data();
|
||||
RadArgs aq{};
|
||||
aq.t = tq;
|
||||
aq.n_t = 3;
|
||||
aq.p = pq;
|
||||
aq.n_p = 4;
|
||||
++cases;
|
||||
if (r4d_rad_swiglu_clamped(&ac, nullptr) != RAD_OK ||
|
||||
r4d_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
RadTensor tf[4] = { t[0], {}, {}, {} };
|
||||
mat(tf[1], RAD_F8E4M3, M, n, qp);
|
||||
tf[1].data = q.data();
|
||||
mat(tf[2], RAD_F32, M, nkb, sp);
|
||||
tf[2].data = s.data();
|
||||
mat(tf[3], RAD_BF16, M, n, yp);
|
||||
tf[3].data = sh.y ? y.data() : nullptr;
|
||||
RadArgs af{};
|
||||
af.t = tf;
|
||||
af.n_t = 4;
|
||||
af.p = pf;
|
||||
af.n_p = 5;
|
||||
const int rc = r4d_rad_swiglu_clamped_quant_fp8(&af, nullptr);
|
||||
int bad = 0;
|
||||
bad += q != q_ref;
|
||||
bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0;
|
||||
if (sh.y)
|
||||
bad += y != y_ref;
|
||||
else
|
||||
for (uint16_t v : y) bad += v != 0x7e57;
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d "
|
||||
"mismatching outputs)\n",
|
||||
M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GatherShape {
|
||||
int M, n, nl, base;
|
||||
bool f32w; /* GLM's f32 routing weights, else bf16 */
|
||||
int shared; /* 0 none, 1 the ungated arm (gate 1, act none), 2 a sigmoid gate */
|
||||
};
|
||||
|
||||
/* moe_gather's kernel (r4d_moe_gather.h) as its launcher runs it, reading the table moe_scatter_inv
|
||||
* wrote, against the same kernel building the table itself from `sorted` (T <= 512) or reading the
|
||||
* prepass's table (above). Ids are distinct per row from 288 experts, a slice drops slots. */
|
||||
void gather_inverse_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const GatherShape shapes[] = {
|
||||
{ 1, 4096, 288, 0, true, 1 }, { 6, 4096, 288, 0, true, 1 }, { 8, 512, 288, 0, true, 1 },
|
||||
{ 24, 512, 144, 72, true, 1 }, { 48, 256, 288, 0, true, 1 }, { 64, 256, 288, 0, true, 0 },
|
||||
{ 100, 256, 96, 0, true, 1 }, { 6, 300, 288, 0, false, 2 }, { 33, 256, 288, 0, false, 0 },
|
||||
};
|
||||
const int k = 8, ne = 288;
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
for (const GatherShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, T = M * k, nl = sh.nl;
|
||||
std::vector<int32_t> ids((size_t)T);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
std::vector<int32_t> pool(ne);
|
||||
for (int e = 0; e < ne; ++e) pool[(size_t)e] = e;
|
||||
std::shuffle(pool.begin(), pool.end(), rng);
|
||||
for (int j = 0; j < k; ++j) ids[(size_t)(r * k + j)] = pool[(size_t)j];
|
||||
}
|
||||
Scatter plain = scatter_kernel(ids, nl, sh.base, nullptr, false);
|
||||
Scatter inv = scatter_kernel(ids, nl, sh.base, nullptr, true);
|
||||
++cases;
|
||||
if (plain.rc != RAD_OK || inv.rc != RAD_OK || inv.sorted != plain.sorted ||
|
||||
inv.off != plain.off || inv.cnt != plain.cnt || inv.inv != inverse_of(plain.sorted)) {
|
||||
std::printf("FAIL moe_scatter with the inverse at M=%d slice %d+%d\n", M, sh.base, nl);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const int ye_ld = n + 3, ew_ld = k + 2, y_ld = n + 5, sh_ld = n + 1, sg_ld = 2;
|
||||
std::vector<uint16_t> ye((size_t)T * ye_ld), shp((size_t)M * sh_ld), sg((size_t)M * sg_ld);
|
||||
for (auto& v : ye) v = f2b(nd(rng));
|
||||
for (auto& v : shp) v = f2b(nd(rng));
|
||||
for (size_t i = 0; i < sg.size(); ++i) sg[i] = sh.shared == 1 ? f2b(1.f) : f2b(nd(rng));
|
||||
std::vector<float> ewf((size_t)M * ew_ld);
|
||||
std::vector<uint16_t> ewb((size_t)M * ew_ld);
|
||||
for (size_t i = 0; i < ewf.size(); ++i) {
|
||||
ewf[i] = std::fabs(nd(rng)) * 0.3f;
|
||||
ewb[i] = f2b(ewf[i]);
|
||||
}
|
||||
const void* ew = sh.f32w ? (const void*)ewf.data() : (const void*)ewb.data();
|
||||
const uint16_t* shv = sh.shared ? shp.data() : nullptr;
|
||||
const uint16_t* sgv = sh.shared ? sg.data() : nullptr;
|
||||
const int sig = sh.shared == 2;
|
||||
const bool small = T <= (int)r4d_moegather::kGatherSelfT;
|
||||
/* the launcher's rule: the self-scan up to 512 slots, the prepass's table above */
|
||||
const std::vector<int32_t> table = inverse_of(plain.sorted);
|
||||
const unsigned gy = (unsigned)((n + 255) / 256);
|
||||
auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * y_ld, 0x7e57);
|
||||
if (sh.f32w)
|
||||
R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, true>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
else
|
||||
R4D_EMIT(nullptr, (r4d_moegather::gather_kernel<256, false>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
};
|
||||
std::vector<uint16_t> y_old, y_new;
|
||||
if (small)
|
||||
gather(nullptr, plain.sorted.data(), y_old);
|
||||
else
|
||||
gather(table.data(), nullptr, y_old);
|
||||
gather(inv.inv.data(), nullptr, y_new);
|
||||
++cases;
|
||||
if (y_new != y_old) {
|
||||
size_t first = 0;
|
||||
while (first < y_new.size() && y_new[first] == y_old[first]) ++first;
|
||||
std::printf("FAIL moe_gather from the inverse at M=%d n=%d slice %d+%d %s weights, "
|
||||
"shared %d: first difference at %zu\n",
|
||||
M, n, sh.base, nl, sh.f32w ? "f32" : "bf16", sh.shared, first);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
int fails = 0, cases = 0;
|
||||
router_scatter_cases(rng, cases, fails);
|
||||
swiglu_quant_cases(rng, cases, fails);
|
||||
gather_inverse_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
/* tests/r4d_emu: the MXFP4 expert GEMM (r4d_moe_mxfp4.hip) on the host SIMT emulator. Every form
|
||||
* the RADIANCE_MXFP4_* switches reach must match the arithmetic-decode row-group form bit for bit,
|
||||
* and both a host restatement of the per-element sequence: per 128 of K in order, per 32-wide group
|
||||
* a fresh 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale *
|
||||
* E8M0 scale with two roundings and an add. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows,
|
||||
* dropped slots inside runs and past the routed rows, columns an odd expert does not have, a
|
||||
* shorter K for odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes
|
||||
* and pointer tables. The P64 forms (RADIANCE_MXFP4_PREFILL_P64) run at every BM, BN, stage and
|
||||
* column-tile count, pinned below their row bound, with jobs cut at 32 and 64 rows, column
|
||||
* blocks past N and the output through LDS at aligned and odd pitches. The table decode is also
|
||||
* held to the arithmetic one over every code. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "r4d_mxfp4.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
/* The arithmetic decode the kernels used before the table (r4d_moe_mxfp4.hip, fp4x4 and its
|
||||
* byte interleave), restated as the reference of r4d_mxfp4_unpack8_exact. */
|
||||
static uint32_t fp4x4_ref(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4);
|
||||
}
|
||||
static int check_decode() {
|
||||
int fails = 0;
|
||||
auto one = [&](uint32_t w) {
|
||||
const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu);
|
||||
const uint32_t lo_ref = __byte_perm(low, high, 0x5140),
|
||||
hi_ref = __byte_perm(low, high, 0x7362);
|
||||
uint32_t lo, hi, tlo, thi;
|
||||
r4d_mxfp4_unpack8_exact(w, &lo, &hi);
|
||||
r4d_mxfp4_unpack8(w, 0, &tlo, &thi);
|
||||
if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) {
|
||||
if (fails < 4)
|
||||
std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi,
|
||||
lo, hi_ref, lo_ref);
|
||||
++fails;
|
||||
}
|
||||
/* each byte against the e2m1 value it encodes */
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const uint32_t c = (w >> (4 * e)) & 15u;
|
||||
static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f };
|
||||
const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u];
|
||||
const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu);
|
||||
if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) {
|
||||
if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
};
|
||||
/* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves
|
||||
* of the word, and random words over all four */
|
||||
for (uint32_t v = 0; v < 65536; ++v) {
|
||||
one(v);
|
||||
one(v << 16);
|
||||
one(v << 8);
|
||||
}
|
||||
std::mt19937 rng(7);
|
||||
for (int i = 0; i < 200000; ++i) one((uint32_t)rng());
|
||||
return fails;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
int N, K, N_odd, K_odd, parts, top;
|
||||
bool sorted_a, tables, exceptional;
|
||||
std::vector<int> runs;
|
||||
int tail; // dropped slots past the routed rows
|
||||
};
|
||||
|
||||
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
|
||||
* default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap;
|
||||
* the card generates the positive quiet NaN, so a NaN's sign carries no information here. */
|
||||
static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); }
|
||||
static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
for (size_t i = 0; i < a.size() && i < b.size(); ++i)
|
||||
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
|
||||
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
|
||||
}
|
||||
static bool same16(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
return a.size() == b.size() && first_diff(a, b) == a.size();
|
||||
}
|
||||
|
||||
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
|
||||
std::vector<int64_t> stride) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
for (size_t i = 0; i < shape.size(); ++i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = stride[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_decode(), cases = 1;
|
||||
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
|
||||
|
||||
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
|
||||
const Case all[] = {
|
||||
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6 },
|
||||
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
|
||||
2 },
|
||||
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4 },
|
||||
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4 },
|
||||
{ "decode band, row groups of 4",
|
||||
64,
|
||||
384,
|
||||
64,
|
||||
384,
|
||||
2,
|
||||
2,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
{ 0, 1, 15, 16, 17, 30 },
|
||||
3 },
|
||||
{ "decode band, row groups of 1",
|
||||
64,
|
||||
256,
|
||||
32,
|
||||
256,
|
||||
1,
|
||||
2,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
{ 1, 0, 3, 15, 1 },
|
||||
2 },
|
||||
{ "P64 jobs at 32 and 64 rows, N under a block",
|
||||
96,
|
||||
512,
|
||||
96,
|
||||
384,
|
||||
1,
|
||||
2,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
{ 32, 33, 31, 96, 128, 129, 0, 2 },
|
||||
9 },
|
||||
{ "P64 resident A, column tiles cut",
|
||||
192,
|
||||
256,
|
||||
128,
|
||||
128,
|
||||
2,
|
||||
4,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
{ 64, 63, 65, 1, 0, 127, 17 },
|
||||
5 },
|
||||
};
|
||||
struct Form {
|
||||
const char* env;
|
||||
int stage, tiles, lut;
|
||||
const char* kernel;
|
||||
bool prefill;
|
||||
bool pipe = false;
|
||||
};
|
||||
/* env: DECODE_EXPERTS, ALIGNED_JOBS, PREFILL_N32, PREFILL_M32, PREFILL_N64, PREFILL_CACHE_ROWS */
|
||||
const Form forms[] = {
|
||||
{ "100000", 256, 1, 0, "moe_mxfp4_expert_kernel<4, 256, false>", false },
|
||||
{ "100000", 256, 1, 1, "moe_mxfp4_expert_kernel<4, 256, true>", false },
|
||||
{ "100000", 256, 4, 0, "moe_mxfp4_expert_staged_kernel<256, 4, false>", false },
|
||||
{ "100000", 256, 4, 1, "moe_mxfp4_expert_staged_kernel<256, 4, true>", false },
|
||||
{ "100000", 128, 1, 0, "moe_mxfp4_expert_staged_kernel<128, 1, false>", false },
|
||||
{ "100000", 128, 1, 1, "moe_mxfp4_expert_staged_kernel<128, 1, true>", false },
|
||||
{ "100000", 128, 4, 0, "moe_mxfp4_expert_staged_kernel<128, 4, false>", false },
|
||||
{ "100000", 128, 4, 1, "moe_mxfp4_expert_staged_kernel<128, 4, true>", false },
|
||||
{ "000000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", false },
|
||||
{ "010000", 0, 0, 1, "moe_mxfp4_fp8_kernel<1, 1, false, true>", true },
|
||||
{ "001000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true },
|
||||
{ "011000", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 1, false, true>", true },
|
||||
{ "011100", 0, 0, 1, "moe_mxfp4_fp8_kernel<2, 2, false, true>", true },
|
||||
{ "011110", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, false, true>", true },
|
||||
{ "011111", 0, 0, 0, "moe_mxfp4_fp8_kernel<4, 2, true, false>", true },
|
||||
{ "011111", 0, 0, 1, "moe_mxfp4_fp8_kernel<4, 2, true, true>", true },
|
||||
{ "011111", 0, 0, 0, "moe_mxfp4_prefill_kernel<false>", true, true },
|
||||
{ "011111", 0, 0, 1, "moe_mxfp4_prefill_kernel<true>", true, true },
|
||||
};
|
||||
/* P64 at every raster point, column tiles 4 (the resident form's default) and 1, and the LDS
|
||||
* output at the default; the K of a case picks streamed or resident A. */
|
||||
struct P64 {
|
||||
int bm, bn, sk, ct, out, db = 0;
|
||||
};
|
||||
std::vector<P64> p64s;
|
||||
for (int bm : { 32, 64 })
|
||||
for (int bn : { 64, 128 })
|
||||
for (int sk : { 128, 256 })
|
||||
for (int ct : { 1, 4 }) p64s.push_back({ bm, bn, sk, ct, 0 });
|
||||
p64s.push_back({ 64, 128, 128, 4, 1 });
|
||||
p64s.push_back({ 32, 64, 256, 1, 1 });
|
||||
/* The double buffer at every BM x BN x stage: where two stages do not fit in LDS, and with
|
||||
* resident A, the single-buffer form runs. */
|
||||
for (int bm : { 32, 64 })
|
||||
for (int bn : { 64, 128 })
|
||||
for (int sk : { 128, 256 }) p64s.push_back({ bm, bn, sk, 4, 0, 1 });
|
||||
p64s.push_back({ 64, 128, 128, 4, 1, 1 });
|
||||
static const char* const kP64[] = { "RADIANCE_MXFP4_PREFILL_P64",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_MIN_T_GATE_UP",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_MIN_T_DOWN",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_BM",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_BN",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_STAGE_K",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_COLTILES",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_STAGE_OUT",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_T_BM64",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_T_BN128",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_T_DOWN_WIDE",
|
||||
"RADIANCE_MXFP4_PREFILL_P64_DB" };
|
||||
/* The rule's tile with nothing pinned, by its row bounds (unset: this test's few rows are
|
||||
* under all of them); the widest tiles take the LDS output. */
|
||||
struct Rule {
|
||||
const char* t_bm64;
|
||||
const char* t_bn128;
|
||||
const char* t_down;
|
||||
const char* streamed;
|
||||
const char* resident;
|
||||
};
|
||||
const Rule rules[] = { { nullptr, nullptr, nullptr, "<32, 64, 256, 1, false>",
|
||||
"<32, 64, 128, 4, true>" },
|
||||
{ "0", nullptr, nullptr, "<64, 64, 256, 1, false>", "<32, 64, 128, 4, true>" },
|
||||
{ "0", "0", "0", "<64, 128, 128, 1, false>", "<64, 128, 128, 4, true>" } };
|
||||
static const char* const kEnv[] = {
|
||||
"RADIANCE_MXFP4_DECODE_EXPERTS", "RADIANCE_MXFP4_ALIGNED_JOBS",
|
||||
"RADIANCE_MXFP4_PREFILL_N32", "RADIANCE_MXFP4_PREFILL_M32",
|
||||
"RADIANCE_MXFP4_PREFILL_N64", "RADIANCE_MXFP4_PREFILL_CACHE_ROWS"
|
||||
};
|
||||
|
||||
for (const Case& c : all) {
|
||||
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
|
||||
int routed = 0;
|
||||
for (int r : c.runs) routed += r;
|
||||
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
|
||||
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
|
||||
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
|
||||
yp = OUT + ((&c - all) % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1000 + cases);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
|
||||
std::vector<float> as((size_t)Arows * asp);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
// A dropped slot about every eleventh row, the first rows of some runs included.
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
|
||||
nexp[2] = { (E + 1) / 2, E / 2 };
|
||||
std::vector<uint8_t> w[2], s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
w[q].resize((size_t)nexp[q] * n[q] * k[q] / 2);
|
||||
s[q].resize((size_t)nexp[q] * n[q] * k[q] / 32);
|
||||
for (auto& v : w[q]) v = (uint8_t)rng();
|
||||
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
|
||||
for (size_t i = 0; i < s[q].size(); ++i)
|
||||
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
|
||||
: (uint8_t)(118 + rng() % 16);
|
||||
for (int x = 0; x < nexp[q]; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)x * n[q] * k[q] / 2);
|
||||
st[q].push_back(s[q].data() + (size_t)x * n[q] * k[q] / 32);
|
||||
}
|
||||
}
|
||||
auto plane = [&](int q, bool scale) {
|
||||
const int64_t cols = scale ? k[q] / 32 : k[q];
|
||||
void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data())
|
||||
: (void*)(scale ? s[q].data() : w[q].data());
|
||||
RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols },
|
||||
{ c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 });
|
||||
return t;
|
||||
};
|
||||
|
||||
/* the per-element sequence, on the host */
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int col = 0; col < OUT; ++col) {
|
||||
uint16_t& out = ref[(size_t)r * yp + col];
|
||||
out = 0;
|
||||
if (owner[r] < 0 || sorted[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top;
|
||||
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
|
||||
const bool valid = within < cw;
|
||||
const int wn = (col / pw) * cw + within;
|
||||
const uint8_t* wr =
|
||||
w[q].data() + (size_t)(e / 2) * n[q] * k[q] / 2 + (size_t)wn * k[q] / 2;
|
||||
const uint8_t* sr =
|
||||
s[q].data() + (size_t)(e / 2) * n[q] * k[q] / 32 + (size_t)wn * k[q] / 32;
|
||||
float total = 0.f;
|
||||
for (int kb = 0; kb < k[q]; kb += 128)
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
float raw = 0.f;
|
||||
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk) {
|
||||
const uint32_t code = valid ? (wr[kk / 2] >> (4 * (kk & 1))) & 15u : 0u;
|
||||
uint32_t lo, hi;
|
||||
r4d_mxfp4_unpack8_exact(code, &lo, &hi);
|
||||
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + kk]) *
|
||||
rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
|
||||
}
|
||||
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
|
||||
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
|
||||
float scale;
|
||||
std::memcpy(&scale, &bits, 4);
|
||||
float t = raw * as[(size_t)ar * asp + kb / 128];
|
||||
t = t * scale;
|
||||
total = total + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &total, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
|
||||
16); // f32_to_bf16, r4d_common.h
|
||||
}
|
||||
|
||||
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
|
||||
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
|
||||
plane(0, false),
|
||||
plane(0, true),
|
||||
ten(sorted.data(), RAD_I32, { T }, { 1 }),
|
||||
ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }),
|
||||
plane(1, false),
|
||||
plane(1, true),
|
||||
RadTensor{} };
|
||||
RadParam p[11]{};
|
||||
auto pi = [](const char* key, long long v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
return x;
|
||||
};
|
||||
auto ps = [](const char* key, const char* v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_STR;
|
||||
x.sval = v;
|
||||
return x;
|
||||
};
|
||||
p[0] = pi("M", T / c.top);
|
||||
p[1] = pi("N", c.N);
|
||||
p[2] = pi("K", c.K);
|
||||
p[3] = pi("N_odd", c.N_odd);
|
||||
p[4] = pi("K_odd", c.K_odd);
|
||||
p[5] = pi("n_expert", E);
|
||||
p[6] = pi("top_k", c.top);
|
||||
p[7] = pi("parts", c.parts);
|
||||
p[8] = pi("group", 128);
|
||||
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
|
||||
p[10] = ps("dtype", "mxfp4a8");
|
||||
auto run = [&](const Form& f, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)T * yp, 0x7777);
|
||||
t[8] = ten(y.data(), RAD_BF16, { T, OUT }, { yp, 1 });
|
||||
for (int i = 0; i < 6; ++i) setenv(kEnv[i], f.env[i] == '1' ? "1" : "0", 1);
|
||||
if (f.stage) {
|
||||
setenv("RADIANCE_MXFP4_EXPERTS_STAGE_K", std::to_string(f.stage).c_str(), 1);
|
||||
setenv("RADIANCE_MXFP4_EXPERTS_COLTILES", std::to_string(f.tiles).c_str(), 1);
|
||||
}
|
||||
setenv("RADIANCE_MXFP4_LUT", f.lut ? "1" : "0", 1);
|
||||
setenv("RADIANCE_MXFP4_PREFILL_PIPE", f.pipe ? "1" : "0", 1);
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 11;
|
||||
emu_last_kernel = "";
|
||||
return r4d_rad_moe_mxfp4(&ar, nullptr);
|
||||
};
|
||||
auto run_p64 = [&](const P64& f, std::vector<uint16_t>& y) {
|
||||
const int v[8] = { 1, 0, 0, f.bm, f.bn, f.sk, f.ct, f.out };
|
||||
for (int i = 0; i < 8; ++i) setenv(kP64[i], std::to_string(v[i]).c_str(), 1);
|
||||
setenv(kP64[11], f.db ? "1" : "0", 1);
|
||||
const Form base = { "000000", 0, 0, 1, "", false };
|
||||
const int rc = run(base, y);
|
||||
setenv(kP64[0], "0", 1);
|
||||
return rc;
|
||||
};
|
||||
const Form alt = { "000000", 0, 0, 0, "moe_mxfp4_fp8_kernel<1, 1, false, false>", false };
|
||||
std::vector<uint16_t> legacy, got;
|
||||
++cases;
|
||||
int rc = run(alt, legacy);
|
||||
if (rc != RAD_OK || !std::strstr(emu_last_kernel, alt.kernel)) {
|
||||
std::printf("FAIL %s: reference form rc %d kernel %s\n", c.name, rc, emu_last_kernel);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
if (!same16(legacy, ref)) {
|
||||
const size_t i = first_diff(legacy, ref);
|
||||
std::printf("FAIL %s: reference form against the host sequence at row %zu col %zu: "
|
||||
"%04x, want %04x\n",
|
||||
c.name, i / yp, i % yp, legacy[i], ref[i]);
|
||||
++fails;
|
||||
}
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (live < T * OUT / 3) {
|
||||
std::printf("FAIL %s: output mostly zero\n", c.name);
|
||||
++fails;
|
||||
}
|
||||
for (const Form& f : forms) {
|
||||
if (f.prefill && T < 512) continue;
|
||||
++cases;
|
||||
rc = run(f, got);
|
||||
const bool reached = std::strstr(emu_last_kernel, f.kernel) != nullptr;
|
||||
if (rc != RAD_OK || !reached || !same16(got, legacy)) {
|
||||
const size_t i = first_diff(got, legacy);
|
||||
std::printf(
|
||||
"FAIL %s: form %s stage %d tiles %d lut %d ran %s (want %s), rc %d, first "
|
||||
"word %zu\n",
|
||||
c.name, f.env, f.stage, f.tiles, f.lut, emu_last_kernel, f.kernel, rc, i);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
const bool resident = NK <= 256;
|
||||
for (const Rule& u : rules) {
|
||||
++cases;
|
||||
for (const char* v : kP64) unsetenv(v);
|
||||
setenv(kP64[0], "1", 1);
|
||||
setenv(kP64[1], "0", 1);
|
||||
setenv(kP64[2], "0", 1);
|
||||
if (u.t_bm64) setenv(kP64[8], u.t_bm64, 1);
|
||||
if (u.t_bn128) setenv(kP64[9], u.t_bn128, 1);
|
||||
if (u.t_down) setenv(kP64[10], u.t_down, 1);
|
||||
const Form base = { "000000", 0, 0, 1, "", false };
|
||||
rc = run(base, got);
|
||||
for (const char* v : kP64) unsetenv(v);
|
||||
const std::string want =
|
||||
std::string("moe_mxfp4_p64_kernel") + (resident ? u.resident : u.streamed);
|
||||
if (rc != RAD_OK || !std::strstr(emu_last_kernel, want.c_str()) ||
|
||||
!same16(got, legacy)) {
|
||||
std::printf("FAIL %s: P64 rule ran %s (want %s), rc %d, first word %zu\n", c.name,
|
||||
emu_last_kernel, want.c_str(), rc, first_diff(got, legacy));
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
for (const P64& f : p64s) {
|
||||
++cases;
|
||||
rc = run_p64(f, got);
|
||||
const bool db = f.db && !resident && (f.sk == 128 || (f.bm == 32 && f.bn == 64));
|
||||
const std::string want = "moe_mxfp4_p64_kernel<" + std::to_string(f.bm) + ", " +
|
||||
std::to_string(f.bn) + ", " + std::to_string(f.sk) + ", " +
|
||||
(resident ? std::to_string(f.ct) : "1") + ", " +
|
||||
(resident ? "true" : "false") + (db ? ", true>" : ">");
|
||||
const bool reached = std::strstr(emu_last_kernel, want.c_str()) != nullptr;
|
||||
if (rc != RAD_OK || !reached || !same16(got, legacy)) {
|
||||
const size_t i = first_diff(got, legacy);
|
||||
std::printf("FAIL %s: P64 bm %d bn %d stage %d tiles %d out %d db %d ran %s (want "
|
||||
"%s), rc %d, "
|
||||
"first word %zu (row %zu col %zu: %04x, want %04x)\n",
|
||||
c.name, f.bm, f.bn, f.sk, f.ct, f.out, f.db, emu_last_kernel,
|
||||
want.c_str(), rc, i, i / yp, i % yp, i < got.size() ? got[i] : 0,
|
||||
i < legacy.size() ? legacy[i] : 0);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const char* v : kEnv) unsetenv(v);
|
||||
for (const char* v : kP64) unsetenv(v);
|
||||
unsetenv("RADIANCE_MXFP4_EXPERTS_STAGE_K");
|
||||
unsetenv("RADIANCE_MXFP4_EXPERTS_COLTILES");
|
||||
unsetenv("RADIANCE_MXFP4_LUT");
|
||||
unsetenv("RADIANCE_MXFP4_PREFILL_PIPE");
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user