Archived
radiance 1.15.0
New models and formats: - IQR for Qwen3.8-27B: weights on the int8 grid under GPTQ, a trellis down each GPTQ column (IQR-V2), and IQR-V3, a computed trellis code under one scale a row, kept at its codes' width in VRAM and decoded in the GEMM; 15 IQR-V3 recipes from ~2 to ~7 bits a weight (data/recipes/q38-27b-*-v3.recipe, docs/IQR.md) - libhalo: a kernel library for Strix Halo (gfx1151), preferred there over libr3d - Nemotron 3.5 Embed 1B and 8B (nemotron35_embed): text and image embeddings through a Pixtral tower, on the card and on the CPU - Nemotron 3.5 Rerank 8B - /v1/systemone: Cloudflare's clef and clef-flash, Convai Innovations' Laya and Mica beside LiquidAI d1; scored steps read the candidates' logits from the head table with no lm_head pass - LFM2's 8-bit trunk: block-fp8 or int8 linears with the fused producers, and the d1-3B recipe - DeepSeek-V4.1's reply format with DSML tool calls and typed argument tags Weights on the drive: - The file tier reads only the experts the pass routes rows to; the draft head's weights stay in the host pool - A hot VRAM cache for routed experts read off the drive, reads deposited straight into free host pool slots, and copyless evictions; the file tier's counters are now ssd_* - GLM-5 Next shards its routed experts by expert, not by width, so they can live on the drive - The stall watch counts drive reads as progress, and the DMA lane's room check reads the lane's own completion fence Quantisation tooling: - --calib-corpus, --calib-dir and --calib-layers record each linear's input Hessian; beside --kld-record the reference's own run records them - --kld-top N records a sparse KL reference (the N most likely tokens and the tail's mass) - GPTQ in a third of the time with the same codes, trellis GPTQ on the card, vector codebooks with coordinate descent, and rad-convert --reuse repeated, each container supplying what the earlier ones lack Speculation: - Prompt lookup alone (--spec-ngram K, --spec-ngram-min/-max): each sequence keeps an index of its n-grams, and a proposal is verified only when its measured step cost says it pays; --draft-window adaptive follows it Speed: - IQR decode: the narrow tile splits K for four times the int8 tile's waves and folds each 128-K block once; at 8 tokens down and the output projections run in 0.61-0.82x and 0.70-0.92x FP8's time (2-6 bits); IQ6R-S-V3 with its DFlash2 drafter steps in 26.3 ms at TP2, against 29.4 ms before and FP8's 27.3 - Qwen MXFP4 feed-forward: the gated fold up to 16 rows, not 8 - libr4d: the gated prefill fold, the short-prompt split row, and the rows forms of rmsnorm and rope; KLATE again for the head-256 gqa6 paged prefill; gram_accum on the matrix cores Features: - /health, /v1/health and /ping answer 503 with "status": "stuck" once the device has advanced nothing for a minute or a queue has faulted, so a supervisor can restart a wedged server (#356) - --image-gen-max-pixels and --image-gen-max-refs size an image generator's buffers (#344) - The startup report lists only the options not at their default, with a count; -v lists all (#250) - --preempt-wait-ms bounds how long a preempted prefill waits for its whole-recompute room - --placement layer_offload spills dense layers so one --max-model-len sequence fits - Startup refuses amdgpu with CWSR off and says how to fix it; --proceed-with-incompatible-configuration starts anyway under an UNSUPPORTED banner Fixes: - The n-gram read-ahead hands each row to the reader once and reads only as far ahead as the row cache holds, and pauses while decode reads: about one drive read a row instead of two (#355) - A file-tier window reads each of its runs once, not once a run per run - The decode split law's verify floor is bounded by the batch's workgroups: max_seqs 256 no longer declares 64x the scratch (#342) - A prefetch DMA list's mark stays out of the signal pool until the engine has read it, and a prefill stage copies only the blocks its own tables name (#343) - The split-KV row sum is read with fetch-inactive (#328) - LFM2 on the host backend: libref and libavx serve the row-form ops it declares (#348) - The preempted-prefill gate skips a KV group that holds no blocks (#352) - Every request entry point bounded, gated and sanitised (JSON depth, invalid UTF-8, control bytes in the log, the dashboard's CSP, cross-origin browsers on the loopback-only routes); a prompt id outside the vocabulary refused at admission; --api-key "" refused at startup - The telemetry the HTTP thread reads is atomic - An RMS norm row no longer depends on how many rows its launch carries; prefill attention's rescale is decided by live rows only - A --kld-record prefill chunk that finishes no sequence gets its logits on a tied-head model - A kernel's lazily made counter block is zeroed outside the lock other ranks take (a TP2 first-step hang) Changes: Plugin ABI 32. Every plugin exports a layout fingerprint of the ABI structs and the loader refuses a plugin without it or with another (#302), so out-of-tree plugins must be rebuilt. Appended: RadBuildCtx calib_* and gen_max_*, RadArchProbe gen_max_*, RadBatch score_only and plugin_words, RadDeviceProps::unified, RadChatFormat arg_json_value_prefix.
This commit is contained in:
commit
9ed3ef7a7b
452 files changed
+167762
-1346
No files matched your search
@@ -0,0 +1,26 @@
|
||||
/* tests/halo_emu: the tuned-configuration readers the emulated GEMM units call (halo_rows.cpp
|
||||
* defines them over its tunable tables; the emulator links the units without the row table).
|
||||
* These answer an untuned install's defaults -- tGemmSkinny's -- or the launch's own parameter. */
|
||||
#include "rad_abi.h"
|
||||
|
||||
struct HaloGemmCfg { int wv, sk, mb, npw, nt; };
|
||||
extern "C" void halo_cfg_gemm(const RadArgs* a, HaloGemmCfg* out) {
|
||||
auto g = [&](const char* k, int d) { long long v; return rad_args_geti(a, k, &v) ? (int)v : d; };
|
||||
out->wv = g("wv", 1); out->sk = g("sk", 0); out->mb = g("mb", 0); out->npw = g("npw", 1);
|
||||
out->nt = g("nt", 1);
|
||||
}
|
||||
|
||||
struct HaloSplitCfg { int splits; };
|
||||
extern "C" void halo_cfg_split(const RadArgs* a, HaloSplitCfg* out) { /* tAttnSplit: 0, the split law */
|
||||
long long v;
|
||||
out->splits = rad_args_geti(a, "splits", &v) ? (int)v : 0;
|
||||
}
|
||||
|
||||
/* halo_gemm_fp8a8.hip's gated row hands its tiled pair's product to halo_fused_quant_fp8.hip's
|
||||
* quantiser, a unit the emulator does not build (it carries the all-reduce headers). The emulated
|
||||
* gated cases run the fold (no scratch, M <= 16), so this is never reached there; it refuses rather
|
||||
* than answer. The pair itself is checked on the card (halo_selftest's fp8_numeric, byte for byte
|
||||
* against gemm_nt_q + gated_quant_fp8). */
|
||||
extern "C" int halo_gated_quant_fp8(long, long, long, long, int, int, int, int, int, int, int, long) {
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
extern "C" {
|
||||
int halo_rad_attn_decode_h128_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa1_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa1_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa2_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa2_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa2w_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa2w_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa8_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h128_gqa8_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa2_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa2_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa4_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa4_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa8_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_decode_h256_gqa8_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa1_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa1_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa2_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa2_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa2w_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa2w_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa8_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h128_gqa8_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa2_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa2_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa4_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa4_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa8_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h256_gqa8_fp8(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_attn_prefill_h64_gqa4_fp8(const RadArgs*, RadStream);
|
||||
int64_t halo_rad_attn_prefill_h128_gqa1_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h128_gqa2_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h128_gqa8_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h256_gqa4_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h256_gqa8_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h256_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_prefill_h64_gqa4_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h128_gqa1_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h128_gqa2_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h128_gqa2w_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h128_gqa8_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h128_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h256_gqa2_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h256_gqa4_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h256_gqa8_scratch(const RadArgs*);
|
||||
int64_t halo_rad_attn_decode_h256_scratch(const RadArgs*);
|
||||
}
|
||||
static const Row kRows[] = {
|
||||
{ "attn_prefill_h256_gqa6_fp8kv", halo_rad_attn_prefill_h256_fp8, halo_rad_attn_prefill_h256_scratch, 256, 6, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h256_gqa6_bf16kv", halo_rad_attn_prefill_h256_bf16, halo_rad_attn_prefill_h256_scratch, 256, 6, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h256_gqa6_fp8kv", halo_rad_attn_decode_h256_fp8, halo_rad_attn_decode_h256_scratch, 256, 6, true, 10, 0, 1 },
|
||||
{ "attn_decode_h256_gqa6_bf16kv", halo_rad_attn_decode_h256_bf16, halo_rad_attn_decode_h256_scratch, 256, 6, false, 10, 0, 1 },
|
||||
{ "attn_decode_h128_gqa4_fp8kv", halo_rad_attn_decode_h128_fp8, halo_rad_attn_decode_h128_scratch, 128, 4, true, 16, 1, 0 },
|
||||
{ "attn_decode_h128_gqa4_bf16kv", halo_rad_attn_decode_h128_bf16, halo_rad_attn_decode_h128_scratch, 128, 4, false, 16, 1, 0 },
|
||||
{ "attn_prefill_h256_gqa2_fp8kv", halo_rad_attn_prefill_h256_gqa2_fp8, nullptr, 256, 2, true, 1048576, 1, 1 },
|
||||
{ "attn_prefill_h256_gqa2_bf16kv", halo_rad_attn_prefill_h256_gqa2_bf16, nullptr, 256, 2, false, 1048576, 1, 1 },
|
||||
{ "attn_decode_h256_gqa2_fp8kv", halo_rad_attn_decode_h256_gqa2_fp8, halo_rad_attn_decode_h256_gqa2_scratch, 256, 2, true, 32, 1, 0 },
|
||||
{ "attn_decode_h256_gqa2_bf16kv", halo_rad_attn_decode_h256_gqa2_bf16, halo_rad_attn_decode_h256_gqa2_scratch, 256, 2, false, 32, 1, 0 },
|
||||
{ "attn_prefill_h128_gqa2w_fp8kv", halo_rad_attn_prefill_h128_gqa2w_fp8, nullptr, 128, 2, true, 1048576, 2, 1 },
|
||||
{ "attn_prefill_h128_gqa2w_bf16kv", halo_rad_attn_prefill_h128_gqa2w_bf16, nullptr, 128, 2, false, 1048576, 2, 1 },
|
||||
{ "attn_decode_h128_gqa2w_fp8kv", halo_rad_attn_decode_h128_gqa2w_fp8, halo_rad_attn_decode_h128_gqa2w_scratch, 128, 2, true, 32, 2, 0 },
|
||||
{ "attn_decode_h128_gqa2w_bf16kv", halo_rad_attn_decode_h128_gqa2w_bf16, halo_rad_attn_decode_h128_gqa2w_scratch, 128, 2, false, 32, 2, 0 },
|
||||
{ "attn_prefill_h128_gqa1_fp8kv", halo_rad_attn_prefill_h128_gqa1_fp8, halo_rad_attn_prefill_h128_gqa1_scratch, 128, 1, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h128_gqa1_bf16kv", halo_rad_attn_prefill_h128_gqa1_bf16, halo_rad_attn_prefill_h128_gqa1_scratch, 128, 1, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h128_gqa1_fp8kv", halo_rad_attn_decode_h128_gqa1_fp8, halo_rad_attn_decode_h128_gqa1_scratch, 128, 1, true, 64, 0, 0 },
|
||||
{ "attn_decode_h128_gqa1_bf16kv", halo_rad_attn_decode_h128_gqa1_bf16, halo_rad_attn_decode_h128_gqa1_scratch, 128, 1, false, 64, 0, 0 },
|
||||
{ "attn_prefill_h256_gqa8_fp8kv", halo_rad_attn_prefill_h256_gqa8_fp8, halo_rad_attn_prefill_h256_gqa8_scratch, 256, 8, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h256_gqa8_bf16kv", halo_rad_attn_prefill_h256_gqa8_bf16, halo_rad_attn_prefill_h256_gqa8_scratch, 256, 8, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h256_gqa8_fp8kv", halo_rad_attn_decode_h256_gqa8_fp8, halo_rad_attn_decode_h256_gqa8_scratch, 256, 8, true, 8, 0, 0 },
|
||||
{ "attn_decode_h256_gqa8_bf16kv", halo_rad_attn_decode_h256_gqa8_bf16, halo_rad_attn_decode_h256_gqa8_scratch, 256, 8, false, 8, 0, 0 },
|
||||
{ "attn_prefill_h256_gqa4_fp8kv", halo_rad_attn_prefill_h256_gqa4_fp8, halo_rad_attn_prefill_h256_gqa4_scratch, 256, 4, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h256_gqa4_bf16kv", halo_rad_attn_prefill_h256_gqa4_bf16, halo_rad_attn_prefill_h256_gqa4_scratch, 256, 4, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h256_gqa4_fp8kv", halo_rad_attn_decode_h256_gqa4_fp8, halo_rad_attn_decode_h256_gqa4_scratch, 256, 4, true, 16, 0, 0 },
|
||||
{ "attn_decode_h256_gqa4_bf16kv", halo_rad_attn_decode_h256_gqa4_bf16, halo_rad_attn_decode_h256_gqa4_scratch, 256, 4, false, 16, 0, 0 },
|
||||
{ "attn_prefill_h64_gqa4_fp8kv", halo_rad_attn_prefill_h64_gqa4_fp8, halo_rad_attn_prefill_h64_gqa4_scratch, 64, 4, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h64_gqa4_bf16kv", halo_rad_attn_prefill_h64_gqa4_bf16, halo_rad_attn_prefill_h64_gqa4_scratch, 64, 4, false, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h128_gqa8_fp8kv", halo_rad_attn_prefill_h128_gqa8_fp8, halo_rad_attn_prefill_h128_gqa8_scratch, 128, 8, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h128_gqa8_bf16kv", halo_rad_attn_prefill_h128_gqa8_bf16, halo_rad_attn_prefill_h128_gqa8_scratch, 128, 8, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h128_gqa8_fp8kv", halo_rad_attn_decode_h128_gqa8_fp8, halo_rad_attn_decode_h128_gqa8_scratch, 128, 8, true, 8, 0, 0 },
|
||||
{ "attn_decode_h128_gqa8_bf16kv", halo_rad_attn_decode_h128_gqa8_bf16, halo_rad_attn_decode_h128_gqa8_scratch, 128, 8, false, 8, 0, 0 },
|
||||
{ "attn_prefill_h128_gqa2_fp8kv", halo_rad_attn_prefill_h128_gqa2_fp8, halo_rad_attn_prefill_h128_gqa2_scratch, 128, 2, true, 1048576, 0, 1 },
|
||||
{ "attn_prefill_h128_gqa2_bf16kv", halo_rad_attn_prefill_h128_gqa2_bf16, halo_rad_attn_prefill_h128_gqa2_scratch, 128, 2, false, 1048576, 0, 1 },
|
||||
{ "attn_decode_h128_gqa2_fp8kv", halo_rad_attn_decode_h128_gqa2_fp8, halo_rad_attn_decode_h128_gqa2_scratch, 128, 2, true, 32, 0, 0 },
|
||||
{ "attn_decode_h128_gqa2_bf16kv", halo_rad_attn_decode_h128_gqa2_bf16, halo_rad_attn_decode_h128_gqa2_scratch, 128, 2, false, 32, 0, 0 },
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_attn.cpp): drives libhalo's windowed attn_paged entry points (halo_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 "halo_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 ? halo_rad_attn_window_h##H##_gqa##G##_fp8 : halo_rad_attn_window_h##H##_gqa##G##_bf16;
|
||||
P(128, 1) 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 s128 = halo_rad_attn_window_h128_scratch(nullptr);
|
||||
const int64_t s256 = halo_rad_attn_window_h256_scratch(nullptr), s512 = halo_rad_attn_window_h512_scratch(nullptr);
|
||||
std::vector<Case> cases = {
|
||||
/* Unlimited-OCR's decoder: h128 MHA, the fused q|k|v plane read at its pitch */
|
||||
{"h128 gqa1 decode split", 128, 1, 1, false, true, false, false, 0, {1}, {700}, -1, 0, s128},
|
||||
{"h128 gqa1 swa w64 verify16", 128, 1, 1, false, true, false, false, 64, {16}, {1100}},
|
||||
{"h128 gqa1 noncausal full", 128, 1, 1, false, false, false, false, 0, {3}, {77}},
|
||||
{"wmma h128 gqa1 prefill 200 of 900", 128, 1, 1, false, true, false, false, 0, {200}, {900},
|
||||
-1, 0, 0, 0, 1},
|
||||
{"wmma h128 gqa1 q-pitch slice", 128, 1, 1, false, true, false, false, 0, {96}, {150}, -1,
|
||||
0, 0, 512, 1},
|
||||
{"wmma h128 gqa1 swa w1024 ragged", 128, 1, 1, false, true, true, false, 1024, {150, 70},
|
||||
{300, 70}, -1, 0, 0, 0, 1},
|
||||
/* 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;
|
||||
}
|
||||
/* [--shard k/n] [name filter]: --shard runs every n-th case from the k-th, so ctest can split
|
||||
* the run into parallel entries. */
|
||||
int shard = 0, shards = 1;
|
||||
const char* filter = nullptr;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
if (std::string(argv[i]) == "--shard" && i + 1 < argc) {
|
||||
if (std::sscanf(argv[++i], "%d/%d", &shard, &shards) != 2 || shards < 1 || shard < 0 ||
|
||||
shard >= shards) {
|
||||
std::fprintf(stderr, "--shard takes k/n with 0 <= k < n\n");
|
||||
return 2;
|
||||
}
|
||||
} else {
|
||||
filter = argv[i];
|
||||
}
|
||||
}
|
||||
int fails = 0;
|
||||
for (size_t i = 0; i < cases.size(); ++i) {
|
||||
const Case& c = cases[i];
|
||||
if ((int)(i % (size_t)shards) != shard) continue;
|
||||
if (filter && c.name.find(filter) == std::string::npos) continue;
|
||||
fails += run(c);
|
||||
}
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_dsa.cpp): GLM's DSA scoring and selection split over the tensor-parallel ranks by query
|
||||
* rows (halo_dsa.hip, then halo_qsa_select_bf16.hip) on the host SIMT emulator.
|
||||
*
|
||||
* Each rank scores its run of R = 4 * ceil(M / (4 * world)) rows with `row_part`, selects over
|
||||
* the rows of that run that exist with the rebased bounds the scorer wrote (`cu_part`), and the
|
||||
* runs are laid end to end as the all_gather concatenates them. The joined table, nsel and
|
||||
* seqused must equal the unsplit scorer and selection byte for byte on every row of the step; a
|
||||
* run's scores must equal the unsplit scores' rows, and its rows past the step score -inf. The
|
||||
* fixtures mix decode rows with a prefill chunk, a missing page, duplicated keys (exact ties) and
|
||||
* signed gates, at world sizes where every rank has rows and where the last ranks have none. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int kHeads = 32, kN = 128, kRatio = 4, kPitch = 136;
|
||||
|
||||
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 Fix {
|
||||
int S = 0, M = 0, nb = 0, pages = 0, topk = 0;
|
||||
std::vector<int32_t> cu, nc, pos, bt;
|
||||
std::vector<uint8_t> q, cache; /* [M*32, 128] codes; [pages, 1, 4, 34] packed keys */
|
||||
std::vector<float> qs, gate; /* [M*32, 1], [M, 32] */
|
||||
};
|
||||
|
||||
/* `decode` one-row sequences, then one prefill chunk of `chunk` rows at `start`. */
|
||||
Fix make(uint32_t seed, int decode, int chunk, int start, int topk) {
|
||||
std::mt19937 rng(seed);
|
||||
std::uniform_int_distribution<int> byte(0, 255), coin(0, 99);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
Fix f;
|
||||
f.S = decode + 1;
|
||||
f.M = decode + chunk;
|
||||
f.topk = topk;
|
||||
f.cu.push_back(0);
|
||||
for (int s = 0; s < decode; ++s) {
|
||||
const int p = 40 + 37 * s + byte(rng) % 50;
|
||||
f.pos.push_back(p);
|
||||
f.cu.push_back(f.cu.back() + 1);
|
||||
f.nc.push_back((p + 1) / kRatio);
|
||||
}
|
||||
for (int i = 0; i < chunk; ++i) f.pos.push_back(start + i);
|
||||
f.cu.push_back(f.M);
|
||||
f.nc.push_back((start + chunk) / kRatio);
|
||||
for (int c : f.nc) f.nb = std::max(f.nb, c + 2);
|
||||
f.pages = f.S * f.nb + 3;
|
||||
f.bt.assign((size_t)f.S * f.nb, -1);
|
||||
for (int s = 0; s < f.S; ++s)
|
||||
for (int b = 0; b <= f.nc[s] && b < f.nb; ++b)
|
||||
f.bt[(size_t)s * f.nb + b] = (s * f.nb + b * 7) % f.pages;
|
||||
f.bt[(size_t)(f.S - 1) * f.nb + 3] = -1;
|
||||
auto code = [&] {
|
||||
int v;
|
||||
do v = byte(rng);
|
||||
while ((v & 0x7f) == 0x7f);
|
||||
return (uint8_t)v;
|
||||
};
|
||||
f.cache.assign((size_t)f.pages * kPitch, 0);
|
||||
for (int p = 0; p < f.pages; ++p) {
|
||||
uint8_t* page = &f.cache[(size_t)p * kPitch];
|
||||
/* Every fifth page repeats its predecessor's key: equal scores on one row. */
|
||||
if (p % 5 == 4)
|
||||
std::memcpy(page, page - kPitch, kPitch);
|
||||
else {
|
||||
for (int d = 0; d < kN; ++d) page[d] = code();
|
||||
const float scale = std::ldexp(1.0f, -6 - p % 3);
|
||||
std::memcpy(page + kN, &scale, 4);
|
||||
}
|
||||
}
|
||||
f.q.resize((size_t)f.M * kHeads * kN);
|
||||
for (auto& v : f.q) v = code();
|
||||
f.qs.resize((size_t)f.M * kHeads);
|
||||
for (size_t i = 0; i < f.qs.size(); ++i) f.qs[i] = std::ldexp(1.0f, -5 - (int)(i % 3));
|
||||
f.gate.resize((size_t)f.M * kHeads);
|
||||
for (auto& v : f.gate) v = nd(rng) * (coin(rng) < 10 ? 0.0f : 1.0f);
|
||||
return f;
|
||||
}
|
||||
|
||||
RadParam pint(const char* k, long long v) { return { k, RAD_P_INT, v, 0, nullptr }; }
|
||||
|
||||
/* Scores `rows` score rows from step row `part * rows` (part < 0: the whole step, no row_part). */
|
||||
int score(const Fix& f, const uint8_t* q, const float* qs, const float* gate, int64_t qrows,
|
||||
int part, int rows, float* out, int32_t* cu_part) {
|
||||
RadTensor t[10] = {
|
||||
tens((void*)q, RAD_F8E4M3, { qrows * kHeads, kN }),
|
||||
tens((void*)qs, RAD_F32, { qrows * kHeads, 1 }),
|
||||
tens((void*)gate, RAD_F32, { qrows, kHeads }),
|
||||
tens((void*)f.cache.data(), RAD_U8, { f.pages, 1, 4, 34 }),
|
||||
RadTensor{},
|
||||
tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }),
|
||||
tens((void*)f.cu.data(), RAD_I32, { f.S + 1 }),
|
||||
tens((void*)f.nc.data(), RAD_I32, { f.S }),
|
||||
tens(out, RAD_F32, { rows, f.nb }),
|
||||
cu_part ? tens(cu_part, RAD_I32, { f.S + 1 }) : RadTensor{},
|
||||
};
|
||||
t[3].stride[0] = kPitch;
|
||||
RadParam p[7] = { pint("M", rows), pint("n", kN), pint("heads", kHeads), pint("blocks", f.nb),
|
||||
pint("seqs", f.S), { "dtype", RAD_P_STR, 0, 0, "fp8_e4m3" },
|
||||
pint("row_part", part) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 10;
|
||||
a.p = p;
|
||||
a.n_p = part < 0 ? 6 : 7;
|
||||
return halo_rad_dsa_score(&a, nullptr);
|
||||
}
|
||||
|
||||
int select(const Fix& f, const float* sc, int rows, const int32_t* pos, const int32_t* cu,
|
||||
int32_t* sel, int32_t* nsel, int32_t* seqused) {
|
||||
RadTensor t[8] = {
|
||||
tens((void*)sc, RAD_F32, { rows, f.nb }),
|
||||
tens((void*)f.bt.data(), RAD_I32, { f.S, f.nb }),
|
||||
tens((void*)f.nc.data(), RAD_I32, { f.S }),
|
||||
tens((void*)pos, RAD_I32, { rows }),
|
||||
tens((void*)cu, RAD_I32, { f.S + 1 }),
|
||||
tens(sel, RAD_I32, { rows, f.topk + 1 }),
|
||||
tens(nsel, RAD_I32, { rows }),
|
||||
tens(seqused, RAD_I32, { rows }),
|
||||
};
|
||||
RadParam p[6] = { pint("M", rows), pint("blocks", f.nb), pint("topk", f.topk),
|
||||
pint("ratio", kRatio), pint("seqs", f.S), pint("signed", 1) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 8;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
const int64_t need = halo_rad_qsa_select_scratch(&a);
|
||||
std::vector<uint32_t> scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u);
|
||||
a.scratch = scratch.data();
|
||||
a.scratch_bytes = need;
|
||||
return halo_rad_qsa_select(&a, nullptr);
|
||||
}
|
||||
|
||||
int check(const char* name, const Fix& f) {
|
||||
const int M = f.M, K = f.topk + 1;
|
||||
std::vector<float> want_sc((size_t)M * f.nb);
|
||||
std::vector<int32_t> want_sel((size_t)M * K, 0x55555555), want_n(M), want_su(M);
|
||||
if (score(f, f.q.data(), f.qs.data(), f.gate.data(), M, -1, M, want_sc.data(), nullptr) ||
|
||||
select(f, want_sc.data(), M, f.pos.data(), f.cu.data(), want_sel.data(), want_n.data(),
|
||||
want_su.data())) {
|
||||
std::printf("FAIL %s: the unsplit launch\n", name);
|
||||
return 1;
|
||||
}
|
||||
int fails = 0;
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
const int R = 4 * ((M + 4 * world - 1) / (4 * world));
|
||||
const int64_t padded = (int64_t)world * R;
|
||||
/* The step's query rows, then rows past the step that a last run reads no further than. */
|
||||
std::vector<uint8_t> q((size_t)padded * kHeads * kN, 0x38);
|
||||
std::vector<float> qs((size_t)padded * kHeads, 1.0f), gate((size_t)padded * kHeads, 3.0f);
|
||||
std::memcpy(q.data(), f.q.data(), f.q.size());
|
||||
std::memcpy(qs.data(), f.qs.data(), f.qs.size() * 4);
|
||||
std::memcpy(gate.data(), f.gate.data(), f.gate.size() * 4);
|
||||
std::vector<int32_t> sel((size_t)padded * K, 0x55555555), ns(padded, 0x55555555),
|
||||
su(padded, 0x55555555);
|
||||
bool ok = true;
|
||||
const char* why = "";
|
||||
for (int part = 0; part < world && ok; ++part) {
|
||||
const int r0 = part * R, have = std::min(R, M - r0);
|
||||
std::vector<float> sc((size_t)R * f.nb, 7.0f);
|
||||
std::vector<int32_t> cu_part(f.S + 1, 0x55555555);
|
||||
if (score(f, q.data(), qs.data(), gate.data(), padded, part, R, sc.data(),
|
||||
cu_part.data())) {
|
||||
ok = false, why = "score launch";
|
||||
break;
|
||||
}
|
||||
for (int s = 0; s <= f.S; ++s) ok = ok && cu_part[s] == f.cu[s] - r0;
|
||||
if (!ok) {
|
||||
why = "cu_part";
|
||||
break;
|
||||
}
|
||||
for (int i = 0; i < R && ok; ++i)
|
||||
for (int b = 0; b < f.nb && ok; ++b) {
|
||||
const float v = sc[(size_t)i * f.nb + b];
|
||||
ok = i < have ? std::memcmp(&v, &want_sc[(size_t)(r0 + i) * f.nb + b], 4) == 0
|
||||
: v == -INFINITY;
|
||||
}
|
||||
if (!ok) {
|
||||
why = "scores";
|
||||
break;
|
||||
}
|
||||
if (have <= 0) continue;
|
||||
if (select(f, sc.data(), have, f.pos.data() + r0, cu_part.data(), &sel[(size_t)r0 * K],
|
||||
&ns[r0], &su[r0])) {
|
||||
ok = false, why = "select launch";
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (ok) {
|
||||
ok = std::memcmp(sel.data(), want_sel.data(), want_sel.size() * 4) == 0;
|
||||
why = "selection";
|
||||
}
|
||||
if (ok) {
|
||||
ok = std::memcmp(ns.data(), want_n.data(), (size_t)M * 4) == 0 &&
|
||||
std::memcmp(su.data(), want_su.data(), (size_t)M * 4) == 0;
|
||||
why = "nsel or seqused";
|
||||
}
|
||||
if (!ok) {
|
||||
std::printf("FAIL %s world %d (R %d): %s differs\n", name, world, R, why);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
int fails = 0, cases = 0;
|
||||
struct Case {
|
||||
const char* name;
|
||||
uint32_t seed;
|
||||
int decode, chunk, start, topk;
|
||||
} cases_[] = {
|
||||
{ "prefill chunk alone", 1, 0, 64, 300, 16 },
|
||||
{ "decode rows beside a chunk", 2, 6, 61, 517, 32 },
|
||||
{ "chunk from position 0, short history", 3, 2, 37, 0, 8 },
|
||||
{ "rows below topk blocks", 4, 3, 29, 20, 64 },
|
||||
};
|
||||
for (const auto& c : cases_) {
|
||||
fails += check(c.name, make(c.seed, c.decode, c.chunk, c.start, c.topk));
|
||||
++cases;
|
||||
}
|
||||
std::printf("dsa split: %d fixture(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_escale.cpp): expert_scale (halo_expert_scale_bf16.hip) on the host SIMT emulator, checked bit
|
||||
* for bit 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; one product rounded once has a single
|
||||
* correct result. 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 "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
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 = halo_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,215 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_f32.cpp): gemm_nt_f32 (halo_glm.hip) on the host SIMT emulator. The form the launcher picks
|
||||
* at each shape (a tile of rows x columns a wave with its steps of k in flight, by M and N; the
|
||||
* shapes reach every one, with K past and short of whole groups of steps) must match the
|
||||
* arithmetic written out here bit for bit: lane l folds k = l, l+32, ... with fmaf, then the xor
|
||||
* butterfly over 16, 8, 4, 2, 1. Tail rows and columns and the pitch's padding stay untouched.
|
||||
*
|
||||
* router_sigmoid_topk from the same unit: the wave-per-row select must match a serial scan written
|
||||
* out here bit for bit, on random and on tied ranks, with the outputs' pitch padding untouched. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
static float gemm_model(const uint16_t* x, const float* w, int k) {
|
||||
float lane[32];
|
||||
for (int l = 0; l < 32; ++l) {
|
||||
float s = 0;
|
||||
for (int j = l; j < k; j += 32) s = std::fmaf(b2f(x[j]), w[j], s);
|
||||
lane[l] = s;
|
||||
}
|
||||
for (int mask = 16; mask; mask >>= 1) {
|
||||
float next[32];
|
||||
for (int l = 0; l < 32; ++l) next[l] = lane[l] + lane[l ^ mask];
|
||||
std::memcpy(lane, next, sizeof lane);
|
||||
}
|
||||
return lane[0];
|
||||
}
|
||||
|
||||
static void router_model(const float* lg, const float* bias, int bp, int ne, int k, int norm,
|
||||
float factor, int* ids, float* w) {
|
||||
float prob[512], rank[512], chosen[32], total = 0;
|
||||
int index[32];
|
||||
for (int e = 0; e < ne; ++e) {
|
||||
prob[e] = 1.0f / (1.0f + expf(-lg[e]));
|
||||
rank[e] = prob[e] + bias[(size_t)e * bp];
|
||||
}
|
||||
for (int j = 0; j < k; ++j) {
|
||||
int best = 0;
|
||||
for (int e = 1; e < ne; ++e)
|
||||
if (rank[e] > rank[best]) best = e;
|
||||
index[j] = best;
|
||||
chosen[j] = prob[best];
|
||||
total += chosen[j];
|
||||
rank[best] = -INFINITY;
|
||||
}
|
||||
const float mult = norm ? factor / (total + 1e-20f) : factor;
|
||||
for (int j = 0; j < k; ++j) {
|
||||
ids[j] = index[j];
|
||||
w[j] = chosen[j] * mult;
|
||||
}
|
||||
}
|
||||
|
||||
static void router_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
struct Shape {
|
||||
int M, ne, k, norm;
|
||||
bool ties;
|
||||
};
|
||||
const Shape shapes[] = { { 1, 288, 8, 1, false }, { 6, 288, 8, 1, false },
|
||||
{ 20, 288, 8, 1, true }, { 48, 288, 8, 1, false },
|
||||
{ 6, 288, 8, 1, true }, { 5, 8, 8, 0, true },
|
||||
{ 5, 32, 32, 0, true }, { 7, 300, 8, 1, false },
|
||||
{ 3, 512, 32, 1, true } };
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.ties ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias) v = sh.ties ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
RadTensor t[4]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 4;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
std::vector<int> ids((size_t)M * ip, -77);
|
||||
std::vector<float> w((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids.data();
|
||||
t[3].data = w.data();
|
||||
++cases;
|
||||
const int rc = halo_rad_router_sigmoid_topk(&a, nullptr);
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M && rc == RAD_OK; ++r) {
|
||||
int mi[32];
|
||||
float mw[32];
|
||||
router_model(&lg[(size_t)r * lp], bias.data(), bp, ne, k, sh.norm, factor, mi, mw);
|
||||
bad += std::memcmp(mi, &ids[(size_t)r * ip], (size_t)k * 4) != 0;
|
||||
bad += std::memcmp(mw, &w[(size_t)r * wp], (size_t)k * 4) != 0;
|
||||
for (int c = k; c < ip; ++c) bad += ids[(size_t)r * ip + c] != -77;
|
||||
for (int c = k; c < wp; ++c) bad += w[(size_t)r * wp + c] != -7.25f;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL router wave select against the scan at M=%d ne=%d k=%d%s (rc %d): "
|
||||
"%d\n",
|
||||
M, ne, k, sh.ties ? " tied" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(17);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
};
|
||||
// One wave an output (M 1), the 2x1, 4x1 (M under 16 or N up to 8), 4x4 and 8x4 tiles.
|
||||
const Shape shapes[] = { { 1, 288, 512 }, { 2, 288, 129 }, { 3, 36, 129 },
|
||||
{ 8, 288, 129 }, { 33, 32, 512 }, { 70, 36, 129 },
|
||||
{ 70, 4, 512 }, { 7, 31, 129 }, { 65, 13, 130 },
|
||||
{ 16, 288, 1056 }, { 24, 288, 1040 }, { 40, 36, 1024 } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, xp = K + 5, yp = N + 3;
|
||||
std::vector<uint16_t> x((size_t)M * xp);
|
||||
std::vector<float> w((size_t)N * K);
|
||||
for (auto& v : x) v = f2b(nd(rng));
|
||||
for (auto& v : w) v = nd(rng) * 0.03f;
|
||||
RadTensor t[3]{};
|
||||
t[0].data = x.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = K;
|
||||
t[0].stride[0] = xp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = w.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 2;
|
||||
t[1].shape[0] = N;
|
||||
t[1].shape[1] = K;
|
||||
t[1].stride[0] = K;
|
||||
t[1].stride[1] = 1;
|
||||
t[2].dtype = RAD_F32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = N;
|
||||
t[2].stride[0] = yp;
|
||||
t[2].stride[1] = 1;
|
||||
RadParam p[4]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3].key = "dtype";
|
||||
p[3].kind = RAD_P_STR;
|
||||
p[3].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 3;
|
||||
a.p = p;
|
||||
a.n_p = 4;
|
||||
std::vector<float> y((size_t)M * yp, -7.25f);
|
||||
t[2].data = y.data();
|
||||
++cases;
|
||||
const int rc = halo_rad_gemm_nt_f32(&a, nullptr);
|
||||
int bad = 0;
|
||||
for (int r = 0; r < M && rc == RAD_OK; ++r) {
|
||||
for (int c = 0; c < N; ++c) {
|
||||
const float e = gemm_model(&x[(size_t)r * xp], &w[(size_t)c * K], K);
|
||||
bad += std::memcmp(&e, &y[(size_t)r * yp + c], 4) != 0;
|
||||
}
|
||||
for (int c = N; c < yp; ++c) bad += y[(size_t)r * yp + c] != -7.25f;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL %s at M=%d N=%d K=%d against its model (rc %d): %d words\n",
|
||||
emu_last_kernel, M, N, K, rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
router_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_fp8f32.cpp): the dense E4M3 GEMM with F32 block scales (halo_fp8_f32scale.hip) on the host SIMT
|
||||
* emulator. The form the rule picks at each shape (the decode form at one and two column tiles a
|
||||
* wave and one to eight waves a block, the 16- and 32-row tiles) must match the legacy 16x64 tile,
|
||||
* which serves an activation pitch off 16 bytes, bit for bit: the same fragments, the same mma
|
||||
* chain per 128-K block and the same fold order. Ragged row counts, pitched rows and a K that
|
||||
* leaves the decode form's last wave group partly idle are covered; the output's pitch padding
|
||||
* stays untouched. The grouped row at GLM's MTP slices is held to a host restatement
|
||||
* (grouped_cases).
|
||||
*
|
||||
* libhalo's unit (halo_gemm_fp8_f32scale.hip) is gfx1151's own design, not a port of these forms,
|
||||
* so this copy does not assert which kernel ran (libr4d's names: the legacy tile, the decode and
|
||||
* small forms); every output comparison stands -- the pitched activation against the unpitched one
|
||||
* byte for byte, and the grouped row against the host restatement byte for byte. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
/* The grouped row at GLM's MTP slices (288 experts, top 8) below 384 routed rows -- the small-M
|
||||
* form at gate_up, the expert-major form at down -- against a host restatement of the
|
||||
* per-element sequence: per 128 of K in order, the
|
||||
* 128-product sum of the emulated WMMA chain from zero, folded as raw * (activation scale *
|
||||
* weight scale) and added. Dropped slots inside runs and past the routed rows, runs longer than an
|
||||
* A tile, token and sorted rows, pointer tables over three slices a class. */
|
||||
static int grouped_cases(int& cases) {
|
||||
struct G {
|
||||
const char* name;
|
||||
int N, K;
|
||||
bool sorted_a;
|
||||
std::vector<int> live;
|
||||
int tail;
|
||||
const char* kernel;
|
||||
};
|
||||
const G all[] = {
|
||||
{ "MTP gate_up, one token", 512, 4096, false, { 1, 1, 1, 1, 1, 1, 1, 1 }, 0,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP gate_up, runs past one tile", 512, 4096, false, { 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }, 2,
|
||||
"fp8_f32scale_small<512>" },
|
||||
{ "MTP down, six tokens", 4096, 256, true, { 3, 1, 10, 2, 1, 5, 1, 1, 17, 4 },
|
||||
3, "(fp8_f32scale_experts<128, 4>)" },
|
||||
};
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
int fails = 0;
|
||||
std::mt19937 rng(77);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (const G& g : all) {
|
||||
const int E = 288, top = 8, N = g.N, K = g.K, kb = K / 128;
|
||||
std::vector<int> runs(E, 0);
|
||||
for (size_t i = 0; i < g.live.size(); ++i) runs[at[i]] = g.live[i];
|
||||
int routed = 0;
|
||||
for (int r : runs) routed += r;
|
||||
const int T = (routed + g.tail + top - 1) / top * top;
|
||||
const int Arows = g.sorted_a ? T : T / top, ap = K + 16, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
std::vector<float> as((size_t)Arows * kb);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
std::vector<uint8_t> w[2];
|
||||
std::vector<float> s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
w[q].resize((size_t)3 * N * K);
|
||||
s[q].resize((size_t)3 * (N / 128) * kb);
|
||||
for (auto& v : w[q]) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
for (auto& v : s[q]) v = std::exp2(oct(rng)) * 0.01f;
|
||||
for (int x = 0; x < E / 2; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % 3) * N * K);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % 3) * (N / 128) * kb);
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777), got((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int n = 0; n < N; ++n) {
|
||||
uint16_t& out = ref[(size_t)r * yp + n];
|
||||
out = 0;
|
||||
if (owner[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1;
|
||||
const bool rv = sorted[r] >= 0;
|
||||
const int ar = !rv ? -1 : g.sorted_a ? r : sorted[r] / top;
|
||||
const uint8_t* wr = (const uint8_t*)wt[q][(size_t)(e / 2)] + (size_t)n * K;
|
||||
const float* sr = (const float*)st[q][(size_t)(e / 2)] + (size_t)(n / 128) * kb;
|
||||
float acc = 0.f;
|
||||
for (int b = 0; b < kb; ++b) {
|
||||
float raw = 0.f;
|
||||
if (rv)
|
||||
for (int k = b * 128; k < b * 128 + 128; ++k)
|
||||
raw += rad_fp8e4m3_to_f32(a[(size_t)ar * ap + k]) *
|
||||
rad_fp8e4m3_to_f32(wr[k]);
|
||||
const float scale = rv ? as[(size_t)ar * kb + b] * sr[b] : 0.f;
|
||||
const float t = raw * scale;
|
||||
acc = acc + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &acc, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
auto ten3 = [](const void* const* tab, uint32_t dt, int64_t n0, int64_t n1, int64_t n2) {
|
||||
RadTensor t{};
|
||||
t.data = (void*)tab;
|
||||
t.dtype = dt;
|
||||
t.rank = 3;
|
||||
t.shape[0] = n0;
|
||||
t.shape[1] = n1;
|
||||
t.shape[2] = n2;
|
||||
t.stride[0] = 0;
|
||||
t.stride[1] = n2;
|
||||
t.stride[2] = 1;
|
||||
return t;
|
||||
};
|
||||
RadTensor t[9] = { mat(a.data(), RAD_F8E4M3, Arows, K, ap),
|
||||
mat(as.data(), RAD_F32, Arows, kb, kb),
|
||||
ten3(wt[0].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[0].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
ten3(wt[1].data(), RAD_F8E4M3, E / 2, N, K),
|
||||
ten3(st[1].data(), RAD_F32, E / 2, N / 128, kb),
|
||||
mat(got.data(), RAD_BF16, T, N, yp) };
|
||||
t[4].data = sorted.data();
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].data = offsets.data();
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = E + 1;
|
||||
t[5].stride[0] = 1;
|
||||
RadParam p[10]{};
|
||||
p[0] = { "M", RAD_P_INT, T / top };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "N_odd", RAD_P_INT, N };
|
||||
p[4] = { "K_odd", RAD_P_INT, K };
|
||||
p[5] = { "n_expert", RAD_P_INT, E };
|
||||
p[6] = { "top_k", RAD_P_INT, top };
|
||||
p[7] = { "group", RAD_P_INT, 128 };
|
||||
p[8].key = "a_order";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = g.sorted_a ? "sorted" : "token";
|
||||
p[9].key = "dtype";
|
||||
p[9].kind = RAD_P_STR;
|
||||
p[9].sval = "fp8a8f32";
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 10;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = halo_rad_moe_fp8_f32scale(&ar, nullptr);
|
||||
size_t i = 0;
|
||||
while (i < got.size() && got[i] == ref[i]) ++i;
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (rc != RAD_OK || i != got.size() || live < routed * N / 2) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu of %zu, %d live\n",
|
||||
g.name, T, emu_last_kernel, g.kernel, rc, i, got.size(), live);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(31);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
struct Shape {
|
||||
int M, N, K;
|
||||
const char* kernel;
|
||||
};
|
||||
const char* const dec1 = "(fp8_f32scale_decode<1, 1>)";
|
||||
const char* const dec2 = "(fp8_f32scale_decode<1, 2>)";
|
||||
const char* const rows = "fp8_f32scale_rows<R>";
|
||||
// Decode at eight, four, two and one waves a block (K blocks 12/32, 4, 2, 1), at two column
|
||||
// tiles a wave from 17 rows over N 1024 and 640; the 16-row tile, and the 32-row one at N 4096.
|
||||
const Shape shapes[] = { { 1, 256, 512, dec1 }, { 6, 128, 1536, dec1 },
|
||||
{ 17, 256, 512, dec1 }, { 48, 128, 512, dec1 },
|
||||
{ 2, 128, 256, dec1 }, { 5, 256, 128, dec1 },
|
||||
{ 3, 128, 4096, dec1 }, { 40, 1024, 512, dec2 },
|
||||
{ 20, 640, 256, dec2 }, { 70, 128, 384, rows },
|
||||
{ 130, 128, 256, rows }, { 33, 4096, 512, rows },
|
||||
{ 70, 4096, 128, rows } };
|
||||
int fails = 0, cases = 0;
|
||||
for (const Shape& sh : shapes) {
|
||||
const int M = sh.M, N = sh.N, K = sh.K, kb = K / 128, ap = K + 16, lp = K + 8, yp = N + 8;
|
||||
std::vector<uint8_t> a((size_t)M * ap), al((size_t)M * lp), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (int r = 0; r < M; ++r) std::memcpy(&al[(size_t)r * lp], &a[(size_t)r * ap], K);
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
// Scales over twelve octaves: K blocks of very different weight cancel, so a changed
|
||||
// summation order shows through the bf16 output.
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
RadTensor t[7] = { mat(a.data(), RAD_F8E4M3, M, K, ap),
|
||||
mat(as.data(), RAD_F32, M, kb, kb),
|
||||
mat(w.data(), RAD_F8E4M3, N, K, K),
|
||||
mat(ws.data(), RAD_F32, N / 128, kb, kb),
|
||||
RadTensor{},
|
||||
RadTensor{},
|
||||
RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "N", RAD_P_INT, N };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
// The pitch off 16 bytes takes the legacy tile.
|
||||
auto run = [&](bool legacy, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * yp, 0x7777);
|
||||
t[0] = legacy ? mat(al.data(), RAD_F8E4M3, M, K, lp)
|
||||
: mat(a.data(), RAD_F8E4M3, M, K, ap);
|
||||
t[4] = mat(y.data(), RAD_BF16, M, N, yp);
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return halo_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> legacy, got;
|
||||
++cases;
|
||||
if (run(true, legacy) != RAD_OK) {
|
||||
std::printf("FAIL legacy M=%d N=%d K=%d ran %s\n", M, N, K, emu_last_kernel);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
int nonzero = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < N; ++c) nonzero += legacy[(size_t)r * yp + c] != 0;
|
||||
if (nonzero < M * N / 2) {
|
||||
std::printf("FAIL legacy output mostly zero at M=%d\n", M);
|
||||
++fails;
|
||||
}
|
||||
/* libhalo's two runs are one kernel at two pitches, so the comparison below checks the
|
||||
* pitch, not the arithmetic: the dense row's numeric anchor is this float64 restatement,
|
||||
* per 128 of K the product sum times (activation scale * weight scale), summed. */
|
||||
{
|
||||
double num = 0, den = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int n = 0; n < N; ++n) {
|
||||
double acc = 0;
|
||||
for (int g = 0; g < kb; ++g) {
|
||||
double sum = 0;
|
||||
for (int k = g * 128; k < g * 128 + 128; ++k)
|
||||
sum += (double)rad_fp8e4m3_to_f32(a[(size_t)r * ap + k]) *
|
||||
(double)rad_fp8e4m3_to_f32(w[(size_t)n * K + k]);
|
||||
acc += sum * (double)as[(size_t)r * kb + g] * (double)ws[(size_t)(n / 128) * kb + g];
|
||||
}
|
||||
const double d = (double)rad_bf16_to_f32(legacy[(size_t)r * yp + n]) - acc;
|
||||
num += d * d;
|
||||
den += acc * acc;
|
||||
}
|
||||
const double rel = std::sqrt(num / den);
|
||||
++cases;
|
||||
if (!(rel < 1e-2)) {
|
||||
std::printf("FAIL dense M=%d N=%d K=%d against float64: rel_l2 %.3e\n", M, N, K, rel);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
++cases;
|
||||
const int rc = run(false, got);
|
||||
if (rc != RAD_OK || got != legacy) {
|
||||
size_t i = 0;
|
||||
while (rc == RAD_OK && i < got.size() && got[i] == legacy[i]) ++i;
|
||||
std::printf("FAIL %s (want %s) at M=%d N=%d K=%d (rc %d, first word %zu)\n",
|
||||
emu_last_kernel, sh.kernel, M, N, K, rc, i);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
fails += grouped_cases(cases);
|
||||
{
|
||||
/* A run of rows and a slice of columns give the bytes the whole product has there: GLM's
|
||||
* MLA split by rows computes q_b and o over a rank's rows at full width, the head form
|
||||
* over every row at a slice of the columns (or of K, as eight rank partials). */
|
||||
const int M = 130, N = 1024, K = 512, kb = K / 128, r0 = 37, mr = 33, c0 = 256, nc = 256;
|
||||
std::vector<uint8_t> a((size_t)M * K), w((size_t)N * K);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng));
|
||||
for (auto& v : w) v = rad_f32_to_fp8e4m3(nd(rng) * 0.5f);
|
||||
std::vector<float> as((size_t)M * kb), ws((size_t)(N / 128) * kb);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
for (auto& v : ws) v = std::exp2(oct(rng)) * 0.01f;
|
||||
auto gemm = [&](int rows, int cols, int row0, int col0, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)rows * cols, 0x7777);
|
||||
RadTensor t[7] = { mat(a.data() + (size_t)row0 * K, RAD_F8E4M3, rows, K, K),
|
||||
mat(as.data() + (size_t)row0 * kb, RAD_F32, rows, kb, kb),
|
||||
mat(w.data() + (size_t)col0 * K, RAD_F8E4M3, cols, K, K),
|
||||
mat(ws.data() + (size_t)(col0 / 128) * kb, RAD_F32, cols / 128, kb,
|
||||
kb),
|
||||
mat(y.data(), RAD_BF16, rows, cols, cols), RadTensor{}, RadTensor{} };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, rows };
|
||||
p[1] = { "N", RAD_P_INT, cols };
|
||||
p[2] = { "K", RAD_P_INT, K };
|
||||
p[3] = { "group", RAD_P_INT, 128 };
|
||||
p[4].key = "dtype";
|
||||
p[4].kind = RAD_P_STR;
|
||||
p[4].sval = "fp8a8f32";
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 7;
|
||||
ar.p = p;
|
||||
ar.n_p = 5;
|
||||
return halo_rad_fp8_f32scale(&ar, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> whole, part;
|
||||
++cases;
|
||||
bool same = gemm(M, N, 0, 0, whole) == RAD_OK && gemm(mr, nc, r0, c0, part) == RAD_OK;
|
||||
for (int r = 0; same && r < mr; ++r)
|
||||
for (int c = 0; c < nc; ++c)
|
||||
same = same && part[(size_t)r * nc + c] == whole[(size_t)(r0 + r) * N + c0 + c];
|
||||
std::printf("%s rows %d..%d x columns %d..%d alone against the %dx%d product\n",
|
||||
same ? "ok " : "FAIL", r0, r0 + mr, c0, c0 + nc, M, N);
|
||||
fails += !same;
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
// tests/halo_emu/test_gemm.cpp -- libhalo's prefill GEMM tiles and the MXFP4 decode plane, run on
|
||||
// the host by tests/r4d_emu's SIMT emulator (its gfx11 WMMA forms), with no card.
|
||||
//
|
||||
// Each tile promises the bytes of a row the card already verified, so each case is a comparison:
|
||||
// gemm_fp8a8_tiled / gemm_i8a8_tiled == gemm_fp8a8_nt_m16 / gemm_i8a8_nt_m16 over 64-row slices,
|
||||
// with the activation plane and without it (decoded while
|
||||
// staging), on both tile arms
|
||||
// gemm_mxfp4a8_tiled == gemm_mxfp4a8_nt_m64 at sk=1 over 64-row slices, both
|
||||
// activation scale grids, ragged N
|
||||
// gemm_mxfp4a8_decode with its activation plane == without it, at every split
|
||||
// plus the narrow fp8 row against a float64 reference, which holds the emulator's gfx11 lane map
|
||||
// to the arithmetic (the narrow kernel is card-verified; a wrong lane map would fail there).
|
||||
// halo_selftest runs the same comparisons on the card at larger shapes.
|
||||
#include "hip/hip_runtime.h" // tests/r4d_emu/emu: the emulator
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h" // rad_f32_to_fp8e4m3: the saturating encoder every fp8 store is held to
|
||||
#include "halo_fp8_frag.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" int halo_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream);
|
||||
extern "C" int64_t halo_rad_gemm_fp8a8_tiled_scratch(const RadArgs*);
|
||||
extern "C" int halo_rad_gemm_fp8a8_m16(const RadArgs*, RadStream);
|
||||
extern "C" int64_t halo_rad_gemm_fp8a8_m16_scratch(const RadArgs*);
|
||||
extern "C" int halo_rad_gemm_i8a8_tiled(const RadArgs*, RadStream);
|
||||
extern "C" int halo_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream);
|
||||
extern "C" int halo_rad_gemm_bf16_tiled(const RadArgs*, RadStream);
|
||||
extern "C" int halo_rad_gemm_bf16_m64(const RadArgs*, RadStream);
|
||||
extern "C" int halo_rad_gemm_i8a8_m16(const RadArgs*, RadStream);
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_tiled(const RadArgs*, RadStream);
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_tiled_plane_scratch(const RadArgs*);
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_m64(const RadArgs*, RadStream);
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_m64_scratch(const RadArgs*);
|
||||
extern "C" int halo_rad_gemm_mxfp4a8_decode(const RadArgs*, RadStream);
|
||||
extern "C" int64_t halo_rad_gemm_mxfp4a8_decode_scratch(const RadArgs*);
|
||||
|
||||
static int g_fail = 0;
|
||||
static void ok(const std::string& what, bool c, const std::string& d = "") {
|
||||
std::printf(" %s %s%s%s\n", c ? "ok " : "FAIL", what.c_str(), d.empty() ? "" : " -- ", d.c_str());
|
||||
if (!c) ++g_fail;
|
||||
}
|
||||
static uint32_t mix(uint32_t x) {
|
||||
x ^= x >> 16; x *= 0x7feb352du; x ^= x >> 15; x *= 0x846ca68bu; x ^= x >> 16; return x;
|
||||
}
|
||||
static RadTensor T(void* d, uint32_t dt, std::vector<int64_t> sh) {
|
||||
RadTensor t; std::memset(&t, 0, sizeof t);
|
||||
t.data = d; t.dtype = dt; t.rank = (uint32_t)sh.size();
|
||||
int64_t acc = 1;
|
||||
for (size_t i = 0; i < sh.size(); ++i) t.shape[i] = sh[i];
|
||||
for (int i = (int)sh.size() - 1; i >= 0; --i) { t.stride[i] = acc; acc *= sh[i]; }
|
||||
return t;
|
||||
}
|
||||
static RadParam PI(const char* k, long long v) { RadParam p; std::memset(&p, 0, sizeof p); p.key = k; p.kind = RAD_P_INT; p.ival = v; return p; }
|
||||
static RadParam PS(const char* k, const char* v) { RadParam p; std::memset(&p, 0, sizeof p); p.key = k; p.kind = RAD_P_STR; p.sval = v; return p; }
|
||||
static float bf(uint16_t h) { uint32_t u = (uint32_t)h << 16; float f; std::memcpy(&f, &u, 4); return f; }
|
||||
static uint16_t to_bf(float f) { uint32_t u; std::memcpy(&u, &f, 4); return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16); }
|
||||
static double e4m3(uint8_t b) {
|
||||
const double s = (b & 0x80) ? -1 : 1; const int ex = (b >> 3) & 15, mn = b & 7;
|
||||
return ex == 0 ? s * mn / 512.0 : s * (1 + mn / 8.0) * std::ldexp(1.0, ex - 7);
|
||||
}
|
||||
|
||||
static int run(int (*launch)(const RadArgs*, RadStream), int64_t (*hook)(const RadArgs*),
|
||||
std::vector<RadTensor> ts, std::vector<RadParam> ps) {
|
||||
RadArgs a; std::memset(&a, 0, sizeof a);
|
||||
a.t = ts.data(); a.n_t = (int)ts.size(); a.p = ps.data(); a.n_p = (int)ps.size(); a.world_size = 1;
|
||||
std::vector<char> scratch;
|
||||
if (hook) {
|
||||
const int64_t need = hook(&a);
|
||||
if (need > 0) { scratch.assign((size_t)need, (char)0x5a); a.scratch = scratch.data(); a.scratch_bytes = need; }
|
||||
}
|
||||
return launch(&a, nullptr);
|
||||
}
|
||||
|
||||
/* fp8 / i8: tiled (plane), tiled (none), the narrow row over 64-row slices. */
|
||||
static void fp8_case(int64_t M, int64_t N, int64_t K, bool i8) {
|
||||
const std::string tag = std::string(i8 ? "i8a8" : "fp8a8") + " tiled M=" + std::to_string(M) +
|
||||
" N=" + std::to_string(N) + " K=" + std::to_string(K);
|
||||
const int64_t sk = K / 128, sn = i8 ? N : N / 128;
|
||||
std::vector<uint8_t> a((size_t)(M * K)), w((size_t)(N * K));
|
||||
std::vector<float> as((size_t)(M * sk));
|
||||
std::vector<uint16_t> ws((size_t)(sn * sk));
|
||||
auto code = [i8](uint32_t i) { uint8_t c = (uint8_t)mix(i); return !i8 && (c & 0x7f) == 0x7f ? (uint8_t)(c ^ 1) : c; };
|
||||
for (size_t i = 0; i < a.size(); ++i) a[i] = code((uint32_t)i * 2u + 1u);
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = code((uint32_t)i * 2u + 0x5bd1e995u);
|
||||
for (size_t i = 0; i < as.size(); ++i) as[i] = std::ldexp(1.0f + (mix((uint32_t)i + 77) & 255) / 256.0f, -(int)(mix((uint32_t)i + 99) % 9) - 4);
|
||||
for (size_t i = 0; i < ws.size(); ++i) ws[i] = to_bf(std::ldexp(1.0f + (mix((uint32_t)i + 5) & 127) / 128.0f, -(int)(mix((uint32_t)i + 7) % 7) - 6));
|
||||
std::vector<uint16_t> y[3];
|
||||
for (auto& v : y) v.assign((size_t)(M * N), 0xffff);
|
||||
const uint32_t cdt = i8 ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
|
||||
auto go = [&](int (*l)(const RadArgs*, RadStream), int64_t (*h)(const RadArgs*), int64_t m0, int64_t mm, std::vector<uint16_t>& out) {
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data() + m0 * K, cdt, { mm, K }), T(as.data() + m0 * sk, RAD_F32, { mm, sk }),
|
||||
T(w.data(), cdt, { N, K }), T(ws.data(), RAD_BF16, { sn, sk }),
|
||||
T(out.data() + m0 * N, RAD_BF16, { mm, N }), T(nullptr, RAD_F32, { 1 }), T(nullptr, RAD_U8, { 1 }) };
|
||||
ts[5].data = nullptr; ts[5].rank = 0; ts[6].data = nullptr; ts[6].rank = 0;
|
||||
return run(l, h, ts, { PI("M", mm), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", i8 ? "i8a8" : "fp8a8") });
|
||||
};
|
||||
int rc = i8 ? go(halo_rad_gemm_i8a8_tiled, nullptr, 0, M, y[0]) : go(halo_rad_gemm_fp8a8_tiled, halo_rad_gemm_fp8a8_tiled_scratch, 0, M, y[0]);
|
||||
rc |= i8 ? go(halo_rad_gemm_i8a8_tiled, nullptr, 0, M, y[1]) : go(halo_rad_gemm_fp8a8_tiled, nullptr, 0, M, y[1]);
|
||||
for (int64_t m0 = 0; m0 < M; m0 += 64)
|
||||
rc |= i8 ? go(halo_rad_gemm_i8a8_m16, nullptr, m0, std::min<int64_t>(64, M - m0), y[2])
|
||||
: go(halo_rad_gemm_fp8a8_m16, halo_rad_gemm_fp8a8_m16_scratch, m0, std::min<int64_t>(64, M - m0), y[2]);
|
||||
if (rc) { ok(tag, false, "rc " + std::to_string(rc)); return; }
|
||||
size_t d0 = 0, d1 = 0;
|
||||
for (size_t e = 0; e < y[2].size(); ++e) { d0 += y[0][e] != y[2][e]; d1 += y[1][e] != y[2][e]; }
|
||||
if (i8) {
|
||||
/* gemm_i8a8_tiled has no scratch hook: both runs take the same path, so one line. */
|
||||
ok(tag + " == narrow slices", d0 == 0 && d1 == 0, std::to_string(d0) + " differ");
|
||||
return;
|
||||
}
|
||||
ok(tag + " (plane) == narrow slices", d0 == 0, std::to_string(d0) + " differ");
|
||||
ok(tag + " (no plane) == narrow slices", d1 == 0, std::to_string(d1) + " differ");
|
||||
/* The narrow row against float64: checks the emulator's WMMA layout (the narrow kernel is
|
||||
* hardware-verified, so an emulator with a wrong lane map would fail here). */
|
||||
std::vector<double> wl((size_t)(N * K));
|
||||
for (int64_t rt = 0; rt < N / 16; ++rt)
|
||||
for (int64_t ks = 0; ks < K / 64; ++ks)
|
||||
for (int ln = 0; ln < 32; ++ln)
|
||||
for (int t = 0; t < 4; ++t)
|
||||
for (int j = 0; j < 8; ++j) {
|
||||
int64_t row, k;
|
||||
halo_fp8::frag_src(rt, ks, ln, t, j, &row, &k);
|
||||
wl[(size_t)(row * K + k)] = e4m3(w[(size_t)(((rt * (K / 64) + ks) * 32 + ln) * 32 + t * 8 + j)]);
|
||||
}
|
||||
double num = 0, den = 0;
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
double acc = 0;
|
||||
for (int64_t g = 0; g < sk; ++g) {
|
||||
double s = 0;
|
||||
for (int64_t k = g * 128; k < g * 128 + 128; ++k) s += e4m3(a[(size_t)(m * K + k)]) * wl[(size_t)(n * K + k)];
|
||||
acc += s * as[(size_t)(m * sk + g)] * bf(ws[(size_t)((n / 128) * sk + g)]);
|
||||
}
|
||||
const double d = bf(y[2][(size_t)(m * N + n)]) - acc;
|
||||
num += d * d; den += acc * acc;
|
||||
}
|
||||
const double rel = std::sqrt(num / den);
|
||||
ok(tag + " narrow vs float64 reference", rel < 1e-2, "rel_l2 " + std::to_string(rel));
|
||||
}
|
||||
|
||||
/* The gated narrow row's contract (its row table): the bytes of gemm_nt_q followed by
|
||||
* gated_quant_fp8. The narrow row computes the [M, N] gate|up product; the quantiser is restated
|
||||
* here in its own arithmetic -- gate and up rounded to bf16, silu(g) * u rounded to bf16, the group
|
||||
* amax over 128 columns, scale amax / 448 (1 at zero), codes of v * (1 / scale) clamped to +-448 by
|
||||
* the saturating encoder -- and the gated row's codes, scales and bf16 product must match. */
|
||||
static void gated_ref_case(int64_t M, int64_t N, int64_t K) {
|
||||
const std::string tag = "fp8a8 gated == gemm_nt_q + gated_quant_fp8, M=" + std::to_string(M) +
|
||||
" N=" + std::to_string(N) + " K=" + std::to_string(K);
|
||||
const int64_t sk = K / 128, sn = N / 128, nout = N / 2;
|
||||
std::vector<uint8_t> a((size_t)(M * K)), w((size_t)(N * K));
|
||||
std::vector<float> as((size_t)(M * sk));
|
||||
std::vector<uint16_t> ws((size_t)(sn * sk));
|
||||
auto code = [](uint32_t i) { uint8_t c = (uint8_t)mix(i); return (c & 0x7f) == 0x7f ? (uint8_t)(c ^ 1) : c; };
|
||||
for (size_t i = 0; i < a.size(); ++i) a[i] = code((uint32_t)i * 2u + 7u);
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = code((uint32_t)i * 2u + 0x1234567u);
|
||||
for (size_t i = 0; i < as.size(); ++i) as[i] = std::ldexp(1.0f + (mix((uint32_t)i + 3) & 255) / 256.0f, -(int)(mix((uint32_t)i + 9) % 5) - 6);
|
||||
for (size_t i = 0; i < ws.size(); ++i) ws[i] = to_bf(std::ldexp(1.0f + (mix((uint32_t)i + 15) & 127) / 128.0f, -(int)(mix((uint32_t)i + 21) % 5) - 8));
|
||||
std::vector<uint16_t> y((size_t)(M * N), 0xffff);
|
||||
{
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data(), RAD_F8E4M3, { M, K }), T(as.data(), RAD_F32, { M, sk }), T(w.data(), RAD_F8E4M3, { N, K }),
|
||||
T(ws.data(), RAD_BF16, { sn, sk }), T(y.data(), RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(nullptr, RAD_U8, { 1 }) };
|
||||
ts[5].data = nullptr; ts[5].rank = 0; ts[6].data = nullptr; ts[6].rank = 0;
|
||||
if (run(halo_rad_gemm_fp8a8_m16, nullptr, ts, { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "fp8a8") })) {
|
||||
ok(tag, false, "the narrow row failed"); return;
|
||||
}
|
||||
}
|
||||
std::vector<uint8_t> q((size_t)(M * nout), 0xee), rq((size_t)(M * nout));
|
||||
std::vector<float> qs((size_t)(M * nout / 128), -1.f), rqs((size_t)(M * nout / 128));
|
||||
std::vector<uint16_t> yg((size_t)(M * nout), 0xffff), ry((size_t)(M * nout));
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t g = 0; g < nout / 128; ++g) {
|
||||
float v[128], amax = 0.f;
|
||||
for (int c = 0; c < 128; ++c) {
|
||||
const int64_t n = g * 128 + c;
|
||||
const float gv = bf(y[(size_t)(m * N + n)]), uv = bf(y[(size_t)(m * N + n + nout)]);
|
||||
const uint16_t hb = to_bf(gv / (1.0f + std::exp(-gv)) * uv);
|
||||
ry[(size_t)(m * nout + n)] = hb;
|
||||
v[c] = bf(hb);
|
||||
amax = std::fmax(amax, std::fabs(v[c]));
|
||||
}
|
||||
const float sc = amax > 0.0f ? amax * (1.0f / 448.0f) : 1.0f;
|
||||
rqs[(size_t)(m * (nout / 128) + g)] = sc;
|
||||
for (int c = 0; c < 128; ++c)
|
||||
rq[(size_t)(m * nout + g * 128 + c)] =
|
||||
rad_f32_to_fp8e4m3(std::fmin(std::fmax(v[c] * (1.0f / sc), -448.0f), 448.0f));
|
||||
}
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data(), RAD_F8E4M3, { M, K }), T(as.data(), RAD_F32, { M, sk }), T(w.data(), RAD_F8E4M3, { N, K }),
|
||||
T(ws.data(), RAD_BF16, { sn, sk }), T(q.data(), RAD_F8E4M3, { M, nout }),
|
||||
T(qs.data(), RAD_F32, { M, nout / 128 }), T(yg.data(), RAD_BF16, { M, nout }) };
|
||||
if (run(halo_rad_gemm_fp8a8_gated_m16, nullptr, ts,
|
||||
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "fp8a8"), PS("act", "silu") })) {
|
||||
ok(tag, false, "the gated row failed"); return;
|
||||
}
|
||||
size_t dq = 0, ds = 0, dy = 0;
|
||||
for (size_t i = 0; i < q.size(); ++i) { dq += q[i] != rq[i]; dy += yg[i] != ry[i]; }
|
||||
for (size_t i = 0; i < qs.size(); ++i) ds += std::memcmp(&qs[i], &rqs[i], 4) != 0;
|
||||
ok(tag, dq == 0 && ds == 0 && dy == 0,
|
||||
std::to_string(dq) + " codes, " + std::to_string(ds) + " scales, " + std::to_string(dy) + " products differ");
|
||||
}
|
||||
|
||||
/* gemm_bf16_nt_tiled's contract (its header): byte-identical to gemm_bf16_nt_m64 at the same
|
||||
* shape -- both take SK from cfg_for, accumulate each slice from zero one WMMA per 16 K in order
|
||||
* and sum the slices from 0.f. Both tile arms (tile 1: 128 x 128, tile 2: 64 x 64), a K the split
|
||||
* law splits, ragged M and N. */
|
||||
static void bf16_case(int64_t M, int64_t N, int64_t K, int tile) {
|
||||
const std::string tag = "bf16 tiled(" + std::to_string(tile) + ") == m64, M=" + std::to_string(M) +
|
||||
" N=" + std::to_string(N) + " K=" + std::to_string(K);
|
||||
std::vector<uint16_t> a((size_t)(M * K)), w((size_t)(N * K));
|
||||
for (size_t i = 0; i < a.size(); ++i) a[i] = to_bf((float)((int)(mix((uint32_t)i + 41) % 2001) - 1000) / 400.0f);
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = to_bf((float)((int)(mix((uint32_t)i + 0x9e37) % 2001) - 1000) / 900.0f);
|
||||
std::vector<uint16_t> y[2];
|
||||
for (auto& v : y) v.assign((size_t)(M * N), 0xffff);
|
||||
int rc = 0;
|
||||
for (int v = 0; v < 2; ++v) {
|
||||
std::vector<RadTensor> ts = { T(a.data(), RAD_BF16, { M, K }), T(w.data(), RAD_BF16, { N, K }),
|
||||
T(y[v].data(), RAD_BF16, { M, N }) };
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PS("dtype", "bf16") };
|
||||
if (v == 0) ps.push_back(PI("tile", tile));
|
||||
rc |= run(v == 0 ? halo_rad_gemm_bf16_tiled : halo_rad_gemm_bf16_m64, nullptr, ts, ps);
|
||||
}
|
||||
if (rc) { ok(tag, false, "rc " + std::to_string(rc)); return; }
|
||||
size_t d = 0;
|
||||
for (size_t i = 0; i < y[0].size(); ++i) d += y[0][i] != y[1][i];
|
||||
ok(tag, d == 0, std::to_string(d) + " of " + std::to_string(y[0].size()) + " differ");
|
||||
}
|
||||
|
||||
/* mxfp4: tiled (plane), tiled (none), m64 at sk=1 over 64-row slices; both scale grids. */
|
||||
/* pb1/pb2 > 0: a partitioned weight (mx_parts) -- the activation one K-wide copy a part, side by
|
||||
* side, each part a column window of the output. */
|
||||
static void mx_case(int64_t M, int64_t N, int64_t K, bool ablk, int64_t pb1 = 0, int64_t pb2 = 0) {
|
||||
const int segs = 1 + (pb1 > 0) + (pb2 > 0);
|
||||
const std::string tag = "mxfp4a8 tiled M=" + std::to_string(M) + " N=" + std::to_string(N) + " K=" +
|
||||
std::to_string(K) + (ablk ? " ascale=row x 128" : " ascale=row") +
|
||||
(segs > 1 ? " parts=" + std::to_string(segs) : "");
|
||||
const int64_t kb = K / 128, sa = ablk ? kb * segs : 1, KA = K * segs;
|
||||
std::vector<uint8_t> a((size_t)(M * KA)), w((size_t)(N * K / 2)), e((size_t)(K / 32 * N)), rf((size_t)N);
|
||||
std::vector<float> as((size_t)(M * sa));
|
||||
for (size_t i = 0; i < a.size(); ++i) { uint8_t c = (uint8_t)mix((uint32_t)i * 2u + 3u); a[i] = (c & 0x7f) == 0x7f ? (uint8_t)(c ^ 1) : c; }
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = (uint8_t)mix((uint32_t)i + 0x2545f491u);
|
||||
for (int64_t n = 0; n < N; ++n) rf[(size_t)n] = (uint8_t)(120 + mix((uint32_t)n + 11) % 15);
|
||||
for (int64_t b = 0; b < K / 32; ++b)
|
||||
for (int64_t n = 0; n < N; ++n) e[(size_t)(b * N + n)] = (uint8_t)(rf[(size_t)n] - 10 + (int)(mix((uint32_t)(b * N + n) + 31) % 21));
|
||||
for (size_t i = 0; i < as.size(); ++i) as[i] = std::ldexp(1.0f + (mix((uint32_t)i + 13) & 255) / 256.0f, -(int)(mix((uint32_t)i + 17) % 9) - 4);
|
||||
std::vector<uint16_t> y[3];
|
||||
for (auto& v : y) v.assign((size_t)(M * N), 0xffff);
|
||||
auto go = [&](int (*l)(const RadArgs*, RadStream), int64_t (*h)(const RadArgs*), int64_t m0, int64_t mm, std::vector<uint16_t>& out, bool one) {
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data() + m0 * KA, RAD_F8E4M3, { mm, KA }),
|
||||
ablk ? T(as.data() + m0 * sa, RAD_F32, { mm, sa }) : T(as.data() + m0, RAD_F32, { mm }),
|
||||
T(w.data(), RAD_U8, { (int64_t)w.size() }), T(e.data(), RAD_U8, { (int64_t)e.size() }),
|
||||
T(out.data() + m0 * N, RAD_BF16, { mm, N }), T(nullptr, RAD_F32, { 1 }), T(rf.data(), RAD_U8, { N }) };
|
||||
ts[5].data = nullptr; ts[5].rank = 0;
|
||||
std::vector<RadParam> ps = { PI("M", mm), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8") };
|
||||
if (one) ps.push_back(PI("sk", 1));
|
||||
if (pb1) ps.push_back(PI("pb1", pb1));
|
||||
if (pb2) ps.push_back(PI("pb2", pb2));
|
||||
return run(l, h, ts, ps);
|
||||
};
|
||||
int rc = go(halo_rad_gemm_mxfp4a8_tiled, halo_rad_gemm_mxfp4a8_tiled_plane_scratch, 0, M, y[0], false);
|
||||
rc |= go(halo_rad_gemm_mxfp4a8_tiled, nullptr, 0, M, y[1], false);
|
||||
for (int64_t m0 = 0; m0 < M; m0 += 64)
|
||||
rc |= go(halo_rad_gemm_mxfp4a8_m64, halo_rad_gemm_mxfp4a8_m64_scratch, m0, std::min<int64_t>(64, M - m0), y[2], true);
|
||||
if (rc) { ok(tag, false, "rc " + std::to_string(rc)); return; }
|
||||
size_t d0 = 0, d1 = 0;
|
||||
for (size_t q = 0; q < y[2].size(); ++q) { d0 += y[0][q] != y[2][q]; d1 += y[1][q] != y[2][q]; }
|
||||
ok(tag + " (plane) == m64 sk=1 slices", d0 == 0, std::to_string(d0) + " differ");
|
||||
ok(tag + " (no plane) == m64 sk=1 slices", d1 == 0, std::to_string(d1) + " differ");
|
||||
}
|
||||
|
||||
/* The decode row with its hook's scratch (split partials + the activation plane) against the same
|
||||
* call with the plane's bytes withheld (partials only: the in-kernel decode), at every split. */
|
||||
static void mxd_case(int64_t M, int64_t N, int64_t K, bool ablk, int ks) {
|
||||
const std::string tag = "mxfp4a8_decode M=" + std::to_string(M) + " N=" + std::to_string(N) + " K=" +
|
||||
std::to_string(K) + " ks=" + std::to_string(ks) + (ablk ? " ascale=row x 128" : " ascale=row");
|
||||
const int64_t kb = K / 128, sa = ablk ? kb : 1;
|
||||
std::vector<uint8_t> a((size_t)(M * K)), w((size_t)(N * K / 2)), e((size_t)(K / 32 * N)), rf((size_t)N);
|
||||
std::vector<float> as((size_t)(M * sa));
|
||||
for (size_t i = 0; i < a.size(); ++i) { uint8_t c = (uint8_t)mix((uint32_t)i * 2u + 3u); a[i] = (c & 0x7f) == 0x7f ? (uint8_t)(c ^ 1) : c; }
|
||||
for (size_t i = 0; i < w.size(); ++i) w[i] = (uint8_t)mix((uint32_t)i + 0x2545f491u);
|
||||
for (int64_t n = 0; n < N; ++n) rf[(size_t)n] = (uint8_t)(120 + mix((uint32_t)n + 11) % 15);
|
||||
for (int64_t b = 0; b < K / 32; ++b)
|
||||
for (int64_t n = 0; n < N; ++n) e[(size_t)(b * N + n)] = (uint8_t)(rf[(size_t)n] - 10 + (int)(mix((uint32_t)(b * N + n) + 31) % 21));
|
||||
for (size_t i = 0; i < as.size(); ++i) as[i] = std::ldexp(1.0f + (mix((uint32_t)i + 13) & 255) / 256.0f, -(int)(mix((uint32_t)i + 17) % 9) - 4);
|
||||
std::vector<uint16_t> y[3];
|
||||
for (auto& v : y) v.assign((size_t)(M * N), 0xffff);
|
||||
int rc = 0;
|
||||
for (int pass = 0; pass < 2; ++pass) {
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data(), RAD_F8E4M3, { M, K }),
|
||||
ablk ? T(as.data(), RAD_F32, { M, kb }) : T(as.data(), RAD_F32, { M }),
|
||||
T(w.data(), RAD_U8, { (int64_t)w.size() }), T(e.data(), RAD_U8, { (int64_t)e.size() }),
|
||||
T(y[pass].data(), RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }), T(rf.data(), RAD_U8, { N }) };
|
||||
ts[5].data = nullptr; ts[5].rank = 0;
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"), PI("ks", ks) };
|
||||
RadArgs ra; std::memset(&ra, 0, sizeof ra);
|
||||
ra.t = ts.data(); ra.n_t = (int)ts.size(); ra.p = ps.data(); ra.n_p = (int)ps.size(); ra.world_size = 1;
|
||||
int64_t need = halo_rad_gemm_mxfp4a8_decode_scratch(&ra);
|
||||
if (pass == 1) need -= M * K * 2; /* partials only: no plane */
|
||||
std::vector<char> sc((size_t)std::max<int64_t>(need, 1), (char)0x5a);
|
||||
ra.scratch = need > 0 ? sc.data() : nullptr; ra.scratch_bytes = need > 0 ? need : 0;
|
||||
rc |= halo_rad_gemm_mxfp4a8_decode(&ra, nullptr);
|
||||
}
|
||||
if (rc) { ok(tag, false, "rc " + std::to_string(rc)); return; }
|
||||
size_t d = 0;
|
||||
for (size_t q = 0; q < y[0].size(); ++q) d += y[0][q] != y[1][q];
|
||||
ok(tag + " plane == no plane", d == 0, std::to_string(d) + " differ");
|
||||
/* At one split the decode row's per-element arithmetic is the skinny kernel's (its header):
|
||||
* the same bytes as gemm_mxfp4a8_nt_m64 at sk=1, over 64-row slices. */
|
||||
if (ks != 1) return;
|
||||
for (int64_t m0 = 0; m0 < M && !rc; m0 += 64) {
|
||||
const int64_t mm = std::min<int64_t>(64, M - m0);
|
||||
std::vector<RadTensor> ts = {
|
||||
T(a.data() + m0 * K, RAD_F8E4M3, { mm, K }),
|
||||
ablk ? T(as.data() + m0 * sa, RAD_F32, { mm, kb }) : T(as.data() + m0, RAD_F32, { mm }),
|
||||
T(w.data(), RAD_U8, { (int64_t)w.size() }), T(e.data(), RAD_U8, { (int64_t)e.size() }),
|
||||
T(y[2].data() + m0 * N, RAD_BF16, { mm, N }), T(nullptr, RAD_F32, { 1 }), T(rf.data(), RAD_U8, { N }) };
|
||||
ts[5].data = nullptr; ts[5].rank = 0;
|
||||
rc |= run(halo_rad_gemm_mxfp4a8_m64, halo_rad_gemm_mxfp4a8_m64_scratch, ts,
|
||||
{ PI("M", mm), PI("N", N), PI("K", K), PI("group", 32), PS("dtype", "mxfp4a8"), PI("sk", 1) });
|
||||
}
|
||||
if (rc) { ok(tag + " == nt_m64 sk=1", false, "rc " + std::to_string(rc)); return; }
|
||||
d = 0;
|
||||
for (size_t q = 0; q < y[0].size(); ++q) d += y[0][q] != y[2][q];
|
||||
ok(tag + " == nt_m64 sk=1 slices", d == 0, std::to_string(d) + " differ");
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const std::string only = argc > 1 ? argv[1] : "";
|
||||
if (only.empty() || only == "fp8") {
|
||||
fp8_case(100, 256, 384, false); /* 64 x 64 arm */
|
||||
fp8_case(520, 1024, 384, false); /* 128 x 128 arm, ragged M */
|
||||
}
|
||||
if (only.empty() || only == "bf16") {
|
||||
bf16_case(40, 272, 640, 2);
|
||||
bf16_case(64, 512, 2560, 1);
|
||||
bf16_case(17, 1040, 5120, 2);
|
||||
bf16_case(64, 384, 1280, 1);
|
||||
}
|
||||
if (only.empty() || only == "gated") {
|
||||
gated_ref_case(5, 512, 256);
|
||||
gated_ref_case(40, 1024, 256);
|
||||
gated_ref_case(64, 512, 256);
|
||||
}
|
||||
if (only.empty() || only == "i8") {
|
||||
fp8_case(100, 256, 384, true);
|
||||
fp8_case(520, 1024, 384, true);
|
||||
}
|
||||
if (only.empty() || only == "mx") {
|
||||
mx_case(100, 272, 640, true);
|
||||
mx_case(100, 272, 640, false);
|
||||
mx_case(330, 1040, 384, true); /* 128 x 128 arm: (1040/128 -> 9) x 3 = 27 < 32 ... */
|
||||
mx_case(520, 1040, 256, false); /* 9 x 5 = 45 >= 32: 128 x 128, ragged N */
|
||||
mx_case(100, 272, 384, true, 96, 192); /* three parts (a fused q|k|v), ragged last */
|
||||
mx_case(300, 1040, 256, true, 512); /* two parts, 128 x 128 arm (parts need the 128 grid) */
|
||||
}
|
||||
if (only.empty() || only == "mxd") {
|
||||
for (int ks : { 1, 2, 4 }) {
|
||||
mxd_case(8, 400, 1024, true, ks);
|
||||
mxd_case(72, 272, 640, false, ks == 4 ? 2 : ks);
|
||||
}
|
||||
}
|
||||
std::printf("%s (%d failure(s))\n", g_fail ? "FAIL" : "PASS", g_fail);
|
||||
return g_fail ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_kda.cpp): kda_update (halo_kda.hip) on the host SIMT emulator, held to libref's kda_update
|
||||
* (from $RADIANCE_HOME, which ctest sets) over the output and the whole state buffer, in all four
|
||||
* modes: prefill per candidate and anchored, verify per candidate and anchored (after the replay
|
||||
* of the accepted prefix). Cold starts, an unseated sequence, an empty sequence and an unwritten
|
||||
* slot are mixed in, so a byte the reference leaves alone must stay as it was. The kernel's lane
|
||||
* reductions sum in another order than libref's loops: f32 state within 2e-5 + 2e-5 |x|, bf16
|
||||
* output within one rounding step. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
static uint16_t f2b(float f) {
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &f, 4);
|
||||
return (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >> 16);
|
||||
}
|
||||
|
||||
/* libref's kda_update, through the plugin's own exports, or null. */
|
||||
static RadLaunchFn load_libref() {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
if (!home || !*home) return nullptr;
|
||||
const std::string p = std::string(home) + "/kernels/libref.so";
|
||||
void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) return nullptr;
|
||||
auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */
|
||||
if (open && open() < 0) return nullptr;
|
||||
auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
if (!cnt || !at) return nullptr;
|
||||
for (int i = 0; i < cnt(); ++i) {
|
||||
const RadKernelInfo* k = at(i);
|
||||
if (k && k->op && !std::strcmp(k->op, "kda_update")) return k->launch;
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static float bf16_value(uint16_t b) {
|
||||
const uint32_t u = (uint32_t)b << 16;
|
||||
float f;
|
||||
std::memcpy(&f, &u, 4);
|
||||
return f;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
const char* mode;
|
||||
bool anchor;
|
||||
int64_t width;
|
||||
std::vector<int> cu, idx, accepted, init;
|
||||
std::vector<std::pair<int64_t, float>> counts;
|
||||
};
|
||||
|
||||
int main() {
|
||||
const RadLaunchFn reference = load_libref();
|
||||
if (!reference) {
|
||||
std::printf("FAIL libref's kda_update not loadable (set RADIANCE_HOME)\n");
|
||||
return 1;
|
||||
}
|
||||
std::mt19937 rng(41);
|
||||
std::uniform_real_distribution<float> u(-1.f, 1.f);
|
||||
const int64_t H = 2, D = 128, slots = 16, tokens = 9;
|
||||
std::vector<float> state0((size_t)(slots * H * D * D)), alog((size_t)H), bias((size_t)(H * D));
|
||||
for (auto& v : state0) v = u(rng);
|
||||
for (auto& v : alog) v = 0.5f * u(rng);
|
||||
for (auto& v : bias) v = u(rng);
|
||||
std::vector<uint16_t> in[5];
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
in[i].resize((size_t)(tokens * H * (i == 4 ? 1 : D)));
|
||||
for (auto& v : in[i]) v = f2b((i >= 3 ? 2.f : 1.f) * u(rng));
|
||||
}
|
||||
const std::vector<Case> cases = {
|
||||
{ "prefill, per candidate",
|
||||
"prefill",
|
||||
false,
|
||||
1,
|
||||
{ 0, 4, 4, 9 },
|
||||
{ 3, 4, -1 },
|
||||
{ 1, 1, 1 },
|
||||
{ 0, 1, 1 },
|
||||
{} },
|
||||
{ "prefill, anchored",
|
||||
"prefill",
|
||||
true,
|
||||
2,
|
||||
{ 0, 5, 9 },
|
||||
{ 1, 2, 3, 4 },
|
||||
{ 1, 1 },
|
||||
{ 1, 0 },
|
||||
{} },
|
||||
{ "verify, per candidate",
|
||||
"verify",
|
||||
false,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, -1 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 0, 1 },
|
||||
{} },
|
||||
{ "verify, anchored",
|
||||
"verify",
|
||||
true,
|
||||
4,
|
||||
{ 0, 4, 7, 9 },
|
||||
{ 1, 9, 5, 9, 2, 9, 6, 9, 3, 9, 7, 9 },
|
||||
{ 3, 2, 1 },
|
||||
{ 1, 1, 0 },
|
||||
{ { 5, 4.f }, { 6, 3.f }, { 7, 0.f } } },
|
||||
};
|
||||
int fails = 0, checks = 0;
|
||||
for (const Case& c : cases) {
|
||||
std::vector<float> start = state0;
|
||||
for (const auto& sc : c.counts)
|
||||
for (int64_t h = 0; h < H; ++h) start[(size_t)((sc.first * H + h) * D * D)] = sc.second;
|
||||
const int64_t seqs = (int64_t)c.cu.size() - 1;
|
||||
std::vector<int> idx = c.idx, cu = c.cu, acc = c.accepted, init = c.init;
|
||||
auto run = [&](RadLaunchFn launch, std::vector<uint16_t>& out, std::vector<float>& state) {
|
||||
out.assign((size_t)(tokens * H * D), 0x7777);
|
||||
state = start;
|
||||
RadTensor t[13] = { tens(in[0].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[1].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[2].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[3].data(), RAD_BF16, { tokens, H, D }),
|
||||
tens(in[4].data(), RAD_BF16, { tokens, H }),
|
||||
tens(alog.data(), RAD_F32, { H }),
|
||||
tens(bias.data(), RAD_F32, { H * D }),
|
||||
tens(state.data(), RAD_F32, { slots, H, D, D }),
|
||||
tens(idx.data(), RAD_I32, { seqs, c.width }),
|
||||
tens(cu.data(), RAD_I32, { seqs + 1 }),
|
||||
tens(acc.data(), RAD_I32, { seqs }),
|
||||
tens(init.data(), RAD_I32, { seqs }),
|
||||
tens(out.data(), RAD_BF16, { tokens, H, D }) };
|
||||
RadParam p[10]{};
|
||||
p[0] = { "heads", RAD_P_INT, H };
|
||||
p[1] = { "head_k", RAD_P_INT, D };
|
||||
p[2] = { "head_v", RAD_P_INT, D };
|
||||
p[3].key = "lower_bound";
|
||||
p[3].kind = RAD_P_F64;
|
||||
p[3].dval = -5;
|
||||
p[4].key = "scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 1.0 / std::sqrt(128.0);
|
||||
p[5].key = "l2_eps";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 1e-6;
|
||||
p[6].key = "mode";
|
||||
p[6].kind = RAD_P_STR;
|
||||
p[6].sval = c.mode;
|
||||
p[7].key = "state_form";
|
||||
p[7].kind = RAD_P_STR;
|
||||
p[7].sval = c.anchor ? "anchor" : "per_candidate";
|
||||
p[8].key = "dtype";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = "bf16";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 13;
|
||||
a.p = p;
|
||||
a.n_p = 9;
|
||||
return launch(&a, nullptr);
|
||||
};
|
||||
std::vector<uint16_t> ref_out, out;
|
||||
std::vector<float> ref_state, state;
|
||||
++checks;
|
||||
if (run(reference, ref_out, ref_state) != RAD_OK ||
|
||||
run(halo_rad_kda_update, out, state) != RAD_OK) {
|
||||
std::printf("FAIL %s: refused\n", c.name);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
bool written = false;
|
||||
for (size_t i = 0; i < ref_out.size(); ++i) written = written || ref_out[i] != 0x7777;
|
||||
size_t bad = 0;
|
||||
double out_err = 0, state_err = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
if (out[i] == ref_out[i]) continue;
|
||||
const float x = bf16_value(out[i]), y = bf16_value(ref_out[i]);
|
||||
const double e = std::fabs((double)x - y);
|
||||
out_err = std::max(out_err, e);
|
||||
if (!std::isfinite(x) || ref_out[i] == 0x7777 || out[i] == 0x7777 ||
|
||||
e > 1e-6 + 0.008 * std::fabs(y))
|
||||
++bad;
|
||||
}
|
||||
for (size_t i = 0; i < state.size(); ++i) {
|
||||
if (state[i] == ref_state[i]) continue;
|
||||
const double e = std::fabs((double)state[i] - ref_state[i]);
|
||||
state_err = std::max(state_err, e);
|
||||
if (!std::isfinite(state[i]) || e > 2e-5 + 2e-5 * std::fabs(ref_state[i])) ++bad;
|
||||
}
|
||||
std::printf("%-24s output max %.3g, state max %.3g%s\n", c.name, out_err, state_err,
|
||||
!written ? " NO OUTPUT" : bad ? " FAIL" : "");
|
||||
if (!written || bad) ++fails;
|
||||
}
|
||||
std::printf("kda_update against libref: %d of %d within bounds\n", checks - fails, checks);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_kvres.cpp): kv_resolve (libhalo/halo_kv_resolve.hip) on the host SIMT emulator, every operand
|
||||
* held to a port of libref's ref_kv_resolve (libref/ref_kvstream.cpp) byte for byte: the rewritten
|
||||
* selection, both residency maps, the slot epochs and heat counters, the control block, the mirror
|
||||
* (untouched) and every byte of the ring.
|
||||
*
|
||||
* The fixtures are the shapes the claim list has to survive:
|
||||
*
|
||||
* - a partly resident pool, an eviction, a second chance: the ordinary decode call;
|
||||
* - identity placement and its two exits: ids that fit the ring and take their own slot, an id
|
||||
* whose slot is occupied by a different block (a clash, which walks from the hand without
|
||||
* evicting), ids past the ring, and a full ring of clashes (which is CLOCK, unchanged);
|
||||
* - 2052 claims (four rows of 513, what `--max-num-seqs 4` selects) and 8000 claims at a launch
|
||||
* wide enough to derive a list of 8192 ids;
|
||||
* - 12 claims into 8 slots: more claims than the ring holds, so the unplaceable ones revert
|
||||
* through the selection and the overflow latch is set;
|
||||
* - the two-bit heat counter: a slot hit twice surviving two sweep passes where the one-bit
|
||||
* CLOCK would evict it, a saturated counter halving 3 -> 1 on a pass, and a saturated counter
|
||||
* outlasting a slot that was only placed last call;
|
||||
* - one bump a slot a call however many rows name it, which is the one place the device's
|
||||
* `atomicExch` and a per-entry reference would part company;
|
||||
* - 8200 claims at a launch whose bound (32 rows x 513) exceeds the workgroup's LDS room, so the
|
||||
* claims are gathered into the row's scratch and sorted there; the slots must still be
|
||||
* libref's.
|
||||
*
|
||||
* A claim count is bounded by the launch's entries, `sum_q nsel[q] <= M * sel_pitch`, so every
|
||||
* fixture's claim count is a number the kernel derives rather than one it assumes. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" int halo_rad_kv_resolve(const RadArgs* a, RadStream stream);
|
||||
|
||||
namespace {
|
||||
|
||||
enum { kNOB = 0xEE };
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* Block `b`'s bytes: a pattern whose block digit is recoverable, so a copy that landed in the wrong
|
||||
* slot shows up in the ring's bytes. */
|
||||
uint8_t block_byte(int64_t b, int64_t i) { return (uint8_t)((29 * b + i) & 0xff); }
|
||||
|
||||
struct Fix {
|
||||
int64_t M = 1, blocks = 1, slots = 1, pitch = 1, bbytes = 8;
|
||||
std::vector<int32_t> sel, nsel, res, sblk, sst, ctl;
|
||||
std::vector<uint8_t> host, pool;
|
||||
|
||||
/* A fresh pool: the maps say what is resident, a free slot holds the marker. */
|
||||
void shape(int64_t M_, int64_t blocks_, int64_t slots_, int64_t pitch_, int64_t bbytes_) {
|
||||
M = M_; blocks = blocks_; slots = slots_; pitch = pitch_; bbytes = bbytes_;
|
||||
sel.assign((size_t)(M * pitch), -1);
|
||||
nsel.assign((size_t)M, 0);
|
||||
res.assign((size_t)blocks, -1);
|
||||
sblk.assign((size_t)slots, -1);
|
||||
sst.assign((size_t)(slots * 2), 0);
|
||||
ctl.assign(16, 0);
|
||||
host.assign((size_t)(blocks * bbytes), 0);
|
||||
pool.assign((size_t)(slots * bbytes), (uint8_t)kNOB);
|
||||
for (int64_t b = 0; b < blocks; ++b)
|
||||
for (int64_t i = 0; i < bbytes; ++i) host[(size_t)(b * bbytes + i)] = block_byte(b, i);
|
||||
}
|
||||
/* Make slot `s` hold block `b`: the map and the bytes, as a resident block leaves them. */
|
||||
void resident(int64_t s, int64_t b) {
|
||||
sblk[(size_t)s] = (int32_t)b;
|
||||
res[(size_t)b] = (int32_t)s;
|
||||
for (int64_t i = 0; i < bbytes; ++i) pool[(size_t)(s * bbytes + i)] = block_byte(b, i);
|
||||
}
|
||||
};
|
||||
|
||||
/* The heat counter's two writes, copied from libref: a use bumps by one and saturates at 3, a
|
||||
* sweep pass halves, and a negative value reads as cold. */
|
||||
int32_t heat_up(int32_t h) { return h < 0 ? 1 : (h < 3 ? h + 1 : 3); }
|
||||
int32_t heat_down(int32_t h) { return h > 0 ? (h >> 1) : 0; }
|
||||
|
||||
/* libref's ref_kv_resolve over a fixture, step for step (libref/ref_kvstream.cpp): the same epoch,
|
||||
* the same one claim per distinct block, the same sorted miss list, the same free-slot-then-CLOCK
|
||||
* sweep over the same two-bit heat counter, the same revert of what it could not place, the same
|
||||
* copies and rewrite. The fixtures are legal calls, so the refusals are not repeated here. */
|
||||
void ref_resolve(Fix& f) {
|
||||
const int64_t M = f.M, blocks = f.blocks, slots = f.slots, pitch = f.pitch, bbytes = f.bbytes;
|
||||
int32_t* const R = f.res.data();
|
||||
int32_t* const SB = f.sblk.data();
|
||||
int32_t* const ST = f.sst.data();
|
||||
int32_t* const C = f.ctl.data();
|
||||
const int64_t stp = 2;
|
||||
|
||||
std::vector<int64_t> off, ent;
|
||||
for (int64_t q = 0; q < M; ++q)
|
||||
for (int64_t i = 0; i < f.nsel[(size_t)q]; ++i) {
|
||||
off.push_back(q * pitch + i);
|
||||
ent.push_back(f.sel[(size_t)(q * pitch + i)]);
|
||||
}
|
||||
|
||||
const int32_t epoch = (int32_t)((uint32_t)C[0] + 1u);
|
||||
|
||||
std::vector<int32_t> miss;
|
||||
for (size_t e = 0; e < ent.size(); ++e) {
|
||||
const int32_t b = (int32_t)ent[e];
|
||||
const int32_t s = R[b];
|
||||
if (s >= 0) {
|
||||
/* One bump a slot a call, not one an entry (libref's step 2). */
|
||||
if (ST[(size_t)s * stp] != epoch) {
|
||||
ST[(size_t)s * stp] = epoch;
|
||||
ST[(size_t)s * stp + 1] = heat_up(ST[(size_t)s * stp + 1]);
|
||||
}
|
||||
} else if (s == -1) {
|
||||
R[b] = -2;
|
||||
miss.push_back(b);
|
||||
}
|
||||
}
|
||||
const int64_t lookups = (int64_t)ent.size();
|
||||
std::sort(miss.begin(), miss.end());
|
||||
|
||||
int64_t free_left = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (SB[s] < 0 && ST[(size_t)s * stp] != epoch) ++free_left;
|
||||
int64_t hand = C[1];
|
||||
int64_t placed = 0;
|
||||
bool overflow = false;
|
||||
for (size_t k = 0; k < miss.size(); ++k) {
|
||||
const int32_t b = miss[k];
|
||||
int64_t victim = -1;
|
||||
/* Identity first: the block's own slot if the id fits the ring and that slot is free (or
|
||||
* already holds it), hand untouched (libref's step 4). */
|
||||
if ((int64_t)b < slots && ST[(int64_t)b * stp] != epoch && (SB[b] < 0 || SB[b] == b))
|
||||
victim = b;
|
||||
if (victim < 0 && free_left > 0) {
|
||||
int64_t h = hand;
|
||||
for (int64_t scanned = 0; scanned < slots; ++scanned) {
|
||||
const int64_t s = h;
|
||||
h = h + 1 == slots ? 0 : h + 1;
|
||||
if (ST[(size_t)s * stp] == epoch) continue;
|
||||
if (SB[s] >= 0) continue;
|
||||
victim = s;
|
||||
hand = h;
|
||||
break;
|
||||
}
|
||||
if (victim < 0) free_left = 0;
|
||||
}
|
||||
if (victim < 0) {
|
||||
for (int64_t scanned = 0; scanned < 3 * slots; ++scanned) {
|
||||
const int64_t s = hand;
|
||||
hand = hand + 1 == slots ? 0 : hand + 1;
|
||||
if (ST[(size_t)s * stp] == epoch) continue;
|
||||
if (SB[s] >= 0 && ST[(size_t)s * stp + 1] > 0) {
|
||||
ST[(size_t)s * stp + 1] = heat_down(ST[(size_t)s * stp + 1]);
|
||||
continue;
|
||||
}
|
||||
victim = s;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (victim < 0) { overflow = true; break; }
|
||||
if (SB[victim] < 0 && free_left > 0) --free_left;
|
||||
if (SB[victim] >= 0) R[SB[victim]] = -1;
|
||||
SB[victim] = b;
|
||||
ST[(size_t)victim * stp] = epoch;
|
||||
ST[(size_t)victim * stp + 1] = heat_up(ST[(size_t)victim * stp + 1]);
|
||||
R[b] = (int32_t)victim;
|
||||
++placed;
|
||||
}
|
||||
for (size_t k = (size_t)placed; k < miss.size(); ++k) R[miss[k]] = -1;
|
||||
|
||||
for (int64_t k = 0; k < placed; ++k) {
|
||||
const int32_t b = miss[(size_t)k];
|
||||
std::memcpy(f.pool.data() + (int64_t)R[b] * bbytes, f.host.data() + (int64_t)b * bbytes,
|
||||
(size_t)bbytes);
|
||||
}
|
||||
for (size_t e = 0; e < ent.size(); ++e) {
|
||||
const int32_t s = R[ent[e]];
|
||||
f.sel[(size_t)off[e]] = s >= 0 ? s : 0;
|
||||
}
|
||||
|
||||
int64_t used = 0;
|
||||
for (int64_t s = 0; s < slots; ++s)
|
||||
if (ST[(size_t)s * stp] == epoch) ++used;
|
||||
const int64_t uni = used + (int64_t)miss.size() - placed;
|
||||
C[0] = epoch;
|
||||
C[1] = (int32_t)hand;
|
||||
C[2] = (int32_t)placed;
|
||||
if (overflow) C[3] = 1;
|
||||
if (uni > C[10]) C[10] = (int32_t)uni;
|
||||
if (placed > C[11]) C[11] = (int32_t)placed;
|
||||
if ((int64_t)miss.size() > C[12]) C[12] = (int32_t)miss.size();
|
||||
uint64_t* const ctr = (uint64_t*)(C + 4);
|
||||
ctr[0] += (uint64_t)placed;
|
||||
ctr[1] += (uint64_t)lookups;
|
||||
ctr[2] += 1u;
|
||||
}
|
||||
|
||||
/* The device entry point over a fixture. Its scratch is the row's `next_pow2(slots)` miss-list ids
|
||||
* (the list is sorted there when a launch is too wide for the shared claim list) then `slots`
|
||||
* slots. */
|
||||
int dev_resolve(Fix& f) {
|
||||
int64_t nlist = 1;
|
||||
while (nlist < f.slots) nlist <<= 1;
|
||||
std::vector<int32_t> scratch((size_t)(nlist + f.slots), 0);
|
||||
RadTensor t[8] = { tens(f.sel.data(), RAD_I32, { f.M, f.pitch }),
|
||||
tens(f.nsel.data(), RAD_I32, { f.M }),
|
||||
tens(f.res.data(), RAD_I32, { f.blocks }),
|
||||
tens(f.sblk.data(), RAD_I32, { f.slots }),
|
||||
tens(f.sst.data(), RAD_I32, { f.slots, 2 }),
|
||||
tens(f.ctl.data(), RAD_I32, { 16 }),
|
||||
tens(f.host.data(), RAD_U8, { f.blocks, f.bbytes }),
|
||||
tens(f.pool.data(), RAD_U8, { f.slots, f.bbytes }) };
|
||||
RadParam p[5]{};
|
||||
p[0] = { "M", RAD_P_INT, f.M };
|
||||
p[1] = { "blocks", RAD_P_INT, f.blocks };
|
||||
p[2] = { "slots", RAD_P_INT, f.slots };
|
||||
p[3] = { "sel_pitch", RAD_P_INT, f.pitch };
|
||||
p[4] = { "block_bytes", RAD_P_INT, f.bbytes };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 8;
|
||||
a.p = p;
|
||||
a.n_p = 5;
|
||||
a.scratch = scratch.data();
|
||||
a.scratch_bytes = (int64_t)scratch.size() * 4;
|
||||
return halo_rad_kv_resolve(&a, nullptr);
|
||||
}
|
||||
|
||||
size_t mismatch(const std::vector<int32_t>& a, const std::vector<int32_t>& b, const char* what,
|
||||
const char* name) {
|
||||
size_t bad = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
if (a[i] != b[i]) {
|
||||
if (!bad)
|
||||
std::printf(" FAIL %-42s %s[%zu]: %d, libref %d\n", name, what, i, a[i], b[i]);
|
||||
++bad;
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
size_t mismatch_bytes(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b,
|
||||
const char* what, const char* name) {
|
||||
size_t bad = 0;
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
if (a[i] != b[i]) {
|
||||
if (!bad)
|
||||
std::printf(" FAIL %-42s %s[%zu]: %u, libref %u\n", name, what, i, a[i], b[i]);
|
||||
++bad;
|
||||
}
|
||||
return bad;
|
||||
}
|
||||
|
||||
/* One fixture, both ways, every operand compared. */
|
||||
int check(const char* name, Fix f) {
|
||||
std::printf(" .. %s\n", name);
|
||||
std::fflush(stdout);
|
||||
Fix ref = f;
|
||||
ref_resolve(ref);
|
||||
const int rc = dev_resolve(f);
|
||||
if (rc != RAD_OK) {
|
||||
std::printf(" FAIL %-42s refused (%d)\n", name, rc);
|
||||
return 1;
|
||||
}
|
||||
size_t bad = 0;
|
||||
bad += mismatch(f.sel, ref.sel, "sel", name);
|
||||
bad += mismatch(f.res, ref.res, "res", name);
|
||||
bad += mismatch(f.sblk, ref.sblk, "slot_block", name);
|
||||
bad += mismatch(f.sst, ref.sst, "slot_state", name);
|
||||
bad += mismatch(f.ctl, ref.ctl, "ctl", name);
|
||||
bad += mismatch_bytes(f.pool, ref.pool, "kv_cache", name);
|
||||
bad += mismatch_bytes(f.host, ref.host, "host", name);
|
||||
if (bad) return 1;
|
||||
std::printf(" ok %-42s %lld claims, %lld placed\n", name, (long long)ref.ctl[12],
|
||||
(long long)ref.ctl[2]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* `n` distinct block ids across `M` rows of `pitch` entries, contiguously from `first`. Each row
|
||||
* declares exactly the entries this fills, since `nsel` is what says an entry is valid -- and a
|
||||
* declared entry holding -1 is a state fault, not padding. */
|
||||
void fill_claims(Fix& f, int64_t first, int64_t n, int64_t per_row) {
|
||||
int64_t k = 0;
|
||||
for (int64_t q = 0; q < f.M; ++q) {
|
||||
int64_t take = per_row;
|
||||
if (take > n - k) take = n - k;
|
||||
if (take < 0) take = 0;
|
||||
f.nsel[(size_t)q] = (int32_t)take;
|
||||
for (int64_t i = 0; i < take; ++i, ++k) f.sel[(size_t)(q * f.pitch + i)] = (int32_t)(first + k);
|
||||
}
|
||||
}
|
||||
|
||||
int run_all() {
|
||||
int fails = 0, cases = 0;
|
||||
++cases;
|
||||
{
|
||||
Fix f;
|
||||
f.shape(2, 8, 4, 4, 8);
|
||||
f.resident(0, 2);
|
||||
f.resident(3, 5);
|
||||
f.sel = { 2, 5, 6, -1, 2, 4, -1, -1 };
|
||||
f.nsel = { 3, 2 };
|
||||
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
|
||||
fails += check("a decode call: two hits, two misses, ascending", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Every slot resident and referenced: the sweep clears four bits and takes the slot the
|
||||
* hand started on, one full turn later. */
|
||||
Fix f;
|
||||
f.shape(1, 8, 4, 2, 4);
|
||||
for (int64_t s = 0; s < 4; ++s) f.resident(s, s + 4);
|
||||
f.sel = { 0, 1 };
|
||||
f.nsel = { 2 };
|
||||
f.sst = { 0, 1, 0, 1, 0, 1, 0, 1 };
|
||||
fails += check("second chance: a full ring clears and wraps", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* 2052 claims, the four-sequence decode shape. */
|
||||
Fix f;
|
||||
f.shape(4, 4096, 2100, 513, 8);
|
||||
fill_claims(f, 100, 2052, 513);
|
||||
fails += check("2052 claims, every slot free", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A launch wide enough that the list is 8192 ids (32 x 513 = 16416 is past the workgroup's
|
||||
* LDS room), with 8000 claims inside it. */
|
||||
Fix f;
|
||||
f.shape(32, 12000, 8100, 513, 8);
|
||||
fill_claims(f, 200, 8000, 250);
|
||||
fails += check("8000 claims inside a derived 8192-id list", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* More claims than the ring: the eight smallest ids take the eight free slots, the rest
|
||||
* revert through the selection and the overflow latches. */
|
||||
Fix f;
|
||||
f.shape(1, 4096, 8, 12, 8);
|
||||
f.sel = { 4090, 3, 2000, 7, 1, 4000, 5, 9, 11, 2, 100, 500 };
|
||||
f.nsel = { 12 };
|
||||
fails += check("12 claims into 8 slots: the smallest eight", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* 8200 claims against a list of 8192: the launch's bound is past the workgroup's LDS room, so
|
||||
* the kernel gathers the claims from the selection into the row's scratch and sorts them
|
||||
* there. Same slots as libref's sort of all 8200, and no walk of `blocks`. */
|
||||
Fix f;
|
||||
f.shape(32, 12000, 8300, 513, 8);
|
||||
fill_claims(f, 0, 8200, 257);
|
||||
fails += check("8200 claims: sorted in the scratch above the list", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Identity's two ways out in one call. Block 1's own slot holds block 6, so it is a clash
|
||||
* and takes the first free slot after the hand (0) -- never an eviction. Block 2's slot is
|
||||
* free, so it takes slot 2 even though the hand has moved to 1. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 4, 4, 8);
|
||||
f.resident(1, 6);
|
||||
f.sel = { 1, 2, 8, -1 };
|
||||
f.nsel = { 3 };
|
||||
f.sst = { 0, 1, 0, 0, 0, 0, 0, 0 };
|
||||
fails += check("identity clash falls back to a free slot, then identity again", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Ids past the ring, the depth case: nothing can be identity, every miss walks from the
|
||||
* hand. */
|
||||
Fix f;
|
||||
f.shape(1, 16, 4, 5, 8);
|
||||
f.sel = { 9, 10, 11, 12, 13 };
|
||||
f.nsel = { 5 };
|
||||
fails += check("ids past the ring: the old free-slot walk, unchanged", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A full ring of clashing slots: identity has nowhere to go and CLOCK picks the victim the
|
||||
* hand walks to, halving one counter on the way. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 3, 2, 8);
|
||||
f.resident(0, 5);
|
||||
f.resident(1, 6);
|
||||
f.resident(2, 7);
|
||||
f.sel = { 0, 1 };
|
||||
f.nsel = { 2 };
|
||||
f.sst = { 0, 1, 0, 1, 0, 1 };
|
||||
fails += check("identity clash on a full ring: CLOCK, unchanged", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A ring wider than one thread's chunk with its free slots far from the hand: the sweep
|
||||
* walks the chunk summaries (2100 slots is 3 a thread) and must still name the first free
|
||||
* slot from the hand. Slots 0..2048 hold blocks, 2049 and 2050 are free, and the misses
|
||||
* are ids past the ring, so identity cannot place them. */
|
||||
Fix f;
|
||||
f.shape(1, 6000, 2100, 3, 8);
|
||||
for (int64_t s = 0; s < 2049; ++s) f.resident(s, s);
|
||||
f.sel = { 4000, 4001, 4002 };
|
||||
f.nsel = { 3 };
|
||||
fails += check("free slots in the last chunk, hand at 0", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* The same ring with the hand past the free region: the walk wraps through the chunk
|
||||
* summaries to slots 0 and 1, in that order, and leaves the hand at 2. */
|
||||
Fix f;
|
||||
f.shape(1, 6000, 2100, 3, 8);
|
||||
for (int64_t s = 2; s < 2100; ++s) f.resident(s, s);
|
||||
f.sel = { 4000, 4001, 4002 };
|
||||
f.nsel = { 3 };
|
||||
f.ctl[1] = 2099;
|
||||
fails += check("free slots at slot 0, hand at the end: the walk wraps", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Heat, the discriminating case: slot 0 was hit twice (counter 2), slots 1 and 2 once each.
|
||||
* A one-bit CLOCK clears all three and evicts slot 0 on the second pass; the counter halves
|
||||
* 2 -> 1 -> 0, so slot 0 survives two passes and slot 1 is the victim. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 1, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 2, 0, 1, 0, 1 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a slot hit twice survives two passes, CLOCK would take it", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* The halving: a saturated 3 is 1 after one pass, not 0, and the cold slot behind it is the
|
||||
* victim. A one-bit CLOCK clears slot 0 and evicts it. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 1, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 3, 0, 0, 0, 0 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a saturated counter halves 3 -> 1 on one pass", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* A saturated counter outlasts a slot that was only placed last call: {3,1,1,1} walks two
|
||||
* full laps, leaving the 3 at 1 then 0, and takes slot 1 (counter 1 -> 0 -> victim). Earning
|
||||
* the same state from placements is what test/kvstream's multi-call case does. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 4, 1, 8);
|
||||
for (int64_t s = 0; s < 4; ++s) f.resident(s, 10 + s);
|
||||
f.sst = { 0, 3, 0, 1, 0, 1, 0, 1 };
|
||||
f.sel = { 20 };
|
||||
f.nsel = { 1 };
|
||||
fails += check("heat: a saturated counter outlasts a fresh placement", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* One bump a slot a call: block 10 is resident and named by both entries, so its counter
|
||||
* gains one step (1 -> 2), not two, where a per-entry bump would disagree with the device's
|
||||
* first-stamp `atomicExch`. */
|
||||
Fix f;
|
||||
f.shape(1, 32, 3, 2, 8);
|
||||
f.resident(0, 10);
|
||||
f.resident(1, 11);
|
||||
f.resident(2, 12);
|
||||
f.sst = { 0, 1, 0, 0, 0, 0 };
|
||||
f.sel = { 10, 10 };
|
||||
f.nsel = { 2 };
|
||||
fails += check("heat: a block two entries name gains one step, not two", f);
|
||||
}
|
||||
++cases;
|
||||
{
|
||||
/* Every miss takes its own slot with a hit and a hand that is not at 0 in play: the
|
||||
* identity fast path must leave the hand exactly where it was and still stamp its slots,
|
||||
* because the fallback never runs. */
|
||||
Fix f;
|
||||
f.shape(1, 12, 8, 6, 8);
|
||||
f.resident(3, 9); /* a resident block the selection does not name */
|
||||
f.ctl[1] = 5;
|
||||
f.sel = { 0, 2, 4, 6, 7 };
|
||||
f.nsel = { 5 };
|
||||
fails += check("identity for every miss, hand untouched", f);
|
||||
}
|
||||
std::printf("%d of %d fixtures match libref\n", cases - fails, cases);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int main() {
|
||||
const int fails = run_all();
|
||||
return fails;
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_lora.cpp): lora_shrink / lora_expand (halo_lora_bf16.hip) on the host SIMT emulator.
|
||||
*
|
||||
* The case matrix and every check are lora_cases.h's, shared with tests/lora_ops_test.cpp (libref and
|
||||
* libavx): base rows untouched by bytes, adapter rows against a double-precision sum within the
|
||||
* bounds stated there. Here the implementations are the emulated kernels (the scalar rows and the
|
||||
* tiled rows: WMMA shrink, LDS-staged expand), ref_host.cpp's restatement of libref's arithmetic,
|
||||
* and libref itself when $RADIANCE_HOME holds one (ctest sets it). Every emulated expand is held
|
||||
* to libref's restatement bit for bit, because its j-ascending sum and its roundings are libref's.
|
||||
* Shrink is held to the bound rather than to libref's bytes: the scalar row sums k in 32 lane
|
||||
* strides and a butterfly, the WMMA row in 32-wide steps over waves and a K split.
|
||||
*
|
||||
* Then what the tiled rows promise beyond the matrix, each proven here on the emulator:
|
||||
*
|
||||
* shapes the real ones (K 2048 / 5120 / 6144 / 17408, R 16 / 48 / 64 / 192, N 256 ..
|
||||
* 12288, odd M, S 1..4, bf16 and E4M3 with a scale every 128): shrink to the f64
|
||||
* bound (and its worst error printed against f64), expand to libref's bytes.
|
||||
* batch a row computed alone (M = 1) and as row p of M in {7, 16, 17, 37, 300}, the others
|
||||
* random slots and base rows: its t and y bits are the same. Every K split, z fan-out
|
||||
* and pass split the tiled rows can take differs between those launches.
|
||||
* layout the same rows through aligned (16-byte loads) and unaligned (element loads)
|
||||
* buffers: the same bits.
|
||||
* base rows y filled with -0, NaN payloads and random values, t with a sentinel: a base row's
|
||||
* bytes are untouched, and a launch of base rows only touches nothing.
|
||||
* decode every fp8 E4M3 / E5M2 / i8 code through a one-hot pool: t is the code times its
|
||||
* group's scale exactly, so the WMMA row's code -> bf16 widening is the ABI's.
|
||||
*/
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include "lora_cases.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdarg>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <dlfcn.h>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using lora_cases::Impl;
|
||||
using lora_cases::LaunchFn;
|
||||
using lora_cases::mk;
|
||||
using lora_cases::Params;
|
||||
|
||||
static int host_shrink(const RadArgs* a, RadStream) { return host_lora_shrink(a); }
|
||||
static int host_expand(const RadArgs* a, RadStream) { return host_lora_expand(a); }
|
||||
|
||||
/* libref's two rows, through the plugin's own exports, or nulls. */
|
||||
static void load_libref(LaunchFn* shrink, LaunchFn* expand) {
|
||||
*shrink = *expand = nullptr;
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
if (!home || !*home) return;
|
||||
const std::string p = std::string(home) + "/kernels/libref.so";
|
||||
void* h = dlopen(p.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!h) return;
|
||||
auto open = (int (*)(void))dlsym(h, "rad_plugin_open"); /* as the loader does */
|
||||
if (open && open() < 0) return;
|
||||
auto cnt = (int (*)(void))dlsym(h, "rad_kernel_count");
|
||||
auto at = (const RadKernelInfo* (*)(int))dlsym(h, "rad_kernel_at");
|
||||
if (!cnt || !at) return;
|
||||
for (int i = 0; i < cnt(); ++i) {
|
||||
const RadKernelInfo* k = at(i);
|
||||
if (!k || !k->op) continue;
|
||||
if (!std::strcmp(k->op, "lora_shrink")) *shrink = k->launch;
|
||||
if (!std::strcmp(k->op, "lora_expand")) *expand = k->launch;
|
||||
}
|
||||
}
|
||||
|
||||
static int g_fails = 0;
|
||||
static void fail(const char* what, const std::string& detail) {
|
||||
++g_fails;
|
||||
if (g_fails <= 40) std::printf("FAIL %s: %s\n", what, detail.c_str());
|
||||
}
|
||||
static std::string fmt(const char* f, ...) __attribute__((format(printf, 1, 2)));
|
||||
static std::string fmt(const char* f, ...) {
|
||||
char b[512];
|
||||
va_list ap;
|
||||
va_start(ap, f);
|
||||
std::vsnprintf(b, sizeof b, f, ap);
|
||||
va_end(ap);
|
||||
return b;
|
||||
}
|
||||
|
||||
static const uint32_t kSent = 0x7fc0deadu;
|
||||
|
||||
/* ------------------------------------------------------------------ one shrink problem
|
||||
* x rows at row stride `lda` (from element `off` of the buffer), the scale stream [M, groups] at
|
||||
* `lds`, dense pools, t dense. Built once a test and launched through any shrink row. */
|
||||
struct Shrink {
|
||||
int M = 0, K = 0, R = 0, S = 0, group = 128, lda = 0, off = 0, lds = 0;
|
||||
uint32_t adt = RAD_BF16;
|
||||
std::vector<uint8_t> abuf; /* (off + M * lda) elements of adt; 16-byte aligned base */
|
||||
std::vector<float> sbuf;
|
||||
std::vector<int32_t> slot;
|
||||
std::vector<uint16_t> la;
|
||||
};
|
||||
|
||||
static size_t esz(uint32_t dt) { return (size_t)rad_dtype_bits(dt) / 8; }
|
||||
|
||||
/* The x element of row m, column k, as the contract defines it (code times scale, one rounding). */
|
||||
static float x_of(const Shrink& P, int m, int k) {
|
||||
float x = lora_cases::get(P.adt, P.abuf.data(), (size_t)(P.off + (size_t)m * P.lda + k));
|
||||
if (lora_cases::coded(P.adt)) x = x * P.sbuf[(size_t)m * P.lds + k / P.group];
|
||||
return x;
|
||||
}
|
||||
|
||||
/* Run `fn` (with its scratch hook) over P; t comes back [M, R], base rows holding kSent. */
|
||||
static int run_shrink(const Shrink& P, LaunchFn fn, lora_cases::ScratchFn hook,
|
||||
std::vector<float>* t) {
|
||||
const bool sc = lora_cases::coded(P.adt);
|
||||
const int groups = (P.K + P.group - 1) / P.group;
|
||||
RadTensor ts[5]{};
|
||||
ts[0] = mk((void*)(P.abuf.data() + (size_t)P.off * esz(P.adt)), P.adt, {P.M, P.K}, {P.lda, 1});
|
||||
if (sc) ts[1] = mk((void*)P.sbuf.data(), RAD_F32, {P.M, groups}, {P.lds, 1});
|
||||
ts[2] = mk((void*)P.slot.data(), RAD_I32, {P.M}, {1});
|
||||
ts[3] = mk((void*)P.la.data(), RAD_BF16, {P.S, P.R, P.K}, {(int64_t)P.R * P.K, P.K, 1});
|
||||
t->assign((size_t)P.M * P.R, 0.0f);
|
||||
for (auto& v : *t) std::memcpy(&v, &kSent, 4);
|
||||
ts[4] = mk(t->data(), RAD_F32, {P.M, P.R}, {P.R, 1});
|
||||
Params Q;
|
||||
Q.i("M", P.M); Q.i("K", P.K); Q.i("R", P.R); Q.i("S", P.S); Q.i("group", sc ? P.group : 0);
|
||||
Q.s("dtype", rad_dtype_name(P.adt));
|
||||
RadArgs a{};
|
||||
a.t = ts; a.n_t = 5; a.p = Q.p.data(); a.n_p = (int)Q.p.size(); a.world_size = 1;
|
||||
std::vector<uint8_t> scr;
|
||||
lora_cases::with_scratch(a, hook, scr);
|
||||
return fn(&a, nullptr);
|
||||
}
|
||||
|
||||
/* Random x, scales, pools; slots as given. `aligned`: row stride a multiple of 16 elements and no
|
||||
* offset, so the tiled row's 16-byte loads are taken; else K + 7 and 3. */
|
||||
static Shrink make_shrink(std::mt19937& rng, int M, int K, int R, int S, uint32_t adt,
|
||||
const std::vector<int32_t>& slot, bool aligned) {
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> ud(0.01f, 0.05f);
|
||||
Shrink P;
|
||||
P.M = M; P.K = K; P.R = R; P.S = S; P.adt = adt;
|
||||
P.lda = aligned ? (K + 15) / 16 * 16 + 16 : K + 7;
|
||||
P.off = aligned ? 0 : 3;
|
||||
const int groups = (K + P.group - 1) / P.group;
|
||||
P.lds = groups + 3;
|
||||
const float amp = adt == RAD_I8 ? 40.0f : (lora_cases::coded(adt) ? 4.0f : 1.0f);
|
||||
P.abuf.assign(((size_t)P.off + (size_t)M * P.lda) * esz(adt) + 64, 0);
|
||||
for (size_t i = 0; i < (size_t)P.off + (size_t)M * P.lda; ++i)
|
||||
lora_cases::put(adt, P.abuf.data(), i, amp * nd(rng));
|
||||
P.sbuf.resize((size_t)M * P.lds);
|
||||
for (auto& v : P.sbuf) v = ud(rng);
|
||||
P.slot = slot;
|
||||
P.la.resize((size_t)S * R * K);
|
||||
for (auto& v : P.la) v = rad_f32_to_bf16(0.05f * nd(rng));
|
||||
return P;
|
||||
}
|
||||
|
||||
/* Copy row `src` of Q (x and scales) into row `dst` of P, which must have Q's K and dtype. */
|
||||
static void copy_row(Shrink& P, int dst, const Shrink& Q, int src) {
|
||||
const size_t e = esz(P.adt);
|
||||
std::memcpy(P.abuf.data() + ((size_t)P.off + (size_t)dst * P.lda) * e,
|
||||
Q.abuf.data() + ((size_t)Q.off + (size_t)src * Q.lda) * e, (size_t)P.K * e);
|
||||
const int groups = (P.K + P.group - 1) / P.group;
|
||||
std::memcpy(&P.sbuf[(size_t)dst * P.lds], &Q.sbuf[(size_t)src * Q.lds], (size_t)groups * 4);
|
||||
}
|
||||
|
||||
/* t against the f64 sum: base rows keep the sentinel, adapter rows within (K + 2) 2^-24 sum|terms|.
|
||||
* Returns the worst |err| / bound and the worst |err| / sum|terms| (the error the report quotes). */
|
||||
static void check_shrink(const char* who, const Shrink& P, const std::vector<float>& t,
|
||||
double* worst_bound, double* worst_rel) {
|
||||
for (int m = 0; m < P.M; ++m) {
|
||||
const int32_t s = P.slot[(size_t)m];
|
||||
const bool base = s < 0 || s >= P.S;
|
||||
for (int j = 0; j < P.R; ++j) {
|
||||
const float v = t[(size_t)m * P.R + j];
|
||||
if (base) {
|
||||
if (std::memcmp(&v, &kSent, 4))
|
||||
fail(who, fmt("shrink wrote base row %d (M %d K %d R %d)", m, P.M, P.K, P.R));
|
||||
continue;
|
||||
}
|
||||
double sum = 0, mag = 0;
|
||||
const uint16_t* ar = &P.la[((size_t)s * P.R + j) * P.K];
|
||||
for (int k = 0; k < P.K; ++k) {
|
||||
const double term = (double)x_of(P, m, k) * rad_bf16_to_f32(ar[k]);
|
||||
sum += term; mag += std::fabs(term);
|
||||
}
|
||||
const double tol = (P.K + 2) * std::ldexp(1.0, -24) * mag + 1e-30;
|
||||
const double e = std::fabs((double)v - sum);
|
||||
*worst_bound = std::max(*worst_bound, e / tol);
|
||||
if (mag > 0) *worst_rel = std::max(*worst_rel, e / mag);
|
||||
if (!(e <= tol))
|
||||
fail(who, fmt("shrink value M %d K %d R %d %s row %d col %d: %g vs %g (tol %g)",
|
||||
P.M, P.K, P.R, rad_dtype_name(P.adt), m, j, (double)v, sum, tol));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ one expand problem */
|
||||
struct Expand {
|
||||
int M = 0, N = 0, R = 0, S = 0, ldy = 0, yoff = 0;
|
||||
uint32_t ydt = RAD_BF16;
|
||||
std::vector<float> t; /* [M, R] */
|
||||
std::vector<int32_t> slot;
|
||||
std::vector<uint16_t> lb; /* [S, N, R] */
|
||||
std::vector<float> sc; /* [S, N] */
|
||||
std::vector<uint8_t> y0; /* (yoff + M * ldy) elements */
|
||||
};
|
||||
|
||||
static Expand make_expand(std::mt19937& rng, int M, int N, int R, int S, uint32_t ydt,
|
||||
const std::vector<int32_t>& slot, bool aligned) {
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> ud(0.5f, 2.0f);
|
||||
std::uniform_int_distribution<int> pick(0, 5);
|
||||
Expand P;
|
||||
P.M = M; P.N = N; P.R = R; P.S = S; P.ydt = ydt; P.slot = slot;
|
||||
P.ldy = aligned ? N : N + 5;
|
||||
P.yoff = aligned ? 0 : 2;
|
||||
P.t.resize((size_t)M * R);
|
||||
for (auto& v : P.t) v = 0.5f * nd(rng);
|
||||
P.lb.resize((size_t)S * N * R);
|
||||
for (auto& v : P.lb) v = rad_f32_to_bf16(0.05f * nd(rng));
|
||||
P.sc.resize((size_t)S * N);
|
||||
for (auto& v : P.sc) v = ud(rng);
|
||||
const size_t ny = (size_t)P.yoff + (size_t)M * P.ldy, e = esz(ydt);
|
||||
P.y0.resize(ny * e);
|
||||
/* -0, NaNs with payloads (quiet and signalling) and ordinary values: a base row must keep
|
||||
* every one of them, bit for bit. */
|
||||
for (size_t i = 0; i < ny; ++i) {
|
||||
const int k = pick(rng);
|
||||
uint8_t* p = &P.y0[i * e];
|
||||
if (k == 0) {
|
||||
lora_cases::put(ydt, P.y0.data(), i, -0.0f);
|
||||
} else if (k == 1 && ydt == RAD_F32) {
|
||||
const uint32_t u = 0x7fa00001u + (uint32_t)(i & 0xff);
|
||||
std::memcpy(p, &u, 4);
|
||||
} else if (k == 1) {
|
||||
const uint16_t u = ydt == RAD_BF16 ? (uint16_t)(0xffa1u + (i & 7)) : (uint16_t)0x7d01u;
|
||||
std::memcpy(p, &u, 2);
|
||||
} else {
|
||||
lora_cases::put(ydt, P.y0.data(), i, nd(rng));
|
||||
}
|
||||
}
|
||||
return P;
|
||||
}
|
||||
|
||||
static int run_expand(const Expand& P, LaunchFn fn, std::vector<uint8_t>* y) {
|
||||
*y = P.y0;
|
||||
const size_t e = esz(P.ydt);
|
||||
RadTensor ts[5]{};
|
||||
ts[0] = mk((void*)P.t.data(), RAD_F32, {P.M, P.R}, {P.R, 1});
|
||||
ts[1] = mk((void*)P.slot.data(), RAD_I32, {P.M}, {1});
|
||||
ts[2] = mk((void*)P.lb.data(), RAD_BF16, {P.S, P.N, P.R}, {(int64_t)P.N * P.R, P.R, 1});
|
||||
ts[3] = mk((void*)P.sc.data(), RAD_F32, {P.S, P.N}, {P.N, 1});
|
||||
ts[4] = mk(y->data() + (size_t)P.yoff * e, P.ydt, {P.M, P.N}, {P.ldy, 1});
|
||||
Params Q;
|
||||
Q.i("M", P.M); Q.i("N", P.N); Q.i("R", P.R); Q.i("S", P.S);
|
||||
Q.s("dtype", rad_dtype_name(P.ydt));
|
||||
RadArgs a{};
|
||||
a.t = ts; a.n_t = 5; a.p = Q.p.data(); a.n_p = (int)Q.p.size(); a.world_size = 1;
|
||||
return fn(&a, nullptr);
|
||||
}
|
||||
|
||||
/* y against reference bytes `want` (an implementation of libref's order on the same operands),
|
||||
* and base rows plus every element outside the slice against the input. */
|
||||
static void check_expand(const char* who, const Expand& P, const std::vector<uint8_t>& y,
|
||||
const std::vector<uint8_t>& want) {
|
||||
const size_t e = esz(P.ydt), ny = (size_t)P.yoff + (size_t)P.M * P.ldy;
|
||||
int64_t bad_base = 0, bad_val = 0;
|
||||
for (size_t i = 0; i < ny; ++i) {
|
||||
const long long q = (long long)i - P.yoff;
|
||||
const int m = q < 0 ? -1 : (int)(q / P.ldy), n = q < 0 ? -1 : (int)(q % P.ldy);
|
||||
const bool inside = m >= 0 && m < P.M && n < P.N && P.slot[(size_t)m] >= 0 &&
|
||||
P.slot[(size_t)m] < P.S;
|
||||
if (!inside) bad_base += std::memcmp(&y[i * e], &P.y0[i * e], e) != 0;
|
||||
else bad_val += std::memcmp(&y[i * e], &want[i * e], e) != 0;
|
||||
}
|
||||
if (bad_base)
|
||||
fail(who, fmt("expand touched %lld base-row / outside bytes (M %d N %d R %d %s)",
|
||||
(long long)bad_base, P.M, P.N, P.R, rad_dtype_name(P.ydt)));
|
||||
if (bad_val)
|
||||
fail(who, fmt("expand: %lld outputs not libref's bytes (M %d N %d R %d %s)",
|
||||
(long long)bad_val, P.M, P.N, P.R, rad_dtype_name(P.ydt)));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the tests */
|
||||
|
||||
struct Rows {
|
||||
LaunchFn ref_shrink, ref_expand; /* libref or ref_host: the bytes expand is held to */
|
||||
};
|
||||
|
||||
/* Slots for M rows over S adapters, with base rows (-1 and S) mixed in. */
|
||||
static std::vector<int32_t> rand_slots(std::mt19937& rng, int M, int S, int base_pct) {
|
||||
std::uniform_int_distribution<int> u(0, 99), s(0, S - 1), b(0, 2);
|
||||
std::vector<int32_t> v((size_t)M);
|
||||
for (auto& x : v) {
|
||||
if (u(rng) < base_pct) {
|
||||
const int k = b(rng);
|
||||
x = k == 0 ? -1 : (k == 1 ? S : -7);
|
||||
} else {
|
||||
x = s(rng);
|
||||
}
|
||||
}
|
||||
return v;
|
||||
}
|
||||
|
||||
/* Real shapes. Each pair is shrink -> expand, as the engine issues it: expand reads the t the
|
||||
* tiled shrink wrote, and is held to libref's bytes over that same t. */
|
||||
static void test_shapes(const Rows& R) {
|
||||
std::mt19937 rng(23);
|
||||
struct Sh { int M, K, R, N, S; uint32_t adt, ydt; bool al; };
|
||||
const Sh shapes[] = {
|
||||
{ 9, 2048, 48, 2560, 4, RAD_BF16, RAD_BF16, true }, /* qkv, decode-ish */
|
||||
{ 37, 2048, 32, 12288, 3, RAD_BF16, RAD_BF16, true }, /* gate_up */
|
||||
{ 17, 6144, 16, 2048, 4, RAD_BF16, RAD_BF16, false }, /* down, unaligned */
|
||||
{ 5, 17408, 16, 256, 2, RAD_BF16, RAD_F32, true }, /* the deepest K */
|
||||
{ 7, 5120, 48, 1024, 4, RAD_F8E4M3, RAD_BF16, true }, /* fp8, group 128 */
|
||||
{ 33, 5120, 64, 640, 1, RAD_F8E4M3, RAD_F16, false }, /* S = 1 */
|
||||
{ 3, 2048, 192, 384, 4, RAD_BF16, RAD_BF16, true }, /* 3 modules x 64 */
|
||||
{ 300, 2048, 48, 256, 2, RAD_BF16, RAD_BF16, true }, /* prefill-ish */
|
||||
{ 131, 1000, 64, 1000, 3, RAD_I8, RAD_F32, false }, /* partial group, odd */
|
||||
{ 21, 6144, 48, 300, 4, RAD_F8E5M2, RAD_BF16, true },
|
||||
};
|
||||
double wb = 0, wr = 0;
|
||||
for (const Sh& sh : shapes) {
|
||||
const std::vector<int32_t> slot = rand_slots(rng, sh.M, sh.S, 25);
|
||||
const Shrink P = make_shrink(rng, sh.M, sh.K, sh.R, sh.S, sh.adt, slot, sh.al);
|
||||
std::vector<float> t;
|
||||
const int rc = run_shrink(P, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch, &t);
|
||||
if (rc != RAD_OK) { fail("shapes", fmt("shrink_wmma rc %d", rc)); continue; }
|
||||
check_shrink("shapes/shrink_wmma", P, t, &wb, &wr);
|
||||
/* expand over the t just computed; base rows' t is the sentinel, never read */
|
||||
Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al);
|
||||
E.t = t;
|
||||
std::vector<uint8_t> want, got;
|
||||
if (run_expand(E, R.ref_expand, &want) != RAD_OK) { fail("shapes", "reference expand"); continue; }
|
||||
if (run_expand(E, halo_rad_lora_expand_tiled, &got) != RAD_OK) {
|
||||
fail("shapes", "expand_tiled rc");
|
||||
continue;
|
||||
}
|
||||
check_expand("shapes/expand_tiled", E, got, want);
|
||||
}
|
||||
std::printf("lora shapes: %zu shrink -> expand pairs; tiled shrink worst |err|/bound %.4f, "
|
||||
"worst |err| / sum|terms| %.3g (2^-24 = %.3g)\n",
|
||||
sizeof(shapes) / sizeof(shapes[0]), wb, wr, std::ldexp(1.0, -24));
|
||||
}
|
||||
|
||||
/* Batch invariance: a row alone and inside batches of other slots and base rows. */
|
||||
static void test_invariance() {
|
||||
std::mt19937 rng(41);
|
||||
struct Sh { int K, R, N, S; uint32_t adt, ydt; };
|
||||
const Sh shapes[] = {
|
||||
{ 2048, 48, 2560, 4, RAD_BF16, RAD_BF16 }, /* 4 K splits x 3 j tiles */
|
||||
{ 6144, 16, 640, 3, RAD_BF16, RAD_F32 }, /* 12 K splits */
|
||||
{ 1000, 64, 300, 4, RAD_F8E4M3, RAD_BF16 }, /* coded, partial group, 2 splits */
|
||||
{ 300, 20, 130, 2, RAD_BF16, RAD_F16 }, /* no split, ragged R and N */
|
||||
};
|
||||
const int Ms[] = { 7, 16, 17, 37, 300 };
|
||||
int compared = 0;
|
||||
for (const Sh& sh : shapes) {
|
||||
for (int al = 0; al < 2; ++al) {
|
||||
/* The target row: one per slot, alone. */
|
||||
for (int s = 0; s < sh.S; ++s) {
|
||||
const std::vector<int32_t> one = { s };
|
||||
const Shrink P1 = make_shrink(rng, 1, sh.K, sh.R, sh.S, sh.adt, one, al);
|
||||
std::vector<float> t1, t1s;
|
||||
if (run_shrink(P1, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch,
|
||||
&t1) != RAD_OK ||
|
||||
run_shrink(P1, halo_rad_lora_shrink, nullptr, &t1s) != RAD_OK) {
|
||||
fail("invariance", "M=1 launch");
|
||||
continue;
|
||||
}
|
||||
Expand E1 = make_expand(rng, 1, sh.N, sh.R, sh.S, sh.ydt, one, al);
|
||||
std::vector<uint8_t> y1, y1s;
|
||||
run_expand(E1, halo_rad_lora_expand_tiled, &y1);
|
||||
run_expand(E1, halo_rad_lora_expand, &y1s);
|
||||
if (y1 != y1s) fail("invariance", "tiled and scalar expand differ at M=1");
|
||||
for (int M : Ms) {
|
||||
const std::vector<int32_t> slot0 = rand_slots(rng, M, sh.S, 30);
|
||||
for (int p : { 0, M / 2, M - 1 }) {
|
||||
std::vector<int32_t> slot = slot0;
|
||||
slot[(size_t)p] = s;
|
||||
/* the same pools; x and t of row p are the solo row's */
|
||||
Shrink PB = make_shrink(rng, M, sh.K, sh.R, sh.S, sh.adt, slot, al != 0);
|
||||
PB.la = P1.la;
|
||||
copy_row(PB, p, P1, 0);
|
||||
std::vector<float> tb;
|
||||
if (run_shrink(PB, halo_rad_lora_shrink_wmma,
|
||||
halo_rad_lora_shrink_wmma_scratch, &tb) != RAD_OK) {
|
||||
fail("invariance", "batch launch");
|
||||
continue;
|
||||
}
|
||||
if (std::memcmp(&tb[(size_t)p * sh.R], t1.data(), (size_t)sh.R * 4))
|
||||
fail("invariance", fmt("shrink_wmma: row %d of M %d (K %d R %d %s, "
|
||||
"%s) is not its M=1 bits", p, M, sh.K, sh.R,
|
||||
rad_dtype_name(sh.adt),
|
||||
al ? "aligned" : "unaligned"));
|
||||
double wb = 0, wr = 0;
|
||||
check_shrink("invariance/shrink_wmma", PB, tb, &wb, &wr);
|
||||
Expand EB = make_expand(rng, M, sh.N, sh.R, sh.S, sh.ydt, slot, al != 0);
|
||||
EB.lb = E1.lb;
|
||||
EB.sc = E1.sc;
|
||||
std::memcpy(&EB.t[(size_t)p * sh.R], E1.t.data(), (size_t)sh.R * 4);
|
||||
const size_t e = esz(sh.ydt);
|
||||
std::memcpy(&EB.y0[((size_t)EB.yoff + (size_t)p * EB.ldy) * e],
|
||||
&E1.y0[(size_t)E1.yoff * e], (size_t)sh.N * e);
|
||||
std::vector<uint8_t> yb, ys;
|
||||
run_expand(EB, halo_rad_lora_expand_tiled, &yb);
|
||||
run_expand(EB, halo_rad_lora_expand, &ys);
|
||||
if (std::memcmp(&yb[((size_t)EB.yoff + (size_t)p * EB.ldy) * e],
|
||||
&y1[(size_t)E1.yoff * e], (size_t)sh.N * e))
|
||||
fail("invariance", fmt("expand_tiled: row %d of M %d (N %d R %d) is "
|
||||
"not its M=1 bits", p, M, sh.N, sh.R));
|
||||
check_expand("invariance/expand_tiled", EB, yb, ys);
|
||||
compared += 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The layouts against each other: one problem through aligned and unaligned buffers. */
|
||||
for (const Sh& sh : shapes) {
|
||||
const std::vector<int32_t> slot = rand_slots(rng, 37, sh.S, 20);
|
||||
const Shrink A = make_shrink(rng, 37, sh.K, sh.R, sh.S, sh.adt, slot, true);
|
||||
Shrink U = make_shrink(rng, 37, sh.K, sh.R, sh.S, sh.adt, slot, false);
|
||||
U.la = A.la;
|
||||
for (int m = 0; m < 37; ++m) copy_row(U, m, A, m);
|
||||
std::vector<float> ta, tu;
|
||||
run_shrink(A, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch, &ta);
|
||||
run_shrink(U, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch, &tu);
|
||||
if (std::memcmp(ta.data(), tu.data(), ta.size() * 4))
|
||||
fail("layout", fmt("shrink_wmma: aligned and unaligned x differ (K %d R %d)", sh.K, sh.R));
|
||||
++compared;
|
||||
}
|
||||
std::printf("lora batch invariance: %d row comparisons (M=1 vs M in {7,16,17,37,300}, three "
|
||||
"positions, aligned and unaligned)\n", compared);
|
||||
}
|
||||
|
||||
/* Base rows only: a prefill-sized launch of nothing but base rows touches no byte of t or y. */
|
||||
static void test_all_base() {
|
||||
std::mt19937 rng(5);
|
||||
std::vector<int32_t> slot((size_t)2048);
|
||||
for (size_t i = 0; i < slot.size(); ++i) slot[i] = (i % 3 == 0) ? -1 : (i % 3 == 1 ? 4 : -100);
|
||||
const Shrink P = make_shrink(rng, 2048, 256, 48, 4, RAD_BF16, slot, true);
|
||||
std::vector<float> t;
|
||||
double wb = 0, wr = 0;
|
||||
if (run_shrink(P, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch, &t) != RAD_OK)
|
||||
fail("all-base", "shrink rc");
|
||||
check_shrink("all-base/shrink_wmma", P, t, &wb, &wr);
|
||||
const Expand E = make_expand(rng, 2048, 640, 48, 4, RAD_BF16, slot, false);
|
||||
std::vector<uint8_t> y;
|
||||
if (run_expand(E, halo_rad_lora_expand_tiled, &y) != RAD_OK) fail("all-base", "expand rc");
|
||||
if (y != E.y0) fail("all-base", "expand_tiled touched a base-only launch");
|
||||
std::printf("lora base rows only: M 2048, t and y untouched\n");
|
||||
}
|
||||
|
||||
/* Every code through a one-hot pool: A[s, j, k] = (k == j), so t[m, j] = x(m, j) = code * scale
|
||||
* exactly (one exact product, the rest +-0), and the WMMA row's code widening is checked code by
|
||||
* code. Codes whose value is NaN or Inf would turn every j's zero products into NaN, so they
|
||||
* get rows of their own, where every t must be NaN as in the f64 sum. */
|
||||
static void test_codes() {
|
||||
int checked = 0;
|
||||
for (uint32_t adt : { (uint32_t)RAD_F8E4M3, (uint32_t)RAD_F8E5M2, (uint32_t)RAD_I8 }) {
|
||||
const int K = 256, R = 256, S = 1;
|
||||
std::vector<int> special;
|
||||
std::vector<uint8_t> row(K);
|
||||
for (int c = 0; c < 256; ++c) {
|
||||
uint8_t b = (uint8_t)c;
|
||||
const float v = lora_cases::get(adt, &b, 0);
|
||||
if (std::isfinite(v)) row[(size_t)c] = b;
|
||||
else { row[(size_t)c] = 0; special.push_back(c); }
|
||||
}
|
||||
const int M = 1 + (int)special.size();
|
||||
Shrink P;
|
||||
P.M = M; P.K = K; P.R = R; P.S = S; P.adt = adt; P.lda = K; P.off = 0;
|
||||
P.lds = 2;
|
||||
P.abuf.assign((size_t)M * K + 64, 0);
|
||||
std::memcpy(P.abuf.data(), row.data(), (size_t)K);
|
||||
for (size_t i = 0; i < special.size(); ++i)
|
||||
P.abuf[(size_t)(1 + i) * K + (size_t)(i * 37 % K)] = (uint8_t)special[i];
|
||||
P.sbuf.resize((size_t)M * 2);
|
||||
for (int m = 0; m < M; ++m) { P.sbuf[(size_t)m * 2] = 0.0371f; P.sbuf[(size_t)m * 2 + 1] = 1.75f; }
|
||||
P.slot.assign((size_t)M, 0);
|
||||
P.la.assign((size_t)R * K, 0);
|
||||
for (int j = 0; j < R; ++j) P.la[(size_t)j * K + j] = rad_f32_to_bf16(1.0f);
|
||||
std::vector<float> t;
|
||||
if (run_shrink(P, halo_rad_lora_shrink_wmma, halo_rad_lora_shrink_wmma_scratch, &t) != RAD_OK) {
|
||||
fail("codes", "rc");
|
||||
continue;
|
||||
}
|
||||
for (int j = 0; j < R; ++j) {
|
||||
const float want = x_of(P, 0, j);
|
||||
if (!(t[(size_t)j] == want))
|
||||
fail("codes", fmt("%s code 0x%02x: t %.9g, want %.9g", rad_dtype_name(adt),
|
||||
(unsigned)row[(size_t)j], (double)t[(size_t)j], (double)want));
|
||||
++checked;
|
||||
}
|
||||
for (int m = 1; m < M; ++m) {
|
||||
const int pos = (int)((size_t)(m - 1) * 37 % K);
|
||||
for (int j = 0; j < R; ++j) {
|
||||
/* j == pos: the code's own value times 1 plus zeros (an Inf stays Inf); every
|
||||
* other j: the code times 0, which is NaN for both NaN and Inf. */
|
||||
const float v = t[(size_t)m * R + j], want = x_of(P, m, pos);
|
||||
const bool okv = (j == pos && !std::isnan(want)) ? v == want : std::isnan(v);
|
||||
if (!okv)
|
||||
fail("codes", fmt("%s code 0x%02x: t[%d] = %g", rad_dtype_name(adt),
|
||||
(unsigned)special[(size_t)m - 1], j, (double)v));
|
||||
}
|
||||
}
|
||||
}
|
||||
std::printf("lora codes: %d codes widened exactly (E4M3, E5M2, i8), NaN / Inf rows NaN\n",
|
||||
checked);
|
||||
}
|
||||
|
||||
/* lora_expand_mm (the generators' expand): t rounded to bf16 and summed on the WMMA in its own
|
||||
* order, so each output is held to the double sum over bf16(t) within one rounding of y plus the
|
||||
* f32 sum's bound; base rows and everything outside the slice untouched, bit for bit. Mixed slots
|
||||
* in a tile, an odd M and N, R not a multiple of 32, every y dtype, aligned and not. */
|
||||
static void test_expand_mm() {
|
||||
std::mt19937 rng(41);
|
||||
struct Sh { int M, N, R, S; uint32_t ydt; bool al; int base_pct; };
|
||||
const Sh shapes[] = {
|
||||
{ 1, 20, 16, 1, RAD_BF16, true, 0 },
|
||||
{ 64, 64, 32, 1, RAD_BF16, true, 0 },
|
||||
{ 130, 300, 48, 2, RAD_BF16, false, 20 },
|
||||
{ 77, 9216, 192, 1, RAD_BF16, true, 0 }, /* a fused qkv, one adapter */
|
||||
{ 200, 1000, 64, 3, RAD_F32, false, 30 },
|
||||
{ 65, 257, 24, 2, RAD_F16, true, 10 },
|
||||
{ 512, 2048, 128, 1, RAD_BF16, true, 0 },
|
||||
};
|
||||
int64_t worst_n = 0;
|
||||
double worst = 0;
|
||||
for (const Sh& sh : shapes) {
|
||||
const std::vector<int32_t> slot = rand_slots(rng, sh.M, sh.S, sh.base_pct);
|
||||
Expand E = make_expand(rng, sh.M, sh.N, sh.R, sh.S, sh.ydt, slot, sh.al);
|
||||
std::vector<uint8_t> got;
|
||||
if (run_expand(E, halo_rad_lora_expand_mm, &got) != RAD_OK) {
|
||||
fail("expand_mm", fmt("rc (M %d N %d R %d)", sh.M, sh.N, sh.R));
|
||||
continue;
|
||||
}
|
||||
const size_t e = esz(sh.ydt), ny = (size_t)E.yoff + (size_t)sh.M * E.ldy;
|
||||
int64_t bad_base = 0, bad_val = 0;
|
||||
for (size_t i = 0; i < ny; ++i) {
|
||||
const long long q = (long long)i - E.yoff;
|
||||
const int m = q < 0 ? -1 : (int)(q / E.ldy), n = q < 0 ? -1 : (int)(q % E.ldy);
|
||||
const int sl = m >= 0 && m < sh.M ? slot[(size_t)m] : -1;
|
||||
if (m < 0 || m >= sh.M || n >= sh.N || sl < 0 || sl >= sh.S) {
|
||||
bad_base += std::memcmp(&got[i * e], &E.y0[i * e], e) != 0;
|
||||
continue;
|
||||
}
|
||||
double acc = 0, terms = 0;
|
||||
for (int j = 0; j < sh.R; ++j) {
|
||||
const double tv = rad_bf16_to_f32(rad_f32_to_bf16(E.t[(size_t)m * sh.R + j]));
|
||||
const double bv = rad_bf16_to_f32(E.lb[((size_t)sl * sh.N + n) * sh.R + j]);
|
||||
acc += tv * bv;
|
||||
terms += std::fabs(tv * bv);
|
||||
}
|
||||
const double sc = E.sc[(size_t)sl * sh.N + n];
|
||||
const double y0 = lora_cases::get(sh.ydt, E.y0.data(), i);
|
||||
const double want = y0 + sc * acc;
|
||||
const double g = lora_cases::get(sh.ydt, got.data(), i);
|
||||
if (std::isnan(y0)) { bad_val += !std::isnan(g); continue; }
|
||||
const double ulp = sh.ydt == RAD_BF16 ? std::ldexp(1.0, -8)
|
||||
: sh.ydt == RAD_F16 ? std::ldexp(1.0, -10) : std::ldexp(1.0, -23);
|
||||
const double tol = std::fabs(want) * ulp + sc * terms * (sh.R + 2) * std::ldexp(1.0, -24) +
|
||||
1e-30;
|
||||
const double r = std::fabs(g - want) / tol;
|
||||
worst = std::max(worst, r);
|
||||
if (r > 1.0) ++bad_val;
|
||||
++worst_n;
|
||||
}
|
||||
if (bad_base)
|
||||
fail("expand_mm", fmt("touched %lld base-row / outside bytes (M %d N %d R %d %s)",
|
||||
(long long)bad_base, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
if (bad_val)
|
||||
fail("expand_mm", fmt("%lld outputs outside the bound (M %d N %d R %d %s)",
|
||||
(long long)bad_val, sh.M, sh.N, sh.R, rad_dtype_name(sh.ydt)));
|
||||
}
|
||||
std::printf("lora expand_mm: %zu shapes, %lld outputs, worst |err|/bound %.3f\n",
|
||||
sizeof(shapes) / sizeof(shapes[0]), (long long)worst_n, worst);
|
||||
}
|
||||
|
||||
int main() {
|
||||
LaunchFn rs = nullptr, re = nullptr;
|
||||
load_libref(&rs, &re);
|
||||
std::printf("lora: libref %s\n", rs && re
|
||||
? "loaded: the emulated kernels are held to it as well"
|
||||
: "not found ($RADIANCE_HOME): held to ref_host.cpp and the double sums only");
|
||||
std::vector<Impl> impls = { { "host", host_shrink, host_expand, true, nullptr } };
|
||||
if (rs && re) impls.push_back({ "libref", rs, re, true, nullptr });
|
||||
impls.push_back({ "r4d-emu", halo_rad_lora_shrink, halo_rad_lora_expand, true, nullptr });
|
||||
impls.push_back({ "r4d-tile", halo_rad_lora_shrink_wmma, halo_rad_lora_expand_tiled, true,
|
||||
halo_rad_lora_shrink_wmma_scratch });
|
||||
lora_cases::Tally T;
|
||||
lora_cases::run_matrix(T, impls, 11);
|
||||
std::printf("lora: %d implementation-cases, %d failure(s); worst |err|/tol shrink %.3f, "
|
||||
"expand %.3f\n", T.cases, T.fails, T.worst_shrink, T.worst_expand);
|
||||
|
||||
Rows R{ rs ? rs : host_shrink, re ? re : host_expand };
|
||||
test_shapes(R);
|
||||
test_invariance();
|
||||
test_all_base();
|
||||
test_codes();
|
||||
test_expand_mm();
|
||||
std::printf("lora tiled rows: %d failure(s)\n", g_fails);
|
||||
return (T.fails != 0 || g_fails != 0) ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_mhc.cpp): GLM's mHC read split by residual chunks (halo_mhc.hip) on the host SIMT emulator.
|
||||
* Each rank's mhc_pre_partial over its chunks, the partials joined row by row as the
|
||||
* row-interleaved all_gather lays them out, then mhc_pre_finish, must give mhc_pre's x, post and
|
||||
* comb bit for bit; the partial matrix's padding slots are zero. On 16-byte rows the vector forms
|
||||
* run, and they are held bit for bit to the same operands on pitched rows, where the scalar forms
|
||||
* run. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
static RadTensor mat(void* p, uint32_t dt, int64_t rows, int64_t cols, int64_t ld) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = 2;
|
||||
t.shape[0] = rows;
|
||||
t.shape[1] = cols;
|
||||
t.stride[0] = ld;
|
||||
t.stride[1] = 1;
|
||||
return t;
|
||||
}
|
||||
static RadTensor vec(void* p, int64_t n) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = RAD_F32;
|
||||
t.rank = 1;
|
||||
t.shape[0] = n;
|
||||
t.stride[0] = 1;
|
||||
return t;
|
||||
}
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
const int64_t n = 4096, hc = 4, W = hc * n, mix = hc * (hc + 2), S = 28, total = 8;
|
||||
std::vector<float> fn((size_t)(mix * W)), scale = { 0.7f, 0.9f, 1.1f }, base((size_t)mix);
|
||||
for (auto& v : fn) v = nd(rng) * 0.01f;
|
||||
for (auto& v : base) v = nd(rng) * 0.5f;
|
||||
int fails = 0, cases = 0;
|
||||
for (int64_t rows : { 1, 5, 37 }) {
|
||||
const int64_t hp = W + 6, xp = n + 2;
|
||||
std::vector<uint16_t> h((size_t)(rows * hp));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
RadParam coef[8]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-5;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
std::vector<uint16_t> x((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post((size_t)(rows * hc)), comb((size_t)(rows * hc * hc));
|
||||
RadTensor t[7] = { mat(h.data(), RAD_BF16, rows, W, hp),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(x.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
if (halo_rad_mhc_pre(&a, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL mhc_pre M=%lld\n", (long long)rows);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
for (int world : { 2, 4, 8 }) {
|
||||
++cases;
|
||||
const int64_t mine = total / world;
|
||||
std::vector<float> gathered((size_t)(rows * total * S));
|
||||
bool padded = true, launched = true;
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
std::vector<float> part((size_t)(rows * mine * S), 7.0f);
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(part.data(), RAD_F32, rows, mine * S, mine * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, rank * mine };
|
||||
pp[5] = { "chunks", RAD_P_INT, mine };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
launched = launched && halo_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
for (int64_t c = 0; c < mine; ++c)
|
||||
for (int64_t j = mix + 1; j < S; ++j)
|
||||
padded = padded && part[(size_t)(r * mine * S + c * S + j)] == 0.0f;
|
||||
std::memcpy(&gathered[(size_t)(r * total * S + rank * mine * S)],
|
||||
&part[(size_t)(r * mine * S)], (size_t)(mine * S * 4));
|
||||
}
|
||||
}
|
||||
std::vector<uint16_t> x2((size_t)(rows * xp), 0x7777);
|
||||
std::vector<float> post2(post.size()), comb2(comb.size());
|
||||
RadTensor ft[7] = { mat(gathered.data(), RAD_F32, rows, total * S, total * S),
|
||||
t[0],
|
||||
t[2],
|
||||
t[3],
|
||||
mat(x2.data(), RAD_BF16, rows, n, xp),
|
||||
mat(post2.data(), RAD_F32, rows, hc, hc),
|
||||
mat(comb2.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadParam fp[8];
|
||||
std::memcpy(fp, coef, sizeof coef);
|
||||
fp[6] = { "chunk", RAD_P_INT, 2048 };
|
||||
fp[7].key = "dtype";
|
||||
fp[7].kind = RAD_P_STR;
|
||||
fp[7].sval = "bf16";
|
||||
RadArgs fa{};
|
||||
fa.t = ft;
|
||||
fa.n_t = 7;
|
||||
fa.p = fp;
|
||||
fa.n_p = 8;
|
||||
launched = launched && halo_rad_mhc_pre_finish(&fa, nullptr) == RAD_OK;
|
||||
const bool same = launched && x2 == x &&
|
||||
std::memcmp(post2.data(), post.data(), post.size() * 4) == 0 &&
|
||||
std::memcmp(comb2.data(), comb.data(), comb.size() * 4) == 0;
|
||||
if (!same || !padded) {
|
||||
std::printf("FAIL M=%lld world %d: %s\n", (long long)rows, world,
|
||||
!launched ? "launch"
|
||||
: !padded ? "padding"
|
||||
: "differs");
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* The vector forms (four-slot partials, the finish's 16-byte collapse, the eight-column
|
||||
* mhc_post) on 16-byte rows against the scalar forms (one slot a thread, four rows and four
|
||||
* coefficients a block from 32 rows, the per-output mhc_post) on the same operands with the
|
||||
* residual pitched by two elements: mhc_pre's x, post and comb, mhc_pre_partial's matrix and
|
||||
* mhc_post's output, bit for bit. */
|
||||
for (int64_t rows : { 1, 5, 16, 37, 64 }) {
|
||||
std::vector<uint16_t> h((size_t)(rows * W)), y((size_t)(rows * n));
|
||||
for (auto& v : h) v = f2b(nd(rng));
|
||||
for (auto& v : y) v = f2b(nd(rng));
|
||||
const int64_t pitched = W + 2;
|
||||
std::vector<uint16_t> hp((size_t)(rows * pitched), 0x7777);
|
||||
for (int64_t r = 0; r < rows; ++r)
|
||||
std::memcpy(&hp[(size_t)(r * pitched)], &h[(size_t)(r * W)], (size_t)W * 2);
|
||||
RadParam coef[7]{};
|
||||
coef[0] = { "M", RAD_P_INT, rows };
|
||||
coef[1] = { "n", RAD_P_INT, n };
|
||||
coef[2] = { "hc", RAD_P_INT, hc };
|
||||
coef[3] = { "iterations", RAD_P_INT, 20 };
|
||||
coef[4].key = "eps";
|
||||
coef[4].kind = RAD_P_F64;
|
||||
coef[4].dval = 1e-6;
|
||||
coef[5].key = "hc_eps";
|
||||
coef[5].kind = RAD_P_F64;
|
||||
coef[5].dval = 1e-6;
|
||||
coef[6].key = "dtype";
|
||||
coef[6].kind = RAD_P_STR;
|
||||
coef[6].sval = "bf16";
|
||||
struct Out {
|
||||
std::vector<uint16_t> x, o;
|
||||
std::vector<float> p, c, part;
|
||||
};
|
||||
auto run = [&](Out* r, const uint16_t* hd, int64_t ld) {
|
||||
r->x.assign((size_t)(rows * n), 0x7777);
|
||||
r->o.assign((size_t)(rows * W), 0x7777);
|
||||
r->p.assign((size_t)(rows * hc), 0);
|
||||
r->c.assign((size_t)(rows * hc * hc), 0);
|
||||
r->part.assign((size_t)(rows * total * S), 7.0f);
|
||||
RadTensor t[7] = { mat((void*)hd, RAD_BF16, rows, W, ld),
|
||||
mat(fn.data(), RAD_F32, mix, W, W),
|
||||
vec(scale.data(), 3),
|
||||
vec(base.data(), mix),
|
||||
mat(r->x.data(), RAD_BF16, rows, n, n),
|
||||
mat(r->p.data(), RAD_F32, rows, hc, hc),
|
||||
mat(r->c.data(), RAD_F32, rows, hc * hc, hc * hc) };
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = coef;
|
||||
a.n_p = 7;
|
||||
bool okay = halo_rad_mhc_pre(&a, nullptr) == RAD_OK;
|
||||
RadTensor pt[3] = { t[0], t[1],
|
||||
mat(r->part.data(), RAD_F32, rows, total * S, total * S) };
|
||||
RadParam pp[7]{};
|
||||
pp[0] = { "M", RAD_P_INT, rows };
|
||||
pp[1] = { "n", RAD_P_INT, n };
|
||||
pp[2] = { "hc", RAD_P_INT, hc };
|
||||
pp[3] = { "chunk", RAD_P_INT, 2048 };
|
||||
pp[4] = { "first", RAD_P_INT, 0 };
|
||||
pp[5] = { "chunks", RAD_P_INT, total };
|
||||
pp[6].key = "dtype";
|
||||
pp[6].kind = RAD_P_STR;
|
||||
pp[6].sval = "bf16";
|
||||
RadArgs pa{};
|
||||
pa.t = pt;
|
||||
pa.n_t = 3;
|
||||
pa.p = pp;
|
||||
pa.n_p = 7;
|
||||
okay = okay && halo_rad_mhc_pre_partial(&pa, nullptr) == RAD_OK;
|
||||
RadTensor ot[5] = { mat(y.data(), RAD_BF16, rows, n, n), t[0], t[5], t[6],
|
||||
mat(r->o.data(), RAD_BF16, rows, W, W) };
|
||||
RadArgs oa{};
|
||||
oa.t = ot;
|
||||
oa.n_t = 5;
|
||||
oa.p = coef;
|
||||
oa.n_p = 7;
|
||||
return okay && halo_rad_mhc_post(&oa, nullptr) == RAD_OK;
|
||||
};
|
||||
Out ref, got;
|
||||
++cases;
|
||||
const bool launched = run(&ref, hp.data(), pitched) && run(&got, h.data(), W);
|
||||
const char* bad = !launched ? "launch"
|
||||
: got.x != ref.x ? "x"
|
||||
: std::memcmp(got.p.data(), ref.p.data(), ref.p.size() * 4) ? "post"
|
||||
: std::memcmp(got.c.data(), ref.c.data(), ref.c.size() * 4) ? "comb"
|
||||
: std::memcmp(got.part.data(), ref.part.data(), ref.part.size() * 4)
|
||||
? "partials"
|
||||
: got.o != ref.o ? "mhc_post"
|
||||
: nullptr;
|
||||
if (bad) {
|
||||
std::printf("FAIL M=%lld 16-byte rows against pitched rows: %s differs\n",
|
||||
(long long)rows, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,789 @@
|
||||
/* Drives libhalo's MLA matrix row (halo_mla.hip, attend_matrix) through the SIMT emulator and checks
|
||||
* every output element against an f64 softmax over each row's own table. The cases put the paired
|
||||
* tile (eight heads of two neighbouring rows) on the tables it meets in serving: a prefill chunk
|
||||
* whose rows share one table, and rows past the DSA budget, where each row selects its own top
|
||||
* blocks and neighbours share most blocks but rarely a table position. The conflict counters
|
||||
* (RADIANCE_MLA_CONFLICT_STATS) show which of the two the pairing saw. Both pairings run on the
|
||||
* same operands: the union at the case's table width, the positional pairing on the table
|
||||
* widened past the union's lists (kUnionBlocks, 520 entries) with absent entries no row reaches.
|
||||
* The rows row (attend_rows, 64 heads of one row a workgroup) runs on its own cases, and a mixed
|
||||
* TP step runs both ways, split by heads over the matrix row and by rows over the rows row. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" void halo_mla_matrix_pin_form(int form);
|
||||
extern "C" void halo_mla_matrix_stats(unsigned long long* out);
|
||||
extern "C" void halo_mla_rows_pin_form(int form);
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int D = 512, BS = 4, kUnionBlocks = 520;
|
||||
|
||||
enum class Fill { prefill, topk, ragged, repeat };
|
||||
|
||||
struct Case {
|
||||
std::string name;
|
||||
int rows, heads, blocks;
|
||||
Fill fill;
|
||||
int swaps = 0; /* topk: blocks exchanged between neighbouring rows */
|
||||
int context = 0; /* topk: tokens of the sequence the rows end */
|
||||
bool scratch = false; /* lets the launcher split the history */
|
||||
int form = 0; /* halo_mla_matrix_pin_form */
|
||||
int expect_second = -1; /* positional pairing: 0 no second pass, 1 some, -1 either */
|
||||
/* Unsplit only: with scratch the widened table gives the positional run more splits. */
|
||||
bool bitwise_a = true; /* the union's request r equals the positional pairing's bit for bit */
|
||||
bool bitwise_all = false; /* both requests do (the tables agree position by position) */
|
||||
bool union_falls_back = false; /* the table is wider than the union's lists */
|
||||
};
|
||||
|
||||
/* Tables as qsa_select emits them past its budget: for the queries at positions context-rows ..
|
||||
* context-1 of one sequence, each row the top blocks-1 of its complete blocks, the strictly higher
|
||||
* ones in block order and a short tie run after them, then the partial page. Row r's choice is row
|
||||
* r-1's with `swaps` members exchanged for non-members. Pages are a fixed shuffle of the blocks. */
|
||||
void topk_tables(int rows, int blocks, int context, int swaps, std::mt19937& rng,
|
||||
std::vector<int>& bt, std::vector<int>& len, int& pages) {
|
||||
const int topk = blocks - 1, universe = context / BS + 1, ties = std::min(4, topk);
|
||||
pages = universe;
|
||||
std::vector<int> page(universe);
|
||||
for (int i = 0; i < universe; ++i) page[i] = i;
|
||||
std::shuffle(page.begin(), page.end(), rng);
|
||||
std::vector<char> in(universe, 0);
|
||||
std::vector<int> members;
|
||||
auto tie_rank = [](int b) { return (uint32_t)b * 2654435761u ^ 0x9e3779b9u; };
|
||||
bt.assign((size_t)rows * blocks, -1);
|
||||
len.assign(rows, 0);
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const int p = context - rows + r, n = (p + 1) / BS;
|
||||
if (n <= topk) {
|
||||
for (int b = 0; b < n; ++b)
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
} else {
|
||||
while ((int)members.size() < topk) {
|
||||
const int b = (int)(rng() % (unsigned)n);
|
||||
if (!in[b]) {
|
||||
in[b] = 1;
|
||||
members.push_back(b);
|
||||
}
|
||||
}
|
||||
for (int s = 0; s < swaps; ++s) {
|
||||
int add;
|
||||
do add = (int)(rng() % (unsigned)n);
|
||||
while (in[add]);
|
||||
const size_t drop = rng() % members.size();
|
||||
in[members[drop]] = 0;
|
||||
members[drop] = add;
|
||||
in[add] = 1;
|
||||
}
|
||||
}
|
||||
std::vector<int> order(members);
|
||||
std::sort(order.begin(), order.end());
|
||||
if (n > topk) {
|
||||
std::vector<int> tied(order);
|
||||
std::sort(tied.begin(), tied.end(),
|
||||
[&](int a, int b) { return tie_rank(a) < tie_rank(b); });
|
||||
tied.resize(ties);
|
||||
std::sort(tied.begin(), tied.end());
|
||||
order.erase(std::remove_if(
|
||||
order.begin(), order.end(),
|
||||
[&](int b) { return std::binary_search(tied.begin(), tied.end(), b); }),
|
||||
order.end());
|
||||
order.insert(order.end(), tied.begin(), tied.end());
|
||||
}
|
||||
int out = 0;
|
||||
for (int b : order) bt[(size_t)r * blocks + out++] = page[b];
|
||||
if ((p + 1) % BS) bt[(size_t)r * blocks + out++] = page[n];
|
||||
len[r] = out ? (out - 1) * BS + p % BS + 1 : 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* The case's page tables and visible lengths; returns the pages the cache holds. */
|
||||
int fill_tables(const Case& c, std::mt19937& rng, std::vector<int>& bt, std::vector<int>& len) {
|
||||
const int M = c.rows, B = c.blocks;
|
||||
int pages = 0;
|
||||
if (c.fill == Fill::topk) {
|
||||
topk_tables(M, B, c.context, c.swaps, rng, bt, len, pages);
|
||||
} else if (c.fill == Fill::prefill) {
|
||||
/* one sequence, its rows the last M positions of the capacity, one table */
|
||||
pages = B + 1;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = (b * 7 + 3) % pages;
|
||||
len[r] = B * BS - M + r + 1;
|
||||
}
|
||||
} else if (c.fill == Fill::repeat) {
|
||||
/* every page twice in a row's table and shifted by one entry from row to row, so a page
|
||||
* repeats within a table and between the pair */
|
||||
pages = M + B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b) bt[(size_t)r * B + b] = ((b + r) / 2 * 5) % pages;
|
||||
len[r] = B * BS - r % 3;
|
||||
}
|
||||
} else {
|
||||
/* every row its own scattered table, with holes and out-of-range pages */
|
||||
pages = M * B;
|
||||
bt.assign((size_t)M * B, -1);
|
||||
len.assign(M, 0);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
for (int b = 0; b < B; ++b)
|
||||
bt[(size_t)r * B + b] = b % 17 == 3 ? -1
|
||||
: b % 19 == 5 ? pages + 3
|
||||
: (b * 7 + r * 11) % pages;
|
||||
len[r] = r % 5 == 4 ? 0 : B * BS - 1 - r % 7;
|
||||
}
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/* An f64 softmax over each row's own table. */
|
||||
std::vector<double> reference(int M, int H, int B, int pages, const std::vector<int>& bt,
|
||||
const std::vector<int>& len, const std::vector<uint16_t>& qb,
|
||||
const std::vector<uint16_t>& kvb, double scale) {
|
||||
std::vector<double> want((size_t)M * H * D);
|
||||
std::vector<double> sc;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int h = 0; h < H; ++h) {
|
||||
const int live = std::min(std::max(len[r], 0), B * BS);
|
||||
sc.assign(live, -INFINITY);
|
||||
double mx = -INFINITY;
|
||||
auto row_of = [&](int j) -> const uint16_t* {
|
||||
const int pg = bt[(size_t)r * B + j / BS];
|
||||
return pg >= 0 && pg < pages ? &kvb[((size_t)pg * BS + j % BS) * D] : nullptr;
|
||||
};
|
||||
const uint16_t* qr = &qb[((size_t)r * H + h) * D];
|
||||
for (int j = 0; j < live; ++j) {
|
||||
const uint16_t* k = row_of(j);
|
||||
if (!k) continue;
|
||||
double dot = 0;
|
||||
for (int d = 0; d < D; ++d)
|
||||
dot += (double)rad_bf16_to_f32(qr[d]) * rad_bf16_to_f32(k[d]);
|
||||
sc[j] = dot * scale;
|
||||
mx = std::max(mx, sc[j]);
|
||||
}
|
||||
std::vector<double> acc(D, 0.0);
|
||||
double sum = 0;
|
||||
for (int j = 0; j < live; ++j) {
|
||||
if (sc[j] == -INFINITY) continue;
|
||||
const double w = std::exp(sc[j] - mx);
|
||||
sum += w;
|
||||
const uint16_t* k = row_of(j);
|
||||
for (int d = 0; d < D; ++d) acc[d] += w * rad_bf16_to_f32(k[d]);
|
||||
}
|
||||
for (int d = 0; d < D; ++d)
|
||||
want[((size_t)r * H + h) * D + d] = sum > 0 ? acc[d] / sum : 0.0;
|
||||
}
|
||||
return want;
|
||||
}
|
||||
|
||||
int run(const Case& c, std::mt19937& rng) {
|
||||
const int M = c.rows, H = c.heads, B = c.blocks;
|
||||
std::vector<int> bt, len;
|
||||
const int pages = fill_tables(c, rng, bt, len);
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
|
||||
RadTensor t[5] = { tens(qb.data(), RAD_BF16, { M, H, D }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
|
||||
tens(out.data(), RAD_BF16, { M, H, D }) };
|
||||
std::vector<RadParam> p;
|
||||
auto pi = [&](const char* k, long long v) {
|
||||
RadParam x{};
|
||||
x.key = k;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
p.push_back(x);
|
||||
};
|
||||
auto pf = [&](const char* k, double v) {
|
||||
RadParam x{};
|
||||
x.key = k;
|
||||
x.kind = RAD_P_F64;
|
||||
x.dval = v;
|
||||
p.push_back(x);
|
||||
};
|
||||
pi("M", M);
|
||||
pi("latent_dim", D);
|
||||
pi("heads", H);
|
||||
pi("blocks", B);
|
||||
pi("block_size", BS);
|
||||
const double scale = 0.0625;
|
||||
pf("scale", scale);
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p.data();
|
||||
a.n_p = (int)p.size();
|
||||
std::vector<char> scratch;
|
||||
if (c.scratch) {
|
||||
const int64_t need = halo_rad_mla_attn_matrix_scratch(&a);
|
||||
scratch.assign((size_t)need + 16, 0);
|
||||
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
}
|
||||
|
||||
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
|
||||
|
||||
/* Both pairings on the same operands: the positional one, on the table widened past the
|
||||
* union's lists, and at the case's own width the launcher's choice, the union, which must
|
||||
* never take a second pass. A tile of 16 heads has no pairing and runs once. */
|
||||
const bool paired = H % 16 == 8;
|
||||
const int wide = std::max(B, kUnionBlocks + 1);
|
||||
std::vector<int> bt_wide((size_t)M * wide, -1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
std::copy(bt.begin() + (size_t)r * B, bt.begin() + (size_t)(r + 1) * B,
|
||||
bt_wide.begin() + (size_t)r * wide);
|
||||
std::vector<uint16_t> by_pos;
|
||||
int fails = 0;
|
||||
for (const char* pairing : { "pos", "union" }) {
|
||||
const bool by_page = !std::strcmp(pairing, "union");
|
||||
if (!paired && by_page) break;
|
||||
const bool widened = paired && !by_page;
|
||||
t[2] = widened ? tens(bt_wide.data(), RAD_I32, { M, wide })
|
||||
: tens(bt.data(), RAD_I32, { M, B });
|
||||
p[3].ival = widened ? wide : B;
|
||||
std::fill(out.begin(), out.end(), 0xffff);
|
||||
unsigned long long stats[3];
|
||||
halo_mla_matrix_stats(stats);
|
||||
halo_mla_matrix_pin_form(c.form);
|
||||
const int rc = halo_rad_mla_attn_matrix(&a, nullptr);
|
||||
halo_mla_matrix_pin_form(0);
|
||||
halo_mla_matrix_stats(stats);
|
||||
if (rc != RAD_OK) {
|
||||
std::printf("%-40s %-5s launch returned %d\n", c.name.c_str(), pairing, rc);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
double max_err = 0;
|
||||
long bad = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
const float got = rad_bf16_to_f32(out[i]);
|
||||
const double e = std::fabs(got - want[i]);
|
||||
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
|
||||
if (std::isfinite(got)) max_err = std::max(max_err, e);
|
||||
}
|
||||
bool ok = bad == 0;
|
||||
std::string note;
|
||||
if (!by_page) {
|
||||
by_pos = out;
|
||||
if (c.expect_second >= 0 && (stats[1] > 0) != (c.expect_second == 1)) {
|
||||
note +=
|
||||
c.expect_second ? " (expected a second pass)" : " (expected no second pass)";
|
||||
ok = false;
|
||||
}
|
||||
} else {
|
||||
if ((stats[1] > 0) != c.union_falls_back) {
|
||||
note += c.union_falls_back ? " (expected the positional fallback)"
|
||||
: " (the union took a second pass)";
|
||||
ok = false;
|
||||
}
|
||||
/* Request r of each pair walks its own table in its own order, as the positional
|
||||
* pairing does, so at one split it must agree to the bit; r+1 sums in another order. */
|
||||
size_t first_diff_a = 0, diff_b = 0;
|
||||
double max_ab = 0;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
|
||||
if (out[i] == by_pos[i]) continue;
|
||||
if (r % 2 == 0)
|
||||
++first_diff_a;
|
||||
else
|
||||
++diff_b;
|
||||
max_ab = std::max(max_ab, (double)std::fabs(rad_bf16_to_f32(out[i]) -
|
||||
rad_bf16_to_f32(by_pos[i])));
|
||||
}
|
||||
char buf[160];
|
||||
std::snprintf(buf, sizeof buf, " vs pos: %zu/%zu differ (r/r+1), max abs %.2e",
|
||||
first_diff_a, diff_b, max_ab);
|
||||
note += buf;
|
||||
if (c.bitwise_a && !c.scratch && first_diff_a) {
|
||||
note += " (request r differs)";
|
||||
ok = false;
|
||||
}
|
||||
if (c.bitwise_all && !c.scratch && diff_b) {
|
||||
note += " (request r+1 differs)";
|
||||
ok = false;
|
||||
}
|
||||
}
|
||||
std::printf("%-40s %-5s M %3d H %2d blocks %3d passes %5llu raster %5llu second %5llu "
|
||||
"max_abs %.2e bad %ld%s %s\n",
|
||||
c.name.c_str(), pairing, M, H, B, stats[0], stats[2], stats[1], max_err, bad,
|
||||
note.c_str(), ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The rows row (attend_rows): one query row and 64 heads a workgroup, as GLM's prefill runs MLA
|
||||
* split by rows. Each form against the f64 softmax and the forms bit for bit against each other
|
||||
* (the element-wise key load; 32 heads a workgroup, whose heads sum alike); unsplit, a run of the
|
||||
* rows against the same rows of the whole batch, since a rank computing its run must produce the
|
||||
* bytes the batch would. */
|
||||
int run_rows(const Case& c, std::mt19937& rng) {
|
||||
const int M = c.rows, H = c.heads, B = c.blocks;
|
||||
std::vector<int> bt, len;
|
||||
const int pages = fill_tables(c, rng, bt, len);
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
const double scale = 0.0625;
|
||||
const std::vector<double> want = reference(M, H, B, pages, bt, len, qb, kvb, scale);
|
||||
std::vector<char> scratch;
|
||||
auto launch = [&](int first, int rows, int form, std::vector<uint16_t>& out) {
|
||||
const size_t q0 = (size_t)first * H * D;
|
||||
RadTensor t[5] = { tens(qb.data() + q0, RAD_BF16, { rows, H, D }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
|
||||
tens(len.data() + first, RAD_I32, { rows }),
|
||||
tens(out.data() + q0, RAD_BF16, { rows, H, D }) };
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { rows, D, H, B, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = scale;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
if (c.scratch) {
|
||||
const int64_t need = halo_rad_mla_attn_matrix_scratch(&a);
|
||||
scratch.assign((size_t)need + 16, 0);
|
||||
a.scratch = scratch.data() + ((16 - ((uintptr_t)scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
}
|
||||
if (form < 0) return halo_rad_mla_attn_matrix(&a, nullptr);
|
||||
halo_mla_rows_pin_form(form);
|
||||
const int rc = halo_rad_mla_attn_rows(&a, nullptr);
|
||||
halo_mla_rows_pin_form(0);
|
||||
return rc;
|
||||
};
|
||||
int fails = 0;
|
||||
std::vector<uint16_t> rule;
|
||||
for (int form : { 3, 1, 2, 0 }) {
|
||||
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
const int rc = launch(0, M, form, out);
|
||||
if (rc != RAD_OK) {
|
||||
std::printf("%-40s form %d launch returned %d FAIL\n", c.name.c_str(), form, rc);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
double max_err = 0;
|
||||
long bad = 0;
|
||||
for (size_t i = 0; i < out.size(); ++i) {
|
||||
const float got = rad_bf16_to_f32(out[i]);
|
||||
const double e = std::fabs(got - want[i]);
|
||||
if (!std::isfinite(got) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad;
|
||||
if (std::isfinite(got)) max_err = std::max(max_err, e);
|
||||
}
|
||||
bool ok = bad == 0;
|
||||
std::string note;
|
||||
/* A split follows the workgroup count, which 32 heads a workgroup doubles; under 32 rows
|
||||
* the rule is the matrix row's kernel. */
|
||||
if (form == 3)
|
||||
rule = out;
|
||||
else if (form == 0 && M < 32) {
|
||||
std::vector<uint16_t> matrix((size_t)M * H * D, 0xffff);
|
||||
const int mrc = launch(0, M, -1, matrix);
|
||||
if (mrc != RAD_OK || matrix != out) {
|
||||
note = " (the rule under 32 rows is not the matrix row)";
|
||||
ok = false;
|
||||
}
|
||||
} else if ((form == 1 || !c.scratch) && out != rule) {
|
||||
note = " (differs from form 3)";
|
||||
ok = false;
|
||||
}
|
||||
std::printf("%-40s form %d M %3d H %2d blocks %3d max_abs %.2e bad %ld%s %s\n",
|
||||
c.name.c_str(), form, M, H, B, max_err, bad, note.c_str(), ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
if (!c.scratch && M >= 3 && !rule.empty()) {
|
||||
std::vector<uint16_t> out((size_t)M * H * D, 0xffff);
|
||||
const int rc = launch(1, M - 2, 3, out);
|
||||
bool same = rc == RAD_OK, untouched = true;
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
|
||||
if (r == 0 || r == M - 1)
|
||||
untouched = untouched && out[i] == 0xffff;
|
||||
else
|
||||
same = same && out[i] == rule[i];
|
||||
}
|
||||
std::printf("%-40s rows 1..%d alone: %s, rows outside %s %s\n", c.name.c_str(), M - 2,
|
||||
same ? "bit-identical to the batch" : "DIFFER from the batch",
|
||||
untouched ? "untouched" : "WRITTEN", same && untouched ? "PASS" : "FAIL");
|
||||
fails += !(same && untouched);
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* A TP step's attention both ways on one operand set: by heads, each of `world` ranks running
|
||||
* the matrix row on its heads of every row (views into the whole [T, 64, 512]), and by rows, each
|
||||
* rank the rows row on its run of ceil(T / world) rows with every head, the last run short. The
|
||||
* step mixes what a step batch carries, decode rows first: single-row decodes on scattered tables,
|
||||
* a verify window of four rows on one table, then a prefill continuing past the DSA budget and a
|
||||
* fresh prompt's first chunk. Both forms against the f64 softmax; how far apart they are is
|
||||
* printed. */
|
||||
int run_split(const char* name, int world, int fresh_rows, std::mt19937& rng) {
|
||||
constexpr int H = 64, B = 65;
|
||||
std::vector<int> bt, len;
|
||||
int pages = 0;
|
||||
auto append = [&](const std::vector<int>& t, const std::vector<int>& l, int segment_pages) {
|
||||
for (int v : t) bt.push_back(v >= 0 ? v + pages : v);
|
||||
len.insert(len.end(), l.begin(), l.end());
|
||||
pages += segment_pages;
|
||||
};
|
||||
{ /* three decodes, each its own table with holes */
|
||||
std::vector<int> t((size_t)3 * B), l(3);
|
||||
for (int r = 0; r < 3; ++r) {
|
||||
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = b % 13 == 5 ? -1 : (b * 5 + r * 17) % (3 * B);
|
||||
l[r] = B * BS - 1 - 3 * r;
|
||||
}
|
||||
append(t, l, 3 * B);
|
||||
}
|
||||
{ /* a verify window: four rows of one sequence on one table */
|
||||
std::vector<int> t((size_t)4 * B), l(4);
|
||||
for (int r = 0; r < 4; ++r) {
|
||||
for (int b = 0; b < B; ++b) t[(size_t)r * B + b] = (b * 3 + 1) % B;
|
||||
l[r] = B * BS - 4 + r + 1;
|
||||
}
|
||||
append(t, l, B);
|
||||
}
|
||||
{ /* a prefill past the DSA budget: every row its own top blocks */
|
||||
std::vector<int> t, l;
|
||||
int segment = 0;
|
||||
topk_tables(23, B, 1200, 4, rng, t, l, segment);
|
||||
append(t, l, segment);
|
||||
}
|
||||
{ /* a fresh prompt's chunk: causal on one table, rows starting at position 0 */
|
||||
std::vector<int> t((size_t)fresh_rows * B, -1), l(fresh_rows);
|
||||
for (int r = 0; r < fresh_rows; ++r) {
|
||||
for (int b = 0; b <= r / BS && b < B; ++b) t[(size_t)r * B + b] = b;
|
||||
l[r] = r + 1;
|
||||
}
|
||||
append(t, l, B);
|
||||
}
|
||||
const int T = (int)len.size();
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)T * H * D), kvb((size_t)pages * BS * D);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
const double scale = 0.0625;
|
||||
const std::vector<double> want = reference(T, H, B, pages, bt, len, qb, kvb, scale);
|
||||
auto launch = [&](bool by_rows, int first, int rows, int h0, int heads,
|
||||
std::vector<uint16_t>& out) {
|
||||
const size_t at = ((size_t)first * H + h0) * D;
|
||||
RadTensor t[5] = { tens(qb.data() + at, RAD_BF16, { rows, heads, D }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data() + (size_t)first * B, RAD_I32, { rows, B }),
|
||||
tens(len.data() + first, RAD_I32, { rows }),
|
||||
tens(out.data() + at, RAD_BF16, { rows, heads, D }) };
|
||||
t[0].stride[0] = t[4].stride[0] = (int64_t)H * D;
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { rows, D, heads, B, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = scale;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
if (!by_rows) return halo_rad_mla_attn_matrix(&a, nullptr);
|
||||
/* Runs this short take the matrix kernel by rule; the rows kernel is what is under test. */
|
||||
halo_mla_rows_pin_form(3);
|
||||
const int rc = halo_rad_mla_attn_rows(&a, nullptr);
|
||||
halo_mla_rows_pin_form(0);
|
||||
return rc;
|
||||
};
|
||||
std::vector<uint16_t> heads_out((size_t)T * H * D, 0xffff), rows_out((size_t)T * H * D, 0xffff);
|
||||
const int per_heads = H / world, run = (T + world - 1) / world;
|
||||
int fails = 0;
|
||||
/* What each rank's run buffer holds after its rows: written through the same launches into
|
||||
* the plane at the run's rows, then copied out as the all_gather moves it, rank r's run of
|
||||
* `run` rows to rows [r * run, (r + 1) * run) of a [world * run] output. */
|
||||
std::vector<uint16_t> gathered((size_t)world * run * H * D, 0xffff);
|
||||
for (int rank = 0; rank < world; ++rank) {
|
||||
fails += launch(false, 0, T, rank * per_heads, per_heads, heads_out) != RAD_OK;
|
||||
const int first = rank * run, n = std::min(run, T - first);
|
||||
if (n > 0) fails += launch(true, first, n, 0, H, rows_out) != RAD_OK;
|
||||
std::vector<uint16_t> part((size_t)run * H * D, 0xeeee);
|
||||
for (int r = 0; r < n; ++r)
|
||||
std::copy(rows_out.begin() + (size_t)(first + r) * H * D,
|
||||
rows_out.begin() + (size_t)(first + r + 1) * H * D,
|
||||
part.begin() + (size_t)r * H * D);
|
||||
std::copy(part.begin(), part.end(), gathered.begin() + (size_t)rank * run * H * D);
|
||||
}
|
||||
bool placed = true;
|
||||
for (size_t i = 0; i < (size_t)T * H * D; ++i) placed = placed && gathered[i] == rows_out[i];
|
||||
if (!placed) {
|
||||
std::printf("%-40s the gathered runs do not land on their rows FAIL\n", name);
|
||||
++fails;
|
||||
}
|
||||
long bad[2] = { 0, 0 };
|
||||
double max_err[2] = { 0, 0 }, apart = 0;
|
||||
for (size_t i = 0; i < want.size(); ++i) {
|
||||
const float got[2] = { rad_bf16_to_f32(heads_out[i]), rad_bf16_to_f32(rows_out[i]) };
|
||||
for (int f = 0; f < 2; ++f) {
|
||||
const double e = std::fabs(got[f] - want[i]);
|
||||
if (!std::isfinite(got[f]) || e > 1e-5 + 0.008 * std::fabs(want[i])) ++bad[f];
|
||||
if (std::isfinite(got[f])) max_err[f] = std::max(max_err[f], e);
|
||||
}
|
||||
apart = std::max(apart, (double)std::fabs(got[0] - got[1]));
|
||||
}
|
||||
const bool ok = !fails && !bad[0] && !bad[1];
|
||||
std::printf("%-40s T %3d world %d run %2d last %2d heads max_abs %.2e bad %ld rows max_abs "
|
||||
"%.2e bad %ld apart %.2e %s\n",
|
||||
name, T, world, run, T - (world - 1) * run, max_err[0], bad[0], max_err[1], bad[1],
|
||||
apart, ok ? "PASS" : "FAIL");
|
||||
return !ok;
|
||||
}
|
||||
|
||||
/* The head form against the row form, row by row and bit by bit, on a TP8 prefill chunk past the
|
||||
* DSA budget: the head form is the paired union tile (eight heads of rows 2i and 2i+1), the row
|
||||
* form's two kernels are the 16-head matrix tile (halo_mla_rows_pin_form(4)) and the rows kernel.
|
||||
* The union's first row of a pair walks its own table in its own order, as the 16-head tile does,
|
||||
* so it must agree to the bit; the second row and the rows kernel sum in other orders, within
|
||||
* rounding. Printed: rows bit-identical, elements differing, and the largest step in bf16 units. */
|
||||
int run_rowwise(std::mt19937& rng) {
|
||||
constexpr int H = 64, B = 65, M = 16;
|
||||
std::vector<int> bt, len;
|
||||
int pages = 0;
|
||||
topk_tables(M, B, 1200, 16, rng, bt, len, pages);
|
||||
std::normal_distribution<float> nrm(0.f, 1.f);
|
||||
std::vector<uint16_t> qb((size_t)M * H * D), kvb((size_t)pages * BS * D);
|
||||
for (auto& v : qb) v = rad_f32_to_bf16(0.25f * nrm(rng));
|
||||
for (auto& v : kvb) v = rad_f32_to_bf16(nrm(rng));
|
||||
auto launch = [&](int kernel, int h0, int heads, std::vector<uint16_t>& out) {
|
||||
RadTensor t[5] = { tens(qb.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }),
|
||||
tens(kvb.data(), RAD_BF16, { pages, 1, BS, D }),
|
||||
tens(bt.data(), RAD_I32, { M, B }), tens(len.data(), RAD_I32, { M }),
|
||||
tens(out.data() + (size_t)h0 * D, RAD_BF16, { M, heads, D }) };
|
||||
t[0].stride[0] = t[4].stride[0] = (int64_t)H * D;
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { M, D, heads, B, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 0.0625;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
if (kernel < 2) return halo_rad_mla_attn_matrix(&a, nullptr);
|
||||
halo_mla_rows_pin_form(3);
|
||||
const int rc = halo_rad_mla_attn_rows(&a, nullptr);
|
||||
halo_mla_rows_pin_form(0);
|
||||
return rc;
|
||||
};
|
||||
std::vector<uint16_t> head((size_t)M * H * D), m16((size_t)M * H * D), rows((size_t)M * H * D);
|
||||
int rc = 0;
|
||||
for (int r = 0; r < 8; ++r) rc |= launch(0, r * 8, 8, head);
|
||||
rc |= launch(1, 0, H, m16);
|
||||
rc |= launch(2, 0, H, rows);
|
||||
auto ord = [](uint16_t h) { return (h & 0x8000) ? -(int)(h & 0x7fff) : (int)h; };
|
||||
int fails = rc != RAD_OK;
|
||||
for (const auto& [name, got] : { std::pair<const char*, const std::vector<uint16_t>*>{
|
||||
"16-head tile", &m16 },
|
||||
{ "rows kernel", &rows } }) {
|
||||
int same_even = 0, same_odd = 0, max_ulp = 0;
|
||||
long diff = 0;
|
||||
double max_abs = 0;
|
||||
for (size_t i = 0; i < head.size(); ++i)
|
||||
max_abs = std::max(max_abs, (double)std::fabs(rad_bf16_to_f32((*got)[i]) -
|
||||
rad_bf16_to_f32(head[i])));
|
||||
for (int r = 0; r < M; ++r) {
|
||||
bool same = true;
|
||||
for (size_t i = (size_t)r * H * D; i < (size_t)(r + 1) * H * D; ++i) {
|
||||
const int u = std::abs(ord((*got)[i]) - ord(head[i]));
|
||||
same = same && !u;
|
||||
diff += u != 0;
|
||||
max_ulp = std::max(max_ulp, u);
|
||||
}
|
||||
(r % 2 ? same_odd : same_even) += same;
|
||||
}
|
||||
/* The 16-head tile must give the union's first rows bit for bit. */
|
||||
const bool ok = std::strcmp(name, "16-head tile") || same_even == M / 2;
|
||||
std::printf("rowwise: %-12s vs head form (union pairs): rows bit-identical %d/%d first, "
|
||||
"%d/%d second of a pair; %ld of %d elements differ, at most %d bf16 steps, "
|
||||
"max abs %.2e %s\n",
|
||||
name, same_even, M / 2, same_odd, M / 2, diff, M * H * D, max_ulp, max_abs,
|
||||
ok ? "PASS" : "FAIL");
|
||||
fails += !ok;
|
||||
}
|
||||
return fails;
|
||||
}
|
||||
|
||||
/* The launcher prints the running totals every 1024th counted launch and must leave them
|
||||
* standing: 1024 one-chunk launches of a pair, then the hook reads exactly 1024 passes. */
|
||||
int periodic_report() {
|
||||
std::vector<uint16_t> q(2 * 8 * D, 0x3f80), kv(4 * BS * D, 0x3f80), out(2 * 8 * D);
|
||||
std::vector<int> bt = { 0, 1 }, len = { 4, 3 };
|
||||
RadTensor t[5]{};
|
||||
auto set = [](RadTensor& x, void* p, uint32_t dt, std::vector<int64_t> shape) {
|
||||
x.data = p;
|
||||
x.dtype = dt;
|
||||
x.rank = (uint32_t)shape.size();
|
||||
int64_t st = 1;
|
||||
for (int i = (int)shape.size() - 1; i >= 0; --i) {
|
||||
x.shape[i] = shape[i];
|
||||
x.stride[i] = st;
|
||||
st *= shape[i];
|
||||
}
|
||||
};
|
||||
set(t[0], q.data(), RAD_BF16, { 2, 8, D });
|
||||
set(t[1], kv.data(), RAD_BF16, { 4, 1, BS, D });
|
||||
set(t[2], bt.data(), RAD_I32, { 2, 1 });
|
||||
set(t[3], len.data(), RAD_I32, { 2 });
|
||||
set(t[4], out.data(), RAD_BF16, { 2, 8, D });
|
||||
RadParam p[6]{};
|
||||
const char* keys[5] = { "M", "latent_dim", "heads", "blocks", "block_size" };
|
||||
const long long vals[5] = { 2, D, 8, 1, BS };
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
p[i].key = keys[i];
|
||||
p[i].kind = RAD_P_INT;
|
||||
p[i].ival = vals[i];
|
||||
}
|
||||
p[5].key = "scale";
|
||||
p[5].kind = RAD_P_F64;
|
||||
p[5].dval = 0.0625;
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 5;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
unsigned long long stats[3];
|
||||
halo_mla_matrix_stats(stats);
|
||||
for (int i = 0; i < 1024; ++i)
|
||||
if (halo_rad_mla_attn_matrix(&a, nullptr) != RAD_OK) {
|
||||
std::printf("periodic report: launch failed\n");
|
||||
return 1;
|
||||
}
|
||||
halo_mla_matrix_stats(stats);
|
||||
const bool ok = stats[0] == 1024 && stats[2] == 1024 && stats[1] == 0;
|
||||
std::printf("periodic report: %llu passes over %llu raster chunks after 1024 launches %s\n",
|
||||
stats[0], stats[2], ok ? "PASS" : "FAIL");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
setenv("RADIANCE_MLA_CONFLICT_STATS", "1", 1);
|
||||
/* name, rows, heads, blocks, fill, swaps, context, scratch, form, expect_second, bitwise_a,
|
||||
* bitwise_all, union_falls_back */
|
||||
std::vector<Case> cases = {
|
||||
{ "prefill, one table", 8, 8, 65, Fill::prefill, 0, 0, false, 0, 0, true, true },
|
||||
{ "prefill, odd rows, split", 7, 8, 33, Fill::prefill, 0, 0, true, 0, 0, true, true },
|
||||
{ "prefill, 16 heads", 4, 16, 33, Fill::prefill, 0, 0, false, 0, 0 },
|
||||
{ "prefill, 24 heads (three pairs)", 5, 24, 17, Fill::prefill, 0, 0, false, 0, 0, true,
|
||||
true },
|
||||
{ "topk d=0", 8, 8, 65, Fill::topk, 0, 600, false, 0, 0, true, true },
|
||||
{ "topk d=4", 8, 8, 65, Fill::topk, 4, 600, false, 0, 1 },
|
||||
{ "topk d=16", 8, 8, 65, Fill::topk, 16, 600, false, 0, 1 },
|
||||
{ "topk d=64 (disjoint neighbours)", 6, 8, 65, Fill::topk, 64, 600, false, 0, 1 },
|
||||
{ "topk d=16, 513 blocks", 4, 8, 513, Fill::topk, 16, 8192, false, 0, 1 },
|
||||
/* a split cuts the union's walk elsewhere than the positional raster */
|
||||
{ "topk d=4, odd rows, split", 5, 8, 33, Fill::topk, 4, 400, true, 0, 1, false },
|
||||
{ "topk d=4, element load", 4, 8, 33, Fill::topk, 4, 400, false, 1, 1 },
|
||||
{ "topk d=4, 16 heads", 4, 16, 33, Fill::topk, 4, 400, false, 0, 0 },
|
||||
{ "topk, table past the union's lists", 4, 8, 600, Fill::topk, 16, 4000, false, 0, 1, true,
|
||||
true, true },
|
||||
{ "repeated pages", 6, 8, 33, Fill::repeat, 0, 0, false, 0, -1 },
|
||||
{ "repeated pages, split", 3, 8, 33, Fill::repeat, 0, 0, true, 0, -1, false },
|
||||
{ "ragged, holes and bad pages", 7, 8, 17, Fill::ragged, 0, 0, false, 0, -1 },
|
||||
{ "ragged, split", 3, 8, 17, Fill::ragged, 0, 0, true, 0, -1, false },
|
||||
};
|
||||
/* The rows row at 64 heads, and at 32, which it serves with two groups a workgroup. */
|
||||
std::vector<Case> rows_cases = {
|
||||
{ "rows: prefill, one table", 8, 64, 65, Fill::prefill },
|
||||
{ "rows: topk d=4", 8, 64, 65, Fill::topk, 4, 600 },
|
||||
{ "rows: topk d=16, 513 blocks", 3, 64, 513, Fill::topk, 16, 8192 },
|
||||
{ "rows: repeated pages", 6, 64, 33, Fill::repeat },
|
||||
{ "rows: ragged, holes and bad pages", 7, 64, 17, Fill::ragged },
|
||||
{ "rows: ragged, split", 3, 64, 17, Fill::ragged, 0, 0, true },
|
||||
{ "rows: prefill, one row, split", 1, 64, 65, Fill::prefill, 0, 0, true },
|
||||
{ "rows: 32 heads", 5, 32, 33, Fill::prefill },
|
||||
{ "rows: 32 heads, topk d=4, split", 2, 32, 33, Fill::topk, 4, 400, true },
|
||||
};
|
||||
const char* filter = argc > 1 ? argv[1] : nullptr;
|
||||
int fails = 0;
|
||||
for (size_t i = 0; i < cases.size(); ++i) {
|
||||
if (filter && cases[i].name.find(filter) == std::string::npos) continue;
|
||||
std::mt19937 rng(20261018u + (unsigned)i);
|
||||
fails += run(cases[i], rng);
|
||||
}
|
||||
for (size_t i = 0; i < rows_cases.size(); ++i) {
|
||||
if (filter && rows_cases[i].name.find(filter) == std::string::npos) continue;
|
||||
std::mt19937 rng(20261020u + (unsigned)i);
|
||||
fails += run_rows(rows_cases[i], rng);
|
||||
}
|
||||
if (!filter || std::strstr("rowwise", filter)) {
|
||||
std::mt19937 rng(20261022u);
|
||||
fails += run_rowwise(rng);
|
||||
}
|
||||
/* T 45 over eight ranks: runs of 6, the last of 3; 37 over four: 10 and 7; 48: whole runs. */
|
||||
const struct {
|
||||
const char* name;
|
||||
int world, fresh;
|
||||
} splits[] = { { "split: heads vs rows, 8 ranks", 8, 15 },
|
||||
{ "split: heads vs rows, 8 ranks, T 300", 8, 270 },
|
||||
{ "split: heads vs rows, 4 ranks", 4, 7 },
|
||||
{ "split: heads vs rows, whole runs", 8, 18 } };
|
||||
for (size_t i = 0; i < sizeof splits / sizeof splits[0]; ++i) {
|
||||
if (filter && !std::strstr(splits[i].name, filter)) continue;
|
||||
std::mt19937 rng(20261021u + (unsigned)i);
|
||||
fails += run_split(splits[i].name, splits[i].world, splits[i].fresh, rng);
|
||||
}
|
||||
if (!filter) fails += periodic_report();
|
||||
std::printf("%d failure(s)\n", fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,614 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_moefuse.cpp): GLM's decode fusions of the MoE block (halo_glm.hip) on the host SIMT emulator,
|
||||
* each byte for byte against the separate launches it replaces.
|
||||
*
|
||||
* router_sigmoid_topk_scatter against router_sigmoid_topk (the emulated kernel), then moe_scatter's
|
||||
* stable counting sort over its ids written out here, then the `fill` of the shared gate with 1:
|
||||
* random, tied and NaN ranks (a row with fewer finite ranks than top_k selects expert 0 for its
|
||||
* empty slots, and the sort takes those as written), slices and protected experts, rows past 64
|
||||
* wrapping over the waves, the sort's bound and its refusal past it. Pitch padding, guards past
|
||||
* every output and the gate's untouched rows show an overrun.
|
||||
*
|
||||
* swiglu_clamped_quant_fp8 against swiglu_clamped then quant_act_fp8 (both emulated): codes,
|
||||
* scales and the optional bf16 product, at GLM's widths and ragged ones, with values far past the
|
||||
* clamp, exactly on it and one bf16 step beyond, all-zero groups (scale 1), a gate so negative the
|
||||
* sigmoid underflows, and NaN and infinite inputs.
|
||||
*
|
||||
* moe_scatter_inv and moe_gather_inv: the small sort's kernel with the inverse against itself
|
||||
* without, and the inverse against the table the gather builds from `sorted`; then moe_gather's
|
||||
* kernel reading that inverse against its self-scan (T <= 512) or the prepass's table (above), at
|
||||
* GLM's f32 routing weights and bf16 ones, with the ungated shared arm, a sigmoid-gated one and
|
||||
* none, and slices that drop slots. moe_scatter's three-pass form (T > 1024) is not here: its
|
||||
* kernels take dynamic LDS through `extern __shared__`, which the emulator cannot give; the card
|
||||
* checks it (halo_selftest --case moe_scatter_inv_i32). */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include "halo_moe_sort.h"
|
||||
#include "halo_moe_gather.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int32_t kPoison = -77;
|
||||
constexpr uint16_t kGatePoison = 0x7e57;
|
||||
|
||||
/* moe_scatter's contract: slot i = token * top_k + slot goes to its expert's run in ascending i;
|
||||
* an expert outside the slice drops the slot; protected experts are placed last in list order;
|
||||
* sorted rows past the live count are -1. */
|
||||
struct SortModel {
|
||||
std::vector<int32_t> sorted, off, cnt;
|
||||
};
|
||||
int32_t place_of(int32_t e, int nl, const std::vector<int>& prot) {
|
||||
int32_t below = 0;
|
||||
for (size_t j = 0; j < prot.size(); ++j) {
|
||||
if (prot[j] == e) return nl - (int32_t)prot.size() + (int32_t)j;
|
||||
below += prot[j] < e;
|
||||
}
|
||||
return e - below;
|
||||
}
|
||||
SortModel sort_model(const std::vector<int32_t>& ids, int M, int k, int ip, int nl, int base,
|
||||
const std::vector<int>& prot) {
|
||||
const int T = M * k;
|
||||
std::vector<int32_t> place((size_t)T);
|
||||
SortModel s;
|
||||
s.cnt.assign((size_t)nl, 0);
|
||||
s.off.assign((size_t)nl + 1, 0);
|
||||
s.sorted.assign((size_t)T, -1);
|
||||
for (int i = 0; i < T; ++i) {
|
||||
const int32_t e = ids[(size_t)(i / k) * ip + i % k] - base;
|
||||
place[(size_t)i] = e >= 0 && e < nl ? place_of(e, nl, prot) : -1;
|
||||
if (place[(size_t)i] >= 0) ++s.cnt[(size_t)place[(size_t)i]];
|
||||
}
|
||||
for (int e = 0; e < nl; ++e) s.off[(size_t)e + 1] = s.off[(size_t)e] + s.cnt[(size_t)e];
|
||||
std::vector<int32_t> seen((size_t)nl, 0);
|
||||
for (int i = 0; i < T; ++i)
|
||||
if (place[(size_t)i] >= 0) {
|
||||
const int32_t e = place[(size_t)i];
|
||||
s.sorted[(size_t)(s.off[(size_t)e] + seen[(size_t)e]++)] = i;
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/* The table the gather builds from `sorted` (gather_kernel's self-scan, or its prepass): slot
|
||||
* sorted[p] at row p, every other slot -1. */
|
||||
std::vector<int32_t> inverse_of(const std::vector<int32_t>& sorted) {
|
||||
std::vector<int32_t> inv(sorted.size(), -1);
|
||||
for (size_t p = 0; p < sorted.size(); ++p)
|
||||
if (sorted[p] >= 0) inv[(size_t)sorted[p]] = (int32_t)p;
|
||||
return inv;
|
||||
}
|
||||
|
||||
/* moe_scatter's small-form kernel (halo_moe_sort.h) over contiguous ids, with or without the
|
||||
* inverse. */
|
||||
struct Scatter {
|
||||
int rc = RAD_OK;
|
||||
std::vector<int32_t> sorted, off, cnt, inv;
|
||||
};
|
||||
Scatter scatter_kernel(const std::vector<int32_t>& ids, int nl, int base, const char* protect,
|
||||
bool with_inv) {
|
||||
const int T = (int)ids.size();
|
||||
Scatter s;
|
||||
s.sorted.assign((size_t)T, kPoison);
|
||||
s.off.assign((size_t)nl + 1, kPoison);
|
||||
s.cnt.assign((size_t)nl, kPoison);
|
||||
s.inv.assign((size_t)T, kPoison);
|
||||
RadParam pp{};
|
||||
pp.key = "protect";
|
||||
pp.kind = RAD_P_STR;
|
||||
pp.sval = protect;
|
||||
RadArgs pa{};
|
||||
pa.p = &pp;
|
||||
pa.n_p = protect ? 1 : 0;
|
||||
halo_moesort::Protect prot;
|
||||
s.rc = halo_moesort::protect_of(&pa, nl, &prot);
|
||||
if (s.rc != RAD_OK) return s;
|
||||
if (with_inv)
|
||||
HALO_EMIT(nullptr, (halo_moesort::scatter_small_kernel<true>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, s.inv.data());
|
||||
else
|
||||
HALO_EMIT(nullptr, (halo_moesort::scatter_small_kernel<false>), dim3(1), dim3(256), 0,
|
||||
ids.data(), s.sorted.data(), s.off.data(), s.cnt.data(), (uint32_t)T, (uint32_t)nl,
|
||||
(int32_t)base, prot, (int32_t*)nullptr);
|
||||
return s;
|
||||
}
|
||||
|
||||
struct RouterShape {
|
||||
int M, ne, k, norm;
|
||||
int mode; /* 0 random, 1 tied ranks, 2 NaN rows */
|
||||
int nl, base; /* the slice: nl 0 is the whole router */
|
||||
const char* protect;
|
||||
bool gate;
|
||||
};
|
||||
|
||||
void router_scatter_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const RouterShape shapes[] = {
|
||||
{ 1, 288, 8, 1, 0, 0, 0, nullptr, true }, { 2, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 6, 288, 8, 1, 0, 0, 0, nullptr, true }, { 8, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 9, 288, 8, 1, 0, 0, 0, nullptr, false }, { 16, 288, 8, 1, 2, 0, 0, nullptr, true },
|
||||
{ 17, 288, 8, 1, 0, 0, 0, nullptr, true }, { 24, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 33, 288, 8, 1, 0, 0, 0, nullptr, true }, { 48, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 48, 288, 8, 1, 2, 0, 0, nullptr, true }, { 65, 288, 8, 1, 1, 0, 0, nullptr, true },
|
||||
{ 100, 288, 8, 0, 0, 0, 0, nullptr, true }, { 128, 288, 8, 1, 0, 0, 0, nullptr, true },
|
||||
{ 24, 288, 8, 1, 0, 144, 144, nullptr, true }, { 24, 288, 8, 1, 1, 96, 32, "3,7,90", true },
|
||||
{ 48, 512, 8, 1, 0, 0, 0, nullptr, true }, { 32, 32, 32, 0, 1, 0, 0, nullptr, true },
|
||||
{ 5, 300, 10, 1, 2, 0, 0, "0,299", true },
|
||||
};
|
||||
std::uniform_int_distribution<int> ud(-1000, 1000);
|
||||
for (const RouterShape& sh : shapes) {
|
||||
const int M = sh.M, ne = sh.ne, k = sh.k, T = M * k;
|
||||
const int nl = sh.nl ? sh.nl : ne, base = sh.base;
|
||||
const int lp = ne + 5, bp = 2, ip = k + 3, wp = k + 1, gp = 3;
|
||||
const float factor = 2.5f;
|
||||
std::vector<float> lg((size_t)M * lp), bias((size_t)ne * bp);
|
||||
for (auto& v : lg) v = sh.mode == 1 ? (float)(ud(rng) % 8) * 0.5f : (float)ud(rng) / 200;
|
||||
for (auto& v : bias)
|
||||
v = sh.mode == 1 ? (float)(ud(rng) % 5) * 0.125f : (float)ud(rng) / 2000;
|
||||
if (sh.mode == 2)
|
||||
for (int r = 0; r < M; r += 2) {
|
||||
/* every other row keeps (r % 5) finite ranks, fewer than top_k */
|
||||
for (int e = 0; e < ne; ++e) lg[(size_t)r * lp + e] = NAN;
|
||||
for (int j = 0; j < r % 5; ++j)
|
||||
lg[(size_t)r * lp + (size_t)(ud(rng) + 1000) % ne] = 0.25f * (float)j;
|
||||
}
|
||||
std::vector<int> prot;
|
||||
if (sh.protect)
|
||||
for (const char* p = sh.protect; *p;) {
|
||||
char* end = nullptr;
|
||||
prot.push_back((int)std::strtol(p, &end, 10));
|
||||
p = *end == ',' ? end + 1 : end;
|
||||
}
|
||||
|
||||
RadTensor t[8]{};
|
||||
t[0].data = lg.data();
|
||||
t[0].dtype = RAD_F32;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = ne;
|
||||
t[0].stride[0] = lp;
|
||||
t[0].stride[1] = 1;
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = bp;
|
||||
t[2].dtype = RAD_I32;
|
||||
t[2].rank = 2;
|
||||
t[2].shape[0] = M;
|
||||
t[2].shape[1] = k;
|
||||
t[2].stride[0] = ip;
|
||||
t[2].stride[1] = 1;
|
||||
t[3].dtype = RAD_F32;
|
||||
t[3].rank = 2;
|
||||
t[3].shape[0] = M;
|
||||
t[3].shape[1] = k;
|
||||
t[3].stride[0] = wp;
|
||||
t[3].stride[1] = 1;
|
||||
t[4].dtype = RAD_I32;
|
||||
t[4].rank = 1;
|
||||
t[4].shape[0] = T;
|
||||
t[4].stride[0] = 1;
|
||||
t[5].dtype = RAD_I32;
|
||||
t[5].rank = 1;
|
||||
t[5].shape[0] = nl + 1;
|
||||
t[5].stride[0] = 1;
|
||||
t[6].dtype = RAD_I32;
|
||||
t[6].rank = 1;
|
||||
t[6].shape[0] = nl;
|
||||
t[6].stride[0] = 1;
|
||||
t[7].dtype = RAD_BF16;
|
||||
t[7].rank = 2;
|
||||
t[7].shape[0] = M;
|
||||
t[7].shape[1] = 1;
|
||||
t[7].stride[0] = gp;
|
||||
t[7].stride[1] = 1;
|
||||
std::vector<RadParam> p(9);
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, sh.norm };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = factor;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
p[6] = { "n_local", RAD_P_INT, nl };
|
||||
p[7] = { "expert_base", RAD_P_INT, base };
|
||||
p[8].key = "protect";
|
||||
p[8].kind = RAD_P_STR;
|
||||
p[8].sval = sh.protect;
|
||||
const int n_p = sh.protect ? 9 : 8;
|
||||
|
||||
/* the separate launches: the selection, then the sort and fill modelled */
|
||||
std::vector<int32_t> ids_ref((size_t)M * ip, kPoison);
|
||||
std::vector<float> w_ref((size_t)M * wp, -7.25f);
|
||||
t[2].data = ids_ref.data();
|
||||
t[3].data = w_ref.data();
|
||||
RadArgs sel{};
|
||||
sel.t = t;
|
||||
sel.n_t = 4;
|
||||
sel.p = p.data();
|
||||
sel.n_p = 6;
|
||||
++cases;
|
||||
if (halo_rad_router_sigmoid_topk(&sel, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL router_sigmoid_topk launch M=%d ne=%d\n", M, ne);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const SortModel ref = sort_model(ids_ref, M, k, ip, nl, base, prot);
|
||||
/* moe_scatter's own kernel over the ids, contiguous as it reads them, held to the model;
|
||||
* with the inverse, which must be the table the gather builds from `sorted`. */
|
||||
std::vector<int32_t> flat((size_t)T);
|
||||
for (int i = 0; i < T; ++i) flat[(size_t)i] = ids_ref[(size_t)(i / k) * ip + i % k];
|
||||
Scatter ks = scatter_kernel(flat, nl, base, sh.protect, true);
|
||||
++cases;
|
||||
if (ks.rc != RAD_OK || ks.sorted != ref.sorted || ks.off != ref.off || ks.cnt != ref.cnt ||
|
||||
ks.inv != inverse_of(ref.sorted)) {
|
||||
std::printf("FAIL moe_scatter kernel against its model at M=%d ne=%d slice %d+%d\n", M,
|
||||
ne, base, nl);
|
||||
++fails;
|
||||
}
|
||||
|
||||
for (int with_inv = 0; with_inv < 2; ++with_inv) {
|
||||
std::vector<int32_t> ids((size_t)M * ip, kPoison), sorted((size_t)T + 4, kPoison),
|
||||
off((size_t)nl + 5, kPoison), cnt((size_t)nl + 4, kPoison),
|
||||
inv((size_t)T + 4, kPoison);
|
||||
std::vector<float> w((size_t)M * wp, -7.25f);
|
||||
std::vector<uint16_t> gate((size_t)(M + 2) * gp, kGatePoison);
|
||||
RadTensor tf[9];
|
||||
std::memcpy(tf, t, sizeof t);
|
||||
tf[2].data = ids.data();
|
||||
tf[3].data = w.data();
|
||||
tf[4].data = sorted.data();
|
||||
tf[5].data = off.data();
|
||||
tf[6].data = cnt.data();
|
||||
tf[7].data = sh.gate ? gate.data() : nullptr;
|
||||
tf[8] = tf[4];
|
||||
tf[8].data = inv.data();
|
||||
RadArgs a{};
|
||||
a.t = tf;
|
||||
a.n_t = with_inv ? 9 : 8;
|
||||
a.p = p.data();
|
||||
a.n_p = n_p;
|
||||
++cases;
|
||||
const int rc = halo_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
int bad = 0;
|
||||
bad += ids != ids_ref;
|
||||
bad += std::memcmp(w.data(), w_ref.data(), w.size() * 4) != 0;
|
||||
bad += std::memcmp(sorted.data(), ks.sorted.data(), (size_t)T * 4) != 0;
|
||||
bad += std::memcmp(off.data(), ks.off.data(), (size_t)(nl + 1) * 4) != 0;
|
||||
bad += std::memcmp(cnt.data(), ks.cnt.data(), (size_t)nl * 4) != 0;
|
||||
if (with_inv) bad += std::memcmp(inv.data(), ks.inv.data(), (size_t)T * 4) != 0;
|
||||
for (int i = 0; i < 4; ++i)
|
||||
bad += sorted[(size_t)T + i] != kPoison || off[(size_t)nl + 1 + i] != kPoison ||
|
||||
cnt[(size_t)nl + i] != kPoison || inv[(size_t)T + i] != kPoison;
|
||||
if (!with_inv)
|
||||
for (int i = 0; i < T; ++i) bad += inv[(size_t)i] != kPoison;
|
||||
for (int r = 0; r < M + 2; ++r)
|
||||
for (int c = 0; c < gp; ++c) {
|
||||
const uint16_t want = sh.gate && r < M && c == 0 ? 0x3f80 : kGatePoison;
|
||||
bad += gate[(size_t)r * gp + c] != want;
|
||||
}
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf(
|
||||
"FAIL router_sigmoid_topk_scatter at M=%d ne=%d k=%d mode %d slice %d+%d%s%s%s "
|
||||
"(rc %d, %d mismatching outputs)\n",
|
||||
M, ne, k, sh.mode, base, nl, sh.protect ? " protect " : "",
|
||||
sh.protect ? sh.protect : "", with_inv ? " with inverse" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Past the sort's one workgroup: refused, nothing written. */
|
||||
{
|
||||
const int M = 129, ne = 288, k = 8;
|
||||
std::vector<float> lg((size_t)M * ne, 0.5f), bias((size_t)ne, 0.f),
|
||||
w((size_t)M * k, -7.25f);
|
||||
std::vector<int32_t> ids((size_t)M * k, kPoison), sorted((size_t)M * k, kPoison),
|
||||
off((size_t)ne + 1, kPoison), cnt((size_t)ne, kPoison);
|
||||
RadTensor t[7]{};
|
||||
auto mat = [](RadTensor& x, void* d, uint32_t dt, int r, int c) {
|
||||
x.data = d;
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = c;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
auto vec = [](RadTensor& x, void* d, int n) {
|
||||
x.data = d;
|
||||
x.dtype = RAD_I32;
|
||||
x.rank = 1;
|
||||
x.shape[0] = n;
|
||||
x.stride[0] = 1;
|
||||
};
|
||||
mat(t[0], lg.data(), RAD_F32, M, ne);
|
||||
t[1].data = bias.data();
|
||||
t[1].dtype = RAD_F32;
|
||||
t[1].rank = 1;
|
||||
t[1].shape[0] = ne;
|
||||
t[1].stride[0] = 1;
|
||||
mat(t[2], ids.data(), RAD_I32, M, k);
|
||||
mat(t[3], w.data(), RAD_F32, M, k);
|
||||
vec(t[4], sorted.data(), M * k);
|
||||
vec(t[5], off.data(), ne + 1);
|
||||
vec(t[6], cnt.data(), ne);
|
||||
RadParam p[6]{};
|
||||
p[0] = { "M", RAD_P_INT, M };
|
||||
p[1] = { "n_expert", RAD_P_INT, ne };
|
||||
p[2] = { "top_k", RAD_P_INT, k };
|
||||
p[3] = { "norm", RAD_P_INT, 1 };
|
||||
p[4].key = "route_scale";
|
||||
p[4].kind = RAD_P_F64;
|
||||
p[4].dval = 2.5;
|
||||
p[5].key = "dtype";
|
||||
p[5].kind = RAD_P_STR;
|
||||
p[5].sval = "f32";
|
||||
RadArgs a{};
|
||||
a.t = t;
|
||||
a.n_t = 7;
|
||||
a.p = p;
|
||||
a.n_p = 6;
|
||||
++cases;
|
||||
const int rc = halo_rad_router_sigmoid_topk_scatter(&a, nullptr);
|
||||
if (rc == RAD_OK || ids[0] != kPoison || sorted[0] != kPoison) {
|
||||
std::printf("FAIL router_sigmoid_topk_scatter served M*top_k=%d past the sort's bound "
|
||||
"(rc %d)\n",
|
||||
M * k, rc);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct QuantShape {
|
||||
int M, n;
|
||||
float limit;
|
||||
int mode; /* 0 random past the clamp, 1 clamp edges and zero groups, 2 NaN and inf */
|
||||
bool y; /* the fused op also writes the bf16 product */
|
||||
};
|
||||
|
||||
void swiglu_quant_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const QuantShape shapes[] = {
|
||||
{ 1, 256, 10.f, 0, false }, { 8, 256, 10.f, 0, true }, { 48, 256, 10.f, 1, false },
|
||||
{ 384, 256, 10.f, 0, false }, { 6, 1536, 10.f, 0, true }, { 3, 2048, 10.f, 1, true },
|
||||
{ 5, 132, 7.f, 1, true }, { 7, 4, 10.f, 0, true }, { 9, 256, 10.f, 2, true },
|
||||
{ 2, 260, 0.5f, 2, false },
|
||||
};
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_int_distribution<int> ud(0, 15);
|
||||
for (const QuantShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, nkb = (n + 127) / 128;
|
||||
const int gp = 2 * n + 6, yp = n + 5, qp = n + 8, sp = nkb + 3;
|
||||
std::vector<uint16_t> gu((size_t)M * gp, f2b(-3.f));
|
||||
const uint16_t lim = f2b(sh.limit), past = (uint16_t)(lim + 1);
|
||||
for (int r = 0; r < M; ++r)
|
||||
for (int c = 0; c < 2 * n; ++c) {
|
||||
float v = nd(rng) * 6.f;
|
||||
uint16_t h = f2b(v);
|
||||
if (sh.mode == 1) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = lim;
|
||||
else if (pick == 1)
|
||||
h = past;
|
||||
else if (pick == 2)
|
||||
h = (uint16_t)(lim | 0x8000u);
|
||||
else if (pick == 3)
|
||||
h = (uint16_t)(past | 0x8000u);
|
||||
else if (pick == 4)
|
||||
h = f2b(-200.f);
|
||||
/* rows divisible by 3 hold an all-zero first group */
|
||||
if (r % 3 == 0 && (c % n) < 128) h = (c < n && (c & 1)) ? f2b(-0.f) : 0;
|
||||
} else if (sh.mode == 2) {
|
||||
const int pick = ud(rng);
|
||||
if (pick == 0)
|
||||
h = 0x7fc0; /* NaN */
|
||||
else if (pick == 1)
|
||||
h = 0x7f80; /* +inf */
|
||||
else if (pick == 2)
|
||||
h = 0xff80; /* -inf */
|
||||
}
|
||||
gu[(size_t)r * gp + c] = h;
|
||||
}
|
||||
RadTensor t[4]{};
|
||||
t[0].data = gu.data();
|
||||
t[0].dtype = RAD_BF16;
|
||||
t[0].rank = 2;
|
||||
t[0].shape[0] = M;
|
||||
t[0].shape[1] = 2 * n;
|
||||
t[0].stride[0] = gp;
|
||||
t[0].stride[1] = 1;
|
||||
auto mat = [](RadTensor& x, uint32_t dt, int r, int c, int pitch) {
|
||||
x.dtype = dt;
|
||||
x.rank = 2;
|
||||
x.shape[0] = r;
|
||||
x.shape[1] = c;
|
||||
x.stride[0] = pitch;
|
||||
x.stride[1] = 1;
|
||||
};
|
||||
RadParam pc[4]{};
|
||||
pc[0] = { "M", RAD_P_INT, M };
|
||||
pc[1] = { "n", RAD_P_INT, n };
|
||||
pc[2].key = "limit";
|
||||
pc[2].kind = RAD_P_F64;
|
||||
pc[2].dval = sh.limit;
|
||||
pc[3].key = "dtype";
|
||||
pc[3].kind = RAD_P_STR;
|
||||
pc[3].sval = "bf16";
|
||||
RadParam pq[4]{};
|
||||
pq[0] = { "M", RAD_P_INT, M };
|
||||
pq[1] = { "n", RAD_P_INT, n };
|
||||
pq[2] = { "group", RAD_P_INT, 128 };
|
||||
pq[3].key = "dtype";
|
||||
pq[3].kind = RAD_P_STR;
|
||||
pq[3].sval = "bf16";
|
||||
RadParam pf[5]{};
|
||||
pf[0] = pc[0];
|
||||
pf[1] = pc[1];
|
||||
pf[2] = pc[2];
|
||||
pf[3] = pq[2];
|
||||
pf[4] = pc[3];
|
||||
|
||||
std::vector<uint16_t> y_ref((size_t)M * yp, 0x7e57), y((size_t)M * yp, 0x7e57);
|
||||
std::vector<uint8_t> q_ref((size_t)M * qp, 0xa5), q((size_t)M * qp, 0xa5);
|
||||
std::vector<float> s_ref((size_t)M * sp, -7.25f), s((size_t)M * sp, -7.25f);
|
||||
RadTensor tc[2] = { t[0], {} };
|
||||
mat(tc[1], RAD_BF16, M, n, yp);
|
||||
tc[1].data = y_ref.data();
|
||||
RadArgs ac{};
|
||||
ac.t = tc;
|
||||
ac.n_t = 2;
|
||||
ac.p = pc;
|
||||
ac.n_p = 4;
|
||||
RadTensor tq[3] = { tc[1], {}, {} };
|
||||
mat(tq[1], RAD_F8E4M3, M, n, qp);
|
||||
tq[1].data = q_ref.data();
|
||||
mat(tq[2], RAD_F32, M, nkb, sp);
|
||||
tq[2].data = s_ref.data();
|
||||
RadArgs aq{};
|
||||
aq.t = tq;
|
||||
aq.n_t = 3;
|
||||
aq.p = pq;
|
||||
aq.n_p = 4;
|
||||
++cases;
|
||||
if (halo_rad_swiglu_clamped(&ac, nullptr) != RAD_OK ||
|
||||
halo_rad_quant_act_fp8(&aq, nullptr) != RAD_OK) {
|
||||
std::printf("FAIL swiglu_clamped + quant_act_fp8 launch M=%d n=%d\n", M, n);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
RadTensor tf[4] = { t[0], {}, {}, {} };
|
||||
mat(tf[1], RAD_F8E4M3, M, n, qp);
|
||||
tf[1].data = q.data();
|
||||
mat(tf[2], RAD_F32, M, nkb, sp);
|
||||
tf[2].data = s.data();
|
||||
mat(tf[3], RAD_BF16, M, n, yp);
|
||||
tf[3].data = sh.y ? y.data() : nullptr;
|
||||
RadArgs af{};
|
||||
af.t = tf;
|
||||
af.n_t = 4;
|
||||
af.p = pf;
|
||||
af.n_p = 5;
|
||||
const int rc = halo_rad_swiglu_clamped_quant_fp8(&af, nullptr);
|
||||
int bad = 0;
|
||||
bad += q != q_ref;
|
||||
bad += std::memcmp(s.data(), s_ref.data(), s.size() * 4) != 0;
|
||||
if (sh.y)
|
||||
bad += y != y_ref;
|
||||
else
|
||||
for (uint16_t v : y) bad += v != 0x7e57;
|
||||
if (rc != RAD_OK || bad) {
|
||||
std::printf("FAIL swiglu_clamped_quant_fp8 at M=%d n=%d limit %g mode %d%s (rc %d, %d "
|
||||
"mismatching outputs)\n",
|
||||
M, n, (double)sh.limit, sh.mode, sh.y ? " with bf16" : "", rc, bad);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct GatherShape {
|
||||
int M, n, nl, base;
|
||||
bool f32w; /* GLM's f32 routing weights, else bf16 */
|
||||
int shared; /* 0 none, 1 the ungated arm (gate 1, act none), 2 a sigmoid gate */
|
||||
};
|
||||
|
||||
/* moe_gather's kernel (halo_moe_gather.h) as its launcher runs it, reading the table moe_scatter_inv
|
||||
* wrote, against the same kernel building the table itself from `sorted` (T <= 512) or reading the
|
||||
* prepass's table (above). Ids are distinct per row from 288 experts, a slice drops slots. */
|
||||
void gather_inverse_cases(std::mt19937& rng, int& cases, int& fails) {
|
||||
const GatherShape shapes[] = {
|
||||
{ 1, 4096, 288, 0, true, 1 }, { 6, 4096, 288, 0, true, 1 }, { 8, 512, 288, 0, true, 1 },
|
||||
{ 24, 512, 144, 72, true, 1 }, { 48, 256, 288, 0, true, 1 }, { 64, 256, 288, 0, true, 0 },
|
||||
{ 100, 256, 96, 0, true, 1 }, { 6, 300, 288, 0, false, 2 }, { 33, 256, 288, 0, false, 0 },
|
||||
};
|
||||
const int k = 8, ne = 288;
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
for (const GatherShape& sh : shapes) {
|
||||
const int M = sh.M, n = sh.n, T = M * k, nl = sh.nl;
|
||||
std::vector<int32_t> ids((size_t)T);
|
||||
for (int r = 0; r < M; ++r) {
|
||||
std::vector<int32_t> pool(ne);
|
||||
for (int e = 0; e < ne; ++e) pool[(size_t)e] = e;
|
||||
std::shuffle(pool.begin(), pool.end(), rng);
|
||||
for (int j = 0; j < k; ++j) ids[(size_t)(r * k + j)] = pool[(size_t)j];
|
||||
}
|
||||
Scatter plain = scatter_kernel(ids, nl, sh.base, nullptr, false);
|
||||
Scatter inv = scatter_kernel(ids, nl, sh.base, nullptr, true);
|
||||
++cases;
|
||||
if (plain.rc != RAD_OK || inv.rc != RAD_OK || inv.sorted != plain.sorted ||
|
||||
inv.off != plain.off || inv.cnt != plain.cnt || inv.inv != inverse_of(plain.sorted)) {
|
||||
std::printf("FAIL moe_scatter with the inverse at M=%d slice %d+%d\n", M, sh.base, nl);
|
||||
++fails;
|
||||
continue;
|
||||
}
|
||||
const int ye_ld = n + 3, ew_ld = k + 2, y_ld = n + 5, sh_ld = n + 1, sg_ld = 2;
|
||||
std::vector<uint16_t> ye((size_t)T * ye_ld), shp((size_t)M * sh_ld), sg((size_t)M * sg_ld);
|
||||
for (auto& v : ye) v = f2b(nd(rng));
|
||||
for (auto& v : shp) v = f2b(nd(rng));
|
||||
for (size_t i = 0; i < sg.size(); ++i) sg[i] = sh.shared == 1 ? f2b(1.f) : f2b(nd(rng));
|
||||
std::vector<float> ewf((size_t)M * ew_ld);
|
||||
std::vector<uint16_t> ewb((size_t)M * ew_ld);
|
||||
for (size_t i = 0; i < ewf.size(); ++i) {
|
||||
ewf[i] = std::fabs(nd(rng)) * 0.3f;
|
||||
ewb[i] = f2b(ewf[i]);
|
||||
}
|
||||
const void* ew = sh.f32w ? (const void*)ewf.data() : (const void*)ewb.data();
|
||||
const uint16_t* shv = sh.shared ? shp.data() : nullptr;
|
||||
const uint16_t* sgv = sh.shared ? sg.data() : nullptr;
|
||||
const int sig = sh.shared == 2;
|
||||
const bool small = T <= (int)halo_moegather::kGatherSelfT;
|
||||
/* the launcher's rule: the self-scan up to 512 slots, the prepass's table above */
|
||||
const std::vector<int32_t> table = inverse_of(plain.sorted);
|
||||
const unsigned gy = (unsigned)((n + 255) / 256);
|
||||
auto gather = [&](const int32_t* tab, const int32_t* sorted, std::vector<uint16_t>& y) {
|
||||
y.assign((size_t)M * y_ld, 0x7e57);
|
||||
if (sh.f32w)
|
||||
HALO_EMIT(nullptr, (halo_moegather::gather_kernel<256, true>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
else
|
||||
HALO_EMIT(nullptr, (halo_moegather::gather_kernel<256, false>), dim3((unsigned)M, gy),
|
||||
dim3(256), 0, ye.data(), ew, tab, y.data(), (uint32_t)M, (uint32_t)n,
|
||||
(uint32_t)k, (uint32_t)ye_ld, (uint32_t)ew_ld, (uint32_t)y_ld, sorted,
|
||||
(uint32_t)T, shv, sgv, (uint32_t)sh_ld, (uint32_t)sg_ld, sig);
|
||||
};
|
||||
std::vector<uint16_t> y_old, y_new;
|
||||
if (small)
|
||||
gather(nullptr, plain.sorted.data(), y_old);
|
||||
else
|
||||
gather(table.data(), nullptr, y_old);
|
||||
gather(inv.inv.data(), nullptr, y_new);
|
||||
++cases;
|
||||
if (y_new != y_old) {
|
||||
size_t first = 0;
|
||||
while (first < y_new.size() && y_new[first] == y_old[first]) ++first;
|
||||
std::printf("FAIL moe_gather from the inverse at M=%d n=%d slice %d+%d %s weights, "
|
||||
"shared %d: first difference at %zu\n",
|
||||
M, n, sh.base, nl, sh.f32w ? "f32" : "bf16", sh.shared, first);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
std::mt19937 rng(23);
|
||||
int fails = 0, cases = 0;
|
||||
router_scatter_cases(rng, cases, fails);
|
||||
swiglu_quant_cases(rng, cases, fails);
|
||||
gather_inverse_cases(rng, cases, fails);
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,426 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_moemx.cpp): the MXFP4 expert GEMM (halo_moe_mxfp4.hip) on the host SIMT emulator. The form the
|
||||
* rule picks at each case (named per case, so a moved bound shows) must match a host restatement
|
||||
* of the per-element sequence bit for bit: per 128 of K in order, per 32-wide group a fresh
|
||||
* 32-product sum in k order (the emulated WMMA pair), folded as raw * activation scale * E8M0
|
||||
* scale with two roundings and an add. Away from GLM's slices the expert-major forms (K 256 and a
|
||||
* longer K) and the row groups; at GLM's TP4 down slice the GLM prefill form, at its TP8 gate_up
|
||||
* slice the P64 form with streamed A. Runs of 0, 1, 15, 16, 17, 63, 64, 65 and 130 rows, dropped
|
||||
* slots inside runs and past the routed rows, columns an odd expert does not have, a shorter K for
|
||||
* odd experts, E8M0 codes 0 and 255, parts 2, token and sorted rows, stacked planes and pointer
|
||||
* tables. At GLM's TP8 slices below P64 the small-M form, with runs longer than one tile. The
|
||||
* table decode is also held to the arithmetic one over every code.
|
||||
*
|
||||
* libhalo serves every one of these shapes with one kernel (mx_moe_kernel in halo_moe_mxfp4.hip),
|
||||
* so this copy does not assert which libr4d form ran; each case's output is still held to the host
|
||||
* restatement bit for bit. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
#include "halo_mxfp4.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
/* The bytewise arithmetic decode, the reference of halo_mxfp4_unpack8_exact: per byte, magnitudes
|
||||
* from 2 map to (m + 12) * 4, 0 and 1 to 0 and 48, the sign to bit 7; then the low and high
|
||||
* nibbles' bytes interleave in k order. */
|
||||
static uint32_t fp4x4_ref(uint32_t n) {
|
||||
const uint32_t mag = n & 0x07070707u, flag = (mag + 0x06060606u) & 0x08080808u;
|
||||
const uint32_t mask = (flag << 5) - (flag >> 3);
|
||||
return (((mag + 0x0c0c0c0cu) << 2) & mask) | (((mag & 0x01010101u) * 0x30u) & ~mask) |
|
||||
((n & 0x08080808u) << 4);
|
||||
}
|
||||
static int check_decode() {
|
||||
int fails = 0;
|
||||
auto one = [&](uint32_t w) {
|
||||
const uint32_t low = fp4x4_ref(w & 0x0f0f0f0fu), high = fp4x4_ref((w >> 4) & 0x0f0f0f0fu);
|
||||
const uint32_t lo_ref = __byte_perm(low, high, 0x5140),
|
||||
hi_ref = __byte_perm(low, high, 0x7362);
|
||||
uint32_t lo, hi, tlo, thi;
|
||||
halo_mxfp4_unpack8_exact(w, &lo, &hi);
|
||||
halo_mxfp4_unpack8(w, 0, &tlo, &thi);
|
||||
if (lo != lo_ref || hi != hi_ref || lo != tlo || hi != thi) {
|
||||
if (fails < 4)
|
||||
std::printf("FAIL decode of %08x: table %08x %08x, arithmetic %08x %08x\n", w, hi,
|
||||
lo, hi_ref, lo_ref);
|
||||
++fails;
|
||||
}
|
||||
/* each byte against the e2m1 value it encodes */
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const uint32_t c = (w >> (4 * e)) & 15u;
|
||||
static const float mag[8] = { 0.f, .5f, 1.f, 1.5f, 2.f, 3.f, 4.f, 6.f };
|
||||
const float want = (c & 8u ? -1.f : 1.f) * mag[c & 7u];
|
||||
const uint8_t b = (uint8_t)(((e < 4 ? lo : hi) >> (8 * (e & 3))) & 0xffu);
|
||||
if (rad_fp8e4m3_to_f32(b) != want || (b & 0x80u) != (c & 8u ? 0x80u : 0u)) {
|
||||
if (fails < 4) std::printf("FAIL code %x at element %d -> byte %02x\n", c, e, b);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
};
|
||||
/* the bytes decode independently: every pair of adjacent bytes exhaustively, at both halves
|
||||
* of the word, and random words over all four */
|
||||
for (uint32_t v = 0; v < 65536; ++v) {
|
||||
one(v);
|
||||
one(v << 16);
|
||||
one(v << 8);
|
||||
}
|
||||
std::mt19937 rng(7);
|
||||
for (int i = 0; i < 200000; ++i) one((uint32_t)rng());
|
||||
return fails;
|
||||
}
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
int N, K, N_odd, K_odd, parts, top;
|
||||
bool sorted_a, tables, exceptional;
|
||||
std::vector<int> runs;
|
||||
int tail; // dropped slots past the routed rows
|
||||
const char* kernel; // the form the rule picks
|
||||
};
|
||||
|
||||
/* Byte equality with every bf16 NaN taken as one value. On x86 inf - inf gives the negative
|
||||
* default NaN, and an add of two NaNs returns its first operand, whose side the compiler may swap;
|
||||
* the card generates the positive quiet NaN, so a NaN's sign carries no information here. */
|
||||
static bool nan16(uint16_t v) { return (v & 0x7f80u) == 0x7f80u && (v & 0x7fu); }
|
||||
static size_t first_diff(const std::vector<uint16_t>& a, const std::vector<uint16_t>& b) {
|
||||
for (size_t i = 0; i < a.size() && i < b.size(); ++i)
|
||||
if (a[i] != b[i] && !(nan16(a[i]) && nan16(b[i]))) return i;
|
||||
return a.size() == b.size() ? a.size() : std::min(a.size(), b.size());
|
||||
}
|
||||
|
||||
static RadTensor ten(void* p, uint32_t dt, std::vector<int64_t> shape,
|
||||
std::vector<int64_t> stride) {
|
||||
RadTensor t{};
|
||||
t.data = p;
|
||||
t.dtype = dt;
|
||||
t.rank = (uint32_t)shape.size();
|
||||
for (size_t i = 0; i < shape.size(); ++i) {
|
||||
t.shape[i] = shape[i];
|
||||
t.stride[i] = stride[i];
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/* GLM's 288 experts: the given runs at experts spread over both classes, every other one empty. */
|
||||
static std::vector<int> glm_runs(std::vector<int> live) {
|
||||
static const int at[] = { 2, 3, 50, 101, 150, 199, 200, 241, 286, 287 };
|
||||
std::vector<int> runs(288, 0);
|
||||
for (size_t i = 0; i < live.size() && i < sizeof at / sizeof at[0]; ++i) runs[at[i]] = live[i];
|
||||
return runs;
|
||||
}
|
||||
|
||||
int main() {
|
||||
int fails = check_decode(), cases = 1;
|
||||
if (fails) std::printf("FAIL table decode: %d mismatches\n", fails);
|
||||
|
||||
const std::vector<int> runs9 = { 0, 1, 15, 16, 17, 63, 64, 65, 130, 141 };
|
||||
const char* const staged = "(moe_mxfp4_expert_staged_kernel<128, 4>)";
|
||||
const char* const expert = "(moe_mxfp4_expert_kernel<4, 256>)";
|
||||
const char* const groups = "moe_mxfp4_fp8_kernel";
|
||||
const Case all[] = {
|
||||
{ "gate_up-like, token rows", 128, 384, 128, 384, 2, 4, false, false, false, runs9, 6,
|
||||
groups },
|
||||
{ "odd experts narrower and shorter", 128, 384, 64, 256, 2, 4, false, true, false, runs9,
|
||||
2, groups },
|
||||
{ "down-like, sorted rows", 64, 256, 64, 256, 1, 2, true, true, false, runs9, 4, groups },
|
||||
{ "exceptional E8M0 codes", 64, 256, 64, 256, 2, 4, false, false, true, runs9, 4, groups },
|
||||
{ "expert-major, K 384",
|
||||
64,
|
||||
384,
|
||||
64,
|
||||
384,
|
||||
2,
|
||||
2,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
{ 0, 1, 15, 16, 17, 30 },
|
||||
3,
|
||||
expert },
|
||||
{ "expert-major, K 256, exceptional codes",
|
||||
64,
|
||||
256,
|
||||
32,
|
||||
256,
|
||||
1,
|
||||
2,
|
||||
true,
|
||||
false,
|
||||
true,
|
||||
{ 1, 0, 3, 15, 1 },
|
||||
2,
|
||||
staged },
|
||||
{ "expert-major, K 512:384, runs past 64 rows, N under a block",
|
||||
96,
|
||||
512,
|
||||
96,
|
||||
384,
|
||||
1,
|
||||
2,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
{ 32, 33, 31, 96, 128, 129, 0, 2 },
|
||||
9,
|
||||
expert },
|
||||
{ "expert-major, K 256:128, column tiles cut",
|
||||
192,
|
||||
256,
|
||||
128,
|
||||
128,
|
||||
2,
|
||||
4,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
{ 64, 63, 65, 1, 0, 127, 17 },
|
||||
5,
|
||||
staged },
|
||||
{ "GLM TP4 down, the GLM prefill form",
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 63, 96, 1, 130, 32, 31, 33, 64, 65 }),
|
||||
13,
|
||||
"moe_mxfp4_prefill_kernel" },
|
||||
{ "GLM TP8 gate_up, P64 BM32 BN64 K256",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 200, 33, 300, 31, 200 }),
|
||||
20,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 256, 1, false>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, four tokens",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
glm_runs({ 1, 2, 1, 3, 1, 6, 1, 2, 9, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 gate_up, small-M form, runs past one tile",
|
||||
512,
|
||||
4096,
|
||||
512,
|
||||
4096,
|
||||
2,
|
||||
8,
|
||||
false,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 12, 1, 16, 17, 3, 0, 5, 9, 2, 33 }),
|
||||
2,
|
||||
"(moe_mxfp4_small_kernel<512, 1>)" },
|
||||
{ "GLM TP8 down, small-M form, a run past one tile",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 3, 1, 17, 2, 1, 1, 1 }),
|
||||
5,
|
||||
"(moe_mxfp4_small_kernel<256, 4>)" },
|
||||
{ "GLM TP8 down, P64 BM32 BN64 K128 x4, A resident",
|
||||
4096,
|
||||
256,
|
||||
4096,
|
||||
256,
|
||||
1,
|
||||
8,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
glm_runs({ 900, 801, 779, 700, 700, 581, 600, 600, 63, 1 }),
|
||||
40,
|
||||
"(moe_mxfp4_p64_kernel<32, 64, 128, 4, true>)" },
|
||||
};
|
||||
|
||||
for (const Case& c : all) {
|
||||
const int E = (int)c.runs.size(), NK = std::max(c.K, c.K_odd), OUT = std::max(c.N, c.N_odd);
|
||||
int routed = 0;
|
||||
for (int r : c.runs) routed += r;
|
||||
const int T = (routed + c.tail + c.top - 1) / c.top * c.top;
|
||||
// An odd pitch on every other case: the LDS output's 16-byte stores need an aligned row.
|
||||
const int Arows = c.sorted_a ? T : T / c.top, ap = NK + 16, asp = NK / 128 + 1,
|
||||
yp = OUT + ((&c - all) % 2 ? 5 : 8);
|
||||
std::mt19937 rng(1000 + cases);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> oct(-6.f, 6.f);
|
||||
std::vector<uint8_t> a((size_t)Arows * ap);
|
||||
for (auto& v : a) v = rad_f32_to_fp8e4m3(nd(rng) * 2.f);
|
||||
std::vector<float> as((size_t)Arows * asp);
|
||||
for (auto& v : as) v = std::exp2(oct(rng));
|
||||
std::vector<int> offsets(E + 1, 0), sorted(T, -1), owner(T, -1);
|
||||
for (int e = 0; e < E; ++e) offsets[e + 1] = offsets[e] + c.runs[e];
|
||||
for (int e = 0; e < E; ++e)
|
||||
for (int r = offsets[e]; r < offsets[e + 1]; ++r) {
|
||||
owner[r] = e;
|
||||
// A dropped slot about every eleventh row, the first rows of some runs included.
|
||||
sorted[r] = (r * 13 + e) % 11 == 0 ? -1 : (int)(rng() % (uint32_t)T);
|
||||
}
|
||||
/* Stacked planes hold every expert; a pointer table names one of at most three slices a
|
||||
* class, so GLM's 288 experts stay small. */
|
||||
const int n[2] = { c.N, c.N_odd }, k[2] = { c.K, c.K_odd },
|
||||
nexp[2] = { (E + 1) / 2, E / 2 };
|
||||
std::vector<uint8_t> w[2], s[2];
|
||||
std::vector<const void*> wt[2], st[2];
|
||||
std::vector<std::vector<float>> wf[2];
|
||||
int slices[2];
|
||||
for (int q = 0; q < 2; ++q) {
|
||||
slices[q] = c.tables ? std::min(nexp[q], 3) : nexp[q];
|
||||
w[q].resize((size_t)slices[q] * n[q] * k[q] / 2);
|
||||
s[q].resize((size_t)slices[q] * n[q] * k[q] / 32);
|
||||
for (auto& v : w[q]) v = (uint8_t)rng();
|
||||
static const uint8_t special[] = { 0, 255, 1, 254, 127 };
|
||||
for (size_t i = 0; i < s[q].size(); ++i)
|
||||
s[q][i] = c.exceptional && rng() % 9 == 0 ? special[rng() % 5]
|
||||
: (uint8_t)(118 + rng() % 16);
|
||||
for (int x = 0; x < nexp[q]; ++x) {
|
||||
wt[q].push_back(w[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 2);
|
||||
st[q].push_back(s[q].data() + (size_t)(x % slices[q]) * n[q] * k[q] / 32);
|
||||
}
|
||||
/* each slice's codes as the E4M3 values the table decode gives */
|
||||
for (int x = 0; x < slices[q]; ++x) {
|
||||
std::vector<float> f((size_t)n[q] * k[q]);
|
||||
const uint8_t* src = w[q].data() + (size_t)x * n[q] * k[q] / 2;
|
||||
for (size_t i = 0; i < f.size(); ++i) {
|
||||
uint32_t lo, hi;
|
||||
halo_mxfp4_unpack8_exact((src[i / 2] >> (4 * (i & 1))) & 15u, &lo, &hi);
|
||||
f[i] = rad_fp8e4m3_to_f32((uint8_t)(lo & 0xffu));
|
||||
}
|
||||
wf[q].push_back(std::move(f));
|
||||
}
|
||||
}
|
||||
auto plane = [&](int q, bool scale) {
|
||||
const int64_t cols = scale ? k[q] / 32 : k[q];
|
||||
void* p = c.tables ? (void*)(scale ? st[q].data() : wt[q].data())
|
||||
: (void*)(scale ? s[q].data() : w[q].data());
|
||||
RadTensor t = ten(p, scale ? RAD_E8M0 : RAD_FP4E2M1, { nexp[q], n[q], cols },
|
||||
{ c.tables ? 0 : (int64_t)n[q] * cols, cols, 1 });
|
||||
return t;
|
||||
};
|
||||
|
||||
/* the per-element sequence, on the host */
|
||||
std::vector<float> af(a.size());
|
||||
for (size_t i = 0; i < a.size(); ++i) af[i] = rad_fp8e4m3_to_f32(a[i]);
|
||||
std::vector<uint16_t> ref((size_t)T * yp, 0x7777);
|
||||
for (int r = 0; r < T; ++r)
|
||||
for (int col = 0; col < OUT; ++col) {
|
||||
uint16_t& out = ref[(size_t)r * yp + col];
|
||||
out = 0;
|
||||
if (owner[r] < 0 || sorted[r] < 0) continue;
|
||||
const int e = owner[r], q = e & 1, ar = c.sorted_a ? r : sorted[r] / c.top;
|
||||
const int pw = OUT / c.parts, cw = n[q] / c.parts, within = col % pw;
|
||||
const bool valid = within < cw;
|
||||
const int wn = (col / pw) * cw + within;
|
||||
const float* wr = wf[q][(size_t)((e / 2) % slices[q])].data() + (size_t)wn * k[q];
|
||||
const uint8_t* sr = (const uint8_t*)st[q][(size_t)(e / 2)] + (size_t)wn * k[q] / 32;
|
||||
const float* arow = af.data() + (size_t)ar * ap;
|
||||
float total = 0.f;
|
||||
for (int kb = 0; kb < k[q]; kb += 128)
|
||||
for (int g = 0; g < 4; ++g) {
|
||||
float raw = 0.f;
|
||||
for (int kk = kb + g * 32; kk < kb + g * 32 + 32; ++kk)
|
||||
raw += arow[kk] * (valid ? wr[kk] : 0.f);
|
||||
const uint32_t x = valid ? sr[kb / 32 + g] : 127u;
|
||||
uint32_t bits = x == 255 ? 0x7fc00000u : x ? x << 23 : 0x00400000u;
|
||||
float scale;
|
||||
std::memcpy(&scale, &bits, 4);
|
||||
float t = raw * as[(size_t)ar * asp + kb / 128];
|
||||
t = t * scale;
|
||||
total = total + t;
|
||||
}
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &total, 4);
|
||||
out = (uint16_t)((u + 0x7fffu + ((u >> 16) & 1u)) >>
|
||||
16); // f32_to_bf16, halo_common.h
|
||||
}
|
||||
int live = 0;
|
||||
for (uint16_t v : ref) live += v != 0 && v != 0x7777;
|
||||
if (live < T * OUT / 3) {
|
||||
std::printf("FAIL %s: output mostly zero\n", c.name);
|
||||
++fails;
|
||||
}
|
||||
|
||||
RadTensor t[9] = { ten(a.data(), RAD_F8E4M3, { Arows, NK }, { ap, 1 }),
|
||||
ten(as.data(), RAD_F32, { Arows, NK / 128 }, { asp, 1 }),
|
||||
plane(0, false),
|
||||
plane(0, true),
|
||||
ten(sorted.data(), RAD_I32, { T }, { 1 }),
|
||||
ten(offsets.data(), RAD_I32, { E + 1 }, { 1 }),
|
||||
plane(1, false),
|
||||
plane(1, true),
|
||||
RadTensor{} };
|
||||
RadParam p[11]{};
|
||||
auto pi = [](const char* key, long long v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_INT;
|
||||
x.ival = v;
|
||||
return x;
|
||||
};
|
||||
auto ps = [](const char* key, const char* v) {
|
||||
RadParam x{};
|
||||
x.key = key;
|
||||
x.kind = RAD_P_STR;
|
||||
x.sval = v;
|
||||
return x;
|
||||
};
|
||||
p[0] = pi("M", T / c.top);
|
||||
p[1] = pi("N", c.N);
|
||||
p[2] = pi("K", c.K);
|
||||
p[3] = pi("N_odd", c.N_odd);
|
||||
p[4] = pi("K_odd", c.K_odd);
|
||||
p[5] = pi("n_expert", E);
|
||||
p[6] = pi("top_k", c.top);
|
||||
p[7] = pi("parts", c.parts);
|
||||
p[8] = pi("group", 128);
|
||||
p[9] = ps("a_order", c.sorted_a ? "sorted" : "token");
|
||||
p[10] = ps("dtype", "mxfp4a8");
|
||||
std::vector<uint16_t> got((size_t)T * yp, 0x7777);
|
||||
t[8] = ten(got.data(), RAD_BF16, { T, OUT }, { yp, 1 });
|
||||
RadArgs ar{};
|
||||
ar.t = t;
|
||||
ar.n_t = 9;
|
||||
ar.p = p;
|
||||
ar.n_p = 11;
|
||||
emu_last_kernel = "";
|
||||
++cases;
|
||||
const int rc = halo_rad_moe_mxfp4(&ar, nullptr);
|
||||
const size_t i = first_diff(got, ref);
|
||||
if (rc != RAD_OK || i != got.size()) {
|
||||
std::printf("FAIL %s (T %d): ran %s (want %s), rc %d, first word %zu (row %zu col %zu: "
|
||||
"%04x, want %04x)\n",
|
||||
c.name, T, emu_last_kernel, c.kernel, rc, i, i / yp, i % yp,
|
||||
i < got.size() ? got[i] : 0, i < ref.size() ? ref[i] : 0);
|
||||
++fails;
|
||||
}
|
||||
}
|
||||
std::printf("%d case(s), %d failure(s)\n", cases, fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_norm.cpp): the sandwich-norm joins (halo_norm_join_bf16.hip) on the host SIMT emulator.
|
||||
*
|
||||
* Two references:
|
||||
* Chain: the unfused sequence the arch plugin would otherwise issue (rmsnorm, add, rmsnorm; or
|
||||
* rmsnorm x2, add, rmsnorm, add, mul_weight) in libhalo's per-element arithmetic, with sums of
|
||||
* squares in this kernel's block order. The fused kernel must match it bit for bit: fusing
|
||||
* changes only the launch count.
|
||||
* Host arm: sums in index order (as a different libr4d block width would) 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 libhalo's rmsnorm_quant_fp8 of the experts' norm: scale amax / 448
|
||||
* per 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 "halo_plugin.h"
|
||||
#include "ref_host.h"
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static std::mt19937 rng(11);
|
||||
|
||||
/* 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;
|
||||
}
|
||||
/* Difference from the host arm in units of the row's RMS. A different summation order moves the
|
||||
* norm factor by an f32 ulp, which flips the odd bf16 rounding; where the residual add cancels,
|
||||
* one ulp of the addend is many ulps of the small sum, so output ulps are the wrong yardstick. */
|
||||
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 (halo_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 (halo_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 at most an eighth of its value, so at most 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 (halo_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,234 @@
|
||||
/* tests/halo_emu: libhalo's paged attention rows (attn_paged: the decode and prefill bodies,
|
||||
* halo_attn_decode_h256_gqa6.hip and halo_attn_prefill_h256_gqa6.hip, through every unit that owns a
|
||||
* geometry) on the host SIMT emulator, against test_attn.cpp's port of libref's ref_attn_paged. The
|
||||
* operand construction and the reference are test_attn's (a shuffled block table with a spare
|
||||
* column, NaN in every slot past a context and every unnamed block, f64 accumulation); the rows come
|
||||
* from the row table (paged_rows.inc: every block-size-16 decode and prefill row, its launch, its
|
||||
* scratch hook and the q_len / window / causal its constraints allow). Decode at one token and at
|
||||
* verify heights, short and split-KV contexts, ragged batches, windows where a row takes one,
|
||||
* fp8 caches with and without per-head descales; prefill over ragged causal batches. */
|
||||
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_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;
|
||||
}
|
||||
|
||||
using Fn = int (*)(const RadArgs*, RadStream);
|
||||
struct Row {
|
||||
const char* name;
|
||||
Fn fn;
|
||||
int64_t (*scratch)(const RadArgs*);
|
||||
int hd, gqa;
|
||||
bool fp8;
|
||||
int qmax; /* the row's q_len bound */
|
||||
int win; /* 0: window EQ 0, 1: window GE 0, 2: window GE 1 */
|
||||
int causal1; /* the row requires causal */
|
||||
};
|
||||
#include "paged_rows.inc"
|
||||
|
||||
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 (rows without a hook) */
|
||||
int qpitch_extra = 0; /* q as a column slice of a wider buffer */
|
||||
};
|
||||
|
||||
static int run(const Row& r, 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", std::min(qmax + 3, r.qmax)); /* the band bound, above the step's max where the row allows */
|
||||
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);
|
||||
/* the host-visible context bound the split law needs (the engine always passes it) */
|
||||
pi("max_ctx", c.max_ctx ? c.max_ctx : (long long)maxb * 16);
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p.data(); a.n_p = (int)p.size();
|
||||
/* the split-KV scratch from the row's own hook, as the engine sizes it */
|
||||
std::vector<char> hook_scratch;
|
||||
if (r.scratch) {
|
||||
const int64_t need = r.scratch(&a);
|
||||
if (need < 0) { std::printf("%-44s scratch hook refused: %lld\n", c.name.c_str(), (long long)need); return 1; }
|
||||
hook_scratch.assign((size_t)need + 64, 0);
|
||||
a.scratch = hook_scratch.data() + ((16 - ((uintptr_t)hook_scratch.data() & 15)) & 15);
|
||||
a.scratch_bytes = need;
|
||||
} else {
|
||||
a.scratch = c.scratch ? sp : nullptr; a.scratch_bytes = c.scratch;
|
||||
}
|
||||
Fn fn = r.fn;
|
||||
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;
|
||||
/* The absolute floor scales with V: an fp8 cache is drawn at 4x a bf16 one's magnitude. */
|
||||
const double vscale = c.fp8 ? 4.0 : 1.0;
|
||||
if (e > 1e-2 * std::max(vscale, 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");
|
||||
return ok ? 0 : 1;
|
||||
}
|
||||
|
||||
int main(int argc, char** argv) {
|
||||
const char* only = argc > 1 ? argv[1] : nullptr;
|
||||
int fails = 0, cases = 0;
|
||||
for (const Row& r : kRows) {
|
||||
if (only && !std::strstr(r.name, only)) continue;
|
||||
const bool decode = std::strncmp(r.name, "attn_decode", 11) == 0;
|
||||
std::vector<Case> cs;
|
||||
auto add = [&](const char* tag, std::vector<int> ql, std::vector<int> ctx, bool causal, int window, bool descale) {
|
||||
Case c;
|
||||
c.name = std::string(r.name) + " " + tag;
|
||||
c.hd = r.hd; c.gqa = r.gqa; c.kvh = 2; c.fp8 = r.fp8;
|
||||
c.causal = r.causal1 ? true : causal;
|
||||
c.ragged = ql.size() > 1 || ql[0] > 1;
|
||||
c.descale = descale && r.fp8;
|
||||
c.window = window;
|
||||
c.qlen = ql; c.ctx = ctx;
|
||||
cs.push_back(c);
|
||||
};
|
||||
const int win = r.win == 2 ? 40 : 0;
|
||||
if (decode) {
|
||||
add("1 tok ctx 1", { 1 }, { 1 }, true, win, false);
|
||||
add("1 tok ctx 17", { 1 }, { 17 }, true, win, true);
|
||||
add("1 tok ctx 300", { 1 }, { 300 }, true, win, false);
|
||||
add("1 tok ctx 2049 (split)", { 1 }, { 2049 }, true, win, true);
|
||||
add("3 seqs ragged ctx", { 1, 1, 1 }, { 5, 64, 129 }, true, win, false);
|
||||
const int v = std::min(r.qmax, 4);
|
||||
add("verify", { v, 1 }, { 90, 33 }, true, win, true);
|
||||
if (r.win == 1) add("window 24", { 1, 2 }, { 200, 61 }, true, 24, false);
|
||||
if (!r.causal1) add("non-causal", { 1 }, { 77 }, false, 0, false);
|
||||
} else {
|
||||
add("prefill 37", { 37 }, { 37 }, true, win, false);
|
||||
add("prefill ragged", { 20, 1, 45 }, { 20, 9, 100 }, true, win, true);
|
||||
/* a short chunk over a long context: split-KV where the row has a scratch hook */
|
||||
add("prefill 11 ctx 2049", { 11 }, { 2049 }, true, win, true);
|
||||
add("prefill ragged ctx 1500", { 20, 1, 45 }, { 700, 9, 1500 }, true, win, false);
|
||||
if (r.win == 1) add("prefill window 16", { 30 }, { 50 }, true, 16, false);
|
||||
}
|
||||
for (const Case& c : cs) {
|
||||
if (std::getenv("HALO_EMU_TRACE")) { std::printf("-> %s\n", c.name.c_str()); std::fflush(stdout); }
|
||||
++cases; fails += run(r, c);
|
||||
}
|
||||
}
|
||||
std::printf("paged attention: %d case(s), %d failure(s)\n", cases, 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 "halo_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 = halo_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 = halo_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;
|
||||
}
|
||||
@@ -0,0 +1,659 @@
|
||||
/* tests/halo_emu (from tests/r4d_emu/test_qsa.cpp): the QSA block selection (halo_qsa_select_bf16.hip) on the host SIMT emulator, each
|
||||
* of its four kernels against a port of libref's ref_qsa_select, byte for byte: the page-id table
|
||||
* (sentinel-filled before every launch, the row pitch's padding and a row past M included), nsel
|
||||
* and seqused.
|
||||
*
|
||||
* Every fixture runs three ways: pinned to the single-workgroup kernel and pinned to the wide one,
|
||||
* both without scratch, and the launcher's own choice with the split path's scratch given (the
|
||||
* local + merge pair for a decode-shaped launch over several chunks, the wide kernel above 64 rows,
|
||||
* else the single-workgroup one). The kernel that ran is checked by name.
|
||||
*
|
||||
* The fixtures follow halo_selftest's qsa_select cases at sizes the emulator runs in seconds, plus a
|
||||
* seeded sweep of small odd shapes (NaN, +-inf, -0.0, denormal and -1e30 scores, pitches, a table
|
||||
* narrower than the scores, rows no sequence holds, topk 1, ratio 1). Which branch a row takes
|
||||
* inside the kernels is predicted from their constants, restated in `Path`; the run fails when the
|
||||
* fixtures stop reaching one of them. `sweep N` runs N seeded fixtures at serving sizes instead.
|
||||
*
|
||||
* Fixtures marked signed run with the op's `signed` parameter: the kernels' signed key order,
|
||||
* against the port's signed ranking, over negative, mixed and the sweep's odd scores. The unsigned
|
||||
* fixtures are the same as without the parameter. */
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include "halo_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" void halo_qsa_select_pin_form(int form);
|
||||
extern int emu_grids;
|
||||
extern const char* emu_last_kernel;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr int32_t kSentinel = 0x55555555;
|
||||
|
||||
struct Fix {
|
||||
std::string name;
|
||||
int S = 1, M = 1, nb_s = 1, nb_t = 1; /* sequences, query rows, score and table widths */
|
||||
int s_ld = 0, t_ld = 0, o_ld = 0; /* row pitches; 0 = tight */
|
||||
int topk = 1, ratio = 1;
|
||||
bool sgn = false; /* the op's `signed` parameter */
|
||||
std::vector<float> sc; /* [M][s_ld] */
|
||||
std::vector<int32_t> bt; /* [S][t_ld] */
|
||||
std::vector<int32_t> nc, pos, cu; /* [S], [M], [S + 1] */
|
||||
void shape(int s, int m, int nbs, int nbt, int tk, int r, int spad = 0, int tpad = 0, int opad = 0) {
|
||||
S = s; M = m; nb_s = nbs; nb_t = nbt; topk = tk; ratio = r;
|
||||
s_ld = nbs + spad; t_ld = nbt + tpad; o_ld = tk + 1 + opad;
|
||||
sc.assign((size_t)M * s_ld, -INFINITY);
|
||||
bt.assign((size_t)S * t_ld, -1);
|
||||
nc.assign((size_t)S, 0); pos.assign((size_t)M, 0); cu.assign((size_t)S + 1, 0);
|
||||
}
|
||||
float& score(int m, int b) { return sc[(size_t)m * s_ld + b]; }
|
||||
int32_t& page(int s, int b) { return bt[(size_t)s * t_ld + b]; }
|
||||
int nb() const { return std::min(nb_s, nb_t); }
|
||||
int seq_of(int m) const {
|
||||
for (int s = 0; s < S; ++s) if (m >= cu[s] && m < cu[s + 1]) return s;
|
||||
return 0;
|
||||
}
|
||||
int n_of(int m) const {
|
||||
const int s = seq_of(m);
|
||||
return (int)std::min<int64_t>(std::min<int64_t>(nc[s], nb()), ((int64_t)pos[m] + 1) / ratio);
|
||||
}
|
||||
};
|
||||
|
||||
/* ---- libref's ref_qsa_select (libref/ref_qsa.cpp), restated over the fixture's arrays: the same
|
||||
* steps in the same order, both rankings. */
|
||||
void ref_select(const Fix& f, std::vector<int32_t>& se, std::vector<int32_t>& ns, std::vector<int32_t>& su) {
|
||||
const int64_t topk = f.topk, ratio = f.ratio;
|
||||
se.assign((size_t)f.M * (topk + 1), 0); ns.assign((size_t)f.M, 0); su.assign((size_t)f.M, 0);
|
||||
for (int64_t m = 0; m < f.M; ++m) {
|
||||
const int64_t s = f.seq_of((int)m), p = f.pos[m];
|
||||
const int64_t n = std::min(std::min<int64_t>(f.nc[s], f.nb()), (p + 1) / ratio);
|
||||
std::vector<float> val((size_t)n);
|
||||
std::vector<int64_t> live;
|
||||
for (int64_t b = 0; b < n; ++b) {
|
||||
const float v = f.sc[(size_t)(m * f.s_ld + b)];
|
||||
if (f.bt[(size_t)(s * f.t_ld + b)] < 0) continue;
|
||||
if (f.sgn ? !std::isfinite(v) : !(v > -1e30f)) continue;
|
||||
val[(size_t)b] = f.sgn ? v : v > 0.0f ? v : 0.0f;
|
||||
live.push_back(b);
|
||||
}
|
||||
std::vector<int64_t> take;
|
||||
if ((int64_t)live.size() <= topk) {
|
||||
take = live;
|
||||
} else {
|
||||
std::vector<float> ord;
|
||||
for (int64_t b : live) ord.push_back(val[(size_t)b]);
|
||||
std::nth_element(ord.begin(), ord.begin() + (topk - 1), ord.end(), std::greater<float>());
|
||||
const float thr = ord[(size_t)(topk - 1)];
|
||||
for (int64_t b : live)
|
||||
if (val[(size_t)b] > thr) take.push_back(b);
|
||||
for (int64_t b : live)
|
||||
if ((int64_t)take.size() < topk && val[(size_t)b] == thr) take.push_back(b);
|
||||
}
|
||||
int32_t* row = &se[(size_t)(m * (topk + 1))];
|
||||
int64_t out = 0;
|
||||
for (int64_t b : take) row[out++] = f.bt[(size_t)(s * f.t_ld + b)];
|
||||
if (n < f.nb() && (p + 1) % ratio != 0) {
|
||||
const int32_t part = f.bt[(size_t)(s * f.t_ld + n)];
|
||||
if (part >= 0) row[out++] = part;
|
||||
}
|
||||
for (int64_t i = out; i <= topk; ++i) row[i] = -1;
|
||||
ns[(size_t)m] = (int32_t)out;
|
||||
su[(size_t)m] = (int32_t)(out == 0 ? 0 : (out - 1) * ratio + p % ratio + 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- Which branch a row takes inside the kernels: the launcher's and kernels' constants
|
||||
* (halo_qsa_select_bf16.hip) on a 64 KiB-LDS device, and their branch conditions. Coverage only: the
|
||||
* tables are checked against the port above whatever the prediction says. */
|
||||
namespace Path {
|
||||
constexpr int kCacheCap = 8192, kCacheMaxM = 64; /* the key cache */
|
||||
constexpr int kSamp = 2048, kSampRun = 32, kSampRuns = 64, kSampMinN = 3 * kSamp, kSampCap = 1920;
|
||||
constexpr int kWideShift = 19, kWideCand = 3840, kMergeAbove = 512, kMergeCand = 1664;
|
||||
constexpr int kWideShiftSigned = 20; /* the signed key's 32 bits */
|
||||
int wide_shift(bool sgn) { return sgn ? kWideShiftSigned : kWideShift; }
|
||||
constexpr int kParM = 32, kParWMax = 16, kParCap = 8192; /* the split path */
|
||||
int par_chunks(int nb) { return std::max(1, std::min(kParWMax, (nb + 4095) / 4096)); }
|
||||
}
|
||||
|
||||
uint32_t keyof(float v, int32_t page) {
|
||||
if (page < 0 || !(v > -1e30f)) return 0u;
|
||||
const float c = v > 0.0f ? v : 0.0f;
|
||||
uint32_t u;
|
||||
std::memcpy(&u, &c, 4);
|
||||
return u + 1u;
|
||||
}
|
||||
|
||||
/* The signed order: the float's total order over 32 bits, -0 keyed as +0, nonfinite dead. */
|
||||
uint32_t keyof_signed(float v, int32_t page) {
|
||||
if (page < 0 || !std::isfinite(v)) return 0u;
|
||||
uint32_t u = 0;
|
||||
if (v != 0.0f) std::memcpy(&u, &v, 4);
|
||||
return (u & 0x80000000u) ? ~u : (u ^ 0x80000000u);
|
||||
}
|
||||
|
||||
enum Form { kSingle, kWide, kAuto };
|
||||
const char* const kFormName[] = { "single", "wide", "auto" };
|
||||
|
||||
bool split_applies(const Fix& f) {
|
||||
const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch;
|
||||
return f.M <= Path::kParM && nch > 1 && chunk <= Path::kParCap && nch * f.topk <= Path::kParCap;
|
||||
}
|
||||
|
||||
std::map<std::string, int> g_paths;
|
||||
|
||||
/* The branches row m reaches under `form`. */
|
||||
void note_paths(const Fix& f, int m, Form form, bool split) {
|
||||
const int s = f.seq_of(m), n = f.n_of(m), topk = f.topk;
|
||||
std::vector<uint32_t> k((size_t)std::max(n, 0));
|
||||
for (int b = 0; b < n; ++b) {
|
||||
const float v = f.sc[(size_t)m * f.s_ld + b];
|
||||
const int32_t pg = f.bt[(size_t)s * f.t_ld + b];
|
||||
k[(size_t)b] = f.sgn ? keyof_signed(v, pg) : keyof(v, pg);
|
||||
}
|
||||
std::vector<uint32_t> live;
|
||||
for (uint32_t x : k) if (x) live.push_back(x);
|
||||
std::sort(live.begin(), live.end(), std::greater<uint32_t>());
|
||||
const int L = (int)live.size();
|
||||
auto hit = [](const char* p) { ++g_paths[p]; };
|
||||
if (n <= topk) hit("rows of at most topk blocks");
|
||||
else if (L == topk) hit("exactly topk live over more blocks");
|
||||
else if (L < topk) hit("fewer than topk live over more blocks");
|
||||
else {
|
||||
hit("a threshold");
|
||||
const uint32_t T = live[(size_t)topk - 1];
|
||||
int above = 0, eq = 0;
|
||||
for (uint32_t x : live) { above += x > T; eq += x == T; }
|
||||
if (eq > topk - above) hit("a threshold whose ties are cut short");
|
||||
if (f.sgn && T < 0x80000000u) hit("signed: a negative threshold");
|
||||
}
|
||||
if (split) {
|
||||
const int nch = Path::par_chunks(f.nb()), chunk = (f.nb() + nch - 1) / nch;
|
||||
int tot = 0;
|
||||
bool over = false;
|
||||
for (int c = 0; c < nch && c * chunk < n; ++c) {
|
||||
const int lo = c * chunk, hi = std::min(lo + chunk, n);
|
||||
int lc = 0;
|
||||
for (int b = lo; b < hi; ++b) lc += k[(size_t)b] != 0;
|
||||
over |= hi - lo > topk && lc > topk;
|
||||
tot += std::min(lc, topk);
|
||||
}
|
||||
if (n <= topk || (!over && tot <= topk)) hit("split: topk or fewer live, every one taken");
|
||||
else if (!over) hit("split: no chunk over topk, more than topk live");
|
||||
else if (tot == topk) hit("split: exactly topk candidates, from a chunk over topk");
|
||||
else hit("split: a chunk over topk");
|
||||
return;
|
||||
}
|
||||
if (form == kSingle || (form == kAuto && f.M <= Path::kCacheMaxM)) {
|
||||
const int cap = f.M <= Path::kCacheMaxM ? std::min(Path::kCacheCap, f.nb()) : 0;
|
||||
hit(n <= cap ? "single: keys cached in LDS" : "single: keys read from global memory");
|
||||
return;
|
||||
}
|
||||
if (n <= topk) return;
|
||||
if (n >= Path::kSampMinN && topk <= Path::kMergeAbove) {
|
||||
std::vector<uint32_t> smp;
|
||||
for (int i = 0; i < Path::kSamp; ++i) {
|
||||
const long b = (long)(i / Path::kSampRun) * (n - Path::kSampRun) / (Path::kSampRuns - 1) + i % Path::kSampRun;
|
||||
if (k[(size_t)b]) smp.push_back(k[(size_t)b]);
|
||||
}
|
||||
std::sort(smp.begin(), smp.end(), std::greater<uint32_t>());
|
||||
const uint32_t ms = std::min<uint32_t>(
|
||||
(uint32_t)(((uint64_t)topk * 2u * Path::kSamp + (uint64_t)n - 1u) / (uint64_t)n) + 8u, Path::kSamp);
|
||||
const uint32_t lo = smp.size() > ms ? smp[ms - 1] : 0u;
|
||||
int cnt = 0;
|
||||
for (uint32_t x : live) cnt += x >= lo;
|
||||
const bool vec = (((uintptr_t)&f.sc[(size_t)m * f.s_ld] | (uintptr_t)&f.bt[(size_t)s * f.t_ld]) & 15u) == 0;
|
||||
hit(vec ? "wide: the sampled pass, rows 16-byte aligned" : "wide: the sampled pass, rows not 16-byte aligned");
|
||||
if (cnt > topk && cnt <= Path::kSampCap) {
|
||||
hit(lo ? "wide: the sampled list" : "wide: the sampled list, holding every live key");
|
||||
return;
|
||||
}
|
||||
hit("wide: a sample that fell back");
|
||||
}
|
||||
if (L <= topk) return;
|
||||
const int shift = Path::wide_shift(f.sgn);
|
||||
const uint32_t B = live[(size_t)topk - 1] >> shift;
|
||||
int in = 0;
|
||||
for (uint32_t x : live) in += (x >> shift) == B;
|
||||
hit(in <= Path::kMergeCand && topk <= Path::kMergeAbove ? "wide: merged lists"
|
||||
: in <= Path::kWideCand ? "wide: the threshold's bin in LDS" : "wide: the threshold's bin over global memory");
|
||||
}
|
||||
|
||||
RadTensor tens(void* p, uint32_t dt, std::vector<int64_t> shape, int64_t ld = 0) {
|
||||
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]; }
|
||||
if (ld && t.rank == 2) t.stride[0] = ld;
|
||||
return t;
|
||||
}
|
||||
|
||||
/* One launch of `form` against the port. Returns the failures (0 or 1). */
|
||||
int run(Fix& f, Form form) {
|
||||
std::vector<int32_t> want, want_n, want_su;
|
||||
ref_select(f, want, want_n, want_su);
|
||||
const int M = f.M, W = f.topk + 1;
|
||||
std::vector<int32_t> se((size_t)(M + 1) * f.o_ld, kSentinel), ns((size_t)M + 1, kSentinel), su((size_t)M + 1, kSentinel);
|
||||
RadTensor t[8] = {
|
||||
tens(f.sc.data(), RAD_F32, {M, f.nb_s}, f.s_ld), tens(f.bt.data(), RAD_I32, {f.S, f.nb_t}, f.t_ld),
|
||||
tens(f.nc.data(), RAD_I32, {f.S}), tens(f.pos.data(), RAD_I32, {M}),
|
||||
tens(f.cu.data(), RAD_I32, {f.S + 1}), tens(se.data(), RAD_I32, {M, W}, f.o_ld),
|
||||
tens(ns.data(), RAD_I32, {M}), tens(su.data(), RAD_I32, {M}),
|
||||
};
|
||||
RadParam p[6]{};
|
||||
p[0] = {"M", RAD_P_INT, M}; p[1] = {"blocks", RAD_P_INT, f.nb()}; p[2] = {"topk", RAD_P_INT, f.topk};
|
||||
p[3] = {"ratio", RAD_P_INT, f.ratio}; p[4] = {"seqs", RAD_P_INT, f.S}; p[5] = {"signed", RAD_P_INT, 1};
|
||||
RadArgs a{}; a.t = t; a.n_t = 8; a.p = p; a.n_p = f.sgn ? 6 : 5;
|
||||
const int64_t need = halo_rad_qsa_select_scratch(&a);
|
||||
std::vector<uint32_t> scratch((size_t)(need / 4 + 1), 0xA5A5A5A5u);
|
||||
if (form == kAuto) { a.scratch = scratch.data(); a.scratch_bytes = need; }
|
||||
halo_qsa_select_pin_form(form == kSingle ? 1 : form == kWide ? 2 : 0);
|
||||
const int g0 = emu_grids;
|
||||
const int rc = halo_rad_qsa_select(&a, nullptr);
|
||||
halo_qsa_select_pin_form(0);
|
||||
const int grids = emu_grids - g0;
|
||||
const bool split = form == kAuto && split_applies(f);
|
||||
const char* expect = split ? "qsa_merge_kernel"
|
||||
: form == kWide || (form == kAuto && f.M > Path::kCacheMaxM) ? "qsa_select_wide_kernel"
|
||||
: "qsa_select_kernel";
|
||||
const char* fn = kFormName[form];
|
||||
if (rc != RAD_OK) { std::printf("FAIL %-48s %-6s launch returned %d\n", f.name.c_str(), fn, rc); return 1; }
|
||||
/* The launch site names the template, `kernel<Signed>`: the name is what precedes it. */
|
||||
const std::string ran(emu_last_kernel, std::strcspn(emu_last_kernel, "<"));
|
||||
if (ran != expect || grids != (split ? 2 : 1)) {
|
||||
std::printf("FAIL %-48s %-6s ran %s in %d grid(s), expected %s in %d\n", f.name.c_str(), fn,
|
||||
emu_last_kernel, grids, expect, split ? 2 : 1);
|
||||
return 1;
|
||||
}
|
||||
int bad_rows = 0;
|
||||
for (int m = 0; m <= M; ++m) {
|
||||
if (m < M) note_paths(f, m, form, split);
|
||||
int diff = 0, first = -1;
|
||||
for (int i = 0; i < f.o_ld; ++i) {
|
||||
const int32_t w = m < M && i < W ? want[(size_t)m * W + i] : kSentinel;
|
||||
if (se[(size_t)m * f.o_ld + i] != w) { ++diff; if (first < 0) first = i; }
|
||||
}
|
||||
const int32_t wn = m < M ? want_n[(size_t)m] : kSentinel, wsu = m < M ? want_su[(size_t)m] : kSentinel;
|
||||
if (!diff && ns[(size_t)m] == wn && su[(size_t)m] == wsu) continue;
|
||||
if (++bad_rows > 4) continue;
|
||||
std::printf("FAIL %-48s %-6s row %d (n %d): nsel %d want %d, seqused %d want %d", f.name.c_str(), fn, m,
|
||||
m < M ? f.n_of(m) : -1, ns[(size_t)m], wn, su[(size_t)m], wsu);
|
||||
if (diff) {
|
||||
const int32_t w = m < M && first < W ? want[(size_t)m * W + first] : kSentinel;
|
||||
std::printf(", %d slot(s) differ, first slot %d: %d want %d", diff, first, se[(size_t)m * f.o_ld + first], w);
|
||||
}
|
||||
std::printf("\n");
|
||||
}
|
||||
return bad_rows ? 1 : 0;
|
||||
}
|
||||
|
||||
uint64_t g_x = 0;
|
||||
uint64_t rnd() { g_x ^= g_x << 13; g_x ^= g_x >> 7; g_x ^= g_x << 17; return g_x; }
|
||||
|
||||
/* halo_selftest's qsa_select_case: decode rows, ties on a coarse grid, a dead page with a winning
|
||||
* score, a tail on alternate rows; rows 0 and 1 have at most topk live. */
|
||||
Fix fix_decode() {
|
||||
Fix f; f.name = "decode: ties, a tail and a dead page";
|
||||
const int M = 6, nb = 900, topk = 64, pages = 4096, ratio = 4;
|
||||
f.shape(M, M, nb, nb, topk, ratio);
|
||||
std::fill(f.sc.begin(), f.sc.end(), 0.0f);
|
||||
for (int m = 0; m < M; ++m) {
|
||||
const int live = m == 0 ? 9 : m == 1 ? topk : 100 + m * 137;
|
||||
f.nc[m] = live; f.cu[m + 1] = m + 1;
|
||||
for (int b = 0; b < nb; ++b) {
|
||||
if (b < live) {
|
||||
f.score(m, b) = (float)((b * 17 + m * 7) % 40) * 0.25f;
|
||||
f.page(m, b) = (b * 31 + m * 11) % pages;
|
||||
if (b == live / 3) { f.score(m, b) = 1e6f; f.page(m, b) = -1; }
|
||||
} else if (b == live) {
|
||||
f.page(m, b) = m % 2 == 0 ? (m * 97 + 5) % pages : -1;
|
||||
}
|
||||
}
|
||||
f.pos[m] = f.page(m, live) >= 0 ? live * ratio + m % 3 : live * ratio - 1;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/* halo_selftest's qsa_select_prefill_case: two chunks over two histories, each query bounded by
|
||||
* its own position, the partial page present exactly when (pos + 1) % ratio != 0. */
|
||||
Fix fix_prefill() {
|
||||
Fix f; f.name = "prefill: per-query bound and the partial page";
|
||||
const int S = 2, nb = 96, topk = 5, pages = 512, ratio = 4, q0 = 9, q1 = 14, M = q0 + q1;
|
||||
const int base[2] = { 137, 4 };
|
||||
f.shape(S, M, nb, nb, topk, ratio);
|
||||
f.cu = { 0, q0, M };
|
||||
for (int i = 0; i < q0; ++i) f.pos[i] = base[0] + i;
|
||||
for (int i = 0; i < q1; ++i) f.pos[q0 + i] = base[1] + i;
|
||||
f.nc = { (base[0] + q0) / ratio, (base[1] + q1) / ratio };
|
||||
for (int s = 0; s < S; ++s)
|
||||
for (int b = 0; b < nb; ++b)
|
||||
f.page(s, b) = b <= (base[s] + (s == 0 ? q0 : q1) - 1) / ratio ? (b * 29 + s * 7) % pages : -1;
|
||||
for (int m = 0; m < M; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 23 + m * 5) % 37) * 0.5f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* halo_selftest's qsa_select_wide_case at emulator size: the first sequence's rows see about 3000,
|
||||
* 5000, 7000 and 8800 blocks (the two-pass form below the sample's 6144, the sampled form above,
|
||||
* the key cache's 8192 crossed), the second's fewer than topk; dead pages and -inf scattered; five
|
||||
* score distributions. Over 4096 blocks at six rows, the automatic choice is the split path. */
|
||||
Fix fix_wide(int dist) {
|
||||
static const char* const kDist[] = { "continuous", "coarse, heavy ties", "an eighth in one first-digit bin",
|
||||
"all in one first-digit bin", "fine ties at the threshold",
|
||||
"signed, heavy ties", "signed, all negative, heavy ties",
|
||||
"signed, continuous across zero" };
|
||||
Fix f; f.name = std::string("wide: ") + kDist[dist];
|
||||
f.sgn = dist >= 5;
|
||||
const int S = 2, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20;
|
||||
f.shape(S, 6, nb, nb, topk, ratio);
|
||||
f.cu = { 0, 4, 6 };
|
||||
f.pos = { 4 * 3000 + 1, 4 * 5000 + 2, 4 * 7000 + 3, 4 * 8800 + 1, 4 * 300, 4 * 337 + 2 };
|
||||
f.nc = { 8900, 340 };
|
||||
g_x = 0x243F6A8885A308D3ull + (uint64_t)dist;
|
||||
for (auto& v : f.bt) v = rnd() % 97 == 0 ? -1 : (int32_t)(rnd() % pages);
|
||||
for (auto& v : f.sc) {
|
||||
const uint64_t u = rnd();
|
||||
if (u % 211 == 0) { v = -INFINITY; continue; }
|
||||
switch (dist) {
|
||||
case 0: v = (float)(u % 1000003) / 1000.0f; break;
|
||||
case 1: v = (float)(u % 23) * 0.25f; break;
|
||||
case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break;
|
||||
case 3: v = 1.0f + (float)(u % 60000) * 1e-6f; break;
|
||||
case 5: v = (float)(u % 23) * 0.25f - 3.0f; break;
|
||||
case 6: v = -(float)(u % 23) * 0.25f - 1.0f; break;
|
||||
case 7: v = (float)(u % 1000003) / 1000.0f - 500.0f; break;
|
||||
default: v = (float)(u % 4999) * 0.01f; break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/* halo_selftest's qsa_select_split_one at emulator size: three chunks, 96 distinct scores so the
|
||||
* tie rule decides, one page in 64 dead, `per` draft rows a sequence. */
|
||||
Fix fix_split(int S, int per) {
|
||||
Fix f; f.name = "split: " + std::to_string(S) + " seq x " + std::to_string(per) + " rows, 96 scores";
|
||||
const int M = S * per, nb = 12001, topk = 512, ratio = 4, pages = 8192, n = 11000;
|
||||
f.shape(S, M, nb, nb, topk, ratio);
|
||||
for (int s = 0; s < S; ++s) {
|
||||
const int ns = n - s * 1300;
|
||||
f.nc[s] = ns; f.cu[s] = s * per;
|
||||
for (int b = 0; b < nb; ++b)
|
||||
f.page(s, b) = b >= ns ? -1 : b % 64 == 37 ? -1 : (b * 4099 + 11 + s * 71) % pages;
|
||||
for (int j = 0; j < per; ++j) f.pos[s * per + j] = ns * ratio + j - 2;
|
||||
}
|
||||
f.cu[S] = M;
|
||||
for (int m = 0; m < M; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 31 + m * 17) % 96) * 0.125f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* Three chunks, none with more than topk live: the merge's candidates are every live key, more
|
||||
* than topk in the first row (its threshold the list's own, coarse scores tied at it), topk or
|
||||
* fewer in the second. The first row's sample holds fewer live keys than its bound, so the wide
|
||||
* kernel's list is every live key. */
|
||||
Fix fix_split_sparse() {
|
||||
Fix f; f.name = "split: no chunk over topk";
|
||||
const int nb = 9000, topk = 512, ratio = 4;
|
||||
f.shape(2, 2, nb, nb, topk, ratio);
|
||||
f.cu = { 0, 1, 2 }; f.nc = { 8990, 8990 }; f.pos = { 4 * 8990 + 1, 4 * 8990 + 3 };
|
||||
for (int s = 0; s < 2; ++s)
|
||||
for (int b = 0; b < nb; ++b) f.page(s, b) = b % (s ? 20 : 9) == 3 ? (b * 131 + s) % 65536 : -1;
|
||||
for (int m = 0; m < 2; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 7 + m) % 13) * 0.5f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* halo_selftest's qsa_select_few_live_case: over more than topk blocks with topk or fewer live.
|
||||
* 0 few live pages, continuous scores 1 few live, most of them scoring zero or less
|
||||
* 2 live pages, most scores -inf 3 exactly topk live, a third tied at zero
|
||||
* 4 all live keys in the first chunk, more than topk, ties at the threshold
|
||||
* 5 nothing live 6 at most topk blocks (control)
|
||||
* 7 everything live (control) */
|
||||
Fix fix_few_live() {
|
||||
Fix f; f.name = "few live: topk or fewer live, in every way";
|
||||
const int S = 8, nb = 9000, topk = 512, ratio = 4, pages = 1 << 20;
|
||||
const int nrow[S] = { 8000, 8000, 8000, 8000, 2000, 8000, 300, 8000 };
|
||||
f.shape(S, S, nb, nb, topk, ratio);
|
||||
g_x = 0x9E3779B97F4A7C15ull;
|
||||
for (int s = 0; s < S; ++s) {
|
||||
const int n = nrow[s];
|
||||
f.nc[s] = n; f.cu[s] = s; f.pos[s] = n * ratio + s % 3;
|
||||
for (int b = 0; b < n; ++b) {
|
||||
float& v = f.score(s, b);
|
||||
int32_t& pg = f.page(s, b);
|
||||
const uint64_t u = rnd();
|
||||
const float cont = (float)(u % 1000003) / 1000.0f + 0.001f;
|
||||
pg = (int32_t)(u % pages);
|
||||
switch (s) {
|
||||
case 0: if (b % 80 != 3) pg = -1; v = cont; break;
|
||||
case 1: if (b % 20 != 7) pg = -1;
|
||||
v = (b / 20) % 4 == 0 ? cont : (b / 20) % 3 == 0 ? -2.5f : (b / 20) % 3 == 1 ? -0.0f : 0.0f;
|
||||
break;
|
||||
case 2: v = b % 40 == 1 ? cont : -INFINITY; break;
|
||||
case 3: if (b % 15 != 2 || b >= 15 * 512) pg = -1;
|
||||
v = b % 45 == 2 ? 0.0f : cont; break;
|
||||
case 4: v = b % 7 == 0 ? cont : (b % 2 ? 0.0f : -0.0f); break;
|
||||
case 5: pg = -1; v = cont; break;
|
||||
case 6: if (b % 9 == 4) pg = -1; v = (float)(u % 13) * 0.5f; break;
|
||||
default: v = cont; break;
|
||||
}
|
||||
}
|
||||
f.page(s, n) = s % 2 == 0 ? (int32_t)(rnd() % pages) : -1;
|
||||
}
|
||||
f.cu[S] = S;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A 70-row prefill chunk: wider than the key cache's gate, so the automatic choice is the wide
|
||||
* kernel and the pinned single-workgroup kernel reads its keys from global memory. */
|
||||
Fix fix_wide_launch() {
|
||||
Fix f; f.name = "a 70-row chunk: the wide kernel by default";
|
||||
const int M = 70, nb = 160, topk = 16, ratio = 4;
|
||||
f.shape(1, M, nb, nb, topk, ratio);
|
||||
f.cu = { 0, M }; f.nc = { 110 };
|
||||
for (int m = 0; m < M; ++m) f.pos[m] = 4 * 90 + m;
|
||||
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 11 == 5 ? -1 : (b * 37 + 3) % 4096;
|
||||
for (int m = 0; m < M; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 13 + m * 3) % 9) * 0.5f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* topk above the merged form's 512: the wide kernel's threshold bin goes to LDS alone, and the
|
||||
* split path still applies (two chunks of 2500, two lists of up to 1000 keys). */
|
||||
Fix fix_big_topk() {
|
||||
Fix f; f.name = "topk 1000: above the merged form";
|
||||
const int nb = 5000, topk = 1000, ratio = 4;
|
||||
f.shape(1, 3, nb, nb, topk, ratio);
|
||||
f.cu = { 0, 3 }; f.nc = { 4990 }; f.pos = { 4 * 4990 + 2, 4 * 3000 - 1, 4 * 900 + 1 };
|
||||
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 13 == 6 ? -1 : (b * 211 + 7) % 100000;
|
||||
for (int m = 0; m < 3; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 11 + m * 5) % 50) * 0.125f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* Where the launcher leaves the split path: 33 query rows (one past its 32), and topk 3000, whose
|
||||
* three chunk lists overflow its 8192 keys. Both take the single-workgroup kernel. */
|
||||
Fix fix_no_split(bool rows) {
|
||||
Fix f; f.name = rows ? "33 rows: past the split path's 32" : "topk 3000: past the split path's lists";
|
||||
const int M = rows ? 33 : 2, nb = rows ? 4500 : 9000, topk = rows ? 64 : 3000, ratio = 4;
|
||||
f.shape(1, M, nb, nb, topk, ratio);
|
||||
f.cu = { 0, M }; f.nc = { nb - 10 };
|
||||
for (int m = 0; m < M; ++m) f.pos[m] = 4 * (nb - 10 - 97 * m) + m % 4;
|
||||
for (int b = 0; b < nb; ++b) f.page(0, b) = b % 17 == 1 ? -1 : (b * 389 + 1) % 200000;
|
||||
for (int m = 0; m < M; ++m)
|
||||
for (int b = 0; b < nb; ++b) f.score(m, b) = (float)((b * 29 + m * 3) % 211) * 0.0625f;
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A seeded small fixture: odd values, pitches, widths and row-to-sequence maps. */
|
||||
Fix fix_sweep(int it) {
|
||||
g_x = 0xD1B54A32D192ED03ull ^ ((uint64_t)(it + 1) * 0x9E3779B97F4A7C15ull);
|
||||
for (int i = 0; i < 4; ++i) rnd();
|
||||
static const int kTopk[] = { 1, 2, 3, 5, 8, 17, 33, 64 }, kRatio[] = { 1, 2, 3, 4, 7 };
|
||||
const int topk = kTopk[rnd() % 8], ratio = kRatio[rnd() % 5], S = 1 + (int)(rnd() % 3);
|
||||
const int nb_t = 1 + (int)(rnd() % 300), nb_s = rnd() % 3 ? nb_t : 1 + (int)(rnd() % 300);
|
||||
std::vector<int> rows((size_t)S);
|
||||
int M = 0;
|
||||
for (auto& r : rows) { r = (int)(rnd() % 5); M += r; }
|
||||
const int lead = rnd() % 4 == 0 ? 1 : 0, trail = rnd() % 4 == 0 ? 1 : 0; /* rows no sequence holds */
|
||||
M += lead + trail;
|
||||
if (M == 0) { rows[0] = 1; M = 1; }
|
||||
Fix f; f.name = "sweep " + std::to_string(it);
|
||||
f.shape(S, M, nb_s, nb_t, topk, ratio, (int)(rnd() % 4), (int)(rnd() % 4), (int)(rnd() % 3));
|
||||
f.cu[0] = lead;
|
||||
for (int s = 0; s < S; ++s) f.cu[s + 1] = f.cu[s] + rows[(size_t)s];
|
||||
const int nb = f.nb();
|
||||
for (int s = 0; s < S; ++s) f.nc[s] = (int)(rnd() % (uint64_t)(nb + 6));
|
||||
for (int m = 0; m < M; ++m) f.pos[m] = (int)(rnd() % (uint64_t)(ratio * (nb + 3)));
|
||||
const unsigned dead = (unsigned)(rnd() % 4); /* none, a tenth, half, nearly all */
|
||||
for (auto& v : f.bt) {
|
||||
const uint64_t u = rnd();
|
||||
v = (dead == 1 && u % 10 == 0) || (dead == 2 && u % 2) || (dead == 3 && u % 20) ? -1 : (int32_t)(u % 100000);
|
||||
}
|
||||
const unsigned grid = 1 + (unsigned)(rnd() % 12); /* distinct values: ties when small */
|
||||
for (auto& v : f.sc) {
|
||||
const uint64_t u = rnd();
|
||||
switch (u % 23) {
|
||||
case 0: v = NAN; break;
|
||||
case 1: v = INFINITY; break;
|
||||
case 2: v = -INFINITY; break;
|
||||
case 3: v = -0.0f; break;
|
||||
case 4: v = 0.0f; break;
|
||||
case 5: v = 1e-40f * (float)(1 + (u >> 8) % 4); break; /* denormal */
|
||||
case 6: v = -1e30f; break; /* not live: the bound is strict */
|
||||
case 7: v = -9e29f; break; /* live, ranked as zero */
|
||||
case 8: v = -(float)((u >> 8) % 100); break;
|
||||
default: v = (float)((u >> 8) % grid) * 0.75f; break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A seeded fixture at serving sizes for `sweep`: 500 to 14500 blocks, topk on both sides of the
|
||||
* merged form's 512 and of the split path's list budget, one to three sequences of a few draft
|
||||
* rows or of a prefill chunk past 64 rows, and dead pages, -inf, NaN and ties in varying amounts. */
|
||||
Fix fix_random(int it) {
|
||||
g_x = 0xA0761D6478BD642Full ^ ((uint64_t)(it + 7) * 0xE7037ED1A0B428DBull);
|
||||
for (int i = 0; i < 4; ++i) rnd();
|
||||
static const int kTopk[] = { 1, 16, 64, 200, 511, 512, 513, 700, 1500, 2600 }, kRatio[] = { 1, 4, 4, 8 };
|
||||
const int topk = kTopk[rnd() % 10], ratio = kRatio[rnd() % 4], S = 1 + (int)(rnd() % 3);
|
||||
const int nb = 500 + (int)(rnd() % 14000);
|
||||
const bool chunk = rnd() % 6 == 0;
|
||||
std::vector<int> rows((size_t)S);
|
||||
int M = 0;
|
||||
for (auto& r : rows) { r = chunk ? 20 + (int)(rnd() % 30) : 1 + (int)(rnd() % 5); M += r; }
|
||||
Fix f; f.name = "sweep " + std::to_string(it) + ": " + std::to_string(M) + " rows, " + std::to_string(nb) +
|
||||
" blocks, topk " + std::to_string(topk);
|
||||
f.shape(S, M, nb, nb + (int)(rnd() % 3), topk, ratio, (int)(rnd() % 5), (int)(rnd() % 5), (int)(rnd() % 3));
|
||||
for (int s = 0; s < S; ++s) f.cu[s + 1] = f.cu[s] + rows[(size_t)s];
|
||||
for (int s = 0; s < S; ++s) f.nc[s] = nb - (int)(rnd() % (uint64_t)(nb / 2 + 1)) + (int)(rnd() % 3);
|
||||
for (int m = 0; m < M; ++m)
|
||||
f.pos[m] = std::max(0, ratio * f.nc[f.seq_of(m)] - (int)(rnd() % (uint64_t)(ratio * nb / 3 + 1)) + (int)(rnd() % 7));
|
||||
const unsigned dead = (unsigned)(rnd() % 6), dist = (unsigned)(rnd() % 6), grid = 1 + (unsigned)(rnd() % 400);
|
||||
for (auto& v : f.bt) {
|
||||
const uint64_t u = rnd();
|
||||
const bool d = dead == 1 ? u % 50 == 0 : dead == 2 ? u % 2 == 0 : dead == 3 ? u % 16 != 0
|
||||
: dead == 4 ? u % 100 != 0 : false;
|
||||
v = d ? -1 : (int32_t)(u % 1000000);
|
||||
}
|
||||
for (auto& v : f.sc) {
|
||||
const uint64_t u = rnd();
|
||||
if (u % 97 == 0) { v = -INFINITY; continue; }
|
||||
if (u % 389 == 0) { v = NAN; continue; }
|
||||
switch (dist) {
|
||||
case 0: v = (float)(u % 1000003) / 1000.0f; break;
|
||||
case 1: v = (float)((u >> 8) % grid) * 0.25f; break;
|
||||
case 2: v = u % 8 == 0 ? 1.0f + (float)(u % 60000) * 1e-6f : (float)(u % 1000) / 2000.0f; break;
|
||||
case 3: v = 1.0f + (float)((u >> 8) % 60000) * 1e-6f; break;
|
||||
case 4: v = (u >> 8) % 3 == 0 ? 0.0f : (u >> 8) % 3 == 1 ? -0.0f : -1.0f; break;
|
||||
default: v = (float)((u >> 8) % 4999) * 0.01f; break;
|
||||
}
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
/* A fixture under the signed order, its finite scores negated on odd rows when `flip` and moved
|
||||
* by `shift`, so live scores straddle zero or fall below it. */
|
||||
Fix as_signed(Fix f, float shift, bool flip = false) {
|
||||
f.sgn = true;
|
||||
f.name = "signed " + f.name;
|
||||
if (shift == 0.0f && !flip) return f; /* as built: keeps -0 apart from +0 */
|
||||
for (int m = 0; m < f.M; ++m)
|
||||
for (int b = 0; b < f.nb_s; ++b) {
|
||||
float& v = f.score(m, b);
|
||||
if (!std::isfinite(v)) continue;
|
||||
if (flip && m % 2) v = -v;
|
||||
v += shift;
|
||||
}
|
||||
return f;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* No argument: the fixtures above and the branch check. `sweep N`: N fix_random fixtures, about
|
||||
* 0.15 s each. */
|
||||
int main(int argc, char** argv) {
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const bool sweep = argc > 1 && std::string(argv[1]) == "sweep";
|
||||
std::vector<std::function<Fix()>> fixtures;
|
||||
if (sweep) {
|
||||
const int n = argc > 2 ? std::atoi(argv[2]) : 100;
|
||||
for (int i = 0; i < n; ++i) fixtures.push_back([i] { return fix_random(i); });
|
||||
for (int i = 0; i < n; ++i) fixtures.push_back([i] { return as_signed(fix_random(i), -1.0f, true); });
|
||||
} else {
|
||||
fixtures = { fix_decode, fix_prefill, fix_few_live, fix_wide_launch,
|
||||
[] { return fix_split(1, 4); }, [] { return fix_split(2, 4); }, fix_split_sparse, fix_big_topk,
|
||||
[] { return fix_no_split(true); }, [] { return fix_no_split(false); } };
|
||||
for (int d = 0; d < 5; ++d) fixtures.push_back([d] { return fix_wide(d); });
|
||||
for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return fix_sweep(i); });
|
||||
fixtures.push_back([] { return as_signed(fix_decode(), -5.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_decode(), -20.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_few_live(), 0.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_split(2, 4), -6.0f); });
|
||||
fixtures.push_back([] { return as_signed(fix_wide_launch(), -1.0f, true); });
|
||||
for (int d = 5; d < 8; ++d) fixtures.push_back([d] { return fix_wide(d); });
|
||||
for (int i = 0; i < 150; ++i) fixtures.push_back([i] { return as_signed(fix_sweep(i), 0.0f); });
|
||||
}
|
||||
int fails = 0, launches = 0;
|
||||
for (auto& make : fixtures) {
|
||||
Fix f = make();
|
||||
for (Form form : { kSingle, kWide, kAuto }) { fails += run(f, form); ++launches; }
|
||||
}
|
||||
if (sweep) {
|
||||
for (const auto& [p, c] : g_paths) std::printf(" %5d row(s): %s\n", c, p.c_str());
|
||||
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
std::printf("qsa_select sweep: %zu fixtures, %d launches, %d failure(s), %.1f s\n", fixtures.size(),
|
||||
launches, fails, sec);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
/* Every branch the fixtures are built to reach. */
|
||||
static const char* const kRequired[] = {
|
||||
"rows of at most topk blocks", "exactly topk live over more blocks", "fewer than topk live over more blocks",
|
||||
"a threshold", "a threshold whose ties are cut short",
|
||||
"single: keys cached in LDS", "single: keys read from global memory",
|
||||
"wide: the sampled pass, rows 16-byte aligned", "wide: the sampled pass, rows not 16-byte aligned",
|
||||
"wide: the sampled list", "wide: the sampled list, holding every live key",
|
||||
"wide: a sample that fell back", "wide: merged lists",
|
||||
"wide: the threshold's bin in LDS", "wide: the threshold's bin over global memory",
|
||||
"split: topk or fewer live, every one taken", "split: no chunk over topk, more than topk live",
|
||||
"split: a chunk over topk", "split: exactly topk candidates, from a chunk over topk",
|
||||
"signed: a negative threshold",
|
||||
};
|
||||
int missing = 0;
|
||||
for (const char* p : kRequired)
|
||||
if (!g_paths.count(p)) { std::printf("FAIL no row reaches: %s\n", p); ++missing; }
|
||||
for (const auto& [p, c] : g_paths) std::printf(" %5d row(s): %s\n", c, p.c_str());
|
||||
const double sec = std::chrono::duration<double>(std::chrono::steady_clock::now() - t0).count();
|
||||
std::printf("qsa_select: %zu fixtures, %d launches, %d failure(s), %d branch(es) unreached, %.1f s\n",
|
||||
fixtures.size(), launches, fails, missing, sec);
|
||||
return fails || missing ? 1 : 0;
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
/* tests/halo_emu: libhalo's elementwise and data-movement rows on the host SIMT emulator, each held
|
||||
* to libref's row for the same op on the same operands.
|
||||
*
|
||||
* These are the image, video, audio and residual-stream helpers no model fixture of rad-kbench
|
||||
* reaches and halo_selftest has no case for (gelu_tanh, cast, the row scatters and gathers,
|
||||
* cu_repeat, randn_lanes, to_rgba8, the depth/space shuffles, ln_mod, l2norm_chan, chan_split,
|
||||
* resample_nearest, fourier_embed, end_status, hc_enter/hc_write). Operands come from libref's own
|
||||
* operand descriptions (RadShapeFn) at a hand-picked geometry -- the schema is shared, so its
|
||||
* descriptors are libhalo's too -- drawn as rad-kbench draws them; every written operand is
|
||||
* compared byte for byte, except where a case names a bound: there the two sides reach the value
|
||||
* by a different summation order (a row norm over 32 lanes against libref's loop) and one bf16
|
||||
* rounding may flip, so floats compare by rel_l2. On the emulator both sides use the host's libm,
|
||||
* so a transcendental is the same function on both.
|
||||
*
|
||||
* libref is opened from $RADIANCE_HOME/kernels; without it the test fails (it has nothing else to
|
||||
* hold the rows to). */
|
||||
#include "hip/hip_runtime.h" // tests/r4d_emu/emu: the emulator
|
||||
#include "rad_abi.h"
|
||||
#include "rad_plugin.h"
|
||||
#include <dlfcn.h>
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <random>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
extern "C" {
|
||||
int halo_rad_gelu_tanh(const RadArgs*, RadStream);
|
||||
int halo_rad_cast_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_cast_widen(const RadArgs*, RadStream);
|
||||
int halo_rad_scatter_rows_bf16(const RadArgs*, RadStream);
|
||||
int halo_rad_cu_repeat(const RadArgs*, RadStream);
|
||||
int halo_rad_randn_lanes(const RadArgs*, RadStream);
|
||||
int halo_rad_to_rgba8(const RadArgs*, RadStream);
|
||||
int halo_rad_d2s_add(const RadArgs*, RadStream);
|
||||
int halo_rad_s2d_avg_add(const RadArgs*, RadStream);
|
||||
int halo_rad_ln_mod(const RadArgs*, RadStream);
|
||||
int halo_rad_l2norm_chan(const RadArgs*, RadStream);
|
||||
int halo_rad_gather_rows2(const RadArgs*, RadStream);
|
||||
int halo_rad_scatter_add_rows(const RadArgs*, RadStream);
|
||||
int halo_rad_chan_split(const RadArgs*, RadStream);
|
||||
int halo_rad_resample_nearest(const RadArgs*, RadStream);
|
||||
int halo_rad_fourier_embed(const RadArgs*, RadStream);
|
||||
int halo_rad_end_status(const RadArgs*, RadStream);
|
||||
int halo_rad_hc_enter(const RadArgs*, RadStream);
|
||||
int halo_rad_hc_write(const RadArgs*, RadStream);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
struct Ref {
|
||||
void* h = nullptr;
|
||||
int (*kc)(void) = nullptr;
|
||||
const RadKernelInfo* (*ka)(int) = nullptr;
|
||||
int (*sc)(void) = nullptr;
|
||||
const RadOpSchema* (*sa)(int) = nullptr;
|
||||
const RadKernelInfo* row(const char* op) const {
|
||||
for (int i = 0; i < kc(); ++i)
|
||||
if (!std::strcmp(ka(i)->op, op)) return ka(i);
|
||||
return nullptr;
|
||||
}
|
||||
const RadOpSchema* schema(const char* op) const {
|
||||
for (int i = 0; i < sc(); ++i)
|
||||
if (!std::strcmp(sa(i)->op, op)) return sa(i);
|
||||
return nullptr;
|
||||
}
|
||||
};
|
||||
|
||||
struct Param {
|
||||
const char* key;
|
||||
long long i;
|
||||
const char* s;
|
||||
double f;
|
||||
int kind;
|
||||
};
|
||||
Param I(const char* k, long long v) { return { k, v, nullptr, 0.0, RAD_P_INT }; }
|
||||
Param S(const char* k, const char* v) { return { k, 0, v, 0.0, RAD_P_STR }; }
|
||||
Param F(const char* k, double v) { return { k, 0, nullptr, v, RAD_P_F64 }; }
|
||||
|
||||
struct Case {
|
||||
const char* name;
|
||||
const char* op;
|
||||
int (*halo)(const RadArgs*, RadStream);
|
||||
std::vector<Param> p;
|
||||
/* Operands libref declines to describe (a signed index): given here, then adjusted. */
|
||||
std::vector<RadOpdDesc> opds = {};
|
||||
void (*fix)(std::vector<std::vector<char>>&) = nullptr;
|
||||
double tol = 0.0; /* 0: every written byte equal; > 0: float outputs within this rel_l2 */
|
||||
};
|
||||
|
||||
RadOpdDesc desc(uint32_t dt, std::vector<int64_t> shape, uint32_t fill = RAD_FILL_NORMAL,
|
||||
int64_t idx_max = 0) {
|
||||
RadOpdDesc d;
|
||||
std::memset(&d, 0, sizeof d);
|
||||
d.dtype = dt; d.rank = (uint32_t)shape.size(); d.fill = fill; d.idx_max = idx_max; d.idx_const = -1;
|
||||
for (size_t i = 0; i < shape.size(); ++i) d.shape[i] = shape[i];
|
||||
return d;
|
||||
}
|
||||
|
||||
std::mt19937_64 rng(97);
|
||||
|
||||
size_t bytes_of(const RadOpdDesc& d) {
|
||||
int64_t n = 1;
|
||||
for (uint32_t i = 0; i < d.rank; ++i) n *= d.shape[i];
|
||||
return (size_t)((n * rad_dtype_bits(d.dtype) + 7) / 8);
|
||||
}
|
||||
int64_t numel(const RadOpdDesc& d) {
|
||||
int64_t n = 1;
|
||||
for (uint32_t i = 0; i < d.rank; ++i) n *= d.shape[i];
|
||||
return n;
|
||||
}
|
||||
|
||||
/* Draws one operand as rad-kbench does for the fill kinds these ops use. */
|
||||
bool draw(const RadOpdDesc& d, std::vector<char>& buf, int64_t prev_lead) {
|
||||
const int64_t n = numel(d);
|
||||
buf.assign(bytes_of(d) + 64, 0);
|
||||
std::normal_distribution<float> nd(0.f, 1.f);
|
||||
std::uniform_real_distribution<float> ud(0.02f, 0.98f);
|
||||
auto put_f = [&](int64_t i, float v) {
|
||||
switch (d.dtype) {
|
||||
case RAD_F32: std::memcpy(buf.data() + 4 * i, &v, 4); break;
|
||||
case RAD_BF16: { const uint16_t b = rad_f32_to_bf16(v); std::memcpy(buf.data() + 2 * i, &b, 2); break; }
|
||||
case RAD_F16: { const _Float16 h = (_Float16)v; std::memcpy(buf.data() + 2 * i, &h, 2); break; }
|
||||
default: break;
|
||||
}
|
||||
};
|
||||
auto put_i = [&](int64_t i, int64_t v) {
|
||||
switch (d.dtype) {
|
||||
case RAD_I32: case RAD_U32: { const int32_t x = (int32_t)v; std::memcpy(buf.data() + 4 * i, &x, 4); break; }
|
||||
case RAD_I64: std::memcpy(buf.data() + 8 * i, &v, 8); break;
|
||||
case RAD_U8: case RAD_I8: case RAD_BOOL: buf[(size_t)i] = (char)v; break;
|
||||
case RAD_I16: { const int16_t x = (int16_t)v; std::memcpy(buf.data() + 2 * i, &x, 2); break; }
|
||||
default: break;
|
||||
}
|
||||
};
|
||||
const bool is_float = d.dtype == RAD_F32 || d.dtype == RAD_BF16 || d.dtype == RAD_F16;
|
||||
switch (d.fill) {
|
||||
case RAD_FILL_NORMAL:
|
||||
if (is_float) for (int64_t i = 0; i < n; ++i) put_f(i, nd(rng));
|
||||
else for (int64_t i = 0; i < n; ++i) put_i(i, (int64_t)(rng() % 7));
|
||||
return true;
|
||||
case RAD_FILL_SIGMOID:
|
||||
for (int64_t i = 0; i < n; ++i) put_f(i, ud(rng));
|
||||
return true;
|
||||
case RAD_FILL_INDEX: {
|
||||
const int64_t hi = d.idx_max > 0 ? d.idx_max : prev_lead;
|
||||
if (d.idx_const >= 0) { for (int64_t i = 0; i < n; ++i) put_i(i, d.idx_const); return true; }
|
||||
if (d.flags & RAD_OPD_F_IDX_CU) {
|
||||
/* [0, ..., hi]: ragged segment ends, strictly non-decreasing */
|
||||
std::vector<int64_t> cut((size_t)n);
|
||||
cut[0] = 0;
|
||||
for (int64_t i = 1; i < n; ++i) cut[(size_t)i] = (int64_t)(rng() % (uint64_t)(hi + 1));
|
||||
std::sort(cut.begin() + 1, cut.end());
|
||||
cut[(size_t)(n - 1)] = hi;
|
||||
for (int64_t i = 0; i < n; ++i) put_i(i, cut[(size_t)i]);
|
||||
return true;
|
||||
}
|
||||
if (d.flags & RAD_OPD_F_IDX_UNIQUE) {
|
||||
if (hi < n) return false;
|
||||
std::vector<int64_t> perm((size_t)hi);
|
||||
for (int64_t i = 0; i < hi; ++i) perm[(size_t)i] = i;
|
||||
std::shuffle(perm.begin(), perm.end(), rng);
|
||||
for (int64_t i = 0; i < n; ++i) put_i(i, perm[(size_t)i]);
|
||||
return true;
|
||||
}
|
||||
if (hi <= 0) return false;
|
||||
for (int64_t i = 0; i < n; ++i) put_i(i, (int64_t)(rng() % (uint64_t)hi));
|
||||
return true;
|
||||
}
|
||||
default:
|
||||
std::printf(" fill kind %u not drawn here\n", d.fill);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
double as_double(const RadOpdDesc& d, const std::vector<char>& b, int64_t i) {
|
||||
switch (d.dtype) {
|
||||
case RAD_F32: { float v; std::memcpy(&v, b.data() + 4 * i, 4); return v; }
|
||||
case RAD_BF16: { uint16_t v; std::memcpy(&v, b.data() + 2 * i, 2); return rad_bf16_to_f32(v); }
|
||||
case RAD_F16: { _Float16 v; std::memcpy(&v, b.data() + 2 * i, 2); return (double)(float)v; }
|
||||
default: return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
int run_case(const Ref& ref, const Case& c) {
|
||||
const RadKernelInfo* rr = ref.row(c.op);
|
||||
const RadOpSchema* sch = ref.schema(c.op);
|
||||
if (!rr || !sch || !rr->opd_shape) {
|
||||
std::printf("FAIL %-34s libref has no row/schema/shape hook for %s\n", c.name, c.op);
|
||||
return 1;
|
||||
}
|
||||
std::vector<RadParam> ps;
|
||||
for (const Param& q : c.p) {
|
||||
RadParam r; std::memset(&r, 0, sizeof r);
|
||||
r.key = q.key; r.kind = q.kind; r.ival = q.i; r.sval = q.s; r.dval = q.f;
|
||||
ps.push_back(r);
|
||||
}
|
||||
const int no = sch->n_operands;
|
||||
std::vector<RadOpdDesc> d((size_t)no);
|
||||
std::vector<std::vector<char>> in((size_t)no);
|
||||
int64_t prev_lead = 0;
|
||||
for (int i = 0; i < no; ++i) {
|
||||
std::memset(&d[(size_t)i], 0, sizeof(RadOpdDesc));
|
||||
d[(size_t)i].idx_const = -1;
|
||||
if (!c.opds.empty()) d[(size_t)i] = c.opds[(size_t)i];
|
||||
else if (rr->opd_shape(ps.data(), (int)ps.size(), i, &d[(size_t)i]) != RAD_OK) {
|
||||
std::printf("FAIL %-34s libref's shape hook refused operand %d\n", c.name, i);
|
||||
return 1;
|
||||
}
|
||||
if (d[(size_t)i].flags & RAD_OPD_F_ABSENT) continue;
|
||||
if (!draw(d[(size_t)i], in[(size_t)i], prev_lead)) {
|
||||
std::printf("FAIL %-34s cannot draw operand %d (%s)\n", c.name, i, sch->operands[i].name);
|
||||
return 1;
|
||||
}
|
||||
if (d[(size_t)i].rank) prev_lead = d[(size_t)i].shape[0];
|
||||
}
|
||||
if (c.fix) c.fix(in);
|
||||
/* Two copies of every operand; outputs start from the same bytes (an INOUT is read too). */
|
||||
std::vector<std::vector<char>> a = in, b = in;
|
||||
auto tensors = [&](std::vector<std::vector<char>>& bufs) {
|
||||
std::vector<RadTensor> ts((size_t)no);
|
||||
for (int i = 0; i < no; ++i) {
|
||||
RadTensor& t = ts[(size_t)i];
|
||||
std::memset(&t, 0, sizeof t);
|
||||
const RadOpdDesc& e = d[(size_t)i];
|
||||
if (e.flags & RAD_OPD_F_ABSENT) continue;
|
||||
t.data = bufs[(size_t)i].data();
|
||||
t.dtype = e.dtype;
|
||||
t.rank = e.rank;
|
||||
int64_t acc = 1;
|
||||
for (int k = (int)e.rank - 1; k >= 0; --k) { t.shape[k] = e.shape[k]; t.stride[k] = acc; acc *= e.shape[k]; }
|
||||
}
|
||||
return ts;
|
||||
};
|
||||
std::vector<RadTensor> ta = tensors(a), tb = tensors(b);
|
||||
RadArgs ra; std::memset(&ra, 0, sizeof ra);
|
||||
ra.t = ta.data(); ra.n_t = no; ra.p = ps.data(); ra.n_p = (int)ps.size(); ra.world_size = 1;
|
||||
RadArgs rb = ra;
|
||||
rb.t = tb.data();
|
||||
std::vector<char> sa, sb;
|
||||
if (rr->scratch) {
|
||||
const int64_t need = rr->scratch(&rb);
|
||||
if (need > 0) { sb.assign((size_t)need, 0); rb.scratch = sb.data(); rb.scratch_bytes = need; }
|
||||
}
|
||||
const int rh = c.halo(&ra, nullptr);
|
||||
const int rf = rr->launch(&rb, nullptr);
|
||||
if (rh != RAD_OK || rf != RAD_OK) {
|
||||
std::printf("FAIL %-34s rc libhalo %d, libref %d\n", c.name, rh, rf);
|
||||
return 1;
|
||||
}
|
||||
int fails = 0;
|
||||
std::string detail;
|
||||
for (int i = 0; i < no; ++i) {
|
||||
const int role = sch->operands[i].role;
|
||||
if (role != RAD_OPD_OUT && role != RAD_OPD_INOUT) continue;
|
||||
const RadOpdDesc& e = d[(size_t)i];
|
||||
if (e.flags & RAD_OPD_F_ABSENT) continue;
|
||||
const int64_t n = numel(e);
|
||||
char buf[160];
|
||||
if (c.tol > 0 && (e.dtype == RAD_F32 || e.dtype == RAD_BF16 || e.dtype == RAD_F16)) {
|
||||
double num = 0, den = 0, worst = 0;
|
||||
int64_t nonfinite = 0;
|
||||
for (int64_t k = 0; k < n; ++k) {
|
||||
const double x = as_double(e, a[(size_t)i], k), y = as_double(e, b[(size_t)i], k);
|
||||
if (std::isfinite(x) != std::isfinite(y)) { ++nonfinite; continue; }
|
||||
if (!std::isfinite(y)) continue;
|
||||
num += (x - y) * (x - y); den += y * y;
|
||||
worst = std::max(worst, std::fabs(x - y));
|
||||
}
|
||||
const double rel = den > 0 ? std::sqrt(num / den) : std::sqrt(num);
|
||||
/* An all-zero reference would pass any kernel that writes nothing: not a check. */
|
||||
const bool ok = nonfinite == 0 && rel < c.tol && den > 0;
|
||||
std::snprintf(buf, sizeof buf, " %s: rel_l2 %.2e max_abs %.2e%s%s", sch->operands[i].name, rel, worst,
|
||||
nonfinite ? " NONFINITE MISMATCH" : "", den > 0 ? "" : " REFERENCE ALL ZERO");
|
||||
detail += buf;
|
||||
fails += !ok;
|
||||
} else {
|
||||
const size_t nb = bytes_of(e);
|
||||
size_t diff = 0, nonzero = 0;
|
||||
for (size_t k = 0; k < nb; ++k) { diff += a[(size_t)i][k] != b[(size_t)i][k]; nonzero += b[(size_t)i][k] != 0; }
|
||||
std::snprintf(buf, sizeof buf, " %s: %zu of %zu bytes differ%s", sch->operands[i].name, diff, nb,
|
||||
nonzero ? "" : " REFERENCE ALL ZERO");
|
||||
detail += buf;
|
||||
fails += diff != 0 || nonzero == 0;
|
||||
}
|
||||
}
|
||||
std::printf("%s %-34s%s\n", fails ? "FAIL" : "ok ", c.name, detail.c_str());
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
const char* home = std::getenv("RADIANCE_HOME");
|
||||
const std::string path = std::string(home ? home : ".") + "/kernels/libref.so";
|
||||
Ref ref;
|
||||
ref.h = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL);
|
||||
if (!ref.h) { std::printf("FAIL cannot open %s: %s\n", path.c_str(), dlerror()); return 1; }
|
||||
ref.kc = (int (*)(void))dlsym(ref.h, "rad_kernel_count");
|
||||
ref.ka = (const RadKernelInfo* (*)(int))dlsym(ref.h, "rad_kernel_at");
|
||||
ref.sc = (int (*)(void))dlsym(ref.h, "rad_kernel_schema_count");
|
||||
ref.sa = (const RadOpSchema* (*)(int))dlsym(ref.h, "rad_kernel_schema_at");
|
||||
if (!ref.kc || !ref.ka || !ref.sc || !ref.sa) { std::printf("FAIL libref has no tables\n"); return 1; }
|
||||
|
||||
const std::vector<Case> cases = {
|
||||
{ "gelu_tanh bf16 M 7 n 1032", "gelu_tanh", halo_rad_gelu_tanh, { I("M", 7), I("n", 1032), S("dtype", "bf16") } },
|
||||
{ "cast f32->bf16 M 5 n 777", "cast", halo_rad_cast_bf16, { I("M", 5), I("n", 777), S("from", "f32"), S("to", "bf16") } },
|
||||
{ "cast bf16->f32 M 5 n 777", "cast", halo_rad_cast_widen, { I("M", 5), I("n", 777), S("from", "bf16"), S("to", "f32") } },
|
||||
{ "scatter_rows bf16 M 9 n 258", "scatter_rows", halo_rad_scatter_rows_bf16, { I("M", 9), I("n", 258), S("dtype", "bf16") } },
|
||||
{ "cu_repeat M 6 mult 3", "cu_repeat", halo_rad_cu_repeat, { I("M", 6), I("mult", 3) } },
|
||||
{ "randn_lanes bf16 M 12 n 64", "randn_lanes", halo_rad_randn_lanes, { I("M", 12), I("n", 64), I("stride", 64), S("dtype", "bf16") } },
|
||||
{ "randn_lanes f32 M 12 n 96 stride 100", "randn_lanes", halo_rad_randn_lanes, { I("M", 12), I("n", 96), I("stride", 100), S("dtype", "f32") } },
|
||||
{ "to_rgba8 bf16 M 33 n 3", "to_rgba8", halo_rad_to_rgba8, { I("M", 33), I("n", 3), S("dtype", "bf16") } },
|
||||
{ "d2s_add bf16 M 4 cin 64 cout 32 ft 2", "d2s_add", halo_rad_d2s_add, { I("M", 4), I("cin", 64), I("cout", 32), I("ft", 2), S("dtype", "bf16") } },
|
||||
{ "s2d_avg_add bf16 M 4 cin 32 cout 64 ft 2", "s2d_avg_add", halo_rad_s2d_avg_add, { I("M", 4), I("cin", 32), I("cout", 64), I("ft", 2), S("dtype", "bf16") } },
|
||||
{ "ln_mod bf16 M 10 n 1032", "ln_mod", halo_rad_ln_mod, { I("M", 10), I("n", 1032), F("eps", 1e-6), S("dtype", "bf16") } },
|
||||
{ "l2norm_chan bf16 M 9 n 520", "l2norm_chan", halo_rad_l2norm_chan, { I("M", 9), I("n", 520), S("act", "none"), S("dtype", "bf16") } },
|
||||
{ "l2norm_chan bf16 silu M 9 n 520", "l2norm_chan", halo_rad_l2norm_chan, { I("M", 9), I("n", 520), S("act", "silu"), S("dtype", "bf16") }, {}, nullptr, 1e-2 },
|
||||
/* y[i] = idx >= 0 ? a[idx] : b[-1 - idx]: a 7-row and a 5-row source, the index drawn over
|
||||
* [0, 12) and moved to [-5, 7) so both sources are read. */
|
||||
{ "gather_rows2 bf16 M 11 n 264", "gather_rows2", halo_rad_gather_rows2, { I("M", 11), I("n", 264), S("dtype", "bf16") },
|
||||
{ desc(RAD_BF16, { 7, 264 }), desc(RAD_BF16, { 5, 264 }), desc(RAD_I32, { 11 }, RAD_FILL_INDEX, 12),
|
||||
desc(RAD_BF16, { 11, 264 }) },
|
||||
[](std::vector<std::vector<char>>& b) {
|
||||
for (int i = 0; i < 11; ++i) { int32_t v; std::memcpy(&v, b[2].data() + 4 * i, 4); v -= 5; std::memcpy(b[2].data() + 4 * i, &v, 4); }
|
||||
} },
|
||||
{ "scatter_add_rows bf16 M 9 n 264", "scatter_add_rows", halo_rad_scatter_add_rows, { I("M", 9), I("n", 264), S("dtype", "bf16") } },
|
||||
{ "chan_split bf16 M 6 n 96 parts 3", "chan_split", halo_rad_chan_split, { I("M", 6), I("n", 96), I("parts", 3), S("dtype", "bf16") } },
|
||||
{ "resample_nearest bf16 M 7 n 48", "resample_nearest", halo_rad_resample_nearest, { I("M", 7), I("n", 48), S("dtype", "bf16") } },
|
||||
{ "fourier_embed bf16 M 5 n 64", "fourier_embed", halo_rad_fourier_embed, { I("M", 5), I("n", 64), I("round", 0), S("dtype", "bf16") } },
|
||||
{ "end_status M 4 end 3 rep 2", "end_status", halo_rad_end_status, { I("M", 4), I("end", 3), I("rep", 2) } },
|
||||
{ "end_status M 3 end 5 rep 1", "end_status", halo_rad_end_status, { I("M", 3), I("end", 5), I("rep", 1) } },
|
||||
{ "hc_enter bf16 M 5 n 520 hc 4", "hc_enter", halo_rad_hc_enter, { I("M", 5), I("n", 520), I("hc", 4), S("dtype", "bf16") } },
|
||||
{ "hc_write bf16 M 5 n 520 hc 4", "hc_write", halo_rad_hc_write, { I("M", 5), I("n", 520), I("hc", 4), S("dtype", "bf16") }, {}, nullptr, 1e-2 },
|
||||
};
|
||||
int fails = 0;
|
||||
for (const Case& c : cases) fails += run_case(ref, c);
|
||||
std::printf("libhalo vs libref: %zu case(s), %d failure(s)\n", cases.size(), fails);
|
||||
return fails ? 1 : 0;
|
||||
}
|
||||
Reference in new issue
Block a user