Archived
radiance 1.5.0
- Gemma 4 31B (PRs #74, #75, #81, #86; sfjes, keptn42): sliding and global attention with their own kernels, the assistant head as a drafter that reads the trunk's cache, the vision tower, a fused w4a8 decode step, bf16 and compressed-tensors int4 checkpoints, and window snapshots so a prefix hit on a sliding-window model resumes instead of prefilling again. deploy/compose/gemma4-31b-w4a8.yaml serves keptn42's container on two cards - ParoQuant (PRs #65, #66, #67; malic): Qwen3.8-27B checkpoints with learned Givens rotations, as int4, int5 and MXFP4, imported without re-quantising, the prefill's rotations on the matrix cores. deploy/compose/qwen3.8-27b-paro.yaml serves them on one card. A ParoQuant container made with the PR builds is refused: convert it again with --reuse <old container> - Gemma 4 26B-A4B with z-lab's DFlash drafter (PR #88; Perire): arch/gemma4 serves Google's bf16 checkpoint with the routed experts in block fp8 or bf16 (data/recipes/gemma4-26b-a4b-df*.recipe), and libr4d gains its windowed paged attention, the fused sandwich-norm joins, expert_scale and the sharded draft head's pair_argmax. A prefill chunk runs as two slices with its all-reduces beside the compute, bit-exact with the whole step. The 31B's global layers take the windowed attention too: an 11.5K-token prefill on two R9700s in 3.1 s instead of 4.9 - a startup that logs nothing for two minutes says where it waits (#89): the system call (a KFD request by name), the library that made it, and its stack, which addr2line resolves against the binary - the prefix cache is kept in VRAM and host memory only (#70): the disk tier wrote every block and snapshot a prompt produced, and its copies never outlived the process. --prefix-cache-host-mib is renamed --prefix-cache-mib; --prefix-cache-dir and --prefix-cache-disk-mib are removed, and startup refuses all three with what replaced them. The compose files no longer mount /data, and .env no longer needs RADIANCE_STATE - --prefix-cache-ttl S (default 3600, 0 never): a conversation no request has used for that long leaves the cache, whichever tier holds it; radiance:prefix_cache_expired_total counts them. A full host tier now drops its least recently used conversations - --vision-tower-placement vram|ram (#84): ram keeps an encoder tower in pinned host memory and gives its VRAM to the KV cache, read over the link once an image - timings carry ttft_ms and total_ms (#85): the server's own time from the request body's arrival to the first and the last token, queueing and tokenisation included - a KV-cache recall that found a moved expert with nowhere to go stopped halfway and leaked the slots it had already freed: after it every recall failed, the cache stayed short until a restart, and requests failed with HTTP 500. A recall now waits for the slots it is owed and always finishes - a tool result or tool-call arguments that are not JSON are no longer refused as nesting past 1024 levels for their unmatched brackets (#90): only text that parses as JSON is held to the bound, since nothing else is parsed into a tree - the host-pool refusal names the limit that applies to pinned memory (RAM less 1/64 and 1.5 GiB), not ttm.pages_limit - --embedding-placement auto, removed in 1.3.0, is refused with what replaced it - for out-of-tree kernel libraries: gemm_nt_q gains two operands (pb1, pb2, the part bounds), and the loader requires identical op schemas, so a library built against 1.4.0 must be rebuilt. For architecture plugins, rad_op_declared(b, op) asks whether an op is in the loaded vocabulary without declaring it
This commit is contained in:
commit
b93b531f63
127 files changed
+9609
-4796
No files matched your search
@@ -0,0 +1,204 @@
|
||||
#include "hip/hip_runtime.h"
|
||||
#include "rad_plugin.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); }
|
||||
int emu_cvt_pk_fp8(float a, float b, int old, bool hi) {
|
||||
const unsigned pk = (unsigned)rad_f32_to_fp8e4m3(a) | ((unsigned)rad_f32_to_fp8e4m3(b) << 8);
|
||||
const unsigned o = (unsigned)old;
|
||||
return (int)(hi ? ((o & 0xffffu) | (pk << 16)) : ((o & 0xffff0000u) | pk));
|
||||
}
|
||||
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,76 @@
|
||||
/* tests/r4d_emu: SIMT EMULATOR SHIM -- runs libr4d 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))
|
||||
/* v_cvt_pk_fp8_f32 (gfx12, OCP E4M3): a and b as two codes into the low half of `old` (hi false)
|
||||
* or its high half, the other half kept; round to nearest even. The project's saturating encoder,
|
||||
* rad_f32_to_fp8e4m3, is the same function on the +-448 a kernel clamps to first. */
|
||||
int emu_cvt_pk_fp8(float a, float b, int old, bool hi);
|
||||
#define __builtin_amdgcn_cvt_pk_fp8_f32(a, b, old, hi) emu_cvt_pk_fp8((a), (b), (old), (hi))
|
||||
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 R4D_KLAUNCH(kernel, grid, block, stream, ...) emu_launch(&kernel, grid, block, __VA_ARGS__)
|
||||
@@ -0,0 +1,213 @@
|
||||
/* ref_host.cpp -- ref_host.h's functions: the rules and roundings of r4d_pair_argmax_f32.hip,
|
||||
* r4d_norm_join_bf16.hip and r4d_expert_scale_bf16.hip, one element at a time. */
|
||||
#include "ref_host.h"
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
/* pair_argmax: the device kernel's rules in plain C++. */
|
||||
int host_pair_argmax(const RadArgs* a) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const RadTensor* p = rad_arg_in(a, 0);
|
||||
const RadTensor* t = rad_arg_in(a, 1);
|
||||
const RadTensor* v = rad_arg_in(a, 2);
|
||||
if (!p || !t) return RAD_E_INVAL;
|
||||
if (p->dtype != RAD_F32 || t->dtype != RAD_I32 || (v && v->dtype != RAD_F32)) return RAD_E_DTYPE;
|
||||
const long long n = rad_args_geti_or(a, "n", 0);
|
||||
if (n <= 0) return RAD_E_SHAPE;
|
||||
if (p->rank == 3) {
|
||||
if (p->shape[1] < n || p->shape[2] != 2 || p->stride[2] != 1 || p->stride[1] != 2) return RAD_E_SHAPE;
|
||||
} else if (p->rank == 2) {
|
||||
if (p->shape[1] < 2 * n || p->stride[1] != 1) return RAD_E_SHAPE;
|
||||
} else {
|
||||
return RAD_E_SHAPE;
|
||||
}
|
||||
const int64_t rows = p->shape[0];
|
||||
if (t->rank < 1 || t->shape[0] < rows || (v && (v->rank < 1 || v->shape[0] < rows))) return RAD_E_SHAPE;
|
||||
const int64_t prs = p->stride[0], trs = t->rank >= 2 ? t->stride[0] : 1;
|
||||
const int64_t vrs = v ? (v->rank >= 2 ? v->stride[0] : 1) : 0;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const float* row = (const float*)p->data + r * prs;
|
||||
int32_t bid = -1;
|
||||
float bv = -INFINITY;
|
||||
for (long long j = 0; j < n; ++j) {
|
||||
int32_t id;
|
||||
std::memcpy(&id, &row[2 * j], 4);
|
||||
const float val = row[2 * j + 1];
|
||||
if (id < 0) continue;
|
||||
if (bid < 0 || val > bv || (val == bv && id < bid)) { bid = id; bv = val; }
|
||||
}
|
||||
((int32_t*)t->data)[r * trs] = bid;
|
||||
if (v) ((float*)v->data)[r * vrs] = bv;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The joins: each value the unfused chain stores is rounded to bf16 where it stores it. Summed in
|
||||
* index order, so a ULP from the device's block order. */
|
||||
static float hb2f(uint16_t h) { const uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t hf2b(float f) {
|
||||
uint32_t u; std::memcpy(&u, &f, 4);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
static float hrbf(float f) { return hb2f(hf2b(f)); }
|
||||
static float hnorm(const float* v, int64_t n, double eps) {
|
||||
float ss = 0.0f;
|
||||
for (int64_t i = 0; i < n; ++i) ss += v[i] * v[i];
|
||||
return 1.0f / std::sqrt(ss / (float)n + (float)eps);
|
||||
}
|
||||
static bool hrows(const RadTensor* t, int64_t n, int64_t* rows, int64_t* ld) {
|
||||
if (!t || t->dtype != RAD_BF16 || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
|
||||
if (t->stride[t->rank - 1] != 1) return false;
|
||||
*rows = rad_tensor_rows(t);
|
||||
*ld = rad_tensor_row_pitch(t);
|
||||
return true;
|
||||
}
|
||||
static bool hgain(const RadTensor* w, int64_t n) {
|
||||
return w && w->dtype == RAD_F32 && rad_tensor_numel(w) == n;
|
||||
}
|
||||
|
||||
/* [rows..., n] of `dt`, dense last axis, for the route form's fp8 codes and f32 scales */
|
||||
static bool hrows_as(const RadTensor* t, uint32_t dt, int64_t n, int64_t* rows, int64_t* ld) {
|
||||
if (!t || t->dtype != dt || t->rank < 1 || rad_tensor_lastdim(t) != n) return false;
|
||||
if (t->stride[t->rank - 1] != 1) return false;
|
||||
*rows = rad_tensor_rows(t);
|
||||
*ld = rad_tensor_row_pitch(t);
|
||||
return true;
|
||||
}
|
||||
|
||||
/* norm_add_norm, and with `route` norm_add_norm_route's three more outputs */
|
||||
static int nan_host(const RadArgs* a, bool route) {
|
||||
if (!a || a->n_t < (route ? 10 : 5)) return RAD_E_INVAL;
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
const double eps = rad_args_getf_or(a, "eps", 1e-6);
|
||||
const float mult = (float)rad_args_getf_or(a, "mult", 1.0);
|
||||
const RadTensor *A_ = rad_arg_in(a, 0), *Wa = rad_arg_in(a, 1), *X = rad_arg_in(a, 2),
|
||||
*Wy = rad_arg_in(a, 3), *Y = rad_arg_in(a, 4);
|
||||
const RadTensor *Wr = route ? rad_arg_in(a, 5) : nullptr, *R = route ? rad_arg_in(a, 6) : nullptr;
|
||||
const RadTensor *We = route ? rad_arg_in(a, 7) : nullptr, *Q = route ? rad_arg_in(a, 8) : nullptr;
|
||||
const RadTensor *S = route ? rad_arg_in(a, 9) : nullptr;
|
||||
if (n <= 0 || !A_ || !X || !Y || (route && (!R || !Q || !S))) return RAD_E_INVAL;
|
||||
if (route && (n % 128 || rad_args_geti_or(a, "group", 0) != 128)) return RAD_E_SHAPE;
|
||||
if (!hgain(Wa, n) || !hgain(Wy, n) || (route && (!hgain(Wr, n) || !hgain(We, n))))
|
||||
return RAD_E_DTYPE;
|
||||
int64_t ra, la, rx, lx, ry, ly, rr = 0, lr = 0, rq = 0, lq = 0, rs = 0, ls = 0;
|
||||
if (!hrows(A_, n, &ra, &la) || !hrows(X, n, &rx, &lx) || !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
|
||||
if (route && (!hrows(R, n, &rr, &lr) || !hrows_as(Q, RAD_F8E4M3, n, &rq, &lq) ||
|
||||
!hrows_as(S, RAD_F32, n / 128, &rs, &ls)))
|
||||
return RAD_E_SHAPE;
|
||||
if (ra < rx || ry < rx || (route && (rr < rx || rq < rx || rs < rx))) return RAD_E_SHAPE;
|
||||
const float *wa = (const float*)Wa->data, *wy = (const float*)Wy->data;
|
||||
std::vector<float> v((size_t)n), xv((size_t)n);
|
||||
for (int64_t m = 0; m < rx; ++m) {
|
||||
const uint16_t* ar = (const uint16_t*)A_->data + m * la;
|
||||
uint16_t* xr = (uint16_t*)X->data + m * lx;
|
||||
uint16_t* yr = (uint16_t*)Y->data + m * ly;
|
||||
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = hb2f(ar[i]);
|
||||
const float sa = hnorm(v.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float t = hrbf((v[(size_t)i] * sa) * wa[i]);
|
||||
xv[(size_t)i] = hrbf(hb2f(xr[i]) + t);
|
||||
xr[i] = hf2b(xv[(size_t)i]);
|
||||
}
|
||||
const float sx = hnorm(xv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((xv[(size_t)i] * sx) * wy[i]);
|
||||
if (!route) continue;
|
||||
/* the router's row, and the experts' as rmsnorm_quant_fp8 writes it (v holds it) */
|
||||
const float *wr = (const float*)Wr->data, *we = (const float*)We->data;
|
||||
uint16_t* rrow = (uint16_t*)R->data + m * lr;
|
||||
uint8_t* qrow = (uint8_t*)Q->data + m * lq;
|
||||
float* srow = (float*)S->data + m * ls;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
rrow[i] = hf2b(((xv[(size_t)i] * sx) * wr[i]) * mult);
|
||||
v[(size_t)i] = hrbf((xv[(size_t)i] * sx) * we[i]);
|
||||
}
|
||||
for (int64_t g = 0; g < n / 128; ++g) {
|
||||
float am = 0.0f;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i)
|
||||
am = std::fmax(am, std::fabs(v[(size_t)i]));
|
||||
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f;
|
||||
const float inv = 1.0f / sc;
|
||||
srow[g] = sc;
|
||||
for (int64_t i = g * 128; i < g * 128 + 128; ++i) {
|
||||
const float c = std::fmin(std::fmax(v[(size_t)i] * inv, -448.0f), 448.0f);
|
||||
qrow[i] = rad_f32_to_fp8e4m3(c);
|
||||
}
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
int host_norm_add_norm(const RadArgs* a) { return nan_host(a, false); }
|
||||
int host_norm_add_norm_route(const RadArgs* a) { return nan_host(a, true); }
|
||||
|
||||
int host_join_add_scale(const RadArgs* a) {
|
||||
if (!a || a->n_t < 7) return RAD_E_INVAL;
|
||||
const RadTensor *Wn = a->n_t > 7 ? rad_arg_in(a, 7) : nullptr,
|
||||
*Y = a->n_t > 8 ? rad_arg_in(a, 8) : nullptr;
|
||||
if (!Wn != !Y) return RAD_E_INVAL;
|
||||
const int64_t n = rad_args_geti_or(a, "n", 0);
|
||||
const double eps = rad_args_getf_or(a, "eps", 1e-6);
|
||||
const RadTensor *D = rad_arg_in(a, 0), *Wd = rad_arg_in(a, 1), *R = rad_arg_in(a, 2),
|
||||
*Wr = rad_arg_in(a, 3), *Wj = rad_arg_in(a, 4), *X = rad_arg_in(a, 5),
|
||||
*Sc = rad_arg_in(a, 6);
|
||||
if (n <= 0 || !D || !R || !X || !Sc) return RAD_E_INVAL;
|
||||
if (!hgain(Wd, n) || !hgain(Wr, n) || !hgain(Wj, n)) return RAD_E_DTYPE;
|
||||
if (Sc->dtype != RAD_BF16 || rad_tensor_numel(Sc) != 1) return RAD_E_DTYPE;
|
||||
if (Wn && !hgain(Wn, n)) return RAD_E_DTYPE;
|
||||
int64_t rd, ld, rr, lr, rx, lx, ry = 0, ly = 0;
|
||||
if (!hrows(D, n, &rd, &ld) || !hrows(R, n, &rr, &lr) || !hrows(X, n, &rx, &lx)) return RAD_E_SHAPE;
|
||||
if (Y && !hrows(Y, n, &ry, &ly)) return RAD_E_SHAPE;
|
||||
if (rd < rx || rr < rx || (Y && ry < rx)) return RAD_E_SHAPE;
|
||||
const float *wd = (const float*)Wd->data, *wr = (const float*)Wr->data, *wj = (const float*)Wj->data;
|
||||
const float sc = hb2f(*(const uint16_t*)Sc->data);
|
||||
std::vector<float> dv((size_t)n), rv((size_t)n);
|
||||
for (int64_t m = 0; m < rx; ++m) {
|
||||
const uint16_t* dr = (const uint16_t*)D->data + m * ld;
|
||||
const uint16_t* rrw = (const uint16_t*)R->data + m * lr;
|
||||
uint16_t* xr = (uint16_t*)X->data + m * lx;
|
||||
for (int64_t i = 0; i < n; ++i) { dv[(size_t)i] = hb2f(dr[i]); rv[(size_t)i] = hb2f(rrw[i]); }
|
||||
const float sd = hnorm(dv.data(), n, eps), sr = hnorm(rv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
dv[(size_t)i] = hrbf(hrbf((dv[(size_t)i] * sd) * wd[i]) + hrbf((rv[(size_t)i] * sr) * wr[i]));
|
||||
const float sj = hnorm(dv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const float x1 = hrbf(hb2f(xr[i]) + hrbf((dv[(size_t)i] * sj) * wj[i]));
|
||||
xr[i] = hf2b(x1 * sc);
|
||||
rv[(size_t)i] = hb2f(xr[i]);
|
||||
}
|
||||
if (Y) {
|
||||
const float* wn = (const float*)Wn->data;
|
||||
uint16_t* yr = (uint16_t*)Y->data + m * ly;
|
||||
const float sn = hnorm(rv.data(), n, eps);
|
||||
for (int64_t i = 0; i < n; ++i) yr[i] = hf2b((rv[(size_t)i] * sn) * wn[i]);
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* expert_scale: the device kernel's one product. */
|
||||
int host_expert_scale(const RadArgs* a) {
|
||||
if (!a || a->n_t < 3) return RAD_E_INVAL;
|
||||
const int64_t k = rad_args_geti_or(a, "top_k", 0), ne = rad_args_geti_or(a, "n_expert", 0);
|
||||
if (k <= 0 || ne <= 0) return RAD_E_SHAPE;
|
||||
const RadTensor *I = rad_arg_in(a, 0), *S = rad_arg_in(a, 1), *W = rad_arg_in(a, 2);
|
||||
if (!I || !S || !W) return RAD_E_INVAL;
|
||||
if (I->dtype != RAD_I32 || S->dtype != RAD_BF16 || W->dtype != RAD_BF16) return RAD_E_DTYPE;
|
||||
if (rad_tensor_numel(S) < ne || rad_tensor_lastdim(I) != k || rad_tensor_lastdim(W) != k)
|
||||
return RAD_E_SHAPE;
|
||||
if (I->stride[I->rank - 1] != 1 || W->stride[W->rank - 1] != 1) return RAD_E_STRIDE;
|
||||
const int64_t rows = rad_tensor_rows(W);
|
||||
if (rad_tensor_rows(I) < rows) return RAD_E_SHAPE;
|
||||
const int64_t li = rad_tensor_row_pitch(I), lw = rad_tensor_row_pitch(W);
|
||||
const uint16_t* sc = (const uint16_t*)S->data;
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
for (int64_t c = 0; c < k; ++c) {
|
||||
const int32_t id = ((const int32_t*)I->data)[r * li + c];
|
||||
const float s = (id >= 0 && id < ne) ? hb2f(sc[id]) : 0.0f;
|
||||
uint16_t* w = (uint16_t*)W->data + r * lw + c;
|
||||
*w = hf2b(hb2f(*w) * s);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/* ref_host.h -- what the four libr4d units r4d_emu runs compute, in plain C++ on the host.
|
||||
*
|
||||
* The device kernels' arithmetic restated, each a RadArgs in and RAD_OK or an error out: the
|
||||
* reference the emulated kernels are held to beside the unfused chain each test builds itself
|
||||
* (the joins, expert_scale) or a brute force (pair_argmax). No HIP, no libr4d header. */
|
||||
#pragma once
|
||||
|
||||
#include "rad_abi.h"
|
||||
|
||||
int host_pair_argmax(const RadArgs* a);
|
||||
int host_norm_add_norm(const RadArgs* a);
|
||||
int host_norm_add_norm_route(const RadArgs* a);
|
||||
int host_join_add_scale(const RadArgs* a);
|
||||
int host_expert_scale(const RadArgs* a);
|
||||
@@ -0,0 +1,30 @@
|
||||
#!/bin/sh
|
||||
# tests/r4d_emu/run.sh -- build and run r4d_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> <libr4d dir> <work dir> [sweep cases]
|
||||
set -e
|
||||
CXX=${1:?usage: run.sh <clang++> <abi dir> <libr4d 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$HERE -I$ABI -I$G"
|
||||
$CXX $F -x c++ -c "$G/r4d_attn_paged_window.hip" -o "$B/k_attn.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_pair_argmax_f32.hip" -o "$B/k_pick.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_norm_join_bf16.hip" -o "$B/k_norm.o"
|
||||
$CXX $F -x c++ -c "$G/r4d_expert_scale_bf16.hip" -o "$B/k_escale.o"
|
||||
$CXX $F -c "$HERE/ref_host.cpp" -o "$B/ref.o"
|
||||
$CXX $F -c "$HERE/emu/emu.cpp" -o "$B/emu.o"
|
||||
for t in attn pick norm escale; 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/k_escale.o" "$B/ref.o" \
|
||||
"$B/emu.o" -o "$B/test_$t"
|
||||
done
|
||||
"$B/test_attn"
|
||||
"$B/test_attn" sweep "$N"
|
||||
"$B/test_pick"
|
||||
"$B/test_norm"
|
||||
"$B/test_escale"
|
||||
@@ -0,0 +1,250 @@
|
||||
/* Drives libr4d's windowed attn_paged entry points (r4d_attn_paged_window.hip) 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 "r4d_plugin.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 ? r4d_rad_attn_window_h##H##_gqa##G##_fp8 : r4d_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
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 = r4d_rad_attn_window_h256_scratch(nullptr), s512 = r4d_rad_attn_window_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,62 @@
|
||||
/* tests/r4d_emu: expert_scale (r4d_expert_scale_bf16.hip) on the host SIMT emulator, against the chain it
|
||||
* replaces -- embed_lookup of the [n_expert, 1] scale table by the ids, then mul into the weights --
|
||||
* and against ref_host.cpp, bit for bit: one product rounded once has no other answer. Ids outside
|
||||
* the table (a negative pad, one past the end) read a zero scale; rows past M and the pitch's
|
||||
* padding stay untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
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); }
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(5);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
int fails = 0, cases = 0;
|
||||
for (int ne : {32, 128}) for (int k : {1, 8}) for (int M : {1, 4, 16, 37}) for (int pad : {0, 3}) {
|
||||
const int ld = k + pad, R = M + 2;
|
||||
std::vector<int32_t> ids((size_t)R * ld);
|
||||
for (auto& v : ids) {
|
||||
const int u = (int)(rng() % 40);
|
||||
v = u == 0 ? -1 : u == 1 ? ne : (int)(rng() % (unsigned)ne); /* pads, one past */
|
||||
}
|
||||
std::vector<uint16_t> table((size_t)ne), ew0((size_t)R * ld);
|
||||
for (auto& v : table) v = f2b(0.5f + 0.25f * nd(rng));
|
||||
for (auto& v : ew0) v = f2b(nd(rng));
|
||||
auto dev = ew0, hst = ew0;
|
||||
RadTensor t[3]{};
|
||||
t[0].data = ids.data(); t[0].dtype = RAD_I32; t[0].rank = 2; t[0].shape[0] = M; t[0].shape[1] = k; t[0].stride[0] = ld; t[0].stride[1] = 1;
|
||||
t[1].data = table.data(); t[1].dtype = RAD_BF16; t[1].rank = 1; t[1].shape[0] = ne; t[1].stride[0] = 1;
|
||||
t[2].dtype = RAD_BF16; t[2].rank = 2; t[2].shape[0] = M; t[2].shape[1] = k; t[2].stride[0] = ld; t[2].stride[1] = 1;
|
||||
RadParam p[4]{}; 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].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;
|
||||
t[2].data = dev.data();
|
||||
const int rd = r4d_rad_expert_scale_bf16(&a, nullptr);
|
||||
t[2].data = hst.data();
|
||||
const int rh = host_expert_scale(&a);
|
||||
bool ok = rd == RAD_OK && rh == RAD_OK;
|
||||
for (int r = 0; r < R && ok; ++r)
|
||||
for (int c = 0; c < ld && ok; ++c) {
|
||||
const size_t o = (size_t)r * ld + c;
|
||||
uint16_t want = ew0[o];
|
||||
if (r < M && c < k) {
|
||||
const int id = ids[o];
|
||||
const uint16_t es = (id >= 0 && id < ne) ? table[(size_t)id] : f2b(0.0f); /* embed_lookup */
|
||||
want = f2b(b2f(ew0[o]) * b2f(es)); /* mul */
|
||||
}
|
||||
ok = dev[o] == want && hst[o] == want;
|
||||
}
|
||||
++cases;
|
||||
if (!ok) { ++fails; std::printf("FAIL n_expert %d top_k %d M %d pitch %d\n", ne, k, M, ld); }
|
||||
}
|
||||
std::printf("expert_scale: %d cases, %d failure(s)\n", cases, fails);
|
||||
return fails != 0;
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
/* tests/r4d_emu: the sandwich-norm joins (r4d_norm_join_bf16.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. The route form's chain adds the router's rmsnorm (with its mult) and libr4d's
|
||||
* rmsnorm_quant_fp8 of the experts' norm -- amax * (1 / 448) a group, the clamped value encoded by
|
||||
* the emulator's v_cvt_pk_fp8_f32, the saturating encoder every fp8 cast here uses. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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 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 (r4d_rad_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_norm_add_norm(&ar) != 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;
|
||||
}
|
||||
|
||||
/* norm_add_norm_route: norm_add_norm, then the router's row r = norm(x) * w_r * mult and the experts'
|
||||
* E4M3 codes q and scales qs of norm(x) * w_e. `zero_group`: w_e zero over the second 128 columns,
|
||||
* so that group's amax is 0 and its scale the quantiser's 1. */
|
||||
static int case_route(int M, int n, int pad, int extra_rows, bool zero_group = false) {
|
||||
const int ld = n + pad, R = M + extra_rows, G = n / 128, ldq = n + pad, lds = G + 3;
|
||||
const float eps = 1e-6f, mult = 1.0f / std::sqrt((float)n);
|
||||
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 r0 = randb((size_t)R * ld, 1.f);
|
||||
auto wa = gains(n), wy = gains(n), wr = gains(n), we = gains(n);
|
||||
if (zero_group && n >= 256) for (int i = 128; i < 256; ++i) we[(size_t)i] = 0.0f;
|
||||
std::vector<uint8_t> q0((size_t)R * ldq);
|
||||
std::vector<float> s0((size_t)R * lds);
|
||||
for (auto& v : q0) v = (uint8_t)(rng() & 0xff);
|
||||
for (auto& v : s0) v = -7.0f;
|
||||
auto xd = x, yd = y0, rd = r0, xh = x, yh = y0, rh = r0;
|
||||
auto qd = q0, qh = q0;
|
||||
auto sd = s0, sh = s0;
|
||||
RadTensor t[10] = { 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), vec(wr.data(), RAD_F32, n),
|
||||
rows(rd.data(), RAD_BF16, M, n, ld), vec(we.data(), RAD_F32, n),
|
||||
rows(qd.data(), RAD_F8E4M3, M, n, ldq), rows(sd.data(), RAD_F32, M, G, lds) };
|
||||
RadParam p[6]{}; 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";
|
||||
p[4].key = "mult"; p[4].kind = RAD_P_F64; p[4].dval = mult; p[5] = {"group", RAD_P_INT, 128};
|
||||
RadArgs ar{}; ar.t = t; ar.n_t = 10; ar.p = p; ar.n_p = 6;
|
||||
if (r4d_rad_norm_add_norm_route_bf16(&ar, nullptr) != RAD_OK) { std::puts("norm_add_norm_route: device launch failed"); return 1; }
|
||||
t[2].data = xh.data(); t[4].data = yh.data(); t[6].data = rh.data(); t[8].data = qh.data(); t[9].data = sh.data();
|
||||
if (host_norm_add_norm_route(&ar) != RAD_OK) { std::puts("norm_add_norm_route: host launch failed"); return 1; }
|
||||
Tally tx, ty, tr;
|
||||
long q_chain = 0, s_chain = 0, q_host_bad = 0, touched = 0;
|
||||
for (int m = 0; m < R; ++m) {
|
||||
const size_t o = (size_t)m * ld, oq = (size_t)m * ldq, os = (size_t)m * lds;
|
||||
if (m >= M) {
|
||||
for (int i = 0; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
|
||||
for (int i = 0; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
|
||||
for (int i = 0; i < lds; ++i) touched += sd[os + i] != s0[os + i];
|
||||
continue;
|
||||
}
|
||||
for (int i = n; i < ld; ++i) touched += (xd[o + i] != x[o + i]) + (yd[o + i] != y0[o + i]) + (rd[o + i] != r0[o + i]);
|
||||
for (int i = n; i < ldq; ++i) touched += qd[oq + i] != q0[oq + i];
|
||||
for (int i = G; i < lds; ++i) touched += sd[os + i] != s0[os + 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), cr((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 float f = block_factor(xv, n, eps);
|
||||
for (int i = 0; i < n; ++i) {
|
||||
cy[(size_t)i] = f2b((xv[(size_t)i] * f) * wy[(size_t)i]); /* rmsnorm */
|
||||
cr[(size_t)i] = f2b(((xv[(size_t)i] * f) * wr[(size_t)i]) * mult); /* the router's */
|
||||
}
|
||||
cmp(&xd[o], cx.data(), &xh[o], n, tx);
|
||||
cmp(&yd[o], cy.data(), &yh[o], n, ty);
|
||||
cmp(&rd[o], cr.data(), &rh[o], n, tr);
|
||||
for (int g = 0; g < G; ++g) { /* rmsnorm_quant_fp8 */
|
||||
float h[128], am = 0.0f;
|
||||
for (int j = 0; j < 128; ++j) { h[j] = rb((xv[(size_t)(g * 128 + j)] * f) * we[(size_t)(g * 128 + j)]); am = std::fmax(am, std::fabs(h[j])); }
|
||||
const float sc = am > 0.0f ? am * (1.0f / 448.0f) : 1.0f, inv = 1.0f / sc;
|
||||
s_chain += sd[os + g] != sc;
|
||||
if (zero_group && g == 1 && sd[os + g] != 1.0f) ++s_chain;
|
||||
for (int j = 0; j < 128; ++j) {
|
||||
const int i = g * 128 + j;
|
||||
q_chain += qd[oq + i] != rad_f32_to_fp8e4m3(std::fmin(std::fmax(h[j] * inv, -448.0f), 448.0f));
|
||||
/* vs the host arm: one code step is an eighth of its value at most, which is no
|
||||
* more than an eighth of the group's amax; a scale an ulp off moves less */
|
||||
const double dv = std::fabs((double)rad_fp8e4m3_to_f32(qd[oq + i]) * sd[os + g] -
|
||||
(double)rad_fp8e4m3_to_f32(qh[oq + i]) * sh[os + g]);
|
||||
if (dv > (double)am / 8 + 1e-30) ++q_host_bad;
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool ok = tx.chain_bad == 0 && ty.chain_bad == 0 && tr.chain_bad == 0 && q_chain == 0 && s_chain == 0 &&
|
||||
tx.host_bad == 0 && ty.host_bad == 0 && tr.host_bad == 0 && q_host_bad == 0 && touched == 0;
|
||||
std::printf("norm_add_norm_route M %3d n %4d pitch %4d%s: vs chain x %ld y %ld r %ld q %ld scale %ld differ; vs host "
|
||||
"arm %ld/%ld/%ld differ, %ld codes past a step; padding touched %ld -> %s\n", M, n, ld,
|
||||
zero_group ? " (a zero group)" : "", tx.chain_bad, ty.chain_bad, tr.chain_bad, q_chain, s_chain,
|
||||
tx.host_diff, ty.host_diff, tr.host_diff, q_host_bad, touched, ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
/* `next`: also the next layer's input norm, y = norm(x) * w_n over the x the join writes */
|
||||
static int case_jas(int M, int n, int pad, int extra_rows, bool next = false) {
|
||||
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), y0 = randb((size_t)R * ld, 1.f);
|
||||
auto wd = gains(n), wr = gains(n), wj = gains(n), wn = gains(n);
|
||||
uint16_t sc = f2b(0.4375f + (float)(rng() % 64) / 128.f);
|
||||
auto xd = x, xh = x, yd = y0, yh = y0;
|
||||
RadTensor t[9] = { 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),
|
||||
vec(wn.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 = next ? 9 : 7; ar.p = p; ar.n_p = 4;
|
||||
if (r4d_rad_join_add_scale_bf16(&ar, nullptr) != RAD_OK) { std::puts("join_add_scale: device launch failed"); return 1; }
|
||||
t[5].data = xh.data(); t[8].data = yh.data();
|
||||
if (host_join_add_scale(&ar) != RAD_OK) { std::puts("join_add_scale: 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> 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);
|
||||
if (next) { /* the next rmsnorm */
|
||||
std::vector<float> xv((size_t)n);
|
||||
for (int i = 0; i < n; ++i) xv[(size_t)i] = b2f(cx[(size_t)i]);
|
||||
const auto yn = chain_norm(xv, wn.data(), n, eps);
|
||||
std::vector<uint16_t> cy((size_t)n);
|
||||
for (int i = 0; i < n; ++i) cy[(size_t)i] = f2b(yn[(size_t)i]);
|
||||
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("join_add_scale%s M %3d n %4d pitch %4d: vs chain %ld/%ld differ; vs host arm %ld/%ld differ, worst %.1e "
|
||||
"of the row rms; padding touched %ld -> %s\n", next ? "+next" : " ", 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;
|
||||
}
|
||||
|
||||
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);
|
||||
/* the edge between the 12-a-thread kernels and the 24: 3072 the last of the first */
|
||||
fails += case_nan(2, 3072, 0, 1) + case_nan(2, 3073, 8, 1);
|
||||
fails += case_jas(2, 3072, 0, 1, true) + case_jas(2, 3073, 8, 1, true) + case_jas(3, 3073, 0, 1);
|
||||
/* and with the next layer's input norm folded in */
|
||||
for (int M : Ms) fails += case_jas(M, 2816, M % 2 ? 64 : 0, 2, true);
|
||||
fails += case_jas(3, 1000, 24, 1, true) + case_jas(2, 6144, 16, 0, true);
|
||||
/* the route form: the 26B-A4B's width at decode, verify and prefill heights, the edge between the
|
||||
* 12- and 24-a-thread kernels, one group, the limit, and a group whose norm is all zero */
|
||||
for (int M : Ms) fails += case_route(M, 2816, M % 2 ? 64 : 0, 2);
|
||||
fails += case_route(2, 3072, 0, 1) + case_route(2, 3200, 16, 1) + case_route(3, 128, 8, 1);
|
||||
fails += case_route(2, 6144, 0, 0) + case_route(4, 2816, 0, 1, true);
|
||||
std::printf("norm joins: %d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/* pair_argmax: device kernel (emulated) vs ref_host.cpp 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 "r4d_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
int main() {
|
||||
std::mt19937 rng(11);
|
||||
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 = r4d_rad_pair_argmax_f32(&a, nullptr);
|
||||
t[1].data = hst.data(); t[2].data = hval.data();
|
||||
int rh = host_pair_argmax(&a);
|
||||
/* 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 = r4d_rad_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