diff --git a/docs/OPS.md b/docs/OPS.md index a588af79..acc99c31 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -190,6 +190,7 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | op | params | operands | |---|---|---| | `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) | +| `rmsnorm_rows` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (the same norm; at n <= 256 with 1024+ rows a wave a row, byte-identical) | | `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` | | `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` | | `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` | @@ -617,6 +618,7 @@ and is optional. | `gated_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `swiglu_clamped_quant_fp8` | `M`(range) `n` `limit`:f64 `group` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | | `gemm_nt_q_gated` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? | +| `gemm_nt_q_gated_wide` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w → `q`, `scale`, `out_bf16`? (the same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile) | | `gemm_nt_q_gated_mx` | `M` `N` `K` `group` `dtype` `act` | `a`, `a_scale`, `b`w, `b_scale`w, `b_ref`w → `q`, `scale`, `out_bf16`? | `quant_cols_fp8` is the same E4M3 quantiser with one scale per column over all `M` rows, @@ -730,6 +732,7 @@ may not have arrived. | `gemm_nt_f32` | `M`(range) `N` `K` `dtype` | `a`, `b`w → `y` | | `gemm_nt_bias` | `M`(range) `N` `K` `dtype` `act`/opt | `a`, `b`w, `bias`w, `res`? → `y` | | `gemm_nt_q` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? | +| `gemm_nt_q_short` | `M`(range) `N` `K` `group` `dtype` `pb1`/opt `pb2`/opt `split_n`/opt | `a`, `a_scale`?, `b`w, `b_scale`w → `y`; `a_sum`?, `b_ref`w? (the narrow fp8 row with the short-prompt split rule: N <= 512, K <= 5120 and 41..64 rows run unsplit) | | `gemm_nt_q_bias` | `M`(range) `N` `K` `group` `dtype` | `a`, `a_scale`, `b`w, `b_scale`w, `bias`w → `y` | `nt` is A row-major `[M,K]` times B transposed `[N,K]`, giving `[M,N]`: the layout every weight in @@ -893,6 +896,7 @@ as the weight's GEMM stored them and claims no form. It changes no value. | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | | `kv_store_streamed` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout, `res`, `host`:inout | | `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` | +| `rope_rows` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt `llama3_factor`:f64/opt `llama3_low`:f64/opt `llama3_high`:f64/opt `llama3_orig`:f64/opt | `qkv`:inout, `positions` (the same rotation; at 64+ rows and 4+ heads one angle a (token, pair), byte-identical) | | `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`?, `q_w`w?, `k_w`w? | | `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `v_norm`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | diff --git a/libr4d/r4d.h b/libr4d/r4d.h index 64350406..0dcde7e8 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -757,6 +757,13 @@ int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, int a_ld, int sa_ld, int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream); int r4d_gemm_fp8a8_gated_nt_m16_max_m(void); +// The same fold at any M (`gemm_nt_q_gated_wide`): past the narrow tile's 64 rows it takes the gated +// prefill tile, whose accumulators are the unfused prefill GEMM's, so its bytes are the pair's. +int r4d_gemm_fp8a8_gated_nt_wide(long a, long ascale, long wq, long ws, + long q, long s, long y, int act, + int M, int K, int nout, + int a_ld, int sa_ld, int w_ld, int sw_ld, + int q_ld, int s_ld, int y_ld, long stream); // The narrow GEMM with a bias: `bias` bf16 [N], added to each output column's f32 accumulator before // its one rounding, and C written at row pitch `c_ld` (0 = N), so C may be a column slice of a wider // buffer. Never split. M up to r4d_gemm_fp8a8_nt_m16_max_m(); K a multiple of 128, N of 16. @@ -811,7 +818,7 @@ int r4d_rmsnorm_had_quant_i8g(long x, long res, long w, long y, long q, long s, int r4d_gated_had_quant_i8g(long gu, long y, long q, long s, int M, int n, int mode, int gu_ld, int y_ld, int q_ld, int s_ld, long stream); // The activation is rounded to bf16 before the product, matching the unfused `sigmoid` then `mul` -// pair with a bf16 buffer between them. +// pair with a bf16 buffer between them; `mode` 2 is the plain product (`mul` + quantiser). // The same epilogue with the gate in a different buffer from what it scales, as in gated // attention: `x` is the attention output and the gate a column slice of the [q|gate] projection. // A row is then a (token, head) pair; both sources are a fixed stride apart and the scale plane diff --git a/libr4d/r4d_fuse.cpp b/libr4d/r4d_fuse.cpp index 8bc0e3c5..3d7dc91e 100644 --- a/libr4d/r4d_fuse.cpp +++ b/libr4d/r4d_fuse.cpp @@ -413,6 +413,9 @@ extern "C" int r4d_fuse_router_sigmoid_topk_scatter(const RadParam* p, int n_p, * The gated attention's gate is a sigmoid, so nothing issues this row with silu and the shim's * `mode` defaults to 1. * + * `act` none is the plain product: the chain is `mul` then `quant_act_fp8`, and the kernel rounds + * the bf16 product once, exactly as mul_bf16 does. The product is TMP(0) or `out_bf16`. + * * TMP(0) is act(gate), an [M, n] bf16 plane the fusion never writes. `out_bf16` is an operand: the * kernel stores the product there when asked and takes the codes over those bytes. */ @@ -423,7 +426,28 @@ extern "C" int r4d_fuse_gate_quant_fp8(const RadParam* p, int n_p, uint64_t pres const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); if (!fp8_geometry_ok(p, n_p, M, n)) return RAD_E_UNSUPPORTED; /* The shim (r4d_fused_quant_fp8.hip) defaults this row's `mode` to 1 (sigmoid). */ - if (!act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED; + const bool none = act_is(p, n_p, "sigmoid", "none"); + if (!none && !act_is(p, n_p, "sigmoid", "sigmoid")) return RAD_E_UNSUPPORTED; + const int16_t mid = RAD_FUSE_HAS(present, 4) ? (int16_t)4 : RAD_FUSE_TMP(0); + + if (none) { + switch (step) { + case 0: { + /* gate * x, rounded to bf16 once: mul_bf16's store. */ + Step s(out, "mul"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "dtype"); + return s.wire({ 0, 1, mid }); /* a, b, y */ + } + case 1: { + Step s(out, "quant_act_fp8"); + s.mirror(p, n_p, "M").mirror(p, n_p, "n").mirror(p, n_p, "group") + .mirror(p, n_p, "dtype"); + return s.wire({ mid, 2, 3 }); /* x, q, scale */ + } + default: + return RAD_E_NOTFOUND; + } + } switch (step) { case 0: { diff --git a/libr4d/r4d_fused_quant_fp8.hip b/libr4d/r4d_fused_quant_fp8.hip index d734c42a..a482c9c8 100644 --- a/libr4d/r4d_fused_quant_fp8.hip +++ b/libr4d/r4d_fused_quant_fp8.hip @@ -245,6 +245,9 @@ __global__ __launch_bounds__(1024) void gated_quant_fp8_kernel( // then contiguous, the gate a fixed stride apart, and the scale plane [T * n_head, head_dim / 128] // is byte-identical to the [T, n_head * head_dim / 128] the out projection reads. Replaces three // launches (sigmoid, multiply, quantise) per attention layer. +// +// 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 __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( const uint16_t* __restrict__ g, const uint16_t* __restrict__ x, uint16_t* __restrict__ y, @@ -270,13 +273,18 @@ __global__ __launch_bounds__(1024) void gate_quant_fp8_kernel( } #pragma unroll for (int j = 0; j < 4; ++j) { - const float gv = bf2f(gb[j]); - // The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8: - // the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between - // them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output. - const uint16_t ab = - f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv))); - const uint16_t h = f2bf(bf2f(ab) * bf2f(xb[j])); + uint16_t h; + if (ACT == 2) { + h = f2bf(bf2f(gb[j]) * bf2f(xb[j])); + } else { + const float gv = bf2f(gb[j]); + // The activation is rounded to bf16 before the multiply, unlike gated_quant_fp8: + // the unfused reference here is `sigmoid` then `mul` with a bf16 buffer between + // them (silu_mul_bf16 keeps f32). Skipping the round trip changes the output. + const uint16_t ab = + f2bf(ACT == 0 ? gv / (1.0f + expf(-gv)) : 1.0f / (1.0f + expf(-gv))); + h = f2bf(bf2f(ab) * bf2f(xb[j])); + } if (yr) yr[c0 + j] = h; v[j] = bf2f(h); } @@ -850,7 +858,7 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in if (!g || !x || !q || !s) return -1; if (M <= 0 || n <= 0) return -2; if (n % 4) return -3; - if (mode != 0 && mode != 1) return -5; + if (mode < 0 || mode > 2) return -5; if (!g_ld) g_ld = n; if (!x_ld) x_ld = n; if (!y_ld) y_ld = n; @@ -867,7 +875,8 @@ static int gate_quant_fp8_emit(long g, long x, long y, long q, long s, int M, in (uint32_t)s_ld) #define R4D_GTQ(a) do { if (i8) R4D_GTQ_I(a, true); else R4D_GTQ_I(a, false); } while (0) if (mode == 0) R4D_GTQ(0); - else R4D_GTQ(1); + else if (mode == 1) R4D_GTQ(1); + else R4D_GTQ(2); #undef R4D_GTQ #undef R4D_GTQ_I if (emit_rc != RAD_OK) return -4; @@ -1058,6 +1067,7 @@ static int act_mode(const RadArgs* a, int dflt) { if (!act) return (int)r4d_geti_or(a, "mode", dflt); if (!std::strcmp(act, "silu")) return 0; if (!std::strcmp(act, "sigmoid")) return 1; + if (!std::strcmp(act, "none")) return 2; return -1; } diff --git a/libr4d/r4d_gemm_fp8a8.hip b/libr4d/r4d_gemm_fp8a8.hip index 5ead5e9c..b206876c 100644 --- a/libr4d/r4d_gemm_fp8a8.hip +++ b/libr4d/r4d_gemm_fp8a8.hip @@ -940,6 +940,185 @@ void gemm_8a8_prefill_kernel(const uint8_t* __restrict__ A, const float* __restr } } +// ---- the prefill tile, gated ------------------------------------------------------------------- +// +// gemm_nt_q_gated at prefill row counts: the gate|up GEMM with SwiGLU and the E4M3 quantiser in the +// epilogue, so the [M, 2n] bf16 product is never written and gated_quant_fp8 never re-reads it +// (7% of a 400-token prefill step of d1-3B on gfx1200: 74 us a layer). +// +// The 8-accumulator cap (above) holds by halving the activation side: a block owns 128 output +// columns, i.e. 128 gate rows and the same 128 up rows of the weight, against 64 activation rows. +// The eight waves are kPWW over the weight and kPWA over the activation as on the prefill tile; a +// wave owns kPTW gate tiles and the kPTW up tiles of the same columns, against kGPTA activation +// tiles. Since the accumulator mapping does not depend on the weight rows, a lane holds the gate +// and the up value of the same (token, column) and the gate needs no exchange; the per-token amax +// over the block's 128 columns closes across the four weight waves through LDS. +// +// Byte-identical to gemm_8a8_prefill_kernel followed by gated_quant_fp8: the K loop, the fold +// (ws * as, one fma) and so every accumulator are the prefill tile's; the accumulator is rounded to +// bf16 as that kernel's store rounds it, and from there the arithmetic is the narrow gated +// epilogue's, which is gated_quant_fp8's. +constexpr uint32_t kGPTA = 2; // activation tiles a wave +constexpr uint32_t kGBM = kPWA * kGPTA * 16; // 64 activation rows a block +constexpr uint32_t kGTW = 2 * kPTW; // the gate tiles, then the up tiles +static_assert(kGBM * 2u <= kPWaves * kWave, "two threads stage an activation row"); + +__global__ __launch_bounds__(kPWaves * kWave) +void gemm_8a8_gated_prefill_kernel(const uint8_t* __restrict__ A, const float* __restrict__ Sa, + const uint8_t* __restrict__ W, const uint16_t* __restrict__ Sw, + uint8_t* __restrict__ Q, float* __restrict__ Sc, + uint16_t* __restrict__ Yb, uint32_t M, uint32_t K, + uint32_t nout, uint32_t a_ld, uint32_t sa_ld, uint32_t sw_ld, + uint32_t q_ld, uint32_t s_ld, uint32_t y_ld) { + constexpr uint32_t P = lds_pitch(); + __shared__ __attribute__((aligned(16))) uint8_t s_a[2][kGBM * P]; + __shared__ float s_as[2][kGBM]; + __shared__ float s_amx[kPWW][kGBM]; + + const uint32_t tid = threadIdx.x, lane = tid % kWave; + const uint32_t wave = __builtin_amdgcn_readfirstlane(tid / kWave); + const uint32_t ww = wave % kPWW, wa = wave / kPWW; + + // The prefill tile's raster groups over activation bands. + uint32_t bm = blockIdx.x, bn = blockIdx.y; + if (gridDim.x > kGroupM) { + const uint32_t per = kGroupM * gridDim.y; + const uint32_t lin = blockIdx.y * gridDim.x + blockIdx.x; + const uint32_t first = (lin / per) * kGroupM, r = lin % per; + const uint32_t gm = min(gridDim.x - first, kGroupM); + bm = first + r % gm; + bn = r / gm; + } + const uint32_t m0 = bm * kGBM, c0 = bn * kBlock; // output columns [c0, c0 + 128) + const uint32_t ksuper = K / kSuperK, nkb = K / kBlock; + + // Staging: two threads a row over the block's 64 rows (the first 128 threads), rows past M + // re-reading row M-1, every load issued as on the prefill tile. + const bool stager = tid < kGBM * 2u; + const uint32_t sr = (tid / 2u) % kGBM, sc = (tid % 2u) * 32u; + const uint8_t* const asrc = A + (size_t)min(m0 + sr, M - 1u) * a_ld + sc; + const float* const ssrc = Sa + (size_t)min(m0 + tid % kGBM, M - 1u) * sa_ld; + // Weight tiles: the gate rows [c0, c0+128) and the up rows [nout + c0, ...), kPTW each a wave. + const uint32_t wtg = c0 / 16u + ww * kPTW, wtu = (nout + c0) / 16u + ww * kPTW; + const uint8_t* const wsg = W + (size_t)wtg * ksuper * kTileBytes + lane * kLaneBytes; + const uint8_t* const wsu = W + (size_t)wtu * ksuper * kTileBytes + lane * kLaneBytes; + auto wsrc = [&](uint32_t i) { + return i < kPTW ? wsg + (size_t)i * ksuper * kTileBytes + : wsu + (size_t)(i - kPTW) * ksuper * kTileBytes; + }; + const uint32_t arow = wa * kGPTA * 16u; + + f8v raw[kGTW][kGPTA], out[kGTW][kGPTA]; +#pragma unroll + for (uint32_t i = 0; i < kGTW; ++i) +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) out[i][j] = acc_zero(); + + Stage8 pa = stage8_load(asrc, stager); + Stage8 w0[kGTW], w1[kGTW]; +#pragma unroll + for (uint32_t i = 0; i < kGTW; ++i) w0[i] = stage8_load(wsrc(i), true); + s_as[0][tid % kGBM] = ssrc[0]; + float scn = ssrc[min(1u, nkb - 1u)]; + + auto tile = [&](uint32_t kb, uint32_t half, Stage8 (&cur)[kGTW], Stage8 (&nxt)[kGTW]) { + if (stager) stage8_store(s_a[half], sr, sc, pa); + if (half == 1u) s_as[(kb + 1u) % 2u][tid % kGBM] = scn; + lds_barrier(); + const uint32_t c1 = min(kb * kBlock + (half + 1u) * kPFK, K - kPFK); + pa = stage8_load(asrc + c1, stager); +#pragma unroll + for (uint32_t i = 0; i < kGTW; ++i) + nxt[i] = stage8_load(wsrc(i) + (size_t)(c1 / kSuperK) * kTileBytes, true); + if (half == 1u) scn = ssrc[min(kb + 2u, nkb - 1u)]; +#pragma unroll + for (uint32_t ks = 0; ks < kPFK / kK; ++ks) { + i2v bf[kGPTA]; +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) bf[j] = frag(s_a[half], arow + j * 16u, ks * kK, lane); +#pragma unroll + for (uint32_t i = 0; i < kGTW; ++i) { + const i2v af = frag_of(cur[i], ks); +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) + raw[i][j] = mma8(af, bf[j], (half == 0u && ks == 0u) ? acc_zero() : raw[i][j]); + } + } + }; + + for (uint32_t kb = 0; kb < nkb; ++kb) { + const float wg = bscale(Sw[(size_t)(c0 / kBlock) * sw_ld + kb]); + const float wu = bscale(Sw[(size_t)((nout + c0) / kBlock) * sw_ld + kb]); + tile(kb, 0u, w0, w1); + tile(kb, 1u, w1, w0); +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) { + const float as = s_as[kb % 2u][arow + j * 16u + frag_c(lane)]; +#pragma unroll + for (uint32_t i = 0; i < kGTW; ++i) { + const float s8 = (i < kPTW ? wg : wu) * as; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) + out[i][j][t] = __builtin_fmaf(acc_val(raw[i][j][t]), s8, out[i][j][t]); + } + } + } + + // gate and up rounded to bf16 as the prefill tile stores them, silu in f32, the product + // rounded to bf16, then the per-(token, 128 columns) E4M3 quantiser. + float v[kPTW][kGPTA][8]; +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) { + float m = 0.0f; +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) { + const float g = bf16_to_f32(f32_to_bf16(out[i][j][t])); + const float a = g / (1.0f + expf(-g)); + const uint16_t h = f32_to_bf16(a * bf16_to_f32(f32_to_bf16(out[i + kPTW][j][t]))); + v[i][j][t] = bf16_to_f32(h); + m = fmaxf(m, fabsf(v[i][j][t])); + } + // A token's 16 columns of a tile are in lanes c and c ^ 16; the other wave columns are in + // the other three weight waves. fmaxf is exact and order-free. + m = fmaxf(m, r4d_xor_lane<16>(m)); + if (lane < 16u) s_amx[ww][arow + j * 16u + lane] = m; + } + __syncthreads(); +#pragma unroll + for (uint32_t j = 0; j < kGPTA; ++j) { + const uint32_t r = arow + j * 16u + frag_c(lane), tok = m0 + r; + if (tok >= M) continue; + float mm = 0.0f; +#pragma unroll + for (uint32_t u = 0; u < kPWW; ++u) mm = fmaxf(mm, s_amx[u][r]); + const float sc8 = mm > 0.0f ? mm * (1.0f / 448.0f) : 1.0f; + if (ww == 0u && (lane >> 4) == 0u) Sc[(size_t)tok * s_ld + bn] = sc8; + const float inv = 1.0f / sc8; +#pragma unroll + for (uint32_t i = 0; i < kPTW; ++i) { + const uint32_t col0 = c0 + (ww * kPTW + i) * 16u + (lane >> 4) * 8u; + // The clamp is required (see r4d_q8.h): the builtin returns NaN out of range. + float qc[8]; +#pragma unroll + for (uint32_t t = 0; t < 8; ++t) qc[t] = fminf(fmaxf(v[i][j][t] * inv, -448.0f), 448.0f); + int pk[2] = { 0, 0 }; +#pragma unroll + for (uint32_t d = 0; d < 2; ++d) { + pk[d] = __builtin_amdgcn_cvt_pk_fp8_f32(qc[d * 4 + 0], qc[d * 4 + 1], pk[d], false); + pk[d] = __builtin_amdgcn_cvt_pk_fp8_f32(qc[d * 4 + 2], qc[d * 4 + 3], pk[d], true); + } + *(uint2*)(Q + (size_t)tok * q_ld + col0) = make_uint2((uint32_t)pk[0], (uint32_t)pk[1]); + if (Yb) { + uint16_t* const yr = Yb + (size_t)tok * y_ld + col0; + *(uint4*)yr = make_uint4(bf16x2_rne(v[i][j][0], v[i][j][1]), bf16x2_rne(v[i][j][2], v[i][j][3]), + bf16x2_rne(v[i][j][4], v[i][j][5]), bf16x2_rne(v[i][j][6], v[i][j][7])); + } + } + } +} + // The narrow tile's K width is kFKNarrow (256 B); 128 B loses at every wave count (see `kTPR`), and // is used only via narrow_fk for a K that 256 does not divide. @@ -1041,13 +1220,22 @@ uint32_t narrow_mw(uint32_t n, uint32_t m) { inline uint32_t narrow_fk(uint32_t K) { return (K % kFKNarrow == 0u) ? kFKNarrow : 128u; } // The split, given the narrow grid. Shared by the scratch query and the launch so they agree on the -// number of partial planes. -uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out) { +// number of partial planes. `short_unsplit` is the `gemm_nt_q_short` row's opt-in (see below). +uint32_t narrow_ksplit(uint32_t N, uint32_t K, uint32_t M, uint32_t* ck_out, + bool short_unsplit = false) { *ck_out = 0; const uint32_t mw = narrow_mw(N, M); const uint32_t fm = mw * 16u; // the narrow tile is one M tile a wave const uint32_t gx = (N + fm - 1) / fm; // the M grid runs over the weight rows if (K < 512u || gx * mw >= kSplitTarget) return 1; + /* A narrow weight (N <= 512, the attention k/v projections) at more than 40 tokens: the split + * runs into a cliff there (gfx1200, cold weights: N = 512, K = 2048, M = 44..64 split 51-54 us, + * unsplit 23-26; K = 5120, M = 41..64 58-63 against 40-48), while at K >= 8192 the split still + * wins. Unsplit changes the order these outputs are summed in, so a k/v row at 41..64 tokens + * differs from the split result in its last bits; the rows are as exact either way. Hence an + * opt-in: only `gemm_nt_q_short`, whose declaration the model owns, takes it, and every other + * caller keeps the split and its bits. */ + if (short_unsplit && N <= 512u && M > 40u && K <= 5120u) return 1; const uint32_t want = (kSplitTarget + gx * mw - 1) / (gx * mw); uint32_t ckw = ((K / want) + kBlock - 1u) / kBlock * kBlock; if (ckw < kBlock) ckw = kBlock; @@ -1073,7 +1261,8 @@ extern "C" int r4d_gemm_fp8a8_block(void) { return (int)kBlock; } static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, RadStream stream, - bool i8 = false, int split_n = 0, bool chain = false); + bool i8 = false, int split_n = 0, bool chain = false, + bool short_unsplit = false); extern "C" int r4d_gemm_fp8a8_nt_m16(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, @@ -1108,11 +1297,11 @@ extern "C" void r4d_gemm_fp8a8_pin_nt(int nt) { // fixes the order K partials are summed in, so a row slice of a wider linear (N rows of a // split_n-row weight) passes the whole width to sum each output as the whole linear does: the // slice's outputs are then the linear's to the bit. -static long m16_scratch(int M, int K, int N, int split_n) { +static long m16_scratch(int M, int K, int N, int split_n, bool short_unsplit = false) { if (M <= 0 || K <= 0 || N <= 0 || M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; uint32_t ck = 0; const uint32_t k2 = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K, - (uint32_t)M, &ck); + (uint32_t)M, &ck, short_unsplit); return k2 > 1 ? (long)k2 * M * N * (long)sizeof(float) : 0; } extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { @@ -1132,7 +1321,7 @@ extern "C" long r4d_gemm_fp8a8_nt_m16_scratch(int M, int K, int N) { static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, int M, int K, int N, int a_ld, int sa_ld, int w_ld, int sw_ld, long scratch, long scratch_bytes, RadStream stream, bool i8, - int split_n, bool chain) { + int split_n, bool chain, bool short_unsplit) { int emit_rc = RAD_OK; if (!a || !ascale || !wq || !ws || !c) return -1; if (M <= 0 || K <= 0 || N <= 0) return -2; @@ -1154,7 +1343,7 @@ static int gemm_fp8a8_nt_m16_emit(long a, long ascale, long wq, long ws, long c, uint32_t ck = 0; uint32_t ksplit = narrow_ksplit((uint32_t)(split_n > 0 ? split_n : N), (uint32_t)K, - (uint32_t)M, &ck); + (uint32_t)M, &ck, short_unsplit); const long need = ksplit > 1 ? (long)ksplit * M * N * (long)sizeof(float) : 0; if (need && (!scratch || scratch_bytes < need)) { ksplit = 1; ck = 0; } @@ -1304,7 +1493,7 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16_max_m(void) { return 64; } static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s, long y, int act, int M, int K, int nout, int a_ld, int sa_ld, int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream, - bool chain); + bool chain, bool wide = false); extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws, long q, long s, long y, int act, int M, int K, int nout, @@ -1313,14 +1502,24 @@ extern "C" int r4d_gemm_fp8a8_gated_nt_m16(long a, long ascale, long wq, long ws return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld, w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false); } +/* The same fold over every row count (`gemm_nt_q_gated_wide`): past the narrow tile's 64 rows it + * takes the gated prefill tile, whose accumulators are the unfused prefill GEMM's. Opt-in by op + * name, so the narrow row above keeps its refusal. */ +extern "C" int r4d_gemm_fp8a8_gated_nt_wide(long a, long ascale, long wq, long ws, + long q, long s, long y, int act, + int M, int K, int nout, + int a_ld, int sa_ld, int w_ld, int sw_ld, + int q_ld, int s_ld, int y_ld, long stream) { + return gemm_fp8a8_gated_launch(a, ascale, wq, ws, q, s, y, act, M, K, nout, a_ld, sa_ld, + w_ld, sw_ld, q_ld, s_ld, y_ld, stream, false, true); +} /* `chain`: the chained form (r4d_rad_gemm_fp8a8_gated_m16 passes the row's parameter). */ static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q, long s, long y, int act, int M, int K, int nout, int a_ld, int sa_ld, int w_ld, int sw_ld, int q_ld, int s_ld, int y_ld, long stream, - bool chain) { + bool chain, bool wide) { if (!a || !ascale || !wq || !ws || !q || !s) return -1; if (M <= 0 || K <= 0 || nout <= 0) return -2; - if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return -3; if (K % (int)kFKNarrow) return -4; // A block emits 128 fused columns, one scale group, so nout must be a multiple of 128. if (nout % 128) return -5; @@ -1336,6 +1535,21 @@ static int gemm_fp8a8_gated_launch(long a, long ascale, long wq, long ws, long q if (!s_ld) s_ld = nout / 128; if (!y_ld) y_ld = nout; + /* Past the narrow tile's rows, the gated prefill tile (gemm_8a8_gated_prefill_kernel), whose + * accumulators are the unfused prefill GEMM's. Only the wide row (`gemm_nt_q_gated_wide`) takes + * it: the narrow op refuses there, as it always has. */ + if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) { + if (!wide) return -3; + if ((q_ld | y_ld) % 8 || (q & 7) || (y && (y & 15))) return -7; + const dim3 grid(((uint32_t)M + kGBM - 1) / kGBM, (uint32_t)(nout / 128), 1); + hipLaunchKernelGGL(gemm_8a8_gated_prefill_kernel, grid, dim3(kPWaves * kWave), 0, + (hipStream_t)stream, (const uint8_t*)a, (const float*)ascale, + (const uint8_t*)wq, (const uint16_t*)ws, (uint8_t*)q, (float*)s, + (uint16_t*)y, (uint32_t)M, (uint32_t)K, (uint32_t)nout, (uint32_t)a_ld, + (uint32_t)sa_ld, (uint32_t)sw_ld, (uint32_t)q_ld, (uint32_t)s_ld, + (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -6; + } // The fold cannot split K, so a shape the split rule would split is refused (gate_up's shape, // N/16 = 1088, never splits). uint32_t ck = 0; @@ -1453,6 +1667,30 @@ extern "C" int r4d_rad_gemm_fp8a8_m16(const RadArgs* a, RadStream stream) { return e == 0 ? RAD_OK : RAD_E_SHAPE; } +/* `gemm_nt_q_short`: the narrow row above with the short-prompt split rule, whose declaration the + * model owns (narrow_ksplit's `short_unsplit`). The scratch query matches it, so the split the + * launch takes is the one the arena was sized for. */ +extern "C" int64_t r4d_rad_gemm_fp8a8_m16_short_scratch(const RadArgs* a) { + const long long M = r4d_geti_or(a, "M", 0), N = r4d_geti_or(a, "N", 0), + K = r4d_geti_or(a, "K", 0), sn = r4d_geti_or(a, "split_n", 0); + if (M < 1 || N < 1 || K < 1) return 0; + if (M > r4d_gemm_fp8a8_nt_m16_max_m()) return 0; + return (int64_t)m16_scratch((int)M, (int)K, (int)N, (int)sn, true); +} + +extern "C" int r4d_rad_gemm_fp8a8_m16_short(const RadArgs* a, RadStream stream) { + Fp8Ops g; + int rc = fp8_ops(a, &g, 1); + if (rc != RAD_OK) return rc; + if (g.M > r4d_gemm_fp8a8_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE); + const int e = gemm_fp8a8_nt_m16_emit( + r4d_addr(g.a), r4d_addr(g.ascale), r4d_addr(g.b), r4d_addr(g.bscale), r4d_addr(g.y), + (int)g.M, (int)g.K, (int)g.N, (int)g.a_ld, (int)g.sa_ld, (int)g.w_ld, (int)g.sw_ld, + (long)(uintptr_t)a->scratch, (long)a->scratch_bytes, stream, false, + (int)r4d_geti_or(a, "split_n", 0), r4d_geti_or(a, "chain", 0) != 0, true); + return e == 0 ? RAD_OK : RAD_E_SHAPE; +} + /* gemm_nt_q_bias's shim: gemm_nt_q's four operands, then the bias and C (oGemmNtQBias in * r4d_rows.cpp). Not fp8_ops: C is operand 5 and may be a column slice of a wider buffer, which * fp8_ops refuses for the unbiased kernels' dense store. */ @@ -1498,7 +1736,9 @@ extern "C" int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs* a, RadStream s) { * `gemm_nt_q_gated`'s (oGemmNtQGated in r4d_rows.cpp). */ enum { GG_A = 0, GG_AS = 1, GG_B = 2, GG_BS = 3, GG_Q = 4, GG_S = 5, GG_Y = 6 }; -extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { +/* The gated shim's body, for the narrow row (`wide` false: M <= 64, the fold's narrow tile) and for + * `gemm_nt_q_gated_wide` (`wide` true: the gated prefill tile past it). */ +static int r4d_rad_gemm_fp8a8_gated(const RadArgs* a, RadStream s, bool wide) { const RadTensor* x = r4d_opt(a, GG_A); const RadTensor* xs = r4d_opt(a, GG_AS); const RadTensor* w = r4d_opt(a, GG_B); @@ -1519,7 +1759,6 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { * it. */ const long long M = q->shape[0], nout = q->shape[1], K = w->shape[1]; if (M < 1 || nout < 1 || K < 1) return R4D_NO(RAD_E_SHAPE); - if (M > r4d_gemm_fp8a8_gated_nt_m16_max_m()) return R4D_NO(RAD_E_SHAPE); if (w->shape[0] != 2 * nout) return R4D_NO(RAD_E_SHAPE); const long long nkb = (K + blk - 1) / blk; if (wsc->shape[0] != (2 * nout + blk - 1) / blk || wsc->shape[1] != nkb) @@ -1544,10 +1783,18 @@ extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { r4d_addr(x), r4d_addr(xs), r4d_addr(w), r4d_addr(wsc), r4d_addr(q), r4d_addr(sc), y ? r4d_addr(y) : 0, 0, (int)M, (int)K, (int)nout, (int)ap, (int)asp, (int)wp, (int)wsp, - (int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0); + (int)qp, (int)sp, (int)yp, (long)(uintptr_t)s, r4d_geti_or(a, "chain", 0) != 0, wide); return e == 0 ? RAD_OK : RAD_E_SHAPE; } +extern "C" int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs* a, RadStream s) { + return r4d_rad_gemm_fp8a8_gated(a, s, false); +} + +extern "C" int r4d_rad_gemm_fp8a8_gated_wide(const RadArgs* a, RadStream s) { + return r4d_rad_gemm_fp8a8_gated(a, s, true); +} + /* ---- the int8 twins' shims: the same operands with i8 codes and the weight's scale plane per * row, which fp8_ops checks at [N][K/128] when asked (FP8_OPS_ROW_SCALE). */ extern "C" int64_t r4d_rad_gemm_i8a8_m16_scratch(const RadArgs* a) { diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 4d384a1e..dff5657a 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -614,6 +614,52 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( } } +// The same rotary at prefill row counts with each (token, pair) angle computed once. rope_kernel +// gives every (head, pair) its own thread, which recomputes powf and the accurate sincosf for every +// head; the angle depends on the token and the pair alone, so at 32 heads 31 of 32 evaluations are +// repeats (q at 408 tokens: ~50 us on gfx1200). Here a thread owns one pair of one token and turns +// that pair in every head. Byte-identical: the angle, cos and sin are rope_kernel's expressions on +// the same inputs, and each head's two stores are its. +__global__ __launch_bounds__(kThreads) void rope_rows_kernel( + uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, uint32_t M, + uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj, + float theta, float rscale, uint32_t row_pitch, + int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn, RadLlama3 l3) { + const uint32_t half = rot / 2; + const uint32_t rpb = kThreads / half; // rows a block; half <= kThreads + const uint32_t m = blockIdx.x * rpb + threadIdx.x / half, i = threadIdx.x % half; + if (threadIdx.x >= rpb * half || m >= M) return; + const float div = rscale != 0.0f ? rscale : 1.0f; + const float p0 = (float)pos[m] / div; + const int sec[3] = { s0, s1, s2 }; + + float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den); + float p = p0; + if (plane) { + uint32_t j = i; + const int c = rope_comp(mode, i, sec, n_sec, &j); + p = (float)pos[(size_t)c * plane + m] / div; + if (mode == 4) + inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c])); + } + inv = yarn.frequency(inv, (int)i); + inv = l3.frequency(inv); + if (i >= nfreq) inv = 0.0f; + const float ang = p * inv; + float c, s; + sincosf(ang, &s, &c); + if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; } + const uint32_t i0 = gptj ? 2 * i : i; + const uint32_t i1 = gptj ? 2 * i + 1 : i + half; + uint16_t* __restrict__ row = qkv + (size_t)m * row_pitch; + for (uint32_t h = 0; h < n_rope_heads; ++h) { + uint16_t* __restrict__ hd = row + (size_t)h * head_dim; + const float x0 = bf16_to_f32(hd[i0]), x1 = bf16_to_f32(hd[i1]); + hd[i0] = f32_to_bf16(x0 * c - x1 * s); + hd[i1] = f32_to_bf16(x0 * s + x1 * c); + } +} + // ---------------------------------------------------------------------------- kv_store // ref_kv_store. The paged layout every kernel in this project shares: // @@ -952,20 +998,65 @@ extern "C" int r4d_scatter_rows_u8(long v, long idx, long x, int M, int n, int d (RadStream)(uintptr_t)stream); } + +// Short rows (n <= 256: per-head q/k norms at head_dim 64..256): a wave a row, eight rows a block. +// rmsnorm_kernel gives such a row a whole workgroup of 256+ threads, most of them idle, and at a +// prefill step's T x heads rows (13,000 at 408 tokens x 32 heads) the launch is bound by workgroup +// dispatch: ~48 us for 1.7 MB on gfx1200. +// +// Byte-identical to rmsnorm_kernel at any width it is launched at. There, with n no wider than the +// block, thread i holds element i alone; each wave's 32 squares are summed by r4d_wave_sum and the +// wave sums are added in wave order from 0.f (block_sum), the waves past the row adding exact +// zeros. Here lane l holds elements l + 32c of the row, chunk c summed by the same r4d_wave_sum, +// and the chunk sums added in the same order. The scale and the store are rmsnorm_kernel's. +constexpr uint32_t kShortNormMax = 256; +template +__global__ __launch_bounds__(256) void rmsnorm_short_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ w, uint16_t* __restrict__ y, + uint32_t n, float eps, float wadd, float mult, uint32_t x_ld, uint32_t y_ld, uint32_t M) { + const uint32_t lane = threadIdx.x & (kWave - 1); + const uint32_t m = blockIdx.x * (256u / kWave) + threadIdx.x / kWave; + if (m >= M) return; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + constexpr uint32_t NC = kShortNormMax / kWave; + float v[NC]; + float ss = 0.0f; +#pragma unroll + for (uint32_t c = 0; c < NC; ++c) { + const uint32_t i = lane + c * kWave; + v[c] = i < n ? bf16_to_f32(xr[i]) : 0.0f; + if (c * kWave < n) { + float q = 0.0f; + q += v[c] * v[c]; + ss += r4d_wave_sum(q); + } + } + const float s = rsqrtf(ss / (float)n + eps); +#pragma unroll + for (uint32_t c = 0; c < NC; ++c) { + const uint32_t i = lane + c * kWave; + if (i >= n) continue; + const float g = !w ? 1.0f : WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); + yr[i] = f32_to_bf16(v[c] * s * (g + wadd) * mult); + } +} + // `w_f32` selects an f32 or bf16 gain; a null `w` is a gain of one. `mult` scales the row before // its single rounding. /* `chain`: the chained form, at decode heights (r4d_rad_rmsnorm passes the row's resolved - * parameter; every other caller none). */ + * parameter; every other caller none). `rows_form`: the caller declared `rmsnorm_rows` and the + * short-row form may be taken (rmsnorm_short_kernel); every other caller keeps rmsnorm_kernel. */ static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd, float mult, int w_f32, int x_ld, int y_ld, long stream, - bool chain); + bool chain, bool rows_form = false); extern "C" int r4d_rmsnorm_mult_bf16(long x, long w, long y, int M, int n, float eps, float wadd, float mult, int w_f32, int x_ld, int y_ld, long stream) { return rmsnorm_mult_launch(x, w, y, M, n, eps, wadd, mult, w_f32, x_ld, y_ld, stream, false); } static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, float wadd, float mult, int w_f32, int x_ld, int y_ld, long stream, - bool chain) { + bool chain, bool rows_form) { if (!x || !y) return -1; if (M <= 0 || n <= 0) return -2; if (!x_ld) x_ld = n; @@ -977,6 +1068,23 @@ static int rmsnorm_mult_launch(long x, long w, long y, int M, int n, float eps, const int thr = r4d_act_threads(M, n); // A drafter's 256-row head norm at 256 threads is exactly a full card; step past the cliff. const bool ch = chain && M <= 64; + /* Short rows at more rows than the card has waves: a wave a row (rmsnorm_short_kernel, the + * same bytes). Below that the per-row workgroups already fill the part. Opt-in by op name, so + * every other caller's launch is the one it had. */ + if (rows_form && n <= (int)kShortNormMax && M >= 1024 && !ch) { + /* Eight waves a block, stepped past the cliff r4d_cliff_rows names for the card's wave + * count (on the 32-CU part 1024 rows are 1024 waves: 17 us against 7 at 3264). */ + const dim3 grid(r4d_cliff_rows(((uint32_t)M + 7u) / 8u, 1, 8)); + if (w_f32) + hipLaunchKernelGGL((rmsnorm_short_kernel), grid, dim3(256), 0, (hipStream_t)stream, + (const uint16_t*)x, (const void*)w, (uint16_t*)y, (uint32_t)n, eps, + wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + else + hipLaunchKernelGGL((rmsnorm_short_kernel), grid, dim3(256), 0, (hipStream_t)stream, + (const uint16_t*)x, (const void*)w, (uint16_t*)y, (uint32_t)n, eps, + wadd, mult, (uint32_t)x_ld, (uint32_t)y_ld, (uint32_t)M); + return hipGetLastError() == hipSuccess ? 0 : -4; + } #define R4D_RN_T(wf, T) \ hipLaunchKernelGGL((ch ? r4dchain_rmsnorm : rmsnorm_kernel), \ dim3(r4d_cliff_rows((uint32_t)M, 1, T / kWave)), \ @@ -1180,7 +1288,7 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec, int plane, RadYarn yarn, long stream, - int nfreq = -1, RadLlama3 l3 = RadLlama3{}) { + int nfreq = -1, RadLlama3 l3 = RadLlama3{}, bool rows_form = false) { if (!qkv || !pos) return -1; if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2; if (rot <= 0 || rot > head_dim || (rot & 1)) return -3; @@ -1190,6 +1298,19 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads const uint32_t gy = (pairs + kThreads - 1) / kThreads; const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0; if (nfreq < 0) nfreq = rot / 2; + /* Prefill rows with at least four heads: one angle a (token, pair), every head turned with it + * (rope_rows_kernel, the same bytes). Decode rows keep a thread a (head, pair), which spreads a + * single token over the card. Opt-in by op name (`rope_rows`): every other caller's launch is + * the one it had. */ + if (rows_form && M >= 64 && n_rope_heads >= 4 && rot / 2 <= (int)kThreads) { + const uint32_t rpb = kThreads / (uint32_t)(rot / 2); + hipLaunchKernelGGL(rope_rows_kernel, dim3(((uint32_t)M + rpb - 1) / rpb), dim3(kThreads), 0, + (hipStream_t)stream, (uint16_t*)qkv, (const int32_t*)pos, (uint32_t)M, + (uint32_t)head_dim, (uint32_t)n_rope_heads, (uint32_t)rot, + (uint32_t)nfreq, (int)den, gptj, theta, rscale, (uint32_t)row_pitch, mode, + s0, s1, s2, n_sec, (uint32_t)plane, yarn, l3); + return hipGetLastError() == hipSuccess ? 0 : -4; + } hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream, (uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim, (uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta, @@ -1696,7 +1817,9 @@ static int rmsnorm_x_f32(const float* x, const void* w, uint16_t* y, int M, int return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; } -extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { +/* `rows_form`: the row is `rmsnorm_rows`, which may take the short-row form (rmsnorm_short_kernel). + * Every other caller passes false and gets the launch it always had. */ +static int rmsnorm_emit(const RadArgs* a, RadStream s, bool rows_form) { const RadTensor* x = r4d_opt(a, RN_X); const RadTensor* w = r4d_opt(a, RN_W); const RadTensor* y = r4d_opt(a, RN_Y); @@ -1746,7 +1869,18 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { return rmsnorm_mult_launch(r4d_addr(x), r4d_addr(w), r4d_addr(y), (int)M, (int)n, eps, wadd, (float)r4d_getf(a, "mult", 1.0), w_f32, (int)x_ld, (int)y_ld, (long)(uintptr_t)s, - r4d_geti_or(a, "chain", 0) != 0) == 0 ? RAD_OK : RAD_E_DEVICE; + r4d_geti_or(a, "chain", 0) != 0, rows_form) == 0 + ? RAD_OK : RAD_E_DEVICE; +} + +extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { + return rmsnorm_emit(a, s, false); +} + +/* `rmsnorm_rows`: the same norm, whose launch may take the short-row form (n <= 256 at 1024 rows + * or more, the head norms of a prefill step). Byte-identical to the row above at every width. */ +extern "C" int r4d_rad_rmsnorm_rows(const RadArgs* a, RadStream s) { + return rmsnorm_emit(a, s, true); } /* ------------------------------------------------------------------ add_rmsnorm */ @@ -2095,7 +2229,9 @@ extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) { enum { RP_QKV = 0, RP_POS }; -extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { +/* `rows_form`: the row is `rope_rows`, which may turn every head of a (token, pair) with the one + * angle it computed (rope_rows_kernel). Every other caller passes false. */ +static int rope_emit(const RadArgs* a, RadStream s, bool rows_form) { const RadTensor* qkv = r4d_opt(a, RP_QKV); const RadTensor* pos = r4d_opt(a, RP_POS); if (!qkv || !pos) return R4D_NO(RAD_E_INVAL); @@ -2181,11 +2317,21 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim, (int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale, (int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s, - (int)nfreq, l3) == 0 + (int)nfreq, l3, rows_form) == 0 ? RAD_OK : RAD_E_DEVICE; } +extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { + return rope_emit(a, s, false); +} + +/* `rope_rows`: the same rotation, whose launch may compute one angle a (token, pair) and turn every + * head with it (rope_rows_kernel, the same bytes) at prefill row counts. */ +extern "C" int r4d_rad_rope_rows(const RadArgs* a, RadStream s) { + return rope_emit(a, s, true); +} + /* ------------------------------------------------------------------ kv_store */ enum { KS_K = 0, KS_V, KS_SLOT, KS_CACHE }; diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 2bc3253e..cf9f0a82 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -575,6 +575,10 @@ int r4d_rad_rope_table (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a16_m1 (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a8_m16 (const RadArgs*, RadStream); int r4d_rad_gemm_fp8a8_gated_m16(const RadArgs*, RadStream); +int r4d_rad_gemm_fp8a8_gated_wide(const RadArgs*, RadStream); +/* `gemm_nt_q_short`: the narrow row with the short-prompt split rule (narrow_ksplit). */ +int r4d_rad_gemm_fp8a8_m16_short(const RadArgs*, RadStream); +int64_t r4d_rad_gemm_fp8a8_m16_short_scratch(const RadArgs*); int r4d_rad_gemm_fp8a8_bias_m16(const RadArgs*, RadStream); int64_t r4d_rad_gemm_fp8a8_m16_scratch(const RadArgs*); int r4d_rad_gemm_fp8a8_tiled(const RadArgs*, RadStream); @@ -740,6 +744,8 @@ int r4d_rad_gather_rows_u8 (const RadArgs*, RadStream); int r4d_rad_scatter_rows_u8 (const RadArgs*, RadStream); int r4d_rad_scatter_rows_bf16(const RadArgs*, RadStream); int r4d_rad_rmsnorm (const RadArgs*, RadStream); +/* The same row choosing the short-row form when it serves (`rmsnorm_rows`, rmsnorm_short_kernel). */ +int r4d_rad_rmsnorm_rows (const RadArgs*, RadStream); int r4d_rad_rmsnorm_p (const RadArgs*, RadStream); int r4d_rad_add (const RadArgs*, RadStream); int r4d_rad_mul (const RadArgs*, RadStream); @@ -798,6 +804,8 @@ int r4d_shape_moe_gather_inv(const RadParam*, int, int, RadOpdDesc*); int r4d_shape_router_sigmoid_topk_scatter(const RadParam*, int, int, RadOpdDesc*); int r4d_rad_gelu_mul (const RadArgs*, RadStream); int r4d_rad_rope (const RadArgs*, RadStream); +/* The same row choosing the per-(token, pair) angles form when it serves (`rope_rows`). */ +int r4d_rad_rope_rows (const RadArgs*, RadStream); /* -- the vision tower's ops (r4d_vit_bf16.hip) -- */ int r4d_rad_layernorm (const RadArgs*, RadStream); int r4d_rad_grid_embed (const RadArgs*, RadStream); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 6a3710aa..dfbd8982 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2919,6 +2919,11 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in " "f32 after the load because forming it in bf16 first costs 0.3% per channel."), + SCHEMA("rmsnorm_rows", pRmsNorm, oRmsNorm, + "the same norm, and its launch is the same except at n <= 256 with 1024 or more rows, " + "where a wave a row computes the row and sums its squares in rmsnorm_kernel's wave " + "order (byte-identical). An op name of its own so a caller that has not asked for it " + "keeps the per-row workgroups it always had."), SCHEMA("rmsnorm_p", pLayernorm, oUnary, "y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. Gemma's " "attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the " @@ -3037,6 +3042,11 @@ static const RadOpSchema kSchemas[] = { "that follow are untouched. The multi-component modes (`mrope`, `imrope`, `axial`) " "take [C, M] component-major positions and `sections`; with [M] positions every " "component is that one, so mrope and imrope over a text batch are neox exactly."), + SCHEMA("rope_rows", pRope, oRope, + "the same rotation, and its launch is the same except with 64 or more rows and 4 or " + "more heads, where a thread owns one (token, pair) angle and turns that pair in every " + "head (byte-identical). An op name of its own so a caller that has not asked for it " + "keeps a thread a (head, pair), which spreads a decode's single token over the card."), SCHEMA("layernorm", pLayernorm, oLayernorm, "y = (x - mean) * rsqrt(var + eps) * w + b, biased variance, two passes. `b` optional."), SCHEMA("grid_embed", pGridEmbed, oGridEmbed, @@ -3298,6 +3308,12 @@ static const RadOpSchema kSchemas[] = { "C[M,N] = A[M,K] @ dequant(Bq)[N,K]^T. `dtype` names the operand COMBINATION, so one " "op covers w4a16 through mxfp4a8 and an architecture plugin that changes quant changes " "one string."), + SCHEMA("gemm_nt_q_short", pGemmNtQ, oGemmNtQ, + "the narrow fp8a8 row of `gemm_nt_q` with the short-prompt split rule: at N <= 512, K " + "<= 5120 and 41..64 rows it runs unsplit, where the split's per-slice floors dominate. " + "The split COUNT changes, so a row here is not bit-identical to the same row split; " + "both are exact. An op name of its own so every other caller keeps the split and " + "its bits."), SCHEMA("gemm_nt_q_bias", pGemmNtQBias, oGemmNtQBias, "gemm_nt_q with a per-column bias added to the f32 product before its one rounding."), SCHEMA("dequant_w4", pDequantW4, oDequantW4, @@ -3450,6 +3466,10 @@ static const RadOpSchema kSchemas[] = { "columns) and optionally the bf16 product, and no [M, 2n] tensor is ever written. " "Byte-identical to the two ops it replaces, which is what makes it substitutable " "rather than a second numerical path."), + SCHEMA("gemm_nt_q_gated_wide", pGemmNtQGated, oGemmNtQGated, + "gemm_nt_q_gated at every M: the narrow tile to 64 rows and the gated prefill tile past " + "them, whose accumulators are the unfused prefill GEMM's. An op name of its own so the " + "narrow row keeps its M <= 64 band, its kernel and every other caller's path."), SCHEMA("gemm_nt_q_gated_mx", pGemmNtQGated, oGemmNtQGatedMx, "gemm_nt_q_gated over an OCP-MXFP4 [2n, K] gate_up weight: gemm_nt_q at dtype mxfp4a8 " "(`b_ref` the per-row reference exponent) with gated_quant_fp8's pass folded into the " @@ -4960,6 +4980,14 @@ static const RadConstraint cGemmNtQGatedFp8[] = { C_LE("M", 64), C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"), }; +/* `gemm_nt_q_gated_wide`: the same fold at any M. Past the narrow tile's 64 rows it runs the gated + * prefill tile, whose accumulators are the unfused prefill GEMM's, so its bytes are the pair's. An + * op name of its own, and one a model declares when it wants the whole prompt in the fold: the + * narrow row above keeps its ceiling, its kernel and every other caller's path. */ +static const RadConstraint cGemmNtQGatedFp8Wide[] = { + C_DIV("K", 256), C_DIV("N", 256), C_GE("N", 2048), + C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "fp8a8"), C_IN("act", "silu"), +}; /* r4d_gemm_mxfp4a8_gated_gemv: the gemv row's WMMA form (K a multiple of 128, M <= 8) with a block * per 16-column tile pair of the gated output. N/2 is a multiple of 128, so each 128-column * group's eight blocks meet at its last arriver, which quantises the group. */ @@ -4980,6 +5008,7 @@ static const RadConstraint cGemmNtQGatedMxWide[] = { static const RadConstraint cGateQuantFp8[] = { C_DIV("n", 4), C_EQ("group", R4D_FP8_BLOCK), C_IN("dtype", "bf16"), }; +/* `act` none is the plain product (`mul`), for a producer that is not a gate activation. */ /* libr4d's cSampleChain. The kernel has no geometry constraint (the radix passes run over a * float's 256 byte buckets), but a row with no predicate would match a query that named nothing. */ static const RadConstraint cSampleChain[] = { @@ -5856,6 +5885,18 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr, r4d_shape_rmsnorm }, +/* The same norm, whose launch takes rows of 256 or fewer columns a wave a row once there are + * enough of them to fill the part; the chunk sums are rmsnorm_kernel's in wave order. */ +{ "rmsnorm_rows_bf16", "rmsnorm_rows", "norm", + "root-mean-square norm with a gain, two passes over the row, a wave a short row at prefill row " + "counts", + "any n; the short-row form needs n <= 256 and 1024 or more rows; byte-identical to rmsnorm", + "bf16 y, x bf16 or (with a gain) f32, bf16 or f32 gain, fp32 reduction", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_rmsnorm_rows, nullptr, nullptr, nullptr, + r4d_shape_rmsnorm }, + { "rmsnorm_p_bf16", "rmsnorm_p", "norm", "weightless root-mean-square norm (no gain), two passes over the row", "any n; the sum of squares accumulates in f32 and only the store narrows", @@ -6114,6 +6155,17 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_rope, nullptr, nullptr, nullptr, r4d_shape_rope }, +/* The same rotation with one angle a (token, pair) and every head turned with it, at prefill row + * counts: the angle does not depend on the head, so a thread owns one pair of one token. */ +{ "rope_rows_bf16", "rope_rows", "attn", + "rotary embedding in place, one thread a (token, pair) angle, every head turned with it", + "the rope row's geometry; the per-angle form needs 64 or more rows and 4 or more heads", + "bf16 qkv, i32 positions, fp32 angles through the accurate sincosf; byte-identical to rope", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRopeRow), NOTUNE, + nullptr, nullptr, r4d_rad_rope_rows, nullptr, nullptr, nullptr, + r4d_shape_rope }, + { "kv_store_bf16", "kv_store", "attn", "scatter k and v into the paged cache, one workgroup a token", "cache exactly [n_blocks, kv_heads, block_size, 2*head_dim]; a negative or out-of-range slot " @@ -7880,6 +7932,22 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block }, +/* The same narrow row with the short-prompt split rule (narrow_ksplit's `short_unsplit`), whose + * declaration the model owns: the scratch hook matches, so the split the launch takes is the one + * the arena was sized for. */ +{ "gemm_fp8a8_nt_m16_short", "gemm_nt_q_short", "gemm", + "gemm_fp8a8_nt_m16 choosing its split from the short-prompt rule: at N <= 512, K <= 5120 and " + "41..64 rows the split's per-slice floors dominate and the row runs unsplit", + "the narrow row's: M <= 64; K a multiple of 128; N a multiple of 16", + "E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, bf16 C. " + "Unsplit sums its K blocks in one order and split its partial planes in another, so a row here " + "differs from the split result in its last bits; both are exact", + RAD_DOMAIN_DEVICE, R4D_PRIO_GEMM_FP8_M16, + ROW(cGemmNtFp8A8M16), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_fp8a8_m16_short, r4d_rad_gemm_fp8a8_m16_short_scratch, + r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, + r4d_shape_gemm_nt_q, r4d_rad_unrelayout_fp8_block }, + { "gemm_fp8a8_gated_nt_m16", "gemm_nt_q_gated", "gemm", "the narrow fp8 GEMM with the SwiGLU and the fp8 quantiser folded into its epilogue: the block's " "waves split in half over the gate rows and the up rows, so a block emits one whole 128-column " @@ -7899,6 +7967,23 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) /* The byte-identity claim above, as a chain of two rows of this plugin (r4d_fuse.cpp). */ r4d_fuse_gemm_nt_q_gated }, +/* The same fold at every M: the narrow tile to 64 rows, past them the gated prefill tile (128 + * gate and 128 up rows against 64 activation rows a block), whose accumulators are the unfused + * prefill GEMM's. An op name of its own, which the model declares when it wants the whole prompt + * in the fold. */ +{ "gemm_fp8a8_gated_nt_wide", "gemm_nt_q_gated_wide", "gemm", + "gemm_fp8a8_gated_nt_m16 at every M", + "any M; K a multiple of 256 and N of 256 for the narrow row's reasons; act silu only; the " + "prefill tile past 64 rows needs q_ld and y_ld multiples of 8 and a 16-byte-aligned y", + "E4M3 A with an f32 scale per (row, 128 K), E4M3 W with a bf16 scale per 128x128 tile, and the " + "QUANTISER's outputs; byte-identical to gemm_nt_q followed by gated_quant_fp8 at every M", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGemmNtQGatedFp8Wide), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_fp8a8_gated_wide, nullptr, + r4d_rad_layout_fp8_block, r4d_rad_relayout_fp8_block, + r4d_shape_gemm_nt_q_gated, r4d_rad_unrelayout_fp8_block, + r4d_fuse_gemm_nt_q_gated }, + { "gemm_fp8a8_tiled", "gemm_nt_q", "gemm", "the same GEMM for prefill row counts: 128x128 tile, eight waves of 2 weight x 4 activation " "tiles, the weight read straight into registers and the activation staged through LDS, one K " @@ -8650,16 +8735,16 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) { "gate_quant_fp8", "gate_quant_fp8", "quant", "an elementwise gated product and the fp8 activation quantiser in one pass, with the gate in " "its own operand: a gated attention's gate is a column slice of the [q|gate] projection and " - "cannot be packed beside the attention output it scales", + "cannot be packed beside the attention output it scales; `act` none is `mul` + `quant_act_fp8`", "n a multiple of 4; gate and x are both [M][n] and may have different pitches; no reduction " - "across the row, so no barrier; group 128; strides in elements", + "across the row, so no barrier; group 128; strides in elements; `act` silu, sigmoid or none", "bf16 in, E4M3 out with an f32 scale per (row, 128 columns) and an optional bf16 out; the codes " "are taken over the BF16-ROUNDED product", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGateQuantFp8), NOTUNE, nullptr, nullptr, r4d_rad_gate_quant_fp8, nullptr, nullptr, nullptr, r4d_shape_gate_quant_fp8, nullptr, - /* `sigmoid` + `mul` + `quant_act_fp8`; the silu arm is declined (r4d_fuse.cpp). */ + /* `sigmoid` + `mul` + `quant_act_fp8`, and `mul` + `quant_act_fp8` for act none (r4d_fuse.cpp). */ r4d_fuse_gate_quant_fp8 }, /* ---------------------------------------------------------------------------------- sampling diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index ac230994..87eaebc3 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -13316,6 +13316,103 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { "rc=" + std::to_string(rc)); else same("gate_quant_fp8 is byte-identical to sigmoid + mul + quant_act_fp8"); + /* --- mul + quant_act_fp8, against gate_quant_fp8 at act none ------------------------------- + * + * LFM2's convolution gate: C * conv(B * x), then the codes its out projection reads. The + * kernel must round the product to bf16 (the `mul` step stores bf16) and take the codes over + * that value. Strided sources: gate and x are column slices of [M, 2K] planes, so a kernel + * ignoring a pitch reads the wrong half. Rows 1, 8 and 65 cover the narrow width's boundary + * and one past it; the scale plane stays K/128 wide at every M. */ + { + const int64_t NROW = 65; + std::vector hg((size_t)NROW * 2 * K), hx2((size_t)NROW * 2 * K); + for (int64_t r = 0; r < NROW; ++r) + for (int64_t c = 0; c < K; ++c) { + const float m = std::ldexp(1.0f, (int)(c / 128) - 2); + const float v = m * (0.041f * (float)((r * 31 + c * 17) % 73) - 1.4f); + hg[(size_t)r * 2 * K + c] = h_to_bf16(c == (r * 13) % K ? v * 23.0f : v); + hx2[(size_t)r * 2 * K + c] = h_to_bf16(m * (0.013f * (float)((r * 7 + c * 11) % 47) - 0.3f)); + } + void* d_g = dalloc(hg.size() * 2); + void* d_x2 = dalloc(hx2.size() * 2); + void* d_py[2] = { dalloc((size_t)NROW * K * 2), dalloc((size_t)NROW * K * 2) }; + void* d_pq[2] = { dalloc((size_t)NROW * K), dalloc((size_t)NROW * K) }; + void* d_ps[2] = { dalloc((size_t)NROW * nkb * 4), dalloc((size_t)NROW * nkb * 4) }; + if (!d_g || !d_x2 || !d_py[1] || !d_pq[1] || !d_ps[1]) { + ok("mul + quant_act_fp8 vs gate_quant_fp8 act none", false, "hipMalloc failed"); + } else { + st_memcpy(d_g, hg.data(), hg.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_x2, hx2.data(), hx2.size() * 2, hipMemcpyHostToDevice); + for (const int64_t m : { (int64_t)1, (int64_t)8, (int64_t)65 }) { + RadTensor g = T(d_g, RAD_BF16, { m, K }); g.stride[0] = 2 * K; + RadTensor x = T(d_x2, RAD_BF16, { m, K }); x.stride[0] = 2 * K; + int r2 = launch_row(ml, { g, x, T(d_py[0], RAD_BF16, { m, K }) }, + { PI("M", m), PI("n", K), PS("dtype", "bf16") }); + if (r2 == RAD_OK) + r2 = launch_row(qz, { T(d_py[0], RAD_BF16, { m, K }), + T(d_pq[0], RAD_F8E4M3, { m, K }), + T(d_ps[0], RAD_F32, { m, nkb }) }, + { PI("M", m), PI("n", K), PI("group", 128), + PS("dtype", "bf16") }); + if (r2 == RAD_OK) + r2 = launch_row(tq, { g, x, T(d_pq[1], RAD_F8E4M3, { m, K }), + T(d_ps[1], RAD_F32, { m, nkb }), + T(d_py[1], RAD_BF16, { m, K }) }, + { PI("M", m), PI("n", K), PI("group", 128), + PS("dtype", "bf16"), PS("act", "none") }); + if (r2 != RAD_OK) { + ok(("mul + quant_act_fp8 vs gate_quant_fp8 act none, M=" + + std::to_string(m)).c_str(), false, "rc=" + std::to_string(r2)); + continue; + } + std::vector y0((size_t)m * K), y1((size_t)m * K); + std::vector qq0((size_t)m * K), qq1((size_t)m * K); + std::vector ss0((size_t)m * nkb), ss1((size_t)m * nkb); + st_memcpy(y0.data(), d_py[0], y0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(y1.data(), d_py[1], y1.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(qq0.data(), d_pq[0], qq0.size(), hipMemcpyDeviceToHost); + st_memcpy(qq1.data(), d_pq[1], qq1.size(), hipMemcpyDeviceToHost); + st_memcpy(ss0.data(), d_ps[0], ss0.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(ss1.data(), d_ps[1], ss1.size() * 4, hipMemcpyDeviceToHost); + size_t ny = 0, nq = 0, ns = 0, nz = 0; + for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i]; + for (size_t i = 0; i < qq0.size(); ++i) { + nq += qq0[i] != qq1[i]; + nz += qq1[i] != 0; + } + for (size_t i = 0; i < ss0.size(); ++i) + ns += std::memcmp(&ss0[i], &ss1[i], 4) != 0; + ok(("gate_quant_fp8 act none is byte-identical to mul + quant_act_fp8, M=" + + std::to_string(m)).c_str(), + ny == 0 && nq == 0 && ns == 0 && nz > qq1.size() / 2, + "bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + + ", scales " + std::to_string(ns) + ", nonzero codes " + + std::to_string(nz)); + + /* Without out_bf16 the codes are taken over the same rounded product. */ + r2 = launch_row(tq, { g, x, T(d_pq[1], RAD_F8E4M3, { m, K }), + T(d_ps[1], RAD_F32, { m, nkb }), + T(nullptr, RAD_BF16, {}) }, + { PI("M", m), PI("n", K), PI("group", 128), + PS("dtype", "bf16"), PS("act", "none") }); + if (r2 != RAD_OK) { + ok(("gate_quant_fp8 act none without out_bf16, M=" + + std::to_string(m)).c_str(), false, "rc=" + std::to_string(r2)); + continue; + } + st_memcpy(qq1.data(), d_pq[1], qq1.size(), hipMemcpyDeviceToHost); + st_memcpy(ss1.data(), d_ps[1], ss1.size() * 4, hipMemcpyDeviceToHost); + size_t dq2 = 0, ds2 = 0; + for (size_t i = 0; i < qq0.size(); ++i) dq2 += qq0[i] != qq1[i]; + for (size_t i = 0; i < ss0.size(); ++i) + ds2 += std::memcmp(&ss0[i], &ss1[i], 4) != 0; + ok(("gate_quant_fp8 act none without out_bf16 keeps the codes, M=" + + std::to_string(m)).c_str(), dq2 == 0 && ds2 == 0, + "codes differ " + std::to_string(dq2) + ", scales " + std::to_string(ds2)); + } + } + } + /* --- the same two at int8 codes, against the same products and quant_act_i8g --- * * With an I8 codes operand the producer writes int8 codes for an int8 trunk linear: the bf16 @@ -14547,6 +14644,90 @@ static void fp8_numeric(const Plugin& pl, int64_t N, int64_t K) { std::to_string(live)); } } + + /* ---- past the narrow tile: `gemm_nt_q_gated_wide` runs the gated prefill tile, + * whose accumulators are the unfused prefill GEMM's, so its codes, scales and bf16 + * product are the pair's over the whole prompt. 65 and 129 rows straddle one and + * two 64-row blocks. */ + const RadKernelInfo* gt = find(pl, "gemm_fp8a8_tiled"); + const RadKernelInfo* gw = find(pl, "gemm_fp8a8_gated_nt_wide"); + for (const int64_t M : { (int64_t)65, (int64_t)129 }) { + if (!gt || !gw) { + ok("gemm_fp8a8_gated_nt_wide numeric", false, "row absent"); + break; + } + void* dx = dalloc((size_t)M * K * 2); + void* dq = dalloc((size_t)M * K); + void* dqs = dalloc((size_t)M * sk * 4); + void* dy = dalloc((size_t)M * N * 2); + void* c0 = dalloc((size_t)M * nout); + void* c1 = dalloc((size_t)M * nout); + void* z0 = dalloc((size_t)M * gkb * 4); + void* z1 = dalloc((size_t)M * gkb * 4); + void* b0 = dalloc((size_t)M * nout * 2); + void* b1 = dalloc((size_t)M * nout * 2); + if (!dx || !dq || !dqs || !dy || !c1 || !z1 || !b1) { + ok("gemm_fp8a8_gated_nt_wide alloc", false, "hipMalloc failed"); + continue; + } + std::vector xm((size_t)M * K); + for (int64_t m = 0; m < M; ++m) + for (int64_t c = 0; c < K; ++c) + xm[(size_t)m * K + c] = xb[(size_t)((c + m * 37) % K)]; + st_memcpy(dx, xm.data(), xm.size() * 2, hipMemcpyHostToDevice); + int rc = launch_row(qz, { T(dx, RAD_BF16, { M, K }), T(dq, RAD_F8E4M3, { M, K }), + T(dqs, RAD_F32, { M, sk }) }, + { PI("M", M), PI("n", K), PI("group", 128), + PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(gt, { T(dq, RAD_F8E4M3, { M, K }), + T(dqs, RAD_F32, { M, sk }), + T(d_wf, RAD_F8E4M3, { N, K }), + T(d_s, RAD_BF16, { sn, sk }), + T(dy, RAD_BF16, { M, N }) }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8") }); + if (rc == RAD_OK) + rc = launch_row(gq, { T(dy, RAD_BF16, { M, N }), + T(c0, RAD_F8E4M3, { M, nout }), + T(z0, RAD_F32, { M, gkb }), + T(b0, RAD_BF16, { M, nout }) }, + { PI("M", M), PI("n", nout), PI("group", 128), + PS("dtype", "bf16"), PS("act", "silu") }); + if (rc == RAD_OK) + rc = launch_row(gw, { T(dq, RAD_F8E4M3, { M, K }), + T(dqs, RAD_F32, { M, sk }), + T(d_wf, RAD_F8E4M3, { N, K }), + T(d_s, RAD_BF16, { sn, sk }), + T(c1, RAD_F8E4M3, { M, nout }), + T(z1, RAD_F32, { M, gkb }), + T(b1, RAD_BF16, { M, nout }) }, + { PI("M", M), PI("N", N), PI("K", K), PI("group", 128), + PS("dtype", "fp8a8"), PS("act", "silu") }); + const std::string wn = + std::string("gemm_fp8a8_gated_nt_wide is byte-identical to the GEMM + " + "gated_quant_fp8, N ") + std::to_string((long long)N) + + " M " + std::to_string((long long)M); + if (rc != RAD_OK) { ok(wn.c_str(), false, "rc=" + std::to_string(rc)); continue; } + std::vector q0((size_t)M * nout), q1((size_t)M * nout); + std::vector s0((size_t)M * gkb), s1((size_t)M * gkb); + std::vector y0((size_t)M * nout), y1((size_t)M * nout); + st_memcpy(q0.data(), c0, q0.size(), hipMemcpyDeviceToHost); + st_memcpy(q1.data(), c1, q1.size(), hipMemcpyDeviceToHost); + st_memcpy(s0.data(), z0, s0.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(s1.data(), z1, s1.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(y0.data(), b0, y0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(y1.data(), b1, y1.size() * 2, hipMemcpyDeviceToHost); + int nc = 0, nz = 0, ny = 0, live = 0; + for (size_t i = 0; i < q0.size(); ++i) nc += q0[i] != q1[i]; + for (size_t i = 0; i < s0.size(); ++i) + nz += std::memcmp(&s0[i], &s1[i], 4) != 0; + for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i]; + for (size_t i = 0; i < q1.size(); ++i) live += q1[i] != 0; + ok(wn.c_str(), nc == 0 && nz == 0 && ny == 0 && live > (int)q1.size() / 2, + "codes differ " + std::to_string(nc) + ", scales " + std::to_string(nz) + + ", bf16 " + std::to_string(ny) + ", nonzero " + std::to_string(live)); + } } } } @@ -28695,9 +28876,10 @@ static void device_phase(const Plugin& pl) { hipDeviceProp_t p; if (hipGetDeviceProperties(&p, d) != hipSuccess) continue; if (!g_case) std::printf(" device %d: %s\n", d, p.gcnArchName); - if (std::strncmp(p.gcnArchName, "gfx1201", 7) == 0) devs.push_back(d); + if (std::strncmp(p.gcnArchName, "gfx1201", 7) == 0 || + std::strncmp(p.gcnArchName, "gfx1200", 7) == 0) devs.push_back(d); } - if (devs.empty()) { skip("device phase", "no gfx1201 device"); return; } + if (devs.empty()) { skip("device phase", "no gfx1200/gfx1201 device"); return; } st_set_device(devs[0]); if (!g_case) std::printf("\ndevice smoke tests (device %d)\n", devs[0]);