Archived
radiance 1.17.0
IQR-V4 for Qwen3.8-27B: - 15 recipes, data/recipes/q38-27b-iq2r-v4 .. q38-27b-iq8r-v4 (2.5 to 8 bits a weight), docs/IQR.md "IQR-V4". On the quantisation board's private split every entry has 2-19% less KL than its V3 twin of the same size (10-19% from 2.5 to 5.4 bits); IQ4R-L-V4 is 24% below the official FP8 checkpoint at 55% of its size, and IQ2R-L-V4 (2.8 bpw) is below the MXFP4 checkpoint. Containers with the DFlash2 drafter and the vision tower: huggingface.co/StillDeadcode/qwen3.8-27b-iqr-v4, served by deploy/compose/qwen3.8-27b-iqr-v4.yaml (IQR_V4 names the size) - GPTQ runs in act order inside the column trellis (tcq_order=1); the head-fed projections (attn_output, ssm_out) take a bf16 scale a (row, 128) block from five bits up; widths from measured prices - A vocabulary-weighted lm_head: four width classes of the computed trellis (output.k<B>), the tokens carrying the probability on the widest, decoded in one launch by logits_gemm_vocab with 16-bit head activations; 0.62 ms at one token on a TP2 rank against the int8 head's 1.02 ms. tools/vhead.py and data/vhead/ build the class split from the bf16 checkpoint; libquant reads the head's input Hessian for every class - At IQ6R-L and up, the int8 lm_head is GPTQ'd against its input Hessian (same bytes, median KL -8..-12%) - embed_lookup_iqr takes u7/u8 tables under a zero point and the 4096-state trellis at 6 and 7 bits - The whitepaper: radiance.stilldeadco.de/whitepapers/iqr-v4.pdf Faster IQR kernels: - The one-token GEMV gives each 16-row weight tile a block whose waves split K (5120 x 6144 at one token 42.3 -> 30.0 us), with a biased-int fold, a v_perm activation broadcast and one code stream a column - A 16-token WMMA tile without block barriers serves 2 to 16 tokens (6- and 7-bit codes from one token): a 4-bit weight takes 0.52-0.66 of FP8's time from one token to sixteen, 1.15-1.74x V3's kernels from four tokens up - The activation quantisers after the IQR gate_up (gemm_iqr_gated), the delta net's decode conv fold (gdn_conv_recurrent_update_had) and the attention gate (gate_had_quant_i8g) are folded into their producers, byte for byte the same codes: 128 fewer launches a decode step - End to end on one R9700 (TP1, no speculation): IQ4R-S-V4 decodes one stream in 24.7 ms against the MXFP4 checkpoint's 25.8 at five times lower KL; IQ3R-S-V4 is faster than MXFP4 at 1 to 8 streams. Prefill stays 8-9% behind MXFP4's 4-bit tile Quantisation tooling: - rescale=1 refits each row's scale to its codes after GPTQ; gptqsim measures a tensor's W16A16 form (tcq_code=mad16); an int8 trunk's calibration Grams can be recorded from the codes its GEMMs read (--calib-dir, TP1) - Fixed: the GPU trellis packs tcq_code=mad16's values two int16 a register New models (merged): - Spark 2.5 (spark25: bf16 and rotated-int8 IQ8R checkpoints, tensor parallelism with exact collectives, reasoning and tagged tool calls) with its DSpark drafter (exact attention and Markov walk ops), docs/SPARK25-IQ8R.md (@gostar) - Ling-3.0-flash (bailing_hybrid: KDA, dense latent attention with mla_attn_paged, group-limited sigmoid routing, the clipped SwiGLU and its MTP layer as a serial drafter), its w4a8 recipes and compose files for four and two cards (@keptn42) - Gemma 4 12B (gemma4_unified, served by the gemma4 plugins): its picture and audio embedders, a picture's placeholders read both ways on the sliding layers as the model was trained (the scheduler ends no prefill chunk inside such a run; RadBatch::n_bidi), windowed attention at head_dim 512, the assistant head as MTP drafter at one, two and four ranks, suppress_tokens from generation_config, bf16 and i8g compose files (@keptn42) Merged: - The prefill KV split sized by the live KV length rather than the model's max_ctx, recorded passes keyed by their split geometry, and --gpu-memory-mib, the inverse of --gpu-headroom-mib (@gostar) - Possessive quantifiers in tokenizer patterns where the greedy reading provably matches the same (Ling-3.0's), and the Grafana dashboard's first screen of totals (@keptn42) - The dashboard's history line (decode, prefill and TTFT over finished requests, kept in the browser, JSON export), session extremes that age and reset on a restart, card-count changes, an Advanced tab for the poll intervals, each request's prefill time from admission in /stats (prefill_s), and the page's JavaScript run by tests/js (@Memoria) - From PR #390: the file tier reads a routed layer with its own router's counts and waits for its deposits; the stop-string hold-back keeps back only a tail that can still become a stop string (before, every delta waited up to the longest stop's length); the sampler's planes are sized by the step's token bound, the n-gram ban runs beside a drafter, and a top-1 row issues no candidate cut (@Code000) - The n-gram reader refills its reads as they land, and a decode gather waits on the other rank's read of a row instead of reading it again (#369, @pokesjw) - libr3d's GEMM structs value-initialised so the tape audit sees no padding (@RikshaDriver) Added: - --ngram-placement disk=DIR: the n-gram table read from its own file, DIR/ngram-<id>.bin, filled from the container at the first start, on a faster or separate drive (#130) Fixed: - input_reference's H.264 round trip runs on libopenh264, which the image carries, at a quantiser held at the crf (a side under 16 padded and cut back); a build with no H.264 encoder answers 501 (#163) - kvtier: at most 1024 session rows under one shared first block; with one shared prompt the list grew a row a request and prefill fell from 9k to 2.5k tok/s after 500K requests (#375) - Speculative steps on an architecture with no pass-key callback keep their recorded passes under the live-KV prefill split Plugin ABI 35: - RadArgs::kv_used_max_h and wgp_count, RadBatch::kv_used_max_h and positions_h, the optional rad_arch_pass_key export and RAD_KERNEL_CAP_DYNAMIC_PREFILL_SPLIT; RadEncoderDecl::bidirectional and RadBatch's n_bidi runs. The layout fingerprint table is regenerated; out-of-tree plugins rebuild against 35 Thanks to @gostar, @keptn42, @Memoria, @Code000, @pokesjw and @RikshaDriver.
This commit is contained in:
1 parent
3af8065cc6
commit
19d4e8fe0e
102 files changed
+9794
-692
No files matched your search
@@ -160,6 +160,7 @@ set(R4D_UNITS
|
||||
"r4d_gemm_fp8a8|"
|
||||
"r4d_gemm_iqr|"
|
||||
"r4d_iqr_embed|"
|
||||
"r4d_logits_vocab|"
|
||||
"r4d_quant_act_fp8|"
|
||||
"r4d_givens_rotate|"
|
||||
"r4d_fused_quant_fp8|"
|
||||
|
||||
@@ -63,9 +63,10 @@ static inline int r4d_prefill_splits_law(int bq, int tile, int q_len, int total_
|
||||
// tells r4d_selftest a split launch from an unsplit one with the same bytes. Not atomic.
|
||||
static int g_prefill_last_splits = 0;
|
||||
|
||||
/* The runtime supplies the live group maximum only when it can prove that the launch's full
|
||||
* seqused operand is the just-built, non-speculative prefill batch. Other shapes use max_ctx below;
|
||||
* never synchronously copy device seqused from a HIP queue independent of the AQL upload queue. */
|
||||
/* RadArgs::kv_used_max_h is the host maximum of the launch's seqused operand (Ctx::issue_body),
|
||||
* -1 where it cannot be proven, which uses max_ctx below. In a recorded pass of a plugin with no
|
||||
* pass-key callback (decode, verify, draft) it is the step's keyed context bound instead. Never
|
||||
* synchronously copy device seqused from a HIP queue independent of the AQL upload queue. */
|
||||
|
||||
/* The KV split's count before the scratch bound: the case's `splits` parameter when it names one
|
||||
* (r4d_selftest; the prefill rows declare no such axis, so the engine passes none), else the law,
|
||||
|
||||
@@ -594,6 +594,46 @@ extern "C" int r4d_fuse_gemm_nt_q_gated_mx(const RadParam* p, int n_p, uint64_t
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gemm_nt_q_gated at i8a8h -- the same fold over an IQR gate_up weight (r4d_iqr.h) under the
|
||||
* rotated int8 trunk. (row: gemm_iqr_gated, M <= 16; kernel: libr4d/r4d_gemm_iqr.hip, the gated
|
||||
* forms of its GEMV and 16-token tile, each byte-identical to the GEMM row gemm_iqr_nt_m64 serves
|
||||
* at that M followed by gated_had_quant_i8g.)
|
||||
*
|
||||
* Operands: [0] a [1] a_scale [2] b [3] b_scale [4] q [5] scale [6] out_bf16
|
||||
*
|
||||
* As gemm_nt_q_gated's chain, with `dtype` i8a8h on the GEMM and the rotated int8 quantiser.
|
||||
*/
|
||||
extern "C" int r4d_fuse_gemm_nt_q_gated_iqr(const RadParam* p, int n_p, uint64_t present, int step,
|
||||
RadFuseStep* out) {
|
||||
(void)present;
|
||||
if (!out) return RAD_E_INVAL;
|
||||
const int64_t M = pi(p, n_p, "M"), N = pi(p, n_p, "N"), K = pi(p, n_p, "K");
|
||||
const char* dt = r4d_pgets(p, n_p, "dtype");
|
||||
if (M <= 0 || N <= 0 || K <= 0 || N % 2) return RAD_E_UNSUPPORTED;
|
||||
if (pi(p, n_p, "group", R4D_FP8_BLOCK) != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
|
||||
if (!dt || std::strcmp(dt, "i8a8h")) return RAD_E_UNSUPPORTED;
|
||||
if (!act_is(p, n_p, "silu", "silu")) return RAD_E_UNSUPPORTED;
|
||||
|
||||
switch (step) {
|
||||
case 0: {
|
||||
Step s(out, "gemm_nt_q");
|
||||
s.mirror(p, n_p, "M").mirror(p, n_p, "N").mirror(p, n_p, "K")
|
||||
.mirror(p, n_p, "group").mirror(p, n_p, "dtype");
|
||||
/* a, a_scale, b, b_scale, y, a_sum, b_ref */
|
||||
return s.wire({ 0, 1, 2, 3, RAD_FUSE_TMP(0), RAD_FUSE_NONE, RAD_FUSE_NONE });
|
||||
}
|
||||
case 1: {
|
||||
Step s(out, "gated_had_quant_i8g");
|
||||
s.mirror(p, n_p, "M").pint("n", (long long)(N / 2)).mirror(p, n_p, "group")
|
||||
.pstr("dtype", "bf16").mirror(p, n_p, "act");
|
||||
return s.wire({ RAD_FUSE_TMP(0), 4, 5, 6 }); /* gate_up, q, scale, out_bf16 */
|
||||
}
|
||||
default:
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
}
|
||||
|
||||
/* ==========================================================================================
|
||||
* gdn_conv_recurrent_update -- the decode convolution folded into the recurrent update's prologue.
|
||||
* (row: gdn_conv_recurrent_update_k128_v128_bf16; kernel: libr4d/
|
||||
|
||||
@@ -262,7 +262,11 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel(
|
||||
//
|
||||
// ACT 2 is the product with no activation: the unfused pair is `mul` then the quantiser, so the
|
||||
// gate is not rounded on its own and the product is rounded once, as mul_bf16 does.
|
||||
template <int ACT, bool I8 = false>
|
||||
//
|
||||
// ROT (with I8: gate_had_quant_i8g) puts the width-128 Hadamard between the bf16-rounded product
|
||||
// and the absmax, as gated_quant_fp8_kernel's ROT, for an out projection stored rotated: the codes
|
||||
// are had_quant_act_i8g's over `y`.
|
||||
template <int ACT, bool I8 = false, bool ROT = false>
|
||||
__global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y,
|
||||
uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, uint32_t nkb, uint32_t g_ld,
|
||||
@@ -303,6 +307,8 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel(
|
||||
v[j] = bf2f(h);
|
||||
}
|
||||
}
|
||||
// The rotated launcher requires n % 128 == 0, so no rotated group contains padding.
|
||||
if constexpr (ROT) r4d_fwht_wave<(int)kGroup>(v, (int)lane);
|
||||
quant_group<I8>(v, s, qr, (size_t)row * s_ld + kb, c0, n, lane);
|
||||
}
|
||||
}
|
||||
@@ -866,11 +872,12 @@ extern "C" int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, i
|
||||
// s [M][ceil(n/128)] f32, `s_ld` elements a row (0 = ceil(n/128))
|
||||
static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, int n, int mode,
|
||||
int g_ld, int x_ld, int y_ld, int q_ld, int s_ld,
|
||||
RadStream stream, bool i8 = false) {
|
||||
RadStream stream, bool i8 = false, bool rot = false) {
|
||||
int emit_rc = RAD_OK;
|
||||
if (!g || !x || !q || !s) return -1;
|
||||
if (M <= 0 || n <= 0) return -2;
|
||||
if (n % 4) return -3;
|
||||
if (rot && (!i8 || n % (int)kGroup)) return -3;
|
||||
if (mode < 0 || mode > 2) return -5;
|
||||
if (!g_ld) g_ld = n;
|
||||
if (!x_ld) x_ld = n;
|
||||
@@ -881,7 +888,11 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in
|
||||
// A wave a group, capped at r4d_act_threads' width, as gated_quant_fp8 above.
|
||||
const int thr = std::min(nkb, r4d_act_threads(M, n) / (int)kWave) * (int)kWave;
|
||||
#define R4D_GTQ_I(a, I) \
|
||||
emit_rc = R4D_EMIT(stream, (gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), dim3(thr), 0, \
|
||||
emit_rc = rot ? R4D_EMIT(stream, (gate_quant_fp8_kernel<a, true, true>), dim3((uint32_t)M), \
|
||||
dim3(thr), 0, (const uint16_t*)g, (const uint16_t*)x, (uint16_t*)y, \
|
||||
(uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, (uint32_t)g_ld, \
|
||||
(uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, (uint32_t)s_ld) \
|
||||
: R4D_EMIT(stream, (gate_quant_fp8_kernel<a, I>), dim3((uint32_t)M), dim3(thr), 0, \
|
||||
(const uint16_t*)g, (const uint16_t*)x, \
|
||||
(uint16_t*)y, (uint8_t*)q, (float*)s, (uint32_t)n, (uint32_t)nkb, \
|
||||
(uint32_t)g_ld, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)q_ld, \
|
||||
@@ -1152,7 +1163,7 @@ static long long tq_pitch(const RadTensor* t, long long width) {
|
||||
/* Two-operand form of gated_quant_fp8 for gated attention: `x` is the attention output and the
|
||||
* gate a column view of the [q|gate] projection. The gate offset comes from the view, so there is
|
||||
* no `gate_offset` parameter. */
|
||||
extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
static int rad_gate_quant(const RadArgs* a, RadStream stream, bool rot) {
|
||||
const RadTensor* g = r4d_opt(a, TQ_G);
|
||||
const RadTensor* x = r4d_opt(a, TQ_X);
|
||||
const RadTensor* q = r4d_opt(a, TQ_Q);
|
||||
@@ -1160,6 +1171,7 @@ extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
const RadTensor* y = r4d_opt(a, TQ_Y);
|
||||
if (!g || !x || !q || !sc) return R4D_NO(RAD_E_INVAL);
|
||||
if (q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
|
||||
if (rot && q->dtype != RAD_I8) return R4D_NO(RAD_E_DTYPE);
|
||||
/* M is numel(x) / n. The `M` parameter is the band's declared maximum, not this issue's, and
|
||||
* shape[0] counts tokens while a row here is a (token, head) pair. */
|
||||
const long long K = r4d_geti_or(a, "n", 0);
|
||||
@@ -1181,7 +1193,16 @@ extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
const int e = gate_quant_fp8_emit(r4d_addr(g), r4d_addr(x), y ? r4d_addr(y) : 0,
|
||||
r4d_addr(q), r4d_addr(sc), (int)M, (int)K, mode,
|
||||
(int)gp, (int)xp, (int)yp, (int)qp, (int)sp, stream,
|
||||
q->dtype == RAD_I8);
|
||||
q->dtype == RAD_I8, rot);
|
||||
return e == 0 ? RAD_OK : RAD_E_SHAPE;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gate_quant_fp8(const RadArgs* a, RadStream stream) {
|
||||
return rad_gate_quant(a, stream, false);
|
||||
}
|
||||
|
||||
/* gate_quant_fp8 at had_quant_act_i8g's codes, for an out projection stored rotated (i8a8h). */
|
||||
extern "C" int r4d_rad_gate_had_quant_i8g(const RadArgs* a, RadStream stream) {
|
||||
return rad_gate_quant(a, stream, true);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
#include "r4d_common.h"
|
||||
#include "r4d_gdn_conv_tap.h"
|
||||
#include "r4d_q8.h" // the 8-bit codes the folded quantiser writes: E4M3 or int8
|
||||
#include "r4d_fwht.h" // NORM 3: had_quant_act_i8g's rotation before the int8 codes
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
@@ -245,6 +246,7 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
|
||||
constexpr int THR = NR * 2;
|
||||
static_assert(!(NORM && VS > 1), "the fused row norm needs the whole 128-wide row");
|
||||
__shared__ float wsum[THR / 32];
|
||||
__shared__ float srot[NORM == 3 ? RU_V : 1]; // NORM 3: the row's bf16 output, for the rotation
|
||||
__shared__ float spart[STG ? RU_TMAX * 4 : 1]; // per (token, half): sum q^2, sum k^2
|
||||
__shared__ float sscl [STG ? RU_TMAX * 2 : 1]; // per token: the two closed scales
|
||||
const int n = blockIdx.x, hv = blockIdx.y;
|
||||
@@ -642,7 +644,32 @@ void r4d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q,
|
||||
// `on`, with r4d_fused_quant_fp8.hip's quant_group arithmetic (including the clamp that keeps
|
||||
// the group maximum from becoming NaN). NORM == 2 writes int8 codes instead (quant_act_i8g:
|
||||
// scale amax / 127, round to nearest-even).
|
||||
if (NORM && oq) {
|
||||
// NORM == 3 writes had_quant_act_i8g's codes: the row's 128 stored bf16 values through
|
||||
// r4d_fwht_wave<128> in one wave (a lane four consecutive channels, that function's mapping),
|
||||
// then its amax / 127 scale and round-to-nearest-even, so the bytes are that quantiser's over
|
||||
// `o`.
|
||||
if (NORM == 3 && oq) {
|
||||
if (half == 0) srot[row] = bf2f(ob);
|
||||
__syncthreads();
|
||||
if (tid < 32) {
|
||||
float rv[4];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j) rv[j] = srot[4 * tid + j];
|
||||
r4d_fwht_wave<128>(rv, tid);
|
||||
float m = fmaxf(fmaxf(fabsf(rv[0]), fabsf(rv[1])), fmaxf(fabsf(rv[2]), fabsf(rv[3])));
|
||||
m = r4d_wave_max(m);
|
||||
const float qs = m > 0.0f ? m * (1.0f / 127.0f) : 1.0f;
|
||||
if (tid == 0) os[(size_t)tok * os_ld + hv] = qs;
|
||||
const float inv = 1.0f / qs;
|
||||
uint32_t pk = 0;
|
||||
#pragma unroll
|
||||
for (int j = 0; j < 4; ++j)
|
||||
pk |= ((uint32_t)(int)rintf(fminf(fmaxf(rv[j] * inv, -127.0f), 127.0f)) & 0xFFu) << (8 * j);
|
||||
*(uint32_t*)(oq + (size_t)tok * oq_pitch + (size_t)hv * RU_V + 4 * tid) = pk;
|
||||
}
|
||||
__syncthreads(); // srot is reused by the next token
|
||||
}
|
||||
if ((NORM == 1 || NORM == 2) && oq) {
|
||||
const float ov = bf2f(ob);
|
||||
float mv = (half == 0) ? fabsf(ov) : 0.0f;
|
||||
mv = fmaxf(mv, r4d_xor_lane<16>(mv)); mv = fmaxf(mv, r4d_xor_lane<8>(mv));
|
||||
@@ -879,7 +906,8 @@ static unsigned int* ru_conv_ctr(RadStream s, const void* out) {
|
||||
|
||||
// The recurrent update with gdn_conv_update folded in, decode shape only (bf16 a/b, fused row
|
||||
// norm, one workgroup per (sequence, value head)). State contract, non-temporal choice and
|
||||
// factor-block bounds are as in ru_update_launch. `w_f32` is the conv weight's type.
|
||||
// factor-block bounds are as in ru_update_launch. `w_f32` is the conv weight's type. `oq_i8`:
|
||||
// E4M3 codes (0), int8 (1), or had_quant_act_i8g's rotated int8 (2).
|
||||
static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void* b, long ab_stride,
|
||||
const void* A_log, const void* dt_bias, void* state,
|
||||
long st_slot, long st_head, void* o, void* oq, void* os,
|
||||
@@ -896,8 +924,9 @@ static int ru_conv_recurrent_launch(const RuConv& cv, const void* a, const void*
|
||||
const bool nt = flood <= (long)RU_NT_MB * 1024 * 1024;
|
||||
const dim3 grid(N, H, 1), blk(RU_V * 2);
|
||||
#define RC_LAUNCH(NTC, ANCC, SDTC, CVC) \
|
||||
do { if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \
|
||||
else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0)
|
||||
do { if (oq_i8 == 2) RC_LAUNCH_NM(3, NTC, ANCC, SDTC, CVC); \
|
||||
else if (oq_i8) RC_LAUNCH_NM(2, NTC, ANCC, SDTC, CVC); \
|
||||
else RC_LAUNCH_NM(1, NTC, ANCC, SDTC, CVC); } while (0)
|
||||
#define RC_LAUNCH_NM(NM, NTC, ANCC, SDTC, CVC) \
|
||||
hipLaunchKernelGGL((r4d_gdn_recurrent_update_kernel<1, NM, 1, NTC, ANCC, 0, SDTC, CVC>), \
|
||||
grid, blk, 0, (hipStream_t)stream, nullptr, nullptr, nullptr, a, b, \
|
||||
@@ -1044,7 +1073,8 @@ enum { OPD_CR_X = 0, OPD_CR_CW, OPD_CR_CB, OPD_CR_CSTATE, OPD_CR_CIDX, OPD_CR_A,
|
||||
OPD_CR_ALOG, OPD_CR_DTB, OPD_CR_STATE, OPD_CR_SIDX, OPD_CR_NACC, OPD_CR_CU, OPD_CR_Z,
|
||||
OPD_CR_NORMW, OPD_CR_O, OPD_CR_OQ, OPD_CR_OS };
|
||||
|
||||
extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) {
|
||||
/* `had`: gdn_conv_recurrent_update_had, whose codes are had_quant_act_i8g's over `o` (required). */
|
||||
static int gdn_conv_recurrent_entry(const RadArgs* a, RadStream s, bool had) {
|
||||
if (gdn_dims_ok() != RAD_OK) return R4D_NO(RAD_E_SHAPE);
|
||||
const RadTensor* x = r4d_opt(a, OPD_CR_X);
|
||||
const RadTensor* cw = r4d_opt(a, OPD_CR_CW);
|
||||
@@ -1070,6 +1100,7 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
|
||||
!z || !nw || !o)
|
||||
return R4D_NO(RAD_E_INVAL);
|
||||
if ((oq != nullptr) != (os != nullptr)) return R4D_NO(RAD_E_INVAL);
|
||||
if (had && (!oq || oq->dtype != RAD_I8)) return R4D_NO(RAD_E_INVAL);
|
||||
if (x->rank != 2 || cst->rank != 3 || o->rank != 3 || ta->rank != 2 || tb->rank != 2)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (state->rank < 2 || sidx->rank < 1 || cidx->rank < 1) return R4D_NO(RAD_E_SHAPE);
|
||||
@@ -1147,5 +1178,13 @@ extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s)
|
||||
os ? (long)r4d_row_pitch(os) : 0, cu->data, sidx->data, (long)sidx->stride[0],
|
||||
nacc ? nacc->data : nullptr, z->data, (long)z_row, nw->data, neps, nact, N, (int)H,
|
||||
(int)Hg, scale, thr, state->dtype == RAD_F16 ? 1 : 0, s,
|
||||
oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0, cw->dtype == RAD_F32);
|
||||
had ? 2 : oq && oq->dtype == RAD_I8 ? 1 : 0, anc != 0, cw->dtype == RAD_F32);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s) {
|
||||
return gdn_conv_recurrent_entry(a, s, false);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gdn_conv_recurrent_update_had(const RadArgs* a, RadStream s) {
|
||||
return gdn_conv_recurrent_entry(a, s, true);
|
||||
}
|
||||
+491
-117
@@ -1,18 +1,20 @@
|
||||
// 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_nt_m64 M <= 64 (decode and speculative verify). At one token (a computed trellis;
|
||||
// M <= 8 for the other forms) a GEMV: a block a 16-row tile, its waves across
|
||||
// K, each lane's decoded values one sudot4 against the activation. To 16 tokens
|
||||
// a WMMA tile of the same shape, each 128-K unit decoded and transposed into
|
||||
// fragment order through the wave's LDS just before its WMMA steps. Above, the
|
||||
// i8a8 narrow tile with the same per-unit decode.
|
||||
// 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.
|
||||
// The narrow tile above 16 tokens and the prefill tile 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 and
|
||||
// the 16-token tile sum per wave and then across waves: the product within f32 rounding.
|
||||
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
@@ -20,6 +22,8 @@
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_iqr.h"
|
||||
#include "r4d_iqr_dec.h"
|
||||
#include "r4d_fwht.h"
|
||||
#include "r4d_q8.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
@@ -48,37 +52,97 @@ constexpr uint32_t kIqrSplitWaves = 512;
|
||||
|
||||
#include "r4d_gemm_8a8_prefill.h"
|
||||
|
||||
/* ---- the gated fold (gemm_nt_q_gated at i8a8h) ----------------------------------------------
|
||||
*
|
||||
* gate_up's GEMM with gated_had_quant_i8g's pass in its epilogue. A block computes one 16-column
|
||||
* tile of the gated output: the gate rows' tile and the up rows' tile, each with the waves and K
|
||||
* order of the plain kernel at the full weight's N, so their bf16 values are the plain kernel's.
|
||||
* It writes silu(gate) * up, rounded as gated_quant_fp8_kernel rounds it, into the op's scratch
|
||||
* (and `out_bf16`), and the last of a 128-column group's eight blocks to arrive rotates and
|
||||
* quantises the group, a wave a token, as that kernel does: so the codes and scales are the
|
||||
* pair's bytes. */
|
||||
struct GatedOut {
|
||||
uint16_t* H; /* [M][n] the bf16 product, scratch */
|
||||
int8_t* Q; /* [M][q_ld] int8 codes */
|
||||
float* S; /* [M][s_ld] a scale per (token, 128 columns) */
|
||||
uint16_t* Yb; /* [M][y_ld] the unrotated bf16 product, or null */
|
||||
unsigned int* cnt; /* an arrival counter per 128-column group */
|
||||
uint32_t n, q_ld, s_ld, y_ld;
|
||||
};
|
||||
|
||||
/* Token m's gated value at column `col` from the gate and up rows' f32 sums (row scale applied). */
|
||||
__device__ __forceinline__ void gated_put(const GatedOut& go, uint32_t m, uint32_t col, float vg,
|
||||
float vu) {
|
||||
const float gv = bf16_to_f32(f32_to_bf16(vg));
|
||||
const float a = gv / (1.0f + expf(-gv));
|
||||
const uint16_t h = f32_to_bf16(a * bf16_to_f32(f32_to_bf16(vu)));
|
||||
go.H[(size_t)m * go.n + col] = h;
|
||||
if (go.Yb) go.Yb[(size_t)m * go.y_ld + col] = h;
|
||||
}
|
||||
|
||||
/* After every thread's gated_put: the group's last arriver quantises it, `nw` waves. */
|
||||
__device__ __forceinline__ void gated_tail(const GatedOut& go, uint32_t M, uint32_t nw) {
|
||||
__shared__ unsigned int s_last;
|
||||
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave;
|
||||
const uint32_t g = blockIdx.x / 8u;
|
||||
__threadfence();
|
||||
__syncthreads();
|
||||
if (tid == 0)
|
||||
s_last = __hip_atomic_fetch_add(&go.cnt[g], 1u, __ATOMIC_ACQ_REL, __HIP_MEMORY_SCOPE_AGENT);
|
||||
__syncthreads();
|
||||
if (s_last != 7u) return;
|
||||
if (tid == 0) __hip_atomic_store(&go.cnt[g], 0u, __ATOMIC_RELAXED, __HIP_MEMORY_SCOPE_AGENT);
|
||||
__threadfence();
|
||||
for (uint32_t m = wave; m < M; m += nw) {
|
||||
const uint32_t c0 = g * 128u + lane * 4u;
|
||||
float v[4];
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < 4; ++j) v[j] = bf16_to_f32(go.H[(size_t)m * go.n + c0 + j]);
|
||||
r4d_fwht_wave<128>(v, (int)lane);
|
||||
const float mx = r4d_wave_max(fmaxf(fmaxf(fabsf(v[0]), fabsf(v[1])), fmaxf(fabsf(v[2]), fabsf(v[3]))));
|
||||
const float sc = mx > 0.0f ? mx * (1.0f / q8_top<true>()) : 1.0f;
|
||||
if (lane == 0) go.S[(size_t)m * go.s_ld + g] = sc;
|
||||
*(uint32_t*)(go.Q + (size_t)m * go.q_ld + c0) = q8_pack4<true>(v[0], v[1], v[2], v[3], 1.0f / sc);
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- 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
|
||||
* A block a 16-row tile, its KW waves across K: wave w takes the tile's 128-K blocks w, w + KW, ..,
|
||||
* so at any time a block's waves read KW consecutive units of one tile. Within a wave lane l takes
|
||||
* columns 4l .. 4l + 3 of each 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. At the end each wave sums its lanes and
|
||||
* the block sums its waves through LDS in ascending order. 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.
|
||||
* an f32 fold.
|
||||
*
|
||||
* 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)
|
||||
* A block lives for 1 / KW of a tile's K, so the card balances over N / 16 short blocks and no
|
||||
* weight needs a split across blocks. A wave a tile over all of K (the previous form) left a
|
||||
* partial last round of long waves on every shape: at 102 VGPRs a SIMD holds 15 waves, and N / 16
|
||||
* tiles (gate_up 2176, down split 7 ways 2240) never divide that.
|
||||
*
|
||||
* The fold order differs from the WMMA tile's (per lane, then across lanes and waves), so the
|
||||
* output is the product within f32 rounding rather than the int8 tile's bytes. */
|
||||
template <class F, uint32_t MT, uint32_t KW, bool GATED = false>
|
||||
__global__ __launch_bounds__((GATED ? 2u : 1u) * KW * 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) {
|
||||
uint16_t* __restrict__ Y, uint32_t N, uint32_t x_ld, uint32_t xs_ld,
|
||||
GatedOut go) {
|
||||
using D = Dec<F, true>;
|
||||
constexpr uint32_t NW = (GATED ? 2u : 1u) * KW;
|
||||
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
|
||||
__shared__ float s_red[NW][16 * MT];
|
||||
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1);
|
||||
const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave);
|
||||
const uint32_t wave0 = __builtin_amdgcn_readfirstlane(tid / kWave);
|
||||
Ctx c = c0;
|
||||
c.tab = s_tab;
|
||||
D::stage(s_tab, c, tid, kGW * kWave);
|
||||
D::stage(s_tab, c, tid, NW * 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);
|
||||
/* Gated, waves KW and up take the up rows' tile, n rows below the gate rows'. */
|
||||
const uint32_t half = GATED ? wave0 / KW : 0u, wave = GATED ? wave0 % KW : wave0;
|
||||
const uint32_t rt = blockIdx.x + half * (N / 32u);
|
||||
const uint32_t myrow = rt * 16u + (lane & 15u);
|
||||
|
||||
float acc[16][MT];
|
||||
@@ -86,10 +150,14 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
|
||||
for (uint32_t q = 0; q < 16; ++q)
|
||||
#pragma unroll
|
||||
for (uint32_t m = 0; m < MT; ++m) acc[q][m] = 0.0f;
|
||||
float fsum[MT]; /* the biased path's fold factors since its last flush (wave-uniform) */
|
||||
#pragma unroll
|
||||
for (uint32_t m = 0; m < MT; ++m) fsum[m] = 0.0f;
|
||||
uint32_t nflush = 0;
|
||||
|
||||
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);
|
||||
typename D::Raw cur = D::fetch(c, rt, wave, lane, wave < c.nkb), nxt;
|
||||
for (uint32_t kb = wave; kb < c.nkb; kb += KW) {
|
||||
if (kb + KW < c.nkb) nxt = D::fetch(c, rt, kb + KW, lane, true);
|
||||
uint32_t xv[MT];
|
||||
float as[MT];
|
||||
#pragma unroll
|
||||
@@ -98,8 +166,25 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
|
||||
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;
|
||||
/* A bf16 scale a (row, 128): the tile's sixteen rows' scales of this block are 32
|
||||
* consecutive bytes at a wave-uniform address, read through the constant address space
|
||||
* into scalar registers, so no row's scale is broadcast by readlane. */
|
||||
constexpr bool SROW = F::SC == kBf16 && F::LRB == 0;
|
||||
[[maybe_unused]] uint32_t sw[8];
|
||||
if constexpr (SROW) {
|
||||
typedef const __attribute__((address_space(4))) uint32_t cu32;
|
||||
cu32* sp = (cu32*)((const uint16_t*)c.S + ((size_t)rt * c.nkb + kb) * 16u);
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < 8; ++i) sw[i] = sp[i];
|
||||
}
|
||||
auto row_fold = [&](uint32_t q, float fs_) {
|
||||
if constexpr (SROW)
|
||||
return __uint_as_float(q & 1u ? sw[q / 2u] & 0xFFFF0000u : sw[q / 2u] << 16);
|
||||
else
|
||||
return __builtin_bit_cast(float, __builtin_amdgcn_readlane(__float_as_int(fs_), q));
|
||||
};
|
||||
const float fs = SROW ? 0.0f : fold_f32<F>(c, myrow, kb);
|
||||
const float ratio = rb_ratio<F>(c, myrow, kb);
|
||||
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. */
|
||||
@@ -108,19 +193,54 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
|
||||
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);
|
||||
xsum[m] = __builtin_amdgcn_sudot4(true, (int)xv[m], false, 0x7E7E7E7E, 0, false);
|
||||
}
|
||||
if constexpr (UNS && MT == 1) {
|
||||
if constexpr (UNS && MT <= 4 && F::SC == kRowF32) {
|
||||
/* 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. */
|
||||
* sums the value's bytes and multiplies in one instruction, nothing packed. Under one
|
||||
* f32 scale a row the block's fold is one factor for all rows, so a row's dot starts
|
||||
* at 0x4B400000 less the lane's bias sum: read as an f32 it is exactly 12582912 plus
|
||||
* the sum (|sum| < 2^22), one fma folds it, and 12582912 times the block's factors
|
||||
* leaves each row once at the end. */
|
||||
uint32_t h[16][4];
|
||||
D::hashes(cur, c, h);
|
||||
#pragma unroll
|
||||
for (uint32_t m = 0; m < MT; ++m) {
|
||||
uint32_t xs[4];
|
||||
#pragma unroll
|
||||
for (uint32_t e = 0; e < 4; ++e) xs[e] = __builtin_amdgcn_perm(0u, xv[m], e * 0x01010101u);
|
||||
const float s = fs * as[m];
|
||||
fsum[m] += s;
|
||||
const int b0 = kRbBias - __builtin_amdgcn_sudot4(true, (int)xv[m], false, 0x7E7E7E7E, 0, false);
|
||||
#pragma unroll
|
||||
for (uint32_t q = 0; q < 16; ++q) {
|
||||
int d = b0;
|
||||
#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][m] = fmaf(__int_as_float(d), s, acc[q][m]);
|
||||
}
|
||||
}
|
||||
/* the bias out every kRbFlush blocks, so a row's sum stays within a few bias terms
|
||||
* of its value (the prefill tile's bound) */
|
||||
if (++nflush == kRbFlush) {
|
||||
#pragma unroll
|
||||
for (uint32_t m = 0; m < MT; ++m) {
|
||||
#pragma unroll
|
||||
for (uint32_t q = 0; q < 16; ++q) acc[q][m] = fmaf(-kRbBiasF, fsum[m], acc[q][m]);
|
||||
fsum[m] = 0.0f;
|
||||
}
|
||||
nflush = 0;
|
||||
}
|
||||
} else if constexpr (UNS && MT == 1) {
|
||||
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;
|
||||
for (uint32_t e = 0; e < 4; ++e) xs[e] = __builtin_amdgcn_perm(0u, xv[0], e * 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));
|
||||
const float wsq = row_fold(q, fs);
|
||||
int d = -xsum[0];
|
||||
#pragma unroll
|
||||
for (uint32_t e = 0; e < 4; ++e)
|
||||
@@ -132,7 +252,7 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
|
||||
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));
|
||||
const float wsq = row_fold(q, fs);
|
||||
#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);
|
||||
@@ -143,58 +263,192 @@ void iqr_gemv_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restri
|
||||
}
|
||||
cur = nxt;
|
||||
}
|
||||
/* every lane's rows carry 12582912 times the factors once for each of its blocks */
|
||||
#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 */
|
||||
for (uint32_t m = 0; m < MT; ++m) acc[q][m] = r4d_wave_sum(fmaf(-kRbBiasF, fsum[m], acc[q][m]));
|
||||
if (lane == 0) {
|
||||
#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]);
|
||||
}
|
||||
}
|
||||
for (uint32_t m = 0; m < MT; ++m) s_red[wave0][q * MT + m] = 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);
|
||||
}
|
||||
__syncthreads();
|
||||
if constexpr (GATED) {
|
||||
if (tid < 16u * MT) {
|
||||
const uint32_t q = tid / MT, m = tid % MT;
|
||||
float vg = 0.0f, vu = 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) vg += s_red[w][tid];
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) vu += s_red[KW + w][tid];
|
||||
vg *= row_scale<F>(c, blockIdx.x * 16u + q);
|
||||
vu *= row_scale<F>(c, (blockIdx.x + N / 32u) * 16u + q);
|
||||
gated_put(go, m, blockIdx.x * 16u + q, vg, vu);
|
||||
}
|
||||
gated_tail(go, MT, NW);
|
||||
} else {
|
||||
if (tid < 16u * MT) {
|
||||
const uint32_t q = tid / MT, m = tid % MT;
|
||||
float v = 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) v += s_red[w][tid];
|
||||
/* each row's own scale, after its blocks' sums */
|
||||
v *= row_scale<F>(c, rt * 16u + q);
|
||||
Y[(size_t)m * N + rt * 16u + q] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the narrow tile: 8 < M <= 64 -----------------------------------------------------------
|
||||
/* ---- the narrow tile at M <= 16 -------------------------------------------------------------
|
||||
*
|
||||
* One 16-token tile: a block a 16-row weight tile, its KW waves across K as the GEMV's (wave w
|
||||
* the tile's 128-K blocks w, w + KW, ..). A wave decodes each unit and transposes it into
|
||||
* fragment order through its own LDS tile (frag), then runs the unit's eight WMMA steps against
|
||||
* the activation's fragments read straight from global memory, where the M x K activation sits
|
||||
* in L2, so the loop has no block barrier and no shared staging. Rows of the token tile past M
|
||||
* read token M - 1; their outputs are not stored.
|
||||
*
|
||||
* Under one f32 scale a row each unit's int32 sums start at 0x4B400000, so a slot read as an f32
|
||||
* is 12582912 plus its sum and one fma folds it (the prefill tile's RB 32 fold), flushed every
|
||||
* kRbFlush units; other scale forms fold the converted sum with their (row, block) scales. The
|
||||
* waves' partials are summed through LDS in ascending wave order, so the output is the product
|
||||
* within f32 rounding, not the int8 tile's bytes. */
|
||||
template <class F, uint32_t KW, bool GATED = false>
|
||||
__global__ __launch_bounds__((GATED ? 2u : 1u) * KW * kWave) R4D_WAVES(6)
|
||||
void iqr_m16_kernel(Ctx c0, const int8_t* __restrict__ X, const float* __restrict__ XS,
|
||||
uint16_t* __restrict__ Y, uint32_t N, uint32_t M, uint32_t x_ld, uint32_t xs_ld,
|
||||
GatedOut go) {
|
||||
using D = Dec<F>;
|
||||
constexpr bool BIAS = F::SC == kRowF32;
|
||||
constexpr uint32_t NW = (GATED ? 2u : 1u) * KW;
|
||||
__shared__ __attribute__((aligned(16))) int8_t s_tab[D::kTab];
|
||||
/* the waves' transpose tiles, then their partials (8 x 32 floats a wave, in its own tile) */
|
||||
__shared__ __attribute__((aligned(16))) uint8_t s_tr[NW * kTrBytes];
|
||||
static_assert(8u * kWave * 4u <= kTrBytes, "a wave's partials in its transpose tile");
|
||||
auto red = [&](uint32_t w) { return (float*)(s_tr + w * kTrBytes); };
|
||||
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1);
|
||||
const uint32_t wave0 = __builtin_amdgcn_readfirstlane(tid / kWave);
|
||||
Ctx c = c0;
|
||||
c.tab = s_tab;
|
||||
uint8_t* const tr = s_tr + wave0 * kTrBytes;
|
||||
D::stage(s_tab, c, tid, NW * kWave);
|
||||
__syncthreads();
|
||||
|
||||
/* Gated, waves KW and up take the up rows' tile, n rows below the gate rows'. */
|
||||
const uint32_t half = GATED ? wave0 / KW : 0u, wave = GATED ? wave0 % KW : wave0;
|
||||
const uint32_t rt = blockIdx.x + half * (N / 32u), row0 = rt * 16u;
|
||||
const uint32_t tok = min(frag_c(lane), M - 1u);
|
||||
const int8_t* const xrow = X + (size_t)tok * x_ld + frag_k0(lane);
|
||||
|
||||
f8v out = acc_zero();
|
||||
float corr = 0.0f; /* BIAS: the units' fold factors since the last flush */
|
||||
uint32_t nflush = 0;
|
||||
auto bload = [&](uint32_t kb, i2v (&b)[8], bool live) {
|
||||
#pragma unroll
|
||||
for (uint32_t ks = 0; ks < 8; ++ks) {
|
||||
const uint2 v = live ? *(const uint2*)(xrow + kb * kBlock + ks * kK) : make_uint2(0u, 0u);
|
||||
b[ks][0] = (int)v.x;
|
||||
b[ks][1] = (int)v.y;
|
||||
}
|
||||
};
|
||||
typename D::Raw cur = D::fetch(c, rt, wave, lane, wave < c.nkb), nxt;
|
||||
i2v bc[8], bn[8];
|
||||
bload(wave, bc, wave < c.nkb);
|
||||
for (uint32_t kb = wave; kb < c.nkb; kb += KW) {
|
||||
if (kb + KW < c.nkb) {
|
||||
nxt = D::fetch(c, rt, kb + KW, lane, true);
|
||||
bload(kb + KW, bn, true);
|
||||
}
|
||||
uint32_t w[16];
|
||||
D::rows(cur, c, rb_ratio<F>(c, row0 + (lane & 15u), kb), w);
|
||||
D::unzero(c, rt, kb, w);
|
||||
Stage8 a8[2];
|
||||
frag(w, tr, lane, a8);
|
||||
/* two chains of four steps, so a step does not wait on the one before it */
|
||||
f8v raw = rb_first<BIAS ? 32 : 0>();
|
||||
#pragma unroll
|
||||
for (uint32_t ks = 0; ks < kBlock / kK; ++ks)
|
||||
raw = mma8<true>(frag_of(a8[ks / 4u], ks % 4u), bc[ks], raw);
|
||||
const float as = XS[(size_t)tok * xs_ld + kb];
|
||||
if constexpr (BIAS) {
|
||||
const float sb = fold_f32<F>(c, row0, kb) * as;
|
||||
corr += sb;
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) out[t] = __builtin_fmaf(raw[t], sb, out[t]);
|
||||
if (++nflush == kRbFlush) {
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) out[t] = __builtin_fmaf(-kRbBiasF, corr, out[t]);
|
||||
corr = 0.0f;
|
||||
nflush = 0;
|
||||
}
|
||||
} else {
|
||||
float wsr[8];
|
||||
if constexpr (F::SC == kBf16 && F::LRB == 0) {
|
||||
/* A bf16 scale a (row, 128): the lane's eight rows are consecutive in the tile's
|
||||
* scale run (own_scale's order), 16 aligned bytes, one load. */
|
||||
const uint4 q4 = *(const uint4*)((const uint16_t*)c.S + ((size_t)rt * c.nkb + kb) * 16u +
|
||||
acc_row(lane, 0));
|
||||
const uint32_t qd[4] = { q4.x, q4.y, q4.z, q4.w };
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 4; ++t) {
|
||||
wsr[2 * t] = __uint_as_float(qd[t] << 16);
|
||||
wsr[2 * t + 1] = __uint_as_float(qd[t] & 0xFFFF0000u);
|
||||
}
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) wsr[t] = fold_f32<F>(c, row0 + acc_row(lane, t), kb);
|
||||
}
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t)
|
||||
out[t] = __builtin_fmaf(acc_val<true>(raw[t]), wsr[t] * as, out[t]);
|
||||
}
|
||||
cur = nxt;
|
||||
#pragma unroll
|
||||
for (uint32_t ks = 0; ks < 8; ++ks) bc[ks] = bn[ks];
|
||||
}
|
||||
/* each wave's partials in its own tile, behind its last transpose's reads */
|
||||
__builtin_amdgcn_fence(__ATOMIC_RELEASE, "wavefront", "local");
|
||||
__builtin_amdgcn_wave_barrier();
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) red(wave0)[t * kWave + lane] = BIAS ? __builtin_fmaf(-kRbBiasF, corr, out[t]) : out[t];
|
||||
__syncthreads();
|
||||
if constexpr (GATED) {
|
||||
if (wave0 == 0) {
|
||||
const uint32_t col = frag_c(lane);
|
||||
const uint32_t r0 = acc_row(lane, 0);
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) {
|
||||
float ag = 0.0f, au = 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) ag += red(w)[t * kWave + lane];
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) au += red(KW + w)[t * kWave + lane];
|
||||
ag *= row_scale<F>(c, blockIdx.x * 16u + r0 + t);
|
||||
au *= row_scale<F>(c, (blockIdx.x + N / 32u) * 16u + r0 + t);
|
||||
if (col < M) gated_put(go, col, blockIdx.x * 16u + r0 + t, ag, au);
|
||||
}
|
||||
}
|
||||
gated_tail(go, M, NW);
|
||||
} else if (wave == 0) {
|
||||
const uint32_t col = frag_c(lane);
|
||||
const uint32_t r0 = row0 + acc_row(lane, 0);
|
||||
float v[8];
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) {
|
||||
float a = 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t w = 0; w < KW; ++w) a += red(w)[t * kWave + lane];
|
||||
v[t] = a * row_scale<F>(c, r0 + t);
|
||||
}
|
||||
if (col < M)
|
||||
*(uint4*)(Y + (size_t)col * N + r0) = 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]));
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the narrow tile: 16 < 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
|
||||
@@ -305,6 +559,20 @@ void iqr_m64_kernel(Ctx c0, const uint8_t* __restrict__ Bp, const float* __restr
|
||||
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 if constexpr (F::SC == kBf16 && F::LRB == 0) {
|
||||
/* A bf16 scale a (row, 128): the lane's eight rows are consecutive in the
|
||||
* tile's scale run (own_scale's order), 16 aligned bytes, one load. Every row
|
||||
* of a live tile is live (rows is a multiple of 16). */
|
||||
uint4 q = make_uint4(0u, 0u, 0u, 0u);
|
||||
if (alive)
|
||||
q = *(const uint4*)((const uint16_t*)c.S +
|
||||
((size_t)(wrow0 / 16u) * c.nkb + kb) * 16u + acc_row(lane, 0));
|
||||
const uint32_t qd[4] = { q.x, q.y, q.z, q.w };
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 4; ++t) {
|
||||
wsr[2 * t] = __uint_as_float(qd[t] << 16);
|
||||
wsr[2 * t + 1] = __uint_as_float(qd[t] & 0xFFFF0000u);
|
||||
}
|
||||
} else {
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t)
|
||||
@@ -568,55 +836,82 @@ Ctx ctx_of(const Operands& g) {
|
||||
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;
|
||||
}
|
||||
|
||||
/* The GEMV, plain into `g.y`, or with `go` the gated fold (a block a gated tile, twice the waves). */
|
||||
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;
|
||||
int gemv_launch(const Operands& g, RadStream stream, const GatedOut* go = nullptr) {
|
||||
const uint32_t N = (uint32_t)g.N, M = (uint32_t)g.M;
|
||||
const Ctx c = ctx_of(g);
|
||||
const dim3 grid(gx, 1, ks);
|
||||
/* Four waves a tile where the tiles alone nearly fill the card, eight on narrow weights (M = 1,
|
||||
* 4 bits: gate_up 146.6 / 147.1 us, down 76.0 / 78.4, the 5120 x 6144 outputs 31.4 / 31.9,
|
||||
* attn_k 9.5 / 8.8). */
|
||||
const uint32_t kw = N >= 4096u ? 4u : 8u;
|
||||
const GatedOut gz = go ? *go : GatedOut{};
|
||||
uint16_t* const y = go ? nullptr : (uint16_t*)g.y->data;
|
||||
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)
|
||||
#define R4D_IQR_GV(mt_, kw_) \
|
||||
rc = go ? R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_, true>), dim3(N / 32u), \
|
||||
dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
|
||||
(const float*)g.as->data, y, N, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) \
|
||||
: R4D_EMIT(stream, (iqr_gemv_kernel<F, mt_, kw_>), dim3(N / 16u), dim3(kw_ * kWave), \
|
||||
0, c, (const int8_t*)g.a->data, (const float*)g.as->data, y, N, \
|
||||
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
|
||||
#define R4D_IQR_GVK(mt_) do { if (kw == 4u) R4D_IQR_GV(mt_, 4u); else R4D_IQR_GV(mt_, 8u); } while (0)
|
||||
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;
|
||||
case 1u: R4D_IQR_GVK(1u); break;
|
||||
case 2u: R4D_IQR_GVK(2u); break;
|
||||
case 3u: R4D_IQR_GVK(3u); break;
|
||||
case 4u: R4D_IQR_GVK(4u); break;
|
||||
case 5u: R4D_IQR_GVK(5u); break;
|
||||
case 6u: R4D_IQR_GVK(6u); break;
|
||||
case 7u: R4D_IQR_GVK(7u); break;
|
||||
case 8u: R4D_IQR_GVK(8u); break;
|
||||
default: return R4D_NO(RAD_E_SHAPE);
|
||||
}
|
||||
#undef R4D_IQR_GVK
|
||||
#undef R4D_IQR_GV
|
||||
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
|
||||
/* The 16-token tile, plain into `g.y` or gated as gemv_launch. */
|
||||
template <class F>
|
||||
int m16_launch(const Operands& g, RadStream stream, const GatedOut* go = nullptr) {
|
||||
const uint32_t N = (uint32_t)g.N, M = (uint32_t)g.M;
|
||||
const Ctx c = ctx_of(g);
|
||||
const GatedOut gz = go ? *go : GatedOut{};
|
||||
uint16_t* const y = go ? nullptr : (uint16_t*)g.y->data;
|
||||
int rc;
|
||||
#define R4D_IQR_M16(kw_) \
|
||||
rc = go ? R4D_EMIT(stream, (iqr_m16_kernel<F, kw_, true>), dim3(N / 32u), \
|
||||
dim3(2u * kw_ * kWave), 0, c, (const int8_t*)g.a->data, \
|
||||
(const float*)g.as->data, y, N, M, (uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz) \
|
||||
: R4D_EMIT(stream, (iqr_m16_kernel<F, kw_>), dim3(N / 16u), dim3(kw_ * kWave), 0, c, \
|
||||
(const int8_t*)g.a->data, (const float*)g.as->data, y, N, M, \
|
||||
(uint32_t)g.a_ld, (uint32_t)g.sa_ld, gz)
|
||||
if (N >= 4096u) R4D_IQR_M16(4u);
|
||||
else R4D_IQR_M16(8u);
|
||||
#undef R4D_IQR_M16
|
||||
return rc == RAD_OK && hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
|
||||
/* A computed trellis's GEMV pays its decode in VALU work beside every token's dot and fold, the
|
||||
* tiles decode a unit once for all tokens. Measured on gate_up (34816 x 5120): at one token the
|
||||
* GEMV wins at every width (2 / 4 / 6 bits 92.6 / 145.2 / 214.6 us, the 16-token tile at 4 / 6 bits
|
||||
* 150.0 / 215.7); at two only on 2- and 3-bit codes under one f32 scale a row, its values dotted
|
||||
* straight from their hashes (128.4 / 132.4 against the tile's 137.7 / 138.5; 4 bits 152.8 against
|
||||
* 150.1); from three tokens the tile. */
|
||||
template <class F>
|
||||
constexpr uint32_t gemv_max() {
|
||||
return F::KIND != kTrellisMad ? kGemvMaxM : F::B <= 3u && F::SC == kRowF32 ? 2u : 1u;
|
||||
}
|
||||
|
||||
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);
|
||||
if (M <= gemv_max<F>()) return gemv_launch<F>(g, stream);
|
||||
if (M <= 16u && ((uintptr_t)g.y->data & 15u) == 0u) return m16_launch<F>(g, 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);
|
||||
@@ -701,11 +996,7 @@ extern "C" int64_t r4d_rad_gemm_iqr_m64_scratch(const RadArgs* a) {
|
||||
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);
|
||||
return k2 > 1 ? (int64_t)k2 * M * N * 4 : 0;
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
|
||||
@@ -723,6 +1014,89 @@ extern "C" int r4d_rad_gemm_iqr_m64(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(RAD_E_UNSUPPORTED);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* gemm_nt_q_gated's operands at i8a8h: [0] a [1] a_scale [2] b [3] b_scale [4] q [5] scale
|
||||
* [6] out_bf16. The weight is one [N, K] IQR plane, gate rows then up rows. */
|
||||
int gated_operands(const RadArgs* a, Operands* g, GatedOut* go) {
|
||||
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 = nullptr;
|
||||
const RadTensor* q = r4d_opt(a, 4);
|
||||
const RadTensor* sc = r4d_opt(a, 5);
|
||||
const RadTensor* yb = r4d_opt(a, 6);
|
||||
if (!g->a || !g->as || !g->b || !g->bs || !q || !sc) 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 || q->dtype != RAD_I8 ||
|
||||
sc->dtype != RAD_F32 || (yb && yb->dtype != RAD_BF16))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (g->b->rank != 2 || g->a->rank < 2 || g->as->rank != 2) return R4D_NO(RAD_E_SHAPE);
|
||||
g->M = g->a->shape[0];
|
||||
g->N = g->b->shape[0];
|
||||
g->K = g->b->shape[1];
|
||||
const long long n = g->N / 2;
|
||||
if (g->M < 1 || g->M > 16 || g->N % 256 || g->K % kFK) return R4D_NO(RAD_E_SHAPE);
|
||||
g->nkb = g->K / kBlock;
|
||||
if (r4d_numel(g->a) != g->M * g->K || g->as->shape[0] != g->M || g->as->shape[1] != g->nkb)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_numel(q) != g->M * n || r4d_numel(sc) != g->M * (n / kBlock) ||
|
||||
(yb && r4d_numel(yb) != g->M * n))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
g->a_ld = r4d_row_pitch(g->a);
|
||||
g->sa_ld = r4d_row_pitch(g->as);
|
||||
const long long q_ld = r4d_row_pitch(q), s_ld = r4d_row_pitch(sc), y_ld = yb ? r4d_row_pitch(yb) : 0;
|
||||
if (g->a_ld < 0 || g->sa_ld < 0 || q_ld < 0 || s_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
if (!r4d_aligned(g->a->data, 16) || !r4d_aligned(g->b->data, 256) || !r4d_aligned(q->data, 4) ||
|
||||
q_ld % 4)
|
||||
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);
|
||||
go->Q = (int8_t*)q->data;
|
||||
go->S = (float*)sc->data;
|
||||
go->Yb = yb ? (uint16_t*)yb->data : nullptr;
|
||||
go->n = (uint32_t)n;
|
||||
go->q_ld = (uint32_t)q_ld;
|
||||
go->s_ld = (uint32_t)s_ld;
|
||||
go->y_ld = (uint32_t)y_ld;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
template <class F>
|
||||
int gated_launch(const Operands& g, const GatedOut& go, RadStream stream) {
|
||||
if (g.M <= gemv_max<F>()) return gemv_launch<F>(g, stream, &go);
|
||||
return m16_launch<F>(g, stream, &go);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int64_t r4d_rad_gemm_iqr_gated_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0);
|
||||
if (M < 1 || N < 2) return 0;
|
||||
return (int64_t)align256(M * (N / 2) * 2);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_gemm_iqr_gated(const RadArgs* a, RadStream s) {
|
||||
Operands g;
|
||||
GatedOut go;
|
||||
const int rc = gated_operands(a, &g, &go);
|
||||
if (rc != RAD_OK) return rc;
|
||||
if (!a->scratch || (long long)a->scratch_bytes < align256(g.M * (g.N / 2) * 2))
|
||||
return R4D_NO(RAD_E_SCRATCH);
|
||||
go.H = (uint16_t*)a->scratch;
|
||||
go.cnt = r4d_8a8_split_ctr(s, go.Q);
|
||||
if (!go.cnt || go.n / 128u > 8192u) return R4D_NO(RAD_E_DEVICE);
|
||||
const uint32_t kw = kernel_word(g.word);
|
||||
#define R4D_IQR_GO(...) \
|
||||
if (kw == R4D_IQR_T(__VA_ARGS__)::word()) return gated_launch<R4D_IQR_T(__VA_ARGS__)>(g, go, 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;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// H += X^T X, in f32, over an E4M3 activation with a per-(row, group) scale, or over a plain bf16
|
||||
// one.
|
||||
// H += X^T X, in f32, over an E4M3 or int8 activation with a per-(row, group) scale, or over a plain
|
||||
// bf16 one.
|
||||
//
|
||||
// Purpose: the device half of GPTQ's Gram matrix `H = sum_t x_t x_t^T` over a calibration corpus,
|
||||
// for the 4-bit expert format (docs/MOE-W4.md).
|
||||
@@ -38,6 +38,9 @@ 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;
|
||||
|
||||
// I8: the codes are int8 (an int8 trunk's activation, quant_act_i8g's), otherwise E4M3; both carry an f32
|
||||
// scale per (row, group).
|
||||
template <bool I8>
|
||||
__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,
|
||||
@@ -79,14 +82,24 @@ __global__ __launch_bounds__(kThreads) void gram_accum_kernel(
|
||||
// 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 constexpr (I8) {
|
||||
a0 = (float)(int8_t)(w & 0xffu) * s; a1 = (float)(int8_t)(w >> 8) * s;
|
||||
a2 = (float)(int8_t)(w >> 16) * s; a3 = (float)(int8_t)(w >> 24) * s;
|
||||
} else {
|
||||
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 constexpr (I8) {
|
||||
b0 = (float)(int8_t)(w & 0xffu) * s; b1 = (float)(int8_t)(w >> 8) * s;
|
||||
b2 = (float)(int8_t)(w >> 16) * s; b3 = (float)(int8_t)(w >> 24) * s;
|
||||
} else {
|
||||
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.
|
||||
@@ -216,8 +229,9 @@ extern "C" int r4d_gram_accum_fp8_tile(void) { return kTile; }
|
||||
// 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; 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, int upper, long stream) {
|
||||
namespace {
|
||||
int gram_accum_codes(bool i8, long q, long s, long h, int M, int K, int grp, 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
|
||||
@@ -227,12 +241,30 @@ 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, 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)(upper != 0));
|
||||
if (i8)
|
||||
hipLaunchKernelGGL(gram_accum_kernel<true>, 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)(upper != 0));
|
||||
else
|
||||
hipLaunchKernelGGL(gram_accum_kernel<false>, 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)(upper != 0));
|
||||
return hipGetLastError() == hipSuccess ? 0 : -4;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
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, int upper, long stream) {
|
||||
return gram_accum_codes(false, q, s, h, M, K, grp, q_ld, s_ld, h_ld, upper, stream);
|
||||
}
|
||||
|
||||
// q [M][K] int8, otherwise as r4d_gram_accum_fp8
|
||||
extern "C" int r4d_gram_accum_i8(long q, long s, long h, int M, int K, int grp,
|
||||
int q_ld, int s_ld, int h_ld, int upper, long stream) {
|
||||
return gram_accum_codes(true, q, s, h, M, K, grp, q_ld, s_ld, h_ld, upper, stream);
|
||||
}
|
||||
|
||||
// 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; `upper` as above
|
||||
@@ -260,7 +292,8 @@ extern "C" int r4d_rad_gram_accum(const RadArgs* a, RadStream s) {
|
||||
const RadTensor* sc = r4d_opt(a, GA_S);
|
||||
const RadTensor* h = r4d_opt(a, GA_H);
|
||||
if (!q || !sc || !h) return R4D_NO(RAD_E_INVAL);
|
||||
if (q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32 || h->dtype != RAD_F32)
|
||||
if ((q->dtype != RAD_F8E4M3 && q->dtype != RAD_I8) || sc->dtype != RAD_F32 ||
|
||||
h->dtype != RAD_F32)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
/* Rows are dim 0 and everything after is the row, as in r4d_rad_quant_act_fp8; `sc` and `h`
|
||||
* are rank 2 by definition. */
|
||||
@@ -274,9 +307,9 @@ extern "C" int r4d_rad_gram_accum(const RadArgs* a, RadStream s) {
|
||||
if (h->shape[0] != K || h->shape[1] != K) return R4D_NO(RAD_E_SHAPE);
|
||||
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,
|
||||
(int)r4d_geti_or(a, "upper", 0), (long)(uintptr_t)s);
|
||||
const int e = gram_accum_codes(q->dtype == RAD_I8, r4d_addr(q), r4d_addr(sc), r4d_addr(h),
|
||||
(int)M, (int)K, (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;
|
||||
}
|
||||
|
||||
|
||||
+9
-3
@@ -181,7 +181,11 @@ R4D_IQR_HD constexpr int64_t tile_major(int64_t r, int64_t kb, int64_t nkb) {
|
||||
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) \
|
||||
X(kTrellisMad, 4, 0, 16, 0, kE4m3Tensor) X(kTrellisMad, 5, 0, 16, 0, kE4m3Tensor) \
|
||||
X(kTrellisMad, 6, 0, 16, 0, kE4m3Tensor) X(kTrellisMad, 7, 0, 16, 0, kE4m3Tensor) \
|
||||
/* the computed trellis under a bf16 scale a (row, 128): the fold reads it in place */ \
|
||||
X(kTrellisMad, 4, 0, 16, 0, kBf16) X(kTrellisMad, 5, 0, 16, 0, kBf16) \
|
||||
X(kTrellisMad, 6, 0, 16, 0, kBf16) X(kTrellisMad, 7, 0, 16, 0, kBf16) \
|
||||
/* 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) \
|
||||
@@ -212,9 +216,11 @@ R4D_IQR_HD constexpr bool built(uint32_t w) {
|
||||
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(kZero, 6, 0, 0, 0, kBf16, 0) X(kZero, 7, 0, 0, 0, kBf16, 0) \
|
||||
X(kZero, 8, 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)
|
||||
X(kTrellis, 4, 0, 12, 0, kE4m3Tensor, 1) X(kTrellis, 5, 0, 12, 0, kE4m3Tensor, 1) \
|
||||
X(kTrellis, 6, 0, 12, 0, kE4m3Tensor, 1) X(kTrellis, 7, 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) \
|
||||
|
||||
+70
-20
@@ -49,13 +49,26 @@ struct Ctx {
|
||||
* rows' 8-byte fragment reads fall on distinct banks. */
|
||||
constexpr uint32_t kTrPitch = 136, kTrBytes = 16 * kTrPitch;
|
||||
|
||||
/* Bits [s, s + n) of the 64 bits hi:lo, n <= 32 (constants after unrolling). On byte bounds one
|
||||
* v_perm, which also zeroes the bytes above; else a funnel shift and a mask. */
|
||||
__device__ __forceinline__ uint32_t window(uint32_t lo, uint32_t hi, uint32_t s, uint32_t n) {
|
||||
if (s % 8u == 0u && n % 8u == 0u && n < 32u) {
|
||||
uint32_t sel = 0x0C0C0C0Cu;
|
||||
for (uint32_t i = 0; i < n / 8u; ++i) /* byte s / 8 + i of hi:lo: lo's 0-3, hi's 4-7 */
|
||||
sel = (sel & ~(0xFFu << (8u * i))) | ((s / 8u + i) << (8u * i));
|
||||
return __builtin_amdgcn_perm(hi, lo, sel);
|
||||
}
|
||||
const uint32_t m = n == 32u ? 0xFFFFFFFFu : ((1u << n) - 1u);
|
||||
return __builtin_amdgcn_alignbit(hi, lo, s) & m;
|
||||
}
|
||||
|
||||
/* `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;
|
||||
return window(d[q], q + 1u < ND ? d[q + 1u] : 0u, s, n);
|
||||
}
|
||||
|
||||
/* Low bytes of two, then of two pairs, into one dword. */
|
||||
@@ -161,9 +174,50 @@ struct Dec {
|
||||
/* 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;
|
||||
/* A trellis column's continuation: its first L - B bits in the unit above, which lie in one
|
||||
* dword of that unit's lane segment for every width (column e starts at bit 16 B e), so a lane
|
||||
* reads that dword alone of each of its four columns: p[e]. */
|
||||
static constexpr uint32_t CB = 16u * B;
|
||||
static constexpr uint32_t NP = TR ? 4u : 1u;
|
||||
static constexpr uint32_t pdw(uint32_t e) { return e * CB / 32u; }
|
||||
static constexpr uint32_t pbit(uint32_t e) { return e * CB % 32u; }
|
||||
struct Raw { uint32_t d[ND]; uint32_t p[NP]; };
|
||||
/* A trellis column's stream: its CB code bits, then its continuation, as NW dwords, which
|
||||
* its sixteen rows' states are windows of (row q's at bit q B). Built once a unit: a dword of
|
||||
* a column that does not start on a dword bound is one funnel shift or v_perm, where reading
|
||||
* each state from the lane's codes would join every state that crosses a bound, and every
|
||||
* continued one, separately. */
|
||||
static constexpr uint32_t NW = TR ? (15u * B + F::L + 31u) / 32u : 1u;
|
||||
__device__ static uint32_t colw(const Raw& r, uint32_t e, uint32_t i) {
|
||||
const uint32_t a = e * CB + 32u * i, oe = e * CB + CB;
|
||||
const uint32_t q = a >> 5, s = a & 31u;
|
||||
if (a + 32u <= oe) return s == 0u ? r.d[q] : __builtin_amdgcn_alignbit(r.d[q + 1u], r.d[q], s);
|
||||
if (a >= oe) return r.p[e] >> (pbit(e) + (a - oe));
|
||||
const uint32_t n0 = oe - a; /* the column's own last bits, then its continuation */
|
||||
if (s + n0 == 32u && pbit(e) == 0u) return __builtin_amdgcn_alignbit(r.p[e], r.d[q], s);
|
||||
if (s % 8u == 0u && n0 % 8u == 0u && pbit(e) % 8u == 0u && s + n0 <= 32u) {
|
||||
uint32_t sel = 0u;
|
||||
for (uint32_t j = 0; j < 4u; ++j) {
|
||||
const uint32_t b = j < n0 / 8u ? s / 8u + j : 4u + pbit(e) / 8u + (j - n0 / 8u);
|
||||
sel |= (b < 8u ? b : 0x0Cu) << (8u * j);
|
||||
}
|
||||
return __builtin_amdgcn_perm(r.p[e], r.d[q], sel);
|
||||
}
|
||||
return field<ND>(r.d, a, n0) | (r.p[e] >> pbit(e)) << n0;
|
||||
}
|
||||
__device__ static void columns(const Raw& r, uint32_t (&cw)[4][NW]) {
|
||||
#pragma unroll
|
||||
for (uint32_t e = 0; e < 4; ++e)
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < NW; ++i) cw[e][i] = colw(r, e, i);
|
||||
}
|
||||
/* Row q's state of column e: L bits from bit q B of the column's stream. */
|
||||
__device__ static uint32_t state(const uint32_t (&cw)[4][NW], uint32_t q, uint32_t e) {
|
||||
constexpr uint32_t L = F::L;
|
||||
const uint32_t o = q * B, i = o >> 5, s = o & 31u;
|
||||
if (s + L <= 32u) return (cw[e][i] >> s) & ((1u << L) - 1u);
|
||||
return window(cw[e][i], cw[e][i + 1u], s, L);
|
||||
}
|
||||
static constexpr bool HALF = H16 && TR && !MAD && F::LRB != 0;
|
||||
static constexpr uint32_t kTab = F::KIND == kTable ? 256u
|
||||
: GRID ? (1u << B) << F::LV
|
||||
@@ -203,9 +257,14 @@ struct Dec {
|
||||
r.d[i] = __builtin_amdgcn_alignbit(i + 1u < ND ? w[i + 1u] : 0u, w[i], sh);
|
||||
}
|
||||
if constexpr (TR) {
|
||||
static_assert(!TR || (pbit(1) + F::L - B <= 32u && pbit(2) + F::L - B <= 32u &&
|
||||
pbit(3) + F::L - B <= 32u),
|
||||
"a column's continuation in one dword");
|
||||
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);
|
||||
const uint32_t* up = (const uint32_t*)(c.W + ((size_t)rp * c.nkb + kb) * ub +
|
||||
(size_t)lane * (LANE_BITS / 8u));
|
||||
#pragma unroll
|
||||
for (uint32_t e = 0; e < 4; ++e) r.p[e] = live ? up[pdw(e)] : 0u;
|
||||
} else {
|
||||
r.p[0] = 0u;
|
||||
}
|
||||
@@ -219,19 +278,14 @@ struct Dec {
|
||||
__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];
|
||||
uint32_t st[64], cw[4][NW];
|
||||
columns(r, cw);
|
||||
#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;
|
||||
}
|
||||
for (uint32_t e = 0; e < 4; ++e) st[q * 4 + e] = state(cw, q, e);
|
||||
[[maybe_unused]] int32_t t[HALF ? 1 : 64];
|
||||
[[maybe_unused]] _Float16 th[HALF ? 64 : 1];
|
||||
if constexpr (MAD) {
|
||||
@@ -315,20 +369,16 @@ struct Dec {
|
||||
* 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];
|
||||
uint32_t cw[4][NW];
|
||||
columns(r, cw);
|
||||
#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;
|
||||
}
|
||||
for (uint32_t e = 0; e < 4; ++e) h[15u - q][e] = (__umul24(state(cw, q, e), A) + Bc) & 0x3F3F3F3Fu;
|
||||
}
|
||||
|
||||
/* Zero: the zero of row (rt*16 + q) for block kb is subtracted bytewise after `rows`. */
|
||||
|
||||
@@ -136,7 +136,8 @@ bool classify(const RadEncoding* enc, const char* tr, Form* f, int64_t* entries)
|
||||
return true;
|
||||
}
|
||||
const int b = unsigned_bits(cp.dtype);
|
||||
if (!b || b > 7) return false;
|
||||
/* eight bits only under a zero: the embedding's u8 table (no GEMM form takes it) */
|
||||
if (!b || b > 8 || (b == 8 && !rad_enc_plane(enc, "zero"))) 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)
|
||||
@@ -733,3 +734,69 @@ extern "C" int r4d_rad_unrelayout_iqr_logits(const RadParam* p, int n_p, int ope
|
||||
std::memcpy(v.aux->data, s + lm_tab(f, rows, dim), (size_t)entries);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ==================================================================== logits_gemm_vocab's classes
|
||||
*
|
||||
* Each width class of the head is a gemm_nt_q weight of its own rows (operands 1 + 3i its codes,
|
||||
* 2 + 3i its scales), stored as that row stores it, with the class's rows (`rows<i>`) and n_embd
|
||||
* as its geometry and the rotated forms (the classes are fwht128). A class's vocabulary ids
|
||||
* (3 + 3i) are read as stored. */
|
||||
namespace {
|
||||
int vocab_geom(const RadParam* p, int n_p, int operand, RadParam (&q)[4], int* il) {
|
||||
if (operand < 1 || operand > 12 || (operand - 1) % 3 == 2) return RAD_E_UNSUPPORTED;
|
||||
static const char* kRows[] = { "rows0", "rows1", "rows2", "rows3" };
|
||||
const int i = (operand - 1) / 3;
|
||||
std::memset(q, 0, sizeof q);
|
||||
q[0].key = "N";
|
||||
q[0].kind = RAD_P_INT;
|
||||
q[0].ival = r4d_pgeti_or(p, n_p, kRows[i], 0);
|
||||
q[1].key = "K";
|
||||
q[1].kind = RAD_P_INT;
|
||||
q[1].ival = r4d_pgeti_or(p, n_p, "n_embd", 0);
|
||||
q[2].key = "group";
|
||||
q[2].kind = RAD_P_INT;
|
||||
q[2].ival = 128;
|
||||
q[3].key = "dtype";
|
||||
q[3].kind = RAD_P_STR;
|
||||
q[3].sval = "i8a8h";
|
||||
*il = (operand - 1) % 3 == 0 ? IL_B : IL_BSCALE;
|
||||
return RAD_OK;
|
||||
}
|
||||
} /* namespace */
|
||||
|
||||
extern "C" int r4d_rad_layout_iqr_vocab(const RadParam* p, int n_p, int operand,
|
||||
const RadEncoding* enc, const int* sel, const RadTensor* pl,
|
||||
int n, RadLayout* out) {
|
||||
RadParam q[4];
|
||||
int il = 0;
|
||||
const int rc = vocab_geom(p, n_p, operand, q, &il);
|
||||
if (rc != RAD_OK) return rc;
|
||||
Form f;
|
||||
int64_t entries = 0;
|
||||
if (!classify(enc, "fwht128", &f, &entries) || f.kind != kTrellisMad || f.scale != kRowF32 ||
|
||||
f.lrb != 0 || f.lrun != 8)
|
||||
return RAD_E_DTYPE;
|
||||
return r4d_rad_layout_iqr(q, 4, il, enc, sel, pl, n, out);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_relayout_iqr_vocab(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) {
|
||||
RadParam q[4];
|
||||
int il = 0;
|
||||
const int rc = vocab_geom(p, n_p, operand, q, &il);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return r4d_rad_relayout_iqr(q, 4, il, enc, sel, pl, n, dst, dst_bytes);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_unrelayout_iqr_vocab(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) {
|
||||
RadParam q[4];
|
||||
int il = 0;
|
||||
const int rc = vocab_geom(p, n_p, operand, q, &il);
|
||||
if (rc != RAD_OK) return rc;
|
||||
return r4d_rad_unrelayout_iqr(q, 4, il, enc, sel, src, src_bytes, pl, n);
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
// logits_gemm_vocab: the lm_head stored as width classes of the vocabulary's rows, each an IQR
|
||||
// computed trellis (r4d_iqr.h: tcq_code=mad, one f32 scale a row under a factor a 128-K block,
|
||||
// fwht128) decoded where it is read.
|
||||
//
|
||||
// KL weighs a head row by its token's probability, so a vocabulary-weighted head gives the likely
|
||||
// tokens' rows more bits than the rare ones'. The rows are sorted into classes of one code width
|
||||
// each (whole 256-row trellis runs), every class a weight of its own whose rows each carry their
|
||||
// vocabulary id, and the logits come out in vocabulary order: nothing after the head knows the rows
|
||||
// were permuted. Stored at its id from the tile, a logit in a random row order is a write to a line
|
||||
// of its own (+120 us of 760 at 8 tokens, +970 of 2350 at 64). So within a class the rows are in
|
||||
// ascending id (the converter's order; a class's rows share a width, so their order is free), and
|
||||
// above 32 tokens the tile stores at the ids directly, the large narrow class's rows then nearly
|
||||
// contiguous; up to 32 it writes a staging plane in row order and a gather through `vrow` (each
|
||||
// id's class and row) puts it in vocabulary order, cheaper there by the narrow classes' scattered
|
||||
// rows (626 / 646 us against 668 / 706 at 8 / 16 tokens; 1618 against 1559 at 64). A rank's rows of
|
||||
// each class hold only ids of that rank's share (an id outside it is dropped), so the head shards by
|
||||
// rows as any lm_head does.
|
||||
//
|
||||
// The activation is the head's bf16 input rotated by the unnormalised Hadamard per 128 of K (the
|
||||
// rotation the codes were quantised under) and held at sixteen bits: one f32 scale a (token, 128)
|
||||
// over integers q = 128 hi + lo, |q| <= 127 * 128, hi and lo int8. The int8 grid the trunk's GEMMs
|
||||
// use costs the head 2e-5 KL on its own (half the weighted head's quantisation cost); sixteen bits
|
||||
// are below bf16's rounding. Each 128-K block's dot is then two int8 WMMA passes over the same
|
||||
// decoded weight fragments, hi then lo, the first scaled by 128 in the accumulator: an exact
|
||||
// integer per (row, token, block), folded once into f32.
|
||||
//
|
||||
// One launch covers every class: a block finds its class among the classes' row ranges (the
|
||||
// widest first, so the narrow classes' cheaper blocks fill the tail) and runs that width's
|
||||
// decoder. A class of one width alone would leave most of the card idle (the widest is a few
|
||||
// thousand rows).
|
||||
|
||||
#include "r4d.h"
|
||||
#include "r4d_args.h"
|
||||
#include "r4d_emit.h"
|
||||
#include "r4d_fp8_wmma.h"
|
||||
#include "r4d_fwht.h"
|
||||
#include "r4d_iqr.h"
|
||||
#include "r4d_iqr_dec.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
namespace {
|
||||
|
||||
using namespace r4d_fp8;
|
||||
using namespace r4d_iqr;
|
||||
using namespace r4d_iqr_dev;
|
||||
|
||||
constexpr uint32_t kWave = 32, kBlock = 128, kFK = 256;
|
||||
constexpr uint32_t kMaxClass = 4;
|
||||
/* Tokens a pass of the tile: four 16-token tiles. More tokens are taken in passes, each reading
|
||||
* the head once (a prefill wants one row's logits; the all-position logits of a KL evaluation are
|
||||
* the case this serves). */
|
||||
constexpr uint32_t kPassTok = 64;
|
||||
/* |q| <= 127 * 128: hi = round(q / 128) stays in int8, lo = q - 128 hi in [-64, 64]. */
|
||||
constexpr float kQMax = 16256.0f;
|
||||
|
||||
/* One width class, as the launch sees it. */
|
||||
struct Cls {
|
||||
const uint8_t* W; /* the IQR weight buffer (codes, then the computed code's A and B) */
|
||||
const uint8_t* S; /* its scale buffer: the rows' f32 scales, then the blocks' factors */
|
||||
uint32_t N; /* rows */
|
||||
uint32_t bits; /* code width */
|
||||
const int32_t* ids; /* the vocabulary id of each row, global, ascending */
|
||||
uint32_t blk0; /* the first grid block of this class */
|
||||
uint32_t row0; /* its first row in the classes' row order (the staging plane's) */
|
||||
};
|
||||
struct Head {
|
||||
Cls c[kMaxClass]; /* widest first */
|
||||
uint32_t n; /* classes */
|
||||
uint32_t nkb; /* K / 128 */
|
||||
int32_t off; /* this rank's first vocabulary id */
|
||||
uint32_t n_vocab; /* this rank's share */
|
||||
};
|
||||
|
||||
/* ---- the activation: rotated, sixteen bits as two int8 planes ------------------------------
|
||||
*
|
||||
* A wave a (token, 128-K block): each lane's four values through r4d_fwht_wave, the block's
|
||||
* absolute maximum, then q = rint(x * kQMax / amax). An all-zero block stores zeros under scale 0. */
|
||||
__global__ __launch_bounds__(kWave) void vocab_quant_kernel(const uint16_t* __restrict__ X,
|
||||
uint32_t x_ld, int8_t* __restrict__ XH,
|
||||
int8_t* __restrict__ XL,
|
||||
float* __restrict__ XS, uint32_t K) {
|
||||
const uint32_t m = blockIdx.x, kb = blockIdx.y, lane = threadIdx.x;
|
||||
const uint32_t nkb = K / kBlock;
|
||||
const uint2 raw = *(const uint2*)(X + (size_t)m * x_ld + kb * kBlock + 4u * lane);
|
||||
float v[4] = { __uint_as_float(raw.x << 16), __uint_as_float(raw.x & 0xFFFF0000u),
|
||||
__uint_as_float(raw.y << 16), __uint_as_float(raw.y & 0xFFFF0000u) };
|
||||
r4d_fwht_wave<128>(v, (int)lane);
|
||||
float a = 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < 4; ++i) a = fmaxf(a, fabsf(v[i]));
|
||||
a = r4d_wave_max(a);
|
||||
const float inv = a > 0.0f ? kQMax / a : 0.0f;
|
||||
uint32_t hp = 0, lp = 0;
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < 4; ++i) {
|
||||
const int q = (int)fminf(fmaxf(rintf(v[i] * inv), -kQMax), kQMax);
|
||||
const int hi = (q + 64) >> 7, lo = q - (hi << 7);
|
||||
hp |= ((uint32_t)hi & 0xFFu) << (8u * i);
|
||||
lp |= ((uint32_t)lo & 0xFFu) << (8u * i);
|
||||
}
|
||||
const size_t o = (size_t)m * K + kb * kBlock + 4u * lane;
|
||||
*(uint32_t*)(XH + o) = hp;
|
||||
*(uint32_t*)(XL + o) = lp;
|
||||
if (lane == 0) XS[(size_t)m * nkb + kb] = a / kQMax;
|
||||
}
|
||||
|
||||
/* ---- vocabulary order through the staging plane ---------------------------------------
|
||||
*
|
||||
* `vrow` is the head's inverse map, one word a vocabulary id: its class's code width in the top four
|
||||
* bits and its row in the class's whole tensor below, of which this rank holds rows
|
||||
* [rank * rows, (rank + 1) * rows). A row's tokens are one contiguous read, consecutive ids
|
||||
* consecutive writes. A staging row is `mp` floats (16-byte aligned). */
|
||||
__global__ void vocab_gather_kernel(Head h, const float* __restrict__ st,
|
||||
const int32_t* __restrict__ vrow, float* __restrict__ out,
|
||||
uint32_t c_ld, uint32_t mp, uint32_t nb) {
|
||||
const uint32_t v = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (v >= h.n_vocab) return;
|
||||
const uint32_t w = (uint32_t)vrow[v], b = w >> 28, rank = (uint32_t)h.off / h.n_vocab;
|
||||
uint32_t rc = 0, r0 = 0;
|
||||
#pragma unroll
|
||||
for (uint32_t k = 0; k < kMaxClass; ++k)
|
||||
if (k < h.n && h.c[k].bits == b) { rc = h.c[k].N; r0 = h.c[k].row0; }
|
||||
const uint32_t j = (w & 0x0FFFFFFFu) - rank * rc;
|
||||
const bool ok = j < rc;
|
||||
const float4* const src = (const float4*)(st + (size_t)(ok ? r0 + j : 0u) * mp);
|
||||
for (uint32_t m4 = 0; m4 < nb; m4 += 4) {
|
||||
float4 q = src[m4 / 4];
|
||||
if (!ok) q = make_float4(0.0f, 0.0f, 0.0f, 0.0f);
|
||||
const float qv[4] = { q.x, q.y, q.z, q.w };
|
||||
#pragma unroll
|
||||
for (uint32_t i = 0; i < 4; ++i)
|
||||
if (m4 + i < nb) out[(size_t)(m4 + i) * c_ld + v] = qv[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the decoder ---------------------------------------------------------------------------
|
||||
*
|
||||
* r4d_iqr_dec.h's for the computed trellis under one scale a row, with the continuation read
|
||||
* compactly: a column's stream is 16 B bits, so each of a lane's four columns starts at bit 0 or
|
||||
* 16 of a dword, and the at most 15 bits a row's state takes from the unit above lie in that one
|
||||
* dword: four dword loads a unit, where Dec reads the unit above's whole segment again (fourteen
|
||||
* dwords at seven bits). */
|
||||
template <uint32_t B>
|
||||
struct HeadDec {
|
||||
static constexpr uint32_t L = 16, LANE_BITS = 64u * B, ND = LANE_BITS / 32u, CB = 16u * B;
|
||||
struct Raw { uint32_t d[ND]; uint32_t p[4]; };
|
||||
|
||||
__device__ static Raw fetch(const uint8_t* W, uint32_t nkb, uint32_t rt, uint32_t kb,
|
||||
uint32_t lane, bool live) {
|
||||
Raw r;
|
||||
constexpr size_t ub = 4u * LANE_BITS;
|
||||
load_dw<ND>(r.d, W + ((size_t)rt * nkb + kb) * ub + lane * (LANE_BITS / 8u), live);
|
||||
/* the unit above in the run of 256 rows (16 tiles), tail-biting at the run's first */
|
||||
const uint32_t rp = rt % 16u == 0u ? rt + 15u : rt - 1u;
|
||||
const uint32_t* up = (const uint32_t*)(W + ((size_t)rp * nkb + kb) * ub + lane * (LANE_BITS / 8u));
|
||||
#pragma unroll
|
||||
for (uint32_t e = 0; e < 4; ++e) r.p[e] = live ? up[e * CB / 32u] : 0u;
|
||||
return r;
|
||||
}
|
||||
|
||||
/* The lane's four values of each of the tile's 16 rows, packed: bytesum((st * A + Bc) &
|
||||
* 0x3F3F3F3F) - 126 a state. */
|
||||
__device__ static void rows(const Raw& r, uint32_t A, uint32_t Bc, uint32_t (&w)[16]) {
|
||||
/* a row's four values packed as soon as they are computed: the tile's NT accumulators
|
||||
* leave no room for all 64 at once */
|
||||
#pragma unroll
|
||||
for (uint32_t q = 0; q < 16; ++q) {
|
||||
uint32_t t[4];
|
||||
#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) |
|
||||
((r.p[e] >> ((e * CB) & 31u)) & ((1u << (L - own)) - 1u)) << own;
|
||||
const uint32_t h = (__umul24(st, A) + Bc) & 0x3F3F3F3Fu;
|
||||
t[e] = (uint32_t)__builtin_amdgcn_sudot4(false, (int)h, false, 0x01010101, -126, false);
|
||||
}
|
||||
w[15u - q] = pack4(pack2(t[0], t[1]), pack2(t[2], t[3]));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/* ---- the tile ------------------------------------------------------------------------------
|
||||
*
|
||||
* gemm_iqr_nt_m64's narrow tile (r4d_gemm_iqr.hip) without the K split: MW waves a block, a wave
|
||||
* one 16-row tile of its class against NT 16-token tiles whose hi and lo planes are staged through
|
||||
* LDS a 256-K chunk at a time. Each unit's codes are fetched a chunk ahead, decoded to int8 and
|
||||
* transposed into fragment order through the wave's LDS tile, then used by both planes' WMMA
|
||||
* steps. */
|
||||
template <uint32_t NT>
|
||||
struct Lds {
|
||||
static constexpr uint32_t FN = NT * 16, kB = FN * lds_pitch<kFK>();
|
||||
};
|
||||
|
||||
template <class F, uint32_t NT, uint32_t MW, bool STAGE>
|
||||
__device__ __forceinline__ void vocab_tile(const Head& h, const Cls& cl, uint32_t bx,
|
||||
const int8_t* __restrict__ XH,
|
||||
const int8_t* __restrict__ XL,
|
||||
const float* __restrict__ XS, float* __restrict__ out,
|
||||
uint32_t c_ld, uint32_t nb, uint8_t* s_bh,
|
||||
uint8_t* s_bl, uint8_t* s_tr) {
|
||||
using D = HeadDec<F::B>;
|
||||
static_assert(F::KIND == kTrellisMad && F::LRB == 0 && F::SC == kRowF32 && F::L == 16,
|
||||
"a computed trellis, one scale a row");
|
||||
constexpr uint32_t FK = kFK, FN = NT * 16, kU = FK / kBlock;
|
||||
const uint32_t tid = threadIdx.x, lane = tid & (kWave - 1), wave = tid / kWave;
|
||||
const uint32_t K = h.nkb * kBlock;
|
||||
|
||||
Ctx c{};
|
||||
c.W = cl.W;
|
||||
c.S = cl.S;
|
||||
c.N = cl.N;
|
||||
c.nkb = h.nkb;
|
||||
c.run_tiles = 256u / 16u;
|
||||
uint8_t* const tr = s_tr + wave * kTrBytes;
|
||||
|
||||
const uint32_t m0 = bx * MW * 16u, n0 = blockIdx.y * FN;
|
||||
const uint32_t wrow0 = m0 + wave * 16u;
|
||||
const uint32_t arow = wrow0 / 16u;
|
||||
const bool alive = wrow0 < cl.N;
|
||||
|
||||
f8v raw[NT], acc[NT];
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) { raw[j] = acc_zero(); acc[j] = acc_zero(); }
|
||||
|
||||
/* Staging: kTPR threads a token row of a chunk, both planes. */
|
||||
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* const hsrc = (const uint8_t*)XH + (size_t)(n0 + sn) * K + sk;
|
||||
const uint8_t* const lsrc = (const uint8_t*)XL + (size_t)(n0 + sn) * K + sk;
|
||||
|
||||
Stage8 ph[kBP], pl[kBP];
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kBP; ++p) {
|
||||
const uint32_t r = sn + p * kRPP;
|
||||
const bool live = r < FN && n0 + r < nb;
|
||||
ph[p] = stage8_load(hsrc + (size_t)p * kRPP * K, live);
|
||||
pl[p] = stage8_load(lsrc + (size_t)p * kRPP * K, live);
|
||||
}
|
||||
typename D::Raw pf[kU], pfn[kU];
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kU; ++p) pf[p] = D::fetch(c.W, c.nkb, arow, p, lane, alive);
|
||||
/* the computed code's A and B, after its 2^16 values (kept for the unrelayout) */
|
||||
constexpr Form fm{ F::KIND, F::B, F::LV, F::L, F::LRB, F::SC, 0 };
|
||||
const uint32_t* const ab = (const uint32_t*)(c.W + aux_off(fm, c.N, (int64_t)K) + (1 << 16));
|
||||
const uint32_t mA = ab[0], mB = ab[1];
|
||||
|
||||
for (uint32_t k0 = 0; k0 < K; k0 += 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_bh, r, sk, ph[p]);
|
||||
stage8_store<FK>(s_bl, r, sk, pl[p]);
|
||||
}
|
||||
}
|
||||
__syncthreads();
|
||||
const uint32_t k1 = k0 + FK;
|
||||
if (k1 < K) {
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kBP; ++p) {
|
||||
const uint32_t r = sn + p * kRPP;
|
||||
const bool live = r < FN && n0 + r < nb;
|
||||
if (r < FN) {
|
||||
ph[p] = stage8_load(hsrc + (size_t)p * kRPP * K + k1, live);
|
||||
pl[p] = stage8_load(lsrc + (size_t)p * kRPP * K + k1, live);
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kU; ++p) pfn[p] = D::fetch(c.W, c.nkb, arow, k1 / kBlock + p, lane, alive);
|
||||
}
|
||||
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kU; ++p) {
|
||||
const uint32_t kb = k0 / kBlock + p;
|
||||
uint32_t w[16];
|
||||
D::rows(pf[p], mA, mB, w);
|
||||
Stage8 a8[2];
|
||||
frag(w, tr, lane, a8);
|
||||
/* hi: 128 times its sum, exactly, in the accumulator; then lo on top */
|
||||
#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);
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) raw[j] = mma8<true>(af, frag<FK>(s_bh, j * 16, ks, lane), raw[j]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j)
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t)
|
||||
raw[j][t] = __int_as_float(__float_as_int(raw[j][t]) << 7);
|
||||
#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);
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) raw[j] = mma8<true>(af, frag<FK>(s_bl, j * 16, ks, lane), raw[j]);
|
||||
}
|
||||
/* the block's factor (shared by every row) times each token's activation scale */
|
||||
const float f = alive ? fold_f32<F>(c, wrow0, kb) : 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) {
|
||||
const uint32_t tok = brow0 + j * 16;
|
||||
const float ws = tok < nb ? f * XS[(size_t)tok * h.nkb + kb] : 0.0f;
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) {
|
||||
acc[j][t] = fmaf(acc_val<true>(raw[j][t]), ws, acc[j][t]);
|
||||
raw[j][t] = 0.0f;
|
||||
}
|
||||
}
|
||||
}
|
||||
#pragma unroll
|
||||
for (uint32_t p = 0; p < kU; ++p) pf[p] = pfn[p];
|
||||
__syncthreads();
|
||||
}
|
||||
|
||||
/* A lane's eight accumulator rows are consecutive rows of the wave's tile, of one token: their
|
||||
* row scales and ids are two 16-byte loads each. STAGE: the logits go to the staging plane in
|
||||
* the classes' row order, `c_ld` (the pass's tokens rounded up to four) a row, a wave's rows
|
||||
* then a few consecutive lines; else each goes to its id. */
|
||||
if (!alive) return;
|
||||
const uint32_t r0 = wrow0 + acc_row(lane, 0);
|
||||
const float4 sa = *(const float4*)((const float*)cl.S + r0), sb = *(const float4*)((const float*)cl.S + r0 + 4);
|
||||
const float rs[8] = { sa.x, sa.y, sa.z, sa.w, sb.x, sb.y, sb.z, sb.w };
|
||||
if constexpr (STAGE) {
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) {
|
||||
const uint32_t tok = brow0 + j * 16;
|
||||
if (tok >= nb) continue;
|
||||
float* const o = out + (size_t)(cl.row0 + r0) * c_ld + tok;
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) o[(size_t)t * c_ld] = acc[j][t] * rs[t];
|
||||
}
|
||||
} else {
|
||||
const int4 ia = *(const int4*)(cl.ids + r0), ib = *(const int4*)(cl.ids + r0 + 4);
|
||||
const int32_t id[8] = { ia.x, ia.y, ia.z, ia.w, ib.x, ib.y, ib.z, ib.w };
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < NT; ++j) {
|
||||
const uint32_t tok = brow0 + j * 16;
|
||||
if (tok >= nb) continue;
|
||||
float* const o = out + (size_t)tok * c_ld;
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < 8; ++t) {
|
||||
const uint32_t v = (uint32_t)(id[t] - h.off);
|
||||
if (v < h.n_vocab) o[v] = acc[j][t] * rs[t];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <uint32_t B>
|
||||
using VF = FormT<kTrellisMad, B, 0, 16, 0, kRowF32>;
|
||||
|
||||
/* The widths the classes may have: the computed trellis's built row forms. */
|
||||
#define R4D_VOCAB_BITS(X) X(2) X(3) X(4) X(5) X(6) X(7)
|
||||
|
||||
/* Six waves a SIMD: 4 and 8 measure within 2% of it at every width (M = 1 .. 64). */
|
||||
template <uint32_t NT, uint32_t MW, bool STAGE>
|
||||
__global__ __launch_bounds__(MW * kWave) R4D_WAVES(6)
|
||||
void vocab_tile_kernel(Head h, const int8_t* __restrict__ XH, const int8_t* __restrict__ XL,
|
||||
const float* __restrict__ XS, float* __restrict__ out, uint32_t c_ld,
|
||||
uint32_t nb) {
|
||||
__shared__ __attribute__((aligned(16))) uint8_t s_bh[Lds<NT>::kB];
|
||||
__shared__ __attribute__((aligned(16))) uint8_t s_bl[Lds<NT>::kB];
|
||||
__shared__ __attribute__((aligned(16))) uint8_t s_tr[MW * kTrBytes];
|
||||
/* the block's class: the last whose first block is at or below this one (uniform), copied
|
||||
* at constant indices so the argument block is never indexed at run time */
|
||||
Cls cl = h.c[0];
|
||||
#pragma unroll
|
||||
for (uint32_t i = 1; i < kMaxClass; ++i)
|
||||
if (i < h.n && blockIdx.x >= h.c[i].blk0) cl = h.c[i];
|
||||
const uint32_t bx = blockIdx.x - cl.blk0;
|
||||
switch (cl.bits) {
|
||||
#define R4D_VOCAB_CASE(b) \
|
||||
case b: vocab_tile<VF<b>, NT, MW, STAGE>(h, cl, bx, XH, XL, XS, out, c_ld, nb, s_bh, s_bl, s_tr); \
|
||||
break;
|
||||
R4D_VOCAB_BITS(R4D_VOCAB_CASE)
|
||||
#undef R4D_VOCAB_CASE
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
constexpr uint32_t kMW = 8;
|
||||
|
||||
struct Operands {
|
||||
const RadTensor* x = nullptr;
|
||||
const RadTensor* y = nullptr;
|
||||
const RadTensor *w[kMaxClass] = {}, *s[kMaxClass] = {}, *r[kMaxClass] = {}, *vrow = nullptr;
|
||||
long long M = 0, K = 0, rows[kMaxClass] = {};
|
||||
uint32_t n = 0;
|
||||
};
|
||||
|
||||
/* Operand order: x, then (w, s, ids) a class, the inverse map, the logits (r4d_rows.cpp's
|
||||
* oLogitsVocab). */
|
||||
constexpr int kOpX = 0, kOpMap = 1 + 3 * (int)kMaxClass, kOpY = kOpMap + 1;
|
||||
|
||||
int operands(const RadArgs* a, Operands* g) {
|
||||
g->x = r4d_opt(a, kOpX);
|
||||
g->y = r4d_opt(a, kOpY);
|
||||
if (!g->x || !g->y) return R4D_NO(RAD_E_INVAL);
|
||||
if (g->x->dtype != RAD_BF16 || g->y->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE);
|
||||
if (g->x->rank < 2 || g->y->rank < 2) return R4D_NO(RAD_E_SHAPE);
|
||||
g->M = g->x->shape[0];
|
||||
g->K = r4d_geti_or(a, "n_embd", 0);
|
||||
if (g->M < 1 || g->K < kFK || g->K % kFK || r4d_numel(g->x) != g->M * g->K)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (g->y->shape[0] < g->M) return R4D_NO(RAD_E_SHAPE);
|
||||
static const char* kRows[kMaxClass] = { "rows0", "rows1", "rows2", "rows3" };
|
||||
for (uint32_t i = 0; i < kMaxClass; ++i) {
|
||||
const RadTensor* w = r4d_opt(a, 1 + 3 * (int)i);
|
||||
const RadTensor* s = r4d_opt(a, 2 + 3 * (int)i);
|
||||
const RadTensor* r = r4d_opt(a, 3 + 3 * (int)i);
|
||||
const long long n = r4d_geti_or(a, kRows[i], 0);
|
||||
if (!w && !s && !r && n == 0) break;
|
||||
if (!w || !s || !r || n < 256 || n % 256) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!is_weight_dtype(w->dtype) || !is_scale_dtype(s->dtype) || r->dtype != RAD_I32)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const uint32_t word = w->dtype & kWordMask;
|
||||
const Form f = form(word);
|
||||
if ((s->dtype & kWordMask) != word || f.kind != kTrellisMad || f.L != 16 || f.lrb != 0 ||
|
||||
f.scale != kRowF32 || f.lrun != 8 || f.bits < 2 || f.bits > 7)
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (w->shape[0] != n || w->shape[1] != g->K || r4d_numel(r) != n) return R4D_NO(RAD_E_SHAPE);
|
||||
if (!r4d_aligned(w->data, 256) || !r4d_aligned(s->data, 16) || !r4d_aligned(r->data, 16))
|
||||
return R4D_NO(RAD_E_ALIGN);
|
||||
g->w[i] = w;
|
||||
g->s[i] = s;
|
||||
g->r[i] = r;
|
||||
g->rows[i] = n;
|
||||
g->n = i + 1;
|
||||
}
|
||||
if (g->n == 0) return R4D_NO(RAD_E_INVAL);
|
||||
g->vrow = r4d_opt(a, kOpMap);
|
||||
if (!g->vrow || g->vrow->dtype != RAD_I32 || r4d_numel(g->vrow) != r4d_geti_or(a, "n_vocab", -1))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
if (r4d_row_pitch(g->x) != g->K) return R4D_NO(RAD_E_STRIDE);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The staging plane's tokens: a pass of up to this many stages, a larger one stores directly
|
||||
* (staging 48 tokens measured 1175 us against the direct store's 1062 at 33). */
|
||||
constexpr uint32_t kStageTok = 32;
|
||||
|
||||
/* Scratch: the two int8 planes and the scales for every token, then the staging plane. */
|
||||
long long scratch_bytes(long long M, long long K, long long rows) {
|
||||
return 2 * align256(M * K) + align256(M * (K / kBlock) * 4) + align256(rows * kStageTok * 4);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" int64_t r4d_rad_logits_gemm_vocab_scratch(const RadArgs* a) {
|
||||
const long long M = r4d_geti_or(a, "M", 0), K = r4d_geti_or(a, "n_embd", 0);
|
||||
static const char* kRows[kMaxClass] = { "rows0", "rows1", "rows2", "rows3" };
|
||||
long long rows = 0;
|
||||
for (const char* k : kRows) rows += r4d_geti_or(a, k, 0);
|
||||
if (M < 1 || K < 1) return 0;
|
||||
return (int64_t)scratch_bytes(M, K, rows);
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_logits_gemm_vocab(const RadArgs* a, RadStream s) {
|
||||
Operands g;
|
||||
const int rc = operands(a, &g);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const long long M = g.M, K = g.K, nkb = K / kBlock;
|
||||
long long rows = 0;
|
||||
for (uint32_t i = 0; i < g.n; ++i) rows += g.rows[i];
|
||||
if (!a->scratch || (long long)a->scratch_bytes < scratch_bytes(M, K, rows))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
int8_t* const xh = (int8_t*)a->scratch;
|
||||
int8_t* const xl = xh + align256(M * K);
|
||||
float* const xs = (float*)(xl + align256(M * K));
|
||||
float* const stg = (float*)((uint8_t*)xs + align256(M * (K / kBlock) * 4));
|
||||
|
||||
Head h{};
|
||||
h.n = g.n;
|
||||
h.nkb = (uint32_t)nkb;
|
||||
h.off = (int32_t)r4d_geti_or(a, "vocab_offset", 0);
|
||||
h.n_vocab = (uint32_t)r4d_geti_or(a, "n_vocab", 0);
|
||||
const long long c_ld = r4d_row_pitch(g.y);
|
||||
if (h.n_vocab < 1 || c_ld < (long long)h.n_vocab) return R4D_NO(RAD_E_SHAPE);
|
||||
/* the widest class first: the narrow classes' cheaper blocks then fill the tail */
|
||||
uint32_t ord[kMaxClass];
|
||||
for (uint32_t i = 0; i < g.n; ++i) ord[i] = i;
|
||||
std::sort(ord, ord + g.n, [&](uint32_t x, uint32_t y) {
|
||||
return form(g.w[x]->dtype & kWordMask).bits > form(g.w[y]->dtype & kWordMask).bits;
|
||||
});
|
||||
uint32_t blocks = 0;
|
||||
for (uint32_t i = 0; i < g.n; ++i) {
|
||||
const uint32_t k = ord[i];
|
||||
Cls& c = h.c[i];
|
||||
c.W = (const uint8_t*)g.w[k]->data;
|
||||
c.S = (const uint8_t*)g.s[k]->data;
|
||||
c.ids = (const int32_t*)g.r[k]->data;
|
||||
c.N = (uint32_t)g.rows[k];
|
||||
c.bits = form(g.w[k]->dtype & kWordMask).bits;
|
||||
c.blk0 = blocks;
|
||||
c.row0 = blocks * kMW * 16u;
|
||||
blocks += c.N / (kMW * 16u);
|
||||
}
|
||||
|
||||
if (R4D_EMIT(s, vocab_quant_kernel, dim3((uint32_t)M, (uint32_t)nkb), dim3(kWave), 0,
|
||||
(const uint16_t*)g.x->data, (uint32_t)K, xh, xl, xs, (uint32_t)K) != RAD_OK)
|
||||
return R4D_NO(RAD_E_DEVICE);
|
||||
for (long long t0 = 0; t0 < M; t0 += kPassTok) {
|
||||
const uint32_t nb = (uint32_t)std::min<long long>(kPassTok, M - t0);
|
||||
const uint32_t nt = nb > 48 ? 4u : nb > 32 ? 3u : nb > 16 ? 2u : 1u;
|
||||
const dim3 grid(blocks, 1, 1);
|
||||
const int8_t* const ph = xh + t0 * K;
|
||||
const int8_t* const pl = xl + t0 * K;
|
||||
const float* const ps = xs + t0 * nkb;
|
||||
const bool stage = nb <= kStageTok;
|
||||
const uint32_t mp = (nb + 3u) / 4u * 4u;
|
||||
float* const po = stage ? stg : (float*)g.y->data + t0 * c_ld;
|
||||
const uint32_t ld = stage ? mp : (uint32_t)c_ld;
|
||||
int e;
|
||||
#define R4D_VOCAB_GO(nt_, st_) \
|
||||
e = R4D_EMIT(s, (vocab_tile_kernel<nt_, kMW, st_>), grid, dim3(kMW * kWave), 0, h, ph, pl, \
|
||||
ps, po, ld, nb)
|
||||
if (nt == 4u) R4D_VOCAB_GO(4u, false);
|
||||
else if (nt == 3u) R4D_VOCAB_GO(3u, false);
|
||||
else if (nt == 2u) R4D_VOCAB_GO(2u, true);
|
||||
else R4D_VOCAB_GO(1u, true);
|
||||
#undef R4D_VOCAB_GO
|
||||
if (e != RAD_OK) return R4D_NO(RAD_E_DEVICE);
|
||||
if (stage && R4D_EMIT(s, vocab_gather_kernel, dim3((h.n_vocab + 255u) / 256u), dim3(256), 0,
|
||||
h, (const float*)stg, (const int32_t*)g.vrow->data,
|
||||
(float*)g.y->data + t0 * c_ld, (uint32_t)c_ld, mp, nb) != RAD_OK)
|
||||
return R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
return hipGetLastError() == hipSuccess ? RAD_OK : R4D_NO(RAD_E_DEVICE);
|
||||
}
|
||||
@@ -441,6 +441,7 @@ int r4d_rad_gdn_recurrent_update(const RadArgs*, RadStream);
|
||||
/* gdn_conv_update folded into the recurrent update's prologue for the decode shape; q/k/v are
|
||||
* never written (r4d_gdn_recurrent_update_k128_v128_bf16_fp32state.hip). */
|
||||
int r4d_rad_gdn_conv_recurrent_update(const RadArgs*, RadStream);
|
||||
int r4d_rad_gdn_conv_recurrent_update_had(const RadArgs*, RadStream);
|
||||
int r4d_rad_gdn_gated_rmsnorm (const RadArgs*, RadStream);
|
||||
int r4d_rad_dflash_conv (const RadArgs*, RadStream);
|
||||
int r4d_rad_dflash_select (const RadArgs*, RadStream);
|
||||
@@ -622,6 +623,9 @@ 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);
|
||||
/* `logits_gemm_vocab`: the head as width classes of the vocabulary's rows (r4d_logits_vocab.hip). */
|
||||
int r4d_rad_logits_gemm_vocab(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_logits_gemm_vocab_scratch(const RadArgs*);
|
||||
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);
|
||||
@@ -629,6 +633,8 @@ 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_gated(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_gemm_iqr_gated_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);
|
||||
@@ -642,6 +648,7 @@ int r4d_rad_gated_quant_fp8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_gated_had_quant_fp8(const RadArgs*, RadStream);
|
||||
int r4d_rad_gated_had_quant_i8g(const RadArgs*, RadStream);
|
||||
int r4d_rad_gate_quant_fp8 (const RadArgs*, RadStream);
|
||||
int r4d_rad_gate_had_quant_i8g(const RadArgs*, RadStream);
|
||||
int r4d_rad_gram_accum (const RadArgs*, RadStream);
|
||||
/* The same accumulator over a plain bf16 activation, no scale operand. */
|
||||
int r4d_rad_gram_accum_bf16 (const RadArgs*, RadStream);
|
||||
@@ -675,6 +682,7 @@ R4D_HOOKS(fp8_block)
|
||||
R4D_HOOKS(i8_block)
|
||||
R4D_HOOKS(iqr)
|
||||
R4D_HOOKS(iqr_logits)
|
||||
R4D_HOOKS(iqr_vocab)
|
||||
R4D_HOOKS(fp8_logits)
|
||||
R4D_HOOKS(i8_logits)
|
||||
R4D_HOOKS(hc_e4m3)
|
||||
@@ -1044,6 +1052,7 @@ int r4d_fuse_router_sigmoid_topk_scatter(const RadParam*, int, uint64_t, int, Ra
|
||||
int r4d_fuse_gate_quant_fp8 (const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_gemm_nt_q_gated (const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_gemm_nt_q_gated_mx (const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_gemm_nt_q_gated_iqr (const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_gdn_conv_recurrent_update(const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_qk_norm_rope_gate_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
int r4d_fuse_qkv_norm_rope_kv_store(const RadParam*, int, uint64_t, int, RadFuseStep*);
|
||||
|
||||
+147
-4
@@ -532,6 +532,29 @@ static const RadOperandSpec oGdnConvRecurrentUpdate[] = {
|
||||
{ "o_scale", RAD_OPD_OUT, 1 },
|
||||
};
|
||||
|
||||
/* gdn_conv_recurrent_update with had_quant_act_i8g's codes of `o` (a rotated int8 out projection's
|
||||
* input): the same operands, the codes required. libr4d's alone; no reference serves it. */
|
||||
static const RadOperandSpec oGdnConvRecurrentUpdateHad[] = {
|
||||
{ "x", RAD_OPD_IN, 0 },
|
||||
{ "conv_w", RAD_OPD_WEIGHT, 0 },
|
||||
{ "conv_b", RAD_OPD_WEIGHT, 1 },
|
||||
{ "conv_state", RAD_OPD_INOUT, 0 },
|
||||
{ "conv_idx", RAD_OPD_IN, 0 },
|
||||
{ "a", RAD_OPD_IN, 0 },
|
||||
{ "b", RAD_OPD_IN, 0 },
|
||||
{ "A_log", RAD_OPD_WEIGHT, 0 },
|
||||
{ "dt_bias", RAD_OPD_WEIGHT, 0 },
|
||||
{ "state", RAD_OPD_INOUT, 0 },
|
||||
{ "state_idx", RAD_OPD_IN, 0 },
|
||||
{ "num_accepted", RAD_OPD_IN, 0 },
|
||||
{ "cu", RAD_OPD_IN, 0 },
|
||||
{ "z", RAD_OPD_IN, 0 },
|
||||
{ "norm_w", RAD_OPD_WEIGHT, 0 },
|
||||
{ "o", RAD_OPD_OUT, 0 },
|
||||
{ "o_q", RAD_OPD_OUT, 0 },
|
||||
{ "o_scale", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* The control vector's projection (r4d_hc_bf16.hip, with the other gated-residual kernels): a bf16
|
||||
* stream, one unit f32 direction for every stream, an int32 switch per row. */
|
||||
static const RadParamSpec pHcProject[] = { P_INT("M"), P_INT("n"), P_INT("hc"), P_F64("scale"),
|
||||
@@ -1250,7 +1273,8 @@ static const RadOperandSpec oGivensDense[] = {
|
||||
*
|
||||
* `h` is inout: a caller zeroes it once and each launch adds its block. The operands are named `a`
|
||||
* and `a_scale` as in `gemm_nt_q`, whose activation this characterises. `a_scale` is optional:
|
||||
* dtype "bf16" reads a plain activation with no scale (a model served at bf16). */
|
||||
* dtype "bf16" reads a plain activation with no scale (a model served at bf16); "i8a8" reads an
|
||||
* int8 trunk's codes. */
|
||||
static const RadParamSpec pGramAccum[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n", RAD_P_INT, RAD_REQUIRED },
|
||||
@@ -2338,6 +2362,38 @@ static const RadOperandSpec oLogits[] = {
|
||||
{ "logits", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* The lm_head as width classes of the vocabulary's rows: up to four (codes, scales, ids) triples,
|
||||
* a class's rows on this rank in `rows<i>`, ids global (`vocab_offset` is this rank's first), and
|
||||
* `vrow`, the inverse: each of the rank's ids' class width and row. */
|
||||
static const RadParamSpec pLogitsVocab[] = {
|
||||
{ "M", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n_vocab", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "n_embd", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "dtype", RAD_P_STR, RAD_REQUIRED },
|
||||
{ "vocab_offset", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "rows0", RAD_P_INT, RAD_REQUIRED },
|
||||
{ "rows1", RAD_P_INT, RAD_OPTIONAL },
|
||||
{ "rows2", RAD_P_INT, RAD_OPTIONAL },
|
||||
{ "rows3", RAD_P_INT, RAD_OPTIONAL },
|
||||
};
|
||||
static const RadOperandSpec oLogitsVocab[] = {
|
||||
{ "x", RAD_OPD_IN, 0 },
|
||||
{ "w0", RAD_OPD_WEIGHT, 0 },
|
||||
{ "s0", RAD_OPD_WEIGHT, 0 },
|
||||
{ "ids0", RAD_OPD_WEIGHT, 0 },
|
||||
{ "w1", RAD_OPD_WEIGHT, 1 },
|
||||
{ "s1", RAD_OPD_WEIGHT, 1 },
|
||||
{ "ids1", RAD_OPD_WEIGHT, 1 },
|
||||
{ "w2", RAD_OPD_WEIGHT, 1 },
|
||||
{ "s2", RAD_OPD_WEIGHT, 1 },
|
||||
{ "ids2", RAD_OPD_WEIGHT, 1 },
|
||||
{ "w3", RAD_OPD_WEIGHT, 1 },
|
||||
{ "s3", RAD_OPD_WEIGHT, 1 },
|
||||
{ "ids3", RAD_OPD_WEIGHT, 1 },
|
||||
{ "vrow", RAD_OPD_WEIGHT, 0 },
|
||||
{ "logits", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
|
||||
/* Every sampler scalar is per row and arrives in `params`, an array of RadSampleParams
|
||||
* (abi/rad_sample.h). Parameters are geometry, frozen at declare, so only the two extents are
|
||||
* parameters. */
|
||||
@@ -3223,6 +3279,15 @@ static const RadOpSchema kSchemas[] = {
|
||||
"present: `tok` holds its row count more tokens after the step's, continuing the LAST "
|
||||
"sequence, and their ids -- as the step that runs them will compute them -- go there; "
|
||||
"the window is the step's own."),
|
||||
SCHEMA("logits_gemm_vocab", pLogitsVocab, oLogitsVocab,
|
||||
"logits[M, n_vocab] = x[M, n_embd] @ lm_head^T over a head stored as width classes of "
|
||||
"the vocabulary's rows: class i is a weight of rows<i> rows on this rank (w<i> its "
|
||||
"codes, s<i> its scales) and ids<i> the global vocabulary id of each, whose logit it "
|
||||
"writes; ids outside [vocab_offset, vocab_offset + n_vocab) are dropped. The classes "
|
||||
"cover the rank's share of the vocabulary once; ascending ids within a class keep the "
|
||||
"stores together. vrow[n_vocab] is the inverse, each of the rank's ids' class width in "
|
||||
"the top four bits and its row in the class's whole tensor below, which must fall in "
|
||||
"this rank's rows (vocab_offset / n_vocab is the rank)."),
|
||||
SCHEMA("logits_gemm", pLogits, oLogits,
|
||||
"the lm_head projection. gemm_nt's arithmetic under the vocabulary edge's parameter "
|
||||
"spelling; M is one row per SAMPLED position, `gather_rows` having run first."),
|
||||
@@ -3355,6 +3420,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
"gdn_conv_update followed by gdn_recurrent_update, with the convolution computed in "
|
||||
"the recurrent update's prologue: q, k and v never reach memory. Byte-identical to "
|
||||
"the two ops it replaces."),
|
||||
SCHEMA("gdn_conv_recurrent_update_had", pGdnConvRecurrentUpdate, oGdnConvRecurrentUpdateHad,
|
||||
"gdn_conv_recurrent_update whose `o_q` / `o_scale` are had_quant_act_i8g's codes of "
|
||||
"`o` (int8, a 128-wide Hadamard before the per-(token, head) amax), for an out "
|
||||
"projection stored rotated (i8a8h). Byte-identical to gdn_conv_recurrent_update "
|
||||
"followed by had_quant_act_i8g."),
|
||||
SCHEMA("hc_enter", pHcPlain, oHcEnter,
|
||||
"h[s] = x for each of the hc streams -- the wide residual stream's first value."),
|
||||
SCHEMA("mhc_pre", pMhcPre, oMhcPre,
|
||||
@@ -3610,6 +3680,11 @@ static const RadOpSchema kSchemas[] = {
|
||||
"epilogue, byte-identical to the two ops it replaces."),
|
||||
SCHEMA("gate_quant_fp8", pGateQuantFp8, oGateQuantFp8,
|
||||
"the same, with the gate in its own operand rather than packed beside x."),
|
||||
SCHEMA("gate_had_quant_i8g", pGateQuantFp8, oGateQuantFp8,
|
||||
"gate_quant_fp8 at int8 codes with a `group`-wide Hadamard before the absmax: "
|
||||
"had_quant_act_i8g's codes of the bf16 product (`out_bf16` the unrotated product), for "
|
||||
"an out projection stored rotated (dtype i8a8h). Byte-identical to gate_quant_fp8's "
|
||||
"product and had_quant_act_i8g over it."),
|
||||
SCHEMA("quant_act_fp8", pQuantActFp8, oQuantActFp8,
|
||||
"per-(row, `group`-column) symmetric E4M3 quantisation of a token-major activation, in "
|
||||
"PLAIN ROW-MAJOR order rather than quant_act_i8's fragment order. The scale is "
|
||||
@@ -5030,6 +5105,12 @@ 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"),
|
||||
};
|
||||
/* The gated fold over an IQR gate_up weight, to the 16-token tile's band: the gated width a whole
|
||||
* number of 128-column groups, silu only (gated_had_quant_i8g's mode the fold compiles). */
|
||||
static const RadConstraint cGemmNtQGatedIqr[] = {
|
||||
C_LE("M", 16), C_DIV("K", 256), C_DIV("N", 256), C_EQ("group", R4D_FP8_BLOCK),
|
||||
C_IN("dtype", "i8a8h"), C_IN("act", "silu"),
|
||||
};
|
||||
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"),
|
||||
@@ -5088,7 +5169,7 @@ static const RadConstraint cQsaBlockKey[] = {
|
||||
* `n` a multiple of 4 is the staging slot (one dword of four codes); the 64-wide C tile masks a
|
||||
* ragged tile. */
|
||||
static const RadConstraint cGramAccum[] = {
|
||||
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"),
|
||||
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8 i8a8"),
|
||||
};
|
||||
/* The bf16 form has no scale grid, so `group` constrains nothing; the staging slot is four
|
||||
* elements of a row. */
|
||||
@@ -5194,6 +5275,10 @@ static const RadConstraint cGemmNtQGatedMxWide[] = {
|
||||
C_GE("M", 9), C_LE("M", 64), C_DIV("K", 128), C_GE("K", 2688), C_DIV("N", 256), C_EQ("group", 32),
|
||||
C_IN("dtype", "mxfp4a8"), C_IN("act", "silu gelu_tanh"),
|
||||
};
|
||||
/* The rotated form: whole 128-column groups (a rotation block cannot straddle a row's end). */
|
||||
static const RadConstraint cGateHadQuantI8g[] = {
|
||||
C_DIV("n", R4D_FP8_BLOCK), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
|
||||
};
|
||||
static const RadConstraint cGateQuantFp8[] = {
|
||||
C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"),
|
||||
};
|
||||
@@ -5696,6 +5781,7 @@ static const RadConstraint cLogitsGemmCols[] = { C_EQ("n_embd", 4096), C_IN("dty
|
||||
* 2560 the row would win selection and then fail at layout with no fallback. r4d_fp8_lm.h pads the
|
||||
* stored row to 16 bytes instead (under 0.3% at K = 2560), so every multiple of 128 is served. */
|
||||
static const RadConstraint cLogitsGemmFp8[] = { C_DIV("n_embd", 128), C_IN("dtype", "bf16") };
|
||||
static const RadConstraint cLogitsVocab[] = { C_DIV("n_embd", 256), C_IN("dtype", "bf16") };
|
||||
|
||||
/* No tunable axes. */
|
||||
#define NOTUNE nullptr, 0, nullptr
|
||||
@@ -6567,6 +6653,21 @@ static const RadKernelInfo kKernels[] = {
|
||||
r4d_rad_layout_i8_logits, r4d_rad_relayout_i8_logits,
|
||||
nullptr, r4d_rad_unrelayout_i8_logits },
|
||||
|
||||
{ "logits_gemm_vocab_iqr", "logits_gemm_vocab", "vocab",
|
||||
"the vocabulary-weighted IQR head in one launch over every class: each block decodes its "
|
||||
"class's computed-trellis codes (the class's width) into int8 fragments through LDS and runs "
|
||||
"two int8 WMMA passes against the rotated activation's sixteen bits (hi and lo planes); up to 32 "
|
||||
"tokens into a staging plane in row order gathered through vrow, above that at each row's id",
|
||||
"any M (64 tokens a pass); n_embd a multiple of 256; each class a multiple of 256 rows",
|
||||
"bf16 x, rotated by fwht128 and quantised to 16 bits a (token, 128) in the call's scratch; "
|
||||
"classes of tcq_code=mad codes (2 to 7 bits, runs of 256 rows) under one f32 scale a row; F32 "
|
||||
"LOGITS OUT, int32 block sums folded in fp32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_LOGITS_FP8,
|
||||
ROW(cLogitsVocab), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_logits_gemm_vocab, r4d_rad_logits_gemm_vocab_scratch,
|
||||
r4d_rad_layout_iqr_vocab, r4d_rad_relayout_iqr_vocab,
|
||||
nullptr, r4d_rad_unrelayout_iqr_vocab },
|
||||
|
||||
{ "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 "
|
||||
@@ -7814,6 +7915,17 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update, nullptr, nullptr, nullptr, nullptr,
|
||||
nullptr, r4d_fuse_gdn_conv_recurrent_update },
|
||||
|
||||
{ "gdn_conv_recurrent_update_had_k128_v128_bf16", "gdn_conv_recurrent_update_had", "gdn",
|
||||
"gdn_conv_recurrent_update_k128_v128_bf16 with had_quant_act_i8g's pass in its epilogue: the "
|
||||
"workgroup's (token, head) row of `o`, one 128-wide group, rotated in one wave and quantised to "
|
||||
"int8, saving that quantiser's launch per layer",
|
||||
"as gdn_conv_recurrent_update_k128_v128_bf16; int8 codes",
|
||||
"as gdn_conv_recurrent_update_k128_v128_bf16, the codes had_quant_act_i8g's over `o`. "
|
||||
"Byte-identical to that row followed by had_quant_act_i8g (r4d_selftest's gdn conv fold)",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGdnConvRecurrentUpdate), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_gdn_conv_recurrent_update_had },
|
||||
|
||||
{ "kda_update_k128_v128_bf16", "kda_update", "gdn", "per-channel KDA recurrence and candidate rollback",
|
||||
"heads 1..65535, K=V=128, prefill and verify", "bf16 activations, f32 gates and state",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cKdaUpdate), NOTUNE,
|
||||
@@ -8426,6 +8538,24 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
r4d_rad_layout_iqr, r4d_rad_relayout_iqr,
|
||||
nullptr, r4d_rad_unrelayout_iqr },
|
||||
|
||||
{ "gemm_iqr_gated", "gemm_nt_q_gated", "gemm",
|
||||
"gemm_iqr_nt_m64's GEMV and 16-token tile over a gate_up weight with gated_had_quant_i8g's pass "
|
||||
"in the epilogue: a block per 16-column tile of the gated output, the plain kernel's waves on the "
|
||||
"gate rows' tile and as many on the up rows', the product in the op's scratch and the last of a "
|
||||
"128-column group's blocks to arrive rotating and quantising it, so the [M, 2n] bf16 plane and "
|
||||
"the quantiser's launch are gone",
|
||||
"M <= 16; K a multiple of 256; N a multiple of 256 (the gated width of the 128-column group), "
|
||||
"and of a trellis's run; act silu; an IQR weight's codes, gate rows then up rows",
|
||||
"i8 A with an f32 scale per (row, 128 K), W an IQR form's codes (as gemm_iqr_nt_m64), and the "
|
||||
"QUANTISER's outputs: int8 codes of the rotated product, an f32 scale per (row, 128 columns) and "
|
||||
"an optional bf16 product. Byte-identical to gemm_iqr_nt_m64 followed by gated_had_quant_i8g",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGemmNtQGatedIqr), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_gemm_iqr_gated, r4d_rad_gemm_iqr_gated_scratch,
|
||||
r4d_rad_layout_iqr, r4d_rad_relayout_iqr, nullptr, r4d_rad_unrelayout_iqr,
|
||||
/* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */
|
||||
r4d_fuse_gemm_nt_q_gated_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 "
|
||||
@@ -9052,10 +9182,11 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
* accumulated Hessians at convert time, from a file. So it is unresolved by the serving graph on
|
||||
* purpose, not an unwired kernel. */
|
||||
{ "gram_accum", "gram_accum", "quant",
|
||||
"h += x^T x over an E4M3 activation, in f32 -- the Gram matrix a GPTQ packer needs",
|
||||
"h += x^T x over an E4M3 or int8 activation, in f32 -- the Gram matrix a GPTQ packer needs",
|
||||
"n a multiple of 4 and group 128, because a 64-wide output tile must lie inside one scale "
|
||||
"group; any M, and the accumulator is READ as well as written",
|
||||
"E4M3 plus an f32 scale per (row, 128 columns) in; an f32 [n][n] accumulator in and out",
|
||||
"E4M3 (dtype fp8a8) or int8 (i8a8) plus an f32 scale per (row, 128 columns) in; an f32 [n][n] "
|
||||
"accumulator in and out",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGramAccum), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_gram_accum, nullptr, nullptr, nullptr,
|
||||
@@ -9165,6 +9296,18 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8)
|
||||
/* `sigmoid` + `mul` + `quant_act_fp8`, and `mul` + `quant_act_fp8` for act none (r4d_fuse.cpp). */
|
||||
r4d_fuse_gate_quant_fp8 },
|
||||
|
||||
{ "gate_had_quant_i8g", "gate_had_quant_i8g", "quant",
|
||||
"gate_quant_fp8 with the width-128 Hadamard between the bf16-rounded product and the absmax and "
|
||||
"int8 codes: had_quant_act_i8g's pass folded in, saving that quantiser's launch before a gated "
|
||||
"attention's rotated out projection",
|
||||
"n a multiple of 128; otherwise as gate_quant_fp8",
|
||||
"bf16 in, int8 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes "
|
||||
"are had_quant_act_i8g's over the BF16-ROUNDED product",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cGateHadQuantI8g), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_gate_had_quant_i8g, nullptr, nullptr, nullptr,
|
||||
r4d_shape_gate_quant_fp8, nullptr },
|
||||
|
||||
/* ---------------------------------------------------------------------------------- sampling
|
||||
*
|
||||
* spec §13 requires sampling on device. This is the only implementation of sample_chain (libref
|
||||
|
||||
+722
-19
@@ -40,6 +40,7 @@
|
||||
#include "r4d_hc_fp8.h"
|
||||
#include "r4d_fp8_frag.h"
|
||||
#include "r4d_fp8_lm.h"
|
||||
#include "r4d_iqr.h"
|
||||
#include "rad_encoding.h"
|
||||
#include "rad_philox.h"
|
||||
#include "rad_sample.h"
|
||||
@@ -4431,11 +4432,15 @@ static int64_t i8_code_misses(const uint16_t* x, int64_t x_ld, const int8_t* q,
|
||||
* codes to quant_act_i8g over its `o`. `f32w` hands the fold the conv weight in f32, as a GGUF
|
||||
* stores it, and leaves the pair's in bf16: the values are bf16's, so the bytes must not change. */
|
||||
static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form,
|
||||
bool i8 = false, bool f32w = false) {
|
||||
const RadKernelInfo* rf = find(pl, "gdn_conv_recurrent_update_k128_v128_bf16");
|
||||
bool i8 = false, bool f32w = false, bool had = false) {
|
||||
/* `had`: the rotated row, against the pair writing `o` and had_quant_act_i8g over it. */
|
||||
if (had) i8 = true;
|
||||
const RadKernelInfo* rf = find(pl, had ? "gdn_conv_recurrent_update_had_k128_v128_bf16"
|
||||
: "gdn_conv_recurrent_update_k128_v128_bf16");
|
||||
const RadKernelInfo* rc = find(pl, "gdn_conv_update_w4_h128_bf16");
|
||||
const RadKernelInfo* rr = find(pl, "gdn_recurrent_update_k128_v128_bf16_fp32state");
|
||||
if (!rf || !rc || !rr) { ok(nm, false, "a row is absent"); return; }
|
||||
const RadKernelInfo* rh = had ? find(pl, "had_quant_act_i8g") : nullptr;
|
||||
if (!rf || !rc || !rr || (had && !rh)) { ok(nm, false, "a row is absent"); return; }
|
||||
|
||||
const int64_t K = 128, V = 128, H = 4, Hg = 2, N = 4, W = 4, MQ = 4, SL = W - 2 + MQ;
|
||||
const int64_t conv_dim = (2 * Hg * K + H * V), in_w = conv_dim + H * V;
|
||||
@@ -4553,15 +4558,24 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
|
||||
int e = run(rc, { tx, tw, none, cs(0), tci, tna, tcu, tq, tk, tv }, pc);
|
||||
if (e == RAD_OK)
|
||||
e = run(rr, { tq, tk, tv, ta, tb, tal, tdt, st(0), tsi, tna, tcu, tz, tnw, to(0),
|
||||
toq(0), tos(0) }, pr);
|
||||
had ? none : toq(0), had ? none : tos(0) }, pr);
|
||||
if (e == RAD_OK && had) {
|
||||
std::vector<RadParam> ph = { PI("M", Td), PI("n", H * V), PI("group", 128), PS("dtype", "bf16") };
|
||||
e = run(rh, { T(d_o[0], RAD_BF16, { Td, H * V }), toq(0), tos(0) }, ph);
|
||||
}
|
||||
if (e != RAD_OK) { why = "pair rc=" + std::to_string(e); break; }
|
||||
e = run(rf, { tx, tfw, none, cs(1), tci, ta, tb, tal, tdt, st(1), tsi, tna, tcu, tz, tnw,
|
||||
to(1), toq(1), tos(1) }, pf);
|
||||
if (e != RAD_OK) { why = "fold rc=" + std::to_string(e); break; }
|
||||
|
||||
/* had_quant_act_i8g also quantises the padded last sequence's row, which the fold skips
|
||||
* (a zero row, scale 1 against unwritten 0): the codes over the real sequences' tokens. */
|
||||
const size_t real = (size_t)cu[(size_t)N - 1];
|
||||
const struct { const char* what; void* a; void* b; size_t n; } cmp[] = {
|
||||
{ "o", d_o[0], d_o[1], o_b }, { "o_q", d_oq[0], d_oq[1], oq_b },
|
||||
{ "o_scale", d_os[0], d_os[1], os_b }, { "state", d_st[0], d_st[1], st_b },
|
||||
{ "o", d_o[0], d_o[1], o_b },
|
||||
{ "o_q", d_oq[0], d_oq[1], had ? real * (size_t)(H * V) : oq_b },
|
||||
{ "o_scale", d_os[0], d_os[1], had ? real * (size_t)H * 4 : os_b },
|
||||
{ "state", d_st[0], d_st[1], st_b },
|
||||
{ "conv_state", d_cs[0], d_cs[1], cs_b },
|
||||
};
|
||||
for (const auto& c : cmp) {
|
||||
@@ -4576,7 +4590,7 @@ static void gdn_conv_fold_run(const Plugin& pl, const char* nm, const char* form
|
||||
}
|
||||
/* At int8 codes, the real sequences' tokens (all but the padded last) against
|
||||
* quant_act_i8g over the pair's `o`. A (token, head) row is one group. */
|
||||
if (i8 && why.empty()) {
|
||||
if (i8 && !had && why.empty()) {
|
||||
const std::vector<uint8_t> O = fetch(d_o[0], o_b), Q = fetch(d_oq[0], oq_b),
|
||||
S = fetch(d_os[0], os_b);
|
||||
const int64_t rows = (int64_t)cu[(size_t)N - 1] * H;
|
||||
@@ -4611,6 +4625,12 @@ static void gdn_conv_fold(const Plugin& pl) {
|
||||
"per_candidate", true);
|
||||
}
|
||||
if (sel(row) || sel(nma)) gdn_conv_fold_run(pl, nma, "anchor");
|
||||
if (sel(row) || sel("gdn_conv_recurrent_update_had")) {
|
||||
gdn_conv_fold_run(pl, "gdn_conv_recurrent_update_had is byte-identical to the pair then "
|
||||
"had_quant_act_i8g, per_candidate", "per_candidate", true, false, true);
|
||||
gdn_conv_fold_run(pl, "gdn_conv_recurrent_update_had is byte-identical to the pair then "
|
||||
"had_quant_act_i8g, anchor", "anchor", true, false, true);
|
||||
}
|
||||
if (sel(row) || sel(nmf)) gdn_conv_fold_run(pl, nmf, "per_candidate", false, true);
|
||||
}
|
||||
|
||||
@@ -6816,10 +6836,11 @@ static void iqr_gemm_case(const Plugin& pl, const IqrCase& f, int64_t M, int64_t
|
||||
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. */
|
||||
/* M <= 16 is the GEMV or the 16-token tile, which sum per wave before summing across waves:
|
||||
* 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;
|
||||
const bool exact = M > 16 && !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. */
|
||||
@@ -14750,6 +14771,214 @@ static void iqr_head_case(const Plugin& pl, int TB, int64_t N, int64_t K, int64_
|
||||
dfree_all();
|
||||
}
|
||||
|
||||
/* logits_gemm_vocab_iqr against the f64 product it computes: each class a computed trellis
|
||||
* (tcq_code=mad, runs of 256 rows, one f32 scale a row under a factor a 128-K block, fwht128) of
|
||||
* random codes, its rows' vocabulary ids a random permutation of the rank's share (`off` = the
|
||||
* share for a second rank's, whose rows are the second half of each class's tensor), the activation
|
||||
* random bf16, at token counts on both sides of the staging plane's 32. The reference rotates the activation in
|
||||
* f32 and quantises it to sixteen bits a (token, 128) as the kernel does, then multiplies the
|
||||
* host's decode of every class in f64: the kernel's f32 folds keep the logits within 2^-18 of their
|
||||
* rms. Every logit must be written once: the output starts as NaN. The classes' planes also go back
|
||||
* through the hooks' inverse. */
|
||||
struct VocabClass { int B; int64_t rows; };
|
||||
|
||||
static void vocab_head_case(const Plugin& pl, const std::vector<VocabClass>& cls, int64_t M,
|
||||
int64_t K, int64_t off) {
|
||||
const char* row = "logits_gemm_vocab_iqr";
|
||||
if (!sel(row)) return;
|
||||
int64_t V = 0;
|
||||
std::string ws;
|
||||
for (const auto& c : cls) { V += c.rows; ws += (ws.empty() ? "" : ",") + std::to_string(c.B) + "x" + std::to_string(c.rows); }
|
||||
char nm[200];
|
||||
std::snprintf(nm, sizeof nm, "%s classes %s K=%lld M=%lld off=%lld", row, ws.c_str(),
|
||||
(long long)K, (long long)M, (long long)off);
|
||||
const RadKernelInfo* r = find(pl, row);
|
||||
if (!r || !r->layout || !r->relayout || !r->scratch) { ok(nm, false, "row or hooks absent"); return; }
|
||||
const int64_t nkb = K / 128;
|
||||
uint64_t z = 0x9E3779B97F4A7C15ull * (uint64_t)(V + M * 7 + K + off);
|
||||
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 };
|
||||
std::vector<int32_t> perm((size_t)V);
|
||||
for (int64_t i = 0; i < V; ++i) perm[(size_t)i] = (int32_t)i;
|
||||
for (int64_t i = V - 1; i > 0; --i) std::swap(perm[(size_t)i], perm[(size_t)(rnd() % (uint64_t)(i + 1))]);
|
||||
|
||||
std::vector<RadParam> gp = { PI("M", M), PI("n_vocab", V), PI("n_embd", K), PS("dtype", "bf16"),
|
||||
PI("vocab_offset", off) };
|
||||
static const char* kRows[] = { "rows0", "rows1", "rows2", "rows3" };
|
||||
for (size_t i = 0; i < cls.size(); ++i) gp.push_back(PI(kRows[i], cls[i].rows));
|
||||
|
||||
/* the decoded head in vocabulary order, f64 */
|
||||
std::vector<double> Wd((size_t)(V * K));
|
||||
std::vector<RadTensor> ts(1 + 3 * 4 + 2);
|
||||
std::vector<std::vector<uint8_t>> keep;
|
||||
/* the inverse map: each id's class width and its row in the class's whole tensor, this rank
|
||||
* being the second of a share `off` (the classes' tensors then twice its rows) when off > 0 */
|
||||
const int64_t rank = off > 0 ? 1 : 0;
|
||||
std::vector<int32_t> vrow((size_t)V, -1);
|
||||
int64_t base = 0;
|
||||
for (size_t ci = 0; ci < cls.size(); ++ci) {
|
||||
const VocabClass& vc = cls[ci];
|
||||
const int64_t N = vc.rows;
|
||||
Planes p;
|
||||
rad_enc_clear(&p.enc);
|
||||
rad_enc_copy_str(p.enc.scheme, "trellis");
|
||||
rad_enc_add_plane(&p.enc, "codes", kU[vc.B], 1, 1);
|
||||
rad_enc_add_plane(&p.enc, "scale", RAD_F32, 1, 0);
|
||||
const int t = rad_enc_add_table(&p.enc, "trellis", RAD_I8, (int64_t)1 << 16, 1);
|
||||
p.enc.plane[t].block[0] = 256;
|
||||
p.enc.plane[t].block[1] = 0;
|
||||
rad_enc_add_table(&p.enc, "trellis.mad", RAD_U32, 2, 1);
|
||||
rad_enc_add_plane(&p.enc, "scale.col", RAD_F32, 0, 128);
|
||||
rad_enc_copy_str(p.enc.transform, "fwht128");
|
||||
p.size(N, K);
|
||||
const int ic = p.find("codes"), is = p.find("scale"), ia = p.find("trellis");
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
for (int64_t c = 0; c < K; ++c)
|
||||
rad_store_bits(p.data[(size_t)ic].data() + n * p.row_bytes(ic), vc.B, c,
|
||||
(uint32_t)(rnd() & ((1ull << vc.B) - 1)));
|
||||
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 << 16); ++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);
|
||||
}
|
||||
std::vector<float> rs((size_t)N), cf((size_t)nkb);
|
||||
for (int64_t n = 0; n < N; ++n) rs[(size_t)n] = std::ldexp(1.0f + (float)(rnd() % 1000) / 1000.0f, -9 - (int)(rnd() % 3));
|
||||
for (int64_t g = 0; g < nkb; ++g) cf[(size_t)g] = 0.5f + (float)(rnd() % 1000) / 1000.0f;
|
||||
for (int64_t n = 0; n < N; ++n) ((float*)p.data[(size_t)is].data())[n] = rs[(size_t)n];
|
||||
for (int64_t g = 0; g < nkb; ++g) ((float*)p.data[(size_t)p.find("scale.col")].data())[g] = cf[(size_t)g];
|
||||
const int C = (16 + vc.B - 1) / vc.B;
|
||||
const int8_t* aux = (const int8_t*)p.data[(size_t)ia].data();
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
const int64_t id = perm[(size_t)(base + n)];
|
||||
for (int64_t k = 0; k < K; ++k) {
|
||||
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 << vc.B) | rad_load_bits(p.data[(size_t)ic].data() + rr * p.row_bytes(ic), vc.B, k)) & 0xFFFFu;
|
||||
}
|
||||
Wd[(size_t)(id * K + k)] = (double)aux[st] * rs[(size_t)n] * cf[(size_t)(k / 128)];
|
||||
}
|
||||
}
|
||||
const int op = 1 + 3 * (int)ci;
|
||||
std::vector<uint8_t> wq, wsc;
|
||||
RadLayout lw, ls;
|
||||
const int rw = stored(r, gp, op, p, { "codes", "trellis", "trellis.mad" }, &wq, &lw);
|
||||
const int rsc = stored(r, gp, op + 1, p, { "scale", "scale.col" }, &wsc, &ls);
|
||||
if (rw != RAD_OK || rsc != RAD_OK) {
|
||||
ok(nm, false, "relayout rc " + std::to_string(rw) + "/" + std::to_string(rsc));
|
||||
return;
|
||||
}
|
||||
std::string why;
|
||||
const bool back = restores(r, gp, op, p, { "codes", "trellis", "trellis.mad" }, wq, &why) &&
|
||||
restores(r, gp, op + 1, p, { "scale", "scale.col" }, wsc, &why);
|
||||
ok((std::string(nm) + ": class " + std::to_string(ci) + "'s planes invert").c_str(), back, why);
|
||||
ok((std::string(nm) + ": class " + std::to_string(ci) + " holds its codes' bits").c_str(),
|
||||
lw.bytes <= N * K * vc.B / 8 + ((int64_t)1 << 16) + 1024,
|
||||
std::to_string(lw.bytes) + " B for " + std::to_string(N * K * vc.B / 8) + " B of codes");
|
||||
std::vector<int32_t> ids((size_t)N);
|
||||
for (int64_t n = 0; n < N; ++n) {
|
||||
ids[(size_t)n] = perm[(size_t)(base + n)] + (int32_t)off;
|
||||
vrow[(size_t)perm[(size_t)(base + n)]] = (int32_t)((uint32_t)vc.B << 28) | (int32_t)(n + rank * N);
|
||||
}
|
||||
void* d_w = dalloc(wq.size());
|
||||
void* d_s = dalloc(wsc.size());
|
||||
void* d_r = dalloc(ids.size() * 4);
|
||||
if (!d_w || !d_s || !d_r) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_w, wq.data(), wq.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_s, wsc.data(), wsc.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_r, ids.data(), ids.size() * 4, hipMemcpyHostToDevice);
|
||||
ts[(size_t)op] = T(d_w, lw.dtype, { N, K });
|
||||
ts[(size_t)op + 1] = T(d_s, ls.dtype, { N, nkb });
|
||||
ts[(size_t)op + 2] = T(d_r, RAD_I32, { N });
|
||||
base += N;
|
||||
}
|
||||
for (size_t ci = cls.size(); ci < 4; ++ci)
|
||||
for (int j = 0; j < 3; ++j) {
|
||||
ts[1 + 3 * ci + (size_t)j] = T(nullptr, RAD_U8, { 1 });
|
||||
absent(ts[1 + 3 * ci + (size_t)j]);
|
||||
}
|
||||
void* d_m = dalloc(vrow.size() * 4);
|
||||
if (!d_m) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_m, vrow.data(), vrow.size() * 4, hipMemcpyHostToDevice);
|
||||
ts[13] = T(d_m, RAD_I32, { V, 1 });
|
||||
|
||||
std::vector<uint16_t> hx((size_t)(M * K));
|
||||
for (auto& v : hx) v = h_to_bf16((float)((double)(int64_t)(rnd() % 20001 - 10000) / 4000.0));
|
||||
/* The activation as the kernel holds it: rotated in f32 (h_fwht's butterflies are
|
||||
* r4d_fwht_wave's, in its order), then q = rint(x * 16256 / amax) a (token, 128) under the
|
||||
* scale amax / 16256. */
|
||||
std::vector<double> xr((size_t)(M * K));
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t g = 0; g < nkb; ++g) {
|
||||
float v[128];
|
||||
for (int j = 0; j < 128; ++j) v[j] = h_bf16(hx[(size_t)(m * K + g * 128 + j)]);
|
||||
h_fwht(v, 128);
|
||||
float a = 0.0f;
|
||||
for (int j = 0; j < 128; ++j) a = std::max(a, std::fabs(v[j]));
|
||||
const float inv = a > 0.0f ? 16256.0f / a : 0.0f, sc = a / 16256.0f;
|
||||
for (int j = 0; j < 128; ++j) {
|
||||
const float q = std::fmin(std::fmax(rintf(v[j] * inv), -16256.0f), 16256.0f);
|
||||
xr[(size_t)(m * K + g * 128 + j)] = (double)q * (double)sc;
|
||||
}
|
||||
}
|
||||
std::vector<double> ref((size_t)(M * V));
|
||||
double r2 = 0.0;
|
||||
for (int64_t m = 0; m < M; ++m)
|
||||
for (int64_t v = 0; v < V; ++v) {
|
||||
double s = 0.0;
|
||||
for (int64_t k = 0; k < K; ++k) s += Wd[(size_t)(v * K + k)] * xr[(size_t)(m * K + k)];
|
||||
ref[(size_t)(m * V + v)] = s;
|
||||
r2 += s * s;
|
||||
}
|
||||
const double rms = std::sqrt(r2 / (double)(M * V));
|
||||
|
||||
void* d_x = dalloc(hx.size() * 2);
|
||||
void* d_y = dalloc((size_t)(M * V) * 4);
|
||||
if (!d_x || !d_y) { ok(nm, false, "hipMalloc failed"); return; }
|
||||
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
|
||||
std::vector<float> nan((size_t)(M * V), std::nanf(""));
|
||||
st_memcpy(d_y, nan.data(), nan.size() * 4, hipMemcpyHostToDevice);
|
||||
ts[0] = T(d_x, RAD_BF16, { M, K });
|
||||
ts[14] = T(d_y, RAD_F32, { M, V });
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size();
|
||||
a.p = gp.data(); a.n_p = (int)gp.size();
|
||||
a.world_size = 1;
|
||||
const int64_t need = r->scratch(&a);
|
||||
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
|
||||
const int rc = r->launch(&a, (RadStream) nullptr);
|
||||
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { ok(nm, false, "rc " + std::to_string(rc)); dfree_all(); return; }
|
||||
std::vector<float> y((size_t)(M * V));
|
||||
st_memcpy(y.data(), d_y, y.size() * 4, hipMemcpyDeviceToHost);
|
||||
int64_t bad = 0, first = -1, unset = 0;
|
||||
double e2 = 0.0;
|
||||
for (size_t i = 0; i < y.size(); ++i) {
|
||||
if (std::isnan(y[i])) { ++unset; if (first < 0) first = (int64_t)i; continue; }
|
||||
const double d = (double)y[i] - ref[i];
|
||||
e2 += d * d;
|
||||
if (!(std::fabs(d) <= std::ldexp(rms, -18))) { if (first < 0) first = (int64_t)i; ++bad; }
|
||||
}
|
||||
const double rel = std::sqrt(e2 / (r2 > 0 ? r2 : 1.0));
|
||||
ok(nm, bad == 0 && unset == 0,
|
||||
bad || unset ? std::to_string(bad) + " off, " + std::to_string(unset) + " unwritten of " +
|
||||
std::to_string(y.size()) + ", first [" + std::to_string(first / V) + "][" +
|
||||
std::to_string(first % V) + "] " + std::to_string(y[(size_t)first]) + " vs " +
|
||||
std::to_string(ref[(size_t)first]) + ", rms " + std::to_string(rms)
|
||||
: "rel_l2 " + std::to_string(rel));
|
||||
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
|
||||
@@ -14764,7 +14993,7 @@ static void iqr_embed_case(const Plugin& pl, const IqrEmbedCase& f, int64_t rows
|
||||
(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 };
|
||||
static const uint32_t kU[] = { 0, RAD_U1, RAD_U2, RAD_U3, RAD_U4, RAD_U5, RAD_U6, RAD_U7, RAD_U8 };
|
||||
const int64_t nkb = dim / 128;
|
||||
uint64_t z = 0xABCDEFull * (uint64_t)(f.kind * 31 + f.B + f.rot);
|
||||
auto rnd = [&]() {
|
||||
@@ -14786,7 +15015,7 @@ static void iqr_embed_case(const Plugin& pl, const IqrEmbedCase& f, int64_t rows
|
||||
} 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);
|
||||
else rad_enc_add_plane(&p.enc, "zero", f.B == 8 ? RAD_U8 : f.B == 7 ? RAD_U7 : RAD_U6, 1, 128);
|
||||
}
|
||||
if (f.rot) rad_enc_copy_str(p.enc.transform, "fwht128");
|
||||
p.size(rows, dim);
|
||||
@@ -14799,7 +15028,8 @@ static void iqr_embed_case(const Plugin& pl, const IqrEmbedCase& f, int64_t rows
|
||||
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));
|
||||
rad_store_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), std::max(f.B, 6), g,
|
||||
(uint32_t)((1 << (std::max(f.B, 6) - 1)) - 8 + 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) {
|
||||
@@ -14827,7 +15057,7 @@ static void iqr_embed_case(const Plugin& pl, const IqrEmbedCase& f, int64_t rows
|
||||
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 if (f.kind == 2) q = (int)code(n, k) - (int)rad_load_bits(p.data[(size_t)ia].data() + n * p.row_bytes(ia), std::max(f.B, 6), k / 128);
|
||||
else {
|
||||
uint32_t st = 0;
|
||||
for (int qq = C - 1; qq >= 0; --qq) {
|
||||
@@ -15927,6 +16157,14 @@ static void perf_row(const Plugin& pl, const char* name, std::vector<RadTensor>
|
||||
const int64_t need = r->scratch(&a);
|
||||
if (need < 0) { std::printf(" %-22s scratch %lld\n", name, (long long)need); return; }
|
||||
if (need > 0) { a.scratch = dalloc((size_t)need); a.scratch_bytes = need; }
|
||||
/* R4D_PERF_RAND_SCRATCH: random scratch bytes, so a variant that skips writing its
|
||||
* scratch still multiplies operands of real entropy (WMMA power tracks the data) */
|
||||
if (need > 0 && std::getenv("R4D_PERF_RAND_SCRATCH")) {
|
||||
std::vector<uint8_t> h((size_t)need);
|
||||
uint64_t z = 0x2545F4914F6CDD1Dull;
|
||||
for (auto& v : h) { z ^= z << 13; z ^= z >> 7; z ^= z << 17; v = (uint8_t)z; }
|
||||
st_memcpy(a.scratch, h.data(), h.size(), hipMemcpyHostToDevice);
|
||||
}
|
||||
}
|
||||
|
||||
/* One warm launch, which also checks the row serves this shape; a refusal is reported, not
|
||||
@@ -16039,6 +16277,312 @@ static void mx_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iters
|
||||
}
|
||||
|
||||
|
||||
/* gate_had_quant_i8g against gate_quant_fp8's bf16 product and had_quant_act_i8g over it, byte for
|
||||
* byte: the codes, the scales and the product. The gate is a column view of a [q|gate] row (pitch
|
||||
* 2n), as a gated attention lays it out; M rows of n, each a (token, head). */
|
||||
static void gate_had_case(const Plugin& pl, int64_t M, int64_t n) {
|
||||
if (!sel("gate_had_quant_i8g")) return;
|
||||
char nm[120];
|
||||
std::snprintf(nm, sizeof nm, "gate_had_quant_i8g is gate_quant_fp8 then had_quant_act_i8g, M=%lld n=%lld",
|
||||
(long long)M, (long long)n);
|
||||
const RadKernelInfo* rh = find(pl, "gate_had_quant_i8g");
|
||||
const RadKernelInfo* rg = find(pl, "gate_quant_fp8");
|
||||
const RadKernelInfo* rq = find(pl, "had_quant_act_i8g");
|
||||
if (!rh || !rg || !rq) { ok(nm, false, "rows absent"); return; }
|
||||
uint32_t z = 0x1234567u + (uint32_t)(M * 7 + n);
|
||||
auto rnd = [&](float span) {
|
||||
z = z * 1664525u + 1013904223u;
|
||||
return ((float)(z >> 8) / 16777216.0f * 2.0f - 1.0f) * span;
|
||||
};
|
||||
std::vector<uint16_t> hg((size_t)(M * 2 * n)), hx((size_t)(M * n));
|
||||
for (auto& v : hg) v = h_to_bf16(rnd(6.0f));
|
||||
for (auto& v : hx) v = h_to_bf16(rnd(3.0f));
|
||||
void* d_g = dalloc(hg.size() * 2);
|
||||
void* d_x = dalloc(hx.size() * 2);
|
||||
void* d_q = dalloc((size_t)(M * n));
|
||||
void* d_s = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
void* d_y = dalloc((size_t)(M * n) * 2);
|
||||
void* d_q2 = dalloc((size_t)(M * n));
|
||||
void* d_s2 = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
void* d_y2 = dalloc((size_t)(M * n) * 2);
|
||||
void* d_f8 = dalloc((size_t)(M * n));
|
||||
void* d_f8s = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
if (!d_g || !d_x || !d_q || !d_s || !d_y || !d_q2 || !d_s2 || !d_y2 || !d_f8 || !d_f8s) {
|
||||
ok(nm, false, "hipMalloc failed");
|
||||
return;
|
||||
}
|
||||
st_memcpy(d_g, hg.data(), hg.size() * 2, hipMemcpyHostToDevice);
|
||||
st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice);
|
||||
RadTensor gate = T((uint8_t*)d_g + n * 2, RAD_BF16, { M, n });
|
||||
gate.stride[0] = 2 * n;
|
||||
auto run = [&](const RadKernelInfo* r, 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;
|
||||
const int rc = r->launch(&a, (RadStream) nullptr);
|
||||
return rc != RAD_OK ? rc : (st_stream_sync(nullptr) != hipSuccess ? -1000 : RAD_OK);
|
||||
};
|
||||
const std::vector<RadParam> pg = { PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"),
|
||||
PS("act", "sigmoid") };
|
||||
int e = run(rh, { gate, T(d_x, RAD_BF16, { M, n }), T(d_q, RAD_I8, { M, n }),
|
||||
T(d_s, RAD_F32, { M, n / 128 }), T(d_y, RAD_BF16, { M, n }) }, pg);
|
||||
if (e == RAD_OK)
|
||||
e = run(rg, { gate, T(d_x, RAD_BF16, { M, n }), T(d_f8, RAD_F8E4M3, { M, n }),
|
||||
T(d_f8s, RAD_F32, { M, n / 128 }), T(d_y2, RAD_BF16, { M, n }) }, pg);
|
||||
if (e == RAD_OK)
|
||||
e = run(rq, { T(d_y2, RAD_BF16, { M, n }), T(d_q2, RAD_I8, { M, n }), T(d_s2, RAD_F32, { M, n / 128 }) },
|
||||
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16") });
|
||||
if (e != RAD_OK) { ok(nm, false, "rc " + std::to_string(e)); return; }
|
||||
auto fetch = [](void* d, size_t b) {
|
||||
std::vector<uint8_t> h(b);
|
||||
st_memcpy(h.data(), d, b, hipMemcpyDeviceToHost);
|
||||
return h;
|
||||
};
|
||||
const bool same = fetch(d_q, (size_t)(M * n)) == fetch(d_q2, (size_t)(M * n)) &&
|
||||
fetch(d_s, (size_t)(M * (n / 128)) * 4) == fetch(d_s2, (size_t)(M * (n / 128)) * 4) &&
|
||||
fetch(d_y, (size_t)(M * n) * 2) == fetch(d_y2, (size_t)(M * n) * 2);
|
||||
ok(nm, same, same ? "" : "codes, scales or product differ");
|
||||
}
|
||||
|
||||
/* The V4 trunk's IQR planes for an [N, K] weight: a 2^16-state computed trellis of B-bit codes in
|
||||
* 256-row runs, one f32 scale a row (each its own, 7 significant bits), a power of two a 128-K block,
|
||||
* fwht128; random codes from `z`. */
|
||||
static Planes iqr_v4_planes(int64_t N, int64_t K, int B, uint64_t z, bool bf16s = false) {
|
||||
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 };
|
||||
constexpr int L = 16;
|
||||
Planes p;
|
||||
rad_enc_clear(&p.enc);
|
||||
rad_enc_copy_str(p.enc.scheme, "trellis");
|
||||
rad_enc_add_plane(&p.enc, "codes", kU[B], 1, 1);
|
||||
if (bf16s) rad_enc_add_plane(&p.enc, "scale", RAD_BF16, 1, 128);
|
||||
else rad_enc_add_plane(&p.enc, "scale", RAD_F32, 1, 0);
|
||||
const int t = rad_enc_add_table(&p.enc, "trellis", RAD_I8, (int64_t)1 << L, 1);
|
||||
p.enc.plane[t].block[0] = 256;
|
||||
p.enc.plane[t].block[1] = 0;
|
||||
rad_enc_add_table(&p.enc, "trellis.mad", RAD_U32, 2, 1);
|
||||
if (!bf16s) rad_enc_add_plane(&p.enc, "scale.col", RAD_F32, 0, 128);
|
||||
rad_enc_copy_str(p.enc.transform, "fwht128");
|
||||
p.size(N, K);
|
||||
for (auto& v : p.data[(size_t)p.find("codes")]) v = (uint8_t)rnd();
|
||||
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;
|
||||
uint8_t* tab = p.data[(size_t)t].data();
|
||||
for (uint32_t st = 0; st < (1u << L); ++st) {
|
||||
const uint32_t h = ((st & 0xFFFFFFu) * A + Bc) & 0x3F3F3F3Fu;
|
||||
tab[st] = (uint8_t)(int8_t)((int)((h & 0xFFu) + ((h >> 8) & 0xFFu) + ((h >> 16) & 0xFFu) + (h >> 24)) - 126);
|
||||
}
|
||||
if (bf16s) {
|
||||
for (int64_t i = 0; i < N * (K / 128); ++i)
|
||||
rad_store_f32(p.data[(size_t)p.find("scale")].data(), RAD_BF16, i,
|
||||
std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -9 - (int)(rnd() % 4)));
|
||||
} else {
|
||||
for (int64_t n = 0; n < N; ++n)
|
||||
((float*)p.data[(size_t)p.find("scale")].data())[n] =
|
||||
std::ldexp(1.0f + (float)(rnd() % 64) / 64.0f, -9 - (int)(rnd() % 4));
|
||||
for (int64_t g = 0; g < K / 128; ++g)
|
||||
((float*)p.data[(size_t)p.find("scale.col")].data())[g] = std::ldexp(1.0f, (int)(rnd() % 4) - 1);
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/* gemm_iqr_gated against its chain, gemm_iqr_nt_m64 then gated_had_quant_i8g, byte for byte: the
|
||||
* codes, the scales and the bf16 product, on the V4 trunk's form; and the gated row stores the
|
||||
* weight as the GEMM row does, so the two read one copy. */
|
||||
static void iqr_gated_case(const Plugin& pl, int B, int64_t M, int64_t n, int64_t K) {
|
||||
if (!sel("gemm_iqr_gated") && !sel("gemm_iqr")) return;
|
||||
const int64_t N = 2 * n, nkb = K / 128;
|
||||
char nm[160];
|
||||
std::snprintf(nm, sizeof nm, "gemm_iqr_gated trellis-mad B=%d row-f32 M=%lld n=%lld K=%lld", B,
|
||||
(long long)M, (long long)n, (long long)K);
|
||||
const RadKernelInfo* rg = find(pl, "gemm_iqr_gated");
|
||||
const RadKernelInfo* rm = find(pl, "gemm_iqr_nt_m64");
|
||||
const RadKernelInfo* rq = find(pl, "gated_had_quant_i8g");
|
||||
if (!rg || !rm || !rq) { ok(nm, false, "rows absent"); return; }
|
||||
Planes p = iqr_v4_planes(N, K, B, 0x6A7ED00Du + (uint64_t)(B * 97 + M));
|
||||
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h") };
|
||||
std::vector<uint8_t> wq, wsc, wq2, wsc2;
|
||||
RadLayout lw, ls;
|
||||
if (stored(rg, lp, 2, p, { "codes", "trellis", "trellis.mad" }, &wq, &lw) != RAD_OK ||
|
||||
stored(rg, lp, 3, p, { "scale", "scale.col" }, &wsc, &ls) != RAD_OK ||
|
||||
stored(rm, lp, 2, p, { "codes", "trellis", "trellis.mad" }, &wq2) != RAD_OK ||
|
||||
stored(rm, lp, 3, p, { "scale", "scale.col" }, &wsc2) != RAD_OK) {
|
||||
ok(nm, false, "relayout refused");
|
||||
return;
|
||||
}
|
||||
ok((std::string(nm) + ": the weight stored as gemm_iqr_nt_m64 stores it").c_str(), wq == wq2 && wsc == wsc2);
|
||||
uint64_t z = 0xA5A5F00Du + (uint64_t)M;
|
||||
auto rnd = [&]() { z ^= z << 13; z ^= z >> 7; z ^= z << 17; return z; };
|
||||
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, -5);
|
||||
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_q = dalloc((size_t)(M * n));
|
||||
void* d_sc = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
void* d_yb = dalloc((size_t)(M * n) * 2);
|
||||
void* d_y = dalloc((size_t)(M * N) * 2);
|
||||
void* d_q2 = dalloc((size_t)(M * n));
|
||||
void* d_sc2 = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
void* d_yb2 = dalloc((size_t)(M * n) * 2);
|
||||
if (!d_a || !d_as || !d_w || !d_s || !d_q || !d_sc || !d_yb || !d_y || !d_q2 || !d_sc2 || !d_yb2) {
|
||||
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);
|
||||
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);
|
||||
};
|
||||
const RadTensor tw = T(d_w, lw.dtype, { N, K }), ts = T(d_s, ls.dtype, { N, nkb });
|
||||
int r1 = RAD_OK;
|
||||
/* Twice: the second call finds the group counters the first left at zero. */
|
||||
for (int rep = 0; rep < 2 && r1 == RAD_OK; ++rep)
|
||||
r1 = launch(rg, { T(d_a, RAD_I8, { M, K }), T(d_as, RAD_F32, { M, nkb }), tw, ts,
|
||||
T(d_q, RAD_I8, { M, n }), T(d_sc, RAD_F32, { M, n / 128 }),
|
||||
T(d_yb, RAD_BF16, { M, n }) },
|
||||
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h"),
|
||||
PS("act", "silu") });
|
||||
std::vector<RadTensor> tm = { T(d_a, RAD_I8, { M, K }), T(d_as, RAD_F32, { M, nkb }), tw, ts,
|
||||
T(d_y, RAD_BF16, { M, N }), T(nullptr, RAD_F32, { 1 }),
|
||||
T(nullptr, RAD_U8, { 1 }) };
|
||||
absent(tm[5]); absent(tm[6]);
|
||||
const int r2 = launch(rm, tm, { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h") });
|
||||
const int r3 = r2 == RAD_OK
|
||||
? launch(rq, { T(d_y, RAD_BF16, { M, N }), T(d_q2, RAD_I8, { M, n }),
|
||||
T(d_sc2, RAD_F32, { M, n / 128 }), T(d_yb2, RAD_BF16, { M, n }) },
|
||||
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") })
|
||||
: r2;
|
||||
if (r1 != RAD_OK || r3 != RAD_OK) {
|
||||
ok(nm, false, "rc " + std::to_string(r1) + " (chain " + std::to_string(r3) + ")");
|
||||
return;
|
||||
}
|
||||
std::vector<uint8_t> q((size_t)(M * n)), q2(q.size()), sc((size_t)(M * (n / 128)) * 4), sc2(sc.size()),
|
||||
yb((size_t)(M * n) * 2), yb2(yb.size());
|
||||
st_memcpy(q.data(), d_q, q.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(q2.data(), d_q2, q2.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(sc.data(), d_sc, sc.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(sc2.data(), d_sc2, sc2.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(yb.data(), d_yb, yb.size(), hipMemcpyDeviceToHost);
|
||||
st_memcpy(yb2.data(), d_yb2, yb2.size(), hipMemcpyDeviceToHost);
|
||||
size_t dq = 0, ds = 0, dy = 0;
|
||||
for (size_t i = 0; i < q.size(); ++i) dq += q[i] != q2[i];
|
||||
for (size_t i = 0; i < sc.size(); i += 4) ds += std::memcmp(&sc[i], &sc2[i], 4) != 0;
|
||||
for (size_t i = 0; i < yb.size(); i += 2) dy += std::memcmp(&yb[i], &yb2[i], 2) != 0;
|
||||
char d[160];
|
||||
std::snprintf(d, sizeof d, "%zu codes, %zu scales, %zu products differ", dq, ds, dy);
|
||||
ok(nm, dq == 0 && ds == 0 && dy == 0, d);
|
||||
}
|
||||
|
||||
/* --perfiqr: the IQR row at one shape over the V4 trunk's form (a 2^16-state computed trellis of
|
||||
* B-bit codes in 256-row runs, one f32 scale a row, fwht128) with random codes, the weight streamed
|
||||
* from DRAM (rotated copies), then the MXFP4 rows at the same shape (--perfmxd). Timing only. */
|
||||
static void iqr_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int B, int iters) {
|
||||
/* B >= 10: the head-fed form (V4's v4h grids), B - 10 bits under a bf16 scale a (row, 128). */
|
||||
const bool bf16s = B >= 10;
|
||||
if (bf16s) B -= 10;
|
||||
if (N % 256 || K % 256 || M < 1 || B < 2 || B > 8) {
|
||||
std::printf("--perfiqr: N and K multiples of 256, M >= 1, 2 <= B <= 8 (+10: bf16 scales)\n");
|
||||
return;
|
||||
}
|
||||
const char* row = M <= 64 ? "gemm_iqr_nt_m64" : "gemm_iqr_tiled";
|
||||
const RadKernelInfo* r = find(pl, row);
|
||||
if (!r || !r->layout || !r->relayout) { std::printf(" %-22s row or hooks absent\n", row); return; }
|
||||
const int64_t nkb = K / 128;
|
||||
uint64_t z = 0x51ED2701u + (uint64_t)B;
|
||||
auto rnd = [&]() {
|
||||
z += 0x9E3779B97F4A7C15ull;
|
||||
uint64_t x = z;
|
||||
x = (x ^ (x >> 30)) * 0xBF58476D1CE4E5B9ull;
|
||||
x = (x ^ (x >> 27)) * 0x94D049BB133111EBull;
|
||||
return x ^ (x >> 31);
|
||||
};
|
||||
Planes p = iqr_v4_planes(N, K, B, z, bf16s);
|
||||
std::vector<RadParam> lp = { PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h") };
|
||||
std::vector<uint8_t> wq, wsc;
|
||||
RadLayout lw, ls;
|
||||
if (stored(r, lp, 2, p, { "codes", "trellis", "trellis.mad" }, &wq, &lw) != RAD_OK ||
|
||||
(bf16s ? stored(r, lp, 3, p, { "scale" }, &wsc, &ls)
|
||||
: stored(r, lp, 3, p, { "scale", "scale.col" }, &wsc, &ls)) != RAD_OK) {
|
||||
std::printf(" %-22s relayout refused\n", row);
|
||||
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);
|
||||
const int copies = (int)std::max<int64_t>(2, (256ll << 20) / (int64_t)wq.size() + 1);
|
||||
void* d_a = dalloc(ha.size());
|
||||
void* d_as = dalloc(has.size() * 4);
|
||||
void* d_w = dalloc(wq.size() * (size_t)copies);
|
||||
void* d_s = dalloc(wsc.size());
|
||||
void* d_y = dalloc((size_t)(M * N) * 2);
|
||||
if (!d_a || !d_as || !d_w || !d_s || !d_y) { std::printf(" %-22s hipMalloc failed\n", row); return; }
|
||||
st_memcpy(d_a, ha.data(), ha.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_as, has.data(), has.size() * 4, hipMemcpyHostToDevice);
|
||||
for (int c = 0; c < copies; ++c)
|
||||
st_memcpy((uint8_t*)d_w + (size_t)c * wq.size(), wq.data(), wq.size(), hipMemcpyHostToDevice);
|
||||
st_memcpy(d_s, wsc.data(), wsc.size(), hipMemcpyHostToDevice);
|
||||
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<RadParam> gp = { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h") };
|
||||
char nm[64];
|
||||
std::snprintf(nm, sizeof nm, "iqr k%d%s %s", B, bf16s ? "h" : "", M <= 64 ? "m64" : "tiled");
|
||||
std::printf("\nN=%lld K=%lld M=%lld\n", (long long)N, (long long)K, (long long)M);
|
||||
perf_row(pl, row, tq, gp, d_w, wq.size(), copies, (double)(wq.size() + wsc.size()), iters, 2, nm);
|
||||
/* At a gate_up shape to 16 tokens: the gated fold, and the quantiser it replaces. */
|
||||
if (N % 256 == 0 && M <= 16) {
|
||||
const int64_t n = N / 2;
|
||||
void* d_q = dalloc((size_t)(M * n));
|
||||
void* d_sc = dalloc((size_t)(M * (n / 128)) * 4);
|
||||
if (d_q && d_sc) {
|
||||
perf_row(pl, "gemm_iqr_gated",
|
||||
{ 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_q, RAD_I8, { M, n }), T(d_sc, RAD_F32, { M, n / 128 }),
|
||||
T(nullptr, RAD_BF16, {}) },
|
||||
{ PI("M", M), PI("N", N), PI("K", K), PI("group", 128), PS("dtype", "i8a8h"),
|
||||
PS("act", "silu") },
|
||||
d_w, wq.size(), copies, (double)(wq.size() + wsc.size()), iters, 2);
|
||||
RadTensor nob = T(nullptr, RAD_BF16, { M, n });
|
||||
absent(nob);
|
||||
perf_row(pl, "gated_had_quant_i8g",
|
||||
{ T(d_y, RAD_BF16, { M, N }), T(d_q, RAD_I8, { M, n }), T(d_sc, RAD_F32, { M, n / 128 }), nob },
|
||||
{ PI("M", M), PI("n", n), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") },
|
||||
d_y, (size_t)(M * N * 2), 1, (double)(M * N * 2), iters, 0);
|
||||
}
|
||||
}
|
||||
dfree_all();
|
||||
mx_perf(pl, N, K, M, iters);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the small ops, timed
|
||||
*
|
||||
* Most of a decode step's kernels are small ops moving a few tens of kilobytes, so their cost is
|
||||
@@ -20636,6 +21180,118 @@ static void fp8f32_forms(const Plugin& pl, int64_t M, int64_t N, int64_t K, int
|
||||
}
|
||||
}
|
||||
|
||||
/* The vocabulary-weighted head at one shape against the int8 head (logits_gemm_i8) and the 6-bit
|
||||
* table head (logits_gemm_iqr) over the same rows: `spec` its classes as B:rows,B:rows (a rank's
|
||||
* share), K n_embd, M tokens. Codes and scales are random bytes (the time does not depend on
|
||||
* them), the vocabulary ids a random permutation, ascending within each class as the converter
|
||||
* stores them. GB/s is on each head's stored bytes. */
|
||||
static void vocab_perf(const Plugin& pl, const char* spec, int64_t K, int64_t M, int iters) {
|
||||
using namespace r4d_iqr;
|
||||
std::vector<std::pair<int, int64_t>> cls;
|
||||
for (const char* p = spec; *p;) {
|
||||
const int B = (int)std::strtol(p, (char**)&p, 10);
|
||||
if (*p != ':') break;
|
||||
const int64_t n = std::strtoll(p + 1, (char**)&p, 10);
|
||||
cls.emplace_back(B, n);
|
||||
if (*p == ',') ++p;
|
||||
}
|
||||
int64_t N = 0;
|
||||
for (auto& c : cls) N += c.second;
|
||||
if (cls.empty() || cls.size() > 4 || K % 256 || M < 1 || N % 16) {
|
||||
std::printf("--perfvocab: B:rows[,B:rows..] (1-4 classes, rows a multiple of 256) K M\n");
|
||||
return;
|
||||
}
|
||||
const RadKernelInfo* rv = find(pl, "logits_gemm_vocab_iqr");
|
||||
const RadKernelInfo* ri = find(pl, "logits_gemm_i8");
|
||||
const RadKernelInfo* rq = find(pl, "logits_gemm_iqr");
|
||||
if (!rv || !ri || !rq) { std::printf("--perfvocab: rows absent\n"); return; }
|
||||
uint64_t z = 12345;
|
||||
auto fill = [&](void* d, size_t n) {
|
||||
std::vector<uint8_t> h(n);
|
||||
for (auto& b : h) { z = z * 6364136223846793005ull + 1442695040888963407ull; b = (uint8_t)(z >> 56) & 0x3Fu; }
|
||||
st_memcpy(d, h.data(), n, hipMemcpyHostToDevice);
|
||||
};
|
||||
void* d_x = dalloc((size_t)(M * K) * 2);
|
||||
void* d_y = dalloc((size_t)(M * N) * 4);
|
||||
fill(d_x, (size_t)(M * K) * 2);
|
||||
std::vector<RadTensor> ts(15);
|
||||
std::vector<RadParam> gp = { PI("M", M), PI("n_vocab", N), PI("n_embd", K), PS("dtype", "bf16"),
|
||||
PI("vocab_offset", 0) };
|
||||
std::vector<int32_t> vrow((size_t)N);
|
||||
static const char* kRows[] = { "rows0", "rows1", "rows2", "rows3" };
|
||||
std::vector<int32_t> perm((size_t)N);
|
||||
for (int64_t i = 0; i < N; ++i) perm[(size_t)i] = (int32_t)i;
|
||||
for (int64_t i = N - 1; i > 0; --i) {
|
||||
z = z * 6364136223846793005ull + 1442695040888963407ull;
|
||||
std::swap(perm[(size_t)i], perm[(size_t)((z >> 33) % (uint64_t)(i + 1))]);
|
||||
}
|
||||
double vbytes = 0;
|
||||
int64_t base = 0;
|
||||
for (size_t i = 0; i < cls.size(); ++i) {
|
||||
const Form f{ kTrellisMad, (uint32_t)cls[i].first, 0, 16, 0, kRowF32, 8, 0 };
|
||||
const int64_t n = cls[i].second, wb = weight_bytes(f, n, K), sb = scale_bytes(f, n, K);
|
||||
void* d_w = dalloc((size_t)wb);
|
||||
void* d_s = dalloc((size_t)sb);
|
||||
fill(d_w, (size_t)wb);
|
||||
std::vector<float> sc((size_t)(sb / 4), 1e-3f);
|
||||
st_memcpy(d_s, sc.data(), (size_t)sb, hipMemcpyHostToDevice);
|
||||
/* a class's ids ascending, as the converter writes them */
|
||||
std::sort(perm.begin() + base, perm.begin() + base + n);
|
||||
for (int64_t j = 0; j < n; ++j)
|
||||
vrow[(size_t)perm[(size_t)(base + j)]] = (int32_t)((uint32_t)cls[i].first << 28) | (int32_t)j;
|
||||
void* d_r = dalloc((size_t)n * 4);
|
||||
st_memcpy(d_r, perm.data() + base, (size_t)n * 4, hipMemcpyHostToDevice);
|
||||
ts[1 + 3 * i] = T(d_w, R4D_DT_IQR_W | word(f), { n, K });
|
||||
ts[2 + 3 * i] = T(d_s, R4D_DT_IQR_S | word(f), { n, K / 128 });
|
||||
ts[3 + 3 * i] = T(d_r, RAD_I32, { n });
|
||||
gp.push_back(PI(kRows[i], n));
|
||||
vbytes += (double)(wb + sb + n * 4);
|
||||
base += n;
|
||||
}
|
||||
for (size_t i = cls.size(); i < 4; ++i)
|
||||
for (int j = 0; j < 3; ++j) { ts[1 + 3 * i + (size_t)j] = T(nullptr, RAD_U8, { 1 }); absent(ts[1 + 3 * i + (size_t)j]); }
|
||||
void* d_m = dalloc((size_t)N * 4);
|
||||
st_memcpy(d_m, vrow.data(), (size_t)N * 4, hipMemcpyHostToDevice);
|
||||
vbytes += (double)N * 4;
|
||||
ts[0] = T(d_x, RAD_BF16, { M, K });
|
||||
ts[13] = T(d_m, RAD_I32, { N, 1 });
|
||||
ts[14] = T(d_y, RAD_F32, { M, N });
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
a.t = ts.data(); a.n_t = (int)ts.size(); a.p = gp.data(); a.n_p = (int)gp.size(); a.world_size = 1;
|
||||
const int64_t need = rv->scratch(&a);
|
||||
a.scratch = dalloc((size_t)need); a.scratch_bytes = need;
|
||||
if (rv->launch(&a, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) { std::printf("--perfvocab: launch failed\n"); return; }
|
||||
const double tv = st_time_us([&](int) { rv->launch(&a, nullptr); }, iters, nullptr);
|
||||
|
||||
/* the int8 head and the 6-bit table head over N rows */
|
||||
const int64_t ib = N * r4d_fp8::lm_row_bytes(K);
|
||||
const Form ft{ kTable, 6, 0, 0, 0, kBf16, 0, 0 };
|
||||
const int64_t qb = lm_bytes(ft, N, K);
|
||||
void* d_i = dalloc((size_t)ib);
|
||||
void* d_q = dalloc((size_t)qb);
|
||||
fill(d_i, (size_t)ib);
|
||||
fill(d_q, (size_t)qb);
|
||||
std::vector<RadParam> lp = { PI("M", M), PI("n_vocab", N), PI("n_embd", K), PS("dtype", "bf16") };
|
||||
std::vector<RadTensor> ti = { T(d_x, RAD_BF16, { M, K }), T(d_i, RAD_I8, { N, K }), T(d_y, RAD_F32, { M, N }) };
|
||||
std::vector<RadTensor> tq = { T(d_x, RAD_BF16, { M, K }), T(d_q, R4D_DT_IQR_W | word(ft), { N, K }), T(d_y, RAD_F32, { M, N }) };
|
||||
auto timed = [&](const RadKernelInfo* r, std::vector<RadTensor>& t) {
|
||||
RadArgs b;
|
||||
std::memset(&b, 0, sizeof(b));
|
||||
b.t = t.data(); b.n_t = (int)t.size(); b.p = lp.data(); b.n_p = (int)lp.size(); b.world_size = 1;
|
||||
if (r->scratch) { const int64_t s = r->scratch(&b); if (s > 0) { b.scratch = dalloc((size_t)s); b.scratch_bytes = s; } }
|
||||
if (r->launch(&b, nullptr) != RAD_OK || st_stream_sync(nullptr) != hipSuccess) return -1.0;
|
||||
return st_time_us([&](int) { r->launch(&b, nullptr); }, iters, nullptr);
|
||||
};
|
||||
const double t8 = timed(ri, ti), t6 = timed(rq, tq);
|
||||
std::printf("\nlm_head N=%lld K=%lld M=%lld, %d iters\n", (long long)N, (long long)K, (long long)M, iters);
|
||||
std::printf(" %-26s %9.1f us %7.1f MiB %6.1f GB/s %.3f b a weight\n", ("vocab " + std::string(spec)).c_str(), tv,
|
||||
vbytes / (1 << 20), vbytes / (tv * 1e3), vbytes * 8 / (double)(N * K));
|
||||
std::printf(" %-26s %9.1f us %7.1f MiB %6.1f GB/s\n", "int8 (logits_gemm_i8)", t8, ib / 1048576.0, ib / (t8 * 1e3));
|
||||
std::printf(" %-26s %9.1f us %7.1f MiB %6.1f GB/s\n", "6-bit table (logits_gemm_iqr)", t6, qb / 1048576.0, qb / (t6 * 1e3));
|
||||
dfree_all();
|
||||
}
|
||||
|
||||
/* The block-quantised trunk GEMMs GLM's checkpoints resolve to, at one shape: E4M3 with F32
|
||||
* 128x128 block scales (gemm_fp8a8_f32scale, the MLA and dense-MLP projections) and OCP-MXFP4
|
||||
* (the shared experts' rows: skinny, decode split and tiled). GB/s is on the weight and its scale
|
||||
@@ -31523,9 +32179,10 @@ static void device_phase(const Plugin& pl) {
|
||||
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. */
|
||||
* tables, grids and zero; V2's 4096-state trellis; V3's 16384-state one on tcq_rb=32. M 1
|
||||
* reaches the GEMV, 2 the GEMV on 2- and 3-bit computed codes under one f32 scale a row, 4
|
||||
* and 8 the GEMV off the computed trellis; else to 16 the 16-token tile; 17 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 },
|
||||
@@ -31538,16 +32195,27 @@ static void device_phase(const Plugin& pl) {
|
||||
{ 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, 5, 0, 16, 1, true, true }, { 6, 6, 0, 16, 1, true, true }, { 6, 7, 0, 16, 1, true, true },
|
||||
{ 6, 4, 0, 16, 1, false, true }, { 6, 5, 0, 16, 1, false, true },
|
||||
{ 6, 6, 0, 16, 1, false, true }, { 6, 7, 0, 16, 1, false, 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 int b : { 2, 3, 4, 6 })
|
||||
for (const int64_t m : { (int64_t)1, (int64_t)2, (int64_t)5, (int64_t)16 })
|
||||
iqr_gated_case(pl, b, m, 1024, 1280);
|
||||
iqr_gated_case(pl, 4, 1, 17408, 5120);
|
||||
iqr_gated_case(pl, 4, 9, 17408, 5120);
|
||||
for (const IqrCase& f : fs) {
|
||||
iqr_gemm_case(pl, f, 1, 512, 1024);
|
||||
iqr_gemm_case(pl, f, 2, 4096, 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, 16, 4096, 2560);
|
||||
iqr_gemm_case(pl, f, 17, 512, 1024);
|
||||
iqr_gemm_case(pl, f, 64, 512, 2560);
|
||||
iqr_gemm_case(pl, f, 300, 512, 1024);
|
||||
}
|
||||
@@ -32805,11 +33473,21 @@ static void device_phase(const Plugin& pl) {
|
||||
iqr_head_case(pl, 5, 4096, 5120, 1);
|
||||
iqr_head_case(pl, 4, 4096, 5120, 8);
|
||||
}
|
||||
if (sel("logits_gemm_vocab_iqr")) {
|
||||
const std::vector<VocabClass> four = { { 4, 768 }, { 5, 512 }, { 6, 256 }, { 7, 256 } };
|
||||
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)16, (int64_t)37, (int64_t)64, (int64_t)100 })
|
||||
vocab_head_case(pl, four, M, 512, 0);
|
||||
vocab_head_case(pl, { { 3, 512 }, { 2, 256 } }, 9, 1024, 768);
|
||||
vocab_head_case(pl, { { 3, 512 }, { 2, 256 } }, 40, 1024, 768);
|
||||
vocab_head_case(pl, { { 5, 1024 } }, 8, 5120, 0);
|
||||
}
|
||||
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 },
|
||||
{ 3, 5, 0, false, false }, { 2, 6, 0, false, false }, { 2, 7, 0, false, false },
|
||||
{ 2, 8, 0, false, false }, { 5, 2, 12, true, true },
|
||||
{ 5, 3, 12, true, true }, { 5, 4, 12, true, true }, { 5, 5, 12, true, true },
|
||||
{ 5, 6, 12, true, true }, { 5, 7, 12, true, true },
|
||||
};
|
||||
for (const IqrEmbedCase& f : es) {
|
||||
iqr_embed_case(pl, f, 512, 640, 1.0f);
|
||||
@@ -32824,6 +33502,8 @@ static void device_phase(const Plugin& pl) {
|
||||
fp8_logits_numeric(pl, 2560, 2560, M, true);
|
||||
}
|
||||
|
||||
gate_had_case(pl, 37, 256);
|
||||
gate_had_case(pl, 4, 128);
|
||||
/* The fused quantisers are checked against the kernels they replace, gated on their own
|
||||
* rows. */
|
||||
if (sel("rmsnorm_quant_fp8") || sel("gated_quant_fp8") || sel("gate_quant_fp8") ||
|
||||
@@ -33079,11 +33759,15 @@ static void usage(void) {
|
||||
" N a gate_up's width) and print the weight bandwidth each reaches.\n"
|
||||
" --perfwpa N K M [iters] [pb1]: the int5 and int4 x int8 tiled GEMMs (gemm_w5a8i8_tiled,\n"
|
||||
" gemm_w4a8i8_tiled), warmed, min / median time and a hash of the output.\n"
|
||||
" --perfiqr N K M B [iters]: the IQR row over a B-bit V4 trunk form (B + 10: the head-fed\n"
|
||||
" form, a bf16 scale a (row, 128)), then --perfmxd\n"
|
||||
" --perfmxd N K M [iters]: the dense MXFP4 GEMM rows (gemv, decode, skinny, tiled) at\n"
|
||||
" one shape, with the weight bandwidth each reaches.\n"
|
||||
" --perfbf16 N K M [iters]: the bf16 skinny GEMM at every variant it has.\n"
|
||||
" --perff32 N K M [iters]: gemm_nt_f32 at the tile form its rule picks, compared\n"
|
||||
" byte for byte with the host arithmetic, with GB/s and TFLOP/s.\n"
|
||||
" --perfvocab B:rows,.. K M [iters]: the vocabulary-weighted head against the int8\n"
|
||||
" and 6-bit table heads over the same rows\n"
|
||||
" --perfq N K M [iters]: the block-quantised trunk rows GLM resolves to: E4M3 with\n"
|
||||
" F32 block scales and the three OCP-MXFP4 rows, GB/s on weight + scales.\n"
|
||||
" --perfw4 N K M [iters]: a tuning sweep of the asymmetric W4 x F16 GEMM;\n"
|
||||
@@ -33204,7 +33888,8 @@ int main(int argc, char** argv) {
|
||||
long long real_woff = 0, real_soff = 0, real_n = 0, real_k = 0;
|
||||
long long perf_n = 0, perf_k = 0, perf_m = 0;
|
||||
int perf_it = 50, perf_w2 = 0, perf_w4 = 0, perf_bf = 0, perf_w8 = 0, perf_f32 = 0,
|
||||
perf_q = 0, perf_mx = 0, perf_wpa = 0;
|
||||
perf_q = 0, perf_mx = 0, perf_wpa = 0, perf_vocab = 0, perf_iqr = 0;
|
||||
const char* vocab_spec = nullptr;
|
||||
long long perf_pb1 = 0;
|
||||
long long sop_m = 0, sop_k = 0;
|
||||
int sop_it = 2000;
|
||||
@@ -33277,6 +33962,13 @@ int main(int argc, char** argv) {
|
||||
perf_m = std::strtoll(argv[++i], nullptr, 0);
|
||||
if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0);
|
||||
if (i + 1 < argc && argv[i + 1][0] != '-') perf_pb1 = std::strtoll(argv[++i], nullptr, 0);
|
||||
} else if (!std::strcmp(argv[i], "--perfiqr")) {
|
||||
if (i + 4 >= argc) { usage(); return 2; }
|
||||
perf_n = std::strtoll(argv[++i], nullptr, 0);
|
||||
perf_k = std::strtoll(argv[++i], nullptr, 0);
|
||||
perf_m = std::strtoll(argv[++i], nullptr, 0);
|
||||
perf_iqr = (int)std::strtol(argv[++i], nullptr, 0);
|
||||
if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0);
|
||||
} else if (!std::strcmp(argv[i], "--perfmxd")) {
|
||||
if (i + 3 >= argc) { usage(); return 2; }
|
||||
perf_mx = 1;
|
||||
@@ -33300,6 +33992,15 @@ int main(int argc, char** argv) {
|
||||
perf_k = std::strtoll(argv[++i], nullptr, 0);
|
||||
perf_m = std::strtoll(argv[++i], nullptr, 0);
|
||||
if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0);
|
||||
} else if (!std::strcmp(argv[i], "--perfvocab")) {
|
||||
/* the vocabulary-weighted head against the int8 and table heads (see vocab_perf) */
|
||||
if (i + 3 >= argc) { usage(); return 2; }
|
||||
perf_vocab = 1;
|
||||
perf_n = 1;
|
||||
vocab_spec = argv[++i];
|
||||
perf_k = std::strtoll(argv[++i], nullptr, 0);
|
||||
perf_m = std::strtoll(argv[++i], nullptr, 0);
|
||||
if (i + 1 < argc && argv[i + 1][0] != '-') perf_it = (int)std::strtol(argv[++i], nullptr, 0);
|
||||
} else if (!std::strcmp(argv[i], "--perfq")) {
|
||||
/* GLM's block-quantised trunk rows (see q_perf). */
|
||||
if (i + 3 >= argc) { usage(); return 2; }
|
||||
@@ -33728,7 +34429,9 @@ int main(int argc, char** argv) {
|
||||
#ifdef RAD_HAVE_HIP
|
||||
if (perf_f32) f32_forms(pl, perf_m, perf_n, perf_k, perf_it, true);
|
||||
else if (perf_q) q_perf(pl, perf_n, perf_k, perf_m, perf_it);
|
||||
else if (perf_vocab) vocab_perf(pl, vocab_spec, perf_k, perf_m, perf_it);
|
||||
else if (perf_wpa) wpa_perf(pl, perf_n, perf_k, perf_m, perf_it, perf_pb1);
|
||||
else if (perf_iqr) iqr_perf(pl, perf_n, perf_k, perf_m, perf_iqr, perf_it);
|
||||
else if (perf_mx) mx_perf(pl, perf_n, perf_k, perf_m, perf_it);
|
||||
else if (perf_bf) bf16_perf(pl, perf_n, perf_k, perf_m, perf_it);
|
||||
else if (perf_w4) w5a16_perf(pl, 4, perf_m, perf_n, perf_k, perf_it,
|
||||
|
||||
@@ -2024,7 +2024,7 @@ extern "C" int r4d_shape_gram_accum(const RadParam* p, int n_p, int operand, Rad
|
||||
const int64_t n = pi(p, n_p, "n");
|
||||
const int64_t g = pi(p, n_p, "group", R4D_FP8_BLOCK);
|
||||
/* dtype bf16 is a plain activation with no scale operand; fp8a8 is E4M3 codes and a dequant
|
||||
* scale per (row, group). */
|
||||
* scale per (row, group), i8a8 the same with int8 codes. */
|
||||
const char* dt = rad_param_gets(p, n_p, "dtype", nullptr);
|
||||
if (dt && !std::strcmp(dt, "bf16")) {
|
||||
const RadOpdDesc l[] = {
|
||||
@@ -2035,8 +2035,10 @@ extern "C" int r4d_shape_gram_accum(const RadParam* p, int n_p, int operand, Rad
|
||||
R4D_PICK(l);
|
||||
}
|
||||
if (g != R4D_FP8_BLOCK) return RAD_E_UNSUPPORTED;
|
||||
/* i8a8: an int8 trunk's codes, with the same scale grid. */
|
||||
const uint32_t q = dt && !std::strcmp(dt, "i8a8") ? (uint32_t)RAD_I8 : (uint32_t)RAD_F8E4M3;
|
||||
const RadOpdDesc l[] = {
|
||||
opd((uint32_t)RAD_F8E4M3, M, n),
|
||||
opd(q, M, n),
|
||||
opd((uint32_t)RAD_F32, M, (n + g - 1) / g),
|
||||
opd((uint32_t)RAD_F32, n, n),
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user