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:
Deadcode committed 2026-10-30 22:01:01 +01:00
commit 9ed3ef7a7b
452 files changed
+167762 -1346

No files matched your search

+4 -1
View File
@@ -158,6 +158,8 @@ set(R4D_UNITS
# checkpoint, and the entry points reject a mismatch.
"r4d_gemm_fp8a16_nt_m1|"
"r4d_gemm_fp8a8|"
"r4d_gemm_iqr|"
"r4d_iqr_embed|"
"r4d_quant_act_fp8|"
"r4d_givens_rotate|"
"r4d_fused_quant_fp8|"
@@ -227,7 +229,8 @@ endforeach()
# The host sources are declaration only: the row table, weight layouts and relayouts, operand
# descriptions and fusion claims. They are pure host C++ that includes neither r4d.h nor
# hip_runtime.h, so these tables compile and can be inspected without ROCm.
set(R4D_DECLARATION r4d_rows.cpp r4d_layout.cpp r4d_fp8_layout.cpp r4d_shapes.cpp r4d_fuse.cpp)
set(R4D_DECLARATION r4d_rows.cpp r4d_layout.cpp r4d_fp8_layout.cpp r4d_iqr_layout.cpp r4d_shapes.cpp
r4d_fuse.cpp)
rad_add_plugin(libr4d kernels
SOURCES ${R4D_DECLARATION}
+13
View File
@@ -677,6 +677,11 @@ int r4d_gemm_fp8a8_nt_m16_max_m(void);
// output element, not the order of the K tiles it accumulates, and the split derives from
// `gx * mw`, which the rule keeps invariant. r4d_selftest compares bytes at every legal count.
void r4d_gemm_fp8a8_pin_mw(int mw);
// Test hook: pins the waves the narrow tiles' K split aims for (fp8a8 and i8a8 128, the IQR narrow
// tile 512) for every subsequent call on every thread; 0 restores each caller's own. Not for
// serving; r4d_selftest holds it at the IQR tile's target around the i8a8 reference, so the two
// split K alike and their bytes compare.
void r4d_gemm_i8a8_pin_split_waves(int waves);
// Test hook: pins the QSA score's form. 0 is the launcher's rule, 1 the scalar decode form, 2 the
// matrix form (which refuses a shape it is not built for). The two sum in different orders, so
// r4d_selftest --perfqsa compares them to a tolerance.
@@ -787,6 +792,14 @@ int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N, int a_ld,
int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long stream);
// The same at a weight scale constant over 8 or 32 rows (a tcq_rb trellis), folded as the fp8
// tile.
int r4d_gemm_i8a8_rb8_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long stream);
int r4d_gemm_i8a8_rb32_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long stream);
int r4d_gemm_fp8a8_block(void);
// Per-(row, 128-column) symmetric E4M3 quantisation of a bf16 activation, read by the fp8a8 GEMMs.
+4 -5
View File
@@ -1389,11 +1389,10 @@ static int rad_ar_rmsnorm_quant(const RadArgs* a, RadStream s, bool hi8) {
R4dArCfg cfgv;
r4d_cfg_ar(a, &cfgv);
/* The width is not tunable here: it decides which columns a thread accumulates into the sum of
* squares, so it must match the standalone rmsnorm_quant_fp8, which uses r4d_act_threads(M, n)
* (1024 up to 32 rows, 512 above). A pinned width would change the summation order, and the
* generated text, at M = 64. Zero means the norm's width, resolved from M by the entry point.
* The tuned block count, drain and acq change no bytes and are honoured. */
/* The width is the standalone rmsnorm_quant_fp8's, r4d_act_threads(M, n) (1024 up to 32 rows,
* 512 above): zero means that, resolved from M by the entry point. The sums fold in
* kR4dSumLanes' partition at every width, so the width changes no bytes; it is not tuned here.
* The tuned block count, drain and acq change no bytes either and are honoured. */
const int nthreads = 0;
/* One block per row, the norm's shape rather than the all-reduce's. The push saturates the
* fabric at four blocks, but the norm serialises the rows a block owns, which costs more than
+5 -5
View File
@@ -609,7 +609,7 @@ void r4d_attn_decode_body(const R4DArgs& a, int splits)
if (!live) return;
// fetch-inactive: the f32 partials read lrow under `if (h == 0)` only (see the prefill kernel's
// epilogue, #328).
// epilogue).
const float lrow = l_i + swap16_fi(l_i);
const int tok = qoff + qrow;
const size_t idx = (size_t)(tok * a.q_heads + qhead) * splits + sp;
@@ -1065,10 +1065,10 @@ void r4d_attn_splitkv_combine_gq_kernel(const R4DArgs a, int splits, int tile,
// keep their segment count. Greedy output is unchanged.
static constexpr int kVerifySplitsMin = 64;
// The floor is also bounded by the batch: at most kVerifyFloorWorkgroups workgroups (segments x KV
// heads x sequences). The declared scratch is the worst over every sequence count up to max_seqs,
// and 64 a sequence at 256 sequences made it 64x the law's (h256/gqa12 at max_ctx 200000: 7.62 ->
// 487.5 MiB a card, issue #342). Up to eight sequences of two KV heads the floor stays 64; at 16 it
// is 32, at 256 two, and the region stays at what eight sequences need.
// heads x sequences). The scratch is sized at declare for the worst sequence count up to max_seqs,
// and an unbounded floor reserves 64 segments for each sequence: 487.5 MiB a card for h256/gqa12 at
// 256 sequences and max_ctx 200000, 7.62 MiB under the bound. Up to eight sequences of two KV
// heads the floor stays 64; at 16 it is 32, at 256 two: the region stays at what eight need.
static constexpr int kVerifyFloorWorkgroups = 1024;
static constexpr int kVerifyMinFrom = 16384;
static constexpr int kVerifyDeepFrom = 65536;
+6 -2
View File
@@ -593,7 +593,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
float smax = sc[0];
#pragma unroll
for (int e = 1; e < 8; ++e) smax = fmaxf(smax, sc[e]);
if (wave_any(smax > m_ref + PGROW)) {
// The rescale is the wave's, so a row's bits depend on the rows sharing its wave. Only
// live rows decide it: a row past qlen limits its keys at its own qpos, past ctx, so it
// scores whatever the cache's last block held before (another request's KV), and the
// last query rows of a sequence's final block would round by that.
if (wave_any(live && smax > m_ref + PGROW)) {
const float rmax = fmaxf(smax, swap16(smax));
const float mnew = fmaxf(fmaxf(m_ref, rmax), -3.0e38f);
const float alpha = ex2(m_ref - mnew);
@@ -680,7 +684,7 @@ void r4d_attn_prefill_kernel(const R4DArgs a)
if (!live) return;
// fetch-inactive: the split store reads l_i under `if (h == 0)` only, so the exchange may be sunk
// into that half; swap16_fi still reads the partner's half of the row sum (#328).
// into that half; swap16_fi still reads the partner's half of the row sum.
l_i += swap16_fi(l_i);
if constexpr (SPLIT) {
// Unnormalised: the merge weighs segments by 2^(m - max m) and applies v_descale itself.
+8
View File
@@ -291,6 +291,14 @@ __host__ __device__ __forceinline__ int r4d_act_threads(int M, int K) {
return M <= lim ? 512 : 256;
}
// The partition a row's sum is folded over, whatever the workgroup width: lane v < kR4dSumLanes
// adds columns v, v + kR4dSumLanes, ... in order, the lanes past it add nothing, and block_sum adds
// the wave sums from the first. Folding over the width instead would round a row's norm by how many
// rows its launch carries, since r4d_act_threads widens the workgroup at small M: the same token in
// a 64-token prefill chunk and in a 2048-token one would get different bits. 256 is the narrowest
// width, so a launch at it keeps the order it always had.
constexpr uint32_t kR4dSumLanes = 256;
// The full-card cliff of the R9700 (gfx1201, 64 CUs). A launch whose wavefront count falls in
// the last 32 before a multiple of 2048 runs about five times slower than the same work one
// workgroup wider, whatever the kernel does: 256-thread workgroups take 27.6 us at 253 to 256 of
+59
View File
@@ -786,6 +786,41 @@ extern "C" int r4d_seg_mean_bf16(long x, long cu, long y, int S, int n, int x_ld
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// ---------------------------------------------------------------------------- seg_softmax_pool
// ref_seg_softmax_pool: row s of y is v's rows [cu[s], cu[s+1]) summed with the softmax of their
// scores as weights, the softmax in f32 with the maximum subtracted, the sum in f32, one rounding.
// A workgroup is 256 columns of one segment, and every thread forms the segment's softmax itself:
// a segment is one question's few options (clef's routing), so the repeat is cheaper than a
// reduction. An empty segment writes zeros.
__global__ __launch_bounds__(kThreads) void seg_softmax_pool_kernel(
const uint16_t* __restrict__ sc, const uint16_t* __restrict__ v, const int* __restrict__ cu,
uint16_t* __restrict__ y, uint32_t n, uint32_t v_ld, uint32_t y_ld) {
const uint32_t s = blockIdx.y;
const uint32_t i = blockIdx.x * kThreads + threadIdx.x;
if (i >= n) return;
const int b0 = cu[s], b1 = cu[s + 1];
float m = -INFINITY;
for (int r = b0; r < b1; ++r) m = fmaxf(m, bf2f(sc[r]));
float z = 0.0f;
for (int r = b0; r < b1; ++r) z += expf(bf2f(sc[r]) - m);
float acc = 0.0f;
for (int r = b0; r < b1; ++r)
acc += expf(bf2f(sc[r]) - m) / z * bf2f(v[(size_t)r * v_ld + i]);
y[(size_t)s * y_ld + i] = f32_to_bf16(b1 > b0 ? acc : 0.0f);
}
extern "C" int r4d_seg_softmax_pool_bf16(long sc, long v, long cu, long y, int S, int n, int v_ld,
int y_ld, long stream) {
if (!sc || !v || !cu || !y) return -1;
if (S <= 0 || n <= 0) return -2;
hipLaunchKernelGGL(seg_softmax_pool_kernel,
dim3((uint32_t)((n + kThreads - 1) / kThreads), (uint32_t)S),
dim3(kThreads), 0, (hipStream_t)stream, (const uint16_t*)sc,
(const uint16_t*)v, (const int*)cu, (uint16_t*)y, (uint32_t)n,
(uint32_t)v_ld, (uint32_t)y_ld);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// mode: 0 neox, 1 gptj, 2 blocks, 3 gptj_blocks, 4 imrope, 5 axial (`blk` and the position plane
// stride `pplane` used only by the last four). A null gain is a unit gain; `rot` 0 is the norm
// alone, and then `pos` may be null. `pos_f32` reads f32 positions as the values they hold.
@@ -1099,6 +1134,30 @@ extern "C" int r4d_rad_seg_mean(const RadArgs* a, RadStream s) {
(int)x_ld, (int)y_ld, (long)(uintptr_t)s));
}
extern "C" int r4d_rad_seg_softmax_pool(const RadArgs* a, RadStream s) {
const RadTensor* Sc = r4d_opt(a, 0);
const RadTensor* V = r4d_opt(a, 1);
const RadTensor* cu = r4d_opt(a, 2);
const RadTensor* Y = r4d_opt(a, 3);
if (!Sc || !V || !cu || !Y) return R4D_NO(RAD_E_INVAL);
R4D_NEED(dt_bf16(Sc));
R4D_NEED(dt_bf16(V));
R4D_NEED(dt_bf16(Y));
if (!r4d_contig(Sc)) return R4D_NO(RAD_E_STRIDE);
if (cu->dtype != RAD_I32 || !r4d_contig(cu) || r4d_numel(cu) < 2) return R4D_NO(RAD_E_SHAPE);
const long long n = r4d_geti_or(a, "n", r4d_dim(Y, (int)Y->rank - 1));
if (n <= 0) return R4D_NO(RAD_E_SHAPE);
const long long S = r4d_numel(cu) - 1;
long long Mv = 0, My = 0;
const long long v_ld = r4d_rows_pitch(V, n, &Mv);
const long long y_ld = r4d_rows_pitch(Y, n, &My);
if (v_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (My < S || r4d_numel(Sc) < Mv) return R4D_NO(RAD_E_SHAPE);
return enc_status(r4d_seg_softmax_pool_bf16(r4d_addr(Sc), r4d_addr(V), r4d_addr(cu),
r4d_addr(Y), (int)S, (int)n, (int)v_ld,
(int)y_ld, (long)(uintptr_t)s));
}
/* ------------------------------------------------------------------ qk_norm_rope */
enum { QN_QKV = 0, QN_POS, QN_QW, QN_KW };
+12 -5
View File
@@ -62,12 +62,19 @@ static inline int fp8_ops(const RadArgs* a, Fp8Ops* g, int want_ascale,
const long long blk = r4d_gemm_fp8a8_block();
if (blk != R4D_FP8_BLOCK) return R4D_NO(RAD_E_SHAPE);
g->nkb = (g->K + blk - 1) / blk;
/* Check the scale plane's extents: a wrong grid still reads plausible numbers. */
if (g->bscale->shape[0] != (wscale == FP8_OPS_ROW_SCALE ? g->N : (g->N + blk - 1) / blk))
return R4D_NO(RAD_E_SHAPE);
if (g->bscale->shape[1] != g->nkb) return R4D_NO(RAD_E_SHAPE);
/* Check the scale plane's extents: a wrong grid still reads plausible numbers. A trellis
* weight's two-level scale (E4M3 per row per 128 K under a second level) is a view of two
* planes, declared at the weight's logical extents [N][K] (which no one-level scale is); its
* layout widens it to the bf16 [N][K/128] a one-level scale is, at that plane's pitch. */
const bool two = wscale == FP8_OPS_ROW_SCALE && g->bscale->shape[0] == g->N &&
g->bscale->shape[1] == g->K;
if (!two) {
if (g->bscale->shape[0] != (wscale == FP8_OPS_ROW_SCALE ? g->N : (g->N + blk - 1) / blk))
return R4D_NO(RAD_E_SHAPE);
if (g->bscale->shape[1] != g->nkb) return R4D_NO(RAD_E_SHAPE);
}
const long long wp = r4d_row_pitch(g->b), sp = r4d_row_pitch(g->bscale);
const long long wp = r4d_row_pitch(g->b), sp = two ? g->nkb : r4d_row_pitch(g->bscale);
const long long yp = r4d_row_pitch(g->y);
if (wp < 0 || sp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE);
/* The output has no pitch argument -- libr4d writes C[r*N + c]. */
+36 -9
View File
@@ -40,9 +40,11 @@
#include "r4d_hc_fp8.h"
#include "r4d_enc.h"
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <vector>
/* Operand indices of `gemm_nt_q`. The schema is positional, so these must follow its order in
* r4d_rows.cpp. */
@@ -233,13 +235,21 @@ extern "C" int r4d_rad_unrelayout_fp8_block(const RadParam* p, int n_p, int oper
* `i8a8h` is the same planes holding a weight rotated by the unnormalised 128-wide Hadamard along
* K, the 1/128 in its scale (libquant's `transform=fwht128`), to be met by had_quant_act_i8g's
* activation. The bytes cannot tell the two apart, so each dtype accepts only its own transform
* and the rotated codes carry a tag of their own. */
* and the rotated codes carry a tag of their own.
*
* Int8 codes only. A narrower weight on the same grid (the IQR forms) is kept at its codes' width
* and read by the gemm_iqr rows (r4d_iqr_layout.cpp). */
namespace {
bool i8_rotated(const RadParam* p, int n_p) {
const char* d = r4d_pgets(p, n_p, "dtype");
return d && std::strcmp(d, "i8a8h") == 0;
}
/* int8 codes with a bf16 scale per (row, 128), at transform `tr`. */
bool i8_codes(const RadEncoding* enc, const char* tr) {
return r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK, RAD_DT_INVALID, tr);
}
int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
if (!out || !pl) return RAD_E_INVAL;
@@ -248,9 +258,7 @@ int i8_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
if (rc != RAD_OK) return rc;
if (operand != FL_B && operand != FL_BSCALE) return RAD_E_UNSUPPORTED;
const bool rot = i8_rotated(p, n_p);
if (!r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK, RAD_DT_INVALID,
rot ? "fwht128" : ""))
return RAD_E_DTYPE;
if (!i8_codes(enc, rot ? "fwht128" : "")) return RAD_E_DTYPE;
if (operand == FL_BSCALE) {
if (!r4d_enc::selects(enc, sel, n, "scale") || !r4d_enc::dims(pl[0], g.N, g.sk))
return RAD_E_SHAPE;
@@ -333,11 +341,17 @@ int lm_enc_layout(const RadParam* p, int n_p, int operand, const RadEncoding* en
FGeom g;
const int rc = lgeom(p, n_p, &g);
if (rc != RAD_OK) return rc;
if (i8 ? !r4d_enc::affine(enc, RAD_I8, RAD_BF16, 1, R4D_FP8_BLOCK) : !fp8_block_enc(enc))
return RAD_E_DTYPE;
if (!r4d_enc::selects(enc, sel, n, "codes", "scale")) return RAD_E_SHAPE;
if (!r4d_enc::dims(pl[0], g.N, g.K) || !r4d_enc::dims(pl[1], i8 ? g.N : g.sn, g.sk))
return RAD_E_SHAPE;
if (i8) {
if (!i8_codes(enc, "")) return RAD_E_DTYPE;
if (!r4d_enc::selects(enc, sel, n, "codes", "scale")) return RAD_E_SHAPE;
if (!r4d_enc::dims(pl[0], g.N, g.K) || !r4d_enc::dims(pl[1], g.N, g.sk))
return RAD_E_SHAPE;
} else {
if (!fp8_block_enc(enc)) return RAD_E_DTYPE;
if (!r4d_enc::selects(enc, sel, n, "codes", "scale")) return RAD_E_SHAPE;
if (!r4d_enc::dims(pl[0], g.N, g.K) || !r4d_enc::dims(pl[1], g.sn, g.sk))
return RAD_E_SHAPE;
}
const long long stride = r4d_fp8::lm_row_bytes(g.K);
ffill(out, i8 ? "r4d.i8lm.r128" : "r4d.fp8lm.b128", i8 ? RAD_I8 : RAD_F8E4M3, g.N, stride,
g.N * stride);
@@ -578,3 +592,16 @@ extern "C" int r4d_rad_layout_embed_q(const RadParam* p, int n_p, int operand,
return RAD_E_SHAPE;
return RAD_E_UNSUPPORTED;
}
/* ================================================================= embed_lookup's table
*
* The bf16 gather reads a plain bf16 table as stored; a table on the int8 grid is the IQR gather's
* (embed_lookup_iqr, r4d_iqr_layout.cpp), kept at its codes' width. */
extern "C" int r4d_rad_layout_embed_bf16(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
(void)p; (void)n_p; (void)sel; (void)pl; (void)n; (void)out;
enum { E_WTE = 1 };
if (operand != E_WTE) return RAD_E_UNSUPPORTED;
return rad_enc_is(enc, "plain") ? RAD_E_UNSUPPORTED : RAD_E_DTYPE;
}
+5 -5
View File
@@ -52,8 +52,8 @@
*
* qk_norm_rope_gate
* Not byte-identical to the four kernels it replaces (docs/OPS.md): it folds a sum of
* squares over one wave per head where `rmsnorm` folds over r4d_act_threads(M, n) threads,
* so the two differ by a ULP.
* squares over one wave per head where `rmsnorm` folds over kR4dSumLanes' 256 lanes, so
* the two differ by a ULP.
*
* sample_chain
* Stands beside the decomposed sampling stages rather than replacing them: one workgroup
@@ -218,9 +218,9 @@ bool fp8_geometry_ok(const RadParam* p, int n_p, int64_t M, int64_t n) {
* All three steps are libr4d rows (add_bf16, rmsnorm_bf16, quant_act_fp8), so the check stays
* within libr4d; `rmsnorm_add` has no libr4d row.
*
* Byte identity depends on the workgroup width agreeing: both kernels take their thread count from
* `r4d_act_threads(M, n)`, which decides the columns each thread folds into the sum of squares
* (see the launcher in r4d_model_bf16.hip). `M` is mirrored verbatim for that reason.
* Both kernels fold the sum of squares in kR4dSumLanes' partition at whatever width
* `r4d_act_threads(M, n)` gives them (r4d_common.h), so the width does not decide the bytes; `M`
* is mirrored verbatim so both launch the same shape.
*
* Step 0 writes the sum into the fused residual operand, both its own `b` and the fused kernel's
* in-place residual, so both sides leave the same buffers behind. `add_bf16` is safe in place:
+30 -14
View File
@@ -77,6 +77,17 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
return s;
}
// A row's sum of squares in the standalone norm's partition (kR4dSumLanes, r4d_common.h): lane
// v < 256 adds columns v, v + 256, ... of `row` in order and the lanes past it add nothing, so a
// row's bits do not depend on the block's width. When the block's threads stored `row`, the
// caller issues the barrier first, as add_rmsnorm does.
__device__ __forceinline__ float lanes_sumsq(const uint16_t* row, uint32_t n) {
float ss = 0.0f;
if (threadIdx.x < kR4dSumLanes)
for (uint32_t i = threadIdx.x; i < n; i += kR4dSumLanes) { const float v = bf2f(row[i]); ss += v * v; }
return ss;
}
// Quantise one 128-column group from the four bf16-rounded values a lane owns. The clamp in
// q8_pack4 is required (see r4d_q8.h): v_cvt_pk_fp8_f32 returns NaN out of range, and
// `amax * (1/scale)` can land an ulp above 448.
@@ -155,8 +166,9 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
const uint16_t* __restrict__ nr = RES ? rr : xr;
// Four strides are loaded before any is used, avoiding one round trip per stride. A stride past
// the row reloads this thread's first column and is skipped below. The summation order is still
// that of `i = tid; i += THR`, shared by every kernel using r4d_act_threads' partition.
// the row reloads this thread's first column and is skipped below. At 256 threads the sum is
// folded in that loop, whose order is kR4dSumLanes' partition; a wider block folds the stored
// row in lanes_sumsq behind a barrier.
constexpr uint32_t kU = 4;
float ss = 0.0f;
for (uint32_t i0 = threadIdx.x; i0 < n; i0 += kU * THR) {
@@ -179,10 +191,15 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_fp8_kernel(
} else {
v = bf2f(xa[u]);
}
ss += v * v;
if constexpr (THR == kR4dSumLanes) ss += v * v;
else (void)v;
}
}
}
if constexpr (THR != kR4dSumLanes) {
if (RES) __syncthreads(); // the residual row, stored across the block's threads
ss = lanes_sumsq(nr, n);
}
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
@@ -307,7 +324,7 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
// Bit-identical to the pair it replaces. Pass two is norm_quant_row. Pass one reproduces the
// all-reduce's arithmetic (an f32 sum stored as bf16, as in r4d_ar_oneshot_2rank_exact's vadd) and
// stores it back into `x`, as the replaced kernel did, so other readers of `x` see the same bytes.
// Both sum the squares in r4d_act_threads' `i = tid; i += THR` order.
// Both sum the squares in the standalone norm's partition (lanes_sumsq).
//
// Both wires are served. Above --tp-wire-min-kb the message is sent 6-bit rotated; a step carries
// n_seq * (1 + n_spec) rows, so it crosses that floor from the second concurrent sequence on, and
@@ -664,9 +681,9 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
uint16_t a;
if constexpr (WIRE == 0) { a = f2bf(bf2f(xr[i]) + bf2f(pr[i])); xr[i] = a; }
else { a = xr[i]; }
const float av = bf2f(a);
s1s += av * av;
if constexpr (THR == kR4dSumLanes) { const float av = bf2f(a); s1s += av * av; }
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); s1s = lanes_sumsq(xr, n); }
const float s1 = rsqrtf(block_sum<THR / kWave>(s1s, lds) / (float)n + eps);
__syncthreads(); // lds is reused by the second sum
for (uint32_t i = tid; i < n; i += THR) {
@@ -674,8 +691,7 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
const uint16_t pv = f2bf(bf2f(xr[i]) * s1 * (g + wadd));
const uint16_t h = f2bf(bf2f(rr[i]) + bf2f(pv));
rr[i] = h;
const float v = bf2f(h);
ss += v * v;
if constexpr (THR == kR4dSumLanes) { const float v = bf2f(h); ss += v * v; }
}
} else
for (uint32_t i = tid; i < n; i += THR) {
@@ -687,8 +703,10 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_fp8_kernel(
float v;
if (RES) { const uint16_t h = f2bf(bf2f(rr[i]) + bf2f(a)); rr[i] = h; v = bf2f(h); }
else { v = bf2f(a); }
ss += v * v;
if constexpr (THR == kR4dSumLanes) ss += v * v;
else (void)v;
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss = lanes_sumsq(nr, n); }
/* block_sum's barrier is also what publishes pass one's stores to pass two's reads. */
const float rs = rsqrtf(block_sum<THR / kWave>(ss, lds) / (float)n + eps);
norm_quant_row<WF32, THR, HI8>(nr, w, y ? y + (size_t)row * y_ld : nullptr,
@@ -734,10 +752,8 @@ static int rmsnorm_quant_launch(long x, long res, long w, long y, long q, long s
if (!s_ld) s_ld = nkb;
// One workgroup per row, so a decode batch is 8-72 workgroups and the kernel is latency bound;
// the workgroup width is the parallelism knob (crossover table in r4d_act_threads).
//
// rmsnorm_bf16 must pick the same width from the same function: the width decides which
// columns a thread sums, so a different width changes the last bits and breaks bit identity.
// the workgroup width is the parallelism knob (crossover table in r4d_act_threads). The sum of
// squares is folded in kR4dSumLanes' partition at every width, as rmsnorm_bf16 folds it.
const int thr = r4d_act_threads(M, n);
#define R4D_RQ_H(wf, rs, T, H) \
hipLaunchKernelGGL((rmsnorm_quant_fp8_kernel<wf, rs, T, H>), dim3((uint32_t)M), dim3(T), 0, \
@@ -934,7 +950,7 @@ static int ar_rmsnorm_quant_launch(long peer_scratch, long my_scratch, long peer
if (nb > M) nb = M;
const int nbw = r4d_ar_max_blocks(); // the counter capacity; see r4d_ar_seq.h
if (nb > nbw) nb = nbw;
// The width must be r4d_act_threads', as for the standalone norm (it fixes the summation order).
// The standalone norm's width; the sums fold in kR4dSumLanes' partition at any of the three.
const int thr = nthreads ? nthreads : r4d_act_threads(M, n);
if (thr != 256 && thr != 512 && thr != 1024) return -6;
const bool pad = wire == 6 && (n % ARQ_CE) != 0;
@@ -850,9 +850,12 @@ constexpr unsigned kMaxConvCtr = 4096;
static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
static std::mutex m;
static std::map<std::pair<RadStream, const void*>, unsigned int*> blocks;
std::lock_guard<std::mutex> lk(m);
const auto key = std::make_pair(s, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
{
// Not held while the block is made, as in split_ctr: the zeroing waits for the card.
std::lock_guard<std::mutex> lk(m);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxConvCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
// Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has finished
@@ -863,8 +866,15 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, (unsigned int*)p);
return (unsigned int*)p;
unsigned int* kept = nullptr;
{
std::lock_guard<std::mutex> lk(m);
const auto [it, fresh] = blocks.emplace(key, (unsigned int*)p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row
+299
View File
@@ -0,0 +1,299 @@
// r4d_gemm_8a8_prefill.h -- the int8 and fp8 prefill tile's body (gemm_8a8_prefill_body), shared
// by r4d_gemm_fp8a8.hip's tiles and r4d_gemm_iqr.hip's, which decodes its weight in the body's
// `begin` hook. Included inside an anonymous namespace after the includer's kWave (32) and kBlock
// (128), with r4d_fp8_wmma.h's names in scope.
// ---- the prefill tile's geometry ---------------------------------------------------------------
//
// A block owns 128 weight rows x 128 activation rows: eight waves as kPWW (weight) x kPWA
// (activation), each wave kPTW weight tiles x kPTA activation tiles of 16 x 16. Eight accumulator
// tiles a wave is a hard cap: each is two f32 sets (`raw` and `out`), so more spills. The staged K
// tile is kPFK bytes, two per 128-column scale block. See gemm_8a8_prefill_kernel for the layout
// and what was measured.
constexpr uint32_t kPTW = 2, kPTA = 4, kPWW = 4, kPWA = 2;
constexpr uint32_t kPBN = kPWW * kPTW * 16, kPBM = kPWA * kPTA * 16; // weight x activation rows
constexpr uint32_t kPWaves = kPWW * kPWA;
constexpr uint32_t kPFK = 64;
static_assert(kPBN == kBlock, "a block's weight rows are one scale row");
// Activation bands per raster group of the prefill tile; see the kernel's grouping.
constexpr uint32_t kGroupM = 8;
/* The LDS the body's activation staging holds, which a `begin` hook may borrow. */
constexpr uint32_t kPrefillLds = 2u * kPBM * (kPFK + 8u);
// ---- the prefill tile ---------------------------------------------------------------------------
//
// 128 weight rows x 128 activation rows a block, eight waves as kPWW (weight) x kPWA (activation),
// a wave kPTW weight tiles x kPTA activation tiles. The weight is the WMMA A operand, read from the
// fragment-order plane straight into registers: a lane's 32 bytes are its four fragments for 64 k,
// so a wave's load is one contiguous KiB and the weight never touches LDS. The activation is the B
// operand, staged through LDS and read by the four waves that share its rows. A lane's accumulator
// is eight consecutive weight rows of one activation row, so the fold takes one activation scale a
// lane a tile (and the block's one weight scale), and the store is one 16-byte write.
//
// What decides the layout is LDS bandwidth. gfx1201 serves 64 bytes of LDS a clock per CU, loads
// and stores alike, and issues an fp8 WMMA every 8 clocks per SIMD, so a CU has 256 bytes of LDS
// per WMMA at the WMMA rate (libr4d/isa/wmmamix.hip). Staging both operands with one activation
// tile x eight weight tiles a wave moves 288 bytes of fragment reads and 64 of stores per WMMA,
// which alone caps a loop at ~73% of the WMMA rate (measured with nothing else in it). This layout
// reads 128 bytes and stores 32 per WMMA, and the weight's 64 bytes come through the vector cache.
//
// At the 300 W limit every GEMM shape here is power-bound (sclk 2.1-2.3 GHz against 2.55 for bare
// WMMA on random operands), so a variant's speed tracks the bytes it moves as much as the
// instructions it issues. Measured against the both-operands-through-LDS 1x8 tile at the DiT's
// shapes (M 18648) and LLM prefill shapes (M 300-4096), 160 TFLOP/s at gate_up:
// - this layout with the per-row activation scales gathered from global, mul + add fold: +12%;
// - the activation scales staged through LDS (`s_as`), one row a thread: +4%. A lane's gather
// touched sixteen cachelines a load, more bytes than its weight fragments;
// - the fold as one fma instead of a rounded multiply and an add: +4-5%. Not bit-identical to
// the separate multiply (rel_l2 ~2e-5 against it, both well inside bf16 output);
// - unconditional prefetch (the last tile's prefetch re-reads the last tile, discarded): +1%.
// A conditional load joins two paths with different counts and the compiler waits for zero;
// - the LDS-only barrier (lds_barrier) instead of __syncthreads: +1%; the latter's release waits
// for every outstanding load, the weight prefetch included;
// - kGroupM 8 instead of 16: +1-3%; 4 ties 8.
// Measured and rejected:
// - 2 x 4 waves of 4 weight x 2 activation tiles (half the LDS reads, twice the weight bytes
// through the vector cache): 3-5% slower;
// - 8 x 1 waves (256 x 64 blocks, no weight tile read twice in a block): ties at o and gate_up;
// - the weight two tiles ahead: 240 VGPRs and scratch spills, 25-38% slower;
// - 12 or 16 waves (192 or 256 activation rows a block, up to a quarter less L2 traffic): ties
// to 1% slower, a higher clock at a lower rate per clock;
// - four threads an activation row, 16 bytes each (whole 64-byte segments a load): neutral;
// - raw buffer loads with 32-bit offsets for both operands: 20% slower;
// - s_setprio around the WMMA run: neutral. CU mode (-mcumode): ~10% slower.
/* RB (I8 only): the weight's scale is one per RB rows and 128 K, as a trellis on libquant's tcq_rb
* grid widens (r4d_fp8_layout.cpp; the per-row plane holds the block's one value in each row):
* RB 8, a lane's eight accumulator rows, one scale per lane per tile; RB 32, a wave's two tiles,
* one scale per wave as the fp8 tile has. The fold is then the fp8 one, one fma per slot: the
* int32 accumulator starts each 128-K block at 0x4B400000, so the slot read as an f32 is exactly
* 12582912 + sum (|sum| <= 128 * 127 * 127 < 2^22) and needs no conversion. The scales are summed
* in `corr` (per lane and tile at RB 8, per lane at RB 32), and 12582912 times them leaves `out`
* every kRbFlush blocks and at the store, which keeps the f32 sum within a few bias terms of its
* value (6.8e-4 of the output's rms against the exact fold, under bf16's own rounding).
*
* M = 2048, one rank, the median of 7 interleaved rounds against the fp8 tile at the same clocks:
* RB 32 -4..0% (gate_up, down, ssm_inz, o), RB 8 -1..+3%, the per-row int8 tile +15..19%. */
constexpr int kRbBias = 0x4B400000;
constexpr float kRbBiasF = 12582912.0f;
constexpr uint32_t kRbFlush = 8;
template <int RB>
__device__ __forceinline__ f8v rb_first() {
if constexpr (RB != 0) return __builtin_bit_cast(f8v, (i8v)(kRbBias));
else return acc_zero();
}
/* What the tile does around its K loop besides the GEMM: `begin(bm, bn, lds)` once the block's
* bands are known and before any weight load, with the activation's staging LDS (`kPrefillLds`
* bytes) free to borrow; `end(bn)` after the block's stores. The int8 and fp8 tiles do nothing; the
* IQR tile decodes its weight there (r4d_gemm_iqr.hip). */
struct PrefillPlain {
__device__ void begin(uint32_t, uint32_t, uint8_t*) const {}
__device__ void end(uint32_t) const {}
};
/* ROWF (RB 32): the weight's scale is one f32 a row times one f32 a 128-K block for all rows (an
* IQR weight under kRowF32): the block's factor `Cf[kb]` is the fold's wave-uniform scale, as RB
* 32's, and each row's `Rs[n]` scales its outputs at the store. */
template <bool I8, int RB, class Pre, bool ROWF = false>
__device__ __forceinline__ void gemm_8a8_prefill_body(
const uint8_t* __restrict__ A, const float* __restrict__ Sa, const uint8_t* __restrict__ W,
const uint16_t* __restrict__ Sw, uint16_t* __restrict__ C, uint32_t M, uint32_t K, uint32_t N,
uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld, const Pre& pre,
const float* __restrict__ Rs = nullptr, const float* __restrict__ Cf = nullptr) {
static_assert(!ROWF || RB == 32, "a row's scale and a block's factor fold as RB 32's one scale");
constexpr uint32_t P = lds_pitch<kPFK>();
static_assert(kPBM * 2u == kPWaves * kWave, "two threads stage an activation row");
// Double-buffered: one barrier a staged tile, which publishes it.
__shared__ __attribute__((aligned(16))) uint8_t s_a[2][kPBM * P];
static_assert(sizeof(s_a) == kPrefillLds, "the staging LDS a begin hook may borrow");
// The activation scales of the current and the next 128-column block, one per block row.
__shared__ float s_as[2][kPBM];
const uint32_t tid = threadIdx.x, lane = tid % kWave;
// Uniform per wave, and through readfirstlane known so, so what derives from it stays scalar.
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
const uint32_t ww = wave % kPWW, wa = wave / kPWW;
// The grid runs in groups of kGroupM activation bands. Blocks dispatch in flattened-id order;
// with the plain x-fastest grid the activation is read once per 128 weight rows, which halves
// the rate once it exceeds the 64 MB MALL. Within a group the bands stay cached across the N
// sweep and the weight is read once per group. With kGroupM bands or fewer the plain order is
// used and the division skipped.
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (gridDim.x > kGroupM) {
const uint32_t per = kGroupM * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kGroupM, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kGroupM);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * kPBM, n0 = bn * kPBN;
const uint32_t ksuper = K / kSuperK, nkb = K / kBlock;
pre.begin(bm, bn, &s_a[0][0]);
// Staging: two threads a row, 32 bytes each. Rows past M re-read row M-1, and every load is
// issued unconditionally (the last tile's prefetch re-reads the last tile), so the loop has no
// branch and its waits count exactly; nothing past M is stored.
const uint32_t sr = tid / 2u, sc = (tid % 2u) * 32u;
const uint8_t* const asrc = A + (size_t)min(m0 + sr, M - 1u) * a_ld + sc;
// Thread t loads the scale of block row t % 128; both threads of a row write the same value.
const float* const ssrc = Sa + (size_t)min(m0 + tid % kPBM, M - 1u) * sa_ld;
// This wave's weight tiles, kTileBytes a 64-k supertile, `ksuper` supertiles a tile row.
const uint32_t wt0 = n0 / 16u + ww * kPTW;
const uint8_t* const wsrc = W + (size_t)wt0 * ksuper * kTileBytes + lane * kLaneBytes;
// Activation rows this wave reads from the staged tile, and the lane's column in each.
const uint32_t arow = wa * kPTA * 16u;
static_assert(!RB || I8, "RB is the int8 tile's");
static_assert(RB == 0 || RB == 8 || RB == 32, "a weight scale per 8 or 32 rows");
static_assert(RB != 32 || kPTW * 16 == 32, "RB 32 is a wave's rows");
constexpr uint32_t kCI = RB == 8 ? kPTW : 1u; // corr's tiles: one per tile, or the wave's
f8v raw[kPTW][kPTA], out[kPTW][kPTA];
float corr[kCI][kPTA];
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) {
out[i][j] = acc_zero();
if constexpr (RB != 0) raw[i][j] = acc_zero();
}
#pragma unroll
for (uint32_t i = 0; i < kCI; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) corr[i][j] = 0.0f;
Stage8 pa = stage8_load(asrc, true);
Stage8 w0[kPTW], w1[kPTW];
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
w0[i] = stage8_load(wsrc + (size_t)i * ksuper * kTileBytes, true);
s_as[0][tid % kPBM] = ssrc[0];
float scn = ssrc[min(1u, nkb - 1u)];
/* One staged K tile, the first or second half of scale block `kb`: publish the activation
* tile (and in the second half the next block's scales), issue the next tile's loads, then four
* k steps from `cur`. The first k step of a block starts from a zero accumulator, so `raw` needs
* no clearing after the fold. */
auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kPTW], Stage8 (&nxt)[kPTW]) {
stage8_store<kPFK>(s_a[half], sr, sc, pa);
if (half == 1u) s_as[(kb + 1u) % 2u][tid % kPBM] = scn;
lds_barrier();
const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK);
pa = stage8_load(asrc + c1, true);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
nxt[i] = stage8_load(wsrc + ((size_t)i * ksuper + c1 / kSuperK) * kTileBytes, true);
if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)];
#pragma unroll
for (uint32_t ks = 0; ks < kPFK / kK; ++ks) {
i2v bf[kPTA];
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) bf[j] = frag<kPFK>(s_a[half], arow + j * 16u, ks * kK, lane);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
const i2v af = frag_of(cur[i], ks);
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j)
raw[i][j] = mma8<I8>(af, bf[j],
(half == 0u && ks == 0u) ? rb_first<RB>() : raw[i][j]);
}
}
};
for (uint32_t kb = 0; kb < nkb; ++kb) {
// The weight's scales for this block, read ahead of the two tiles that hide them: one bf16
// for the block's 128 rows, or with I8 one per row, a lane's eight rows of a tile adjacent
// in the tile-major [N/16][K/128][16] plane.
float ws = 0.0f;
uint4 w8[I8 && !RB ? kPTW : 1u];
float wb[RB == 8 ? kPTW : 1u];
if constexpr (ROWF) {
ws = Cf[kb];
} else if constexpr (RB == 32) {
/* the wave's 32 rows hold one value: the first's, a wave-uniform load */
ws = bscale(Sw[((size_t)wt0 * nkb + kb) * 16u]);
} else if constexpr (RB == 8) {
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
wb[i] = bscale(Sw[((size_t)(wt0 + i) * nkb + kb) * 16u + (lane >> 4) * 8u]);
} else if constexpr (I8) {
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
w8[i] = *(const uint4*)(Sw + ((size_t)(wt0 + i) * nkb + kb) * 16u + (lane >> 4) * 8u);
} else {
ws = bscale(Sw[(size_t)(n0 / kBlock) * sw_ld + kb]);
}
tile(kb, 0u, w0, w1);
tile(kb, 1u, w1, w0);
if constexpr (RB != 0) {
if (kb % kRbFlush == 0u && kb) { // the last kRbFlush blocks' bias, before this fold
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[i][j][t] = __builtin_fmaf(-kRbBiasF, corr[RB == 8 ? i : 0][j],
out[i][j][t]);
#pragma unroll
for (uint32_t i = 0; i < kCI; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) corr[i][j] = 0.0f;
}
}
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) {
const float as = s_as[kb % 2u][arow + j * 16u + frag_c(lane)];
if constexpr (RB == 32) corr[0][j] = __builtin_fmaf(ws, as, corr[0][j]);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
if constexpr (RB != 0) {
const float sb = (RB == 8 ? wb[i] : ws) * as;
if constexpr (RB == 8) corr[i][j] += sb;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[i][j][t] = __builtin_fmaf(raw[i][j][t], sb, out[i][j][t]);
continue;
}
float s[8];
if constexpr (I8) {
const uint32_t d[4] = { w8[i].x, w8[i].y, w8[i].z, w8[i].w };
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
s[t] = as * bscale((uint16_t)(d[t / 2] >> (16 * (t % 2))));
} else {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) s[t] = ws * as;
}
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[i][j][t] = __builtin_fmaf(acc_val<I8>(raw[i][j][t]), s[t], out[i][j][t]);
}
}
}
// D is [weight row][activation row]: eight consecutive columns of one C row a lane a tile.
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) {
const uint32_t m = m0 + arow + j * 16u + frag_c(lane);
const uint32_t n = n0 + (ww * kPTW + i) * 16u + acc_row(lane, 0);
if (m < M) {
f8v v = out[i][j];
if constexpr (RB != 0)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
v[t] = __builtin_fmaf(-kRbBiasF, corr[RB == 8 ? i : 0][j], v[t]);
if constexpr (ROWF)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) v[t] *= Rs[n + t];
/* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits). */
*(uint4*)(C + (size_t)m * N + n) =
make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]),
bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7]));
}
}
pre.end(bn);
}
+147 -22
View File
@@ -31,6 +31,7 @@
#include "r4d_fp8_lm.h"
#include "r4d_fp8_wmma.h"
#include "r4d_chain.h"
#include "r4d_iqr.h"
#include <algorithm>
@@ -184,6 +185,91 @@ __device__ __forceinline__ float code1(uint8_t b) {
else return e4m3(b);
}
/* An IQR head (r4d_iqr.h's lm row: TB-bit codes indexing an int8 table of 2^TB entries, the row's
* bf16 scales after its codes): TB = 0 is a byte a code (E4M3, or int8 with I8). The table sits
* after the last row (lm_tab), and a kernel holds it in sixteen dwords (`tv`) for byte permutes:
* a lookup of four codes is one v_perm a group of eight entries, the groups chosen bytewise by the
* codes' upper bits. */
template <uint32_t TB>
__device__ __forceinline__ void lm_table(const uint8_t* W, uint32_t rows, uint32_t w_ld,
uint32_t (&tv)[16]) {
#pragma unroll
for (uint32_t i = 0; i < 16; ++i) tv[i] = 0u;
if constexpr (TB != 0) {
const uint32_t* t = (const uint32_t*)(W + ((size_t)rows * w_ld + 255u) / 256u * 256u);
#pragma unroll
for (uint32_t i = 0; i < ((1u << TB) + 3u) / 4u; ++i) tv[i] = t[i];
}
}
/* The table entries of four codes, one a byte of `x`. */
template <uint32_t TB>
__device__ __forceinline__ uint32_t lm_lookup4(uint32_t x, const uint32_t (&tv)[16]) {
const uint32_t lo = x & 0x07070707u;
uint32_t g[8];
#pragma unroll
for (uint32_t i = 0; i < 8; ++i)
if (i < ((1u << TB) + 7u) / 8u) g[i] = __builtin_amdgcn_perm(tv[2 * i + 1], tv[2 * i], lo);
#pragma unroll
for (uint32_t b = 3; b < TB; ++b) {
/* bytes whose bit b is set take the upper half of each pair of groups */
const uint32_t m = ((x >> b) & 0x01010101u) * 0xFFu;
const uint32_t half = 1u << (b - 3);
#pragma unroll
for (uint32_t i = 0; i < 8; i += 2 * half)
if (i + half < ((1u << TB) + 7u) / 8u) g[i] = (g[i + half] & m) | (g[i] & ~m);
}
return g[0];
}
/* Sixteen consecutive codes from column c (a multiple of 16) of a row, as int8 bytes. */
template <uint32_t TB>
__device__ __forceinline__ uint4 lm_codes16(const uint8_t* __restrict__ row, uint32_t c,
const uint32_t (&tv)[16]) {
if constexpr (TB == 0) {
return *(const uint4*)(row + c);
} else {
/* 2*TB bytes from offset 2*TB*(c/16), read from the dword-aligned window over them */
constexpr uint32_t ND = (2u * TB + 3u + 3u) / 4u;
const uint32_t off = c / 16u * 2u * TB;
const uint32_t* p = (const uint32_t*)(row + (off & ~3u));
uint32_t w[ND];
#pragma unroll
for (uint32_t i = 0; i < ND; ++i) w[i] = p[i];
const uint32_t sh = (off & 3u) * 8u;
uint32_t d[ND];
#pragma unroll
for (uint32_t i = 0; i < ND; ++i)
d[i] = __builtin_amdgcn_alignbit(i + 1u < ND ? w[i + 1u] : 0u, w[i], sh);
uint32_t o[4];
#pragma unroll
for (uint32_t q = 0; q < 4; ++q) {
uint32_t x = 0;
#pragma unroll
for (uint32_t j = 0; j < 4; ++j) {
const uint32_t bit = (q * 4u + j) * TB, i = bit >> 5, s = bit & 31u;
const uint32_t v = (s + TB <= 32u ? d[i] >> s
: __builtin_amdgcn_alignbit(d[i + 1u], d[i], s)) &
((1u << TB) - 1u);
x |= v << (8u * j);
}
o[q] = lm_lookup4<TB>(x, tv);
}
return make_uint4(o[0], o[1], o[2], o[3]);
}
}
/* One code's value, for a ragged tail. */
template <uint32_t TB, bool I8>
__device__ __forceinline__ float lm_code1(const uint8_t* __restrict__ row, uint32_t c,
const uint32_t (&tv)[16]) {
if constexpr (TB == 0) {
return code1<I8>(row[c]);
} else {
const uint32_t bit = c * TB;
const uint32_t w = (uint32_t)row[bit >> 3] | (uint32_t)row[(bit >> 3) + 1] << 8;
const uint32_t code = (w >> (bit & 7u)) & ((1u << TB) - 1u);
return (float)(int8_t)(tv[code / 4u] >> (8u * (code % 4u)));
}
}
// MT token rows against RB weight rows per wave: a speculative verify step (M = 1 + n_spec) reads
// the weight once for all MT rows instead of falling to r4d_gemm_fp8a8_nt_m16.
//
@@ -193,13 +279,15 @@ __device__ __forceinline__ float code1(uint8_t b) {
// The E4M3 decode is hoisted out of the token loop. The a0/a1 split (even columns, odd columns, per
// lane, one wave reduction) keeps row_dot's summation order, so MT = 1 is bit-identical to row_dot
// and RB changes only which wave owns a row.
template <uint32_t MT, uint32_t RB, bool SROW, bool I8 = false>
template <uint32_t MT, uint32_t RB, bool SROW, bool I8 = false, uint32_t TB = 0>
__device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
const uint16_t* __restrict__ S,
const uint16_t* __restrict__ X, uint32_t a_ld,
uint32_t row0, uint32_t rows, uint32_t cols,
uint32_t w_ld, uint32_t sc_cols, uint32_t m_real,
int lane, float* __restrict__ acc) {
uint32_t tv[16];
lm_table<TB>(W, rows, w_ld, tv);
const uint32_t stride = kWave * 16u;
const uint32_t full = (cols / stride) * stride;
// The activation row a token slot reads. Above kMaxMt, M is rounded up to a multiple of four and
@@ -216,7 +304,8 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
// the loop uniform.
const uint32_t rr = (row0 + r < rows) ? (row0 + r) : (rows - 1);
w[r] = W + (size_t)rr * w_ld;
srow[r] = SROW ? (const uint16_t*)(w[r] + cols) : S + (size_t)(rr / kBlock) * sc_cols;
srow[r] = SROW ? (const uint16_t*)(w[r] + (TB ? cols / 8u * TB : cols))
: S + (size_t)(rr / kBlock) * sc_cols;
}
#pragma unroll
for (uint32_t i = 0; i < RB * MT; ++i) acc[i] = 0.0f;
@@ -233,7 +322,7 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
auto load = [&](uint32_t c) {
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) {
wn[r] = *(const uint4*)(w[r] + c);
wn[r] = lm_codes16<TB>(w[r], c, tv);
sn[r] = srow[r][c / kBlock];
}
if constexpr (kPre) {
@@ -264,7 +353,7 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
for (uint32_t r = 0; r < RB; ++r) {
uint4 packed;
if constexpr (kPre) packed = wc[r];
else packed = *(const uint4*)(w[r] + c);
else packed = lm_codes16<TB>(w[r], c, tv);
const uint32_t* pw = (const uint32_t*)&packed;
#pragma unroll
for (int k = 0; k < 4; ++k) {
@@ -313,7 +402,7 @@ __device__ __forceinline__ void rows_dot_mt(const uint8_t* __restrict__ W,
for (uint32_t c = full + (uint32_t)lane; c < cols; c += kWave) {
#pragma unroll
for (uint32_t r = 0; r < RB; ++r) {
const float wv = code1<I8>(w[r][c]), s = bscale(srow[r][c / kBlock]);
const float wv = lm_code1<TB, I8>(w[r], c, tv), s = bscale(srow[r][c / kBlock]);
#pragma unroll
for (uint32_t m = 0; m < MT; ++m)
acc[r * MT + m] =
@@ -331,7 +420,7 @@ template <class OT> __device__ __forceinline__ OT mvm_store(float v);
template <> __device__ __forceinline__ uint16_t mvm_store<uint16_t>(float v) { return f32_to_bf16(v); }
template <> __device__ __forceinline__ float mvm_store<float>(float v) { return v; }
template <uint32_t MT, bool SROW, class OT, uint32_t RB = 1, bool I8 = false>
template <uint32_t MT, bool SROW, class OT, uint32_t RB = 1, bool I8 = false, uint32_t TB = 0>
__global__ __launch_bounds__(kDenseThreads) void mvm_kernel(
const uint8_t* __restrict__ W, const uint16_t* __restrict__ S,
const uint16_t* __restrict__ X, uint32_t a_ld, OT* __restrict__ out, uint32_t c_ld,
@@ -343,8 +432,8 @@ __global__ __launch_bounds__(kDenseThreads) void mvm_kernel(
for (uint32_t r0 = ((uint32_t)blockIdx.x * kDenseWaves + (uint32_t)wave) * RB; r0 < rows;
r0 += step) {
float acc[RB * MT];
rows_dot_mt<MT, RB, SROW, I8>(W, S, X, a_ld, r0, rows, cols, w_ld, sc_cols, m_real, lane,
acc);
rows_dot_mt<MT, RB, SROW, I8, TB>(W, S, X, a_ld, r0, rows, cols, w_ld, sc_cols, m_real,
lane, acc);
// C is [M][N]: lane 0 writes MT scattered values `c_ld` apart, negligible against the
// weight read. Rows m >= m_real are padding (M rounded up) and are discarded.
if (lane == 0) {
@@ -481,7 +570,7 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
}
// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it.
template <uint32_t MT, uint32_t FKB, bool I8, uint32_t MH = 1>
template <uint32_t MT, uint32_t FKB, bool I8, uint32_t MH = 1, uint32_t TB = 0>
__device__ __forceinline__ void lm_wmma_body(
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
float* __restrict__ C, uint32_t c_ld,
@@ -503,12 +592,15 @@ __device__ __forceinline__ void lm_wmma_body(
const uint32_t mo = (wv / (kDenseWaves / MH)) * 16u * MT; /* its M half's first row */
const uint32_t c = lane & 15u; /* this lane's weight row inside its 16-row tile */
const uint32_t h = lane >> 4; /* which half of the K step */
uint32_t tv[16];
lm_table<TB>(W, rows, w_ld, tv);
for (uint32_t base = (uint32_t)blockIdx.x * kRows; base < rows; base += gridDim.x * kRows) {
/* Clamped, not skipped: a tail workgroup recomputes the last row; the store drops it. */
const uint32_t n = base + wn * 16u + c;
const uint32_t nc = (n < rows) ? n : (rows - 1u);
const uint16_t* scl = (const uint16_t*)(W + (size_t)nc * w_ld + cols);
const uint16_t* scl =
(const uint16_t*)(W + (size_t)nc * w_ld + (TB ? cols / 8u * TB : cols));
f8v acc[MT];
#pragma unroll
@@ -545,8 +637,8 @@ __device__ __forceinline__ void lm_wmma_body(
const uint32_t u = tid + i * kDenseThreads;
const uint32_t r = u / (kFK / 16u), off = (u % (kFK / 16u)) * 16u;
const uint32_t g = base + r;
const uint8_t* src = W + (size_t)((g < rows) ? g : (rows - 1u)) * w_ld + kt + off;
*(uint4*)(s_w + (size_t)r * kPitch + off) = *(const uint4*)src;
const uint8_t* src = W + (size_t)((g < rows) ? g : (rows - 1u)) * w_ld;
*(uint4*)(s_w + (size_t)r * kPitch + off) = lm_codes16<TB>(src, kt + off, tv);
}
lds_barrier();
@@ -607,16 +699,16 @@ __device__ __forceinline__ void lm_wmma_body(
#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \
uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \
uint32_t w_ld, uint32_t m_real
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1, uint32_t TB = 0>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
R4D_LMW_PARAMS) {
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
lm_wmma_body<MT, FKB, I8, MH, TB>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
}
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1, uint32_t TB = 0>
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma(
R4D_LMW_PARAMS) {
r4d_chain_wait();
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
lm_wmma_body<MT, FKB, I8, MH, TB>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
r4d_chain_done();
}
#undef R4D_LMW_PARAMS
@@ -698,7 +790,7 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c,
// This row must serve every M: all bands of one op read the same stored bytes, so a band falling
// to another kernel (e.g. the bf16 projection) would misread the E4M3 codes.
// core/build/rad_builder.cpp refuses such a split at declare time.
template <bool I8>
template <bool I8, uint32_t TB = 0>
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
int w_ld, long stream, bool chain = false);
@@ -716,7 +808,7 @@ extern "C" int r4d_logits_gemm_i8(long a, long wq, long c, int M, int K, int N,
/* `chain`: the WMMA pass's chained form (the plugin entry, where the row resolved with `chain`);
* the matvec below three rows stays plain. */
template <bool I8>
template <bool I8, uint32_t TB>
static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld, int c_ld,
int w_ld, long stream, bool chain) {
if (!a || !wq || !c) return -1;
@@ -747,12 +839,12 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
float* cc = (float*)c + (size_t)m0 * c_ld;
if (fkb == 2u)
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 2, I8, 2> : lm_wmma_kernel<4, 2, I8, 2>),
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 2, I8, 2, TB> : lm_wmma_kernel<4, 2, I8, 2, TB>),
dim3(blocks), dim3(kDenseThreads), 0,
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
else
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 1, I8, 2> : lm_wmma_kernel<4, 1, I8, 2>),
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 1, I8, 2, TB> : lm_wmma_kernel<4, 1, I8, 2, TB>),
dim3(blocks), dim3(kDenseThreads), 0,
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
@@ -769,7 +861,7 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
float* cc = (float*)c + (size_t)m0 * c_ld;
#define R4D_LMW2(MTV, FKV) \
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<MTV, FKV, I8> : lm_wmma_kernel<MTV, FKV, I8>), \
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<MTV, FKV, I8, 1, TB> : lm_wmma_kernel<MTV, FKV, I8, 1, TB>), \
dim3(blocks), dim3(kDenseThreads), 0, \
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc, \
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc)
@@ -789,7 +881,7 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
const uint32_t blocks = std::min<uint32_t>(2048u, (rows + kDenseWaves - 1) / kDenseWaves);
#define R4D_LGF8(NM) \
hipLaunchKernelGGL((mvm_kernel<NM, true, float, 1, I8>), dim3(blocks), dim3(kDenseThreads), \
hipLaunchKernelGGL((mvm_kernel<NM, true, float, 1, I8, TB>), dim3(blocks), dim3(kDenseThreads), \
0, (hipStream_t)stream, (const uint8_t*)wq, (const uint16_t*)nullptr, \
(const uint16_t*)a, (uint32_t)a_ld, (float*)c, (uint32_t)c_ld, \
rows, cols, (uint32_t)w_ld, 0u, (uint32_t)M)
@@ -900,6 +992,39 @@ extern "C" int r4d_rad_logits_gemm_i8(const RadArgs* a, RadStream s) {
return rad_logits_gemm_8(a, s, true);
}
/* An IQR head (r4d_iqr.h's lm form): the int8 head's kernels with each sixteen codes read at their
* width and looked up in the row form's table (lm_codes16), so the arithmetic is the int8 head's
* over the same values. */
extern "C" int r4d_rad_logits_gemm_iqr(const RadArgs* a, RadStream s) {
const RadTensor* x = r4d_opt(a, LG_X);
const RadTensor* w = r4d_opt(a, LG_W);
const RadTensor* y = r4d_opt(a, LG_Y);
if (!x || !w || !y) return R4D_NO(RAD_E_INVAL);
if (x->dtype != RAD_BF16 || y->dtype != RAD_F32 || !r4d_iqr::is_weight_dtype(w->dtype))
return R4D_NO(RAD_E_DTYPE);
const uint32_t word = w->dtype & r4d_iqr::kWordMask;
if (!r4d_iqr::lm_built(word)) return R4D_NO(RAD_E_DTYPE);
const r4d_iqr::Form f = r4d_iqr::form(word);
const long long n_vocab = r4d_geti_or(a, "n_vocab", r4d_dim(w, 0));
const long long n_embd = r4d_geti_or(a, "n_embd", 0);
if (n_vocab <= 0 || n_embd <= 0 || n_embd % 128) return R4D_NO(RAD_E_SHAPE);
if (w->rank != 2 || w->shape[0] != n_vocab || w->shape[1] != n_embd) return R4D_NO(RAD_E_SHAPE);
const long long stride = r4d_iqr::lm_row(f, n_embd);
long long M = 0, My = 0;
const long long x_ld = r4d_rows_pitch(x, n_embd, &M);
const long long y_ld = r4d_rows_pitch(y, n_vocab, &My);
if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE);
if (!r4d_aligned(x->data, 16) || !r4d_aligned(w->data, 256)) return R4D_NO(RAD_E_ALIGN);
const bool ch = r4d_geti_or(a, "chain", 0) != 0 && M <= 64;
int (*go)(long, long, long, int, int, int, int, int, int, long, bool) =
f.bits == 2u ? logits_gemm_8<true, 2> : f.bits == 3u ? logits_gemm_8<true, 3>
: f.bits == 4u ? logits_gemm_8<true, 4> : f.bits == 5u ? logits_gemm_8<true, 5>
: logits_gemm_8<true, 6>;
return go(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n_embd, (int)n_vocab, (int)x_ld,
(int)y_ld, (int)stride, (long)(uintptr_t)s, ch) == 0 ? RAD_OK : RAD_E_DEVICE;
}
// ============================================================== the plugin ABI entry points
//
// The shared operand reader is r4d_fp8_args.h; see libr4d/r4d_args.h.
+89 -204
View File
@@ -55,20 +55,8 @@ constexpr uint32_t kBlock = 128;
// bandwidth; 128 B is also full speed; 512 B needs 64 VGPRs of prefetch and does not build).
constexpr uint32_t kFKNarrow = 256;
// ---- the prefill tile's geometry ---------------------------------------------------------------
//
// A block owns 128 weight rows x 128 activation rows: eight waves as kPWW (weight) x kPWA
// (activation), each wave kPTW weight tiles x kPTA activation tiles of 16 x 16. Eight accumulator
// tiles a wave is a hard cap: each is two f32 sets (`raw` and `out`), so more spills. The staged K
// tile is kPFK bytes, two per 128-column scale block. See gemm_8a8_prefill_kernel for the layout
// and what was measured.
constexpr uint32_t kPTW = 2, kPTA = 4, kPWW = 4, kPWA = 2;
constexpr uint32_t kPBN = kPWW * kPTW * 16, kPBM = kPWA * kPTA * 16; // weight x activation rows
constexpr uint32_t kPWaves = kPWW * kPWA;
constexpr uint32_t kPFK = 64;
static_assert(kPBN == kBlock, "a block's weight rows are one scale row");
// Activation bands per raster group of the prefill tile; see the kernel's grouping.
constexpr uint32_t kGroupM = 8;
// ---- the prefill tile: its geometry and body (shared with the IQR tile) ------------------------
#include "r4d_gemm_8a8_prefill.h"
// Blocks the split aims for. A fixed tuning default, not derived from the CU count: `ksplit` sets
// the order K partials are summed in, so deriving it would make output depend on the card.
@@ -754,190 +742,13 @@ __global__ void splitk_reduce_kernel(const float* __restrict__ ws, uint16_t* __r
y[i] = f32_to_bf16(acc);
}
// ---- the prefill tile ---------------------------------------------------------------------------
//
// 128 weight rows x 128 activation rows a block, eight waves as kPWW (weight) x kPWA (activation),
// a wave kPTW weight tiles x kPTA activation tiles. The weight is the WMMA A operand, read from the
// fragment-order plane straight into registers: a lane's 32 bytes are its four fragments for 64 k,
// so a wave's load is one contiguous KiB and the weight never touches LDS. The activation is the B
// operand, staged through LDS and read by the four waves that share its rows. A lane's accumulator
// is eight consecutive weight rows of one activation row, so the fold takes one activation scale a
// lane a tile (and the block's one weight scale), and the store is one 16-byte write.
//
// What decides the layout is LDS bandwidth. gfx1201 serves 64 bytes of LDS a clock per CU, loads
// and stores alike, and issues an fp8 WMMA every 8 clocks per SIMD, so a CU has 256 bytes of LDS
// per WMMA at the WMMA rate (libr4d/isa/wmmamix.hip). Staging both operands with one activation
// tile x eight weight tiles a wave moves 288 bytes of fragment reads and 64 of stores per WMMA,
// which alone caps a loop at ~73% of the WMMA rate (measured with nothing else in it). This layout
// reads 128 bytes and stores 32 per WMMA, and the weight's 64 bytes come through the vector cache.
//
// At the 300 W limit every GEMM shape here is power-bound (sclk 2.1-2.3 GHz against 2.55 for bare
// WMMA on random operands), so a variant's speed tracks the bytes it moves as much as the
// instructions it issues. Measured against the both-operands-through-LDS 1x8 tile at the DiT's
// shapes (M 18648) and LLM prefill shapes (M 300-4096), 160 TFLOP/s at gate_up:
// - this layout with the per-row activation scales gathered from global, mul + add fold: +12%;
// - the activation scales staged through LDS (`s_as`), one row a thread: +4%. A lane's gather
// touched sixteen cachelines a load, more bytes than its weight fragments;
// - the fold as one fma instead of a rounded multiply and an add: +4-5%. Not bit-identical to
// the separate multiply (rel_l2 ~2e-5 against it, both well inside bf16 output);
// - unconditional prefetch (the last tile's prefetch re-reads the last tile, discarded): +1%.
// A conditional load joins two paths with different counts and the compiler waits for zero;
// - the LDS-only barrier (lds_barrier) instead of __syncthreads: +1%; the latter's release waits
// for every outstanding load, the weight prefetch included;
// - kGroupM 8 instead of 16: +1-3%; 4 ties 8.
// Measured and rejected:
// - 2 x 4 waves of 4 weight x 2 activation tiles (half the LDS reads, twice the weight bytes
// through the vector cache): 3-5% slower;
// - 8 x 1 waves (256 x 64 blocks, no weight tile read twice in a block): ties at o and gate_up;
// - the weight two tiles ahead: 240 VGPRs and scratch spills, 25-38% slower;
// - 12 or 16 waves (192 or 256 activation rows a block, up to a quarter less L2 traffic): ties
// to 1% slower, a higher clock at a lower rate per clock;
// - four threads an activation row, 16 bytes each (whole 64-byte segments a load): neutral;
// - raw buffer loads with 32-bit offsets for both operands: 20% slower;
// - s_setprio around the WMMA run: neutral. CU mode (-mcumode): ~10% slower.
template <bool I8>
template <bool I8, int RB = 0>
__global__ __launch_bounds__(kPWaves * kWave) R4D_WAVES(6)
void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restrict__ Sa,
const uint8_t* __restrict__ W, const uint16_t* __restrict__ Sw,
uint16_t* __restrict__ C, uint32_t M, uint32_t K, uint32_t N,
uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld) {
constexpr uint32_t P = lds_pitch<kPFK>();
static_assert(kPBM * 2u == kPWaves * kWave, "two threads stage an activation row");
// Double-buffered: one barrier a staged tile, which publishes it.
__shared__ __attribute__((aligned(16))) uint8_t s_a[2][kPBM * P];
// The activation scales of the current and the next 128-column block, one per block row.
__shared__ float s_as[2][kPBM];
const uint32_t tid = threadIdx.x, lane = tid % kWave;
// Uniform per wave, and through readfirstlane known so, so what derives from it stays scalar.
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
const uint32_t ww = wave % kPWW, wa = wave / kPWW;
// The grid runs in groups of kGroupM activation bands. Blocks dispatch in flattened-id order;
// with the plain x-fastest grid the activation is read once per 128 weight rows, which halves
// the rate once it exceeds the 64 MB MALL. Within a group the bands stay cached across the N
// sweep and the weight is read once per group. With kGroupM bands or fewer the plain order is
// used and the division skipped.
uint32_t bm = blockIdx.x, bn = blockIdx.y;
if (gridDim.x > kGroupM) {
const uint32_t per = kGroupM * gridDim.y;
const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x;
const uint32_t first = (lin / per) * kGroupM, r = lin % per;
const uint32_t gm = min(gridDim.x - first, kGroupM);
bm = first + r % gm;
bn = r / gm;
}
const uint32_t m0 = bm * kPBM, n0 = bn * kPBN;
const uint32_t ksuper = K / kSuperK, nkb = K / kBlock;
// Staging: two threads a row, 32 bytes each. Rows past M re-read row M-1, and every load is
// issued unconditionally (the last tile's prefetch re-reads the last tile), so the loop has no
// branch and its waits count exactly; nothing past M is stored.
const uint32_t sr = tid / 2u, sc = (tid % 2u) * 32u;
const uint8_t* const asrc = A + (size_t)min(m0 + sr, M - 1u) * a_ld + sc;
// Thread t loads the scale of block row t % 128; both threads of a row write the same value.
const float* const ssrc = Sa + (size_t)min(m0 + tid % kPBM, M - 1u) * sa_ld;
// This wave's weight tiles, kTileBytes a 64-k supertile, `ksuper` supertiles a tile row.
const uint32_t wt0 = n0 / 16u + ww * kPTW;
const uint8_t* const wsrc = W + (size_t)wt0 * ksuper * kTileBytes + lane * kLaneBytes;
// Activation rows this wave reads from the staged tile, and the lane's column in each.
const uint32_t arow = wa * kPTA * 16u;
f8v raw[kPTW][kPTA], out[kPTW][kPTA];
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) out[i][j] = acc_zero();
Stage8 pa = stage8_load(asrc, true);
Stage8 w0[kPTW], w1[kPTW];
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
w0[i] = stage8_load(wsrc + (size_t)i * ksuper * kTileBytes, true);
s_as[0][tid % kPBM] = ssrc[0];
float scn = ssrc[min(1u, nkb - 1u)];
/* One staged K tile, the first or second half of scale block `kb`: publish the activation
* tile (and in the second half the next block's scales), issue the next tile's loads, then four
* k steps from `cur`. The first k step of a block starts from a zero accumulator, so `raw` needs
* no clearing after the fold. */
auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kPTW], Stage8 (&nxt)[kPTW]) {
stage8_store<kPFK>(s_a[half], sr, sc, pa);
if (half == 1u) s_as[(kb + 1u) % 2u][tid % kPBM] = scn;
lds_barrier();
const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK);
pa = stage8_load(asrc + c1, true);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
nxt[i] = stage8_load(wsrc + ((size_t)i * ksuper + c1 / kSuperK) * kTileBytes, true);
if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)];
#pragma unroll
for (uint32_t ks = 0; ks < kPFK / kK; ++ks) {
i2v bf[kPTA];
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) bf[j] = frag<kPFK>(s_a[half], arow + j * 16u, ks * kK, lane);
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
const i2v af = frag_of(cur[i], ks);
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j)
raw[i][j] = mma8<I8>(af, bf[j], (half == 0u && ks == 0u) ? acc_zero() : raw[i][j]);
}
}
};
for (uint32_t kb = 0; kb < nkb; ++kb) {
// The weight's scales for this block, read ahead of the two tiles that hide them: one bf16
// for the block's 128 rows, or with I8 one per row, a lane's eight rows of a tile adjacent
// in the tile-major [N/16][K/128][16] plane.
float ws = 0.0f;
uint4 w8[I8 ? kPTW : 1u];
if constexpr (I8) {
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
w8[i] = *(const uint4*)(Sw + ((size_t)(wt0 + i) * nkb + kb) * 16u + (lane >> 4) * 8u);
} else {
ws = bscale(Sw[(size_t)(n0 / kBlock) * sw_ld + kb]);
}
tile(kb, 0u, w0, w1);
tile(kb, 1u, w1, w0);
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) {
const float as = s_as[kb % 2u][arow + j * 16u + frag_c(lane)];
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i) {
float s[8];
if constexpr (I8) {
const uint32_t d[4] = { w8[i].x, w8[i].y, w8[i].z, w8[i].w };
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
s[t] = as * bscale((uint16_t)(d[t / 2] >> (16 * (t % 2))));
} else {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) s[t] = ws * as;
}
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
out[i][j][t] = __builtin_fmaf(acc_val<I8>(raw[i][j][t]), s[t], out[i][j][t]);
}
}
}
// D is [weight row][activation row]: eight consecutive columns of one C row a lane a tile.
#pragma unroll
for (uint32_t i = 0; i < kPTW; ++i)
#pragma unroll
for (uint32_t j = 0; j < kPTA; ++j) {
const uint32_t m = m0 + arow + j * 16u + frag_c(lane);
const uint32_t n = n0 + (ww * kPTW + i) * 16u + acc_row(lane, 0);
if (m < M) {
const f8v v = out[i][j];
/* Packed in whole registers (bf16x2_rne, f32_to_bf16's bits). */
*(uint4*)(C + (size_t)m * N + n) =
make_uint4(bf16x2_rne(v[0], v[1]), bf16x2_rne(v[2], v[3]),
bf16x2_rne(v[4], v[5]), bf16x2_rne(v[6], v[7]));
}
}
gemm_8a8_prefill_body<I8, RB>(A, Sa, W, Sw, C, M, K, N, a_ld, sa_ld, sw_ld, PrefillPlain{});
}
// ---- the prefill tile, gated -------------------------------------------------------------------
@@ -1135,13 +946,19 @@ constexpr uint32_t kMaxCtr = 8192;
* (rad_kernel_concurrent); overlapping launches on one stream write disjoint outputs, and launches
* sharing an output on one stream are ordered by their dependency. A step has a few dozen distinct
* outputs at fixed arena addresses, so this is a few dozen 32 KiB blocks, allocated once. A block
* is never freed: a recorded pass replays the pointer. */
* is never freed: a recorded pass replays the pointer.
*
* The lock is not held while a block is made. Zeroing it waits for the card, and under tensor
* parallelism the card can be inside an all-reduce whose other half the peer rank has yet to issue;
* if the peer's first launch of a split GEMM then waited on this lock, neither rank would advance. */
unsigned int* split_ctr(RadStream s, const void* out) {
static std::mutex m;
static std::map<std::pair<RadStream, const void*>, unsigned int*> blocks;
std::lock_guard<std::mutex> lk(m);
const auto key = std::make_pair(s, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
{
std::lock_guard<std::mutex> lk(m);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
void* p = nullptr;
if (hipMalloc(&p, (size_t)kMaxCtr * sizeof(unsigned int)) != hipSuccess) return nullptr;
/* Zero before any launch reads it. In the engine hipMemset is the AQL backend's and has
@@ -1152,8 +969,15 @@ unsigned int* split_ctr(RadStream s, const void* out) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, (unsigned int*)p);
return (unsigned int*)p;
unsigned int* kept = nullptr;
{
std::lock_guard<std::mutex> lk(m);
const auto [it, fresh] = blocks.emplace(key, (unsigned int*)p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The narrow tile's wave count MW, which is its M tile: the wave grid is MW x 1, so a block covers
// MW*16 weight rows and the grid over N is N/(MW*16). The rule is fitted together with
@@ -1219,15 +1043,23 @@ uint32_t narrow_mw(uint32_t n, uint32_t m) {
* must agree. */
inline uint32_t narrow_fk(uint32_t K) { return (K % kFKNarrow == 0u) ? kFKNarrow : 128u; }
/* Test hook behind r4d_gemm_i8a8_pin_split_waves: zero is each caller's own target, anything else
* overrides every call's. The selftest pins the IQR narrow tile's target around its int8
* reference, so the two sum their K partials in one order and compare to the byte. */
std::atomic<uint32_t> g_split_waves_force{0u};
// The split, given the narrow grid. Shared by the scratch query and the launch so they agree on the
// number of partial planes. `short_unsplit` is the `gemm_nt_q_short` row's opt-in (see below).
// `target` is the waves the split aims for: kSplitTarget for the fp8a8 and i8a8 tiles; the IQR
// narrow tile (r4d_gemm_iqr.hip), whose waves decode before they multiply, asks for more.
uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out,
bool short_unsplit = false) {
bool short_unsplit = false, uint32_t target = kSplitTarget) {
*ck_out = 0;
if (const uint32_t f = g_split_waves_force.load(std::memory_order_relaxed)) target = f;
const uint32_t mw = narrow_mw(N, M);
const uint32_t fm = mw * 16u; // the narrow tile is one M tile a wave
const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over the weight rows
if (K < 512u || gx * mw >= kSplitTarget) return 1;
if (K < 512u || gx * mw >= target) return 1;
/* A narrow weight (N <= 512, the attention k/v projections) at more than 40 tokens: the split
* runs into a cliff there (gfx1200, cold weights: N = 512, K = 2048, M = 44..64 split 51-54 us,
* unsplit 23-26; K = 5120, M = 41..64 58-63 against 40-48), while at K >= 8192 the split still
@@ -1236,7 +1068,7 @@ uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out,
* opt-in: only `gemm_nt_q_short`, whose declaration the model owns, takes it, and every other
* caller keeps the split and its bits. */
if (short_unsplit && N <= 512u && M > 40u && K <= 5120u) return 1;
const uint32_t want = (kSplitTarget + gx * mw - 1) / (gx * mw);
const uint32_t want = (target + gx * mw - 1) / (gx * mw);
uint32_t ckw = ((K / want) + kBlock - 1u) / kBlock * kBlock;
if (ckw < kBlock) ckw = kBlock;
uint32_t k2 = (K + ckw - 1) / ckw;
@@ -1255,6 +1087,14 @@ uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out,
} // namespace
/* The narrow tile's grid and split rules and its finisher's counters, for the IQR narrow tile
* (r4d_gemm_iqr.hip): its split sums each output as this tile's does. */
uint32_t r4d_8a8_narrow_mw(uint32_t n, uint32_t m) { return narrow_mw(n, m); }
uint32_t r4d_8a8_narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck, uint32_t target) {
return narrow_ksplit(N, K, M, ck, false, target);
}
unsigned int* r4d_8a8_split_ctr(RadStream s, const void* out) { return split_ctr(s, out); }
// ================================================================== the entry points
extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; }
@@ -1275,6 +1115,10 @@ extern "C" int r4d_gemm_fp8a8_nt_m16_max_m(void) { return 64; }
/* See r4d.h. Only instantiated wave counts are accepted; anything else clears the override rather
* than falling through to the dispatch's last arm. */
extern "C" void r4d_gemm_i8a8_pin_split_waves(int waves) {
g_split_waves_force.store(waves > 0 ? (uint32_t)waves : 0u, std::memory_order_relaxed);
}
extern "C" void r4d_gemm_fp8a8_pin_mw(int mw) {
const uint32_t v = (mw == 1 || mw == 2 || mw == 4 || mw == 8 || mw == 16) ? (uint32_t)mw : 0u;
g_mw_force.store(v, std::memory_order_relaxed);
@@ -1590,7 +1434,7 @@ static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q
// The same GEMM for prefill row counts: same operands and layouts, the 128x128 prefill tile
// (gemm_8a8_prefill_kernel). No split-K: the grid is ceil(M/128) x N/128, hundreds of blocks at any
// prefill shape.
template <bool I8>
template <bool I8, int RB = 0>
static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
int a_ld, int sa_ld, int w_ld, int sw_ld, long stream);
@@ -1608,6 +1452,23 @@ extern "C" int r4d_gemm_i8a8_tiled(long a, long ascale, long wq, long ws, long c
return gemm_8a8_tiled<true>(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld, stream);
}
// The same with the weight's scale one per 8 rows and 128 K (each row of the plane holding its
// block's value), folded as the fp8 tile folds (gemm_8a8_prefill_kernel's RB).
extern "C" int r4d_gemm_i8a8_rb8_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld,
int sw_ld, long stream) {
return gemm_8a8_tiled<true, 8>(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld,
stream);
}
// The same at a weight scale per 32 rows, a wave's: the fp8 tile's fold.
extern "C" int r4d_gemm_i8a8_rb32_tiled(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld,
int sw_ld, long stream) {
return gemm_8a8_tiled<true, 32>(a, ascale, wq, ws, c, M, K, N, a_ld, sa_ld, w_ld, sw_ld,
stream);
}
extern "C" int r4d_gemm_i8a8_nt_m16(long a, long ascale, long wq, long ws, long c,
int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld,
long scratch, long scratch_bytes, long stream) {
@@ -1615,7 +1476,7 @@ extern "C" int r4d_gemm_i8a8_nt_m16(long a, long ascale, long wq, long ws, long
scratch, scratch_bytes, (RadStream)(uintptr_t)stream, true);
}
template <bool I8>
template <bool I8, int RB>
static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M, int K, int N,
int a_ld, int sa_ld, int w_ld, int sw_ld, long stream) {
if (!a || !ascale || !wq || !ws || !c) return -1;
@@ -1633,7 +1494,7 @@ static int gemm_8a8_tiled(long a, long ascale, long wq, long ws, long c, int M,
if (!sw_ld) sw_ld = nkb;
const dim3 grid(((uint32_t)M + kPBM - 1) / kPBM, (uint32_t)N / kPBN, 1);
const int rc = R4D_EMIT((RadStream)(uintptr_t)stream, gemm_8a8_prefill_kernel<I8>, grid,
const int rc = R4D_EMIT((RadStream)(uintptr_t)stream, (gemm_8a8_prefill_kernel<I8, RB>), grid,
dim3(kPWaves * kWave), 0, (const uint8_t*)a, (const float*)ascale,
(const uint8_t*)wq, (const uint16_t*)ws, (uint16_t*)c, (uint32_t)M,
(uint32_t)K, (uint32_t)N, (uint32_t)a_ld, (uint32_t)sa_ld,
@@ -1827,6 +1688,30 @@ extern "C" int r4d_rad_gemm_i8a8_tiled(const RadArgs* a, RadStream s) {
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_gemm_i8a8_rb8_tiled(const RadArgs* a, RadStream s) {
Fp8Ops g;
int rc = fp8_ops(a, &g, 1, FP8_OPS_ROW_SCALE);
if (rc != RAD_OK) return rc;
if (g.a->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
const int e = r4d_gemm_i8a8_rb8_tiled(
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_gemm_i8a8_rb32_tiled(const RadArgs* a, RadStream s) {
Fp8Ops g;
int rc = fp8_ops(a, &g, 1, FP8_OPS_ROW_SCALE);
if (rc != RAD_OK) return rc;
if (g.a->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
const int e = r4d_gemm_i8a8_rb32_tiled(
r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y),
(int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld,
(long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
extern "C" int r4d_rad_gemm_fp8a8_tiled(const RadArgs* a, RadStream s) {
Fp8Ops g;
int rc = fp8_ops(a, &g, 1);
+747
View File
@@ -0,0 +1,747 @@
// gemm_nt_q over the IQR weights (r4d_iqr.h), decoded from their codes where they are read; VRAM
// holds a B-bit weight in B bits. Two rows, as the int8 family's (r4d_gemm_fp8a8.hip):
//
// gemm_iqr_nt_m64 M <= 64 (decode and speculative verify). At M <= 8 a GEMV: a wave a 16-row
// tile, its lanes across K, each lane's decoded values one sudot4 against the
// activation. Above, the i8a8 narrow tile with each 128-K block's weight decoded
// and transposed into fragment order through LDS just before its WMMA steps.
// gemm_iqr_tiled any M (prefill). The i8a8 prefill tile over the int8 fragment plane in the
// caller's scratch, which the tile's blocks decode as they arrive, each value
// once.
//
// The narrow and prefill tiles compute what the int8 tiles compute over the same int8 values (their
// split, staging, accumulation order and fold), so a weight decoded here and the same weight's int8
// values in the int8 kernels give the same output bytes. The GEMV folds per lane and then sums
// across lanes: the product within f32 rounding.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_fp8_wmma.h"
#include "r4d_iqr.h"
#include "r4d_iqr_dec.h"
#include <algorithm>
#include <cstdio>
/* The i8a8 narrow tile's grid and split rules and its finisher counters (r4d_gemm_fp8a8.hip): a
* split here sums each output as the int8 tile's does. */
uint32_t r4d_8a8_narrow_mw(uint32_t n, uint32_t m);
uint32_t r4d_8a8_narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck, uint32_t target);
unsigned int* r4d_8a8_split_ctr(RadStream s, const void* out);
namespace {
using namespace r4d_fp8;
using namespace r4d_iqr;
using namespace r4d_iqr_dev;
constexpr uint32_t kWave = 32, kBlock = 128, kFK = 256;
/* The waves the narrow tile's K split aims for: four times the int8 tile's 128. A wave here decodes
* each unit and transposes it through LDS before its WMMA steps, so a weight N = 5120 rows wide
* (down, the attention and delta-net outputs: 320 waves) left unsplit keeps about one wave a SIMD
* and stalls on its own decode. At 8 tokens, 2 / 4 / 6 bits: down (K = 8704) 74 -> 54 / 56 / 66 us,
* the outputs (K = 3072) 29 -> 24 / 25 / 30 us; 1024 and more lose on the outputs. */
constexpr uint32_t kIqrSplitWaves = 512;
#include "r4d_gemm_8a8_prefill.h"
/* ---- the GEMV: M <= 8 ----------------------------------------------------------------------
*
* A wave a 16-row tile, its lanes across K: lane l takes columns 4l .. 4l + 3 of each 128-K block,
* so its decoded values of a row are one sudot4 against the activation's four bytes there, and a
* row's sum is folded into f32 with the (row, block) and (token, block) scales a block at a time,
* in each lane, then summed across the wave once at the end. The weight stream is the codes' own
* bytes, fetched a block ahead; the work a value is its decode, a quarter sudot4 a token and half
* an f32 fold. Split over K into partial planes when the tiles alone leave the card idle; the last
* z block of a column of blocks sums them in ascending z.
*
* The fold order differs from the WMMA tile's (per lane, then across lanes), so the output is the
* product within f32 rounding rather than the int8 tile's bytes. */
constexpr uint32_t kGW = 8; /* waves a block */
template <class F, uint32_t MT>
__global__ __launch_bounds__(kGW * kWave) R4D_WAVES(6)
void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restrict__ XS,
float* __restrict__ part, uint16_t* __restrict__ Y,
unsigned int* __restrict__ Ctr, uint32_t N, uint32_t x_ld, uint32_t xs_ld,
uint32_t kbs) {
using D = Dec<F, true>;
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1);
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
Ctx c = c0;
c.tab = s_tab;
D::stage(s_tab, c, tid, kGW * kWave);
__syncthreads();
const uint32_t rt = blockIdx.x * kGW + wave;
const bool alive = rt * 16u < N;
const uint32_t kb0 = blockIdx.z * kbs, kb1 = min(c.nkb, kb0 + kbs);
const uint32_t myrow = rt * 16u + (lane & 15u);
float acc[16][MT];
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) acc[q][m] = 0.0f;
typename D::Raw cur = D::fetch(c, rt, kb0, lane, alive && kb0 < kb1), nxt;
for (uint32_t kb = kb0; kb < kb1; ++kb) {
if (kb + 1u < kb1) nxt = D::fetch(c, rt, kb + 1u, lane, alive);
uint32_t xv[MT];
float as[MT];
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) {
xv[m] = *(const uint32_t*)(X + (size_t)m * x_ld + kb * kBlock + 4u * lane);
as[m] = XS[(size_t)m * xs_ld + kb];
}
/* Row (lane & 15)'s fold scale and ratio, read by every lane through readlane. */
const float fs = alive ? fold_f32<F>(c, myrow, kb) : 0.0f;
const float ratio = alive ? rb_ratio<F>(c, myrow, kb) : 0.0f;
uint32_t w[16];
/* A computed trellis off the tcq_rb grid decodes each value as its byte sum, the value
* plus 126: one sudot4 of the unsigned sums less 126 times the lane's activation sum. */
constexpr bool UNS = D::MAD && F::LRB == 0;
[[maybe_unused]] int xsum[MT];
if constexpr (UNS) {
#pragma unroll
for (uint32_t m = 0; m < MT; ++m)
xsum[m] = 126 * __builtin_amdgcn_sudot4(true, (int)xv[m], false, 0x01010101, 0, false);
}
if constexpr (UNS && MT == 1) {
/* One token: each value's hash dotted with its activation byte in every byte lane
* sums the value's bytes and multiplies in one instruction, nothing packed. */
uint32_t h[16][4];
D::hashes(cur, c, h);
uint32_t xs[4];
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) xs[e] = ((xv[0] >> (8u * e)) & 0xFFu) * 0x01010101u;
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
const float wsq = __builtin_bit_cast(float, __builtin_amdgcn_readlane(__float_as_int(fs), q));
int d = -xsum[0];
#pragma unroll
for (uint32_t e = 0; e < 4; ++e)
d = __builtin_amdgcn_sudot4(false, (int)h[q][e], true, (int)xs[e], d, false);
acc[q][0] = fmaf((float)d, wsq * as[0], acc[q][0]);
}
} else {
D::template rows<UNS>(cur, c, ratio, w);
D::unzero(c, rt, kb, w);
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
const float wsq = __builtin_bit_cast(float, __builtin_amdgcn_readlane(__float_as_int(fs), q));
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) {
int d = __builtin_amdgcn_sudot4(!UNS, (int)w[q], true, (int)xv[m], 0, false);
if constexpr (UNS) d -= xsum[m];
acc[q][m] = fmaf((float)d, wsq * as[m], acc[q][m]);
}
}
}
cur = nxt;
}
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) acc[q][m] = r4d_wave_sum(acc[q][m]);
if constexpr (F::SC == kRowF32) {
/* each row's own scale, after its blocks' sums (lane q's row q; a split's partials are
* linear in it) */
const float rs = alive ? row_scale<F>(c, rt * 16u + (lane & 15u)) : 0.0f;
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
const float rq = __builtin_bit_cast(float, __builtin_amdgcn_readlane(__float_as_int(rs), q));
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) acc[q][m] *= rq;
}
}
if (lane < 16u && alive) {
/* lane q stores row q: the sums are wave-uniform, picked by a constant index */
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
if (lane == q) {
#pragma unroll
for (uint32_t m = 0; m < MT; ++m) {
const size_t o = (size_t)m * N + rt * 16u + q;
if (gridDim.z > 1u) part[(size_t)blockIdx.z * MT * N + o] = acc[q][m];
else Y[o] = f32_to_bf16(acc[q][m]);
}
}
}
if (gridDim.z > 1u) {
__threadfence();
__syncthreads();
__shared__ unsigned int s_arrived;
if (tid == 0)
s_arrived = __hip_atomic_fetch_add(&Ctr[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (s_arrived + 1u == gridDim.z) {
if (tid == 0)
__hip_atomic_store(&Ctr[blockIdx.x], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__threadfence();
const uint32_t r0 = blockIdx.x * kGW * 16u, nr = min(kGW * 16u, N - r0);
for (uint32_t i = tid; i < nr * MT; i += kGW * kWave) {
const size_t o = (size_t)(i / nr) * N + r0 + i % nr;
float v = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) v += part[(size_t)z * MT * N + o];
Y[o] = f32_to_bf16(v);
}
}
}
}
/* ---- the narrow tile: 8 < M <= 64 -----------------------------------------------------------
*
* r4d_gemm_fp8a8.hip's gemm_fp8a8_body at I8, unfused: MW waves a block, a wave one 16-row weight
* tile against NT 16-token tiles staged through LDS, split-K over the caller's scratch with the
* last z block reducing. Only the weight operand's source differs: each 128-K block's unit is
* decoded and transposed into fragment order through the wave's LDS tile (r4d_iqr_dec.h), its two
* supertiles just before their eight WMMA steps. The int8 tile's arithmetic, so its bytes. */
template <class F, uint32_t NT, uint32_t MW>
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(MW >= 8u ? 4u : 6u)
void iqr_m64_kernel(Ctx c0, const uint8_t* __restrict__ Bp, const float* __restrict__ Sb,
void* __restrict__ Y, uint16_t* __restrict__ C, unsigned int* __restrict__ Ctr,
uint32_t rows, uint32_t cols, uint32_t nb, uint32_t b_ld, uint32_t sb_ld,
uint32_t ck) {
using D = Dec<F>;
constexpr uint32_t FK = kFK, FN = NT * 16, FM = MW * 16, kU = FK / kBlock;
__shared__ uint8_t s_b[FN * lds_pitch<FK>()];
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
__shared__ __attribute__((aligned(16))) uint8_t s_tr[MW * kTrBytes];
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave;
const uint32_t kbeg = ck ? blockIdx.z * ck : 0u;
const uint32_t kend = ck ? min(cols, kbeg + ck) : cols;
if (kbeg >= kend) return;
Ctx c = c0;
c.tab = s_tab;
uint8_t* const tr = s_tr + wave * kTrBytes;
D::stage(s_tab, c, tid, MW * kWave);
const uint32_t m0 = blockIdx.x * FM, n0 = blockIdx.y * FN;
const uint32_t wrow0 = m0 + wave * 16u;
f8v raw[NT], out[NT];
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) { raw[j] = acc_zero(); out[j] = acc_zero(); }
/* The activation's staging: the int8 narrow tile's (kTPR threads a row). */
constexpr uint32_t kSeg = 32, kTPR = FK / kSeg, kRPP = (MW * kWave) / kTPR;
constexpr uint32_t kBP = (FN + kRPP - 1) / kRPP;
const uint32_t sn = tid / kTPR, sk = (tid % kTPR) * kSeg;
const uint32_t brow0 = n0 + frag_c(lane);
const uint8_t* bsrc = Bp + (size_t)(n0 + sn) * b_ld + sk;
const uint32_t arow = wrow0 / 16u;
const bool alive = wrow0 < rows;
const bool k_live = kbeg + sk + kSeg <= cols;
Stage8 pb[kBP];
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
pb[p] = stage8_load(bsrc + (size_t)p * kRPP * b_ld + kbeg, k_live && r < FN && n0 + r < nb);
}
typename D::Raw pf[kU], pfn[kU];
#pragma unroll
for (uint32_t p = 0; p < kU; ++p) {
const uint32_t kb = kbeg / kBlock + p;
pf[p] = D::fetch(c, arow, kb, lane, alive && kb < c.nkb);
}
__syncthreads(); /* the table */
for (uint32_t c0k = kbeg; c0k < kend; c0k += FK) {
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r < FN) stage8_store<FK>(s_b, r, sk, pb[p]);
}
__syncthreads();
const uint32_t c1 = c0k + FK;
if (c1 < kend) {
const bool live = c1 + sk + kSeg <= cols;
#pragma unroll
for (uint32_t p = 0; p < kBP; ++p) {
const uint32_t r = sn + p * kRPP;
if (r < FN) pb[p] = stage8_load(bsrc + (size_t)p * kRPP * b_ld + c1, live && n0 + r < nb);
}
#pragma unroll
for (uint32_t p = 0; p < kU; ++p) {
const uint32_t kb = c1 / kBlock + p;
pfn[p] = D::fetch(c, arow, kb, lane, alive && kb < c.nkb);
}
}
#pragma unroll
for (uint32_t p = 0; p < kU; ++p) {
const uint32_t kbu = c0k / kBlock + p;
uint32_t w[16];
D::rows(pf[p], c, alive ? rb_ratio<F>(c, wrow0 + (lane & 15u), kbu) : 0.0f, w);
D::unzero(c, arow, kbu, w);
Stage8 a8[2];
frag(w, tr, lane, a8);
#pragma unroll
for (uint32_t kk = 0; kk < kBlock / kK; ++kk) {
const uint32_t ks = p * kBlock + kk * kK;
const i2v af = frag_of(a8[kk / 4u], kk % 4u);
i2v bf[NT];
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) bf[j] = frag<FK>(s_b, j * 16, ks, lane);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) raw[j] = mma8<true>(af, bf[j], raw[j]);
}
/* The unit's 128-K block is done: fold its sums. Units are 128-K aligned and a split's
* slice is a whole number of FK chunks (narrow_ksplit), so every block ends here. */
{
const uint32_t kb = kbu;
/* A lane's eight accumulator rows, consecutive rows of the wave's tile; under one
* f32 scale a row the block's factor is the same for all of them. */
float wsr[8];
if constexpr (F::SC == kRowF32) {
const float f = alive ? fold_f32<F>(c, wrow0, kb) : 0.0f;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) wsr[t] = f;
} else {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t)
wsr[t] = alive ? fold_f32<F>(c, wrow0 + acc_row(lane, t), kb) : 0.0f;
}
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t tok = brow0 + j * 16;
const float s = tok < nb ? Sb[(size_t)tok * sb_ld + kb] : 0.0f;
if constexpr (F::SC == kRowF32) {
const float ws = wsr[0] * s;
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += acc_val<true>(raw[j][t]) * ws;
raw[j][t] = 0.0f;
}
} else {
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) {
out[j][t] += acc_val<true>(raw[j][t]) * (wsr[t] * s);
raw[j][t] = 0.0f;
}
}
}
}
}
#pragma unroll
for (uint32_t p = 0; p < kU; ++p) pf[p] = pfn[p];
__syncthreads();
}
/* The int8 narrow tile's store: eight consecutive weight rows of one token a lane a tile, one
* 16-byte write (rows is a multiple of 16), into the split's partial plane or C. */
float* const part = ck ? (float*)Y + (size_t)blockIdx.z * rows * nb : nullptr;
const uint32_t cl = frag_c(lane);
#pragma unroll
for (uint32_t j = 0; j < NT; ++j) {
const uint32_t col = n0 + j * 16 + cl;
const uint32_t r0 = wrow0 + acc_row(lane, 0);
if (col >= nb || r0 >= rows) continue;
f8v ov = out[j];
if constexpr (F::SC == kRowF32)
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) ov[t] *= row_scale<F>(c, r0 + t);
const size_t o = (size_t)col * rows + r0;
if (ck) {
__attribute__((aligned(16))) float pv[8];
#pragma unroll
for (uint32_t t = 0; t < 8; ++t) pv[t] = ov[t];
*(uint4*)(part + o) = *(const uint4*)pv;
*(uint4*)(part + o + 4) = *(const uint4*)(pv + 4);
} else {
*(uint4*)(C + o) = make_uint4(bf16x2_rne(ov[0], ov[1]), bf16x2_rne(ov[2], ov[3]),
bf16x2_rne(ov[4], ov[5]), bf16x2_rne(ov[6], ov[7]));
}
}
/* The int8 narrow tile's split finisher: the last z block of a column sums the partials in
* ascending z, so the bytes are those of the separate reduce. */
if (ck && Ctr) {
__threadfence();
__syncthreads();
__shared__ unsigned int s_arrived;
if (tid == 0)
s_arrived = __hip_atomic_fetch_add(&Ctr[blockIdx.x], 1u, __ATOMIC_ACQ_REL,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
if (s_arrived + 1u == gridDim.z) {
if (tid == 0)
__hip_atomic_store(&Ctr[blockIdx.x], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__threadfence();
const uint32_t rlo = m0, rhi = min(m0 + FM, rows);
const float* const w0 = (const float*)Y;
for (uint32_t idx = tid; idx < (rhi - rlo) * nb; idx += MW * kWave) {
const uint32_t r = rlo + idx / nb, col = idx % nb;
const size_t o = (size_t)col * rows + r;
float acc = 0.0f;
for (uint32_t z = 0; z < gridDim.z; ++z) acc += w0[(size_t)z * rows * nb + o];
C[o] = f32_to_bf16(acc);
}
}
}
}
/* The split's separate reduce, for a split with no counter block (r4d_gemm_fp8a8.hip's). */
__global__ void iqr_splitk_reduce(const float* __restrict__ ws, uint16_t* __restrict__ y,
uint32_t n_out, uint32_t ksplit) {
const size_t i = (size_t)blockIdx.x * blockDim.x + threadIdx.x;
if (i >= n_out) return;
float acc = 0.0f;
for (uint32_t z = 0; z < ksplit; ++z) acc += ws[(size_t)z * n_out + i];
y[i] = f32_to_bf16(acc);
}
/* ---- the prefill: 64 < M ---------------------------------------------------------------------
*
* The int8 prefill tile (r4d_gemm_8a8_prefill.h) over the int8 fragment plane in the caller's
* scratch, which the tile's own blocks decode as they arrive. The blocks of one 128-row N tile are
* consecutive in the tile's raster order (its M bands within a group); each claims one of the N
* tile's eight 16-row tiles at a time, decodes it into the plane (and its fold scales, where the
* scale buffer is not already the int8 tile's), and once all eight are decoded every block of the
* N tile runs the K loop over them. A block claims until none is left before it waits, so it never
* waits on a block that has not started: no deadlock whatever the dispatch order. Later groups'
* blocks find the N tile decoded and go straight to the K loop; the last block of the N tile
* resets its three counters (claimed, decoded, finished), so they are zero for the next call.
*
* The decode is each value's once, overlapped with the other blocks' K loops, and the K loop is
* the int8 tile's, so the output is its bytes. */
template <class F>
struct IqrPre {
Ctx c;
uint8_t* fragp;
uint16_t* sc; /* the fold scales the tile reads, or null where the scale buffer is */
unsigned int* ctl; /* three counters an N tile */
uint32_t nbm; /* the M bands: blocks an N tile */
__device__ void begin(uint32_t bm, uint32_t bn, uint8_t* lds) const {
(void)bm;
using D = Dec<F>;
static_assert(kPWaves * kTrBytes <= kPrefillLds, "a wave's transpose tile in the staging LDS");
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
__shared__ uint32_t s_part;
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave;
unsigned int* const claimed = ctl + 3u * bn;
unsigned int* const decoded = claimed + 1;
Ctx cc = c;
cc.tab = s_tab;
uint8_t* const tr = lds + wave * kTrBytes;
const uint32_t ksuper = c.nkb * 2u;
bool staged = false;
for (;;) {
if (tid == 0)
s_part = __hip_atomic_load(decoded, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT) >= 8u
? 8u
: __hip_atomic_fetch_add(claimed, 1u, __ATOMIC_RELAXED,
__HIP_MEMORY_SCOPE_AGENT);
__syncthreads();
const uint32_t part = s_part;
__syncthreads();
if (part >= 8u) break;
if (!staged) {
D::stage(s_tab, cc, tid, kPWaves * kWave);
__syncthreads();
staged = true;
}
const uint32_t rt = bn * 8u + part;
/* A unit's codes are fetched a unit ahead of its decode, so a wave's units do not
* each wait out a memory round trip. */
typename D::Raw cur = D::fetch(cc, rt, wave, lane, wave < c.nkb), nxt;
for (uint32_t kb = wave; kb < c.nkb; kb += kPWaves) {
if (kb + kPWaves < c.nkb) nxt = D::fetch(cc, rt, kb + kPWaves, lane, true);
uint32_t w[16];
D::rows(cur, cc, rb_ratio<F>(cc, rt * 16u + (lane & 15u), kb), w);
cur = nxt;
D::unzero(cc, rt, kb, w);
Stage8 s8[2];
frag(w, tr, lane, s8);
#pragma unroll
for (uint32_t h = 0; h < 2; ++h) {
uint8_t* d = fragp + ((size_t)rt * ksuper + 2u * kb + h) * kTileBytes +
lane * kLaneBytes;
*(uint4*)d = s8[h].v;
*(uint4*)(d + 16) = s8[h].w;
}
}
if (sc)
for (uint32_t i = tid; i < 16u * c.nkb; i += kPWaves * kWave) {
const uint32_t kb = i / 16u;
sc[((size_t)rt * c.nkb + kb) * 16u + i % 16u] =
(uint16_t)fold_scale<F>(cc, rt * 16u + i % 16u, kb);
}
__threadfence();
__syncthreads();
if (tid == 0)
__hip_atomic_fetch_add(decoded, 1u, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_AGENT);
}
if (tid == 0)
while (__hip_atomic_load(decoded, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_AGENT) < 8u)
__builtin_amdgcn_s_sleep(2);
__syncthreads();
}
__device__ void end(uint32_t bn) const {
if (threadIdx.x != 0) return;
unsigned int* const claimed = ctl + 3u * bn;
if (__hip_atomic_fetch_add(claimed + 2, 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT) + 1u ==
nbm) {
__hip_atomic_store(claimed, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__hip_atomic_store(claimed + 1, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
__hip_atomic_store(claimed + 2, 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
}
}
};
template <class F, int RB>
__global__ __launch_bounds__(kPWaves * kWave) R4D_WAVES(6)
void iqr_prefill_kernel(IqrPre<F> pre, const uint8_t* __restrict__ A, const float* __restrict__ Sa,
const uint8_t* __restrict__ W, const uint16_t* __restrict__ Sw,
uint16_t* __restrict__ C, uint32_t M, uint32_t K, uint32_t N, uint32_t a_ld,
uint32_t sa_ld, uint32_t sw_ld) {
if constexpr (F::SC == kRowF32) {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint8_t* const sb = pre.c.S;
gemm_8a8_prefill_body<true, 32, IqrPre<F>, true>(
A, Sa, W, Sw, C, M, K, N, a_ld, sa_ld, sw_ld, pre, (const float*)sb,
(const float*)(sb + cf_off(f, N, K)));
} else {
gemm_8a8_prefill_body<true, RB>(A, Sa, W, Sw, C, M, K, N, a_ld, sa_ld, sw_ld, pre);
}
}
/* ---- the forms built: r4d_iqr.h's list ------------------------------------------------ */
#define R4D_IQR_T(k, b, lv, l, lrb, sc) FormT<k, b, lv, l, lrb, sc>
struct Operands {
const RadTensor *a, *as, *b, *bs, *y;
long long M, N, K, nkb, a_ld, sa_ld;
uint32_t word;
};
int operands(const RadArgs* a, Operands* g) {
g->a = r4d_opt(a, 0);
g->as = r4d_opt(a, 1);
g->b = r4d_opt(a, 2);
g->bs = r4d_opt(a, 3);
g->y = r4d_opt(a, 4);
if (!g->a || !g->as || !g->b || !g->bs || !g->y) return R4D_NO(RAD_E_INVAL);
if (!is_weight_dtype(g->b->dtype) || !is_scale_dtype(g->bs->dtype)) return R4D_NO(RAD_E_DTYPE);
g->word = g->b->dtype & kWordMask;
if ((g->bs->dtype & kWordMask) != g->word) return R4D_NO(RAD_E_DTYPE);
if (g->a->dtype != RAD_I8 || g->as->dtype != RAD_F32 || g->y->dtype != RAD_BF16)
return R4D_NO(RAD_E_DTYPE);
if (g->b->rank != 2 || g->y->rank < 2 || g->a->rank < 2 || g->as->rank != 2)
return R4D_NO(RAD_E_SHAPE);
g->M = g->y->shape[0];
if (g->M < 1 || r4d_numel(g->y) % g->M) return R4D_NO(RAD_E_SHAPE);
g->N = r4d_numel(g->y) / g->M;
g->K = g->b->shape[1];
if (g->b->shape[0] != g->N || g->N % 16 || g->K % kFK) return R4D_NO(RAD_E_SHAPE);
g->nkb = g->K / kBlock;
if (g->a->shape[0] != g->M || r4d_numel(g->a) != g->M * g->K) return R4D_NO(RAD_E_SHAPE);
if (g->as->shape[0] != g->M || g->as->shape[1] != g->nkb) return R4D_NO(RAD_E_SHAPE);
g->a_ld = r4d_row_pitch(g->a);
g->sa_ld = r4d_row_pitch(g->as);
if (g->a_ld < 0 || g->sa_ld < 0 || r4d_row_pitch(g->y) != g->N) return R4D_NO(RAD_E_STRIDE);
if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 256)) return R4D_NO(RAD_E_ALIGN);
const Form f = form(g->word);
if (is_trellis(f.kind) && g->N % ((long long)1 << f.lrun)) return R4D_NO(RAD_E_SHAPE);
return RAD_OK;
}
Ctx ctx_of(const Operands& g) {
Ctx c{};
c.W = (const uint8_t*)g.b->data;
c.S = (const uint8_t*)g.bs->data;
c.N = (uint32_t)g.N;
c.nkb = (uint32_t)g.nkb;
const Form f = form(g.word);
c.run_tiles = is_trellis(f.kind) ? (1u << f.lrun) / 16u : 1u;
return c;
}
/* The GEMV's K split: enough waves to keep the card's memory busy (2048 tiles' worth), each split at
* least four blocks. A function of N and K alone. */
constexpr uint32_t kGemvMaxM = 8;
uint32_t gemv_ksplit(uint32_t N, uint32_t nkb) {
const uint32_t tiles = N / 16u;
uint32_t ks = std::min((2048u + tiles - 1u) / tiles, std::max(1u, nkb / 4u));
const uint32_t kbs = (nkb + ks - 1u) / ks;
return (nkb + kbs - 1u) / kbs;
}
template <class F>
int gemv_launch(const Operands& g, void* scratch, long long scratch_bytes, RadStream stream) {
const uint32_t N = (uint32_t)g.N, M = (uint32_t)g.M, nkb = (uint32_t)g.nkb;
uint32_t ks = gemv_ksplit(N, nkb);
const uint32_t gx = (N / 16u + kGW - 1u) / kGW;
unsigned int* ctr = nullptr;
if (ks > 1u) {
ctr = gx <= 8192u ? r4d_8a8_split_ctr(stream, g.y->data) : nullptr;
if (!ctr || !scratch || scratch_bytes < (long long)ks * kGemvMaxM * N * 4) ks = 1u;
}
const uint32_t kbs = (nkb + ks - 1u) / ks;
const Ctx c = ctx_of(g);
const dim3 grid(gx, 1, ks);
int rc = RAD_E_SHAPE;
#define R4D_IQR_GV(mt_) rc = R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_>), grid, dim3(kGW * kWave), 0, c, (const int8_t*)g.a->data, (const float*)g.as->data, (float*)scratch, (uint16_t*)g.y->data, ctr, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, kbs)
switch (M) {
case 1u: R4D_IQR_GV(1u); break;
case 2u: R4D_IQR_GV(2u); break;
case 3u: R4D_IQR_GV(3u); break;
case 4u: R4D_IQR_GV(4u); break;
case 5u: R4D_IQR_GV(5u); break;
case 6u: R4D_IQR_GV(6u); break;
case 7u: R4D_IQR_GV(7u); break;
case 8u: R4D_IQR_GV(8u); break;
default: return R4D_NO(RAD_E_SHAPE);
}
#undef R4D_IQR_GV
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
template <class F>
int m64_launch(const Operands& g, void* scratch, long long scratch_bytes, int split_n,
RadStream stream) {
const uint32_t N = (uint32_t)g.N, K = (uint32_t)g.K, M = (uint32_t)g.M;
/* A computed trellis's GEMV pays its decode in VALU work beside every token's dot and fold;
* from five tokens the narrow tile, which decodes a unit once for all of them, is faster
* (gate_up at 4 bits: GEMV 120 / 136 / 186 us at 3 / 4 / 8 tokens, the tile 151 / 154 / 157). */
constexpr uint32_t gemv_max = F::KIND == kTrellisMad ? 4u : kGemvMaxM;
if (M <= gemv_max) return gemv_launch<F>(g, scratch, scratch_bytes, stream);
/* At most eight waves a block: each has its own transpose tile in LDS. The wave count changes
* no output bit (r4d_gemm_fp8a8.hip's narrow_mw). */
const uint32_t mw = std::min(r4d_8a8_narrow_mw(N, M), 8u);
const uint32_t gx = (N + mw * 16u - 1) / (mw * 16u);
uint32_t ck = 0;
uint32_t ksplit = r4d_8a8_narrow_ksplit(split_n > 0 ? (uint32_t)split_n : N, K, M, &ck,
kIqrSplitWaves);
const long long need = ksplit > 1 ? (long long)ksplit * M * N * 4 : 0;
if (need && (!scratch || scratch_bytes < need)) { ksplit = 1; ck = 0; }
const uint32_t nt = M > 48 ? 4u : M > 32 ? 3u : M > 16 ? 2u : 1u;
unsigned int* const ctr =
ksplit > 1 && gx <= 8192u ? r4d_8a8_split_ctr(stream, g.y->data) : nullptr;
void* const dst = ksplit > 1 ? scratch : g.y->data;
const Ctx c = ctx_of(g);
const dim3 grid(gx, 1, ksplit);
int rc = RAD_E_SHAPE;
#define R4D_IQR_M64(mw_, nt_) \
rc = R4D_EMIT(stream, (iqr_m64_kernel<F, nt_, mw_>), grid, dim3(mw_ * kWave), 0, c, \
(const uint8_t*)g.a->data, (const float*)g.as->data, dst, (uint16_t*)g.y->data, \
ctr, N, K, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, ck)
#define R4D_IQR_M64_NT(mw_) \
do { if (nt == 4u) R4D_IQR_M64(mw_, 4u); else if (nt == 3u) R4D_IQR_M64(mw_, 3u); \
else if (nt == 2u) R4D_IQR_M64(mw_, 2u); else R4D_IQR_M64(mw_, 1u); } while (0)
if (mw == 4u) R4D_IQR_M64_NT(4u);
else if (mw == 8u) R4D_IQR_M64_NT(8u);
else return R4D_NO(RAD_E_SHAPE);
#undef R4D_IQR_M64_NT
#undef R4D_IQR_M64
if (rc != RAD_OK || hipGetLastError() != hipSuccess) return R4D_NO(RAD_E_DEVICE);
if (ksplit > 1 && !ctr) {
const uint32_t n = M * N;
if (R4D_EMIT(stream, iqr_splitk_reduce, dim3((n + 255) / 256), dim3(256), 0,
(const float*)scratch, (uint16_t*)g.y->data, n, ksplit) != RAD_OK)
return R4D_NO(RAD_E_DEVICE);
}
return RAD_OK;
}
/* The prefill's scratch: the int8 fragment plane, then (unless the scale buffer already is the
* int8 tile's) its bf16 tile-major scales. */
bool own_scales_serve(const Form& f) {
return (f.scale == kBf16 && f.lrb == 0) || f.scale == kRowF32; /* kRowF32: read in place */
}
long long tiled_scratch(const Form& f, long long N, long long K) {
return align256(N * K) + (own_scales_serve(f) ? 0 : align256(N * (K / kBlock) * 2));
}
template <class F>
int tiled_launch(const Operands& g, void* scratch, long long scratch_bytes, RadStream stream) {
const Form f = form(g.word);
if (!scratch || scratch_bytes < tiled_scratch(f, g.N, g.K)) return R4D_NO(RAD_E_SHAPE);
if (g.N % kPBN || (uintptr_t)g.y->data & 15u) return R4D_NO(RAD_E_SHAPE);
unsigned int* const ctl = r4d_8a8_split_ctr(stream, g.y->data);
if (!ctl || 3u * (uint32_t)(g.N / kPBN) > 8192u) return R4D_NO(RAD_E_DEVICE);
IqrPre<F> pre;
pre.c = ctx_of(g);
pre.fragp = (uint8_t*)scratch;
pre.sc = own_scales_serve(f) ? nullptr : (uint16_t*)(pre.fragp + align256(g.N * g.K));
pre.ctl = ctl;
const dim3 grid((uint32_t)((g.M + kPBM - 1) / kPBM), (uint32_t)(g.N / kPBN), 1);
pre.nbm = grid.x;
const uint16_t* const ws = pre.sc ? pre.sc : (const uint16_t*)g.bs->data;
int rc;
#define R4D_IQR_PF(rb_) \
rc = R4D_EMIT(stream, (iqr_prefill_kernel<F, rb_>), grid, dim3(kPWaves * kWave), 0, pre, \
(const uint8_t*)g.a->data, (const float*)g.as->data, (const uint8_t*)pre.fragp, \
ws, (uint16_t*)g.y->data, (uint32_t)g.M, (uint32_t)g.K, (uint32_t)g.N, \
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, (uint32_t)g.nkb)
if (f.lrb >= 5) R4D_IQR_PF(32);
else if (f.lrb >= 3) R4D_IQR_PF(8);
else R4D_IQR_PF(0);
#undef R4D_IQR_PF
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
} // namespace
extern "C" int64_t r4d_rad_gemm_iqr_m64_scratch(const RadArgs* a) {
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0),
K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0);
if (M < 1 || N < 1 || K < 1 || M > 64) return 0;
uint32_t ck = 0;
const uint32_t k2 = r4d_8a8_narrow_ksplit((uint32_t)(sn > 0 ? sn : N), (uint32_t)K,
(uint32_t)M, &ck, kIqrSplitWaves);
/* The band's bound covers the GEMV's split at M <= 4 too. */
const int64_t tile = k2 > 1 ? (int64_t)k2 * M * N * 4 : 0;
const uint32_t kg = gemv_ksplit((uint32_t)N, (uint32_t)(K / kBlock));
const int64_t gemv = kg > 1 ? (int64_t)kg * kGemvMaxM * N * 4 : 0;
return std::max(tile, gemv);
}
extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
Operands g;
const int rc = operands(a, &g);
if (rc != RAD_OK) return rc;
if (g.M > 64) return R4D_NO(RAD_E_SHAPE);
const uint32_t kw = kernel_word(g.word);
const int sn = (int)r4d_geti_or(a, "split_n", 0);
#define R4D_IQR_GO(...) \
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return m64_launch<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, sn, s);
R4D_IQR_FORMS(R4D_IQR_GO)
#undef R4D_IQR_GO
return R4D_NO(RAD_E_UNSUPPORTED);
}
extern "C" int64_t r4d_rad_gemm_iqr_tiled_scratch(const RadArgs* a) {
const long long N = r4d_geti_or(a, "N", 0), K = r4d_geti_or(a, "K", 0);
if (N < 1 || K < 1) return 0;
/* The scale part's size is the form's; the bound covers every form. */
Form f;
f.scale = kE4m3Tensor;
return (int64_t)tiled_scratch(f, N, K);
}
extern "C" int r4d_rad_gemm_iqr_tiled(const RadArgs* a, RadStream s) {
Operands g;
const int rc = operands(a, &g);
if (rc != RAD_OK) return rc;
if (g.N % kBlock) return R4D_NO(RAD_E_SHAPE);
const uint32_t kw = kernel_word(g.word);
#define R4D_IQR_GO(...) \
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) \
return tiled_launch<R4D_IQR_T(__VA_ARGS__)>(g, a->scratch, (long long)a->scratch_bytes, s);
R4D_IQR_FORMS(R4D_IQR_GO)
#undef R4D_IQR_GO
return R4D_NO(RAD_E_UNSUPPORTED);
}
+15 -4
View File
@@ -466,9 +466,13 @@ unsigned* m2d_out_ctr(const void* out) {
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
const size_t n = R4D_M2D_MAX_N / (R4D_M2D_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
@@ -479,8 +483,15 @@ unsigned* m2d_out_ctr(const void* out) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule).
+15 -4
View File
@@ -495,9 +495,13 @@ unsigned* mxd_out_ctr(const void* out) {
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
const size_t n = R4D_MXD_MAX_N / (R4D_MXD_DWN * 16);
unsigned* p = nullptr;
if (hipMalloc((void**)&p, n * sizeof(unsigned)) != hipSuccess) return nullptr;
@@ -508,8 +512,15 @@ unsigned* mxd_out_ctr(const void* out) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The split, slab and load hint for a launch, from M, the shape and the tunables (0 = the rule; see
+15 -4
View File
@@ -678,9 +678,13 @@ unsigned* mxgg_out_ctr(const void* out) {
static std::map<std::pair<int, const void*>, unsigned*> blocks;
int dev = 0;
if (hipGetDevice(&dev) != hipSuccess) return nullptr;
std::lock_guard<std::mutex> lk(mu);
const auto key = std::make_pair(dev, out);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
{
// Not held while the block is made, as in split_ctr (r4d_gemm_fp8a8.hip): the zeroing waits
// for the card.
std::lock_guard<std::mutex> lk(mu);
if (auto it = blocks.find(key); it != blocks.end()) return it->second;
}
unsigned* p = nullptr;
if (hipMalloc((void**)&p, R4D_MXGG_MAX_GROUPS * sizeof(unsigned)) != hipSuccess) return nullptr;
// Zero before any launch reads it: the memset is on the null stream, which the engine's streams
@@ -690,8 +694,15 @@ unsigned* mxgg_out_ctr(const void* out) {
(void)hipFree(p);
return nullptr;
}
blocks.emplace(key, p);
return p;
unsigned* kept = nullptr;
{
std::lock_guard<std::mutex> lk(mu);
const auto [it, fresh] = blocks.emplace(key, p);
if (fresh) return it->second;
kept = it->second;
}
(void)hipFree(p); // another thread made this key's block in the meantime
return kept;
}
// The scratch: the bf16 product [M, n], then each tile's per-row amax [n / 16][M] fp32.
+123 -47
View File
@@ -9,8 +9,8 @@
//
// E4M3 input: the taps are the MoE block's own quantiser outputs (`had_quant_act_fp8` for gate_up,
// `gated_had_quant_fp8` for down), the bytes the expert GEMM actually contracts, and the only form
// the rotated path stores. A bf16 instantiation reads the plain activation of a bf16-served model;
// everything past the staging is shared.
// the rotated path stores, contracted by a scalar kernel. A plain bf16 activation (a bf16-served
// model's) goes through the matrix cores instead: see gram_accum_bf16_wmma.
//
// The gate_up tap is the unsorted activation. Every token is routed to exactly top_k experts, so
// the expert GEMM's input distribution gives H_sorted = top_k * H_token, and GPTQ is invariant to a
@@ -26,6 +26,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_fp8_wmma.h"
#include "r4d_gdn_wmma.h"
namespace {
@@ -37,12 +38,13 @@ constexpr int kThreads = 256;
constexpr int kMB = 32; // M rows staged a pass; 2 * 32 * 64 * 4 = 16 KiB of LDS
constexpr int kTT = 4;
/* BF16 reads a plain bf16 activation with no scale: a staging slot is four elements in two dwords.
* Everything after the staging is shared with the fp8 form. */
template <bool BF16>
__global__ __launch_bounds__(kThreads) void gram_accum_kernel(
const void* __restrict__ qv, const float* __restrict__ sc, float* __restrict__ h,
uint32_t M, uint32_t K, uint32_t q_ld, uint32_t s_ld, uint32_t h_ld, uint32_t grp) {
uint32_t M, uint32_t K, uint32_t q_ld, uint32_t s_ld, uint32_t h_ld, uint32_t grp,
uint32_t upper) {
// `upper`: only the tiles on or above the diagonal; H is symmetric, and a caller that reads
// only k2 >= k1 halves the work.
if (upper && blockIdx.y < blockIdx.x) return;
__shared__ float sa[kMB][kTile];
__shared__ float sb[kMB][kTile];
@@ -50,8 +52,8 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
const uint32_t k1_0 = blockIdx.x * (uint32_t)kTile;
const uint32_t k2_0 = blockIdx.y * (uint32_t)kTile;
const uint32_t tx = threadIdx.x & 15u, ty = threadIdx.x >> 4; // 16 x 16
// Both tiles sit inside one scale group each -- see kTile's note. bf16 has no groups.
const uint32_t g1 = BF16 ? 0u : k1_0 / grp, g2 = BF16 ? 0u : k2_0 / grp;
// Both tiles sit inside one scale group each -- see kTile's note.
const uint32_t g1 = k1_0 / grp, g2 = k2_0 / grp;
float acc[kTT][kTT];
#pragma unroll
@@ -72,33 +74,19 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
if (m < M) {
const size_t qrow = (size_t)m * q_ld;
const uint32_t c1 = k1_0 + cq, c2 = k2_0 + cq;
if constexpr (BF16) {
// K is a multiple of four, so a slot never runs past the row.
if (c1 < K) {
const uint2 w = *(const uint2*)((const uint16_t*)qv + qrow + c1);
a0 = bf16_to_f32((uint16_t)w.x); a1 = bf16_to_f32((uint16_t)(w.x >> 16));
a2 = bf16_to_f32((uint16_t)w.y); a3 = bf16_to_f32((uint16_t)(w.y >> 16));
}
if (c2 < K) {
const uint2 w = *(const uint2*)((const uint16_t*)qv + qrow + c2);
b0 = bf16_to_f32((uint16_t)w.x); b1 = bf16_to_f32((uint16_t)(w.x >> 16));
b2 = bf16_to_f32((uint16_t)w.y); b3 = bf16_to_f32((uint16_t)(w.y >> 16));
}
} else {
if (c1 < K) {
// The row is owned out to K rounded up to four bytes (quant_act_fp8's
// contract), so a dword load at c1 < K stays inside the allocation.
const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c1);
const float s = sc[(size_t)m * s_ld + g1];
const v2f lo = r4d_fp8::e4m3_pk<false>(w), hi = r4d_fp8::e4m3_pk<true>(w);
a0 = lo.x * s; a1 = lo.y * s; a2 = hi.x * s; a3 = hi.y * s;
}
if (c2 < K) {
const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c2);
const float s = sc[(size_t)m * s_ld + g2];
const v2f lo = r4d_fp8::e4m3_pk<false>(w), hi = r4d_fp8::e4m3_pk<true>(w);
b0 = lo.x * s; b1 = lo.y * s; b2 = hi.x * s; b3 = hi.y * s;
}
if (c1 < K) {
// The row is owned out to K rounded up to four bytes (quant_act_fp8's
// contract), so a dword load at c1 < K stays inside the allocation.
const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c1);
const float s = sc[(size_t)m * s_ld + g1];
const v2f lo = r4d_fp8::e4m3_pk<false>(w), hi = r4d_fp8::e4m3_pk<true>(w);
a0 = lo.x * s; a1 = lo.y * s; a2 = hi.x * s; a3 = hi.y * s;
}
if (c2 < K) {
const uint32_t w = *(const uint32_t*)((const uint8_t*)qv + qrow + c2);
const float s = sc[(size_t)m * s_ld + g2];
const v2f lo = r4d_fp8::e4m3_pk<false>(w), hi = r4d_fp8::e4m3_pk<true>(w);
b0 = lo.x * s; b1 = lo.y * s; b2 = hi.x * s; b3 = hi.y * s;
}
}
// Columns past K stage as zeros and contribute nothing; the store masks them anyway.
@@ -135,15 +123,101 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
}
}
// The bf16 form on the matrix cores. One 256-thread block owns a 128x128 C tile; its eight waves
// each own 32x64 of it (2x4 WMMA tiles of 16x16). The contraction runs over the M rows: a pass
// stages 64 rows of both column strips into LDS row-major ([row][column], as they lie in global)
// and each wave reads its fragments transposed (fragT), eight 16-bit reads a fragment. A transpose
// at staging would cost the same reads as stores with an 8-way bank conflict. Products of bf16
// are exact in f32 and WMMA accumulates in f32, so this matches the scalar form up to summation
// order, and an entry and its mirror are the same products in the same order (symmetric to the
// bit). `upper` keeps the scalar form's 64-tile rule, so both forms touch the same entries.
constexpr int kWT = 128; // C tile
constexpr int kWMB = 64; // M rows staged a pass: four 16-deep WMMA steps
constexpr int kWP = kWT + 8; // LDS pitch: the two half-waves' rows land 16 banks apart
__device__ __forceinline__ v8bf gram_frag(const unsigned short* src, int base, int kbase, int lane) {
return fragT(src, kWP, base, kbase, lane);
}
__global__ __launch_bounds__(kThreads) void gram_accum_bf16_wmma(
const uint16_t* __restrict__ x, float* __restrict__ h, uint32_t M, uint32_t K, uint32_t x_ld,
uint32_t h_ld, uint32_t upper) {
if (upper && blockIdx.y < blockIdx.x) return;
__shared__ __attribute__((aligned(16))) unsigned short sa[kWMB * kWP];
__shared__ __attribute__((aligned(16))) unsigned short sb[kWMB * kWP];
const uint32_t k1_0 = blockIdx.x * (uint32_t)kWT, k2_0 = blockIdx.y * (uint32_t)kWT;
const bool diag = blockIdx.x == blockIdx.y; // both strips are the same columns
const int lane = (int)(threadIdx.x & 31u), wave = (int)(threadIdx.x >> 5);
const int wr = (wave & 3) * 32, wc = (wave >> 2) * 64;
v8f acc[2][4];
#pragma unroll
for (int i = 0; i < 2; ++i)
#pragma unroll
for (int j = 0; j < 4; ++j)
#pragma unroll
for (int e = 0; e < 8; ++e) acc[i][j][e] = 0.0f;
for (uint32_t m0 = 0; m0 < M; m0 += (uint32_t)kWMB) {
__syncthreads();
// 64 rows x 32 slots of four columns = 2048 a strip, eight per thread. K is a multiple
// of four, so a slot is wholly inside or wholly past the row.
for (uint32_t idx = threadIdx.x; idx < (uint32_t)(kWMB * kWT / 4); idx += (uint32_t)kThreads) {
const uint32_t mi = idx >> 5, c = (idx & 31u) * 4u;
const uint32_t m = m0 + mi;
uint2 wa = make_uint2(0u, 0u), wb = make_uint2(0u, 0u);
if (m < M) {
const uint16_t* row = x + (size_t)m * x_ld;
if (k1_0 + c < K) wa = *(const uint2*)(row + k1_0 + c);
if (!diag && k2_0 + c < K) wb = *(const uint2*)(row + k2_0 + c);
}
*(uint2*)(sa + mi * kWP + c) = wa;
if (!diag) *(uint2*)(sb + mi * kWP + c) = wb;
}
__syncthreads();
const unsigned short* B = diag ? sa : sb;
// Rows past M were staged as zeros, so a whole pass runs and adds nothing for them.
#pragma unroll
for (int ks = 0; ks < kWMB / 16; ++ks) {
v8bf fa[2], fb[4];
#pragma unroll
for (int i = 0; i < 2; ++i) fa[i] = gram_frag(sa, wr + i * 16, ks * 16, lane);
#pragma unroll
for (int j = 0; j < 4; ++j) fb[j] = gram_frag(B, wc + j * 16, ks * 16, lane);
#pragma unroll
for (int i = 0; i < 2; ++i)
#pragma unroll
for (int j = 0; j < 4; ++j) acc[i][j] = mma(fa[i], fb[j], acc[i][j]);
}
}
// D: column n = lane % 16 of the B strip (k2), rows m = 8 * (lane / 16) + e of the A strip
// (k1). One block owns the tile, so the read-modify-write is race-free.
#pragma unroll
for (int i = 0; i < 2; ++i)
#pragma unroll
for (int j = 0; j < 4; ++j) {
const uint32_t k2 = k2_0 + (uint32_t)(wc + j * 16 + (lane & 15));
if (k2 >= K) continue;
#pragma unroll
for (int e = 0; e < 8; ++e) {
const uint32_t k1 = k1_0 + (uint32_t)(wr + i * 16 + 8 * (lane >> 4) + e);
if (k1 >= K || (upper && k2 / (uint32_t)kTile < k1 / (uint32_t)kTile)) continue;
h[(size_t)k1 * h_ld + k2] += acc[i][j][e];
}
}
}
} // namespace
extern "C" int r4d_gram_accum_fp8_tile(void) { return kTile; }
// q [M][K] E4M3, `q_ld` bytes a row (0 = K), owned out to a multiple of 4
// s [M][ceil(K/grp)] f32, `s_ld` elements a row (0 = ceil(K/grp))
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written; with `upper`
// only the 64-wide tiles on or above the diagonal are added to
extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp,
int q_ld, int s_ld, int h_ld, long stream) {
int q_ld, int s_ld, int h_ld, int upper, long stream) {
if (!q || !s || !h) return -1;
if (M <= 0 || K <= 0) return -2;
if (K % 4) return -3; // a staging slot is one dword of four codes
@@ -153,26 +227,27 @@ extern "C" int r4d_gram_accum_fp8(long q, long s, long h, int M, int K, int grp,
if (!s_ld) s_ld = (K + grp - 1) / grp;
if (!h_ld) h_ld = K;
const uint32_t nt = (uint32_t)((K + kTile - 1) / kTile);
hipLaunchKernelGGL(gram_accum_kernel<false>, dim3(nt, nt), dim3(kThreads), 0,
hipLaunchKernelGGL(gram_accum_kernel, dim3(nt, nt), dim3(kThreads), 0,
(hipStream_t)stream, (const void*)q, (const float*)s, (float*)h,
(uint32_t)M, (uint32_t)K, (uint32_t)q_ld, (uint32_t)s_ld, (uint32_t)h_ld,
(uint32_t)grp);
(uint32_t)grp, (uint32_t)(upper != 0));
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// a [M][K] bf16, `a_ld` elements a row (0 = K)
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written
extern "C" int r4d_gram_accum_bf16(long a, long h, int M, int K, int a_ld, int h_ld, long stream) {
// h [K][K] f32, `h_ld` elements a row (0 = K), read and written; `upper` as above
extern "C" int r4d_gram_accum_bf16(long a, long h, int M, int K, int a_ld, int h_ld, int upper,
long stream) {
if (!a || !h) return -1;
if (M <= 0 || K <= 0) return -2;
if (K % 4) return -3; // a staging slot is four elements of one row
if (!a_ld) a_ld = K;
if (a_ld % 4 || (a % 8)) return -6; // ...loaded as two aligned dwords
if (!h_ld) h_ld = K;
const uint32_t nt = (uint32_t)((K + kTile - 1) / kTile);
hipLaunchKernelGGL(gram_accum_kernel<true>, dim3(nt, nt), dim3(kThreads), 0,
(hipStream_t)stream, (const void*)a, (const float*)nullptr, (float*)h,
(uint32_t)M, (uint32_t)K, (uint32_t)a_ld, 0u, (uint32_t)h_ld, 1u);
const uint32_t nt = (uint32_t)((K + kWT - 1) / kWT);
hipLaunchKernelGGL(gram_accum_bf16_wmma, dim3(nt, nt), dim3(kThreads), 0, (hipStream_t)stream,
(const uint16_t*)a, (float*)h, (uint32_t)M, (uint32_t)K, (uint32_t)a_ld,
(uint32_t)h_ld, (uint32_t)(upper != 0));
return hipGetLastError() == hipSuccess ? 0 : -4;
}
@@ -200,7 +275,8 @@ extern "C" int r4d_rad_gram_accum(const RadArgs* a, RadStream s) {
const long long qp = r4d_row_pitch(q), sp = r4d_row_pitch(sc), hp = r4d_row_pitch(h);
if (qp < 0 || sp < 0 || hp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = r4d_gram_accum_fp8(r4d_addr(q), r4d_addr(sc), r4d_addr(h), (int)M, (int)K,
(int)grp, (int)qp, (int)sp, (int)hp, (long)(uintptr_t)s);
(int)grp, (int)qp, (int)sp, (int)hp,
(int)r4d_geti_or(a, "upper", 0), (long)(uintptr_t)s);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
@@ -219,6 +295,6 @@ extern "C" int r4d_rad_gram_accum_bf16(const RadArgs* a, RadStream s) {
const long long xp = r4d_row_pitch(x), hp = r4d_row_pitch(h);
if (xp < 0 || hp < 0) return R4D_NO(RAD_E_STRIDE);
const int e = r4d_gram_accum_bf16(r4d_addr(x), r4d_addr(h), (int)M, (int)K, (int)xp, (int)hp,
(long)(uintptr_t)s);
(int)r4d_geti_or(a, "upper", 0), (long)(uintptr_t)s);
return e == 0 ? RAD_OK : R4D_NO(RAD_E_SHAPE);
}
+5 -2
View File
@@ -3199,7 +3199,10 @@ void hc_quant_rows_kernel(const unsigned short* __restrict__ x, unsigned char* _
constexpr unsigned kMaxMixCtr = 2048;
unsigned int* hc_mix_ctr(RadStream s) {
static std::mutex m;
/* A lock a device: zeroing a block waits for the card, and under tensor parallelism the card
* can be inside an all-reduce whose other half the peer rank has yet to issue, so a peer's
* first call must not wait behind this card's (see split_ctr). */
static std::mutex m[16];
struct Slot { std::atomic<RadStream> key{nullptr}; std::atomic<unsigned int*> ctr{nullptr}; };
static Slot slot[16][4];
int dev = 0;
@@ -3207,7 +3210,7 @@ unsigned int* hc_mix_ctr(RadStream s) {
for (int i = 0; i < 4; ++i)
if (slot[dev][i].key.load(std::memory_order_acquire) == s)
return slot[dev][i].ctr.load(std::memory_order_acquire);
std::lock_guard<std::mutex> lk(m);
std::lock_guard<std::mutex> lk(m[dev]);
for (int i = 0; i < 4; ++i)
if (slot[dev][i].key.load(std::memory_order_relaxed) == s)
return slot[dev][i].ctr.load(std::memory_order_relaxed);
+264
View File
@@ -0,0 +1,264 @@
/* r4d_iqr.h -- the narrow int8-grid weights (IQR) as libr4d keeps them in VRAM: the stored codes
* reordered for the GEMMs that decode them, never widened. Pure C++ (no HIP), shared by the layout
* hooks (r4d_iqr_layout.cpp) and the kernels (r4d_gemm_iqr.hip).
*
* Every form is an int8 value per weight times a scale per (row, 128 K), the int8 grid IQ8R's GEMMs
* read, and every form's int8 value is a function of its codes alone, so a kernel decodes it where
* it reads it:
* - Signed iB codes, the value itself (B = 2..7);
* - Zero uB codes less a zero per (row, 128) (u6 codes under a u6 zero in IQ6R);
* - Table uB codes indexing a table of up to 2^B int8 values (IQR-V1's scalar codebooks);
* - Grid one uB code a V-vector of K, indexing a table of 2^B int8 vectors (V1's vector
* codebooks: V = 4, B = 8..12);
* - Trellis uB codes a bitshift trellis shifts in down each column: row r's value is the table
* entry of state_r = (state_{r-1} << B | code_r) mod 2^L, tail-biting over runs of T
* rows (IQR-V2, L = 12; IQR-V3, L = 14 on the tcq_rb grid, below);
* - TrellisMad the same trellis whose state values are computed, not read: state st's value is
* bytesum((st * A + B) mod 2^32 & 0x3F3F3F3F) - 126 (libquant's tcq_code=mad), one
* multiply-add, a mask and a byte-sum dot a value, so the GEMMs read no table and
* L = 16 costs nothing more than L = 14.
* The scale is a bf16 per (row, 128), or an E4M3 per (row, 128) under an f32 for the tensor or the
* row, whose product rounded to bf16 is the row's scale (libquant's grid_tcq_settle). A trellis on
* libquant's tcq_rb grid (rb > 1) reads one scale per rb rows, the largest of the block's own, and
* a state's value v becomes rint(v * own / B) against it, the int8 the codes were chosen against.
*
* ---- the form word ------------------------------------------------------------------------------
*
* The launch sees a weight only as its stored dtype and declared [N, K], so the form rides in the
* stored dtype: R4D_DT_IQR_W | word for the weight buffer and R4D_DT_IQR_S | word for its scales.
*
* ---- the codes: lane segments ------------------------------------------------------------------
*
* The unit is a 16-row x 128-K tile, one scale block of one 16-row tile (tile rt, block kb at unit
* rt * K/128 + kb). A unit is 32 lane segments of lane_bits() each, back to back: lane l holds
* columns 4l .. 4l + 3 of the block for the tile's 16 rows, so a lane's four values of a row are
* one sudot4 against four activation bytes, and a 16-row x 128-K int8 tile in WMMA fragment order
* is one LDS transpose away (r4d_iqr_dec.h). Within a segment:
* - scalar forms: row r's four codes at codes 4r .. 4r + 3, B bits each, the first in the low
* bits;
* - Grid: row r's 4/V codes at codes (4/V) r .., B bits each (V = 2 or 4);
* - Trellis: column e's 16 codes at codes 16e .. 16e + 15, bottom-up (row 15 of the tile first,
* row 0 last). The codes after a column's last are then the first ones of the same column in
* the unit above (rt - 1, or the run's last tile at a run's first, the run being tail-biting),
* so a row's state is the L bits starting at its own code in that stream, its code lowest.
* A unit is 4 * lane_bits() bytes, and the codes plane is exactly N*K*B/8 bytes (N*K*B/(8V) for a
* grid): a reorder of the stored bits.
*
* ---- the rest ------------------------------------------------------------------------------------
*
* After the codes, at aux_off(), the form's table (Table: 256 int8, zero-padded; Grid: 2^B * V;
* Trellis: 2^L; TrellisMad: its 2^L values, kept for the unrelayout, then A and B as two u32) or,
* for Zero, its zero plane as u8 in the scale order below. The scale buffer is
* tile-major, [N/16][K/128][16]: the 16 rows of a tile side by side for one 128-K block, as the
* int8 GEMMs' (r4d_fp8_layout.cpp): bf16, or E4M3 bytes followed at s2_off() by the second level as
* f32 (one, or one a row) and, with rb > 1, at blk_off() the bf16 block scale B per [N/rb][K/128].
*/
#pragma once
#include <cstdint>
#if defined(__HIPCC__) || defined(__HIP__)
#define R4D_IQR_HD __host__ __device__
#else
#define R4D_IQR_HD
#endif
namespace r4d_iqr {
enum Kind : uint32_t { kSigned = 1, kZero = 2, kTable = 3, kGrid = 4, kTrellis = 5, kTrellisMad = 6 };
/* Scale forms. kRowF32: one f32 a row over the whole K times one f32 a 128-K block shared by every
* row (libquant's tcq_colf; 1 without it): a GEMM folds the block's factor with the activation's
* per-128 scale and the row's in its epilogue, so its K loop reads no weight scale a row. */
enum Scale : uint32_t { kBf16 = 0, kE4m3Tensor = 1, kE4m3Row = 2, kRowF32 = 3 };
/* The private dtype bases (rad_types.h's RAD_DT_PLUGIN_BASE and up are the plugin's). */
constexpr uint32_t R4D_DT_IQR_W = 0x40000000u, R4D_DT_IQR_S = 0x50000000u;
constexpr uint32_t kWordMask = 0x0FFFFFFFu;
struct Form {
uint32_t kind = 0; /* Kind */
uint32_t bits = 0; /* B: code bits */
uint32_t lv = 0; /* Grid: log2 V */
uint32_t L = 0; /* Trellis: state bits */
uint32_t lrb = 0; /* Trellis: log2 rows a scale (tcq_rb), 0 for one a row */
uint32_t scale = 0; /* Scale */
uint32_t lrun = 0; /* Trellis: log2 rows a run */
uint32_t rot = 0; /* the embedding's forms: each 128 of a row rotated (fwht128) */
};
R4D_IQR_HD constexpr uint32_t word(const Form& f) {
return (f.kind & 15u) | (f.bits & 31u) << 4 | (f.lv & 7u) << 9 | (f.L & 31u) << 12 |
(f.lrb & 7u) << 17 | (f.scale & 3u) << 20 | (f.lrun & 15u) << 22 | (f.rot & 1u) << 26;
}
R4D_IQR_HD constexpr Form form(uint32_t w) {
Form f;
f.kind = w & 15u;
f.bits = (w >> 4) & 31u;
f.lv = (w >> 9) & 7u;
f.L = (w >> 12) & 31u;
f.lrb = (w >> 17) & 7u;
f.scale = (w >> 20) & 3u;
f.lrun = (w >> 22) & 15u;
f.rot = (w >> 26) & 1u;
return f;
}
inline bool is_weight_dtype(uint32_t dt) { return (dt & ~kWordMask) == R4D_DT_IQR_W; }
inline bool is_scale_dtype(uint32_t dt) { return (dt & ~kWordMask) == R4D_DT_IQR_S; }
/* A trellis kind: the codes' stream, the run and the continuation into the unit above. */
R4D_IQR_HD constexpr bool is_trellis(uint32_t kind) { return kind == kTrellis || kind == kTrellisMad; }
/* Bits of one lane's segment of a unit. */
R4D_IQR_HD constexpr uint32_t lane_bits(const Form& f) {
return f.kind == kGrid ? (64u >> f.lv) * f.bits : 64u * f.bits;
}
R4D_IQR_HD constexpr int64_t unit_bytes(const Form& f) { return 4 * (int64_t)lane_bits(f); }
R4D_IQR_HD constexpr int64_t codes_bytes(const Form& f, int64_t N, int64_t K) {
return (N / 16) * (K / 128) * unit_bytes(f);
}
R4D_IQR_HD constexpr int64_t align256(int64_t b) { return (b + 255) / 256 * 256; }
/* The codes plane is followed by 16 bytes a lane's last dword read may reach. */
R4D_IQR_HD constexpr int64_t aux_off(const Form& f, int64_t N, int64_t K) {
return align256(codes_bytes(f, N, K) + 16);
}
R4D_IQR_HD constexpr int64_t aux_bytes(const Form& f, int64_t N, int64_t K) {
return f.kind == kTable ? 256
: f.kind == kGrid ? ((int64_t)1 << f.bits) << f.lv
: f.kind == kTrellis ? (int64_t)1 << f.L
: f.kind == kTrellisMad ? ((int64_t)1 << f.L) + 8
: f.kind == kZero ? N * (K / 128)
: 0;
}
R4D_IQR_HD constexpr int64_t weight_bytes(const Form& f, int64_t N, int64_t K) {
return aux_off(f, N, K) + align256(aux_bytes(f, N, K) + 16);
}
/* The scale buffer. kRowF32: the rows' f32 scales, then at cf_off() the blocks' f32 factors. */
R4D_IQR_HD constexpr int64_t s1_bytes(const Form& f, int64_t N, int64_t K) {
return f.scale == kRowF32 ? N * 4 : N * (K / 128) * (f.scale == kBf16 ? 2 : 1);
}
R4D_IQR_HD constexpr int64_t cf_off(const Form& f, int64_t N, int64_t K) {
return align256(s1_bytes(f, N, K));
}
R4D_IQR_HD constexpr int64_t s2_off(const Form& f, int64_t N, int64_t K) {
return align256(s1_bytes(f, N, K));
}
R4D_IQR_HD constexpr int64_t s2_bytes(const Form& f, int64_t N) {
return f.scale == kE4m3Tensor ? 16 : f.scale == kE4m3Row ? 4 * N : 0;
}
R4D_IQR_HD constexpr int64_t blk_off(const Form& f, int64_t N, int64_t K) {
return s2_off(f, N, K) + align256(s2_bytes(f, N));
}
R4D_IQR_HD constexpr int64_t scale_bytes(const Form& f, int64_t N, int64_t K) {
return f.scale == kRowF32 ? cf_off(f, N, K) + align256((K / 128) * 4)
: blk_off(f, N, K) + (f.lrb ? align256((N >> f.lrb) * (K / 128) * 2) : 0);
}
/* The tile-major index of (row r, 128-K block kb). */
R4D_IQR_HD constexpr int64_t tile_major(int64_t r, int64_t kb, int64_t nkb) {
return ((r / 16) * nkb + kb) * 16 + r % 16;
}
/* The forms libr4d's kernels are built for, as (kind, B, log2 V, L, log2 rb, scale): one list, so
* the layout hook refuses at declare a form no kernel reads. */
#define R4D_IQR_FORMS(X) \
/* IQR-V1: scalar tables, vector grids, 6-bit codes under a zero */ \
X(kTable, 2, 0, 0, 0, kBf16) X(kTable, 3, 0, 0, 0, kBf16) X(kTable, 4, 0, 0, 0, kBf16) \
X(kTable, 5, 0, 0, 0, kBf16) \
X(kGrid, 8, 2, 0, 0, kBf16) X(kGrid, 9, 2, 0, 0, kBf16) X(kGrid, 10, 2, 0, 0, kBf16) \
X(kGrid, 12, 2, 0, 0, kBf16) \
X(kZero, 6, 0, 0, 0, kBf16) \
/* IQR-V2: the 4096-state trellis, E4M3 scales under one f32 */ \
X(kTrellis, 2, 0, 12, 0, kE4m3Tensor) X(kTrellis, 3, 0, 12, 0, kE4m3Tensor) \
X(kTrellis, 4, 0, 12, 0, kE4m3Tensor) X(kTrellis, 5, 0, 12, 0, kE4m3Tensor) \
X(kTrellis, 6, 0, 12, 0, kE4m3Tensor) X(kTrellis, 7, 0, 12, 0, kE4m3Tensor) \
/* IQR-V3: the 16384-state trellis on the tcq_rb=32 grid */ \
X(kTrellis, 2, 0, 14, 5, kE4m3Tensor) X(kTrellis, 3, 0, 14, 5, kE4m3Tensor) \
X(kTrellis, 4, 0, 14, 5, kE4m3Tensor) X(kTrellis, 5, 0, 14, 5, kE4m3Tensor) \
X(kTrellis, 6, 0, 14, 5, kE4m3Tensor) X(kTrellis, 7, 0, 14, 5, kE4m3Tensor) \
/* the computed 65536-state trellis on the tcq_rb=32 grid */ \
X(kTrellisMad, 2, 0, 16, 5, kE4m3Tensor) X(kTrellisMad, 3, 0, 16, 5, kE4m3Tensor) \
X(kTrellisMad, 4, 0, 16, 5, kE4m3Tensor) X(kTrellisMad, 5, 0, 16, 5, kE4m3Tensor) \
X(kTrellisMad, 6, 0, 16, 5, kE4m3Tensor) X(kTrellisMad, 7, 0, 16, 5, kE4m3Tensor) \
/* the computed trellis with a scale a row (no rescale a value) */ \
X(kTrellisMad, 2, 0, 16, 0, kE4m3Tensor) X(kTrellisMad, 3, 0, 16, 0, kE4m3Tensor) \
X(kTrellisMad, 4, 0, 16, 0, kE4m3Tensor) \
/* the computed trellis under one scale a row and a factor a 128-K block */ \
X(kTrellisMad, 2, 0, 16, 0, kRowF32) X(kTrellisMad, 3, 0, 16, 0, kRowF32) \
X(kTrellisMad, 4, 0, 16, 0, kRowF32) X(kTrellisMad, 5, 0, 16, 0, kRowF32) \
X(kTrellisMad, 6, 0, 16, 0, kRowF32) X(kTrellisMad, 7, 0, 16, 0, kRowF32) \
X(kTrellisMad, 2, 0, 15, 0, kRowF32)
/* The form word without its run, which the kernels take as an argument. */
R4D_IQR_HD constexpr uint32_t kernel_word(uint32_t w) {
return word(Form{ form(w).kind, form(w).bits, form(w).lv, form(w).L, form(w).lrb,
form(w).scale, 0, form(w).rot });
}
R4D_IQR_HD constexpr bool built(uint32_t w) {
#define R4D_IQR_IS(k, b, lv, l, lrb, sc) \
kernel_word(w) == word(Form{ k, b, lv, l, lrb, sc, 0 }) ||
return R4D_IQR_FORMS(R4D_IQR_IS) false;
#undef R4D_IQR_IS
}
/* ---- the embedding table ---------------------------------------------------------------------
*
* embed_lookup reads a handful of rows a step, so its table keeps the container's row-major planes
* as they are (each row's codes from a byte, B bits a code), with the form's table or, for Zero,
* its zero plane as u8 [rows][K/128], then the scale plane as stored ([rows][K/128] bf16 or E4M3),
* its second level as f32 and, with rb > 1, the block scale B per [rows/rb][K/128]. The forms
* built, as R4D_IQR_FORMS plus rot: */
#define R4D_IQR_EMBED_FORMS(X) \
X(kTable, 2, 0, 0, 0, kBf16, 0) X(kTable, 3, 0, 0, 0, kBf16, 0) \
X(kTable, 4, 0, 0, 0, kBf16, 0) X(kTable, 5, 0, 0, 0, kBf16, 0) \
X(kTable, 2, 0, 0, 0, kBf16, 1) X(kTable, 3, 0, 0, 0, kBf16, 1) \
X(kTable, 4, 0, 0, 0, kBf16, 1) X(kTable, 5, 0, 0, 0, kBf16, 1) \
X(kZero, 6, 0, 0, 0, kBf16, 0) \
X(kTrellis, 2, 0, 12, 0, kE4m3Tensor, 1) X(kTrellis, 3, 0, 12, 0, kE4m3Tensor, 1) \
X(kTrellis, 4, 0, 12, 0, kE4m3Tensor, 1) X(kTrellis, 5, 0, 12, 0, kE4m3Tensor, 1)
R4D_IQR_HD constexpr bool embed_built(uint32_t w) {
#define R4D_IQR_EIS(k, b, lv, l, lrb, sc, r) \
kernel_word(w) == word(Form{ k, b, lv, l, lrb, sc, 0, r }) ||
return R4D_IQR_EMBED_FORMS(R4D_IQR_EIS) false;
#undef R4D_IQR_EIS
}
struct EmbedOff { int64_t codes_row, aux, sc, s2, blk, bytes; };
R4D_IQR_HD constexpr int64_t code_cols(const Form& f, int64_t K) {
return f.kind == kGrid ? K >> f.lv : K;
}
R4D_IQR_HD constexpr EmbedOff embed_off(const Form& f, int64_t rows, int64_t K) {
EmbedOff o{};
o.codes_row = (code_cols(f, K) * f.bits + 7) / 8;
o.aux = align256(rows * o.codes_row + 16);
const int64_t aux_b = f.kind == kZero ? rows * (K / 128) : aux_bytes(f, rows, K);
o.sc = o.aux + align256(aux_b + 16);
o.s2 = o.sc + align256(rows * (K / 128) * (f.scale == kBf16 ? 2 : 1));
o.blk = o.s2 + align256(s2_bytes(f, rows));
o.bytes = o.blk + (f.lrb ? align256((rows >> f.lrb) * (K / 128) * 2) : 0);
return o;
}
/* ---- the lm_head ------------------------------------------------------------------------------
*
* logits_gemm's row form (r4d_fp8_lm.h) at B bits a code: each row its K codes packed as the
* container stores them, then its bf16 scale per 128 columns, padded to 16 bytes; the table of
* 2^B int8 entries after the last row, 256-aligned. Table forms of 2 to 6 bits, unrotated. */
R4D_IQR_HD constexpr int64_t lm_row(const Form& f, int64_t K) {
return (K / 8 * f.bits + 2 * (K / 128) + 15) / 16 * 16;
}
R4D_IQR_HD constexpr int64_t lm_tab(const Form& f, int64_t N, int64_t K) {
return align256(N * lm_row(f, K));
}
R4D_IQR_HD constexpr int64_t lm_bytes(const Form& f, int64_t N, int64_t K) {
return lm_tab(f, N, K) + 256;
}
R4D_IQR_HD constexpr bool lm_built(uint32_t w) {
return form(w).kind == kTable && form(w).bits >= 2 && form(w).bits <= 6 &&
form(w).scale == kBf16 && !form(w).rot && !form(w).lrb;
}
/* A trellis's codes a state spans. */
R4D_IQR_HD constexpr uint32_t span(const Form& f) { return (f.L + f.bits - 1) / f.bits; }
} // namespace r4d_iqr
+383
View File
@@ -0,0 +1,383 @@
/* r4d_iqr_dec.h -- device decoders of the IQR weights (r4d_iqr.h), decoded from their codes where
* they are read.
*
* A decoder is fetch (a lane's raw code dwords of one 16-row x 128-K unit, issued ahead like any
* operand load) and rows (raw to the int8 values: for each of the tile's 16 rows, the lane's four
* columns packed in a dword, the operand of one sudot4). A GEMM on the WMMA tiles takes the unit
* through `frag`: the 16 x 128 bytes through this wave's LDS tile, read back as the int8 tiles'
* fragment order (r4d_fp8_frag.h), two 64-K supertiles.
*
* The forms' tables are read from LDS, staged once a block by `stage`: Table and Trellis entries
* one byte each, Grid entries one V-vector each.
*
* A trellis column's 16 codes are followed in its stream by the first ones of the same column in
* the unit above, so each row's state is a field of that stream at a fixed position. On libquant's
* tcq_rb grid (LRB > 0) a value v is rint(v * own / B), own the row's scale and B its block's, the
* int8 libquant's grid_tcq_decode reads; the ratio is one IEEE division a (row, 128-K block), the
* host's f32 operations, computed by the lane of its row and read by the others. */
#pragma once
#include "r4d_fp8_wmma.h"
#include "r4d_iqr.h"
#include <hip/hip_runtime.h>
#include <cstdint>
namespace r4d_iqr_dev {
using namespace r4d_fp8;
using namespace r4d_iqr;
template <uint32_t KIND_, uint32_t B_, uint32_t LV_ = 0, uint32_t L_ = 0, uint32_t LRB_ = 0,
uint32_t SC_ = kBf16>
struct FormT {
static constexpr uint32_t KIND = KIND_, B = B_, LV = LV_, L = L_, LRB = LRB_, SC = SC_;
static constexpr uint32_t word() {
return r4d_iqr::word(Form{ KIND, B, LV, L, LRB, SC, 0 });
}
};
/* What a decoder reads besides the codes. */
struct Ctx {
const uint8_t* W; /* the weight buffer */
const uint8_t* S; /* the scale buffer */
const int8_t* tab; /* the form's table, staged in LDS */
uint32_t N, nkb;
uint32_t run_tiles; /* a trellis run's 16-row tiles */
};
/* The LDS tile a unit is transposed through: 16 rows of 128 bytes and 8 of padding, so the sixteen
* rows' 8-byte fragment reads fall on distinct banks. */
constexpr uint32_t kTrPitch = 136, kTrBytes = 16 * kTrPitch;
/* `n` <= 32 bits of a little-endian dword stream from bit `o` (constant after unrolling). */
template <uint32_t ND>
__device__ __forceinline__ uint32_t field(const uint32_t (&d)[ND], uint32_t o, uint32_t n) {
const uint32_t q = o >> 5, s = o & 31u;
const uint32_t m = n == 32u ? 0xFFFFFFFFu : ((1u << n) - 1u);
if (s + n <= 32u) return (d[q] >> s) & m;
return __builtin_amdgcn_alignbit(q + 1u < ND ? d[q + 1u] : 0u, d[q], s) & m;
}
/* Low bytes of two, then of two pairs, into one dword. */
__device__ __forceinline__ uint32_t pack2(uint32_t lo, uint32_t hi) {
return __builtin_amdgcn_perm(hi, lo, 0x0c0c0400u);
}
__device__ __forceinline__ uint32_t pack4(uint32_t p01, uint32_t p23) {
return __builtin_amdgcn_perm(p23, p01, 0x05040100u);
}
template <uint32_t N>
__device__ __forceinline__ void load_dw(uint32_t (&d)[N], const uint8_t* p, bool live) {
#pragma unroll
for (uint32_t i = 0; i < N; ++i) d[i] = 0u;
if (!live) return;
uint32_t i = 0;
#pragma unroll
for (; i + 4u <= N; i += 4u) {
const uint4 v = *(const uint4*)(p + 4 * i);
d[i] = v.x; d[i + 1] = v.y; d[i + 2] = v.z; d[i + 3] = v.w;
}
if constexpr (N % 4u == 3u) {
const uint3 v = *(const uint3*)(p + 4 * i);
d[i] = v.x; d[i + 1] = v.y; d[i + 2] = v.z;
} else if constexpr (N % 4u == 2u) {
const uint2 v = *(const uint2*)(p + 4 * i);
d[i] = v.x; d[i + 1] = v.y;
} else if constexpr (N % 4u == 1u) {
d[i] = *(const uint32_t*)(p + 4 * i);
}
}
/* The bf16 bits of x rounded to nearest even, as the host relayout and libquant round. */
__device__ __forceinline__ uint32_t bf16_bits(float x) {
const uint32_t u = __float_as_uint(x);
return (u + 0x7FFFu + ((u >> 16) & 1u)) >> 16;
}
/* A row's own scale for 128-K block kb, as bf16 bits. */
template <class F>
__device__ __forceinline__ uint32_t own_scale(const Ctx& c, uint32_t r, uint32_t kb) {
const size_t i = ((size_t)(r / 16u) * c.nkb + kb) * 16u + r % 16u;
if constexpr (F::SC == kBf16) {
return ((const uint16_t*)c.S)[i];
} else {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const float* s2 = (const float*)(c.S + s2_off(f, c.N, (int64_t)c.nkb * 128));
return bf16_bits(s2[F::SC == kE4m3Row ? r : 0u] * e4m3(c.S[i]));
}
}
/* The scale the GEMM folds a row's block kb at: its own, or with LRB its block's. */
template <class F>
__device__ __forceinline__ uint32_t fold_scale(const Ctx& c, uint32_t r, uint32_t kb) {
if constexpr (F::LRB != 0) {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint16_t* bp = (const uint16_t*)(c.S + blk_off(f, c.N, (int64_t)c.nkb * 128));
return bp[(size_t)(r >> F::LRB) * c.nkb + kb];
} else {
return own_scale<F>(c, r, kb);
}
}
/* The f32 a GEMM folds row r's block kb at (with the activation's per-128 scale): the bf16 fold
* scale, or under one scale a row (kRowF32) the block's shared factor, the row's own then taken
* in the epilogue (row_scale). */
template <class F>
__device__ __forceinline__ float fold_f32(const Ctx& c, uint32_t r, uint32_t kb) {
if constexpr (F::SC == kRowF32) {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
(void)r;
return ((const float*)(c.S + cf_off(f, c.N, (int64_t)c.nkb * 128)))[kb];
} else {
return bscale(fold_scale<F>(c, r, kb));
}
}
/* The factor row r's sums take in the epilogue: its kRowF32 scale, else 1. */
template <class F>
__device__ __forceinline__ float row_scale(const Ctx& c, uint32_t r) {
if constexpr (F::SC == kRowF32) return ((const float*)c.S)[r];
else { (void)c; (void)r; return 1.0f; }
}
/* The tcq_rb ratio own / B of a row's block kb (1 off that grid). */
template <class F>
__device__ __forceinline__ float rb_ratio(const Ctx& c, uint32_t r, uint32_t kb) {
if constexpr (F::LRB != 0) {
const float so = __uint_as_float(own_scale<F>(c, r, kb) << 16);
const float sb = __uint_as_float(fold_scale<F>(c, r, kb) << 16);
return sb > 0.0f ? __fdiv_rn(so, sb) : 0.0f;
} else {
return 1.0f;
}
}
/* H16: a tcq_rb trellis's state values staged as f16 (exact for int8), so a value's product with
* its ratio is one mixed-precision fma instead of a conversion and a multiply; twice the LDS, which
* the GEMV has to spare and the tiles do not. */
template <class F, bool H16 = false>
struct Dec {
static constexpr uint32_t B = F::B;
static constexpr bool TR = is_trellis(F::KIND), GRID = F::KIND == kGrid;
static constexpr bool MAD = F::KIND == kTrellisMad; /* values computed, no table */
static constexpr uint32_t LANE_BITS = GRID ? (64u >> F::LV) * B : 64u * B;
/* A grid lane segment may start mid-dword: read the dword-aligned window covering it. */
static constexpr bool ALIGNED = LANE_BITS % 32u == 0u;
static constexpr uint32_t ND = ALIGNED ? LANE_BITS / 32u : (LANE_BITS + 24u + 31u) / 32u;
/* The dwords of the unit above a trellis column's continuation can reach: its first codes. */
static constexpr uint32_t NP = TR ? ND : 1;
struct Raw { uint32_t d[ND]; uint32_t p[NP]; };
static constexpr bool HALF = H16 && TR && !MAD && F::LRB != 0;
static constexpr uint32_t kTab = F::KIND == kTable ? 256u
: GRID ? (1u << B) << F::LV
: TR && !MAD ? (1u << F::L) * (HALF ? 2u : 1u) : 4u;
/* Copy the form's table into LDS; the caller then barriers. */
__device__ static void stage(int8_t* tab, const Ctx& c, uint32_t tid, uint32_t nthr) {
if constexpr (F::KIND == kTable || GRID || (TR && !MAD)) {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* src = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128));
if constexpr (HALF) {
for (uint32_t i = tid; i < (1u << F::L) / 4u; i += nthr) {
const uint32_t q = src[i];
#pragma unroll
for (uint32_t j = 0; j < 4; ++j)
((_Float16*)tab)[4 * i + j] = (_Float16)(float)(int8_t)(q >> (8 * j));
}
} else {
for (uint32_t i = tid; i < kTab / 4u; i += nthr) ((uint32_t*)tab)[i] = src[i];
}
}
}
__device__ static Raw fetch(const Ctx& c, uint32_t rt, uint32_t kb, uint32_t lane, bool live) {
Raw r;
constexpr size_t ub = 4u * LANE_BITS;
const uint8_t* unit = c.W + ((size_t)rt * c.nkb + kb) * ub;
if constexpr (ALIGNED) {
load_dw<ND>(r.d, unit + (size_t)lane * (LANE_BITS / 8u), live);
} else {
const uint32_t off = lane * (LANE_BITS / 8u); /* LANE_BITS is whole bytes */
uint32_t w[ND];
load_dw<ND>(w, unit + (off & ~3u), live);
const uint32_t sh = (off & 3u) * 8u;
#pragma unroll
for (uint32_t i = 0; i < ND; ++i)
r.d[i] = __builtin_amdgcn_alignbit(i + 1u < ND ? w[i + 1u] : 0u, w[i], sh);
}
if constexpr (TR) {
const uint32_t rp = rt % c.run_tiles == 0u ? rt + c.run_tiles - 1u : rt - 1u;
const uint8_t* up = c.W + ((size_t)rp * c.nkb + kb) * ub;
load_dw<NP>(r.p, up + (size_t)lane * (LANE_BITS / 8u), live);
} else {
r.p[0] = 0u;
}
return r;
}
/* The lane's four values of each of the tile's 16 rows, packed. `ratio` is row (lane & 15)'s
* tcq_rb ratio for this block (rb_ratio). UNS (a computed trellis off the tcq_rb grid): each
* value as its unsigned byte sum, the value plus 126, which the caller corrects in its sums. */
template <bool UNS = false>
__device__ static void rows(const Raw& r, const Ctx& c, float ratio, uint32_t (&w)[16]) {
static_assert(!UNS || (MAD && F::LRB == 0), "unsigned values: a computed trellis, one scale a row");
if constexpr (TR) {
constexpr uint32_t L = F::L, CB = 16u * B;
/* All 64 states, then all 64 lookups, then the values: the LDS reads go out together
* instead of each waiting on the last's use. */
uint32_t st[64];
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) {
const uint32_t pos = e * CB + q * B, own = CB - q * B;
st[q * 4 + e] = L <= own ? field<ND>(r.d, pos, L)
: field<ND>(r.d, pos, own) |
field<NP>(r.p, e * CB, L - own) << own;
}
[[maybe_unused]] int32_t t[HALF ? 1 : 64];
[[maybe_unused]] _Float16 th[HALF ? 64 : 1];
if constexpr (MAD) {
/* bytesum((st * A + B) & 0x3F3F3F3F) - 126: st < 2^16 and A < 2^24, so the
* 24-bit multiply is the full product mod 2^32 */
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128) +
((int64_t)1 << F::L));
const uint32_t A = ab[0], Bc = ab[1];
#pragma unroll
for (uint32_t i = 0; i < 64; ++i) {
/* the byte sum less the code's bias, in the dot's own accumulator */
const uint32_t h = (__umul24(st[i], A) + Bc) & 0x3F3F3F3Fu;
t[i] = __builtin_amdgcn_sudot4(false, (int)h, false, 0x01010101, UNS ? 0 : -126, false);
}
} else {
#pragma unroll
for (uint32_t i = 0; i < 64; ++i) {
if constexpr (HALF) th[i] = ((const _Float16*)c.tab)[st[i]];
else t[i] = c.tab[st[i]];
}
}
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
uint32_t v[4];
if constexpr (F::LRB != 0) {
/* rint(t * rq) as the low byte of t * rq + 1.5 * 2^23: the add rounds the f32
* product to an integer, nearest even as rintf does, and |t * rq| <= 127
* leaves it in the mantissa's low bits, two's complement in its low byte. */
const float rq = __builtin_bit_cast(
float, __builtin_amdgcn_readlane(__float_as_int(ratio), 15 - q));
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) {
/* the f16 value times rq, rounded once: the f32 product of the int8; a
* computed code rounds the exact product, one fma */
if constexpr (MAD) {
v[e] = __float_as_uint(__builtin_fmaf((float)t[q * 4 + e], rq, 12582912.0f));
} else {
const float pr = HALF ? __builtin_fmaf((float)th[q * 4 + e], rq, 0.0f)
: __fmul_rn((float)t[HALF ? 0 : q * 4 + e], rq);
v[e] = __float_as_uint(__fadd_rn(pr, 12582912.0f));
}
}
} else {
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) v[e] = (uint32_t)t[HALF ? 0 : q * 4 + e];
}
w[15u - q] = pack4(pack2(v[0], v[1]), pack2(v[2], v[3]));
}
} else if constexpr (GRID) {
constexpr uint32_t V = 1u << F::LV, PER = 4u / V;
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
if constexpr (V == 4u) {
w[q] = *(const uint32_t*)(c.tab + field<ND>(r.d, q * B, B) * 4u);
} else {
const uint32_t g0 = *(const uint16_t*)(c.tab + field<ND>(r.d, (q * PER) * B, B) * 2u);
const uint32_t g1 = *(const uint16_t*)(c.tab + field<ND>(r.d, (q * PER + 1) * B, B) * 2u);
w[q] = g0 | g1 << 16;
}
}
} else {
(void)ratio;
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
uint32_t v[4];
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) {
const uint32_t code = field<ND>(r.d, (q * 4u + e) * B, B);
if constexpr (F::KIND == kTable) v[e] = (uint8_t)c.tab[code];
else if constexpr (F::KIND == kZero) v[e] = code;
else v[e] = (uint32_t)((int32_t)(code << (32u - B)) >> (32u - B));
}
w[q] = pack4(pack2(v[0], v[1]), pack2(v[2], v[3]));
}
}
}
/* A computed trellis's masked hashes, one a value: h[q][e] for the lane's column e of row q,
* whose four bytes sum to the value plus 126. A dot of h with an activation byte repeated in
* each byte is the value plus 126 times the activation, the sum and the product in one. */
__device__ static void hashes(const Raw& r, const Ctx& c, uint32_t (&h)[16][4]) {
static_assert(MAD, "hashes: a computed trellis");
constexpr uint32_t L = F::L, CB = 16u * B;
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint32_t* ab = (const uint32_t*)(c.W + aux_off(f, c.N, (int64_t)c.nkb * 128) +
((int64_t)1 << F::L));
const uint32_t A = ab[0], Bc = ab[1];
#pragma unroll
for (uint32_t q = 0; q < 16; ++q)
#pragma unroll
for (uint32_t e = 0; e < 4; ++e) {
const uint32_t pos = e * CB + q * B, own = CB - q * B;
const uint32_t st = L <= own ? field<ND>(r.d, pos, L)
: field<ND>(r.d, pos, own) | field<NP>(r.p, e * CB, L - own) << own;
h[15u - q][e] = (__umul24(st, A) + Bc) & 0x3F3F3F3Fu;
}
}
/* Zero: the zero of row (rt*16 + q) for block kb is subtracted bytewise after `rows`. */
__device__ static void unzero(const Ctx& c, uint32_t rt, uint32_t kb, uint32_t (&w)[16]) {
if constexpr (F::KIND == kZero) {
constexpr Form f{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
const uint8_t* zp = c.W + aux_off(f, c.N, (int64_t)c.nkb * 128) +
((size_t)rt * c.nkb + kb) * 16u;
const uint4 z4 = *(const uint4*)zp; /* the tile's 16 rows, one byte each */
const uint32_t zd[4] = { z4.x, z4.y, z4.z, z4.w };
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) {
const uint32_t z = (zd[q / 4u] >> (8u * (q % 4u))) & 0xFFu;
/* codes and zero are below 128, so bytewise subtraction borrows nothing across
* bytes once 0x80 is added to each code byte and taken off the result */
w[q] = ((w[q] | 0x80808080u) - z * 0x01010101u) ^ 0x80808080u;
}
} else {
(void)c; (void)rt; (void)kb; (void)w;
}
}
};
/* The unit's int8 tile in fragment order, two 64-K supertiles, through this wave's LDS tile `tr`.
* A wave's LDS accesses complete in order, so only the compiler must not move the reads above the
* writes; the second fence keeps the next unit's writes below these reads. */
__device__ __forceinline__ void frag(const uint32_t (&w)[16], uint8_t* tr, uint32_t lane,
Stage8 (&s)[2]) {
#pragma unroll
for (uint32_t q = 0; q < 16; ++q) *(uint32_t*)(tr + q * kTrPitch + 4u * lane) = w[q];
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront", "local");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront", "local");
const uint8_t* row = tr + (lane & 15u) * kTrPitch + (lane >> 4) * 8u;
#pragma unroll
for (uint32_t h = 0; h < 2; ++h) {
uint32_t o[8];
#pragma unroll
for (uint32_t t = 0; t < 4; ++t) {
const uint2 g = *(const uint2*)(row + h * 64u + t * 16u);
o[2 * t] = g.x;
o[2 * t + 1] = g.y;
}
s[h].v = make_uint4(o[0], o[1], o[2], o[3]);
s[h].w = make_uint4(o[4], o[5], o[6], o[7]);
}
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront", "local");
__builtin_amdgcn_wave_barrier();
__builtin_amdgcn_fence(__ATOMIC_ACQUIRE, "wavefront", "local");
}
} // namespace r4d_iqr_dev
+142
View File
@@ -0,0 +1,142 @@
// embed_lookup over an IQR table (r4d_iqr.h's embed_off): the gather decodes each requested row
// from its codes, so VRAM holds the table at its codes' width.
//
// ref_embed_lookup's contract (r4d_model_bf16.hip's embed_lookup_kernel): x[m] is the table's row
// tok[m] - vocab_offset, a zero row for an id outside this rank's rows, times `mult` with one
// rounding. A row's value is the form's int8 value times its (row, 128) scale in f32, the 128-wide
// Hadamard undone in f32 on a rotated table (libquant's butterfly order: span 1, 2, .., 64, each
// pair (a, b) to (a + b, a - b)), rounded to bf16 to nearest even: the values the table's bf16
// widening at load produced, bit for bit.
#include "r4d.h"
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_fp8_wmma.h"
#include "r4d_iqr.h"
#include "r4d_iqr_dec.h"
namespace {
using namespace r4d_iqr;
using namespace r4d_iqr_dev;
/* `n` <= 16 bits of a byte stream from bit `o`. */
__device__ __forceinline__ uint32_t bits_at(const uint8_t* p, uint64_t o, uint32_t n) {
const uint8_t* b = p + (o >> 3);
const uint32_t w = (uint32_t)b[0] | (uint32_t)b[1] << 8 | (uint32_t)b[2] << 16;
return (w >> (o & 7u)) & ((1u << n) - 1u);
}
template <uint32_t KIND, uint32_t B, uint32_t LV, uint32_t L, uint32_t LRB, uint32_t SC, uint32_t ROT>
__global__ __launch_bounds__(128) void iqr_embed_kernel(const int32_t* __restrict__ tok,
const uint8_t* __restrict__ W,
uint16_t* __restrict__ x, uint32_t n_embd,
int32_t n_vocab, int32_t vocab_off,
uint32_t x_ld, float mult) {
constexpr Form f{ KIND, B, LV, L, LRB, SC, 0, ROT };
__shared__ float s_v[128];
const uint32_t m = blockIdx.x, g = blockIdx.y, t = threadIdx.x, k = g * 128u + t;
const int32_t id = tok[m] - vocab_off;
uint16_t* dst = x + (size_t)m * x_ld + k;
if (id < 0 || id >= n_vocab) {
*dst = 0;
return;
}
const EmbedOff o = embed_off(f, n_vocab, n_embd);
const uint32_t nkb = n_embd / 128u, r = (uint32_t)id;
auto code = [&](uint32_t row, uint32_t col) {
return bits_at(W + (size_t)row * o.codes_row, (uint64_t)col * B, B);
};
const int8_t* aux = (const int8_t*)(W + o.aux);
int32_t v;
if constexpr (KIND == kTable) {
v = aux[code(r, k)];
} else if constexpr (KIND == kGrid) {
v = aux[code(r, k >> LV) * (1u << LV) + (k & ((1u << LV) - 1u))];
} else if constexpr (KIND == kZero) {
v = (int32_t)code(r, k) - (int32_t)((const uint8_t*)aux)[(size_t)r * nkb + g];
} else if constexpr (KIND == kSigned) {
v = (int32_t)(code(r, k) << (32u - B)) >> (32u - B);
} else {
/* The trellis: row r's state is its last ceil(L/B) codes in its column, the run's 256
* rows wrapping (the launch refuses another run). */
constexpr uint32_t C = (L + B - 1) / B, run = 256u;
const uint32_t r0 = r / run * run;
uint32_t st = 0;
#pragma unroll
for (uint32_t q = C; q-- > 0;) {
const uint32_t rr = r0 + (r - r0 + run - q) % run;
st = ((st << B) | code(rr, k)) & ((1u << L) - 1u);
}
v = aux[st];
}
/* The row's scale as bf16 bits: its own, or its block's on a tcq_rb grid, against which the
* value is rint(v * own / B). */
uint32_t own;
if constexpr (SC == kBf16) {
own = ((const uint16_t*)(W + o.sc))[(size_t)r * nkb + g];
} else {
const float s2 = ((const float*)(W + o.s2))[SC == kE4m3Row ? r : 0u];
own = bf16_bits(s2 * e4m3((W + o.sc)[(size_t)r * nkb + g]));
}
uint32_t sb = own;
if constexpr (LRB != 0) {
sb = ((const uint16_t*)(W + o.blk))[(size_t)(r >> LRB) * nkb + g];
const float so = __uint_as_float(own << 16), sbf = __uint_as_float(sb << 16);
v = sbf > 0.0f ? (int32_t)rintf(__fmul_rn((float)v, __fdiv_rn(so, sbf))) : 0;
}
float val = __fmul_rn((float)v, __uint_as_float(sb << 16));
if constexpr (ROT != 0) {
s_v[t] = val;
__syncthreads();
#pragma unroll
for (uint32_t h = 1; h < 128u; h <<= 1) {
const float a = s_v[t & ~h], b = s_v[t | h];
const float y = (t & h) ? __fsub_rn(a, b) : __fadd_rn(a, b);
__syncthreads();
s_v[t] = y;
__syncthreads();
}
val = s_v[t];
}
uint32_t bits = bf16_bits(val);
if (mult != 1.0f) bits = f32_to_bf16(__uint_as_float(bits << 16) * mult);
*dst = (uint16_t)bits;
}
} // namespace
enum { EL_TOK = 0, EL_WTE, EL_X };
extern "C" int r4d_rad_embed_lookup_iqr(const RadArgs* a, RadStream stream) {
const RadTensor* tok = r4d_opt(a, EL_TOK);
const RadTensor* wte = r4d_opt(a, EL_WTE);
const RadTensor* x = r4d_opt(a, EL_X);
if (!tok || !wte || !x) return R4D_NO(RAD_E_INVAL);
if (tok->dtype != RAD_I32 || x->dtype != RAD_BF16 || !is_weight_dtype(wte->dtype))
return R4D_NO(RAD_E_DTYPE);
if (!r4d_contig(tok)) return R4D_NO(RAD_E_STRIDE);
const long long n_embd = r4d_geti_or(a, "n_embd", 0), n_vocab = r4d_geti_or(a, "n_vocab", 0);
const long long voff = r4d_geti_or(a, "vocab_offset", 0);
if (n_embd <= 0 || n_embd % 128 || n_vocab <= 0 || voff < 0) return R4D_NO(RAD_E_SHAPE);
long long M = 0;
const long long x_ld = r4d_rows_pitch(x, n_embd, &M);
if (x_ld < 0) return R4D_NO(RAD_E_STRIDE);
if (M <= 0 || r4d_numel(tok) < M) return R4D_NO(RAD_E_SHAPE);
const float mult = (float)r4d_getf(a, "mult", 1.0);
const uint32_t kw = kernel_word(wte->dtype & kWordMask);
const Form f = form(wte->dtype & kWordMask);
/* The run, which the kernel assumes, is libquant's tcq_rows = 256. */
if (f.kind == kTrellis && f.lrun != 8u) return R4D_NO(RAD_E_SHAPE);
const dim3 grid((uint32_t)M, (uint32_t)(n_embd / 128));
int rc = RAD_E_UNSUPPORTED;
#define R4D_IQR_EGO(k, b, lv, l, lrb, sc, r) \
if (kw == word(Form{ k, b, lv, l, lrb, sc, 0, r })) \
rc = R4D_EMIT(stream, (iqr_embed_kernel<k, b, lv, l, lrb, sc, r>), grid, dim3(128), 0, \
(const int32_t*)tok->data, (const uint8_t*)wte->data, (uint16_t*)x->data, \
(uint32_t)n_embd, (int32_t)n_vocab, (int32_t)voff, (uint32_t)x_ld, mult); \
else
R4D_IQR_EMBED_FORMS(R4D_IQR_EGO) { return R4D_NO(RAD_E_UNSUPPORTED); }
#undef R4D_IQR_EGO
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
}
+735
View File
@@ -0,0 +1,735 @@
/* r4d_iqr_layout.cpp -- the IQR weights' stored form (r4d_iqr.h) from a container's planes, and
* back. Pure host C++, as r4d_fp8_layout.cpp.
*
* The weight buffer is the codes reordered into lane segments plus the form's table or zero plane;
* the scale buffer is the scale plane in tile-major order, with its second level and, on a tcq_rb
* trellis, the block scale B each block of rows is read at. Every bit of the codes is kept and
* nothing is widened: VRAM holds a B-bit weight in B bits. The relayout refuses (RAD_E_FORMAT) a
* code no entry answers and a value outside the int8 grid's -127..127, which no kernel could
* read. */
#include "r4d_plugin.h"
#include "r4d_iqr.h"
#include "r4d_fp8_frag.h"
#include "r4d_enc.h"
#include <algorithm>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <thread>
#include <vector>
using namespace r4d_iqr;
/* Operand indices of `gemm_nt_q` (r4d_rows.cpp). */
enum { IL_B = 2, IL_BSCALE = 3 };
namespace {
int log2_exact(int64_t v) {
if (v <= 0 || (v & (v - 1))) return -1;
int l = 0;
while (((int64_t)1 << l) < v) ++l;
return l;
}
int unsigned_bits(uint32_t dt) {
static const uint32_t kU[] = { RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6, RAD_U7, RAD_U8 };
for (int i = 0; i < 8; ++i)
if (dt == kU[i]) return i + 1;
return 0;
}
int signed_bits(uint32_t dt) {
static const uint32_t kS[] = { RAD_I2, RAD_I3, RAD_I4, RAD_I5, RAD_I6, RAD_I7 };
for (int i = 0; i < 6; ++i)
if (dt == kS[i]) return i + 2;
return 0;
}
/* The scale plane a form reads: one bf16 per [1 x 128], or E4M3 per [1 x 128] under an f32 or bf16
* second level for the tensor or the row. */
bool scale_form(const RadEncoding* enc, int want_planes, uint32_t* out) {
const RadEncPlane* sc = rad_enc_plane(enc, "scale");
const RadEncPlane* s2 = rad_enc_plane(enc, "scale.1");
/* one f32 a row (block [1 x whole]), with a "scale.col" f32 a [whole x 128] or none */
if (sc && sc->kind == RAD_PLANE_TILED && sc->block[0] == 1 && sc->block[1] == 0 &&
sc->dtype == RAD_F32 && !s2) {
const RadEncPlane* cf = rad_enc_plane(enc, "scale.col");
if (cf && (cf->kind != RAD_PLANE_TILED || cf->dtype != RAD_F32 || cf->block[0] != 0 ||
cf->block[1] != 128))
return false;
if (enc->n_planes != want_planes + (cf ? 1 : 0)) return false;
*out = kRowF32;
return true;
}
if (!sc || sc->kind != RAD_PLANE_TILED || sc->block[0] != 1 || sc->block[1] != 128) return false;
if (!s2) {
if (sc->dtype != RAD_BF16 || enc->n_planes != want_planes) return false;
*out = kBf16;
return true;
}
if (sc->dtype != RAD_F8E4M3 || enc->n_planes != want_planes + 1) return false;
if (s2->kind != RAD_PLANE_TILED || (s2->dtype != RAD_F32 && s2->dtype != RAD_BF16) ||
s2->block[1] != 0 || (s2->block[0] != 0 && s2->block[0] != 1))
return false;
*out = s2->block[0] == 0 ? kE4m3Tensor : kE4m3Row;
return true;
}
/* Which IQR form `enc` is at transform `tr`, and the entries its table holds. Int8 codes are not
* one: the int8 GEMMs read them as they are. */
bool classify(const RadEncoding* enc, const char* tr, Form* f, int64_t* entries) {
*f = Form{};
*entries = 0;
if (!enc || std::strncmp(enc->transform, tr, RAD_ENC_STR) != 0) return false;
const RadEncPlane& cp = enc->plane[0];
if (std::strncmp(cp.role, "codes", RAD_ENC_STR) != 0) return false;
if (rad_enc_is(enc, "trellis")) {
const RadEncPlane* tp = rad_enc_plane(enc, "trellis");
/* tcq_code=mad: A and B beside the table, the values computed where they are read */
const RadEncPlane* mp = rad_enc_plane(enc, "trellis.mad");
const int b = unsigned_bits(cp.dtype);
uint32_t sc = 0;
if (!tp || !b || cp.block[0] != 1 || cp.block[1] != 1 || !scale_form(enc, mp ? 4 : 3, &sc))
return false;
if (mp && (mp->kind != RAD_PLANE_TABLE || mp->dtype != RAD_U32 || mp->extent[0] != 2 ||
mp->extent[1] != 1))
return false;
const int L = log2_exact(tp->extent[0]);
const int lrun = log2_exact(tp->block[0]);
const int lrb = tp->block[1] > 1 ? log2_exact(tp->block[1]) : 0;
/* A table's values are read from LDS (16 KiB at L = 14), a computed code's from none; a run
* is whole 16-row tiles. */
if (tp->kind != RAD_PLANE_TABLE || tp->dtype != RAD_I8 || tp->extent[1] != 1 || L <= b ||
L > (mp ? 16 : 14) || lrun < 4 || lrb < 0 || lrb > lrun)
return false;
f->kind = mp ? kTrellisMad : kTrellis; f->bits = (uint32_t)b; f->L = (uint32_t)L; f->lrun = (uint32_t)lrun;
f->lrb = (uint32_t)lrb; f->scale = sc;
*entries = tp->extent[0];
return span(*f) <= 16;
}
if (!rad_enc_is(enc, "affine")) return false;
uint32_t sc = 0;
if (cp.block[0] != 1) return false;
/* A vector grid: one code a V-vector (V 2 or 4: a lane's four columns hold whole vectors), an i8
* table of V-vectors. */
if (cp.block[1] > 1) {
const RadEncPlane* gr = rad_enc_plane(enc, "grid");
const int b = unsigned_bits(cp.dtype) ? unsigned_bits(cp.dtype)
: cp.dtype == RAD_U9 ? 9 : cp.dtype == RAD_U10 ? 10 : cp.dtype == RAD_U11 ? 11
: cp.dtype == RAD_U12 ? 12 : 0;
const int lv = log2_exact(cp.block[1]);
if (!gr || !b || lv < 1 || lv > 2 || !scale_form(enc, 3, &sc) || sc != kBf16 ||
gr->kind != RAD_PLANE_TABLE || gr->dtype != RAD_I8 || gr->extent[1] != cp.block[1] ||
gr->extent[0] < 1 || gr->extent[0] > ((int64_t)1 << b) ||
((int64_t)1 << b) * cp.block[1] > 16384)
return false;
f->kind = kGrid; f->bits = (uint32_t)b; f->lv = (uint32_t)lv; f->scale = kBf16;
*entries = gr->extent[0];
return true;
}
if (const int b = signed_bits(cp.dtype)) {
if (!scale_form(enc, 2, &sc) || sc != kBf16) return false;
f->kind = kSigned; f->bits = (uint32_t)b;
return true;
}
const int b = unsigned_bits(cp.dtype);
if (!b || b > 7) return false;
if (const RadEncPlane* zp = rad_enc_plane(enc, "zero")) {
if (!scale_form(enc, 3, &sc) || sc != kBf16 || !unsigned_bits(zp->dtype) ||
zp->block[0] != 1 || zp->block[1] != 128)
return false;
f->kind = kZero; f->bits = (uint32_t)b;
return true;
}
if (const RadEncPlane* tp = rad_enc_plane(enc, "table")) {
if (!scale_form(enc, 3, &sc) || sc != kBf16 || tp->kind != RAD_PLANE_TABLE ||
tp->dtype != RAD_I8 || tp->extent[0] != 1 || tp->extent[1] < 2 ||
tp->extent[1] > ((int64_t)1 << b))
return false;
f->kind = kTable; f->bits = (uint32_t)b;
*entries = tp->extent[1];
return true;
}
return false;
}
struct Geom { long long N, K, nkb; };
int geom(const RadParam* p, int n_p, Geom* g) {
g->N = r4d_pgeti_or(p, n_p, "N", 0);
g->K = r4d_pgeti_or(p, n_p, "K", 0);
if (g->N <= 0 || g->K <= 0) return RAD_E_SHAPE;
if (r4d_pgeti_or(p, n_p, "group", 128) != 128) return RAD_E_SHAPE;
if (g->N % 16 || g->K % 128) return RAD_E_SHAPE;
g->nkb = g->K / 128;
return RAD_OK;
}
void lfill(RadLayout* out, const char* tag, uint32_t dt, long long d0, long long d1,
long long bytes) {
std::memset(out, 0, sizeof(*out));
out->tag = tag;
out->dtype = dt;
out->rank = 2;
out->shape[0] = d0;
out->shape[1] = d1;
out->align = 256;
out->bytes = bytes;
}
/* The selected planes by role. */
struct Planes {
const RadTensor *codes = nullptr, *aux = nullptr, *scale = nullptr, *scale2 = nullptr,
*mad = nullptr, *colf = nullptr;
};
bool planes_of(const RadEncoding* enc, const int* sel, const RadTensor* pl, int n, Planes* o) {
if (!sel || !pl) return false;
for (int i = 0; i < n; ++i) {
const char* r = r4d_enc::role(enc, sel, i);
if (!std::strncmp(r, "codes", RAD_ENC_STR)) o->codes = &pl[i];
else if (!std::strncmp(r, "scale", RAD_ENC_STR)) o->scale = &pl[i];
else if (!std::strncmp(r, "scale.1", RAD_ENC_STR)) o->scale2 = &pl[i];
else if (!std::strncmp(r, "trellis.mad", RAD_ENC_STR)) o->mad = &pl[i];
else if (!std::strncmp(r, "scale.col", RAD_ENC_STR)) o->colf = &pl[i];
else if (!std::strncmp(r, "zero", RAD_ENC_STR) || !std::strncmp(r, "table", RAD_ENC_STR) ||
!std::strncmp(r, "grid", RAD_ENC_STR) || !std::strncmp(r, "trellis", RAD_ENC_STR))
o->aux = &pl[i];
else return false;
}
return true;
}
/* The weight's form and planes, checked against its geometry. */
int weight_view(const RadParam* p, int n_p, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, Geom* g, Form* f, int64_t* entries, Planes* v) {
int rc = geom(p, n_p, g);
if (rc != RAD_OK) return rc;
const char* d = r4d_pgets(p, n_p, "dtype");
const bool rot = d && std::strcmp(d, "i8a8h") == 0;
if (!classify(enc, rot ? "fwht128" : "", f, entries) || !built(word(*f))) return RAD_E_DTYPE;
if (!planes_of(enc, sel, pl, n, v) || !v->codes) return RAD_E_SHAPE;
const bool aux = f->kind != kSigned;
if (aux != (v->aux != nullptr) || (f->kind == kTrellisMad) != (v->mad != nullptr))
return RAD_E_SHAPE;
const long long kc = f->kind == kGrid ? g->K >> f->lv : g->K;
if (!r4d_enc::dims(*v->codes, g->N, kc)) return RAD_E_SHAPE;
if (is_trellis(f->kind) && g->N % ((long long)1 << f->lrun)) return RAD_E_SHAPE;
if (f->kind == kZero && !r4d_enc::dims(*v->aux, g->N, g->nkb)) return RAD_E_SHAPE;
return RAD_OK;
}
/* ---- bits ----------------------------------------------------------------------------------- */
/* `n` <= 57 bits of a plane row from bit `o`. */
inline uint64_t get_bits(const uint8_t* row, long long o, int n) {
const uint8_t* b = row + (o >> 3);
const int sh = (int)(o & 7);
const int bytes = (sh + n + 7) >> 3;
uint64_t w = 0;
for (int i = 0; i < bytes; ++i) w |= (uint64_t)b[i] << (8 * i);
return (w >> sh) & (n == 64 ? ~0ull : ((1ull << n) - 1ull));
}
/* OR `n` <= 57 bits into a zeroed buffer at bit `o`. */
inline void put_bits(uint8_t* dst, long long o, uint64_t v, int n) {
uint8_t* b = dst + (o >> 3);
const int sh = (int)(o & 7);
const int bytes = (sh + n + 7) >> 3;
v <<= sh;
for (int i = 0; i < bytes; ++i) b[i] |= (uint8_t)(v >> (8 * i));
}
/* Runs f(lo, hi) over [0, n) in parallel chunks. A model's weights relayout at load, gigabytes of
* them, so the walk is split over the host's cores. */
template <typename F>
void par_for(long long n, F f) {
const unsigned hc = std::max(1u, std::min(16u, std::thread::hardware_concurrency()));
const long long per = std::max(1ll, (n + hc - 1) / hc);
std::vector<std::thread> th;
for (long long lo = 0; lo < n; lo += per) th.emplace_back(f, lo, std::min(n, lo + per));
for (std::thread& t : th) t.join();
}
/* Visits each code of the weight with its row-major position (row r, code column c in the codes
* plane) and its bit in the stored codes plane: the one definition of r4d_iqr.h's order, walked
* forwards by the relayout and backwards by the unrelayout. `per_tile(rt, visit)` gives a worker a
* whole 16-row tile so it can read its rows once. */
template <typename V>
void walk_tile(const Form& f, long long K, long long rt, V visit) {
const long long nkb = K / 128;
const long long ub = unit_bytes(f) * 8;
const int B = (int)f.bits;
for (long long kb = 0; kb < nkb; ++kb) {
const long long u0 = (rt * nkb + kb) * ub;
for (int lane = 0; lane < 32; ++lane) {
const long long l0 = u0 + (long long)lane * lane_bits(f), k0 = kb * 128 + 4 * lane;
if (is_trellis(f.kind)) {
for (int e = 0; e < 4; ++e)
for (int q = 0; q < 16; ++q)
visit(rt * 16 + 15 - q, k0 + e, l0 + (e * 16 + q) * B);
continue;
}
const int per = f.kind == kGrid ? 4 >> f.lv : 4; /* codes a row */
for (int r = 0; r < 16; ++r)
for (int e = 0; e < per; ++e)
visit(rt * 16 + r, f.kind == kGrid ? (k0 >> f.lv) + e : k0 + e,
l0 + (r * per + e) * B);
}
}
}
/* The value a decoded code stands for, or a code no entry answers (-1000). */
int scalar_value(const Form& f, const Planes& v, int64_t entries, long long r, long long c,
uint32_t code) {
if (f.kind == kSigned) return (int)(code << (32 - f.bits)) >> (32 - f.bits);
if (f.kind == kTable)
return (int64_t)code < entries ? ((const int8_t*)v.aux->data)[code] : -1000;
if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
return (int)code - (int)rad_load_bits(r4d_enc::row(*v.aux, r), zb, c / 128);
}
return 0;
}
int weight_relayout(const Form& f, const Geom& g, int64_t entries, const Planes& v, uint8_t* d,
int64_t bytes) {
if (bytes != weight_bytes(f, g.N, g.K) || !v.codes->data) return RAD_E_SHAPE;
std::memset(d, 0, (size_t)bytes);
std::atomic<int> bad{ RAD_OK };
const int B = (int)f.bits;
par_for(g.N / 16, [&](long long lo, long long hi) {
for (long long rt = lo; rt < hi; ++rt)
walk_tile(f, g.K, rt, [&](long long r, long long c, long long bit) {
const uint32_t code = (uint32_t)get_bits(r4d_enc::row(*v.codes, r), c * B, B);
if (f.kind == kSigned || f.kind == kTable || f.kind == kZero) {
const int val = scalar_value(f, v, entries, r, c, code);
if (val < -127 || val > 127) bad = RAD_E_FORMAT;
} else if (f.kind == kGrid && (int64_t)code >= entries) {
bad = RAD_E_FORMAT;
}
put_bits(d, bit, code, B);
});
});
if (bad != RAD_OK) return bad;
uint8_t* aux = d + aux_off(f, g.N, g.K);
if (f.kind == kTable || f.kind == kGrid || is_trellis(f.kind)) {
const long long n = f.kind == kTable ? entries
: f.kind == kGrid ? entries << f.lv : entries;
const int8_t* t = (const int8_t*)v.aux->data;
for (long long i = 0; i < n; ++i)
if (t[i] < -127 && f.kind != kTable) return RAD_E_FORMAT;
std::memcpy(aux, t, (size_t)n);
if (f.kind == kTrellisMad) {
/* The kernels compute the values from A and B: the stored table must be that code. */
if (!v.mad || !v.mad->data) return RAD_E_SHAPE;
const uint32_t a = ((const uint32_t*)v.mad->data)[0], b = ((const uint32_t*)v.mad->data)[1];
for (long long st = 0; st < n; ++st) {
const uint32_t h = (((uint32_t)st & 0xFFFFFFu) * (a & 0xFFFFFFu) + b) & 0x3F3F3F3Fu;
const int q = (int)((h & 0xFFu) + ((h >> 8) & 0xFFu) + ((h >> 16) & 0xFFu) + (h >> 24)) - 126;
if (q != t[st]) return RAD_E_FORMAT;
}
std::memcpy(aux + n, v.mad->data, 8);
}
} else if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
for (long long r = 0; r < g.N; ++r)
for (long long kb = 0; kb < g.nkb; ++kb)
aux[tile_major(r, kb, g.nkb)] = (uint8_t)rad_load_bits(r4d_enc::row(*v.aux, r), zb, kb);
}
return RAD_OK;
}
int weight_unrelayout(const Form& f, const Geom& g, int64_t entries, const Planes& v,
const uint8_t* s, int64_t bytes) {
if (bytes != weight_bytes(f, g.N, g.K) || !v.codes->data) return RAD_E_SHAPE;
const int B = (int)f.bits;
const long long rb = rad_dtype_bytes(v.codes->dtype, v.codes->shape[1]);
std::memset(v.codes->data, 0, (size_t)(rb * g.N));
par_for(g.N / 16, [&](long long lo, long long hi) {
for (long long rt = lo; rt < hi; ++rt)
walk_tile(f, g.K, rt, [&](long long r, long long c, long long bit) {
put_bits((uint8_t*)v.codes->data + r * rb, c * B, get_bits(s, bit, B), B);
});
});
const uint8_t* aux = s + aux_off(f, g.N, g.K);
if (f.kind == kTable || f.kind == kGrid || is_trellis(f.kind)) {
const long long n = f.kind == kGrid ? entries << f.lv : entries;
std::memcpy(v.aux->data, aux, (size_t)n);
if (f.kind == kTrellisMad && v.mad && v.mad->data) std::memcpy(v.mad->data, aux + n, 8);
} else if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
const long long zr = rad_dtype_bytes(v.aux->dtype, v.aux->shape[1]);
std::memset(v.aux->data, 0, (size_t)(zr * g.N));
for (long long r = 0; r < g.N; ++r)
for (long long kb = 0; kb < g.nkb; ++kb)
rad_store_bits((uint8_t*)v.aux->data + r * zr, zb, kb, aux[tile_major(r, kb, g.nkb)]);
}
return RAD_OK;
}
/* ---- scales --------------------------------------------------------------------------------- */
/* The bf16 bits of a row's scale for block kb: the plane's own, or the E4M3 times its second level
* rounded to nearest even (libquant's grid_tcq_settle). */
uint16_t own_scale(const Form& f, const Planes& v, long long r, long long kb) {
if (f.scale == kBf16) return ((const uint16_t*)r4d_enc::row(*v.scale, r))[kb];
const uint8_t e = r4d_enc::row(*v.scale, r)[kb];
const float s2 = rad_load_f32(v.scale2->data, v.scale2->dtype, f.scale == kE4m3Row ? r : 0);
const float x = s2 * rad_fp8e4m3_to_f32(e);
uint32_t u;
std::memcpy(&u, &x, 4);
u += 0x7FFFu + ((u >> 16) & 1u);
return (uint16_t)(u >> 16);
}
int scale_view(const RadParam* p, int n_p, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, Geom* g, Form* f, Planes* v) {
int rc = geom(p, n_p, g);
if (rc != RAD_OK) return rc;
const char* d = r4d_pgets(p, n_p, "dtype");
const bool rot = d && std::strcmp(d, "i8a8h") == 0;
int64_t entries = 0;
if (!classify(enc, rot ? "fwht128" : "", f, &entries) || !built(word(*f))) return RAD_E_DTYPE;
if (!planes_of(enc, sel, pl, n, v) || !v->scale || v->codes || v->aux) return RAD_E_SHAPE;
if (f->scale == kRowF32) {
if (v->scale2 || !r4d_enc::dims(*v->scale, g->N, 1)) return RAD_E_SHAPE;
if (v->colf && !r4d_enc::dims(*v->colf, 1, g->nkb)) return RAD_E_SHAPE;
if ((rad_enc_plane(enc, "scale.col") != nullptr) != (v->colf != nullptr)) return RAD_E_SHAPE;
return RAD_OK;
}
if ((f->scale != kBf16) != (v->scale2 != nullptr)) return RAD_E_SHAPE;
if (!r4d_enc::dims(*v->scale, g->N, g->nkb)) return RAD_E_SHAPE;
if (v->scale2 && (v->scale2->rank != 2 || v->scale2->shape[1] != 1 ||
v->scale2->shape[0] != (f->scale == kE4m3Row ? g->N : 1)))
return RAD_E_SHAPE;
return RAD_OK;
}
int scale_relayout(const Form& f, const Geom& g, const Planes& v, uint8_t* d, int64_t bytes) {
if (bytes != scale_bytes(f, g.N, g.K) || !v.scale->data) return RAD_E_SHAPE;
std::memset(d, 0, (size_t)bytes);
if (f.scale == kRowF32) {
float* rs = (float*)d;
float* cf = (float*)(d + cf_off(f, g.N, g.K));
for (long long r = 0; r < g.N; ++r) rs[r] = *(const float*)r4d_enc::row(*v.scale, r);
for (long long kb = 0; kb < g.nkb; ++kb)
cf[kb] = v.colf ? ((const float*)v.colf->data)[kb] : 1.0f;
return RAD_OK;
}
for (long long r = 0; r < g.N; ++r)
for (long long kb = 0; kb < g.nkb; ++kb) {
const long long i = tile_major(r, kb, g.nkb);
if (f.scale == kBf16) ((uint16_t*)d)[i] = ((const uint16_t*)r4d_enc::row(*v.scale, r))[kb];
else d[i] = r4d_enc::row(*v.scale, r)[kb];
}
if (f.scale != kBf16) {
float* s2 = (float*)(d + s2_off(f, g.N, g.K));
const long long n2 = f.scale == kE4m3Row ? g.N : 1;
for (long long r = 0; r < n2; ++r) s2[r] = rad_load_f32(v.scale2->data, v.scale2->dtype, r);
}
if (f.lrb) {
/* Scales are positive, so their bf16 bits order as the values do. */
uint16_t* bp = (uint16_t*)(d + blk_off(f, g.N, g.K));
const long long rb = 1ll << f.lrb;
for (long long b = 0; b < g.N / rb; ++b)
for (long long kb = 0; kb < g.nkb; ++kb) {
uint16_t m = 0;
for (long long r = b * rb; r < b * rb + rb; ++r) m = std::max(m, own_scale(f, v, r, kb));
bp[b * g.nkb + kb] = m;
}
}
return RAD_OK;
}
int scale_unrelayout(const Form& f, const Geom& g, const Planes& v, const uint8_t* s,
int64_t bytes) {
if (bytes != scale_bytes(f, g.N, g.K) || !v.scale->data) return RAD_E_SHAPE;
if (f.scale == kRowF32) {
const float* rs = (const float*)s;
const float* cf = (const float*)(s + cf_off(f, g.N, g.K));
for (long long r = 0; r < g.N; ++r) *(float*)((uint8_t*)v.scale->data + r * 4) = rs[r];
if (v.colf)
for (long long kb = 0; kb < g.nkb; ++kb) ((float*)v.colf->data)[kb] = cf[kb];
return RAD_OK;
}
for (long long r = 0; r < g.N; ++r)
for (long long kb = 0; kb < g.nkb; ++kb) {
const long long i = tile_major(r, kb, g.nkb);
uint8_t* row = (uint8_t*)v.scale->data + r * rad_dtype_bytes(v.scale->dtype, g.nkb);
if (f.scale == kBf16) ((uint16_t*)row)[kb] = ((const uint16_t*)s)[i];
else row[kb] = s[i];
}
/* The second level is f32 here and may be bf16 in the container; a bf16 one round-trips
* through f32 exactly. */
if (f.scale != kBf16) {
const float* s2 = (const float*)(s + s2_off(f, g.N, g.K));
const long long n2 = f.scale == kE4m3Row ? g.N : 1;
for (long long r = 0; r < n2; ++r) {
if (v.scale2->dtype == RAD_F32) {
((float*)v.scale2->data)[r] = s2[r];
} else {
uint32_t u;
std::memcpy(&u, &s2[r], 4);
((uint16_t*)v.scale2->data)[r] = (uint16_t)(u >> 16);
}
}
}
return RAD_OK;
}
} /* namespace */
/* ==================================================================== the hooks */
extern "C" int r4d_rad_layout_iqr(const RadParam* p, int n_p, int operand, const RadEncoding* enc,
const int* sel, const RadTensor* pl, int n, RadLayout* out) {
if (!out) return RAD_E_INVAL;
Geom g;
Form f;
Planes v;
if (operand == IL_B) {
int64_t entries = 0;
const int rc = weight_view(p, n_p, enc, sel, pl, n, &g, &f, &entries, &v);
if (rc != RAD_OK) return rc;
lfill(out, "r4d.iqr.w", R4D_DT_IQR_W | word(f), g.N, g.K, weight_bytes(f, g.N, g.K));
return RAD_OK;
}
if (operand == IL_BSCALE) {
const int rc = scale_view(p, n_p, enc, sel, pl, n, &g, &f, &v);
if (rc != RAD_OK) return rc;
lfill(out, "r4d.iqr.s", R4D_DT_IQR_S | word(f), g.N, g.nkb, scale_bytes(f, g.N, g.K));
return RAD_OK;
}
return RAD_E_UNSUPPORTED;
}
extern "C" int r4d_rad_relayout_iqr(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* pl,
int n, void* dst, int64_t dst_bytes) {
Geom g;
Form f;
Planes v;
if (operand == IL_B) {
int64_t entries = 0;
const int rc = weight_view(p, n_p, enc, sel, pl, n, &g, &f, &entries, &v);
if (rc != RAD_OK) return rc;
if (v.aux && !v.aux->data) return RAD_E_SHAPE;
return weight_relayout(f, g, entries, v, (uint8_t*)dst, dst_bytes);
}
if (operand == IL_BSCALE) {
const int rc = scale_view(p, n_p, enc, sel, pl, n, &g, &f, &v);
if (rc != RAD_OK) return rc;
if (v.scale2 && !v.scale2->data) return RAD_E_SHAPE;
return scale_relayout(f, g, v, (uint8_t*)dst, dst_bytes);
}
return RAD_E_UNSUPPORTED;
}
extern "C" int r4d_rad_unrelayout_iqr(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const void* src,
int64_t src_bytes, const RadTensor* pl, int n) {
Geom g;
Form f;
Planes v;
if (operand == IL_B) {
int64_t entries = 0;
const int rc = weight_view(p, n_p, enc, sel, pl, n, &g, &f, &entries, &v);
if (rc != RAD_OK) return rc;
if (v.aux && !v.aux->data) return RAD_E_SHAPE;
return weight_unrelayout(f, g, entries, v, (const uint8_t*)src, src_bytes);
}
if (operand == IL_BSCALE) {
const int rc = scale_view(p, n_p, enc, sel, pl, n, &g, &f, &v);
if (rc != RAD_OK) return rc;
if (v.scale2 && !v.scale2->data) return RAD_E_SHAPE;
return scale_unrelayout(f, g, v, (const uint8_t*)src, src_bytes);
}
return RAD_E_UNSUPPORTED;
}
/* ==================================================================== embed_lookup's table
*
* The rows as the container stores them (r4d_iqr.h's embed_off): only the gather's handful of rows
* a step are decoded, so nothing is reordered, and nothing is widened. A plain bf16 table is the
* bf16 gather's. */
namespace {
enum { EL_WTE = 1 };
int embed_view(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, Form* f, int64_t* entries, Planes* v, long long* rows,
long long* dim) {
if (operand != EL_WTE) return RAD_E_UNSUPPORTED;
*rows = r4d_pgeti_or(p, n_p, "n_vocab", 0);
*dim = r4d_pgeti_or(p, n_p, "n_embd", 0);
if (*rows <= 0 || *dim <= 0 || *dim % 128) return RAD_E_SHAPE;
if (rad_enc_is(enc, "plain")) return RAD_E_DTYPE;
const bool rot = !std::strncmp(enc->transform, "fwht128", RAD_ENC_STR);
if (!classify(enc, rot ? "fwht128" : "", f, entries)) return RAD_E_DTYPE;
f->rot = rot ? 1u : 0u;
if (!embed_built(word(*f))) return RAD_E_DTYPE;
if (!planes_of(enc, sel, pl, n, v) || !v->codes || !v->scale) return RAD_E_SHAPE;
if ((f->kind != kSigned) != (v->aux != nullptr)) return RAD_E_SHAPE;
if ((f->scale != kBf16) != (v->scale2 != nullptr)) return RAD_E_SHAPE;
const long long nkb = *dim / 128;
if (!r4d_enc::dims(*v->codes, *rows, code_cols(*f, *dim)) ||
!r4d_enc::dims(*v->scale, *rows, nkb))
return RAD_E_SHAPE;
if (f->kind == kTrellis && *rows % (1ll << f->lrun)) return RAD_E_SHAPE;
if (f->kind == kZero && !r4d_enc::dims(*v->aux, *rows, nkb)) return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_iqr_embed(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel, const RadTensor* pl,
int n, RadLayout* out) {
if (!out) return RAD_E_INVAL;
Form f;
int64_t entries = 0;
Planes v;
long long rows = 0, dim = 0;
const int rc = embed_view(p, n_p, operand, enc, sel, pl, n, &f, &entries, &v, &rows, &dim);
if (rc != RAD_OK) return rc;
lfill(out, "r4d.iqr.embed", R4D_DT_IQR_W | word(f), rows, dim, embed_off(f, rows, dim).bytes);
return RAD_OK;
}
extern "C" int r4d_rad_relayout_iqr_embed(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
Form f;
int64_t entries = 0;
Planes v;
long long rows = 0, dim = 0;
const int rc = embed_view(p, n_p, operand, enc, sel, pl, n, &f, &entries, &v, &rows, &dim);
if (rc != RAD_OK) return rc;
const EmbedOff o = embed_off(f, rows, dim);
if (dst_bytes != o.bytes || !v.codes->data || !v.scale->data || (v.aux && !v.aux->data) ||
(v.scale2 && !v.scale2->data))
return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
const long long nkb = dim / 128, crow = rad_dtype_bytes(v.codes->dtype, v.codes->shape[1]);
if (crow != o.codes_row) return RAD_E_SHAPE;
std::memcpy(d, v.codes->data, (size_t)(rows * crow));
uint8_t* aux = d + o.aux;
if (f.kind == kTable || f.kind == kGrid || f.kind == kTrellis) {
const long long na = f.kind == kGrid ? entries << f.lv : entries;
const int8_t* t = (const int8_t*)v.aux->data;
for (long long i = 0; i < na; ++i)
if (t[i] < -127) return RAD_E_FORMAT;
std::memcpy(aux, t, (size_t)na);
} else if (f.kind == kZero) {
const int zb = unsigned_bits(v.aux->dtype);
for (long long r = 0; r < rows; ++r)
for (long long kb = 0; kb < nkb; ++kb)
aux[r * nkb + kb] = (uint8_t)rad_load_bits(r4d_enc::row(*v.aux, r), zb, kb);
}
const long long sb = f.scale == kBf16 ? 2 : 1;
for (long long r = 0; r < rows; ++r)
std::memcpy(d + o.sc + r * nkb * sb, r4d_enc::row(*v.scale, r), (size_t)(nkb * sb));
if (f.scale != kBf16) {
float* s2 = (float*)(d + o.s2);
for (long long r = 0; r < (f.scale == kE4m3Row ? rows : 1); ++r)
s2[r] = rad_load_f32(v.scale2->data, v.scale2->dtype, r);
}
if (f.lrb) {
uint16_t* bp = (uint16_t*)(d + o.blk);
const long long rb = 1ll << f.lrb;
for (long long b = 0; b < rows / rb; ++b)
for (long long kb = 0; kb < nkb; ++kb) {
uint16_t m = 0;
for (long long r = b * rb; r < b * rb + rb; ++r) m = std::max(m, own_scale(f, v, r, kb));
bp[b * nkb + kb] = m;
}
}
return RAD_OK;
}
/* ==================================================================== logits_gemm's head
*
* The rows of r4d_iqr.h's lm form: the container's packed codes and the row's scales, the table
* after the last row. A reorder of the stored bytes, so it inverts. */
namespace {
enum { LG_W = 1 };
int lm_view(const RadParam* p, int n_p, int operand, const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, Form* f, int64_t* entries, Planes* v, long long* rows,
long long* dim) {
if (operand != LG_W) return RAD_E_UNSUPPORTED;
*rows = r4d_pgeti_or(p, n_p, "n_vocab", 0);
*dim = r4d_pgeti_or(p, n_p, "n_embd", 0);
if (*rows <= 0 || *dim <= 0 || *dim % 128) return RAD_E_SHAPE;
if (!classify(enc, "", f, entries) || !lm_built(word(*f))) return RAD_E_DTYPE;
if (!planes_of(enc, sel, pl, n, v) || !v->codes || !v->scale || !v->aux) return RAD_E_SHAPE;
if (!r4d_enc::dims(*v->codes, *rows, *dim) || !r4d_enc::dims(*v->scale, *rows, *dim / 128))
return RAD_E_SHAPE;
return RAD_OK;
}
} /* namespace */
extern "C" int r4d_rad_layout_iqr_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, RadLayout* out) {
if (!out) return RAD_E_INVAL;
Form f;
int64_t entries = 0;
Planes v;
long long rows = 0, dim = 0;
const int rc = lm_view(p, n_p, operand, enc, sel, pl, n, &f, &entries, &v, &rows, &dim);
if (rc != RAD_OK) return rc;
lfill(out, "r4d.iqr.lm", R4D_DT_IQR_W | word(f), rows, lm_row(f, dim), lm_bytes(f, rows, dim));
return RAD_OK;
}
extern "C" int r4d_rad_relayout_iqr_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const RadTensor* pl, int n, void* dst,
int64_t dst_bytes) {
Form f;
int64_t entries = 0;
Planes v;
long long rows = 0, dim = 0;
const int rc = lm_view(p, n_p, operand, enc, sel, pl, n, &f, &entries, &v, &rows, &dim);
if (rc != RAD_OK) return rc;
if (dst_bytes != lm_bytes(f, rows, dim) || !v.codes->data || !v.scale->data || !v.aux->data)
return RAD_E_SHAPE;
uint8_t* d = (uint8_t*)dst;
std::memset(d, 0, (size_t)dst_bytes);
const long long stride = lm_row(f, dim), cb = dim / 8 * f.bits, nkb = dim / 128;
for (long long r = 0; r < rows; ++r) {
uint8_t* row = d + r * stride;
std::memcpy(row, r4d_enc::row(*v.codes, r), (size_t)cb);
std::memcpy(row + cb, r4d_enc::row(*v.scale, r), (size_t)(2 * nkb));
}
const int8_t* t = (const int8_t*)v.aux->data;
for (int64_t i = 0; i < entries; ++i)
if (t[i] < -127) return RAD_E_FORMAT;
std::memcpy(d + lm_tab(f, rows, dim), t, (size_t)entries);
return RAD_OK;
}
extern "C" int r4d_rad_unrelayout_iqr_logits(const RadParam* p, int n_p, int operand,
const RadEncoding* enc, const int* sel,
const void* src, int64_t src_bytes,
const RadTensor* pl, int n) {
Form f;
int64_t entries = 0;
Planes v;
long long rows = 0, dim = 0;
const int rc = lm_view(p, n_p, operand, enc, sel, pl, n, &f, &entries, &v, &rows, &dim);
if (rc != RAD_OK) return rc;
if (src_bytes != lm_bytes(f, rows, dim) || !v.codes->data || !v.scale->data || !v.aux->data)
return RAD_E_SHAPE;
const uint8_t* s = (const uint8_t*)src;
const long long stride = lm_row(f, dim), cb = dim / 8 * f.bits, nkb = dim / 128;
for (long long r = 0; r < rows; ++r) {
std::memcpy((uint8_t*)v.codes->data + r * cb, s + r * stride, (size_t)cb);
std::memcpy((uint8_t*)v.scale->data + r * nkb * 2, s + r * stride + cb, (size_t)(2 * nkb));
}
std::memcpy(v.aux->data, s + lm_tab(f, rows, dim), (size_t)entries);
return RAD_OK;
}
+6 -4
View File
@@ -338,13 +338,15 @@ void sz_read(const WGeom& g, const uint32_t* sz, const RadTensor* pl, bool asym)
}
}
/* A rotated asymmetric grid (ParoQuant): codes of dtype `codes`, an f16 scale and a zero point
* per group, optionally with a `givens` transform and its tables. The bytes are the unrotated
* grid's; the rotation is applied to the activation. */
/* A rotated asymmetric grid: codes of dtype `codes`, an f16 scale and a zero point per group,
* optionally with ParoQuant's `givens` transform and its tables, or libquant's `fwht128` (the
* scale carrying its 1/128). The bytes are the unrotated grid's; the rotation is applied to the
* activation. */
static bool paro_asym_enc(const RadEncoding* e, uint32_t codes, long long group) {
if (!e || !rad_enc_is(e, "affine") || e->n_planes < 3) return false;
const bool giv = std::strncmp(e->transform, "givens", RAD_ENC_STR) == 0;
if (!giv && e->transform[0]) return false;
const bool fwht = std::strncmp(e->transform, "fwht128", RAD_ENC_STR) == 0;
if (!giv && !fwht && e->transform[0]) return false;
if (!giv && e->n_planes != 3) return false;
if (giv && (!rad_enc_valid(e) || rad_enc_find(e, "t.pairs") < 0)) return false;
if (std::strncmp(e->plane[0].role, "codes", RAD_ENC_STR) != 0 || e->plane[0].dtype != codes ||
+28 -12
View File
@@ -247,7 +247,11 @@ __device__ __forceinline__ void rmsnorm_body(
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = act_f32(xr[i]); ss += v * v; }
if (threadIdx.x < kR4dSumLanes)
for (uint32_t i = threadIdx.x; i < n; i += kR4dSumLanes) {
const float v = act_f32(xr[i]);
ss += v * v;
}
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
for (uint32_t i = threadIdx.x; i < n; i += THR) {
@@ -273,9 +277,10 @@ __global__ __launch_bounds__(THR) void r4dchain_rmsnorm(R4D_RN_PARAMS) {
// ---------------------------------------------------------------------------- add_rmsnorm
// x = x + a, rounded as `add` rounds it, then y = rmsnorm(x) over the x just written, computed as
// rmsnorm_kernel computes it: the same width (r4d_act_threads), the same columns a thread, the same
// block_sum. A thread re-reads only the x it wrote itself, so no barrier separates the passes.
// Byte-identical to `add` followed by `rmsnorm`, on x and on y.
// rmsnorm_kernel computes it: the same width (r4d_act_threads), the sum over kR4dSumLanes' columns,
// the same block_sum. Byte-identical to `add` followed by `rmsnorm`, on x and on y. At the
// narrowest width a thread sums only the x it wrote itself, so the add and the sum are one pass;
// a wider block sums x other threads wrote, behind a barrier.
template <bool WF32, uint32_t THR>
__device__ __forceinline__ void add_rmsnorm_body(
uint16_t* __restrict__ x, const uint16_t* __restrict__ a, const void* __restrict__ w,
@@ -289,11 +294,22 @@ __device__ __forceinline__ void add_rmsnorm_body(
uint16_t* __restrict__ yr = y + (size_t)m * y_ld;
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i]));
xr[i] = h;
const float v = bf16_to_f32(h);
ss += v * v;
if constexpr (THR == kR4dSumLanes) {
for (uint32_t i = threadIdx.x; i < n; i += THR) {
const uint16_t h = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i]));
xr[i] = h;
const float v = bf16_to_f32(h);
ss += v * v;
}
} else {
for (uint32_t i = threadIdx.x; i < n; i += THR)
xr[i] = f32_to_bf16(bf16_to_f32(xr[i]) + bf16_to_f32(ar[i]));
__syncthreads();
if (threadIdx.x < kR4dSumLanes)
for (uint32_t i = threadIdx.x; i < n; i += kR4dSumLanes) {
const float v = bf16_to_f32(xr[i]);
ss += v * v;
}
}
ss = block_sum<THR / kWave>(ss, lds);
const float s = rsqrtf(ss / (float)n + eps);
@@ -1062,9 +1078,9 @@ static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps,
if (!x_ld) x_ld = n;
if (!y_ld) y_ld = n;
// One workgroup per row, so decode rows are latency-bound. r4d_act_threads is the measured
// width table; r4d_rmsnorm_quant_fp8 must use the same one, because the width decides which
// columns a thread folds into the sum of squares and the fused kernel must be byte-identical
// to this one followed by the quantiser.
// width table; the sum of squares folds in kR4dSumLanes' partition at every width, so the
// fused norms (r4d_rmsnorm_quant_fp8, r4d_rmsnorm_quant_i8) stay byte-identical to this one
// followed by the quantiser at whatever width they run.
const int thr = r4d_act_threads(M, n);
// A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff.
const bool ch = chain && M <= 64;
+21
View File
@@ -598,7 +598,16 @@ int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_m16 (const RadArgs*, RadStream);
int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs*);
int r4d_rad_logits_gemm_i8(const RadArgs*, RadStream);
int r4d_rad_logits_gemm_iqr(const RadArgs*, RadStream);
int r4d_rad_logit_rerank_iqr(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_rb8_tiled(const RadArgs*, RadStream);
int r4d_rad_gemm_i8a8_rb32_tiled(const RadArgs*, RadStream);
/* The IQR weights, decoded from their codes where they are read (r4d_gemm_iqr.hip). */
int r4d_rad_gemm_iqr_m64(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_iqr_m64_scratch(const RadArgs*);
int r4d_rad_gemm_iqr_tiled(const RadArgs*, RadStream);
int64_t r4d_rad_gemm_iqr_tiled_scratch(const RadArgs*);
int r4d_rad_quant_act_i8g(const RadArgs*, RadStream);
int r4d_rad_had_quant_act_i8g(const RadArgs*, RadStream);
int r4d_rad_quant_act_fp8 (const RadArgs*, RadStream);
@@ -641,6 +650,8 @@ int r4d_rad_logits_gemm_fp8 (const RadArgs*, RadStream);
const void*, int64_t, const RadTensor*, int);
R4D_HOOKS(fp8_block)
R4D_HOOKS(i8_block)
R4D_HOOKS(iqr)
R4D_HOOKS(iqr_logits)
R4D_HOOKS(fp8_logits)
R4D_HOOKS(i8_logits)
R4D_HOOKS(hc_e4m3)
@@ -652,6 +663,15 @@ R4D_HOOKS(moe_w4_mod4)
#undef R4D_HOOKS
int r4d_rad_layout_fp8_rowmajor(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
/* embed_lookup_bf16's check that its table is plain bf16 (r4d_fp8_layout.cpp), and the IQR
* table's hooks and gather (r4d_iqr_layout.cpp, r4d_iqr_embed.hip). */
int r4d_rad_layout_embed_bf16(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_iqr_embed(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_relayout_iqr_embed(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, void*, int64_t);
int r4d_rad_embed_lookup_iqr(const RadArgs*, RadStream);
int r4d_rad_layout_embed_q(const RadParam*, int, int, const RadEncoding*, const int*,
const RadTensor*, int, RadLayout*);
int r4d_rad_layout_moe_fp8(const RadParam*, int, int, const RadEncoding*, const int*,
@@ -765,6 +785,7 @@ int r4d_rad_mul (const RadArgs*, RadStream);
int r4d_rad_mul_weight (const RadArgs*, RadStream);
int r4d_rad_act_mul (const RadArgs*, RadStream);
int r4d_rad_seg_mean (const RadArgs*, RadStream);
int r4d_rad_seg_softmax_pool(const RadArgs*, RadStream);
int r4d_rad_seg_mean_bf16_sum(const RadArgs*, RadStream);
int r4d_rad_qk_norm_rope (const RadArgs*, RadStream);
int r4d_rad_cast_widen (const RadArgs*, RadStream);
+5 -5
View File
@@ -28,15 +28,15 @@
// One block per (token, head) and one element per lane, required for bit-equality.
//
// Eight consecutive elements per lane with one wave per head (no LDS, rotary partner one shuffle
// away) computes a different function. r4d_rmsnorm_bf16's width decides which columns a thread
// away) computes a different function. r4d_rmsnorm_bf16's partition decides which columns a lane
// folds into the sum of squares, and a last-bit difference in the norm becomes a few percent where
// a rotated element's two products nearly cancel, enough to change the engine's text within a few
// dozen steps.
//
// The reference's fold is easy to reproduce: `rmsnorm_bf16` runs
// `for (i = threadIdx.x; i < n; i += THR)`, `r4d_act_threads` never returns fewer than 256 threads,
// and every head_dim here is at most 256, so it always folds exactly one element per thread. Lanes
// past the head add exact zeros, so `block_sum` over 8 or 32 wave partials gives the same number.
// The reference's fold is easy to reproduce: `rmsnorm_bf16` folds a row over kR4dSumLanes' 256
// lanes, lane v adding columns v, v+256, ... (r4d_common.h), and every head_dim here is at most
// 256, so it always folds exactly one element per lane. Lanes past the head add exact zeros, so
// `block_sum` over 8 or 32 wave partials gives the same number.
// Hence one element a lane, 256 threads, `block_sum` in ascending wave order.
//
// Cost: at rot 64 the rotary partner is in another wave. The lane re-derives it instead of an LDS
+12 -12
View File
@@ -8,11 +8,12 @@
//
// Byte-identical to the five (see r4d_rmsnorm_quant_i8.hip for why that matters), because:
//
// * each norm's sum of squares uses its standalone kernel's partition. rmsnorm runs one workgroup
// per row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t folds
// columns t, t+THR, ... in order and the waves are summed in order through LDS. Here a
// workgroup is head_dim threads, and thread t < min(THR, head_dim) folds the same columns in the
// same order while the rest hold zero, as the standalone kernel's surplus waves do;
// * each norm's sum of squares uses its standalone kernel's partition. rmsnorm folds a row over
// kR4dSumLanes' 256 lanes whatever its width (r4d_common.h) and rmsnorm_p runs at 256; lane
// t < min(256, head_dim) folds columns t, t+256, ... in order and the waves are summed in
// order through LDS. Here a workgroup is head_dim threads, and thread t < min(256, head_dim)
// folds the same columns in the same order while the rest hold zero, as the standalone
// kernel's surplus lanes do;
// * the norm output is rounded to bf16 as the standalone norm stores it, and the rotary reads that;
// * the rotary's per-pair arithmetic is rope_kernel's (powf ladder, sincosf, `x0*c - x1*s`,
// `x0*s + x1*c`), under the library's -ffp-contract=off.
@@ -45,8 +46,8 @@ constexpr uint32_t kWave = 32;
__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); }
// THR threads' partition of one head's sum of squares inside a head_dim-wide workgroup: thread
// t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order.
// The standalone norm's partition of one head's sum of squares inside a head_dim-wide workgroup:
// thread t < P = min(256, HD) folds t, t+P, ...; the waves are then summed in order.
template <uint32_t HD>
__device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_t P, float* lds) {
float ss = 0.0f;
@@ -281,11 +282,10 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store)
const long long Mp = r4d_numel(ps);
if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE);
// The standalone kernels' widths, from the same function: rmsnorm (one row per head) at
// r4d_act_threads(rows, head_dim), rmsnorm_p at 256.
const uint32_t pq = nq ? (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nq), (int)hd), hd)
: (uint32_t)hd;
const uint32_t pk = (uint32_t)std::min<long long>(r4d_act_threads((int)(M * nkv), (int)hd), hd);
// The standalone kernels' partitions: rmsnorm (one row per head) folds over kR4dSumLanes'
// lanes at any width, rmsnorm_p runs at 256.
const uint32_t pq = nq ? (uint32_t)std::min<long long>(kR4dSumLanes, hd) : (uint32_t)hd;
const uint32_t pk = (uint32_t)std::min<long long>(kR4dSumLanes, hd);
const uint32_t pv = (uint32_t)std::min<long long>(256, hd);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
+60 -29
View File
@@ -17,10 +17,11 @@
// * every intermediate the chain stores in bf16 is rounded to bf16 here and the next stage reads
// the rounded value: the post-norm output, the residual sum, the scaled residual and the norm
// output the quantiser reduces over;
// * both sums of squares use the standalone norm's partition: the width r4d_act_threads(M, n)
// picks, thread t folding columns t, t+THR, ... in order, then r4d_wave_sum and the waves in
// order through LDS (copied from r4d_model_bf16.hip's rmsnorm_kernel and block_sum, which live
// in another unit);
// * both sums of squares use the standalone norm's partition (kR4dSumLanes, r4d_common.h): lane
// v < 256 folds columns v, v+256, ... in order, the lanes past it add nothing, then r4d_wave_sum
// and the waves in order through LDS (copied from r4d_model_bf16.hip's rmsnorm_kernel and
// block_sum, which live in another unit). At 256 threads a thread's own columns are that
// partition; a wider block stages the row in LDS and its first 256 lanes fold it there;
// * each element's arithmetic matches the standalone kernels (`x * s * (g + wadd)`,
// `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f`), under -ffp-contract=off.
//
@@ -58,6 +59,17 @@ __device__ __forceinline__ float block_sum(float v, float* lds) {
return s;
}
// A row's sum of squares in the standalone norm's partition (kR4dSumLanes): lane v < 256 adds
// columns v, v + 256, ... of `row` in order, the lanes past it add nothing, so a row's bits do not
// depend on the block's width. `row` holds the row's bf16 values; when the block's threads wrote
// it, the caller issues the barrier first.
__device__ __forceinline__ float lanes_sumsq(const uint16_t* row, uint32_t n) {
float ss = 0.0f;
if (threadIdx.x < kR4dSumLanes)
for (uint32_t i = threadIdx.x; i < n; i += kR4dSumLanes) { const float f = bf2f(row[i]); ss += f * f; }
return ss;
}
__device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) {
return f32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]);
}
@@ -86,9 +98,10 @@ __device__ __forceinline__ void junction_row(
if (SCL) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
}
const float f = bf2f(v);
ss2 += f * f;
if constexpr (THR == kR4dSumLanes) { const float f = bf2f(v); ss2 += f * f; }
else ybuf[i] = v;
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss2 = lanes_sumsq(ybuf, n); }
ss2 = block_sum<THR / kWave>(ss2, l2);
const float s2 = rsqrtf(ss2 / (float)n + eps);
@@ -164,7 +177,10 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
float s1 = 0.0f;
if (POST) {
float ss = 0.0f;
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
if constexpr (THR == kR4dSumLanes)
for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
else
ss = lanes_sumsq(xr, n); // the branch output, read-only here
ss = block_sum<THR / kWave>(ss, l1);
s1 = rsqrtf(ss / (float)n + eps);
}
@@ -177,11 +193,11 @@ __global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel(
// The same kernel at decode heights (THR 1024, n <= 1024 * EPT), with every operand of the row
// loaded in one go before the first reduction. The kernel above reads the row again in each pass,
// each read behind a barrier, so a row costs three dependent memory round trips; on gfx1201 at
// 1 to 16 rows of 5376 that is 11 us a launch against 8.2 us for this form. Every pass partitions
// the row the same way (thread t takes columns t, t+THR, ...), so each thread keeps its own
// columns in registers and none needs another's; only the fragment-order store crosses threads,
// through `ybuf`. The sums, their order and every element's arithmetic are junction_row's, so the
// output bytes are the same. One row of it, for this kernel and for the all-reduce's tail
// 1 to 16 rows of 5376 that is 11 us a launch against 8.2 us for this form. Every elementwise pass
// partitions the row the same way (thread t takes columns t, t+THR, ...), so each thread keeps its
// own columns in registers; the sums and the fragment-order store cross threads through `ybuf`,
// which holds the row each sum folds in the standalone norm's partition. The sums, their order and
// every element's arithmetic are junction_row's, so the output bytes are the same. One row of it, for this kernel and for the all-reduce's tail
// (ar_rmsnorm_quant_i8_tail_kernel).
template <bool WF32, bool RES, bool POST, bool SCL, uint32_t THR, uint32_t EPT>
__device__ __forceinline__ void junction_reg_row(
@@ -211,7 +227,11 @@ __device__ __forceinline__ void junction_reg_row(
float ss = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e)
if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; }
if (tid + e * THR < n) {
if constexpr (THR == kR4dSumLanes) { const float v = bf2f(xv[e]); ss += v * v; }
else ybuf[tid + e * THR] = xv[e];
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss = lanes_sumsq(ybuf, n); }
s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
}
@@ -229,10 +249,11 @@ __device__ __forceinline__ void junction_reg_row(
rr[i] = v;
}
xv[e] = v;
const float f = bf2f(v);
ss2 += f * f;
if constexpr (THR == kR4dSumLanes) { const float f = bf2f(v); ss2 += f * f; }
else ybuf[i] = v;
}
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss2 = lanes_sumsq(ybuf, n); }
const float s2 = rsqrtf(block_sum<THR / kWave>(ss2, l2) / (float)n + eps);
// ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax
@@ -360,8 +381,13 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
for (uint32_t i = tid; i < n; i += THR) {
const uint16_t a = f32_to_bf16(bf2f(xr[i]) + bf2f(pr[i]));
xr[i] = a;
if (POST) { const float v = bf2f(a); ss += v * v; }
if (POST) {
if constexpr (THR == kR4dSumLanes) { const float v = bf2f(a); ss += v * v; }
else ybuf[i] = a;
}
}
if constexpr (THR != kR4dSumLanes)
if (POST) { __syncthreads(); ss = lanes_sumsq(ybuf, n); }
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
junction_row<WF32, RES, POST, SCL, THR>(
@@ -382,8 +408,8 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel(
// * A block owns whole rows, the two-rank fused form's partition, since a post-norm's sum of
// squares closes over one row. Every rank runs the same grid over the same M, so block b's
// words are the same words on every rank and the per-block handshake pairs them.
// * The reduce is element by element in the norm's partition (thread t folds columns t, t+THR,
// ...), so the post-norm's sum of squares is the standalone norm's. Each element is ar_vsum's
// * The reduce is element by element, stored back into `x`, and the post-norm's sum of squares
// folds the stored row in the standalone norm's partition (lanes_sumsq). Each element is ar_vsum's
// arithmetic exactly: fp32 from 0.0f, the ranks in ascending order, one rounding to bf16 as the
// __hip_bfloat16 cast rounds (bf16_hi_rne_nan). So the reduced row is the standalone exact
// all-reduce's to the bit, and what follows is rmsnorm_quant_i8's junction over it.
@@ -445,15 +471,15 @@ __global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_wide_kernel(
uint16_t* __restrict__ xr = x + o;
/* The fold a 16-byte word a thread, every source's word in flight at once (the peers' are
* in fine-grained memory, a round trip each), stored back into `x`; then the post-norm's
* sum of squares over the stored row in the norm's partition. Per element it is the fold
* fold_word8 documents, and the sum reads the same rounded values in the same order, so
* the bytes are those of the fold and the sum taken in one pass. */
* sum of squares over the stored row in the standalone norm's partition. Per element it is
* the fold fold_word8 documents, and the sum reads the rounded values the standalone
* all-reduce stores, so the bytes are those of the all-reduce and the norm taken apart. */
for (int k = (int)tid; k < wpr; k += (int)THR)
((int4*)xr)[k] = fold_word8<WS>(src4, (size_t)row * wpr + k);
float ss = 0.0f;
if (POST) {
__syncthreads(); /* the folded row, read across the block's threads */
for (uint32_t i = tid; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; }
ss = lanes_sumsq(xr, n);
}
float s1 = 0.0f;
if (POST) s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
@@ -635,8 +661,8 @@ __global__ __launch_bounds__(1024) void r4dchain_ar_rmsnorm_quant_i8_tail(R4D_AR
// the two-shot's first hop) and takes the handshake;
// 2. on its own row it folds the four partials in rank order -- r4d_ar_to_f, f32, rank 0 first,
// r4d_ar_from_f, the standalone exact all-reduce's fold, so the same bf16 sum -- and runs the
// junction on it in the register form at the standalone norm's width (r4d_act_threads), each
// thread holding the columns the standalone's does, so every sum is the standalone's; it
// junction on it in the register form, each sum folded in the standalone norm's partition
// (lanes_sumsq), so every sum is the standalone's; it
// stores the residual row and pushes the row's int8 codes and scale (and with `gres` the
// residual row) into every peer's slot past the first hop's region, then takes the handshake;
// 3. it copies the peers' local row b of codes and scales (and residual) into place.
@@ -719,7 +745,11 @@ __device__ __forceinline__ void ar_rmsnorm_quant_i8_sp_body(
float ss = 0.0f;
#pragma unroll
for (uint32_t e = 0; e < EPT; ++e)
if (tid + e * THR < n) { const float v = bf2f(xv[e]); ss += v * v; }
if (tid + e * THR < n) {
if constexpr (THR == kR4dSumLanes) { const float v = bf2f(xv[e]); ss += v * v; }
else ybuf[tid + e * THR] = xv[e];
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss = lanes_sumsq(ybuf, n); }
const float s1 = rsqrtf(block_sum<THR / kWave>(ss, l1) / (float)n + eps);
float ss2 = 0.0f;
#pragma unroll
@@ -731,10 +761,11 @@ __device__ __forceinline__ void ar_rmsnorm_quant_i8_sp_body(
if (sc) v = f32_to_bf16(bf2f(v) * sv);
rr[i] = v;
xv[e] = v;
const float f = bf2f(v);
ss2 += f * f;
if constexpr (THR == kR4dSumLanes) { const float f = bf2f(v); ss2 += f * f; }
else ybuf[i] = v;
}
}
if constexpr (THR != kR4dSumLanes) { __syncthreads(); ss2 = lanes_sumsq(ybuf, n); }
const float s2 = rsqrtf(block_sum<THR / kWave>(ss2, l2) / (float)n + eps);
float m = 0.0f;
#pragma unroll
@@ -878,8 +909,8 @@ extern "C" int r4d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream stream) {
const size_t lds = (size_t)n * sizeof(uint16_t);
if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE);
// The same width rmsnorm_bf16 and quant_act_i8 pick, from the same function: it decides which
// columns a thread folds into each sum of squares, hence the byte-identity.
// The same width rmsnorm_bf16 and quant_act_i8 pick, from the same function. The sums fold in
// kR4dSumLanes' partition at any width, so the width changes speed, not bytes.
const int thr = r4d_act_threads((int)M, (int)n);
const float eps = (float)r4d_getf(a, "eps", 1e-6);
const float wadd = (float)r4d_getf(a, "wadd", 0.0);
+137 -2
View File
@@ -23,6 +23,7 @@
*/
#include "r4d_plugin.h"
#include "rad_abi_layout.h"
#include <cstdlib>
#include <cstring>
@@ -849,6 +850,9 @@ static const RadParamSpec pGemmNtQ[] = {
/* The width whose K split a row slice of a wider linear takes (docs/OPS.md); only the narrow
* fp8a8 / i8a8 rows split K by N, and they read it. */
{ "split_n", RAD_P_INT, RAD_OPTIONAL },
/* The weight rows one int8 scale covers, when the weight's form makes it more than one (a
* trellis on libquant's tcq_rb grid); the rb8 tile reads it (docs/OPS.md). */
{ "w_rb", RAD_P_INT, RAD_OPTIONAL },
};
/* docs/OPS.md's `gemm_nt_q` is `a`, `a_scale`, `b`w, `b_scale`w -> `y`. Two of libr4d's six
* quantised GEMMs need a seventh operand. RadLayout can declare aux streams beside a weight, but
@@ -1238,6 +1242,7 @@ static const RadParamSpec pGramAccum[] = {
{ "n", RAD_P_INT, RAD_REQUIRED },
{ "group", RAD_P_INT, RAD_REQUIRED },
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "upper", RAD_P_INT, RAD_OPTIONAL }, /* 1: only k2 >= k1 is accumulated (H is symmetric) */
};
static const RadOperandSpec oGramAccum[] = {
{ "a", RAD_OPD_IN, 0 },
@@ -1920,6 +1925,15 @@ static const RadOperandSpec oSegMean[] = {
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
static const RadParamSpec pSegPool[] = {
P_INT("M"), P_INT("n"), P_STR("dtype"),
};
static const RadOperandSpec oSegPool[] = {
{ "score", RAD_OPD_IN, 0 },
{ "v", RAD_OPD_IN, 0 },
{ "cu_seqlens", RAD_OPD_IN, 0 },
{ "y", RAD_OPD_OUT, 0 },
};
/* docs/OPS.md's `qk_norm_rope`: a fused [q | k | v] row in place, theta and not a table. */
static const RadParamSpec pQkNormRope[] = {
P_INT("M"), P_INT("head_dim"), P_INT("n_head"), P_INT("n_head_kv"), P_F64("theta"),
@@ -2999,6 +3013,10 @@ static const RadOpSchema kSchemas[] = {
SCHEMA("seg_mean", pSegMean, oSegMean,
"Row s of y is the mean of x's rows [cu_seqlens[s], cu_seqlens[s+1]), summed in f64 "
"and rounded once; an empty segment is zeros."),
SCHEMA("seg_softmax_pool", pSegPool, oSegPool,
"Row s of y is v's rows [cu_seqlens[s], cu_seqlens[s+1]) summed with the softmax of "
"their scores (one a row, f32, the maximum subtracted) as weights, in f32 and rounded "
"once; an empty segment is zeros."),
SCHEMA("seg_mean_bf16_sum", pSegMean, oSegMean,
"BF16 masked mean: f32 segment sum rounded to BF16 before division, then BF16 output."),
SCHEMA("qk_norm_rope", pQkNormRope, oQkNormRope,
@@ -4877,6 +4895,25 @@ static const RadConstraint cGemmNtI8A8Tiled[] = {
C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "i8a8 i8a8h"),
};
/* The rb8 and rb32 tiles': a weight scale per whole 8- or 32-row blocks (`w_rb` a multiple). */
static const RadConstraint cGemmNtI8A8Rb8Tiled[] = {
C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "i8a8 i8a8h"), C_GE("w_rb", 8), C_DIV("w_rb", 8),
};
static const RadConstraint cGemmNtI8A8Rb32Tiled[] = {
C_DIV("K", R4D_FP8_BLOCK), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "i8a8 i8a8h"), C_GE("w_rb", 32), C_DIV("w_rb", 32),
};
/* The IQR weights (r4d_gemm_iqr.hip): the int8 twins' bands over a weight kept at its codes' width.
* K a multiple of 256, the narrow tile's K step, which both rows check so they serve one band. */
static const RadConstraint cGemmNtIqrM64[] = {
C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 16), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "i8a8 i8a8h"),
};
static const RadConstraint cGemmNtIqrTiled[] = {
C_DIV("K", 256), C_DIV("N", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK),
C_IN("dtype", "i8a8 i8a8h"),
};
/* libr4d's `K DIV 4`, renamed to docs/OPS.md's `n` as in every quantiser row here. */
static const RadConstraint cQuantActFp8[] = {
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
@@ -5668,12 +5705,25 @@ static const RadKernelInfo kKernels[] = {
{ "embed_lookup_bf16", "embed_lookup", "vocab",
"embedding gather, one workgroup a token",
"any n_embd and n_vocab; a negative or out-of-range id writes a zero row",
"i32 tokens, bf16 table and output",
"i32 tokens, a plain bf16 table and bf16 output",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_embed_lookup, nullptr, nullptr, nullptr,
nullptr, nullptr, r4d_rad_embed_lookup, nullptr, r4d_rad_layout_embed_bf16, nullptr,
r4d_shape_embed_lookup },
{ "embed_lookup_iqr", "embed_lookup", "vocab",
"embedding gather over an IQR table kept at its codes' width: a workgroup a token and 128 "
"columns, each thread a value decoded from its codes, the 128-wide Hadamard of a rotated table "
"undone in LDS",
"n_embd a multiple of 128; a negative or out-of-range id writes a zero row",
"i32 tokens, an IQR table (r4d_iqr.h: uB codes under a table or a zero, or a 4096-state "
"trellis, rotated or not), bf16 output; each value the form's int8 times its row's scale, the "
"rotation undone in f32 and rounded once, as the table widened to bf16 would hold it",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_embed_lookup_iqr, nullptr, r4d_rad_layout_iqr_embed,
r4d_rad_relayout_iqr_embed, r4d_shape_embed_lookup },
{ "embed_lookup_q_bf16", "embed_lookup_q", "vocab",
"quantised embedding gather, four entries a thread",
"any n_embd and n_vocab; a negative or out-of-range id writes a zero row",
@@ -5826,6 +5876,16 @@ static const RadKernelInfo kKernels[] = {
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_seg_mean },
{ "seg_softmax_pool_bf16", "seg_softmax_pool", "elem",
"a segment's rows summed with the softmax of their scores as weights: one row a cu_seqlens "
"segment",
"any n; a thread an output column, one workgroup row a segment, the softmax formed in f32 by "
"every thread",
"bf16 scores, rows and out, f32 weights and sum, one rounding",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cBf16Row), NOTUNE,
nullptr, nullptr, r4d_rad_seg_softmax_pool },
{ "qk_norm_rope_bf16", "qk_norm_rope", "attn",
"per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place",
"head_dim up to 1024, a multiple of 32 for neox (rotary_dim / 2 a multiple of 32) and gptj; "
@@ -6355,6 +6415,19 @@ static const RadKernelInfo kKernels[] = {
r4d_rad_layout_i8_logits, r4d_rad_relayout_i8_logits,
nullptr, r4d_rad_unrelayout_i8_logits },
{ "logits_gemm_iqr", "logits_gemm", "vocab",
"logits_gemm_i8 over an IQR head kept at its codes' width: each lane's sixteen codes read at "
"their width and looked up in the head's table by byte permutes, then the int8 head's matvec "
"or WMMA tile",
"logits_gemm_fp8's: any M, n_embd a multiple of 128",
"bf16 x, an IQR head (r4d_iqr.h's lm form: 2- to 6-bit codes indexing an int8 table, a bf16 "
"scale per ROW per 128 columns in the row's tail), F32 LOGITS OUT, fp32 accumulate",
RAD_DOMAIN_DEVICE, R4D_PRIO_LOGITS_FP8,
ROW(cLogitsGemmFp8), NOTUNE,
nullptr, nullptr, r4d_rad_logits_gemm_iqr, nullptr,
r4d_rad_layout_iqr_logits, r4d_rad_relayout_iqr_logits,
nullptr, r4d_rad_unrelayout_iqr_logits },
/* ---------------------------- the decomposed sampler chain (r4d_sample_stages_f32.hip) ------
*
* Distinct from sample_chain, which fuses temperature, softmax, top_k, top_p, min_p and the draw
@@ -8113,6 +8186,56 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
r4d_rad_layout_i8_block, r4d_rad_relayout_i8_block,
nullptr, r4d_rad_unrelayout_i8_block },
{ "gemm_i8a8_rb8_tiled", "gemm_nt_q", "gemm",
"gemm_i8a8_tiled at a weight scale constant over 8 rows: one scale a lane a tile, the int32 "
"accumulator started at 0x4B400000 so a slot reads as f32 with no conversion, the fp8 fold",
"the i8 row's, at w_rb a multiple of 8",
"i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per 8 ROWS per 128 K (each row "
"of the plane holding its block's), bf16 C; dtype i8a8h as the i8 row",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED + 1,
ROW(cGemmNtI8A8Rb8Tiled), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_i8a8_rb8_tiled, nullptr,
r4d_rad_layout_i8_block, r4d_rad_relayout_i8_block,
nullptr, r4d_rad_unrelayout_i8_block },
{ "gemm_i8a8_rb32_tiled", "gemm_nt_q", "gemm",
"gemm_i8a8_rb8_tiled at a weight scale per 32 rows: one scale a wave, the fp8 tile's fold and "
"registers",
"the i8 row's, at w_rb a multiple of 32",
"i8 A with an f32 scale per (row, 128 K), i8 W with a bf16 scale per 32 ROWS per 128 K (each "
"row of the plane holding its block's), bf16 C; dtype i8a8h as the i8 row",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED + 2,
ROW(cGemmNtI8A8Rb32Tiled), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_i8a8_rb32_tiled, nullptr,
r4d_rad_layout_i8_block, r4d_rad_relayout_i8_block,
nullptr, r4d_rad_unrelayout_i8_block },
{ "gemm_iqr_nt_m64", "gemm_nt_q", "gemm",
"gemm_i8a8_nt_m16 over an IQR weight (r4d_iqr.h) kept at its codes' width: each wave fetches its "
"16 rows' codes a K tile ahead and decodes each 64-K supertile into its int8 fragments just "
"before the supertile's WMMA steps (tables and trellis states from LDS)",
"M <= 64; K a multiple of 256; N a multiple of 16, and of a trellis's run",
"i8 A with an f32 scale per (row, 128 K), W an IQR form's codes, decoding to int8 values with a "
"scale per row per 128 K (bf16, or E4M3 under an f32; on a tcq_rb trellis its block's), bf16 C; "
"the int8 narrow tile's split, accumulation and fold, so its output bytes",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_M16,
ROW(cGemmNtIqrM64), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_iqr_m64, r4d_rad_gemm_iqr_m64_scratch,
r4d_rad_layout_iqr, r4d_rad_relayout_iqr,
nullptr, r4d_rad_unrelayout_iqr },
{ "gemm_iqr_tiled", "gemm_nt_q", "gemm",
"the prefill GEMM over an IQR weight: the call decodes the weight's codes into the int8 fragment "
"plane in its scratch, once, and runs gemm_i8a8_tiled (or its rb8 / rb32 fold on a tcq_rb "
"trellis) over it",
"any M; K a multiple of 256 and N of 128",
"as gemm_iqr_nt_m64, through the int8 prefill tile's arithmetic and output bytes",
RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_TILED,
ROW(cGemmNtIqrTiled), NOTUNE,
nullptr, nullptr, r4d_rad_gemm_iqr_tiled, r4d_rad_gemm_iqr_tiled_scratch,
r4d_rad_layout_iqr, r4d_rad_relayout_iqr,
nullptr, r4d_rad_unrelayout_iqr },
/* Band read off the entry point's own rejection tests, not a kernel-side row. */
{ "gemm_w8a8_nt_m64", "gemm_nt_q", "gemm",
"skinny GEMM with an 8-bit weight and an 8-bit activation: the promoted linears of the INT4 "
@@ -8545,6 +8668,17 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
/* No opd_shape, for logit_rerank's reason: the declared shape and the stored row differ. */
nullptr, r4d_rad_unrelayout_i8_logits },
{ "logit_rerank_iqr", "logit_rerank", "select",
"logit_rerank over an IQR head: the same candidates rescored against logits_gemm_iqr's rows",
"logit_rerank's: any M, R <= 32, bf16 x and the IQR lm_head rows logits_gemm_iqr stores",
"bf16 in, f32 values + i32 ids out, ties to the lower id",
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
ROW(cLogitRerank), NOTUNE,
nullptr, nullptr, r4d_rad_logit_rerank_iqr, nullptr,
r4d_rad_layout_iqr_logits, r4d_rad_relayout_iqr_logits,
/* No opd_shape, for logit_rerank's reason: the declared shape and the stored row differ. */
nullptr, r4d_rad_unrelayout_iqr_logits },
{ "rowtopk_merge", "row_topk_merge", "select",
"the global top-R of world_size all-gathered per-rank candidate sets",
"any M, R <= 32; `gathered` is [M, world_size * R, 2] f32 pairs, an int32 id in the first slot; "
@@ -10169,6 +10303,7 @@ extern "C" int r4d_record_dispatches(const void** fns, int cap) {
}
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
RAD_PLUGIN_ABI_LAYOUT_EXPORT
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
extern "C" int rad_kernel_schema_count(void) {
+39 -11
View File
@@ -49,6 +49,7 @@
#include "r4d_fp8_wmma.h"
#include "r4d_fp8_lm.h"
#include "r4d_chain.h"
#include "r4d_iqr.h"
#include <hip/hip_bf16.h>
#include <cstdint>
@@ -376,7 +377,9 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE) void r4dchain_rowtopk_merge(
// rescores against whichever head the trunk's logits GEMM reads, so an int8 head needs this form.
#define R4D_RERANK_WPB 8 // waves a block: 256 threads, and R <= 32 so a wave takes <= 4
template <bool I8>
/* TB > 0: an IQR head (r4d_iqr.h's lm form), TB-bit codes then the row's scales, the table of 2^TB
* int8 entries after the last row. */
template <bool I8, uint32_t TB = 0>
__global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rerank_kernel(
const unsigned short* __restrict__ X, const int* __restrict__ IN,
const unsigned char* __restrict__ W, int* __restrict__ OI, float* __restrict__ OV,
@@ -400,9 +403,18 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera
* column's block scale locally, so the fold is a plain sum whose order depends only on the
* lane count. */
const unsigned char* const wr = W + (size_t)loc * w_ld;
const unsigned short* const sr = (const unsigned short*)(wr + K);
const unsigned short* const sr = (const unsigned short*)(wr + (TB ? K / 8 * TB : K));
[[maybe_unused]] const int8_t* const tab =
(const int8_t*)(W + ((size_t)nv * w_ld + 255) / 256 * 256);
for (long k = lane; k < K; k += R4D_TOPK_WAVE) {
const float c = I8 ? (float)(int8_t)wr[k] : r4d_fp8::e4m3((uint32_t)wr[k]);
float c;
if constexpr (TB != 0) {
const long bit = k * (long)TB;
const uint32_t wv = (uint32_t)wr[bit >> 3] | (uint32_t)wr[(bit >> 3) + 1] << 8;
c = (float)tab[(wv >> (bit & 7)) & ((1u << TB) - 1u)];
} else {
c = I8 ? (float)(int8_t)wr[k] : r4d_fp8::e4m3((uint32_t)wr[k]);
}
acc = fmaf(c * r4d_fp8::bscale(sr[k / 128]), bf16_to_f32(xr[k]), acc);
}
acc = r4d_wave_sum(acc);
@@ -436,17 +448,22 @@ __global__ __launch_bounds__(R4D_TOPK_WAVE * R4D_RERANK_WPB) void r4d_logit_rera
static int logit_rerank_emit(long x, long idx_in, long head, long outi, long outv, long outp,
int M, int R, long K, long voff, long nv, RadStream stream,
bool i8) {
const long w_ld = r4d_fp8::lm_row_bytes(K);
bool i8, uint32_t tb = 0) {
r4d_iqr::Form tf;
tf.bits = tb;
const long w_ld = tb ? (long)r4d_iqr::lm_row(tf, K) : r4d_fp8::lm_row_bytes(K);
// R <= PT2 makes the re-sort exact for any scores (one lane holds the whole answer), so it is
// checked, not clamped.
if (M < 1 || R < 1 || K < 1 || nv < 1 || R > R4D_TOPK_PT2) return R4D_NO(RAD_E_SHAPE);
#define R4D_RERANK_EMIT(I8) \
R4D_EMIT(stream, r4d_logit_rerank_kernel<I8>, dim3(M), dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), \
#define R4D_RERANK_EMIT(I8, TB) \
R4D_EMIT(stream, (r4d_logit_rerank_kernel<I8, TB>), dim3(M), dim3(R4D_TOPK_WAVE * R4D_RERANK_WPB), \
0, (const unsigned short*)x, (const int*)idx_in, (const unsigned char*)head, \
(int*)outi, \
(float*)outv, (float*)outp, R, K, voff, nv, w_ld)
const int rc = i8 ? R4D_RERANK_EMIT(true) : R4D_RERANK_EMIT(false);
const int rc = tb == 2u ? R4D_RERANK_EMIT(true, 2) : tb == 3u ? R4D_RERANK_EMIT(true, 3)
: tb == 4u ? R4D_RERANK_EMIT(true, 4) : tb == 5u ? R4D_RERANK_EMIT(true, 5)
: tb == 6u ? R4D_RERANK_EMIT(true, 6)
: i8 ? R4D_RERANK_EMIT(true, 0) : R4D_RERANK_EMIT(false, 0);
#undef R4D_RERANK_EMIT
return rc;
}
@@ -572,7 +589,7 @@ extern "C" int r4d_rad_rowtopk_merge(const RadArgs* a, RadStream s) {
/* `M` and the candidate count come from the operands, as in rowtopk_merge: `M` is a band ceiling.
* `n_vocab` is this rank's rows of the head, so the ownership guard is a shard test. */
static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8) {
static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8, bool iqr = false) {
const RadTensor* x = r4d_opt(a, 0);
const RadTensor* w = r4d_opt(a, 1);
const RadTensor* in = r4d_opt(a, 2);
@@ -586,7 +603,14 @@ static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8) {
* hook's rule; the engine's layout-tag check guarantees agreement by refusing a container laid
* out for another row. So the head is accepted at either spelling and read as r4d.fp8lm.b128,
* or r4d.i8lm.r128 for the int8 form. */
if (w->dtype != (i8 ? RAD_I8 : RAD_F8E4M3) && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE);
uint32_t tb = 0;
if (iqr) {
if (!r4d_iqr::is_weight_dtype(w->dtype) || !r4d_iqr::lm_built(w->dtype & r4d_iqr::kWordMask))
return R4D_NO(RAD_E_DTYPE);
tb = r4d_iqr::form(w->dtype & r4d_iqr::kWordMask).bits;
} else if (w->dtype != (i8 ? RAD_I8 : RAD_F8E4M3) && w->dtype != RAD_BF16) {
return R4D_NO(RAD_E_DTYPE);
}
if (in->dtype != RAD_I32 || idx->dtype != RAD_I32 || val->dtype != RAD_F32)
return R4D_NO(RAD_E_DTYPE);
if (pr && pr->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
@@ -608,7 +632,7 @@ static int rad_logit_rerank(const RadArgs* a, RadStream stream, bool i8) {
return logit_rerank_emit(r4d_addr(x), r4d_addr(in), r4d_addr(w), r4d_addr(idx), r4d_addr(val),
pr ? r4d_addr(pr) : 0, (int)M, (int)R, (long)K, (long)voff, (long)NV,
stream, i8);
stream, i8, tb);
}
extern "C" int r4d_rad_logit_rerank(const RadArgs* a, RadStream stream) {
return rad_logit_rerank(a, stream, false);
@@ -616,4 +640,8 @@ extern "C" int r4d_rad_logit_rerank(const RadArgs* a, RadStream stream) {
extern "C" int r4d_rad_logit_rerank_i8(const RadArgs* a, RadStream stream) {
return rad_logit_rerank(a, stream, true);
}
/* An IQR head's rows (r4d_iqr.h's lm form), as logits_gemm_iqr reads them. */
extern "C" int r4d_rad_logit_rerank_iqr(const RadArgs* a, RadStream stream) {
return rad_logit_rerank(a, stream, true, true);
}
+792 -6
View File
@@ -134,6 +134,7 @@ struct Plugin {
/* Test hooks, not part of the plugin ABI: libr4d's own, resolved from the same .so. r4d.h
* explains why the wave count cannot be compared any other way. */
void (*pin_mw)(int) = nullptr;
void (*pin_split_waves)(int) = nullptr;
void (*pin_nt)(int) = nullptr;
void (*pin_qsa)(int) = nullptr;
void (*pin_moe)(int) = nullptr;
@@ -205,6 +206,7 @@ static bool load(Plugin* pl, const char* path) {
okall &= sym(pl->h, "rad_kernel_count", &pl->kernel_count);
okall &= sym(pl->h, "rad_kernel_at", &pl->kernel_at);
okall &= sym(pl->h, "r4d_gemm_fp8a8_pin_mw", &pl->pin_mw);
okall &= sym(pl->h, "r4d_gemm_i8a8_pin_split_waves", &pl->pin_split_waves);
okall &= sym(pl->h, "r4d_gemm_fp8a8_pin_nt", &pl->pin_nt);
okall &= sym(pl->h, "r4d_qsa_score_pin_form", &pl->pin_qsa);
okall &= sym(pl->h, "r4d_moe_gemm_pin_prefill", &pl->pin_moe);
@@ -1092,7 +1094,7 @@ static void decode_split_law_case(const Plugin& pl) {
{ 1, 8, 1024, 32, 32 }, { 4, 8, 640, 16, 16 }, { 8, 4, 100000, 16, 16 },
{ 16, 4, 100000, 8, 8 }, { 4, 1, 100000, 32, 32 }, { 1, 1, 100000, 128, 128 },
/* Past eight sequences the floor shrinks to kVerifyFloorWorkgroups over the batch, so the region
* stays at what eight sequences need (issue #342: 64 a sequence at max_seqs 256 made it 64x). */
* stays at what eight sequences need. */
{ 16, 8, 100000, 32, 32 }, { 16, 8, 32768, 32, 32 }, { 256, 8, 100000, 2, 2 },
};
int bad = 0;
@@ -6262,11 +6264,15 @@ static void bias_gemm_numeric(const Plugin& pl, int64_t M, int64_t N, int64_t K,
* `codes=i8 group=128 scale=bf16 clamp=sym`), stored through the row's hooks. The reference uses
* the codes the quantiser wrote, read back, so only the GEMM is under test; the quantiser is
* checked separately, code for code. Ragged M reaches the guarded fold. */
static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K) {
/* `rb` > 1: the weight's scale one per rb rows (a tcq_rb trellis as libr4d widens it: every row
* of a block holds the block's largest), launched with `w_rb`. */
static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N, int64_t K,
int64_t rb = 1) {
if (!sel(row) && !sel("quant_act_i8g")) return;
char nm[160];
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld", row, (long long)M,
(long long)N, (long long)K);
std::snprintf(nm, sizeof nm, "%s numeric M=%lld N=%lld K=%lld%s", row, (long long)M,
(long long)N, (long long)K,
rb > 1 ? (", a scale per " + std::to_string(rb) + " rows").c_str() : "");
const RadKernelInfo* r = find(pl, row);
const RadKernelInfo* qz = find(pl, "quant_act_i8g");
if (!r || !qz || !r->layout || !r->relayout) { ok(nm, false, "rows or hooks absent"); return; }
@@ -6283,7 +6289,9 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N
for (int64_t n = 0; n < N; ++n)
for (int64_t g = 0; g < nkb; ++g) {
float amax = 0.0f;
for (int64_t j = 0; j < 128; ++j) amax = std::max(amax, std::fabs(wf[(size_t)(n * K + g * 128 + j)]));
for (int64_t q = n / rb * rb; q < n / rb * rb + rb; ++q)
for (int64_t j = 0; j < 128; ++j)
amax = std::max(amax, std::fabs(wf[(size_t)(q * K + g * 128 + j)]));
rad_store_f32(p.data[1].data(), RAD_BF16, n * nkb + g, amax > 0 ? amax / 127.0f : 1.0f);
const float sc = rad_load_f32(p.data[1].data(), RAD_BF16, n * nkb + g);
for (int64_t j = 0; j < 128; ++j) {
@@ -6370,7 +6378,10 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N
T(nullptr, RAD_U8, { 1 }),
};
absent(ts[5]); absent(ts[6]);
rc = launch(r, ts, { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8") });
std::vector<RadParam> gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128),
PS("dtype", "i8a8") };
if (rb > 1) gp.push_back(PI("w_rb", rb));
rc = launch(r, ts, gp);
if (rc != RAD_OK) { ok(nm, false, "rc=" + std::to_string(rc)); return; }
std::vector<uint16_t> hy((size_t)(M * N));
st_memcpy(hy.data(), d_y, hy.size() * 2, hipMemcpyDeviceToHost);
@@ -6393,6 +6404,303 @@ static void i8a8_numeric(const Plugin& pl, const char* row, int64_t M, int64_t N
ok(nm, rel < 5e-3, d);
}
/* gemm_iqr_nt_m64 and gemm_iqr_tiled against the int8 rows over the same weight decoded on the
* host. An IQR form's int8 values and fold scales, stored as `codes=i8` through gemm_i8a8's hooks,
* must give the same output bytes: the IQR rows run the int8 rows' arithmetic over the values they
* decode, so any decode, order or fold difference shows as a differing byte. The IQR planes also go
* back through the hooks' inverse. The forms are r4d_iqr.h's: kind 2 a u6 code under a u6 zero, 3 a
* uB table, 4 a uB code a V-vector, 5 a trellis of 2^L states over runs of 256 rows (`rb` rows a
* scale on libquant's tcq_rb grid), `two` E4M3 scales under one f32, `rot` the fwht128 forms. */
struct IqrCase { int kind, B, V, L, rb; bool two, rot; bool rowf = false; };
static void iqr_gemm_case(const Plugin& pl, const IqrCase& f, int64_t M, int64_t N, int64_t K) {
const char* row = M <= 64 ? "gemm_iqr_nt_m64" : "gemm_iqr_tiled";
const char* ref = M <= 64 ? "gemm_i8a8_nt_m16"
: f.rb >= 32 ? "gemm_i8a8_rb32_tiled"
: f.rb >= 8 ? "gemm_i8a8_rb8_tiled" : "gemm_i8a8_tiled";
if (!sel(row) && !sel("gemm_iqr")) return;
static const char* kKind[] = { "", "signed", "zero", "table", "grid", "trellis", "trellis-mad" };
const bool tr = f.kind == 5 || f.kind == 6; /* 6: the computed trellis (tcq_code=mad) */
char nm[200];
std::snprintf(nm, sizeof nm, "%s %s B=%d%s%s%s M=%lld N=%lld K=%lld", row,
kKind[f.kind], f.B,
f.kind == 4 ? (" V=" + std::to_string(f.V)).c_str()
: tr ? (" L=" + std::to_string(f.L)).c_str() : "",
f.rb > 1 ? (" rb=" + std::to_string(f.rb)).c_str() : "",
f.rowf ? " row-f32" : f.two ? " e4m3" : "",
(long long)M, (long long)N, (long long)K);
const RadKernelInfo* r = find(pl, row);
const RadKernelInfo* ri = find(pl, ref);
if (!r || !ri || !r->layout || !r->relayout || !ri->layout || !ri->relayout) {
ok(nm, false, "rows or hooks absent");
return;
}
const int64_t nkb = K / 128;
uint64_t z = 0x9E3779B97F4A7C15ull * (uint64_t)(f.kind * 131 + f.B * 17 + f.L + f.rb + M);
auto rnd = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return x ^ (x >> 31);
};
static const uint32_t kU[] = { 0, RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6, RAD_U7,
RAD_U8, RAD_U9, RAD_U10, RAD_U11, RAD_U12 };
Planes p;
if (tr) {
rad_enc_clear(&p.enc);
rad_enc_copy_str(p.enc.scheme, "trellis");
rad_enc_add_plane(&p.enc, "codes", kU[f.B], 1, 1);
if (f.rowf) rad_enc_add_plane(&p.enc, "scale", RAD_F32, 1, 0);
else rad_enc_add_plane(&p.enc, "scale", f.two ? RAD_F8E4M3 : RAD_BF16, 1, 128);
if (f.two && !f.rowf) rad_enc_add_plane(&p.enc, "scale.1", RAD_F32, 0, 0);
const int t = rad_enc_add_table(&p.enc, "trellis", RAD_I8, (int64_t)1 << f.L, 1);
p.enc.plane[t].block[0] = 256;
p.enc.plane[t].block[1] = f.rb > 1 ? f.rb : 0;
if (f.kind == 6) rad_enc_add_table(&p.enc, "trellis.mad", RAD_U32, 2, 1);
if (f.rowf) rad_enc_add_plane(&p.enc, "scale.col", RAD_F32, 0, 128);
} else {
p.enc = rad_enc_affine(kU[f.B], RAD_BF16, 1, 128);
if (f.kind == 4) {
p.enc.plane[0].block[1] = f.V;
rad_enc_add_table(&p.enc, "grid", RAD_I8, (int64_t)1 << f.B, f.V);
} else if (f.kind == 3) {
rad_enc_add_table(&p.enc, "table", RAD_I8, 1, (int64_t)1 << f.B);
} else if (f.kind == 2) {
rad_enc_add_plane(&p.enc, "zero", RAD_U6, 1, 128);
}
}
if (f.rot) rad_enc_copy_str(p.enc.transform, "fwht128");
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale"), is2 = p.find("scale.1");
const int ia = tr ? p.find("trellis") : f.kind == 4 ? p.find("grid")
: f.kind == 3 ? p.find("table") : f.kind == 2 ? p.find("zero") : -1;
const int64_t cols = f.kind == 4 ? K / f.V : K;
for (int64_t n = 0; n < N; ++n)
for (int64_t c = 0; c < cols; ++c)
rad_store_bits(p.data[(size_t)ic].data() + n * p.row_bytes(ic), f.B, c,
(uint32_t)(rnd() & ((1ull << f.B) - 1)));
if (f.kind == 2)
for (int64_t n = 0; n < N; ++n)
for (int64_t g = 0; g < nkb; ++g)
rad_store_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), 6, g,
(uint32_t)(24 + rnd() % 17));
else if (ia >= 0)
for (auto& v : p.data[(size_t)ia]) v = (uint8_t)(int8_t)((int)(rnd() % 255) - 127);
if (f.kind == 6) {
/* the table the code computes, from a random odd 24-bit A and a random B */
const uint32_t A = (uint32_t)(rnd() & 0xFFFFFFu) | 1u, Bc = (uint32_t)rnd();
uint32_t* ab = (uint32_t*)p.data[(size_t)p.find("trellis.mad")].data();
ab[0] = A;
ab[1] = Bc;
for (uint32_t st = 0; st < (1u << f.L); ++st) {
const uint32_t h = ((st & 0xFFFFFFu) * A + Bc) & 0x3F3F3F3Fu;
p.data[(size_t)ia][st] = (uint8_t)(int8_t)((int)((h & 0xFFu) + ((h >> 8) & 0xFFu) +
((h >> 16) & 0xFFu) + (h >> 24)) - 126);
}
}
/* kRowF32: a row's scale of 7 significant bits times a block's power of two, whose product a
* bf16 holds exactly, so the int8 row reads the same scales */
std::vector<float> rsv((size_t)N), cfv((size_t)nkb);
if (f.rowf) {
for (int64_t n = 0; n < N; ++n)
rsv[(size_t)n] = std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -9 - (int)(rnd() % 4));
for (int64_t g = 0; g < nkb; ++g) cfv[(size_t)g] = std::ldexp(1.0f, (int)(rnd() % 4) - 1);
for (int64_t n = 0; n < N; ++n) ((float*)p.data[(size_t)is].data())[n] = rsv[(size_t)n];
float* cfp = (float*)p.data[(size_t)p.find("scale.col")].data();
for (int64_t g = 0; g < nkb; ++g) cfp[g] = cfv[(size_t)g];
}
for (int64_t n = 0; n < N && !f.rowf; ++n)
for (int64_t g = 0; g < nkb; ++g) {
if (f.two) p.data[(size_t)is][(size_t)(n * nkb + g)] = (uint8_t)(0x30 + rnd() % 0x28);
else rad_store_f32(p.data[(size_t)is].data(), RAD_BF16, n * nkb + g,
std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -9 - (int)(rnd() % 4)));
}
if (f.two) rad_store_f32(p.data[(size_t)is2].data(), RAD_F32, 0, 0.0123f);
/* The host decode: each row's own bf16 scale, on tcq_rb its block's largest, and the values. */
auto own = [&](int64_t n, int64_t g) -> uint16_t {
if (f.rowf) {
const float x = rsv[(size_t)n] * cfv[(size_t)g];
uint32_t u;
std::memcpy(&u, &x, 4);
return (uint16_t)(u >> 16);
}
if (!f.two) return ((const uint16_t*)p.data[(size_t)is].data())[n * nkb + g];
const float x = rad_load_f32(p.data[(size_t)is2].data(), RAD_F32, 0) *
rad_fp8e4m3_to_f32(p.data[(size_t)is][(size_t)(n * nkb + g)]);
uint32_t u;
std::memcpy(&u, &x, 4);
u += 0x7FFFu + ((u >> 16) & 1u);
return (uint16_t)(u >> 16);
};
auto blk = [&](int64_t n, int64_t g) -> uint16_t {
if (f.rb <= 1) return own(n, g);
uint16_t m = 0;
for (int64_t q = n / f.rb * f.rb; q < n / f.rb * f.rb + f.rb; ++q) m = std::max(m, own(q, g));
return m;
};
Planes pi;
pi.enc = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
if (f.rot) rad_enc_copy_str(pi.enc.transform, "fwht128");
pi.size(N, K);
auto code = [&](int64_t n, int64_t c) {
return rad_load_bits(p.data[(size_t)ic].data() + n * p.row_bytes(ic), f.B, c);
};
const int8_t* aux = ia >= 0 && f.kind != 2 ? (const int8_t*)p.data[(size_t)ia].data() : nullptr;
const int C = tr ? (f.L + f.B - 1) / f.B : 1;
for (int64_t n = 0; n < N; ++n)
for (int64_t k = 0; k < K; ++k) {
int v = 0;
if (f.kind == 3) v = aux[code(n, k)];
else if (f.kind == 4) v = aux[code(n, k / f.V) * f.V + k % f.V];
else if (f.kind == 2)
v = (int)code(n, k) - (int)rad_load_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), 6, k / 128);
else {
uint32_t st = 0;
for (int q = C - 1; q >= 0; --q) {
const int64_t rr = n / 256 * 256 + (n % 256 - q + 256) % 256;
st = ((st << f.B) | code(rr, k)) & ((1u << f.L) - 1u);
}
v = aux[st];
if (f.rb > 1) {
const uint32_t bo = (uint32_t)own(n, k / 128) << 16, bb = (uint32_t)blk(n, k / 128) << 16;
float so, sb;
std::memcpy(&so, &bo, 4);
std::memcpy(&sb, &bb, 4);
/* a computed code rounds the exact product (libquant's rb_round) */
v = sb > 0.0f ? (f.kind == 6 ? (int)(std::fma((float)v, so / sb, 12582912.0f) - 12582912.0f)
: (int)rintf((float)v * (so / sb)))
: 0;
}
}
pi.data[0][(size_t)(n * K + k)] = (uint8_t)(int8_t)v;
}
for (int64_t n = 0; n < N; ++n)
for (int64_t g = 0; g < nkb; ++g)
((uint16_t*)pi.data[1].data())[n * nkb + g] = blk(n, g);
const char* dt = f.rot ? "i8a8h" : "i8a8";
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", dt) };
std::vector<uint8_t> wq, wsc, iq, isc;
RadLayout lw, ls;
const bool aux_view = f.kind != 1;
const char* aux_role = tr ? "trellis" : f.kind == 4 ? "grid" : f.kind == 3 ? "table" : "zero";
int rw = f.kind == 6 ? stored(r, lp, 2, p, { "codes", aux_role, "trellis.mad" }, &wq, &lw)
: aux_view ? stored(r, lp, 2, p, { "codes", aux_role }, &wq, &lw)
: stored(r, lp, 2, p, { "codes" }, &wq, &lw);
int rs = f.rowf ? stored(r, lp, 3, p, { "scale", "scale.col" }, &wsc, &ls)
: f.two ? stored(r, lp, 3, p, { "scale", "scale.1" }, &wsc, &ls)
: stored(r, lp, 3, p, { "scale" }, &wsc, &ls);
if (rw != RAD_OK || rs != RAD_OK) {
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rs));
return;
}
{
std::string why;
const bool back = (f.kind == 6 ? restores(r, lp, 2, p, { "codes", aux_role, "trellis.mad" }, wq, &why)
: aux_view ? restores(r, lp, 2, p, { "codes", aux_role }, wq, &why)
: restores(r, lp, 2, p, { "codes" }, wq, &why)) &&
(f.rowf ? restores(r, lp, 3, p, { "scale", "scale.col" }, wsc, &why)
: f.two ? restores(r, lp, 3, p, { "scale", "scale.1" }, wsc, &why)
: restores(r, lp, 3, p, { "scale" }, wsc, &why));
ok((std::string(nm) + ": the stored planes invert").c_str(), back, why);
const int64_t want = (f.kind == 4 ? N * K / f.V : N * K) * f.B / 8;
ok((std::string(nm) + ": VRAM holds the codes' bits").c_str(),
lw.bytes >= want && lw.bytes <= want + 1024 + (f.kind == 2 ? N * nkb : 0) + ((int64_t)1 << f.L) + 32768,
"weight " + std::to_string(lw.bytes) + " B for " + std::to_string(want) + " B of codes");
}
if (stored(ri, lp, 2, pi, { "codes" }, &iq) != RAD_OK || stored(ri, lp, 3, pi, { "scale" }, &isc) != RAD_OK) {
ok(nm, false, "int8 reference relayout failed");
return;
}
std::vector<int8_t> ha((size_t)(M * K));
std::vector<float> has((size_t)(M * nkb));
for (auto& v : ha) v = (int8_t)((int)(rnd() % 255) - 127);
for (auto& v : has) v = std::ldexp(1.0f + (float)(rnd() % 256) / 256.0f, -7);
void* d_a = dalloc(ha.size());
void* d_as = dalloc(has.size() * 4);
void* d_w = dalloc(wq.size());
void* d_s = dalloc(wsc.size());
void* d_iw = dalloc(iq.size());
void* d_is = dalloc(isc.size());
void* d_y = dalloc((size_t)(M * N) * 2);
void* d_yr = dalloc((size_t)(M * N) * 2);
if (!d_a || !d_as || !d_w || !d_s || !d_iw || !d_is || !d_y || !d_yr) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
st_memcpy(d_as, has.data(), has.size() * 4, hipMemcpyHostToDevice);
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_s, wsc.data(), wsc.size(), hipMemcpyHostToDevice);
st_memcpy(d_iw, iq.data(), iq.size(), hipMemcpyHostToDevice);
st_memcpy(d_is, isc.data(), isc.size(), hipMemcpyHostToDevice);
auto launch = [&](const RadKernelInfo* k, 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;
if (k->scratch) {
const int64_t need = k->scratch(&a);
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
}
const int rc = k->launch(&a, (RadStream) nullptr);
return rc == RAD_OK && st_stream_sync(nullptr) == hipSuccess ? RAD_OK : (rc ? rc : -1);
};
std::vector<RadParam> gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", dt) };
if (f.rb > 1) gp.push_back(PI("w_rb", f.rb));
std::vector<RadTensor> tq = {
T(d_a, RAD_I8, { M, K }), T(d_as, RAD_F32, { M, nkb }), T(d_w, lw.dtype, { N, K }),
T(d_s, ls.dtype, { N, nkb }), T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }),
T(nullptr, RAD_U8, { 1 }),
};
absent(tq[5]); absent(tq[6]);
std::vector<RadTensor> ti = tq;
ti[2] = T(d_iw, RAD_I8, { N, K });
ti[3] = T(d_is, RAD_BF16, { N, nkb });
ti[4] = T(d_yr, RAD_BF16, { M, N });
/* The narrow IQR row splits K for 512 waves, the int8 tile for 128; the reference is pinned to
* the IQR row's target so the two sum their partials in one order. */
const int rq = launch(r, tq, gp);
if (M <= 64 && pl.pin_split_waves) pl.pin_split_waves(512);
const int rr = launch(ri, ti, gp);
if (M <= 64 && pl.pin_split_waves) pl.pin_split_waves(0);
if (rq != RAD_OK || rr != RAD_OK) {
ok(nm, false, "rc " + std::to_string(rq) + " (int8 " + std::to_string(rr) + ")");
return;
}
std::vector<uint16_t> y((size_t)(M * N)), yr((size_t)(M * N));
st_memcpy(y.data(), d_y, y.size() * 2, hipMemcpyDeviceToHost);
st_memcpy(yr.data(), d_yr, yr.size() * 2, hipMemcpyDeviceToHost);
/* M <= 8 is the GEMV, which folds per lane before summing across lanes: the product within
* f32 rounding, so bf16 outputs a rounding apart. Above, the int8 tiles' bytes. */
/* kRowF32 scales its sums in the epilogue, not a block at a time: to a rounding too. */
const bool exact = M > 8 && !f.rowf;
/* An output's rounding is bounded by its sum's magnitude, not its own: a row that cancels to
* near zero keeps the error of its terms. The bound is a bf16 step of the output plus 2^-8 of
* the outputs' rms. */
double r2 = 0.0;
for (size_t i = 0; i < y.size(); ++i) r2 += (double)h_bf16(yr[i]) * h_bf16(yr[i]);
const float rms = (float)std::sqrt(r2 / (double)y.size());
int64_t bad = 0, first = -1;
double e2 = 0.0;
for (size_t i = 0; i < y.size(); ++i) {
const float a = h_bf16(y[i]), b = h_bf16(yr[i]);
e2 += (double)(a - b) * (a - b);
const bool off = exact ? y[i] != yr[i]
: !(std::fabs(a - b) <= std::ldexp(std::fabs(b), -7) + std::ldexp(rms, -8));
if (off) { if (first < 0) first = (int64_t)i; ++bad; }
}
const double rel = std::sqrt(e2 / (r2 > 0 ? r2 : 1.0));
ok(nm, bad == 0, bad ? std::to_string(bad) + " of " + std::to_string(y.size()) +
" outputs differ from the int8 row's, first [" +
std::to_string(first / N) + "][" + std::to_string(first % N) + "] " +
std::to_string(h_bf16(y[(size_t)first])) + " vs " +
std::to_string(h_bf16(yr[(size_t)first])) + ", rms " + std::to_string(rms)
: exact ? "the int8 row's bytes" : "the int8 row's to a rounding, rel_l2 " + std::to_string(rel));
dfree_all();
}
/* The rotated int8 trunk against the f32 product it approximates. i8a8_numeric's reference uses
* the quantiser's own codes, so it would pass with the weight and activation rotated by different
* transforms; this one measures meaning. The weight is quantised on the host as libquant writes
@@ -6673,6 +6981,61 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t
ok(nm, all, d);
}
/* The same rows on both sides of the band edge: the first 64 rows of A as a 64-row op (the skinny
* row) and inside a 128-row op (the tiled row). A prefill chunk of 64 tokens and one of more give
* a token the same bits only if these agree, which bf16_tiled_identity (both rows at one M) does
* not show. N and K are the shapes a dense model issues. */
static void bf16_band_edge(const Plugin& pl, int64_t N, int64_t K) {
if (!sel("gemm_bf16_nt_tiled")) return;
char nm[128];
std::snprintf(nm, sizeof nm, "gemm_bf16 rows 0..63 at M=64 == at M=128 N=%lld K=%lld",
(long long)N, (long long)K);
const RadKernelInfo* rt = find(pl, "gemm_bf16_nt_tiled");
const RadKernelInfo* rs = find(pl, "gemm_bf16_nt_m64");
if (!rt || !rs) { ok(nm, false, "row absent"); return; }
const int64_t M = 128, H = 64;
std::vector<uint16_t> ha((size_t)(M * K)), hw((size_t)(N * K));
for (size_t i = 0; i < ha.size(); ++i)
ha[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 401) - 200) * 0.5f);
for (size_t i = 0; i < hw.size(); ++i)
hw[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i ^ 0x9e3779b9u) % 199) - 99) * 0.01f);
std::vector<RadTensor> ts = {
T(nullptr, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, { N, K }),
T(nullptr, RAD_BF16, { M, N }),
};
for (auto& t : ts) t.data = alloc_for(t);
if (!ts[0].data || !ts[1].data || !ts[2].data) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(ts[0].data, ha.data(), ha.size() * 2, hipMemcpyHostToDevice);
st_memcpy(ts[1].data, hw.data(), hw.size() * 2, hipMemcpyHostToDevice);
auto run = [&](const RadKernelInfo* r, int64_t m, std::vector<uint16_t>& out) {
std::vector<RadTensor> tm = ts;
tm[0].shape[0] = m;
tm[2].shape[0] = m;
std::vector<RadParam> ps = { PI("M", m), PI("N", N), PI("K", K), PS("dtype", "bf16") };
if (hipMemset(ts[2].data, 0xA5, (size_t)(M * N) * 2) != hipSuccess) return -1;
RadArgs a;
std::memset(&a, 0, sizeof(a));
a.t = tm.data(); a.n_t = (int)tm.size();
a.p = ps.data(); a.n_p = (int)ps.size();
a.world_size = 1;
const int rc = r->launch(&a, (RadStream) nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : -1;
out.assign((size_t)(H * N), 0);
st_memcpy(out.data(), ts[2].data, out.size() * 2, hipMemcpyDeviceToHost);
return 0;
};
std::vector<uint16_t> lo, hi;
if (run(rs, H, lo) != 0) { ok(nm, false, "skinny launch failed"); return; }
if (run(rt, M, hi) != 0) { ok(nm, false, "tiled launch failed"); return; }
size_t diff = 0;
for (size_t i = 0; i < lo.size(); ++i) diff += lo[i] != hi[i];
ok(nm, diff == 0, diff ? std::to_string(diff) + " of " + std::to_string(lo.size()) + " differ"
: std::string("same"));
}
/* logit_softcap, against an f64 evaluation of the same formula.
*
* Two caps: the model's (Gemma 4 issues 30.0) and a smaller one, so a hard-wired 30.0 or a cap
@@ -6833,6 +7196,65 @@ static void hc_project_case(const Plugin& pl) {
}
}
/* rmsnorm's rows against the same rows in a larger launch, byte for byte. The workgroup widens at
* small M (r4d_act_threads: 1024 threads to 32 rows, 512 to the K crossover, 256 past it), and a
* row's norm must not move with it: a token prefilled in a 64-token chunk and in a 2048-token one
* gets the same bits. The leading rows run at M 1, 8, 32, 64 and 100, each against the 256-row
* launch, at the hidden width and at a QK-norm head. */
static void rmsnorm_rows_invariant(const Plugin& pl) {
const RadKernelInfo* r = find(pl, "rmsnorm_bf16");
for (const int64_t n : { (int64_t)5120, (int64_t)256 }) {
char nm[96];
std::snprintf(nm, sizeof nm, "rmsnorm_bf16 rows do not depend on M (n=%lld)", (long long)n);
if (!r) { ok(nm, false, "row absent"); return; }
const int64_t M = 256;
std::vector<uint16_t> xh((size_t)(M * n));
for (size_t i = 0; i < xh.size(); ++i)
xh[i] = h_to_bf16((float)((int)(st_mix32((uint32_t)i) % 401) - 200) * 0.03f);
std::vector<float> wh((size_t)n);
for (size_t i = 0; i < wh.size(); ++i)
wh[i] = (float)((int)(st_mix32((uint32_t)i ^ 0x5bd1e995u) % 199) - 99) * 0.01f;
void* d_x = dalloc(xh.size() * 2);
void* d_w = dalloc(wh.size() * 4);
void* d_y = dalloc(xh.size() * 2);
if (!d_x || !d_w || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice);
st_memcpy(d_w, wh.data(), wh.size() * 4, hipMemcpyHostToDevice);
auto run = [&](int64_t m, std::vector<uint16_t>& out) {
std::vector<RadTensor> ts = { T(d_x, RAD_BF16, { m, n }), T(d_w, RAD_F32, { n }),
T(d_y, RAD_BF16, { m, n }) };
std::vector<RadParam> ps = { PI("M", m), PI("n", n), PF("eps", 1e-6), PF("wadd", 1.0),
PS("dtype", "bf16") };
if (hipMemset(d_y, 0xA5, xh.size() * 2) != hipSuccess) return -1;
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();
const int rc = r->launch(&a, nullptr);
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return rc != RAD_OK ? rc : -1;
out.assign((size_t)(m * n), 0);
st_memcpy(out.data(), d_y, out.size() * 2, hipMemcpyDeviceToHost);
return 0;
};
std::vector<uint16_t> ref, got;
if (run(M, ref) != 0) { ok(nm, false, "launch failed at M=256"); return; }
std::string d;
bool all = true;
for (const int64_t m : { 1, 8, 32, 64, 100 }) {
size_t diff = 0;
const int rc = run(m, got);
if (rc == 0)
for (size_t i = 0; i < got.size(); ++i) diff += got[i] != ref[i];
all = all && rc == 0 && diff == 0;
d += (d.empty() ? "" : ", ") + std::string("M=") + std::to_string(m) + ": " +
(rc ? std::string("launch failed") : diff ? std::to_string(diff) + " differ"
: std::string("same"));
}
ok(nm, all, d);
}
}
/* rmsnorm_p, against an f64 evaluation of the weightless normalisation.
*
* Two eps values: the model's (Gemma 4 issues 1e-6) and 1e-2, so a hard-wired 1e-6 or a dropped
@@ -14038,6 +14460,270 @@ static void rmsnorm_quant_i8_numeric(const Plugin& pl) {
}
}
/* The IQR head (logits_gemm_iqr, logit_rerank_iqr) against the int8 head's rows over the same
* values: a TB-bit table head and its int8 decode, the latter stored as `codes=i8` through
* logits_gemm_i8's hooks. The IQR rows decode each code to the int8 head's byte and then run its
* arithmetic, so the logits and the reranked candidates are the int8 rows' to the bit. */
static void iqr_head_case(const Plugin& pl, int TB, int64_t N, int64_t K, int64_t M) {
char nm[160];
std::snprintf(nm, sizeof nm, "logits_gemm_iqr table B=%d N=%lld K=%lld M=%lld", TB, (long long)N,
(long long)K, (long long)M);
const RadKernelInfo* lq = find(pl, "logits_gemm_iqr");
const RadKernelInfo* li = find(pl, "logits_gemm_i8");
const RadKernelInfo* rq = find(pl, "logit_rerank_iqr");
const RadKernelInfo* ri = find(pl, "logit_rerank_i8");
if (!lq || !li || !rq || !ri) { ok(nm, false, "rows absent"); return; }
static const uint32_t kU[] = { 0, 0, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6 };
const int64_t nkb = K / 128;
uint64_t z = 0x1234567ull * (uint64_t)(TB * 7 + M);
auto rnd = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return x ^ (x >> 31);
};
Planes p;
p.enc = rad_enc_affine(kU[TB], RAD_BF16, 1, 128);
rad_enc_add_table(&p.enc, "table", RAD_I8, 1, (int64_t)1 << TB);
p.size(N, K);
const int ic = p.find("codes"), is = p.find("scale"), it = p.find("table");
for (int64_t r = 0; r < N; ++r)
for (int64_t c = 0; c < K; ++c)
rad_store_bits(p.data[(size_t)ic].data() + r * p.row_bytes(ic), TB, c,
(uint32_t)(rnd() & ((1u << TB) - 1)));
for (auto& v : p.data[(size_t)it]) v = (uint8_t)(int8_t)((int)(rnd() % 255) - 127);
for (int64_t i = 0; i < N * nkb; ++i)
rad_store_f32(p.data[(size_t)is].data(), RAD_BF16, i,
std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -8 - (int)(rnd() % 3)));
Planes pi;
pi.enc = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
pi.size(N, K);
for (int64_t r = 0; r < N; ++r)
for (int64_t c = 0; c < K; ++c)
pi.data[0][(size_t)(r * K + c)] = p.data[(size_t)it][rad_load_bits(
p.data[(size_t)ic].data() + r * p.row_bytes(ic), TB, c)];
pi.data[1] = p.data[(size_t)is];
std::vector<RadParam> lp = { PI("n_vocab", N), PI("n_embd", K) };
std::vector<uint8_t> wq, wi;
RadLayout lay;
if (stored(lq, lp, 1, p, { "codes", "scale", "table" }, &wq, &lay) != RAD_OK ||
stored(li, lp, 1, pi, { "codes", "scale" }, &wi) != RAD_OK) {
ok(nm, false, "relayout failed");
return;
}
{
std::string why;
ok((std::string(nm) + ": the stored rows invert").c_str(),
restores(lq, lp, 1, p, { "codes", "scale", "table" }, wq, &why), why);
ok((std::string(nm) + ": VRAM holds the codes' bits").c_str(),
(int64_t)wq.size() < N * (K * TB / 8 + 2 * nkb + 16) + 512,
std::to_string(wq.size()) + " bytes");
}
std::vector<uint16_t> xb((size_t)(M * K));
for (auto& v : xb) v = h_to_bf16((float)((int)(rnd() % 2001) - 1000) * 0.001f);
void* d_q = dalloc(wq.size());
void* d_i = dalloc(wi.size());
void* d_x = dalloc(xb.size() * 2);
void* d_yq = dalloc((size_t)(M * N) * 4);
void* d_yi = dalloc((size_t)(M * N) * 4);
if (!d_q || !d_i || !d_x || !d_yq || !d_yi) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_q, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_i, wi.data(), wi.size(), hipMemcpyHostToDevice);
st_memcpy(d_x, xb.data(), xb.size() * 2, hipMemcpyHostToDevice);
std::vector<RadParam> gp = { PI("M", M), PI("n_vocab", N), PI("n_embd", K), PS("dtype", "bf16") };
const int r1 = launch_row(lq, { T(d_x, RAD_BF16, { M, K }), T(d_q, lay.dtype, { N, K }),
T(d_yq, RAD_F32, { M, N }) }, gp);
const int r2 = launch_row(li, { T(d_x, RAD_BF16, { M, K }), T(d_i, RAD_I8, { N, K }),
T(d_yi, RAD_F32, { M, N }) }, gp);
if (r1 != RAD_OK || r2 != RAD_OK) {
ok(nm, false, "rc " + std::to_string(r1) + " (int8 " + std::to_string(r2) + ")");
return;
}
std::vector<uint32_t> yq((size_t)(M * N)), yi((size_t)(M * N));
st_memcpy(yq.data(), d_yq, yq.size() * 4, hipMemcpyDeviceToHost);
st_memcpy(yi.data(), d_yi, yi.size() * 4, hipMemcpyDeviceToHost);
int64_t bad = 0;
for (size_t i = 0; i < yq.size(); ++i) bad += yq[i] != yi[i];
ok(nm, bad == 0, bad ? std::to_string(bad) + " logits differ from the int8 head's" : "the int8 head's bits");
/* The rerank over R candidates a row, some outside the shard. */
const int64_t R = 8;
std::vector<int32_t> cand((size_t)(M * R));
for (auto& v : cand) v = (int32_t)(rnd() % (uint64_t)(N + 40)) - 20;
void* d_c = dalloc(cand.size() * 4);
void* d_oi[2] = { dalloc(cand.size() * 4), dalloc(cand.size() * 4) };
void* d_ov[2] = { dalloc(cand.size() * 4), dalloc(cand.size() * 4) };
st_memcpy(d_c, cand.data(), cand.size() * 4, hipMemcpyHostToDevice);
std::vector<RadParam> rp = { PI("M", M), PI("n_vocab", N), PI("n_embd", K), PI("R", R),
PI("vocab_off", 0) };
const int r3 = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(d_q, lay.dtype, { N, K }),
T(d_c, RAD_I32, { M, R }), T(d_oi[0], RAD_I32, { M, R }),
T(d_ov[0], RAD_F32, { M, R }), T(nullptr, RAD_F32, {}) }, rp);
const int r4 = launch_row(ri, { T(d_x, RAD_BF16, { M, K }), T(d_i, RAD_I8, { N, K }),
T(d_c, RAD_I32, { M, R }), T(d_oi[1], RAD_I32, { M, R }),
T(d_ov[1], RAD_F32, { M, R }), T(nullptr, RAD_F32, {}) }, rp);
std::vector<uint32_t> oq((size_t)(2 * M * R)), oi((size_t)(2 * M * R));
if (r3 == RAD_OK && r4 == RAD_OK) {
st_memcpy(oq.data(), d_oi[0], (size_t)(M * R) * 4, hipMemcpyDeviceToHost);
st_memcpy(oq.data() + M * R, d_ov[0], (size_t)(M * R) * 4, hipMemcpyDeviceToHost);
st_memcpy(oi.data(), d_oi[1], (size_t)(M * R) * 4, hipMemcpyDeviceToHost);
st_memcpy(oi.data() + M * R, d_ov[1], (size_t)(M * R) * 4, hipMemcpyDeviceToHost);
}
ok((std::string("logit_rerank_iqr table B=") + std::to_string(TB) + " M=" + std::to_string(M)).c_str(),
r3 == RAD_OK && r4 == RAD_OK && oq == oi,
r3 != RAD_OK || r4 != RAD_OK ? "rc " + std::to_string(r3) + "/" + std::to_string(r4)
: oq == oi ? "the int8 rerank's ids and scores" : "differs from the int8 rerank");
dfree_all();
}
/* embed_lookup_iqr against the table its forms stood for when libr4d widened them to bf16 at
* load: each value the form's int8 times its row's bf16 scale in f32, the fwht128 rotation undone
* in libquant's butterfly order, rounded to bf16 to nearest even, then times `mult` with one
* rounding. Ids outside the shard (negative, past it) give zero rows. */
struct IqrEmbedCase { int kind, B, L; bool two, rot; };
static void iqr_embed_case(const Plugin& pl, const IqrEmbedCase& f, int64_t rows, int64_t dim,
float mult) {
static const char* kKind[] = { "", "signed", "zero", "table", "grid", "trellis" };
char nm[160];
std::snprintf(nm, sizeof nm, "embed_lookup_iqr %s B=%d%s%s mult=%g", kKind[f.kind], f.B,
f.kind == 5 ? (" L=" + std::to_string(f.L)).c_str() : "", f.rot ? " rotated" : "",
(double)mult);
const RadKernelInfo* r = find(pl, "embed_lookup_iqr");
if (!r || !r->layout || !r->relayout) { ok(nm, false, "row or hooks absent"); return; }
static const uint32_t kU[] = { 0, RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6 };
const int64_t nkb = dim / 128;
uint64_t z = 0xABCDEFull * (uint64_t)(f.kind * 31 + f.B + f.rot);
auto rnd = [&]() {
z += 0x9E3779B97F4A7C15ull;
uint64_t x = z;
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
return x ^ (x >> 31);
};
Planes p;
if (f.kind == 5) {
rad_enc_clear(&p.enc);
rad_enc_copy_str(p.enc.scheme, "trellis");
rad_enc_add_plane(&p.enc, "codes", kU[f.B], 1, 1);
rad_enc_add_plane(&p.enc, "scale", f.two ? RAD_F8E4M3 : RAD_BF16, 1, 128);
if (f.two) rad_enc_add_plane(&p.enc, "scale.1", RAD_F32, 0, 0);
const int t = rad_enc_add_table(&p.enc, "trellis", RAD_I8, (int64_t)1 << f.L, 1);
p.enc.plane[t].block[0] = 256;
} else {
p.enc = rad_enc_affine(kU[f.B], RAD_BF16, 1, 128);
if (f.kind == 3) rad_enc_add_table(&p.enc, "table", RAD_I8, 1, (int64_t)1 << f.B);
else rad_enc_add_plane(&p.enc, "zero", RAD_U6, 1, 128);
}
if (f.rot) rad_enc_copy_str(p.enc.transform, "fwht128");
p.size(rows, dim);
const int ic = p.find("codes"), is = p.find("scale"), is2 = p.find("scale.1");
const int ia = f.kind == 5 ? p.find("trellis") : f.kind == 3 ? p.find("table") : p.find("zero");
for (int64_t n = 0; n < rows; ++n)
for (int64_t c = 0; c < dim; ++c)
rad_store_bits(p.data[(size_t)ic].data() + n * p.row_bytes(ic), f.B, c,
(uint32_t)(rnd() & ((1u << f.B) - 1)));
if (f.kind == 2)
for (int64_t n = 0; n < rows; ++n)
for (int64_t g = 0; g < nkb; ++g)
rad_store_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), 6, g, (uint32_t)(24 + rnd() % 17));
else
for (auto& v : p.data[(size_t)ia]) v = (uint8_t)(int8_t)((int)(rnd() % 255) - 127);
for (int64_t i = 0; i < rows * nkb; ++i) {
if (f.two) p.data[(size_t)is][(size_t)i] = (uint8_t)(0x30 + rnd() % 0x28);
else rad_store_f32(p.data[(size_t)is].data(), RAD_BF16, i, std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -6));
}
if (f.two) rad_store_f32(p.data[(size_t)is2].data(), RAD_F32, 0, 0.0123f);
/* The host reference. */
auto code = [&](int64_t n, int64_t c) {
return rad_load_bits(p.data[(size_t)ic].data() + n * p.row_bytes(ic), f.B, c);
};
auto own = [&](int64_t n, int64_t g) -> uint16_t {
if (!f.two) return ((const uint16_t*)p.data[(size_t)is].data())[n * nkb + g];
const float x = rad_load_f32(p.data[(size_t)is2].data(), RAD_F32, 0) *
rad_fp8e4m3_to_f32(p.data[(size_t)is][(size_t)(n * nkb + g)]);
uint32_t u;
std::memcpy(&u, &x, 4);
u += 0x7FFFu + ((u >> 16) & 1u);
return (uint16_t)(u >> 16);
};
const int C = f.kind == 5 ? (f.L + f.B - 1) / f.B : 1;
auto row_ref = [&](int64_t n, std::vector<uint16_t>* out) {
std::vector<float> v((size_t)dim);
for (int64_t k = 0; k < dim; ++k) {
int q;
if (f.kind == 3) q = ((const int8_t*)p.data[(size_t)ia].data())[code(n, k)];
else if (f.kind == 2) q = (int)code(n, k) - (int)rad_load_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), 6, k / 128);
else {
uint32_t st = 0;
for (int qq = C - 1; qq >= 0; --qq) {
const int64_t rr = n / 256 * 256 + (n % 256 - qq + 256) % 256;
st = ((st << f.B) | code(rr, k)) & ((1u << f.L) - 1u);
}
q = ((const int8_t*)p.data[(size_t)ia].data())[st];
}
const uint32_t sb = (uint32_t)own(n, k / 128) << 16;
float s;
std::memcpy(&s, &sb, 4);
v[(size_t)k] = (float)q * s;
}
if (f.rot)
for (int64_t g = 0; g < dim; g += 128)
for (int64_t h = 1; h < 128; h <<= 1)
for (int64_t i = g; i < g + 128; i += h << 1)
for (int64_t j = i; j < i + h; ++j) {
const float a = v[(size_t)j], b = v[(size_t)(j + h)];
v[(size_t)j] = a + b;
v[(size_t)(j + h)] = a - b;
}
for (int64_t k = 0; k < dim; ++k) {
uint16_t bb = h_to_bf16(v[(size_t)k]);
if (mult != 1.0f) bb = h_to_bf16(h_bf16(bb) * mult);
(*out)[(size_t)k] = bb;
}
};
std::vector<RadParam> lp = { PI("n_vocab", rows), PI("n_embd", dim) };
std::vector<uint8_t> wq;
RadLayout lay;
std::vector<const char*> roles;
const int rc = f.kind == 5 ? (f.two ? stored(r, lp, 1, p, { "codes", "scale", "scale.1", "trellis" }, &wq, &lay)
: stored(r, lp, 1, p, { "codes", "scale", "trellis" }, &wq, &lay))
: f.kind == 3 ? stored(r, lp, 1, p, { "codes", "scale", "table" }, &wq, &lay)
: stored(r, lp, 1, p, { "codes", "scale", "zero" }, &wq, &lay);
if (rc != RAD_OK) { ok(nm, false, "relayout rc " + std::to_string(rc)); return; }
ok((std::string(nm) + ": VRAM holds the codes' bits").c_str(),
(int64_t)wq.size() < rows * dim * f.B / 8 + rows * nkb * 3 + ((int64_t)1 << f.L) + 4096,
std::to_string(wq.size()) + " bytes");
const int64_t M = 9;
std::vector<int32_t> tok = { 0, 1, (int32_t)rows - 1, -1, (int32_t)rows, 255, 256, 3, (int32_t)rows / 2 };
void* d_w = dalloc(wq.size());
void* d_t = dalloc(tok.size() * 4);
void* d_x = dalloc((size_t)(M * dim) * 2);
if (!d_w || !d_t || !d_x) { ok(nm, false, "hipMalloc failed"); return; }
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
st_memcpy(d_t, tok.data(), tok.size() * 4, hipMemcpyHostToDevice);
std::vector<RadParam> ep = { PI("M", M), PI("n_embd", dim), PI("n_vocab", rows), PS("dtype", "bf16"),
PI("vocab_offset", 0) };
RadParam pm;
std::memset(&pm, 0, sizeof pm);
pm.key = "mult"; pm.kind = RAD_P_F64; pm.dval = mult;
if (mult != 1.0f) ep.push_back(pm);
const int lr = launch_row(r, { T(d_t, RAD_I32, { M }), T(d_w, lay.dtype, { rows, dim }),
T(d_x, RAD_BF16, { M, dim }) }, ep);
if (lr != RAD_OK) { ok(nm, false, "rc " + std::to_string(lr)); return; }
std::vector<uint16_t> got((size_t)(M * dim)), want((size_t)dim);
st_memcpy(got.data(), d_x, got.size() * 2, hipMemcpyDeviceToHost);
int64_t bad = 0;
for (int64_t m = 0; m < M; ++m) {
if (tok[(size_t)m] < 0 || tok[(size_t)m] >= rows) std::fill(want.begin(), want.end(), 0);
else row_ref(tok[(size_t)m], &want);
for (int64_t k = 0; k < dim; ++k) bad += got[(size_t)(m * dim + k)] != want[(size_t)k];
}
ok(nm, bad == 0, bad ? std::to_string(bad) + " values differ from the widened table's" : "the widened table's bf16");
dfree_all();
}
/* The fp8 lm_head, end to end through its own hooks.
*
* Unlike the linears' separate [sn][sk] plane, each stored row carries its own bf16 scales in its
@@ -25407,6 +26093,34 @@ static void gram_accum_bf16_case(const Plugin& pl, int64_t M, int64_t K) {
ok(what.c_str(), rel >= 0.0 && rel < 1e-5,
"rel_l2 " + std::to_string(rel) + ", worst " + std::to_string(worst));
/* upper=1 into the seed: k2 >= k1 is seed + want, and each tile wholly below the diagonal
* keeps the seed. */
st_memcpy(d_h, seed.data(), seed.size() * 4, hipMemcpyHostToDevice);
ps.push_back(PI("upper", 1));
a.p = ps.data(); a.n_p = (int)ps.size();
rc = g->launch(&a, nullptr);
st_stream_sync(nullptr);
ps.pop_back();
a.p = ps.data(); a.n_p = (int)ps.size();
if (rc != RAD_OK) { ok(what.c_str(), false, "upper launch rc=" + std::to_string(rc)); return; }
st_memcpy(got.data(), d_h, got.size() * 4, hipMemcpyDeviceToHost);
num = den = 0.0;
int64_t touched = 0;
for (int64_t k1 = 0; k1 < K; ++k1)
for (int64_t k2 = 0; k2 < K; ++k2) {
const size_t i = (size_t)(k1 * K + k2);
if (k2 >= k1) {
const double exp = (double)seed[i] + want[i], d = (double)got[i] - exp;
num += d * d; den += exp * exp;
} else if (k2 / 64 < k1 / 64 && std::memcmp(&got[i], &seed[i], 4)) {
++touched;
}
}
const double rel_u = den > 0.0 ? std::sqrt(num / den) : -1.0;
ok((what + ": upper=1 adds k2 >= k1 and leaves the tiles below").c_str(),
rel_u >= 0.0 && rel_u < 1e-5 && touched == 0,
"rel_l2 " + std::to_string(rel_u) + ", " + std::to_string(touched) + " entries below touched");
/* A scale handed to the bf16 form is refused. */
ts[1] = T(d_h, RAD_F32, { M, 1 });
rc = g->launch(&a, nullptr);
@@ -29220,6 +29934,18 @@ static void device_phase(const Plugin& pl) {
run_case(r, ts, ps);
}
}
if (sel("seg_softmax_pool_bf16")) {
const RadKernelInfo* r = find(pl, "seg_softmax_pool_bf16");
if (!r) ok("seg_softmax_pool_bf16", false, "row absent");
else {
std::vector<RadTensor> ts = { T(nullptr, RAD_BF16, { 23 }),
T(nullptr, RAD_BF16, { 23, 645 }),
T(nullptr, RAD_I32, { 4 }),
T(nullptr, RAD_BF16, { 3, 645 }) };
std::vector<RadParam> ps = { PI("M", 23), PI("n", 645), PS("dtype", "bf16") };
run_case(r, ts, ps);
}
}
if (sel("qk_norm_rope_bf16")) {
const RadKernelInfo* r = find(pl, "qk_norm_rope_bf16");
if (!r) ok("qk_norm_rope_bf16", false, "row absent");
@@ -29443,6 +30169,7 @@ static void device_phase(const Plugin& pl) {
want[(size_t)(m * n + i)] = x[(size_t)(m * n + i)] * s * w[(size_t)i] * 0.5f;
}
check("rmsnorm_bf16 mult numerics", down(dy, x.size()), want, 1e-2);
rmsnorm_rows_invariant(pl);
}
if (sel("conv2d_bf16")) {
const RadKernelInfo* r = find(pl, "conv2d_bf16");
@@ -30395,6 +31122,41 @@ static void device_phase(const Plugin& pl) {
i8a8_numeric(pl, "gemm_i8a8_nt_m16", 64, 512, 640);
i8a8_numeric(pl, "gemm_i8a8_tiled", 200, 256, 640);
i8a8_numeric(pl, "gemm_i8a8_tiled", 2048, 512, 2560);
i8a8_numeric(pl, "gemm_i8a8_rb8_tiled", 200, 256, 640, 8);
i8a8_numeric(pl, "gemm_i8a8_rb8_tiled", 2048, 512, 2560, 8);
i8a8_numeric(pl, "gemm_i8a8_rb8_tiled", 300, 256, 5120, 8);
i8a8_numeric(pl, "gemm_i8a8_rb32_tiled", 200, 256, 640, 32);
i8a8_numeric(pl, "gemm_i8a8_rb32_tiled", 300, 256, 5120, 32);
/* The IQR forms, decoded where they are read, against the int8 rows on their values: V1's
* tables, grids and zero; V2's 4096-state trellis; V3's 16384-state one on tcq_rb=32. M 1,
* 4 and 8 reach the GEMV (split over K at N 512), 9 and 64 the narrow tile (64 a split at N
* 512), 300 the prefill decode. */
{
const IqrCase fs[] = {
{ 3, 2, 0, 0, 1, false, false }, { 3, 3, 0, 0, 1, false, true }, { 3, 4, 0, 0, 1, false, true },
{ 3, 5, 0, 0, 1, false, false }, { 4, 8, 4, 0, 1, false, true }, { 4, 9, 4, 0, 1, false, true },
{ 4, 10, 4, 0, 1, false, false }, { 4, 12, 4, 0, 1, false, true }, { 2, 6, 0, 0, 1, false, true },
{ 5, 2, 0, 12, 1, true, true }, { 5, 3, 0, 12, 1, true, true }, { 5, 4, 0, 12, 1, true, false },
{ 5, 5, 0, 12, 1, true, true }, { 5, 6, 0, 12, 1, true, true }, { 5, 7, 0, 12, 1, true, true },
{ 5, 2, 0, 14, 32, true, true }, { 5, 3, 0, 14, 32, true, true }, { 5, 4, 0, 14, 32, true, true },
{ 5, 5, 0, 14, 32, true, false }, { 5, 6, 0, 14, 32, true, true }, { 5, 7, 0, 14, 32, true, true },
{ 6, 2, 0, 16, 32, true, true }, { 6, 3, 0, 16, 32, true, true }, { 6, 4, 0, 16, 32, true, true },
{ 6, 5, 0, 16, 32, true, true }, { 6, 6, 0, 16, 32, true, true }, { 6, 7, 0, 16, 32, true, true },
{ 6, 2, 0, 16, 1, true, true }, { 6, 4, 0, 16, 1, true, true },
{ 6, 2, 0, 16, 1, false, true, true }, { 6, 3, 0, 16, 1, false, true, true },
{ 6, 4, 0, 16, 1, false, true, true }, { 6, 5, 0, 16, 1, false, true, true },
{ 6, 6, 0, 16, 1, false, true, true }, { 6, 7, 0, 16, 1, false, true, true },
{ 6, 2, 0, 15, 1, false, true, true },
};
for (const IqrCase& f : fs) {
iqr_gemm_case(pl, f, 1, 512, 1024);
iqr_gemm_case(pl, f, 4, 2048, 2560);
iqr_gemm_case(pl, f, 8, 512, 1024);
iqr_gemm_case(pl, f, 9, 512, 1024);
iqr_gemm_case(pl, f, 64, 512, 2560);
iqr_gemm_case(pl, f, 300, 512, 1024);
}
}
/* The bias GEMM: three shapes on the 128 x 128 kernel (ragged N with an unaligned pitch;
* an aligned ragged N with a K tail; K below one tile) and one on the 64 x 64 kernel. */
bias_gemm_numeric(pl, 1100, 1001, 200, 1, true, false);
@@ -31616,6 +32378,25 @@ static void device_phase(const Plugin& pl) {
logits_cols_check(pl, M, 2051);
logits_cols_check(pl, 6, 19360);
}
/* The IQR head and embedding table, at their codes' width. */
if (sel("logits_gemm_iqr") || sel("logit_rerank_iqr")) {
for (const int tb : { 2, 3, 4, 5, 6 })
for (const int64_t M : { (int64_t)1, (int64_t)2, (int64_t)5, (int64_t)70 })
iqr_head_case(pl, tb, 1000, 640, M);
iqr_head_case(pl, 5, 4096, 5120, 1);
iqr_head_case(pl, 4, 4096, 5120, 8);
}
if (sel("embed_lookup_iqr")) {
const IqrEmbedCase es[] = {
{ 3, 2, 0, false, false }, { 3, 3, 0, false, false }, { 3, 4, 0, false, true },
{ 3, 5, 0, false, false }, { 2, 6, 0, false, false }, { 5, 2, 12, true, true },
{ 5, 3, 12, true, true }, { 5, 4, 12, true, true }, { 5, 5, 12, true, true },
};
for (const IqrEmbedCase& f : es) {
iqr_embed_case(pl, f, 512, 640, 1.0f);
iqr_embed_case(pl, f, 512, 640, 3.25f);
}
}
/* The int8 head over the same stored row: both forms, and the padded K = 2560 row. */
if (sel("logits_gemm_i8") || sel("logit_rerank_i8")) {
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33, (int64_t)64, (int64_t)100 })
@@ -31679,6 +32460,11 @@ static void device_phase(const Plugin& pl) {
bf16_tiled_identity(pl, 333, 1040, 2560); /* ragged M and N, two slices */
bf16_tiled_identity(pl, 77, 128, 64); /* one slice per k step, the band's floor */
bf16_gemm_numeric(pl, "gemm_bf16_nt_tiled", 300, 1040, 2560);
/* Qwen3.8 27B at TP2: the delta net's in/z/out, the MLP, the attention's q/k/v and o */
static const int64_t kNK[][2] = { { 5168, 5120 }, { 3072, 5120 }, { 5120, 3072 },
{ 17408, 5120 }, { 5120, 8704 }, { 6144, 5120 },
{ 512, 5120 } };
for (const auto& nk : kNK) bf16_band_edge(pl, nk[0], nk[1]);
}
/* Every collective has a host twin (r4d_rows.cpp): the same kernel with its mailbox in pinned