Archived
tests: g4k_emu -- gemma4k's kernel source on the host, every GPU thread a fiber
gemma4k builds for gfx12 only and its two joins have no libref oracle, so nothing on a machine without the card, and nothing in rad-kbench, would ever run its kernels. g4k_emu compiles the .hip sources as host C++ against a HIP shim: every GPU thread a fiber, __syncthreads and every cross-lane op a barrier (one not reached uniformly is reported as a deadlock), the WMMA operand layouts gfx12's. Checked against a port of libref's ref_attn_paged (attention, fixed cases and a random sweep over every compiled geometry), against the host rows (pair_argmax), and against the unfused chain bit for bit (the joins). Registered in CTest under the label g4k_emu, on x86-64 with a clang: the kernels use ext_vector_type and the fiber switch is SysV inline assembly. Under a clang C++ compiler they are ordinary targets. The docker image compiles host C++ with g++, so there g4k_emu/run.sh builds the same tests with the HIP compiler, ROCm's own clang++, and runs them as one test -- so wherever gemma4k is built, this runs, the image's host-test stage included. About 40 s at the default 40-case sweep (50 s through run.sh, which compiles too); `g4k_emu_attn sweep 200` is the long run. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
833173cc04
commit
846e52148a
7 files changed
+840
No files matched your search
@@ -181,6 +181,53 @@ if(TARGET libavx AND TARGET rad-avx-check)
|
||||
set_tests_properties(avx_check PROPERTIES TIMEOUT 600)
|
||||
endif()
|
||||
|
||||
# ================================================================== gemma4k's kernels, on the host
|
||||
#
|
||||
# gemma4k builds for gfx12 only, and two of its ops (the sandwich-norm joins) have no libref oracle
|
||||
# by design (docs/OPS.md), so neither rad-kbench nor a no-card machine would ever run its kernels.
|
||||
# g4k_emu runs their SOURCE on the host instead: emu/hip/hip_runtime.h supplies the HIP names, every
|
||||
# GPU thread is a fiber, __syncthreads and every cross-lane op a barrier (one not reached uniformly
|
||||
# is reported as a deadlock), and the kernels' launch macro is pointed at the emulator. Checked
|
||||
# against a port of libref's ref_attn_paged, against the host rows, and -- for the joins -- against
|
||||
# the unfused chain, bit for bit.
|
||||
#
|
||||
# CLANG AND x86-64: the kernels use clang's ext_vector_type, and the fiber switch is x86-64 SysV
|
||||
# inline assembly. Under a clang C++ compiler they are ordinary targets here, the .hip files
|
||||
# compiled as C++ (`-x c++`, which is what makes them host code; the property is per directory, so
|
||||
# gemma4k's own HIP build is untouched). Under g++ -- the docker image's -- a build with a card
|
||||
# still has a clang: its HIP compiler, ROCm's own clang++, and g4k_emu/run.sh builds and runs the
|
||||
# same tests with that. So wherever gemma4k is built, this runs.
|
||||
set(G4K_DIR ${CMAKE_SOURCE_DIR}/gemma4k)
|
||||
set(G4K_EMU ${CMAKE_CURRENT_SOURCE_DIR}/g4k_emu)
|
||||
if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$")
|
||||
# no fiber switch for this ISA: nothing to register
|
||||
elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
|
||||
set(G4K_HIP ${G4K_DIR}/g4k_attn.hip ${G4K_DIR}/g4k_pick.hip ${G4K_DIR}/g4k_norm.hip)
|
||||
set_source_files_properties(${G4K_HIP} PROPERTIES LANGUAGE CXX COMPILE_OPTIONS "-x;c++")
|
||||
add_library(g4k_emu_kernels OBJECT ${G4K_HIP} ${G4K_DIR}/g4k_rows.cpp ${G4K_EMU}/emu/emu.cpp)
|
||||
target_include_directories(g4k_emu_kernels PUBLIC ${G4K_EMU}/emu ${G4K_DIR})
|
||||
target_link_libraries(g4k_emu_kernels PUBLIC rad_abi)
|
||||
# As libr4d compiles every unit: the joins are held to the chain bit for bit, and a contracted
|
||||
# multiply-add is a different rounding.
|
||||
target_compile_options(g4k_emu_kernels PRIVATE -ffp-contract=off -Wno-psabi)
|
||||
foreach(t attn pick norm)
|
||||
add_executable(g4k_emu_${t} ${G4K_EMU}/test_${t}.cpp)
|
||||
target_link_libraries(g4k_emu_${t} PRIVATE g4k_emu_kernels)
|
||||
target_compile_options(g4k_emu_${t} PRIVATE -ffp-contract=off -Wno-psabi)
|
||||
set_target_properties(g4k_emu_${t} PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/tests)
|
||||
add_test(NAME g4k_emu_${t} COMMAND g4k_emu_${t})
|
||||
endforeach()
|
||||
# The random sweep at a size the inner loop can afford; `g4k_emu_attn sweep 200` is the long one.
|
||||
add_test(NAME g4k_emu_attn_sweep COMMAND g4k_emu_attn sweep 40)
|
||||
set_tests_properties(g4k_emu_attn g4k_emu_pick g4k_emu_norm g4k_emu_attn_sweep
|
||||
PROPERTIES LABELS "g4k_emu" TIMEOUT 600)
|
||||
elseif(RAD_HIP_FOUND AND CMAKE_HIP_COMPILER_ID MATCHES "Clang")
|
||||
add_test(NAME g4k_emu
|
||||
COMMAND sh ${G4K_EMU}/run.sh ${CMAKE_HIP_COMPILER} ${CMAKE_SOURCE_DIR}/abi ${G4K_DIR}
|
||||
${CMAKE_CURRENT_BINARY_DIR}/g4k_emu 40)
|
||||
set_tests_properties(g4k_emu PROPERTIES LABELS "g4k_emu" TIMEOUT 900)
|
||||
endif()
|
||||
|
||||
# ================================================================== the document as a test
|
||||
#
|
||||
# docs/OPS.md calls its resolved table "THE AUTHORITY FOR THE OPS IN IT" and says of itself that
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
#include "hip/hip_runtime.h"
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
|
||||
/* ---- the context switch: callee-saved registers and the stack pointer (x86-64 SysV) */
|
||||
extern "C" void emu_switch(void** save_sp, void* new_sp);
|
||||
asm(R"(
|
||||
.text
|
||||
.globl emu_switch
|
||||
.type emu_switch,@function
|
||||
emu_switch:
|
||||
pushq %rbp
|
||||
pushq %rbx
|
||||
pushq %r12
|
||||
pushq %r13
|
||||
pushq %r14
|
||||
pushq %r15
|
||||
movq %rsp, (%rdi)
|
||||
movq %rsi, %rsp
|
||||
popq %r15
|
||||
popq %r14
|
||||
popq %r13
|
||||
popq %r12
|
||||
popq %rbx
|
||||
popq %rbp
|
||||
ret
|
||||
)");
|
||||
|
||||
namespace {
|
||||
constexpr size_t kStack = 512 * 1024;
|
||||
struct Fiber {
|
||||
void* sp = nullptr;
|
||||
std::vector<char> stack;
|
||||
EmuIdx tid{};
|
||||
bool done = false;
|
||||
unsigned bar_gen = 0; /* block barrier generation this fiber waits on */
|
||||
unsigned wbar_gen = 0;
|
||||
int waiting = 0; /* 0 run, 1 block barrier, 2 wave barrier */
|
||||
};
|
||||
struct Sched {
|
||||
std::vector<Fiber> f;
|
||||
void* main_sp = nullptr;
|
||||
int cur = -1, nthreads = 0;
|
||||
EmuIdx bid{};
|
||||
void (*body)(void*) = nullptr;
|
||||
void* ctx = nullptr;
|
||||
/* block barrier */
|
||||
int arrive = 0; unsigned gen = 0;
|
||||
/* wave barriers and exchange slots, double-buffered by parity */
|
||||
int warrive[64] = {}; unsigned wgen[64] = {};
|
||||
int slot[64][2][32] = {};
|
||||
unsigned xparity[1024] = {};
|
||||
} S;
|
||||
|
||||
void yield() { Fiber& me = S.f[S.cur]; emu_switch(&me.sp, S.main_sp); }
|
||||
|
||||
extern "C" void emu_trampoline() {
|
||||
S.body(S.ctx);
|
||||
S.f[S.cur].done = true;
|
||||
yield();
|
||||
std::abort();
|
||||
}
|
||||
/* the entry a fresh stack "returns" into, keeping the SysV alignment at call boundaries */
|
||||
asm(R"(
|
||||
.text
|
||||
.globl emu_entry
|
||||
.type emu_entry,@function
|
||||
emu_entry:
|
||||
andq $-16, %rsp
|
||||
call emu_trampoline
|
||||
ud2
|
||||
)");
|
||||
extern "C" void emu_entry();
|
||||
} // namespace
|
||||
|
||||
EmuIdx& emu_thread_idx() { return S.f[S.cur].tid; }
|
||||
EmuIdx& emu_block_idx() { return S.bid; }
|
||||
|
||||
void __syncthreads() {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.gen;
|
||||
if (++S.arrive == S.nthreads) { S.arrive = 0; ++S.gen; return; }
|
||||
me.waiting = 1;
|
||||
while (S.gen == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
|
||||
static void wave_barrier(int w) {
|
||||
Fiber& me = S.f[S.cur];
|
||||
const unsigned g = S.wgen[w];
|
||||
if (++S.warrive[w] == 32) { S.warrive[w] = 0; ++S.wgen[w]; return; }
|
||||
me.waiting = 2;
|
||||
while (S.wgen[w] == g) yield();
|
||||
me.waiting = 0;
|
||||
}
|
||||
|
||||
int emu_bpermute(int addr, int v) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
S.slot[w][par][l] = v;
|
||||
wave_barrier(w);
|
||||
return S.slot[w][par][(addr >> 2) & 31];
|
||||
}
|
||||
int emu_readlane(int v, int lane) { return emu_bpermute(lane << 2, v); }
|
||||
static short g_wa[64][2][32][8], g_wb[64][2][32][8];
|
||||
emu_v8f emu_wmma_bf16(emu_v8s a, emu_v8s b, emu_v8f c) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
for (int e = 0; e < 8; ++e) { g_wa[w][par][l][e] = a[e]; g_wb[w][par][l][e] = b[e]; }
|
||||
wave_barrier(w);
|
||||
auto bf = [](short v) { unsigned u = (unsigned)(unsigned short)v << 16; float f; std::memcpy(&f, &u, 4); return f; };
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 8 * h + e;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += bf(g_wa[w][par][M + 16 * (k >> 3)][k & 7]) * bf(g_wb[w][par][N + 16 * (k >> 3)][k & 7]);
|
||||
d[e] = acc;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
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) {
|
||||
const int t = (int)S.f[S.cur].tid.x, w = t >> 5, l = t & 31;
|
||||
const unsigned par = S.xparity[t]++ & 1u;
|
||||
for (int e = 0; e < 8; ++e) { g_ha[w][par][l][e] = a[e]; g_hb[w][par][l][e] = b[e]; }
|
||||
wave_barrier(w);
|
||||
const int N = l & 15, h = l >> 4;
|
||||
emu_v8f d;
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int M = 8 * h + e;
|
||||
float acc = c[e];
|
||||
for (int k = 0; k < 16; ++k)
|
||||
acc += (float)g_ha[w][par][M + 16 * (k >> 3)][k & 7] * (float)g_hb[w][par][N + 16 * (k >> 3)][k & 7];
|
||||
d[e] = acc;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
unsigned emu_ballot(bool p) {
|
||||
unsigned m = 0;
|
||||
for (int l = 0; l < 32; ++l) m |= (unsigned)(emu_readlane(p ? 1 : 0, l) & 1) << l;
|
||||
return m;
|
||||
}
|
||||
|
||||
int emu_grids = 0;
|
||||
int emu_last_block = 0;
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx) {
|
||||
++emu_grids;
|
||||
const int n = (int)(block.x * block.y * block.z);
|
||||
emu_last_block = n;
|
||||
if (block.y != 1 || block.z != 1 || n % 32 || n > 1024) { std::fprintf(stderr, "emu: block shape\n"); std::abort(); }
|
||||
S.body = body; S.ctx = ctx; S.nthreads = n;
|
||||
S.f.resize(n);
|
||||
for (auto& f : S.f) if (f.stack.size() != kStack) f.stack.assign(kStack, 0);
|
||||
for (unsigned bz = 0; bz < grid.z; ++bz)
|
||||
for (unsigned by = 0; by < grid.y; ++by)
|
||||
for (unsigned bx = 0; bx < grid.x; ++bx) {
|
||||
S.bid = EmuIdx{bx, by, bz};
|
||||
S.arrive = 0; S.gen = 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];
|
||||
f.done = false; f.waiting = 0; f.tid = EmuIdx{(unsigned)t, 0, 0};
|
||||
S.xparity[t] = 0;
|
||||
/* a fresh stack: six callee-saved slots, then the entry as the return address */
|
||||
void** top = (void**)(f.stack.data() + kStack - 64);
|
||||
*--top = (void*)&emu_entry;
|
||||
for (int r = 0; r < 6; ++r) *--top = nullptr;
|
||||
f.sp = top;
|
||||
}
|
||||
int live = n;
|
||||
while (live > 0) {
|
||||
int progressed = 0;
|
||||
const int live_before = live;
|
||||
const unsigned g0 = S.gen; unsigned wg0[64]; for (int w = 0; w < 64; ++w) wg0[w] = S.wgen[w];
|
||||
int arr0 = S.arrive; int warr0[64]; for (int w = 0; w < 64; ++w) warr0[w] = S.warrive[w];
|
||||
live = 0;
|
||||
for (int t = 0; t < n; ++t) {
|
||||
if (S.f[t].done) continue;
|
||||
S.cur = t;
|
||||
emu_switch(&S.main_sp, S.f[t].sp);
|
||||
S.cur = -1;
|
||||
if (!S.f[t].done) ++live;
|
||||
}
|
||||
progressed = S.gen != g0 || S.arrive != arr0 || live != live_before;
|
||||
for (int w = 0; w < 64; ++w) progressed |= (S.wgen[w] != wg0[w]) || (S.warrive[w] != warr0[w]);
|
||||
if (live > 0 && !progressed) {
|
||||
int done = 0, wb = 0, bb = 0;
|
||||
for (auto& f : S.f) { done += f.done; wb += f.waiting == 2; bb += f.waiting == 1; }
|
||||
std::fprintf(stderr, "emu: DEADLOCK in block (%u,%u,%u): %d threads done, %d at a block "
|
||||
"barrier, %d at a wave barrier -- a barrier not reached uniformly\n",
|
||||
bx, by, bz, done, bb, wb);
|
||||
std::abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/* tests/g4k_emu: SIMT EMULATOR SHIM -- runs gemma4k's kernel source on the host. Every GPU thread is a fiber on
|
||||
* one OS thread; __syncthreads and every cross-lane op are barriers the scheduler enforces, and a
|
||||
* barrier some threads never reach is reported as a deadlock rather than hung. Test-only. */
|
||||
#pragma once
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#define __global__
|
||||
#define __device__
|
||||
#define __host__
|
||||
#define __shared__ static
|
||||
#define __forceinline__ inline
|
||||
#define __launch_bounds__(n)
|
||||
|
||||
struct dim3 {
|
||||
unsigned x, y, z;
|
||||
constexpr dim3(unsigned a = 1, unsigned b = 1, unsigned c = 1) : x(a), y(b), z(c) {}
|
||||
};
|
||||
typedef void* hipStream_t;
|
||||
typedef int hipError_t;
|
||||
enum { hipSuccess = 0 };
|
||||
inline hipError_t hipGetLastError() { return 0; }
|
||||
|
||||
struct EmuIdx { unsigned x, y, z; };
|
||||
EmuIdx& emu_thread_idx();
|
||||
EmuIdx& emu_block_idx();
|
||||
#define threadIdx (emu_thread_idx())
|
||||
#define blockIdx (emu_block_idx())
|
||||
void __syncthreads();
|
||||
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))
|
||||
#define __builtin_amdgcn_readlane(v, l) emu_readlane((v), (l))
|
||||
unsigned emu_ballot(bool p);
|
||||
#define __builtin_amdgcn_ballot_w32(p) emu_ballot((p))
|
||||
/* 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);
|
||||
#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))
|
||||
extern int emu_last_block; /* threads a block of the last grid had: which kernel ran */
|
||||
|
||||
struct alignas(8) uint2 { unsigned x, y; };
|
||||
struct alignas(16) uint4 { unsigned x, y, z, w; };
|
||||
struct alignas(16) float4 { float x, y, z, w; };
|
||||
inline uint4 make_uint4(unsigned a, unsigned b, unsigned c, unsigned d) { return uint4{a, b, c, d}; }
|
||||
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 */
|
||||
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; }
|
||||
|
||||
/* one block at a time, every thread a fiber */
|
||||
void emu_run_grid(dim3 grid, dim3 block, void (*body)(void*), void* ctx);
|
||||
template <typename K, typename A>
|
||||
struct EmuCall { K k; A a; static void run(void* p) { auto* c = (EmuCall*)p; c->k(c->a); } };
|
||||
template <typename A>
|
||||
void emu_launch(void (*k)(A), dim3 g, dim3 b, A a) {
|
||||
EmuCall<void (*)(A), A> c{k, a};
|
||||
emu_run_grid(g, b, &EmuCall<void (*)(A), A>::run, &c);
|
||||
}
|
||||
#define G4K_LAUNCH(kernel, grid, block, stream, ...) emu_launch(&kernel, grid, block, __VA_ARGS__)
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
# tests/g4k_emu/run.sh -- build and run g4k_emu with a clang that is not the build's C++ compiler.
|
||||
#
|
||||
# A build whose C++ compiler is clang builds these as ordinary targets (tests/CMakeLists.txt). The
|
||||
# docker image compiles host C++ with g++, which has no ext_vector_type; its HIP compiler is ROCm's
|
||||
# own clang++, and with `-x c++` that compiles the kernel sources as the host code this test needs.
|
||||
#
|
||||
# run.sh <clang++> <abi dir> <gemma4k dir> <work dir> [sweep cases]
|
||||
set -e
|
||||
CXX=${1:?usage: run.sh <clang++> <abi dir> <gemma4k dir> <work dir> [sweep cases]}
|
||||
ABI=$2; G=$3; B=$4; N=${5:-40}
|
||||
HERE=$(cd "$(dirname "$0")" && pwd)
|
||||
mkdir -p "$B"
|
||||
F="-std=c++20 -O2 -ffp-contract=off -Wno-psabi -I$HERE/emu -I$ABI -I$G"
|
||||
for u in attn pick norm; do $CXX $F -x c++ -c "$G/g4k_$u.hip" -o "$B/k_$u.o"; done
|
||||
$CXX $F -c "$G/g4k_rows.cpp" -o "$B/rows.o"
|
||||
$CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o"
|
||||
for t in attn pick norm; do
|
||||
$CXX $F -c "$HERE/test_$t.cpp" -o "$B/test_$t.o"
|
||||
$CXX "$B/test_$t.o" "$B/k_attn.o" "$B/k_pick.o" "$B/k_norm.o" "$B/rows.o" "$B/emu.o" -o "$B/test_$t"
|
||||
done
|
||||
"$B/test_attn"
|
||||
"$B/test_attn" sweep "$N"
|
||||
"$B/test_pick"
|
||||
"$B/test_norm"
|
||||
@@ -0,0 +1,249 @@
|
||||
/* Drives gemma4k's attn_paged entry points through the SIMT emulator and checks every output
|
||||
* element against a port of libref's ref_attn_paged (same mask predicates, f64 accumulation). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "g4k.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::mt19937 rng(1234);
|
||||
extern int emu_grids;
|
||||
extern int emu_last_block; /* threads a block of the last grid: 512 is the WMMA kernel */
|
||||
static float nrm() { static std::normal_distribution<float> d(0.f, 1.f); return d(rng); }
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
int hd, gqa, kvh;
|
||||
bool fp8, causal, ragged, descale;
|
||||
int window;
|
||||
std::vector<int> qlen, ctx; /* per sequence */
|
||||
int missing_block = -1; /* sequence 0's block index to mark -1, or -1 */
|
||||
long long max_ctx = 0; /* 0: not passed */
|
||||
int64_t scratch = 0; /* 0: no scratch */
|
||||
int qpitch_extra = 0; /* q as a column slice of a wider buffer */
|
||||
int expect_wmma = -1; /* 1: must take the WMMA kernel, 0: must not, -1: either */
|
||||
};
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
static Fn pick(int hd, int gqa, bool fp8) {
|
||||
#define P(H, G) if (hd == H && gqa == G) return fp8 ? g4k_attn_h##H##_gqa##G##_fp8kv : g4k_attn_h##H##_gqa##G##_bf16kv;
|
||||
P(256, 1) P(256, 2) P(256, 4) P(256, 8) P(512, 1) P(512, 2) P(512, 4) P(512, 8)
|
||||
#undef P
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static int run(const Case& c) {
|
||||
const int n_seq = (int)c.qlen.size(), HD = c.hd, kvh = c.kvh, qh = kvh * c.gqa;
|
||||
int rows = 0; for (int q : c.qlen) rows += q;
|
||||
/* blocks: each sequence gets ceil(ctx/16) blocks at shuffled ids */
|
||||
int maxb = 0; for (int x : c.ctx) maxb = std::max(maxb, (x + 15) / 16);
|
||||
maxb += 1; /* a spare column: the table is wider than any sequence needs */
|
||||
const int nblocks = n_seq * maxb + 3;
|
||||
std::vector<int> ids(nblocks); for (int i = 0; i < nblocks; ++i) ids[i] = i;
|
||||
std::shuffle(ids.begin(), ids.end(), rng);
|
||||
std::vector<int> bt(n_seq * maxb, -1);
|
||||
int nx = 0;
|
||||
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < (c.ctx[s] + 15) / 16; ++b) bt[s * maxb + b] = ids[nx++];
|
||||
if (c.missing_block >= 0) bt[c.missing_block] = -1;
|
||||
/* the cache, filled everywhere -- including slots past each context, with NaN in some, so a
|
||||
* kernel that reads a masked key's V without guarding is caught */
|
||||
const int64_t slot = 2 * HD, nel = (int64_t)nblocks * kvh * 16 * slot;
|
||||
std::vector<float> kvf(nel);
|
||||
std::vector<uint16_t> kvb(nel); std::vector<uint8_t> kv8(nel);
|
||||
for (int64_t i = 0; i < nel; ++i) {
|
||||
float v = nrm();
|
||||
if (c.fp8) { kv8[i] = rad_f32_to_fp8e4m3(v * 4.f); kvf[i] = rad_fp8e4m3_to_f32(kv8[i]); }
|
||||
else { kvb[i] = rad_f32_to_bf16(v); kvf[i] = rad_bf16_to_f32(kvb[i]); }
|
||||
}
|
||||
/* poison: every slot at or past a sequence's context in its last block, and every block no
|
||||
* table names */
|
||||
std::vector<char> named(nblocks, 0);
|
||||
for (int s = 0; s < n_seq; ++s) for (int b = 0; b < maxb; ++b) if (bt[s * maxb + b] >= 0) named[bt[s * maxb + b]] = 1;
|
||||
auto poison = [&](int64_t i) { if (c.fp8) { kv8[i] = 0x7f; } else { kvb[i] = 0x7fc0; } kvf[i] = NAN; };
|
||||
for (int blk = 0; blk < nblocks; ++blk) if (!named[blk]) for (int64_t i = 0; i < kvh * 16 * slot; ++i) poison((int64_t)blk * kvh * 16 * slot + i);
|
||||
for (int s = 0; s < n_seq; ++s) {
|
||||
const int last = (c.ctx[s] - 1) / 16, blk = bt[s * maxb + last];
|
||||
if (blk < 0) continue;
|
||||
for (int o = c.ctx[s] % 16 ? c.ctx[s] % 16 : 16; o < 16; ++o)
|
||||
for (int h = 0; h < kvh; ++h) for (int d = 0; d < slot; ++d) poison((((int64_t)blk * kvh + h) * 16 + o) * slot + d);
|
||||
}
|
||||
const int qcols = qh * HD + c.qpitch_extra;
|
||||
std::vector<uint16_t> qb((size_t)rows * qcols); std::vector<float> qf(qb.size());
|
||||
for (size_t i = 0; i < qb.size(); ++i) { qb[i] = rad_f32_to_bf16(nrm()); qf[i] = rad_bf16_to_f32(qb[i]); }
|
||||
std::vector<int> su(c.ctx), cu(n_seq + 1, 0);
|
||||
for (int s = 0; s < n_seq; ++s) cu[s + 1] = cu[s] + c.qlen[s];
|
||||
std::vector<float> kd(n_seq * kvh, 1.f), vd(n_seq * kvh, 1.f);
|
||||
if (c.descale) for (auto* v : {&kd, &vd}) for (auto& x : *v) x = 0.5f + (float)(rng() % 100) / 100.f;
|
||||
std::vector<uint16_t> out((size_t)rows * qh * HD, 0xffff);
|
||||
std::vector<char> scratch(c.scratch + 64);
|
||||
char* sp = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
|
||||
RadTensor t[8];
|
||||
t[0] = tens(qb.data(), RAD_BF16, {rows, qh * HD}); t[0].stride[0] = qcols;
|
||||
t[1] = tens(c.fp8 ? (void*)kv8.data() : (void*)kvb.data(), c.fp8 ? RAD_F8E4M3 : RAD_BF16, {nblocks, kvh, 16, slot});
|
||||
t[2] = tens(bt.data(), RAD_I32, {n_seq, maxb});
|
||||
t[3] = tens(su.data(), RAD_I32, {n_seq});
|
||||
t[4] = c.descale ? tens(kd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
t[5] = c.descale ? tens(vd.data(), RAD_F32, {n_seq, kvh}) : RadTensor{};
|
||||
t[6] = c.ragged ? tens(cu.data(), RAD_I32, {n_seq + 1}) : RadTensor{};
|
||||
t[7] = tens(out.data(), RAD_BF16, {rows, qh, HD});
|
||||
int qmax = 0; for (int q : c.qlen) qmax = std::max(qmax, q);
|
||||
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 ps = [&](const char* k, const char* v) { RadParam x{}; x.key = k; x.kind = RAD_P_STR; x.sval = 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("q_len", qmax + 3); /* the band bound, above the step's max */
|
||||
pi("head_dim", HD); pi("gqa", c.gqa); pi("block_size", 16); pi("causal", c.causal); pi("window", c.window);
|
||||
ps("q_dtype", "bf16"); ps("kv_dtype", c.fp8 ? "fp8_e4m3" : "bf16");
|
||||
const double scale = 1.0 / std::sqrt((double)HD) * 1.3; /* not the default: the param must be read */
|
||||
pf("scale", scale); pi("n_head", qh); pi("max_seqs", n_seq);
|
||||
if (c.max_ctx) pi("max_ctx", c.max_ctx);
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p.data(); a.n_p = (int)p.size();
|
||||
a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch;
|
||||
Fn fn = pick(HD, c.gqa, c.fp8);
|
||||
const int g0 = emu_grids;
|
||||
const int rc = fn(&a, nullptr);
|
||||
const int launches = emu_grids - g0;
|
||||
if (rc != RAD_OK) { std::printf("%-44s launch returned %d\n", c.name.c_str(), rc); return 1; }
|
||||
|
||||
/* the reference */
|
||||
double max_err = 0, max_ref = 0, se = 0, sr = 0; long bad = 0, nan_out = 0;
|
||||
for (int s = 0; s < n_seq; ++s) for (int i = 0; i < c.qlen[s]; ++i) for (int h = 0; h < qh; ++h) {
|
||||
const int tok = cu[s] + i, kh = h / c.gqa, pos = c.ctx[s] - c.qlen[s] + i;
|
||||
auto visible = [&](int j) {
|
||||
if (c.causal ? j > pos : j >= c.ctx[s]) return false;
|
||||
if (c.window > 0) { const int d = pos - j; if (c.causal ? d >= c.window : (d >= c.window || d <= -c.window)) return false; }
|
||||
return bt[s * maxb + j / 16] >= 0;
|
||||
};
|
||||
std::vector<double> sc(c.ctx[s], -INFINITY); double mx = -INFINITY;
|
||||
for (int j = 0; j < c.ctx[s]; ++j) {
|
||||
if (!visible(j)) continue;
|
||||
const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot;
|
||||
double dot = 0; for (int d = 0; d < HD; ++d) dot += (double)qf[(size_t)tok * qcols + h * HD + d] * kvf[kb + d] * kd[s * kvh + kh];
|
||||
sc[j] = dot * scale; mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(HD, 0.0); double sum = 0;
|
||||
if (mx > -INFINITY)
|
||||
for (int j = 0; j < c.ctx[s]; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx); sum += w;
|
||||
const int64_t kb = (((int64_t)bt[s * maxb + j / 16] * kvh + kh) * 16 + j % 16) * slot;
|
||||
for (int d = 0; d < HD; ++d) acc[d] += w * kvf[kb + HD + d] * vd[s * kvh + kh];
|
||||
}
|
||||
for (int d = 0; d < HD; ++d) {
|
||||
const double ref = sum > 0 ? acc[d] / sum : 0.0;
|
||||
const float got = rad_bf16_to_f32(out[((size_t)tok * qh + h) * HD + d]);
|
||||
if (std::isnan(got)) { ++nan_out; continue; }
|
||||
const double e = std::fabs(got - ref);
|
||||
max_err = std::max(max_err, e); max_ref = std::max(max_ref, std::fabs(ref));
|
||||
se += e * e; sr += ref * ref;
|
||||
if (e > 1e-2 * std::max(1.0, std::fabs(ref)) + 4e-3 * std::fabs(ref)) ++bad;
|
||||
}
|
||||
}
|
||||
const double rel = std::sqrt(se / std::max(sr, 1e-30));
|
||||
const bool ok = bad == 0 && nan_out == 0 && rel < 5e-3;
|
||||
std::printf("%-44s rows %4d %s rel_l2 %.2e max_abs %.2e bad %ld nan %ld %s\n", c.name.c_str(), rows,
|
||||
launches > 1 ? "split" : emu_last_block == 512 ? "wmma " : " ", rel, max_err, bad, nan_out,
|
||||
ok ? "PASS" : "FAIL");
|
||||
if (c.expect_wmma >= 0 && (emu_last_block == 512) != (c.expect_wmma == 1)) {
|
||||
std::printf("%-44s took the %s kernel, expected the %s one\n", c.name.c_str(),
|
||||
emu_last_block == 512 ? "WMMA" : "scalar", c.expect_wmma ? "WMMA" : "scalar");
|
||||
return 1;
|
||||
}
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const int64_t s256 = g4k_attn_h256_scratch(nullptr), s512 = g4k_attn_h512_scratch(nullptr);
|
||||
std::vector<Case> cases = {
|
||||
/* Gemma 4 sliding: h256 gqa2, causal, windowed; a ragged mixed step */
|
||||
{"h256 gqa2 swa w64 ragged bf16", 256, 2, 2, false, true, true, false, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
{"h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {1, 5, 40}, {200, 77, 140}},
|
||||
/* the real window, a context past it, a verify-sized query */
|
||||
{"h256 gqa2 swa w1024 verify16", 256, 2, 1, false, true, false, false, 1024, {16}, {1100}},
|
||||
/* split-KV decode: one row a sequence, long context, scratch present */
|
||||
{"h256 gqa2 swa w1024 decode split", 256, 2, 2, false, true, true, false, 1024, {1, 1}, {1300, 40}, -1, 0, s256},
|
||||
/* Gemma 4 full: h512, causal, no window, at the three TP ratios */
|
||||
{"h512 gqa8 full ragged bf16", 512, 8, 1, false, true, true, false, 0, {2, 7}, {90, 33}},
|
||||
{"h512 gqa8 full decode split fp8", 512, 8, 1, true, true, false, true, 0, {1}, {700}, -1, 4096, s512},
|
||||
{"h512 gqa4 full verify16 split", 512, 4, 1, false, true, false, false, 0, {16}, {300}, -1, 1024, s512},
|
||||
/* the serving case: max_ctx 262144 gives a decode step 64 splits, most of them empty */
|
||||
{"h512 gqa4 full decode, 64 splits, short ctx", 512, 4, 1, false, true, false, false, 0, {4}, {37}, -1, 262144, s512},
|
||||
{"h256 gqa2 swa w1024 verify, ragged, splits", 256, 2, 2, true, true, true, true, 1024, {3, 5}, {20, 900}, -1, 262144, s256},
|
||||
{"h512 gqa2 full ragged", 512, 2, 2, false, true, true, false, 0, {3, 1, 9}, {50, 64, 9}},
|
||||
/* the coverage the rows claim beyond Gemma: non-causal, two-sided window, a missing block */
|
||||
{"h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {6, 2}, {70, 30}, 2},
|
||||
{"h512 gqa1 noncausal full", 512, 1, 1, false, false, false, false, 0, {4}, {37}},
|
||||
{"h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {5}, {21}, -1, 0, 0, 512},
|
||||
/* no scratch where a split was wanted: falls back to the unsplit kernel */
|
||||
{"h256 gqa2 decode, split wanted, no scratch", 256, 2, 1, false, true, false, false, 0, {1}, {500}},
|
||||
/* PREFILL-SHAPED: the WMMA kernel (a 64-row query, or longer) */
|
||||
{"wmma h512 gqa4 prefill 200 of 900", 512, 4, 1, false, true, false, false, 0, {200}, {900}, -1, 262144, s512, 0, 1},
|
||||
{"wmma h512 gqa8 prefill fp8+descale", 512, 8, 1, true, true, false, true, 0, {130}, {130}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa2 kvh2 ragged + decode rows", 512, 2, 2, false, true, true, false, 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1},
|
||||
{"wmma h512 gqa1 noncausal", 512, 1, 1, false, false, false, false, 0, {64}, {100}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w1024 prefill 300 of 1500", 256, 2, 2, false, true, false, false, 1024, {300}, {1500}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa2 swa w64 ragged fp8+descale", 256, 2, 2, true, true, true, true, 64, {100, 90}, {250, 90}, -1, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa4 noncausal w20 missing-block", 256, 4, 1, false, false, true, false, 20, {80, 70}, {200, 70}, 3, 0, 0, 0, 1},
|
||||
{"wmma h256 gqa8 causal q-pitch slice", 256, 8, 1, false, true, false, false, 0, {64}, {64}, -1, 0, 0, 512, 1},
|
||||
{"wmma h256 gqa1 causal w5 fp8", 256, 1, 1, true, true, false, false, 5, {96}, {150}, -1, 0, 0, 0, 1},
|
||||
/* and what must stay scalar: a verify batch, many sequences, a few rows each */
|
||||
{"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16},
|
||||
{40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0},
|
||||
};
|
||||
if (argc > 1 && std::string(argv[1]) == "sweep") {
|
||||
const int n = argc > 2 ? std::atoi(argv[2]) : 200;
|
||||
int fails = 0, splits = 0, wmmas = 0;
|
||||
const int hds[2] = {256, 512}, gqas[4] = {1, 2, 4, 8};
|
||||
for (int it = 0; it < n; ++it) {
|
||||
Case c;
|
||||
c.hd = hds[rng() % 2]; c.gqa = gqas[rng() % 4]; c.kvh = 1 + rng() % 3;
|
||||
c.fp8 = rng() % 2; c.causal = rng() % 4 != 0; c.ragged = rng() % 2; c.descale = rng() % 2;
|
||||
c.window = rng() % 3 == 0 ? 0 : 1 + rng() % 200;
|
||||
const int ns = 1 + rng() % 4;
|
||||
const bool pre = rng() % 3 == 0; /* prefill-shaped: the WMMA kernel */
|
||||
const int qspan = pre ? 160 : 40, qmin = pre ? 64 : 1;
|
||||
const int ql = qmin + rng() % qspan;
|
||||
for (int s = 0; s < ns; ++s) {
|
||||
int q = c.ragged ? (int)(rng() % 3 == 0 ? 0 : qmin + rng() % qspan) : ql;
|
||||
if (c.ragged && s == 0 && q == 0) q = 1;
|
||||
c.qlen.push_back(q);
|
||||
c.ctx.push_back(q + (int)(rng() % 400));
|
||||
}
|
||||
if (rng() % 2) c.scratch = c.hd == 256 ? s256 : s512;
|
||||
if (rng() % 2) c.max_ctx = 512;
|
||||
if (rng() % 5 == 0) c.missing_block = (int)(rng() % ((c.ctx[0] + 15) / 16));
|
||||
c.name = "sweep " + std::to_string(it) + " h" + std::to_string(c.hd) + " g" + std::to_string(c.gqa) +
|
||||
" kvh" + std::to_string(c.kvh) + (c.fp8 ? " fp8" : " bf16") + (c.causal ? " c" : " nc") +
|
||||
" w" + std::to_string(c.window) + (c.ragged ? " rag" : "");
|
||||
const int g0 = emu_grids;
|
||||
fails += run(c);
|
||||
splits += emu_grids - g0 > 1;
|
||||
wmmas += emu_last_block == 512;
|
||||
}
|
||||
std::printf("sweep: %d cases, %d took the split path, %d the WMMA kernel, %d failure(s)\n", n, splits,
|
||||
wmmas, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
int fails = 0;
|
||||
for (auto& c : cases) {
|
||||
if (argc > 1 && c.name.find(argv[1]) == std::string::npos) continue;
|
||||
fails += run(c);
|
||||
}
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
/* tests/g4k_emu: the sandwich-norm joins (g4k_norm.hip) on the host SIMT emulator.
|
||||
*
|
||||
* Two references. The CHAIN is the unfused sequence the arch plugin would otherwise issue -- rmsnorm,
|
||||
* add, rmsnorm (or rmsnorm x2, add, rmsnorm, add, mul_weight) -- in libr4d's per-element arithmetic,
|
||||
* its sums of squares added in this kernel's block order: the fused kernel must match it BIT FOR
|
||||
* BIT, which is the claim that fusing changes nothing but the launch count. The HOST ARM sums in
|
||||
* index order -- what a different libr4d block width does too -- and may differ by a flipped
|
||||
* rounding, measured against the row's scale (see cmp). Padding columns and rows past M must be
|
||||
* left alone. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "g4k.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
extern "C" const RadKernelInfo* rad_kernel_at(int);
|
||||
extern "C" int rad_kernel_count(void);
|
||||
|
||||
static std::mt19937 rng(11);
|
||||
static float b2f(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t f2b(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
|
||||
static float rb(float f) { return b2f(f2b(f)); }
|
||||
|
||||
/* the kernel's sum of squares: 256 threads strided over the row, a butterfly a wave, waves in order */
|
||||
static float block_factor(const std::vector<float>& v, int n, float eps) {
|
||||
float part[256];
|
||||
for (int t = 0; t < 256; ++t) {
|
||||
float s = 0.0f;
|
||||
for (int k = 0; k < 24; ++k) { const int i = t + 256 * k; const float x = i < n ? v[(size_t)i] : 0.0f; s += x * x; }
|
||||
part[t] = s;
|
||||
}
|
||||
float total = 0.0f;
|
||||
for (int w = 0; w < 8; ++w) {
|
||||
float l[32];
|
||||
for (int i = 0; i < 32; ++i) l[i] = part[w * 32 + i];
|
||||
for (int d = 16; d >= 1; d >>= 1) {
|
||||
float nl[32];
|
||||
for (int i = 0; i < 32; ++i) nl[i] = l[i] + l[i ^ d];
|
||||
std::memcpy(l, nl, sizeof l);
|
||||
}
|
||||
total += l[0];
|
||||
}
|
||||
return 1.0f / std::sqrt(total / (float)n + eps);
|
||||
}
|
||||
static std::vector<float> chain_norm(const std::vector<float>& v, const float* g, int n, float eps) {
|
||||
const float f = block_factor(v, n, eps);
|
||||
std::vector<float> y((size_t)n);
|
||||
for (int i = 0; i < n; ++i) y[(size_t)i] = rb((v[(size_t)i] * f) * g[i]);
|
||||
return y;
|
||||
}
|
||||
|
||||
static RadTensor rows(void* p, uint32_t dt, int64_t M, int64_t n, int64_t ld) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = M; t.shape[1] = n; t.stride[0] = ld; t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, uint32_t dt, int64_t n) {
|
||||
RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
static const RadKernelInfo* host_row(const char* op) {
|
||||
for (int i = 0; i < rad_kernel_count(); ++i)
|
||||
if (rad_kernel_at(i)->domain == RAD_DOMAIN_HOST && !std::strcmp(rad_kernel_at(i)->op, op)) return rad_kernel_at(i);
|
||||
return nullptr;
|
||||
}
|
||||
static std::vector<uint16_t> randb(size_t k, float sd) {
|
||||
std::normal_distribution<float> d(0.f, sd);
|
||||
std::vector<uint16_t> v(k);
|
||||
for (auto& x : v) x = f2b(d(rng));
|
||||
return v;
|
||||
}
|
||||
static std::vector<float> gains(int n) {
|
||||
std::normal_distribution<float> d(1.f, 0.4f);
|
||||
std::vector<float> g((size_t)n);
|
||||
for (auto& x : g) x = d(rng);
|
||||
return g;
|
||||
}
|
||||
/* vs the host arm, the difference in units of the row's RMS: a different summation order moves the
|
||||
* norm factor by an f32 ulp, which flips a bf16 rounding here and there -- and where the residual
|
||||
* add cancels, a flipped ulp of the addend is many ulps of a small sum, so ulps of the OUTPUT are
|
||||
* the wrong yardstick and the row's scale is the right one. */
|
||||
struct Tally { long chain_bad = 0, host_diff = 0, host_bad = 0, pad = 0; double worst = 0.0; };
|
||||
static void cmp(const uint16_t* got, const uint16_t* chain, const uint16_t* host, int n, Tally& t) {
|
||||
double ss = 0.0;
|
||||
for (int i = 0; i < n; ++i) ss += (double)b2f(host[i]) * b2f(host[i]);
|
||||
const double rms = std::sqrt(ss / n) + 1e-30;
|
||||
for (int i = 0; i < n; ++i) {
|
||||
if (got[i] != chain[i]) ++t.chain_bad;
|
||||
if (got[i] == host[i]) continue;
|
||||
++t.host_diff;
|
||||
const double e = std::fabs((double)b2f(got[i]) - b2f(host[i])) / rms;
|
||||
if (e > t.worst) t.worst = e;
|
||||
/* one bf16 ulp of an element at 4x the row's rms is up to 3% of it: 1/16 passes a flipped
|
||||
* rounding of a large element and fails anything a real bug produces */
|
||||
if (e > 1.0 / 16) ++t.host_bad;
|
||||
}
|
||||
}
|
||||
|
||||
static int case_nan(int M, int n, int pad, int extra_rows) {
|
||||
const int ld = n + pad, R = M + extra_rows;
|
||||
const float eps = 1e-6f;
|
||||
auto a = randb((size_t)R * ld, 3.f), x = randb((size_t)R * ld, 1.f), y0 = randb((size_t)R * ld, 1.f);
|
||||
auto wa = gains(n), wy = gains(n);
|
||||
auto xd = x, yd = y0, xh = x, yh = y0;
|
||||
RadTensor t[5] = { rows(a.data(), RAD_BF16, M, n, ld), vec(wa.data(), RAD_F32, n),
|
||||
rows(xd.data(), RAD_BF16, M, n, ld), vec(wy.data(), RAD_F32, n),
|
||||
rows(yd.data(), RAD_BF16, M, n, ld) };
|
||||
RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 5; ar.p = p; ar.n_p = 4;
|
||||
if (g4k_norm_add_norm_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm: device launch failed"); return 1; }
|
||||
t[2].data = xh.data(); t[4].data = yh.data();
|
||||
if (host_row("norm_add_norm")->launch(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm: host launch failed"); return 1; }
|
||||
Tally tx, ty;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld;
|
||||
if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]); continue; }
|
||||
for (int i = n; i < ld; ++i) tx.pad += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]);
|
||||
std::vector<float> av((size_t)n), xv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) av[(size_t)i] = b2f(a[o + i]);
|
||||
const auto t1 = chain_norm(av, wa.data(), n, eps); /* rmsnorm */
|
||||
std::vector<uint16_t> cx((size_t)n), cy((size_t)n);
|
||||
for (int i = 0; i < n; ++i) { xv[(size_t)i] = rb(b2f(x[o + i]) + t1[(size_t)i]); cx[(size_t)i] = f2b(xv[(size_t)i]); } /* add */
|
||||
const auto t2 = chain_norm(xv, wy.data(), n, eps); /* rmsnorm */
|
||||
for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(t2[(size_t)i]);
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
cmp(&yd[o], cy.data(), &yh[o], n, ty);
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tx.host_bad == 0 && ty.host_bad == 0 && tx.pad == 0;
|
||||
std::printf("norm_add_norm M %3d n %4d pitch %4d: vs chain x %ld y %ld differ; vs host arm %ld/%ld differ, worst "
|
||||
"%.1e of the row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, ty.chain_bad, tx.host_diff,
|
||||
ty.host_diff, tx.worst > ty.worst ? tx.worst : ty.worst, tx.pad, ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
static int case_jas(int M, int n, int pad, int extra_rows) {
|
||||
const int ld = n + pad, R = M + extra_rows;
|
||||
const float eps = 1e-6f;
|
||||
/* the two arms as one [2M, n] buffer, as the plugin holds them: dense rows, then routed */
|
||||
auto ff = randb((size_t)2 * R * ld, 2.f), x = randb((size_t)R * ld, 4.f);
|
||||
auto wd = gains(n), wr = gains(n), wj = gains(n);
|
||||
uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f);
|
||||
auto xd = x, xh = x;
|
||||
RadTensor t[7] = { rows(ff.data(), RAD_BF16, M, n, ld), vec(wd.data(), RAD_F32, n),
|
||||
rows(ff.data() + (size_t)M * ld, RAD_BF16, M, n, ld), vec(wr.data(), RAD_F32, n),
|
||||
vec(wj.data(), RAD_F32, n), rows(xd.data(), RAD_BF16, M, n, ld), vec(&sc, RAD_BF16, 1) };
|
||||
RadParam p[4]{}; p[0] = {"M", RAD_P_INT, M}; p[1] = {"n", RAD_P_INT, n};
|
||||
p[2].key = "eps"; p[2].kind = RAD_P_F64; p[2].dval = eps; p[3].key = "dtype"; p[3].kind = RAD_P_STR; p[3].sval = "bf16";
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 7; ar.p = p; ar.n_p = 4;
|
||||
if (g4k_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; }
|
||||
t[5].data = xh.data();
|
||||
if (host_row("join_add_scale")->launch(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: host launch failed"); return 1; }
|
||||
Tally tx;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld;
|
||||
if (m >= M) { for (int i = 0; i < ld; ++i) tx.pad += xd[o + i] != x[o + i]; continue; }
|
||||
for (int i = n; i < ld; ++i) tx.pad += xd[o + i] != x[o + i];
|
||||
std::vector<float> dv((size_t)n), rv((size_t)n), sv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) { dv[(size_t)i] = b2f(ff[o + i]); rv[(size_t)i] = b2f(ff[(size_t)M * ld + o + i]); }
|
||||
const auto d1 = chain_norm(dv, wd.data(), n, eps); /* rmsnorm (arm 1) */
|
||||
const auto r1 = chain_norm(rv, wr.data(), n, eps); /* rmsnorm (arm 2) */
|
||||
for (int i = 0; i < n; ++i) sv[(size_t)i] = rb(d1[(size_t)i] + r1[(size_t)i]); /* add */
|
||||
const auto j = chain_norm(sv, wj.data(), n, eps); /* rmsnorm */
|
||||
std::vector<uint16_t> cx((size_t)n);
|
||||
for (int i = 0; i < n; ++i) cx[(size_t)i] = f2b(rb(b2f(x[o + i]) + j[(size_t)i]) * b2f(sc)); /* add, mul_weight */
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && tx.host_bad == 0 && tx.pad == 0;
|
||||
std::printf("join_add_scale M %3d n %4d pitch %4d: vs chain %ld differ; vs host arm %ld differ, worst %.1e of the "
|
||||
"row rms; padding touched %ld -> %s\n", M, n, ld, tx.chain_bad, tx.host_diff, tx.worst, tx.pad,
|
||||
ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = 0;
|
||||
/* Gemma 4 26B's 2816 at decode and verify heights, a prefill height, odd widths, the limit */
|
||||
const int Ms[] = {1, 4, 16, 37};
|
||||
for (int M : Ms) fails += case_nan(M, 2816, M % 2 ? 64 : 0, 2);
|
||||
for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 0 : 128, 2);
|
||||
fails += case_nan(3, 1000, 24, 1) + case_jas(3, 1000, 24, 1);
|
||||
fails += case_nan(2, 6144, 0, 0) + case_jas(2, 6144, 16, 0);
|
||||
fails += case_nan(5, 256, 8, 1) + case_jas(5, 5376, 0, 1);
|
||||
std::printf("norm joins: %d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/* pair_argmax: device kernel (emulated) vs the host row vs brute force, over the row-interleaved
|
||||
* [rows][world][R][2] layout the all_gather produces -- ties, negative (unfilled) ids, -inf, empty rows. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "g4k.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
extern "C" const RadKernelInfo* rad_kernel_at(int);
|
||||
extern "C" int rad_kernel_count(void);
|
||||
int main() {
|
||||
std::mt19937 rng(11);
|
||||
const RadKernelInfo* host = nullptr;
|
||||
for (int i = 0; i < rad_kernel_count(); ++i)
|
||||
if (!std::strcmp(rad_kernel_at(i)->op, "pair_argmax") && rad_kernel_at(i)->domain == RAD_DOMAIN_HOST) host = rad_kernel_at(i);
|
||||
int fails = 0, cases = 0;
|
||||
for (int world : {1, 2, 4, 8}) for (int R : {2, 4}) for (int rows : {1, 7, 16, 33, 240}) for (int rank3 = 0; rank3 < 2; ++rank3) {
|
||||
const int n = world * R;
|
||||
std::vector<float> pairs((size_t)rows * n * 2);
|
||||
std::vector<int32_t> ref(rows), dev(rows, 12345), hst(rows, 12345), pitched(rows * 3, 777);
|
||||
std::vector<float> dval(rows), hval(rows);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
int32_t bid = -1; float bv = -INFINITY;
|
||||
const int mode = rng() % 5; /* 0: ties, 1: some unfilled, 2: all unfilled, else random */
|
||||
for (int j = 0; j < n; ++j) {
|
||||
int32_t id = (int32_t)(rng() % 262144);
|
||||
float v = mode == 0 ? 3.5f : std::ldexp((float)(int)(rng() % 2000) - 1000.f, -4);
|
||||
if ((mode == 1 && rng() % 3 == 0) || mode == 2) { id = -1; v = -INFINITY; }
|
||||
std::memcpy(&pairs[((size_t)r * n + j) * 2], &id, 4);
|
||||
pairs[((size_t)r * n + j) * 2 + 1] = v;
|
||||
if (id >= 0 && (bid < 0 || v > bv || (v == bv && id < bid))) { bid = id; bv = v; }
|
||||
}
|
||||
ref[r] = bid;
|
||||
}
|
||||
RadTensor t[3]{};
|
||||
t[0].data = pairs.data(); t[0].dtype = RAD_F32;
|
||||
if (rank3) { t[0].rank = 3; t[0].shape[0] = rows; t[0].shape[1] = n; t[0].shape[2] = 2; t[0].stride[0] = n * 2; t[0].stride[1] = 2; t[0].stride[2] = 1; }
|
||||
else { t[0].rank = 2; t[0].shape[0] = rows; t[0].shape[1] = 2 * n; t[0].stride[0] = 2 * n; t[0].stride[1] = 1; }
|
||||
t[1].dtype = RAD_I32; t[1].rank = 2; t[1].shape[0] = rows; t[1].shape[1] = 1; t[1].stride[0] = 1; t[1].stride[1] = 1;
|
||||
t[2].dtype = RAD_F32; t[2].rank = 2; t[2].shape[0] = rows; t[2].shape[1] = 1; t[2].stride[0] = 1; t[2].stride[1] = 1;
|
||||
RadParam p[3]{}; p[0] = {"M", RAD_P_INT, rows}; p[1] = {"n", RAD_P_INT, n}; p[2].key = "dtype"; p[2].kind = RAD_P_STR; p[2].sval = "f32";
|
||||
RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 3;
|
||||
t[1].data = dev.data(); t[2].data = dval.data();
|
||||
int rc = g4k_pair_argmax_f32(&a, nullptr);
|
||||
t[1].data = hst.data(); t[2].data = hval.data();
|
||||
int rh = host->launch(&a, nullptr);
|
||||
/* a pitched output: every third element, the rest must stay untouched */
|
||||
RadTensor tp = t[1]; tp.data = pitched.data(); tp.stride[0] = 3; RadTensor t3[3] = {t[0], tp, RadTensor{}};
|
||||
RadArgs ap = a; ap.t = t3;
|
||||
int rp = g4k_pair_argmax_f32(&ap, nullptr);
|
||||
bool ok = rc == 0 && rh == 0 && rp == 0;
|
||||
for (int r = 0; r < rows && ok; ++r) {
|
||||
ok = dev[r] == ref[r] && hst[r] == ref[r] && pitched[3 * r] == ref[r] && pitched[3 * r + 1] == 777 && pitched[3 * r + 2] == 777;
|
||||
if (ok && ref[r] < 0) ok = std::isinf(dval[r]) && dval[r] < 0;
|
||||
}
|
||||
++cases; if (!ok) { ++fails; std::printf("FAIL world %d R %d rows %d rank%d\n", world, R, rows, rank3 ? 3 : 2); }
|
||||
}
|
||||
std::printf("pair_argmax: %d cases, %d failure(s)\n", cases, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
Reference in new issue
Block a user