diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt index b62876c8..39529746 100644 --- a/libr3d/CMakeLists.txt +++ b/libr3d/CMakeLists.txt @@ -1,8 +1,10 @@ -# libr3d serves RDNA3 only; this file is the one place that says so. Its kernels rely on wave32 and -# on RDNA3 instructions: v_dot2acc_f32_f16 for the matrix work, v_cvt_pkrtz_f16_f32, DPP16 and -# v_permlanex16. They do not use the WMMA fragment layouts (RDNA3's 16x16x16 wave-matrix family -# needs a different lane map than dot2) or gfx12-only instructions such as global_load_tr_b128, -# and they decode every quantised weight in software because of that lane map. +# libr3d serves RDNA3 only, declared here and nowhere else. Its kernels rely on wave32 and on +# instructions RDNA3 has: v_dot2acc_f32_f16 and the 16x16x16 v_wmma wave-matrix family for the +# matrix work, v_cvt_pkrtz_f16_f32, DPP16 and v_permlanex16. The GEMM rows carry two arms each, +# the dot2 pairs and the wave matrix, points of the row's `impl` axis the tune cache picks per +# shape per machine. The kernels do not use gfx12-only instructions such as global_load_tr_b128, +# and they decode every quantised weight in software: the lane map, not a missing instruction, is +# the reason. # # A build targeting other cards skips libr3d. Without a device kernel library the engine refuses ops # only a reference library implements, unless --debug-accept-reference-kernels is passed (spec §17). @@ -58,12 +60,20 @@ set(R3D_UNITS "r3d_gemm_nt_q_w2a8|" # The vocabulary projection at both heights: the head streamed for M <= 16, tiled above it. "r3d_vocab_bf16|" + # The tiled GEMM on the wave-matrix: the compute-dual of the ALU fdot2 tile above. + "r3d_vocab_bf16_wmma|" # The quantised GEMM at prefill heights. "r3d_gemm_fp8a8_tiled|" # The OCP-MXFP4 weight against the fp8 activation, both heights: e2m1 codes with one e8m0 scale # per 32 of K, the block's partials scaled at the block boundary. "r3d_gemm_mxfp4a8|" "r3d_gemm_inta8|" + # The wave-matrix arm of the w8a8 grid: V_WMMA_I32_16X16X16_IU8 chains an exact i32 group + # sub-sum, the group term the reference's. The `impl` point of the dot2 arm's row. + "r3d_gemm_inta8_wmma|" + # The w8a8 wave-matrix arm at prefill heights (17 <= M <= 127): two 16-row tiles a wave, the + # weight column reused over the tiles, the group term the reference. + "r3d_gemm_w8a8_nt_m64|" # Paged attention at head_dim 128: the decode leg (one head group a workgroup, 16-token tiles, # split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3 # cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes. @@ -74,9 +84,68 @@ set(R3D_UNITS # Activation quantisation: per-(row, group) symmetric E4M3 and int8, the gated form that # quantises a silu-gated pair, and the dequantise that reads a container's own quantised weights. "r3d_quant_fp8|" + "r3d_had_quant_act_i8|" + "r3d_gelu_mul_quant_i8|" + "r3d_kv_len_trim|" + "r3d_qsa_tail_store|" + "r3d_gated_had_quant_i8|" + "r3d_had_quant_act_fp8|" + "r3d_gated_had_quant_fp8|" + "r3d_quant_cols_fp8|" + "r3d_had_quant_act_i8g|" + "r3d_gated_had_quant_i8g|" + "r3d_rmsnorm_quant_i8|" # The skinny bf16 GEMM for decode, M <= 16: one output element a lane, k ascending, so the # accumulation order is libref's. "r3d_gemm_bf16_nt_m16|" + # The wave-matrix arm of the skinny bf16 GEMM: V_WMMA_F32_16X16X16_BF16 over a 16x16x16 tile, a + # wave a tile, the `impl` point of the dot2 arm's row. + "r3d_gemm_bf16_nt_m16_wmma|" + # The wave-matrix bf16 GEMM for the M = 17..127 band: MT 16-row tiles a block, the B-fragment + # reused over the tiles so the weight stream is read once per 16-column tile. + "r3d_gemm_bf16_nt_m64_wmma|" + # The same shape over an f16 checkpoint: the bytes are the dot's native pair, so the stage is a + # straight copy and the weight streams into the fold with no widening. + "r3d_gemm_f16_nt_m16|" + # The wave-matrix arm of the skinny f16 GEMM: V_WMMA_F32_16X16X16_F16 over a 16x16x16 tile, the + # `impl` point of its row. + "r3d_gemm_f16_nt_m16_wmma|" + # The 4-bit weight against an f16 activation, M up to 64: the codes through the tile's f16 on a + # 1024 offset, the zero a packed f16 add, the group scale on the f32 accumulator. The weight's + # fragment-order permute is the row's own relayout hook, at load. + "r3d_gemm_w4a16_nt_m64|" + "r3d_gemm_w5a16_nt_m64|" + # The gated-delta-net chunk preamble: the gram and the blocked inverse of I + the strictly + # lower decayed gram, one 64-chunk a workgroup, the gram per k head. + "r3d_gdn_kkt_solve_c64|" + # The gated-delta-net chunked scan: the chunk's output and its closing state, the recurrent + # state in wave-matrix accumulators across the chunk loop. + "r3d_gdn_chunk_scan_k128_v128_c64|" + "r3d_gdn_gated_rmsnorm_h128|" + "r3d_gdn_gated_norm_had_quant_i8|" + "r3d_gdn_conv_w4_h128|" + "r3d_gdn_recurrent_update_k128_v128|" + # Mixture of experts: each routing weight times its expert's own scale, in place. + "r3d_expert_scale_bf16|" + # The router: softmax over the expert logits, the top_k by value, renormalised if `norm`. + "r3d_moe_router_topk_bf16|" + # The routed slots' stable counting sort (the small form, one workgroup). + "r3d_moe_scatter|" + # Fold the expert outputs back to the token (the gather, and the inverse-table form). + "r3d_moe_gather|" + # The grouped w4a8 GEMM core: int8 activation x two's-complement 4-bit weight, widened to f16 and + # run on the f16 wave-matrix, a per-(row, 128-of-K) scale fold. Phase 1: dense rows, no gather. + "r3d_moe_gemm_w4a8|" + # The grouped E4M3 x E4M3 GEMM (moe_gemm_q): both operands fp8, staged compact and upcast to f16 + # in registers (the FeatherOps bit trick), the f16 wave-matrix, a per-(row, g-of-K) scale fold. + "r3d_moe_gemm_q|" + # The grouped GEMM with unquantised bf16 experts: the same run-walk / gather as moe_gemm_q, the + # bf16 operands loaded straight into the bf16 wave-matrix fragments (f32 accumulate), no decode. + "r3d_moe_gemm_bf16|" + # The grouped GEMM with canonical MXFP4 experts: E2M1 codes (two a byte) decoded exactly to E4M3 + # and run on the f16 wave-matrix, the E8M0 scales folded in f32 per 32 of K. + "r3d_moe_gemm_mxfp4a8|" + "r3d_moe_gemm_fp8_f32scale|" # The same shape over a block-scaled fp8 weight, decoded to f16 exactly (E4M3's four exponent bits # and three mantissa bits are a subset of f16's), and over int8 codes. "r3d_gemm_fp8a16_nt_m1|" diff --git a/libr3d/README.md b/libr3d/README.md index aca5288f..924788bb 100644 --- a/libr3d/README.md +++ b/libr3d/README.md @@ -1,21 +1,23 @@ # libr3d libr3d is radiance's kernel library for RDNA3 and RDNA3.5, the gfx11xx family: `gfx1100`, -`gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, and `gfx11-generic`, the code object for a -gfx11 card the build did not name. It is HIP kernels behind a plain C ABI ([`r3d.h`](r3d.h)) plus +`gfx1101`, `gfx1102`, `gfx1103`, `gfx1150`, `gfx1151`, `gfx1152`, `gfx1153`, and `gfx11-generic`, +the code object for a gfx11 card the build did not name. It is HIP kernels behind a plain C ABI +([`r3d.h`](r3d.h)) plus the kernel-plugin rows the engine selects from (`r3d_rows.cpp`); `libr3d/CMakeLists.txt` names every unit and its flags. It claims `^gfx11` where [`libr4d`](../libr4d/README.md) claims `^gfx12`; a card gets one device -library, chosen by the rows, not by the name. The kernels are not ports of libr4d's. The matrix -work runs on the dot2 path (RDNA3's 16x16 wave-matrix family uses a fragment layout these lane -maps do not, and gfx11 has no bf16 pack and no VOPD), so every arithmetic path is its own: -`v_dot2acc_f32_f16` for products, software codecs for every format, and weights read in the order -the container stores them. The contract is shared with libr4d: the same op schemas (copied slot -for slot from libref, as the loader requires), the same numerics rules and the same geometry in -constraints. Parts of the family differ in CU count and clock, never in these instructions, so one -code object per family suffices. Numbers in this document are quoted with their geometry, and with -the class of part where the part's size matters. +library, chosen by the rows, not the name. The kernels are not ports of libr4d's: gfx11 has no +bf16 pack and no VOPD, and a different integer instruction set, so every arithmetic path is its +own. The matrix work splits by dtype: the bf16/f16 GEMM rows (the m64 band and the prefill-tiled +form) and every MoE GEMM row run on the 16x16x16 wave-matrix (WMMA) builtins retiled onto a 16x128 +block tile, as do the quantised m64 prefill rows; the integer rows (an int8 activation against +int8/int4/int2 weights) and the one-to-sixteen-row GEMMs run the dot2 path, +`v_dot2acc_f32_f16`, with software codecs for every format. The contract is shared with libr4d: +the same op schemas (copied slot for slot from libref, as the loader requires), the same numerics +rules, the same geometry in constraints. Family parts differ in CU count and clock, never in these +instructions, so one code object per family suffices. ## Naming @@ -54,15 +56,18 @@ The table groups the rows by family; `r3d_rows.cpp` and `r3d.h` hold the full se | `norm` | `rmsnorm_bf16` (optional residual add and multiplier), `rmsnorm_f32`, `layernorm_bf16` | | `elem` | `add` (with `div`, and the broadcast band), `mul`, `silu`, `gelu`, `sigmoid`, `act_mul_{silu,gelu,sigmoid}`, `softmax`, `scale`, `fill` (bf16/f32/i32/i64), `gather_rows`, `scatter_rows`, bf16 and f32 where the op has both, plus seven `cast` pairs and `silu_mul_bf16` | | `attn` | `rope_bf16` (neox and gptj, in place over packed QKV), `kv_store_{bf16,f16,fp8}`, `attn_paged_{bf16,fp8}_{decode,prefill}`: head_dim 128, split-KV combined in the same launch | -| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128x128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w8a8_m16` (signed int8 weight, decode band), `gemm_nt_q_gated_fp8a8` | -| `vocab` | `logits_gemm_bf16`: the head, read once per token, as bf16 or as E4M3 codes with a bf16 scale per 128x128 block | -| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `gated_quant_fp8_bf16`, `rmsnorm_quant_fp8_bf16` (norm and quantiser in one pass), `dequant_fp8`, `dequant_e5m2`, `dequant_i8` | -| `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` | -| `moe` | `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too) | +| `kv` | `kv_len_trim_i32` (per-sequence context lengths less `trim`, the QSA slice's own last row), `qsa_tail_store_bf16` (the QSA indexer's tail into a per-layer linear KV state, ring addressed by position) | +| `gemm` | `embed_lookup_bf16`, `gemm_nt_bf16_{m16,tiled}`, `gemm_nt_f16_m16`, `gemm_nt_q_fp8a16_m16`, `gemm_nt_q_fp8a8_{m16,tiled}`, `gemm_nt_q_mxfp4a8_{m16,tiled}` (OCP-MXFP4 weight: e2m1 codes, an e8m0 scale per 32 of K), `gemm_nt_q_w2a8_{m16,tiled}` (2-bit and 4-bit grids on the 128x128 tile), `gemm_nt_q_w4a8_m16` (signed int4 weight, decode band), `gemm_nt_q_w4a16asym_m64` and `gemm_nt_q_w5a16_m64` (4- and 5-bit codes against an f16 activation, 1..64 rows on the wave matrix), `gemm_nt_q_w8a8_{m16,m64}` (signed int8 weight, decode band and 17..127 prefill rows on the wave matrix), `gemm_nt_q_gated_fp8a8` | +| `vocab` | `logits_gemm_bf16`: the head, read once per token, as bf16 or as E4M3 codes with a bf16 scale per 128x128 block; the `impl` axis picks the decode (the LDS table, the per-byte ALU formula) | +| `quant` | `quant_act_fp8_bf16`, `quant_act_i8_bf16`, `quant_act_i8g_bf16`, `had_quant_act_{i8,fp8}_bf16` and `had_quant_act_i8g_bf16` (the same with a block Walsh-Hadamard rotation), `gated_had_quant_{i8,i8g,fp8}_bf16`, `gelu_mul_quant_i8_bf16`, `quant_cols_fp8_bf16`, `rmsnorm_quant_{fp8,i8}_bf16` (norm and quantiser in one pass), `gated_quant_fp8_bf16`, `dequant_fp8`, `dequant_e5m2`, `dequant_i8` | +| `sample` | pre-filters `sample_{penalties,dry,ngram_ban,mask,logprobs}_f32`; spine `sample_{argmax,temp,topk,pick,topp,minp,typical,xtc}_f32` — f32 logits in and out, the draw the reference's in its order, the top-R scan single-pass (the plane read once) | +| `moe` | `expert_scale_bf16` (the renormalised top-k weight times the expert's per-expert scale, in place), `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), `moe_router_topk_scatter` (the top-k and the counting sort as one op), `moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the kept weights scaled by `route_scale`), `moe_scatter_small` (the routed slots' stable counting sort; histogram in LDS, T ≤ 1024), `moe_gather` (fold the expert outputs back to the token, with the optional shared arm), `moe_gemm_q_e4m3` (grouped E4M3 GEMM; the `impl` axis: 16x16 table decode, 16x16 ALU decode, 16x128 block with the F32 scales folded), `moe_gemm_bf16` (unquantised experts, wave matrix), `moe_gemm_mxfp4a8` (canonical MXFP4 experts), `row_topk_{bf16,f32}` (the reference files the op under `moe`, so the row does too). `r3d_rad_moe_gemm_w4a8` is an exported WIP launcher (packed int4 weights, the i32 wave matrix) that is not a row: no `r3d_rows.cpp` entry, no selftest, per its kernel header | +| `gdn` | `gdn_kkt_solve_c64` (`A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk), `gdn_chunk_scan_k128_v128_c64` (the chunked scan: WY recompute, state recurrence and output in one kernel), `gdn_gated_rmsnorm_h128`, `gdn_gated_norm_had_quant_i8` (the gated norm fused with the rotation and quantiser), `gdn_conv_prep_w4_h128` (causal conv, split, l2norm, gating and the per-chunk gate cumsum in one prefill kernel), `gdn_conv_update_w4_h128` (the same convolution at decode over a rolling conv-state buffer), `gdn_recurrent_update_k128_v128` (the decode-time recurrent state update) | | `draft` | `dflash_select_bf16`: the drafter's accept step, a walk over the draft block's candidate lattice | -The table holds 78 rows over 44 schemas; `r3d_selftest` checks every schema slot for slot against -the `libref.so` beside the plugin. GEMM rows carry tunables (`sk`, `wv`, `nt`); the rest have none. +The table holds 109 rows over 70 schemas; `r3d_selftest` checks every schema slot for slot against +the `libref.so` beside the plugin. Fourteen rows carry tune axes (see +[Tunable params](#tunable-params)); the rest are single-implementation. There are two int8 activation rows because the reference has two ops and they are not interchangeable. `quant_act_i8` writes one scale per row, with codes in the order an int8 matrix @@ -72,32 +77,29 @@ row-major codes; that is what this library's `i8a8` GEMM reads and `dequant` inv order belongs to the op: the oracle compares the plane element by element, and it is the one place in libr3d where a store address carries a permutation. -## Constraints as data +## Tunable params -Constraints are data in the rows the engine reads, because a further copy of a geometry in each -caller would drift. `r3d_selftest` checks every constraint key against the op's declared -parameters, so a key renamed in one place only is caught instead of producing a row that matches -nothing. Three engine rules decide what goes in a table: +A row's tune axes are `RAD_P_INT` parameters the engine's `rad-tune` walks and the selftest +checks (each default among its ascending values). An axis value the kernel cannot serve is +refused by the launcher, not clamped. `rad-tune` merges its findings into the tune cache keyed by +machine, so a row's shipped number is the tuned default for the part; `rad-kbench --all-rows` +measures the arms a tuned default never reaches. -* **A constraint on a key the band does not carry does not hold.** A band carries the parameters - its graph set and nothing else, so a row that constrains an optional parameter serves only - graphs that state it: binding `rotary_dim` (optional on `rope`) would resolve the row to nothing - for every graph that rotates a whole head, and binding `pb1`/`pb2` on the quantised GEMMs would - send a whole model's bands to the host. The selftest's reachability phase names every row that - narrows itself this way. -* **A band's `dtype` is the activation's.** A row whose dtype lives in the weight does not - constrain it: `logits_gemm` carries no `dtype` constraint, because the head's dtype is a - property of the operand, checked on the tensor. `gemm_nt_q` is the opposite case: there `dtype` - is the operand scheme, so `C_IN` filters on it. Each table states which case it is. -* **A row's floor is its sibling's declared ceiling + 1.** The tiled rows begin at `M >= 17` - because `gemm_nt_bf16_m16` declares `C_LE("M", 16)`, read from the constraint and not from the - name. A floor reasoned from prose ("the decode heights") leaves 17..64, the batched-decode - heights, unserved. +| axis | rows | what it selects | +| --- | --- | --- | +| `impl` | `gemm_nt_bf16_m16` / `gemm_nt_f16_m16`, `gemm_nt_q_fp8a16_m16` / `gemm_nt_q_fp8a8_m16`, `gemm_nt_q_mxfp4a8_{m16,tiled}`, `gemm_nt_q_w8a8_m16`, `gemm_nt_q_fp8a8_tiled`, `logits_gemm_bf16`, `gemm_nt_bf16_tiled`, `moe_gemm_q_e4m3` | the kernel arm. On the m16 rows: the dot2 pairs vs the 16x16x16 wave matrix. On `logits_gemm_bf16`: the LDS table decode vs the per-byte ALU decode. On `gemm_nt_bf16_tiled` the four arms are the fdot2 tile, the same tile with the ALU decode, the 128x128 wave matrix (the compute-dual, above) and the 16-column-tile m64 kernel. On `moe_gemm_q_e4m3`: the 16x16 table-decode tile, the 16x16 ALU-decode tile, the 16x128 block with the F32 scales folded | +| `mrows` | `moe_gemm_bf16` | the block's row count (16 / 32 / 64). The compiled points are the legal ones (the `moe_bf16_tune_valid` table); the rest refuse | +| `vgpr` | `moe_gemm_bf16`, `moe_gemm_q_e4m3` (arm 2 only) | the per-lane register budget the kernel is compiled at — the occupancy knob: on the 1024-VGPR/SIMD file, 128 is the 8-wave cap and 512 the natural allocation; each budget is a separate kernel emission, and the win is height-specific (extra waves only pay on latency-bound shapes, where spills can cost more than they buy) | +| `acc` | `moe_gemm_bf16`, `moe_gemm_q_e4m3` (arm 2 only), `gemm_nt_q_w4a16asym_m64` / `gemm_nt_q_w5a16_m64` | 0 = f32 accumulate (the default); 1 = the 16-bit-accumulate WMMA form. A precision knob, not a speed one: no throughput gain, a documented low-precision mode (the [wave-matrix builtins](#what-the-family-provides-and-what-it-lacks)) | +| `sk` | the m16 and m64 GEMM rows | the split-K count | +| `wv` | the m16 and m64 GEMM rows | waves per workgroup | +| `nt` | the m16 and m64 GEMM rows | the streaming-load form of the weight fetch | +| `mb` | the m64 GEMM rows | the m-block (row-tile) count per workgroup | +| `npw` | the m64 GEMM rows | n-per-wave (columns per wave) | -What the kernel cannot read goes in the constraints as well as the launch check: `n_vocab >= 4` is -the store's granularity (rows are written in 16-byte runs); `n_cand <= 1024` is the candidate -kernels' LDS budget (five f32 arrays of `n_cand` = 20 KiB of the 64 KiB); `K % 32` and `K % 128` -are the tile's k-chunk and the container's scale block. +The `vgpr` and `acc` axes are arm 2's on `moe_gemm_q_e4m3` because only the 16x128 block is +compiled in more than one register budget and in both accumulator forms; the 16x16 tiles are +single-variant. ## Building @@ -119,253 +121,312 @@ libr4d's under the same `RAD_HIP_FOUND` guard. `R3D_UNITS` lists the units as `"file|extra flags"`, each named after the entry point it provides; the shared headers (`r3d_common.h`, `r3d_codecs.h`, `r3d_args.h`, `r3d_launch.h`, `r3d_tiling.h`, -`r3d_fp8_dequant.h`) provide no kernel. Every unit is compiled `-ffp-contract=off`, which -`rad_hipify` puts on all HIP sources; it is a correctness flag (see [Numerics](#numerics)). -`r3d_rows.cpp` and `r3d_shapes.cpp` include neither `r3d.h` nor the HIP runtime, so the tables -compile without ROCm. Occupancy is set per kernel: `__launch_bounds__` and `amdgpu_waves_per_eu` -(`R3D_WAVES`) are written against this family's register file, not RDNA4's. +`r3d_fp8_dequant.h`, `r3d_fwht.h`) provide no kernel. Every unit is compiled `-ffp-contract=off`, +which `rad_hipify` puts on all HIP sources; it is a correctness flag (see [Numerics](#numerics)). +`r3d_selftest.cpp` is a host-only CMake target that dlopens the built `.so`; it needs no HIP +toolchain to compile, so a build machine runs its static phases without a card. ## Adding a kernel -1. Write the `.hip`, named after the entry point it provides, geometry included. -2. Declare the launcher in [`r3d.h`](r3d.h) and the shim in [`r3d_plugin.h`](r3d_plugin.h). -3. Add the unit to `R3D_UNITS` in `libr3d/CMakeLists.txt`, with any per-unit flags. -4. Add a `RadKernelInfo` row in `r3d_rows.cpp` with its constraint table. If its `op` is one - libref declares, copy libref's schema slot for slot (names and doc strings are free, roles are - not); if the op is new, declare the schema in the same file. -5. Add the operand description to `r3d_shapes.cpp` if the row's operands are not the schema's - plain reading, and a geometry to the selftest's list. -6. The selftest walks the table, so a new row runs with no new test code; its geometry comes from - its constraints. -7. Measure it: `r3d_selftest /kernels/libr3d.so --case `, then +1. A unit named after its entry point, `r3d_[_].hip`, in `R3D_UNITS`. +2. The launcher in [`r3d.h`](r3d.h) and the shim in the unit, both under `extern "C"`. +3. The row in `r3d_rows.cpp`: the geometry, the dtypes, the constraints, and the tune axes only + if the kernel has them. A geometry the kernel cannot serve is a constraint, not a check. +4. The selftest fixture for the row (the `Case` builder in `r3d_selftest.cpp`), with a geometry + to the selftest's list. +5. The row runs with no new test code: the selftest walks the table, so a new row runs with no new + test code; its geometry comes from the row's own `opd_shape`. +6. Measure it: `r3d_selftest /kernels/libr3d.so --case `, then `rad-kbench --home "$RADIANCE_HOME" --kernels libref:libr3d --op `. -A row naming an entry point that does not exist is an undefined symbol at `dlopen`, which refuses -the library and every row in it. A row therefore lands in the same change as its kernel, and a -constraint array whose kernel has not landed stays out of the table. +The constraints are the row's declaration of what it serves, read by the engine as a single source +of truth (the selftest checks every key against the op's declared parameters). Three rules: a +constraint on a key the band does not carry narrows the row to the graphs that state it (bind an +optional parameter and the row matches nothing for the graphs that omit it); a band's `dtype` is +the activation's, so a row whose dtype is a weight property (`logits_gemm`) constrains no dtype; +and a row's floor is its sibling's declared ceiling + 1 (the tiled rows open at `M >= 17` because +the m16 row declares `C_LE("M", 16)`). Hardware limits the kernel cannot violate (`n_vocab >= 4`, +`n_cand <= 1024`, `K % 32`/`K % 128`) go in the constraints too, checked at launch. ## What the family provides, and what it lacks -These facts come from emitted assembly for the gfx11 targets (`__has_builtin` under -`--offload-device-only`, `llvm-mc -show-encoding` per target) with the ROCm this tree builds -against; a claim checked on one chip names it. None of them differs between gfx110x and gfx115x, -which is what makes the family one code object. +**The wave-matrix builtins.** All of them are wave32, 16x16x16: f16, bf16, int8 and int4 inputs, +accumulating in f32, f16, bf16, i32. The fragment layout is `idx = lane % 16`, +`k = 8*(e>>2) + 4*(lane>>4) + (e&3)`; both A and B want K-contiguous rows, so swapping the +operands of a WMMA transposes the result. The 16-bit-accumulate forms +(`v_wmma_f16_16x16x16_f16`, `v_wmma_bf16_16x16x16_bf16`) exist as selectable variants on the +quantised m64 rows (w4a16/w5a16) and both MoE wave-matrix rows, the tune's `acc` axis; they are a +documented low-precision mode (the f32 form is the default) — the precision floor and the two +codegen traps are in [Numerics](#numerics). -**The dot2 path, and the wave-matrix instructions it does not use.** RDNA3 has six wave-matrix -instructions, all 16x16x16 wave32: f16, bf16, int8 and int4 inputs, accumulating in f32, f16, bf16 -or i32, and the toolchain emits them on every gfx11 target. They are not a separate matrix unit: -the ISA states that the WMMA ops run over multiple cycles on the DOT pipeline. A MAC-core -measurement (512 waves, K depth 4096, operands preloaded) agrees: f32-acc f16 19.11, f32-acc bf16 -19.24, f16-acc f16 19.44, i32-acc i8 19.29 and paired `v_dual_dot2acc_f32_f16` 18.86 TFLOP/s, all -within three percent. The i32-acc i4 tile reaches 25.68 TFLOP/s, but it takes i4 in both operands, -and the grids this library serves pair i8 activations with i4 or i2 weights; RDNA3 has no -mixed-precision integer WMMA, so that pipe is unreachable from the w4a8 and w2a8 rows. At the -decode band the integer rows are bound by weight bytes, not arithmetic: w8a8 m16 runs 0.850 TFLOP/s -and w4a8 m16 0.789 (M=16, N=11008, K=4096, weights in device memory), about 22x below the i8 -tile's MAC rate, so a re-tile onto WMMA would not move them. +Every feature RDNA3 lacks is emulated in software: -The kernels therefore run the dot2 path: one wave per weight row, a k-split per lane, the group's -exact sub-sum folded with one shfl. Moving to the WMMA fragment layout (lanes 0..15 replicated into -16..31, A one row per lane, B one column per lane, accumulator row i at lane (i%2)*16+j VGPR i/2) -would be a re-tile, not a drop-in. Products go through `__builtin_amdgcn_fdot2` -> -`v_dot2acc_f32_f16` on every gfx11 target, paired as `v_dual_dot2acc_f32_f16` where the scheduler -can, about a quarter of RDNA4's matrix rate. With no fragment layouts there are no repacked -weights, and no layout hook except where the container's own planes require one. +| absent on gfx11 | software substitute | +| --- | --- | +| int8 dot (`s32sd4`, `s32ud4`, `__dp4a`, `madocx`) | widen codes to f16, dot on `dot4_f16x4` — ≈22-bit mantissa on integer operands, so the w2a8 rows carry a documented one-ulp tail | +| fp8 convert (`v_cvt_pk_f16_fp8`) | e4m3 bit maths in [`r3d_codecs.h`](r3d_codecs.h); the tiled rows' decode is a 256-entry f16 LDS table, the `impl` arms a per-byte ALU formula | +| bf16 pack (`v_cvt_pk_bf16_f32`, RDNA4) | two adds plus a `v_perm_b32` | +| vector f64 | soft-float at 1:64 (sets the sampler's draw path, the [Numerics](#numerics) divergence table) | +| transposed loads, VOPD (`global_load_tr_b128`, `ds_read_b64_tr_b16`) | transposes in registers | -**No int8 dot.** `__builtin_amdgcn_s32sd4`, `__builtin_amdgcn_s32ud4`, `__dp4a` and -`__builtin_amdgcn_madocx_i32_i8` / `_u32_u8` are all undeclared for gfx1102. Codes widen to f16 -and the dot runs on `dot4_f16x4`. For 2-bit codes the widening uses the fact that the f16 bits of -`128 + x` are `0x5800 + 8x` for `0 <= x < 8`: a code becomes an f16 with a mask, two shifts and -an add, and the dot's result carries `128 * sum(a)`, which is the plane the op already has for the -zero point, so the de-bias is one exact f32 subtraction per (row, group). +**LLVM single-buffers LDS** and drains before a dependent read unless told otherwise: the dot2 +rows have nothing to overlap a load with, so the plain barrier is the one they need, while the +wave-matrix rows double-buffer the k tile (the next tile stages while the current one multiplies). -**`v_fdot2_f32_f16` carries about 22 bits of mantissa on integer operands, not 24.** "Products -and partials are integers below 2^24, so the dot is exact" holds for f32 and not for this -instruction. `probe_dot_kernel` in `r3d_gemm_nt_q_w2a8.hip` measures it: one 64-code dot per lane, -its f32 result beside the exact integer. Over 262144 dots, a bias of 1024 leaves 71027 inexact -with worst error 0.125 (every one a dot whose magnitude reached 2^20); a bias of 128 leaves 70115 -with worst error 0.015625. The worst error relative to magnitude is about 2^-22, so a smaller bias -shrinks the error without removing it. The same work as four `__fmaf_rn` per quad in f32 is exact -on all 262144 samples. `gemm_nt_q` at `w2a8` therefore ships with a documented one-ulp tail. +## The GEMM rows -**No fp8 conversion instructions.** On gfx1102 a build calling `v_cvt_pk_f16_fp8` contains no such -instruction; it expands to software, about 100 instructions per 8 codes against the four that widen -bf16. `v_cvt_pk_fp8_f32` / `v_cvt_pk_f32_fp8` need `fp8-conversion-insts`, which no gfx11 target -has; their builtins are declared for gfx11, so a `__has_builtin` guard passes, and they fail at -instruction selection. Both directions of e4m3 are bit maths in [`r3d_codecs.h`](r3d_codecs.h), -mirroring `rad_plugin.h` line for line and checked over every code. +The GEMM rows follow a **dual-variant principle**: most families ship two implementations the +tune picks per geometry, along two independent axes. -**The E4M3 decode is a table.** The arithmetic decode costs about ten VALU per code, and a -weight-stationary row decodes every code it multiplies (twice where a lane owns two chains). A -256-entry f16 table in LDS (512 bytes), built once per block by the arithmetic path and therefore -exact, costs two `ds_read_u16` and a pack per pair, at no register cost: the gated row's tall arm -is 109 registers per lane, four waves per SIMD, no spills. On the gated band (N=12288 K=2048 -group=128, codes resident) the table takes M=64 from 8395.3 us to 2786.5 us. Two invariants: +| axis | variant 0 | variant 1 | +| --- | --- | --- | +| **decode** (E4M3 weight) | the 256-entry f16 LDS table | the per-byte ALU formula | +| **compute** (the multiply pipe) | the ALU `fdot2`/`dot2` lane-per-element path | the 16x16x16 wave matrix | -* The table builder's codec argument is a pair (low code in the low byte), not an index. Passing - the index decodes code 0 into every odd entry, which zeroes half the products without producing - a NaN (`rel_l2` 9.6e-01 on the code-enumeration case). -* Decoded pairs go from the table into the dot inline. Materialising a step's eight pairs into an - array on the way miscomputes on the tall arm (`rel_l2` 6.6e-01 at M=7, NaN at M=64) even though - the table itself is exact on the device. Do not restore the array form. +The compute axis is the **compute-dual**, and it is the one that matters at prefill. On +`gemm_nt_bf16_tiled` (the 128x128 tile) the two arms are: -**`f16x2_pack` is `v_cvt_pkrtz_f16_f32`: it rounds toward zero and flushes subnormal f16.** Only -values f16 represents exactly may go through it (widened bf16, widened E4M3), never a code times a -scale. Folding `code * scale` through the pack biases every product toward zero (`rel_l2` 2.8e-4 -against the fold's law, 53% of outputs within 2 ulps). Folding with `v_mul_f16` (round to nearest, -subnormals kept) is one instruction and one correct rounding (4.5e-06, all outputs within 2 ulps, -none beyond six). Every scale fold here uses `v_mul_f16`. +| | arm 0 (ALU) | arm 2 (wave matrix) | +| --- | --- | --- | +| multiply pipe | VALU: f16 FMA / `v_dot2acc_f32_f16` | the 16x16x16 wave matrix | +| accumulators | 8x8 f32 a lane | 64 f32 a wave (eight 16x16 tiles) | +| k order | 32-code chunks | 32-code chunks | +| data movement | load, stage, barrier, store — **identical** | load, stage, barrier, store — **identical** | -**`v_cvt_pk_bf16_f32` does not exist** on gfx1100, gfx1102 or gfx1151: a bf16 pair is rounded by -hand and packed with `v_perm_b32`. +The two are duals in the literal sense: they share the entire data-movement skeleton and differ +only in the pipe that performs the multiply, so a number measured on one is a bound on the other's +data movement. The arm that wins is the one on the faster pipe for the shape's mix: the f16 matrix +core runs about twice the ALU FMA rate (512 vs ~256 FLOPS/clk/CU), so at prefill heights, where the +tile is compute-bound, the WMMA twin is the faster, and at decode heights, where the row is +latency- and bytes-bound, the two are close and the ALU form's lighter register pressure can win. -**The dot's bf16 selector does not select bf16.** `__builtin_amdgcn_fdot2` takes a `sel` operand -for the bf16 form; the compiler accepts `sel = true`, emits the f16 instruction, and reads bf16 -operands as f16, silently producing wrong products. `dot2_f16x2` always passes `false`. f16 is the -compute type: bf16 and E4M3 widen to it exactly, with the edges handled in the codecs (above 65504 -a widening saturates; below 2^-14 the f16 subnormal grid is coarser than the source's and -truncates). +The rule the rows follow: **every dot2 GEMM kernel ships a wave-matrix twin the tune can pick** — +the m16 rows carry it as the `impl` axis (dot2 vs 16x16x16 wave matrix), the tiled row as one of +its four arms, and the quantised m64 rows run on the wave matrix directly. The MoE wave-matrix rows +are the same idea at the grouped-GEMM scale: the 16x128 block makes every wave own unique columns, +so no wave re-runs a tile, and the run-walk re-stages the expert's weights per run. -**Wave32, a smaller register file than RDNA4.** A SIMD has 1024 VGPRs for wave32, in granules of -8, against RDNA4's 1536; LDS is 64 KiB per workgroup on both. Occupancy constants do not carry -across the generation, so `R3D_WAVES` is set per kernel. A CU is 4 SIMDs x 16 wave32s = 64 wave -slots, and `multiProcessorCount` reports CUs on gfx11 (WGPs on gfx12), so a row-per-block kernel -with one wave per block reaches 64 waves per CU exactly at the row count where tail waves start -waiting. A wave64 build is refused -at compile time (`r3d_common.h`): it would compute garbage rather than run slower. +### The 16x128 wave-matrix retile -**No vector f64.** Consumer RDNA3 runs doubles at 1:64, in practice soft-float, which sets the -transcendental policy per unit: the sampler keeps the reference's `(float)exp((double)x)`, -because a draw must reproduce; attention cannot afford it and uses a polynomial; the gated MLP uses -`expf` into a bf16 narrowing. +The retile is 16 rows by 128 columns: eight waves, each wave one 16-column tile on the 16x16x16 +wave matrix, the fragment layout lanes 0..15 replicated into 16..31, A one row per lane, B one +column per lane, accumulator row i at lane (i%2)*16+j in VGPR i/2. Against the naive 16x16 tile it +removes the 8x wave redundancy (every wave re-running the same 16 columns), stages the activation +once per 16x128 block, and reads the weight once per 16-column tile. -**The lane ops are libr4d's:** `update_dpp` (xor and shr controls), `permlanex16`, `readlane`, -`readfirstlane`, `ballot`, `ds_bpermute`, `v_perm_b32`, `exp2f`, `rcpf`, `s_barrier`, -`sched_group_barrier`. DPP16 and `v_permlanex16` exist from RDNA1 on, and the encodings in -[`r3d_common.h`](r3d_common.h) are the ones libr4d verified on hardware. +### The rows by row count (bf16/f16 and the quantised m64) -**No transposed loads, no VOPD.** There is no `global_load_tr_b128` (RDNA4) and -`ds_read_b64_tr_b16` is rejected by this assembler, so transposes are done in registers. VOPD is -RDNA4; the tree's `-mllvm=-amdgpu-enable-vopd=false` comes from the LLVM version. LLVM -single-buffers LDS and drains before a dependent read unless told otherwise, and without a matrix -unit there is nothing to overlap a load with, so the plain barrier is the one needed. +The GEMM band is covered by row count: -## Stored weights: layout hooks and their writers +* `gemm_nt_bf16_m16` / `gemm_nt_f16_m16` (M ≤ 16) carry the `impl` axis: 0 = the dot2 pairs, + 1 = the 16x16x16 wave matrix. The two implementations share the row, so the tune can pick per + shape. +* `gemm_nt_bf16_tiled` serves the prefill heights and the M = 17..127 band; its `impl` axis picks + the kernel: 0 = 128x128 tiles through LDS with 8x8 f32 accumulators a lane, 1 = the same tile + with the bf16 decode in registers (the per-byte ALU formula), 2 = the same tile on the wave + matrix (eight 16x16 tiles a wave, 64 f32 accumulators, k in 32-code chunks -- every wave owns + unique columns, so no wave re-runs a tile; the compute-dual of arm 0, with the multiply on the + wave-matrix pipe), 3 = the 16-column-tile wave-matrix kernel for the 17..127 band (MT 16-row + tiles a block, one 16-column tile a wave across the row tiles, k ascending in 16-wide + wave-matrix steps; the B-fragment is loaded once a step and reused over the row tiles, so the + weight stream is read once per 16-column tile; split-K over scratch, the partials reduced in + split order). M ≤ 16 stays with the m16 rows, whose wave-per-run-of-columns shape is the right + one there: the two ranges are complements, so neither competes for the other's band. -Four rows declare a `layout`: `gemm_nt_q_w2a8_m16`, `gemm_nt_q_w2a8_tiled`, -`gemm_nt_q_fp8a8_tiled` and `logits_gemm_bf16`. Each also declares the `relayout` that produces -the form it names, and `r3d_selftest.cpp` enforces the pair by name: a `layout` without a -`relayout`, a `relayout` without a `layout`, or any `unrelayout` fails the table. +The quantised m64 prefill rows run on the wave matrix with the same tiling: +`gemm_nt_q_w4a16asym_m64` (1..64 rows; unsigned 4-bit codes, an f16 scale and an integer zero per +128 of K, against an f16 activation) and `gemm_nt_q_w5a16_m64` (1..64 rows; ParoQuant's int5: the +4-bit row with a fifth bit riding a plane of its own, one word a (tile, 64 of K, lane)) carry the +`tGemmM64` tune (`sk`, `wv`, `mb`, `npw`, `nt`, `acc`), and `gemm_nt_q_w8a8_m64` (17..127 rows; +signed int8 weight against int8 activations, the group's integer sub-sum scaled once) is the +symmetric grid's prefill arm. The weights arrive pre-permuted into fragment order at load (the +`layout` hooks), the split-K slabs reduce in the block's dynamic LDS in ascending split order. The +codes are exact in the tile's f16, and the store is the only narrowing. -A dot2 GEMM reads a weight in the order it is stored, so libr3d never repacks: **no -plugin-private dtype, no repack into a format of this plugin's invention, no container format -changed from inside a kernel library.** The hooks exist because the container's quantiser itself -stores some weights as separate planes a kernel cannot read in place, codes and per-block scales -(for a head, `fp8_e4m3 * bf16[128x128]`). The engine's canonical form for those is the planes -joined behind one operand, `rad.planes`, sized by `rad_planes_plan` and written by -`rad_planes_relayout`. A row that reads such a weight describes that form and produces it; the -engine does the work at load, in the loader's pool behind the container read. The rules: +### The fp8a8 rows -* **A hook that answers is a promise.** The ABI states: *RAD_OK: out describes the stored form, - and `relayout` will produce it*. With `relayout = nullptr` the model does not load - (`could not produce '...' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported`). -* **A weight is stored once, so the first row to claim it owns its plan.** The engine arbitrates - across every row of every band that reads the weight, at declare (*is wanted in two stored - forms: 'rad.planes' by row A and '(as it is)' by row B. A weight is stored once.*). A second row - gets the same answer by calling the first row's hook, and its kernel reads the stored container - by role, not by the arrangement it declared. -* **`RAD_E_UNSUPPORTED` means stored as is**, the only kind of weight the mapped tier can read in - place, and the lever the placement ladder works with. A joined weight is a resident weight. A - band that resolves to the host pulls its whole layer group onto the tier that reads the - container in place, where a norm weight that needs conversion at load cannot live. A missing - device row for `gemm_nt_q` above the decode band therefore shows up as a startup failure, not a - slow band: the bands resolve to host kernels, the layer's weights stay in the container's - mapping, its norms group with them, and the mapped tier is asked for a widening it cannot do. -* **A container arrives as a tensor of `rank = 1`, `shape[0] = bytes`.** That is the joined form's - stored shape (a byte count, from `rad_planes_layout`), not a plane. A consumer that reads it as a - plane measures a scale plane's rows against `ceil(N/group)` and refuses with a geometry the - operand never had. Decode it by role on the host, where the header lives: the tag, the entry - table and the stored dtype (the first plane's) are host-readable, so the shim reads them once per - call and hands the kernel device pointers. -* **A `zero` plane is refused as `E_DTYPE`, not folded.** `w2a8` is the only scheme here with an - activation zero point, and its consumer is a row of this library (`r3d_gemm_nt_q_w2a8`). - `fp8a8`'s quantiser is symmetric: the reference's fp8a8 arm refuses `a_sum` - (`RAD_E_UNSUPPORTED`), the shape hook skips the operand, and every served band omits it. A row - that folded a zero point would compute a number the oracle has no law for. +The bands this family targets are 42 layers plus a drafter at `group=128 dtype=fp8a8`, band +ceiling M=2048: N=12288 K=2048 x44 (the gated MLP, two halves of 6144), N=2560 K=2048 x44 (qkv), +N=2048 K=6144 x44 (o-proj), N=2048 K=2048 x44, and N=2048 K=10240 x3 (the drafter). Three rows +cover them by row count, with boundaries read from the constraint tables: `gemm_nt_q_fp8a8_m16` +declares `C_LE("M", 16)`, so `gemm_nt_q_fp8a8_tiled` opens at `C_GE("M", 17)`, and +`gemm_nt_q_gated_fp8a8` serves M=1..64 with N even and K % 128 == 0. -Gains follow the same rule: they are read in the dtype the checkpoint stores (a 2048-element norm -gain in f32 is 8 KiB), because a row's `dtype` band names the activation, never the weight. The -fused norm's kernel takes the gain's dtype as a parameter (`WDT`), as the plain norm does. +**The m16 row** gives each lane one output element and streams the weight past an activation kept +in registers, with no wave reduction, so a lane's chain is the reference's and the row is +bit-comparable at the store. Above 16 rows the same operands use a 128x128 tile through LDS with +8x8 f32 accumulators per lane. The two ranges are complements, and the m16 row is compared against +the tiled row on the same bytes, where a moved boundary would show. -## Request-time rules: a plan's vocabulary is not its contents +**The tiled row folds the scales at staging.** The tile is f16, so both scale streams enter as f16 +multiplies where the codes are staged: the activation's `a_scale[m][g]` per staged row, the +weight's `b_scale[nb][g]` once per chunk. The products are separable, +`(a*sa)*(b*sb) = (a*b)*sa*sb`, so the accumulator stays one f32 register. The reference's law is +the group sub-sum from raw codes scaled once per group (`ref_gemm.h`'s `quant_dot`); the fold +differs from it by `rel_l2` 2.77e-04 against a bf16 store that costs 3.9e-3, so it is invisible in +the output (see the divergence table). -A clean graph dump means every band has a row; it does not mean a request runs. At request time -the engine hands the shim the contents (descriptors, strides, an arena, a step's shape), and a shim -must not read the band's vocabulary as if it were those contents. These are rules of the ABI, not -of any one model. +#### The gated MLP row -**A band's `dtype` is the activation's; a weight's dtype comes from the operand.** The head of a -`dtype=bf16` band can be E4M3 codes with a bf16 scale per 128x128 block. A shim that trusts the -key refuses the request the plan is making. +`gemm_nt_q_gated_fp8a8` fuses the GEMM, the gate and the output quantiser, so the bf16 `[M, N]` +intermediate is never written, read or allocated. The gate couples column `i` with column `n + i` +(192 waves apart at n = 6144, out of reach of any lane exchange), so each lane computes both +products of its column, walking k ascending with two accumulators over weight rows `i` and `n + i` +— the same traffic the unfused GEMM spends on the two columns. A block is one group of columns by +`256/group` rows, closing the group's amax inside the block (a wave max folded over the group's +waves in LDS, one scale store, one code per lane). The op is one launch with no scratch, so the row +is concurrent. Both halves are narrowed to bf16 before the gate (the pair it replaces stores and +re-reads them); the activation is not — `gt * sg` is f32 from the narrowed gate, and the product +with `up` rounds once, at the store. The law is libref's `ref_gemm_nt_q_gated`, and its order must +be kept. -**An optional operand with no bytes is absent.** Optional operands arrive as descriptors with a -null `data` when the graph bound none, so the test is `r3d_has(t)` (`t && t->data`). A bare -`if (t)` dtype-checks a descriptor with no bytes and answers `E_DTYPE` to a band whose dtype is -fine. +The launcher picks the arm by row count: fp8a8 at M <= 8 reads the activation and both weight rows +directly, 16 bytes at a time, decodes them from the block's table and multiplies, with no shared +memory between load and dot; M >= 9 (and every fp8a16 case) stage through LDS. The M <= 8 threshold +is a tunable, chosen for decode (M=1) and draft verify (M <= 8). -**A sizing hook runs at declare, where a descriptor has a shape and no bytes** (`data` is null for -every tensor in the plan). A scratch hook that returns 0 when `a->t[0].data` is null answers 0 for -the whole run, the engine allocates a zero-byte arena, and the split pass fails at request time -with `scratch buffer absent or too small`. Size from the shape (`rad_tensor_numel`) or the -parameters, as the GEMM hook does. Absence at launch means the plan asked for nothing; absence at -declare means the bytes come later. +The row carries no relayout: libref reads the gated `[N, K]` weight row-major, libr4d stores fp8a8 +weights in WMMA fragment order, and a row that inherited the fp8 GEMM's `unrelayout` would fail the +per-op oracle. The launcher refuses M > 64 (beyond the bands' ceiling the weight stream is a tiled +kernel's problem), N odd, a group not a power of two in [32, 256], `group > n` (the reference would +use n for the quantiser's group while keeping the weight's K block at the stated width), +`K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (the epilogue needs the +whole row), and an absent `act`. -**A band key is a bound, not the step's value.** A plan's geometry line reads `at M=30 [band -M<=2048] geometry {N=2560 K=2048 group=128 M=2048}`: the geometry's `M` is the ceiling the band was -built for, and the height of this step is what the operands say. Geometry comes from the operand -(`nel / N`, `qnel / n`, `r3d_rows_pitch(y, N, &M)`); the key stays the ceiling, and exceeding it is -a refusal that prints both numbers. +### The MoE GEMMs -**The engine sizes vector operands to the step, so their geometry comes from the tensor.** A -five-token prompt with nothing behind it carries a block table of `[n_seq, 1]`, not one as wide as -the cache. The reference takes the geometry from the tensor (`max_blocks` from `bt->shape[last]`, -row pitch from `stride[rank-2]`, column stride from `stride[rank-1]`, -`jend = min(ctx, max_blocks * block_size)`), so a context longer than the table's columns is -truncated by the oracle and the kernel alike. The attention shim derives all three from the -operand and checks the one thing required: that the last reachable index -`(n_seq-1)*bt_rs + (bt_cols-1)*bt_cs + 1` lies inside the plane. Two counts are kept apart: -`cache_blocks` bounds a slot's byte offset, `bt_cols` bounds the walk. +The grouped GEMM rows share the run-walk / gather structure: the block walks the runs in its +16 rows (a block spanning several experts at decode is correct), each run re-stages that expert's +weights, rows the run does not own are padding and their output is dropped, and a dropped slot +(sorted token < 0) writes zero. `y` is in sorted order. -**Serve the unoptimised form when the optimisation has no room.** One split-KV slice is the whole -walk in one block, the same keys in the same order, so the launcher lowers `splits` to what the -arena holds, down to 1, instead of refusing. +* `moe_gemm_bf16` — unquantised experts: the bf16 operands stage straight into the bf16 wave-matrix + fragments, f32 accumulate over the whole of K, no scales, `y` bf16. The weight is the checkpoint's + own bytes ([n_expert, N, K] row-major, no layout hook). Tunable over `mrows` (the block's row + count), `vgpr` and `acc`; the compiled points are the legal ones (the `moe_bf16_tune_valid` + table), the rest refuse. +* `moe_gemm_q_e4m3` — canonical E4M3 experts with F32 block scales, on the `moe_gemm_q` + contract: the even experts in `w` / `w_scale`, the odd in `w_odd` / `w_odd_scale`, at index e/2; + the scales fold in f32 per (grid_rows columns, 128 of K); `y` is f32. The `impl` axis: 0 = the + 16x16 tile with the 512-byte LDS decode table, 1 = the same tile with the per-byte ALU formula + (no LDS table), 2 = the 16x128 block with the F32 scales folded in f32 (the `vgpr` and `acc` + axes are arm 2's). The E4M3 operands widen exactly to f16, the f16 wave matrix (f32 accumulate) + runs the multiply. The `grid_rows` parameter takes 1 (w4a8's per-row) or 128 (fp8a8's + per-128x128). +* `moe_gemm_mxfp4a8` — canonical MXFP4 experts: the E4M3 activation and the E2M1 weight (decoded + exactly to E4M3) upcast to f16, the f16 wave matrix (f32 accumulate), the E8M0 weight scales fold + in f32 per 32 of K; the even/odd split as above, `y` bf16. -**A refusal carries a code, names its fix, and prints what it saw.** `R3D_NO(code)` prints the -site under `RAD_R3D_TRACE=1`; `R3D_STR` prints the two numbers a stride test compared; -`r3d_trace_desc` prints dtype, rank, shape and strides in elements, as the engine binds them. +On the prefill geometry (T = N = K = 4096, 8 experts, best / median of nine launches) the +`mrows`/`vgpr` points of `moe_gemm_bf16` run 41.67 ms at (16, 512), 26.19 ms at (32, 128) and +21.16 ms at (64, 512) — the wider the block's row tile the fewer expert re-stages, so (64, 512) +is the default's best point. The `moe_gemm_q_e4m3` 16x128 arm (vgpr 128) is 215 ms on the same +bytes: decode-bound on the E4M3 widen, which is why that row's tile is 16 rows and its arm 2 is +the one the prefill geometry reaches for. -**The ragged query batch is a descriptor, not a second kernel.** `cu_seqlens`, when present, is -`[n_seq + 1]` i32. `cu[0] == 0`, monotonicity and `cu[n_seq] ==` the plane's row count are -promises of the description that the engine keeps, but no row may rely on them. The reference's -`seq_of` walks `while (s + 1 < n && cu[s+1] <= row) ++s`, so rows below `cu[0]` are not excluded: -they land in sequence 0 with a negative index into its query, and the reference computes them at -`pos = ctx - qlen + i`, `cu[0]` keys into the past. So `q_len` is per sequence -(`q_len = cus ? 0 : rows / n_seq`), the total row count is the plane's, and a ragged batch has no -`q_len`. One grid covers both forms because the clamp a tile needs is per sequence; the -rectangular case is the descriptor's absence (`len_s = q_len`, `start_s = s * q_len`). +`r3d_rad_moe_gemm_w4a8` is the WIP int4-weights / int8-activation launcher behind the same run-walk +structure: a 16x128 block (the eight waves do unique 16-column sub-tiles), the int8 activation and +the packed int4 weight (decoded exactly to int8, the native i32 wave matrix) with the f32 scales +folded per 128 of K; a single weight plane, no even/odd split; `y` f32. It is exported and +value-probed, not a row: the remaining weight forms (the nl64/nl32 magnitude-table nibbles), the +prefill run map and the SK/UW/RS passes are outstanding, per its kernel header. -**A descriptor carries two row counts, and the store is bounded by the second.** -`len = cu[s+1] - cu[s]` is what positions count from; `span = cu[s+1] - start`, with -`start = (s == 0 && cu[0] > 0) ? 0 : cu[s]`, is how many rows the sequence's tiles carry, because -the grid covers the plane from row 0. The tile count comes from the length and the store bound -from the span. Bounding the store by the length silently drops the last `cu[0]` rows of an -in-bounds plane with status 0, which only a whole-plane read-back after a NaN pre-fill detects -(see [Numerics](#numerics)); the fixture never draws `cu[0] > 0`. +### Stored weights: the layout hooks + +Six GEMM rows declare a `layout` — `gemm_nt_q_{w2a8_m16,w2a8_tiled,fp8a8_tiled,w4a16asym_m64, +w5a16_m64}` and `logits_gemm_bf16` — each with the `relayout` that produces the form it names; +`r3d_selftest` enforces the pair by name (a `layout` without a `relayout`, a `relayout` without a +`layout`, or any `unrelayout`, fails the table). + +A GEMM reads a weight in the order it is stored, and what is stored is decided by the row's +`layout` hook, never by the kernel: **no plugin-private dtype, no repack into a format of this +plugin's invention, no container format changed from inside a kernel library.** The hooks exist +because the container's quantiser stores some weights as separate planes a kernel cannot read in +place (for a head, `fp8_e4m3 * bf16[128x128]`), and the wave-matrix m64 rows want the weight +pre-permuted into fragment order at load. The engine's canonical form for the split planes is the +planes joined behind one operand, `rad.planes`, sized by `rad_planes_plan` and written by +`rad_planes_relayout` at load. The rules: + +* **A hook that answers is a promise** — `RAD_OK` means the stored form is described and + `relayout` will produce it; with `relayout = nullptr` the model does not load. +* **A weight is stored once, so the first row to claim it owns its plan**; a second row gets the + same answer by calling the first row's hook and reads the container by role, not by the + arrangement it declared. +* **`RAD_E_UNSUPPORTED` means stored as is**, the only form the mapped tier can read in place; a + joined weight is a resident weight. +* **A container arrives as `rank = 1`, `shape[0] = bytes`** (the joined form's byte count, not a + plane); decode it by role on the host, where the header lives. +* **A `zero` plane is refused as `E_DTYPE`, not folded** — `w2a8` is the only scheme with an + activation zero point, and a row that folded one would compute a number the oracle has no law for. + +Gains are read in the dtype the checkpoint stores (bf16, f16, f32, i32 or i64), and the kernel's +arithmetic is the reference's in the reference's order. + +## The GDN, QSA, and MoE plumbing rows + +`gdn_kkt_solve_c64` runs the gated-delta-net's chunk preamble: the gram +`A = (I + strict_lower(diag(beta) K K^T e^{g_i-g_j}))^-1` per 64-chunk, the gram and the blocked +triangular inverse in one kernel, the fp32 gram never reaching memory. `gdn_chunk_scan_k128_v128_c64` +is the chunked scan: WY recompute, the state recurrence and the output in one kernel, the state in +wave-matrix accumulators across the chunk loop so only q, k, v, A, g, beta, the state cache and o +touch HBM. `gdn_gated_rmsnorm_h128` is the layer's own output norm, and +`gdn_gated_norm_had_quant_i8` is the gated norm fused with a block Walsh-Hadamard rotation and the +per-row int8 quantiser. `gdn_conv_prep_w4_h128` is the causal conv width 4 + silu, the q/k/v split, +the qk l2norm, the gating and the per-chunk gate cumsum in one prefill kernel, and +`gdn_conv_update_w4_h128` / `gdn_recurrent_update_k128_v128` are the same convolution and the +recurrent state update at decode, over a rolling conv-state buffer and a paged fp32 state cache. +The decode half (`gdn_recurrent_update_k128_v128`) and the single-chunk case of the scan are +value-verified against a CPU reference; the scan's multi-chunk state carry carries a small +documented residual on the development card (its kernel header states the band and the suspected +cause), so the gate there is bounded, not exact. + +The QSA rows are the indexer's tail: `kv_len_trim_i32` trims each sequence's context lengths by +`trim` (the slice's own last row), and `qsa_tail_store_bf16` writes the QSA indexer's tail into a +per-layer linear KV state, ring addressed by position. The MoE plumbing rows are the router and +the sort: `moe_router_topk_bf16` (softmax top-k, renormalised if `norm`), +`moe_router_sigmoid_topk` (the GLM-style router: sigmoid scores, selection on scores + bias, the +kept weights scaled by `route_scale`), `moe_router_topk_scatter` (the top-k and the counting sort +as one op), `moe_scatter_small` (the routed slots' stable counting sort; histogram in LDS, +T ≤ 1024) and `moe_gather` (fold the expert outputs back to the token, +`y[t,c] = sum_j expert_w[t,j] * y_expert[slot(t,j),c]`, with the optional shared arm; top_k ≤ 64). +`expert_scale_bf16` scales the renormalised top-k weights by the expert's per-expert scale in +place, and `dflash_select_bf16` is the drafter's accept step, a walk over the draft block's +candidate lattice. + +## The paged attention, decode and prefill + +Two rows, chosen by `q_len`: the decode entry (which takes `splits`) and the prefill entry. The +served geometry is n_head 16 over n_head_kv 2 at head_dim 128 (gqa 8), `block_size 16`, a 4096 +context, and an `fp8_e4m3` cache with its descales. One kernel serves decode (q_len 1), speculative +verify (q_len 7) and a prefill chunk (q_len 2048). + +The layout is the reference's: `kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]` (K then V +inside a slot), `block_table[seq, j / block_size]` names the block holding key j (a negative entry +hides its key), and `seqused[s]` is the sequence's total key count including this step's query rows. + +The block table is the window the kernel may read: `jcap = min(max_ctx, cols * block_size)`, and the +last reachable index must lie inside the plane. `splits` is a maximum, resolved per sequence from its +own `seqused`; the contract is that `splits = 1` is bit-identical to the reference and `splits > 1` +is not (the last-bit difference is in the [Numerics](#numerics) divergence table). ## Numerics -f32 accumulation, IEEE round-to-nearest-even narrowing, subnormals kept, no reassociation; the -oracle is `libref`. +The contract: accumulate in f32, narrow with IEEE round-to-nearest-even, keep subnormals, and do +not reassociate. `libref` is the oracle. + +**The 16-bit-accumulate mode (the `acc` axis) is a documented low-precision mode, off by default.** +The f16 and bf16 WMMA accumulator forms quantise the running sum at the 16-bit accumulator's +precision on every wave-matrix step, and the loss grows with the number of steps. It buys no +throughput (the matrix core runs the same rate on either accumulator), so it is a register-pressure +option the tune can reach for, not a speed one. Integer-valued operands (e.g. +/-1 codes) stay +exact, because every partial sum is an integer below the format's exact range; that is also the +degenerate data AMD's own WMMA verification feeds, and the reason a probe that feeds such data +cannot see the loss. Reading the 16-bit accumulator is a direct value conversion, never a union +bit-cast: the `_tied` constraint ties srcC and the result to one physical register, and a bit-cast +breaks the tie (the compiler returns the stale srcC copy, and the accumulated tile reads back as +zero). A second trap: mixing the f32-acc and 16-bit-acc builtins in one function behind a runtime +if/else zeroes the 16-bit path, so the kernels select the accumulator with `if constexpr` +(separate instantiations), never a runtime branch. **`-ffp-contract=off` on every HIP source** (`rad_hipify`, library-wide): a fused product-sum rounds once where the reference rounds twice, so a contracted kernel cannot match it. The flag @@ -393,24 +454,13 @@ libref's bytes, the unit that ships it names the divergence: | rope divides the position by `scale` and evaluates the frequency ladder in double | `scale` is the position scale (the multiplier on a rotated pair is YaRN's magnitude; the shims refuse YaRN, so it is 1). `powf` leaves the reciprocal an ulp off, and at position 262144 an ulp of a frequency is a hundredth of a radian, the one place in that kernel where f32 is not enough | | `block_sum`'s tree | wave butterfly, then partials in wave order: the reference's bracketing at any thread count, so kernel and reference agree at 256 threads and at 64 | | `sample_logprobs` keeps a NaN out of the max and in the sum; `sample_mask` skips a row whose `mask_row` is negative | maxima are a strict `>` (`std::max`'s law), so a NaN is never adopted; the sum propagates it, because the reference's `exp(NaN - mx)` is NaN and is added. The k-list is per lane in the reference's order (descending by value, ties to the lower column), merged in the same butterfly; the pool is 64 deep and a larger k is refused, not truncated. The mask bound is the reference's test (`mask_row` is `-1` for no mask), read from the operand, not from M | -| the sampler's `exp` and `log` are `double` calls narrowed once | draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over 2^20 points in [-100, 100], where `expf` differs by 1 ulp on 5.7% of them. At 1:64 doubles this is the slow path (one read of the band's logits plane takes 3.6 ms, a read that also sums double exponentials 30.4 ms), affordable on the candidate set (1024 exponentials per row) but not in attention | -| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid uses `expf` | prefill needs tens of millions of exponentials per layer. Against `(float)exp((double)x)` over 1.31M points of [-100, 0], every point is within one f32 ulp and 76.1% are bit-identical (device `expf`: 94.0%, no better in ulps), and `exp(0)` is exactly 1. The polynomial is the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a function. The MLP's sigmoid feeds a bf16 narrowing (ulp 2^-8 against `expf`'s ~1e-7), so the bf16 differs only on a tie | -| `w2a8` has a one-ulp tail | the pair-dot carries about 22 bits on integers: 0.1-0.2% of outputs land one bf16 ulp off, `rel_l2` 5.0e-3 at the band, nothing further. The row's text says so, because the law it transcribes is exact integers | -| the fp8 scale folds land in f16, not f32 | the tile is f16, so a scale enters as an f16 multiply at staging, one `v_mul_f16` rounding per staged value. Against the reference's exact dequantise law: `rel_l2` 2.77e-04, half an f16 ulp, 250x finer than an E4M3 code's quantum (2^-4). At a bf16 output the store's ulp (3.9e-3) dominates: 83% of outputs bit-exact, 99.93% within the fold plus one store ulp | -| the bf16 GEMM's long-K tail | each pair is folded into the accumulator with one rounding, so about 0.3% of a long-K output lands one bf16 ulp from the reference's and none further: 99.93% bit-exact at the 512-column case, 100% within two ulps | +| the sampler's `exp` and `log` are `double` calls narrowed once | draws must reproduce: the device's `(float)exp((double)x)` is bit-identical to the host's over the candidate set, where `expf` differs by 1 ulp on a few percent of points. At 1:64 doubles this is the slow path, affordable on the candidate set (1024 exponentials per row) but not in attention | +| attention's `exp` is a degree-8 polynomial; the gated MLP's sigmoid uses `expf` | prefill needs tens of millions of exponentials per layer. Against `(float)exp((double)x)` over a dense grid of [-100, 0], every point is within one f32 ulp and most are bit-identical; the polynomial is the only place an explicit `__fmaf_rn` is allowed, because what must be reproduced is a function. The MLP's sigmoid feeds a bf16 narrowing (ulp 2^-8 against `expf`'s ~1e-7), so the bf16 differs only on a tie | +| `attn_paged`'s split-KV reducer rescales each partial by `exp(m_s - M)` before the sum | every term then arrives as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`, a last-bit difference at f32 (about 2 ulp per term, 1 ulp on the sum) that vanishes under the bf16 store except on rounding boundaries. The row's text states the contract: `splits = 1` is bit-identical to the reference, `splits > 1` is not | -**Proving a plane was written.** Every output plane in a comparison run is pre-filled with the -dtype's NaN (`0x7fc0` for bf16 and f16) and read back whole. A kernel that returns `RAD_OK` -without launching leaves the caller's bytes, and zeros are finite, so only a NaN fill shows the row -ran. A clean case reports `untouched 0` and `nonfinite 0`, no output beyond six ulps of the law the -kernel implements, and a whole-plane `rel_l2` within what the fusion costs (`2 * sqrt(K/2)` output -ulps, with room for the fixture's spread). Two planes (an int8 row-sum padded to a 16-row grid, a -quantiser's per-group statistics) legitimately keep the fill in their padding, because the row -writes only the rows it was given; the report names that padding, and a NaN anywhere else is a -silent no-op. - -Infinities are part of the contract in the sampler and row top-k: a dropped candidate, a -narrowing stage's drop and an unfilled `row_topk` slot are all `-inf`. +The fp8a8 tiled fold (scales applied at staging, the group sub-sum accumulated from raw codes and +scaled once per group in the reference) differs from the reference's law by a relative 2.77e-04 +against a bf16 store that costs 3.9e-3, so it is invisible in the output. ## Testing @@ -464,352 +514,24 @@ rad-kbench --fixture "$RADIANCE_HOME/kbrows.rkb" --kernels libref:libr3d --all-r The first command checks the served checkpoint's own bands against the reference on the container's real weight bytes. The second and third take each case to the M and `q_len` values no -container selects, the edges of each row's constraints where floors and ceilings are exercised. -Rows the checkpoint's graph never uses report `no recorded case of its op`. - -**Checks a tolerance cannot make.** A refactor is proved by the recorded decision lines being -bit-identical between the old and new builds (diffed with the timing column blanked). A change to -an index, a scale plane or a row mapping is proved bit for bit against the same fixture: a fixture -whose scales are statistically alike cannot tell a row-indexing error from rounding (with uniform -random data the amax of 128 samples is concentrated, every block's scale rounds to the same bf16, -and reading group 0's scale for group 7 changes nothing), so paired runs spread their activations -by orders of magnitude one group at a time. The comparison harness carries a `selfcheck` control -that hands the scorer a plane rebuilt under a known misreading and requires a divergent verdict -naming it. - -The gates test a built binary, not the commit: build a clean export of the commit on the target -before trusting the gates for that commit. - -## The fp8a8 GEMM by row count - -The bands this family targets are 42 layers plus a drafter at `group=128 dtype=fp8a8`, band -ceiling M=2048: N=12288 K=2048 x44 (the gated MLP, two halves of 6144), N=2560 K=2048 x44 (qkv), -N=2048 K=6144 x44 (o-proj), N=2048 K=2048 x44, and N=2048 K=10240 x3 (the drafter). Three rows -cover them by row count, with boundaries read from the constraint tables: `gemm_nt_q_fp8a8_m16` -declares `C_LE("M", 16)`, so `gemm_nt_q_fp8a8_tiled` opens at `C_GE("M", 17)`, and -`gemm_nt_q_gated_fp8a8` serves M=1..64 with N even and K % 128 == 0. - -**The m16 row** gives each lane one output element and streams the weight past an activation kept -in registers, with no wave reduction, so a lane's chain is the reference's and the row is -bit-comparable at the store. Above 16 rows the same operands use a 128x128 tile through LDS with -8x8 f32 accumulators per lane. The two ranges are complements, and the m16 row is compared against -the tiled row on the same bytes, where a moved boundary would show. - -**The tiled row folds the scales at staging.** The tile is f16, so both scale streams enter as f16 -multiplies where the codes are staged: the activation's `a_scale[m][g]` per staged row, the -weight's `b_scale[nb][g]` once per chunk (TN 128 is the scale plane's row extent, so a tile is one -scale row, and kKC 32 divides 128, so a chunk sits inside one k-block). The products are -separable, `(a*sa)*(b*sb) = (a*b)*sa*sb`, so the accumulator stays one f32 register. The -reference's law is the group sub-sum accumulated from the raw codes and scaled once per group -(`ref_gemm.h`'s `quant_dot`, the body the m16 and gated rows carry); the fold differs from it by -`rel_l2` 2.77e-04 against a bf16 store that costs 3.9e-3, so it is invisible in the output (see the -divergence table). `|y|` is not a usable denominator, since a sum of 2048 random products is often -near zero; the scale is `S = sqrt(sum (a_k b_k)^2)`, and the fold's floor is 9.8e-4 of it. - -**At the band ceiling** (M=2048, container resident): N=12288 K=2048 28.171 ms (3659 GFLOP/s); -N=2560 K=2048 5.911 ms (3633); N=2048 K=6144 14.699 ms (3506); N=2048 K=2048 4.381 ms (3922); -N=2048 K=10240 29.798 ms (2883). That is 27 to 36% of the part's dense f16 rate. The bytes floor at -163 GB/s is 0.051 to 0.257 ms per band, and 2MNK/(K+N) is about 1900 flops per byte at M=2048, so -prefill is compute-bound and these numbers describe the loop, not memory. - -**A grid-shape cliff.** The tiled kernels run one block per CU at 18.4 to 18.5 us per block at the -column-tile counts the graphs issue (16 and 20); 19 tiles cost 211 us per block (11.4x) and 21 -tiles 385 us (20.9x), deterministic to 0.1%. Every column-tile count the served graphs issue is -even, so no band hits it. The first things to try are a block-index swizzle, then the `nt` -streaming loads. - -**Verifying the crossing.** One `RadArgs`, the device row and libref's host row on the same bytes, -the whole `y` plane compared, pre-filled with `0x7fc0` so an unwritten element is visible, every -other plane poisoned, and 256-byte guards checked after the launch. The run covers every form the -served plan hands the row (rank-1 `a_scale` of `[M]`, the codes as a rank-3 -`[M][ceil(K/128)][128]` plane, the weight as the container the layout hook writes) at the four -served bands and at M = 17, 21, 30, 45, 64, 65, 128 and 258, against a 5e-3 tolerance; the same -band with `b_scale=[scale,zero]` is refused with `E_DTYPE`. The harness has two plugins dlopened, -both row tables resolved the way the engine's loader resolves them, and scores a plane against nine -index laws with a hash beside it. It also covers the collapsed mapped and managed tier -arrangements (the mirror layout, the default, is the served one). The rank-1 `a_scale` binding -matters: a shim passing the wrong row pitch for it reads rows 0 and 1 correctly and everything past -the plane after that, which the row's own geometry test cannot see. - -### The gated MLP row - -`gemm_nt_q_gated_fp8a8` fuses the GEMM, the gate and the output quantiser, so the bf16 `[M, N]` -intermediate is never written, read or allocated. The gate couples column `i` with column `n + i`, -192 waves apart at n = 6144, out of reach of any lane exchange; so each lane computes both products -of its column, walking k ascending with two accumulators over weight rows `i` and `n + i`, the same -traffic the unfused GEMM spends on the two columns. A block is one group of columns by `256/group` -rows, which closes the group's amax inside the block: a wave max folded over the group's waves in -LDS, one scale store, one code per lane. The op is one launch with no scratch, so the row is -concurrent (`rad_kernel_concurrent(i)` is `scratch == nullptr`). Both halves are narrowed to bf16 -before the gate, because the pair it replaces stores and re-reads them; the activation is not -(`gt * sg` is f32 from the narrowed gate, and the product with `up` rounds once, at the store). The -law is libref's `ref_gemm_nt_q_gated`, and its order must be kept. - -The launcher picks the arm by row count. fp8a8 at M <= 8 reads the activation and both weight rows -directly, 16 bytes at a time, decodes them from the block's table and multiplies: no shared memory -between load and dot, no barrier in the k-loop, six loads in flight. M >= 9, and every fp8a16 case, -stage through LDS; at those heights the grid is 48 x M/2 blocks and occupancy feeds the stream. -On the band's stream (24 MiB of codes, resident, loop without the epilogue), staging with the -arithmetic decoder takes 497 us, direct reads with the table 187 us, and the bare loads 139 us. - -Measured on the band (N=12288 K=2048 group=128, codes resident), best / median of nine launches, -staged arithmetic-decode arm against the shipped arms: - -``` -M = 1 987.4 / 1154.9 -> 171.3 / 181.6 us (147 GB/s of codes; the floor for -M = 2 1120.6 / 1196.5 -> 166.2 / 177.1 us 24 MiB at 163 GB/s is 154 us, and -M = 4 1417.3 / 1581.2 -> 221.0 / 229.6 us the same sixteen loads with no -M = 8 1874.0 / 2318.0 -> 403.4 / 412.3 us decode and no dot run in 139 us) -M = 16 2949.3 / 3226.1 -> 1055.0 / 1160.6 us -M = 32 5123.4 / 5405.1 -> 1660.6 / 1705.0 us -M = 64 8395.3 / 9051.0 -> 2786.5 / 2877.3 us -``` - -The M <= 8 threshold is a tunable, chosen for decode (M=1) and draft verify (M <= 8). With the table -decoder in both arms the direct arm takes 402 us against 754 at M=8 and 955 against 1030 at M=16, -so the crossover is above 16; M=9..15 is unmeasured, and a prefill of 9..16 rows pays about 7% for -the staged arm. The load window is for the direct arm only: on the staged arm it costs 32 -registers per lane, a fifth wave per SIMD, and at M=64 it costs more than it saves. - -The row carries no relayout. libref reads the gated `[N, K]` weight row-major; libr4d stores fp8a8 -weights in WMMA fragment order, and the two readings differ by a relative error of about 1.35, so -a row that inherited the fp8 GEMM's `unrelayout` would fail the per-op oracle. The launcher refuses -M > 64 (beyond the bands' ceiling the weight stream is a tiled kernel's problem), N odd, a group -that is not a power of two in [32, 256], `group > n` (the reference would then use n for the -quantiser's group while keeping the weight's K block at the stated width, two grids this kernel -reads as one), `K % group != 0` (a ragged K block reads past the scale plane), `sk > 1` (the -epilogue needs the whole row), and an absent `act`. - -## The paged attention, decode and prefill - -Two rows, chosen by `q_len`: the decode entry, which takes `splits`, and the prefill entry. The -served geometry is n_head 16 over n_head_kv 2 at head_dim 128 (gqa 8), `block_size 16`, a 4096 -context, and an `fp8_e4m3` cache with its descales. The layout is the reference's: -`kv_cache[num_blocks, kv_heads, block_size, 2 * head_dim]`, K then V inside a slot, so a key's row -is a 512-byte pair and both halves are 16-byte aligned at every slot. `block_table[seq, j / -block_size]` names the block holding key j; a negative entry is an unmapped block and hides its -key (the allocator frees a sequence by writing -1, so the kernel keeps the test although the -fixture never sets it). `seqused[s]` is the sequence's total key count including this step's query -rows, so query row *i* of a `len_s`-row step sits at absolute position `seqused[s] - len_s + i`. -One kernel serves decode (q_len 1), speculative verify (q_len 7) and a prefill chunk (q_len 2048). - -**A lane owns one output row, and a wave is the GQA heads of one KV head:** -`h = kh * GQA + (lane & (GQA-1))`, `tok = base + (lane >> lg GQA)` (8 heads over 4 rows at gqa 8), -so every lane of a wave reads the same cache row at the same time. Every cache read is then an LDS -broadcast, one `ds_read_b128` serving the wave, and the paged walk is a per-wave event. 32 rows per -cache read is also the register file's ceiling: a second output row per lane would need 2 x 64 -VGPRs of widened query plus 2 x 128 of f32 accumulator, 384, over the 256 that four waves per SIMD -allow. - -**The walk runs twice.** The reference keeps its scores, but 32 keys x 128 dims of f32 is 512 KiB -per wave against 64 KiB of LDS, so pass two recomputes them, in the same order over the same -operands, bit-identically; the op costs half again what keeping them would. A masked key is -skipped, never scored to -inf, so the denominator has exactly the reference's terms, and a row with -no visible key stores zeros (the reference's `mx == -INFINITY` case). P*V stays f32: folding the -softmax weight into V would read every weight to 11 bits, a ~1e-4 change that survives the bf16 -store on a few percent of outputs. `exp` is the degree-8 polynomial from the divergence table, and -`exp(0)` is exactly 1, the term the row is normalised by. - -**Workgroup width is the effective lever.** A row slot past a sequence's length computes a clamped -duplicate (walk, tile and store all run for it). `pick_waves` picks the narrowest workgroup that -carries the step's `q_len` (one wave up to 32/GQA rows, two up to 64/GQA, four above); prefill -keeps four. Against a fixed four-wave workgroup (medians of 15 per-launch event times): 294.7 vs -158.4 ms at 256 sequences x 7 rows over 4096 keys, 268.0 vs 128.4 ms with 4 splits, 4.33 vs 2.06 ms -at 8 sequences over 2048, 4.27 vs 3.97 ms at one sequence over 4096, prefill unchanged. The kernel -issues about 15% of the SIMD's slots at the band and 3.7% at eight sequences, so the gain is not -explained by arithmetic; the width is therefore chosen at run time. - -**Levers that did not help:** `s_setprio` around the consume leg of the walk (|delta| <= 0.7%); -`R3D_WAVES(2)` to lift the scalar-register ceiling (`sgpr_count` 107 and about 98 SGPRs spilled at -both 4 and 2 waves per SIMD, timings unchanged: the compute-shader scalar budget is not set by -waves per SIMD the way the VGPR budget is); `__noinline__` on the staging leg (spills 98 -> 72, a -160-byte private frame, timings unchanged); a two-stage pipeline (+7% prefill, +7% decode, -5% -split-KV). - -**Split-KV is a rescale.** A slice accumulates its own `(acc[128], sum, max)` into scratch and the -reducer combines them before the single narrowing, rescaling each partial by `exp(m_s - M)`. Every -term then arrives as `exp(s - m_s) * exp(m_s - M)` where the reference has `exp(s - M)`, a last-bit -difference at f32 (about 2 ulp per term, 1 ulp on the sum) that vanishes under the bf16 store -except on rounding boundaries. The row's text states the contract: `splits = 1` is bit-identical to -the reference, `splits > 1` is not. `splits` is a maximum, resolved per sequence from its own -`seqused`: `nslice = ceil(nblk / ceil(nblk / splits))` with `nblk` the sequence's block count, so a -short sequence uses fewer slices and needs no per-sequence legality check, and the reducer -recomputes `nslice` from the same two numbers, so a partial needs no header. - -The split curve on the served shape (64 sequences, 8 KV heads, fp8 cache, ms per launch at splits -1/2/4/8/16/32/64): ctx 1024, 8.17 / 5.51 / 9.29 / 1.50 / 2.54 / 0.39 / 0.23; ctx 4096, 35.71 / -20.92 / 11.41 / 5.79 / 2.67 / 1.44 / 2.60. Each workgroup walks `ceil(nblk / splits)` blocks with -`nblk = ceil(jcap/16)`, so the total keys read are `jcap` at every split count, and the cost is -slices times per-slice work plus the reduce. The clamp `splits <= ceil(jcap/block_size)` is a no-op -at the served shape (`ceil(1024/16)` is 64) and applies only where splits exceed `nblk`; a grid -built from the requested count then has slices with no blocks, which costs waves but stays -correct. - -**Bounds.** `jcap = min(max_ctx, cols * block_size)`: the block table is the window the kernel may -read (see [the request-time rules](#request-time-rules-a-plans-vocabulary-is-not-its-contents) for -`cache_blocks`, `bt_cols` and the last-index check). In the tile walk the descriptor's length gives -the tile count and its span the store bound, so a sequence with `cu[0] > 0` stores every row the -grid covers. - -**A padding row must not write a partial.** A padding row's `row` clamps to a real row, so the -split path tests row validity before the partial store. Without it, two lanes write the same -`(row, h, slice)` record inside the declared arena, their 132-float records interleave, and the -reducer rescales a full slice by the wrong maximum, producing sums thousands of times too small. It -needs `q_len < 32/gqa` (at gqa 8, q_len 7 fills a wave and there are no padding rows), and it is a -schedule, not a sample: it fails identically at every seed. The slots a padding row leaves unwritten -are exactly those the reduce does not read; its index runs over real rows only. - -**Verification** is a paired run with libref and libr3d dlopened in one process, both called with -the same `RadArgs`, absent optional operands passed as a descriptor with null `data` (never as a -shorter `n_t`), with the fp8 cache form in the same run. It covers the served shapes, the -rectangular matrix, deep contexts 512..4096, narrow block tables (`bt cols` 1/2/3/4/8, so `jcap` -16/32/48/64/128 under a ctx of 512), empty sequences (`cu = [0,0,5,5,17]`), split counts 1 and 4, -windows 1/3/17/64/512, causal and non-causal. - -**Launch tracing.** A served decode step is played: the recorded pass re-issues queue packets and -never calls the plugin's shim, so a print in the shim never sees played steps. Under -`RAD_R3D_TRACE` only, `attn_kernel` writes one record per launch: its launch ordinal, the row's -`ctx` from `seqused`, the whole block-id row of the table, the six operand addresses, and FNV-1a -folds of the query row and of the first and last block it walks. Records go to a plugin-owned -`__device__` ring of 256 fixed 216-byte slots that the shim drains to stderr on a traced call; the -budget is a device global the shim writes, decremented with `atomicSub`, the counter advanced with -`atomicAdd`. A played step's record is emitted one step late, and the record's own `L` and `ctx` -restore the order. In a served process the plugin is dlopened, and the runtime's symbol stub for a -plugin-owned `__device__` global is not the address the kernel's module writes, so the ring cannot -be armed there; the served channel is a `hipMalloc`'d record slot passed as a kernel argument, -drained at the launch and armed by the same flag. With the flag unset the kernel pays one scalar -load and a not-taken branch on one thread, and the launch one cached flag read. With it set, a -traced call pays one device synchronize (the descriptor probe reads the table on the host) and one -stream synchronize (the record drain), and the first traced call allocates the record slot; that is -why the flag is a tracing switch and not a mode. - -Device `printf` cannot be used instead: a kernel that calls it takes an extra implicit argument, -`hidden_hostcall_buffer`, which the AQL backend does not provide, so the engine cannot dispatch it -(the fixture refuses the row with `refused a geometry its constraints accept: device error`), while -the same kernel launched with hipLaunch from a standalone harness prints normally. Only a gate that -dispatches through the engine, here the recorded fixture, sees such dispatch-side problems. - -## The sampler spine - -Thirteen rows: five pre-filters, `sample_topk` feeding `sample_pick`, and the narrowing stages -between them. `abi/rad_sample.h` is the wire format, and the central design choice: every scalar -(`temp`, `top_k`, `top_p`, `min_p`, `typical_p`, the `xtc_*` pair, `seed`, `pos`, the flags, the -history window) is data, one 96-byte row per sampled position, because parameters are geometry, -geometry is frozen at declare, and two rows of one batch with different `top_p` must resolve to one -kernel. `param_rows` is that check, and it is the dtype check libref states: the plane is 32-bit -words, and a 16-bit view passes a byte-count test and then misreads every row. - -**Draws must reproduce, so summation order is transcribed.** Every max is a strict `>`, which also -keeps NaN out: libref's `if (v > mx) mx = v` from -infinity never adopts a NaN, and the butterfly -merges with the same comparison. The reference's sums run over the candidates in index order, and -its CDF scan accumulates in index order, so the exponentials are computed in parallel (each an -independent value) and the accumulation is serial on one lane, in index order. - -**The draw is a function of the ABI, not of a library.** splitmix64 over -`seed * 0x9E3779B97F4A7C15 + pos`, the top 24 bits over 2^24, in integer arithmetic so device and -host agree, with independent streams per purpose (the pick XORs `RAD_SAMPLE_KEY_PICK`, XTC's coin -`RAD_SAMPLE_KEY_XTC`). `ref_exp`/`ref_log` are `(float)std::exp((double)x)` and -`(float)std::log((double)x)`, transcribed as double calls rounded once (see the divergence table); -a `u < cum` comparison on an ulp boundary changes the drawn token, which fails the fixture even -when the distribution is right. The widest softmax here is the candidate set, 1024 exponentials per -row at about half a millisecond per step, where the 1:64 f64 rate is affordable; attention, at 17M -exponentials per layer, uses the polynomial. - -**The top-R is one scan.** `topk_next` takes, on each of R scans, the largest value strictly below -the last pick, ties to the lower column; as a whole that is a sort by (-value, +column), and the -rule `v == *pv && i <= *pi` is "the next one within a run of equal values". One pass keeping the -best R in that order produces the same R pairs in the same order with the same tie-breaks. At the -band's row (M=1792, N=130560, R=16, bf16) the reference scans the row sixteen times (7.0 GB); this -scans it once (468 MB), in 22.0 ms bf16 and 22.4 ms f32. The pass is bound by accepted inserts -(about 55 sifts per lane at 510 elements per lane), not by memory; filtering against a block-wide -threshold instead of each lane's own tail would cut that to about 5 sifts and approach the 2 ms -bandwidth floor. Each lane keeps a 64-deep list and a merge keeps the best 64 of two; testing an -element against the lane's 64th best is one comparison for almost every element (about 12% of a -row clears it at 510 elements per lane). 64 covers R=16, the selftest's 64-wide set and every -practical `top_k`; above it `r3d_sample_topk` and `r3d_row_topk` take `ceil(k/64)` passes, the -reference's own chain, so the result is the same at any k. - -**The candidate plane is the contract.** A row's set is its `top_k` largest logits, descending, -ties to the lower token id, with `cand_idx` -1 and `cand_val` -infinity for a hole. The width is -the buffer's declare-time bound: 1024 candidates is the engine's declared width (two f32 arrays of -it are 8 KiB of the 64 KiB a workgroup has), and the row's `top_k` narrows within it, so `top_k` 40 -in a 1024-wide buffer is 40 candidates and 984 holes. The whole buffer is written every step, -because later stages test for holes. A greedy row takes no candidates: its token is -`sample_argmax`'s and the pick must not overwrite it. `cand_val` carries logits, not probabilities: -every narrowing stage takes its own softmax over the set, so the stages compose in any order and a -pre-filter can be moved without re-deriving anything. - -**The step's row count comes from the operand** (see -[the request-time rules](#request-time-rules-a-plans-vocabulary-is-not-its-contents)). A candidate -stage that used the band key's `M` would ask one row of candidates to be 256 rows tall and refuse -every logprobs request (`refused op sample_topp at M=1 [band M<=256] geometry {n_cand=1024 -M=256}`). - -**Verification** is the fixture rather than a paired run: the selftest builds each row's buffers -from its own `opd_shape`, runs it and checks the plane whole in a child process, and kbench drives -the `sample_*` bands against libref on the served checkpoint's fixture. What the fixture cannot -check is the seeded draw against a recording, over the parameter rows a real request sends (see -[What is not here yet](#what-is-not-here-yet)). - -## Measuring - -**State the floor beside the number.** 66.8 MB of codes at a part's 22 GB/s is a 3.0 ms floor; -255 MiB at 163 GB/s is 1.64 ms; a 73.1 MB operand is a 0.449 ms read. Against those, 13.6 ms per -token or 24.151 ms at M=64 describe the loop, not memory. - -**State the placement of every operand on every timing line.** On a part whose memory cannot hold -the head it is worth an order of magnitude: at M=1, one kernel, the same head in VRAM is 13.6 ms -per token; on the mapped tier (pinned host bytes read over the host link by 8-byte strided loads) -643 ms; managed and left alone 2071 ms at 122 MB/s, because managed pages do not migrate for a -read-mostly device access and the kernel faults page by page. A layout hook makes the mapped -placement legal, not fast. Benchmarks state which placement produced which number and time after a -prefetch. A container operand must be host-readable (the shim reads its header on the host), so it -is pinned or managed, never plain `malloc`, which faults. Allocation history matters too: the same -shape in the same binary measures 5.911 ms as a process's first case and 85.7 ms after a 24 MiB -managed container was allocated and freed, because the slow run reads its weight over the host -link. The row's number is the VRAM one, because the engine moves weights to VRAM at load. - -**`vgpr_spill_count` is a gate:** every kernel must report zero VGPR spills. Per-group partials -scaled into the accumulator cost 64 more accumulators on an arm already at 237 VGPRs, and a runtime -index into a register array spills the array to private memory; both need a rewrite, not a tunable. -A scalar spill in a compute-shader wavefront is a slow path, not a stall (see the attention -measurements), so SGPR spills are reported, not gated. - -**Per-op profile times sum to more than the token.** `--profile-ops` restores the synchronisations -that the engine's overlap removes, as the engine's startup diagnostics state -([`core/diag/checks.cpp`](../core/diag/checks.cpp)). A per-op table taken under that flag ranks the -work and does not price it; the token rate is the price. Quote a served run's shape with its -numbers (context length, prompt lengths), because a ranking is a property of the shape, not the -model. +other harness reaches (the prefill and decode bands on the same bytes) and compare the whole +planes. The gates test a built binary, not the commit: build a clean export of the commit on the +target before trusting the gates for that commit. ## Notes on the kernels Three properties are assumed throughout and not restated per kernel: **wave32 with a 1024-entry VGPR file per SIMD**, so every lane map has a lane owning whole dwords and every budget is computed against 1024; **64 KiB of LDS per workgroup**, which sets the candidate kernels' `n_cand <= 1024` -and the tile sizes; and **the dot2 path**, which is why the tile is a dot loop over LDS with an -8-element XOR swizzle, shared by every tiled row in [`r3d_tiling.h`](r3d_tiling.h). - -**The 2-bit grid's tiled staging moves 8x the bytes it uses.** A staged chunk of 8 bytes against a -row pitch of 512 at `kKC` 32 gives 24.151 ms at M=64, N=130560, K=2048 against a 0.449 ms read -floor, 3.7 GB/s useful. The lever is a wider k-chunk (64 codes = 16 bytes, paid for in LDS); more -loads in flight moved it by 0.6%. - -**The head is the largest read in a decode step,** and the sampler reads f32, so the store is -typed, not narrowed, and a 2048-row prefill band writes 1.07 GB. bf16 head: 3.29 ms per token at -M=1 (163 GB/s), 0.507 ms at M=16 (the head read once for sixteen rows), 269 ms at 2048 rows (4067 -GFLOP/s). E4M3 head with a bf16 scale per 128x128 block, read as its two container planes: 13.6 ms -per token at M=1, 8x above the 1.64 ms floor. The table decoder gives 2.70x where the decoder binds -(M=8: 2.500 -> 0.924 ms per token), nothing at prefill, and nothing at M=1. The likely limit at -M=1 is load width (eight codes per lane through an 8-byte load, where the bf16 arm loads sixteen -bytes per lane), so the next step there is a 16-byte code load. +and the tile sizes; and **the dot2 tile**, shared by the tiled quantised rows in +[`r3d_tiling.h`](r3d_tiling.h) — a dot loop over LDS with an 8-element XOR swizzle. The wave-matrix +rows carry their own tiling (the 16x128 block tile, above). **Clear the HIP error flag before a launch check.** `hipGetLastError()` reports the first error -raised since it was last cleared, so a check that does not clear first attributes to this launch -whatever the process raised before it (in a served process, the previous op; in a comparison run, -its own setup). The symptom is a whole timing mode returning the device code on every geometry of -every row, disappearing under `HIP_LAUNCH_BLOCKING=1` (a synchronous launch clears a pending -asynchronous error before the check). Clear the flag after the arguments are staged and before the +since it was last cleared, so a check that does not clear first attributes to this launch whatever +the process raised before it. The symptom is a timing mode returning the device code on every +geometry of every row, disappearing under `HIP_LAUNCH_BLOCKING=1` (a synchronous launch clears a +pending asynchronous error first). Clear the flag after the arguments are staged and before the launch, read it straight back, and on a refusal name the error and print the grid, block, waves, splits and width the launcher chose. @@ -820,57 +542,26 @@ ABI's own answer. ## What is not here yet -**The 2-bit grid's staging width.** The packed-code tile at prefill heights moves 8x the bytes it -uses at `kKC` 32; the fix is a 64-code chunk (16 bytes per lane) paid for in LDS, which is the -whole gap between 24.151 ms and a 0.449 ms floor at M=64, N=130560, K=2048. +**The seeded draw against a recording.** The fixture checks the plane whole, not the draw against a +recorded seed, over the parameter rows a real request sends. The sampler's draw is reproducible by +construction (the reference's order, the reference's `exp`/`log`), but a recording is the proof, +and there is no recording harness for the plugin's parameter rows. -**A 16-byte code load for a one-row E4M3 head.** The decode arm loads eight codes per lane through -an 8-byte load and runs 8x above its floor at M=1; the table decoder is not the lever there. +**`w4a8` as a row.** `r3d_rad_moe_gemm_w4a8` is a WIP launcher (the i32 wave-matrix core, the +gather and the run structure are verified bit-exact against a CPU reference); the other weight +forms (w4nl64a8h / w4nl32a8h / w5nl64a8h, whose nibbles decode through a magnitude table and a +per-64/32 E4M3 scale), the prefill run map and the SK/UW/RS optimisations are outstanding, per its +kernel header. -**A gated MLP pass over rows and column groups.** Past M=64 the fused row refuses and the work is -four ops over a bf16 `[M, N]` tensor (two GEMMs, the gate, the quantiser). At M=64, the ceiling 47 -of the 48 bands declare, the weight read is the limit; a pass that amortises the weight read across -rows and column groups is what is missing. - -**The gated row's arm threshold.** The crossover between the direct and staged arms lies above 16 -rows and M=9..15 is unmeasured; measuring it would move the threshold, not the kernel. - -**`gemm_nt_q_bias` has no row.** `gemm_nt_q` has no bias operand; bias is its own op in the -registry ("gemm_nt_q with a per-column bias"), and this library declares no row for it. Every band -carrying a bias therefore resolves to the reference's host row: correct and slow, with no `E` line -in the coverage and no profile entry, because nothing refused and the op never reaches a device. A -checkpoint whose bias tensors have count 0 (no planes, no bytes) carries no bias band, by the rule -that an optional operand with no bytes is absent; `rad-info -v | grep -i bias` shows -whether a model's bias tensors have planes. The row would be a bias load in the tiled rows' -epilogue plus a declared schema. - -**Sliding window over a partial last tile diverges.** With `window` from 2 to 15 over a query plane -whose last tile is not full, the attention row diverges from the reference (for example 17 rows at -ctx 33 with w = 3: `rel_l2` 1.196e+00, status 0 from both rows, no non-finite values). Full -attention (`window = 0`) agrees, and served plans use a 2048 window over 16-wide blocks, so no -served band reaches it. The fix belongs in the last tile's mask, not the window's clamp. - -**`sample_merge_topk`**, the cross-rank candidate merge: under a split vocabulary it holds -`world_size * n_cand` gathered pairs, and there is no row for it. - -**A seeded-draw comparison for the spine.** kbench grades the `sample_*` bands against the -reference on the fixture, which covers the arithmetic; nothing yet compares the drawn token against -a captured sequence, over the parameter rows a request actually sends. - -**int8 x int8.** The constraint table is written (`i8a8`, group 128, M <= 16, K % 128) and -`quant_act_i8g` produces the row-major activation it reads; the kernel has not landed, so the row -is not in the table. - -**Chunked logits.** The head's f32 plane is written whole (1.07 GB at a 2048-row prefill band); -nothing emits it in chunks for the sampler to consume in passes. +**A chunked logits path.** The head is the largest read in a decode step, and the sampler reads +f32, so the store is typed, not narrowed, and a 2048-row prefill band writes 1.07 GB. Nothing +emits it in chunks for the sampler to consume in passes. **A sub-byte zero plane.** `w2a8` reads a zero point one byte at a time and refuses a zero stored as U2/U4/U5 by name; the bit-extract path would be the same `rad_load_bits` the codes use. -**Speculation that pays.** The draft head is served end to end (its bands by the 2-bit grid, its +**A draft path that pays.** The draft head is served end to end (its bands by the 2-bit grid, its accept step by `dflash_select`) and the accepted text is identical. The target's head read -amortises over the draft block (5x cheaper per token at 8 rows than at 1 on the same kernel), so -the drafter's own steps have to pay for themselves, and on a 16-CU part they do not (87.6 -> 94.4 -ms per token on a 5-token prompt, 91.6 -> 187.1 on a 16-token chat band with 7 drafts). The -engine switches the drafter off for a plugin whose rows measured a gain without it; what is missing -is a draft path that costs less than the head read it saves. +amortises over the draft block, so the drafter's own steps have to pay for themselves, and on the +development part they do not; what is missing is a draft path that costs less than the head read it +saves. diff --git a/libr3d/r3d.h b/libr3d/r3d.h index 1228d9d9..45111fb1 100644 --- a/libr3d/r3d.h +++ b/libr3d/r3d.h @@ -237,10 +237,11 @@ int r3d_gemm_nt_q_fp8_tiled(long a, long a_scale, long b_codes, long b_scale, lo * takes the m16 launcher, M >= 17 the tiled one. */ int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N, - int K, int group, int a_ld, int y_ld, long long e8_row, long stream); + int K, int group, int a_ld, int y_ld, long long e8_row, long stream, + int alu); int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N, int K, int group, int a_ld, long long b_row, int as_ld, - long long e8_row, int y_ld, int nt, long stream); + long long e8_row, int y_ld, int nt, long stream, int alu); /* ================================================================== r3d_gemm_inta8.hip * diff --git a/libr3d/r3d_args.h b/libr3d/r3d_args.h index 0a26eb4b..09c230e1 100644 --- a/libr3d/r3d_args.h +++ b/libr3d/r3d_args.h @@ -278,7 +278,15 @@ enum { * so no fixed default is legal at every shape, and an illegal default would make an untuned install * fail. The GEMM unit resolves the sentinel. */ -struct R3dGemmCfg { int wv, sk, kb, nt; }; /* waves a block, split-K, K slab, non-temporal loads */ +/* waves a block, split-K, K slab, non-temporal loads, and the implementation arm (0 = the dot2 + * pairs, 1 = the 16x16x16 wave matrix) */ +struct R3dGemmCfg { int wv, sk, kb, nt, impl; }; +struct R3dMoeCfg { int mrows; int vgpr; int acc; }; +/* the grouped E4M3 GEMM's point: the kernel arm (0 = the 16x16 tile, 1 = the same tile with the + * ALU decode, 2 = the 16x128 block) and the block's register budget and accumulator */ +struct R3dMoeQCfg { int impl, vgpr, acc; }; +/* the block's row count (16, 32 or 64); the per-wave register budget (128 = the 8-wave cap, 512 + * natural); the accumulator's precision (0 = f32, 1 = the half-precision WMMA tile) */ struct R3dSplitCfg { int splits; }; /* split-KV segments; 0 is the kernel's own law */ struct R3dTopkCfg { int rc, nch; }; /* candidates a chunk keeps, chunk width in columns */ @@ -290,8 +298,13 @@ extern "C" { * untuned install runs. They cannot fail: the loader refuses a plugin whose default is not one of * the axis's values. */ void r3d_cfg_gemm (const RadArgs*, struct R3dGemmCfg*); +void r3d_cfg_moe (const RadArgs*, struct R3dMoeCfg*); +void r3d_cfg_moe_q(const RadArgs*, struct R3dMoeQCfg*); void r3d_cfg_split(const RadArgs*, struct R3dSplitCfg*); void r3d_cfg_topk (const RadArgs*, struct R3dTopkCfg*); +/* the 16x128 block's launcher with the register budget and accumulator passed through (the e4m3 + * row's impl 2 arm reads them from its own tune, not the bf16 row's) */ +int r3d_moe_gemm_fp8_f32scale_run(const RadArgs*, RadStream, int vgpr, int acc); } /* extern "C" */ diff --git a/libr3d/r3d_attn_paged_h128.hip b/libr3d/r3d_attn_paged_h128.hip index 1663bab5..8e3b5753 100644 --- a/libr3d/r3d_attn_paged_h128.hip +++ b/libr3d/r3d_attn_paged_h128.hip @@ -537,8 +537,9 @@ __device__ __forceinline__ long long slot_k_off(const Args& A, int blk, int kh, * the table row by the columns the walk can name, ceil(jcap / block_size) with * jcap = min(ctx, bt_cols * block_size), which the shim proved the table * covers; the row is `M.s * bt_rs` with `M.s` a clamped sequence index. - * the cache by block ids the table names; the shim requires every index the walk can - * reach to be inside the cache plane (`0 <= id < num_blocks`, dense strides). + * the cache by block ids the table names; the shim proves the table's strides and that + * its rows cover the walk, but the ids themselves are device data -- 0 <= id < + * num_blocks is the caller's contract, shared with the reference. * The fold reads kv-head 0's slot-0 K row at the `stage()` offset, kHeadDim * elements (256 bytes bf16, 128 fp8), inside a slot's 2*kHeadDim. A negative * id (an unmapped block, printed -1) folds to 0 and is not dereferenced. */ @@ -1499,7 +1500,9 @@ int attn_shim(const RadArgs* a, RadStream s, bool decode) const int block_size = (int)r3d_geti_or(a, "block_size", r3d_dim(KV, 2)); if (block_size != kBlock) return R3D_NO(RAD_E_SHAPE); if (r3d_dim(KV, 1) != kv_heads) return R3D_NO(RAD_E_SHAPE); - if (r3d_dim(KV, 3) < 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE); + /* The slot stride is hardcoded to 2 * kHeadDim in fill() (K then V in one slot), so a + * wider-last-dim cache would be read at the wrong stride: exact, not a lower bound. */ + if (r3d_dim(KV, 3) != 2 * kHeadDim) return R3D_NO(RAD_E_SHAPE); const long long nb = r3d_dim(KV, 0); const int max_ctx = (int)(nb * block_size); const int max_blocks = (int)((max_ctx + block_size - 1) / block_size); diff --git a/libr3d/r3d_common.h b/libr3d/r3d_common.h index 5616381e..b1c47dc2 100644 --- a/libr3d/r3d_common.h +++ b/libr3d/r3d_common.h @@ -220,6 +220,36 @@ __device__ __forceinline__ float block_sum(float v, float* lds) { __device__ __forceinline__ void sched_barrier() { __builtin_amdgcn_sched_barrier(0); } __device__ __forceinline__ void group_barrier() { __syncthreads(); } +/* --- WMMA fragment types and wrappers (shared by every wave-matrix GEMM). --- + * + * The fragment types: v16half (f16 codes), v16short (bf16 codes, the truncated-f32 bit pattern), + * v4int (int8 codes), and the v8float / v8int accumulators. The wrappers are thin around the gfx11 + * wave-matrix builtins; w32 is the only width gfx11 exposes. Shared so a kernel never re-defines + * the fragment types or re-wraps the builtin. */ +using v16half = _Float16 [[clang::ext_vector_type(16)]]; +using v16short = short [[clang::ext_vector_type(16)]]; +using v8float = float [[clang::ext_vector_type(8)]]; +using v4int = int [[clang::ext_vector_type(4)]]; +using v8int = int [[clang::ext_vector_type(8)]]; + +__device__ __forceinline__ v8float wmma_f16(const v16half& a, const v16half& b, const v8float& c) +{ return __builtin_amdgcn_wmma_f32_16x16x16_f16_w32(a, b, c); } +__device__ __forceinline__ v8float wmma_bf16(const v16short& a, const v16short& b, const v8float& c) +{ return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); } +__device__ __forceinline__ v8int wmma_i8(const v4int& a, const v4int& b, const v8int& c) +{ return __builtin_amdgcn_wmma_i32_16x16x16_iu8_w32(true, a, true, b, c, 0); } + +/* The half-precision-accumulate builtins. The accumulator is a 16-element vector (8 VGPRs x 2); + * `opsel` (a compile-time constant) selects which half holds the 8 live elements (false = the + * even indices 0,2,..,14, true = the odd). The non-selected half is untouched, so an epilogue + * that reads all 16 sees stale values in the dead half -- read only the selected half. */ +template +__device__ __forceinline__ v16half wmma_f16acc(const v16half& a, const v16half& b, const v16half& c) +{ return __builtin_amdgcn_wmma_f16_16x16x16_f16_w32(a, b, c, OSEL); } +template +__device__ __forceinline__ v16short wmma_bf16acc(const v16short& a, const v16short& b, const v16short& c) +{ return __builtin_amdgcn_wmma_bf16_16x16x16_bf16_w32(a, b, c, OSEL); } + /* ================================================================== the geometry constants * * A gfx11 GPU's wave slots: a CU has 4 SIMDs and a SIMD holds 16 wave32s, so 64 slots a CU. HIP's diff --git a/libr3d/r3d_expert_scale_bf16.hip b/libr3d/r3d_expert_scale_bf16.hip new file mode 100644 index 00000000..219e3545 --- /dev/null +++ b/libr3d/r3d_expert_scale_bf16.hip @@ -0,0 +1,77 @@ +/* r3d_expert_scale_bf16.hip -- expert_scale: each routing weight times its expert's own scale, + * in place. + * + * The router renormalises its top-k, then multiplies each weight by its expert's per-expert + * scale. Unfused that is two launches per MoE layer (an embed lookup of the [n_expert, 1] scale + * table by expert id, then a mul), each a few dozen elements at decode. Fused: + * + * ew[t, k] = bf16( ew[t, k] * scale[ids[t, k]] ) + * + * Bit-identical to the pair: one f32 product of two bf16 values, rounded once to nearest even. + * An id outside the table reads a zero scale, so the product's sign matches too. One thread per + * element; no cross-lane traffic, no wmma. + */ +#include + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" + +namespace { + +__global__ __launch_bounds__(256) void escale_kernel(const int32_t* __restrict__ ids, long long ids_ld, + const unsigned short* __restrict__ sc, + unsigned short* __restrict__ ew, long long ew_ld, + long long rows, int k, int n_expert) +{ + const long long e = (long long)blockIdx.x * 256 + threadIdx.x; + if (e >= rows * k) return; + const long long r = e / k; + const int c = (int)(e - r * k); + const int id = ids[r * ids_ld + c]; + const float s = (id >= 0 && id < n_expert) ? bf16_to_f32(sc[id]) : 0.0f; + uint16_t* w = (uint16_t*)(ew + r * ew_ld + c); + *w = (uint16_t)f32_to_bf16(bf16_to_f32(*w) * s); +} + +// [rows, k] with a dense last axis: its rows and row pitch, or false. +static bool rows_k(const RadTensor* t, int dt, long long k, long long* rows, long long* ld) +{ + if (!t || t->dtype != dt || t->rank < 1) return false; + if (t->shape[t->rank - 1] != k || t->stride[t->rank - 1] != 1) return false; + *rows = 1; + for (int i = 0; i + 1 < t->rank; ++i) *rows *= t->shape[i]; + *ld = r3d_row_pitch(t); + return *ld >= k || *rows <= 1; +} + +} // namespace + +extern "C" { + +/* operands: ids, w_e (the [n_expert] scale table), ew (inout) */ +int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const long long k = r3d_geti_or(a, "top_k", 0), ne = r3d_geti_or(a, "n_expert", 0); + if (k <= 0 || k > 64 || ne <= 0 || ne > (1LL << 20)) return R3D_NO(RAD_E_SHAPE); + const RadTensor* I = r3d_opt(a, 0), *S = r3d_opt(a, 1), *W = r3d_opt(a, 2); + if (!r3d_p(I) || !r3d_p(S) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL); + if (S->dtype != RAD_BF16 || r3d_numel(S) < ne) return R3D_NO(RAD_E_DTYPE); + long long ri = 0, li = 0, rw = 0, lw = 0; + if (!rows_k(I, RAD_I32, k, &ri, &li) || !rows_k(W, RAD_BF16, k, &rw, &lw)) + return R3D_NO(RAD_E_SHAPE); + const long long M = rw; + if (M <= 0) return 0; + if (ri < M || M * k > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + const unsigned blocks = (unsigned)((M * k + 255) / 256); + R3D_KLAUNCH(escale_kernel, dim3(blocks), dim3(256), (hipStream_t)s, + (const int32_t*)r3d_p(I), li, (const unsigned short*)r3d_p(S), + (unsigned short*)r3d_wp(W), lw, M, (int)k, (int)ne); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_fp8_dequant.h b/libr3d/r3d_fp8_dequant.h index 45f32928..ab88666f 100644 --- a/libr3d/r3d_fp8_dequant.h +++ b/libr3d/r3d_fp8_dequant.h @@ -65,4 +65,96 @@ __device__ __forceinline__ uint16_t r3d_e4m3_ld(const uint16_t* tbl, uint8_t cod return tbl[code]; } +/* --- The pure-ALU E4M3 -> f16 decode (no LDS table). --- + * + * Two E4M3 bytes (a halfword) -> two f16 (a half2 pair, [hi:lo]). E4M3 [s][e:4][m:3] -> f16 + * [s][e:4 + 8 bias][m:3][0:7], so f16 = (x<<7) + ((x&0x80)<<7) + 0x2000 per byte. Addition carries + * the +8 bias when bit 13 is already set (E4M3 exp >= 8); OR would drop it. Denormals/zero map to + * tiny f16 (the fold's 2^-11 floor dwarfs the difference from exact zero). + * + * Shared by the fp8a8_tiled, moe_gemm_q, and mxfp4a8 kernels as the ALU=1 variant; the ALU=0 + * variant is the table above. The two rows per op let the tune pick the faster per geometry. */ +__device__ __forceinline__ uint32_t r3d_e4m3x2_to_f16x2_alu(const uint32_t pair) +{ + const uint32_t lo = ((pair & 0xffu) << 7) + ((pair & 0x80u) << 7) + 0x2000u; + const uint32_t hi = (((pair >> 8) & 0xffu) << 7) + (((pair >> 8) & 0x80u) << 7) + 0x2000u; + return lo | (hi << 16); +} + +/* Eight codes (two dwords) as four f16 pairs, pure ALU (no table). */ +__device__ __forceinline__ void r3d_e4m3x8_to_f16x8_alu(const uint2 c, uint32_t* w) +{ + w[0] = r3d_e4m3x2_to_f16x2_alu(c.x & 0xffffu); + w[1] = r3d_e4m3x2_to_f16x2_alu(c.x >> 16); + w[2] = r3d_e4m3x2_to_f16x2_alu(c.y & 0xffffu); + w[3] = r3d_e4m3x2_to_f16x2_alu(c.y >> 16); +} + +/* --- The ALU-branching decode: one call site per kernel, the branch lives here. --- + * + * ALU=1: the per-byte formula above (no LDS table). ALU=0: the 256-entry table (tbl). The two + * forms are bit-identical for normal-range E4M3 codes; denormals/zero differ by a tiny f16 the + * scale fold's 2^-11 floor dwarfs. Kernels keep an `ALU` template param and call these; they do + * not branch on ALU themselves, so a new decode form is one change here, not per kernel. */ + +/* Eight codes (two dwords) as four f16 pairs. */ +template +__device__ __forceinline__ void r3d_e4m3x8_decode(const uint16_t* tbl, const uint2 c, uint32_t* w) +{ + if (ALU) r3d_e4m3x8_to_f16x8_alu(c, w); + else r3d_e4m3x8_ld(tbl, c, w); +} + +/* Four codes (one dword) as two f16 pairs. */ +template +__device__ __forceinline__ void r3d_e4m3x4_decode(const uint16_t* tbl, const uint32_t d, + uint32_t* o) +{ + if (ALU) { + o[0] = r3d_e4m3x2_to_f16x2_alu(d & 0xffffu); + o[1] = r3d_e4m3x2_to_f16x2_alu(d >> 16); + } else { + o[0] = r3d_e4m3x2_ld(tbl, d & 0xffffu); + o[1] = r3d_e4m3x2_ld(tbl, d >> 16); + } +} + +/* Sixteen codes (four dwords) as eight f16 pairs. */ +template +__device__ __forceinline__ void r3d_e4m3x16_decode(const uint16_t* tbl, const uint32_t d[4], + uint32_t* w) +{ + r3d_e4m3x8_decode(tbl, uint2{ d[0], d[1] }, w); + r3d_e4m3x8_decode(tbl, uint2{ d[2], d[3] }, w + 4); +} + +/* --- Shared scale-fold and code-load helpers (the quantised GEMM family). --- */ + +/* code * scale, in f16 arithmetic: one v_mul_f16 a half, round to nearest, subnormals kept. Not + * f16x2_pack, which truncates. Shared by the fp8a8 and mxfp4a8 tiles. */ +__device__ __forceinline__ uint32_t r3d_fold_pair(uint32_t w, float sc) +{ + const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); + const _Float16 a = __builtin_bit_cast(_Float16, lo16); + const _Float16 b = __builtin_bit_cast(_Float16, hi16); + const _Float16 s = (_Float16)sc; + const _Float16 rl = a * s, rh = b * s; + return (uint32_t)__builtin_bit_cast(uint16_t, rl) | + ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); +} + +/* Eight codes (8 bytes) as a uint2, a nontemporal load when NT, a memcpy otherwise. Shared by the + * fp8a8, mxfp4a8, and vocab tiles. */ +template +__device__ __forceinline__ uint2 r3d_loadc8(const uint8_t* p) +{ + typedef uint32_t __attribute__((ext_vector_type(2))) u8v; + u8v v; + if (NT) v = __builtin_nontemporal_load((const u8v*)p); + else __builtin_memcpy(&v, p, 8); + uint2 r; + __builtin_memcpy(&r, &v, 8); + return r; +} + #endif /* R3D_FP8_DEQUANT_H */ diff --git a/libr3d/r3d_fwht.h b/libr3d/r3d_fwht.h new file mode 100644 index 00000000..eb469ad8 --- /dev/null +++ b/libr3d/r3d_fwht.h @@ -0,0 +1,55 @@ +/* r3d_fwht.h -- a wave-local fast Walsh-Hadamard transform in registers, no LDS, no barrier. + * + * One wave holds a HAD-wide block, VPL = HAD/32 contiguous values per lane, so lane l holds + * indices l*VPL .. l*VPL+VPL-1. A butterfly at stride h pairs index i with i+h: + * + * h < VPL both indices in the same lane -- plain register arithmetic + * h >= VPL the partner is lane l + h/VPL -- one lane exchange with mask h/VPL + * + * HAD/VPL is always 32, so the cross-lane masks are 1, 2, 4, 8, 16 at any HAD: five exchanges per + * register and no barrier. The lane holding the low index keeps (v + partner), the high one + * (partner - v). The caller still needs one barrier before a whole-row reduction. + * + * Unnormalised: the caller folds 1/sqrt(HAD) into whatever scale it already applies. + */ +#pragma once +#include +#include "r3d_common.h" + +/* `hi ? (o - v) : (v + o)` as `o + (hi ? -v : v)`, the sign flip one XOR against a stage-uniform + * mask, so there is no per-element select. Bit-identical: negation is exact, addition commutes. */ +template +__device__ __forceinline__ void r3d_fwht_xstage(float* v, int lane) +{ + const unsigned int sm = (lane & MASK) ? 0x80000000u : 0u; +#pragma unroll + for (int j = 0; j < VPL; ++j) { + const float o = r3d_xor_lane(v[j]); + v[j] = __int_as_float(__float_as_uint(v[j]) ^ sm) + o; + } +} + +/* In-register FWHT of a HAD-wide block held VPL = HAD/32 values per lane, lane-major. */ +template +__device__ __forceinline__ void r3d_fwht_wave(float* v, int lane) +{ + constexpr int VPL = HAD / 32; + // in-lane stages: stride 1 .. VPL/2, entirely within this lane's registers +#pragma unroll + for (int h = 1; h < VPL; h <<= 1) { +#pragma unroll + for (int j = 0; j < VPL; ++j) { + if ((j & h) == 0) { + const float a = v[j], b = v[j + h]; + v[j] = a + b; + v[j + h] = a - b; + } + } + } + // cross-lane stages: stride VPL*mask for mask = 1, 2, 4, 8, 16 + r3d_fwht_xstage(v, lane); + r3d_fwht_xstage(v, lane); + r3d_fwht_xstage(v, lane); + r3d_fwht_xstage(v, lane); + r3d_fwht_xstage(v, lane); +} diff --git a/libr3d/r3d_gated_had_quant_fp8.hip b/libr3d/r3d_gated_had_quant_fp8.hip new file mode 100644 index 00000000..ef3bf3a3 --- /dev/null +++ b/libr3d/r3d_gated_had_quant_fp8.hip @@ -0,0 +1,142 @@ +/* r3d_gated_had_quant_fp8.hip -- gated_had_quant_fp8: a gated product, a 128-wide block Hadamard, + * then per-group E4M3, in one pass. + * + * mode 0 (silu) is down_proj's input, mode 1 (sigmoid) a gated attention o_proj's. The gate and up + * arrive as two halves of a fused gate_up of row pitch 2*n. The gated product is formed in fp32, + * the 128-wide Hadamard shrinks the group maximum (e4m3's exponent bits carry the outliers better + * after the rotation), and the codes are row-major E4M3. The normalisation (1/sqrt(128)) is folded + * into the scale. + * + * gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here + * (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs + * the whole FWHT with no group loop. A wider n is declined. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopE4M3 = 448.0f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) { + const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3)); + const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3)); + return lo | (hi << 16); +} +__device__ __forceinline__ float wave_max_f(float v) { + v = fmaxf(v, r3d_xor_lane<16>(v)); + v = fmaxf(v, r3d_xor_lane<8>(v)); + v = fmaxf(v, r3d_xor_lane<4>(v)); + v = fmaxf(v, r3d_xor_lane<2>(v)); + v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_fp8_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ yo, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + constexpr int HAD = 128, VPL = HAD / 32; + __shared__ float lds[128]; + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* g = gu + (size_t)row * gu_ld; + const uint16_t* u = g + n; + uint8_t* qr = q + (size_t)row * n; + uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.0f; + if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102) + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) { + const float xg = ld_bf(g, base + j); + const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */ + v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(u, base + j); + } + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { + lds[base + j] = v[j]; + m = fmaxf(m, fabsf(v[j])); + if (yop) yop[base + j] = f32_to_bf16(v[j]); + } + } + m = wave_max_f(m); + if (lane == 0) red[wave] = m; + __syncthreads(); + m = red[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]); + const float scale = m > 0.0f ? m * (1.0f / kTopE4M3) : 1.0f; + const float inv = 1.0f / scale; + if (threadIdx.x == 0) s[row] = scale * (1.0f / sqrtf((float)HAD)); + + if (wave == 0) + for (uint32_t c = lane * 4; c < n; c += kWave * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j]; + *(uint32_t*)(qr + c) = e4m3_codes4(v, inv); + } +} + +} // namespace + +extern "C" { + +int r3d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + /* The schema's order: gate_up, q, scale, out_bf16. */ + const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2), + *y = r3d_opt(a, 3); + if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (gu->dtype != RAD_BF16 || q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + long long M = 0, n = 0; + if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL); + if (n <= 0 || n % 4) return R3D_NO(RAD_E_SHAPE); + const long long grp = r3d_geti_or(a, "group", 128); + if (grp != 128 || n != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102) + if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + uint32_t y_ld = n; + if (y) { + if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE); + if (y->rank >= 2 && y->shape[1] > n) y_ld = (uint32_t)y->shape[1]; + } + + const char* act = r3d_gets(a, "act"); + const long long mode = act && 0 == std::strcmp(act, "sigmoid") ? 1 : 0; + const uint32_t gu_ld = (uint32_t)(gu->rank >= 2 ? gu->shape[1] : gu->stride[0]); + dim3 grid((unsigned)M), blk(kThreads); + if (mode == 0) + R3D_KLAUNCH(R3D_KNAME(gated_had_quant_fp8_kernel<0>), grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld); + else + R3D_KLAUNCH(R3D_KNAME(gated_had_quant_fp8_kernel<1>), grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_gated_had_quant_i8.hip b/libr3d/r3d_gated_had_quant_i8.hip new file mode 100644 index 00000000..85cd4d53 --- /dev/null +++ b/libr3d/r3d_gated_had_quant_i8.hip @@ -0,0 +1,159 @@ +/* r3d_gated_had_quant_i8.hip -- gated_had_quant_i8: an elementwise gated product, then the block + * Hadamard, then the per-row symmetric int8 quantiser, in one pass. + * + * Two of the four rotated sites have this shape and differ by one multiply: + * mode 0, down_proj's input silu(a) * b = a * sigmoid(a) * b (vLLM's silu_and_mul) + * mode 1, o_proj's input sigmoid(a) * b (attn_output * sigmoid(gate)) + * + * `a` is the gate and `b` the up; when `b` is absent it aliases `a + n` in a fused gate_up of row + * pitch 2*n. The transform is the wave-local FWHT of r3d_fwht.h; normalisation is folded into the + * scale. The codes are written in the int8 WMMA step order the w4a8/w8a8/w2a8 GEMMs read. + * + * silu is computed in fp32: the product feeds a rotation that mixes n values, so a bf16 rounding + * error in one lands on all of them. + * + * gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles + * here (a non-first wave drops out -- the same bug as the GDN recurrent kernel, the MoE router, + * and had_quant_act_i8). This serves the single-block form, n == group: one wave runs the whole + * FWHT with no block loop. A wider n is declined. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopI8 = 127.0f; +constexpr float kI8Floor = 1e-8f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} +__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) { + return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1); +} +__device__ __forceinline__ float block_max(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + v = wave_max(v); + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]); + return t; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_i8_kernel( + const uint16_t* __restrict__ g, const uint16_t* __restrict__ u, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t g_ld, uint32_t u_ld, float rnorm) { + constexpr int VPL = HAD / 32; + __shared__ float lds[1024]; + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* gp = g + (size_t)row * g_ld; + const uint16_t* up = u + (size_t)row * u_ld; + uint8_t* qr = q + (size_t)row * n; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.0f; + if (wave == 0) { // one wave does the whole single-block FWHT (no block loop, gfx1102) + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) { + const float xg = ld_bf(gp, base + j); + const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */ + v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(up, base + j); + } + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); } + } + m = block_max(m, red); + m = fmaxf(m, kI8Floor); + const float inv = kTopI8 / m; + if (threadIdx.x == 0) s[row] = m * rnorm / kTopI8; + + for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? lds[c + (uint32_t)j] : 0.0f; + *(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv); + } +} + +} // namespace + +extern "C" { + +int r3d_rad_gated_had_quant_i8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* gate = r3d_opt(a, 0), *up = r3d_opt(a, 1), *q = r3d_opt(a, 2), + *sc = r3d_opt(a, 3); + if (!r3d_p(gate) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (gate->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + long long M = 0, n = 0; + if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL); + if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); + + // `b` (up) is absent only in the fused form, where it aliases gate + n in a [M, 2n] gate_up. + const uint32_t g_ld = (uint32_t)(gate->rank >= 2 ? gate->shape[1] : gate->stride[0]); + uint32_t u_ld = g_ld; + const uint16_t* up_p; + if (up) { + if (up->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + u_ld = (uint32_t)(up->rank >= 2 ? up->shape[1] : up->stride[0]); + up_p = (const uint16_t*)r3d_p(up); + } else { + up_p = (const uint16_t*)r3d_p(gate) + (size_t)n; + } + if (up) { + if (r3d_numel(gate) < M * n || r3d_numel(up) < M * n) return R3D_NO(RAD_E_SHAPE); + } else if (r3d_numel(gate) < M * 2 * n) { + return R3D_NO(RAD_E_SHAPE); + } + + const long long had = r3d_geti_or(a, "group", 128); + if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE); + if (n != had) return R3D_NO(RAD_E_SHAPE); // single-block form (gfx1102, see the header) + + const long long mode = r3d_geti_or(a, "mode", 0); + if (mode != 0 && mode != 1) return R3D_NO(RAD_E_SHAPE); + const float rnorm = 1.0f / sqrtf((float)had); + dim3 grid((unsigned)M), blk(kThreads); + const uint32_t nn = (uint32_t)n; +#define GHQ(H, MD) \ + R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8_kernel), grid, blk, (hipStream_t)s, \ + (const uint16_t*)r3d_p(gate), up_p, (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), nn, g_ld, \ + u_ld, rnorm) + if (mode == 0) { + if (had == 256) GHQ(256, 0); else if (had == 512) GHQ(512, 0); else GHQ(128, 0); + } else { + if (had == 256) GHQ(256, 1); else if (had == 512) GHQ(512, 1); else GHQ(128, 1); + } +#undef GHQ + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_gated_had_quant_i8g.hip b/libr3d/r3d_gated_had_quant_i8g.hip new file mode 100644 index 00000000..8c709ceb --- /dev/null +++ b/libr3d/r3d_gated_had_quant_i8g.hip @@ -0,0 +1,144 @@ +/* r3d_gated_had_quant_i8g.hip -- gated_had_quant_i8g: a gated product, a 128-wide block Hadamard, + * then per-group int8 (row-major), in one pass. + * + * mode 0 (silu) is down_proj's input, mode 1 (sigmoid) a gated attention o_proj's. The gate and up + * arrive as two halves of a fused gate_up of row pitch 2*n. The gated product is formed in fp32, + * the 128-wide Hadamard shrinks the group maximum, and the codes are row-major int8 (the i8a8 dot2 + * GEMM reads stored order), with one scale per (row, group). The normalisation (1/sqrt(128)) is + * folded into the scale. + * + * gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here + * (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs + * the whole FWHT with no group loop. A wider n is declined. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopI8 = 127.0f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} +__device__ __forceinline__ float wave_max_f(float v) { + v = fmaxf(v, r3d_xor_lane<16>(v)); + v = fmaxf(v, r3d_xor_lane<8>(v)); + v = fmaxf(v, r3d_xor_lane<4>(v)); + v = fmaxf(v, r3d_xor_lane<2>(v)); + v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gated_had_quant_i8g_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ yo, uint8_t* __restrict__ q, + float* __restrict__ s, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + constexpr int HAD = 128, VPL = HAD / 32; + __shared__ float lds[128]; + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* g = gu + (size_t)row * gu_ld; + const uint16_t* u = g + n; + uint8_t* qr = q + (size_t)row * n; + uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.0f; + if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102) + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) { + const float xg = ld_bf(g, base + j); + const float sg = 1.0f / (1.0f + expf(-xg)); /* full exp: the reference's sigmoid */ + v[j] = (MODE == 0 ? xg * sg : sg) * ld_bf(u, base + j); + } + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { + lds[base + j] = v[j]; + m = fmaxf(m, fabsf(v[j])); + if (yop) yop[base + j] = f32_to_bf16(v[j]); + } + } + m = wave_max_f(m); + if (lane == 0) red[wave] = m; + __syncthreads(); + m = red[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]); + m = m > 0.0f ? m : 1e-8f; + const float inv = kTopI8 / m; + if (threadIdx.x == 0) s[row] = m * (1.0f / sqrtf((float)HAD)) / kTopI8; + + if (wave == 0) + for (uint32_t c = lane * 4; c < n; c += kWave * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j]; + *(uint32_t*)(qr + c) = i8_codes4(v, inv); // row-major (the i8a8 GEMM's layout) + } +} + +} // namespace + +extern "C" { + +int r3d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + /* The schema's order: gate_up, q, scale, out_bf16. */ + const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2), + *y = r3d_opt(a, 3); + if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + long long M = 0, n = 0; + if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL); + if (n <= 0 || n % 4) return R3D_NO(RAD_E_SHAPE); + const long long grp = r3d_geti_or(a, "group", 128); + if (grp != 128 || n != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102) + if (r3d_numel(gu) < M * 2 * n) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + uint32_t y_ld = n; + if (y) { + if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE); + if (y->rank >= 2 && y->shape[1] > n) y_ld = (uint32_t)y->shape[1]; + } + + const char* act = r3d_gets(a, "act"); + const long long mode = act && 0 == std::strcmp(act, "sigmoid") ? 1 : 0; + const uint32_t gu_ld = (uint32_t)(gu->rank >= 2 ? gu->shape[1] : gu->stride[0]); + dim3 grid((unsigned)M), blk(kThreads); + if (mode == 0) + R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8g_kernel<0>), grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld); + else + R3D_KLAUNCH(R3D_KNAME(gated_had_quant_i8g_kernel<1>), grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(gu), (uint16_t*)(y ? r3d_wp(y) : nullptr), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)n, gu_ld, y_ld); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip b/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip new file mode 100644 index 00000000..53d94a01 --- /dev/null +++ b/libr3d/r3d_gdn_chunk_scan_k128_v128_c64.hip @@ -0,0 +1,740 @@ +/* r3d_gdn_chunk_scan_k128_v128_c64.hip -- the gated-delta-net chunked scan: + * + * STATUS: single-chunk value probe is green (o and the closing state exact to bf16). The + * multi-chunk probe shows a residual that tracks the chunk-0 gate: with a decayed chunk-0 + * state, chunk 1's o / state come off by ~0.2-0.5 on O(10) values (~5500 / 65536 state + * elements past a 1% tolerance); with an undecayed chunk-0 state the same two-chunk run is + * clean to ~0.12. The chunk-1 s.S reads are the suspect (the chunk-0 writes are proven + * exact by the single-chunk gate and by the in-place ht), and the dependence on the state's + * value pattern -- not its magnitude -- places this with the card's data-dependent LDS + * misbehaviour that this file documents elsewhere. The state math, the tile map and every + * product were re-derived against a value probe during that pass; no logic change was found + * to be in error. + * + * The original status: the manual-FMA path is in. The + * staging is clean (verified: the k/v LDS buffers match the inputs bit-for-bit), the h0 / + * O^T / state-decay / ht paths are correct (mode-1 probe green), and the V' / sA structure + * matches the source. The wmma A-operand fragment read of the s.k buffer is decimated on this + * card -- the fragment's even k-elements come back correct and the odd ones zero, in every load + * form tried (uint4 / uint2 / scalar / volatile loads, 16B-aligned staging columns, tid-derived + * (pinned) row/col indices, a padded / relocated s.k, and swapping the operands to P = Q@K^T, + * s.k as the B-operand, which produced NaNs). The raw LDS value s.k[row][col] is verifiably + * correct at the read point, and the same read width (16 x 2B, scalar, volatile) from the s.S + * buffer is exact -- so it is the s.k A-operand path specifically, not the load, the offset, or + * the data. The three products that take s.k as the A-operand (U = K@S, P^T = K@Q^T and the + * state's V'^T@(gs*K)) therefore run as manual FMAs over the exact scalar reads; O^T = S@Q^T, + * V' = A@W and O += sA@V' stay on the wave matrix. + * + * U = K@S W = beta*(V - ge*U) V' = A@W (undecayed) + * P = Q@K^T sA = scale*e^{g_i-g_j}*tril(P) + * O = scale*ge*(Q@S) + sA@V' + * S = e^{g_last}*S + V'^T@(gs*K) + * + * per 64-token chunk, per v head; A is the kkt_solve row's output (the decayed gram's inverse, + * decay folded in). The recurrent state stays in wave-matrix accumulators across the chunk + * loop, so h / w / u / v_new never touch HBM. Every decay factor formed is <= 1: the intra-chunk + * gate span overflows a split exponent, so e^{g_i-g_j} (j <= i) and e^{g_last-g_j} are kept + * whole, in (0, 1]. + * + * ---- the tile map (the port's structural change) ------------------------------------------- + * + * The source row was written for the wave-matrix ISA of the card it was probed on, whose + * 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row, + * r3d_gemm_bf16_nt_m16_wmma.hip): + * + * A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous + * B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous + * C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane + * + * so the fragment loads are the GEMM row's 32-byte reads (the source's 16-byte half-K reads, + * doubled), and every accumulator store the source made as one 16-byte vector is here eight + * scalar bf16 stores along the map's stride-2 axis -- the W, sA, V', state and output stores, + * and the h0 / ht state transfers (k = 2e + hi strides two). The transposed-operand reads + * (fragT) keep the source's lane-to-row assignment, which the two ISAs share. + * + * The O accumulator works in the transposed frame end to end: the first product is S@Q^T + * (C[v][token]) and the second adds V'.(sA)^T, the transpose of sA@V', so one accumulator + * carries O^T and the store reads token off the lane's n axis. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" + +#include +#include +#include + +namespace { + +constexpr int kBT = 64; // chunk +constexpr int kKD = 128; // head_k +constexpr int kVD = 128; // head_v +constexpr int kBV = 64; // v per workgroup; also halves the Q@K^T redundancy +constexpr int kKP = 132; // row pitch of the [.][KD] buffers, in shorts +constexpr int kAP = 68; // row pitch of the [.][BT] buffers, in shorts +constexpr int kNW = 8; // waves; the [4 token][4 v] tile grid is fixed by BT and BV, so + // eight waves carry two tiles each +constexpr int kNTHR = kNW * 32; +constexpr int kNTV = 2; // n tiles per wave in the main / V' / O loops +constexpr int kSKT = 2; // the wave's slice of the 8 k-tile x 4 v-tile state grid is 2 x 2 +constexpr int kSVT = 2; +constexpr int kNST = kSKT * kSVT; + +struct CsSmem { + // k must not sit at a low LDS offset: on this card a 16-element fragment read from the + // first ~16 KB of the block is decimated (odd elements read back zero), while the same + // read from a higher offset is exact. The state buffer occupies the low region, so k + // lives where the source card's k lived (after the 68-pitch buffers). + unsigned short S[kBV][kKP]; // B: state, V-major + unsigned short A[kBT][kAP]; // B-source for sA (written as [i][j]) + unsigned short k[kBT][kKP]; // A: K / B: K^T for P=Q@K^T + unsigned short W[kBV][kAP]; // B: W (transposed) + unsigned short D[kBV][kAP]; // staged V as [token][v]; then V' as [v][token] + float ge[kBT], gv[kBT], gg[kBT], bt[kBT]; +}; + +using v8f = float __attribute__((ext_vector_type(8))); +using v16short = short __attribute__((ext_vector_type(16))); + +/* One 16x16x16 tile, f32 accumulate. */ +__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c) +{ + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +} + +/* A/B fragment from a row pointer already advanced to this lane's row: the 16 k contiguous, + * 32 bytes, two 16-byte reads (the GEMM row's exact form). */ +__device__ __forceinline__ v16short fragP(const unsigned short* p) +{ + // Four 8-byte LDS loads. The two-16-byte form lowers to a strided, decimated read at + // these lane-dependent offsets on this card (odd elements come back zero); 8-byte loads + // only need 8-byte alignment, which the 264-byte row pitch and 32-byte k-step guarantee. + union { uint2 w[4]; v16short f; } u; + u.w[0] = *(const uint2*)(p + 0); + u.w[1] = *(const uint2*)(p + 4); + u.w[2] = *(const uint2*)(p + 8); + u.w[3] = *(const uint2*)(p + 12); + return u.f; +} + +/* Global fragment off a 32-bit element offset split from a uniform base. */ +__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off) +{ + return fragP(base + off); +} + +/* Scalar A-fragment: sixteen 2-byte LDS loads. The vector form of the same read is + * decimated on this card for the k-buffer addresses; the scalar form is exact. */ +__device__ __forceinline__ v16short fragPs(const unsigned short* p) +{ + union { unsigned short h[16]; v16short f; } u; +#pragma unroll + for (int e = 0; e < 16; ++e) u.h[e] = p[e]; + return u.f; +} + +/* Volatile scalar A-fragment: the non-volatile scalar read of the k-buffer has its odd + * k-elements constant-folded to zero on this card; a volatile pointer stops that. */ +__device__ __forceinline__ v16short fragPv(const unsigned short* p) +{ + const volatile unsigned short* pv = p; + union { unsigned short h[16]; v16short f; } u; +#pragma unroll + for (int e = 0; e < 16; ++e) u.h[e] = pv[e]; + return u.f; +} + +/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */ +__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base, + int kbase, int lane) +{ + return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase); +} + +/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */ +__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base, + int kbase, int lane) +{ + const int idx = base + (lane & 15); + union { unsigned short h[16]; v16short f; } u; +#pragma unroll + for (int e = 0; e < 16; ++e) + u.h[e] = src[(size_t)(kbase + e) * pitch + idx]; + return u.f; +} + +/* A block barrier the backend cannot move; see the GEMM rows' note. */ +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +/* byte offset of buffer[base + lo] from the base of the shared block (the 16-k fragment starts + * at the row's head on this card; the source's + 4*hi half-K offset does not exist here) */ +#define ROWO(buf, pitch, base) \ + ((unsigned)((const char*)&(buf)[0][0] - (const char*)&s) + \ + (unsigned)(((base) + lo) * (pitch) * 2)) + +/* The state cache's element type (0 = fp32, 1 = fp16); all arithmetic is fp32. The cache is + * shared with the recurrent update and allocated from the engine's ssm-cache dtype, so both + * kernels must agree. */ +template struct cs_state { using T = float; }; +template <> struct cs_state<1> { using T = _Float16; }; + +#define PFW 8 // shorts staged per lane per step +#define PFZERO make_uint4(0u, 0u, 0u, 0u) +#define NKB (kBT * kKD / (kNTHR * PFW)) +#define NVB (kBT * kBV / (kNTHR * PFW)) + +template +__global__ __launch_bounds__(kNTHR) void r3d_gdn_chunk_scan_kernel( + const unsigned short* __restrict__ q, const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, const unsigned short* __restrict__ Amat, + const float* __restrict__ gcs, const float* __restrict__ beta, + const typename cs_state::T* __restrict__ h0, unsigned short* __restrict__ o, + typename cs_state::T* __restrict__ ht, const int* __restrict__ cu, + const int* __restrict__ sidx, long sidx_stride, long st_slot, long st_head, + int H, int Hg, float scale, unsigned short* __restrict__ dbg) +{ + __shared__ CsSmem s; + const int bv = blockIdx.x, hv = blockIdx.y, nq = blockIdx.z; + int tid = threadIdx.x; + asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it + const int w = tid >> 5, lane = tid & 31; + const int hq = hv / (H / Hg), v0 = bv * kBV; + const int tb = cu[nq], te = cu[nq + 1]; + // The state slot comes from the cache manager (sidx), not the batch position; without sidx + // the kernel uses state[nq], valid only while slots match batch order. + const long si = sidx ? (long)sidx[(size_t)nq * sidx_stride] : (long)nq; + if (si < 0) return; // a padded row owns no state + const size_t st_base = (size_t)si * st_slot + (size_t)hv * st_head; + const int nchunk = (te - tb + kBT - 1) / kBT; + const int lo = lane & 15, hi = lane >> 4; + + const int mt = w >> 1, ntb = (w & 1) * 2; // [BT][BV]: 2 tiles/wave + // The state accumulator is held transposed, C[m=k-dim][n=v]. A and B fragments share a + // lane layout, so swapping the state update's operands is free, and the k-dim becomes the + // per-lane axis of the 2e + hi map. + const int kt0 = (w >> 1) * 2, vt0 = (w & 1) * 2; // 2 x 2 + + uint4 kb[NKB], vb[NVB]; + // Staging index, derived from the pinned tid at every point of use. A lane stages 16 + // contiguous bytes, so the column starts at a 16-byte boundary: (tid&15)*8 shorts for k, + // (tid&7)*8 for v. The lanes of a wave cover two k rows per pass (lanes 0-15 the even row, + // 16-31 the odd one) and four v rows. The row and column are recomputed from tid alone at + // the load and the store: a cached wave index clobbers across the wmma builtins and turns + // a staging address into garbage (a NaN from an out-of-bounds global row). +#define KROW(u) (2 * (tid >> 5) + ((tid >> 4) & 1) + 16 * (u)) +#define KCOL ((tid & 15) * PFW) +#define VROW(u) (4 * (tid >> 5) + ((tid >> 3) & 3) + 32 * (u)) +#define VCOL ((tid & 7) * PFW) + // Staged rows past the chunk end are zeroed, not clamped to the last live row. A clamp + // looks harmless (beta and gv are 0 there, the tril mask drops padding j, the O store is + // guarded), yet with it a prompt whose trailing chunk is not a multiple of 16 tokens + // returns one repeated token. +#define PFSTORE(dst, val) \ + do { \ + /* Eight scalar stores: the two-uint2 form lowers to a decimated, \ + * shifted 16-byte store at a lane-dependent LDS address on this card. \ + */ \ + unsigned short* dp_ = (dst); \ + dp_[0] = (unsigned short)((val).x & 0xffffu); \ + dp_[1] = (unsigned short)((val).x >> 16); \ + dp_[2] = (unsigned short)((val).y & 0xffffu); \ + dp_[3] = (unsigned short)((val).y >> 16); \ + dp_[4] = (unsigned short)((val).z & 0xffffu); \ + dp_[5] = (unsigned short)((val).z >> 16); \ + dp_[6] = (unsigned short)((val).w & 0xffffu); \ + dp_[7] = (unsigned short)((val).w >> 16); \ + } while (0) +#define PREFETCH(CH) \ + { \ + const int pc0 = tb + (CH) * kBT, pnv = std::min(kBT, te - pc0); \ + const unsigned short* kb_ = k + ((size_t)pc0 * Hg + hq) * kKD; \ + const unsigned short* vb_ = v + ((size_t)pc0 * H + hv) * kVD + v0; \ + _Pragma("unroll") for (int u = 0; u < NKB; ++u) { \ + const int r = KROW(u); \ + /* Volatile scalars: the vector form miscompiles on this card (a \ + * strided, shifted read, and a data-dependent select over it drops \ + * lanes to NaN); one distinct 2-byte load per element. \ + */ \ + if (r < pnv) { \ + const volatile unsigned short* kp = kb_ + (unsigned)(r * (Hg * kKD)) + KCOL; \ + kb[u].x = kp[0] | (kp[1] << 16); \ + kb[u].y = kp[2] | (kp[3] << 16); \ + kb[u].z = kp[4] | (kp[5] << 16); \ + kb[u].w = kp[6] | (kp[7] << 16); \ + } else \ + kb[u] = PFZERO; \ + } \ + _Pragma("unroll") for (int u = 0; u < NVB; ++u) { \ + const int r = VROW(u); \ + if (r < pnv) { \ + const volatile unsigned short* vp = vb_ + (unsigned)(r * (H * kVD)) + VCOL; \ + vb[u].x = vp[0] | (vp[1] << 16); \ + vb[u].y = vp[2] | (vp[3] << 16); \ + vb[u].z = vp[4] | (vp[5] << 16); \ + vb[u].w = vp[6] | (vp[7] << 16); \ + } else \ + vb[u] = PFZERO; \ + } \ + } + + v8f St[kNST]; // state: SKT k-tiles x SVT v-tiles +#define KT(t) (kt0 + (t) / kSVT) +#define VT(t) (vt0 + (t) % kSVT) + // This card's D map puts element e at k = 2e + hi: the h0 / ht rows stride two. + if (H0) { +#pragma unroll + for (int t = 0; t < kNST; ++t) { + const typename cs_state::T* p = h0 + st_base + (size_t)(v0 + VT(t) * 16 + lo) * kKD + + KT(t) * 16; +#pragma unroll + for (int e = 0; e < 8; ++e) { + if (SDT) + St[t][e] = (float)p[2 * e + hi]; + else + St[t][e] = p[2 * e + hi]; + } + } + } else { +#pragma unroll + for (int t = 0; t < kNST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) St[t][e] = 0.0f; + } +#define SWRITE() \ + _Pragma("unroll") for (int t = 0; t < kNST; ++t) { \ + _Pragma("unroll") for (int e = 0; e < 8; ++e) \ + s.S[VT(t) * 16 + lo][KT(t) * 16 + 2 * e + hi] = f32_to_bf16(St[t][e]); \ + } + SWRITE(); + R3D_BARRIER(); + PREFETCH(0); + + const char* const sbase = (const char*)&s; + // scale goes inside the score exponent, exp(g_i + log(scale) - g_j), saving eight multiplies + // per tile. + const float lgs = __logf(scale); + for (int ci = 0; ci < nchunk; ++ci) { + const int c0 = tb + ci * kBT, nval = std::min(kBT, te - c0); + const int lim = nval - 1; + const unsigned short* qg = q + ((size_t)c0 * Hg + hq) * kKD; + const unsigned short* ag = Amat + ((size_t)c0 * H + hv) * kBT; + const size_t qrs = (size_t)Hg * kKD, ars = (size_t)H * kBT; + const float gl = gcs[(size_t)(c0 + lim) * H + hv]; + + // Issued before the staging store so the LDS writes cover their latency. Only waves 0-1 + // (tid < BT) run this; the others wait at (1). + float ggr = 0.f, btr = 0.f; + if (tid < kBT) { + const bool ok = tid < nval; + ggr = ok ? gcs[(size_t)(c0 + tid) * H + hv] : 0.f; + btr = ok ? beta[(size_t)(c0 + tid) * H + hv] : 0.f; + } + { // consume the previous iteration's prefetch, issued a whole chunk of compute ago +#pragma unroll + for (int u = 0; u < NKB; ++u) PFSTORE(&s.k[KROW(u)][KCOL], kb[u]); +#pragma unroll + for (int u = 0; u < NVB; ++u) PFSTORE(&s.D[VROW(u)][VCOL], vb[u]); + } + if (tid < kBT) { + const bool ok = tid < nval; + s.bt[tid] = btr; + s.ge[tid] = __expf(ggr); + // g is a within-chunk cumsum of log-sigmoid gates, so it is non-increasing and gl is + // its minimum. A padding row gets gl, not 0: it is scored against live j with very + // negative g_j, and g_i = 0 would give exp(+400) = inf in s.A. With gl the exponent + // stays in (0, scale]. The row is discarded anyway (the O store is guarded). + s.gg[tid] = ok ? ggr : gl; + s.gv[tid] = ok ? __expf(gl - ggr) : 0.f; // gs + } + R3D_BARRIER(); // (1) + PREFETCH(std::min(ci + 1, nchunk - 1)); // issue only; consumed next iteration + if (dbg && ci == 0) { + for (int i = tid; i < kBT * (kKD / 4); i += kNTHR) { + const int r = i / (kKD / 4), c = (i % (kKD / 4)) * 4; + unsigned short* o = dbg + 4 * kBT * kBT + (size_t)r * kBT + c; + const unsigned short* a1 = &s.k[r][c]; + o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3]; + } + } + + // ---- U = K@S, O^T = S@Q^T and P^T = K@Q^T share the q and k fragments. + // Tiles above the diagonal (A is unit lower triangular, sA is masked) are computed + // anyway: skipping them is 2.4% slower on the source card, since some wave still + // carries two tiles, so the barrier arrival does not move, and the guards stop + // fragment loads batching ahead of the WMMAs. + v8f O[kNTV], u[kNTV], p[kNTV]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) { O[i] = (v8f){}; u[i] = (v8f){}; p[i] = (v8f){}; } + { + const char* sb = sbase; + unsigned oSn[kNTV]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) { + oSn[i] = ROWO(s.S, kKP, (ntb + i) * 16); + asm volatile("" : "+v"(oSn[i])); + } +#define pSnf(i, ko) fragP((const unsigned short*)(sb + oSn[i] + (ko) * 2u)) + const unsigned qo = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)qrs; +#define pqf(ko) fragGo(qg, qo + (ko)) + // O^T = S@Q^T stays on the wave matrix: its s.S B-operand and the global Q read are + // exact. U = K@S and P^T = K@Q^T run as manual FMAs: the s.k A-operand fragment + // read is decimated on this card (the odd k-elements come back zero, in every load + // form tried), while the scalar read of the same buffer is verifiably exact. +#pragma unroll + for (int sk = 0; sk < kKD / 16; ++sk) { + const int ko = sk * 16; + const v16short aq = pqf(ko); +#pragma unroll + for (int i = 0; i < kNTV; ++i) + O[i] = mmab(pSnf(i, ko), aq, O[i]); // O^T: m = v-tile, n = token-tile + } +#pragma unroll + for (int i = 0; i < kNTV; ++i) { + const unsigned short* srow = &s.S[(ntb + i) * 16 + lo][0]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const unsigned short* krow = &s.k[mt * 16 + 2 * e + hi][0]; + float acc = 0.f; +#pragma unroll + for (int kk = 0; kk < kKD; ++kk) + acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(srow[kk]), acc); + u[i][e] = acc; + } + } + // P^T: the Q row is clamped to the last live token, as the fragment read was. + { + const unsigned short* qrow = + qg + (unsigned)std::min(mt * 16 + lo, lim) * (unsigned)qrs; +#pragma unroll + for (int i = 0; i < kNTV; ++i) { + if (dbg && ci == 0 && i == 0) + dbg[9 * kBT * kBT + lane] = s.k[(ntb) * 16 + lo][0]; // raw LDS value +#pragma unroll + for (int e = 0; e < 8; ++e) { + const unsigned short* krow = &s.k[(ntb + i) * 16 + 2 * e + hi][0]; + float acc = 0.f; +#pragma unroll + for (int kk = 0; kk < kKD; ++kk) + acc = fmaf(bf16_to_f32(krow[kk]), bf16_to_f32(qrow[kk]), acc); + p[i][e] = acc; + } + } + } + } + { + const float g = scale * s.ge[mt * 16 + lo]; // token index is constant per lane +#pragma unroll + for (int i = 0; i < kNTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) O[i][e] *= g; + } + // W = beta * (V - ge*U) (beta folded here: (A*beta_col)@W == A@(beta_row*W)) + { + float wa[kNTV][8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { // the U token is 2e + hi on this card + const int tok = mt * 16 + 2 * e + hi; + const float f = s.bt[tok], g = s.ge[tok]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) + wa[i][e] = f * (bf16_to_f32(s.D[tok][(ntb + i) * 16 + lo]) - g * u[i][e]); + } +#pragma unroll + for (int i = 0; i < kNTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) + s.W[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(wa[i][e]); + } + // sA = scale * e^{g_i-g_j} * tril(P). Row ii is constant per lane and the eight g_j are + // uniform per 16 lanes: eight broadcast LDS reads and a v_exp per tile (log(scale) is + // in the exponent). Where kept, g_i - g_j <= 0, so the exp cannot overflow. + if (dbg && ci == 0) { +#pragma unroll + for (int i = 0; i < kNTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) + dbg[3 * kBT * kBT + (mt * 16 + lo) * kBT + (ntb + i) * 16 + 2 * e + hi] = + f32_to_bf16(p[i][e]); + } + { + const int ii = mt * 16 + lo; + const float gis = s.gg[ii] + lgs; +#pragma unroll + for (int i = 0; i < kNTV; ++i) { + const int j0 = (ntb + i) * 16; + float a[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int j = j0 + 2 * e + hi; + a[e] = (j <= ii) ? p[i][e] * __expf(gis - s.gg[j]) : 0.f; + } +#pragma unroll + for (int e = 0; e < 8; ++e) + s.A[ii][j0 + 2 * e + hi] = f32_to_bf16(a[e]); + } + } + R3D_BARRIER(); // (2) + + // ---- V' = A @ W -> D (stored [v][token], transposed for the state read) + { + v8f d[kNTV]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) d[i] = (v8f){}; + const unsigned ao = (unsigned)std::min(mt * 16 + (lane & 15), lim) * (unsigned)ars; +#define paf(ko) fragGo(ag, ao + (ko)) + const unsigned short* pwn[kNTV]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) + pwn[i] = &s.W[(ntb + i) * 16 + lo][0]; +#define pwnf(i, ko) fragP(pwn[i] + (ko)) +#pragma unroll + for (int sk = 0; sk < kBT / 16; ++sk) { + const int ko = sk * 16; + const v16short a = paf(ko); +#pragma unroll + for (int i = 0; i < kNTV; ++i) d[i] = mmab(a, pwnf(i, ko), d[i]); + } +#pragma unroll + for (int i = 0; i < kNTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) + s.D[(ntb + i) * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(d[i][e]); + } + // K <- gs * K in place, for the state's V'^T @ K: (diag(gs) V')^T K == V'^T (diag(gs) K), + // and K is otherwise dead. All raw-K reads (U, P) retired before barrier (2); s.k is + // restaged next chunk; barrier (3) publishes the scaled K. +#pragma unroll + for (int u = 0; u < kBT * (kKD / 4) / kNTHR; ++u) { + const int idx = tid + u * kNTHR; + const int t = idx / (kKD / 4), c = (idx % (kKD / 4)) * 4; + const float f = s.gv[t]; + unsigned short* kp = &s.k[t][c]; +#pragma unroll + for (int e = 0; e < 4; ++e) kp[e] = f32_to_bf16(bf16_to_f32(kp[e]) * f); + } + R3D_BARRIER(); // (3) + if (dbg && ci == 0) { + for (int i = tid; i < kBT * (kBT / 4); i += kNTHR) { + const int r = i / (kBT / 4), c = (i % (kBT / 4)) * 4; + unsigned short* o = dbg + (size_t)r * kBT + c; + const unsigned short* a1 = &s.A[r][c]; + const unsigned short* a2 = &s.W[r][c]; + const unsigned short* a3 = &s.D[r][c]; + o[0] = a1[0]; o[1] = a1[1]; o[2] = a1[2]; o[3] = a1[3]; + o[kBT*kBT] = a2[0]; o[kBT*kBT+1] = a2[1]; o[kBT*kBT+2] = a2[2]; o[kBT*kBT+3] = a2[3]; + o[2*kBT*kBT] = a3[0]; o[2*kBT*kBT+1] = a3[1]; o[2*kBT*kBT+2] = a3[2]; o[2*kBT*kBT+3] = a3[3]; + } + } + + // ---- O += sA @ V' ; store. V' also feeds the state update, unchanged. The product + // runs in the transposed frame (V' as A, sA as B), adding (sA@V')^T to O^T. + { + const unsigned short* pA = &s.A[mt * 16 + lo][0]; + const unsigned short* pdn[kNTV]; +#pragma unroll + for (int i = 0; i < kNTV; ++i) + pdn[i] = &s.D[(ntb + i) * 16 + lo][0]; +#define pAf(ko) fragP(pA + (ko)) +#define pdnf(i, ko) fragP(pdn[i] + (ko)) +#pragma unroll + for (int sk = 0; sk < kBT / 16; ++sk) { + const int ko = sk * 16; + const v16short b = pAf(ko); +#pragma unroll + for (int i = 0; i < kNTV; ++i) O[i] = mmab(pdnf(i, ko), b, O[i]); + } + } + { + const int tok = mt * 16 + lo; + // The padding rows carry zero (the zeroed K, beta, gv and Q rows), so the store is + // unguarded and the output is finite at every row the caller can index. + { + unsigned short* op = o + ((size_t)(c0 + tok) * H + hv) * kVD + v0; +#pragma unroll + for (int i = 0; i < kNTV; ++i) +#pragma unroll + for (int e = 0; e < 8; ++e) + op[(ntb + i) * 16 + 2 * e + hi] = f32_to_bf16(O[i][e]); + } + } + + // ---- S = e^{gl} * S + V'^T @ (gs*K) (A needs K as [dim][token] -> strided fragT) + { + const float ec = __expf(gl); // gl <= 0: the decay is already on K +#pragma unroll + for (int t = 0; t < kNST; ++t) +#pragma unroll + for (int e = 0; e < 8; ++e) St[t][e] *= ec; + // The s.k A-operand (the fragT read) is decimated like the U / P reads, so the + // product runs as a manual FMA over the exact scalar reads. +#pragma unroll + for (int t = 0; t < kNST; ++t) { + const int v = VT(t) * 16 + lo; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int kx = KT(t) * 16 + 2 * e + hi; + float acc = 0.f; +#pragma unroll + for (int tk = 0; tk < kBT; ++tk) + acc = fmaf(bf16_to_f32(s.k[tk][kx]), bf16_to_f32(s.D[v][tk]), acc); + St[t][e] += acc; + } + } + } + // No barrier before the writeback: s.S aliases nothing, and barrier (2) proves every + // wave finished its U/O reads of s.S this chunk. + SWRITE(); + R3D_BARRIER(); // (4) + } + + if (HT) { + typename cs_state::T* p = ht + st_base; +#pragma unroll + for (int t = 0; t < kNST; ++t) { + typename cs_state::T* pw = p + (size_t)(v0 + VT(t) * 16 + lo) * kKD + KT(t) * 16; +#pragma unroll + for (int e = 0; e < 8; ++e) { + if (SDT) + pw[2 * e + hi] = (typename cs_state::T)St[t][e]; + else + pw[2 * e + hi] = St[t][e]; + } + } + } +} + +int r3d_gdn_chunk_scan_launch(const void* q, const void* k, const void* v, const void* A, + const void* g, const void* beta, const void* h0, void* o, + void* ht, const void* cu, const void* sidx, long sidx_stride, + long st_slot, long st_head, int N, int H, int Hg, int K, int V, + int chunk, float scale, int state_fp16, void* dbg, hipStream_t stream) +{ + if (K != kKD || V != kVD || chunk != kBT) return -1; + if (Hg <= 0 || H % Hg) return -2; + dim3 grid(V / kBV, H, N), blk(kNTHR); +#define CS_LAUNCH(SDTC, H0C, HTC) \ + R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_chunk_scan_kernel)), grid, blk, 0, stream, \ + (const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, \ + (const unsigned short*)A, (const float*)g, (const float*)beta, \ + (const cs_state::T*)h0, (unsigned short*)o, (cs_state::T*)ht, \ + (const int*)cu, (const int*)sidx, sidx_stride, st_slot, st_head, H, Hg, scale, (unsigned short*)dbg) +#define CS_PICK(SDTC) \ + do { if (h0 && ht) CS_LAUNCH(SDTC, true, true); \ + else if (h0) CS_LAUNCH(SDTC, true, false); \ + else if (ht) CS_LAUNCH(SDTC, false, true); \ + else CS_LAUNCH(SDTC, false, false); } while (0) + if (state_fp16) CS_PICK(1); else CS_PICK(0); +#undef CS_PICK +#undef CS_LAUNCH + return (int)hipGetLastError(); +} + +} // namespace + +/* ------------------------------------------------------------------ the raw entry */ + +extern "C" int r3d_gdn_chunk_scan_k128_v128_c64(long q, long k, long v, long A, long g, long beta, + long h0, long o, long ht, long cu, long sidx, + long sidx_stride, long st_slot, long st_head, + int N, int H, int Hg, int K, int V, int chunk, + double scale, int state_fp16, long dbg, long stream) +{ + if (!q || !k || !v || !A || !g || !beta || !cu || !o) return -1; + if (N < 1 || H < 1 || Hg < 1) return -2; + return r3d_gdn_chunk_scan_launch((const void*)q, (const void*)k, (const void*)v, (const void*)A, + (const void*)g, (const void*)beta, (const void*)h0, + (void*)o, (void*)ht, (const void*)cu, (const void*)sidx, + sidx_stride, st_slot, st_head, N, H, Hg, K, V, chunk, + (float)scale, state_fp16, (void*)dbg, (hipStream_t)stream); +} + +/* ------------------------------------------------------------------ the plugin ABI */ + +enum { CS_Q = 0, CS_K, CS_V, CS_A, CS_G, CS_BETA, CS_H0, CS_CU, CS_O, CS_HT, CS_SIDX }; + +extern "C" int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* qt = r3d_opt(a, CS_Q); + const RadTensor* kt = r3d_opt(a, CS_K); + const RadTensor* vt = r3d_opt(a, CS_V); + const RadTensor* At = r3d_opt(a, CS_A); + const RadTensor* gt = r3d_opt(a, CS_G); + const RadTensor* btt = r3d_opt(a, CS_BETA); + const RadTensor* h0t = r3d_opt(a, CS_H0); + const RadTensor* cut = r3d_opt(a, CS_CU); + const RadTensor* ot = r3d_opt(a, CS_O); + const RadTensor* htt = r3d_opt(a, CS_HT); + const RadTensor* sit = r3d_opt(a, CS_SIDX); + if (!r3d_p(qt) || !r3d_p(kt) || !r3d_p(vt) || !r3d_p(At) || !r3d_p(gt) || !r3d_p(btt) || + !r3d_p(cut) || !r3d_wp(ot)) + return R3D_NO(RAD_E_INVAL); + // bf16 q/k/v/A/o, f32 gate/beta; the state cache is f32 or f16, taken from the operand's + // dtype (a property of the allocation), so this kernel and the recurrent update, which + // share the cache, agree on it. + if (!r3d_is_bf16(qt) || !r3d_is_bf16(kt) || !r3d_is_bf16(vt) || !r3d_is_bf16(At) || + !r3d_is_f32(gt) || !r3d_is_f32(btt) || !r3d_is_bf16(ot)) + return R3D_NO(RAD_E_DTYPE); + uint32_t st_dt = RAD_F32; + if (r3d_has(h0t)) { if (!r3d_is_f32(h0t) && !r3d_is_f16(h0t)) return R3D_NO(RAD_E_DTYPE); + st_dt = h0t->dtype; } + if (r3d_has(htt)) { + if (htt->dtype != st_dt) return R3D_NO(RAD_E_DTYPE); + st_dt = htt->dtype; + } + if (r3d_has(sit) && !r3d_is_i32(sit)) return R3D_NO(RAD_E_DTYPE); + + if (cut->rank != 1 || cut->shape[0] < 2 || !r3d_contig(cut)) return R3D_NO(RAD_E_SHAPE); + const int N = (int)(cut->shape[0] - 1); + + const long long T = r3d_dim(qt, 0), Hg = r3d_dim(qt, 1), K = r3d_dim(qt, 2); + const long long H = r3d_dim(vt, 1), V = r3d_dim(vt, 2); + const long long chunk = r3d_dim(At, 2); + if (r3d_dim(kt, 0) != T || r3d_dim(kt, 1) != Hg || r3d_dim(kt, 2) != K) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(vt, 0) != T) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(ot, 0) != T || r3d_dim(ot, 1) != H || r3d_dim(ot, 2) != V) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(At, 0) != T || r3d_dim(At, 1) != H) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(btt, 0) != T || r3d_dim(btt, 1) != H) return R3D_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); + // The state slot strides come from the tensor, not from H, V and K, so a cache with padded + // slots is served too. h0 and ht must share strides: the kernel uses one base for both. + long long st_slot = 0, st_head = 0; + if (r3d_has(h0t)) { + if (h0t->rank < 2) return R3D_NO(RAD_E_SHAPE); + st_slot = h0t->stride[0]; st_head = h0t->stride[1]; + } + if (r3d_has(htt)) { + if (htt->rank < 2) return R3D_NO(RAD_E_SHAPE); + if (r3d_has(h0t) && (htt->stride[0] != st_slot || htt->stride[1] != st_head)) + return R3D_NO(RAD_E_STRIDE); + st_slot = htt->stride[0]; st_head = htt->stride[1]; + } + if (r3d_has(sit)) { + if (sit->rank < 1 || sit->shape[0] != N) return R3D_NO(RAD_E_SHAPE); + if (sit->stride[sit->rank - 1] != 1) return R3D_NO(RAD_E_STRIDE); + } + if (!r3d_contig(qt) || !r3d_contig(kt) || !r3d_contig(vt) || !r3d_contig(At) || + !r3d_contig(gt) || !r3d_contig(btt) || !r3d_contig(ot)) + return R3D_NO(RAD_E_STRIDE); + + const double scale = r3d_getf(a, "scale", 1.0); + const int state_fp16 = st_dt == RAD_F16; + + const int e = r3d_gdn_chunk_scan_launch(r3d_p(qt), r3d_p(kt), r3d_p(vt), r3d_p(At), r3d_p(gt), + r3d_p(btt), r3d_has(h0t) ? r3d_p(h0t) : nullptr, r3d_wp(ot), + r3d_has(htt) ? r3d_wp(htt) : nullptr, r3d_p(cut), + r3d_has(sit) ? r3d_p(sit) : nullptr, + r3d_has(sit) && sit->rank >= 2 ? sit->stride[0] : 1, + st_slot, st_head, N, (int)H, (int)Hg, (int)K, (int)V, + (int)chunk, (float)scale, state_fp16, nullptr, (hipStream_t)s); + /* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The + * plugin ABI takes RadStatus, so normalise. */ + if (e < 0) return R3D_NO(RAD_E_INVAL); + return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK; +} diff --git a/libr3d/r3d_gdn_conv_w4_h128.hip b/libr3d/r3d_gdn_conv_w4_h128.hip new file mode 100644 index 00000000..2d803ace --- /dev/null +++ b/libr3d/r3d_gdn_conv_w4_h128.hip @@ -0,0 +1,585 @@ +/* r3d_gdn_conv_w4_h128.hip -- the gated-delta-net depthwise causal convolution and the work fused + * around it, one entry point per serving phase. + * + * PREFILL (gdn_conv_prep): everything the layer does between the qkv projection and the chunked + * scan, in one kernel: + * + * conv(x) depthwise causal convolution, width 4, silu, varlen, with the conv-state + * cache read at a sequence's first chunk and rewritten from its last tokens + * split the packed [q | k | v] channel range into three contiguous tensors + * l2norm over each 128-dim q and k head + * gate g = -exp(A_log) . softplus(a + dt_bias), beta = sigmoid(b) + * cumsum g summed along the chunk, which is what the scan actually consumes + * + * The conv output is rounded to bf16 before the norm and the store, so this kernel is a bit-exact + * drop-in for the unfused causal_conv1d_fn + fused_post_conv_prep + chunk_local_cumsum pair. + * + * DECODE (gdn_conv_update): the same filter, but a step's tokens are a speculative window and the + * state cache is a rolling buffer of width-1 + num_spec entries: a step reads its window starting + * at the slot the last accepted token left, and rewrites the buffer shifted by one. + * + * A workgroup is HPB waves, one wave per 128-dim head, four dims per lane, so a head's norm is a + * barrier-free wave reduction and each lane does one 8-byte access. Tokens are blocked by the + * 64-token chunk because the cumsum is per chunk. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kHD = 128; // dims per head, q k and v alike +constexpr int kBT = 64; // token block = the scan's chunk, so the cumsum stays wave-local +constexpr int kW = 4; // conv width +constexpr int kST = kW - 1; // conv state depth (3 taps of history) +constexpr int kMAXT = 8; // tokens the decode update preloads into registers +constexpr int kDPL = 4; // dims per lane (kHD / 32) + +/* One convolution tap: rounded to bf16 by the caller. The reciprocal form is two instructions + * against ~10 for an IEEE-exact divide, and v_rcp_f32 is 1 ULP against bf16's 2^-8 quantum. */ +__device__ __forceinline__ float cp_silu(float z) +{ + return z * __builtin_amdgcn_rcpf(1.0f + __expf(-z)); +} + +/* softplus, in the two-sided form with the same large-x cutoff. */ +__device__ __forceinline__ float cp_softplus(float x, float thr) +{ + if (x > thr) return x; + return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); +} + +/* a and b are read where they lie: a chunk() of the ba projection, bf16 with row stride 2*H (or + * fp32), avoiding a copy and two launches per layer. */ +template +__device__ __forceinline__ float cp_ab(const void* p, size_t i) +{ + return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i]; +} + +/* `has_init` says whether the slot holds a history; its element width (int32 or byte) is given + * by the caller. Read as bytes, a ctx_len of 512 would look like 0 and the conv window would + * silently start from zeros. */ +__device__ __forceinline__ bool r3d_has_init(const void* p, int i32, int n) +{ + if (!p) return false; + return i32 ? ((const int*)p)[n] != 0 : ((const unsigned char*)p)[n] != 0; +} + +/* ================================ the prefill convolution ================================ */ + +template +__global__ __launch_bounds__(HPB * 32) +void r3d_gdn_conv_prep_kernel(const unsigned short* __restrict__ x, long long xpitch, + const unsigned short* __restrict__ wgt, + const unsigned short* __restrict__ bias, + unsigned short* __restrict__ cstate, + long long cs_seq, long long cs_dim, long long cs_tok, + const int* __restrict__ cache_idx, long long ci_stride, + const void* __restrict__ has_init, int hi_i32, + const void* __restrict__ av, const void* __restrict__ bv, + long long ab_stride, + const float* __restrict__ A_log, const float* __restrict__ dt_bias, + unsigned short* __restrict__ q, unsigned short* __restrict__ k, + unsigned short* __restrict__ v, + float* __restrict__ go, float* __restrict__ beta, + const int* __restrict__ cu, int N, int H, int Hg, float sp_thr) +{ + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + + // flat chunk id -> (sequence, chunk); the grid is an upper bound. + int n = -1, t0 = 0, bos = 0, rows = 0, slen = 0; + { + int acc = 0, want = blockIdx.x; + for (int i = 0; i < N; ++i) { + const int b = cu[i], e = cu[i + 1]; + const int nc = (e - b + kBT - 1) / kBT; + if (want < acc + nc) { n = i; bos = b; slen = e - b; t0 = (want - acc) * kBT; + rows = min(kBT, slen - t0); break; } + acc += nc; + } + if (n < 0) return; + } + const bool first = (t0 == 0); + + // ---- the gating half, on one workgroup per chunk -------------------------------------- + if (blockIdx.y == 0) { + for (int hv = warp; hv < H; hv += HPB) { + const float alog = __expf(A_log[hv]), dtb = dt_bias[hv]; + const int i0 = 2 * lane, i1 = i0 + 1; + float g0 = 0.0f, g1 = 0.0f; + if (i0 < rows) + g0 = -alog * cp_softplus(cp_ab(av, (size_t)(bos + t0 + i0) * ab_stride + hv) + + dtb, sp_thr); + if (i1 < rows) + g1 = -alog * cp_softplus(cp_ab(av, (size_t)(bos + t0 + i1) * ab_stride + hv) + + dtb, sp_thr); + // inclusive wave scan of the per-lane pair sums, made exclusive by subtracting the pair + float p = g0 + g1; +#pragma unroll + for (int d = 1; d < 32; d <<= 1) { + const float o = __shfl_up(p, d, 32); + if (lane >= d) p += o; + } + const float pre = p - (g0 + g1); + if (i0 < rows) { + go[(size_t)(bos + t0 + i0) * H + hv] = pre + g0; + beta[(size_t)(bos + t0 + i0) * H + hv] = 1.0f / (1.0f + __expf( + -cp_ab(bv, (size_t)(bos + t0 + i0) * ab_stride + hv))); + } + if (i1 < rows) { + go[(size_t)(bos + t0 + i1) * H + hv] = pre + g0 + g1; + beta[(size_t)(bos + t0 + i1) * H + hv] = 1.0f / (1.0f + __expf( + -cp_ab(bv, (size_t)(bos + t0 + i1) * ab_stride + hv))); + } + } + } + + // ---- the convolution half -------------------------------------------------------------- + const int unit = blockIdx.y * HPB + warp; + const int d0 = unit * kHD + lane * kDPL; + const unsigned short* xp = x + (size_t)(bos + t0) * xpitch + d0; + + float wt[kW][kDPL], bs[kDPL]; +#pragma unroll + for (int c = 0; c < kDPL; ++c) { +#pragma unroll + for (int i = 0; i < kW; ++i) wt[i][c] = bf16_to_f32(wgt[(size_t)(d0 + c) * kW + i]); + bs[c] = bias ? bf16_to_f32(bias[d0 + c]) : 0.0f; + } + + // win[i] holds x[t - (W-1) + i]; seeded from the previous tokens, or from the conv state cache + // at the sequence's first chunk. + float win[kW][kDPL]; + { + const bool init = first && r3d_has_init(has_init, hi_i32, n); + const unsigned short* sp = init ? (cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq + + (size_t)d0 * cs_dim) : nullptr; +#pragma unroll + for (int i = 0; i < kST; ++i) { // i = 0,1,2 -> x[t0-3+i] + const int src = t0 - kST + i; +#pragma unroll + for (int c = 0; c < kDPL; ++c) { + float val = 0.0f; + if (src >= 0) val = bf16_to_f32(x[(size_t)(bos + src) * xpitch + d0 + c]); + else if (init) val = bf16_to_f32(sp[(size_t)c * cs_dim + (size_t)(kST + src) * cs_tok]); + win[i][c] = val; + } + } + } + + // ---- write the new conv state, from x, at the sequence's first chunk -------------------- + if (first && cache_idx) { + unsigned short* sp = cstate + (size_t)cache_idx[(size_t)n * ci_stride] * cs_seq + + (size_t)d0 * cs_dim; + const bool init = r3d_has_init(has_init, hi_i32, n); + // Channel-major: the cache is [dim][slot] with slot contiguous, so a lane's kDPL*kST + // shorts are one contiguous run. +#pragma unroll + for (int c = 0; c < kDPL; ++c) { +#pragma unroll + for (int i = 0; i < kST; ++i) { + const int src = slen - kST + i; + unsigned short val = 0; + if (src >= 0) val = x[(size_t)(bos + src) * xpitch + d0 + c]; + else if (init) val = sp[(size_t)c * cs_dim + (size_t)(kST + src) * cs_tok]; + sp[(size_t)c * cs_dim + (size_t)i * cs_tok] = val; + } + } + } + + const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg; + const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2); + + for (int t = 0; t < rows; ++t) { + float o[kDPL]; + { + const unsigned short* xr = xp + (size_t)t * xpitch; + const ushort4 raw = *(const ushort4*)xr; + win[kW - 1][0] = bf16_to_f32(raw.x); win[kW - 1][1] = bf16_to_f32(raw.y); + win[kW - 1][2] = bf16_to_f32(raw.z); win[kW - 1][3] = bf16_to_f32(raw.w); + } +#pragma unroll + for (int c = 0; c < kDPL; ++c) { + float acc = bs[c]; +#pragma unroll + for (int i = 0; i < kW; ++i) acc += wt[i][c] * win[i][c]; + o[c] = bf16_to_f32(f32_to_bf16(cp_silu(acc))); + } + + if (region < 2) { + float ss = 0.0f; +#pragma unroll + for (int c = 0; c < kDPL; ++c) ss += o[c] * o[c]; + ss += r3d_xor_lane<16>(ss); ss += r3d_xor_lane<8>(ss); ss += r3d_xor_lane<4>(ss); + ss += r3d_xor_lane<2>(ss); ss += r3d_xor_lane<1>(ss); + const float inv = 1.0f / sqrtf(ss + 1e-6f); + unsigned short* dst = (region ? k : q) + + ((size_t)(bos + t0 + t) * Hg + (region ? hk : hq)) * kHD + + lane * kDPL; + *(ushort4*)dst = make_ushort4(f32_to_bf16(o[0] * inv), f32_to_bf16(o[1] * inv), + f32_to_bf16(o[2] * inv), f32_to_bf16(o[3] * inv)); + } else { + unsigned short* dst = v + ((size_t)(bos + t0 + t) * H + hv) * kHD + lane * kDPL; + *(ushort4*)dst = make_ushort4(f32_to_bf16(o[0]), f32_to_bf16(o[1]), + f32_to_bf16(o[2]), f32_to_bf16(o[3])); + } + +#pragma unroll + for (int i = 0; i < kW - 1; ++i) +#pragma unroll + for (int c = 0; c < kDPL; ++c) win[i][c] = win[i + 1][c]; + } +} + +int r3d_gdn_conv_prep_launch(const void* x, long long xpitch, const void* wgt, const void* bias, + void* cstate, long long cs_seq, long long cs_dim, long long cs_tok, + const void* cache_idx, long long ci_stride, const void* has_init, + int hi_i32, const void* a, const void* b, long long ab_stride, + int ab_is_bf16, const void* A_log, const void* dt_bias, void* q, + void* k, void* v, void* g, void* beta, const void* cu, + int N, int T, int H, int Hg, int width, float softplus_thr, + hipStream_t stream) +{ + const int units = 2 * Hg + H; + int hpb = 8; + while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1; + const int nchunk_ub = (T + kBT - 1) / kBT + N; + dim3 grid(nchunk_ub, units / hpb), blk(hpb * 32); +#define CP_LAUNCH(P, AB) \ + R3D_KLAUNCH(R3D_KNAME((r3d_gdn_conv_prep_kernel)), grid, blk, stream, \ + (const unsigned short*)x, xpitch, (const unsigned short*)wgt, \ + (const unsigned short*)bias, (unsigned short*)cstate, \ + cs_seq, cs_dim, cs_tok, (const int*)cache_idx, ci_stride, \ + has_init, hi_i32, a, b, ab_stride, \ + (const float*)A_log, (const float*)dt_bias, (unsigned short*)q, \ + (unsigned short*)k, (unsigned short*)v, (float*)g, (float*)beta, \ + (const int*)cu, N, H, Hg, softplus_thr) +#define CP_SWITCH(AB) \ + switch (hpb) { \ + case 8: CP_LAUNCH(8, AB); break; \ + case 4: CP_LAUNCH(4, AB); break; \ + case 2: CP_LAUNCH(2, AB); break; \ + default: CP_LAUNCH(1, AB); break; \ + } + if (ab_is_bf16) { CP_SWITCH(1); } else { CP_SWITCH(0); } +#undef CP_SWITCH +#undef CP_LAUNCH + return (int)hipGetLastError(); +} + +/* ================================ the decode convolution ================================ */ + +template +__global__ __launch_bounds__(HPB * 32) +void r3d_gdn_conv_update_kernel(const unsigned short* __restrict__ x, long long xpitch, + const unsigned short* __restrict__ wgt, + const unsigned short* __restrict__ bias, + unsigned short* __restrict__ cstate, + long long cs_seq, long long cs_dim, long long cs_tok, + int state_len_max, + const int* __restrict__ cache_idx, long long ci_stride, + const int* __restrict__ naccept, + unsigned short* __restrict__ q, unsigned short* __restrict__ k, + unsigned short* __restrict__ v, + const int* __restrict__ cu, int H, int Hg, int maxq) +{ + const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; + const int n = blockIdx.x; + const int bos = cu[n], slen = cu[n + 1] - bos; + if (slen <= 0) return; + const int slot = cache_idx[(size_t)n * ci_stride]; + if (slot < 0) return; + + const int off = naccept ? (naccept[n] - 1) : 0; + const int slen_eff = state_len_max - (maxq - slen); + + const int unit = blockIdx.y * HPB + warp; + const int d0 = unit * kHD + lane * kDPL; + + static_assert(kW == 4, "the weight load reads a channel's taps as one ushort4"); + float wt[kW][kDPL], bs[kDPL]; +#pragma unroll + for (int c = 0; c < kDPL; ++c) { + const ushort4 w4 = *(const ushort4*)(wgt + (size_t)(d0 + c) * kW); + const unsigned short* ws = (const unsigned short*)&w4; +#pragma unroll + for (int i = 0; i < kW; ++i) wt[i][c] = bf16_to_f32(ws[i]); + bs[c] = bias ? bf16_to_f32(bias[d0 + c]) : 0.0f; + } + + const int csd = (int)cs_dim, cst = (int)cs_tok, xpi = (int)xpitch; + unsigned short* const sp = cstate + (size_t)slot * cs_seq + (size_t)d0 * cs_dim; + const unsigned short* const xrow = x + (size_t)bos * xpitch + d0; + ushort4 xb[kMAXT]; + const bool xpre = (slen <= kMAXT); +#pragma unroll + for (int t = 0; t < kMAXT; ++t) + if (xpre && t < slen) xb[t] = *(const ushort4*)(xrow + t * xpi); + float win[kW][kDPL]; + unsigned short hist[kST][kDPL]; + { + const unsigned short* hp = sp + off * cst; +#pragma unroll + for (int i = 0; i < kST; ++i) +#pragma unroll + for (int c = 0; c < kDPL; ++c) { + const unsigned short raw = hp[c * csd + i * cst]; + hist[i][c] = raw; + win[i][c] = bf16_to_f32(raw); + } + } + + const int hq = unit, hk = unit - Hg, hv = unit - 2 * Hg; + const int region = (unit < Hg) ? 0 : ((unit < 2 * Hg) ? 1 : 2); + + unsigned short* op = (region == 2) + ? (v + ((size_t)bos * H + hv) * kHD + lane * kDPL) + : ((region ? k : q) + ((size_t)bos * Hg + (region ? hk : hq)) * kHD + lane * kDPL); + const int ostep = (region == 2) ? H * kHD : Hg * kHD; + +#define CU_TOKEN_BODY(RAW) \ + { \ + const ushort4 raw_ = (RAW); \ + win[kW - 1][0] = bf16_to_f32(raw_.x); win[kW - 1][1] = bf16_to_f32(raw_.y); \ + win[kW - 1][2] = bf16_to_f32(raw_.z); win[kW - 1][3] = bf16_to_f32(raw_.w); \ + unsigned short out[kDPL]; \ + _Pragma("unroll") \ + for (int c = 0; c < kDPL; ++c) { \ + float acc = bs[c]; \ + _Pragma("unroll") \ + for (int i = 0; i < kW; ++i) acc += wt[i][c] * win[i][c]; \ + out[c] = f32_to_bf16(cp_silu(acc)); \ + } \ + *(ushort4*)op = make_ushort4(out[0], out[1], out[2], out[3]); \ + op += ostep; \ + _Pragma("unroll") \ + for (int i = 0; i < kW - 1; ++i) \ + _Pragma("unroll") \ + for (int c = 0; c < kDPL; ++c) win[i][c] = win[i + 1][c]; \ + } + if (xpre) { +#pragma unroll + for (int t = 0; t < kMAXT; ++t) { + if (t < slen) CU_TOKEN_BODY(xb[t]) + } + } else { + for (int t = 0; t < slen; ++t) CU_TOKEN_BODY(*(const ushort4*)(xrow + t * xpi)) + } + + // Rewrite the cache shifted by one. + const int VAL = kW - 2; + const int nh = slen_eff - slen < 0 ? 0 : (slen_eff - slen); +#pragma unroll + for (int c = 0; c < kDPL; ++c) { + unsigned short* dst = sp + c * csd; +#pragma unroll + for (int i = 0; i + 1 < kST; ++i) + if (i < nh && i < slen_eff) dst[i * cst] = hist[i + 1][c]; + if (xpre) { +#pragma unroll + for (int t = 0; t < kMAXT; ++t) { + const int i = t + VAL; + if (i >= nh && i < slen_eff && t < slen) { + const ushort4 vv = xb[t]; + dst[i * cst] = (c == 0) ? vv.x : (c == 1) ? vv.y : (c == 2) ? vv.z : vv.w; + } + } + } + for (int i = nh; i < slen_eff; ++i) { + const int ti = i - VAL; + if (!xpre || ti < 0 || ti >= slen) dst[i * cst] = xrow[ti * xpi + c]; + } + } +#undef CU_TOKEN_BODY +} + +int r3d_gdn_conv_update_launch(const void* x, long long xpitch, const void* wgt, const void* bias, + void* cstate, long long cs_seq, long long cs_dim, long long cs_tok, + int state_len_max, const void* cache_idx, long long ci_stride, + const void* num_accepted, void* q, void* k, void* v, + const void* cu, int N, int H, int Hg, int width, int max_query_len, + hipStream_t stream) +{ + const int units = 2 * Hg + H; + int hpb = 8; + while (hpb > 1 && (Hg % hpb || H % hpb)) hpb >>= 1; + while (hpb > 1 && (long)N * (units / hpb) < 256) hpb >>= 1; + dim3 grid(N, units / hpb), blk(hpb * 32); +#define CU_LAUNCH(P) \ + R3D_KLAUNCH(R3D_KNAME((r3d_gdn_conv_update_kernel

)), grid, blk, stream, \ + (const unsigned short*)x, xpitch, (const unsigned short*)wgt, \ + (const unsigned short*)bias, (unsigned short*)cstate, cs_seq, cs_dim, \ + cs_tok, state_len_max, (const int*)cache_idx, ci_stride, \ + (const int*)num_accepted, (unsigned short*)q, (unsigned short*)k, \ + (unsigned short*)v, (const int*)cu, H, Hg, max_query_len) + switch (hpb) { + case 8: CU_LAUNCH(8); break; + case 4: CU_LAUNCH(4); break; + case 2: CU_LAUNCH(2); break; + default: CU_LAUNCH(1); break; + } +#undef CU_LAUNCH + return (int)hipGetLastError(); +} + +/* A contiguous cu (rank 1, >= 2) gives the sequence count; -1 on refusal. */ +static int seqs_of(const RadTensor* cu, int* out) +{ + if (!cu || cu->rank != 1 || cu->shape[0] < 2) return -1; + if (!r3d_contig(cu)) return -2; + *out = (int)(cu->shape[0] - 1); + return 0; +} + +} // namespace + +/* ------------------------------------------------------------------ the plugin ABI: conv prep */ + +enum { CP_X = 0, CP_W, CP_B, CP_ALOG, CP_DTB, CP_CSTATE, CP_CU, CP_A, CP_BGATE, CP_CACHE_IDX, + CP_HAS_INIT, CP_Q, CP_K, CP_V, CP_G, CP_BETA }; + +extern "C" int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, CP_X); + const RadTensor* w = r3d_opt(a, CP_W); + const RadTensor* b = r3d_opt(a, CP_B); + const RadTensor* alog = r3d_opt(a, CP_ALOG); + const RadTensor* dtb = r3d_opt(a, CP_DTB); + const RadTensor* cst = r3d_opt(a, CP_CSTATE); + const RadTensor* cu = r3d_opt(a, CP_CU); + const RadTensor* q = r3d_opt(a, CP_Q); + const RadTensor* k = r3d_opt(a, CP_K); + const RadTensor* v = r3d_opt(a, CP_V); + const RadTensor* g = r3d_opt(a, CP_G); + const RadTensor* beta = r3d_opt(a, CP_BETA); + const RadTensor* ta = r3d_opt(a, CP_A); + const RadTensor* tb = r3d_opt(a, CP_BGATE); + const RadTensor* cidx = r3d_opt(a, CP_CACHE_IDX); + const RadTensor* hin = r3d_opt(a, CP_HAS_INIT); + + if (!r3d_p(x) || !r3d_p(w) || !r3d_p(alog) || !r3d_p(dtb) || !r3d_p(cst) || !r3d_p(cu) || + !r3d_wp(q) || !r3d_wp(k) || !r3d_wp(v) || !r3d_wp(g) || !r3d_wp(beta)) + return R3D_NO(RAD_E_INVAL); + // Optional in the schema but required here: the kernel dereferences all three. + if (!r3d_p(ta) || !r3d_p(tb) || !r3d_p(cidx)) return R3D_NO(RAD_E_INVAL); + + if (x->rank < 2 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R3D_NO(RAD_E_SHAPE); + if (g->rank != 2 || beta->rank != 2 || cst->rank != 3 || ta->rank != 2) return R3D_NO(RAD_E_SHAPE); + + int N = 0; + if (seqs_of(cu, &N) != 0) return R3D_NO(RAD_E_SHAPE); + + const long long xpitch = r3d_row_pitch(x); + if (xpitch < 0) return R3D_NO(RAD_E_STRIDE); + const long long ab_stride = r3d_row_pitch(ta); + if (ab_stride < 0) return R3D_NO(RAD_E_STRIDE); + if (r3d_row_pitch(tb) != ab_stride) return R3D_NO(RAD_E_STRIDE); + + if (!r3d_contig(q) || !r3d_contig(k) || !r3d_contig(v) || !r3d_contig(g) || + !r3d_contig(beta) || !r3d_contig(w) || !r3d_contig(alog) || !r3d_contig(dtb)) + return R3D_NO(RAD_E_STRIDE); + if (cidx->rank < 1) return R3D_NO(RAD_E_SHAPE); + + const long long T = q->shape[0]; + const long long Hg = q->shape[1]; + const long long K = q->shape[2]; + const long long H = v->shape[1]; + const long long V = v->shape[2]; + if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3D_NO(RAD_E_SHAPE); + if (v->shape[0] != T) return R3D_NO(RAD_E_SHAPE); + if (g->shape[0] != T || g->shape[1] != H) return R3D_NO(RAD_E_SHAPE); + if (beta->shape[0] != T || beta->shape[1] != H) return R3D_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); + if (K != kHD || V != kHD) return R3D_NO(RAD_E_SHAPE); + + const int width = (int)r3d_geti_or(a, "conv_width", kW); + if (width != kW) return R3D_NO(RAD_E_SHAPE); + const float thr = (float)r3d_getf(a, "softplus_thr", 20.0); + if ((float)r3d_getf(a, "l2_eps", 1e-6) != 1e-6f) return R3D_NO(RAD_E_UNSUPPORTED); + const int ab_is_bf16 = (ta->dtype == RAD_BF16) ? 1 : 0; + if (tb->dtype != ta->dtype) return R3D_NO(RAD_E_DTYPE); + if (!ab_is_bf16 && ta->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + + if (!r3d_is_bf16(x) || !r3d_is_bf16(w) || !r3d_is_bf16(cst) || + !r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v) || + !r3d_is_f32(alog) || !r3d_is_f32(dtb) || !r3d_is_f32(g) || !r3d_is_f32(beta)) + return R3D_NO(RAD_E_DTYPE); + + return r3d_gdn_conv_prep_launch(r3d_p(x), xpitch, r3d_p(w), b ? r3d_p(b) : nullptr, r3d_wp(cst), + cst->stride[0], cst->stride[1], cst->stride[2], + r3d_p(cidx), cidx->stride[0], hin ? r3d_p(hin) : nullptr, + hin && (hin->dtype == RAD_I32 || hin->dtype == RAD_U32), + r3d_p(ta), r3d_p(tb), ab_stride, ab_is_bf16, + r3d_p(alog), r3d_p(dtb), r3d_wp(q), r3d_wp(k), r3d_wp(v), + r3d_wp(g), r3d_wp(beta), r3d_p(cu), + N, (int)T, (int)H, (int)Hg, width, thr, (hipStream_t)s); +} + +/* ------------------------------------------------------------------ the plugin ABI: conv update */ + +enum { CU_X = 0, CU_W, CU_B, CU_CSTATE, CU_SIDX, CU_NACC, CU_CU, CU_Q, CU_K, CU_V }; + +extern "C" int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, CU_X); + const RadTensor* w = r3d_opt(a, CU_W); + const RadTensor* b = r3d_opt(a, CU_B); + const RadTensor* cst = r3d_opt(a, CU_CSTATE); + const RadTensor* sidx = r3d_opt(a, CU_SIDX); + const RadTensor* nacc = r3d_opt(a, CU_NACC); + const RadTensor* cu = r3d_opt(a, CU_CU); + const RadTensor* q = r3d_opt(a, CU_Q); + const RadTensor* k = r3d_opt(a, CU_K); + const RadTensor* v = r3d_opt(a, CU_V); + if (!r3d_p(x) || !r3d_p(w) || !r3d_p(cst) || !r3d_p(sidx) || !r3d_p(cu) || + !r3d_wp(q) || !r3d_wp(k) || !r3d_wp(v)) + return R3D_NO(RAD_E_INVAL); + if (cst->rank != 3 || q->rank != 3 || k->rank != 3 || v->rank != 3) return R3D_NO(RAD_E_SHAPE); + if (sidx->rank < 1) return R3D_NO(RAD_E_SHAPE); + + int N = 0; + if (seqs_of(cu, &N) != 0) return R3D_NO(RAD_E_SHAPE); + + const long long xpitch = r3d_row_pitch(x); + if (xpitch < 0) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(q) || !r3d_contig(k) || !r3d_contig(v) || !r3d_contig(w)) + return R3D_NO(RAD_E_STRIDE); + + const long long T = q->shape[0]; + const long long Hg = q->shape[1]; + const long long K = q->shape[2]; + const long long H = v->shape[1]; + const long long V = v->shape[2]; + if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); + if (v->shape[0] != T || k->shape[0] != T) return R3D_NO(RAD_E_SHAPE); + if (K != kHD || V != kHD) return R3D_NO(RAD_E_SHAPE); + + if (!r3d_is_bf16(x) || !r3d_is_bf16(w) || !r3d_is_bf16(cst) || + !r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v)) + return R3D_NO(RAD_E_DTYPE); + + const int width = (int)r3d_geti_or(a, "conv_width", kW); + const long long state_len_max = cst->shape[2]; + const long long mql = state_len_max - (width - 2); + if (width != kW || mql < 1) return R3D_NO(RAD_E_SHAPE); + + return r3d_gdn_conv_update_launch(r3d_p(x), xpitch, r3d_p(w), b ? r3d_p(b) : nullptr, + r3d_wp(cst), cst->stride[0], cst->stride[1], cst->stride[2], + (int)state_len_max, r3d_p(sidx), sidx->stride[0], + nacc ? r3d_p(nacc) : nullptr, r3d_wp(q), r3d_wp(k), r3d_wp(v), + r3d_p(cu), N, (int)H, (int)Hg, width, (int)mql, + (hipStream_t)s); +} diff --git a/libr3d/r3d_gdn_gated_norm_had_quant_i8.hip b/libr3d/r3d_gdn_gated_norm_had_quant_i8.hip new file mode 100644 index 00000000..c4b4bef9 --- /dev/null +++ b/libr3d/r3d_gdn_gated_norm_had_quant_i8.hip @@ -0,0 +1,183 @@ +/* r3d_gdn_gated_norm_had_quant_i8.hip -- the GDN block's gated RMS norm, block Hadamard and + * per-row int8 quantiser in one pass: out_proj's input on the 48 linear-attention layers (the + * fourth rotated site in a W4A8 layer). + * + * out = x * rsqrt(mean_head(x^2) + eps) * w * silu(z) + * + * Two extents: the RMS is per head (head_dim = 128), while the rotation and the int8 scale are + * per token over the flattened H*128. The reduction is segmented: a head is 128/VPL consecutive + * lanes, and the xor masks below that stay inside one head. + * + * HAD=128 VPL=4 32 lanes/head one head per rotation block + * HAD=256 VPL=8 16 lanes/head two heads per block + * HAD=512 VPL=16 8 lanes/head four heads per block + * + * At width 128 the rotation mixes only within a head; wider widths mix across heads. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" +#include "r3d_fwht.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kHEAD = 128; // head_dim + +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +__host__ __device__ __forceinline__ int r3d_act_threads(int M, int K) +{ + if (M <= 32) return 1024; + const int lim = K >= 8192 ? (1 << 24) : (K >= 4096 ? 120 : 72); + return M <= lim ? 512 : 256; +} + +template +__global__ __launch_bounds__(THR) void r3d_gdn_gated_norm_had_quant_i8_kernel( + const unsigned short* __restrict__ X, const unsigned short* __restrict__ Z, + const float* __restrict__ Wg, signed char* __restrict__ Q, float* __restrict__ S, + int K, long long xrow, long long zrow, int zgrp, int zblk, float eps, float rnorm) +{ + constexpr int VPL = HAD / 32, NW = THR / 32; + constexpr int LPH = kHEAD / VPL; // lanes spanned by one head + extern __shared__ float lds[]; + float* red = lds + K; + const int row = blockIdx.x; + const unsigned short* x = X + (size_t)row * xrow; + const unsigned short* z = Z + (size_t)row * zrow; + // zgrp != 0: Z is read in place from the interleaved qkvz projection (avoiding a `z_out[:] = z` + // copy per layer): element i is at (i / zblk) * zgrp + (i % zblk). zblk is a multiple of HAD, + // so a rotation block never straddles a group. + const int lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.f; + for (int blk = wave; blk < K / HAD; blk += NW) { + const int base = blk * HAD + lane * VPL; + const int zbase = zgrp ? (base / zblk) * zgrp + (base % zblk) : base; + float v[VPL]; + float ss = 0.f; +#pragma unroll + for (int j = 0; j < VPL; ++j) { + v[j] = bf16_to_f32(x[base + j]); + ss += v[j] * v[j]; + } + // segmented: masks below LPH never cross a head + ss = r3d_xor_sum(ss); + const float rms = __frsqrt_rn(ss * (1.f / (float)kHEAD) + eps); +#pragma unroll + for (int j = 0; j < VPL; ++j) { + const float g = bf16_to_f32(z[zbase + j]); + v[j] = v[j] * rms * Wg[(base + j) & (kHEAD - 1)] * (g / (1.f + __expf(-g))); + } + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { + lds[base + j] = v[j]; + m = fmaxf(m, fabsf(v[j])); + } + } + + m = wave_max(m); + if (lane == 0) red[wave] = m; + R3D_BARRIER(); + m = red[0]; +#pragma unroll + for (int i = 1; i < NW; ++i) m = fmaxf(m, red[i]); + m = fmaxf(m, 1e-8f); + const float inv = 127.f / m; + if (threadIdx.x == 0) S[row] = m * rnorm / 127.f; + + signed char* q = Q + (size_t)row * K; + for (int i = threadIdx.x; i < K; i += THR) { + const int st = i >> 4, j = i & 15; + const int sr = (st << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = __float2int_rn(lds[sr] * inv); + q[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } +} + +int r3d_gdn_gated_norm_hq_i8_launch(const void* x, const void* z, const void* w, void* q, + void* sc, int M, int K, long long xrow, long long zrow, + int zgrp, int zblk, int had, float eps, hipStream_t stream) +{ + const float rn = 1.f / sqrtf((float)had); + const long long xr = xrow ? xrow : K, zr = zrow ? zrow : K; + const int thr = r3d_act_threads(M, K); + const size_t shmem = (size_t)K * sizeof(float) + (size_t)(thr / 32) * sizeof(float); + if (shmem > 65536) return -3; +#define R3D_GNHQ_LAUNCH(H, T) \ + R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_norm_had_quant_i8_kernel)), dim3((unsigned)M), \ + dim3(T), shmem, stream, (const unsigned short*)x, (const unsigned short*)z, \ + (const float*)w, (signed char*)q, (float*)sc, K, xr, zr, zgrp, zblk, eps, rn) +#define R3D_GNHQ_T(H) switch (thr) { \ + case 256: R3D_GNHQ_LAUNCH(H, 256); break; \ + case 512: R3D_GNHQ_LAUNCH(H, 512); break; \ + case 1024: R3D_GNHQ_LAUNCH(H, 1024); break; \ + default: return -2; } + switch (had) { + case 128: R3D_GNHQ_T(128); break; + case 256: R3D_GNHQ_T(256); break; + default: R3D_GNHQ_T(512); break; + } +#undef R3D_GNHQ_T +#undef R3D_GNHQ_LAUNCH + return (int)hipGetLastError(); +} + +} // namespace + +/* ------------------------------------------------------------------ the plugin ABI */ + +enum { GNH_X = 0, GNH_Z, GNH_W, GNH_Q, GNH_S }; + +extern "C" int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, GNH_X); + const RadTensor* z = r3d_opt(a, GNH_Z); + const RadTensor* w = r3d_opt(a, GNH_W); + const RadTensor* q = r3d_opt(a, GNH_Q); + const RadTensor* sc = r3d_opt(a, GNH_S); + if (!r3d_p(x) || !r3d_p(z) || !r3d_p(w) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_bf16(x) || !r3d_is_bf16(z) || !r3d_is_f32(w)) return R3D_NO(RAD_E_DTYPE); + if (q->dtype != RAD_I8 && q->dtype != RAD_U8) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(sc)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(q) || !r3d_contig(sc) || !r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); + + long long M = 0, K = 0; + if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_SHAPE); + const long long head = r3d_geti_or(a, "head_dim", kHEAD); + if (head != kHEAD) return R3D_NO(RAD_E_SHAPE); + if (K % kHEAD) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(w) != head) return R3D_NO(RAD_E_SHAPE); // wgain is 128 floats, not K + + const long long had = r3d_geti_or(a, "group", 0); + if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE); + // A rotation block cannot straddle a tensor-parallel shard boundary. + if (K % had) return R3D_NO(RAD_E_SHAPE); + + const long long xrow = r3d_row_pitch(x); + const long long zrow = r3d_row_pitch(z); + if (xrow < 0 || zrow < 0) return R3D_NO(RAD_E_STRIDE); + + // Interleaved-gate layout (see the kernel); zgrp 0 means contiguous. + const long long zgrp = r3d_geti_or(a, "zgrp", 0); + const long long zblk = r3d_geti_or(a, "zblk", 0); + if (zgrp && (zblk % had || zblk < had || zgrp < zblk)) return R3D_NO(RAD_E_INVAL); + + const float eps = (float)r3d_getf(a, "eps", 1e-6); + + return r3d_gdn_gated_norm_hq_i8_launch(r3d_p(x), r3d_p(z), r3d_p(w), r3d_wp(q), r3d_wp(sc), + (int)M, (int)K, xrow, zrow, (int)zgrp, (int)zblk, + (int)had, eps, (hipStream_t)s); +} diff --git a/libr3d/r3d_gdn_gated_rmsnorm_h128.hip b/libr3d/r3d_gdn_gated_rmsnorm_h128.hip new file mode 100644 index 00000000..baab437a --- /dev/null +++ b/libr3d/r3d_gdn_gated_rmsnorm_h128.hip @@ -0,0 +1,175 @@ +/* r3d_gdn_gated_rmsnorm_h128.hip -- the gated RMS norm a gated-delta-net layer applies to its + * own output before the output projection: + * + * out[r][d] = x[r][d] * rsqrt(mean_d(x[r][:]^2) + eps) * w[d] * act(z[r][d]) + * + * one row per (token, head), 128 wide; act is silu (the default) or sigmoid. Replaces FLA's + * rmsnorm_fn (mamba/ops/layernorm_gated). A separate row because the chunked scan's workgroup + * owns only 64 of a row's 128 v channels; the decode recurrent update owns whole rows and fuses + * this into its epilogue. + * + * One wave per row, four channels per lane: a barrier-free five-shuffle wave sum, and one 8-byte + * access per lane for each load and the store. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" + +#include +#include +#include + +namespace { + +constexpr int kD = 128; // channels per row +constexpr int kDPL = 4; // channels per lane +constexpr int kNW = 8; // rows in flight per workgroup +constexpr int kNTHR = kNW * 32; + +__device__ __forceinline__ float gn_act(float z, int kind) +{ + const float s = 1.0f / (1.0f + __expf(-z)); + return kind ? s : z * s; // 1 = sigmoid, 0 = silu / swish +} + +template +__global__ __launch_bounds__(kNTHR) +void r3d_gdn_gated_rmsnorm_kernel(const unsigned short* __restrict__ x, + const unsigned short* __restrict__ z, + const float* __restrict__ w, + unsigned short* __restrict__ o, + long long rows, long long xrow, long long zrow, + long long orow, long long zheads, long long ztok, float eps) +{ + const int lane = threadIdx.x & 31, warp = threadIdx.x >> 5; + const long long r = (long long)blockIdx.x * kNW + warp; + if (r >= rows) return; + const int d0 = lane * kDPL; + // The gate may be a column view of a fused [q|k|v|z] projection: within a token the `zheads` + // gate rows are `zrow` apart and the next token is `ztok` away. zheads <= 0 is the flat case. + const long long zoff = zheads > 0 ? (r / zheads) * ztok + (r % zheads) * zrow : r * zrow; + + const ushort4 xv = *(const ushort4*)(x + r * xrow + d0); + float v[kDPL] = {bf16_to_f32(xv.x), bf16_to_f32(xv.y), bf16_to_f32(xv.z), bf16_to_f32(xv.w)}; + + float ss = 0.0f; +#pragma unroll + for (int c = 0; c < kDPL; ++c) ss += v[c] * v[c]; + ss = wave_sum(ss); + const float scale = __frsqrt_rn(ss * (1.0f / kD) + eps); + + const ushort4 zv = *(const ushort4*)(z + zoff + d0); + const float zz[kDPL] = {bf16_to_f32(zv.x), bf16_to_f32(zv.y), + bf16_to_f32(zv.z), bf16_to_f32(zv.w)}; + const float4 ww = *(const float4*)(w + d0); + const float wv[kDPL] = {ww.x, ww.y, ww.z, ww.w}; + + unsigned short out[kDPL]; +#pragma unroll + for (int c = 0; c < kDPL; ++c) + out[c] = f32_to_bf16(v[c] * scale * wv[c] * gn_act(zz[c], ACT)); + *(ushort4*)(o + r * orow + d0) = make_ushort4(out[0], out[1], out[2], out[3]); +} + +int r3d_gdn_gated_rmsnorm_launch(const void* x, const void* z, const void* w, void* o, + long long rows, long long xrow, long long zrow, long long orow, + long long zheads, long long ztok, int act, float eps, + hipStream_t stream) +{ + dim3 grid((unsigned)((rows + kNW - 1) / kNW)), blk(kNTHR); + if (act) + R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_rmsnorm_kernel<1>)), grid, blk, 0, stream, + (const unsigned short*)x, (const unsigned short*)z, (const float*)w, + (unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps); + else + R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_gated_rmsnorm_kernel<0>)), grid, blk, 0, stream, + (const unsigned short*)x, (const unsigned short*)z, (const float*)w, + (unsigned short*)o, rows, xrow, zrow, orow, zheads, ztok, eps); + return (int)hipGetLastError(); +} + +} // namespace + +/* ------------------------------------------------------------------ the raw entry */ + +extern "C" int r3d_gdn_gated_rmsnorm_h128(long x, long z, long w, long o, long long rows, + long long xrow, long long zrow, long long orow, + long long zheads, long long ztok, int width, + float eps, int act, long stream) +{ + if (!x || !z || !w || !o) return -1; + if (width != kD || rows < 1) return -2; + return r3d_gdn_gated_rmsnorm_launch((const void*)x, (const void*)z, (const void*)w, (void*)o, + rows, xrow, zrow, orow, zheads, ztok, act, eps, + (hipStream_t)stream); +} + +/* ------------------------------------------------------------------ the plugin ABI */ + +enum { GN_X = 0, GN_Z, GN_W, GN_O }; + +/* The (token, head) row pitch of an operand whose last axis is `width`: the stride of the axis + * above it (the head axis), -1 when the layout does not put consecutive rows that far apart. */ +static long long gn_row_pitch(const RadTensor* t, long long width) +{ + if (!t || t->rank < 1) return -1; + if (t->shape[t->rank - 1] == width) { + if (t->stride[t->rank - 1] != 1) return -1; + return t->rank >= 2 ? t->stride[t->rank - 2] : width; + } + return r3d_contig(t) ? width : -1; +} + +extern "C" int r3d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, GN_X); + const RadTensor* z = r3d_opt(a, GN_Z); + const RadTensor* w = r3d_opt(a, GN_W); + const RadTensor* o = r3d_opt(a, GN_O); + if (!r3d_p(x) || !r3d_p(z) || !r3d_p(w) || !r3d_wp(o)) return R3D_NO(RAD_E_INVAL); + if (!r3d_is_bf16(x) || !r3d_is_bf16(z) || !r3d_is_bf16(o) || !r3d_is_f32(w)) + return R3D_NO(RAD_E_DTYPE); + if (x->rank < 2 || z->rank < 2 || o->rank < 2) return R3D_NO(RAD_E_SHAPE); + + if (!r3d_contig(w)) return R3D_NO(RAD_E_STRIDE); + + // One row is one (token, head). x and out are [tokens, heads, channels] (rank 3, as the chunk + // scan requires) while the gate may be the flat [tokens, heads*channels] projection. So the + // width comes from `channels` (or x's last axis), the row count from x, and each operand's + // pitch between consecutive (token, head) rows is read per its shape. + const long long width = r3d_geti_or(a, "channels", x->shape[x->rank - 1]); + if (width <= 0 || r3d_numel(x) % width) return R3D_NO(RAD_E_SHAPE); + const long long rows = r3d_numel(x) / width; + if (r3d_numel(z) < rows * width || r3d_numel(o) < rows * width) return R3D_NO(RAD_E_SHAPE); + + const long long xrow = gn_row_pitch(x, width); + const long long orow = gn_row_pitch(o, width); + if (xrow < 0 || orow < 0) return R3D_NO(RAD_E_STRIDE); + + // The gate may also be a column slice of a wider [q|k|v|z] row (fp8 delta net): heads are + // `width` apart within a token and tokens are the slice's stride apart, so the kernel also + // takes the head count. zheads stays 0 for the flat layouts. + long long zrow = gn_row_pitch(z, width), zheads = 0, ztok = 0; + if (zrow < 0 && z->rank == 2 && z->stride[1] == 1 && z->shape[1] % width == 0) { + zheads = z->shape[1] / width; + ztok = z->stride[0]; + zrow = width; + if (zheads <= 0 || rows % zheads) return R3D_NO(RAD_E_SHAPE); + if (x->rank >= 3 && x->shape[x->rank - 2] != zheads) return R3D_NO(RAD_E_SHAPE); + } + if (zrow < 0) return R3D_NO(RAD_E_STRIDE); + + const float eps = (float)r3d_getf(a, "eps", 1e-6); + const int act = r3d_act_code(a, "act", nullptr, -1); + if (act != 0 && act != 1) return R3D_NO(RAD_E_INVAL); + + return r3d_gdn_gated_rmsnorm_launch(r3d_p(x), r3d_p(z), r3d_p(w), r3d_wp(o), + rows, xrow, zrow, orow, zheads, ztok, + act, eps, (hipStream_t)s); +} diff --git a/libr3d/r3d_gdn_kkt_solve_c64.hip b/libr3d/r3d_gdn_kkt_solve_c64.hip new file mode 100644 index 00000000..bbf0388b --- /dev/null +++ b/libr3d/r3d_gdn_kkt_solve_c64.hip @@ -0,0 +1,475 @@ +/* r3d_gdn_kkt_solve_c64.hip -- the gated-delta-net chunk preamble in one kernel: + * + * A = (I + strict_lower(diag(beta) . K K^T . e^{g_i - g_j}))^{-1} per chunk of 64 + * + * The FLA chunk_scaled_dot_kkt_fwd + solve_tril pair, fused: the gram stays in LDS and only the + * bf16 inverse is stored. The gram is computed once per k head, not per v head: K K^T does not + * depend on beta or g, so one workgroup owns a (chunk, k head) and applies each v head's scales + * to it. The decay is applied per element as e^{g_i-g_j}, not split about a per-chunk reference: + * each half of e^{g_i-c} * e^{c-g_j} can overflow fp32 on its own, and the exponent is always + * <= 0 here (g decreases along the chunk and only i > j is kept). + * + * The inverse is blocked 16 -> 32 -> 64. The four diagonal blocks use fp32 forward substitution + * (one wave each, one lane per column), cheaper than a WMMA Neumann series at this size and exact + * in fp32, as in FLA. The 32-merges and the 64-merge are wave-matrix, using + * + * [[P, 0], [R, Q]]^-1 = [[P^-1, 0], [-Q^-1 R P^-1, Q^-1]] + * + * mma(X, Y) computes X . Y^T from two k-contiguous operands, so a left operand is row-major and a + * right operand is stored transposed. The intermediates are staged transposed in the 32x32 + * scratch; the final inverse is assembled row-major for the HBM store. + * + * ---- the tile map (the port's one structural change) --------------------------------------- + * + * The source row was written for the wave-matrix ISA of the card it was probed on, whose + * 16x16x16 fragment map differs from this card's. This card's map (probed in the bf16 GEMM row, + * r3d_gemm_bf16_nt_m16_wmma.hip): + * + * A fragment: lane L holds row L % 16 of the tile, the 16 k contiguous + * B fragment: lane L holds column L % 16 of the tile, the 16 k contiguous + * C/D: lane L, element e holds D[2e + L / 16][L % 16], eight f32 a lane + * + * so the fragment loads are the bf16 GEMM row's 32-byte reads, and every accumulator store that + * the source row made as one 16-byte vector is here eight scalar bf16 stores along the map's + * stride-2 axis. The transposed-operand reads (fragT) keep the source's lane-to-row assignment, + * which the two ISAs share. + * + * The blocked inverse reads the blocks it overwrites before writing them, with barriers between + * stages, so one 64x64 buffer plus a 32x32 scratch carries the whole solve: 11 KiB of LDS. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" + +#include +#include +#include + +namespace { + +constexpr int kBT = 64; // chunk +constexpr int kKD = 128; // head_k +constexpr int kNBK = 4; // 16x16 blocks per chunk edge +constexpr int kAP = 68; // row pitch of the [BT][BT] buffers, in shorts: 8-byte aligned + // for the store, and 16 rows still cover every bank +constexpr int kNW = 4; +constexpr int kNTHR = kNW * 32; +constexpr int kNTILE = 10; // upper-triangular tiles of a 4x4 tiling +constexpr int kMAXT = (kNTILE + kNW - 1) / kNW; + +using v8f = float __attribute__((ext_vector_type(8))); +using v16short = short __attribute__((ext_vector_type(16))); + +/* One 16x16x16 tile, f32 accumulate. */ +__device__ __forceinline__ v8f mmab(const v16short& a, const v16short& b, const v8f& c) +{ + return __builtin_amdgcn_wmma_f32_16x16x16_bf16_w32(a, b, c); +} + +/* A/B fragment from a row pointer already advanced to this lane's row and half-K: the 16 k + * contiguous, 32 bytes, two 16-byte reads. The row pitches are multiples of 4 shorts and the + * kbase is a multiple of 16, so the 16-byte alignment the reads need holds. */ +__device__ __forceinline__ v16short fragP(const unsigned short* p) +{ + // The GEMM row's exact form: load a uint4, bit-cast it. Loading the ext-vector type + // directly lowers differently on this backend and corrupts the fragment. + union { r3d_u32x4 w[2]; v16short f; } u; + u.w[0] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); + u.w[1] = __builtin_bit_cast(r3d_u32x4, *(const uint4*)(p + 8)); + return u.f; +} + +/* Global fragment off a 32-bit element offset split from a uniform base: the immediate-offset + * form the bf16 GEMM row's note describes. The row is clamped at the call site so a partial last + * chunk cannot read past the tensor (those rows are discarded downstream). */ +__device__ __forceinline__ v16short fragGo(const unsigned short* base, unsigned off) +{ + return fragP(base + off); +} + +/* K-contiguous fragment: src[idx][k], row pitch `pitch` (in elements). */ +__device__ __forceinline__ v16short frag(const unsigned short* src, int pitch, int base, + int kbase, int lane) +{ + return fragP(src + (size_t)(base + (lane & 15)) * pitch + kbase); +} + +/* Same fragment but the source is stored transposed: src[k][idx]. Sixteen scalar reads. */ +__device__ __forceinline__ v16short fragT(const unsigned short* src, int pitch, int base, + int kbase, int lane) +{ + const int idx = base + (lane & 15); + union { unsigned short h[16]; v16short f; } u; +#pragma unroll + for (int e = 0; e < 16; ++e) + u.h[e] = src[(size_t)(kbase + e) * pitch + idx]; + return u.f; +} + +/* C[mt*16 .. ][nt*16 .. ] += A[M][K] @ B[N][K]^T over KSTEP 16-wide steps. */ +template +__device__ __forceinline__ v8f gemm16(const unsigned short* A, int Ap, int mt, + const unsigned short* B, int Bp, int nt, + int lane, v8f acc) +{ +#pragma unroll + for (int s = 0; s < KSTEP; ++s) + acc = mmab(frag(A, Ap, mt * 16, s * 16, lane), frag(B, Bp, nt * 16, s * 16, lane), acc); + return acc; +} + +/* A block barrier the backend cannot move; see the GEMM rows' note. */ +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +/* The chunk's buffers. One 64x64 buffer plus a 32x32 scratch. ST is a staging line: every + * scattered store out of a wmma accumulator goes through it first. A scattered store issued + * directly from the accumulator registers is miscompiled on this backend (the wmma result is + * corrupted by the store's address arithmetic); a contiguous lane-major store into LDS, a + * barrier, and the scatter out of LDS is the proven safe form. */ +struct KkSmem { + unsigned short A[kBT][kAP]; // A on the way in, its inverse on the way out + unsigned short TMP[32][36]; // one 32x32 intermediate, transposed + float ST[kNTHR * 8]; // one gram round (128 threads x 8), contiguous per thread + float gb[kBT], bt[kBT]; // the chunk's gate cumsum and beta, per token +}; + +/* (mt, nt) of upper-triangular tile ti, computed with wave-uniform arithmetic instead of a + * table load. */ +__device__ __forceinline__ void kkt_tile(int ti, int* mt, int* nt) +{ + int m = 0, n = ti; + while (n >= kNBK - m) { n -= (kNBK - m); ++m; } + *mt = m; *nt = n + m; +} + +template +__global__ __launch_bounds__(kNTHR) +void r3d_gdn_kkt_solve_kernel(const unsigned short* __restrict__ k, + const float* __restrict__ beta, + const float* __restrict__ g, + unsigned short* __restrict__ Ao, + const int* __restrict__ cu, + int N, int H, int Hg) +{ + __shared__ KkSmem s; + int tid = threadIdx.x; + asm volatile("" : "+v"(tid)); // pin the hw thread-id vreg before the allocator can reuse it + const int lane = tid & 31, warp = tid >> 5; + const int lo = lane & 15, hi = lane >> 4; + const int hg = blockIdx.y; + + // Resolve the flat chunk id to (sequence, chunk). The grid is an upper bound on the chunk + // count, so surplus workgroups exit here; this saves the host a device-to-host sync to size + // the grid exactly. + int n = -1, t0 = 0, bos = 0, rows = 0; + { + int acc = 0, want = blockIdx.x; + for (int i = 0; i < N; ++i) { + const int b = cu[i], e = cu[i + 1]; + const int nc = (e - b + kBT - 1) / kBT; + if (want < acc + nc) { n = i; bos = b; t0 = (want - acc) * kBT; + rows = std::min(kBT, e - b - t0); break; } + acc += nc; + } + if (n < 0) return; + } + + // ---- zero A once: the parts no store reaches (the upper tiles) are the same for every head. + // 16-byte stores (the buffer is 8704 bytes, 16-byte aligned). + for (int i = tid; i < kBT * kAP / 8; i += kNTHR) ((uint4*)&s.A[0][0])[i] = make_uint4(0, 0, 0, 0); + + // ---- the gram, once for all HG_RATIO v heads of this k head ----------------------------- + const unsigned short* kp = k + ((size_t)(bos + t0) * Hg + hg) * kKD; + const unsigned krow = (unsigned)(Hg * kKD); + // The gram, once for all v heads: tile (mt, nt) of P is staged lane-contiguous into ST and + // then parked in A's upper triangle, where A is zero. An off-diagonal tile goes into the + // (mt, nt) slot; a diagonal tile goes straight into its (nt, mt) target slot, so the + // per-head pass below is an in-place scale for it (no cross-lane read/write on one tile). +#pragma unroll + for (int t = 0; t < kMAXT; ++t) { + const int ti = warp + t * kNW; + v8f P = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + if (ti < kNTILE) { + int mt, nt; kkt_tile(ti, &mt, &nt); + // One 32-bit offset per operand row, hoisted out of the k loop. + const unsigned om = (unsigned)(std::min(mt * 16 + (lane & 15), rows - 1)) * krow; + const unsigned on = (unsigned)(std::min(nt * 16 + (lane & 15), rows - 1)) * krow; +#pragma unroll + for (int sk = 0; sk < kKD / 16; ++sk) { + const v16short fa = fragGo(kp, om + sk * 16); + const v16short fb = fragGo(kp, on + sk * 16); + + P = mmab(fa, fb, P); + } + } + +#pragma unroll + for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = P[e]; + R3D_BARRIER(); + if (ti < kNTILE) { + int mt, nt; kkt_tile(ti, &mt, &nt); +#pragma unroll + for (int e = 0; e < 8; ++e) { + if (mt == nt) + s.A[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); + else + s.A[mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]); + } + } + } + R3D_BARRIER(); + + for (int hh = 0; hh < HG_RATIO; ++hh) { + const int hv = hg * HG_RATIO + hh; + + // ---- per-head gate and beta for this chunk + if (tid < kBT) { + const int t = std::min(tid, rows - 1); + s.gb[tid] = g[(size_t)(bos + t0 + t) * H + hv]; + s.bt[tid] = beta[(size_t)(bos + t0 + t) * H + hv]; + } + R3D_BARRIER(); + + // ---- scale, mask and place the gram as the strictly lower half of A ----------------- + // Element e of tile (mt, nt) lands at A[i = nt*16 + lo][j = mt*16 + 2e + hi], the lower + // triangle when i > j. Off-diagonal tiles were parked transposed at A[j][i], so the + // scale reads that slot; diagonal tiles are scaled in place. +#pragma unroll + for (int t = 0; t < kMAXT; ++t) { + const int ti = warp + t * kNW; + if (ti < kNTILE) { + int mt, nt; kkt_tile(ti, &mt, &nt); + const int i = nt * 16 + lo; // row of A + const bool live = (i < rows); + const float bi = live ? s.bt[i] : 0.0f; + const float gi = live ? s.gb[i] : 0.0f; +#pragma unroll + for (int e = 0; e < 8; ++e) { + const int j = mt * 16 + 2 * e + hi; + const float pv = (mt == nt) ? bf16_to_f32(s.A[i][j]) + : bf16_to_f32(s.A[j][i]); + // For a live row, i > j gives g_i <= g_j, so the exponent is never positive. + // Padding rows and columns must be masked to -inf: with gi = 0 the exponent + // -gb[j] is large and positive, 0 * inf = NaN, and the WMMA merges in the + // blocked inverse would spread it into live rows. + const float d = (live && i > j && j < rows) ? (gi - s.gb[j]) : -INFINITY; + s.A[i][j] = f32_to_bf16(bi * __expf(d) * pv); + } + } + } + + R3D_BARRIER(); + + // ---- 1. the four diagonal blocks, by fp32 forward substitution ---------------------- + // D = (I + N)^-1 solves D = I - N D row by row. Lane l owns column l of D, so the dot + // product over j < i is in 16 registers and N[i][j] is a broadcast LDS read. + for (int p = warp; p < kNBK; p += kNW) { + const int b0 = p * 16; + float d[16]; +#pragma unroll + for (int i = 0; i < 16; ++i) { + float acc = 0.0f; +#pragma unroll + for (int j = 0; j < 16; ++j) + if (j < i) acc += bf16_to_f32(s.A[b0 + i][b0 + j]) * d[j]; + d[i] = ((lo == i) ? 1.0f : 0.0f) - acc; + } + if (lane < 16) { +#pragma unroll + for (int i = 0; i < 16; ++i) s.A[b0 + i][b0 + lo] = f32_to_bf16(d[i]); + } + } + R3D_BARRIER(); + + // ---- 2. the two 32-merges: M10 = -D1 A10 D0 ----------------------------------------- + for (int blk = warp; blk < 2; blk += kNW) { + const int r0 = blk * 32; // 32-block origin + // X = A10 . D0 (left A10 row-major, right D0 transposed) + v8f X = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + const v16short af = frag(&s.A[0][0], kAP, r0 + 16, r0, lane); + X = mmab(af, fragT(&s.A[0][0], kAP, r0, r0, lane), X); + // Stage X lane-contiguous, then scatter it out of ST (see the KkSmem note). The + // stage is transposed for the next product: TMP[n][m] = X[m][n], and element e is + // X[m = 2e + hi][n = lo]. Each of the two merges owns 16 rows of TMP. +#pragma unroll + for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = X[e]; + R3D_BARRIER(); +#pragma unroll + for (int e = 0; e < 8; ++e) + s.TMP[blk * 16 + lo][2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); + R3D_BARRIER(); + // M10 = -D1 . X (left D1 row-major, in place in A; right X transposed, in TMP) + v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; + Y = mmab(frag(&s.A[0][0], kAP, r0 + 16, r0 + 16, lane), + frag(&s.TMP[0][0], 36, blk * 16, 0, lane), Y); +#pragma unroll + for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e]; + R3D_BARRIER(); + // Element e is A[r0 + 16 + 2e + hi][r0 + lo]. +#pragma unroll + for (int e = 0; e < 8; ++e) + s.A[r0 + 16 + 2 * e + hi][r0 + lo] = f32_to_bf16(-s.ST[tid * 8 + e]); + } + R3D_BARRIER(); + + + R3D_BARRIER(); + + // Flip the sign of the R block with a binary subtraction. In this kernel context the + // compiler drops unary minus on the 64-merge accumulator store, so the overall minus + // of M[32:,:32] = -Q^-1 (R P^-1) is carried by the negated R: the merge computes + // Q^-1 . (-R) . P^-1 and stores it as-is. (Flipping Q^-1 in place instead breaks its + // final value, because the restoring flip is dropped in the same way.) + for (int idx = tid; idx < 32 * 32; idx += kNTHR) { + const int r = 32 + idx / 32, c = idx % 32; + s.A[r][c] = f32_to_bf16(0.0f - bf16_to_f32(s.A[r][c])); + } + R3D_BARRIER(); + + // ---- 3. the 64-merge: M[32:,:32] = -Q^-1 (R P^-1) ----------------------------------- + // Y = R . P^-1, R = A[32:,:32] row-major, P^-1 read transposed out of A[:32,:32] + for (int t = warp; t < 4; t += kNW) { + const int mt = t >> 1, nt = t & 1; + v8f Y = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int sk = 0; sk < 2; ++sk) + Y = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, sk * 16, lane), + fragT(&s.A[0][0], kAP, nt * 16, sk * 16, lane), Y); + // Stage Y lane-contiguous for the transposed scatter below. +#pragma unroll + for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Y[e]; + } + R3D_BARRIER(); + // TMP[n][m] = Y[m][n]; element e is Y[m = 2e + hi (within the mt tile)][n = lo + // (within the nt tile)]. + for (int t = warp; t < 4; t += kNW) { + const int mt = t >> 1, nt = t & 1; +#pragma unroll + for (int e = 0; e < 8; ++e) + s.TMP[nt * 16 + lo][mt * 16 + 2 * e + hi] = f32_to_bf16(s.ST[tid * 8 + e]); + } + R3D_BARRIER(); // every wave has read R into TMP; now it may be overwritten + // Z = -Q^-1 . Y, Q^-1 = A[32:,32:] row-major, Y transposed = TMP + for (int t = warp; t < 4; t += kNW) { + const int mt = t >> 1, nt = t & 1; + v8f Z = (v8f){0, 0, 0, 0, 0, 0, 0, 0}; +#pragma unroll + for (int sk = 0; sk < 2; ++sk) + Z = mmab(frag(&s.A[0][0], kAP, 32 + mt * 16, 32 + sk * 16, lane), + frag(&s.TMP[0][0], 36, nt * 16, sk * 16, lane), Z); +#pragma unroll + for (int e = 0; e < 8; ++e) s.ST[tid * 8 + e] = Z[e]; + } + R3D_BARRIER(); + for (int t = warp; t < 4; t += kNW) { + const int mt = t >> 1, nt = t & 1; + // Element e is A[32 + mt*16 + 2e + hi][nt*16 + lo]. This wmma instance + // negates its product on this toolchain, so the minus belongs to it: + // store the accumulator as-is. +#pragma unroll + for (int e = 0; e < 8; ++e) + s.A[32 + mt * 16 + 2 * e + hi][nt * 16 + lo] = f32_to_bf16(s.ST[tid * 8 + e]); + } + R3D_BARRIER(); + + // Clear the upper-triangular parking slots (they still hold gram values) so the + // stored matrix is a clean lower-triangular inverse. + for (int idx = tid; idx < 64 * 64; idx += kNTHR) { + const int r = idx / 64, c = idx % 64; + if (c > r) s.A[r][c] = 0; + } + R3D_BARRIER(); + + + // ---- store: one row of the inverse is 64 bf16, contiguous in HBM --------------------- + { + unsigned short* op = Ao + ((size_t)(bos + t0) * H + hv) * kBT; + const size_t orow = (size_t)H * kBT; + for (int r = tid / 8; r < rows; r += kNTHR / 8) { + const int c8 = (tid & 7) * 8; + *(uint4*)(op + (size_t)r * orow + c8) = *(const uint4*)(&s.A[r][c8]); + } + } + if (hh + 1 < HG_RATIO) R3D_BARRIER(); + } +} + +int r3d_gdn_kkt_solve_launch(const void* k, const void* beta, const void* g, void* A, + const void* cu, int N, int T, int H, int Hg, int K, int chunk, + hipStream_t stream) +{ + if (K != kKD || chunk != kBT) return -1; + if (H % Hg) return -2; + const int nchunk_ub = (T + kBT - 1) / kBT + N; // sum of per-sequence chunk counts, bounded + dim3 grid(nchunk_ub, Hg), blk(kNTHR); +#define R3D_KKLAUNCH(R) \ + R3D_KLAUNCH_S(R3D_KNAME((r3d_gdn_kkt_solve_kernel)), grid, blk, 0, stream, \ + (const unsigned short*)k, (const float*)beta, (const float*)g, \ + (unsigned short*)A, (const int*)cu, N, H, Hg) + switch (H / Hg) { + case 1: R3D_KKLAUNCH(1); break; + case 2: R3D_KKLAUNCH(2); break; + case 3: R3D_KKLAUNCH(3); break; + case 4: R3D_KKLAUNCH(4); break; + case 6: R3D_KKLAUNCH(6); break; + case 8: R3D_KKLAUNCH(8); break; + default: return -3; + } +#undef R3D_KKLAUNCH + return (int)hipGetLastError(); +} + +} // namespace + +/* ------------------------------------------------------------------ the raw entry */ + +extern "C" int r3d_gdn_kkt_solve_c64(long k, long beta, long g, long A, long cu, + int N, int T, int H, int Hg, int K, int chunk, + long stream) +{ + if (!k || !beta || !g || !A || !cu) return -1; + if (N < 1 || T < 1) return -2; + if (H < 1 || Hg < 1) return -2; + return r3d_gdn_kkt_solve_launch((const void*)k, (const void*)beta, (const void*)g, (void*)A, + (const void*)cu, N, T, H, Hg, K, chunk, (hipStream_t)stream); +} + +/* ------------------------------------------------------------------ the plugin ABI */ + +enum { QK_K = 0, QK_BETA, QK_G, QK_CU, QK_A }; + +extern "C" int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* kt = r3d_opt(a, QK_K); + const RadTensor* bt = r3d_opt(a, QK_BETA); + const RadTensor* gt = r3d_opt(a, QK_G); + const RadTensor* cu = r3d_opt(a, QK_CU); + const RadTensor* Ao = r3d_opt(a, QK_A); + if (!r3d_p(kt) || !r3d_p(bt) || !r3d_p(gt) || !r3d_p(cu) || !r3d_wp(Ao)) + return R3D_NO(RAD_E_INVAL); + if (!r3d_is_bf16(kt) || !r3d_is_f32(bt) || !r3d_is_f32(gt) || !r3d_is_i32(cu) || + !r3d_is_bf16(Ao)) + return R3D_NO(RAD_E_DTYPE); + + if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE); + const int N = (int)(cu->shape[0] - 1); + + const long long T = r3d_dim(kt, 0), Hg = r3d_dim(kt, 1), K = r3d_dim(kt, 2); + const long long H = r3d_dim(bt, 1), chunk = r3d_dim(Ao, 2); + if (r3d_dim(gt, 0) != T || r3d_dim(gt, 1) != H || r3d_dim(bt, 0) != T) + return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(Ao, 0) != T || r3d_dim(Ao, 1) != H) return R3D_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(kt) || !r3d_contig(bt) || !r3d_contig(gt) || !r3d_contig(Ao)) + return R3D_NO(RAD_E_STRIDE); + + return r3d_gdn_kkt_solve_launch(r3d_p(kt), r3d_p(bt), r3d_p(gt), r3d_wp(Ao), r3d_p(cu), + N, (int)T, (int)H, (int)Hg, (int)K, (int)chunk, + (hipStream_t)s); +} diff --git a/libr3d/r3d_gdn_recurrent_update_k128_v128.hip b/libr3d/r3d_gdn_recurrent_update_k128_v128.hip new file mode 100644 index 00000000..f1cd2308 --- /dev/null +++ b/libr3d/r3d_gdn_recurrent_update_k128_v128.hip @@ -0,0 +1,350 @@ +/* r3d_gdn_recurrent_update_k128_v128.hip -- the gated-delta-net recurrent state update, run by + * + * STATUS: the loop-restructure workaround is in; the value probe is the remaining gate. Three + * compiler bugs were found, two worked around outright and the third around by loop shape: + * + * 1. A DPP shuffle (__shfl_xor) inside the token loop miscompiles: 48 of the 256 threads drop + * out and the row's stores never land. Worked around: every cross-lane exchange (the l2 + * norms, the S k / S q closes, the gated-norm wave sum) goes through an __shared__ scratch + * instead of a shuffle. + * + * 2. As a template the kernel's device code is present and the launch + * succeeds, but the kernel never runs (not even a prologue sentinel lands), while a plain + * kernel in the same file runs fine. Worked around: the kernel is plain; norm and ab_bf16 + * are runtime parameters. + * + * 3. With both fixes in, the loop was compiler-sensitive: the fused in-loop pair (the state + * update h[j] += u*kk[j] with the on accumulation) plus the third cross-lane exchange and + * the o write produced a kernel whose token loop did not land its o stores, while + * near-identical variants did. The trigger is a specific interaction of the 64-element + * register state, the LDS exchanges and the o write; it has not been reduced to a minimal + * repro. Worked around: the update and the o dot run as separate loops, and the o store is + * volatile. The value probe is the gate. + * + * decode (prefill runs the chunked scan). One kernel for the whole step: + * + * g = -exp(A_log) . softplus(a + dt_bias) beta = sigmoid(b) q, k l2-normalised + * S *= e^g + * u = beta . (v - S k) S += u k^T o = S q + * + * per token, against a paged state cache: the initial state is read from the slot the step's + * tokens leave, and every token writes its own slot. The state stays in registers: one thread + * owns one v row and half its k range, so + * + * * S k and S q are in-lane dot products closed by a single lane<->lane^1 exchange, not a tree; + * * the outer-product update is 64 independent FMAs with no cross-lane traffic; + * * a thread's 64 state elements are contiguous in k, so the load and every store is eight + * 8-byte accesses over one 256-byte run. + * + * The cross-lane exchanges (the l2 norms, the S k and S q closes, the gated-norm wave sum) go + * through LDS, not a shuffle. A DPP shuffle inside the token loop miscompiles on gfx1102: with + * the lane<->lane^1 __shfl_xor in the loop, 48 of the 256 threads drop out and the row's stores + * never land. Routing the same exchange through a __shared__ scratch (one store, a barrier, one + * read of the neighbour) is correct and costs a barrier per token. + * + * This is the non-speculative core: a step's tokens are the cu window (width 1 for a plain + * decode step), the state cache is fp32, and the gated RMS norm is folded into the epilogue + * (z and norm_w present) or omitted. The speculative anchor, the folded decode convolution and + * the folded out-projection quantiser are not part of this row. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_args.h" +#include "r3d_codecs.h" + +#include +#include +#include +#include + +namespace { + +constexpr int kK = 128; // head_k +constexpr int kV = 128; // head_v +constexpr int kHK = 64; // k elements per thread (kK / 2) +constexpr int kTHR = kV * 2; // two threads per v row + +typedef float ru_f4 __attribute__((ext_vector_type(4))); + +template +__device__ __forceinline__ void ru_load8(float* d, const float* p) +{ + const ru_f4* q = (const ru_f4*)p; + *(ru_f4*)d = NT ? __builtin_nontemporal_load(q) : *q; + *(ru_f4*)(d + 4) = NT ? __builtin_nontemporal_load(q + 1) : *(q + 1); +} + +template +__device__ __forceinline__ void ru_store8(float* p, const float* d) +{ + ru_f4* q = (ru_f4*)p; + if (NT) { + __builtin_nontemporal_store(*(const ru_f4*)d, q); + __builtin_nontemporal_store(*(const ru_f4*)(d + 4), q + 1); + } else { + *q = *(const ru_f4*)d; + *(q + 1) = *(const ru_f4*)(d + 4); + } +} + +__device__ __forceinline__ float ru_softplus(float x, float thr) +{ + if (x > thr) return x; + return (x > 0.0f) ? (x + __logf(1.0f + __expf(-x))) : __logf(1.0f + __expf(x)); +} + +template +__device__ __forceinline__ float ru_ab(const void* p, size_t i) +{ + return ABF16 ? bf16_to_f32(((const unsigned short*)p)[i]) : ((const float*)p)[i]; +} + +__device__ __forceinline__ float ru_act(float z, int kind) +{ + const float s = 1.0f / (1.0f + __expf(-z)); + return kind ? s : z * s; +} + +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +/* norm: 0 = no epilogue norm, 1 = sigmoid, 2 = silu (the row's `act`). ab_bf16: a/b are bf16. + * A plain kernel, not a template: on gfx1102 the template instantiation miscompiles (the device + * code is present and the launch succeeds, but the kernel never runs -- not even a prologue + * sentinel lands, while a plain kernel in the same file runs fine). */ +__global__ __launch_bounds__(kTHR) +void r3d_gdn_recurrent_update_kernel(const unsigned short* __restrict__ q, + const unsigned short* __restrict__ k, + const unsigned short* __restrict__ v, + const void* __restrict__ av, const void* __restrict__ bv, + long long ab_stride, + const float* __restrict__ A_log, const float* __restrict__ dt_bias, + float* __restrict__ state, + long long st_slot, long long st_head, + const int* __restrict__ sidx, long long sidx_stride, + const unsigned short* __restrict__ zg, long long zg_pitch, + const float* __restrict__ nw, + unsigned short* __restrict__ o, + const int* __restrict__ cu, int H, int Hg, + float scale, float sp_thr, float neps, + int norm, int ab_bf16) +{ + const int tid = threadIdx.x; + const int row = (tid >> 1), half = tid & 1, k0 = half * kHK; + const int n = blockIdx.x, hv = blockIdx.y; + const int bos = cu[n], T = cu[n + 1] - bos; + if (T <= 0) return; + const int hk = hv / (H / Hg); + + /* Read early so their latency overlaps the state load. */ + const float a_log_h = A_log[hv], dtb = dt_bias[hv]; + const float alog = __expf(a_log_h); + + float h[kHK]; + { + const float* p = state + (size_t)sidx[(size_t)n * sidx_stride] * st_slot + + (size_t)hv * st_head + (size_t)row * kK + k0; +#pragma unroll + for (int j = 0; j < kHK; j += 8) ru_load8<0>(&h[j], p + j); + } + + // LDS scratch for the cross-lane exchanges. ex holds the per-thread value being exchanged + // (lane<->lane^1, or a full wave for the gated norm); wsum holds the eight wave sums. + __shared__ float ex[2 * kTHR]; + __shared__ float wsum[kTHR / 32]; + + for (int t = 0; t < T; ++t) { + const int tok = bos + t; + const unsigned short* qp = q + ((size_t)tok * Hg + hk) * kK + k0; + const unsigned short* kp = k + ((size_t)tok * Hg + hk) * kK + k0; + + float qq[kHK], kk[kHK]; + for (int j = 0; j < kHK; ++j) { qq[j] = bf16_to_f32(qp[j]); kk[j] = bf16_to_f32(kp[j]); } + + // l2 norms: 64 in-lane terms, then one exchange with the lane holding the other half. + // (LDS, not a shuffle -- a DPP in this loop miscompiles on gfx1102.) + float sq = 0.0f, sk = 0.0f; + for (int j = 0; j < kHK; ++j) { sq += qq[j] * qq[j]; sk += kk[j] * kk[j]; } + ex[tid] = sq; ex[tid + kTHR] = sk; + R3D_BARRIER(); + sq += ex[tid ^ 1]; sk += ex[tid ^ 1 + kTHR]; + const float qs = __frsqrt_rn(sq + 1e-6f) * scale, ks = __frsqrt_rn(sk + 1e-6f); + for (int j = 0; j < kHK; ++j) { qq[j] *= qs; kk[j] *= ks; } + + const size_t ab_i = (size_t)tok * ab_stride + hv; + const float ra = ab_bf16 ? bf16_to_f32(((const unsigned short*)av)[ab_i]) : ((const float*)av)[ab_i]; + const float rb = ab_bf16 ? bf16_to_f32(((const unsigned short*)bv)[ab_i]) : ((const float*)bv)[ab_i]; + const float g = -alog * ru_softplus(ra + dtb, sp_thr); + const float bt = 1.0f / (1.0f + __expf(-rb)); + const float eg = __expf(g); + + float dot = 0.0f; + for (int j = 0; j < kHK; ++j) { h[j] *= eg; dot += h[j] * kk[j]; } + ex[tid] = dot; + R3D_BARRIER(); + dot += ex[tid ^ 1]; + + const float vraw = bf16_to_f32(v[((size_t)tok * H + hv) * kV + row]); + const float u = (vraw - dot) * bt; + + // The outer-product update and the o dot run as separate loops: fused, with the + // third exchange and the o write live, the token loop's o stores stopped landing on + // gfx1102 (a compiler interaction, not reduced to a minimal repro); split, they land. + for (int j = 0; j < kHK; ++j) h[j] += u * kk[j]; + float on = 0.0f; + for (int j = 0; j < kHK; ++j) on += h[j] * qq[j]; + ex[tid] = on; + R3D_BARRIER(); + on += ex[tid ^ 1]; + + if (norm) { + ex[tid] = (half == 0) ? on * on : 0.0f; + R3D_BARRIER(); + const int wave = tid >> 5; + float s = 0.0f; + for (int i = 0; i < 32; ++i) s += ex[wave * 32 + i]; + if ((tid & 31) == 0) wsum[wave] = s; + R3D_BARRIER(); + float tot = 0.0f; + for (int i = 0; i < kTHR / 32; ++i) tot += wsum[i]; + const float sc = __frsqrt_rn(tot * (1.0f / kV) + neps); + const unsigned short zr = zg[(size_t)tok * zg_pitch + (size_t)hv * kV + row]; + on *= sc * nw[row] * ru_act(bf16_to_f32(zr), norm); + R3D_BARRIER(); + } + + const unsigned short ob = f32_to_bf16(on); + if (half == 0) { + // Volatile: the plain store was the one the compiler dropped in the fused form. + volatile unsigned short* ov = o; + ov[((size_t)tok * H + hv) * kV + row] = ob; + } + + const int so = sidx[(size_t)n * sidx_stride + t]; + if (so >= 0) { + float* p = state + (size_t)so * st_slot + (size_t)hv * st_head + + (size_t)row * kK + k0; + for (int j = 0; j < kHK; j += 8) ru_store8<0>(p + j, &h[j]); + } + } +} + +int r3d_gdn_recurrent_update_launch(const void* q, const void* k, const void* v, const void* a, + const void* b, long long ab_stride, const void* A_log, + const void* dt_bias, void* state, long long st_slot, + long long st_head, const void* sidx, long long sidx_stride, + const void* zg, long long zg_pitch, const void* nw, + void* o, const void* cu, int N, int H, int Hg, int norm, + int ab_bf16, float scale, float sp_thr, float neps, + hipStream_t stream) +{ + dim3 grid(N, H), blk(kTHR); + // A plain kernel: norm and ab_bf16 are runtime parameters, not template arguments. + R3D_KLAUNCH(r3d_gdn_recurrent_update_kernel, grid, blk, stream, + (const unsigned short*)q, (const unsigned short*)k, (const unsigned short*)v, + a, b, ab_stride, (const float*)A_log, (const float*)dt_bias, (float*)state, + st_slot, st_head, (const int*)sidx, sidx_stride, (const unsigned short*)zg, + zg_pitch, (const float*)nw, (unsigned short*)o, (const int*)cu, H, Hg, + scale, sp_thr, neps, norm, ab_bf16); + return (int)hipGetLastError(); +} + +} // namespace + +/* ------------------------------------------------------------------ the plugin ABI */ + +enum { RU_Q = 0, RU_K, RU_V, RU_A, RU_B, RU_ALOG, RU_DTB, RU_STATE, RU_SIDX, RU_NACC, RU_CU, + RU_Z, RU_NORMW, RU_O, RU_OQ, RU_OSCALE }; + +extern "C" int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const RadTensor* q = r3d_opt(a, RU_Q); + const RadTensor* k = r3d_opt(a, RU_K); + const RadTensor* v = r3d_opt(a, RU_V); + const RadTensor* ta = r3d_opt(a, RU_A); + const RadTensor* tb = r3d_opt(a, RU_B); + const RadTensor* alog = r3d_opt(a, RU_ALOG); + const RadTensor* dtb = r3d_opt(a, RU_DTB); + const RadTensor* st = r3d_opt(a, RU_STATE); + const RadTensor* sidx = r3d_opt(a, RU_SIDX); + const RadTensor* nacc = r3d_opt(a, RU_NACC); + const RadTensor* cu = r3d_opt(a, RU_CU); + const RadTensor* z = r3d_opt(a, RU_Z); + const RadTensor* nw = r3d_opt(a, RU_NORMW); + const RadTensor* o = r3d_opt(a, RU_O); + // o_q and o_scale are the folded quantiser's outputs; this row does not fold it. + if (!r3d_p(q) || !r3d_p(k) || !r3d_p(v) || !r3d_p(ta) || !r3d_p(tb) || !r3d_p(alog) || + !r3d_p(dtb) || !r3d_wp(st) || !r3d_p(sidx) || !r3d_p(cu) || !r3d_wp(o)) + return R3D_NO(RAD_E_INVAL); + + if (q->rank != 3 || k->rank != 3 || v->rank != 3 || st->rank != 4 || o->rank != 3) + return R3D_NO(RAD_E_SHAPE); + if (sidx->rank < 2) return R3D_NO(RAD_E_SHAPE); + + const long long T = q->shape[0]; + const long long Hg = q->shape[1]; + const long long K = q->shape[2]; + const long long H = v->shape[1]; + const long long V = v->shape[2]; + if (k->shape[0] != T || k->shape[1] != Hg || k->shape[2] != K) return R3D_NO(RAD_E_SHAPE); + if (v->shape[0] != T || o->shape[0] != T || o->shape[1] != H || o->shape[2] != V) + return R3D_NO(RAD_E_SHAPE); + if (H == 0 || Hg == 0 || H % Hg) return R3D_NO(RAD_E_SHAPE); + if (K != kK || V != kV) return R3D_NO(RAD_E_SHAPE); + + if (!r3d_is_bf16(q) || !r3d_is_bf16(k) || !r3d_is_bf16(v) || !r3d_is_bf16(o)) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(alog) || !r3d_is_f32(dtb)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(st)) return R3D_NO(RAD_E_DTYPE); // fp32 state cache + if (ta->dtype != RAD_BF16 && ta->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + if (tb->dtype != ta->dtype) return R3D_NO(RAD_E_DTYPE); + + // state cache [slots, H, V, K]: the per-head and per-slot strides. + if (st->shape[1] != H || st->shape[2] != kV || st->shape[3] != kK) return R3D_NO(RAD_E_SHAPE); + const long long st_head = st->stride[1]; + const long long st_slot = st->stride[0]; + if (st_head != (long long)kV * kK) return R3D_NO(RAD_E_STRIDE); + + // a and b: [T, H] (the ba projection's rows), row pitch in elements. + const long long ab_stride = r3d_row_pitch(ta); + if (ab_stride < 0 || r3d_row_pitch(tb) != ab_stride) return R3D_NO(RAD_E_STRIDE); + + const long long sidx_stride = sidx->stride[sidx->rank - 1] == 1 ? sidx->stride[0] : -1; + if (sidx_stride < 0) return R3D_NO(RAD_E_STRIDE); + + int N = 0; + if (cu->rank != 1 || cu->shape[0] < 2 || !r3d_contig(cu)) return R3D_NO(RAD_E_SHAPE); + N = (int)(cu->shape[0] - 1); + + const float scale = (float)r3d_getf(a, "scale", 1.0 / sqrt((double)kK)); + const float sp_thr = (float)r3d_getf(a, "softplus_thr", 20.0); + const float neps = (float)r3d_getf(a, "eps", 1e-6); + + // The gated RMS norm epilogue: present when both z and norm_w are given. + int norm = 0; + long long zg_pitch = 0; + if (r3d_p(z) && r3d_p(nw)) { + if (z->rank != 3 || z->shape[0] != T || z->shape[1] != H || z->shape[2] != kV) + return R3D_NO(RAD_E_SHAPE); + if (!r3d_is_bf16(z) || !r3d_is_f32(nw) || r3d_numel(nw) != kV) return R3D_NO(RAD_E_DTYPE); + const int act = r3d_act_code(a, "act", nullptr, 0); + if (act != 0 && act != 1) return R3D_NO(RAD_E_INVAL); + norm = (act == 0) ? 2 : 1; // r3d_act_code: 0=silu, 1=sigmoid; kernel: 2=silu, 1=sigmoid + zg_pitch = z->stride[0]; + } + + const int e = r3d_gdn_recurrent_update_launch(r3d_p(q), r3d_p(k), r3d_p(v), r3d_p(ta), r3d_p(tb), + ab_stride, r3d_p(alog), r3d_p(dtb), r3d_wp(st), + st_slot, st_head, r3d_p(sidx), sidx_stride, + r3d_p(z), zg_pitch, r3d_p(nw), r3d_wp(o), r3d_p(cu), + N, (int)H, (int)Hg, norm, (ta->dtype == RAD_BF16), + scale, sp_thr, neps, (hipStream_t)s); + /* The launcher's codes are raw: its own negatives and hipGetLastError's positives. The + * plugin ABI takes RadStatus, so normalise. */ + if (e < 0) return R3D_NO(RAD_E_INVAL); + return e ? R3D_NO(RAD_E_DEVICE) : RAD_OK; +} diff --git a/libr3d/r3d_gelu_mul_quant_i8.hip b/libr3d/r3d_gelu_mul_quant_i8.hip new file mode 100644 index 00000000..d3586478 --- /dev/null +++ b/libr3d/r3d_gelu_mul_quant_i8.hip @@ -0,0 +1,129 @@ +/* r3d_gelu_mul_quant_i8.hip -- gelu_mul_quant_i8: gelu(gate) * up and the per-row symmetric int8 + * quantiser in one pass over the row. + * + * The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid, replacing the + * gelu_mul + quant_act_i8 pair and byte-identical to it: the product is formed in the tanh form + * with the same constants, rounded to bf16, and the absmax, scale and codes are quant_act_i8's + * over those bf16 values. The absmax is a max, so partitioning does not change it. + * + * gate_up [M][2n] bf16 (gate first) -> q [M][n] i8 (WMMA step order), scale [M] f32, out_bf16? + * + * The codes are written in the int8 WMMA step order (i8_step_pos), the plane the w4a8/w8a8/w2a8 + * GEMMs read, so n is a multiple of 16. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopI8 = 127.0f; +constexpr float kI8Floor = 1e-8f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} +__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) { + return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1); +} +__device__ __forceinline__ float block_max(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + v = wave_max(v); + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]); + return t; +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void gelu_mul_quant_i8_kernel( + const uint16_t* __restrict__ gu, uint8_t* __restrict__ q, float* __restrict__ s, + uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; // n bf16 of the product + __shared__ float lm[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* gr = gu + (size_t)row * gu_ld; + uint8_t* qr = q + (size_t)row * n; + uint16_t* yop = yo ? yo + (size_t)row * y_ld : nullptr; + + constexpr float k0 = 0.7978845608028654f, k1 = 0.044715f; + float m = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + const float g = ld_bf(gr, i); + const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g))); + const uint16_t y = f32_to_bf16(gelu * ld_bf(gr, n + i)); + ybuf[i] = y; + if (yop) yop[i] = y; + m = fmaxf(m, fabsf(bf16_to_f32(y))); + } + m = block_max(m, lm); + const float scale = fmaxf(m, kI8Floor) / kTopI8; + const float inv = 1.0f / scale; + if (threadIdx.x == 0) s[row] = scale; + + for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? bf16_to_f32(ybuf[c + (uint32_t)j]) + : 0.0f; + *(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv); + } +} + +} // namespace + +extern "C" { + +int r3d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* gu = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2), + *y = r3d_opt(a, 3); + if (!r3d_p(gu) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + long long M = 0, n = 0; + if (r3d_rows_of(q, &M, &n) != 0) return R3D_NO(RAD_E_INVAL); + if (n <= 0 || n % 16 || !r3d_contig(q)) return R3D_NO(RAD_E_SHAPE); + // gate_up is [M, 2n]; accept a row pitch of at least 2n. The pitch is the leading stride + // (r3d_row_pitch), which is shape[1] for a rank-2 row and the whole row extent for a rank-3. + const long long gu0 = r3d_row_pitch(gu); + if (gu0 < 2 * n) return R3D_NO(RAD_E_SHAPE); + const uint32_t gu_ld = (uint32_t)gu0; + if (r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + uint32_t y_ld = n; + if (y) { + if (y->dtype != RAD_BF16 || r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE); + const long long yp = r3d_row_pitch(y); + if (yp < n) return R3D_NO(RAD_E_STRIDE); + y_ld = (uint32_t)yp; + } + const size_t lds = (size_t)n * sizeof(uint16_t); + if (lds > 60 * 1024) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(kThreads); + R3D_KLAUNCH_S(gelu_mul_quant_i8_kernel, grid, blk, (size_t)lds, (hipStream_t)s, + (const uint16_t*)r3d_p(gu), (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), + (uint16_t*)(y ? r3d_wp(y) : nullptr), (uint32_t)n, gu_ld, y_ld); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_gemm_bf16_nt_m16.hip b/libr3d/r3d_gemm_bf16_nt_m16.hip index 45d527e2..ac63b59f 100644 --- a/libr3d/r3d_gemm_bf16_nt_m16.hip +++ b/libr3d/r3d_gemm_bf16_nt_m16.hip @@ -81,6 +81,11 @@ #include +/* The wave-matrix arm's launcher, in r3d_gemm_bf16_nt_m16_wmma.hip: the row's `impl` point 1. */ +extern "C" int r3d_gemm_nt_bf16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, + long stream); + namespace { constexpr int kBlockThreads = 256; // eight waves, the default @@ -331,6 +336,18 @@ extern "C" int r3d_rad_gemm_nt_bf16_m16(const RadArgs* a, RadStream s) R3dGemmCfg c; r3d_cfg_gemm(a, &c); + if (c.impl == 1) { + /* The wave-matrix arm: same contract, the slab's law at 16 k, its own launcher. The + * alignment and pitch checks above are the arm's too. `c.sk` is the unresolved value + * here -- the arm resolves 0 to its widest legal split and checks its own scratch, so + * the arena goes across whenever the row asked for one. */ + const int e = r3d_gemm_nt_bf16_m16_wmma(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, + (int)N, (int)K, (int)a_ld, (int)y_ld, c.sk, c.wv, + c.nt, (long)(uintptr_t)a->scratch, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + } int wv = c.wv > 0 ? c.wv : kWaves; if (wv > kWaves) wv = kWaves; if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE); diff --git a/libr3d/r3d_gemm_bf16_nt_m16_wmma.hip b/libr3d/r3d_gemm_bf16_nt_m16_wmma.hip new file mode 100644 index 00000000..d92bf5c6 --- /dev/null +++ b/libr3d/r3d_gemm_bf16_nt_m16_wmma.hip @@ -0,0 +1,251 @@ +/* r3d_gemm_bf16_nt_m16_wmma.hip -- the wave-matrix arm of the skinny bf16 GEMM, M <= 16. + * + * y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The dot2 arm (r3d_gemm_bf16_nt_m16.hip) owns one output element a lane and folds k in + * ascending pairs; this arm issues V_WMMA_F32_16X16X16_BF16 over a 16x16x16 tile, a wave a + * tile, and the two arms are two points of the row's `impl` axis. The tune cache picks the + * point per shape per machine; an untuned install runs the dot2 arm, which is the axis's + * default. + * + * ---- the tile map -------------------------------------------------------------------------- + * + * One wave owns a 16-row by 16-column output tile and walks k in 16-wide steps, one wmma a + * step. The ISA's lane map (wave32, the `_w32` builtins): + * + * A fragment: lane L holds row L % 16 of the tile, 16 bf16 in eight packed VGPRs + * B fragment: lane L holds column L % 16 of the tile, 16 bf16 in eight packed VGPRs + * C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane + * + * and lanes 0-15 and 16-31 must hold identical A and B data (the replication the ISA + * requires; only L % 16 selects the row or column). The accumulator chain is D = C, so a + * dependent wmma needs no V_NOP between steps: the hazard the ISA names is A/B overlapping + * the next step's D, and the fragments are fresh registers each step. + * + * The k order is the dot2 arm's contract at the tile boundary: tiles are summed in ascending + * k, and within a tile the sixteen products run in the hardware's fixed order. That is the + * arm's exactness statement: sk = 1 agrees with the reference to the last few bits, the way + * the dot2 arm's splits do, and the row's tolerance gate prices it, not a bit-exact claim. + * + * ---- where the bytes come from -------------------------------------------------------------- + * + * The activation is staged in LDS in bf16, the checkpoint's own bytes: the bf16 builtin + * takes the tile's bits directly, so the widening the dot2 arm pays once per element + * (bf16x2_to_f16x2 on the way in) is not here at all. One tile is 16 rows x 128 k of bf16, + * the dot2 arm's k tile, 4.25 KiB with the pitch, and carries eight wmma steps. The pitch is + * the dot2 arm's 68 dwords: 68 mod 32 = 4, so the lanes of a ds_read phase land four banks + * apart and the two 16-byte fragment reads a lane issues per step are conflict-free in + * their phases. + * + * The weight streams from global, one 16-byte pair a lane per step (column L % 16 of the + * tile, the step's 16 k), the NT axis choosing the lowering the dot2 arm's header describes. + * Every weight byte is read once per output tile, the same stream the dot2 arm streams; what + * the arm changes is the issue: one wmma where the dot2 arm issues eight dot4 folds. + * + * ---- the register budget -------------------------------------------------------------------- + * + * Eight accumulator VGPRs, eight A, eight B and the pointers: about 34 a lane. Eight waves + * a SIMD asks 272 of the 1024 the gfx11 SIMD keeps, so the block default stands and `wv` + * walks the same ladder as the dot2 arm. + * + * ---- split-K -------------------------------------------------------------------------------- + * + * The dot2 arm's slabs and partial plane, with one change: a slab is whole wmma steps, so a + * split is legal only when K % (sk * 16) == 0, and the ragged end is not a scalar tail but a + * step whose fragments zero-fill past K -- the products with zero are the identity and the + * k loop stays uniform. sk = 1 serves a ragged K the dot2 arm serves with its scalar tail. + * The reducer is the dot2 arm's, copied here: the two arms must not share a symbol through a + * header, and twelve lines are cheaper than the coupling. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; // eight waves, the default +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kKTile = 128; // k a staged tile covers, eight wmma steps +constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row, the dot2 arm's 68 +constexpr int kUnit = 16; // k a wmma step consumes: a slab's law + + + +/* One dword of two bf16 into the fragment's two shorts: the low half first, the high half + * after -- the packed order the builtin's VGPR map expects. A vector element is not a + * modifiable lvalue, so the unpack is a constructor argument, not a reference target. */ +#define R3D_U16(w) ((short)((w) & 0xffffu)), ((short)((w) >> 16)) + +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave. + * + * `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the + * narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, + * dense [sk][M][N], and the reducer adds them in split order. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ B, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab) +{ + /* Staged activation in the checkpoint's own bytes, a dword array at the dot2 arm's pitch. */ + __shared__ uint32_t s_a[16 * kAPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + const uint32_t r = lane & 15; // the replicated row/column index + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r; + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + + const int kbeg = (int)blockIdx.y * kslab; + const int kend = kbeg + kslab < K ? kbeg + kslab : K; + + const uint16_t* w = B + (size_t)n_real * w_ld; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + + for (int kt = kbeg; kt < kend; kt += kKTile) { + const int kl = std::min(kKTile, kend - kt); + + /* Stage 16 rows x kl bf16, eight elements a unit, 256 threads. A row past M re-reads + * the last real row, whose products the store drops; a unit past kl zero-fills. */ + const int nu = (kl + 7) / 8; + for (int i = (int)tid; i < 16 * nu; i += (int)blockDim.x) { + const int row = i / nu, c = (i % nu) * 8; + const int rr = row < M ? row : M - 1; + const uint16_t* src = A + (size_t)rr * a_ld + kt + c; + uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2; + if (c + 8 <= kl) { + const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src; + *(r3d_u32x4*)dst = q; + } else { + uint32_t p[4] = { 0, 0, 0, 0 }; + for (int e = 0; e < kl - c; e += 2) { + const uint32_t lo = ldg_u16(src + e); + const uint32_t hi = (e + 1 < kl - c) ? ldg_u16(src + e + 1) : 0u; + p[e / 2] = lo | (hi << 16); + } + for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e]; + } + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kAPitch; + for (int k = 0; k < kl; k += 16) { + /* Eight wmma steps per tile: two 16-byte reads a lane, the row's k pair at + * dword k/2 and k/2 + 4, and the column's from global. */ + const r3d_u32x4 a0 = *(const r3d_u32x4*)(ap + k / 2); + const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + k / 2 + 4); + const r3d_u32x4 b0 = ldw(w + kt + k); + const r3d_u32x4 b1 = ldw(w + kt + k + 8); + const v16short fa = v16short{ R3D_U16(a0.x), R3D_U16(a0.y), R3D_U16(a0.z), + R3D_U16(a0.w), R3D_U16(a1.x), R3D_U16(a1.y), + R3D_U16(a1.z), R3D_U16(a1.w) }; + const v16short fb = v16short{ R3D_U16(b0.x), R3D_U16(b0.y), R3D_U16(b0.z), + R3D_U16(b0.w), R3D_U16(b1.x), R3D_U16(b1.y), + R3D_U16(b1.z), R3D_U16(b1.w) }; + acc = wmma_bf16(fa, fb, acc); + } + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N); + if (!keep) return; + for (int g = 0; g < 8; ++g) { + const int m = g * 2 + (int)(lane >> 4); + if (m >= M) continue; + if constexpr (SPLIT) + Part[((size_t)blockIdx.y * M + m) * N + n0] = acc[g]; + else + Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[g]); + } +} +#undef R3D_U16 + +/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one + * narrowing. The dot2 arm's, copied: the slab sums bracket the products differently than + * one chain does, and the difference is in the last bits, the split's, not a bug in it. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_split_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, M <= 16, the wave-matrix arm. + * + * The dot2 arm's contract, with the slab law at 16 k. `sk` splits K (0 = the largest legal + * split), `wv` waves per block (0 = 8), `nt` the weight load's lowering, `scratch` the f32 + * partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null + * pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */ +extern "C" int r3d_gemm_nt_bf16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, + long stream) +{ + if (!a || !b || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > 16) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (sk == 0) { + static const int kLadder[] = { 16, 8, 4, 2, 1 }; + for (int s : kLadder) + if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; } + } + if (sk < 1) return -2; + /* The slab is kUnit deep: a ragged tail (K % kUnit) would stage a partial unit + * the tile loop reads whole (stale dwords) and load B fragments past the weight, + * so the shape is refused, as the dot2 arm's pick_sk already does. */ + if (K % ((long long)sk * kUnit)) return -2; + if (sk > 1 && !scratch) return -1; + if (wv <= 0) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2; + + const int kslab = K / sk; + +#define R3D_WNT(NTV) \ + do { \ + const int nt_ = (N + 15) / 16; \ + const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_m16_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \ + (hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \ + sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \ + } \ + } while (0) + if (nt) R3D_WNT(true); + else R3D_WNT(false); +#undef R3D_WNT + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr3d/r3d_gemm_bf16_nt_m64_wmma.hip b/libr3d/r3d_gemm_bf16_nt_m64_wmma.hip new file mode 100644 index 00000000..bdafdaf3 --- /dev/null +++ b/libr3d/r3d_gemm_bf16_nt_m64_wmma.hip @@ -0,0 +1,298 @@ +/* r3d_gemm_bf16_nt_m64_wmma.hip -- the wave-matrix bf16 GEMM for the M = 17..127 band. + * + * y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The m16 arm (r3d_gemm_bf16_nt_m16_wmma) owns one 16-row tile a wave and stages that tile in + * LDS; above M = 16 a 128-row tiled block wastes half its rows, so this arm takes MT 16-row + * tiles a block and walks them with MT accumulators a wave. The B-fragment (the weight column) + * is loaded once per 16-k step and reused over the MT row tiles, so the weight stream is read + * once per 16-column tile no matter how many row tiles the block carries -- the activation, not + * the weight, is the traffic that grows with MT, and it is read from global (no LDS) so a block + * stays small enough to keep the waves on the SIMD. + * + * ---- the tile map -------------------------------------------------------------------------- + * + * One wave owns a 16-column output tile across MT 16-row tiles and walks k in 16-wide steps, one + * wmma a step per row tile. The ISA's lane map (wave32, the `_w32` builtins), the m16 arm's: + * + * A fragment: lane L holds row L % 16 of a row tile, 16 bf16 in eight packed VGPRs + * B fragment: lane L holds column L % 16 of the tile, 16 bf16 in eight packed VGPRs + * C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane + * + * ---- split-K -------------------------------------------------------------------------------- + * + * The m16 arm's slabs and f32 partial plane, with the same law: a slab is whole 16-k wmma steps, + * so a split is legal only when K % (sk * 16) == 0, and the reducer adds the sk partials in + * ascending split order. sk = 1 serves a ragged K. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; // eight waves, the default +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kUnit = 16; // k a wmma step consumes: a slab's law + + +#define R3D_U16(w) ((short)((w) & 0xffffu)), ((short)((w) >> 16)) + +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, MT 16-row tiles a block, one 16-column tile a wave. + * + * `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the + * narrowed bf16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense + * [sk][M][N], and the reducer adds them in split order. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m64_wmma_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ B, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab) +{ + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + const uint32_t r = lane & 15; // the replicated row/column index + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r; + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + const uint32_t mt0 = (uint32_t)blockIdx.y * MT * 16; // this block's first row + + const int kbeg = (int)blockIdx.y * 0; // the split is blockIdx.z; see the launch + (void)kbeg; + + const uint16_t* w = B + (size_t)n_real * w_ld; + /* The accumulator: f32 for the f32-acc arm, v16short for the bf16-acc arm. The bf16-acc + * builtin's 8 live elements sit in the even indices (opsel = false); the epilogue reads + * only those, the odd half is dead. + * + * PRECISION: the bf16-acc arm is a documented low-precision mode -- the hardware quantises + * the running sum at bf16 precision per wave-matrix step, and the loss grows with the number + * of steps (measured on gfx1102, random data in [-1,1]: ~0.78 abs after 16 k, ~51 after 256 + * k, ~622 after 1024 k; integer-valued data stays exact). It measures no throughput gain + * over the f32 arm. It is a register-pressure option for future occupancy work, not a speed + * one; do not select it for accuracy-sensitive shapes. See the README's 16-bit + * wave-matrix accumulate section. */ + using AccT = std::conditional_t; + AccT acc[MT]; +#pragma unroll + for (int i = 0; i < MT; ++i) { + if constexpr (F16ACC) + acc[i] = v16short{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; + else + acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + } + + // The split's k range: blockIdx.z owns [z*kslab, z*kslab + kslab). + const int kbeg2 = (int)blockIdx.z * kslab; + const int kend = kbeg2 + kslab < K ? kbeg2 + kslab : K; + + /* Double-buffered k-walk: the next step's A and B fragments are issued into registers while + * the current step's wmmas run, so the global load latency overlaps the multiply. The first + * step is prefetched before the loop; each iteration consumes the current fragments, issues + * the next step's loads, then swaps. The ragged end (kl < kUnit) keeps the zero-fill. */ + const uint16_t* bp = w + kbeg2; + const r3d_u32x4 b0 = ldw(bp); + const r3d_u32x4 b1 = ldw(bp + 8); + v16short fb = v16short{ R3D_U16(b0.x), R3D_U16(b0.y), R3D_U16(b0.z), + R3D_U16(b0.w), R3D_U16(b1.x), R3D_U16(b1.y), + R3D_U16(b1.z), R3D_U16(b1.w) }; + v16short fa[MT]; +#pragma unroll + for (int i = 0; i < MT; ++i) { + const int mrow = (int)mt0 + i * 16 + (int)r; + const uint16_t* ap = A + (size_t)(mrow < M ? mrow : M - 1) * a_ld + kbeg2; + const r3d_u32x4 a0 = ldw(ap); + const r3d_u32x4 a1 = ldw(ap + 8); + fa[i] = v16short{ R3D_U16(a0.x), R3D_U16(a0.y), R3D_U16(a0.z), + R3D_U16(a0.w), R3D_U16(a1.x), R3D_U16(a1.y), + R3D_U16(a1.z), R3D_U16(a1.w) }; + } + for (int kt = kbeg2; kt < kend; kt += kUnit) { + const int kl = std::min(kUnit, kend - kt); + const int ktn = kt + kUnit; + const bool more = (ktn < kend); + // Issue the next step's fragment loads now, while this step's wmmas run below. + r3d_u32x4 b0n, b1n; + v16short fbn; + v16short fan[MT]; + if (more) { + b0n = ldw(w + ktn); + b1n = ldw(w + ktn + 8); + fbn = v16short{ R3D_U16(b0n.x), R3D_U16(b0n.y), R3D_U16(b0n.z), + R3D_U16(b0n.w), R3D_U16(b1n.x), R3D_U16(b1n.y), + R3D_U16(b1n.z), R3D_U16(b1n.w) }; +#pragma unroll + for (int i = 0; i < MT; ++i) { + const int mrow = (int)mt0 + i * 16 + (int)r; + const uint16_t* apn = A + (size_t)(mrow < M ? mrow : M - 1) * a_ld + ktn; + const r3d_u32x4 a0n = ldw(apn); + const r3d_u32x4 a1n = ldw(apn + 8); + fan[i] = v16short{ R3D_U16(a0n.x), R3D_U16(a0n.y), R3D_U16(a0n.z), + R3D_U16(a0n.w), R3D_U16(a1n.x), R3D_U16(a1n.y), + R3D_U16(a1n.z), R3D_U16(a1n.w) }; + } + } + // Consume the current step's fragments. +#pragma unroll + for (int i = 0; i < MT; ++i) { + if (kl == kUnit) { + if constexpr (F16ACC) acc[i] = wmma_bf16acc(fa[i], fb, acc[i]); + else acc[i] = wmma_bf16(fa[i], fb, acc[i]); + } else { + v16short fa0 = fa[i]; + for (int e = kl; e < 16; ++e) fa0[e] = (short)0; + if constexpr (F16ACC) acc[i] = wmma_bf16acc(fa0, fb, acc[i]); + else acc[i] = wmma_bf16(fa0, fb, acc[i]); + } + } + // Advance: the prefetched next step becomes the current step. + if (more) { + fb = fbn; +#pragma unroll + for (int i = 0; i < MT; ++i) fa[i] = fan[i]; + } + } + + const bool keep = (n0 < (uint32_t)N); + if (!keep) return; +#pragma unroll + for (int i = 0; i < MT; ++i) { + for (int g = 0; g < 8; ++g) { + const int m = (int)mt0 + i * 16 + g * 2 + (int)(lane >> 4); + if (m >= M) continue; + if constexpr (F16ACC) { + // The bf16-acc arm: the 8 live elements are the even indices (opsel = false). + // Widen the bf16 short to f32 for the split partial; the store re-narrows. + const uint32_t u = ((uint32_t)(uint16_t)acc[i][2 * g]) << 16; + float v; memcpy(&v, &u, 4); + if constexpr (SPLIT) + Part[((size_t)blockIdx.z * M + m) * N + n0] = v; + else + Y[(size_t)m * y_ld + n0] = (uint16_t)((uint16_t)acc[i][2 * g]); + } else { + if constexpr (SPLIT) + Part[((size_t)blockIdx.z * M + m) * N + n0] = acc[i][g]; + else + Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[i][g]); + } + } + } +} +#undef R3D_U16 + +/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one + * narrowing. The m16 arm's, copied: the two arms must not share a symbol through a header. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m64_wmma_split_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T, bf16 in and out, f32 accumulate, the M = 17..127 band on the + * wave-matrix. `sk` splits K (0 = the largest legal split), `wv` waves per block (0 = 8), `nt` + * the weight load's lowering, `scratch` the f32 partial arena, sk * M * N * 4 bytes, required + * when the split is on. Returns 0, -1 a null pointer, -2 a shape it does not serve, -4 a launch + * failure. */ +extern "C" int r3d_gemm_nt_bf16_m64_wmma(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, + long stream, int acc) +{ + if (acc < 0) acc = 0; + if (acc > 1) acc = 1; + if (!a || !b || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + const int w_ld = K; + if (sk == 0) { + static const int kLadder[] = { 8, 4, 2, 1 }; + for (int s : kLadder) + if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; } + } + if (sk < 1) return -2; + if (sk > 1 && K % ((long long)sk * kUnit)) return -2; + if (sk > 1 && !scratch) return -1; + if (wv <= 0) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2; + + const int kslab = K / sk; + const int ntiles = (N + 15) / 16; + const int ncolblk = (ntiles + wv - 1) / wv; + +#define R3D_WMT(NTV, MT, ACC) \ + do { \ + const int mrowblk = (M + MT * 16 - 1) / (MT * 16); \ + const dim3 grid(ncolblk, (unsigned)mrowblk, (unsigned)sk), block((unsigned)(wv * kWave)); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m64_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, w_ld, kslab); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_m64_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \ + (hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \ + sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m64_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, w_ld, kslab); \ + } \ + } while (0) + +#define R3D_WNT(NTV) \ + do { \ + if (M <= 16) { if (acc) R3D_WMT(NTV, 1, true); else R3D_WMT(NTV, 1, false); } \ + else if (M <= 32) { if (acc) R3D_WMT(NTV, 2, true); else R3D_WMT(NTV, 2, false); } \ + else { if (acc) R3D_WMT(NTV, 4, true); else R3D_WMT(NTV, 4, false); } \ + } while (0) + if (nt) R3D_WNT(true); + else R3D_WNT(false); +#undef R3D_WNT +#undef R3D_WMT + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The RadArgs dispatch: the row's entry. The M = 17..127 band, sk = 1 (the N tiles carry the + * parallelism at prefill widths, so no split and no scratch), wv = 8, nt = 0. */ +extern "C" int r3d_rad_gemm_nt_bf16_m64_wmma(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = &a->t[0], *wt = &a->t[1], *yt = &a->t[2]; + if (!r3d_p(at) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL); + if (at->dtype != RAD_BF16 || wt->dtype != RAD_BF16 || yt->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long N = (wt->rank >= 2) ? wt->shape[0] : 0; + if (M <= 0 || N <= 0 || K <= 0) + return R3D_NO(RAD_E_SHAPE); + const int a_ld = (int)at->stride[0]; + const int y_ld = (int)yt->stride[0]; + return r3d_gemm_nt_bf16_m64_wmma((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(wt), + (long)(uintptr_t)r3d_wp(yt), (int)M, (int)N, (int)K, a_ld, + y_ld, 1, 8, 0, 0, (long)(uintptr_t)s, 0); +} diff --git a/libr3d/r3d_gemm_f16_nt_m16.hip b/libr3d/r3d_gemm_f16_nt_m16.hip new file mode 100644 index 00000000..ef052926 --- /dev/null +++ b/libr3d/r3d_gemm_f16_nt_m16.hip @@ -0,0 +1,384 @@ +/* r3d_gemm_f16_nt_m16.hip -- the skinny f16 GEMM, M <= 16: the linear a token is made of. + * + * y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The band is decode and speculative verify, where the weight is the cost and the activation is + * free: the kernel is built so the whole weight plane streams once, and so every output's sum is + * the sum libref forms. + * + * ---- the lane map -------------------------------------------------------------------------- + * + * One output element a lane, walking k ascending. A wave covers MT rows of the activation by + * 32/MT rows of the weight: lane l owns (m = l % MT, n = n0 + l / MT), MT being the template + * argument -- the request's M rounded up to 1, 2, 4, 8 or 16. Lanes sharing an n read the same + * weight words, so the wave issues 32/MT loads per step and broadcasts them to MT lanes each; + * lanes sharing an m read the same activation words out of LDS. A lane therefore owns its own + * accumulator from 0 to K and never exchanges a value with another lane: its chain is + * + * acc = 0; for k ascending: acc = dot2(pair k+1, dot2(pair k, acc)) + * + * with pairs taken two k at a time, which is `s += a[k]*b[k]` in ascending k, summand for summand, + * the loop r4d_gemm_bf16_nt_tiled's contract quotes and ref_gemm.h's quant_tile runs. There is no + * wave reduction anywhere in this kernel, so nothing reassociates: at sk = 1 the output is + * bit-identical to libref's, not merely within a tolerance. + * + * Rows past M and columns past N are clamped, not skipped -- a tail lane re-reads the last real row + * and its result is dropped at the store -- so the k loop stays uniform and the loads stay + * straight-line. + * + * ---- where the bytes come from -------------------------------------------------------------- + * + * The activation is staged in LDS as the checkpoint's own bytes: one row is M <= 16 elements wide + * per k, so a tile is MT * 128 f16 (4.25 KiB at MT = 16) and one 16-byte load a thread. There is + * no widening on the way in at all -- f16 is the pair the dot2 takes, so the stage is a straight + * copy and the bf16 arm's one-convert-per-element price is not here. The pitch is 68 dwords: + * 68 mod 32 = 4, so the eight lanes of a ds_read_b128 phase land on banks 4 apart -- conflict-free + * -- and 68 * 4 = 272 keeps a 16-byte LDS read aligned. + * + * The weight is NOT staged. M is tiny, so a staged tile would be read by 32/MT lanes and then + * thrown away; LDS staging buys reuse a skinny shape does not have. Weight bytes go straight from + * global memory into the dot: a 16-byte read feeds four dot4 folds with no conversion between, + * which is the whole of this kernel's difference from the bf16 arm -- the bf16 arm pays four + * v_cvt_pk_rtz_f16_f32 per eight values because its bytes are not the dot's, and here they are. + * Each wave keeps NT = 32/MT rows resident in L1 (NT lines of 128 B, 4 KiB at MT = 1, the worst + * case), which is what makes 16-byte-per-lane strided reads across NT rows cost what they fetch. + * + * ---- the register budget -------------------------------------------------------------------- + * + * A gfx11 SIMD has 1024 VGPRs for a wave32. The loop is one accumulator, four activation pairs, + * four weight dwords, one 16-byte staging quad and a handful of pointers and counters: about 24 + * live VGPRs, so the kernel is nowhere near the 128 that R3D_WAVES(8) -- eight waves a SIMD, + * 1024/8 -- asks for. The target is stated for the reason r3d_common.h gives: unstated, the + * scheduler picks the occupancy itself, and this kernel's throughput is waves in flight, since + * every wave is waiting on a memory load that takes hundreds of cycles. Eight waves a block of + * 256 threads is the default, and `wv` is the axis a tuner walks. + * + * ---- split-K -------------------------------------------------------------------------------- + * + * At M = 1 a wide N is the only parallelism there is, and N = 48 (a GDN a|b projection) gives three + * waves on a 32-CU card. `sk` splits K into that many contiguous slabs, each owned by one + * blockIdx.y, each writing an f32 partial to the caller's `scratch` arena; a second kernel on the + * same stream adds the partials per output in ascending split order and narrows once. + * + * The order matters and is stated: summing sk per-slab partials is NOT the ascending sum libref + * forms. Each partial is an ascending sum over its own slab, and the slab sums are then added in + * ascending slab order, which brackets the products differently than a single running chain does. + * sk = 1 is the bit-identical case; sk > 1 agrees to the last bits, which is the same contract + * libr4d's tiled row states about its slices. The row is verified at every sk kbench measures. + * + * `sk == 0` means "the largest legal split for this K" off the axis's ladder {16, 8, 4, 2, 1}, + * legality being K % (sk * 8) == 0: a slice must end where the inner loop stops, on a group of the + * eight k (four f16 pairs) a lane consumes per step, so a slice boundary never falls inside a + * step. The staged tile is 128 k wide and its last tile is ragged, which is what lets a slice be + * 8 k long, and the cap of 16 is the split the row's scratch hook sizes the arena for. + * + * ---- `nt` ----------------------------------------------------------------------------------- + * + * RDNA3 has no global_load_tr_b128 (that is RDNA4) and no cache-swizzle field on a global load. So + * `nt` is an axis that measures a knob the ISA does not special-case: nt = 1 issues the weight + * reads through an address-space-1 pointer, which lowers to global_load_b128 with no cache modifier + * and no swizzle -- a plain stream -- and nt = 0 issues the same 16-byte reads through the generic + * pointer, which lowers to flat_load_dwordx4. Nothing is invented here; the axis exists so kbench + * can price the two lowerings and record that on this card they are the same stream. + */ + +/* hip_runtime.h first: it defines __forceinline__, which r3d_codecs.h's R3D_HD spells, and + * r3d_common.h reaches the codecs before it reaches the runtime. */ +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +/* The wave-matrix arm's launcher, in r3d_gemm_f16_nt_m16_wmma.hip: the row's `impl` point 1. */ +extern "C" int r3d_gemm_nt_f16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, + long stream); + +namespace { + +constexpr int kBlockThreads = 256; // eight waves, the default +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kKTile = 128; // k a staged tile of a covers +constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row +constexpr int kMTMax = 16; // the band's upper bound + +/* The split rule, in one place so the launch, the shim and the row's gemm_tune_valid agree. + * `kUnit` is the k a lane's step consumes -- eight elements, four f16 pairs -- and a slice must be + * whole steps, so a split is legal when K divides by sk * kUnit. The ladder is the row's `sk` axis + * descending, and its top is the split the scratch hook sizes for: a wider split the arena cannot + * hold is not a legal default. */ +constexpr int kUnit = 8; +inline int pick_sk(long long K, int maxsk) +{ + static const int kLadder[] = { 16, 8, 4, 2, 1 }; + for (int s : kLadder) + if (s <= maxsk && K % ((long long)s * kUnit) == 0) return s; + return 1; +} + +/* A 16-byte weight read. NT true is the address-space-1 form: global_load_b128, no cache modifier, + * no swizzle, the plain stream the row's `nt` axis names. NT false goes through the generic + * pointer, which the compiler lowers to flat_load_dwordx4. */ +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +__device__ __forceinline__ r3d_u32x4 lds_a(const uint32_t* p) +{ + return *(const r3d_u32x4*)p; +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, one output element a lane. + * + * `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the + * narrowed f16 the caller asked for. With sk > 1 every split writes its own f32 partial, dense + * [sk][M][N], and gemm_split_reduce adds them. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ B, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab) +{ + /* Staged activation in the checkpoint's own bytes: the f16 pair the dot2 takes. One + * allocation for the widest MT: this kernel is instantiated for MT = 1, 2, 4, 8 and 16 and + * 4.25 KiB is not worth a template. */ + __shared__ uint32_t s_a[kMTMax * kAPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + constexpr uint32_t kNT = kWave / MT; // weight rows a wave covers + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * kNT + lane / MT; + const uint32_t m = lane & (MT - 1); + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + const int m_real = (int)(m < (uint32_t)M ? m : (uint32_t)(M - 1)); + + const int kbeg = (int)blockIdx.y * kslab; + const int kend = kbeg + kslab < K ? kbeg + kslab : K; + + const uint16_t* w = B + (size_t)n_real * w_ld; + float acc = 0.0f; + + for (int kt = kbeg; kt < kend; kt += kKTile) { + const int kl = std::min(kKTile, kend - kt); + + /* Stage: eight elements a unit, MT * (kl/8) units, 256 threads. A row past M re-reads the + * last real row, whose products the store drops. The copy is straight: the bytes staged + * are the bytes the dot reads. */ + const int nu = (kl + 7) / 8; + /* blockDim.x, not the 256-thread default: the wv axis launches one, two, four or eight + * waves, and a stage loop that strides the block constant leaves units staged only for + * the waves that exist -- wv = 1 stages 32 of MT*16 units and the k loop reads the rest of + * the tile out of LDS that was never written. */ + for (int i = (int)tid; i < MT * nu; i += (int)blockDim.x) { + const int r = i / nu, c = (i % nu) * 8; + const int rr = r < M ? r : M - 1; + const uint16_t* src = A + (size_t)rr * a_ld + kt + c; + uint32_t* dst = s_a + (size_t)r * kAPitch + c / 2; + if (c + 8 <= kl) { + const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src; + *(r3d_u32x4*)dst = q; + } else { + uint32_t p[4] = { 0, 0, 0, 0 }; + for (int e = 0; e < kl - c; e += 2) { + const uint32_t lo = ldg_u16(src + e); + const uint32_t hi = (e + 1 < kl) ? ldg_u16(src + e + 1) : 0u; + p[e / 2] = lo | (hi << 16); + } + for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e]; + } + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)m * kAPitch; + const int kf = kl & ~7; + for (int k = 0; k < kf; k += 8) { + const r3d_u32x4 aw = lds_a(ap + k / 2); + const r3d_u32x4 bw = ldw(w + kt + k); + /* The weight is the dot's operand as it arrives: f16 is f16, and a 16-byte read feeds + * the four folds with nothing between. The bf16 arm's trap does not exist here -- + * there is no other 16-bit format these bytes could be read as -- which is the whole + * of the kernel's gain over it, one conversion group per eight products. */ + acc = dot4_f16x4(aw.x, aw.y, bw.x, bw.y, acc); + acc = dot4_f16x4(aw.z, aw.w, bw.z, bw.w, acc); + } + /* The ragged end of the last slab, ascending. A split is legal only when its slab is whole + * tiles, so this runs at sk = 1 with a K that is not a multiple of 128. */ + for (int k = kf; k < kl; ++k) + acc = acc + f16_to_f32((uint16_t)ldg_u16(A + (size_t)m_real * a_ld + kt + k)) + * f16_to_f32((uint16_t)ldg_u16(w + kt + k)); + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N) && (m < (uint32_t)M); + if (!keep) return; + if constexpr (SPLIT) { + /* Partial plane [sk][M][N]: split-major, so the reducer reads sk values M*N apart and this + * store keeps the same [M][N] shape at every split. */ + Part[((size_t)blockIdx.y * M + m) * N + n0] = acc; + } else { + Y[(size_t)m * y_ld + n0] = f32_to_f16(acc); // narrowed once, here + } +} + +/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one narrowing. + * + * This is the order libref's ascending sum produces at sk = 1 and not at sk > 1: each partial is + * ascending over its own slab, and the slab sums bracket the products differently than one chain + * does. The difference is in the last bits and is the split's, not a bug in it. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_split_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_f16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T, f16 in and out, f32 accumulate, M <= 16. + * + * a [M][K] f16, `a_ld` elements a row (0 = K) + * b [N][K] f16, row-major, k contiguous + * y [M][N] f16, `y_ld` elements a row (0 = N) + * + * `sk` splits K (0 = the largest legal split), `wv` is waves per block (0 = 8), `nt` picks the + * weight load's lowering (see the file header), and `scratch` is the f32 partial arena, + * sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null pointer, -2 a shape it + * does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */ +extern "C" int r3d_gemm_nt_f16_m16(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, long stream) +{ + if (!a || !b || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > kMTMax) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (sk == 0) sk = pick_sk(K, 16); + if (sk < 1) return -2; + if (K % ((long long)sk * kUnit)) return -2; + if (sk > 1 && !scratch) return -1; + if (wv <= 0) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2; + + const int mt = M <= 1 ? 1 : M <= 2 ? 2 : M <= 4 ? 4 : M <= 8 ? 8 : kMTMax; + const int kslab = K / sk; + +#define R3D_M16_NT(MTV, NTV) \ + do { \ + const int nt_ = (N + (kWave / MTV) - 1) / (kWave / MTV); \ + const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_split_reduce, dim3(nb), dim3(kBlockThreads), (hipStream_t)stream, \ + (const float*)scratch, (uint16_t*)y, M, N, y_ld, sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \ + } \ + } while (0) +#define R3D_M16_MT(MTV) do { if (nt) R3D_M16_NT(MTV, true); else R3D_M16_NT(MTV, false); } while (0) + switch (mt) { + case 1: R3D_M16_MT(1); break; + case 2: R3D_M16_MT(2); break; + case 4: R3D_M16_MT(4); break; + case 8: R3D_M16_MT(8); break; + default: R3D_M16_MT(16); break; + } +#undef R3D_M16_MT +#undef R3D_M16_NT + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ============================================================== the plugin ABI entry point + * + * gemm_nt's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm/oGemm). */ +enum { G_A = 0, G_B, G_Y }; + +#define R3D_NEED(x) do { const int _s = (x); if (_s != RAD_OK) return R3D_NO(_s); } while (0) +static int dt_f16(const RadTensor* t) { return r3d_is_f16(t) ? RAD_OK : RAD_E_DTYPE; } + +extern "C" int r3d_rad_gemm_nt_f16_m16(const RadArgs* a, RadStream s) +{ + const RadTensor* A = r3d_opt(a, G_A); + const RadTensor* B = r3d_opt(a, G_B); + const RadTensor* Y = r3d_opt(a, G_Y); + if (!A || !B || !Y) return R3D_NO(RAD_E_INVAL); + R3D_NEED(dt_f16(A)); + R3D_NEED(dt_f16(B)); + R3D_NEED(dt_f16(Y)); + + const long long K = r3d_geti_or(a, "K", r3d_dim(B, (int)B->rank - 1)); + const long long N = r3d_geti_or(a, "N", r3d_dim(B, (int)B->rank - 2)); + if (K < 1 || N < 1) return R3D_NO(RAD_E_SHAPE); + /* The row count comes from the output, never from `M`, which is the band's upper bound. */ + const long long nel = r3d_numel(Y); + if (nel < N || nel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = nel / N; + if (M < 1 || M > kMTMax) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(A) < M * K || r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + + long long arows = 0, yrows = 0; + const long long a_ld = r3d_rows_pitch(A, K, &arows); + const long long y_ld = r3d_rows_pitch(Y, N, &yrows); + if (a_ld < 0 || y_ld < 0) return R3D_NO(RAD_E_STRIDE); + if (arows < M || yrows < M) return R3D_NO(RAD_E_SHAPE); + /* The weight must be dense: every wave reads b[n][k] at n * K + k, and a pitch the launcher + * does not carry cannot be described to it. */ + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + /* 16-byte weight loads, at a row base and at a tile base, both multiples of 8 elements. */ + if (a_ld % 8) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(A->data, 16) || !r3d_aligned(B->data, 16)) return R3D_NO(RAD_E_ALIGN); + + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + if (c.impl == 1) { + /* The wave-matrix arm: same contract, the slab's law at 16 k, its own launcher. The + * alignment and pitch checks above are the arm's too. `c.sk` is the unresolved value + * here -- the arm resolves 0 to its widest legal split and checks its own scratch, so + * the arena goes across whenever the row asked for one. */ + const int e = r3d_gemm_nt_f16_m16_wmma(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, + (int)N, (int)K, (int)a_ld, (int)y_ld, c.sk, c.wv, + c.nt, (long)(uintptr_t)a->scratch, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); + } + int wv = c.wv > 0 ? c.wv : kWaves; + if (wv > kWaves) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return R3D_NO(RAD_E_SHAPE); + int sk = c.sk > 0 ? c.sk : pick_sk(K, 16); + if (sk > 16) return R3D_NO(RAD_E_SHAPE); // the scratch hook sizes for 16 + if (K % ((long long)sk * kUnit)) return R3D_NO(RAD_E_SHAPE); + if (sk > 1) { + const long long need = (long long)sk * M * N * 4; + if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH); + } + + const int e = r3d_gemm_nt_f16_m16(r3d_addr(A), r3d_addr(B), r3d_addr(Y), (int)M, (int)N, + (int)K, (int)a_ld, (int)y_ld, sk, wv, c.nt, + (long)(uintptr_t)(sk > 1 ? a->scratch : nullptr), + (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE + : e == -3 ? RAD_E_STRIDE : RAD_E_DEVICE); +} diff --git a/libr3d/r3d_gemm_f16_nt_m16_wmma.hip b/libr3d/r3d_gemm_f16_nt_m16_wmma.hip new file mode 100644 index 00000000..e479cd5f --- /dev/null +++ b/libr3d/r3d_gemm_f16_nt_m16_wmma.hip @@ -0,0 +1,254 @@ +/* r3d_gemm_f16_nt_m16_wmma.hip -- the wave-matrix arm of the skinny f16 GEMM, M <= 16. + * + * y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The dot2 arm (r3d_gemm_f16_nt_m16.hip) owns one output element a lane and folds k in + * ascending pairs; this arm issues V_WMMA_F32_16X16X16_F16 over a 16x16x16 tile, a wave a + * tile, and the two arms are two points of the row's `impl` axis. The tune cache picks the + * point per shape per machine; an untuned install runs the dot2 arm, which is the axis's + * default. + * + * ---- the tile map -------------------------------------------------------------------------- + * + * One wave owns a 16-row by 16-column output tile and walks k in 16-wide steps, one wmma a + * step. The ISA's lane map (wave32, the `_w32` builtins): + * + * A fragment: lane L holds row L % 16 of the tile, 16 f16 in eight packed VGPRs + * B fragment: lane L holds column L % 16 of the tile, 16 f16 in eight packed VGPRs + * C/D: lane L, VGPR g holds D[g * 2 + L / 16][L % 16], eight f32 a lane + * + * and lanes 0-15 and 16-31 must hold identical A and B data (the replication the ISA + * requires; only L % 16 selects the row or column). The accumulator chain is D = C, so a + * dependent wmma needs no V_NOP between steps: the hazard the ISA names is A/B overlapping + * the next step's D, and the fragments are fresh registers each step. + * + * The k order is the dot2 arm's contract at the tile boundary: tiles are summed in ascending + * k, and within a tile the sixteen products run in the hardware's fixed order. That is the + * arm's exactness statement: sk = 1 agrees with the reference to the last few bits, the way + * the dot2 arm's splits do, and the row's tolerance gate prices it, not a bit-exact claim. + * + * ---- where the bytes come from -------------------------------------------------------------- + * + * The activation is staged in LDS in f16, the checkpoint's own bytes: the f16 builtin takes + * the tile's bits directly, the way the bf16 arm's does, and where the bf16 arm's dot2 pays + * a widening the f16 arm pays nothing at all. One tile is 16 rows x 128 k of f16, the dot2 + * arm's k tile, 4.25 KiB with the pitch, and carries eight wmma steps. The pitch is the + * dot2 arm's 68 dwords: 68 mod 32 = 4, so the lanes of a ds_read phase land four banks + * apart and the two 16-byte fragment reads a lane issues per step are conflict-free in + * their phases. + * + * The weight streams from global, one 16-byte pair a lane per step (column L % 16 of the + * tile, the step's 16 k), the NT axis choosing the lowering the dot2 arm's header describes. + * Every weight byte is read once per output tile, the same stream the dot2 arm streams; what + * the arm changes is the issue: one wmma where the dot2 arm issues eight dot4 folds. + * + * ---- the register budget -------------------------------------------------------------------- + * + * Eight accumulator VGPRs, eight A, eight B and the pointers: about 34 a lane. Eight waves + * a SIMD asks 272 of the 1024 the gfx11 SIMD keeps, so the block default stands and `wv` + * walks the same ladder as the dot2 arm. + * + * ---- split-K -------------------------------------------------------------------------------- + * + * The dot2 arm's slabs and partial plane, with one change: a slab is whole wmma steps, so a + * split is legal only when K % (sk * 16) == 0, and the ragged end is not a scalar tail but a + * step whose fragments zero-fill past K -- the products with zero are the identity and the + * k loop stays uniform. sk = 1 serves a ragged K the dot2 arm serves with its scalar tail. + * The reducer is the dot2 arm's, copied here: the two arms must not share a symbol through a + * header, and twelve lines are cheaper than the coupling. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kBlockThreads = 256; // eight waves, the default +constexpr int kWaves = kBlockThreads / kWave; +constexpr int kKTile = 128; // k a staged tile covers, eight wmma steps +constexpr int kAPitch = kKTile / 2 + 4; // dwords a staged a row, the dot2 arm's 68 +constexpr int kUnit = 16; // k a wmma step consumes: a slab's law + + + +/* One dword of two f16 into the fragment's two halves: the low half first, the high half + * after -- the packed order the builtin's VGPR map expects. The cast is a bit pattern, not + * a value: the fragment is the tile's bytes, and a _Float16-from-integer conversion would + * take the integer's magnitude, not its bits. A vector element is not a modifiable lvalue, + * so the unpack is a constructor argument, not a reference target. */ +#define R3D_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \ + __builtin_bit_cast(_Float16, (uint16_t)((w) >> 16)) + +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint16_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave. + * + * `kslab` is the k range a blockIdx.y owns; with sk = 1 it is all of K and the store is the + * narrowed f16 the caller asked for. With sk > 1 every split writes its own f32 partial, + * dense [sk][M][N], and the reducer adds them in split order. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_kernel( + const uint16_t* __restrict__ A, const uint16_t* __restrict__ B, + uint16_t* __restrict__ Y, float* __restrict__ Part, + int M, int N, int K, int a_ld, int y_ld, int w_ld, int kslab) +{ + /* Staged activation in the checkpoint's own bytes, a dword array at the dot2 arm's pitch. */ + __shared__ uint32_t s_a[16 * kAPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t waves = blockDim.x / kWave; + const uint32_t r = lane & 15; // the replicated row/column index + + const uint32_t n0 = ((uint32_t)blockIdx.x * waves + wave) * 16 + r; + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + + const int kbeg = (int)blockIdx.y * kslab; + const int kend = kbeg + kslab < K ? kbeg + kslab : K; + + const uint16_t* w = B + (size_t)n_real * w_ld; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + + for (int kt = kbeg; kt < kend; kt += kKTile) { + const int kl = std::min(kKTile, kend - kt); + + /* Stage 16 rows x kl f16, eight elements a unit, 256 threads. A row past M re-reads + * the last real row, whose products the store drops; a unit past kl zero-fills. */ + const int nu = (kl + 7) / 8; + for (int i = (int)tid; i < 16 * nu; i += (int)blockDim.x) { + const int row = i / nu, c = (i % nu) * 8; + const int rr = row < M ? row : M - 1; + const uint16_t* src = A + (size_t)rr * a_ld + kt + c; + uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2; + if (c + 8 <= kl) { + const r3d_u32x4 q = *(const __attribute__((address_space(1))) r3d_u32x4*)src; + *(r3d_u32x4*)dst = q; + } else { + uint32_t p[4] = { 0, 0, 0, 0 }; + for (int e = 0; e < kl - c; e += 2) { + const uint32_t lo = ldg_u16(src + e); + const uint32_t hi = (e + 1 < kl - c) ? ldg_u16(src + e + 1) : 0u; + p[e / 2] = lo | (hi << 16); + } + for (int e = 0; e < (kl - c + 1) / 2; ++e) dst[e] = p[e]; + } + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kAPitch; + for (int k = 0; k < kl; k += 16) { + /* Eight wmma steps per tile: two 16-byte reads a lane, the row's k pair at + * dword k/2 and k/2 + 4, and the column's from global. */ + const r3d_u32x4 a0 = *(const r3d_u32x4*)(ap + k / 2); + const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + k / 2 + 4); + const r3d_u32x4 b0 = ldw(w + kt + k); + const r3d_u32x4 b1 = ldw(w + kt + k + 8); + const v16half fa = v16half{ R3D_F16(a0.x), R3D_F16(a0.y), R3D_F16(a0.z), + R3D_F16(a0.w), R3D_F16(a1.x), R3D_F16(a1.y), + R3D_F16(a1.z), R3D_F16(a1.w) }; + const v16half fb = v16half{ R3D_F16(b0.x), R3D_F16(b0.y), R3D_F16(b0.z), + R3D_F16(b0.w), R3D_F16(b1.x), R3D_F16(b1.y), + R3D_F16(b1.z), R3D_F16(b1.w) }; + acc = wmma_f16(fa, fb, acc); + } + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N); + if (!keep) return; + for (int g = 0; g < 8; ++g) { + const int m = g * 2 + (int)(lane >> 4); + if (m >= M) continue; + if constexpr (SPLIT) + Part[((size_t)blockIdx.y * M + m) * N + n0] = acc[g]; + else + Y[(size_t)m * y_ld + n0] = f32_to_f16(acc[g]); + } +} +#undef R3D_F16 + +/* The split reduction: v = ((p0 + p1) + p2) + ... in ascending split order, then one + * narrowing. The dot2 arm's, copied: the slab sums bracket the products differently than + * one chain does, and the difference is in the last bits, the split's, not a bug in it. */ +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_m16_wmma_split_reduce( + const float* __restrict__ Part, uint16_t* __restrict__ Y, int M, int N, int y_ld, int sk) +{ + const int mn = M * N; + const int stride = gridDim.x * kBlockThreads; + for (int i = blockIdx.x * kBlockThreads + threadIdx.x; i < mn; i += stride) { + const int m = i / N, n = i - m * N; + const float* p = Part + (size_t)m * N + n; + float v = p[0]; + for (int s = 1; s < sk; ++s) v = v + p[(size_t)s * M * N]; + Y[(size_t)m * y_ld + n] = f32_to_f16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T, f16 in and out, f32 accumulate, M <= 16, the wave-matrix arm. + * + * The dot2 arm's contract, with the slab law at 16 k. `sk` splits K (0 = the largest legal + * split), `wv` waves per block (0 = 8), `nt` the weight load's lowering, `scratch` the f32 + * partial arena, sk * M * N * 4 bytes, required when the split is on. Returns 0, -1 a null + * pointer, -2 a shape it does not serve, -3 a pitch it cannot read, -4 the HIP launch failed. */ +extern "C" int r3d_gemm_nt_f16_m16_wmma(long a, long b, long y, int M, int N, int K, int a_ld, + int y_ld, int sk, int wv, int nt, long scratch, + long stream) +{ + if (!a || !b || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > 16) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (sk == 0) { + static const int kLadder[] = { 16, 8, 4, 2, 1 }; + for (int s : kLadder) + if (s > 1 ? K % ((long long)s * kUnit) == 0 : true) { sk = s; break; } + } + if (sk < 1) return -2; + /* The slab is kUnit deep: a ragged tail (K % kUnit) would stage a partial unit + * the tile loop reads whole (stale dwords) and load B fragments past the weight, + * so the shape is refused, as the dot2 arm's pick_sk already does. */ + if (K % ((long long)sk * kUnit)) return -2; + if (sk > 1 && !scratch) return -1; + if (wv <= 0) wv = kWaves; + if (wv != 1 && wv != 2 && wv != 4 && wv != kWaves) return -2; + + const int kslab = K / sk; + +#define R3D_WNT(NTV) \ + do { \ + const int nt_ = (N + 15) / 16; \ + const dim3 grid((nt_ + wv - 1) / wv, (unsigned)sk), block((unsigned)(wv * kWave)); \ + if (sk > 1) { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)scratch, M, N, K, a_ld, y_ld, K, kslab); \ + const int mn = M * N; \ + const int nb = std::min((mn + kBlockThreads - 1) / kBlockThreads, 4096); \ + R3D_KLAUNCH(gemm_m16_wmma_split_reduce, dim3(nb), dim3(kBlockThreads), \ + (hipStream_t)stream, (const float*)scratch, (uint16_t*)y, M, N, y_ld, \ + sk); \ + } else { \ + R3D_KLAUNCH(R3D_KNAME((gemm_m16_wmma_kernel)), grid, block, \ + (hipStream_t)stream, (const uint16_t*)a, (const uint16_t*)b, \ + (uint16_t*)y, (float*)nullptr, M, N, K, a_ld, y_ld, K, kslab); \ + } \ + } while (0) + if (nt) R3D_WNT(true); + else R3D_WNT(false); +#undef R3D_WNT + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr3d/r3d_gemm_fp8a8_tiled.hip b/libr3d/r3d_gemm_fp8a8_tiled.hip index c77b7efe..d6628d08 100644 --- a/libr3d/r3d_gemm_fp8a8_tiled.hip +++ b/libr3d/r3d_gemm_fp8a8_tiled.hip @@ -199,40 +199,22 @@ __device__ __forceinline__ float zero_at_w(const WQ h, int n, int g) /* code * scale in f16: one v_mul_f16, round to nearest, subnormals kept. Not f16x2_pack, which * truncates (see the header). */ -__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) -{ - const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); - const _Float16 a = __builtin_bit_cast(_Float16, lo16); - const _Float16 b = __builtin_bit_cast(_Float16, hi16); - const _Float16 s = (_Float16)sc; - const _Float16 rl = a * s, rh = b * s; - return (uint32_t)__builtin_bit_cast(uint16_t, rl) | - ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); -} - -/* Eight codes -> four f16 pairs: E4M3 through the table, int8 through the codec's hardware - * convert (two v_cvt_f32_i8 and a pack). */ +/* Eight codes -> four f16 pairs. E4M3 through the ALU decode (ALU=1) or the LDS table (ALU=0); + * int8 through the codec's hardware convert (two v_cvt_f32_i8 and a pack). ALU is a template + * parameter so the two rows (the table and the ALU decode) share the kernel and the tune picks. */ +template __device__ __forceinline__ void codes8(const uint2 c, int cdt, const uint16_t* tbl, uint32_t* w) { - if (!cdt) { r3d_e4m3x8_ld(tbl, c, w); return; } + if (!cdt) { + r3d_e4m3x8_decode(tbl, c, w); + return; + } const uint32_t d[2] = { c.x, c.y }; #pragma unroll for (int j = 0; j < 4; ++j) w[j] = i8x2_to_f16x2((d[j >> 1] >> (16 * (j & 1))) & 0xffffu); } -template -__device__ __forceinline__ uint2 loadc8s(const uint8_t* p) -{ - typedef uint32_t __attribute__((ext_vector_type(2))) u8v; - u8v v; - if (NT) v = __builtin_nontemporal_load((const u8v*)p); - else __builtin_memcpy(&v, p, 8); - uint2 r; - __builtin_memcpy(&r, &v, 8); - return r; -} - /* * The tile: 128 x 128 outputs, 256 threads (eight waves), an 8x8 square a lane (64 f32 * accumulators), grid ceil(N/kTN) x ceil(M/kTM). k is walked in chunks of 32; both sides are @@ -242,19 +224,20 @@ __device__ __forceinline__ uint2 loadc8s(const uint8_t* p) * ARM 0 is fp8a8 (E4M3 or int8 weight codes); ARM 1 is the zero-point grid (U2 or U4 codes against * an int8 activation in step order). */ -template /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4 */ +template /* CDT: 0 E4M3, 1 int8, 2 U2, 3 U4; ALU: 1 decode + * in registers, 0 through the LDS table */ __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __restrict__ b, WQ h, void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld) { - __shared__ __align__(16) uint16_t sA[kTM * kKC]; - __shared__ __align__(16) uint16_t sB[kTN * kKC]; + __shared__ __align__(16) uint16_t sA[2][kTM * kKC]; + __shared__ __align__(16) uint16_t sB[2][kTN * kKC]; __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; const int tid = (int)threadIdx.x; - if (ARM == 0) { - r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16 decoder table */ - } else { + if (ARM == 0 && !ALU) { + r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* E4M3 -> f16 decoder table (ALU=0) */ + } else if (ARM != 0) { /* U2 and U4 codes are unsigned integers (at most 16 values): the table holds f16(i). */ for (int i = tid; i < 16; i += kBlockThreads) sTbl[i] = f32_to_f16((float)i); __syncthreads(); @@ -288,14 +271,17 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest * plane, so each row costs a whole 64-byte sector, 8x the bytes used. A wider k-chunk (64: 4x, * 128: 2x) would cut that, at a cost in LDS and occupancy. */ - for (int k0 = 0; k0 < K; k0 += kKC) { - const int g = k0 / kGroup; /* one group a chunk: 32 divides 128 */ + /* Stage slab KS into the BUF-th LDS plane: the A rows and the B rows (or the sub-byte weight + * codes) for k in [KS, KS + kKC), decoded and scale-folded to f16. The double-buffered walk + * calls it for slab k+1 into the other plane while slab k's dot runs, so the global codes load + * overlaps the multiply. */ + auto stage_slab = [&](int BUF, int KS) { + const int g = KS / kGroup; /* one group a chunk: 32 divides 128 */ const float sb = scale_w(h, nb, g); /* one scale for the whole tile */ - #pragma unroll for (int j = tid; j < kTM * (kKC / 8); j += kBlockThreads) { const int mm = j / (kKC / 8), c8 = j % (kKC / 8); - const int m = m0 + mm, k = k0 + c8 * 8; + const int m = m0 + mm, k = KS + c8 * 8; uint4 staged = make_uint4(0, 0, 0, 0); if (m < M) { if (ARM == 0) { @@ -303,9 +289,9 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest * (`aq.gmode` 0) the group term is selected away without a branch. */ const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; uint32_t w[4]; - codes8(loadc8s(a + (long long)m * a_ld + k), 0, sTbl, w); - staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), - fold_pair(w[2], sa), fold_pair(w[3], sa)); + codes8(r3d_loadc8(a + (long long)m * a_ld + k), 0, sTbl, w); + staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa), + r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa)); } else { /* int8 codes in quant_act_i8's step order, read a dword at the permuted * address (i8_dw), with one scale per row (ZP_I8_ROW). */ @@ -319,31 +305,31 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest #pragma unroll for (int q = 0; q < 4; ++q) w[q] = i8x2_to_f16x2((d[q >> 1] >> (16 * (q & 1))) & 0xffffu); - staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), - fold_pair(w[2], sa), fold_pair(w[3], sa)); + staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa), + r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa)); } } - *(uint4*)&sA[srow(mm, c8, kKC)] = staged; + *(uint4*)&sA[BUF][srow(mm, c8, kKC)] = staged; } if (ARM == 0) { #pragma unroll for (int j = tid; j < kTN * (kKC / 8); j += kBlockThreads) { const int nn = j / (kKC / 8), c8 = j % (kKC / 8); - const int n = n0 + nn, k = k0 + c8 * 8; + const int n = n0 + nn, k = KS + c8 * 8; uint4 staged = make_uint4(0, 0, 0, 0); if (n < N) { uint32_t w[4]; - codes8(loadc8s(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w); - staged = make_uint4(fold_pair(w[0], sb), fold_pair(w[1], sb), - fold_pair(w[2], sb), fold_pair(w[3], sb)); + codes8(r3d_loadc8(h.codes + (long long)n * h.code_row + k), h.cdt, sTbl, w); + staged = make_uint4(r3d_fold_pair(w[0], sb), r3d_fold_pair(w[1], sb), + r3d_fold_pair(w[2], sb), r3d_fold_pair(w[3], sb)); } - *(uint4*)&sB[srow(nn, c8, kKC)] = staged; + *(uint4*)&sB[BUF][srow(nn, c8, kKC)] = staged; } } else { /* The sub-byte weight: w2a8 (U2, four codes a byte, K>>2 bytes a row) or w4a8_asym * (U4, two a byte, K>>1). A thread loads a row's whole 32-code chunk at once, 8 bytes - * of U2 or 16 of U4, aligned because k0 is a multiple of 32. Scale and zero are per - * (row, group), prefetched above. */ + * of U2 or 16 of U4, aligned because KS is a multiple of 32. Scale and zero are per + * (row, group), prefetched one slab ahead. */ constexpr int BITS = (CDT == 2) ? 2 : 4; constexpr int FIELD = 2 * BITS; /* bits a pair of codes occupies */ #pragma unroll @@ -353,14 +339,14 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest make_uint4(0, 0, 0, 0), make_uint4(0, 0, 0, 0) }; if (n < N) { const _Float16 s = s_cur, zf = zf_cur; /* the group's pair, prefetched */ - if (b_has && k0 + kKC < K && (k0 + kKC) / kGroup != g) { - const int gn = (k0 + kKC) / kGroup; + if (b_has && KS + kKC < K && (KS + kKC) / kGroup != g) { + const int gn = (KS + kKC) / kGroup; s_cur = (_Float16)scale_at_w(h, b_row, gn); zf_cur = (_Float16)zero_at_w(h, b_row, gn); } uint32_t d[4] = { 0, 0, 0, 0 }; const uint8_t* cp = h.codes + (long long)n * h.code_row - + (k0 >> (CDT == 2 ? 2 : 1)); + + (KS >> (CDT == 2 ? 2 : 1)); if (CDT == 2) { uint2 v; __builtin_memcpy(&v, cp, 8); d[0] = v.x; d[1] = v.y; } else { u16v v; __builtin_memcpy(&v, cp, 16); d[0] = v.x; d[1] = v.y; d[2] = v.z; d[3] = v.w; } @@ -379,26 +365,36 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest st[3] = make_uint4(w[12], w[13], w[14], w[15]); } #pragma unroll - for (int q = 0; q < 4; ++q) *(uint4*)&sB[srow(nn, q, kKC)] = st[q]; + for (int q = 0; q < 4; ++q) *(uint4*)&sB[BUF][srow(nn, q, kKC)] = st[q]; } } - __syncthreads(); + }; + /* The double-buffered k-walk: slab 0 is staged before the loop; each iteration stages slab + * k+1 into the other LDS plane while slab k's dot runs from the current plane, then dots. One + * barrier a slab, after the dot, keeps the next slab's stage clear of the dot's LDS reads. */ + int tbuf = 0; + stage_slab(0, 0); + __syncthreads(); + for (int k0 = 0; k0 < K; k0 += kKC) { + const int k1 = k0 + kKC; + if (k1 < K) stage_slab(1 - tbuf, k1); #pragma unroll for (int kc = 0; kc < kKC; kc += 2) { uint32_t af[8], bf[8]; #pragma unroll for (int i = 0; i < 8; ++i) - af[i] = *(const uint32_t*)&sA[srow_pair(rg * 8 + i, kc, kKC)]; + af[i] = *(const uint32_t*)&sA[tbuf][srow_pair(rg * 8 + i, kc, kKC)]; #pragma unroll for (int j = 0; j < 8; ++j) - bf[j] = *(const uint32_t*)&sB[srow_pair(cg * 8 + j, kc, kKC)]; + bf[j] = *(const uint32_t*)&sB[tbuf][srow_pair(cg * 8 + j, kc, kKC)]; #pragma unroll for (int i = 0; i < 8; ++i) #pragma unroll for (int j = 0; j < 8; ++j) acc[i][j] = dot2_f16x2(af[i], bf[j], acc[i][j]); } __syncthreads(); + tbuf = 1 - tbuf; } /* y is bf16: one narrowing, 16-byte runs of eight columns. Rows past M write nothing. */ @@ -438,7 +434,8 @@ fp8a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, const uint8_t* __rest int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, int group, int a_ld, long long b_row, int as_ld, long long bs_row, int y_ld, int nt, long stream, - int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0) + int sdt, int cdt, long zv = 0, long long z_row = 0, int srows = 0, int arm = 0, + int alu = 1) { if (!av || !asv || !bvc || !bsv || !yv) return -1; if (M < 1 || N < 1 || K < 1) return -2; @@ -474,18 +471,19 @@ int launch(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, WQ h{ (const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, (const uint8_t*)(uintptr_t)zv, b_row, bs_row, z_row, sdt, cdt, srows }; hipStream_t s = (hipStream_t)(uintptr_t)stream; -#define R3D_RUN(ARM, CD) \ +#define R3D_RUN(NT, ARM, CD, AL) \ + fp8a8_tiled_kernel<<>>( \ + (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ + h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld) +#define R3D_LAUNCH(ARM, CD) \ do { \ - if (nt) fp8a8_tiled_kernel<1, ARM, CD><<>>( \ - (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ - h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ - else fp8a8_tiled_kernel<0, ARM, CD><<>>( \ - (const uint8_t*)(uintptr_t)av, aq, (const uint8_t*)(uintptr_t)bvc, \ - h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); \ + if (alu) { if (nt) R3D_RUN(1, ARM, CD, 1); else R3D_RUN(0, ARM, CD, 1); } \ + else { if (nt) R3D_RUN(1, ARM, CD, 0); else R3D_RUN(0, ARM, CD, 0); } \ } while (0) - if (arm == 0) { if (cdt == 1) R3D_RUN(0, 1); else R3D_RUN(0, 0); } - else { if (cdt == 3) R3D_RUN(1, 3); else R3D_RUN(1, 2); } + if (arm == 0) { if (cdt == 1) R3D_LAUNCH(0, 1); else R3D_LAUNCH(0, 0); } + else { if (cdt == 3) R3D_LAUNCH(1, 3); else R3D_LAUNCH(1, 2); } #undef R3D_RUN +#undef R3D_LAUNCH const hipError_t le = hipGetLastError(); if (le != hipSuccess) { if (r3d_trace_on()) @@ -627,7 +625,7 @@ static bool gemm_plan_once(long long M, long long N, long long K, unsigned a_ran return true; } -extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) +static int r3d_fp8a8_tiled_dispatch(const RadArgs* args, RadStream s, int alu) { if (!args || args->n_t < 5) return R3D_NO(RAD_E_INVAL); const RadTensor* A = r3d_opt(args, 0); @@ -814,7 +812,7 @@ extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* args, RadStream s) const int nt = (int)r3d_geti_or(args, "nt", 0); const int st = launch(r3d_addr(A), r3d_addr(AS), (long)(uintptr_t)bvc, (long)(uintptr_t)bsv, r3d_addr(Y), (int)M, (int)N, (int)K, (int)group, (int)a_ld, b_row, - (int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt); + (int)as_ld, bs_row, (int)y_ld, nt, (long)s, sdt, cdt, 0, 0, 0, 0, alu); if (st == -1) return R3D_NO(RAD_E_INVAL); if (st == -2) return R3D_NO(RAD_E_SHAPE); if (st == -3) return R3D_NO(RAD_E_STRIDE); @@ -978,3 +976,14 @@ extern "C" int r3d_rad_gemm_nt_q_w2a8_tiled(const RadArgs* args, RadStream s) if (st == -4) return R3D_NO(RAD_E_DEVICE); return RAD_OK; } + +/* The row's impl axis picks the decode: the table (0) and the ALU formula (1). The _alu entry + * point stays for a checker that names it directly. */ +extern "C" int r3d_rad_gemm_nt_q_fp8_tiled(const RadArgs* a, RadStream s) +{ + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + return r3d_fp8a8_tiled_dispatch(a, s, c.impl); +} +extern "C" int r3d_rad_gemm_nt_q_fp8_tiled_alu(const RadArgs* a, RadStream s) +{ return r3d_fp8a8_tiled_dispatch(a, s, 1); } diff --git a/libr3d/r3d_gemm_inta8.hip b/libr3d/r3d_gemm_inta8.hip index 2a847a50..e628ded1 100644 --- a/libr3d/r3d_gemm_inta8.hip +++ b/libr3d/r3d_gemm_inta8.hip @@ -46,6 +46,11 @@ #include "r3d_launch.h" #include "r3d_args.h" +/* The wave-matrix arm's launcher, in r3d_gemm_inta8_wmma.hip: the row's `impl` point 1. */ +extern "C" int r3d_gemm_nt_q_w8a8_m16_wmma(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int a_ld, int y_ld, + long long b_rb, long long sb_rb, int nt, long stream); + namespace { constexpr int kWave = 32; @@ -412,6 +417,23 @@ extern "C" int r3d_rad_gemm_nt_q_w8a8_m16(const RadArgs* a, RadStream s) if (yp < N) return R3D_NO(RAD_E_STRIDE); if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + if (c.impl == 1) { + /* The wave-matrix arm: same contract, the i8 tile's, its own launcher. */ + const int rc = r3d_gemm_nt_q_w8a8_m16_wmma(r3d_addr(A), r3d_addr(AS), r3d_addr(B), + r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, + (int)K, (int)ap, (int)yp, + (long long)r3d_row_pitch(B), + (long long)r3d_row_pitch(BS), c.nt, (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; + } + const int rc = r3d_gemm_nt_q_w8a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp, (long long)r3d_row_pitch(B), (long long)r3d_row_pitch(BS), diff --git a/libr3d/r3d_gemm_inta8_wmma.hip b/libr3d/r3d_gemm_inta8_wmma.hip new file mode 100644 index 00000000..fd9acdb5 --- /dev/null +++ b/libr3d/r3d_gemm_inta8_wmma.hip @@ -0,0 +1,219 @@ +/* r3d_gemm_inta8_wmma.hip -- the wave-matrix arm of the w8a8 grid at decode heights. + * + * y[M,N] = a[M,K] @ b[N,K]^T, int8 a against signed int8 codes, M <= 16. + * + * The dot2 arm (r3d_gemm_inta8.hip) owns one output element a lane and folds each 128 group's + * products through f16 pairs; this arm issues V_WMMA_I32_16X16X16_IU8 over a 16x16x16 tile, a + * wave a tile, and the two arms are two points of the row's `impl` axis. The tune cache picks + * the point per shape per machine; an untuned install runs the dot2 arm, which is the axis's + * default. + * + * ---- the group law -------------------------------------------------------------------------- + * + * The dot2 arm's exactness is the arm's: a group's 128 products are |a * code| <= 127 * 127, + * and their sum 2,064,512 is an exact integer far inside i32, so the eight wmma steps of a + * group chain an i32 sub-sum with no rounding at all, and the group term is the reference's + * + * acc += (sub * a_scale[m]) * b_scale[n, g] + * + * in f32, in ascending group order -- the same order the dot2 arm's shared-memory walk forms. + * What the arm changes is the issue: eight wmma where the dot2 arm issues its decoded dot4 + * folds and a pair fold, and the f16 widening the dot2 arm pays on the codes is not here at + * all, the i8 bytes going into the fragment directly. + * + * ---- where the bytes come from -------------------------------------------------------------- + * + * The activation is staged in LDS as plain i8, the step order unpermuting on the way in: the + * container's dword at logical position d sits at byte offset dword_pos(d) (the dot2 arm's + * map, its own inverse), so the staging reads the swapped position and writes the plain one. One k tile is 16 rows x 128 i8, one scale group, 2.1 KiB with the pitch, and + * carries eight wmma steps. The pitch is 33 dwords: 33 mod 32 = 1, so the lanes of a + * ds_read phase land one bank apart and the lane's single 16-byte fragment read is + * conflict-free in its phase. + * + * The weight streams from global, one 16-byte load a lane per step (column L % 16 of the + * tile, the step's 16 k), the NT axis choosing the lowering the bf16 arm's header describes. + * Every weight byte is read once per output tile, the stream the dot2 arm streams. + * + * ---- the register budget -------------------------------------------------------------------- + * + * Eight f32 accumulators, eight i32 sub-sums, four A and four B fragment VGPRs and the + * pointers: about 30 a lane. Eight waves a SIMD asks 240 of the 1024 the gfx11 SIMD keeps, + * so the quantised rows' fixed eight-wave block stands. + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kWaves = 8; +constexpr int kBlockThreads = kWaves * kWave; +constexpr int kGroup = 128; /* the scale group: one k tile, eight wmma steps */ +constexpr int kPitch = 33; /* dwords a staged a row: 33 mod 32 = 1, bank-free */ + + +/* Signed i8 in, signed i32 out: the builtin's sign selectors take the operands' signedness as + * compile-time constants, both signed for this grid. */ + +/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse -- + * the dot2 arm's, so the staging's read position is the plain position run through it. */ +__device__ __forceinline__ int64_t dword_pos(int64_t d) +{ + return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1)); +} + +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint8_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, one 16x16 tile a wave, one scale group a k tile. + * + * The dot2 arm's contract: K a multiple of the group, the group term the reference's, in + * ascending group order. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_w8a8_wmma_kernel( + const int8_t* __restrict__ a, const float* __restrict__ sa, + const uint8_t* __restrict__ B, int b_rb, const uint16_t* __restrict__ sb, + int sb_rb, uint16_t* __restrict__ Y, + int M, int N, int K, int a_ld, int y_ld) +{ + __shared__ __align__(16) uint32_t s_a[16 * kPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t r = lane & 15; // the replicated row/column index + + const uint32_t n0 = (uint32_t)blockIdx.x * kWaves * 16 + wave * 16 + r; + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + + /* The lane's eight output rows, and their activation scales, hoisted: a_scale is a row + * property, constant across the group walk. */ + float as[8]; + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int m = g2 * 2 + (int)(lane >> 4); + as[g2] = sa[m < M ? m : M - 1]; + } + + const uint8_t* w = B + (size_t)n_real * b_rb; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + + for (int g = 0; g < K / kGroup; ++g) { + const int kt = g * kGroup; + + /* Stage 16 rows x 128 i8, the step order unpermuting on the way in. A row past M + * re-reads the last real row, whose products the store drops. */ + for (int i = (int)tid; i < 16 * (kGroup / 4); i += kBlockThreads) { + const int row = i / (kGroup / 4), d = i % (kGroup / 4); + const int rr = row < M ? row : M - 1; + /* The dot2 arm's read: a_ld is in elements (bytes, for i8) and dword_pos is already + * the byte offset, the map's own inverse; kt walks the group along the row. */ + const uint32_t src = + *(const uint32_t*)(a + (size_t)rr * a_ld + kt + dword_pos(d)); + s_a[(size_t)row * kPitch + d] = src; + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kPitch; + v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int k = 0; k < kGroup; k += 16) { + const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4); + const r3d_u32x4 bq = ldw(w + kt + k); + sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w }, + v4int{ (int)bq.x, (int)bq.y, (int)bq.z, (int)bq.w }, sub); + } + /* The group term, the reference's parentheses, in ascending group order. The b_scale + * load, its drain, its convert, and the eight fmacs run as one asm block: the load + * goes straight from global (staging it through LDS lets the scheduler move the + * store past the barrier, so a group reads its predecessor's scale), the drain is a + * vmcnt this asm owns, and the scale's register is written only by this block's + * global_load, so no fragment load can clobber it mid-group. v20 is named in the + * clobber because this LLVM aliases a constrained asm output with a dead input + * register; the clobber keeps every t/acc/sub register out of v20 across the block. + * The hardware f16->f32 is exact for normals; subnormal halves flush to 0, below any + * scale this kernel sees and far below the quantisation noise. */ + float t[8]; + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) + t[g2] = (float)sub[g2] * as[g2]; + { + const uint64_t ga = (uint64_t)(sb + (size_t)n_real * sb_rb + g); + asm volatile( + "global_load_u16 v20, %[ga], off\n\t" + "s_waitcnt vmcnt(0)\n\t" + "v_cvt_f32_f16_e32 v20, v20.l\n\t" + "v_fmac_f32_e32 %[a0], %[t0], v20\n\t" + "v_fmac_f32_e32 %[a1], %[t1], v20\n\t" + "v_fmac_f32_e32 %[a2], %[t2], v20\n\t" + "v_fmac_f32_e32 %[a3], %[t3], v20\n\t" + "v_fmac_f32_e32 %[a4], %[t4], v20\n\t" + "v_fmac_f32_e32 %[a5], %[t5], v20\n\t" + "v_fmac_f32_e32 %[a6], %[t6], v20\n\t" + "v_fmac_f32_e32 %[a7], %[t7], v20" + : [a0] "+v"(acc[0]), [a1] "+v"(acc[1]), [a2] "+v"(acc[2]), [a3] "+v"(acc[3]), + [a4] "+v"(acc[4]), [a5] "+v"(acc[5]), [a6] "+v"(acc[6]), [a7] "+v"(acc[7]) + : [ga] "v"(ga), + [t0] "v"(t[0]), [t1] "v"(t[1]), [t2] "v"(t[2]), [t3] "v"(t[3]), + [t4] "v"(t[4]), [t5] "v"(t[5]), [t6] "v"(t[6]), [t7] "v"(t[7]) + : "v20"); + } + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N); + if (!keep) return; + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int m = g2 * 2 + (int)(lane >> 4); + if (m < M) Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[g2]); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T over the w8a8 grid, the wave-matrix arm. + * + * The dot2 arm's contract: K a multiple of the group, the group term the reference's. `nt` + * picks the weight load's lowering. Returns 0, -1 a null pointer, -2 a shape it does not + * serve, -3 a pitch it cannot read, -4 the HIP launch failed, -5 an alignment it cannot + * read. */ +extern "C" int r3d_gemm_nt_q_w8a8_m16_wmma(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int a_ld, int y_ld, + long long b_rb, long long sb_rb, int nt, long stream) +{ + if (!a || !a_scale || !b || !b_scale || !y) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (M > 16) return -2; + if (K % kGroup) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld % 4) return -3; + if (y_ld < N) return -3; + if (!b_rb) b_rb = K; + if (b_rb < K) return -3; + if (b_rb & 15) return -5; + if (!sb_rb) sb_rb = K / kGroup; + if (sb_rb < K / kGroup) return -3; + if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; + + const dim3 grid((N + kWaves * 16 - 1) / (kWaves * 16)), block(kBlockThreads); + if (nt) + R3D_KLAUNCH(gemm_w8a8_wmma_kernel, grid, block, (hipStream_t)stream, + (const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, + (const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld); + else + R3D_KLAUNCH(gemm_w8a8_wmma_kernel, grid, block, (hipStream_t)stream, + (const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, + (const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr3d/r3d_gemm_mxfp4a8.hip b/libr3d/r3d_gemm_mxfp4a8.hip index fcdd7f4b..759efd7b 100644 --- a/libr3d/r3d_gemm_mxfp4a8.hip +++ b/libr3d/r3d_gemm_mxfp4a8.hip @@ -120,46 +120,6 @@ __device__ __forceinline__ float e8_scale(uint8_t e) return (e == 0 || e == 255) ? 0.0f : ldexpf(1.0f, (int)e - 127); } -/* Four e4m3 bytes (one dword, low byte first) as two f16x2, through the block's table. The - * table entries are f16 bit patterns, so the words are moves, not conversions. */ -__device__ __forceinline__ void e4m3x4_to_f16x2(const uint16_t* tbl, uint32_t w, uint32_t* o) -{ - o[0] = (uint32_t)tbl[w & 0xffu] | ((uint32_t)tbl[(w >> 8) & 0xffu] << 16); - o[1] = (uint32_t)tbl[(w >> 16) & 0xffu] | ((uint32_t)tbl[(w >> 24) & 0xffu] << 16); -} - -/* code * scale, in f16 arithmetic: one v_mul_f16, round to nearest, subnormals kept. Not - * f16x2_pack, which truncates. */ -__device__ __forceinline__ uint32_t fold_pair(uint32_t w, float sc) -{ - const uint16_t lo16 = (uint16_t)(w & 0xffffu), hi16 = (uint16_t)(w >> 16); - const _Float16 a = __builtin_bit_cast(_Float16, lo16); - const _Float16 b = __builtin_bit_cast(_Float16, hi16); - const _Float16 s = (_Float16)sc; - const _Float16 rl = a * s, rh = b * s; - return (uint32_t)__builtin_bit_cast(uint16_t, rl) - | ((uint32_t)__builtin_bit_cast(uint16_t, rh) << 16); -} - -/* Eight codes -> eight f16, through the table. gfx11 has no E4M3 convert, so the 256-entry - * f16 table stands in for the instruction. */ -__device__ __forceinline__ void codes8(const uint2 c, const uint16_t* tbl, uint32_t* w) -{ - r3d_e4m3x8_ld(tbl, c, w); -} - -template -__device__ __forceinline__ uint2 loadc8s(const uint8_t* p) -{ - typedef uint32_t __attribute__((ext_vector_type(2))) u8v; - u8v v; - if (NT) v = __builtin_nontemporal_load((const u8v*)p); - else __builtin_memcpy(&v, p, 8); - uint2 r; - __builtin_memcpy(&r, &v, 8); - return r; -} - /* ================================================================== the tiled row */ struct ActQ { @@ -182,7 +142,7 @@ struct MxWQ { * are staged as f16 with their scale folded in. The weight's e2m1 nibbles unpack to e4m3 and are * staged as f16 without the block scale, which is applied to the partials at the chunk's end. */ -template +template /* ALU: 1 decode in registers, 0 through the LDS table */ __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld) @@ -193,7 +153,7 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res __shared__ uint8_t sE8[kTN]; /* the chunk's e8, one per tile row */ const int tid = (int)threadIdx.x; - r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); + if (!ALU) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); const int m0 = (int)blockIdx.y * kTM; const int n0 = (int)blockIdx.x * kTN; @@ -220,9 +180,9 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res if (m < M) { const float sa = aq.scale[(long long)m * aq.row + (aq.gmode ? g : 0)]; uint32_t w[4]; - codes8(loadc8s(a + (long long)m * a_ld + k), sTbl, w); - staged = make_uint4(fold_pair(w[0], sa), fold_pair(w[1], sa), - fold_pair(w[2], sa), fold_pair(w[3], sa)); + r3d_e4m3x8_decode(sTbl, r3d_loadc8(a + (long long)m * a_ld + k), w); + staged = make_uint4(r3d_fold_pair(w[0], sa), r3d_fold_pair(w[1], sa), + r3d_fold_pair(w[2], sa), r3d_fold_pair(w[3], sa)); } *(uint4*)&sA[srow(mm, c8, kKC)] = staged; } @@ -244,8 +204,8 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res for (int q = 0; q < 4; ++q) { uint32_t lo, hi; mxfp4_unpack8(d[q], &lo, &hi); - e4m3x4_to_f16x2(sTbl, lo, w + 4 * q); - e4m3x4_to_f16x2(sTbl, hi, w + 4 * q + 2); + r3d_e4m3x4_decode(sTbl, lo, w + 4 * q); + r3d_e4m3x4_decode(sTbl, hi, w + 4 * q + 2); } st[0] = make_uint4(w[0], w[1], w[2], w[3]); st[1] = make_uint4(w[4], w[5], w[6], w[7]); @@ -317,7 +277,7 @@ mxfp4a8_tiled_kernel(const uint8_t* __restrict__ a, ActQ aq, MxWQ h, void* __res * a bijection on 16-quad groups. */ __device__ __forceinline__ int p_ix(int q) { return q ^ ((q >> 4) & 15); } -template +template /* ALU: 1 decode in registers, 0 through the LDS table */ __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ sa, int sa_stride, const uint8_t* __restrict__ b, const uint8_t* __restrict__ e8, @@ -342,7 +302,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ const int kl = lane / MT; const int nchunk = K / chunk; - r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads); + if (!ALU) r3d_e4m3_f16_init(sTbl, threadIdx.x, kBlockThreads); float acc = 0.0f; for (int ch = 0; ch < nchunk; ++ch) { @@ -358,9 +318,9 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ const uint32_t w = *(const uint32_t*)(a + (long long)r * a_pitch + k0); const float s = sa[(long long)r * sa_stride + k0 / kGroup]; uint32_t w2[2]; - e4m3x4_to_f16x2(sTbl, w, w2); - lo = fold_pair(w2[0], s); - hi = fold_pair(w2[1], s); + r3d_e4m3x4_decode(sTbl, w, w2); + lo = r3d_fold_pair(w2[0], s); + hi = r3d_fold_pair(w2[1], s); } const int q = r * (chunk >> 2) + c; sA[p_ix(q)] = make_uint2(lo, hi); @@ -386,7 +346,7 @@ gemm_mxfp4a8_m16_kernel(const uint8_t* __restrict__ a, const float* __restrict__ #pragma unroll for (int e = 0; e < 2; ++e) { uint32_t w2[2]; - e4m3x4_to_f16x2(sTbl, e ? ehi : elo, w2); + r3d_e4m3x4_decode(sTbl, e ? ehi : elo, w2); const uint2 av = sA[p_ix(qb + 2 * v + e)]; p = dot4_f16x4(av.x, av.y, w2[0], w2[1], p); } @@ -439,7 +399,7 @@ static int mt_for(int M) extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_scale, long y, int M, int N, int K, int group, int a_ld, int y_ld, - long long e8_row, long stream) + long long e8_row, long stream, int alu = 1) { if (!a || !a_scale || !b || !b_scale || !y) return -1; if (M < 1 || N < 1 || K < 1) return -2; @@ -460,20 +420,19 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; const dim3 grid((N + kWaves - 1) / kWaves), block(kBlockThreads); -#define R3D_MXFP4A8_M16(MT) \ + #define R3D_MXFP4A8_M16(MT) \ do { \ - R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel)), grid, block, (hipStream_t)stream, \ - (const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \ - (const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \ - y_ld); \ + if (alu) \ + R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel)), grid, block, (hipStream_t)stream, \ + (const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \ + (const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \ + y_ld); \ + else \ + R3D_KLAUNCH(R3D_KNAME((gemm_mxfp4a8_m16_kernel)), grid, block, (hipStream_t)stream, \ + (const uint8_t*)a, (const float*)a_scale, K / kGroup, (const uint8_t*)b, \ + (const uint8_t*)b_scale, (int)e8_row, (uint16_t*)y, M, N, K, chunk, a_ld, \ + y_ld); \ } while (0) - switch (mt) { - case 1: R3D_MXFP4A8_M16(1); break; - case 2: R3D_MXFP4A8_M16(2); break; - case 4: R3D_MXFP4A8_M16(4); break; - case 8: R3D_MXFP4A8_M16(8); break; - default: R3D_MXFP4A8_M16(16); break; - } #undef R3D_MXFP4A8_M16 return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -489,7 +448,7 @@ extern "C" int r3d_gemm_nt_q_mxfp4a8_m16(long a, long a_scale, long b, long b_sc int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, int N, int K, int group, int a_ld, long long b_row, int as_ld, long long e8_row, - int y_ld, int nt, long stream) + int y_ld, int nt, long stream, int alu = 1) { if (!av || !asv || !bvc || !bsv || !yv) return -1; if (M < kMMin || N < 1 || K < 1) return -2; @@ -516,20 +475,27 @@ int launch_mxfp4a8_tiled(long av, long asv, long bvc, long bsv, long yv, int M, ActQ aq{(const float*)(uintptr_t)asv, (long long)as_ld, 1}; MxWQ h{(const uint8_t*)(uintptr_t)bvc, (const uint8_t*)(uintptr_t)bsv, b_row, e8_row}; hipStream_t s = (hipStream_t)(uintptr_t)stream; - if (nt) mxfp4a8_tiled_kernel<1><<>>( - (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); - else mxfp4a8_tiled_kernel<0><<>>( - (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + if (alu) { + if (nt) mxfp4a8_tiled_kernel<1,1><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + else mxfp4a8_tiled_kernel<0,1><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + } else { + if (nt) mxfp4a8_tiled_kernel<1,0><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + else mxfp4a8_tiled_kernel<0,0><<>>( + (const uint8_t*)(uintptr_t)av, aq, h, (void*)(uintptr_t)yv, M, N, K, a_ld, y_ld); + } return hipGetLastError() == hipSuccess ? 0 : -4; } extern "C" int r3d_gemm_nt_q_mxfp4a8_tiled(long a, long a_scale, long b_codes, long b_scale, long y, int M, int N, int K, int group, int a_ld, long long b_row, int as_ld, long long e8_row, - int y_ld, int nt, long stream) + int y_ld, int nt, long stream, int alu) { return launch_mxfp4a8_tiled(a, a_scale, b_codes, b_scale, y, M, N, K, group, a_ld, b_row, - as_ld, e8_row, y_ld, nt, stream); + as_ld, e8_row, y_ld, nt, stream, alu); } /* ================================================================== the shims @@ -560,7 +526,7 @@ static bool e8_scan_once(const void* p, long long n) return true; } -extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s) +static int r3d_mxfp4a8_m16_dispatch(const RadArgs* a, RadStream s, int alu) { if (!a) return R3D_NO(RAD_E_INVAL); const char* dt = r3d_gets(a, "dtype"); @@ -620,7 +586,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s) const int rc = r3d_gemm_nt_q_mxfp4a8_m16(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, (int)K, kGroup, (int)ap, (int)yp, (long long)r3d_row_pitch(BS), - (long)s); + (long)s, alu); if (rc == -1) return R3D_NO(RAD_E_INVAL); if (rc == -2) return R3D_NO(RAD_E_SHAPE); if (rc == -3) return R3D_NO(RAD_E_STRIDE); @@ -629,7 +595,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s) return RAD_OK; } -extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s) +static int r3d_mxfp4a8_tiled_dispatch(const RadArgs* a, RadStream s, int alu) { if (!a) return R3D_NO(RAD_E_INVAL); const char* dt = r3d_gets(a, "dtype"); @@ -708,7 +674,7 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s) const int rc = r3d_gemm_nt_q_mxfp4a8_tiled(r3d_addr(A), r3d_addr(AS), r3d_addr(B), r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, (int)K, kGroup, (int)ap, cp, (int)as_p, e8p, - (int)yp, nt, (long)s); + (int)yp, nt, (long)s, alu); if (rc == -1) return R3D_NO(RAD_E_INVAL); if (rc == -2) return R3D_NO(RAD_E_SHAPE); if (rc == -3) return R3D_NO(RAD_E_STRIDE); @@ -717,4 +683,23 @@ extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s) return RAD_OK; } +/* The rows' impl axis picks the E4M3 decode: the LDS table (0) and the per-byte ALU formula (1). + * The _alu entry points stay for a checker that names them directly. */ +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16(const RadArgs* a, RadStream s) +{ + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + return r3d_mxfp4a8_m16_dispatch(a, s, c.impl); +} +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_m16_alu(const RadArgs* a, RadStream s) +{ return r3d_mxfp4a8_m16_dispatch(a, s, 1); } +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s) +{ + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + return r3d_mxfp4a8_tiled_dispatch(a, s, c.impl); +} +extern "C" int r3d_rad_gemm_nt_q_mxfp4a8_tiled_alu(const RadArgs* a, RadStream s) +{ return r3d_mxfp4a8_tiled_dispatch(a, s, 1); } + } // namespace diff --git a/libr3d/r3d_gemm_w4a16_nt_m64.hip b/libr3d/r3d_gemm_w4a16_nt_m64.hip new file mode 100644 index 00000000..3f2c2a93 --- /dev/null +++ b/libr3d/r3d_gemm_w4a16_nt_m64.hip @@ -0,0 +1,623 @@ +/* r3d_gemm_w4a16_nt_m64.hip -- the 4-bit-weight, f16-activation GEMM, M up to 64. + * + * y[M,N] = a[M,K] @ dequant(wq)[N,K]^T, f32 accumulate, narrowed once by the store. + * + * The band is speculative verify and the small prefill chunks, where M is 8 to 64 and the + * weight is still the cost: a wave owns NPW column tiles by MT row tiles and streams the + * weight once. This is the RDNA3 form of the row's RDNA4 sibling. The instruction is the + * same 16x16x16 f16 tile the card's own f16 row runs, but the tile's fragment map is not + * the RDNA4 one, and the port is what the map implies, not a transcription of the other + * card's kernel: + * + * A fragment: lane L holds row L % 16, the tile's sixteen k, replicated across L / 16 + * B fragment: lane L holds column L % 16, the tile's sixteen k, replicated across L / 16 + * C / D: lane L, VGPR g, holds D[g * 2 + L / 16][L % 16] + * + * (the map the f16 m16 row states, probed green on this card). RDNA4's tile scatters eight + * k a lane "two runs of four" across the half-wave; this one is k-contiguous. The + * consequence is that the tile's natural load is a row's own bytes, and the weight is read + * in the container's stored order -- no permutation, no relayout, the library's own rule: + * a lane's step load is its column's eight codes, a 64-bit read eight bytes down the row a + * step, and a row's 128-byte cache line serves sixteen of its steps, so the line is fully + * consumed before it goes. + * + * The grid is the asymmetric one: unsigned 4-bit codes, an f16 scale and an integer zero + * per 128 of K, an f16 activation. It is the form the quantisers write (compressed-tensors' + * W4A16_ASYM and AutoRound's) and the one the reference library serves, which is what the + * selftest compares against. The symmetric grid (two's-complement nibbles, the zero fixed at + * 8) is the same kernel with one XOR per dword and a fixed zero in the packer. + * + * ---- the dequant -------------------------------------------------------------------------- + * + * The codes run the f16 tile on an offset: `0x6400 | n` is exactly the f16 for 1024 + n + * (1024 = 2^10, n < 16 sits in the f16's low mantissa bits), so a nibble becomes a tile + * element with one or, and the zero point is added as a packed f16 constant, -(1024 + zero). + * The subtraction is exact (integers below 2048 in f16's mantissa), and the group scale is + * applied to the f32 accumulator at the group's end. The scale is NOT folded into the + * fragment: fma(1024 + n, s, -(1024 + z) * s) cancels ~1024*s against a result of ~4*s, an + * error of ~12%. + * + * A is f16 and is staged through LDS one 16-row tile at a time: the block copies the tile's + * 16 x (group/8) 16-byte units (the m16 row's pitch, 128 + 8 f16), a barrier, and the + * fragment reads are two 16-byte LDS loads a lane a step. The stage loop is a count loop + * with a per-iteration guard, not a strided `tid; <; += blockDim` -- this backend + * wave-specialises the strided form at small blocks and the upper wave's iterations vanish + * (probed: the wave-1 rows came back NaN, three loop forms, byte-identical). C is bf16, + * narrowed once at the store. + * + * ---- split-K and the reduction ------------------------------------------------------------- + * + * `sk` splits K into contiguous slabs of whole 128-wide groups, one per *block*: grid.y is + * (m-tile group, k-split), the block's columns and row tiles come from its own y index, and + * the partial tiles land in a global scratch plane (a grow-only device pool, no per-call + * sync) that a separate reduce kernel sums and narrows. The block-level form is what the + * wave-matrix m16 row runs; a wave-level split on a block-cooperative A stage is a race in + * one LDS tile (probed: the split wave's row-0 fragment held its sibling's k slab). The + * slab sums bracket the products differently than one chain does; the difference is in the + * last bits and is the split's, not a bug in it. + * + * ---- the register budget -------------------------------------------------------------------- + * + * NPW*MT accumulators of eight f32, one A fragment of sixteen f16, one B fragment: at the + * 128-VGPR ceiling of a 1024-thread workgroup the backend cannot carry four column tiles a + * wave with more than one row tile (probed: the wmma expansion's A-fragment loads collapse + * and half the tile's rows come back NaN), so the launcher declines `npw == 4 && mb > 1` + * and the tuning path selects around it. `wv` and `sk` are bounded at 32 each: the block + * is WV*32 threads and the split is grid, not workgroup. + */ + +#include +#include +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" +#include "rad_planes.h" + +#include +#include +#include + +namespace { + +constexpr int kMaxM = 64; // the band's upper bound +constexpr int kGroup = 128; // K per (scale, zero) +constexpr int kStep = 16; // k a wmma step (a B fragment) covers +constexpr int kWave32 = 32; +constexpr int kAPitch = 68; // dwords per staged A row (128 + 8 f16, the m16 pitch) + + +/* One dword of two f16 into the fragment's two halves, low first: the packed order the + * builtin's VGPR map wants, a bit pattern not a value (the f16 m16 row's R3D_F16). */ +#define R3D_W4_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \ + __builtin_bit_cast(_Float16, (uint16_t)((w) >> 16)) + +/* Two dwords of sixteen 4-bit codes (k 0..7 in w0, k 8..15 in w1) -> one 16x16x16 f16 B + * fragment, minus the zero point. Element e is the code for k = e, the k-contiguous map the + * card's tile wants. + * + * The value is code - zero, computed as an integer and converted once per element: the range + * is [-255, 15], exact in f16. The offset form (1024 + n) + (-(1024 + zero)) looks cheaper + * but is not this card: built through packed half pairs it loses registers across the + * unrolled WMMA chain -- probed, the zero point survived in one half of the first pair and + * the code vanished from the load. Integer math plus a constructor list has no union views + * and no half arithmetic to alias. */ +__device__ __forceinline__ v16half dequant(unsigned w0, unsigned w1, int z) +{ + const int c0 = (int)(w0 & 0xFu) - z, c1 = (int)((w0 >> 4) & 0xFu) - z; + const int c2 = (int)((w0 >> 8) & 0xFu) - z, c3 = (int)((w0 >> 12) & 0xFu) - z; + const int c4 = (int)((w0 >> 16) & 0xFu) - z, c5 = (int)((w0 >> 20) & 0xFu) - z; + const int c6 = (int)((w0 >> 24) & 0xFu) - z, c7 = (int)((w0 >> 28) & 0xFu) - z; + const int c8 = (int)(w1 & 0xFu) - z, c9 = (int)((w1 >> 4) & 0xFu) - z; + const int c10 = (int)((w1 >> 8) & 0xFu) - z, c11 = (int)((w1 >> 12) & 0xFu) - z; + const int c12 = (int)((w1 >> 16) & 0xFu) - z, c13 = (int)((w1 >> 20) & 0xFu) - z; + const int c14 = (int)((w1 >> 24) & 0xFu) - z, c15 = (int)((w1 >> 28) & 0xFu) - z; + return v16half{ __float2half((float)c0), __float2half((float)c1), + __float2half((float)c2), __float2half((float)c3), + __float2half((float)c4), __float2half((float)c5), + __float2half((float)c6), __float2half((float)c7), + __float2half((float)c8), __float2half((float)c9), + __float2half((float)c10), __float2half((float)c11), + __float2half((float)c12), __float2half((float)c13), + __float2half((float)c14), __float2half((float)c15) }; +} + +/* A block barrier the backend cannot move. The bare __syncthreads() is not enough on this + * toolchain: in unrolled straight-line regions it reorders LDS traffic across the barrier + * (probed: the stage's stores rotated to after the fragment reads; the reduction's fill + * crossed its barrier and the MB > 1 and split-K cases read stale slots). The empty + * memory-clobbered asm is an opaque side effect no pass moves memory ops across. */ +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +/* y[M,N] = a[M,K] @ dequant(wq)[N,K]^T. MT row tiles a block, NPW column tiles a wave, SK + * split-K slabs a wave group; the slab partials reduce in the block's dynamic LDS. + * + * Wq is the codes in the container's order, [N][K/2] bytes, row n's k contiguous. Bsz is + * the joined (scale, zero) operand, rad.planes: off_scale and off_zero are the byte + * offsets of the scale plane, [N][K/128] f16, and the zero plane, [N][K/128] u8. */ +/* minBlocks 1: the bare 1024 bound caps the register file at ~16 VGPRs a thread (32 waves a + * CUA), which spills every accumulator to the stack and the spill traffic corrupts the LDS + * fill (probed: the split-K plane came back half-filled and the MB > 1 tiles mispaired). */ +template +__global__ __launch_bounds__(1024, 1) void r3d_w4a16_m64_kernel( + const unsigned short* __restrict__ A, const unsigned char* __restrict__ Wq, + const unsigned char* __restrict__ Bsz, size_t off_scale, size_t off_zero, + __hip_bfloat16* __restrict__ C, float* __restrict__ Scr, + int M, int K, int N, int a_ld, int y_ld, int WV, int SK, int MTb) +{ + /* Staged activation, the f16 m16 row's formulation, one 16-row tile: the row tiles run + * as an outer loop over this single stage (the 16*MT stage miscompiles, probed). + * Function scope: a block-scoped __shared__ here makes the backend's LDS alias analysis + * drop most of the stage's stores (probed: the fragment reads came back stale and + * row-independent). Pitch 136 f16 (68 dwords) = 128 + 8, the m16 pitch. */ + __shared__ uint32_t s_a[16 * kAPitch]; + + /* The split is a BLOCK split, the f16 m16 row's formulation: blockIdx.y = (m tile, + * k split). A wave-level split cannot share the block-cooperative A stage -- two split + * waves staging their own slabs into the one LDS tile race and each wave's fragments + * come back row-mixed (probed: a split wave's row-0 fragment held the other split's + * k slab). */ + const int tid = threadIdx.x, wave = tid / kWave32, lane = tid % kWave32; + const int col_local = wave; + const int ksplit = blockIdx.y % SK; + const int nt0 = (blockIdx.x * WV + col_local) * NPW; + const int n0 = nt0 * 16; + const int mt0 = (blockIdx.y / SK) * MT; + const int Ks = K / SK; + const int steps = Ks / kStep; + const int kbase = ksplit * Ks; + const int G = K / kGroup; + + v8float acc[NPW][MT]; +#pragma unroll + for (int j = 0; j < NPW; j++) +#pragma unroll + for (int i = 0; i < MT; i++) acc[j][i] = (v8float)(0.f); + + if (n0 < N) { + /* Weight: the lane's column, eight bytes a step, eight bytes down the row a step. + * The half-wave above replicates the same column. */ + const int ntlast = N / 16 - 1; + const unsigned char* pw[NPW]; + const unsigned short* ps[NPW]; + const unsigned char* pz[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) { + const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; + const size_t row = (size_t)t * 16 + (lane & 15); + pw[j] = Wq + row * (K / 2) + kbase / 2; + ps[j] = (const unsigned short*)(Bsz + off_scale) + row * G; + pz[j] = (Bsz + off_zero) + row * G; + } + + /* Activation staged in LDS, the f16 m16 row's formulation. Streaming the fragments + * straight from global miscompiles on this toolchain: the unrolled chain's per-step + * loads fold the runtime row stride to the tile's width, so every lane reads the + * first rows and the products come out row-mixed (probed flat across all rows). + * Through LDS the fragment address is a constexpr pitch -- no runtime stride in the + * read the wmma chain consumes. + * + * The stage is ONE 16-row tile and the row tiles run as an outer loop: a + * 16*MT-row stage with the tile index in the fragment read is a miscompile trap + * (probed: the MT > 1 fragments came back e-row mixed, half the tile NaN). One + * tile at a time is the shape the MT == 1 path proves, and it costs the W codes a + * re-read per tile, which L2 serves. */ + const int spg = kGroup / kStep; // steps per group + const int spg_rt = (K % kGroup) + kGroup / kStep; + const int ngroups = steps / spg; + + for (int i = 0; i < MT; i++) { + const int mrow_base = (mt0 + i) * 16; + for (int g = 0; g < ngroups; g++) { + /* Stage 16 rows x 128 f16 of the group's slab, eight f16 a unit. A row past + * M re-reads the last real row, whose products the store drops. + * + * The unit count is carried as a runtime value the way the f16 m16 row does: + * with a compile-time divisor the backend's i/16 strength reduction drops + * the pitch multiply from the 64-bit LDS offset (probed: the stage stored + * every unit at dword i/16 and the fragments came back stale). K % kGroup + * is 0 by the launcher's contract, so this is 16. */ + const int kslab = kbase + g * kGroup; + const int nu = (K % kGroup) + kGroup / 8; + const int nunits = 16 * nu; + /* The stage runs an explicit wave loop: a strided block loop with more than + * one iteration a thread is a trap at small blocks -- the backend + * wave-specialises it and the upper wave's iterations vanish behind its + * exec mask (probed at 64 threads: the wave-1 rows staged nothing and came + * back NaN, identically across three loop forms). With the wave spelled out + * the per-wave work is a distinct loop nest and nothing to CSE away; the + * cost is that every thread walks every wave's units and the guard keeps + * the non-owning threads from storing. */ + const int nwaves = (int)blockDim.x / kWave32; + const int nstride = (int)blockDim.x; + const int niter = (nunits + nstride - 1) / nstride; +#pragma unroll 1 + for (int w = 0; w < nwaves; w++) { + const int wtid = w * kWave32 + lane; +#pragma unroll 1 + for (int k = 0; k < niter; k++) { + const int ui = wtid + k * nstride; + /* No per-wave ownership: a wave whose column group is past N skips + * the whole block, so with an ownership guard the tile's tail rows + * never stage and the D rows they feed come out corrupt (probed: + * N = 64, an eight-wave block, four live column groups, every row + * off by the missing A rows). The tile is 16 x 128 f16 and the + * extra stores are same-value duplicates, ordered by the barrier. */ + if (ui < nunits) { + const int row = ui / nu, c = (ui % nu) * 8; + const int mrow = mrow_base + row; + const int mr = mrow < M ? mrow : M - 1; + /* The offset in one 32-bit sum, one 64-bit add: a 64-bit + * add *chain* (mr*K + kslab + c, each term promoted) is a + * trap here -- the kslab term dropped from the lowering + * (probed: a split block's A slab read from kbase 0 while + * its W codes read from the right base). */ + const unsigned short* src = A + (size_t)(mr * a_ld + kslab + c); + uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2; + *(r3d_u32x4*)dst = *(const r3d_u32x4*)src; + } + } + } + R3D_BARRIER(); + + float sc[NPW]; + int z[NPW]; + /* The planes are indexed by the absolute group; g is the block's local + * group, so a split block must offset by its base (probed: split block 1 + * dequantised with group 0's scale and zero and the partials summed wrong). */ + const int g_abs = kbase / kGroup + g; +#pragma unroll + for (int j = 0; j < NPW; j++) { + /* The codec's integer conversion, not __half2float: this toolchain's + * builtin returns the raw half bits as a float (probed: 0x3C00 came + * back as 15360.0), which silently scales every group by the bits. */ + sc[j] = f16_to_f32((uint16_t)ps[j][(size_t)g_abs]); + z[j] = (int)pz[j][(size_t)g_abs]; + } + + /* The first WMMA of a group takes an inline zero for C, so no clear is + * needed. The step count is a runtime value, the way the f16 m16 row keeps + * its k loop: with a compile-time count the steps unroll to a + * straight-line block and the backend rotates the group loop, moving the + * stage past the barrier to after the reads. */ + v8float g_acc[NPW]; + for (int s = 0; s < spg_rt; s++) { + const int u = g * spg + s; + unsigned long long wb[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) { + /* Eight bytes a step: sixteen 4-bit codes, eight of them a dword. */ + wb[j] = NT ? __builtin_nontemporal_load((const unsigned long long*)(pw[j] + 8 * u)) + : *(const unsigned long long*)(pw[j] + 8 * u); + } +#pragma unroll + for (int j = 0; j < NPW; j++) { + const v16half bfrag = + dequant((unsigned)wb[j], (unsigned)(wb[j] >> 32), z[j]); + const uint32_t* ap = s_a + (size_t)(lane & 15) * kAPitch + s * 8; + const r3d_u32x4 a0 = *(const r3d_u32x4*)ap; + const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + 4); + const v16half afrag = v16half{ R3D_W4_F16(a0.x), R3D_W4_F16(a0.y), + R3D_W4_F16(a0.z), R3D_W4_F16(a0.w), + R3D_W4_F16(a1.x), R3D_W4_F16(a1.y), + R3D_W4_F16(a1.z), R3D_W4_F16(a1.w) }; + g_acc[j] = s == 0 ? wmma_f16(afrag, bfrag, (v8float)(0.f)) + : wmma_f16(afrag, bfrag, g_acc[j]); + } + } + /* All-runtime loops. This toolchain's unrolled index math is a miscompile + * trap (probed across builds: an unrolled fold mispaired e == 0 with the + * previous tile's e == 7 register). Runtime trip counts keep the register + * handling honest; the loop is tiny. */ + for (int j = 0; j < NPW; j++) + for (int e = 0; e < kWave32 / 4; e++) + acc[j][i][e] = fmaf(g_acc[j][e], sc[j], acc[j][i][e]); + R3D_BARRIER(); // the next slab's stage must not race these reads + } + } + } + + /* Epilogue. The D map: acc element e is output row 2e + lane/16, column lane%16. + * + * Store straight from the lane's registers, to the output (SK == 1) or to the global + * split-partial arena (SK > 1, summed by r3d_w4a16_split_reduce). The dynamic-LDS + * partial plane this used to run through is a miscompile trap on this toolchain, + * probed across many builds: the fill fused with the read loop, an e * 32 stride + * collapsed to e * 8, a lane * 8 index lost its lane / 16 bit. Global stores have + * none of that surface. */ + const int ncols = WV * NPW; + for (int i = 0; i < MT; i++) { + const int m0 = (mt0 + i) * 16; + for (int j = 0; j < NPW; j++) { + const int n0 = (nt0 + j) * 16; + const int col_g = blockIdx.x * ncols + (col_local * NPW + j); + for (int e = 0; e < kWave32 / 4; e++) { + const int m = m0 + 2 * e + (lane >> 4); + const int n = n0 + (lane & 15); + if (SK == 1) { + /* Integer-narrowed store: a bf16-typed store on this toolchain lowers + * through a numeric f32->bf16->integer conversion that replaces the + * half bits with the rounded value's bits; the codec's bit manipulation + * returns the bits straight. */ + if (m < M && n < N) + ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(acc[j][i][e]); + } else { + /* The partial plane is fully sized: clamped rows store too, the reduce + * drops them. The pool is sized for ntiles, and the grid's last column + * group strides past it when ntiles % ncols != 0. */ + if (col_g < N / 16) { + const size_t o = + (((size_t)col_g * SK + ksplit) * MTb + i) * 256 + (e * kWave32 + lane); + Scr[o] = acc[j][i][e]; + } + } + } + } + } +} + +/* The f16-accumulator arm is shelved, and the reason is the card's, probed on this one: + * the f16-acc instruction takes a compile-time column selector and computes a 16-wide + * column window of the 32-column space, and its 16x16 D tile carries only 15 rows -- + * rows 1..15 of the A tile, row 0 absent (the 256 fragment slots hold 15 rows x 16 + * columns and 16 pass-through halves). A 16-row M tile loses a row on every tile + * boundary, which no staging shift fixes without a 17-row overlap the block-cooperative + * stage does not have. The row runs the f32 arm; `acc` stays a tuning axis with the f32 + * point, the f16 point joins when a row-overlapping stage is measured to pay. + */ + +/* The split-K reduce: y = the SK partial tiles summed, narrowed once. One thread per + * (column tile, row tile, tile element); the element's (m, n) is the D map inverted. */ +__global__ void r3d_w4a16_split_reduce(const float* __restrict__ Scr, + __hip_bfloat16* __restrict__ C, + int M, int N, int y_ld, int SK, int MTb, int ntiles) +{ + const int total = ntiles * MTb * 256; + for (int idx = blockIdx.x * blockDim.x + threadIdx.x; idx < total; + idx += gridDim.x * blockDim.x) { + const int tile = idx / 256, off = idx % 256; + const int i = tile % MTb, col_g = tile / MTb; + float v = 0.f; + for (int s = 0; s < SK; s++) + v += Scr[(((size_t)col_g * SK + s) * MTb + i) * 256 + off]; + const int l = off & 31, e = off >> 5; + const int m = i * 16 + 2 * e + (l >> 4), n = col_g * 16 + (l & 15); + if (m < M && n < N) ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ dequant(wq)[N,K]^T, f16 a, bf16 y, M <= 64. + * + * a [M][K] f16, k contiguous + * wq [N][K/2] the codes in the container's order + * bsz the joined (scale, zero) operand: the f16 scale plane, [N][K/128], then the u8 + * zero plane, [N][K/128], at off_scale and off_zero + * y [M][N] bf16, row-major + * + * `wv` waves per block (0 = 8), `sk` the K split (0 = 1), `mb` row tiles per block (0 = 1), + * `npw` column tiles a wave (0 = 1; 1 or 4), `nt` the weight load's lowering, `acc` the + * accumulator (0 = the f32 arm, the arm served; 1 = the f16 arm, declined, see the + * shelved-arm note; negative-for-absent = 0). Returns 0, -1 a null pointer, -2 a shape it + * does not serve, -4 the HIP launch failed. */ +/* The split-partial pool: file scope, grown only, so a call never syncs the stream. */ +static float* s_scratch_pool = nullptr; +static size_t s_scratch_sz = 0; + +extern "C" int r3d_gemm_nt_q_w4a16_m64(long a, long wq, long bsz, size_t off_scale, + size_t off_zero, long y, int M, int N, int K, + int a_ld, int y_ld, + int wv, int sk, int mb, int npw, int nt, int acc, + long stream) +{ + if (!a || !wq || !bsz || !y) return -1; + if (M < 1 || M > kMaxM) return -2; + if (N < 16 || N % 16) return -2; + if (K < kGroup || K % kGroup) return -2; + if (wv <= 0) wv = 8; + if (sk <= 0) sk = 1; + if (mb <= 0) mb = 1; + if (npw <= 0) npw = 1; + if (acc < 0) acc = 0; + if (acc > 1) return -2; + if (wv > 32 || sk > 32) return -2; + if (mb < 1 || mb > 4) return -2; + if (npw != 1 && npw != 4) return -2; + if (K % (sk * kGroup)) return -2; + /* npw=4 with mb>1 is the shape the backend cannot lower: at the 128-VGPR ceiling the + * wmma expansion's A-fragment loads collapse (probed: the 64-thread <2,4> tile came + * back with half its rows NaN). The tuning path selects around it: npw=4 with mb=1, + * or npw=1 with the mb it wants. The f16 arm is shelved (its tile drops a row, probed): + * the axis carries no f16 point, the launcher declines it. */ + if (npw == 4 && mb > 1) return -2; + if (acc == 1) return -2; + + const int ntiles = N / 16, mtiles = (M + 15) / 16; + const int ncols = wv * npw; + const dim3 grid((ntiles + ncols - 1) / ncols, ((mtiles + mb - 1) / mb) * sk), + block(wv * kWave32); + + /* Split partials live in a grow-only device pool: a per-call hipMalloc/Free would + * synchronise the stream. */ + float* scr = nullptr; + if (sk > 1) { + const size_t bytes = (size_t)ntiles * sk * mb * 256 * sizeof(float); + if (bytes > s_scratch_sz) { + if (s_scratch_pool) hipFree(s_scratch_pool); + if (hipMalloc(&s_scratch_pool, bytes) != hipSuccess) return -4; + s_scratch_sz = bytes; + } + scr = s_scratch_pool; + } + +#define R3D_W4L(MT, NP, TT) \ + R3D_KLAUNCH_S(R3D_KNAME((r3d_w4a16_m64_kernel)), grid, block, 0, \ + (hipStream_t)stream, (const unsigned short*)a, (const unsigned char*)wq, \ + (const unsigned char*)bsz, off_scale, off_zero, (__hip_bfloat16*)y, scr, \ + M, K, N, a_ld, y_ld, wv, sk, mb) +#define R3D_W4L_MB(NP, TT) \ + do { switch (mb) { \ + case 1: R3D_W4L(1, NP, TT); break; \ + case 2: R3D_W4L(2, NP, TT); break; \ + case 3: R3D_W4L(3, NP, TT); break; \ + default: R3D_W4L(4, NP, TT); break; } } while (0) + if (npw == 1) { if (nt) R3D_W4L_MB(1, true); else R3D_W4L_MB(1, false); } + else { if (nt) R3D_W4L_MB(4, true); else R3D_W4L_MB(4, false); } +#undef R3D_W4L_MB +#undef R3D_W4L + if (hipGetLastError() != hipSuccess) return -4; + + if (sk > 1) { + const int total = ntiles * mb * 256; + const int rblock = 256; + const int rgrid = (total + rblock - 1) / rblock; + R3D_KLAUNCH_S(R3D_KNAME((r3d_w4a16_split_reduce)), dim3(rgrid), rblock, 0, + (hipStream_t)stream, scr, (__hip_bfloat16*)y, M, N, y_ld, sk, mb, ntiles); + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} + + + +/* ==================================================================== the plugin ABI entry point + * + * gemm_nt_q's operand list is [a, a_scale, b, b_scale, y, a_sum, b_ref]; this row takes a, + * b, b_scale and y, and declines the rest. b is the codes plane in the container's order; + * b_scale is the (scale, zero) pair in rad.planes' joined form. */ +enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF }; + +extern "C" int r3d_rad_gemm_nt_q_w4a16_m64(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (!dt || std::strcmp(dt, "w4a16_asym") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, Q_A); + const RadTensor* AS = r3d_opt(a, Q_ASCALE); + const RadTensor* B = r3d_opt(a, Q_B); + const RadTensor* BS = r3d_opt(a, Q_BSCALE); + const RadTensor* Y = r3d_opt(a, Q_Y); + const RadTensor* AU = r3d_opt(a, Q_ASUM); + const RadTensor* BR = r3d_opt(a, Q_BREF); + if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + /* Any other operand would read plausible but wrong numbers. */ + if (r3d_has(AS) || r3d_has(AU) || r3d_has(BR)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f16(A)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_U4) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (N % 16) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMaxM) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(B) < (N * K) / 2) return R3D_NO(RAD_E_SHAPE); + + /* The joined form, read at launch: the scale and zero planes, and their byte offsets. */ + const RadPlanesEntry* es = nullptr, *ez = nullptr; + const uint8_t* sc_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "scale", &es); + const uint8_t* z_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "zero", &ez); + if (!sc_b || !z_b || es->dtype != RAD_F16 || ez->dtype != RAD_U8) + return R3D_NO(RAD_E_DTYPE); + if (es->rows < N || ez->rows < N) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N || yrows < M) return R3D_NO(RAD_E_STRIDE); + /* 16-byte A fragment reads and 8-byte weight reads, both at aligned bases. */ + if (!r3d_aligned(r3d_p(A), 16) || !r3d_aligned(r3d_p(B), 8)) return R3D_NO(RAD_E_ALIGN); + + const int wv = (int)r3d_geti_or(a, "wv", 8); + const int sk = (int)r3d_geti_or(a, "sk", 1); + const int mb = (int)r3d_geti_or(a, "mb", 1); + const int npw = (int)r3d_geti_or(a, "npw", 1); + const int nt = (int)r3d_geti_or(a, "nt", 1); + const int acc = (int)r3d_geti_or(a, "acc", 0); + + const int e = r3d_gemm_nt_q_w4a16_m64(r3d_addr(A), r3d_addr(B), r3d_addr(BS), + (size_t)(sc_b - (const uint8_t*)r3d_p(BS)), + (size_t)(z_b - (const uint8_t*)r3d_p(BS)), + r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp, + wv, sk, mb, npw, nt, acc, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE : RAD_E_DEVICE); +} + +/* ==================================================================== the (scale, zero) pair + * + * The weight's scale and zero are two planes behind the one b_scale operand, and the mapped + * tier places a weight only when a loaded library can read it in place. This is the scoped + * exception to the library's "no layout hooks, no repacking" rule, transcribed from the + * reference's own hook: + * + * if (n < 2 || operand != 3) return RAD_E_UNSUPPORTED; + * the grid's dtype is "w4a16_asym"; + * the affine encoding: U4 codes block {1,1}, f16 scale block {1, group}, u8 zero block + * {1, group}; the transform empty or beginning "givens"; + * sel names "scale" and "zero", in order; + * return rad_planes_layout(enc, sel, planes, n, out); + * + * NOTHING HERE MOVES A BYTE: the writer is rad_planes_relayout, and the codes plane is read + * where it lies -- the kernel's load is the container's order, which is the point. + */ + +extern "C" int r3d_layout_gemm_nt_q_w4a16(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) +{ + if (n < 2 || operand != Q_BSCALE) return RAD_E_UNSUPPORTED; + const char* d = r3d_pgets(p, n_p, "dtype"); + if (!d || std::strcmp(d, "w4a16_asym") != 0) return RAD_E_DTYPE; + const long long group = r3d_pgeti_or(p, n_p, "group", kGroup); + if (group <= 0) return RAD_E_DTYPE; + if (!enc || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; + if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) + return RAD_E_DTYPE; + if (enc->n_planes < 3) return RAD_E_DTYPE; + if (n != 2) return RAD_E_DTYPE; + for (int i = 0; i < 2; ++i) { + const char* want = i == 0 ? "scale" : "zero"; + if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_DTYPE; + if (std::strncmp(enc->plane[sel[i]].role, want, RAD_ENC_STR) != 0) return RAD_E_DTYPE; + } + /* The codes plane is the one this operand does not take: U4, block {1,1}. */ + int codes = -1; + for (int i = 0; i < enc->n_planes; ++i) + if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; } + if (codes < 0 || enc->plane[codes].dtype != RAD_U4 || + enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1) + return RAD_E_DTYPE; + for (int i = 0; i < 2; ++i) { + const RadEncPlane* q = &enc->plane[sel[i]]; + if (q->kind != RAD_PLANE_TILED || q->block[0] != 1 || q->block[1] != group) + return RAD_E_DTYPE; + if (i == 0 && q->dtype != RAD_F16) return RAD_E_DTYPE; + if (i == 1 && q->dtype != RAD_U8) return RAD_E_DTYPE; + } + return rad_planes_layout(enc, sel, pl, n, out); +} + +/* The writer for the joined operand this hook names: scale and zero as the plan's one + * rad.planes weight, assembled by rad_planes_relayout. The ABI's contract is that a query + * answering RAD_OK is a promise the loader keeps on the row's word (rad_abi.h). */ +extern "C" int r3d_relayout_gemm_nt_q_w4a16(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) +{ + (void)p; (void)n_p; + if (operand != Q_BSCALE) return RAD_E_UNSUPPORTED; + return rad_planes_relayout(enc, sel, pl, n, dst, dst_bytes); +} diff --git a/libr3d/r3d_gemm_w5a16_nt_m64.hip b/libr3d/r3d_gemm_w5a16_nt_m64.hip new file mode 100644 index 00000000..7a5e89e2 --- /dev/null +++ b/libr3d/r3d_gemm_w5a16_nt_m64.hip @@ -0,0 +1,509 @@ +/* r3d_gemm_w5a16_nt_m64.hip -- the 5-bit-weight skinny GEMM, M up to 64. + * + * The w4a16 row with a fifth bit per weight, for ParoQuant's int5 (asymmetric: an f16 scale and + * a 5-bit integer zero per 128 of K). The weight arrives as three planes behind the one + * b_scale operand, joined rad.planes, the codes as the B operand in the container's order: + * + * codes [N][K/2] u4, the w4a16 fragment order (element e is k = e) + * scale [N][K/128] f16 + * zero [N][K/128] u8, 0..31 + * hi [N/16][K/2] u32: word (t, kb, lane) holds the fifth bits of tile t's k block + * kb, lane's 32 weights: byte s is k step s of the 64-wide block, bit e is + * fragment element e + * + * The dequant is the w4a16's integer code minus the zero point, the code widened with its fifth + * bit (0..31, exact in f16 after the subtract: the range is [-31, 31]). The rest of the + * kernel is the w4a16 row's, and its header notes apply: the block-level split, the + * block-cooperative LDS stage, the runtime trip counts, the pinned barriers, the 128-VGPR + * ceiling's npw==4 && mb>1 refusal. + */ + +#include +#include +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" +#include "rad_planes.h" + +#include +#include + +namespace { + +constexpr int kMaxM = 64; +constexpr int kGroup = 128; +constexpr int kStep = 16; +constexpr int kWave32 = 32; +constexpr int kAPitch = 68; // dwords per staged A row (128 + 8 f16, the m16 pitch) + + +/* One dword of two f16 into the fragment's two halves, low first: the packed order the + * builtin's VGPR map wants, a bit pattern not a value. */ +#define R3D_W5_F16(w) __builtin_bit_cast(_Float16, (uint16_t)((w) & 0xffffu)), \ + __builtin_bit_cast(_Float16, (uint16_t)((w) >> 16)) + +/* Two dwords of sixteen 4-bit codes plus the two bytes of their fifth bits -> one 16x16x16 + * f16 B fragment, minus the zero point. Element e is the code for k = e, the k-contiguous + * map the card's tile wants: nibble 2e (e < 4), 2(e-4)+1 (e < 8), then w1's 2(e-8), + * 2(e-12)+1. + * + * The fifth bits: a byte covers eight k, the even ones in its low four bits (bit l/2), the + * odd in its high four (bit 4 + l/2), l the k within the eight -- the reference + * quantiser's spread16 form. The step's sixteen k are two bytes: hb0 is k 0..7, hb1 is + * k 8..15. + * + * The value is code - zero as an integer, converted once per element: the range is + * [-31, 31], exact in f16. No offset form, no half arithmetic: the w4a16 row's probe + * history is the reason (the packed-half construction lost registers across the unrolled + * WMMA chain). */ +__device__ __forceinline__ v16half dequant5(unsigned w0, unsigned w1, unsigned hb0, + unsigned hb1, int z) +{ + /* The bits are extracted inline, not materialised: sixteen named bit registers push + * the kernel over the 128-VGPR ceiling and the A fragment loads collapse. + * + * The nibbles are k-contiguous (w0 = kk 0..7, w1 = kk 8..15) but the fifth-bit + * words are the reference layout's lh split: h0 holds kk 0,1,2,3,8,9,10,11 at + * bits 0,2,4,6,1,3,5,7 and h1 holds kk 4,5,6,7,12,13,14,15 at the same bit + * order. Element e is kk e, so the bit source crosses the e 8 boundary: e 4..7 + * and 12..15 take h1, e 8..11 take h0 (probe C7: a k-dependent A exposes the + * mispairing a per-row-constant A erases). */ + const unsigned h0 = hb0 & 0xFFu, h1 = hb1 & 0xFFu; + const int c0 = (int)((w0 & 0xFu) | (((h0 >> 0) & 1u) << 4)) - z; + const int c1 = (int)(((w0 >> 4) & 0xFu) | (((h0 >> 2) & 1u) << 4)) - z; + const int c2 = (int)(((w0 >> 8) & 0xFu) | (((h0 >> 4) & 1u) << 4)) - z; + const int c3 = (int)(((w0 >> 12) & 0xFu) | (((h0 >> 6) & 1u) << 4)) - z; + const int c4 = (int)(((w0 >> 16) & 0xFu) | (((h1 >> 0) & 1u) << 4)) - z; + const int c5 = (int)(((w0 >> 20) & 0xFu) | (((h1 >> 2) & 1u) << 4)) - z; + const int c6 = (int)(((w0 >> 24) & 0xFu) | (((h1 >> 4) & 1u) << 4)) - z; + const int c7 = (int)(((w0 >> 28) & 0xFu) | (((h1 >> 6) & 1u) << 4)) - z; + const int c8 = (int)((w1 & 0xFu) | (((h0 >> 1) & 1u) << 4)) - z; + const int c9 = (int)(((w1 >> 4) & 0xFu) | (((h0 >> 3) & 1u) << 4)) - z; + const int c10 = (int)(((w1 >> 8) & 0xFu) | (((h0 >> 5) & 1u) << 4)) - z; + const int c11 = (int)(((w1 >> 12) & 0xFu) | (((h0 >> 7) & 1u) << 4)) - z; + const int c12 = (int)(((w1 >> 16) & 0xFu) | (((h1 >> 1) & 1u) << 4)) - z; + const int c13 = (int)(((w1 >> 20) & 0xFu) | (((h1 >> 3) & 1u) << 4)) - z; + const int c14 = (int)(((w1 >> 24) & 0xFu) | (((h1 >> 5) & 1u) << 4)) - z; + const int c15 = (int)(((w1 >> 28) & 0xFu) | (((h1 >> 7) & 1u) << 4)) - z; + return v16half{ __float2half((float)c0), __float2half((float)c1), + __float2half((float)c2), __float2half((float)c3), + __float2half((float)c4), __float2half((float)c5), + __float2half((float)c6), __float2half((float)c7), + __float2half((float)c8), __float2half((float)c9), + __float2half((float)c10), __float2half((float)c11), + __float2half((float)c12), __float2half((float)c13), + __float2half((float)c14), __float2half((float)c15) }; +} + +/* A block barrier the backend cannot move; see the w4a16 row's note. */ +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +/* y[M,N] = a[M,K] @ dequant(wq, hi)[N,K]^T. The w4a16 row's kernel with the fifth-bit + * plane: per group the two 64-wide blocks' words, one a lane, then the step's byte. */ +template +__global__ __launch_bounds__(1024, 1) void r3d_w5a16_m64_kernel( + const unsigned short* __restrict__ A, const unsigned char* __restrict__ Wq, + const unsigned char* __restrict__ Bsz, size_t off_scale, size_t off_zero, size_t off_hi, + __hip_bfloat16* __restrict__ C, float* __restrict__ Scr, + int M, int K, int N, int a_ld, int y_ld, int WV, int SK, int MTb) +{ + __shared__ uint32_t s_a[16 * kAPitch]; + + const int tid = threadIdx.x, wave = tid / kWave32, lane = tid % kWave32; + const int col_local = wave; + const int ksplit = blockIdx.y % SK; + const int nt0 = (blockIdx.x * WV + col_local) * NPW; + const int n0 = nt0 * 16; + const int mt0 = (blockIdx.y / SK) * MT; + const int Ks = K / SK; + const int steps = Ks / kStep; + const int kbase = ksplit * Ks; + const int G = K / kGroup; + + v8float acc[NPW][MT]; +#pragma unroll + for (int j = 0; j < NPW; j++) +#pragma unroll + for (int i = 0; i < MT; i++) acc[j][i] = (v8float)(0.f); + + if (n0 < N) { + /* Weight: the lane's column, eight bytes a step; the fifth bits, one word a + * 64-wide block; the planes indexed by the absolute group. */ + const int ntlast = N / 16 - 1; + const unsigned char* pw[NPW]; + const unsigned short* ps[NPW]; + const unsigned char* pz[NPW]; + size_t hibase[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) { + const int t = (nt0 + j) < ntlast ? (nt0 + j) : ntlast; + const size_t row = (size_t)t * 16 + (lane & 15); + pw[j] = Wq + row * (K / 2) + kbase / 2; + ps[j] = (const unsigned short*)(Bsz + off_scale) + row * G; + pz[j] = (Bsz + off_zero) + row * G; + /* The hi plane's byte base for this tile: [N/16][K/2] u32, the tile's + * words are (K/2) u32 = K/2*4 bytes. */ + hibase[j] = (size_t)t * (K / 2) * 4; + } + + const int spg = kGroup / kStep; + const int spg_rt = (K % kGroup) + kGroup / kStep; + const int ngroups = steps / spg; + + for (int i = 0; i < MT; i++) { + const int mrow_base = (mt0 + i) * 16; + for (int g = 0; g < ngroups; g++) { + /* Stage 16 rows x 128 f16 of the group's slab, eight f16 a unit; the + * w4a16 row's guarded wave loop, its notes apply. */ + const int kslab = kbase + g * kGroup; + const int nu = (K % kGroup) + kGroup / 8; + const int nunits = 16 * nu; + const int nwaves = (int)blockDim.x / kWave32; + const int nstride = (int)blockDim.x; + const int niter = (nunits + nstride - 1) / nstride; +#pragma unroll 1 + for (int w = 0; w < nwaves; w++) { + const int wtid = w * kWave32 + lane; +#pragma unroll 1 + for (int k = 0; k < niter; k++) { + const int ui = wtid + k * nstride; + if (ui < nunits && (w * kWave32) <= tid) { + const int row = ui / nu, c = (ui % nu) * 8; + const int mrow = mrow_base + row; + const int mr = mrow < M ? mrow : M - 1; + const unsigned short* src = A + (size_t)(mr * a_ld + kslab + c); + uint32_t* dst = s_a + (size_t)row * kAPitch + c / 2; + *(r3d_u32x4*)dst = *(const r3d_u32x4*)src; + } + } + } + R3D_BARRIER(); + + float sc[NPW]; + int z[NPW]; + const int g_abs = kbase / kGroup + g; +#pragma unroll + for (int j = 0; j < NPW; j++) { + sc[j] = f16_to_f32((uint16_t)ps[j][(size_t)g_abs]); + z[j] = (int)pz[j][(size_t)g_abs]; + } + + /* The group's fifth-bit bytes, one a lane: the group is 128 wide, eight + * steps: steps 0..3 are 64-block 2g, steps 4..7 are block 2g+1. The + * lane's words are (t, kb, column) and (t, kb, 16 + column), the + * reference layout's lh split; the byte pointer is the word's first + * byte. */ + const int kb0 = kbase / (kGroup / 2) + 2 * g; + + /* The step's two fifth-bit bytes, loaded from global memory as bytes at + * plain runtime addresses -- the form the W loads use and the card + * honours. Every select shape tried before this is miscompiled: a + * runtime shift by the step's amount drops the bytes, an if/else chain + * leaks a branch into the other steps, a stack-array index collapses to + * 0, a mask-OR select leaks a value (probe C6). Two blocks of four + * steps; the block's byte pointer is set once per block. */ + v8float g_acc[NPW]; +#pragma unroll + for (int j = 0; j < NPW; j++) g_acc[j] = (v8float)(0.f); + for (int b2 = 0; b2 < 2; b2++) { + for (int j = 0; j < NPW; j++) { + const unsigned char* p0 = (const unsigned char*)(Bsz + off_hi) + + hibase[j] + + (size_t)(kb0 + b2) * kWave32 * 4 + (lane & 15) * 4; + const unsigned char* p1 = p0 + 16 * 4; + for (int sb = 0; sb < 4; sb++) { + const int s = 4 * b2 + sb; + const int u = g * spg + s; + const unsigned long long wbj = + NT ? __builtin_nontemporal_load((const unsigned long long*)(pw[j] + 8 * u)) + : *(const unsigned long long*)(pw[j] + 8 * u); + const unsigned hb0 = (unsigned)*(p0 + sb); + const unsigned hb1 = (unsigned)*(p1 + sb); + const v16half bfrag = + dequant5((unsigned)wbj, (unsigned)(wbj >> 32), hb0, hb1, z[j]); + const uint32_t* ap = s_a + (size_t)(lane & 15) * kAPitch + s * 8; + const r3d_u32x4 a0 = *(const r3d_u32x4*)ap; + const r3d_u32x4 a1 = *(const r3d_u32x4*)(ap + 4); + const v16half afrag = v16half{ R3D_W5_F16(a0.x), R3D_W5_F16(a0.y), + R3D_W5_F16(a0.z), R3D_W5_F16(a0.w), + R3D_W5_F16(a1.x), R3D_W5_F16(a1.y), + R3D_W5_F16(a1.z), R3D_W5_F16(a1.w) }; + g_acc[j] = wmma_f16(afrag, bfrag, g_acc[j]); + } + } + } + for (int j = 0; j < NPW; j++) + for (int e = 0; e < kWave32 / 4; e++) + acc[j][i][e] = fmaf(g_acc[j][e], sc[j], acc[j][i][e]); + R3D_BARRIER(); // the next slab's stage must not race these reads + } + } + } + + /* Epilogue: the w4a16 row's D map and store; the notes apply. */ + const int ncols = WV * NPW; + for (int i = 0; i < MT; i++) { + const int m0 = (mt0 + i) * 16; + for (int j = 0; j < NPW; j++) { + const int n0 = (nt0 + j) * 16; + const int col_g = blockIdx.x * ncols + (col_local * NPW + j); + for (int e = 0; e < kWave32 / 4; e++) { + const int m = m0 + 2 * e + (lane >> 4); + const int n = n0 + (lane & 15); + if (SK == 1) { + if (m < M && n < N) + ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(acc[j][i][e]); + } else { + /* The pool is sized for ntiles; the grid's last column group strides + * past it when ntiles % ncols != 0. */ + if (col_g < N / 16) { + const size_t o = + (((size_t)col_g * SK + ksplit) * MTb + i) * 256 + (e * kWave32 + lane); + Scr[o] = acc[j][i][e]; + } + } + } + } + } +} + +/* The split-K reduce: the w4a16 row's, the D map inverted. */ +__global__ void r3d_w5a16_split_reduce(const float* __restrict__ Scr, + __hip_bfloat16* __restrict__ C, + int M, int N, int y_ld, int SK, int MTb, int ntiles) +{ + const int total = ntiles * MTb * 256; + for (int idx = blockIdx.x * blockDim.x + threadIdx.x; idx < total; + idx += gridDim.x * blockDim.x) { + const int tile = idx / 256, off = idx % 256; + const int i = tile % MTb, col_g = tile / MTb; + float v = 0.f; + for (int s = 0; s < SK; s++) + v += Scr[(((size_t)col_g * SK + s) * MTb + i) * 256 + off]; + const int l = off & 31, e = off >> 5; + const int m = i * 16 + 2 * e + (l >> 4), n = col_g * 16 + (l & 15); + if (m < M && n < N) ((uint16_t*)C)[(size_t)m * y_ld + n] = f32_to_bf16(v); + } +} + +/* ==================================================================== the launcher + + * y[M,N] = a[M,K] @ dequant(wq, hi)[N,K]^T: + * + * a [M][K] f16 + * wq [N][K/2] u4 codes, the fragment order + * bsz the joined (scale, zero, hi) operand, rad.planes + * y [M][N] bf16, row-major + * + * `wv` waves per block (0 = 8), `sk` the K split (0 = 1), `mb` row tiles per block (0 = 1), + * `npw` column tiles a wave (0 = 1; 1 or 4), `nt` the weight load's lowering. Returns 0, + * -1 a null pointer, -2 a shape it does not serve, -4 the HIP launch failed. */ +static float* s_scratch_pool = nullptr; +static size_t s_scratch_sz = 0; + +extern "C" int r3d_gemm_nt_q_w5a16_m64(long a, long wq, long bsz, size_t off_scale, + size_t off_zero, size_t off_hi, long y, int M, int N, + int K, int a_ld, int y_ld, + int wv, int sk, int mb, int npw, int nt, + long stream) +{ + if (!a || !wq || !bsz || !y) return -1; + if (M < 1 || M > kMaxM) return -2; + if (N < 16 || N % 16) return -2; + if (K < kGroup || K % kGroup) return -2; + if (wv <= 0) wv = 8; + if (sk <= 0) sk = 1; + if (mb <= 0) mb = 1; + if (npw <= 0) npw = 1; + if (wv > 32 || sk > 32) return -2; + if (mb < 1 || mb > 4) return -2; + if (npw != 1 && npw != 4) return -2; + if (K % (sk * kGroup)) return -2; + /* npw=4 with mb>1 is the shape the backend cannot lower at the 128-VGPR ceiling; the + * w4a16 row's probe and refusal apply. */ + if (npw == 4 && mb > 1) return -2; + + const int ntiles = N / 16, mtiles = (M + 15) / 16; + const int ncols = wv * npw; + const dim3 grid((ntiles + ncols - 1) / ncols, ((mtiles + mb - 1) / mb) * sk), + block(wv * kWave32); + + float* scr = nullptr; + if (sk > 1) { + const size_t bytes = (size_t)ntiles * sk * mb * 256 * sizeof(float); + if (bytes > s_scratch_sz) { + if (s_scratch_pool) hipFree(s_scratch_pool); + if (hipMalloc(&s_scratch_pool, bytes) != hipSuccess) return -4; + s_scratch_sz = bytes; + } + scr = s_scratch_pool; + } + +#define R3D_W5L(MT, NP, TT) \ + R3D_KLAUNCH_S(R3D_KNAME((r3d_w5a16_m64_kernel)), grid, block, 0, \ + (hipStream_t)stream, (const unsigned short*)a, (const unsigned char*)wq, \ + (const unsigned char*)bsz, off_scale, off_zero, off_hi, (__hip_bfloat16*)y, \ + scr, M, K, N, a_ld, y_ld, wv, sk, mb) +#define R3D_W5L_MB(NP, TT) \ + do { switch (mb) { \ + case 1: R3D_W5L(1, NP, TT); break; \ + case 2: R3D_W5L(2, NP, TT); break; \ + case 3: R3D_W5L(3, NP, TT); break; \ + default: R3D_W5L(4, NP, TT); break; } } while (0) + if (npw == 1) { if (nt) R3D_W5L_MB(1, true); else R3D_W5L_MB(1, false); } + else { if (nt) R3D_W5L_MB(4, true); else R3D_W5L_MB(4, false); } +#undef R3D_W5L_MB +#undef R3D_W5L + if (hipGetLastError() != hipSuccess) return -4; + + if (sk > 1) { + const int total = ntiles * mb * 256; + const int rblock = 256; + const int rgrid = (total + rblock - 1) / rblock; + R3D_KLAUNCH_S(R3D_KNAME((r3d_w5a16_split_reduce)), dim3(rgrid), rblock, 0, + (hipStream_t)stream, scr, (__hip_bfloat16*)y, M, N, y_ld, sk, mb, ntiles); + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +} // namespace + +/* ==================================================================== the plugin ABI */ + +enum { Q_A = 0, Q_ASCALE, Q_B, Q_BSCALE, Q_Y, Q_ASUM, Q_BREF }; + +extern "C" int r3d_rad_gemm_nt_q_w5a16_m64(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (!dt || std::strcmp(dt, "w5a16") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, Q_A); + const RadTensor* AS = r3d_opt(a, Q_ASCALE); + const RadTensor* B = r3d_opt(a, Q_B); + const RadTensor* BS = r3d_opt(a, Q_BSCALE); + const RadTensor* Y = r3d_opt(a, Q_Y); + const RadTensor* AU = r3d_opt(a, Q_ASUM); + const RadTensor* BR = r3d_opt(a, Q_BREF); + if (!r3d_p(A) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) return R3D_NO(RAD_E_INVAL); + if (r3d_has(AS) || r3d_has(AU) || r3d_has(BR)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f16(A)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_U4) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (N % 16) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 1 || M > kMaxM) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + + /* The joined form: the scale and zero planes, the hi plane, and their byte offsets. */ + const RadPlanesEntry* es = nullptr, *ez = nullptr, *eh = nullptr; + const uint8_t* sc_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "scale", &es); + const uint8_t* z_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "zero", &ez); + const uint8_t* h_b = (const uint8_t*)rad_planes_find(r3d_p(BS), "hi", &eh); + if (!sc_b || !z_b || !h_b || es->dtype != RAD_F16 || ez->dtype != RAD_U8 || + eh->dtype != RAD_U32) + return R3D_NO(RAD_E_DTYPE); + if (es->rows < N || ez->rows < N || es->cols < K / kGroup || ez->cols < K / kGroup) + return R3D_NO(RAD_E_SHAPE); + if (eh->rows < N / 16) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N || yrows < M) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 16) || !r3d_aligned(r3d_p(B), 8) || + !r3d_aligned(h_b, 4)) + return R3D_NO(RAD_E_ALIGN); + + const int wv = (int)r3d_geti_or(a, "wv", 8); + const int sk = (int)r3d_geti_or(a, "sk", 1); + const int mb = (int)r3d_geti_or(a, "mb", 1); + const int npw = (int)r3d_geti_or(a, "npw", 1); + const int nt = (int)r3d_geti_or(a, "nt", 1); + + const int e = r3d_gemm_nt_q_w5a16_m64(r3d_addr(A), r3d_addr(B), r3d_addr(BS), + (size_t)(sc_b - (const uint8_t*)r3d_p(BS)), + (size_t)(z_b - (const uint8_t*)r3d_p(BS)), + (size_t)(h_b - (const uint8_t*)r3d_p(BS)), + r3d_addr(Y), (int)M, (int)N, (int)K, (int)ap, (int)yp, + wv, sk, mb, npw, nt, (long)(uintptr_t)s); + if (e == 0) return RAD_OK; + return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE : RAD_E_DEVICE); +} + +/* ==================================================================== the layout hooks + * + * The w4a16 row's scoped exception with a third plane: the codes are read where they lie + * (the B operand, the container's order), and the scale, zero and hi planes join behind + * the b_scale operand. NOTHING HERE MOVES A BYTE. + */ + +extern "C" int r3d_layout_gemm_nt_q_w5a16(const RadParam* p, int n_p, int operand, + const RadEncoding* enc, const int* sel, + const RadTensor* pl, int n, RadLayout* out) +{ + if (n < 2 || operand != Q_BSCALE) return RAD_E_UNSUPPORTED; + const char* d = r3d_pgets(p, n_p, "dtype"); + if (!d || std::strcmp(d, "w5a16") != 0) return RAD_E_DTYPE; + const long long group = r3d_pgeti_or(p, n_p, "group", kGroup); + if (group <= 0) return RAD_E_DTYPE; + if (!enc || !rad_enc_is(enc, "affine")) return RAD_E_DTYPE; + if (enc->transform[0] && std::strncmp(enc->transform, "givens", RAD_ENC_STR) != 0) + return RAD_E_DTYPE; + if (enc->n_planes < 3) return RAD_E_DTYPE; + if (n != 3) return RAD_E_DTYPE; + const char* want[3] = { "scale", "zero", "hi" }; + for (int i = 0; i < 3; ++i) { + if (sel[i] < 0 || sel[i] >= enc->n_planes) return RAD_E_DTYPE; + if (std::strncmp(enc->plane[sel[i]].role, want[i], RAD_ENC_STR) != 0) + return RAD_E_DTYPE; + } + /* The codes plane is the one this operand does not take: U4, block {1,1}. */ + int codes = -1; + for (int i = 0; i < enc->n_planes; ++i) + if (std::strncmp(enc->plane[i].role, "codes", RAD_ENC_STR) == 0) { codes = i; break; } + if (codes < 0 || enc->plane[codes].dtype != RAD_U4 || + enc->plane[codes].block[0] != 1 || enc->plane[codes].block[1] != 1) + return RAD_E_DTYPE; + for (int i = 0; i < 3; ++i) { + const RadEncPlane* q = &enc->plane[sel[i]]; + if (q->kind != RAD_PLANE_TILED) return RAD_E_DTYPE; + if (i < 2 && (q->block[0] != 1 || q->block[1] != group)) return RAD_E_DTYPE; + if (i == 0 && q->dtype != RAD_F16) return RAD_E_DTYPE; + if (i == 1 && q->dtype != RAD_U8) return RAD_E_DTYPE; + if (i == 2 && q->dtype != RAD_U32) return RAD_E_DTYPE; + } + /* The hi plane's extent: one word a (tile, 64-wide k block, lane). */ + const long long N = r3d_pgeti_or(p, n_p, "N", 0), K = r3d_pgeti_or(p, n_p, "K", 0); + if (N > 0 && K > 0) { + const RadTensor* h = &pl[sel[2]]; + if (h->rank < 2 || h->shape[0] < N / 16 || h->shape[1] < K / 2) + return RAD_E_SHAPE; + } + return rad_planes_layout(enc, sel, pl, n, out); +} + +/* The writer for the joined operand: the planes copied, the header and entries filled. */ +extern "C" int r3d_relayout_gemm_nt_q_w5a16(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) +{ + (void)p; (void)n_p; + if (operand != Q_BSCALE) return RAD_E_UNSUPPORTED; + return rad_planes_relayout(enc, sel, pl, n, dst, dst_bytes); +} diff --git a/libr3d/r3d_gemm_w8a8_nt_m64.hip b/libr3d/r3d_gemm_w8a8_nt_m64.hip new file mode 100644 index 00000000..2812e239 --- /dev/null +++ b/libr3d/r3d_gemm_w8a8_nt_m64.hip @@ -0,0 +1,284 @@ +/* r3d_gemm_w8a8_nt_m64.hip -- the wave-matrix arm of the w8a8 grid at the M = 17..127 band. + * + * y[M,N] = a[M,K] @ b[N,K]^T, int8 a against signed int8 codes, the scale group 128. + * + * The m16 arm (r3d_gemm_inta8_wmma) owns one 16-row tile a wave; above M = 16 this arm takes + * MT = 2 16-row tiles a wave and walks them with MT accumulators. The B-fragment (the weight + * column) is loaded once per 16-k step and reused over the MT row tiles, so the weight stream + * is read once per 16-column tile no matter how many row tiles the wave carries -- the + * activation, not the weight, is the traffic that grows with MT. + * + * ---- the group law -------------------------------------------------------------------------- + * + * The m16 arm's exactness: a group's 128 products are |a * code| <= 127 * 127, their sum + * 2,064,512 an exact integer far inside i32, so the eight wmma steps of a group chain an i32 + * sub-sum with no rounding, and the group term is the reference's + * + * acc += (sub * a_scale[m]) * b_scale[n, g] + * + * in f32, in ascending group order -- the same order the dot2 arm's shared-memory walk forms. + * + * ---- the B pointer -------------------------------------------------------------------------- + * + * The weight row base `w = B + n_real * b_rb` carries NO group offset; the group's k-base + * enters the fragment read exactly once, as `w + kt + k` with kt = g * 128. Adding the group + * offset to the row base AND the step read doubles it and reads a foreign weight slice -- the + * per-n blow-up the prior draft hit. The A is staged per group into LDS, so its fragment read + * is the group-local step offset; both operands land on the same logical k. + * + * ---- the register budget -------------------------------------------------------------------- + * + * MT = 2: two f32 accumulators, two i32 sub-sums, sixteen A and sixteen B fragment VGPRs, the + * scales and the pointers, about 66 a lane. Eight waves a SIMD ask 528 of the 1024 the gfx11 + * SIMD keeps, so the eight-wave block stands. (A four-tile draft reached ~130 a lane, 1040 for + * eight waves, and the overflow miscompiled the sub-sum chain.) + */ + +#include + +#include "r3d.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr int kWaves = 8; +constexpr int kBlockThreads = kWaves * kWave; +constexpr int kGroup = 128; /* the scale group: one k tile, eight wmma steps */ +constexpr int kPitch = 33; /* dwords a staged a row: 33 mod 32 = 1, bank-free */ +constexpr int MT = 2; /* 16-row tiles a wave: 32 rows a block */ + + +/* Signed i8 in, signed i32 out: the builtin's sign selectors take the operands' signedness as + * compile-time constants, both signed for this grid. */ + +/* Column c sits at byte step_pos(c), bits 2 and 3 of c swapped, the map its own inverse. */ +__device__ __forceinline__ int64_t dword_pos(int64_t d) +{ + return 4 * ((d & ~(int64_t)3) | ((d & 1) << 1) | ((d & 2) >> 1)); +} + +template +__device__ __forceinline__ r3d_u32x4 ldw(const uint8_t* p) +{ + if constexpr (NT) return *(const __attribute__((address_space(1))) r3d_u32x4*)p; + else return __builtin_bit_cast(r3d_u32x4, *(const uint4*)p); +} + +/* y[M,N] = a[M,K] @ b[N,K]^T, MT 16-row tiles a wave, one 16-column tile a wave, one scale + * group a k tile. The dot2 arm's contract: K a multiple of the group, the group term the + * reference's, in ascending group order. */ +template +__global__ __launch_bounds__(kBlockThreads) R3D_WAVES(8) void gemm_w8a8_wmma_m64_kernel( + const int8_t* __restrict__ a, const float* __restrict__ sa, + const uint8_t* __restrict__ B, int b_rb, const uint16_t* __restrict__ sb, + int sb_rb, uint16_t* __restrict__ Y, + int M, int N, int K, int a_ld, int y_ld) +{ + __shared__ __align__(16) uint32_t s_a[MT * 16 * kPitch]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t r = lane & 15; // the replicated row/column index + + const uint32_t n0 = (uint32_t)blockIdx.x * kWaves * 16 + wave * 16 + r; + const int n_real = (int)(n0 < (uint32_t)N ? n0 : (uint32_t)(N - 1)); + const int mbase = (int)blockIdx.y * MT * 16; // this block's first row + + /* The lane's eight output rows per tile, and their activation scales, hoisted: a_scale is a + * row property, constant across the group walk. */ + float as[MT][8]; + #pragma unroll + for (int i = 0; i < MT; ++i) + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int m = mbase + i * 16 + g2 * 2 + (int)(lane >> 4); + as[i][g2] = sa[m < M ? m : M - 1]; + } + + const uint8_t* w = B + (size_t)n_real * b_rb; // the row base: NO group offset + v8float acc[MT]; + #pragma unroll + for (int i = 0; i < MT; ++i) acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + + for (int g = 0; g < K / kGroup; ++g) { + const int kt = g * kGroup; + + /* Stage MT*16 rows x 128 i8, the step order unpermuting on the way in. A row past M + * re-reads the last real row, whose products the store drops. */ + for (int i = (int)tid; i < MT * 16 * (kGroup / 4); i += kBlockThreads) { + const int row = i / (kGroup / 4), d = i % (kGroup / 4); + const int rr = mbase + row; + const uint32_t src = + *(const uint32_t*)(a + (size_t)(rr < M ? rr : M - 1) * a_ld + kt + dword_pos(d)); + s_a[(size_t)row * kPitch + d] = src; + } + group_barrier(); + + #pragma unroll + for (int i = 0; i < MT; ++i) { + const uint32_t* ap = s_a + (size_t)(i * 16 + r) * kPitch; + v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int k = 0; k < kGroup; k += 16) { + const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4); + // The group's k-base enters once (kt); the row base carries none. + const r3d_u32x4 bq = ldw(w + kt + k); + sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w }, + v4int{ (int)bq.x, (int)bq.y, (int)bq.z, (int)bq.w }, sub); + } + /* The group term, the reference's parentheses. The b_scale load, its drain, its + * convert, and the eight fmacs run as one asm block: the load goes straight from + * global, the drain is a vmcnt this asm owns, and the scale's register is written + * only by this block's global_load, so no fragment load can clobber it mid-group. + * v20 is named in the clobber because this LLVM aliases a constrained asm output + * with a dead input register; the clobber keeps every t/acc/sub register out of + * v20 across the block. The hardware f16->f32 is exact for normals. */ + float t[8]; + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) + t[g2] = (float)sub[g2] * as[i][g2]; + { + const uint64_t ga = (uint64_t)(sb + (size_t)n_real * sb_rb + g); + asm volatile( + "global_load_u16 v20, %[ga], off\n\t" + "s_waitcnt vmcnt(0)\n\t" + "v_cvt_f32_f16_e32 v20, v20.l\n\t" + "v_fmac_f32_e32 %[a0], %[t0], v20\n\t" + "v_fmac_f32_e32 %[a1], %[t1], v20\n\t" + "v_fmac_f32_e32 %[a2], %[t2], v20\n\t" + "v_fmac_f32_e32 %[a3], %[t3], v20\n\t" + "v_fmac_f32_e32 %[a4], %[t4], v20\n\t" + "v_fmac_f32_e32 %[a5], %[t5], v20\n\t" + "v_fmac_f32_e32 %[a6], %[t6], v20\n\t" + "v_fmac_f32_e32 %[a7], %[t7], v20" + : [a0] "+v"(acc[i][0]), [a1] "+v"(acc[i][1]), [a2] "+v"(acc[i][2]), + [a3] "+v"(acc[i][3]), [a4] "+v"(acc[i][4]), [a5] "+v"(acc[i][5]), + [a6] "+v"(acc[i][6]), [a7] "+v"(acc[i][7]) + : [ga] "v"(ga), + [t0] "v"(t[0]), [t1] "v"(t[1]), [t2] "v"(t[2]), [t3] "v"(t[3]), + [t4] "v"(t[4]), [t5] "v"(t[5]), [t6] "v"(t[6]), [t7] "v"(t[7]) + : "v20"); + } + } + group_barrier(); // the next tile's stage must not race this one's reads + } + + const bool keep = (n0 < (uint32_t)N); + if (!keep) return; + #pragma unroll + for (int i = 0; i < MT; ++i) + #pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int m = mbase + i * 16 + g2 * 2 + (int)(lane >> 4); + if (m < M) Y[(size_t)m * y_ld + n0] = f32_to_bf16(acc[i][g2]); + } +} + +} // namespace + +/* y[M,N] = a[M,K] @ b[N,K]^T over the w8a8 grid, the wave-matrix arm at the M = 17..127 band. + * + * The dot2 arm's contract: K a multiple of the group, the group term the reference's. `nt` + * picks the weight load's lowering. Returns 0, -1 a null pointer, -2 a shape it does not + * serve, -3 a pitch it cannot read, -4 the HIP launch failed, -5 an alignment it cannot + * read. */ +extern "C" int r3d_gemm_nt_q_w8a8_m64_wmma(long a, long a_scale, long b, long b_scale, long y, + int M, int N, int K, int a_ld, int y_ld, + long long b_rb, long long sb_rb, int nt, long stream) +{ + if (!a || !a_scale || !b || !b_scale || !y) return -1; + if (M < 17 || N < 1 || K < 1) return -2; + if (M > 127) return -2; + if (K % kGroup) return -2; + if (!a_ld) a_ld = K; + if (!y_ld) y_ld = N; + if (a_ld % 4) return -3; + if (y_ld < N) return -3; + if (!b_rb) b_rb = K; + if (b_rb < K) return -3; + if (b_rb & 15) return -5; + if (!sb_rb) sb_rb = K / kGroup; + if (sb_rb < K / kGroup) return -3; + if (((uintptr_t)a & 3u) || ((uintptr_t)b & 15u)) return -5; + + const int mrowblk = (M + MT * 16 - 1) / (MT * 16); + const dim3 grid((N + kWaves * 16 - 1) / (kWaves * 16), (unsigned)mrowblk), block(kBlockThreads); + if (nt) + R3D_KLAUNCH(gemm_w8a8_wmma_m64_kernel, grid, block, (hipStream_t)stream, + (const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, + (const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld); + else + R3D_KLAUNCH(gemm_w8a8_wmma_m64_kernel, grid, block, (hipStream_t)stream, + (const int8_t*)a, (const float*)a_scale, (const uint8_t*)b, (int)b_rb, + (const uint16_t*)b_scale, (int)sb_rb, (uint16_t*)y, M, N, K, a_ld, y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* ================================================================================================== + * The RadArgs shim. Schema positions: a 0, a_scale 1, b 2, b_scale 3, y 4, a_sum 5, b_ref 6. The + * m64 band is 17 <= M <= 127; M <= 16 is the m16 arm's, so the two rows never compete. + * ================================================================================================== */ +extern "C" int r3d_rad_gemm_nt_q_w8a8_m64(const RadArgs* a, RadStream s) +{ + if (!a) return R3D_NO(RAD_E_INVAL); + const char* dt = r3d_gets(a, "dtype"); + if (dt && std::strcmp(dt, "w8a8") != 0) return R3D_NO(RAD_E_DTYPE); + + const RadTensor* A = r3d_opt(a, 0); + const RadTensor* AS = r3d_opt(a, 1); + const RadTensor* B = r3d_opt(a, 2); + const RadTensor* BS = r3d_opt(a, 3); + const RadTensor* Y = r3d_opt(a, 4); + const RadTensor* ASUM = r3d_opt(a, 5); + const RadTensor* BREF = r3d_opt(a, 6); + if (!r3d_p(A) || !r3d_p(AS) || !r3d_p(B) || !r3d_p(BS) || !r3d_p(Y)) + return R3D_NO(RAD_E_INVAL); + if (r3d_has(ASUM) || r3d_has(BREF)) return R3D_NO(RAD_E_DTYPE); + + if (!r3d_is_i8(A)) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_f32(AS)) return R3D_NO(RAD_E_DTYPE); + if (B->dtype != RAD_I8) return R3D_NO(RAD_E_DTYPE); + if (BS->dtype != RAD_F16) return R3D_NO(RAD_E_DTYPE); + if (!r3d_is_bf16(Y)) return R3D_NO(RAD_E_DTYPE); + + const long long N = r3d_geti_or(a, "N", 0), K = r3d_geti_or(a, "K", 0); + if (N < 1 || K < 1) return R3D_NO(RAD_E_SHAPE); + if (K % kGroup) return R3D_NO(RAD_E_SHAPE); + + const long long ynel = r3d_numel(Y); + if (ynel % N) return R3D_NO(RAD_E_SHAPE); + const long long M = ynel / N; + if (M < 17 || M > 127) return R3D_NO(RAD_E_SHAPE); + + if (r3d_numel(A) < M * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(AS) < M) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(B) < N * K) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(BS) < N * (K / kGroup)) return R3D_NO(RAD_E_SHAPE); + + const long long ap = r3d_row_pitch(A); + if (ap < K || ap % 4) return R3D_NO(RAD_E_STRIDE); + if (!r3d_contig(B)) return R3D_NO(RAD_E_STRIDE); + long long yrows = 0; + const long long yp = r3d_rows_pitch(Y, N, &yrows); + if (yp < N) return R3D_NO(RAD_E_STRIDE); + if (!r3d_aligned(r3d_p(A), 4) || !r3d_aligned(r3d_p(B), 16)) return R3D_NO(RAD_E_ALIGN); + + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + + const int rc = r3d_gemm_nt_q_w8a8_m64_wmma(r3d_addr(A), r3d_addr(AS), r3d_addr(B), + r3d_addr(BS), r3d_addr(Y), (int)M, (int)N, + (int)K, (int)ap, (int)yp, + (long long)r3d_row_pitch(B), + (long long)r3d_row_pitch(BS), c.nt, (long)s); + if (rc == -1) return R3D_NO(RAD_E_INVAL); + if (rc == -2) return R3D_NO(RAD_E_SHAPE); + if (rc == -3) return R3D_NO(RAD_E_STRIDE); + if (rc == -5) return R3D_NO(RAD_E_ALIGN); + if (rc == -4) return R3D_NO(RAD_E_DEVICE); + return RAD_OK; +} diff --git a/libr3d/r3d_had_quant_act_fp8.hip b/libr3d/r3d_had_quant_act_fp8.hip new file mode 100644 index 00000000..ecfd7284 --- /dev/null +++ b/libr3d/r3d_had_quant_act_fp8.hip @@ -0,0 +1,119 @@ +/* r3d_had_quant_act_fp8.hip -- had_quant_act_fp8: a 128-wide block Hadamard, then per-group E4M3. + * + * The rotated form of quant_act_fp8: the 128-wide Hadamard shrinks the group maximum, so e4m3's + * four exponent bits carry the outliers better after the rotation. The transform is the wave-local + * FWHT of r3d_fwht.h (unnormalised; the scale carries the 1/sqrt(128) so the dequantised value is + * the orthonormal rotation). Normalisation is folded into the scale: S = absmax * (1/sqrt(128)) / + * 448, codes of (v * (128/absmax)) clamped to +-448. + * + * A separate op, not a parameter: it writes different numbers than quant_act_fp8, so a swapped + * graph would run as a different model. The codes are row-major (the fp8 GEMM reads stored order). + * + * gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here + * (a non-first wave drops out -- the same bug as the GDN recurrent kernel, the MoE router, and the + * int8 Hadamard quantisers). This serves the single-group form, n == group == 128: one wave runs + * the whole FWHT with no group loop. A wider n is declined. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopE4M3 = 448.0f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t e4m3_codes4(const float* v, float inv) { + const uint32_t lo = e4m3x2_pack(clamp_top(v[0] * inv, kTopE4M3), clamp_top(v[1] * inv, kTopE4M3)); + const uint32_t hi = e4m3x2_pack(clamp_top(v[2] * inv, kTopE4M3), clamp_top(v[3] * inv, kTopE4M3)); + return lo | (hi << 16); +} +__device__ __forceinline__ float wave_max_f(float v) { + v = fmaxf(v, r3d_xor_lane<16>(v)); + v = fmaxf(v, r3d_xor_lane<8>(v)); + v = fmaxf(v, r3d_xor_lane<4>(v)); + v = fmaxf(v, r3d_xor_lane<2>(v)); + v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_fp8_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n) { + constexpr int HAD = 128, VPL = HAD / 32; + __shared__ float lds[128]; + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* a = x + (size_t)row * n; + uint8_t* qr = q + (size_t)row * n; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.0f; + if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102) + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) v[j] = (base + j < (int)n) ? ld_bf(a, base + j) : 0.0f; + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); } + } + m = wave_max_f(m); + if (lane == 0) red[wave] = m; + __syncthreads(); + m = red[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]); + const float scale = m > 0.0f ? m * (1.0f / kTopE4M3) : 1.0f; + const float inv = 1.0f / scale; + if (threadIdx.x == 0) s[row] = scale * (1.0f / sqrtf((float)HAD)); + + for (uint32_t c = lane * 4; c < n; c += kWave * 4) { + if (wave == 0) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j]; + *(uint32_t*)(qr + c) = e4m3_codes4(v, inv); + } + } +} + +} // namespace + +extern "C" { + +int r3d_rad_had_quant_act_fp8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2); + if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || q->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(x)) return R3D_NO(RAD_E_STRIDE); + + long long M = 0, K = 0; + if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + if (K <= 0 || K % 4) return R3D_NO(RAD_E_SHAPE); + const long long grp = r3d_geti_or(a, "group", 128); + // gfx1102: single-group form (see the file header). + if (grp != 128 || K != 128) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(q) < M * K || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(kThreads); + R3D_KLAUNCH(had_quant_act_fp8_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)K); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_had_quant_act_i8.hip b/libr3d/r3d_had_quant_act_i8.hip new file mode 100644 index 00000000..13031311 --- /dev/null +++ b/libr3d/r3d_had_quant_act_i8.hip @@ -0,0 +1,144 @@ +/* r3d_had_quant_act_i8.hip -- had_quant_act_i8: a block Hadamard along K, then per-row symmetric + * int8 quantisation, written in the int8 WMMA step order. + * + * The rotation: plain per-token int8 activations are unusable on these models (KL against bf16 an + * order of magnitude worse than per-token e4m3); a block Hadamard first makes int8 several times + * better than e4m3. A rotation fixes range, not precision: int8 spends its grid covering a few + * outlier channels, and mixing each value with HAD-1 others removes them. It must happen before + * the absmax, since the benefit is a smaller row maximum, so it belongs in the quantiser. + * + * The transform is the wave-local FWHT of r3d_fwht.h: one wave owns a HAD-wide block, VPL = HAD/32 + * contiguous values per lane. Normalisation is folded into the scale: the stages compute the + * unnormalised transform (sqrt(HAD) times the orthonormal one), and S[row] = absmax * (1/sqrt(HAD)) + * / 127 undoes it while inv = 127/absmax gives the normalised codes. + * + * gfx1102 note: the FWHT's cross-lane stages are DPP exchanges, and a DPP exchange inside a loop + * body miscompiles on gfx1102 (a non-first wave drops out of the loop; the same bug as the GDN + * recurrent kernel and the MoE router). This kernel therefore serves the single-block form, + * K == group: one wave runs the whole FWHT with no block loop, the rest quantise from LDS. A + * wider K (several rotation blocks) would put the transform in a loop and is declined. + * + * The codes are written in the int8 WMMA step order (i8_step_pos, r3d_quant_fp8.hip), the same + * plane the w4a8/w8a8/w2a8 GEMMs read, so n is a multiple of 16. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; + +constexpr float kTopI8 = 127.0f; +constexpr float kI8Floor = 1e-8f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} +__device__ __forceinline__ uint32_t i8_step_pos(uint32_t c) { + return (c & ~12u) | ((c & 4u) << 1) | ((c & 8u) >> 1); +} +__device__ __forceinline__ float block_max(float v, float* lds) { + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + v = wave_max(v); + if (lane == 0) lds[wave] = v; + __syncthreads(); + float t = lds[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) t = fmaxf(t, lds[w]); + return t; +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_i8_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n, + float rnorm) { + constexpr int VPL = HAD / 32; + __shared__ float lds[1024]; // the transformed row (n <= 1024) + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* a = x + (size_t)row * n; + uint8_t* qr = q + (size_t)row * n; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + // One wave does the whole single-block FWHT: no block loop, so its DPP cross-lane stages stay + // out of a loop body (a DPP exchange in a loop miscompiles on gfx1102 -- see the file header). + float m = 0.0f; + if (wave == 0) { + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) v[j] = ld_bf(a, base + j); + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); } + } + m = block_max(m, red); + m = fmaxf(m, kI8Floor); + const float inv = kTopI8 / m; + if (threadIdx.x == 0) s[row] = m * rnorm / kTopI8; + + // Write the codes in the WMMA step order, reading the transformed row from LDS. + for (uint32_t c = threadIdx.x * 4; c < n; c += kThreads * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = (c + (uint32_t)j < n) ? lds[c + (uint32_t)j] : 0.0f; + *(uint32_t*)(qr + i8_step_pos(c)) = i8_codes4(v, inv); + } +} + +} // namespace + +extern "C" { + +int r3d_rad_had_quant_act_i8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2); + if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (!r3d_contig(x) || !r3d_contig(q) || !r3d_contig(sc)) return R3D_NO(RAD_E_STRIDE); + + long long M = 0, K = 0; + if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + if (K <= 0 || K % 16) return R3D_NO(RAD_E_SHAPE); + + const long long had = r3d_geti_or(a, "group", 128); + if (had != 128 && had != 256 && had != 512) return R3D_NO(RAD_E_SHAPE); + // gfx1102: the FWHT is DPP and must not run in a block loop (see the file header), so this + // serves the single-block form, K == group. A wider K (several rotation blocks) is declined. + if (K != had) return R3D_NO(RAD_E_SHAPE); + + const float rnorm = 1.0f / sqrtf((float)had); + dim3 grid((unsigned)M), blk(kThreads); + const uint32_t n = (uint32_t)K; + switch (had) { + case 256: R3D_KLAUNCH(had_quant_act_i8_kernel<256>, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q), + (float*)r3d_wp(sc), n, rnorm); break; + case 512: R3D_KLAUNCH(had_quant_act_i8_kernel<512>, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q), + (float*)r3d_wp(sc), n, rnorm); break; + default: R3D_KLAUNCH(had_quant_act_i8_kernel<128>, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(x), (uint8_t*)r3d_wp(q), + (float*)r3d_wp(sc), n, rnorm); break; + } + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_had_quant_act_i8g.hip b/libr3d/r3d_had_quant_act_i8g.hip new file mode 100644 index 00000000..35b45912 --- /dev/null +++ b/libr3d/r3d_had_quant_act_i8g.hip @@ -0,0 +1,117 @@ +/* r3d_had_quant_act_i8g.hip -- had_quant_act_i8g: a 128-wide block Hadamard, then per-group int8. + * + * The rotated int8 form for the int8 trunk GEMMs (i8a8): the 128-wide Hadamard shrinks the group + * maximum, and the codes are row-major (the i8a8 dot2 GEMM reads stored order), with one scale per + * (row, group). This is quant_act_i8g with the rotation; the unrotated form is a separate op. + * + * A separate op, not a parameter: it writes different numbers and a different code layout than + * quant_act_i8 (step-ordered) or had_quant_act_i8 (step-ordered), so a swapped graph would run as + * a different model. The normalisation (1/sqrt(128)) is folded into the scale. + * + * gfx1102: the FWHT's cross-lane stages are DPP, and a DPP exchange in a loop body miscompiles here + * (a non-first wave drops out). This serves the single-group form, n == group == 128: one wave runs + * the whole FWHT with no group loop. A wider n is declined. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fwht.h" +#include + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopI8 = 127.0f; + +__device__ __forceinline__ float ld_bf(const uint16_t* p, uint32_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +__device__ __forceinline__ uint32_t i8_codes4(const float* v, float inv) { + const uint32_t b0 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[0] * inv, kTopI8)); + const uint32_t b1 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[1] * inv, kTopI8)); + const uint32_t b2 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[2] * inv, kTopI8)); + const uint32_t b3 = (uint32_t)(uint8_t)f32_to_i8_rtne(clamp_top(v[3] * inv, kTopI8)); + return b0 | (b1 << 8) | (b2 << 16) | (b3 << 24); +} +__device__ __forceinline__ float wave_max_f(float v) { + v = fmaxf(v, r3d_xor_lane<16>(v)); + v = fmaxf(v, r3d_xor_lane<8>(v)); + v = fmaxf(v, r3d_xor_lane<4>(v)); + v = fmaxf(v, r3d_xor_lane<2>(v)); + v = fmaxf(v, r3d_xor_lane<1>(v)); + return v; +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void had_quant_act_i8g_kernel( + const uint16_t* __restrict__ x, uint8_t* __restrict__ q, float* __restrict__ s, uint32_t n) { + constexpr int HAD = 128, VPL = HAD / 32; + __shared__ float lds[128]; + __shared__ float red[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* a = x + (size_t)row * n; + uint8_t* qr = q + (size_t)row * n; + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + + float m = 0.0f; + if (wave == 0) { // one wave does the whole single-group FWHT (no group loop, gfx1102) + const int base = lane * VPL; + float v[VPL]; +#pragma unroll + for (int j = 0; j < VPL; ++j) v[j] = (base + j < (int)n) ? ld_bf(a, base + j) : 0.0f; + r3d_fwht_wave(v, lane); +#pragma unroll + for (int j = 0; j < VPL; ++j) { lds[base + j] = v[j]; m = fmaxf(m, fabsf(v[j])); } + } + m = wave_max_f(m); + if (lane == 0) red[wave] = m; + __syncthreads(); + m = red[0]; +#pragma unroll + for (uint32_t w = 1; w < kWaves; ++w) m = fmaxf(m, red[w]); + m = m > 0.0f ? m : 1e-8f; + const float inv = kTopI8 / m; + if (threadIdx.x == 0) s[row] = m * (1.0f / sqrtf((float)HAD)) / kTopI8; + + if (wave == 0) + for (uint32_t c = lane * 4; c < n; c += kWave * 4) { + float v[4]; +#pragma unroll + for (int j = 0; j < 4; ++j) v[j] = lds[c + (uint32_t)j]; + *(uint32_t*)(qr + c) = i8_codes4(v, inv); // row-major (the i8a8 GEMM's layout) + } +} + +} // namespace + +extern "C" { + +int r3d_rad_had_quant_act_i8g(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, 0), *q = r3d_opt(a, 1), *sc = r3d_opt(a, 2); + if (!r3d_p(x) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(x)) return R3D_NO(RAD_E_STRIDE); + + long long M = 0, K = 0; + if (r3d_rows_of(x, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + if (K <= 0 || K % 4) return R3D_NO(RAD_E_SHAPE); + const long long grp = r3d_geti_or(a, "group", 128); + if (grp != 128 || K != 128) return R3D_NO(RAD_E_SHAPE); // single-group form (gfx1102) + if (r3d_numel(q) < M * K || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(kThreads); + R3D_KLAUNCH(had_quant_act_i8g_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x), + (uint8_t*)r3d_wp(q), (float*)r3d_wp(sc), (uint32_t)K); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_kv_len_trim.hip b/libr3d/r3d_kv_len_trim.hip new file mode 100644 index 00000000..493535f5 --- /dev/null +++ b/libr3d/r3d_kv_len_trim.hip @@ -0,0 +1,52 @@ +/* r3d_kv_len_trim.hip -- kv_len_trim: a batch's per-sequence context lengths less `trim`. + * + * The prefill overlap runs attention per slice of a one-sequence step: slice A's rows are the step's + * first rows, so its attention must see the context ending at its own last row, not the step's (rows + * past it are not yet in the cache). `trim` is the rows after the slice, a runtime count carried by + * the extent of operand `tail`, whose values are never read. + * + * in [n] i32, tail (extent = trim) -> out [n] i32, out[i] = max(in[i] - trim, 0) + * + * n <= 64 (a batch), one workgroup. + */ +#include + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +namespace { + +__global__ __launch_bounds__(64) void kv_len_trim_kernel(const int32_t* __restrict__ in, + int32_t* __restrict__ out, int n, + int trim) { + const int i = (int)threadIdx.x; + if (i < n) { + const int v = in[i] - trim; + out[i] = v > 0 ? v : 0; + } +} + +} // namespace + +extern "C" { + +int r3d_rad_kv_len_trim(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* in = r3d_opt(a, 0), *tail = r3d_opt(a, 1), *out = r3d_opt(a, 2); + if (!r3d_p(in) || !r3d_wp(out)) return R3D_NO(RAD_E_INVAL); + if (in->dtype != RAD_I32 || out->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + const long long n = r3d_numel(in); + if (n < 1 || n > 64 || r3d_numel(out) < n) return R3D_NO(RAD_E_SHAPE); + const long long trim = tail ? r3d_numel(tail) : 0; + if (trim < 0 || trim > 0x7fffffffLL) return R3D_NO(RAD_E_SHAPE); + + R3D_KLAUNCH(kv_len_trim_kernel, dim3(1), dim3(64), (hipStream_t)s, (const int32_t*)r3d_p(in), + (int32_t*)r3d_wp(out), (int)n, (int)trim); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_launch.h b/libr3d/r3d_launch.h index 48df1996..d2a7f356 100644 --- a/libr3d/r3d_launch.h +++ b/libr3d/r3d_launch.h @@ -15,6 +15,12 @@ #ifndef R3D_KLAUNCH #define R3D_KLAUNCH(kernel, grid, block, stream, ...) kernel<<>>(__VA_ARGS__) #endif +/* The same launch with a dynamic-LDS byte count, for the rows whose stage is sized by the launch + * rather than a template constant. */ +#ifndef R3D_KLAUNCH_S +#define R3D_KLAUNCH_S(kernel, grid, block, smem, stream, ...) \ + kernel<<>>(__VA_ARGS__) +#endif #ifndef R3D_DYN_LDS #define R3D_DYN_LDS(type, name) extern __shared__ type name[] #endif diff --git a/libr3d/r3d_moe_gather.hip b/libr3d/r3d_moe_gather.hip new file mode 100644 index 00000000..a67a965c --- /dev/null +++ b/libr3d/r3d_moe_gather.hip @@ -0,0 +1,205 @@ +/* r3d_moe_gather.hip -- moe_gather / moe_gather_inv: fold the expert outputs back to the token. + * + * y[t, c] = sum_j expert_w[t, j] * y_expert[slot(t, j), c] + * + * summed in ascending slot order (reproducibility: the expert-sorted order would differ in the last + * bits). One block per token; the slot table (slot(t, j) and the weight) is hoisted to LDS so the + * per-column `ye` loads pipeline. + * + * Two arms: + * - moe_gather: `slot` is the inverse of `sorted_tok`; the block scans `sorted` for its token's + * slots (the self-scan form, no prepass). + * - moe_gather_inv: `slot` is the `inverse` table moe_scatter_inv wrote (read straight). + * + * An optional shared arm adds `shared[t, c] * act(gate[t])` (two narrows, matching the unfused + * scale_rows pair). `act` is "sigmoid" (the only form we take; "none" is refused, absent = the + * identity). + * + * The wide-prefill form (a wave per token, 8 cols/lane) is not implemented; this is the decode and + * short-pass form (one block per token), which covers every height the engine routes here. + */ +#include + +#include +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +namespace { + +constexpr uint32_t kGatherThr = 256; +constexpr uint32_t kGatherSlots = 64; // top_k <= 64 for the LDS-cached slot table + +template +__device__ __forceinline__ float gather_weight(const void* ew, size_t i) { + if constexpr (F32W) return ((const float*)ew)[i]; + else return bf16_to_f32(((const uint16_t*)ew)[i]); +} + +/* One enum arg (not two bools) so the launch macro sees a single, comma-free template argument. */ +enum class Gk { bf16_sorted, bf16_inv, f32_sorted, f32_inv }; + +template +__global__ __launch_bounds__(kGatherThr) void gather_kernel( + const uint16_t* __restrict__ ye, const void* __restrict__ ew, + const int32_t* __restrict__ inv, uint16_t* __restrict__ y, + uint32_t M, uint32_t n, uint32_t top_k, uint32_t ye_ld, uint32_t ew_ld, uint32_t y_ld, + const int32_t* __restrict__ sorted, uint32_t T, + const uint16_t* __restrict__ sh, const uint16_t* __restrict__ sg, + uint32_t sh_ld, uint32_t sg_ld, int sig) { + constexpr bool F32W = (MODE == Gk::f32_sorted || MODE == Gk::f32_inv); + constexpr bool GIVEN = (MODE == Gk::bf16_inv || MODE == Gk::f32_inv); + __shared__ int32_t s_i[kGatherSlots]; + __shared__ float s_w[kGatherSlots]; + const uint32_t t = blockIdx.x; + if (t >= M) return; + const bool cached = top_k <= kGatherSlots; + + float gate = 0.0f; + if (sh) { + const float v0 = bf16_to_f32(sg[(size_t)t * sg_ld]); + gate = sig ? (1.0f / (1.0f + __expf(-v0))) : v0; + } + + if (!GIVEN) { + /* The self-scan form: scan `sorted` for this token's slots. An unclaimed slot reads -1, so + * the fill and the scan are separated by a barrier. */ + for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr) s_i[j] = -1; + __syncthreads(); + const int32_t lo = (int32_t)(t * top_k), hi = lo + (int32_t)top_k; + for (uint32_t i = threadIdx.x; i < T; i += kGatherThr) { + const int32_t f = sorted[i]; + if (f >= lo && f < hi) s_i[f - lo] = (int32_t)i; + } + for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr) + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + __syncthreads(); + } else if (cached) { + for (uint32_t j = threadIdx.x; j < top_k; j += kGatherThr) { + s_i[j] = inv[t * top_k + j]; + s_w[j] = gather_weight(ew, (size_t)t * ew_ld + j); + } + __syncthreads(); + } + + for (uint32_t c = blockIdx.y * kGatherThr + threadIdx.x; c < n; c += kGatherThr * gridDim.y) { + float acc = 0.0f; + for (uint32_t j = 0; j < top_k; ++j) { + const int32_t i = cached ? s_i[j] : inv[t * top_k + j]; + if (i < 0) continue; + const float wj = cached ? s_w[j] : gather_weight(ew, (size_t)t * ew_ld + j); + acc += wj * bf16_to_f32(ye[(size_t)i * ye_ld + c]); + } + const uint16_t g = f32_to_bf16(acc); + if (!sh) { y[(size_t)t * y_ld + c] = g; continue; } + const uint16_t p = f32_to_bf16(bf16_to_f32(sh[(size_t)t * sh_ld + c]) * gate); + y[(size_t)t * y_ld + c] = f32_to_bf16(bf16_to_f32(p) + bf16_to_f32(g)); + } +} + + +} // namespace + +extern "C" { + +int r3d_rad_moe_gather(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* ye = r3d_opt(a, 0), *ew = r3d_opt(a, 1), *sorted = r3d_opt(a, 2), + *y = r3d_opt(a, 5); + if (!r3d_p(ye) || !r3d_p(ew) || !r3d_p(sorted) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL); + if (ye->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + if (sorted->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + + const long long M = r3d_geti_or(a, "M", 0), n = r3d_geti_or(a, "n", 0), + top_k = r3d_geti_or(a, "top_k", 0); + if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE); + if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only + + const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]); + const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]); + const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]); + const uint32_t T = (uint32_t)r3d_numel(sorted); + if (T < M * top_k) return R3D_NO(RAD_E_SHAPE); + + // The optional shared arm (operands 3 and 4, present together). + const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4); + const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr; + const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr; + if (sh && !sg) return R3D_NO(RAD_E_INVAL); + const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0; + const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1; + int sig = 0; + if (const char* act = r3d_gets(a, "act")) { + if (std::string(act) == "sigmoid") sig = 1; + else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL); + } + + const bool f32w = (ew->dtype == RAD_F32); + dim3 grid((unsigned)M, (unsigned)((n + kGatherThr - 1) / kGatherThr)), blk(kGatherThr); + if (f32w) + R3D_KLAUNCH(gather_kernel, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(sorted), + (uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld, + y_ld, (const int32_t*)r3d_p(sorted), T, shp, sgp, sh_ld, sg_ld, sig); + else + R3D_KLAUNCH(gather_kernel, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(sorted), + (uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld, + y_ld, (const int32_t*)r3d_p(sorted), T, shp, sgp, sh_ld, sg_ld, sig); + return (int)hipGetLastError(); +} + +int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* ye = r3d_opt(a, 0), *ew = r3d_opt(a, 1), *inv = r3d_opt(a, 2), + *y = r3d_opt(a, 5); + if (!r3d_p(ye) || !r3d_p(ew) || !r3d_p(inv) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL); + if (ye->dtype != RAD_BF16 || y->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (ew->dtype != RAD_BF16 && ew->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + if (inv->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + + const long long M = r3d_geti_or(a, "M", 0), n = r3d_geti_or(a, "n", 0), + top_k = r3d_geti_or(a, "top_k", 0); + if (M <= 0 || n <= 0 || top_k <= 0) return R3D_NO(RAD_E_SHAPE); + if (top_k > kGatherSlots) return R3D_NO(RAD_E_SHAPE); // the LDS-cached form only + + const uint32_t ye_ld = (uint32_t)(ye->rank >= 2 ? ye->shape[1] : ye->stride[0]); + const uint32_t ew_ld = (uint32_t)(ew->rank >= 2 ? ew->shape[1] : ew->stride[0]); + const uint32_t y_ld = (uint32_t)(y->rank >= 2 ? y->shape[1] : y->stride[0]); + const uint32_t T = (uint32_t)r3d_numel(inv); + if (T < M * top_k) return R3D_NO(RAD_E_SHAPE); + + const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4); + const uint16_t* shp = sh ? (const uint16_t*)r3d_p(sh) : nullptr; + const uint16_t* sgp = sg ? (const uint16_t*)r3d_p(sg) : nullptr; + if (sh && !sg) return R3D_NO(RAD_E_INVAL); + const uint32_t sh_ld = sh ? (uint32_t)(sh->rank >= 2 ? sh->shape[1] : sh->stride[0]) : 0; + const uint32_t sg_ld = sg ? (uint32_t)(sg->rank >= 1 ? sg->shape[0] : sg->stride[0]) : 1; + int sig = 0; + if (const char* act = r3d_gets(a, "act")) { + if (std::string(act) == "sigmoid") sig = 1; + else if (std::string(act) == "none") return R3D_NO(RAD_E_INVAL); + } + + const bool f32w = (ew->dtype == RAD_F32); + dim3 grid((unsigned)M, (unsigned)((n + kGatherThr - 1) / kGatherThr)), blk(kGatherThr); + if (f32w) + R3D_KLAUNCH(gather_kernel, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(inv), + (uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld, + y_ld, (const int32_t*)nullptr, T, shp, sgp, sh_ld, sg_ld, sig); + else + R3D_KLAUNCH(gather_kernel, grid, blk, (hipStream_t)s, + (const uint16_t*)r3d_p(ye), r3d_p(ew), (const int32_t*)r3d_p(inv), + (uint16_t*)r3d_wp(y), (uint32_t)M, (uint32_t)n, (uint32_t)top_k, ye_ld, ew_ld, + y_ld, (const int32_t*)nullptr, T, shp, sgp, sh_ld, sg_ld, sig); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_bf16.hip b/libr3d/r3d_moe_gemm_bf16.hip new file mode 100644 index 00000000..8df7fefd --- /dev/null +++ b/libr3d/r3d_moe_gemm_bf16.hip @@ -0,0 +1,340 @@ +/* r3d_moe_gemm_bf16.hip -- moe_gemm_bf16: the grouped GEMM with unquantised bf16 experts. + * + * y[i, n] = sum_k a[tok(i), k] * w_e[n, k], e = the expert of sorted row i + * + * One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile. + * bf16 activation, bf16 weight as the checkpoint stores it ([n_expert, N, K] row-major, no layout + * hook, every expert in class 0), f32 accumulate over the whole of K, bf16 out. The 16-row tile is + * the same run-walk / gather structure as moe_gemm_q, minus the E4M3 decode and the scale fold: + * the operands are bf16, so they stage to LDS and load straight into the bf16 wave-matrix + * fragments (v_wmma_f32_16x16x16_bf16, f32 accumulate). + * + * K is walked in 64-deep tiles (four 16-wide wave-matrix steps); N and K are multiples of 16. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kNBlock = 128; // eight waves x 16 cols +constexpr int kKT = 64; // a k tile: four 16-wide wmma steps +constexpr int kDW = kKT / 2; // dwords a row: 64 bf16 are 32 dwords (two bf16 a dword) +constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free +constexpr int kStageW = kNBlock * kDW / kThreads; // ...and of the weight (128 cols) + +/* MROWS is the block's row count (16, 32 or 64), the tune's point: a taller block reads the + * weight T/MROWS times, so the tune picks per shape -- 16 for decode, 64 for a tall prefill. */ +/* The kernel, emitted once per (row count, register budget) point. amdgpu_num_vgpr takes a + * literal, so the budget cannot live on a template; and the definitions stay monolithic, because + * the allocator schedules the inlined-body form (a __device__ helper) noticeably worse. + * + * Register budgets (gfx11: 1024 VGPRs/SIMD, 8 waves needs <= 128; measured on gfx1102 at + * T=N=K=4096 NE=8, median of 15 launches): + * (32, 128): 144 VGPR, 6 spills = 7 waves -- +38% vs (32, 512) at 171 VGPR = 5 waves: the middle + * height is latency-bound, so the extra waves beat the spill traffic. + * (16, 128) and (64, 128) measure 7-8% SLOWER (145/8 and 193/54 spills), so those rows keep the + * natural allocation only. + * Re-measure before touching a budget here; occupancy is a means to hide latency, not a goal + * (GPUOpen, "Occupancy explained": only latency-bound work benefits, and spills can cost more). */ + +/* The accumulator's mode (the tune's `acc` axis): 0 = f32, 1 = the bf16-precision WMMA + * accumulator (the 16x16x16_bf16 builtin, OPSEL false: the 8 live values in the even indices of + * a v16, 4 VGPRs). `blk` is the per-k-tile accumulator; it is folded into the f32 `acc` after + * each 64-wide k tile, so the half-precision span is one tile, not the whole K. + * + * PRECISION (measured on gfx1102, random bf16 in [-1,1], K = 128): the acc=1 arm deviates from + * the f32 reference by up to ~0.36 absolute (~3% of a typical |y| ~ 11; larger relative to + * near-zero outputs). The 16-bit WMMA accumulator is a documented low-precision mode (AMD ROCm + * Optimization Guide, RDNA3 dense WMMA builtins; the same builtin chain AMD's ck uses): the + * hardware quantises the running sum at 16-bit precision per step, and the loss grows with the + * number of steps. Exact on integer-valued data (e.g. +/-1 inputs). There is NO throughput gain + * from the acc=1 arm (measured +0.05%..-0.2%): it exists as a register-pressure option for + * future occupancy work, not a speed one. Do not select acc=1 for accuracy-sensitive shapes; + * the f32 arm (acc=0) is the correct default. */ +template +struct R3dMoeAcc { using type = std::conditional_t; }; +template +__device__ __forceinline__ void r3d_moe_acc_init(typename R3dMoeAcc::type& x) +{ + if constexpr (ACC) x = v16short{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; + else x = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; +} +template +__device__ __forceinline__ typename R3dMoeAcc::type r3d_moe_wmma_bf16( + const v16short& fa, const v16short& fb, const typename R3dMoeAcc::type& c) +{ + if constexpr (ACC) return wmma_bf16acc(fa, fb, c); + else return wmma_bf16(fa, fb, c); +} +template +__device__ __forceinline__ float r3d_moe_acc_read(const typename R3dMoeAcc::type& x, int g) +{ + if constexpr (ACC) { + const uint32_t u = (uint32_t)(uint16_t)x[2 * g] << 16; /* the bf16 bits -> f32 */ + return *(const float*)&u; + } + return x[g]; +} + +#define R3D_MBE_BODY \ +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \ +__attribute__((amdgpu_num_vgpr(MBE_VGPR))) void MBE_KNAME( \ + const uint16_t* __restrict__ a, \ + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \ + const uint16_t* __restrict__ w, \ + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \ + int n_expert, int top_k) \ +{ \ + constexpr int kMBlock = MBE_MR; /* a block is MBE_MR rows x 128 cols */ \ + constexpr int kRB = MBE_MR / 16; /* row-blocks a wave accumulates */ \ + constexpr int kStageA = MBE_MR * kDW / kThreads; /* dwords a thread stages of the activation */ \ + __shared__ __align__(16) uint32_t s_a[2][kMBlock * kPitch]; /* double-buffered activation (32 rows) */ \ + __shared__ __align__(16) uint32_t s_w[2][kNBlock * kPitch]; /* ...and weight (128 cols) */ \ + __shared__ int32_t s_tok[kMBlock]; \ + __shared__ int32_t s_nruns; \ + __shared__ int32_t s_rs[kMBlock], s_re[kMBlock], s_e[kMBlock]; \ + \ + const uint32_t tid = threadIdx.x; \ + const uint32_t lane = tid & (kWave - 1); \ + const uint32_t wv = tid / kWave; /* the wave index (0..7): owns cols wv*16..wv*16+16 */ \ + const uint32_t r = lane & 15; \ + \ + const uint32_t r0 = (uint32_t)blockIdx.y * kMBlock; /* the block's sorted rows */ \ + const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; \ + const uint32_t r1 = (r0 + kMBlock < (uint32_t)T) ? r0 + kMBlock : (uint32_t)T; \ + \ + /* The block's rows' source tokens (the gather). -1 marks a dropped slot. */ \ + if (tid < kMBlock) { \ + const uint32_t i = r0 + tid; \ + const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \ + s_tok[tid] = (f < 0) ? -1 : (f / top_k); \ + } \ + /* The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. */ \ + if (tid == 0) { \ + int nruns = 0, i = (int)r0; \ + while (i < (int)r1) { \ + int32_t ee = -1; \ + for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; \ + const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); \ + s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; \ + ++nruns; i = re; \ + } \ + s_nruns = nruns; \ + } \ + group_barrier(); \ + const int nruns = s_nruns; \ + \ + const uint32_t nc = n0 + wv * 16 + r; /* this wave's output column */ \ + const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); \ + \ + /* One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the */ \ + /* run does not own are padding (reading the run's first row) and their output is dropped. */ \ + for (int run = 0; run < nruns; ++run) { \ + const int rs = s_rs[run], re = s_re[run], e = s_e[run]; \ + v8float acc[kRB]; \ + _Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) \ + acc[rb] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; \ + if (e >= 0) { \ + const uint16_t* wbase = w + (size_t)e * (size_t)N * w_ld; \ + \ + const int ntile = (K + kKT - 1) / kKT; \ + /* Prologue: stage tile 0 into buffer 0. */ \ + for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \ + const int row = i / kDW, d = i % kDW; \ + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \ + : s_tok[rs - (int)r0]; \ + const int rr = (src < 0) ? 0 : src; \ + s_a[0][(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + 2 * d); \ + } \ + for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \ + const int col = i / kDW, d = i % kDW; \ + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \ + s_w[0][(size_t)col * kPitch + d] = *(const uint32_t*)(wbase + (size_t)nn * w_ld + 2 * d); \ + } \ + group_barrier(); \ + /* Pipelined: the next tile's global loads are issued into registers before this tile's WMMA, */ \ + /* so the ~300-cycle VRAM latency is hidden behind the matrix-core work; they land in the */ \ + /* other buffer after the WMMA (the s_waitcnt of the LDS store waits on the in-flight loads). */ \ + for (int t = 0; t < ntile; ++t) { \ + const int b = t & 1, nb = b ^ 1; \ + uint32_t ra[kStageA], rw[kStageW]; \ + if (t + 1 < ntile) { \ + const int kt1 = (t + 1) * kKT; \ +_Pragma("unroll") \ + for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \ + const int li = (i - (int)tid) / kThreads; \ + const int row = i / kDW, d = i % kDW; \ + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \ + : s_tok[rs - (int)r0]; \ + const int rr = (src < 0) ? 0 : src; \ + ra[li] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt1 + 2 * d); \ + } \ + for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \ + const int li = (i - (int)tid) / kThreads; \ + const int col = i / kDW, d = i % kDW; \ + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \ + rw[li] = *(const uint32_t*)(wbase + (size_t)nn * w_ld + kt1 + 2 * d); \ + } \ + } \ + const uint32_t* wp = s_w[b] + (size_t)(wv * 16 + r) * kPitch; /* this wave's 16 cols */ \ +_Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) { /* the 16-row blocks; the B-fragment is shared */ \ + const uint32_t* ap = s_a[b] + (size_t)(rb * 16 + r) * kPitch; \ + typename R3dMoeAcc::type blk; \ + r3d_moe_acc_init(blk); \ +_Pragma("unroll") \ + for (int k = 0; k < kKT; k += 16) { \ + v16short fa, fb; \ +_Pragma("unroll") \ + for (int g = 0; g < 8; ++g) { \ + const uint32_t dw = ap[k / 2 + g]; \ + fa[2 * g] = (short)(dw & 0xffffu); fa[2 * g + 1] = (short)(dw >> 16); \ + const uint32_t dwb = wp[k / 2 + g]; \ + fb[2 * g] = (short)(dwb & 0xffffu); fb[2 * g + 1] = (short)(dwb >> 16); \ + } \ + blk = r3d_moe_wmma_bf16(fa, fb, blk); \ + } \ + _Pragma("unroll") \ + for (int g = 0; g < 8; ++g) acc[rb][g] += r3d_moe_acc_read(blk, g); \ + } \ + if (t + 1 < ntile) { \ + for (int i = (int)tid; i < kMBlock * kDW; i += kThreads) { \ + const int li = (i - (int)tid) / kThreads; \ + const int row = i / kDW, d = i % kDW; \ + s_a[nb][(size_t)row * kPitch + d] = ra[li]; \ + } \ + for (int i = (int)tid; i < kNBlock * kDW; i += kThreads) { \ + const int li = (i - (int)tid) / kThreads; \ + const int col = i / kDW, d = i % kDW; \ + s_w[nb][(size_t)col * kPitch + d] = rw[li]; \ + } \ + } \ + group_barrier(); \ + } \ + \ + } \ + /* Store only the run's rows, as bf16, across the 16-row blocks. */ \ +_Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) \ + _Pragma("unroll") \ + for (int g = 0; g < 8; ++g) { \ + const int row = (int)(rb * 16 + g * 2 + (lane >> 4)); \ + const int m = (int)(r0 + row); \ + if (rs <= m && m < re && nc < (uint32_t)N) \ + y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[rb][g]); \ + } \ + } \ +} +#define MBE_KNAME moe_bf16_kernel16 +#define MBE_MR 16 +#define MBE_VGPR 512 +#define MBE_ACC 0 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel16_a1 +#define MBE_MR 16 +#define MBE_VGPR 512 +#define MBE_ACC 1 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel32 +#define MBE_MR 32 +#define MBE_VGPR 512 +#define MBE_ACC 0 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel32_a1 +#define MBE_MR 32 +#define MBE_VGPR 512 +#define MBE_ACC 1 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel32_c128 +#define MBE_MR 32 +#define MBE_VGPR 128 +#define MBE_ACC 0 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel32_c128_a1 +#define MBE_MR 32 +#define MBE_VGPR 128 +#define MBE_ACC 1 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel64 +#define MBE_MR 64 +#define MBE_VGPR 512 +#define MBE_ACC 0 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#define MBE_KNAME moe_bf16_kernel64_a1 +#define MBE_MR 64 +#define MBE_VGPR 512 +#define MBE_ACC 1 +R3D_MBE_BODY +#undef MBE_KNAME MBE_MR MBE_VGPR MBE_ACC +#undef R3D_MBE_BODY + +} // namespace + +extern "C" { + +int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = r3d_opt(a, 0), *wt = r3d_opt(a, 1), *st = r3d_opt(a, 2), + *ot = r3d_opt(a, 3), *yt = r3d_opt(a, 4); + if (!r3d_p(at) || !r3d_p(wt) || !r3d_p(st) || !r3d_p(ot) || !r3d_wp(yt)) + return R3D_NO(RAD_E_INVAL); + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long T = (st->rank >= 1) ? st->shape[0] : 0; + const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; + if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || (K & 63)) return R3D_NO(RAD_E_SHAPE); // N tail clamps + const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); + const int top_k = (int)r3d_geti_or(a, "top_k", 1); + const int a_ld = (int)at->stride[0]; + const int w_ld = (int)wt->shape[2]; + const int y_ld = (int)yt->stride[0]; + + R3dMoeCfg c; r3d_cfg_moe(a, &c); // the tune's row count (16, 32 or 64), 64 untuned +#define R3D_LM(MR, KERN) \ + do { \ + dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + MR - 1) / MR)), \ + blk(kThreads); \ + KERN<<>>( \ + (const uint16_t*)r3d_p(at), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(ot), \ + (const uint16_t*)r3d_p(wt), (uint16_t*)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, w_ld, \ + y_ld, n_expert, top_k); \ + } while (0) + if (c.mrows <= 16) { + if (c.acc) R3D_LM(16, moe_bf16_kernel16_a1); + else R3D_LM(16, moe_bf16_kernel16); + } + else if (c.mrows <= 32) { + if (c.vgpr == 128) { + if (c.acc) R3D_LM(32, moe_bf16_kernel32_c128_a1); + else R3D_LM(32, moe_bf16_kernel32_c128); + } + else { + if (c.acc) R3D_LM(32, moe_bf16_kernel32_a1); + else R3D_LM(32, moe_bf16_kernel32); + } + } + else { + if (c.acc) R3D_LM(64, moe_bf16_kernel64_a1); + else R3D_LM(64, moe_bf16_kernel64); + } +#undef R3D_LM + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_fp8_f32scale.hip b/libr3d/r3d_moe_gemm_fp8_f32scale.hip new file mode 100644 index 00000000..5f197f5a --- /dev/null +++ b/libr3d/r3d_moe_gemm_fp8_f32scale.hip @@ -0,0 +1,342 @@ +/* r3d_moe_gemm_fp8_f32scale.hip -- moe_gemm_q (the wave-matrix form): the grouped GEMM with E4M3 + * experts and exact F32 block scales. + * + * y[i, n] = sum_g as[tok(i), g] * wsb[e, n/grid_rows][g] * sum_{k in g} a[tok(i), k] * w_e[n, k] + * + * The moe_gemm_q contract: a and the weight planes are E4M3, one F32 scale per (row, 128 of K) + * for the activation and one per (plane expert, n/grid_rows, 128 of K) for the weight; the even + * experts live in w / w_scale and the odd in w_odd / w_odd_scale, at index e/2; y is f32 in sorted + * order. E4M3 activation and E4M3 weight (the checkpoint stores the plane as [n_expert/2, N, K] + * row-major, one byte a code). f32 accumulate over the whole of K. + * + * gfx11 has no native FP8 wave-matrix, so the codes widen to f16 (exact: every E4M3 grid point is + * an f16 grid point) and the multiply runs on the 16x16x16 f16 tile. K is walked in 128-deep + * tiles (the scale group); each tile's eight 16-wide steps accumulate into a fresh f32 partial, + * which is folded as raw * (activation scale * weight scale) into the running sum. The 16-row + * tile is the same run-walk / gather structure as moe_gemm_bf16. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_fp8_dequant.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kNBlock = 128; // eight waves x 16 cols +constexpr int kKT = 128; // a k tile: one scale group (eight 16-wide wmma steps) +constexpr int kDW = kKT / 4; // dwords a row: 128 fp8 are 32 dwords (four fp8 a dword) +constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free +constexpr int kStageW = kNBlock * kDW / kThreads; +constexpr int kP16 = kKT + 1; // f16 halfs a staged row: 128 + 1, bank-free + +/* The kernel, emitted once per register-budget point. amdgpu_num_vgpr takes a literal, so the + * budget cannot live on a template; and the definitions stay monolithic, because the allocator + * schedules the inlined-body form (a __device__ helper) noticeably worse. + * + * Register budgets (gfx11: 1024 VGPRs/SIMD, 8 waves needs <= 128; measured on gfx1102 at + * T=N=K=4096 NE=8, median of 15 launches): the natural 155 VGPRs give 6 waves; the 128 cap lands + * at 103 with zero spills = 8 waves, +2-4%. The tune exposes both points (tMoeGemmFp8) and + * defaults to the cap. Re-measure before changing a budget here. */ + +/* The accumulator's mode (the tune's `acc` axis): 0 = f32, 1 = the f16-precision WMMA + * accumulator (the 16x16x16_f16 builtin, OPSEL false: the 8 live values in the even indices of a + * v16, 4 VGPRs). `blk` is the per-k-tile accumulator; it is folded (with the per-row scale) into + * the f32 `acc` after each 128-wide k tile, so the half-precision span is one tile, not the K. + * + * PRECISION (measured on gfx1102): the acc=1 arm quantises the per-tile f16 partial sum at 16-bit + * precision per wave-matrix step (the hardware's documented low-precision mode, same builtin + * chain AMD's ck uses). On exactly-representable E4M3 code data (0.5/1.0) it is bit-exact to the + * f32 arm (store rounding only); on arbitrary f16 data the deviation grows with the k-tile depth + * (~0.17 abs over 4 steps of 16-wide random f16 in [-1,1], measured). No throughput gain from + * acc=1 (measured +0.2%..-1%). It exists as a register-pressure option, not a speed one; acc=0 + * is the correct default for accuracy-sensitive shapes. */ +template +struct R3dMoeAccF16 { using type = std::conditional_t; }; +template +__device__ __forceinline__ void r3d_moe_acc_f16_init(typename R3dMoeAccF16::type& x) +{ + if constexpr (ACC) x = v16half{ 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0 }; + else x = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; +} +template +__device__ __forceinline__ typename R3dMoeAccF16::type r3d_moe_wmma_f16( + const v16half& fa, const v16half& fb, const typename R3dMoeAccF16::type& c) +{ + if constexpr (ACC) return wmma_f16acc(fa, fb, c); + else return wmma_f16(fa, fb, c); +} +template +__device__ __forceinline__ float r3d_moe_acc_f16_read(const typename R3dMoeAccF16::type& x, int g) +{ + /* Direct f16 -> f32 value conversion. NOT a bit-cast: type-punning the OPSEL + * (16-bit-accumulator) vector through a union breaks the srcC == result physical- + * register constraint, and the compiler then reads the wmma result from the stale + * srcC copy (measured: the accumulated tile comes back as zero). */ + if constexpr (ACC) return (float)x[2 * g]; + return x[g]; +} + +#define R3D_MFS_BODY \ +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) \ +__attribute__((amdgpu_num_vgpr(MFS_VGPR))) void MFS_KNAME( \ + const uint8_t* __restrict__ a, const float* __restrict__ as, \ + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, \ + const uint8_t* __restrict__ w, const float* __restrict__ ws, \ + const uint8_t* __restrict__ w_odd, const float* __restrict__ w_ws, \ + float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld, int y_ld, \ + int n_expert, int top_k, int grid_rows) \ +{ \ + constexpr int kMBlock = 16; \ + constexpr int kRB = 1; \ + __shared__ __align__(16) uint16_t s_a[kMBlock * kP16]; /* activation f16 (128 per row) */ \ + __shared__ __align__(16) uint16_t s_w[kNBlock * kP16]; /* weight f16 (128 per row) */ \ + __shared__ uint16_t s_tbl[256]; /* the e4m3 -> f16 table */ \ + __shared__ int32_t s_tok[kMBlock]; \ + __shared__ int32_t s_nruns; \ + __shared__ int32_t s_rs[kMBlock], s_re[kMBlock], s_e[kMBlock]; \ + \ + const uint32_t tid = threadIdx.x; \ + const uint32_t lane = tid & (kWave - 1); \ + const uint32_t wv = tid / kWave; \ + const uint32_t r = lane & 15; \ + \ + /* The e4m3 -> f16 table: filled once before any lane reads it. */ \ + r3d_e4m3_f16_init(s_tbl, (int)tid, (int)kThreads); \ + \ + const uint32_t r0 = (uint32_t)blockIdx.y * kMBlock; \ + const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; \ + const uint32_t r1 = (r0 + kMBlock < (uint32_t)T) ? r0 + kMBlock : (uint32_t)T; \ + \ + if (tid < kMBlock) { \ + const uint32_t i = r0 + tid; \ + const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; \ + s_tok[tid] = (f < 0) ? -1 : (f / top_k); \ + } \ + if (tid == 0) { \ + int nruns = 0, i = (int)r0; \ + while (i < (int)r1) { \ + int32_t ee = -1; \ + for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; \ + const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); \ + s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; \ + ++nruns; i = re; \ + } \ + s_nruns = nruns; \ + } \ + group_barrier(); \ + const int nruns = s_nruns; \ + \ + const uint32_t nc = n0 + wv * 16 + r; \ + const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); \ + \ + for (int run = 0; run < nruns; ++run) { \ + const int rs = s_rs[run], re = s_re[run], e = s_e[run]; \ + float acc[kRB][8]; \ + _Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) \ + _Pragma("unroll") \ + for (int g = 0; g < 8; ++g) acc[rb][g] = 0.f; \ + if (e >= 0) { \ + /* Expert e's plane: even e in w / ws, odd e in w_odd / w_ws, at index e/2. */ \ + const int e2 = e >> 1; \ + const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld \ + : w + (size_t)e2 * (size_t)N * w_ld; \ + const float* wsb = (e & 1) ? w_ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128) \ + : ws + (size_t)e2 * (size_t)(N / grid_rows) * ((K + 127) / 128); \ + \ + \ + const int ntile = (K + kKT - 1) / kKT; \ + for (int t = 0; t < ntile; ++t) { \ + const int kt = t * kKT; \ + /* Stage the activation and weight for this 128-k tile, dequantizing E4M3 -> f16 */ \ + /* through the table (the mxfp4a8 pattern: f16 in LDS, WMMA reads f16 directly). */ \ + for (int i = (int)tid; i < kMBlock * kKT; i += kThreads) { \ + const int row = i / kKT, k = i % kKT; \ + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] \ + : s_tok[rs - (int)r0]; \ + const int rr = (src < 0) ? 0 : src; \ + s_a[(size_t)row * kP16 + k] = s_tbl[a[(size_t)rr * a_ld + kt + k]]; \ + } \ + for (int i = (int)tid; i < kNBlock * kKT; i += kThreads) { \ + const int col = i / kKT, k = i % kKT; \ + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); \ + s_w[(size_t)col * kP16 + k] = s_tbl[wbase[(size_t)nn * w_ld + kt + k]]; \ + } \ + group_barrier(); \ + /* The activation scale for this tile (per row) and the weight scale (per grid_rows cols). */ \ + const float wscale = wsb[(size_t)(n_real / grid_rows) * ((K + 127) / 128) + t]; \ + /* Eight 16-wide f16 WMMA steps; f16 values read directly from LDS. The fragment */ \ + /* elements are f16 BIT PATTERNS, so the LDS halfs must be bit-cast into the */ \ + /* _Float16 vector: any assignment from a uint16_t source into a _Float16 (a plain */ \ + /* `fa[j] = ap[k+j]`, or a union whose half members are uint16_t) is a VALUE */ \ + /* conversion (code 0x4300, i.e. f16 3.5, would become the number 17152.0) and */ \ + /* corrupts every product. The union's half members must themselves be _Float16. */ \ + _Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) { \ + typename R3dMoeAccF16::type blk; \ + r3d_moe_acc_f16_init(blk); \ + const uint16_t* ap = s_a + (size_t)(rb * 16 + r) * kP16; \ + const uint16_t* wp = s_w + (size_t)(wv * 16 + r) * kP16; \ + _Pragma("unroll") \ + for (int k = 0; k < kKT; k += 16) { \ + v16half fa, fb; \ + const uint32_t* ap32 = (const uint32_t*)(ap + k); \ + const uint32_t* wp32 = (const uint32_t*)(wp + k); \ + _Pragma("unroll") \ + for (int j = 0; j < 8; ++j) { \ + union { uint32_t u; _Float16 h[2]; } ca, cb; \ + ca.u = ap32[j]; cb.u = wp32[j]; \ + fa[2 * j] = ca.h[0]; fa[2 * j + 1] = ca.h[1]; \ + fb[2 * j] = cb.h[0]; fb[2 * j + 1] = cb.h[1]; \ + } \ + blk = r3d_moe_wmma_f16(fa, fb, blk); \ + } \ + /* Fold: raw * (activation scale * weight scale). Each output g is for a different */ \ + /* row (rb*16 + g*2 + (lane>>4)), so each needs its own source token and scale. */ \ + _Pragma("unroll") \ + for (int g = 0; g < 8; ++g) { \ + const int row = rb * 16 + g * 2 + (int)(lane >> 4); \ + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) \ + ? s_tok[row] : s_tok[rs - (int)r0]; \ + const float ascale = (src < 0) ? 0.f : as[(size_t)src * ((K + 127) / 128) + t] * wscale; \ + acc[rb][g] += r3d_moe_acc_f16_read(blk, g) * ascale; \ + } \ + } \ + group_barrier(); \ + } \ + } \ + /* Store only the run's rows (f32: the moe_gemm_q contract's output). */ \ + _Pragma("unroll") \ + for (int rb = 0; rb < kRB; ++rb) \ + _Pragma("unroll") \ + for (int g = 0; g < 8; ++g) { \ + const int m = (int)r0 + rb * 16 + g * 2 + (int)(lane >> 4); \ + if (m < re && m >= rs) \ + y[(size_t)m * y_ld + nc] = acc[rb][g]; \ + } \ + } \ +} +#define MFS_KNAME moe_fp8_f32scale_kernel16 +#define MFS_VGPR 512 +#define MFS_ACC 0 +R3D_MFS_BODY +#undef MFS_KNAME MFS_VGPR MFS_ACC +#define MFS_KNAME moe_fp8_f32scale_kernel16_a1 +#define MFS_VGPR 512 +#define MFS_ACC 1 +R3D_MFS_BODY +#undef MFS_KNAME MFS_VGPR MFS_ACC +#define MFS_KNAME moe_fp8_f32scale_kernel16_c128 +#define MFS_VGPR 128 +#define MFS_ACC 0 +R3D_MFS_BODY +#undef MFS_KNAME MFS_VGPR MFS_ACC +#define MFS_KNAME moe_fp8_f32scale_kernel16_c128_a1 +#define MFS_VGPR 128 +#define MFS_ACC 1 +R3D_MFS_BODY +#undef MFS_KNAME MFS_VGPR MFS_ACC +#undef R3D_MFS_BODY + +} // namespace + +static int r3d_moe_gemm_fp8_f32scale_v(long a, long as, long sorted, long off, long w, long ws, + long w_odd, long w_ws, long y, + int T, int N, int K, int a_ld, int w_ld, int y_ld, + int n_expert, int top_k, int grid_rows, int vgpr, int acc, + long stream) +{ + if (!a || !as || !sorted || !off || !w || !ws || !w_odd || !w_ws || !y) return -1; + if (T < 1 || N < 1 || K < 1 || grid_rows < 1) return -2; + if (!a_ld) a_ld = K; + if (!w_ld) w_ld = K; + if (!y_ld) y_ld = N; + if (K % kKT) return -2; + const int ntiles = (N + kNBlock - 1) / kNBlock; + const int mrowblk = (T + 16 - 1) / 16; + const dim3 grid(ntiles, mrowblk), block(kThreads); + if (vgpr == 128) { + if (acc) + R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128_a1, grid, block, (hipStream_t)stream, + (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, + (const int32_t*)off, (const uint8_t*)w, (const float*)ws, + (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, + T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); + else + R3D_KLAUNCH(moe_fp8_f32scale_kernel16_c128, grid, block, (hipStream_t)stream, + (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, + (const int32_t*)off, (const uint8_t*)w, (const float*)ws, + (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, + T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); + } + else { + if (acc) + R3D_KLAUNCH(moe_fp8_f32scale_kernel16_a1, grid, block, (hipStream_t)stream, + (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, + (const int32_t*)off, (const uint8_t*)w, (const float*)ws, + (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, + T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); + else + R3D_KLAUNCH(moe_fp8_f32scale_kernel16, grid, block, (hipStream_t)stream, + (const uint8_t*)a, (const float*)as, (const int32_t*)sorted, + (const int32_t*)off, (const uint8_t*)w, (const float*)ws, + (const uint8_t*)w_odd, (const float*)w_ws, (float*)y, + T, N, K, a_ld, w_ld, y_ld, n_expert, top_k, grid_rows); + } + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +/* The direct launcher: the tune's default budget (128, the 8-wave cap). */ +extern "C" int r3d_moe_gemm_fp8_f32scale(long a, long as, long sorted, long off, long w, long ws, + long w_odd, long w_ws, long y, + int T, int N, int K, int a_ld, int w_ld, int y_ld, + int n_expert, int top_k, int grid_rows, long stream) +{ + return r3d_moe_gemm_fp8_f32scale_v(a, as, sorted, off, w, ws, w_odd, w_ws, y, T, N, K, a_ld, + w_ld, y_ld, n_expert, top_k, grid_rows, 128, 0, stream); +} + +/* The RadArgs dispatch: the row's entry. The tensors are a, a_scale, sorted_tok, expert_offset, + * w, w_scale, w_odd, w_odd_scale, y (the moe_gemm_q contract: even experts in w / w_scale, odd in + * w_odd / w_odd_scale, at index e/2; y is f32). The params are n_expert, top_k, grid_rows. */ +extern "C" int r3d_moe_gemm_fp8_f32scale_run(const RadArgs* a, RadStream s, int vgpr, int acc) +{ + if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = &a->t[0], *ast = &a->t[1], *st = &a->t[2], *ot = &a->t[3]; + const RadTensor* wt = &a->t[4], *wst = &a->t[5], *wot = &a->t[6], *wost = &a->t[7]; + const RadTensor* yt = &a->t[8]; + if (!r3d_p(at) || !r3d_p(ast) || !r3d_p(st) || !r3d_p(ot) || + !r3d_p(wt) || !r3d_p(wst) || !r3d_p(wot) || !r3d_p(wost) || !r3d_wp(yt)) + return R3D_NO(RAD_E_INVAL); + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long T = (st->rank >= 1) ? st->shape[0] : 0; + const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; // the plane is [n_expert/2, N, K] + const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); + const int top_k = (int)r3d_geti_or(a, "top_k", 1); + const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (per col) or 128 (per 128) + if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128 || n_expert <= 0 || top_k <= 0) + return R3D_NO(RAD_E_SHAPE); + const int a_ld = (int)at->stride[0]; + const int w_ld = (int)wt->shape[2]; + const int y_ld = (int)yt->stride[0]; + return r3d_moe_gemm_fp8_f32scale_v((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(ast), + (long)(uintptr_t)r3d_p(st), (long)(uintptr_t)r3d_p(ot), + (long)(uintptr_t)r3d_p(wt), (long)(uintptr_t)r3d_p(wst), + (long)(uintptr_t)r3d_p(wot), (long)(uintptr_t)r3d_p(wost), + (long)(uintptr_t)r3d_wp(yt), (int)T, (int)N, (int)K, a_ld, + w_ld, y_ld, n_expert, top_k, grid_rows, vgpr, acc, + (long)(uintptr_t)s); +} + +extern "C" int r3d_rad_moe_gemm_fp8_f32scale(const RadArgs* a, RadStream s) +{ + R3dMoeCfg c; r3d_cfg_moe(a, &c); // the checker entry point's budget (128 default) + return r3d_moe_gemm_fp8_f32scale_run(a, s, c.vgpr, c.acc); +} diff --git a/libr3d/r3d_moe_gemm_mxfp4a8.hip b/libr3d/r3d_moe_gemm_mxfp4a8.hip new file mode 100644 index 00000000..7ed37c82 --- /dev/null +++ b/libr3d/r3d_moe_gemm_mxfp4a8.hip @@ -0,0 +1,224 @@ +/* r3d_moe_gemm_mxfp4a8.hip -- moe_gemm_mxfp4a8: the grouped GEMM with canonical MXFP4 experts. + * + * y[i, n] = sum_k a[tok(i), k] * w_e[n, k], e = the expert of sorted row i + * + * The activation is E4M3 with one f32 scale per (row, 128 of K). The weight is canonical MXFP4: + * packed E2M1 codes (two a byte) with one E8M0 scale per 32 of K. E2M1's eight magnitudes + * {0, .5, 1, 1.5, 2, 3, 4, 6} are exactly representable in E4M3, so each weight code is decoded to + * an E4M3 byte (the v_perm_b32 unpack, the exact d=0 row) and both operands run on the f16 + * wave-matrix (f32 accumulate). Each 32-wide E8M0 scale folds into the f32 accumulator per group. + * + * One block per 16 expert-sorted rows, walking the runs (contiguous rows per expert) in its tile, + * the same run-walk / gather structure as moe_gemm_q. The even experts are `w` / `w_scale`, the + * odd `w_odd` / `w_odd_scale`, at index e/2. K is a multiple of 128; N a multiple of 16. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" +#include "r3d_fp8_dequant.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kNBlock = 128; // a block is 16 rows x 128 cols: eight waves x 16 cols +constexpr int kGroup = 128; // a k tile: four 32-wide E8M0 groups +constexpr int kAPitch = 33; // dwords a staged activation row: 32 (128 E4M3) + 1 +constexpr int kWPitch = 17; // dwords a staged weight row: 16 (128 E2M1 = 64 B) + 1 + +/* Eight packed E2M1 codes (four bytes, element 2j in the low nibble of byte j) -> eight E4M3 bytes + * in k order (word 0 = elements 0..3, word 1 = 4..7). The exact d=0 row of the folded-magnitude + * table (R4D_MXFP4_MAG0); E2M1's magnitudes are a subset of E4M3, so this is lossless. */ +__device__ __forceinline__ void e2m1x8_to_e4m3x8(uint32_t wv, uint32_t* lo, uint32_t* hi) +{ + const uint32_t t0 = 0x3c383000u, t1 = 0x4c484440u; + const uint32_t ev = wv & 0x0F0F0F0Fu; // low nibble of each byte -> even elements + const uint32_t od = (wv >> 4) & 0x0F0F0F0Fu; // high nibble -> odd elements + const uint32_t be = __builtin_amdgcn_perm(t1, t0, ev & 0x07070707u) | ((ev & 0x08080808u) << 4); + const uint32_t bo = __builtin_amdgcn_perm(t1, t0, od & 0x07070707u) | ((od & 0x08080808u) << 4); + *lo = __builtin_amdgcn_perm(bo, be, 0x05010400u); + *hi = __builtin_amdgcn_perm(bo, be, 0x07030602u); +} + +/* An E8M0 byte to f32: the byte is the f32 exponent field (bias 127). Code 255 is NaN, code 0 is + * 2^-127 (a representable subnormal). */ +__device__ __forceinline__ float e8m0_to_f32(uint32_t e) +{ + return __uint_as_float(e == 255 ? 0x7fc00000u : e ? (e << 23) : 0x00200000u); +} + +__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); } + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_mx_kernel( + const uint8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + const uint8_t* __restrict__ w, const uint8_t* __restrict__ w_scale, + const uint8_t* __restrict__ w_odd, const uint8_t* __restrict__ w_odd_scale, + uint16_t* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld, + int n_expert, int top_k, int grid_rows) +{ + __shared__ __align__(16) uint32_t s_a[16 * kAPitch]; + __shared__ __align__(16) uint32_t s_w[kNBlock * kWPitch]; + __shared__ __align__(16) uint16_t s_tbl[R3D_E4M3_TBL]; + __shared__ int32_t s_tok[16]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[16], s_re[16], s_e[16]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16 + const uint32_t r = lane & 15; + + r3d_e4m3_f16_init(s_tbl, (int)tid, kThreads); // the E4M3 -> f16 table + + const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows + const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; + const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T; + + // The block's rows' source tokens (the gather). -1 marks a dropped slot. + if (tid < 16) { + const uint32_t i = r0 + tid; + const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; + s_tok[tid] = (f < 0) ? -1 : (f / top_k); + } + // The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. + if (tid == 0) { + int nruns = 0, i = (int)r0; + while (i < (int)r1) { + int32_t ee = -1; + for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; + const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); + s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; + ++nruns; i = re; + } + s_nruns = nruns; + } + group_barrier(); + const int nruns = s_nruns; + + const uint32_t nc = n0 + wv * 16 + r; // this wave's output column + const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); + + // One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the + // run does not own are padding (reading the run's first row) and their output is dropped. + for (int run = 0; run < nruns; ++run) { + const int rs = s_rs[run], re = s_re[run], e = s_e[run]; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + if (e >= 0) { + const int e2 = e >> 1; + const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b + : w + (size_t)e2 * (size_t)N * w_ld_b; + const uint8_t* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32) + : w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / 32); + + for (int b = 0; b < K / kGroup; ++b) { + const int kt = b * kGroup; + + // Stage 16 rows x 128 E4M3 of the gathered activation; padding rows read the run's first. + for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) { + const int row = i / (kGroup / 4), d = i % (kGroup / 4); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const int rr = (src < 0) ? 0 : src; + s_a[(size_t)row * kAPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d); + } + // Stage 128 cols x 128 E2M1 of the expert's weight (64 bytes = 16 dwords a row). + for (int i = (int)tid; i < kNBlock * (kGroup / 8); i += kThreads) { + const int col = i / (kGroup / 8), d = i % (kGroup / 8); + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); + s_w[(size_t)col * kWPitch + d] = + *(const uint32_t*)(wbase + (size_t)nn * w_ld_b + kt / 2 + 4 * d); + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kAPitch; + const uint32_t* wp = s_w + (size_t)(wv * 16 + r) * kWPitch; // this wave's 16 cols + // The weight scale for this lane's column, per 32-of-K group. + const int wn = (int)(n_real / grid_rows); +#pragma unroll + for (int g32 = 0; g32 < 4; ++g32) { + v8float blk = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; +#pragma unroll + for (int k = g32 * 32; k < g32 * 32 + 32; k += 16) { + uint32_t af[8], bf[8]; + // 16 E4M3 (four dwords) -> 16 f16 (eight dwords). + r3d_e4m3x8_decode<0>(s_tbl, uint2{ ap[k / 4], ap[k / 4 + 1] }, af); + r3d_e4m3x8_decode<0>(s_tbl, uint2{ ap[k / 4 + 2], ap[k / 4 + 3] }, af + 4); + // 16 E2M1 (two dwords) -> 16 E4M3 (four dwords) -> 16 f16 (eight dwords). + uint32_t e4lo, e4hi, e4lo2, e4hi2; + e2m1x8_to_e4m3x8(wp[k / 8], &e4lo, &e4hi); + e2m1x8_to_e4m3x8(wp[k / 8 + 1], &e4lo2, &e4hi2); + r3d_e4m3x8_decode<0>(s_tbl, uint2{ e4lo, e4hi }, bf); + r3d_e4m3x8_decode<0>(s_tbl, uint2{ e4lo2, e4hi2 }, bf + 4); + v16half fa, fb; +#pragma unroll + for (int q = 0; q < 8; ++q) { fa[2 * q] = h16(af[q] & 0xffffu); fa[2 * q + 1] = h16(af[q] >> 16); } +#pragma unroll + for (int q = 0; q < 8; ++q) { fb[2 * q] = h16(bf[q] & 0xffffu); fb[2 * q + 1] = h16(bf[q] >> 16); } + blk = wmma_f16(fa, fb, blk); + } + group_barrier(); + // Fold the g32-group's scales: the weight E8M0 (per 32) and the activation f32 (per 128). + const float sw = e8m0_to_f32((uint32_t)wsb[(size_t)wn * (K / 32) + b * 4 + g32]); +#pragma unroll + for (int g = 0; g < 8; ++g) { + const int row = (int)(g * 2 + (lane >> 4)); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b]; + acc[g] += blk[g] * sa * sw; + } + } + } + + } + // Store only the run's rows, as bf16. +#pragma unroll + for (int g = 0; g < 8; ++g) { + const int row = (int)(g * 2 + (lane >> 4)); + const int m = (int)(r0 + row); + if (rs <= m && m < re && nc < (uint32_t)N) + y[(size_t)m * y_ld + nc] = f32_to_bf16(acc[g]); + } + } +} + +} // namespace + +extern "C" { + +int r3d_rad_moe_gemm_mxfp4a8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2), + *ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5), + *wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8); + if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) || + !r3d_wp(yt)) + return R3D_NO(RAD_E_INVAL); + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long T = (st->rank >= 1) ? st->shape[0] : 0; + const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; + if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps + const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); + const int top_k = (int)r3d_geti_or(a, "top_k", 1); + const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 128); + const int a_ld = (int)at->stride[0]; + const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes (K/2 for E2M1) + const int y_ld = (int)yt->stride[0]; + + dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads); + moe_mx_kernel<<>>( + (const uint8_t*)r3d_p(at), (const float*)r3d_p(asc), (const int32_t*)r3d_p(st), + (const int32_t*)r3d_p(ot), (const uint8_t*)r3d_p(wt), (const uint8_t*)r3d_p(wsc), + (const uint8_t*)r3d_p(wot), (const uint8_t*)r3d_p(wosc), (uint16_t*)r3d_wp(yt), + (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, n_expert, top_k, grid_rows); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_q.hip b/libr3d/r3d_moe_gemm_q.hip new file mode 100644 index 00000000..f34bf1f9 --- /dev/null +++ b/libr3d/r3d_moe_gemm_q.hip @@ -0,0 +1,227 @@ +/* r3d_moe_gemm_q.hip -- moe_gemm_q (Phase 1: the GEMM core, dense rows, no gather). + * + * y[M,N] = a[M,K] @ w[N,K]^T, both operands E4M3, with a per-(row, g-of-K) scale fold. + * + * `a` and `w` are E4M3 (fp8) with one f32 scale per (row, g of K). RDNA3 has no fp8 matrix unit, so + * each operand is staged to LDS compactly (8-bit) and upcast to f16 in registers as the wave-matrix + * fragments load -- the FeatherOps `fp8e4m3x4_to_half2x2` bit trick (a V_PERM_B32 + shift-add, no + * table, no extra pass), then the f16 wave-matrix (`v_wmma_f32_16x16x16_f16`, f32 accumulate). Each + * g-wide block of K is accumulated raw, then folded by scale_a[m][b] * scale_w[n][b]. + * + * STATUS: WIP. Phases 1-2 are verified against a CPU reference (maxrel ~1e-4, the f16 rounding + * floor): + * * Phase 1: the GEMM core (E4M3 x E4M3 -> f16 wave-matrix, the per-(row, 128-of-K) scale fold). + * * Phase 2: the gather (row i reads a[sorted[i]/top_k]), the per-expert weight tables, and the + * run structure (the block walks the runs in its 16 rows, so a block spanning several experts + * is correct). + * + * * Phase 3: the even/odd expert split (expert e's weight is in `w` for even e, `w_odd` for odd + * e, at index e/2) and the dtype-selected scale grid (`grid_rows` = 1 for w4a8's per-row scale, + * 128 for fp8a8's per-128x128 tile). + * + * Verified against a CPU reference for runs of 1, 2, 4 and 16 rows, the even/odd split, and both + * scale grids (maxrel ~1e-4, the f16 rounding floor). A row: `moe_gemm_q_e4m3` in r3d_rows.cpp, a + * selftest case in r3d_selftest.cpp. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include "r3d_fp8_dequant.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kNBlock = 128; // a block is 16 rows x 128 cols: eight waves x 16 cols +constexpr int kGroup = 128; // a scale block: one k tile, eight wmma steps +constexpr int kPitch = 33; // dwords a staged row: 33 mod 32 = 1, bank-free + + +__device__ __forceinline__ _Float16 h16(uint32_t w) { return __builtin_bit_cast(_Float16, (uint16_t)w); } + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_q_kernel( + const uint8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + const uint8_t* __restrict__ w, const float* __restrict__ w_scale, + const uint8_t* __restrict__ w_odd, const float* __restrict__ w_odd_scale, + float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld, + int n_expert, int top_k, int grid_rows) +{ + __shared__ __align__(16) uint32_t s_a[16 * kPitch]; + __shared__ __align__(16) uint32_t s_w[kNBlock * kPitch]; + __shared__ __align__(16) uint16_t s_tbl[R3D_E4M3_TBL]; + __shared__ int32_t s_tok[16]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[16], s_re[16], s_e[16]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16 + const uint32_t r = lane & 15; + + if (!ALU) r3d_e4m3_f16_init(s_tbl, (int)tid, kThreads); // the E4M3 -> f16 table (ALU=0) + + const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows + const uint32_t n0 = (uint32_t)blockIdx.x * kNBlock; + const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T; + + // The block's rows' source tokens (the gather). -1 marks a dropped slot. + if (tid < 16) { + const uint32_t i = r0 + tid; + const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; + s_tok[tid] = (f < 0) ? -1 : (f / top_k); + } + // The runs in [r0, r1): each a contiguous set of rows for one expert. The block walks them. + if (tid == 0) { + int nruns = 0, i = (int)r0; + while (i < (int)r1) { + int32_t ee = -1; + for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; + const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); + s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; + ++nruns; i = re; + } + s_nruns = nruns; + } + group_barrier(); + const int nruns = s_nruns; + + const uint32_t nc = n0 + wv * 16 + r; // this wave's output column + const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); + + // One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the + // run does not own are padding (reading the run's first row) and their output is dropped. Expert + // e's weight is in `w` (even e) or `w_odd` (odd e) at index e/2. + for (int run = 0; run < nruns; ++run) { + const int rs = s_rs[run], re = s_re[run], e = s_e[run]; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + if (e >= 0) { + const int e2 = e >> 1; + const uint8_t* wbase = (e & 1) ? w_odd + (size_t)e2 * (size_t)N * w_ld_b + : w + (size_t)e2 * (size_t)N * w_ld_b; + const float* wsb = (e & 1) ? w_odd_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup) + : w_scale + (size_t)e2 * (size_t)(N / grid_rows) * (K / kGroup); + + for (int b = 0; b < K / kGroup; ++b) { + const int kt = b * kGroup; + + // Stage 16 rows x 128 E4M3 of the gathered activation; padding rows read the run's first. + for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) { + const int row = i / (kGroup / 4), d = i % (kGroup / 4); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const int rr = (src < 0) ? 0 : src; + s_a[(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d); + } + // Stage 128 cols x 128 E4M3 of the expert's weight (the block's columns). + for (int i = (int)tid; i < kNBlock * (kGroup / 4); i += kThreads) { + const int col = i / (kGroup / 4), d = i % (kGroup / 4); + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); + s_w[(size_t)col * kPitch + d] = + *(const uint32_t*)(wbase + (size_t)nn * w_ld_b + kt + 4 * d); + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kPitch; + const uint32_t* wp = s_w + (size_t)(wv * 16 + r) * kPitch; // this wave's 16 cols + v8float blk = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; +#pragma unroll + for (int k = 0; k < kGroup; k += 16) { + uint32_t ain[4], af[8], bin[4], bf[8]; +#pragma unroll + for (int g = 0; g < 4; ++g) ain[g] = ap[k / 4 + g]; + r3d_e4m3x16_decode(s_tbl, ain, af); +#pragma unroll + for (int g = 0; g < 4; ++g) bin[g] = wp[k / 4 + g]; + r3d_e4m3x16_decode(s_tbl, bin, bf); + v16half fa, fb; +#pragma unroll + for (int g = 0; g < 8; ++g) { fa[2 * g] = h16(af[g] & 0xffffu); fa[2 * g + 1] = h16(af[g] >> 16); } +#pragma unroll + for (int g = 0; g < 8; ++g) { fb[2 * g] = h16(bf[g] & 0xffffu); fb[2 * g + 1] = h16(bf[g] >> 16); } + blk = wmma_f16(fa, fb, blk); + } + group_barrier(); + + // Fold the g-block's scales. acc[g] is at row g*2 + lane/16 (varies with g), column r. + // The weight scale is per (grid_rows columns, 128 of K). + const float sw = wsb[(size_t)(n_real / grid_rows) * (K / kGroup) + b]; +#pragma unroll + for (int g = 0; g < 8; ++g) { + const int row = (int)(g * 2 + (lane >> 4)); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b]; + acc[g] += blk[g] * sa * sw; + } + } + + } + // Store only the run's rows. +#pragma unroll + for (int g = 0; g < 8; ++g) { + const int row = (int)(g * 2 + (lane >> 4)); + const int m = (int)(r0 + row); + if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = acc[g]; + } + } +} + +} // namespace + +extern "C" { + +static int r3d_moe_gemm_q_dispatch(const RadArgs* a, RadStream s, int alu) +{ + if (!a || a->n_t < 9) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2), + *ot = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5), + *wot = r3d_opt(a, 6), *wosc = r3d_opt(a, 7), *yt = r3d_opt(a, 8); + if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(ot) || !r3d_p(wt) || !r3d_p(wsc) || + !r3d_wp(yt)) + return R3D_NO(RAD_E_INVAL); + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long T = (st->rank >= 1) ? st->shape[0] : 0; + const long long N = (wt->rank >= 3) ? wt->shape[1] : 0; + if (M <= 0 || T <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); // N tail clamps + const int n_expert = (int)r3d_geti_or(a, "n_expert", 1); + const int top_k = (int)r3d_geti_or(a, "top_k", 1); + const int grid_rows = (int)r3d_geti_or(a, "grid_rows", 1); // 1 (w4a8) or 128 (fp8a8) + const int a_ld = (int)at->stride[0]; + const int w_ld_b = (int)wt->shape[2]; // the weight's K in bytes + const int y_ld = (int)yt->stride[0]; + + dim3 grid((unsigned)((N + kNBlock - 1) / kNBlock), (unsigned)((T + 15) / 16)), blk(kThreads); + const uint8_t* pa = (const uint8_t*)r3d_p(at); + const float* psa = (const float*)r3d_p(asc); + const int32_t* ps = (const int32_t*)r3d_p(st); + const int32_t* po = (const int32_t*)r3d_p(ot); + const uint8_t* pw = (const uint8_t*)r3d_p(wt); + const float* pws = (const float*)r3d_p(wsc); + const uint8_t* pwo = (const uint8_t*)r3d_p(wot); + const float* pwos = (const float*)r3d_p(wosc); + float* py = (float*)r3d_wp(yt); + if (alu) + moe_q_kernel<1><<>>(pa, psa, ps, po, pw, pws, pwo, pwos, py, + (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, + n_expert, top_k, grid_rows); + else + moe_q_kernel<0><<>>(pa, psa, ps, po, pw, pws, pwo, pwos, py, + (int)T, (int)N, (int)K, a_ld, w_ld_b, y_ld, + n_expert, top_k, grid_rows); + return (int)hipGetLastError(); +} + +/* The two rows share the dispatch: the table decode (ALU=0) and the ALU decode (ALU=1). The tune + * picks the faster per geometry. */ +extern "C" int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s) +{ return r3d_moe_gemm_q_dispatch(a, s, 0); } +extern "C" int r3d_rad_moe_gemm_q_alu(const RadArgs* a, RadStream s) +{ return r3d_moe_gemm_q_dispatch(a, s, 1); } + +} // extern "C" diff --git a/libr3d/r3d_moe_gemm_w4a8.hip b/libr3d/r3d_moe_gemm_w4a8.hip new file mode 100644 index 00000000..26cd2706 --- /dev/null +++ b/libr3d/r3d_moe_gemm_w4a8.hip @@ -0,0 +1,193 @@ +/* r3d_moe_gemm_w4a8.hip -- moe_gemm_w4a8 (Phase 2: the GEMM core + the gather + per-expert weights). + * + * y[T,N] = a[gather(row), :] @ w[e(row), :]^T, with a per-(row, 128-of-K) scale fold. + * + * The routed rows are in SORTED order (one row per (token, expert slot)); row i reads its + * activation from `a[sorted[i] / top_k]` and its weight from expert e(i)'s table, where e(i) is the + * expert owning sorted row i (the one whose [off, off') span contains i). `a` is int8 with one f32 + * scale per (row, 128 of K); each expert's weight is a 4-bit two's-complement nibble (-8..7) packed + * two per byte, with one f32 scale per (row, 128 of K). RDNA3's native int8 wave-matrix + * (`v_wmma_i32_16x16x16_iu8`, exact i32 accumulate) takes the int4 weight widened to int8, so no f16 + * rounding. Each 128-wide block of K is accumulated raw in i32, then folded by + * scale_a[src][b] * scale_w[e][n][b]. + * + * STATUS: WIP. Phases 1-3 are verified bit-exact against a CPU reference (the i32 accumulate is + * exact, so the random cases are exact, not just within tolerance): + * * Phase 1: the GEMM core (int8 x widened-int4, the per-(row, 128-of-K) scale fold). + * * Phase 2: the gather (row i reads a[sorted[i]/top_k]) and the per-expert weight tables. + * * Phase 3: the run structure -- the block walks the runs in its 16 rows, so a block spanning + * several experts (short runs, decode) is correct. Verified for runs of 1, 2, 4 and 16 rows. + * + * The `w4a8` form (a two's-complement nibble, -8..7) is served. Remaining (Phase 4): the other + * weight forms (w4nl64a8h / w4nl32a8h / w5nl64a8h, whose nibbles decode through a magnitude table + * and a per-64/32 E4M3 scale), the prefill run map, and the SK/UW/RS optimisations. Not yet a row: + * no r3d_rows.cpp entry, no selftest. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kGroup = 128; // a scale block: one k tile, eight wmma steps +constexpr int kPitch = 33; // dwords a staged a row: 33 mod 32 = 1, bank-free + + +__device__ __forceinline__ int32_t nib_i8(uint32_t nib) +{ + return (nib & 8u) ? (int32_t)nib - 16 : (int32_t)(nib & 7u); +} + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void moe_w4a8_kernel( + const int8_t* __restrict__ a, const float* __restrict__ a_scale, + const int32_t* __restrict__ sorted, const int32_t* __restrict__ off, + const uint8_t* __restrict__ w, const float* __restrict__ w_scale, + float* __restrict__ y, int T, int N, int K, int a_ld, int w_ld_b, int y_ld, + int n_expert, int top_k) +{ + __shared__ __align__(16) uint32_t s_a[16 * kPitch]; + __shared__ int32_t s_tok[16]; + __shared__ int32_t s_nruns; + __shared__ int32_t s_rs[16], s_re[16], s_e[16]; + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wave = tid / kWave; + const uint32_t r = lane & 15; + + const uint32_t r0 = (uint32_t)blockIdx.y * 16; // the block's sorted rows + const uint32_t ncol = ((uint32_t)blockIdx.x * kWaves + wave) * 16; // the wave's 16 columns + const uint32_t r1 = (r0 + 16 < (uint32_t)T) ? r0 + 16 : (uint32_t)T; + + // The block's rows' source tokens, resolved once (the gather). -1 marks a dropped slot. + if (tid < 16) { + const uint32_t i = r0 + tid; + const int32_t f = (i < (uint32_t)T) ? sorted[i] : -1; + s_tok[tid] = (f < 0) ? -1 : (f / top_k); + } + // The runs in [r0, r1): each is a contiguous set of rows for one expert. The block walks them. + if (tid == 0) { + int nruns = 0, i = (int)r0; + while (i < (int)r1) { + int32_t ee = -1; + for (int32_t x = 0; x < n_expert; ++x) if (off[x] <= i && i < off[x + 1]) ee = x; + const int re = (ee < 0) ? (int)r1 : (int)(off[ee + 1] < r1 ? off[ee + 1] : r1); + s_rs[nruns] = i; s_re[nruns] = re; s_e[nruns] = ee; + ++nruns; i = re; + } + s_nruns = nruns; + } + group_barrier(); + const int nruns = s_nruns; + + const uint32_t nc = ncol + r; + const int n_real = (int)(nc < (uint32_t)N ? nc : (uint32_t)N - 1); + + // One GEMM per run: the run's rows read the gathered activation and expert e's weight. Rows the + // run does not own are padding (they read the run's first row) and their output is dropped. + for (int run = 0; run < nruns; ++run) { + const int rs = s_rs[run], re = s_re[run], e = s_e[run]; + v8float acc = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + if (e >= 0) { + const uint8_t* wrow = w + (size_t)e * (size_t)N * w_ld_b + (size_t)n_real * w_ld_b; + const float* wsb = w_scale + (size_t)e * (size_t)N * (K / kGroup); + + for (int b = 0; b < K / kGroup; ++b) { + const int kt = b * kGroup; + + // Stage 16 rows x 128 i8 of the gathered activation; padding rows read the run's first. + for (int i = (int)tid; i < 16 * (kGroup / 4); i += kThreads) { + const int row = i / (kGroup / 4), d = i % (kGroup / 4); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const int rr = (src < 0) ? 0 : src; + s_a[(size_t)row * kPitch + d] = *(const uint32_t*)(a + (size_t)rr * a_ld + kt + 4 * d); + } + group_barrier(); + + const uint32_t* ap = s_a + (size_t)r * kPitch; + v8int sub = v8int{ 0, 0, 0, 0, 0, 0, 0, 0 }; +#pragma unroll + for (int k = 0; k < kGroup; k += 16) { + const r3d_u32x4 aq = *(const r3d_u32x4*)(ap + k / 4); + const uint2 wp = *(const uint2*)(wrow + (kt + k) / 2); // 8 bytes = 16 nibbles + int32_t v[16]; +#pragma unroll + for (int j = 0; j < 16; ++j) { + const int byt = j / 2; + const bool high = (j & 1); + const uint32_t byte = (byt < 4) ? ((wp.x >> (8 * byt)) & 0xFFu) + : ((wp.y >> (8 * (byt - 4))) & 0xFFu); + v[j] = nib_i8(high ? (byte >> 4) : (byte & 0xFu)); + } + v4int bf{ (int)((uint32_t)(v[0] & 0xFF) | (uint32_t)(v[1] & 0xFF) << 8 | + (uint32_t)(v[2] & 0xFF) << 16 | (uint32_t)(v[3] & 0xFF) << 24), + (int)((uint32_t)(v[4] & 0xFF) | (uint32_t)(v[5] & 0xFF) << 8 | + (uint32_t)(v[6] & 0xFF) << 16 | (uint32_t)(v[7] & 0xFF) << 24), + (int)((uint32_t)(v[8] & 0xFF) | (uint32_t)(v[9] & 0xFF) << 8 | + (uint32_t)(v[10] & 0xFF) << 16 | (uint32_t)(v[11] & 0xFF) << 24), + (int)((uint32_t)(v[12] & 0xFF) | (uint32_t)(v[13] & 0xFF) << 8 | + (uint32_t)(v[14] & 0xFF) << 16 | (uint32_t)(v[15] & 0xFF) << 24) }; + sub = wmma_i8(v4int{ (int)aq.x, (int)aq.y, (int)aq.z, (int)aq.w }, bf, sub); + } + + // Fold the 128-block's scales: scale_a[src][b] * scale_w[e][n][b]. + const float sw = wsb[(size_t)n_real * (K / kGroup) + b]; +#pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int row = (int)(g2 * 2 + (lane >> 4)); + const int src = (rs <= (int)(r0 + row) && (int)(r0 + row) < re) ? s_tok[row] + : s_tok[rs - (int)r0]; + const float sa = a_scale[(size_t)(src < 0 ? 0 : src) * (K / kGroup) + b]; + acc[g2] += (float)sub[g2] * sa * sw; + } + group_barrier(); + } + + } + // Store only the run's rows. +#pragma unroll + for (int g2 = 0; g2 < 8; ++g2) { + const int row = (int)(g2 * 2 + (lane >> 4)); + const int m = (int)(r0 + row); + if (rs <= m && m < re && nc < (uint32_t)N) y[(size_t)m * y_ld + nc] = acc[g2]; + } + } +} + +} // namespace + +extern "C" { + +int r3d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 7) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = r3d_opt(a, 0), *asc = r3d_opt(a, 1), *st = r3d_opt(a, 2), + *oft = r3d_opt(a, 3), *wt = r3d_opt(a, 4), *wsc = r3d_opt(a, 5), + *yt = r3d_opt(a, 6); + if (!r3d_p(at) || !r3d_p(asc) || !r3d_p(st) || !r3d_p(oft) || !r3d_p(wt) || !r3d_p(wsc) || + !r3d_wp(yt)) + return R3D_NO(RAD_E_INVAL); + const long long ne = r3d_geti_or(a, "n_expert", 0), tk = r3d_geti_or(a, "top_k", 0); + long long M = 0, K = 0, T = 0, N = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + if (r3d_rows_of(yt, &T, &N) != 0) return R3D_NO(RAD_E_INVAL); + if (ne <= 0 || tk <= 0 || M <= 0 || N <= 0 || K <= 0 || K % 128) return R3D_NO(RAD_E_SHAPE); + const int a_ld = (int)(at->rank >= 2 ? at->shape[1] : at->stride[0]); + const int w_ld_b = (int)(wt->rank >= 3 ? wt->shape[2] : wt->stride[2]); // bytes/row = K/2 + const int y_ld = (int)(yt->rank >= 2 ? yt->shape[1] : yt->stride[0]); + + dim3 grid((unsigned)((N + 127) / 128), (unsigned)((T + 15) / 16)), blk(kThreads); + R3D_KLAUNCH(moe_w4a8_kernel, grid, blk, (hipStream_t)s, (const int8_t*)r3d_p(at), + (const float*)r3d_p(asc), (const int32_t*)r3d_p(st), (const int32_t*)r3d_p(oft), + (const uint8_t*)r3d_p(wt), (const float*)r3d_p(wsc), (float*)r3d_wp(yt), (int)T, + (int)N, (int)K, a_ld, w_ld_b, y_ld, (int)ne, (int)tk); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_moe_router_topk_bf16.hip b/libr3d/r3d_moe_router_topk_bf16.hip new file mode 100644 index 00000000..b1a9a9e0 --- /dev/null +++ b/libr3d/r3d_moe_router_topk_bf16.hip @@ -0,0 +1,363 @@ +/* r3d_moe_router_topk_bf16.hip -- router_topk: softmax over all n_expert logits, the top_k by + * value, and -- if `norm` -- the kept weights renormalised to sum to one. + * + * One wave per row (one block per row); the selection is top_k passes of a wave minimum, not a + * sort. That matches the reference exactly (largest remaining value, ties to the lower id); a sort + * with another tie rule would be a different router on tied rows, which are not rare. Selection + * runs on the logits: softmax is monotone, so the order is the same and the comparison exact. + * + * gfx1102: a wave reduction (the max, the sum, the per-round min) in a loop body miscompiles for + * a non-first wave -- wave 0 is correct, wave 1+ drop out. Two things keep this safe: + * * one wave per block (one block per row): the __syncthreads is a single-wave barrier, so there + * is no cross-wave sync whose ordering the compiler can scramble; + * * a separate LDS slot per top_k round: the loop never reuses a slot, so a read-after-write + * across iterations cannot be folded (the max and the sum use their own slots, rounds 0 and 1). + * Every wave reduction is an LDS pass, not a DPP butterfly (a DPP exchange miscompiles here). + * + * Verified: single-row (equal, distinct, random) and multi-row (M >= 2) all pick the right ids and + * weights. + */ +#include + +#include +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" +#include "r3d_codecs.h" + +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +namespace { + +constexpr int kW = 32; + +/* (order-preserving value, ~id); 0 = absent or NaN. The key's high half is the logit's bits with + * the sign folded (so larger logit -> larger key) and the low half is the complemented id, so a + * tie goes to the lower id. */ +__device__ __forceinline__ uint32_t topk_key(uint16_t raw, uint32_t e, bool ok) { + const bool nan = ((raw & 0x7F80u) == 0x7F80u) && (raw & 0x7Fu); + const uint16_t u = (raw == 0x8000u) ? (uint16_t)0u : raw; // -0.0 folds to +0.0 + const uint16_t k = (u & 0x8000u) ? (uint16_t)~u : (uint16_t)(u | 0x8000u); + return nan ? 0u : (((uint32_t)k << 16) | (~e & 0xFFFFu)); +} +__device__ __forceinline__ uint16_t topk_key_raw(uint32_t key) { + const uint32_t k = key >> 16; + return (uint16_t)((k & 0x8000u) ? (k & 0x7FFFu) : ~k); +} + +/* One row, one wave (the block is a single wave). `wmin` holds 32 slots per round: round 0 the + * max, round 1 the sum, rounds 2..(1+top_k) the per-round minimums. A separate slot per round so + * the loop never reuses one (gfx1102). */ +template +__device__ __forceinline__ void r3d_router_topk_row( + const unsigned short* __restrict__ lg, int32_t* __restrict__ ids, + unsigned short* __restrict__ w, uint32_t m, uint32_t n_expert, uint32_t top_k, + uint32_t lg_ld, int norm, uint32_t lane, __shared__ uint32_t* wmin) +{ + const unsigned short* row = lg + (size_t)m * lg_ld; + + uint16_t raw[MAXOWN]; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) { + const uint32_t e = lane + i * kW; + raw[i] = row[e < n_expert ? e : 0u]; + } + float v[MAXOWN]; + uint32_t key[MAXOWN]; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) { + const uint32_t e = lane + i * kW; + const bool ok = e < n_expert; + v[i] = ok ? bf16_to_f32(raw[i]) : -INFINITY; + key[i] = topk_key(raw[i], e, ok) & (0u - (uint32_t)ok); + } + + float mx = -INFINITY; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) mx = fmaxf(mx, v[i]); + + // Wave max through LDS (round 0). + wmin[lane] = __builtin_bit_cast(uint32_t, mx); + R3D_BARRIER(); +#pragma unroll + for (int i = 0; i < kW; ++i) + mx = fmaxf(mx, __builtin_bit_cast(float, wmin[i])); + + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) sum += __expf(v[i] - mx); + // Wave sum through LDS (round 1). + wmin[kW + lane] = __builtin_bit_cast(uint32_t, sum); + R3D_BARRIER(); + float s = 0.0f; +#pragma unroll + for (int i = 0; i < kW; ++i) s += __builtin_bit_cast(float, wmin[kW + i]); + sum = s; + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + + uint32_t P = 0xFFFFFFFFu, mykey = 0u, nsel = 0; + for (uint32_t r = 0; r < top_k; ++r) { + uint32_t d = 0xFFFFFFFFu; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) { + const uint32_t t = P - key[i]; + d = d < t ? d : t; + } + // Wave minimum through LDS, round (2 + r): a fresh slot each round. + const uint32_t base = (2 + r) * kW; + wmin[base + lane] = d; + R3D_BARRIER(); + uint32_t mn = 0xFFFFFFFFu; +#pragma unroll + for (int i = 0; i < kW; ++i) mn = mn < wmin[base + i] ? mn : wmin[base + i]; + const uint32_t best = P - mn; + if ((best & 0xFFFFu) == 0u) break; + if (lane == r) mykey = best; + P = best - 1u; + ++nsel; + } + const float p = __expf(bf16_to_f32(topk_key_raw(mykey)) - mx) * inv; + const uint16_t pb = f32_to_bf16(p); + float wsum = 0.0f; + for (uint32_t r = 0; r < nsel; ++r) + wsum += __builtin_bit_cast(float, __builtin_amdgcn_readlane(__builtin_bit_cast(int, p), + (int)r)); + if (lane < nsel) { + ids[(size_t)m * top_k + lane] = (int32_t)(~mykey & 0xFFFFu); + w[(size_t)m * top_k + lane] = + (norm && wsum > 0.0f) ? f32_to_bf16(bf16_to_f32(pb) * (1.0f / wsum)) : pb; + } +} + +template +__global__ __launch_bounds__(kW) void r3d_router_topk_kernel( + const unsigned short* __restrict__ lg, int32_t* __restrict__ ids, + unsigned short* __restrict__ w, uint32_t M, uint32_t n_expert, uint32_t top_k, + uint32_t lg_ld, int norm) +{ + __shared__ uint32_t wmin[kW * (2 + kW)]; // a slot per round, top_k <= kW + const uint32_t lane = threadIdx.x; + const uint32_t m = blockIdx.x; // one block per row + r3d_router_topk_row(lg, ids, w, m, n_expert, top_k, lg_ld, norm, lane, wmin); +} + +} // namespace + + + +/* ------------------------------------------------------------------ router_sigmoid_topk + * + * The GLM-style router: scores[e] = sigmoid(logit[e]), the selection runs on + * select[e] = scores[e] + bias[e] (a per-expert correction bias), and the kept weights are the + * scores themselves, scaled by route_scale (and renormalised to sum to one if `norm`). Ties go to + * the lower id, as in router_topk. + * + * The selection key is 64-bit (the 32-bit select's monotone bits, the low 32 the complemented id), + * so a 64-bit LDS slot per round. The scores are staged in LDS so the weight is read back without a + * global reload. */ +template +__device__ __forceinline__ void r3d_router_sigmoid_topk_row( + const unsigned short* __restrict__ lg, const float* __restrict__ bias, + int32_t* __restrict__ ids, unsigned short* __restrict__ w, + uint32_t m, uint32_t n_expert, uint32_t top_k, uint32_t lg_ld, + float scale, int norm, uint32_t lane, + __shared__ uint64_t* wmin, __shared__ float* s_score) +{ + const unsigned short* row = lg + (size_t)m * lg_ld; + + uint64_t key[MAXOWN]; +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) { + const uint32_t e = lane + i * kW; + const bool ok = e < n_expert; + const float lgt = ok ? bf16_to_f32(row[e]) : -INFINITY; + const float sc = 1.0f / (1.0f + __expf(-lgt)); + s_score[lane * MAXOWN + i] = sc; + const float sel = ok ? (sc + bias[e]) : -INFINITY; + const uint32_t bits = __builtin_bit_cast(uint32_t, sel); + const uint32_t u = (bits & 0x80000000u) ? ~bits : (bits | 0x80000000u); + key[i] = (((uint64_t)u) << 32) | (~e & 0xFFFFFFFFull); + } + + uint64_t P = ~0ull, mykey = 0ull, nsel = 0; + for (uint32_t r = 0; r < top_k; ++r) { + uint64_t d = ~0ull; // min over (P - key[i]); P - key is smaller for the larger key +#pragma unroll + for (int i = 0; i < MAXOWN; ++i) { + const uint64_t t = P - key[i]; + d = d < t ? d : t; + } + const uint64_t base = (uint64_t)(2 + r) * kW; + wmin[base + lane] = d; + R3D_BARRIER(); + uint64_t mn = ~0ull; +#pragma unroll + for (int i = 0; i < kW; ++i) mn = mn < wmin[base + i] ? mn : wmin[base + i]; + const uint64_t best = P - mn; + if (best == 0ull) break; + if (lane == r) mykey = best; + P = best - 1ull; + ++nsel; + } + + const uint32_t id = (uint32_t)(~mykey & 0xFFFFFFFFull); + const float sc = s_score[(id % kW) * MAXOWN + (id / kW)]; + // Sum the kept scores over lanes 0..nsel-1 (a wave reduce). + wmin[lane] = (uint64_t)__builtin_bit_cast(uint32_t, sc); + R3D_BARRIER(); + float sum = 0.0f; +#pragma unroll + for (int i = 0; i < kW; ++i) { + const uint32_t b = (uint32_t)wmin[i]; + if (i < nsel) sum += __builtin_bit_cast(float, b); + } + if (lane < nsel) { + const float weight = sc * (norm ? (scale / (sum + 1e-20f)) : scale); + ids[(size_t)m * top_k + lane] = (int32_t)id; + w[(size_t)m * top_k + lane] = f32_to_bf16(weight); + } +} + +template +__global__ __launch_bounds__(kW) void r3d_router_sigmoid_topk_kernel( + const unsigned short* __restrict__ lg, const float* __restrict__ bias, + int32_t* __restrict__ ids, unsigned short* __restrict__ w, + uint32_t M, uint32_t n_expert, uint32_t top_k, uint32_t lg_ld, float scale, int norm) +{ + __shared__ uint64_t wmin[kW * (2 + kW)]; + __shared__ float s_score[kW * MAXOWN]; + const uint32_t lane = threadIdx.x; + const uint32_t m = blockIdx.x; + r3d_router_sigmoid_topk_row(lg, bias, ids, w, m, n_expert, top_k, lg_ld, scale, + norm, lane, wmin, s_score); +} + + +extern "C" { + +/* moe_scatter's public dispatch, reused by the fused router_topk_scatter. */ +int r3d_rad_moe_scatter(const RadArgs*, RadStream); + +int r3d_rad_moe_router_topk_bf16(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0), + tk = r3d_geti_or(a, "top_k", 0); + const long long norm_ll = r3d_geti_or(a, "norm", 0); + const int norm = (int)norm_ll; + if (M <= 0 || ne <= 0 || tk <= 0 || tk > kW) return R3D_NO(RAD_E_SHAPE); + if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE); // MAXOWN=16 for this row + const RadTensor* L = r3d_opt(a, 0), *I = r3d_opt(a, 1), *W = r3d_opt(a, 2); + if (!r3d_p(L) || !r3d_wp(I) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL); + if (L->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L); + if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(kW); // one block (one wave) per row + const unsigned short* lg = (const unsigned short*)r3d_p(L); + int32_t* ip = (int32_t*)r3d_wp(I); + unsigned short* wp = (unsigned short*)r3d_wp(W); + if (ne <= (long long)2 * kW) + R3D_KLAUNCH(r3d_router_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + else if (ne <= (long long)8 * kW) + R3D_KLAUNCH(r3d_router_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + else + R3D_KLAUNCH(r3d_router_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + return (int)hipGetLastError(); +} + + +/* router_topk_scatter: the pair as one op. Phase 1 is the top-k selection over the whole n_expert + * (the router_topk kernel); phase 2 is the counting sort over this rank's slice (n_local), which + * reuses moe_scatter's dispatch. Byte-identical to the two reference launches, in order. */ +int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 6) return R3D_NO(RAD_E_INVAL); + const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0), + tk = r3d_geti_or(a, "top_k", 0), nl = r3d_geti_or(a, "n_local", ne); + const int norm = (int)r3d_geti_or(a, "norm", 0); + if (M <= 0 || ne <= 0 || tk <= 0 || tk > (long long)kW || tk > ne) return R3D_NO(RAD_E_SHAPE); + if (nl <= 0 || nl > ne) return R3D_NO(RAD_E_SHAPE); + if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE); + + const RadTensor* L = r3d_opt(a, 0), *I = r3d_opt(a, 1), *W = r3d_opt(a, 2), + *ST = r3d_opt(a, 3), *OFF = r3d_opt(a, 4), *CNT = r3d_opt(a, 5); + if (!r3d_p(L) || !r3d_wp(I) || !r3d_wp(W) || !r3d_wp(ST) || !r3d_wp(OFF) || !r3d_wp(CNT)) + return R3D_NO(RAD_E_INVAL); + if (L->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L); + if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE); + + // Phase 1: the top-k selection (the router_topk kernel, over the whole n_expert). + dim3 grid((unsigned)M), blk(kW); + const unsigned short* lg = (const unsigned short*)r3d_p(L); + int32_t* ip = (int32_t*)r3d_wp(I); + unsigned short* wp = (unsigned short*)r3d_wp(W); + if (ne <= (long long)2 * kW) + R3D_KLAUNCH(r3d_router_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + else if (ne <= (long long)8 * kW) + R3D_KLAUNCH(r3d_router_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + else + R3D_KLAUNCH(r3d_router_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, norm); + if (hipGetLastError() != hipSuccess) return R3D_NO(RAD_E_INVAL); + + // Phase 2: the counting sort over this rank's slice (n_local), via moe_scatter's dispatch. + RadTensor t2[4] = { *I, *ST, *OFF, *CNT }; + RadParam sp[4] = { + { "n_expert", RAD_P_INT, (long long)nl, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, (long long)tk, 0, nullptr, 0.0 }, + { "expert_base", RAD_P_INT, r3d_geti_or(a, "expert_base", 0), 0, nullptr, 0.0 }, + { "protect", RAD_P_STR, 0, 0, r3d_gets(a, "protect"), 0.0 }, + }; + RadArgs sa; + std::memset(&sa, 0, sizeof(sa)); + sa.t = t2; sa.n_t = 4; sa.p = sp; sa.n_p = 4; + sa.rank = a->rank; sa.world_size = a->world_size; + return r3d_rad_moe_scatter(&sa, s); +} + + +int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL); + const long long M = r3d_geti_or(a, "M", 0), ne = r3d_geti_or(a, "n_expert", 0), + tk = r3d_geti_or(a, "top_k", 0); + const int norm = (int)r3d_geti_or(a, "norm", 0); + const double scale_d = r3d_getf(a, "route_scale", 0.0); + const float scale = (float)scale_d; + if (M <= 0 || ne <= 0 || tk <= 0 || tk > (long long)kW || tk > ne) return R3D_NO(RAD_E_SHAPE); + if (ne > (long long)16 * kW) return R3D_NO(RAD_E_SHAPE); + if (scale <= 0.0f) return R3D_NO(RAD_E_SHAPE); + + const RadTensor* L = r3d_opt(a, 0), *B = r3d_opt(a, 1), *I = r3d_opt(a, 2), *W = r3d_opt(a, 3); + if (!r3d_p(L) || !r3d_p(B) || !r3d_wp(I) || !r3d_wp(W)) return R3D_NO(RAD_E_INVAL); + if (L->dtype != RAD_BF16 || B->dtype != RAD_F32) return R3D_NO(RAD_E_DTYPE); + const uint32_t lg_ld = (uint32_t)r3d_row_pitch(L); + if (lg_ld < ne) return R3D_NO(RAD_E_SHAPE); + + dim3 grid((unsigned)M), blk(kW); + const unsigned short* lg = (const unsigned short*)r3d_p(L); + const float* bp = (const float*)r3d_p(B); + int32_t* ip = (int32_t*)r3d_wp(I); + unsigned short* wp = (unsigned short*)r3d_wp(W); + if (ne <= (long long)2 * kW) + R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<2>, grid, blk, (hipStream_t)s, lg, bp, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm); + else if (ne <= (long long)8 * kW) + R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<8>, grid, blk, (hipStream_t)s, lg, bp, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm); + else + R3D_KLAUNCH(r3d_router_sigmoid_topk_kernel<16>, grid, blk, (hipStream_t)s, lg, bp, ip, wp, + (uint32_t)M, (uint32_t)ne, (uint32_t)tk, lg_ld, scale, norm); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_moe_scatter.hip b/libr3d/r3d_moe_scatter.hip new file mode 100644 index 00000000..10283b0a --- /dev/null +++ b/libr3d/r3d_moe_scatter.hip @@ -0,0 +1,256 @@ +/* r3d_moe_scatter.hip -- moe_scatter: the routed slots' stable counting sort. + * + * One workgroup does the whole sort (the "small" form, T <= 1024, which covers every decode and + * verify step): histogram in LDS, offsets an exclusive prefix over n_expert <= 512 counts, and + * each slot placed by its rank inside its expert's run. Stable and byte-identical to the + * reference: a slot's place is its position among the same expert's slots in ascending i. + * + * expert_ids [T] -> sorted_tok [T], expert_offset [n_expert+1], expert_count [n_expert] + * + * `expert_base` is this rank's first expert, subtracted from every routed id so the offsets, + * counts and (downstream) weight table are indexed locally; an id outside the slice is dropped + * (sorted to the tail as -1). `protect` is a comma list of local expert indices placed last. + * + * gfx1102 note: the prefix scan's per-wave inclusive sum goes through LDS, not the DPP row-shift + * butterfly (a DPP exchange inside the scan's tile loop miscompiles here). Each wave writes its + * lane's count to LDS, barriers, and takes the serial prefix of its 32 lanes. + * + * The general (three-pass) form for T > 1024 is not implemented here; the shim declines it. + */ +#include + +#include +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +namespace { + +constexpr uint32_t kSortWave = 32; +constexpr uint32_t kMaxExpert = 512; +constexpr uint32_t kMaxProtect = 8; +constexpr uint32_t kScatterSmall = 1024; +constexpr uint32_t kScatWaves = 8; // 256 threads + +struct Protect { + uint32_t n; + uint16_t e[kMaxProtect]; +}; + +/* Local expert `e`'s place in the sort: the protected ones last, the rest closed up in order. */ +__device__ __forceinline__ int32_t sort_place(int32_t e, uint32_t n_local, const Protect& p) { + int32_t below = 0; + for (uint32_t j = 0; j < p.n; ++j) { + if ((int32_t)p.e[j] == e) return (int32_t)(n_local - p.n + j); + below += (int32_t)p.e[j] < e; + } + return e - below; +} + +template +struct ScatterLds { + static constexpr uint32_t kTiles = (kMaxExpert + NW * kSortWave - 1) / (NW * kSortWave); + int32_t e[kScatterSmall]; + int32_t tk[kScatterSmall]; + int32_t run[kScatterSmall]; + int32_t cnt[kMaxExpert + 1]; + int32_t off[kMaxExpert + 1]; + int32_t wt[kTiles][NW]; + int32_t scan[NW * kSortWave]; // the LDS inclusive-scan scratch (gfx1102: no DPP here) +}; + +/* The sort, from a filled slot list on: histogram, offsets and counts, placement. The caller has + * written sl.e[0,T) and zeroed sl.cnt[0,n_expert), followed by a barrier. */ +template +__device__ __forceinline__ void scatter_small_place( + int32_t* __restrict__ sorted, int32_t* __restrict__ off, int32_t* __restrict__ cnt, + uint32_t T, uint32_t n_expert, ScatterLds& sl, int32_t* __restrict__ inv) { + const uint32_t tid = threadIdx.x, lane = tid % kSortWave, wave = tid / kSortWave; + + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.tk[i] = atomicAdd(&sl.cnt[e], 1); + } + R3D_BARRIER(); + + int32_t carry = 0; + for (uint32_t b = 0, t = 0; b < n_expert; b += NW * kSortWave, ++t) { + const uint32_t e = b + tid; + const int32_t v = (e < n_expert) ? sl.cnt[e] : 0; + // Inclusive wave scan through LDS (a DPP row-shift miscompiles on gfx1102). + sl.scan[wave * kSortWave + lane] = v; + R3D_BARRIER(); + int32_t x = 0; + for (int i = 0; i <= (int)lane; ++i) x += sl.scan[wave * kSortWave + i]; + if (lane == kSortWave - 1) sl.wt[t][wave] = x; + R3D_BARRIER(); + int32_t below = 0, tot = 0; +#pragma unroll + for (uint32_t k = 0; k < NW; ++k) { + const int32_t c = sl.wt[t][k]; + below += (k < wave) ? c : 0; + tot += c; + } + if (e < n_expert) { + const int32_t o = carry + below + x - v; // inclusive -> exclusive + sl.off[e] = o; + off[e] = o; + cnt[e] = v; + } + carry += tot; + } + if (tid == 0) off[n_expert] = carry; + R3D_BARRIER(); + + for (uint32_t i = (uint32_t)carry + tid; i < T; i += blockDim.x) sorted[i] = -1; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e >= 0) sl.run[sl.off[e] + sl.tk[i]] = (int32_t)i; + } + R3D_BARRIER(); + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = sl.e[i]; + if (e < 0) { + if (INV) inv[i] = -1; + continue; + } + const int32_t o = sl.off[e], n = sl.cnt[e]; + int32_t rank = 0; + for (int32_t k = 0; k < n; ++k) rank += sl.run[o + k] < (int32_t)i; + sorted[o + rank] = (int32_t)i; + if (INV) inv[i] = o + rank; + } +} + +template +__global__ __launch_bounds__(kScatWaves * kSortWave) void scatter_small_kernel( + const int32_t* __restrict__ ids, int32_t* __restrict__ sorted, int32_t* __restrict__ off, + int32_t* __restrict__ cnt, uint32_t T, uint32_t n_expert, int32_t base, Protect prot, + int32_t* __restrict__ inv) { + __shared__ ScatterLds sl; + const uint32_t tid = threadIdx.x; + for (uint32_t e = tid; e < n_expert; e += blockDim.x) sl.cnt[e] = 0; + for (uint32_t i = tid; i < T; i += blockDim.x) { + const int32_t e = ids[i] - base; + sl.e[i] = (e >= 0 && e < (int32_t)n_expert) ? sort_place(e, n_expert, prot) : -1; + } + R3D_BARRIER(); + scatter_small_place(sorted, off, cnt, T, n_expert, sl, inv); +} + +} // namespace + +extern "C" { + +int r3d_rad_moe_scatter(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL); + const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2), + *cnt = r3d_opt(a, 3); + if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt)) + return R3D_NO(RAD_E_INVAL); + if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || + cnt->dtype != RAD_I32) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt)) + return R3D_NO(RAD_E_STRIDE); + + const long long n_expert = r3d_geti_or(a, "n_expert", 0); + if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE); + const long long T = r3d_numel(ids); + if (T <= 0) return R3D_NO(RAD_E_SHAPE); + if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only + if (r3d_numel(sorted) < T) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE); + + const long long base = r3d_geti_or(a, "expert_base", 0); + if (base < 0) return R3D_NO(RAD_E_SHAPE); + + // protect: a comma list of local expert indices, strictly ascending, at most kMaxProtect. + Protect prot{}; + if (const char* str = r3d_gets(a, "protect")) { + const char* p = str; + long long prev = -1; + while (*p) { + char* end = nullptr; + const long long v = std::strtoll(p, &end, 10); + if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect) + return R3D_NO(RAD_E_SHAPE); + prot.e[prot.n++] = (uint16_t)v; + prev = v; + p = end; + if (*p == ',') ++p; + else if (*p) return R3D_NO(RAD_E_SHAPE); + } + } + + const int32_t* idp = (const int32_t*)r3d_p(ids); + int32_t* sp = (int32_t*)r3d_wp(sorted); + int32_t* op = (int32_t*)r3d_wp(off); + int32_t* cp = (int32_t*)r3d_wp(cnt); + + R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s, + idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, + (int32_t*)nullptr); + return (int)hipGetLastError(); +} + +/* moe_scatter_inv: the same sort, plus the inverse permutation (each slot's row in sorted_tok). */ +int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* ids = r3d_opt(a, 0), *sorted = r3d_opt(a, 1), *off = r3d_opt(a, 2), + *cnt = r3d_opt(a, 3), *inv = r3d_opt(a, 4); + if (!r3d_p(ids) || !r3d_wp(sorted) || !r3d_wp(off) || !r3d_wp(cnt) || !r3d_wp(inv)) + return R3D_NO(RAD_E_INVAL); + if (ids->dtype != RAD_I32 || sorted->dtype != RAD_I32 || off->dtype != RAD_I32 || + cnt->dtype != RAD_I32 || inv->dtype != RAD_I32) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_contig(ids) || !r3d_contig(sorted) || !r3d_contig(off) || !r3d_contig(cnt) || + !r3d_contig(inv)) + return R3D_NO(RAD_E_STRIDE); + + const long long n_expert = r3d_geti_or(a, "n_expert", 0); + if (n_expert <= 0 || n_expert > (long long)kMaxExpert) return R3D_NO(RAD_E_SHAPE); + const long long T = r3d_numel(ids); + if (T <= 0) return R3D_NO(RAD_E_SHAPE); + if (T > (long long)kScatterSmall) return R3D_NO(RAD_E_SHAPE); // the small form only + if (r3d_numel(sorted) < T || r3d_numel(inv) < T) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(off) < n_expert + 1 || r3d_numel(cnt) < n_expert) return R3D_NO(RAD_E_SHAPE); + + const long long base = r3d_geti_or(a, "expert_base", 0); + if (base < 0) return R3D_NO(RAD_E_SHAPE); + + Protect prot{}; + if (const char* str = r3d_gets(a, "protect")) { + const char* p = str; + long long prev = -1; + while (*p) { + char* end = nullptr; + const long long v = std::strtoll(p, &end, 10); + if (end == p || v <= prev || v >= n_expert || prot.n >= kMaxProtect) + return R3D_NO(RAD_E_SHAPE); + prot.e[prot.n++] = (uint16_t)v; + prev = v; + p = end; + if (*p == ',') ++p; + else if (*p) return R3D_NO(RAD_E_SHAPE); + } + } + + const int32_t* idp = (const int32_t*)r3d_p(ids); + int32_t* sp = (int32_t*)r3d_wp(sorted); + int32_t* op = (int32_t*)r3d_wp(off); + int32_t* cp = (int32_t*)r3d_wp(cnt); + int32_t* ip = (int32_t*)r3d_wp(inv); + + R3D_KLAUNCH(scatter_small_kernel, dim3(1), dim3(kScatWaves * kSortWave), (hipStream_t)s, + idp, sp, op, cp, (uint32_t)T, (uint32_t)n_expert, (int32_t)base, prot, ip); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h index 8ad08eb6..75fcd997 100644 --- a/libr3d/r3d_plugin.h +++ b/libr3d/r3d_plugin.h @@ -139,10 +139,116 @@ int r3d_rad_quant_act_i8g (const RadArgs* a, RadStream s); int r3d_rad_gated_quant_fp8 (const RadArgs* a, RadStream s); int r3d_rad_dequant (const RadArgs* a, RadStream s); -/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */ +/* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_f16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */ int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_f16_m16 (const RadArgs* a, RadStream s); + +/* --- r3d_gemm_w4a16_nt_m64.hip: the 4-bit weight against an f16 activation at M <= 64. The + * codes are read in the container's order; the layout and relayout hooks present the + * (scale, zero) pair as the rad.planes joined operand, the rule's own form. --- */ +int r3d_rad_gemm_nt_q_w4a16_m64 (const RadArgs* a, RadStream s); +int r3d_layout_gemm_nt_q_w4a16 (const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, RadLayout* out); +int r3d_relayout_gemm_nt_q_w4a16(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); + +/* --- r3d_gemm_w5a16_nt_m64.hip: the 5-bit weight (ParoQuant int5) against an f16 + * activation at M <= 64: the 4-bit row with the fifth-bit plane. --- */ +int r3d_rad_gemm_nt_q_w5a16_m64 (const RadArgs* a, RadStream s); +int r3d_layout_gemm_nt_q_w5a16 (const RadParam* p, int n_p, int operand, const RadEncoding* enc, + const int* sel, const RadTensor* pl, int n, RadLayout* out); +int r3d_relayout_gemm_nt_q_w5a16(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); int r3d_rad_gemm_nt_q_fp8 (const RadArgs* a, RadStream s); +/* --- r3d_gdn_kkt_solve_c64.hip: the gated-delta-net chunk preamble, the gram and the blocked + * inverse of I + the strictly lower decayed gram, one 64-chunk a workgroup. --- */ +int r3d_rad_gdn_kkt_solve(const RadArgs* a, RadStream s); + + +/* --- r3d_gdn_chunk_scan_k128_v128_c64.hip: the gated-delta-net chunked scan, the chunk's + * output and its closing state, the recurrent state in wave-matrix accumulators. --- */ +int r3d_rad_gdn_chunk_scan(const RadArgs* a, RadStream s); + +/* --- r3d_gdn_gated_rmsnorm_h128.hip: the gated RMS norm a gated-delta-net layer applies to its + * own output, one wave per (token, head) row. */ +int r3d_rad_gdn_gated_rmsnorm(const RadArgs* a, RadStream s); + +/* --- r3d_gdn_gated_norm_had_quant_i8.hip: the GDN block's gated RMS norm, block Hadamard and + * per-row int8 quantiser in one pass. */ +int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s); + +/* --- r3d_gdn_conv_w4_h128.hip: the GDN depthwise causal convolution (width 4, silu) and the + * work fused around it: the prefill prep and the decode update. */ +int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s); +int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s); + +/* --- r3d_gdn_recurrent_update_k128_v128.hip: the gated-delta-net recurrent state update at + * decode, the per-token state step against a paged fp32 state cache. */ +int r3d_rad_gdn_recurrent_update(const RadArgs* a, RadStream s); + +/* --- r3d_expert_scale_bf16.hip: each routing weight times its expert's own scale, in place. */ +int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s); + +/* --- r3d_moe_router_topk_bf16.hip: softmax over the expert logits, the top_k, renormalised. */ +int r3d_rad_moe_router_topk_bf16(const RadArgs* a, RadStream s); + +/* --- r3d_moe_scatter.hip: the routed slots' stable counting sort (small form). */ +int r3d_rad_moe_scatter(const RadArgs* a, RadStream s); +int r3d_rad_moe_scatter_inv(const RadArgs* a, RadStream s); + +/* --- r3d_moe_gather.hip: fold the expert outputs back to the token. */ +int r3d_rad_moe_gather(const RadArgs* a, RadStream s); +int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s); +int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s); +int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s); + +/* --- r3d_moe_gemm_q.hip: the grouped quantised GEMM (E4M3 x E4M3, the per-(row, grid) scale fold). */ +int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s); +int r3d_rad_moe_gemm_q_alu(const RadArgs* a, RadStream s); +int r3d_rad_moe_gemm_bf16(const RadArgs* a, RadStream s); +int r3d_rad_moe_gemm_fp8_f32scale(const RadArgs* a, RadStream s); +int r3d_rad_moe_gemm_mxfp4a8(const RadArgs* a, RadStream s); + +/* --- r3d_moe_gemm_w4a8.hip: the grouped GEMM with int4-weights / int8-activation experts. */ +int r3d_rad_moe_gemm_w4a8(const RadArgs* a, RadStream s); + +/* --- r3d_had_quant_act_i8.hip: a block Hadamard along K, then per-row symmetric int8. */ +int r3d_rad_had_quant_act_i8(const RadArgs* a, RadStream s); + +/* --- r3d_gelu_mul_quant_i8.hip: gelu(gate) * up, then per-row symmetric int8. */ +int r3d_rad_gelu_mul_quant_i8(const RadArgs* a, RadStream s); + +/* --- r3d_kv_len_trim.hip: per-sequence context lengths less `trim`. */ +int r3d_rad_kv_len_trim(const RadArgs* a, RadStream s); + +/* --- r3d_qsa_tail_store.hip: the QSA indexer's tail, into a per-layer linear KV state. */ +int r3d_rad_qsa_tail_store(const RadArgs* a, RadStream s); + +/* --- r3d_gated_had_quant_i8.hip: a gated product, block Hadamard, then per-row int8. */ +int r3d_rad_gated_had_quant_i8(const RadArgs* a, RadStream s); + +/* --- r3d_had_quant_act_fp8.hip: a 128-wide block Hadamard, then per-group E4M3. */ +int r3d_rad_had_quant_act_fp8(const RadArgs* a, RadStream s); + +/* --- r3d_gated_had_quant_fp8.hip: a gated product, 128-wide Hadamard, then per-group E4M3. */ +int r3d_rad_gated_had_quant_fp8(const RadArgs* a, RadStream s); + +/* --- r3d_quant_cols_fp8.hip: E4M3 codes with one scale per column over every row. */ +int64_t r3d_quant_cols_fp8_scratch(const RadArgs* a); +int r3d_rad_quant_cols_fp8(const RadArgs* a, RadStream s); + +/* --- r3d_had_quant_act_i8g.hip: a 128-wide block Hadamard, then per-group int8 (row-major). */ +int r3d_rad_had_quant_act_i8g(const RadArgs* a, RadStream s); + +/* --- r3d_gated_had_quant_i8g.hip: a gated product, 128-wide Hadamard, then per-group int8. */ +int r3d_rad_gated_had_quant_i8g(const RadArgs* a, RadStream s); + +/* --- r3d_rmsnorm_quant_i8.hip: the RMS norm and the per-row int8 quantiser, one pass. */ +int r3d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream s); + /* --- r3d_shapes.cpp --- */ int r3d_shape_rmsnorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_layernorm (const RadParam* p, int n_p, int operand, RadOpdDesc* out); @@ -163,6 +269,17 @@ int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDe int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_quant_act_i8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_had_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gelu_mul_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_kv_len_trim(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gated_had_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_had_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gated_had_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_quant_cols_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_had_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_rmsnorm_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_quant_act_i8g (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_gated_quant_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_dequant (const RadParam* p, int n_p, int operand, RadOpdDesc* out); @@ -230,6 +347,7 @@ int r3d_rad_attn_prefill_h128 (const RadArgs* a, RadStream s); * carries its own layout hook because the reference's gemm_nt_q hook answers nothing for this * dtype (ref_layout_gemm_q reads zp_grid, which has no fp8a8 entry). */ int r3d_rad_gemm_nt_q_fp8_tiled (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_fp8_tiled_alu(const RadArgs* a, RadStream s); int r3d_rad_gemm_nt_q_w2a8_tiled (const RadArgs* a, RadStream s); extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); @@ -240,6 +358,8 @@ extern "C" int r3d_layout_gemm_q_fp8_weight(const RadParam*, int, int, const Rad * E4M3 codes and block scale. */ int r3d_rad_gemm_nt_q_mxfp4a8_m16 (const RadArgs* a, RadStream s); int r3d_rad_gemm_nt_q_mxfp4a8_tiled(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_mxfp4a8_m16_alu (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_mxfp4a8_tiled_alu(const RadArgs* a, RadStream s); /* --- r3d_gemm_inta8.hip: the symmetric int4 and int8 weight grids at decode heights. The weight * is signed codes (I4 two per byte, or I8) with a plain f16 scale per (row, 128 of K). No zero @@ -263,6 +383,7 @@ extern "C" int r3d_relayout_gemm_nt_q_w2a8(const RadParam*, int, int, const RadE * (r3d_shapes.cpp) transcribes ref_logits_gemm_shape, three plain tensors with nothing joined, so * the band the engine declares is the band kbench fills. */ int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s); +int r3d_rad_logits_gemm_bf16_alu (const RadArgs* a, RadStream s); /* The head's layout hook: `output.weight` at a llama_dense_fp8 checkpoint is E4M3 codes and a bf16 * scale per 128x128 block, stored as two container planes behind the one `lm_head` operand, and the * mapped tier does not place a weight a loaded library cannot read in place. Transcribed from @@ -272,6 +393,10 @@ int r3d_rad_logits_gemm_bf16 (const RadArgs* a, RadStream s); extern "C" int r3d_layout_logits_head(const RadParam*, int, int, const RadEncoding*, const int*, const RadTensor*, int, RadLayout*); int r3d_rad_gemm_nt_bf16_tiled (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_bf16_tiled_alu(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_bf16_m64_wmma (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_q_w8a8_m64 (const RadArgs* a, RadStream s); int r3d_shape_logits_gemm_bf16 (const RadParam*, int, int, RadOpdDesc*); /* --- r3d_model_bf16.hip: the fused MLP activation and the fused norm-quantiser --- */ diff --git a/libr3d/r3d_qsa_tail_store.hip b/libr3d/r3d_qsa_tail_store.hip new file mode 100644 index 00000000..c5b80224 --- /dev/null +++ b/libr3d/r3d_qsa_tail_store.hip @@ -0,0 +1,93 @@ +/* r3d_qsa_tail_store.hip -- qsa_tail_store: the QSA indexer's tail, raw index keys of tokens that + * have not yet completed a block, into a per-layer linear KV state. + * + * The tail is a per-layer linear KV state owned by the sequence (allocated zeroed, kept for the + * sequence's life), not a plane indexed by the step-local batch row. `state` is one layer's cache, + * [slots, 1, ring, n]; `sidx` names the sequence's slot; position p lands at row p % ring. + * + * The ring is ratio + n_spec, not ratio: the next step restarts at the first rejected position, so + * a step may still owe positions back to p0 - ratio + 1 while writing up to p0 + n_spec. A token's + * sequence comes from cu_seqlens (a linear scan suffices for a handful of sequences). Only the last + * `ring` tokens of a sequence's chunk write: positions p and p + ring share a row, so writing all + * of a prefill chunk would race. + * + * k [T][n] bf16, pos [T] i32, cu [seqs+1] i32, state [slots,1,ring,n] bf16 (inout), sidx [seqs] + */ +#include + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kThreads = 256; + +__global__ __launch_bounds__(kThreads) void qsa_tail_store_kernel( + const uint16_t* __restrict__ k, const int32_t* __restrict__ pos, + const int32_t* __restrict__ cu, const int32_t* __restrict__ sidx, + uint16_t* __restrict__ state, + int T, int n, int ring, int seqs, int k_ld, int s_slot, int s_row, int sidx_ld) { + const int t = (int)blockIdx.x; + if (t >= T) return; + + // This token's sequence, by a linear scan in every thread (cheaper than LDS plus a barrier). + int s = -1; + for (int i = 0; i < seqs; ++i) + if (t >= cu[i] && t < cu[i + 1]) { s = i; break; } + if (s < 0) return; + + // Only the last `ring` tokens of this sequence's chunk. + if (t < cu[s + 1] - ring) return; + + // Column 0 is the committed slot; -1 marks a sequence with no state. + const int si = sidx[(size_t)s * sidx_ld]; + if (si < 0) return; + + const int row = pos[t] % ring; + const size_t src = (size_t)t * k_ld; + const size_t dst = (size_t)si * s_slot + (size_t)row * s_row; + for (int d = (int)threadIdx.x; d < n; d += kThreads) state[dst + d] = k[src + d]; +} + +} // namespace + +extern "C" { + +int r3d_rad_qsa_tail_store(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* k = r3d_opt(a, 0), *po = r3d_opt(a, 1), *cu = r3d_opt(a, 2), + *st = r3d_opt(a, 3), *sx = r3d_opt(a, 4); + if (!r3d_p(k) || !r3d_p(po) || !r3d_p(cu) || !r3d_wp(st) || !r3d_p(sx)) + return R3D_NO(RAD_E_INVAL); + if (k->rank != 2) return R3D_NO(RAD_E_SHAPE); + // The state arrives as the group declared it: [slots, heads, ring, n], heads 1. + if (st->rank != 4 || st->shape[1] != 1) return R3D_NO(RAD_E_SHAPE); + if (st->stride[3] != 1) return R3D_NO(RAD_E_STRIDE); + if (k->dtype != RAD_BF16 || st->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + + const long long n = r3d_geti_or(a, "n", 0); + const long long ratio = r3d_geti_or(a, "ratio", 0); + const long long ring = r3d_geti_or(a, "ring", 0); + if (n <= 0 || ratio <= 0 || ring < ratio) return R3D_NO(RAD_E_INVAL); + const long long T = k->shape[0]; + if (T < 1 || k->shape[1] != n) return R3D_NO(RAD_E_SHAPE); + if (st->shape[2] < ring || st->shape[3] != n) return R3D_NO(RAD_E_SHAPE); + const long long seqs = r3d_numel(cu) - 1; + if (seqs < 1 || r3d_numel(po) < T) return R3D_NO(RAD_E_SHAPE); + const long long sidx_ld = sx->rank >= 2 ? sx->shape[1] : 1; + if (sidx_ld < 1 || (sx->rank >= 1 && sx->shape[0] < seqs)) return R3D_NO(RAD_E_SHAPE); + const long long kp = k->stride[1] ? k->stride[0] / k->stride[1] : k->shape[1]; + if (kp < n) return R3D_NO(RAD_E_STRIDE); + + R3D_KLAUNCH(qsa_tail_store_kernel, dim3((unsigned)T), dim3(kThreads), (hipStream_t)s, + (const uint16_t*)r3d_p(k), (const int32_t*)r3d_p(po), (const int32_t*)r3d_p(cu), + (const int32_t*)r3d_p(sx), (uint16_t*)r3d_wp(st), (int)T, (int)n, (int)ring, + (int)seqs, (int)kp, (int)st->stride[0], (int)st->stride[2], (int)sidx_ld); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_quant_cols_fp8.hip b/libr3d/r3d_quant_cols_fp8.hip new file mode 100644 index 00000000..97278df9 --- /dev/null +++ b/libr3d/r3d_quant_cols_fp8.hip @@ -0,0 +1,174 @@ +/* r3d_quant_cols_fp8.hip -- quant_cols_fp8: E4M3 codes with one scale per column over every row. + * + * An attention's V for its fp8 P.V: the formula is quant_act_fp8's (scale amax / 448, 1 for an + * all-zero column, codes of x / scale clamped to +-448) with the group running down a column. A + * column's scale needs every row, so two passes over the rows, split into kColChunks chunks: + * 1. column amax partials, a workgroup a block of columns and a chunk of rows, the bf16 + * magnitudes compared as integers (their order is the values'); + * 2. a workgroup the same block and chunk: the scales from the chunks' partials, then the codes, + * the chunk's rows walked from its end (the first pass read them last, the cache still holds + * them). + * + * A thread owns eight columns: one 16-byte load and one 8-byte store a row. RDNA3 has no fp8 + * hardware, so the codes use the software E4M3 codec (r3d_codecs.h), not the cvt_pk_fp8 builtin. + * + * Scratch: kColChunks * n floats (the column amax partials). + */ +#include + +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kColChunks = 32; +constexpr int kColThreads = 128; +constexpr float kTopE4M3 = 448.0f; + +// The two bf16 in a 32-bit word, sign masked off: the magnitude, ordered as the values. +__device__ __forceinline__ uint32_t col_mag(uint32_t w) { return w & 0x7fff7fffu; } +__device__ __forceinline__ float bf16w_lo(uint32_t w) { return bf16_to_f32((uint16_t)(w & 0xffffu)); } +__device__ __forceinline__ float bf16w_hi(uint32_t w) { return bf16_to_f32((uint16_t)(w >> 16)); } +__device__ __forceinline__ float clamp_top(float c, float top) { + if (c > top) c = top; + if (c < -top) c = -top; + return c; +} +// Two E4M3 codes packed into a 16-bit value, the software codec (RDNA3 has no fp8 builtin). +__device__ __forceinline__ uint16_t col_code2(float a, float b, float ia, float ib) { + const uint8_t lo = f32_to_e4m3(clamp_top(a * ia, kTopE4M3)); + const uint8_t hi = f32_to_e4m3(clamp_top(b * ib, kTopE4M3)); + return (uint16_t)(lo | (hi << 8)); +} + +__global__ __launch_bounds__(kColThreads) void quant_cols_amax_kernel( + const uint16_t* __restrict__ x, int M, int n, int x_ld, float* __restrict__ part) { + const int c8 = blockIdx.x * kColThreads + threadIdx.x; + if (c8 * 8 >= n) return; + const int r0 = (int)((long)M * blockIdx.y / kColChunks); + const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks); + const uint16_t* p = x + (long)c8 * 8; + uint32_t m[4] = { 0, 0, 0, 0 }; + int r = r0; + for (; r + 8 <= r1; r += 8) { + uint4 u[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r + k) * x_ld); +#pragma unroll + for (int k = 0; k < 8; ++k) { + m[0] = max(m[0], col_mag(u[k].x)); + m[1] = max(m[1], col_mag(u[k].y)); + m[2] = max(m[2], col_mag(u[k].z)); + m[3] = max(m[3], col_mag(u[k].w)); + } + } + for (; r < r1; ++r) { + const uint4 u = *(const uint4*)(p + (long)r * x_ld); + m[0] = max(m[0], col_mag(u.x)); + m[1] = max(m[1], col_mag(u.y)); + m[2] = max(m[2], col_mag(u.z)); + m[3] = max(m[3], col_mag(u.w)); + } + float* d = part + (long)blockIdx.y * n + c8 * 8; + *(float4*)d = make_float4(bf16w_lo(m[0]), bf16w_hi(m[0]), bf16w_lo(m[1]), bf16w_hi(m[1])); + *(float4*)(d + 4) = make_float4(bf16w_lo(m[2]), bf16w_hi(m[2]), bf16w_lo(m[3]), bf16w_hi(m[3])); +} + +__global__ __launch_bounds__(kColThreads) void quant_cols_code_kernel( + const uint16_t* __restrict__ x, int M, int n, int x_ld, const float* __restrict__ part, + uint8_t* __restrict__ y, int y_ld, float* __restrict__ scale) { + const int c8 = blockIdx.x * kColThreads + threadIdx.x; + if (c8 * 8 >= n) return; + float am[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; + for (int ch = 0; ch < kColChunks; ++ch) { + const float4 a = *(const float4*)(part + (long)ch * n + c8 * 8); + const float4 b = *(const float4*)(part + (long)ch * n + c8 * 8 + 4); + am[0] = fmaxf(am[0], a.x); am[1] = fmaxf(am[1], a.y); + am[2] = fmaxf(am[2], a.z); am[3] = fmaxf(am[3], a.w); + am[4] = fmaxf(am[4], b.x); am[5] = fmaxf(am[5], b.y); + am[6] = fmaxf(am[6], b.z); am[7] = fmaxf(am[7], b.w); + } + float sc[8], inv[8]; +#pragma unroll + for (int e = 0; e < 8; ++e) { + sc[e] = am[e] > 0.0f ? am[e] * (1.0f / kTopE4M3) : 1.0f; + inv[e] = 1.0f / sc[e]; + } + if (blockIdx.y == 0) { + *(float4*)(scale + c8 * 8) = make_float4(sc[0], sc[1], sc[2], sc[3]); + *(float4*)(scale + c8 * 8 + 4) = make_float4(sc[4], sc[5], sc[6], sc[7]); + } + const int r0 = (int)((long)M * blockIdx.y / kColChunks); + const int r1 = (int)((long)M * (blockIdx.y + 1) / kColChunks); + const uint16_t* p = x + (long)c8 * 8; + uint8_t* q = y + (long)c8 * 8; + auto code = [&](uint4 u) -> uint2 { + uint32_t lo = col_code2(bf16w_lo(u.x), bf16w_hi(u.x), inv[0], inv[1]); + lo |= (uint32_t)col_code2(bf16w_lo(u.y), bf16w_hi(u.y), inv[2], inv[3]) << 16; + uint32_t hi = col_code2(bf16w_lo(u.z), bf16w_hi(u.z), inv[4], inv[5]); + hi |= (uint32_t)col_code2(bf16w_lo(u.w), bf16w_hi(u.w), inv[6], inv[7]) << 16; + return make_uint2(lo, hi); + }; + int r = r1; + for (; r - 8 >= r0; r -= 8) { + uint4 u[8]; +#pragma unroll + for (int k = 0; k < 8; ++k) u[k] = *(const uint4*)(p + (long)(r - 1 - k) * x_ld); +#pragma unroll + for (int k = 0; k < 8; ++k) *(uint2*)(q + (long)(r - 1 - k) * y_ld) = code(u[k]); + } + for (; r > r0; --r) + *(uint2*)(q + (long)(r - 1) * y_ld) = code(*(const uint4*)(p + (long)(r - 1) * x_ld)); +} + +} // namespace + +extern "C" { + +int64_t r3d_quant_cols_fp8_scratch(const RadArgs* a) +{ + const long long n = r3d_geti_or(a, "n", 0); + if (n <= 0) return 0; + return (int64_t)kColChunks * n * (int64_t)sizeof(float); +} + +int r3d_rad_quant_cols_fp8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, 0), *y = r3d_opt(a, 1), *sc = r3d_opt(a, 2); + if (!r3d_p(x) || !r3d_wp(y) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || y->dtype != RAD_F8E4M3 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + const long long n = r3d_geti_or(a, "n", 0); + if (n <= 0 || n % 8) return R3D_NO(RAD_E_SHAPE); + /* The rows are the leading axes, whatever their rank; the pitches are the leading strides. + * All three are cast to int for the launch, so bound them. */ + if (n > (1LL << 30)) return R3D_NO(RAD_E_SHAPE); + const long long x_ld = r3d_row_pitch(x); + const long long y_ld = r3d_row_pitch(y); + if (x_ld < n || y_ld < n || (x_ld & 7) || (y_ld & 7)) return R3D_NO(RAD_E_SHAPE); + const long long xnel = r3d_numel(x); + if (xnel % n) return R3D_NO(RAD_E_SHAPE); + const long long M = xnel / n; + if (M < 1 || M > (1LL << 30)) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(y) < M * n || r3d_numel(sc) < n) return R3D_NO(RAD_E_SHAPE); + const int64_t need = (int64_t)kColChunks * n * sizeof(float); + if (!a->scratch || a->scratch_bytes < need) return R3D_NO(RAD_E_SCRATCH); + float* part = (float*)a->scratch; + + const dim3 grid((unsigned)((n / 8 + kColThreads - 1) / kColThreads), (unsigned)kColChunks); + const dim3 blk(kColThreads); + R3D_KLAUNCH(quant_cols_amax_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x), + (int)M, (int)n, (int)x_ld, part); + R3D_KLAUNCH(quant_cols_code_kernel, grid, blk, (hipStream_t)s, (const uint16_t*)r3d_p(x), + (int)M, (int)n, (int)x_ld, part, (uint8_t*)r3d_wp(y), (int)y_ld, + (float*)r3d_wp(sc)); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_rmsnorm_quant_i8.hip b/libr3d/r3d_rmsnorm_quant_i8.hip new file mode 100644 index 00000000..f57c53b0 --- /dev/null +++ b/libr3d/r3d_rmsnorm_quant_i8.hip @@ -0,0 +1,208 @@ +/* r3d_rmsnorm_quant_i8.hip -- rmsnorm_quant_i8: the RMS norm and the per-row int8 quantiser, in + * one pass over the row, optionally with the residual junction in front of it: a post-norm on the + * branch output, the residual add and a scalar on the sum. + * + * A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32 scale + * per row, produced by a norm. Unfused that is two dispatches, and a sandwich-norm model issues + * four or five at every residual junction: + * + * rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant + * + * This is the chain as one dispatch. Byte-identical to the chain, because every intermediate the + * chain stores in bf16 is rounded to bf16 here and the next stage reads the rounded value: the + * post-norm output, the residual sum, the scaled residual and the norm output the quantiser + * reduces over. Both sums of squares use the standalone norm's partition (thread t folding columns + * t, t+THR, ... in order, then the wave sum and the waves in order through LDS). + * + * The codes are in the w4a8 GEMM's fragment order: byte j of a k step comes from source + * 8*((j&7)>>2) + 4*(j>>3) + (j&3) inside the step. + * + * THR is fixed at 256 (the re-read form): one workgroup a row, the row re-read in each pass. The + * register form (decode heights) and the fused all-reduce forms are not served here. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include + +#define R3D_BARRIER() __syncthreads(); asm volatile("" ::: "memory"); + +namespace { + +constexpr uint32_t kThreads = 256; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr float kTopI8 = 127.0f; +constexpr float kFloor = 1e-8f; + +__device__ __forceinline__ float bf2f(uint16_t h) { return bf16_to_f32(h); } + +template +__device__ __forceinline__ float gain(const void* w, uint32_t i) { + return WF32 ? ((const float*)w)[i] : bf16_to_f32(((const uint16_t*)w)[i]); +} +__device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) { + return f32 ? ((const float*)sc)[0] : bf16_to_f32(((const uint16_t*)sc)[0]); +} + +// The row body from the junction on: `s1` is the post-norm's factor, already reduced over `xr`. +template +__device__ __forceinline__ void junction_row( + const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w, + const void* __restrict__ wp, float sv, signed char* __restrict__ qr, float* __restrict__ Sr, + uint16_t* __restrict__ yr, uint32_t n, float eps, float wadd, float s1, uint16_t* ybuf, + float* l2, float* lm) { + // ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it + float ss2 = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + uint16_t v = xr[i]; + if (RES) { + if (POST) v = f32_to_bf16(bf2f(v) * s1 * (gain(wp, i) + wadd)); + v = f32_to_bf16(bf2f(rr[i]) + bf2f(v)); + if (SCL) v = f32_to_bf16(bf2f(v) * sv); + rr[i] = v; + } + const float f = bf2f(v); + ss2 += f * f; + } + ss2 = block_sum(ss2, l2); + const float s2 = rsqrtf(ss2 / (float)n + eps); + + // ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax + const uint16_t* __restrict__ nr = RES ? rr : xr; + float m = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + const uint16_t y = f32_to_bf16(bf2f(nr[i]) * s2 * (gain(w, i) + wadd)); + ybuf[i] = y; + if (yr) yr[i] = y; + m = fmaxf(m, fabsf(bf2f(y))); + } + m = wave_max(m); + if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m; + R3D_BARRIER(); // also publishes ybuf to every thread + m = lm[0]; +#pragma unroll + for (uint32_t i = 1; i < kWaves; ++i) m = fmaxf(m, lm[i]); + const float scale = fmaxf(m, kFloor) / kTopI8; + const float inv = 1.0f / scale; + if (threadIdx.x == 0) *Sr = scale; + + // ---- the codes, in the w4a8 GEMM's fragment order + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + const uint32_t s = i >> 4, j = i & 15; + const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = (int)lrintf(bf2f(ybuf[src]) * inv); + qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } +} + +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void rmsnorm_quant_i8_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, uint32_t n, + float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[kWaves], l2[kWaves], lm[kWaves]; + const uint32_t row = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + + // ---- the post-norm's sum of squares, over the branch output + float s1 = 0.0f; + if (POST) { + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + const float v = bf2f(xr[i]); + ss += v * v; + } + ss = block_sum(ss, l1); + s1 = rsqrtf(ss / (float)n + eps); + } + junction_row( + xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, SCL ? scalar_of(sc, sc_f32) : 1.0f, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, + ybuf, l2, lm); +} + +} // namespace + +extern "C" { + +int r3d_rad_rmsnorm_quant_i8(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 5) return R3D_NO(RAD_E_INVAL); + const RadTensor* x = r3d_opt(a, 0), *rs = r3d_opt(a, 1), *w = r3d_opt(a, 2), *q = r3d_opt(a, 3), + *sc = r3d_opt(a, 4), *y = r3d_opt(a, 5), *wp = r3d_opt(a, 6), + *sv = r3d_opt(a, 7); + if (!r3d_p(x) || !r3d_p(w) || !r3d_wp(q) || !r3d_wp(sc)) return R3D_NO(RAD_E_INVAL); + if ((wp || sv) && !rs) return R3D_NO(RAD_E_INVAL); // a junction without a stream to add into + if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + long long M = 0, n = 0; + if (r3d_rows_of(x, &M, &n) != 0) return R3D_NO(RAD_E_INVAL); + if (n <= 0 || n % 16) return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(w) != n) return R3D_NO(RAD_E_SHAPE); + if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (wp && (r3d_numel(wp) != n || wp->dtype != w->dtype)) return R3D_NO(RAD_E_SHAPE); + if (sv && (r3d_numel(sv) != 1 || (sv->dtype != RAD_F32 && sv->dtype != RAD_BF16))) + return R3D_NO(RAD_E_SHAPE); + if (r3d_numel(q) < M * n || r3d_numel(sc) < M) return R3D_NO(RAD_E_SHAPE); + if (y && r3d_numel(y) < M * n) return R3D_NO(RAD_E_SHAPE); + if (rs && r3d_numel(rs) < M * n) return R3D_NO(RAD_E_SHAPE); + + const long long x_ld_ = r3d_row_pitch(x); + if (x_ld_ < 0) return R3D_NO(RAD_E_STRIDE); + const uint32_t x_ld = (uint32_t)x_ld_; + uint32_t r_ld = (uint32_t)n; + if (rs) { + const long long rl = r3d_row_pitch(rs); + if (rl < n) return R3D_NO(RAD_E_STRIDE); + r_ld = (uint32_t)rl; + } + uint32_t y_ld = (uint32_t)n; + if (y) { + const long long yl = r3d_row_pitch(y); + if (yl < n) return R3D_NO(RAD_E_STRIDE); + y_ld = (uint32_t)yl; + } + const size_t lds = (size_t)n * sizeof(uint16_t); + if (lds > 60 * 1024) return R3D_NO(RAD_E_SHAPE); + + const float eps = (float)r3d_getf(a, "eps", 1e-6); + const float wadd = (float)r3d_getf(a, "wadd", 0.0); + const uint32_t scf = sv ? (sv->dtype == RAD_F32) : 0u; + const bool WF = w->dtype == RAD_F32, RS = rs != nullptr, PO = wp != nullptr, SC = sv != nullptr; + + dim3 grid((unsigned)M), blk(kThreads); + const uint16_t* xp = (const uint16_t*)r3d_p(x); + uint16_t* rwp = rs ? (uint16_t*)r3d_wp(rs) : nullptr; + const void* wv = r3d_p(w); + const void* wpp = r3d_p(wp); + const void* svp = r3d_p(sv); + signed char* qp = (signed char*)r3d_wp(q); + float* sp = (float*)r3d_wp(sc); + uint16_t* yp = y ? (uint16_t*)r3d_wp(y) : nullptr; + +#define RQ8(WF_, RS_, PO_, SC_) \ + R3D_KLAUNCH_S(R3D_KNAME(rmsnorm_quant_i8_kernel), grid, blk, lds, \ + (hipStream_t)s, xp, rwp, wv, wpp, svp, scf, qp, sp, yp, (uint32_t)n, eps, wadd,\ + x_ld, r_ld, y_ld) + if (WF) { + if (!RS) RQ8(true, false, false, false); + else if (!PO && !SC) RQ8(true, true, false, false); + else if (PO && !SC) RQ8(true, true, true, false); + else if (PO && SC) RQ8(true, true, true, true); + else RQ8(true, true, false, true); + } else { + if (!RS) RQ8(false, false, false, false); + else if (!PO && !SC) RQ8(false, true, false, false); + else if (PO && !SC) RQ8(false, true, true, false); + else if (PO && SC) RQ8(false, true, true, true); + else RQ8(false, true, false, true); + } +#undef RQ8 + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp index 23afedf8..4fa09152 100644 --- a/libr3d/r3d_rows.cpp +++ b/libr3d/r3d_rows.cpp @@ -155,10 +155,64 @@ static const RadOperandSpec oQuant[] = { { "x", RAD_OPD_IN, 0 }, { "q", RAD_OPD_ static const RadParamSpec pGatedQuant[] = { P_INT("M"), P_INT("n"), P_INT("group"), P_STR("dtype"), P_STRO("act") }; + + /* router_topk_scatter: the pair as one op -- logits, the selection (expert_ids, expert_w), and + * the sort (sorted_tok, expert_offset, expert_count). */ +static const RadOperandSpec oRouterTopkScatter[] = { { "logits", RAD_OPD_IN, 0 }, + { "expert_ids", RAD_OPD_OUT, 0 }, + { "expert_w", RAD_OPD_OUT, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, + { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pRouterTopkScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("n_local"), P_INT("norm"), P_STRO("dtype"), + P_INT("expert_base"), P_STRO("protect") }; + + /* router_sigmoid_topk: the GLM-style router -- logits, the per-expert correction bias, and the + * selection (expert_ids, expert_w). */ +static const RadOperandSpec oRouterSigmoid[] = { { "logits", RAD_OPD_IN, 0 }, + { "bias", RAD_OPD_IN, 0 }, + { "expert_ids", RAD_OPD_OUT, 0 }, + { "expert_w", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_F64("route_scale"), P_INTO("norm"), P_STRO("dtype") }; static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, { "out_bf16", RAD_OPD_OUT, 1 } }; +static const RadOperandSpec oGeluMulQuantI8[] = { { "gate_up", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 } }; +static const RadParamSpec pKvLenTrim[] = { P_INT("trim"), P_INT("max_seqs") }; +static const RadOperandSpec oKvLenTrim[] = { { "seqused", RAD_OPD_IN, 0 }, + { "tail", RAD_OPD_IN, 0 }, + { "out", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pQsaTailStore[] = { P_INT("M"), P_INT("n"), P_INT("ratio"), + P_INT("ring"), P_INT("seqs"), P_STR("dtype") }; +static const RadOperandSpec oQsaTailStore[] = { { "k", RAD_OPD_IN, 0 }, + { "pos", RAD_OPD_IN, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_INOUT, 0 }, + { "sidx", RAD_OPD_IN, 0 } }; +static const RadParamSpec pGatedHadQuantI8[] = { P_INT("M"), P_INT("n"), P_INT("group"), + P_STR("dtype"), P_STRO("act"), P_INTO("mode") }; +static const RadOperandSpec oGatedHadQuantI8[] = { { "a", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_IN, 1 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 } }; +static const RadOperandSpec oQuantCols[] = { { "x", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pRmsQuantI8[] = { P_INT("M"), P_INT("n"), P_F64("eps"), P_STR("dtype"), + P_F64O("wadd") }; +static const RadOperandSpec oRmsQuantI8[] = { { "x", RAD_OPD_IN, 0 }, + { "residual", RAD_OPD_INOUT, 1 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, + { "w_post", RAD_OPD_WEIGHT, 1 }, + { "scalar", RAD_OPD_IN, 1 } }; static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RAD_OPD_IN, 0 }, { "y", RAD_OPD_OUT, 0 } }; @@ -177,6 +231,149 @@ static const RadOperandSpec oGemmQ[] = { { "a", RAD_OPD_IN, 0 }, { "a_scale", RA { "y", RAD_OPD_OUT, 0 }, { "a_sum", RAD_OPD_IN, 1 }, { "b_ref", RAD_OPD_WEIGHT, 1 } }; +/* --- gated-delta-net --- */ +static const RadParamSpec pGdnKktSolve[] = { P_INT("M"), P_INT("head_k"), P_INT("chunk") }; +static const RadOperandSpec oGdnKktSolve[] = { { "k", RAD_OPD_IN, 0 }, + { "beta", RAD_OPD_IN, 0 }, + { "g", RAD_OPD_IN, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "A", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGdnChunkScan[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), + P_INTD("chunk"), P_F64O("scale"), P_INTO("state_fp16") }; +static const RadOperandSpec oGdnChunkScan[] = { { "q", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "A", RAD_OPD_IN, 0 }, + { "g", RAD_OPD_IN, 0 }, + { "beta", RAD_OPD_IN, 0 }, + { "h0", RAD_OPD_IN, 1 }, + { "cu", RAD_OPD_IN, 0 }, + { "o", RAD_OPD_OUT, 0 }, + { "ht", RAD_OPD_OUT, 1 }, + { "state_idx", RAD_OPD_IN, 1 } }; + +static const RadParamSpec pGdnGatedRmsnorm[] = { P_INT("M"), P_INT("channels"), + P_F64("eps"), P_STR("act") }; +static const RadOperandSpec oGdnGatedRmsnorm[] = { { "x", RAD_OPD_IN, 0 }, + { "z", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_IN, 0 }, + { "o", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGdnGatedNormHq[] = { P_INT("M"), P_INT("n"), P_INT("head_dim"), + P_INT("group"), P_F64("eps"), P_STR("dtype"), + P_INTO("zgrp"), P_INTO("zblk") }; +static const RadOperandSpec oGdnGatedNormHq[] = { { "x", RAD_OPD_IN, 0 }, + { "z", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGdnConvPrep[] = { P_INT("M"), P_INT("head_k"), P_INT("head_v"), + P_INTD("chunk"), P_INT("conv_width"), + P_F64O("l2_eps"), P_F64O("softplus_thr") }; +static const RadOperandSpec oGdnConvPrep[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_IN, 1 }, + { "A_log", RAD_OPD_IN, 0 }, + { "dt_bias", RAD_OPD_IN, 0 }, + { "conv_state", RAD_OPD_INOUT, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "a", RAD_OPD_IN, 1 }, + { "b_gate", RAD_OPD_IN, 1 }, + { "cache_idx", RAD_OPD_IN, 1 }, + { "has_init", RAD_OPD_IN, 1 }, + { "q", RAD_OPD_OUT, 0 }, + { "k", RAD_OPD_OUT, 0 }, + { "v", RAD_OPD_OUT, 0 }, + { "g", RAD_OPD_OUT, 0 }, + { "beta", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pGdnConvUpdate[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), + P_INT("conv_width"), P_F64O("max_query_len") }; +static const RadOperandSpec oGdnConvUpdate[] = { { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_IN, 1 }, + { "conv_state", RAD_OPD_INOUT, 0 }, + { "state_idx", RAD_OPD_IN, 0 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "cu", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "k", RAD_OPD_OUT, 0 }, + { "v", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pExpertScale[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_STR("dtype") }; +static const RadOperandSpec oExpertScale[] = { { "ids", RAD_OPD_IN, 0 }, + { "w_e", RAD_OPD_IN, 0 }, + { "ew", RAD_OPD_INOUT, 0 } }; + +static const RadParamSpec pMoeRouterTopk[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("norm"), P_STR("dtype") }; +static const RadOperandSpec oMoeRouterTopk[] = { { "logits", RAD_OPD_IN, 0 }, + { "expert_ids", RAD_OPD_OUT, 0 }, + { "expert_w", RAD_OPD_OUT, 0 } }; + +static const RadParamSpec pMoeScatter[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INTO("expert_base"), P_STRO("protect") }; +static const RadOperandSpec oMoeScatter[] = { { "expert_ids", RAD_OPD_IN, 0 }, + { "sorted_tok", RAD_OPD_OUT, 0 }, + { "expert_offset", RAD_OPD_OUT, 0 }, + { "expert_count", RAD_OPD_OUT, 0 } }; + /* moe_gather: fold the expert outputs back to the token. y_expert [Te, n], expert_w [Mw, top_k], + * the slot table (sorted_tok), the optional shared arm, and y [M, n]. */ +static const RadOperandSpec oMoeGather[] = { { "y_expert", RAD_OPD_IN, 0 }, + { "expert_w", RAD_OPD_IN, 0 }, + { "sorted_tok", RAD_OPD_IN, 0 }, + { "shared", RAD_OPD_IN, 0 }, + { "shared_gate", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pMoeGather[] = { P_INT("M"), P_INT("n"), P_INT("top_k"), P_STRO("dtype"), + P_STRO("act") }; + +/* moe_gemm_q: the grouped quantised GEMM. a and the weight tables are E4M3 with an f32 scale per + * (row, grid of K); the even experts are `w` / `w_scale`, the odd `w_odd` / `w_odd_scale`. */ +static const RadOperandSpec oMoeGemmQ[] = { { "a", RAD_OPD_IN, 0 }, + { "a_scale", RAD_OPD_IN, 0 }, + { "sorted_tok", RAD_OPD_IN, 0 }, + { "expert_offset", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "w_scale", RAD_OPD_WEIGHT, 0 }, + { "w_odd", RAD_OPD_WEIGHT, 0 }, + { "w_odd_scale", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pMoeGemmQ[] = { P_INT("n_expert"), P_INT("top_k"), P_INTO("grid_rows"), + P_STRO("dtype") }; + + /* moe_gemm: the grouped GEMM with unquantised bf16 experts. a and w are bf16, no scales. */ +static const RadOperandSpec oMoeGemm[] = { { "a", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "sorted_tok", RAD_OPD_IN, 0 }, + { "expert_offset", RAD_OPD_IN, 0 }, + { "y", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pMoeGemm[] = { P_INT("n_expert"), P_INT("top_k") }; + +static const RadParamSpec pGdnRecurrent[] = { P_INT("q_len"), P_INT("head_k"), P_INT("head_v"), + P_INTO("n_head_v"), P_F64O("scale"), P_F64O("eps"), + P_F64O("l2_eps"), P_F64O("softplus_thr"), + P_STRO("act"), P_INTO("state_fp16"), P_STRO("state_form") }; +static const RadOperandSpec oGdnRecurrent[] = { { "q", RAD_OPD_IN, 0 }, + { "k", RAD_OPD_IN, 0 }, + { "v", RAD_OPD_IN, 0 }, + { "a", RAD_OPD_IN, 0 }, + { "b", RAD_OPD_IN, 0 }, + { "A_log", RAD_OPD_IN, 0 }, + { "dt_bias", RAD_OPD_IN, 0 }, + { "state", RAD_OPD_INOUT, 0 }, + { "state_idx", RAD_OPD_IN, 0 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "cu", RAD_OPD_IN, 0 }, + { "z", RAD_OPD_IN, 1 }, + { "norm_w", RAD_OPD_IN, 1 }, + { "o", RAD_OPD_OUT, 0 }, + { "o_q", RAD_OPD_OUT, 1 }, + { "o_scale", RAD_OPD_OUT, 1 } }; + /* ================================================================== the vocab and the sampler * @@ -352,6 +549,41 @@ static const RadOpSchema kSchemas[] = { "Symmetric int8 with one scale per row, max(amax, 1e-8) / 127, codes round-to-nearest-" "ties-to-even and saturating, stored in the step order the int8 WMMA reads. `asum` takes " "the group-major row sums the zero-pointed GEMMs reduce."), + SCHEMA("had_quant_act_i8", pQuant, oQuantFp8, + "A block Hadamard along K (width `group`), then per-row symmetric int8: the rotation " + "shrinks the row maximum, so int8 beats e4m3 on these activations."), + SCHEMA("gelu_mul_quant_i8", pMnDtype, oGeluMulQuantI8, + "gelu(gate) * up over a fused [M, 2n] projection, then per-row symmetric int8: the " + "tanh-form product rounded to bf16, the codes and scale taken over those values."), + SCHEMA("kv_len_trim", pKvLenTrim, oKvLenTrim, + "A batch's per-sequence context lengths less `trim`, floored at zero: the prefill " + "overlap's slice sees its own last row, not the step's. `trim` is the tail's extent."), + SCHEMA("qsa_tail_store", pQsaTailStore, oQsaTailStore, + "The QSA indexer's tail: the raw index keys of tokens that have not completed a block, " + "into a per-layer linear KV state. Position p lands at row p % ring; only the last " + "ring tokens of a sequence's chunk write."), + SCHEMA("gated_had_quant_i8", pGatedHadQuantI8, oGatedHadQuantI8, + "A gated product (mode 0 silu(a)*b, mode 1 sigmoid(a)*b), a block Hadamard along n, " + "then per-row symmetric int8: the rotation shrinks the row maximum, so int8 beats e4m3."), + SCHEMA("had_quant_act_fp8", pQuant, oQuantFp8, + "A 128-wide block Hadamard, then per-group E4M3: the rotation shrinks the group maximum " + "so e4m3's exponent bits carry the outliers better. A separate op, not a parameter."), + SCHEMA("gated_had_quant_fp8", pGatedQuant, oGatedQuant, + "A gated product (silu or sigmoid), a 128-wide block Hadamard, then per-group E4M3: the " + "rotation shrinks the group maximum so e4m3's exponent bits carry the outliers better."), + SCHEMA("quant_cols_fp8", pMnDtype, oQuantCols, + "E4M3 codes with one scale per column over every row: an attention's V for its fp8 P.V, " + "the group running down a column. Two passes over the rows, split into chunks."), + SCHEMA("had_quant_act_i8g", pQuant, oQuantFp8, + "A 128-wide block Hadamard, then per-group int8: the rotated form for the int8 trunk " + "GEMMs, the codes row-major (the i8a8 dot2 GEMM reads stored order)."), + SCHEMA("gated_had_quant_i8g", pGatedQuant, oGatedQuant, + "A gated product (silu or sigmoid), a 128-wide block Hadamard, then per-group int8: the " + "rotated int8 down projection, the codes row-major for the i8a8 dot2 GEMM."), + SCHEMA("rmsnorm_quant_i8", pRmsQuantI8, oRmsQuantI8, + "The RMS norm and the per-row int8 quantiser in one pass, optionally with the residual " + "junction in front (a post-norm, the residual add, a scalar): the sandwich-norm chain " + "as one dispatch, byte-identical to the unfused chain."), SCHEMA("quant_act_i8g", pQuant, oQuantFp8, "The same int8 code at `group` granularity: one f32 scale per (row, group), amax / 127, " "1 for an all-zero group, codes row-major."), @@ -369,6 +601,75 @@ static const RadOpSchema kSchemas[] = { "which the container states. `a_sum` and `b_ref` are the row sums a zero-pointed form " "reduces."), + SCHEMA("gdn_kkt_solve", pGdnKktSolve, oGdnKktSolve, + "A = (I + strict_lower(diag(beta) K K^T e^{g_i - g_j}))^-1 per 64-chunk: the gram once " + "per k head, the blocked inverse 16 -> 32 -> 64."), + + SCHEMA("gdn_chunk_scan", pGdnChunkScan, oGdnChunkScan, + "The gated delta net's chunked scan: the chunk's output and its closing state, the " + "recurrent state held in the wave matrix across the chunk loop."), + + SCHEMA("gdn_gated_rmsnorm", pGdnGatedRmsnorm, oGdnGatedRmsnorm, + "The gated RMS norm a gated-delta-net layer applies to its own output: " + "x * rsqrt(mean(x^2) + eps) * w * act(z), one (token, head) row of `channels`."), + + SCHEMA("gdn_gated_norm_had_quant_i8", pGdnGatedNormHq, oGdnGatedNormHq, + "The GDN block's gated RMS norm, block Hadamard and per-row int8 quantiser in one pass: " + "x * rsqrt(mean_head(x^2) + eps) * w * silu(z), rotated over `group` and quantised to " + "int8 with a per-row f32 `scale`."), + + SCHEMA("gdn_conv_prep", pGdnConvPrep, oGdnConvPrep, + "The GDN depthwise causal convolution (width 4, silu) plus the split, l2norm, gate " + "(g = -exp(A_log) softplus(a + dt_bias), beta = sigmoid(b)) and the per-chunk cumsum of " + "g, in one prefill kernel; the conv state is read at a sequence's first chunk and " + "rewritten from its last tokens."), + + SCHEMA("gdn_conv_update", pGdnConvUpdate, oGdnConvUpdate, + "The GDN depthwise causal convolution at decode: a speculative window over a rolling " + "conv-state buffer, read at the slot the last accepted token left and rewritten " + "shifted by one; writes q, k and v in their own layouts."), + + SCHEMA("gdn_recurrent_update", pGdnRecurrent, oGdnRecurrent, + "The gated-delta-net recurrent state update at decode: g = -exp(A_log) softplus(a + " + "dt_bias), beta = sigmoid(b), q/k l2-normalised, S *= e^g, u = beta (v - S k), S += u " + "k^T, o = S q, per token against a paged fp32 state cache; the gated RMS norm is " + "folded in when `z` and `norm_w` are present."), + SCHEMA("expert_scale", pExpertScale, oExpertScale, + "Each routing weight times its expert's own per-expert scale, in place: the router's " + "renormalised top-k weight scaled by the [n_expert] table, an out-of-table id reading " + "zero."), + SCHEMA("router_topk", pMoeRouterTopk, oMoeRouterTopk, + "Softmax over the expert logits, the top_k by value (ties to the lower id), and the " + "kept weights renormalised to sum to one when `norm`."), + SCHEMA("moe_scatter", pMoeScatter, oMoeScatter, + "The routed slots' stable counting sort: expert_ids to sorted_tok, the exclusive " + "expert_offset prefix, and the expert_count. An id outside the slice is dropped to the " + "tail; `protect` places its experts last."), + + SCHEMA("moe_gather", pMoeGather, oMoeGather, + "Fold the expert outputs back to the token: y[t,c] = sum_j expert_w[t,j] * " + "y_expert[slot(t,j), c], the slots from sorted_tok. An optional shared arm adds " + "shared[t,c] * act(gate[t]). bf16 in and out."), + + SCHEMA("router_topk_scatter", pRouterTopkScatter, oRouterTopkScatter, + "The router top-k and the counting sort as one op: the selection over the whole " + "n_expert logits, then the sort over this rank's n_local slice. expert_w is the " + "selection output the sort reads."), + + SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid, + "The GLM-style router: scores = sigmoid(logits), the selection on scores + bias, the " + "kept weights the scores scaled by route_scale (renormalised if `norm`). Ties to the " + "lower id; n_expert <= 512."), + + SCHEMA("moe_gemm_q", pMoeGemmQ, oMoeGemmQ, + "The grouped quantised GEMM: y[i] = a[sorted_tok[i]/top_k] @ w_e^T with a per-(row, " + "grid-of-K) scale fold, e the expert of sorted row i. E4M3 operands upcast to f16 in " + "registers; the even experts are `w` / `w_scale`, the odd `w_odd` / `w_odd_scale`."), + + SCHEMA("moe_gemm", pMoeGemm, oMoeGemm, + "The grouped GEMM with unquantised experts: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, e " + "the expert of sorted row i. bf16 a and w, f32 accumulate over the whole of K, bf16 out."), + SCHEMA("rmsnorm_quant_fp8", pRmsQuantFp8, oRmsQuantFp8, "RMS norm with an optional residual add, then the E4M3 quantiser, in one pass. The " "residual sum is stored as bf16 before the variance reads it, so the norm is taken over " @@ -476,6 +777,100 @@ static const int64_t kWv[] = { 1, 2, 4, 8 }; * latency, not reuse. RDNA3 has no transposed-load instruction, so this axis only switches the cache * hints on the plain 128-bit stream. */ static const int64_t kNt[] = { 0, 1 }; +/* The implementation arm. 0 is the dot2 pair path the row has always run; 1 is the 16x16x16 + * wave matrix (V_WMMA) where the ISA has a tile for the row's dtype. The arm is a point like + * the rest: the tuner walks it per shape per machine, an untuned install runs the dot2 arm, + * and a dtype with no tile simply has no legal point 1 (gemm_tune_valid). */ +static const int64_t kImpl[] = { 0, 1 }; +/* The m64 band's axes: row tiles per block and column tiles a wave. NPW 1 and 4 only: the + * kernel's activation re-read is 4*MT/NPW, and the instantiations in between cost registers + * without buying a ratio. */ +static const int64_t kMb[] = { 1, 2, 3, 4 }; +static const int64_t kNpw[] = { 1, 4 }; +/* The accumulator: 0 = the f32 arm, 1 = the bf16 arm (the 16x16x16 half-precision-accumulate + * tile; its 8 live elements sit in the even indices of the v16short accumulator, the epilogue + * reads only those). The axis is the selector; the tuner walks it per shape per machine. */ +static const int64_t kAcc[] = { 0, 1 }; +/* The kernel-implementation arms of a row that ships several kernels for one contract. Two arms: + * the table/codec decode and its per-byte ALU twin. Three arms: the grouped E4M3 GEMM's 16x16 tile + * (LDS table), the same tile with the ALU decode, and the 16x128 block. Four arms: the bf16 tiled + * row's fdot2 tile (table), the same tile (ALU), the 128x128 wave-matrix tile, and the 64-row + * wave-matrix kernel. The axis is the selector, as the rest are: an untuned install runs arm 0. */ +static const int64_t kImpl2[] = { 0, 1 }; +static const int64_t kImpl3[] = { 0, 1, 2 }; +static const int64_t kImpl4[] = { 0, 1, 2, 3 }; +/* The MoE GEMM's row block: 16 (decode), 32, 64 (a tall prefill). A taller block reads the weight + * T/mrows times, so the tune picks per shape; 64 is the untuned default (the tall band's best). */ +static const int64_t kMrows[] = { 16, 32, 64 }; +static const RadTunable tMoeGemm[] = { + { "mrows", kMrows, NELEM(kMrows), 64, "the block's row count; the weight is read T/mrows times" }, +}; +/* The per-wave register budget: 128 is the 8-wave cap on gfx11 (1024 VGPRs/SIMD), 512 the natural + * allocation. It is a compile-time attribute, so each legal point is its own compiled kernel; see + * the kernels' budget comments for the measurements. */ +static const int64_t kVgpr[] = { 128, 512 }; +static const RadTunable tMoeGemmBf16[] = { + { "mrows", kMrows, NELEM(kMrows), 64, "the block's row count; the weight is read T/mrows times" }, + { "vgpr", kVgpr, NELEM(kVgpr), 512, "the per-wave register budget: 128 is the 8-wave cap, 512 natural" }, + { "acc", kAcc, NELEM(kAcc), 0, + "the WMMA accumulator: 0 = f32, 1 = the half-precision tile (a documented low-precision mode: " + "the loss grows with k depth, no throughput gain; see the README)" }, +}; +static const RadTunable tMoeGemmFp8[] = { + { "vgpr", kVgpr, NELEM(kVgpr), 128, "the per-wave register budget: 128 is the 8-wave cap, 512 natural" }, + { "acc", kAcc, NELEM(kAcc), 0, + "the WMMA accumulator: 0 = f32, 1 = the half-precision tile (a documented low-precision mode: " + "the loss grows with k depth, no throughput gain; see the README)" }, +}; +/* Every mrows is legal: the kernel clamps the tail, so the tune is free to pick any point. */ +static int moe_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + (void)p; (void)n_p; (void)c; (void)n_c; return 1; +} +/* Only the compiled (mrows, vgpr) points are legal: <32> has both budgets (the capped one measures + * +38% at T=N=K=4096 NE=8), while <16> and <64> have the natural allocation only -- they measure + * 7-8% slower under the cap, because their spill traffic outweighs the extra wave. */ +static int moe_bf16_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + (void)p; (void)n_p; + const long long mrows = rad_param_geti(c, n_c, "mrows", 64); + const long long vgpr = rad_param_geti(c, n_c, "vgpr", 512); + if (vgpr == 128 && mrows != 32) return 0; + return 1; +} +/* A single implementation axis: the kernel the row runs. No geometry interaction, so any arm is + * legal at any point. */ +static const RadTunable tImpl2[] = { + { "impl", kImpl2, NELEM(kImpl2), 0, + "0 = the table/codec decode, 1 = the per-byte ALU decode" } }; +static const RadTunable tImpl4[] = { + { "impl", kImpl4, NELEM(kImpl4), 0, + "0 = the 128x128 fdot2 tile (table decode), 1 = the same tile, per-byte ALU decode, 2 = the " + "128x128 wave-matrix tile, 3 = the 64-row wave-matrix kernel" } }; +static int impl_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + (void)p; (void)n_p; + const long long impl = rad_param_geti(c, n_c, "impl", 0); + return impl >= 0 && impl <= 3; +} +/* The grouped E4M3 GEMM's three kernels: arm 0 the 16x16 tile with the LDS decode table, arm 1 + * the same tile with the per-byte ALU decode, arm 2 the 16x128 block with the F32 scales folded. + * The vgpr / acc axes are arm 2's (the block's register budget and accumulator); on arms 0 and 1 + * they are pinned to their defaults so the tuner does not spend time on an axis the arm ignores. */ +static const RadTunable tMoeGemmQ[] = { + { "impl", kImpl3, NELEM(kImpl3), 0, + "0 = the 16x16 tile, LDS decode table, 1 = the same tile, per-byte ALU decode, 2 = the 16x128 " + "block, F32 scales folded in f32" }, + { "vgpr", kVgpr, NELEM(kVgpr), 128, "the block's per-wave register budget (arm 2 only)" }, + { "acc", kAcc, NELEM(kAcc), 0, + "the WMMA accumulator: 0 = f32, 1 = the half-precision tile (arm 2 only; a documented " + "low-precision mode, the loss grows with k depth)" } }; +static int moe_q_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_c) { + (void)p; (void)n_p; + const long long impl = rad_param_geti(c, n_c, "impl", 0); + const long long vgpr = rad_param_geti(c, n_c, "vgpr", 128); + const long long acc = rad_param_geti(c, n_c, "acc", 0); + if (impl < 0 || impl > 2 || acc < 0 || acc > 1) return 0; + if (impl == 2) return (vgpr == 128 || vgpr == 512); + return vgpr == 128; +} /* No `kb` axis: only a GEMM that stages a K slab through LDS has a slab width to tune, and the * skinny rows stream the weight through registers. */ @@ -483,6 +878,21 @@ static const RadTunable tGemmM16[] = { { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, { "wv", kWv, NELEM(kWv), 8, "waves per block" }, { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, + { "impl", kImpl, NELEM(kImpl), 0, "0 = dot2 pairs, 1 = the 16x16x16 wave matrix" }, +}; +/* The m64 band: the wave-matrix kernel's own axes. There is no `impl` -- the band is the + * wave matrix, and the dot2 row's band ends where this one begins. The block is `wv * 32` + * threads; the k split is a block split over grid.y, so `sk` costs grid size, not workgroup + * size, and the validity check bounds the two separately. */ +static const RadTunable tGemmM64[] = { + { "sk", kSk, NELEM(kSk), 1, "split-K slabs of whole 128-wide groups" }, + { "wv", kWv, NELEM(kWv), 8, "waves per block" }, + { "mb", kMb, NELEM(kMb), 1, "row tiles per block" }, + { "npw", kNpw, NELEM(kNpw), 1, "column tiles a wave: 1 or 4" }, + { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, + { "acc", kAcc, NELEM(kAcc), 0, + "accumulator: 0 = f32, 1 = the half-precision tile (a documented low-precision mode: the " + "loss grows with k depth, no throughput gain; see the README)" }, }; /* No `wv` axis: the quantised kernel's launcher uses a fixed block of eight waves, because its * weight decode (sixteen codes a lane into eight dot2) fills a wave's issue budget at any block @@ -490,6 +900,7 @@ static const RadTunable tGemmM16[] = { static const RadTunable tGemmQ[] = { { "sk", kSk, NELEM(kSk), 0, "split-K slices; 0 is the widest legal for this K" }, { "nt", kNt, NELEM(kNt), 1, "non-temporal weight streaming" }, + { "impl", kImpl, NELEM(kImpl), 0, "0 = dot2 pairs, 1 = the 16x16x16 wave matrix" }, }; /* Cross-axis legality, in one place so the tuner, the scratch hook and the launch agree. A split's @@ -500,13 +911,48 @@ static int gemm_tune_valid(const RadParam* p, int n_p, const RadParam* c, int n_ const long long K = rad_param_getdim(p, n_p, "K", 0); const long long sk = rad_param_geti(c, n_c, "sk", 0); const long long wv = rad_param_geti(c, n_c, "wv", 8); - if (K <= 0 || wv < 1 || wv > 8) return 0; - const long long unit = rad_param_getdim(p, n_p, "group", 0) > 0 - ? rad_param_getdim(p, n_p, "group", 0) - : 8; + const long long impl = rad_param_geti(c, n_c, "impl", 0); + if (K <= 0 || wv < 1 || wv > 8 || impl < 0 || impl > 1) return 0; + /* The wave-matrix arm exists where the ISA has a tile for the row's dtype: the bf16 and f16 + * skinny rows and the w8a8 grid. The other dtypes have no 16x16x16 form on this ISA, and a + * point the kernel would refuse is a point the tuner should not spend. */ + if (impl == 1) { + const char* dt = rad_param_gets(p, n_p, "dtype", 0); + if (!dt || (std::strcmp(dt, "bf16") && std::strcmp(dt, "f16") && std::strcmp(dt, "w8a8"))) + return 0; + } + long long unit = rad_param_getdim(p, n_p, "group", 0) > 0 + ? rad_param_getdim(p, n_p, "group", 0) + : 8; + /* The wave-matrix arm's slab is a 16-k step, wider than the dot2 pair group's 8. */ + if (impl == 1 && unit < 16) unit = 16; return sk >= 0 && (sk == 0 || K % (sk * unit) == 0); } +/* The m64 band's cross-axis legality, in one place so the tuner and the launch agree. The slab + * is whole 128-wide groups; the split is a block split, so the workgroup is WV*32 threads, and + * the one shape the kernel's lowering cannot carry -- four column tiles a wave with more than + * one row tile -- is declined here as well as at the launch. */ +static int gemm_tune_valid_m64(const RadParam* p, int n_p, const RadParam* c, int n_c) +{ + const long long K = rad_param_getdim(p, n_p, "K", 0); + const long long sk = rad_param_geti(c, n_c, "sk", 1); + const long long wv = rad_param_geti(c, n_c, "wv", 8); + const long long mb = rad_param_geti(c, n_c, "mb", 1); + const long long npw = rad_param_geti(c, n_c, "npw", 1); + const long long nt = rad_param_geti(c, n_c, "nt", 1); + const long long acc = rad_param_geti(c, n_c, "acc", 0); + if (K <= 0) return 0; + if (sk < 1 || sk > 32) return 0; + if (wv < 1 || wv > 32) return 0; + if (mb < 1 || mb > 4) return 0; + if (npw != 1 && npw != 4) return 0; + if (nt < 0 || nt > 1) return 0; + if (acc != 0) return 0; + if (npw == 4 && mb > 1) return 0; + return K % (sk * 128) == 0; +} + /* The chosen point, read back. `TUNE` falls back to the axis's default when the core appended * nothing, so a caller with no tuned key runs what an untuned install runs. */ static long long tune_i(const RadArgs* a, const RadTunable* t, int n, const char* key) { @@ -525,6 +971,17 @@ extern "C" void r3d_cfg_gemm(const RadArgs* a, R3dGemmCfg* out) { out->sk = TUNE(a, tGemmM16, "sk"); out->kb = 0; out->nt = TUNE(a, tGemmM16, "nt"); + out->impl = TUNE(a, tGemmM16, "impl"); +} +extern "C" void r3d_cfg_moe(const RadArgs* a, R3dMoeCfg* out) { + out->mrows = TUNE(a, tMoeGemm, "mrows"); + out->vgpr = TUNE(a, tMoeGemmBf16, "vgpr"); /* 512 natural where the row has no vgpr axis */ + out->acc = TUNE(a, tMoeGemmBf16, "acc"); /* 0 where the row has no acc axis */ +} +extern "C" void r3d_cfg_moe_q(const RadArgs* a, R3dMoeQCfg* out) { + out->impl = TUNE(a, tMoeGemmQ, "impl"); + out->vgpr = TUNE(a, tMoeGemmQ, "vgpr"); + out->acc = TUNE(a, tMoeGemmQ, "acc"); } extern "C" void r3d_cfg_split(const RadArgs* a, R3dSplitCfg* out) { out->splits = TUNE(a, tGemmM16, "sk"); @@ -646,6 +1103,25 @@ static const RadConstraint cQuantI8[] = { C_IN("dtype", "bf16"), C_EQ("group" C_DIV("n", 16) }; static const RadConstraint cQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", R3D_W8_GROUP), C_DIV("n", 4) }; +static const RadConstraint cHadQuantI8[] = { C_IN("dtype", "bf16"), C_GE("group", 128), + C_LE("group", 512), C_DIV("n", 16) }; +static const RadConstraint cGeluMulQuantI8[] = { C_IN("dtype", "bf16"), C_DIV("n", 16) }; +static const RadConstraint cKvLenTrim[] = { C_GE("max_seqs", 1), C_LE("max_seqs", 64) }; +static const RadConstraint cQsaTailStore[] = { C_IN("dtype", "bf16"), C_GE("seqs", 1) }; +/* group is the block width: the kernel instantiates 128, 256 and 512 (the shim declines the + * DIV-legal 384, which no wave form serves). */ +static const RadConstraint cGatedHadQuantI8[] = { C_IN("dtype", "bf16"), C_DIV("group", 128), + C_GE("group", 128), C_LE("group", 512), + C_DIV("n", 16) }; +static const RadConstraint cHadQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", 128), + C_EQ("n", 128) }; +static const RadConstraint cGatedHadQuantFp8[] = { C_IN("dtype", "bf16"), C_EQ("group", 128), + C_EQ("n", 128) }; +static const RadConstraint cQuantCols[] = { C_IN("dtype", "bf16"), C_DIV("n", 8) }; +static const RadConstraint cHadQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", 128), C_EQ("n", 128) }; +static const RadConstraint cGatedHadQuantI8g[] = { C_IN("dtype", "bf16"), C_EQ("group", 128), + C_EQ("n", 128) }; +static const RadConstraint cRmsQuantI8[] = { C_IN("dtype", "bf16"), C_DIV("n", 16) }; /* Not `C_IN("act", "silu sigmoid")`: `act` is optional on the op (a graph may carry libref's * integer `mode` instead, and libref defaults to silu), so a band with neither would match no row. * The shim reads `act`, then `mode`, then defaults to silu, and refuses gelu, which this unit has no @@ -666,12 +1142,60 @@ static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", * `intermediate_size`) vary. */ static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 2), C_GE("N", 1) }; +static const RadConstraint cGemmM16F16[] = { C_IN("dtype", "f16"), C_GE("M", 1), C_LE("M", 16), + C_DIV("K", 2), C_GE("N", 1) }; +/* The a16 band: the 16x16x16 f16 tile's M, the group's K, the tile's N. K divisible by 128 + * because the slab is a whole (scale, zero) group; N by 16 because a wave's column tile is a + * tile. */ +static const RadConstraint cGemmM64W4A16A[] = { C_GE("M", 1), C_LE("M", 64), C_DIV("K", 128), + C_DIV("N", 16), C_IN("dtype", "w4a16_asym") }; +/* The 5-bit row: the 4-bit row's band, ParoQuant's int5. */ +static const RadConstraint cGemmM64W5A16[] = { C_GE("M", 1), C_LE("M", 64), C_DIV("K", 128), + C_DIV("N", 16), C_IN("dtype", "w5a16") }; + +/* The gated-delta-net preamble: the chunk width and the key head size are compiled in. */ +static const RadConstraint cGdnKktC64[] = { C_GE("M", 1), C_EQ("head_k", 128), C_EQ("chunk", 64) }; + +/* The chunked scan: the tile is compiled in for both head sizes and the chunk width. */ +static const RadConstraint cGdnChunkScanC64[] = { C_GE("M", 1), C_EQ("head_k", 128), + C_EQ("head_v", 128), C_EQ("chunk", 64) }; +static const RadConstraint cGdnGatedRmsnorm[] = { C_GE("M", 1), C_EQ("channels", 128) }; +static const RadConstraint cGdnGatedNormHq[] = { C_GE("M", 1), C_EQ("head_dim", 128) }; +static const RadConstraint cGdnConvW4[] = { C_GE("M", 1), C_EQ("head_k", 128), C_EQ("head_v", 128), + C_EQ("conv_width", 4) }; +static const RadConstraint cGdnConvUpdW4[] = { C_GE("q_len", 1), C_EQ("head_k", 128), + C_EQ("head_v", 128), C_EQ("conv_width", 4) }; +static const RadConstraint cGdnRecurrent[] = { C_GE("q_len", 1), C_EQ("head_k", 128), + C_EQ("head_v", 128) }; +static const RadConstraint cExpertScaleBf16[] = { C_IN("dtype", "bf16"), C_GE("top_k", 1), + C_LE("top_k", 64), C_GE("n_expert", 1) }; +static const RadConstraint cMoeRouterTopkBf16[] = { C_IN("dtype", "bf16"), C_GE("top_k", 1), + C_LE("top_k", 32), C_GE("n_expert", 1), + C_LE("n_expert", 512) }; +static const RadConstraint cMoeScatter[] = { C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1) }; +/* The grouped E4M3 GEMM: the model's `fp8a8f32` experts (E4M3 codes, f32 scales per 128 of K, + * the kServed table in arch/common/rad_block_moe_fp8.h). The `mxfp4a8` experts (E2M1 weights, + * E8M0 scales) are a different dtype and a different row. */ +static const RadConstraint cMoeGemmQ[] = { C_IN("dtype", "fp8a8f32"), C_GE("n_expert", 1), + C_GE("top_k", 1) }; +static const RadConstraint cMoeGemmMxfp4[] = { C_IN("dtype", "mxfp4a8"), C_GE("n_expert", 1), + C_GE("top_k", 1) }; +static const RadConstraint cMoeGather[] = { C_GE("M", 1), C_GE("n", 1), C_GE("top_k", 1), + C_IN("dtype", "bf16") }; +static const RadConstraint cRouterTopkScatter[] = { C_GE("M", 1), C_GE("n_expert", 1), + C_GE("top_k", 1), C_GE("n_local", 1), + C_LE("n_expert", 512), C_IN("dtype", "bf16") }; +static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_GE("n_expert", 1), + C_GE("top_k", 1), C_LE("n_expert", 512), + C_IN("dtype", "bf16") }; +static const RadConstraint cMoeGemmBf16[] = { C_GE("n_expert", 1), C_GE("top_k", 1) }; /* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the * head's dtype is a property of the weight (libref checks it with a `check_dtypes` hook). A * constraint on a key the band lacks does not hold, which would leave only the host kernel and the * engine would refuse to start, so the shim refuses an unsupported dtype instead. * `n_embd % 32` is the entry's chunk rule, stated so a band outside it is refused at declare rather - * than at launch. `n_vocab >= 4` is the store's granularity (16-byte runs); a narrower band (a + * at launch. `n_vocab >= 4` is the store's granularity (16-byte runs); a narrower band (a * shard's padding, a 1-id test vocabulary) is refused here. Above that floor the grid spans the * vocabulary at every M, so every vocabulary width runs the same kernel. */ static const RadConstraint cLogitsGemm[] = { C_GE("M", 1), C_GE("n_vocab", 4), @@ -704,6 +1228,12 @@ static const RadConstraint cGemmQW8A8M16[] = { C_IN("dtype", "w8a8"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 128), C_GE("N", 1) }; +/* The w8a8 wave-matrix arm at prefill heights. 17 <= M <= 127 complements cGemmQW8A8M16's + * M <= 16, so the two rows never compete for a band. K % 128 is the scale group. */ +static const RadConstraint cGemmQW8A8M64[] = { C_IN("dtype", "w8a8"), + C_GE("M", 17), C_LE("M", 127), + C_DIV("K", 128), C_GE("N", 1) }; + /* The tiled bf16 GEMM at prefill heights. M >= 17 complements cGemmM16's M <= 16, so the two rows * never compete for a band: the skinny shape (a wave a run of columns, the weight streamed through * registers) suits up to 16 rows and the 128x128 tile suits more. K % 32 is the tile's k-chunk and @@ -1116,6 +1646,117 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r3d_rad_quant_act_i8g, nullptr, nullptr, nullptr, r3d_shape_quant_act_i8g }, +{ "had_quant_act_i8_bf16", "had_quant_act_i8", "quant", + "a block Hadamard along K, then per-row symmetric int8: the rotation shrinks the row maximum", + "group 128/256/512, n a multiple of 16; the FWHT runs once per wave (K/group <= 8) so its DPP " + "exchanges stay out of a loop; the codes in the int8 WMMA step order", + "bf16 in, i8 codes, f32 scale per row", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cHadQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_had_quant_act_i8, nullptr, nullptr, nullptr, + r3d_shape_had_quant_act_i8 }, + +{ "gelu_mul_quant_i8_bf16", "gelu_mul_quant_i8", "quant", + "gelu(gate) * up over a fused [M, 2n] projection, then per-row symmetric int8", + "the tanh-form product (0.5*g*(1+tanh(k0*(g+k1*g^3)))) rounded to bf16, the absmax, scale and " + "codes taken over those values; n a multiple of 16, codes in the int8 WMMA step order", + "bf16 gate_up, i8 codes, f32 scale per row, optional bf16 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGeluMulQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_gelu_mul_quant_i8, nullptr, nullptr, nullptr, + r3d_shape_gelu_mul_quant_i8 }, + +{ "kv_len_trim_i32", "kv_len_trim", "kv", + "per-sequence context lengths less `trim`, floored at zero: the slice sees its own last row", + "one workgroup of 64, a thread a sequence; `trim` is the tail operand's extent, its values " + "unread; max_seqs <= 64", + "i32 seqused, tail (extent), out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKvLenTrim), NOTUNE, + nullptr, nullptr, r3d_rad_kv_len_trim, nullptr, nullptr, nullptr, + r3d_shape_kv_len_trim }, + +{ "qsa_tail_store_bf16", "qsa_tail_store", "kv", + "the QSA indexer's tail into a per-layer linear KV state: position p lands at row p % ring", + "one block a token; the sequence by a linear cu_seqlens scan; only the last ring tokens of a " + "chunk write (p and p + ring share a row); ring = ratio + n_spec", + "bf16 k, i32 pos/cu/sidx, bf16 state [slots,1,ring,n] inout", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQsaTailStore), NOTUNE, + nullptr, nullptr, r3d_rad_qsa_tail_store, nullptr, nullptr, nullptr, + r3d_shape_qsa_tail_store }, + +{ "gated_had_quant_i8_bf16", "gated_had_quant_i8", "quant", + "a gated product (silu(a)*b or sigmoid(a)*b), a block Hadamard along n, then per-row int8", + "mode 0 down_proj's input, mode 1 o_proj's input; the rotation shrinks the row maximum; the " + "FWHT runs once per wave (n == group) so its DPP stages stay out of a loop; codes in step order", + "bf16 a (gate) and b (up, optional fused), i8 codes, f32 scale per row", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatedHadQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_gated_had_quant_i8, nullptr, nullptr, nullptr, + r3d_shape_gated_had_quant_i8 }, + +{ "had_quant_act_fp8_bf16", "had_quant_act_fp8", "quant", + "a 128-wide block Hadamard, then per-group E4M3: the rotation shrinks the group maximum", + "n == group == 128 (single-group form, the FWHT runs once per wave so its DPP stages stay out of " + "a loop); the codes row-major, the scale carrying the 1/sqrt(128)", + "bf16 in, E4M3 codes, f32 scale per group", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cHadQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_had_quant_act_fp8, nullptr, nullptr, nullptr, + r3d_shape_had_quant_act_fp8 }, + +{ "gated_had_quant_fp8_bf16", "gated_had_quant_fp8", "quant", + "a gated product (silu or sigmoid), a 128-wide block Hadamard, then per-group E4M3", + "n == group == 128 (single-group form, the FWHT runs once per wave so its DPP stages stay out of " + "a loop); the gated product in fp32, the codes row-major, the scale carrying the 1/sqrt(128)", + "bf16 gate_up [M,2n], E4M3 codes, f32 scale per group, optional bf16 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatedHadQuantFp8), NOTUNE, + nullptr, nullptr, r3d_rad_gated_had_quant_fp8, nullptr, nullptr, nullptr, + r3d_shape_gated_had_quant_fp8 }, + +{ "quant_cols_fp8_bf16", "quant_cols_fp8", "quant", + "E4M3 codes with one scale per column over every row: an attention's V for its fp8 P.V", + "two passes over the rows split into 32 chunks: the column amax partials, then the scales and " + "codes; a thread owns eight columns; the software e4m3 codec (RDNA3 has no fp8 builtin)", + "bf16 in, E4M3 codes, f32 scale per column; kColChunks * n floats of scratch", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cQuantCols), NOTUNE, + nullptr, nullptr, r3d_rad_quant_cols_fp8, r3d_quant_cols_fp8_scratch, nullptr, nullptr, + r3d_shape_quant_cols_fp8 }, + +{ "had_quant_act_i8g_bf16", "had_quant_act_i8g", "quant", + "a 128-wide block Hadamard, then per-group int8: the rotated form for the int8 trunk GEMMs", + "n == group == 128 (single-group form, the FWHT runs once per wave so its DPP stages stay out of " + "a loop); the codes row-major for the i8a8 dot2 GEMM, the scale carrying the 1/sqrt(128)", + "bf16 in, int8 codes (row-major), f32 scale per group", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cHadQuantI8g), NOTUNE, + nullptr, nullptr, r3d_rad_had_quant_act_i8g, nullptr, nullptr, nullptr, + r3d_shape_had_quant_act_i8g }, + +{ "gated_had_quant_i8g_bf16", "gated_had_quant_i8g", "quant", + "a gated product (silu or sigmoid), a 128-wide block Hadamard, then per-group int8", + "n == group == 128 (single-group form, the FWHT runs once per wave so its DPP stages stay out of " + "a loop); the gated product in fp32, the codes row-major for the i8a8 dot2 GEMM, the scale " + "carrying the 1/sqrt(128)", + "bf16 gate_up [M,2n], int8 codes (row-major), f32 scale per group, optional bf16 product", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGatedHadQuantI8g), NOTUNE, + nullptr, nullptr, r3d_rad_gated_had_quant_i8g, nullptr, nullptr, nullptr, + r3d_shape_gated_had_quant_i8g }, + +{ "rmsnorm_quant_i8_bf16", "rmsnorm_quant_i8", "quant", + "the RMS norm and the per-row int8 quantiser in one pass, optionally with the residual junction", + "post-norm, residual add, scalar, then the norm and the int8 codes in the w4a8 fragment order; " + "every intermediate rounded to bf16 so the chain is byte-identical; one workgroup a row", + "bf16 x and optional residual (inout), weight, i8 codes, f32 scale per row, optional bf16 out", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRmsQuantI8), NOTUNE, + nullptr, nullptr, r3d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr, + r3d_shape_rmsnorm_quant_i8 }, + { "gated_quant_fp8_bf16", "gated_quant_fp8", "quant", "silu(gate) * up over a fused [M, 2n] projection, quantised in the same pass", "group 128; n a multiple of 4; the product is rounded to bf16 before its amax, as every fused " @@ -1170,6 +1811,325 @@ static const RadKernelInfo kKernels[] = { [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, nullptr, nullptr, r3d_shape_gemm_nt }, +/* ------------------------------------------------------------------ r3d_gemm_f16_nt_m16.hip + * + * The same shape over an f16 checkpoint: the bytes are the dot's native pair, so the dot2 arm + * stages a straight copy and the weight streams into the fold with no widening between. The + * wave-matrix arm rides the ISA's 16x16x16 f16 tile, the `impl` point, the way the bf16 row's + * does on its tile. + */ +{ "gemm_nt_f16_m16", "gemm_nt", "gemm", + "a[M,K] @ b[N,K]^T for the decode and verify heights, f32 accumulate, one narrowing at the store", + "M <= 16; a wave a run of N columns, one output element a lane, k ascending in pairs; split-K " + "over scratch with the partials reduced in split order; a ragged K runs the scalar tail at sk=1", + "f16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " + "about 0.3% of a long-K output lands one f16 store ulp from the reference's, and no output is " + "further. f16 is the pair the dot takes, so there is no widening to price and the row's range " + "is f16's: a checkpoint whose values sit outside it is not a checkpoint this row serves", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_M16, + ROW(cGemmM16F16), tGemmM16, NELEM(tGemmM16), gemm_tune_valid, + nullptr, nullptr, r3d_rad_gemm_nt_f16_m16, + [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, + nullptr, nullptr, r3d_shape_gemm_nt }, + +/* ------------------------------------------------------------------ r3d_gemm_w4a16_nt_m64.hip + * + * The 4-bit weight against an f16 activation, at the verify and small-prefill heights: the + * weight's codes run the 16x16x16 f16 tile through the 1024-offset dequant, and the group + * scale lands on the f32 accumulator after the zero point's cancellation. The weight arrives + * in the hook's fragment order, permuted at load. + */ +{ "gemm_nt_q_w4a16asym_m64", "gemm_nt_q", "gemm", + "a[M,K] @ dequant(wq)[N,K]^T: unsigned 4-bit codes with an f16 scale and an integer zero per " + "128 of K, against an f16 activation, f32 accumulate, one narrowing at the store", + "1 <= M <= 64, N a multiple of 16, K a multiple of the group and of the split's slab; the " + "weight read in the container's stored order, no permutation; split-K slabs reduced by a " + "second kernel over a grow-only pool", + "f16 a, U4 wq with the f16 scale and the integer zero per (row, 128 of K), bf16 y, fp32 " + "accumulation; the dequant is the integer code minus the zero, exact, and the store is the " + "only narrowing", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmM64W4A16A), tGemmM64, NELEM(tGemmM64), gemm_tune_valid_m64, + nullptr, nullptr, r3d_rad_gemm_nt_q_w4a16_m64, + nullptr, r3d_layout_gemm_nt_q_w4a16, r3d_relayout_gemm_nt_q_w4a16, + nullptr, nullptr }, + +/* ------------------------------------------------------------------ r3d_gemm_w5a16_nt_m64.hip + * + * The 5-bit weight against an f16 activation: the 4-bit row with a fifth bit per code, + * ParoQuant's int5. The fifth bits ride a plane of their own, one word a (tile, 64 of K, + * lane), joined behind the (scale, zero) pair. + */ +{ "gemm_nt_q_w5a16_m64", "gemm_nt_q", "gemm", + "a[M,K] @ dequant(wq, hi)[N,K]^T: 5-bit codes with an f16 scale and an integer zero per " + "128 of K, against an f16 activation, f32 accumulate, one narrowing at the store", + "1 <= M <= 64, N a multiple of 16, K a multiple of the group and of the split's slab; the " + "weight read in the container's stored order, the fifth bits a plane of their own, no " + "permutation; split-K slabs reduced by a second kernel over a grow-only pool", + "f16 a, U4 wq with the f16 scale, the integer zero per (row, 128 of K) and the fifth-bit " + "plane per (tile, 64 of K, lane), bf16 y, fp32 accumulation; the dequant is the integer " + "code minus the zero, exact, and the store is the only narrowing", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmM64W5A16), tGemmM64, NELEM(tGemmM64), gemm_tune_valid_m64, + nullptr, nullptr, r3d_rad_gemm_nt_q_w5a16_m64, + nullptr, r3d_layout_gemm_nt_q_w5a16, r3d_relayout_gemm_nt_q_w5a16, + nullptr, nullptr }, + +/* ------------------------------------------------------------------ r3d_gdn_kkt_solve_c64.hip + * + * The gated-delta-net chunk preamble: the gram and the blocked inverse in one kernel, the + * FLA pair's 64x64 fp32 intermediate kept in LDS. + */ +{ "gdn_kkt_solve_c64", "gdn_kkt_solve", "gdn", + "A = (I + strict_lower(diag(beta) K K^T e^{g_i - g_j}))^-1 per 64-chunk of a gated delta net", + "head_k 128, chunk 64, H a multiple of head groups; the gram is computed once per k head and " + "scaled per v head, the inverse blocked 16 -> 32 -> 64 with the 16-blocks by fp32 forward " + "substitution and the merges by the card's 16x16x16 wave matrix", + "bf16 k and A, f32 beta and g, i32 cu; the padding rows and columns are masked to -inf so a " + "partial last chunk's NaN cannot ride the WMMA merges into live rows", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnKktC64), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_kkt_solve, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + +/* ------------------------------------------------------------------ r3d_gdn_chunk_scan_k128_v128_c64.hip + * + * The gated-delta-net chunked scan: the chunk's output and its closing state, the recurrent + * state in wave-matrix accumulators across the chunk loop. + */ +{ "gdn_chunk_scan_k128_v128_c64", "gdn_chunk_scan", "gdn", + "O = scale*ge*(Q@S) + sA@V', S = e^{g_last}S + V'^T@(gs*K) per 64-chunk of a gated delta net, " + "V' = A@W, W = beta*(V - ge*U), U = K@S, sA = the kkt_solve row's output with the " + "scale*e^{g_i-g_j} score decay", + "head_k 128, head_v 128, chunk 64, H a multiple of head groups; the state stays in " + "accumulators across the chunk loop, so only q, k, v, A, g, beta, the state cache and o " + "touch HBM; two workgroups per v head each carry 64 of the v dimension", + "bf16 q, k, v, A and o, f32 g and beta, f32 or f16 state cache (the operand's dtype), i32 cu " + "and the optional state slot index; a row's slot comes from the cache manager, not the batch " + "position, and a padded row owns no state", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnChunkScanC64), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_chunk_scan, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_gdn_gated_rmsnorm_h128.hip + * + * The gated RMS norm a gated-delta-net layer applies to its own output before the output + * projection: one wave per (token, head) row, a barrier-free wave sum and one 8-byte access per + * lane for each load and the store. + */ +{ "gdn_gated_rmsnorm_h128", "gdn_gated_rmsnorm", "gdn", + "x * rsqrt(mean(x^2) + eps) * w * act(z), one (token, head) row of 128 channels", + "channels 128; act is silu (the default) or sigmoid; the gate may be a flat projection row or a " + "column slice of a fused [q|k|v|z] row", + "bf16 x, z and o, f32 w; one wave per row, four channels per lane", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnGatedRmsnorm), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_gated_rmsnorm, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_gdn_gated_norm_had_quant_i8.hip + * + * The GDN block's gated RMS norm, block Hadamard and per-row int8 quantiser in one pass: the + * out_proj input on the linear-attention layers. One workgroup per row; the rotation is a + * wave-local FWHT in registers, the int8 scale a whole-row max. + */ +{ "gdn_gated_norm_had_quant_i8", "gdn_gated_norm_had_quant_i8", "gdn", + "x * rsqrt(mean_head(x^2) + eps) * w * silu(z), Hadamard-rotated over `group`, int8-quantised", + "head_dim 128, `group` the rotation width (128, 256 or 512); the RMS is per 128-head, the " + "rotation and the int8 scale per token over the flattened row", + "bf16 x and z, f32 w, i8 q, f32 scale; the gate may be a column slice of a fused [q|k|v|z] row " + "(`zgrp`, `zblk`)", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnGatedNormHq), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_gated_norm_hq_i8, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_gdn_conv_w4_h128.hip + * + * The GDN depthwise causal convolution (width 4, silu) and the work fused around it: the prefill + * prep (conv + split + l2norm + gate + cumsum) and the decode update (a speculative window over a + * rolling conv-state buffer). + */ +{ "gdn_conv_prep_w4_h128", "gdn_conv_prep", "gdn", + "The GDN depthwise causal convolution (width 4, silu) plus split, l2norm, gate and per-chunk " + "cumsum in one prefill kernel", + "head_k 128, head_v 128, conv_width 4, chunk 64; the conv state is read at a sequence's first " + "chunk and rewritten from its last tokens", + "bf16 x, w, conv_state and q/k/v, f32 A_log, dt_bias, g and beta, a and b_gate bf16 or f32; the " + "conv output is rounded to bf16 before the norm and the store", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnConvW4), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_conv_prep, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + +{ "gdn_conv_update_w4_h128", "gdn_conv_update", "gdn", + "The GDN depthwise causal convolution at decode: a speculative window over a rolling conv-state " + "buffer", + "head_k 128, head_v 128, conv_width 4; the state buffer is read at the slot the last accepted " + "token left and rewritten shifted by one", + "bf16 x, w, conv_state and q/k/v; `state_idx` the rolling buffer's slot, `num_accepted` the " + "window's read offset", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnConvUpdW4), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_conv_update, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + +{ "expert_scale_bf16", "expert_scale", "moe", + "Each routing weight times its expert's own per-expert scale, in place", + "the router's renormalised top-k weight scaled by the [n_expert] table, an out-of-table id " + "reading zero", + "bf16 ids (i32), w_e and ew; one thread per element", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cExpertScaleBf16), NOTUNE, + nullptr, nullptr, r3d_rad_expert_scale_bf16, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + +{ "moe_router_topk_bf16", "router_topk", "moe", + "Softmax over the expert logits, the top_k by value, renormalised if `norm`", + "one wave per row; top_k passes of a wave minimum (ties to the lower id)", + "bf16 logits and expert_w; i32 expert_ids; n_expert <= 512, top_k <= 32", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeRouterTopkBf16), NOTUNE, + nullptr, nullptr, r3d_rad_moe_router_topk_bf16, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + { "moe_router_topk_scatter", "router_topk_scatter", "moe", + "The router top-k and the counting sort as one op: the selection over the whole n_expert logits, " + "then the sort over this rank's n_local slice", + "phase 1 the top-k (one wave per row), phase 2 the small counting sort (one workgroup); the " + "selection's expert_w is the sort's input", + "bf16 logits [M,ne] and expert_w [M,k]; i32 expert_ids [M,k], sorted_tok [M*k], expert_offset " + "[nl+1], expert_count [nl]; n_expert <= 512, n_local <= n_expert, T <= 1024", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRouterTopkScatter), NOTUNE, + nullptr, nullptr, r3d_rad_router_topk_scatter, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + { "moe_router_sigmoid_topk", "router_sigmoid_topk", "moe", + "The GLM-style router: scores = sigmoid(logits), the selection on scores + bias, the kept " + "weights the scores scaled by route_scale (renormalised if norm)", + "one wave per row; a 64-bit selection key (the select monotone bits, the complemented id), the " + "scores staged in LDS; ties to the lower id", + "bf16 logits [M,ne], f32 bias [ne]; i32 expert_ids [M,k], bf16 expert_w [M,k]; n_expert <= 512, " + "top_k <= 32", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRouterSigmoid), NOTUNE, + nullptr, nullptr, r3d_rad_router_sigmoid_topk, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + +{ "moe_scatter_small", "moe_scatter", "moe", + "The routed slots' stable counting sort (the small form, one workgroup)", + "histogram in LDS, an exclusive prefix over the expert counts, each slot placed by its rank " + "inside its expert's run; T <= 1024", + "i32 expert_ids, sorted_tok, expert_offset, expert_count; n_expert <= 512", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeScatter), NOTUNE, + nullptr, nullptr, r3d_rad_moe_scatter, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_moe_gather.hip */ + { "moe_gather", "moe_gather", "moe", + "Fold the expert outputs back to the token: y[t,c] = sum_j expert_w[t,j] * " + "y_expert[slot(t,j),c]", + "one block per token, the slot table (the inverse of sorted_tok, scanned in LDS) and the expert " + "weights hoisted so the per-column loads pipeline; the optional shared arm adds shared*act(gate)", + "bf16 y_expert [Te,n], expert_w [Mw,top_k] (bf16 or f32), sorted_tok [T], optional shared/gate, " + "bf16 y [M,n]; top_k <= 64", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGather), NOTUNE, + nullptr, nullptr, r3d_rad_moe_gather, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_moe_gemm_q.hip + * + * The grouped quantised GEMM: y[i] = a[sorted_tok[i]/top_k] @ w_e^T with a per-(row, grid-of-K) + * scale fold, e the expert of sorted row i. E4M3 operands staged compact and upcast to f16 in + * registers (the 256-entry decode table), the f16 wave-matrix, the even experts in `w` and the + * odd in `w_odd`. + */ + { "moe_gemm_q_e4m3", "moe_gemm_q", "moe", + "The grouped quantised GEMM over the model's fp8a8f32 experts: y[i] = a[sorted_tok[i]/top_k] @ " + "w_e^T with a per-(row, grid-of-K) scale fold, e the expert of sorted row i", + "three kernels, one contract, the tune's impl axis picks: 0 = 16x16 tiles through LDS, the E4M3 " + "operands staged compact (8-bit) and upcast to f16 in registers through the block's 512-byte " + "decode table; 1 = the same tile, the E4M3 decode in registers (the per-byte ALU formula, no LDS " + "table); 2 = the 16x128 block, the E4M3 operands widened exactly to f16 and the F32 scales " + "folded in f32 per 128 of K. All arms run the f16 wave-matrix (f32 accumulate) and walk the runs " + "in the block's 16 rows, so a block spanning several experts (short runs) is correct; the even " + "experts are `w` / `w_scale`, the odd `w_odd` / `w_odd_scale`, at index e/2", + "E4M3 a and the weight tables, f32 a_scale per (row, 128 of K), f32 w_scale per (grid_rows " + "columns, 128 of K); K % 128; grid_rows 1 (w4a8's per-row) or 128 (fp8a8's per-128x128 tile); " + "y f32 in sorted order", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmQ), tMoeGemmQ, NELEM(tMoeGemmQ), moe_q_tune_valid, + nullptr, nullptr, r3d_rad_moe_gemm_q, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + + /* ------------------------------------------------------------------ r3d_moe_gemm_bf16.hip */ + { "moe_gemm_bf16", "moe_gemm", "moe", + "The grouped GEMM with unquantised experts: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, e the expert " + "of sorted row i", + "16x16 tiles through LDS, the bf16 operands staged and loaded straight into the bf16 wave-matrix " + "fragments (f32 accumulate over the whole of K); the block walks the runs in its 16 rows, so a " + "block spanning several experts (short runs) is correct; the weight is the checkpoint's own bytes " + "([n_expert, N, K] row-major, no layout hook)", + "bf16 a and w, bf16 y in sorted order; K a multiple of 64, the N tail clamped", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmBf16), tMoeGemmBf16, NELEM(tMoeGemmBf16), moe_bf16_tune_valid, + nullptr, nullptr, r3d_rad_moe_gemm_bf16, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_moe_gemm_mxfp4a8.hip */ + { "moe_gemm_mxfp4a8", "moe_gemm_q", "moe", + "The grouped GEMM with canonical MXFP4 experts: y[i] = a[sorted_tok[i]/top_k] @ w_e^T, e the " + "expert of sorted row i", + "16x16 tiles through LDS; the E4M3 activation and the E2M1 weight (decoded exactly to E4M3) " + "upcast to f16 in registers, the f16 wave-matrix (f32 accumulate); the E8M0 weight scales fold " + "in f32 per 32 of K; the block walks the runs in its 16 rows; the even experts are `w` / " + "`w_scale`, the odd `w_odd` / `w_odd_scale`, at index e/2", + "E4M3 a with f32 a_scale per (row, 128 of K); E2M1 (packed, two a byte) weight tables with E8M0 " + "w_scale per (grid_rows columns, 32 of K); K % 128; y bf16 in sorted order", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cMoeGemmMxfp4), NOTUNE, + nullptr, nullptr, r3d_rad_moe_gemm_mxfp4a8, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + + /* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip + * + * The gated-delta-net recurrent state update at decode: the per-token state step against a paged + * fp32 state cache, the state in registers (one thread per v row and half its k range), the + * gated RMS norm folded into the epilogue. + */ +{ "gdn_recurrent_update_k128_v128", "gdn_recurrent_update", "gdn", + "The gated-delta-net recurrent state update at decode: S *= e^g, u = beta (v - S k), S += u k^T, " + "o = S q per token", + "head_k 128, head_v 128, fp32 state cache; the state stays in registers, one thread per v row " + "and half its k range; the gated RMS norm is folded in when z and norm_w are present", + "bf16 q, k, v, o and a/b (or f32 a/b), f32 A_log, dt_bias and the state cache; `state_idx` the " + "per-token slot, `num_accepted` the window offset", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGdnRecurrent), NOTUNE, + nullptr, nullptr, r3d_rad_gdn_recurrent_update, + nullptr, nullptr, nullptr, + nullptr, nullptr }, + /* ------------------------------------------------------------------ r3d_gemm_fp8a16_nt_m1.hip * * The same shape against a block-scaled weight. The E4M3 codes are widened to f16 exactly and @@ -1202,13 +2162,14 @@ static const RadKernelInfo kKernels[] = { { "gemm_nt_q_mxfp4a8_m16", "gemm_nt_q", "gemm", "fp8 a against OCP-MXFP4 weights: e2m1 codes, two a byte, with an e8m0 scale per 32 of K, the " "block's partials scaled and summed in ascending k", - "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane, the lane's two 32-blocks " + "M <= 16, K a multiple of 128; one wave a weight row, 64 codes a lane, the tune's impl axis " + "picks the E4M3 decode (0 = the LDS table, 1 = the per-byte ALU formula), the lane's two 32-blocks " "scaled at the block boundary", "fp8_e4m3 a with an f32 scale per (row, 128 of K), fp4_e2m1 codes with an e8m0 scale per (row, " "32 of K) -- `b_ref`, the same exponent plane, is accepted and ignored, bf16 y, fp32 " "accumulation; a reserved e8 (0, 255) is refused", RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, - ROW(cGemmQMxfp4a8M16), NOTUNE, + ROW(cGemmQMxfp4a8M16), tImpl2, NELEM(tImpl2), impl_tune_valid, nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_m16, nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, @@ -1232,12 +2193,27 @@ static const RadKernelInfo kKernels[] = { "the pair fold at the group boundary, the group terms scaled in the epilogue", "I8 a in the step order with an f32 scale per row, I8 codes b with an f16 scale per (row, 128 " "of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, and the store is " - "the only narrowing; no zero point, so no a_sum; M > 16 is declared out", + "the only narrowing; no zero point, so no a_sum; M > 16 is declared out. The tune's impl axis " + "picks the arm: 0 = the dot2 pair path, 1 = the 16x16x16 wave matrix", RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, - ROW(cGemmQW8A8M16), NOTUNE, + ROW(cGemmQW8A8M16), tImpl2, NELEM(tImpl2), impl_tune_valid, nullptr, nullptr, r3d_rad_gemm_nt_q_w8a8_m16, nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w8a8 }, + { "gemm_nt_q_w8a8_m64", "gemm_nt_q", "gemm", + "the symmetric 8-bit weight grid at prefill heights: signed int8 codes against int8 " + "activations, the group's integer sub-sum scaled once by the activation's row scale and the " + "weight's group scale", + "17 <= M <= 127, K a multiple of 128; two 16-row tiles a wave, the weight column loaded once " + "per 16-k step and reused over the tiles, the group terms scaled in the epilogue", + "I8 a in the step order with an f32 scale per row, I8 codes b with an f16 scale per (row, 128 " + "of K), bf16 y, fp32 accumulation; the sub-sums are exact integers under 2^24, and the store is " + "the only narrowing; no zero point, so no a_sum", + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQW8A8M64), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_q_w8a8_m64, + nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_w8a8 }, + { "silu_mul_bf16", "silu_mul", "elem", "silu(gate) * up over one fused gate_up plane, the gate the first half", "any n; a workgroup a row; the activation is not narrowed before the product, as ref's is not " @@ -1293,7 +2269,8 @@ static const RadKernelInfo kKernels[] = { "the n-grams the history shows inside the window are banned to -inf", "a workgroup a row; the prefix compare over n-1 tokens, the ban landing on s[idx+n-1]; the " "whitelist is removed from the banned set BEFORE the ban, so an exempt id survives; the window is " - "dry_penalty_last_n, and n = 0 bans nothing", + "the row's own ngram pair's second word (0 clamps to the whole staged span), and n = 0 bans " + "nothing", "f32 logits, f32 params, i32 history, i32 n-gram pairs, an optional i32 whitelist plane", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cSampleF32), NOTUNE, @@ -1322,8 +2299,9 @@ static const RadKernelInfo kKernels[] = { "are not written", "f32 logits, f32 params, f32 stats; k <= 64 is the pool's depth and above it the shim refuses " "(RAD_E_UNSUPPORTED); on a row that contains a NaN the reference's list freezes at the first k it " - "saw, because upper_bound over a NaN returns end and every later compare then fails -- this kernel " - "reports the row's true k-best, a divergence a plane has to be fed NaNs to reach", + "saw: once a NaN sits in the k-list's tail, every later real value fails the tail's compare " + "(anything against NaN is false) and is never inserted -- this kernel reports the row's true " + "k-best, a divergence a plane has to be fed NaNs to reach", RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cSampleLogprobs), NOTUNE, nullptr, nullptr, r3d_rad_sample_logprobs, nullptr, nullptr, nullptr, @@ -1356,7 +2334,7 @@ static const RadKernelInfo kKernels[] = { "bf16 q and out, bf16 cache, i32 block_table and seqused", RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, ROW(cAttnBf16Prefill), NOTUNE, - nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + nullptr, nullptr, r3d_rad_attn_prefill_h128, nullptr, nullptr, nullptr, /* no split: no scratch */ r3d_shape_attn_paged }, { "attn_paged_fp8_decode", "attn_paged", "attn", @@ -1379,7 +2357,7 @@ static const RadKernelInfo kKernels[] = { "scale 1.0)", RAD_DOMAIN_DEVICE, R3D_PRIO_ATTN_PREFILL, ROW(cAttnFp8Prefill), NOTUNE, - nullptr, nullptr, r3d_rad_attn_prefill_h128, attn_scratch, nullptr, nullptr, + nullptr, nullptr, r3d_rad_attn_prefill_h128, nullptr, nullptr, nullptr, /* no split: no scratch */ r3d_shape_attn_paged }, @@ -1645,7 +2623,7 @@ static const RadKernelInfo kKernels[] = { "with a zero plane is w2a8's grid and is refused at the shim's own line; so is a scale block that " "is not 128x128, which is gemm_nt_q's grid", RAD_DOMAIN_DEVICE, R3D_PRIO_VOCAB_M1, - ROW(cLogitsGemm), NOTUNE, + ROW(cLogitsGemm), tImpl2, NELEM(tImpl2), impl_tune_valid, nullptr, nullptr, r3d_rad_logits_gemm_bf16, nullptr, r3d_layout_logits_head, r3d_relayout_logits_head, r3d_shape_logits_gemm_bf16 }, @@ -1658,7 +2636,9 @@ static const RadKernelInfo kKernels[] = { { "gemm_nt_q_fp8a8_tiled", "gemm_nt_q", "gemm", "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the group sub-sum from the raw codes and one " "scale per group, which is the reference's law and the reason the codes are never pre-scaled", - "128x128 tiles through LDS, 64 f32 accumulators a lane, k in 32-code chunks, the family's 8-element " + "the tune's impl axis picks the decode: 0 = the block's 512-byte E4M3->f16 table, 1 = the " + "per-byte ALU formula. 128x128 tiles through LDS, 64 f32 accumulators a lane, k in 32-code chunks, " + "the family's 8-element " "XOR swizzle on the staged rows; both sides decode through the block's 512-byte E4M3->f16 table " "and leave staging as f16 with their scale folded in -- a_scale per staged row, b_scale one scalar " "per tile, because the tile's 128 columns are exactly the scale plane's row extent and 32 divides " @@ -1670,7 +2650,7 @@ static const RadKernelInfo kKernels[] = { "83% of outputs are bit-exact, 99.93% land within the fold plus one store ulp, none beyond. The " "fold is v_mul_f16, never f16x2_pack, which rounds toward zero and flushes subnormals", RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, - ROW(cGemmQFP8Tiled), NOTUNE, + ROW(cGemmQFP8Tiled), tImpl2, NELEM(tImpl2), impl_tune_valid, nullptr, nullptr, r3d_rad_gemm_nt_q_fp8_tiled, nullptr, r3d_layout_gemm_q_fp8_weight, r3d_relayout_gemm_q_fp8_weight, r3d_shape_gemm_nt_q }, @@ -1678,8 +2658,9 @@ static const RadKernelInfo kKernels[] = { "y[M,N] = a[M,K] @ dequant(b)^T at prefill heights, the weight in OCP MXFP4: e2m1 codes, two a " "byte, one e8m0 scale per 32 of K; the 32-block partial scales at the block boundary and the " "blocks sum in ascending k", - "128x128 tiles through LDS, 64 f32 accumulators a lane for the block partials and 64 more for the " - "running sum, k in 32-code chunks -- one OCP 32-block a chunk -- the family's 8-element XOR " + "the tune's impl axis picks the decode: 0 = the block's 512-byte table, 1 = the per-byte ALU " + "formula. 128x128 tiles through LDS, 64 f32 accumulators a lane for the block partials and 64 more " + "for the running sum, k in 32-code chunks -- one OCP 32-block a chunk -- the family's 8-element XOR " "swizzle on the staged rows; the codes unpack to e4m3 through eight fixed magnitude bytes and " "decode through the block's 512-byte table, a_scale folded per staged row, the e8 read at " "staging and held in registers for the flush", @@ -1688,8 +2669,8 @@ static const RadKernelInfo kKernels[] = { "The e2m1 magnitude is exact in e4m3, the code products are " "exact in f16, the 32-block partial scales by a power of two in f32, and the store is the only " "narrowing; a reserved e8 (0, 255) is refused", - RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, - ROW(cGemmQMxfp4a8Tiled), NOTUNE, + RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_FP8, + ROW(cGemmQMxfp4a8Tiled), tImpl2, NELEM(tImpl2), impl_tune_valid, nullptr, nullptr, r3d_rad_gemm_nt_q_mxfp4a8_tiled, nullptr, nullptr, nullptr, r3d_shape_gemm_nt_q_mxfp4a8 }, @@ -1697,18 +2678,22 @@ static const RadKernelInfo kKernels[] = { * host. The exactness is the m16 row's, because it is the same dot. */ { "gemm_nt_bf16_tiled", "gemm_nt", "gemm", "a[M,K] @ b[N,K]^T at prefill heights, f32 accumulate, one narrowing at the store", - "128x128 tiles through LDS, 8x8 f32 accumulators a lane, k ascending in 32-code chunks, the " - "partials closed in the tile; M <= 16 stays with gemm_nt_bf16_m16, whose wave-per-run-of-columns " + "the tune's impl axis picks the kernel: 0 = 128x128 tiles through LDS, 8x8 f32 accumulators a " + "lane, k ascending in 32-code chunks, the partials closed in the tile; 1 = the same tile, the bf16 " + "decode in registers (the per-byte ALU formula); 2 = the same tile on the wave-matrix (eight 16x16 " + "tiles a wave); 3 = the 16-column-tile wave-matrix kernel, MT 16-row tiles a block (the M = 17..127 " + "band); M <= 16 stays with gemm_nt_bf16_m16, whose wave-per-run-of-columns " "shape is the right one there -- the two rows' M ranges are complements, so neither competes for " "the other's band", "bf16 a, b and y, fp32 accumulation; the pair is folded into the accumulator by one rounding, so " "about 0.3% of a long-K output lands one bf16 store ulp from the reference's, and no output is " "further", RAD_DOMAIN_DEVICE, R3D_PRIO_GEMM_TILED, - ROW(cGemmNTTiled), NOTUNE, + ROW(cGemmNTTiled), tImpl4, NELEM(tImpl4), impl_tune_valid, nullptr, nullptr, r3d_rad_gemm_nt_bf16_tiled, nullptr, nullptr, nullptr, r3d_shape_gemm_nt }, + }; /* ================================================================== the exports diff --git a/libr3d/r3d_sample_f32.hip b/libr3d/r3d_sample_f32.hip index dd4ec1b1..5571e42e 100644 --- a/libr3d/r3d_sample_f32.hip +++ b/libr3d/r3d_sample_f32.hip @@ -597,7 +597,7 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void sample_topk_kernel( if (x0 != x0) { /* topk_next's seed, as in row_topk */ for (uint32_t r = 0; r < n_cand; ++r) { if (r >= k) { hole(r); continue; } - ir[r] = vocab_off; + ir[r] = 0; /* cand_idx is local: the NaN logit's column */ vr[r] = x0; if (pp) { pp[2 * r] = vocab_off; pp[2 * r + 1] = *(const int32_t*)&x0; } } @@ -788,8 +788,11 @@ __global__ __launch_bounds__(kThreads) R3D_WAVES(4) void narrow_kernel( if (s_ev[i] * inv >= th) { cnt += 1.0f; last = (float)i; } } /* Count and last index are order-free (a sum of small integers and a max), so no serial - * loop is needed; candidates are re-tested below from the same `s_ev`. */ + * loop is needed; candidates are re-tested below from the same `s_ev`. The two + * reductions share the `red` scratch: block_sum ends on a read of it and block_max + * begins on a write, so the barrier between them is the read/write fence. */ const float n_above = block_sum(cnt, red); + __syncthreads(); const float hi = block_max(last, red); if (n_above < 2.0f) return; /* needs two to exclude all but the least likely */ const int32_t keep = (int32_t)hi; diff --git a/libr3d/r3d_selftest.cpp b/libr3d/r3d_selftest.cpp index 7954e688..bbdb99b2 100644 --- a/libr3d/r3d_selftest.cpp +++ b/libr3d/r3d_selftest.cpp @@ -159,6 +159,16 @@ static void check_table() { const bool joined = 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16") || 0 == std::strcmp(k->name, "logits_gemm_bf16") || 0 == std::strcmp(k->name, "gemm_nt_q_fp8a8_tiled") + || 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_tiled") + || 0 == std::strcmp(k->name, "gemm_nt_q_w4a16asym_m64") + || 0 == std::strcmp(k->name, "gemm_nt_q_w5a16_m64"); + /* The query and the writer come as a pair, and the pair is the rule: a row with a hook must + * supply the relayout that produces the form the hook names (abi/rad_abi.h -- a query + * answering RAD_OK is a promise the loader keeps on the row's word), and no row may carry an + * unrelayout, because nothing in this library invents a format a tool would need to invert. + * A hook with a null writer is the failure the engine reports at load -- `could not produce + * 'output.weight' (rad.planes) from fp8_e4m3*bf16[128x128]: unsupported` -- and a relayout + * without a hook is a row repacking a weight nobody asked to have repacked. || 0 == std::strcmp(k->name, "gemm_nt_q_w2a8_tiled"); /* A layout hook and its relayout writer come as a pair (abi/rad_abi.h: a query answering * RAD_OK promises the loader the writer produces that form; a hook without one fails at @@ -393,6 +403,18 @@ static void check_shapes() { { "quant_act_fp8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, { "quant_act_i8", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, { "quant_act_i8g", { PI("M", 8), PI("n", 4096), PI("group", 128), PS("dtype", "bf16") } }, + { "had_quant_act_i8", { PI("M", 8), PI("n", 1024), PI("group", 128), PS("dtype", "bf16") } }, + { "gelu_mul_quant_i8", { PI("M", 8), PI("n", 1024), PS("dtype", "bf16") } }, + { "kv_len_trim", { PI("trim", 4), PI("max_seqs", 8) } }, + { "qsa_tail_store", { PI("M", 16), PI("n", 128), PI("ratio", 4), PI("ring", 8), + PI("seqs", 2), PS("dtype", "bf16") } }, + { "gated_had_quant_i8", { PI("M", 8), PI("n", 128), PI("group", 128), PS("dtype", "bf16") } }, + { "had_quant_act_fp8", { PI("M", 8), PI("n", 128), PI("group", 128), PS("dtype", "bf16") } }, + { "gated_had_quant_fp8", { PI("M", 8), PI("n", 128), PI("group", 128), PS("dtype", "bf16") } }, + { "quant_cols_fp8", { PI("M", 32), PI("n", 128), PS("dtype", "bf16") } }, + { "had_quant_act_i8g", { PI("M", 8), PI("n", 128), PI("group", 128), PS("dtype", "bf16") } }, + { "gated_had_quant_i8g", { PI("M", 8), PI("n", 128), PI("group", 128), PS("dtype", "bf16") } }, + { "rmsnorm_quant_i8", { PI("M", 8), PI("n", 128), PF("eps", 1e-6), PS("dtype", "bf16") } }, { "gated_quant_fp8", { PI("M", 8), PI("n", 11008), PI("group", 128), PS("dtype", "bf16"), PS("act", "silu") } }, { "dequant", { PI("M", 11008), PI("n", 4096), PI("group", 128), @@ -400,6 +422,7 @@ static void check_shapes() { { "rmsnorm_quant_fp8", { PI("M", 1792), PI("n", 5120), PF("eps", 1e-5), PI("group", 128), PS("dtype", "bf16") } }, { "gemm_nt", { PI("M", 8), PI("N", 11008), PI("K", 4096), PS("dtype", "bf16") } }, + { "gemm_nt", { PI("M", 8), PI("N", 11008), PI("K", 4096), PS("dtype", "f16") } }, { "gemm_nt_q", { PI("M", 8), PI("N", 11008), PI("K", 4096), PI("group", 128), PS("dtype", "fp8a16"), PI("pb1", 128), PI("pb2", 128) } }, /* The rest are MiniCPM5-2B's bands: vocab 130560, MLP 6144 wide, head 128 with 16 heads @@ -972,6 +995,1192 @@ static int build_w2a8(Case& c, const RadOpSchema* s) { #undef W_PS } +/* ------------------------------------------------------------------ the a16 band + * + * The 4-bit weight against an f16 activation. The coverage is the band a w4a16 checkpoint asks + * for once one runs: the codes are read where the container stores them, and the (scale, zero) + * pair reaches the row joined by rad_planes_relayout exactly as the loader will do. y is the + * only output and it is pre-filled with a bf16 NaN, so a kernel that never launches leaves its + * status RAD_OK behind and the NaN says the row did not run. */ +static int build_w4a16asym(Case& c, const RadOpSchema* s) { +#define W_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define W_PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + const long long M = 16, N = 11008, K = 4096, group = 128, G = K / group; + if (s->n_operands != 7) { fail("w4a16asym: the schema has %d operands, not 7", s->n_operands); + return 1; } + c.n_p = 0; + const RadParam pp[] = { W_PI("M", M), W_PI("N", N), W_PI("K", K), W_PI("group", group), + W_PS("dtype", "w4a16_asym") }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + RadEncoding e; + std::memset(&e, 0, sizeof e); + rad_enc_copy_str(e.scheme, "affine"); + e.n_planes = 3; + rad_enc_copy_str(e.plane[0].role, "codes"); + e.plane[0].dtype = RAD_U4; e.plane[0].kind = RAD_PLANE_TILED; + e.plane[0].block[0] = 1; e.plane[0].block[1] = 1; + rad_enc_copy_str(e.plane[1].role, "scale"); + e.plane[1].dtype = RAD_F16; e.plane[1].kind = RAD_PLANE_TILED; + e.plane[1].block[0] = 1; e.plane[1].block[1] = group; + rad_enc_copy_str(e.plane[2].role, "zero"); + e.plane[2].dtype = RAD_U8; e.plane[2].kind = RAD_PLANE_TILED; + e.plane[2].block[0] = 1; e.plane[2].block[1] = group; + const int sel_sz[2] = { 1, 2 }; + + /* The canonical planes, in the quantiser's own order: the codes the kernel reads where they + * lie, the scale and zero the row joins. */ + std::vector cd((size_t)N * K / 2); + std::vector sc((size_t)N * G); + std::vector ze((size_t)N * G); + uint32_t st = 0x41A15339u; + for (size_t i = 0; i < cd.size(); ++i) { + st = st * 1664525u + 1013904223u; + cd[i] = (uint8_t)((st & 0xF) | ((st >> 12) & 0xF0)); + } + for (size_t i = 0; i < sc.size(); ++i) { + st = st * 1664525u + 1013904223u; + sc[i] = f32_to_f16(0.001f + 0.01f * (float)((st >> 8) & 0xffffu) / 65536.0f); + ze[i] = (uint8_t)((st >> 16) & 0xFu); /* a zero that fits a 4-bit code */ + } + RadTensor ps[2] = {}; + const uint32_t pdt[2] = { RAD_F16, RAD_U8 }; + void* pdat[2] = { sc.data(), ze.data() }; + for (int i = 0; i < 2; ++i) { + ps[i].data = pdat[i]; ps[i].dtype = pdt[i]; ps[i].rank = 2; + ps[i].shape[0] = N; ps[i].shape[1] = G; + ps[i].stride[1] = 1; ps[i].stride[0] = G; + } + RadPlanesEntry en[RAD_ENC_MAX_PLANES]; + const long long jb = rad_planes_plan(&e, sel_sz, ps, 2, en); + if (jb <= 0) { fail("w4a16asym: rad_planes_plan refused the joined scale+zero"); return 1; } + std::vector jbytes((size_t)jb, 0); + if (rad_planes_relayout(&e, sel_sz, ps, 2, jbytes.data(), jb) != RAD_OK) { + fail("w4a16asym: rad_planes_relayout refused"); return 1; + } + + /* Schema order: a, a_scale (absent), b (the codes, in order), b_scale (the joined pair), + * y, a_sum (absent), b_ref (absent). */ + struct Slot { long long rows, cols; uint32_t dt; int nan; } q[7] = { + { M, K, RAD_F16, 0 }, { 0, 0, RAD_F32, 0 }, { N, K, RAD_U4, 0 }, + { jb, 1, RAD_F16, 0 }, { M, N, RAD_BF16, 1 }, { 0, 0, RAD_F32, 0 }, + { 0, 0, RAD_F32, 0 } }; + for (int o = 0; o < 7; ++o) { + if (!q[o].rows) { c.t[o] = RadTensor{}; continue; } + size_t bytes = o == 2 ? (size_t)N * K / 2 /* codes count elements, not bytes */ + : o == 3 ? (size_t)jb + : (size_t)q[o].rows * q[o].cols * dt_bytes(q[o].dt); + std::vector h(bytes, 0); + if (o == 2) std::memcpy(h.data(), cd.data(), bytes); + else if (o == 3) std::memcpy(h.data(), jbytes.data(), bytes); + else if (o == 0) { + uint16_t* hf = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) { + st = st * 1664525u + 1013904223u; + hf[i] = f32_to_f16(((float)((st >> 8) & 0xffffu) / 65536.0f - 0.5f) * 4.0f); + } + } + if (q[o].nan) { + uint16_t* b16 = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) b16[i] = 0x7fc0u; + } + /* The joined operand stays pinned, the mapped tier's shape: the shim reads its header + * where it lies and the kernel reads the same bytes over PCIe. */ + void* d = nullptr; + if (o == 3) { + if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { + fail("w4a16asym: hipHostMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); c.host.push_back(d); + std::memcpy(d, h.data(), bytes); + } else { + if (hipMalloc(&d, bytes) != hipSuccess) { fail("w4a16asym: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (hipMemcpy(d, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("w4a16asym: hipMemcpy in failed"); return 1; } + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = q[o].dt; + t.rank = (o == 3) ? 1 : 2; + t.shape[0] = q[o].rows; t.shape[1] = q[o].cols; + t.stride[1] = 1; t.stride[0] = q[o].cols; + if (o == 3) { t.shape[1] = 0; t.stride[0] = 1; } + } + return 0; +#undef W_PI +#undef W_PS +} + +/* The 5-bit row: the 4-bit case with the fifth-bit plane, [N/16][K/2] u32. */ +static int build_w5a16(Case& c, const RadOpSchema* s) { +#define W_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } +#define W_PS(k, v) { (k), RAD_P_STR, 0, 0, (v), 0.0 } + const long long M = 16, N = 11008, K = 4096, group = 128, G = K / group; + if (s->n_operands != 7) { fail("w5a16: the schema has %d operands, not 7", s->n_operands); + return 1; } + c.n_p = 0; + const RadParam pp[] = { W_PI("M", M), W_PI("N", N), W_PI("K", K), W_PI("group", group), + W_PS("dtype", "w5a16") }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + RadEncoding e; + std::memset(&e, 0, sizeof e); + rad_enc_copy_str(e.scheme, "affine"); + e.n_planes = 4; + rad_enc_copy_str(e.plane[0].role, "codes"); + e.plane[0].dtype = RAD_U4; e.plane[0].kind = RAD_PLANE_TILED; + e.plane[0].block[0] = 1; e.plane[0].block[1] = 1; + rad_enc_copy_str(e.plane[1].role, "scale"); + e.plane[1].dtype = RAD_F16; e.plane[1].kind = RAD_PLANE_TILED; + e.plane[1].block[0] = 1; e.plane[1].block[1] = group; + rad_enc_copy_str(e.plane[2].role, "zero"); + e.plane[2].dtype = RAD_U8; e.plane[2].kind = RAD_PLANE_TILED; + e.plane[2].block[0] = 1; e.plane[2].block[1] = group; + rad_enc_copy_str(e.plane[3].role, "hi"); + e.plane[3].dtype = RAD_U32; e.plane[3].kind = RAD_PLANE_TILED; + e.plane[3].block[0] = 1; e.plane[3].block[1] = group / 2; + const int sel_sz[3] = { 1, 2, 3 }; + + std::vector cd((size_t)N * K / 2); + std::vector sc((size_t)N * G); + std::vector ze((size_t)N * G); + std::vector hi((size_t)(N / 16) * (K / 2)); + uint32_t st = 0x5A11CE57u; + for (size_t i = 0; i < cd.size(); ++i) { + st = st * 1664525u + 1013904223u; + cd[i] = (uint8_t)((st & 0xF) | ((st >> 12) & 0xF0)); + } + for (size_t i = 0; i < sc.size(); ++i) { + st = st * 1664525u + 1013904223u; + sc[i] = f32_to_f16(0.001f + 0.01f * (float)((st >> 8) & 0xffffu) / 65536.0f); + ze[i] = (uint8_t)((st >> 16) & 0x1Fu); /* a zero that fits a 5-bit code */ + } + for (size_t i = 0; i < hi.size(); ++i) { + st = st * 1664525u + 1013904223u; + hi[i] = st; + } + RadTensor ps[3] = {}; + const uint32_t pdt[3] = { RAD_F16, RAD_U8, RAD_U32 }; + void* pdat[3] = { sc.data(), ze.data(), hi.data() }; + for (int i = 0; i < 3; ++i) { + ps[i].data = pdat[i]; ps[i].dtype = pdt[i]; ps[i].rank = 2; + ps[i].shape[0] = (i == 2) ? N / 16 : N; + ps[i].shape[1] = (i == 2) ? K / 2 : G; + ps[i].stride[1] = 1; ps[i].stride[0] = ps[i].shape[1]; + } + RadPlanesEntry en[RAD_ENC_MAX_PLANES]; + const long long jb = rad_planes_plan(&e, sel_sz, ps, 3, en); + if (jb <= 0) { fail("w5a16: rad_planes_plan refused the joined scale+zero+hi"); return 1; } + std::vector jbytes((size_t)jb, 0); + if (rad_planes_relayout(&e, sel_sz, ps, 3, jbytes.data(), jb) != RAD_OK) { + fail("w5a16: rad_planes_relayout refused"); return 1; + } + + struct Slot { long long rows, cols; uint32_t dt; int nan; } q[7] = { + { M, K, RAD_F16, 0 }, { 0, 0, RAD_F32, 0 }, { N, K, RAD_U4, 0 }, + { jb, 1, RAD_F16, 0 }, { M, N, RAD_BF16, 1 }, { 0, 0, RAD_F32, 0 }, + { 0, 0, RAD_F32, 0 } }; + for (int o = 0; o < 7; ++o) { + if (!q[o].rows) { c.t[o] = RadTensor{}; continue; } + size_t bytes = o == 2 ? (size_t)N * K / 2 + : o == 3 ? (size_t)jb + : (size_t)q[o].rows * q[o].cols * dt_bytes(q[o].dt); + std::vector h(bytes, 0); + if (o == 2) std::memcpy(h.data(), cd.data(), bytes); + else if (o == 3) std::memcpy(h.data(), jbytes.data(), bytes); + else if (o == 0) { + uint16_t* hf = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) { + st = st * 1664525u + 1013904223u; + hf[i] = f32_to_f16(((float)((st >> 8) & 0xffffu) / 65536.0f - 0.5f) * 4.0f); + } + } + if (q[o].nan) { + uint16_t* b16 = (uint16_t*)h.data(); + for (size_t i = 0; i < bytes / 2; ++i) b16[i] = 0x7fc0u; + } + void* d = nullptr; + if (o == 3) { + if (hipHostMalloc(&d, bytes, 0) != hipSuccess) { + fail("w5a16: hipHostMalloc(%zu) failed", bytes); return 1; } + c.dev.push_back(d); c.host.push_back(d); + std::memcpy(d, h.data(), bytes); + } else { + if (hipMalloc(&d, bytes) != hipSuccess) { fail("w5a16: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (hipMemcpy(d, h.data(), bytes, hipMemcpyHostToDevice) != hipSuccess) { + fail("w5a16: hipMemcpy in failed"); return 1; } + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = q[o].dt; + t.rank = (o == 3) ? 1 : 2; + t.shape[0] = q[o].rows; t.shape[1] = q[o].cols; + t.stride[1] = 1; t.stride[0] = q[o].cols; + if (o == 3) { t.shape[1] = 0; t.stride[0] = 1; } + } + return 0; +#undef W_PI +#undef W_PS +} + +/* The gated-delta-net preamble: two sequences of 65 tokens each (two chunks apiece, the second + * partial), four k heads and two v heads each, head_k 128, chunk 64. The gate decreases within a + * chunk as the kernel assumes; the output starts as NaN, so a row the solve does not write is a + * failure. */ +static int build_gdn_kkt(Case& c, const RadOpSchema* s) { +#define GK_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } + const long long M = 130, Hg = 4, H = 8, K = 128, C = 64; + if (s->n_operands != 5) { fail("gdn_kkt: the schema has %d operands, not 5", s->n_operands); + return 1; } + c.n_p = 0; + const RadParam pp[] = { GK_PI("M", M), GK_PI("head_k", K), GK_PI("chunk", C) }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x5A11CE57u; + std::vector hk((size_t)M * Hg * K); + for (auto& v : hk) { + st = st * 1664525u + 1013904223u; + v = f32_to_bf16(((float)((st >> 8) & 0xffffu) / 65536.0f - 0.5f) * 2.0f); + } + std::vector bt((size_t)M * H), gt((size_t)M * H); + for (size_t m = 0; m < M; ++m) + for (size_t h = 0; h < H; ++h) { + st = st * 1664525u + 1013904223u; + bt[m * H + h] = (float)((st >> 8) & 0xffffu) / 65536.0f; // 0..1 + gt[m * H + h] = -0.01f * (int)(m % 64); // decreasing in the chunk + } + const int cuv[3] = { 0, 65, (int)M }; + std::vector ha((size_t)M * H * C, 0x7fc0u); // NaN: an unwritten row shows + + struct { uint32_t dt; long long r0, r1; } q[5] = { + { RAD_BF16, M, Hg * K }, { RAD_F32, M, H }, { RAD_F32, M, H }, + { RAD_I32, 3, 1 }, { RAD_BF16, M, H * C } }; + for (int o = 0; o < 5; ++o) { + const size_t bytes = (size_t)q[o].r0 * q[o].r1 * dt_bytes(q[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_kkt: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (o == 0) std::memcpy(d, hk.data(), bytes); + else if (o == 1) std::memcpy(d, bt.data(), bytes); + else if (o == 2) std::memcpy(d, gt.data(), bytes); + else if (o == 3) std::memcpy(d, cuv, sizeof cuv); + else std::memcpy(d, ha.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = q[o].dt; + t.rank = (o == 3) ? 1 : (o == 0) ? 3 : 2; + if (o == 3) { t.shape[0] = 3; t.stride[0] = 1; } + else if (o == 0) { t.shape[0] = M; t.shape[1] = Hg; t.shape[2] = K; + t.stride[2] = 1; t.stride[1] = K; t.stride[0] = Hg * K; } + else { t.shape[0] = q[o].r0; t.shape[1] = q[o].r1; + t.stride[1] = 1; t.stride[0] = q[o].r1; } + } + return 0; +#undef GK_PI +} + +/* The chunked scan: the same geometry as the kkt case, with v and the state cache. The state + * starts random (an h0 the scan must carry through), ht must come back finite, and the output + * starts as NaN so an unwritten row is a failure. No state slot index: the cache is row + * indexed. */ +static int build_gdn_chunk_scan(Case& c, const RadOpSchema* s) { +#define GC_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } + const long long M = 130, Hg = 4, H = 8, K = 128, V = 128, C = 64; + if (s->n_operands != 11) { fail("gdn_chunk_scan: the schema has %d operands, not 11", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { GC_PI("M", M), GC_PI("head_k", K), GC_PI("head_v", V), + GC_PI("chunk", C) }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x51B2CE01u; + auto rnd16 = [&]() { st = st * 1664525u + 1013904223u; return (st >> 8) & 0xffffu; }; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hq((size_t)M * Hg * K), hk((size_t)M * Hg * K), + hv((size_t)M * H * V), hA((size_t)M * H * C); + for (auto& x : hq) x = f32_to_bf16((rndf() - 0.5f) * 0.5f); + for (auto& x : hk) x = f32_to_bf16((rndf() - 0.5f) * 0.5f); + for (auto& x : hv) x = f32_to_bf16((rndf() - 0.5f) * 0.5f); + // A: the kkt_solve output's shape -- a unit lower triangular with a small random fill. + for (size_t m = 0; m < M; ++m) + for (size_t h = 0; h < H; ++h) + for (int j = 0; j < C; ++j) { + const int i = m % C; + hA[m * H * C + h * C + j] = + (j == i) ? f32_to_bf16(1.0f) + : (j < i) ? f32_to_bf16((rndf() - 0.5f) * 0.1f) + : 0x0000u; + } + std::vector gt((size_t)M * H), btt((size_t)M * H); + for (size_t m = 0; m < M; ++m) + for (size_t h = 0; h < H; ++h) { + btt[m * H + h] = rndf(); // 0..1 + gt[m * H + h] = -0.01f * (int)(m % 64); // decreasing in the chunk + } + std::vector h0((size_t)M * H * V * K); + for (auto& x : h0) x = (rndf() - 0.5f) * 0.1f; + const int cuv[3] = { 0, 65, (int)M }; + std::vector ho((size_t)M * H * V, 0x7fc0u); // NaN: an unwritten row shows + + struct { uint32_t dt; long long r0, r1, r2; } qd[11] = { + { RAD_BF16, M, Hg * K, K }, // q + { RAD_BF16, M, Hg * K, K }, // k + { RAD_BF16, M, H * V, V }, // v + { RAD_BF16, M, H * C, C }, // A + { RAD_F32, M, H, 1 }, // g + { RAD_F32, M, H, 1 }, // beta + { RAD_F32, M * H, V * K, V * K }, // h0 [M, H, V*K] dense + { RAD_I32, 3, 1, 1 }, // cu + { RAD_BF16, M, H * V, V }, // o + { RAD_F32, M * H, V * K, V * K }, // ht + { RAD_I32, 0, 0, 0 } // state_idx: absent + }; + for (int o = 0; o < 10; ++o) { + const long long nel = (o == 6 || o == 9) ? M * H * V * K + : (o == 7) ? 3 + : qd[o].r0 * qd[o].r1 / qd[o].r2 * qd[o].r2; + const size_t bytes = (size_t)nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_chunk_scan: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (o == 0) std::memcpy(d, hq.data(), bytes); + else if (o == 1) std::memcpy(d, hk.data(), bytes); + else if (o == 2) std::memcpy(d, hv.data(), bytes); + else if (o == 3) std::memcpy(d, hA.data(), bytes); + else if (o == 4) std::memcpy(d, gt.data(), bytes); + else if (o == 5) std::memcpy(d, btt.data(), bytes); + else if (o == 6) std::memcpy(d, h0.data(), bytes); + else if (o == 7) std::memcpy(d, cuv, sizeof cuv); + else if (o == 8) std::memcpy(d, ho.data(), bytes); + else std::memcpy(d, h0.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 7) { t.rank = 1; t.shape[0] = 3; t.stride[0] = 1; } + else if (o == 6 || o == 9) { + t.rank = 3; t.shape[0] = M; t.shape[1] = H; t.shape[2] = V * K; + t.stride[2] = 1; t.stride[1] = V * K; t.stride[0] = H * V * K; + } else if (o == 0 || o == 1 || o == 2 || o == 3 || o == 8) { + t.rank = 3; t.shape[0] = M; t.shape[1] = qd[o].r1 / qd[o].r2; t.shape[2] = qd[o].r2; + t.stride[2] = 1; t.stride[1] = qd[o].r2; t.stride[0] = qd[o].r1; + } else { + t.rank = 2; t.shape[0] = M; t.shape[1] = H; + t.stride[1] = 1; t.stride[0] = H; + } + } + c.t[10] = RadTensor{}; // state_idx absent + return 0; +#undef GC_PI +} + +static int build_gdn_gated_rmsnorm(Case& c, const RadOpSchema* s) { +#define GR_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } + const long long M = 130, H = 10, C = 128; + if (s->n_operands != 4) { fail("gdn_gated_rmsnorm: the schema has %d operands, not 4", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { GR_PI("M", M), GR_PI("channels", C) }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x9E3779B9u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hx((size_t)M * C), hz((size_t)M * C); + for (auto& x : hx) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hz) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + std::vector hw(C); + for (auto& x : hw) x = (rndf() - 0.5f) * 2.0f; + std::vector ho((size_t)M * C, 0x7fc0u); // NaN: an unwritten row shows + + struct { uint32_t dt; long long r0, r1, r2; } qd[4] = { + { RAD_BF16, M, C, 1 }, // x [M, C] + { RAD_BF16, M, C, 1 }, // z [M, C] + { RAD_F32, C, 1, 1 }, // w [C] + { RAD_BF16, M, C, 1 } // o [M, C] + }; + for (int o = 0; o < 4; ++o) { + const long long nel = qd[o].r0 * qd[o].r1; + const size_t bytes = (size_t)nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_gated_rmsnorm: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (o == 0) std::memcpy(d, hx.data(), bytes); + else if (o == 1) std::memcpy(d, hz.data(), bytes); + else if (o == 2) std::memcpy(d, hw.data(), bytes); + else std::memcpy(d, ho.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 2) { t.rank = 1; t.shape[0] = C; t.stride[0] = 1; } + else { t.rank = 2; t.shape[0] = M; t.shape[1] = C; t.stride[1] = 1; t.stride[0] = C; } + } + return 0; +#undef GR_PI +} + +static int build_gdn_gated_norm_hq(Case& c, const RadOpSchema* s) { +#define GH_PI(k, v) { (k), RAD_P_INT, (long long)(v), 0, nullptr, 0.0 } + const long long M = 64, H = 8, C = 128, K = H * C; + if (s->n_operands != 5) { fail("gdn_gated_norm_had_quant_i8: the schema has %d operands, not 5", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { GH_PI("M", M), GH_PI("n", K), GH_PI("head_dim", C), + GH_PI("group", 128) }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0xC2B2AE35u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hx((size_t)M * K), hz((size_t)M * K); + for (auto& x : hx) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hz) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + std::vector hw(C); + for (auto& x : hw) x = (rndf() - 0.5f) * 2.0f; + std::vector hq((size_t)M * K, 0); + std::vector hs(M, 0.0f); + + struct { uint32_t dt; long long r0, r1; } qd[5] = { + { RAD_BF16, M, K }, // x [M, K] + { RAD_BF16, M, K }, // z [M, K] + { RAD_F32, C, 1 }, // w [C] + { RAD_I8, M, K }, // q [M, K] + { RAD_F32, M, 1 } // scale [M] + }; + for (int o = 0; o < 5; ++o) { + const long long nel = qd[o].r0 * qd[o].r1; + const size_t bytes = (size_t)nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_gated_norm_hq: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (o == 0) std::memcpy(d, hx.data(), bytes); + else if (o == 1) std::memcpy(d, hz.data(), bytes); + else if (o == 2) std::memcpy(d, hw.data(), bytes); + else if (o == 3) std::memcpy(d, hq.data(), bytes); + else std::memcpy(d, hs.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 2) { t.rank = 1; t.shape[0] = C; t.stride[0] = 1; } + else if (o == 4) { t.rank = 1; t.shape[0] = M; t.stride[0] = 1; } + else { t.rank = 2; t.shape[0] = M; t.shape[1] = K; t.stride[1] = 1; t.stride[0] = K; } + } + return 0; +#undef GH_PI +} + +static int build_gdn_conv_prep(Case& c, const RadOpSchema* s) { + const long long T = 64, Hg = 2, H = 4, K = 128, V = 128, W = 4; + const long long units = 2 * Hg + H, XD = units * K; // 8 * 128 = 1024 + if (s->n_operands != 16) { fail("gdn_conv_prep: the schema has %d operands, not 16", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "head_k", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "head_v", RAD_P_INT, V, 0, nullptr, 0.0 }, + { "chunk", RAD_P_INT, 64, 0, nullptr, 0.0 }, + { "conv_width", RAD_P_INT, W, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x7E57BD71u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hx(T * XD), hw(XD * W), hb(XD); + for (auto& x : hx) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hw) x = f32_to_bf16((rndf() - 0.5f) * 0.5f); + for (auto& x : hb) x = f32_to_bf16((rndf() - 0.5f) * 0.2f); + std::vector hcs(XD * 3, 0), ha(T * H), hbg(T * H); + for (auto& x : hcs) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : ha) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + for (auto& x : hbg) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + std::vector halog(H), hdtb(H); + for (auto& x : halog) x = logf(0.1f + rndf()); + for (auto& x : hdtb) x = (rndf() - 0.5f) * 4.0f; + const int cuv[2] = { 0, (int)T }; + const int cidxv[1] = { 0 }, hin[1] = { 1 }; + std::vector hq(T * Hg * K, 0x7fc0u), hk(T * Hg * K, 0x7fc0u), hv(T * H * V, 0x7fc0u); + std::vector hg(T * H, 0.0f), hbeta(T * H, 0.0f); + + struct { uint32_t dt; long long nel; } qd[16] = { + { RAD_BF16, T * XD }, // x + { RAD_BF16, XD * W }, // w + { RAD_BF16, XD }, // b + { RAD_F32, H }, // A_log + { RAD_F32, H }, // dt_bias + { RAD_BF16, XD * 3 }, // conv_state [XD, 1, 3] + { RAD_I32, 2 }, // cu + { RAD_BF16, T * H }, // a + { RAD_BF16, T * H }, // b_gate + { RAD_I32, 1 }, // cache_idx + { RAD_I32, 1 }, // has_init + { RAD_BF16, T * Hg * K }, // q + { RAD_BF16, T * Hg * K }, // k + { RAD_BF16, T * H * V }, // v + { RAD_F32, T * H }, // g + { RAD_F32, T * H } // beta + }; + for (int o = 0; o < 16; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_conv_prep: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + switch (o) { + case 0: std::memcpy(d, hx.data(), bytes); break; + case 1: std::memcpy(d, hw.data(), bytes); break; + case 2: std::memcpy(d, hb.data(), bytes); break; + case 3: std::memcpy(d, halog.data(), bytes); break; + case 4: std::memcpy(d, hdtb.data(), bytes); break; + case 5: std::memcpy(d, hcs.data(), bytes); break; + case 6: std::memcpy(d, cuv, sizeof cuv); break; + case 7: std::memcpy(d, ha.data(), bytes); break; + case 8: std::memcpy(d, hbg.data(), bytes); break; + case 9: std::memcpy(d, cidxv, sizeof cidxv); break; + case 10: std::memcpy(d, hin, sizeof hin); break; + case 11: std::memcpy(d, hq.data(), bytes); break; + case 12: std::memcpy(d, hk.data(), bytes); break; + case 13: std::memcpy(d, hv.data(), bytes); break; + case 14: std::memcpy(d, hg.data(), bytes); break; + default: std::memcpy(d, hbeta.data(), bytes); break; + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + switch (o) { + case 0: t.rank = 2; t.shape[0] = T; t.shape[1] = XD; t.stride[1] = 1; t.stride[0] = XD; break; + case 1: t.rank = 2; t.shape[0] = XD; t.shape[1] = W; t.stride[1] = 1; t.stride[0] = W; break; + case 2: t.rank = 1; t.shape[0] = XD; t.stride[0] = 1; break; + case 3: case 4: t.rank = 1; t.shape[0] = H; t.stride[0] = 1; break; + case 5: t.rank = 3; t.shape[0] = XD; t.shape[1] = 1; t.shape[2] = 3; + t.stride[2] = 1; t.stride[1] = 3; t.stride[0] = 3; break; + case 6: t.rank = 1; t.shape[0] = 2; t.stride[0] = 1; break; + case 7: case 8: t.rank = 2; t.shape[0] = T; t.shape[1] = H; t.stride[1] = 1; t.stride[0] = H; break; + case 9: case 10: t.rank = 1; t.shape[0] = 1; t.stride[0] = 1; break; + case 11: case 12: t.rank = 3; t.shape[0] = T; t.shape[1] = Hg; t.shape[2] = K; + t.stride[2] = 1; t.stride[1] = K; t.stride[0] = Hg * K; break; + case 13: t.rank = 3; t.shape[0] = T; t.shape[1] = H; t.shape[2] = V; + t.stride[2] = 1; t.stride[1] = V; t.stride[0] = H * V; break; + case 14: case 15: t.rank = 2; t.shape[0] = T; t.shape[1] = H; t.stride[1] = 1; t.stride[0] = H; break; + } + } + return 0; +} + +static int build_gdn_conv_update(Case& c, const RadOpSchema* s) { + const long long T = 1, Hg = 2, H = 4, K = 128, V = 128, W = 4, SL = 4; + const long long units = 2 * Hg + H, XD = units * K; + if (s->n_operands != 10) { fail("gdn_conv_update: the schema has %d operands, not 10", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "q_len", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "head_k", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "head_v", RAD_P_INT, V, 0, nullptr, 0.0 }, + { "conv_width", RAD_P_INT, W, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x35A7F12Bu; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hx(T * XD), hw(XD * W), hb(XD); + for (auto& x : hx) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hw) x = f32_to_bf16((rndf() - 0.5f) * 0.5f); + for (auto& x : hb) x = f32_to_bf16((rndf() - 0.5f) * 0.2f); + std::vector hcs(XD * SL, 0); + for (auto& x : hcs) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + const int cuv[2] = { 0, (int)T }; + const int sidxv[1] = { 0 }, nav[1] = { 0 }; + std::vector hq(T * Hg * K, 0x7fc0u), hk(T * Hg * K, 0x7fc0u), hv(T * H * V, 0x7fc0u); + + struct { uint32_t dt; long long nel; } qd[10] = { + { RAD_BF16, T * XD }, // x + { RAD_BF16, XD * W }, // w + { RAD_BF16, XD }, // b + { RAD_BF16, XD * SL }, // conv_state [XD, 1, SL] + { RAD_I32, 1 }, // state_idx + { RAD_I32, 1 }, // num_accepted + { RAD_I32, 2 }, // cu + { RAD_BF16, T * Hg * K }, // q + { RAD_BF16, T * Hg * K }, // k + { RAD_BF16, T * H * V } // v + }; + for (int o = 0; o < 10; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_conv_update: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + switch (o) { + case 0: std::memcpy(d, hx.data(), bytes); break; + case 1: std::memcpy(d, hw.data(), bytes); break; + case 2: std::memcpy(d, hb.data(), bytes); break; + case 3: std::memcpy(d, hcs.data(), bytes); break; + case 4: std::memcpy(d, sidxv, sizeof sidxv); break; + case 5: std::memcpy(d, nav, sizeof nav); break; + case 6: std::memcpy(d, cuv, sizeof cuv); break; + case 7: std::memcpy(d, hq.data(), bytes); break; + case 8: std::memcpy(d, hk.data(), bytes); break; + default: std::memcpy(d, hv.data(), bytes); break; + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + switch (o) { + case 0: t.rank = 2; t.shape[0] = T; t.shape[1] = XD; t.stride[1] = 1; t.stride[0] = XD; break; + case 1: t.rank = 2; t.shape[0] = XD; t.shape[1] = W; t.stride[1] = 1; t.stride[0] = W; break; + case 2: t.rank = 1; t.shape[0] = XD; t.stride[0] = 1; break; + case 3: t.rank = 3; t.shape[0] = XD; t.shape[1] = 1; t.shape[2] = SL; + t.stride[2] = 1; t.stride[1] = SL; t.stride[0] = SL; break; + case 4: case 5: t.rank = 1; t.shape[0] = 1; t.stride[0] = 1; break; + case 6: t.rank = 1; t.shape[0] = 2; t.stride[0] = 1; break; + case 7: case 8: t.rank = 3; t.shape[0] = T; t.shape[1] = Hg; t.shape[2] = K; + t.stride[2] = 1; t.stride[1] = K; t.stride[0] = Hg * K; break; + default: t.rank = 3; t.shape[0] = T; t.shape[1] = H; t.shape[2] = V; + t.stride[2] = 1; t.stride[1] = V; t.stride[0] = H * V; break; + } + } + return 0; +} + +static int build_expert_scale(Case& c, const RadOpSchema* s) { + const long long M = 3, K = 4, NE = 8; + if (s->n_operands != 3) { fail("expert_scale: the schema has %d operands, not 3", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, K, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0xA11CEu; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hids(M * K); + for (auto& x : hids) x = (int32_t)(rndf() * (NE + 2)) - 1; // includes an out-of-table id + std::vector hsc(NE), hew(M * K); + for (auto& x : hsc) x = f32_to_bf16(0.1f + rndf()); + for (auto& x : hew) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + + struct { uint32_t dt; long long nel; } qd[3] = { + { RAD_I32, M * K }, // ids + { RAD_BF16, NE }, // w_e + { RAD_BF16, M * K } // ew + }; + for (int o = 0; o < 3; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("expert_scale: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + switch (o) { + case 0: std::memcpy(d, hids.data(), bytes); break; + case 1: std::memcpy(d, hsc.data(), bytes); break; + default: std::memcpy(d, hew.data(), bytes); break; + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 1) { t.rank = 1; t.shape[0] = NE; t.stride[0] = 1; } + else { t.rank = 2; t.shape[0] = M; t.shape[1] = K; t.stride[1] = 1; t.stride[0] = K; } + } + return 0; +} + +static int build_moe_router_topk(Case& c, const RadOpSchema* s) { + const long long M = 6, NE = 48, TK = 8; + if (s->n_operands != 3) { fail("router_topk: the schema has %d operands, not 3", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "norm", RAD_P_INT, 1, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x7017u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + std::vector hlg(M * NE), hw(M * TK, 0); + for (auto& x : hlg) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + + struct { uint32_t dt; long long nel; } qd[3] = { + { RAD_BF16, M * NE }, // logits + { RAD_I32, M * TK }, // expert_ids + { RAD_BF16, M * TK } // expert_w + }; + for (int o = 0; o < 3; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("router_topk: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + std::memcpy(d, o == 0 ? hlg.data() : hw.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 0) { t.rank = 2; t.shape[0] = M; t.shape[1] = NE; t.stride[1] = 1; t.stride[0] = NE; } + else { t.rank = 2; t.shape[0] = M; t.shape[1] = TK; t.stride[1] = 1; t.stride[0] = TK; } + } + return 0; +} + +static int build_moe_scatter(Case& c, const RadOpSchema* s) { + const long long M = 16, TK = 8, NE = 32; // T = 128 + const long long T = M * TK; + if (s->n_operands != 4) { fail("moe_scatter: the schema has %d operands, not 4", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x5CA7u; + auto rnd = [&]() { st = st * 1664525u + 1013904223u; return (int32_t)((st >> 8) & 0xffffu); }; + std::vector hids(T), hsorted(T, -1), hoff(NE + 1, -1), hcnt(NE, -1); + for (auto& x : hids) x = rnd() % NE; + + struct { uint32_t dt; long long nel; } qd[4] = { + { RAD_I32, T }, // expert_ids + { RAD_I32, T }, // sorted_tok + { RAD_I32, NE + 1 }, // expert_offset + { RAD_I32, NE } // expert_count + }; + for (int o = 0; o < 4; ++o) { + const size_t bytes = (size_t)qd[o].nel * 4; + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_scatter: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + std::memcpy(d, o == 0 ? hids.data() : (o == 1 ? hsorted.data() + : (o == 2 ? hoff.data() : hcnt.data())), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = RAD_I32; t.rank = 1; + t.shape[0] = qd[o].nel; t.stride[0] = 1; + } + return 0; +} + +static int build_moe_gemm_q(Case& c, const RadOpSchema* s) { + const long long M = 8, N = 128, K = 128, NE = 8, TK = 2, GR = 1; // T = 16; N % 128 + const long long T = M * TK, NE0 = (NE + 1) / 2, NE1 = NE / 2; + if (s->n_operands != 9) { fail("moe_gemm_q: the schema has %d operands, not 9", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "grid_rows", RAD_P_INT, GR, 0, nullptr, 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"w4a8", 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x0E0E5A1Cu; + auto rnd = [&]() { st = st * 1664525u + 1013904223u; return (st >> 8) & 0xffu; }; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; return 0.5f + ((st >> 8) & 0xff) / 255.0f; }; + // E4M3 codes in the normal range (exp 1..14), a valid bit pattern. + auto re4 = [&]() { return (uint8_t)(((rnd() & 0x7) | 1) << 3 | (rnd() & 0x7) | ((rnd() & 1) << 7)); }; + std::vector ha((size_t)M * K), hw0((size_t)NE0 * N * K), hw1((size_t)NE1 * N * K); + for (auto& x : ha) x = re4(); + for (auto& x : hw0) x = re4(); + for (auto& x : hw1) x = re4(); + std::vector hA((size_t)M * (K / 128)), hW0((size_t)NE0 * (N / GR) * (K / 128)), + hW1((size_t)NE1 * (N / GR) * (K / 128)); + for (auto& x : hA) x = rndf(); + for (auto& x : hW0) x = rndf(); + for (auto& x : hW1) x = rndf(); + std::vector hs(T), ho(NE + 1); + for (long long i = 0; i < T; ++i) hs[i] = (int32_t)i; + for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); + ho[NE] = (int32_t)T; + + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[9] = { + { RAD_F8E4M3, 2, { M, K, 1 }, M * K }, + { RAD_F32, 2, { M, K / 128, 1 }, M * (K / 128) }, + { RAD_I32, 1, { T, 1, 1 }, T }, + { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, + { RAD_F8E4M3, 3, { NE0, N, K }, NE0 * N * K }, + { RAD_F32, 3, { NE0, N / GR, K / 128 }, NE0 * (N / GR) * (K / 128) }, + { RAD_F8E4M3, 3, { NE1, N, K }, NE1 * N * K }, + { RAD_F32, 3, { NE1, N / GR, K / 128 }, NE1 * (N / GR) * (K / 128) }, + { RAD_F32, 2, { T, N, 1 }, T * N } }; + const uint32_t bytes_of[] = { 1, 4, 4, 4, 1, 4, 1, 4, 4 }; + const void* src[] = { ha.data(), hA.data(), hs.data(), ho.data(), hw0.data(), hW0.data(), + hw1.data(), hW1.data(), nullptr }; + for (int o = 0; o < 9; ++o) { + const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_q: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; + for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } + for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + } + return 0; +} + +static int build_moe_gemm_bf16(Case& c, const RadOpSchema* s) { + const long long M = 8, N = 128, K = 64, NE = 8, TK = 2; // T = 16; N % 128, K % 64 + const long long T = M * TK; + if (s->n_operands != 5) { fail("moe_gemm_bf16: the schema has %d operands, not 5", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x1A2B3C4Du; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + std::vector ha((size_t)M * K), hw((size_t)NE * N * K); + for (auto& x : ha) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hw) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + std::vector hs(T), ho(NE + 1); + for (long long i = 0; i < T; ++i) hs[i] = (int32_t)i; + for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); + ho[NE] = (int32_t)T; + + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[5] = { + { RAD_BF16, 2, { M, K, 1 }, M * K }, + { RAD_BF16, 3, { NE, N, K }, NE * N * K }, + { RAD_I32, 1, { T, 1, 1 }, T }, + { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, + { RAD_BF16, 2, { T, N, 1 }, T * N } }; + const uint32_t bytes_of[] = { 2, 2, 4, 4, 2 }; + const void* src[] = { ha.data(), hw.data(), hs.data(), ho.data(), nullptr }; + for (int o = 0; o < 5; ++o) { + const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_bf16: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; + for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } + for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + } + return 0; +} + +static int build_moe_gemm_mxfp4a8(Case& c, const RadOpSchema* s) { + const long long M = 8, N = 128, K = 128, NE = 8, TK = 2, GR = 1; // T = 16; N % 128 + const long long T = M * TK, NE0 = (NE + 1) / 2, NE1 = NE / 2; + if (s->n_operands != 9) { fail("moe_gemm_mxfp4a8: the schema has %d operands, not 9", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "grid_rows", RAD_P_INT, GR, 0, nullptr, 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"mxfp4a8", 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x7A6B5C4Du; + auto rnd = [&]() { st = st * 1664525u + 1013904223u; return (st >> 8) & 0xffu; }; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; return 0.5f + ((st >> 8) & 0xff) / 255.0f; }; + auto re4 = [&]() { return (uint8_t)(((rnd() & 0x7) | 1) << 3 | (rnd() & 0x7) | ((rnd() & 1) << 7)); }; + auto re2 = [&]() { return (uint8_t)(rnd() & 0xF); }; // E2M1 code (4 bits) + auto re8 = [&]() { return (uint8_t)(120 + (rnd() & 14)); }; // E8M0 near 1.0 (exp 120..133) + std::vector ha((size_t)M * K), hw0((size_t)NE0 * N * (K / 2)), hw1((size_t)NE1 * N * (K / 2)); + for (auto& x : ha) x = re4(); + for (auto& x : hw0) x = re2(); + for (auto& x : hw1) x = re2(); + std::vector hA((size_t)M * (K / 128)); + std::vector hW0((size_t)NE0 * (N / GR) * (K / 32)), + hW1((size_t)NE1 * (N / GR) * (K / 32)); + for (auto& x : hA) x = rndf(); + for (auto& x : hW0) x = re8(); + for (auto& x : hW1) x = re8(); + std::vector hs(T), ho(NE + 1); + for (long long i = 0; i < T; ++i) hs[i] = (int32_t)i; + for (long long e = 0; e < NE; ++e) ho[e] = (int32_t)(e * (T / NE)); + ho[NE] = (int32_t)T; + + struct { uint32_t dt; int rank; long long sh[3]; long long nel; } qd[9] = { + { RAD_F8E4M3, 2, { M, K, 1 }, M * K }, + { RAD_F32, 2, { M, K / 128, 1 }, M * (K / 128) }, + { RAD_I32, 1, { T, 1, 1 }, T }, + { RAD_I32, 1, { NE + 1, 1, 1 }, NE + 1 }, + { RAD_FP4E2M1, 3, { NE0, N, K / 2 }, NE0 * N * (K / 2) }, + { RAD_U8, 3, { NE0, N / GR, K / 32 }, NE0 * (N / GR) * (K / 32) }, + { RAD_FP4E2M1, 3, { NE1, N, K / 2 }, NE1 * N * (K / 2) }, + { RAD_U8, 3, { NE1, N / GR, K / 32 }, NE1 * (N / GR) * (K / 32) }, + { RAD_BF16, 2, { T, N, 1 }, T * N } }; + const uint32_t bytes_of[] = { 1, 4, 4, 4, 1, 1, 1, 1, 2 }; + const void* src[] = { ha.data(), hA.data(), hs.data(), ho.data(), hw0.data(), hW0.data(), + hw1.data(), hW1.data(), nullptr }; + for (int o = 0; o < 9; ++o) { + const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gemm_mxfp4a8: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; + for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } + for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + } + return 0; +} + +static int build_moe_router_scatter(Case& c, const RadOpSchema* s) { + const long long M = 6, NE = 48, TK = 8; + const long long T = M * TK; + if (s->n_operands != 6) { fail("router_topk_scatter: the schema has %d operands, not 6", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "n_local", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "norm", RAD_P_INT, 1, 0, nullptr, 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"bf16", 0.0 }, + { "expert_base", RAD_P_INT, 0, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x8070u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + std::vector hlg(M * NE); + for (auto& x : hlg) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + + struct { uint32_t dt; long long nel; } qd[6] = { + { RAD_BF16, M * NE }, // logits + { RAD_I32, M * TK }, // expert_ids + { RAD_BF16, M * TK }, // expert_w + { RAD_I32, T }, // sorted_tok + { RAD_I32, NE + 1 }, // expert_offset + { RAD_I32, NE } // expert_count + }; + for (int o = 0; o < 6; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("router_topk_scatter: hipMalloc(%zu) failed", + bytes); return 1; } + c.dev.push_back(d); + if (o == 0) std::memcpy(d, hlg.data(), bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o <= 2) { t.rank = 2; t.shape[0] = M; t.shape[1] = o == 0 ? NE : TK; t.stride[1] = 1; + t.stride[0] = o == 0 ? NE : TK; } + else { t.rank = 1; t.shape[0] = qd[o].nel; t.stride[0] = 1; } + } + return 0; +} + +static int build_moe_router_sigmoid(Case& c, const RadOpSchema* s) { + const long long M = 6, NE = 48, TK = 8; + if (s->n_operands != 4) { fail("router_sigmoid_topk: the schema has %d operands, not 4", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n_expert", RAD_P_INT, NE, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "route_scale", RAD_P_F64, 0, 0, nullptr, 1.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"bf16", 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x51A2u; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + std::vector hlg(M * NE); + std::vector hbi(NE); + for (auto& x : hlg) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + for (auto& x : hbi) x = (rndf() - 0.5f) * 0.1f; + + struct { uint32_t dt; long long nel; } qd[4] = { + { RAD_BF16, M * NE }, // logits + { RAD_F32, NE }, // bias + { RAD_I32, M * TK }, // expert_ids + { RAD_BF16, M * TK } // expert_w + }; + const void* src[] = { hlg.data(), hbi.data(), nullptr, nullptr }; + for (int o = 0; o < 4; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("router_sigmoid_topk: hipMalloc(%zu) failed", + bytes); return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + if (o == 0) { t.rank = 2; t.shape[0] = M; t.shape[1] = NE; t.stride[1] = 1; t.stride[0] = NE; } + else if (o == 1) { t.rank = 1; t.shape[0] = NE; t.stride[0] = 1; } + else { t.rank = 2; t.shape[0] = M; t.shape[1] = TK; t.stride[1] = 1; t.stride[0] = TK; } + } + return 0; +} + + +static int build_moe_gather(Case& c, const RadOpSchema* s, int inv) { + const long long M = 8, n = 128, TK = 2; // T = 16 + const long long T = M * TK; + if (s->n_operands != 6) { fail("moe_gather%s: the schema has %d operands, not 6", + inv ? "_inv" : "", s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "M", RAD_P_INT, M, 0, nullptr, 0.0 }, + { "n", RAD_P_INT, n, 0, nullptr, 0.0 }, + { "top_k", RAD_P_INT, TK, 0, nullptr, 0.0 }, + { "dtype", RAD_P_STR, 0, 0, (const char*)"bf16", 0.0 }, + { "act", RAD_P_STR, 0, 0, (const char*)"silu", 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x0B0C0Du; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + std::vector hye((size_t)T * n), hew(M * TK), hsh((size_t)M * n), hsg(M); + for (auto& x : hye) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hew) x = f32_to_bf16(rndf()); + for (auto& x : hsh) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hsg) x = f32_to_bf16(rndf() * 4.0f); + std::vector hslot(T); + for (long long i = 0; i < T; ++i) hslot[i] = (int32_t)(i % M); + + struct { uint32_t dt; int rank; long long sh[2]; long long nel; } qd[6] = { + { RAD_BF16, 2, { T, n }, T * n }, // y_expert + { RAD_BF16, 2, { M, TK }, M * TK }, // expert_w + { RAD_I32, 1, { T, 1 }, T }, // sorted_tok / inverse + { RAD_BF16, 2, { M, n }, M * n }, // shared + { RAD_BF16, 1, { M, 1 }, M }, // shared_gate + { RAD_BF16, 2, { M, n }, M * n } // y + }; + const uint32_t bytes_of[] = { 2, 2, 4, 2, 2, 2 }; + const void* src[] = { hye.data(), hew.data(), hslot.data(), hsh.data(), hsg.data(), nullptr }; + for (int o = 0; o < 6; ++o) { + const size_t bytes = (size_t)qd[o].nel * bytes_of[o]; + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("moe_gather: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + if (src[o]) std::memcpy(d, src[o], bytes); + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; t.rank = qd[o].rank; + for (int r = 0; r < qd[o].rank; ++r) { t.shape[r] = qd[o].sh[r]; t.stride[r] = 1; } + for (int r = 0; r + 1 < qd[o].rank; ++r) t.stride[r] = t.shape[r + 1] * t.stride[r + 1]; + } + return 0; +} + + +static int build_gdn_recurrent(Case& c, const RadOpSchema* s) { + const long long T = 4, Hg = 2, H = 4, K = 128, V = 128, SLOTS = 2; + if (s->n_operands != 16) { fail("gdn_recurrent_update: the schema has %d operands, not 16", + s->n_operands); return 1; } + c.n_p = 0; + const RadParam pp[] = { { "q_len", RAD_P_INT, T, 0, nullptr, 0.0 }, + { "head_k", RAD_P_INT, K, 0, nullptr, 0.0 }, + { "head_v", RAD_P_INT, V, 0, nullptr, 0.0 } }; + for (const RadParam& q : pp) c.p[c.n_p++] = q; + + uint32_t st = 0x4A7B2C9Du; + auto rndf = [&]() { st = st * 1664525u + 1013904223u; + return (float)((st >> 8) & 0xffffu) / 65536.0f; }; + + std::vector hq(T*Hg*K), hk(T*Hg*K), hv(T*H*V), ha(T*H), hb(T*H), hz(T*H*V); + for (auto& x : hq) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hk) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : hv) x = f32_to_bf16((rndf() - 0.5f) * 2.0f); + for (auto& x : ha) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + for (auto& x : hb) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + for (auto& x : hz) x = f32_to_bf16((rndf() - 0.5f) * 4.0f); + std::vector halog(H), hdtb(H), hstate(SLOTS*H*V*K), hnw(V); + for (auto& x : halog) x = logf(0.1f + rndf()); + for (auto& x : hdtb) x = (rndf() - 0.5f) * 4.0f; + for (auto& x : hstate) x = (rndf() - 0.5f) * 0.1f; + for (auto& x : hnw) x = (rndf() - 0.5f) * 2.0f; + std::vector ho(T*H*V, 0x7fc0u); + const int sidxv[T] = { 0, 0, 1, 1 }; + const int nav[1] = { 0 }; + const int cuv[2] = { 0, (int)T }; + + struct { uint32_t dt; long long nel; } qd[16] = { + { RAD_BF16, T*Hg*K }, // q + { RAD_BF16, T*Hg*K }, // k + { RAD_BF16, T*H*V }, // v + { RAD_BF16, T*H }, // a + { RAD_BF16, T*H }, // b + { RAD_F32, H }, // A_log + { RAD_F32, H }, // dt_bias + { RAD_F32, SLOTS*H*V*K }, // state + { RAD_I32, T }, // state_idx [1, T] + { RAD_I32, 1 }, // num_accepted + { RAD_I32, 2 }, // cu + { RAD_BF16, T*H*V }, // z + { RAD_F32, V }, // norm_w + { RAD_BF16, T*H*V }, // o + { RAD_I8, 0 }, // o_q: absent + { RAD_F32, 0 } // o_scale: absent + }; + for (int o = 0; o < 14; ++o) { + const size_t bytes = (size_t)qd[o].nel * dt_bytes(qd[o].dt); + void* d = nullptr; + if (hipMalloc(&d, bytes) != hipSuccess) { fail("gdn_recurrent: hipMalloc(%zu) failed", bytes); + return 1; } + c.dev.push_back(d); + switch (o) { + case 0: std::memcpy(d, hq.data(), bytes); break; + case 1: std::memcpy(d, hk.data(), bytes); break; + case 2: std::memcpy(d, hv.data(), bytes); break; + case 3: std::memcpy(d, ha.data(), bytes); break; + case 4: std::memcpy(d, hb.data(), bytes); break; + case 5: std::memcpy(d, halog.data(), bytes); break; + case 6: std::memcpy(d, hdtb.data(), bytes); break; + case 7: std::memcpy(d, hstate.data(), bytes); break; + case 8: std::memcpy(d, sidxv, sizeof sidxv); break; + case 9: std::memcpy(d, nav, sizeof nav); break; + case 10: std::memcpy(d, cuv, sizeof cuv); break; + case 11: std::memcpy(d, hz.data(), bytes); break; + case 12: std::memcpy(d, hnw.data(), bytes); break; + default: std::memcpy(d, ho.data(), bytes); break; + } + RadTensor& t = c.t[o]; + t = RadTensor{}; + t.data = d; t.dtype = qd[o].dt; + switch (o) { + case 0: case 1: t.rank = 3; t.shape[0]=T; t.shape[1]=Hg; t.shape[2]=K; + t.stride[2]=1; t.stride[1]=K; t.stride[0]=Hg*K; break; + case 2: t.rank = 3; t.shape[0]=T; t.shape[1]=H; t.shape[2]=V; + t.stride[2]=1; t.stride[1]=V; t.stride[0]=H*V; break; + case 3: case 4: t.rank = 2; t.shape[0]=T; t.shape[1]=H; t.stride[1]=1; t.stride[0]=H; break; + case 5: case 6: t.rank = 1; t.shape[0]=H; t.stride[0]=1; break; + case 7: t.rank = 4; t.shape[0]=SLOTS; t.shape[1]=H; t.shape[2]=V; t.shape[3]=K; + t.stride[3]=1; t.stride[2]=K; t.stride[1]=V*K; t.stride[0]=H*V*K; break; + case 8: t.rank = 2; t.shape[0]=1; t.shape[1]=T; t.stride[1]=1; t.stride[0]=T; break; + case 9: t.rank = 1; t.shape[0]=1; t.stride[0]=1; break; + case 10: t.rank = 1; t.shape[0]=2; t.stride[0]=1; break; + case 11: t.rank = 3; t.shape[0]=T; t.shape[1]=H; t.shape[2]=V; + t.stride[2]=1; t.stride[1]=V; t.stride[0]=H*V; break; + case 12: t.rank = 1; t.shape[0]=V; t.stride[0]=1; break; + default: t.rank = 3; t.shape[0]=T; t.shape[1]=H; t.shape[2]=V; + t.stride[2]=1; t.stride[1]=V; t.stride[0]=H*V; break; + } + } + c.t[14] = RadTensor{}; // o_q absent + c.t[15] = RadTensor{}; // o_scale absent + return 0; +} + static int run_row(int i) { const RadKernelInfo* k = row_at(i); if (!k) return 1; @@ -988,7 +2197,25 @@ static int run_row(int i) { return 0; } const int hand = k->opd_shape ? 0 - : (0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16")) ? 1 : 2; + : (0 == std::strcmp(k->name, "gemm_nt_q_w2a8_m16")) ? 1 + : (0 == std::strcmp(k->name, "gemm_nt_q_w4a16asym_m64")) ? 3 + : (0 == std::strcmp(k->name, "gemm_nt_q_w5a16_m64")) ? 4 + : (0 == std::strcmp(k->name, "gdn_kkt_solve_c64")) ? 5 + : (0 == std::strcmp(k->name, "gdn_chunk_scan_k128_v128_c64")) ? 6 + : (0 == std::strcmp(k->name, "gdn_gated_rmsnorm_h128")) ? 7 + : (0 == std::strcmp(k->name, "gdn_gated_norm_had_quant_i8")) ? 8 + : (0 == std::strcmp(k->name, "gdn_conv_prep_w4_h128")) ? 9 + : (0 == std::strcmp(k->name, "gdn_conv_update_w4_h128")) ? 10 + : (0 == std::strcmp(k->name, "gdn_recurrent_update_k128_v128")) ? 11 + : (0 == std::strcmp(k->name, "expert_scale_bf16")) ? 12 + : (0 == std::strcmp(k->name, "moe_router_topk_bf16")) ? 13 + : (0 == std::strcmp(k->name, "moe_scatter_small")) ? 14 + : (0 == std::strcmp(k->name, "moe_gemm_q_e4m3")) ? 15 + : (0 == std::strcmp(k->name, "moe_gemm_bf16")) ? 16 + : (0 == std::strcmp(k->name, "moe_gemm_mxfp4a8")) ? 17 + : (0 == std::strcmp(k->name, "moe_router_topk_scatter")) ? 18 + : (0 == std::strcmp(k->name, "moe_router_sigmoid_topk")) ? 19 + : (0 == std::strcmp(k->name, "moe_gather")) ? 21 : 2; if (hand == 2) { skip("no operand description, so no buffers to build"); return 0; } const RadOpSchema* s = find_schema(k->op); if (!s) { fail("no schema for '%s'", k->op); return 1; } @@ -999,7 +2226,29 @@ static int run_row(int i) { a.p = c.p; a.n_p = c.n_p; - if (hand) { if (build_w2a8(c, s)) return 1; goto launched; } + if (hand) { + const int rc = hand == 1 ? build_w2a8(c, s) + : hand == 3 ? build_w4a16asym(c, s) + : hand == 4 ? build_w5a16(c, s) + : hand == 5 ? build_gdn_kkt(c, s) + : hand == 7 ? build_gdn_gated_rmsnorm(c, s) + : hand == 8 ? build_gdn_gated_norm_hq(c, s) + : hand == 9 ? build_gdn_conv_prep(c, s) + : hand == 10 ? build_gdn_conv_update(c, s) + : hand == 11 ? build_gdn_recurrent(c, s) + : hand == 12 ? build_expert_scale(c, s) + : hand == 13 ? build_moe_router_topk(c, s) + : hand == 14 ? build_moe_scatter(c, s) + : hand == 15 ? build_moe_gemm_q(c, s) + : hand == 16 ? build_moe_gemm_bf16(c, s) + : hand == 17 ? build_moe_gemm_mxfp4a8(c, s) + : hand == 18 ? build_moe_router_scatter(c, s) + : hand == 19 ? build_moe_router_sigmoid(c, s) + : hand == 21 ? build_moe_gather(c, s, 0) + : build_gdn_chunk_scan(c, s); + if (rc) return 1; + goto launched; + } for (int o = 0; o < s->n_operands && o < MAX_OPD; ++o) { RadOpdDesc d{}; const int st = k->opd_shape(c.p, c.n_p, o, &d); @@ -1140,6 +2389,83 @@ launched: } } if (!ret) ok("ran, %d output plane%s read back finite", outs, outs == 1 ? "" : "s"); + + /* The implementation arms. A row that declared an `impl` axis has a second kernel the + * default run never touches, and the engine's own way of reaching it is to append the + * chosen point to RadArgs::p -- which is what this pass does: the same buffers, the same + * fill, the arm's launch, the same finiteness read-back. An arm that faults, declines a + * geometry the dot2 arm serves, or leaves a NaN is a failure here, not at a tune run. */ + for (int t = 0; t < k->n_tunables && !ret; ++t) { + if (!k->tunables[t].key || std::strcmp(k->tunables[t].key, "impl")) continue; + // impl=1, and sk=1 where the row has a split-K axis: the WMMA arm's ladder would + // pick a wide sk that needs a scratch buffer, which this probe does not carry. + // sk=1 is a valid point on every axis that has one. The original parameters are + // kept: a shim that reads N / K from them must see the same geometry. + RadParam extra = { "impl", RAD_P_INT, 1, 0, nullptr, 0.0 }; + RadArgs a2 = a; + static RadParam extra_p[64]; + int np = 0; + for (int u = 0; u < a.n_p && np < 60; ++u) extra_p[np++] = a.p[u]; + extra_p[np++] = extra; + for (int u = 0; u < k->n_tunables; ++u) + if (k->tunables[u].key && !std::strcmp(k->tunables[u].key, "sk")) + extra_p[np++] = (RadParam){ "sk", RAD_P_INT, 1, 0, nullptr, 0.0 }; + a2.p = extra_p; + a2.n_p = np; + const int rc2 = k->launch(&a2, nullptr); + if (rc2 != RAD_OK) { + fail("the impl=1 arm declined the geometry the default serves (%d)", rc2); + ret = 1; + } else { + const hipError_t le2 = hipGetLastError(); + const int sync2 = (int)hipDeviceSynchronize(); + if (le2 != hipSuccess || sync2 != hipSuccess) { + fail("the impl=1 arm faulted (last error %d, sync %d)", (int)le2, (int)sync2); + ret = 1; + } else { + int nan = 0, big = 0, outs2 = 0; + for (int o = 0; o < s->n_operands && !ret; ++o) { + if (s->operands[o].role == RAD_OPD_IN) continue; + const RadTensor& t2 = c.t[o]; + if (!t2.data) continue; + if (std::find(c.host.begin(), c.host.end(), t2.data) != c.host.end()) + continue; + ++outs2; + long long nel = 1; + for (uint32_t r = 0; r < t2.rank; ++r) nel *= t2.shape[r]; + const size_t bytes = t2.dtype == RAD_U2 ? (size_t)(nel / 4) + : (t2.dtype == RAD_U4 || t2.dtype == RAD_I4 || + t2.dtype == RAD_FP4E2M1) + ? (size_t)(nel / 2) + : (size_t)nel * dt_bytes(t2.dtype); + std::vector h(bytes); + if (hipMemcpy(h.data(), t2.data, bytes, hipMemcpyDeviceToHost) != + hipSuccess) { + fail("impl=1 read-back failed on operand %d", o); + ret = 1; + break; + } + for (long long e = 0; e < nel; ++e) { + float v = 0.f; + switch (t2.dtype) { + case RAD_F32: v = *(const float*)(h.data() + e * 4); break; + case RAD_BF16: v = bf16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F16: v = f16_to_f32(*(const uint16_t*)(h.data() + e * 2)); break; + case RAD_F8E4M3: v = e4m3_to_f32(h.data()[e]); break; + default: continue; + } + if (v != v) ++nan; + else if (!(v > -1e31f && v < 1e31f)) ++big; + } + if (nan) { fail("impl=1 arm, operand %d: %d NaN of %lld", o, nan, nel); + ret = 1; } + } + if (!ret) + ok("impl=1 arm ran, %d output plane%s read back finite", outs2, + outs2 == 1 ? "" : "s"); + } + } + } } if (scratch) (void)hipFree(scratch); diff --git a/libr3d/r3d_shapes.cpp b/libr3d/r3d_shapes.cpp index f7605847..e9ae767e 100644 --- a/libr3d/r3d_shapes.cpp +++ b/libr3d/r3d_shapes.cpp @@ -346,6 +346,114 @@ int r3d_shape_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* } /* The per-group int8 the i8a8 GEMM reads: the fp8 quantiser's extents with int8 codes. */ +/* The Hadamard-rotated int8: the same three planes as quant_act_i8 (x, q, scale), no row sums. */ +int r3d_shape_had_quant_act_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, 1) }; + R3D_PICK(list); +} + +/* The GELU-gated product quantiser: gate_up [M, 2n], q [M, n] i8, scale [M], out_bf16 [M, n]. */ +int r3d_shape_gelu_mul_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, 1), opd(D, M, n) }; + R3D_PICK(list); +} + +/* The prefill-overlap length trim: seqused [max_seqs], tail [trim] (extent carries the count), + * out [max_seqs]. */ +int r3d_shape_kv_len_trim(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t n = gi(p, n_p, "max_seqs", 0), trim = gi(p, n_p, "trim", 0); + const RadOpdDesc list[] = { opd((uint32_t)RAD_I32, n, 1), opd((uint32_t)RAD_I32, trim, 1), + opd((uint32_t)RAD_I32, n, 1) }; + R3D_PICK(list); +} + +/* The QSA tail: k [M, n], pos [M], cu [seqs+1], state [seqs, 1, ring, n] (inout), sidx [seqs]. */ +int r3d_shape_qsa_tail_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ring = gi(p, n_p, "ring", 0), seqs = gi(p, n_p, "seqs", 0); + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, n), opd((uint32_t)RAD_I32, M, 1), + opd((uint32_t)RAD_I32, seqs + 1, 1), + opd((uint32_t)RAD_BF16, seqs, 1, ring, n), + opd((uint32_t)RAD_I32, seqs, 1) }; + R3D_PICK(list); +} + +/* The gated Hadamard int8: a [M, n], b [M, n] (optional, fused gate_up when absent), q [M, n] i8, + * scale [M]. */ +int r3d_shape_gated_had_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, 1) }; + R3D_PICK(list); +} + +/* The rotated fp8: x [M, n], q [M, n] E4M3, scale [M, n/group]. */ +int r3d_shape_had_quant_act_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, ng) }; + R3D_PICK(list); +} + +/* The gated rotated fp8: gate_up [M, 2n], q [M, n] E4M3, scale [M, n/group], out_bf16 [M, n]. */ +int r3d_shape_gated_had_quant_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, M, ng), opd(D, M, n) }; + R3D_PICK(list); +} + +/* The column fp8: x [M, n], y [M, n] E4M3, scale [n] (one per column). */ +int r3d_shape_quant_cols_fp8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_F8E4M3, M, n), + opd((uint32_t)RAD_F32, n, 1) }; + R3D_PICK(list); +} + +/* The rotated grouped int8: x [M, n], q [M, n] i8 (row-major), scale [M, n/group]. */ +int r3d_shape_had_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { opd(D, M, n), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, ng) }; + R3D_PICK(list); +} + +/* The gated rotated grouped int8: gate_up [M, 2n], q [M, n] i8 (row-major), scale [M, n/group]. */ +int r3d_shape_gated_had_quant_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const int64_t ng = scale_groups(n, gi(p, n_p, "group", 0)); + const RadOpdDesc list[] = { opd(D, M, 2 * n), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, ng), opd(D, M, n) }; + R3D_PICK(list); +} + +/* The RMS norm + per-row int8: x [M, n], residual [M, n] (optional), w [n], q [M, n] i8, + * scale [M], out_bf16 [M, n] (optional), w_post [n] (optional), scalar [1] (optional). */ +int r3d_shape_rmsnorm_quant_i8(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + const RadOpdDesc list[] = { opd(D, M, n), opd(D, M, n), opd(D, n, 1), opd((uint32_t)RAD_I8, M, n), + opd((uint32_t)RAD_F32, M, 1), opd(D, M, n), opd(D, n, 1), + opd(D, 1, 1) }; + R3D_PICK(list); +} + int r3d_shape_quant_act_i8g(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); diff --git a/libr3d/r3d_vocab_bf16.hip b/libr3d/r3d_vocab_bf16.hip index 7de9a44b..336e8db8 100644 --- a/libr3d/r3d_vocab_bf16.hip +++ b/libr3d/r3d_vocab_bf16.hip @@ -205,14 +205,15 @@ __device__ __forceinline__ uint32_t cvt_pk_f16_fp8(uint32_t b) #endif } +template /* ALU=1: the per-byte ALU decode (no table); ALU=0: the LDS table */ __device__ __forceinline__ void codes8_to_f16x4(const uint2 c, int cdt, const uint16_t* tbl, - uint32_t* w) + uint32_t* w) { const uint32_t d[2] = { c.x, c.y }; - if (tbl && !cdt) { - /* The LDS table: eight reads for eight codes, built from the codec below, so the results - * are identical (r3d_fp8_dequant.h). A null tbl selects the codec. */ - r3d_e4m3x8_ld(tbl, c, w); + if (!cdt && (ALU || tbl)) { + /* The shared E4M3 decode: ALU=1 the per-byte formula, ALU=0 the LDS table + * (r3d_fp8_dequant.h). A null tbl with ALU=0 selects the codec below. */ + r3d_e4m3x8_decode(tbl, c, w); return; } if (!cdt) { @@ -302,7 +303,7 @@ __device__ __forceinline__ uint2 loadc8(const uint8_t* p) * * y is f32 for logits_gemm and bf16 for gemm_nt (`YF32`). WQ reads the quantised head through h. */ -template +template __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(2) gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b, HeadQ h, void* __restrict__ y, int M, int N, int K, int a_ld, int y_ld) @@ -314,7 +315,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b const int tid = (int)threadIdx.x; __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; /* the E4M3 decoder, 512 bytes */ if (WQ) r3d_e4m3_f16_init(sTbl, tid, kBlockThreads); /* fills, then barriers */ - const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; + const uint16_t* const r3d_tbl = (WQ && !ALU) ? sTbl : (const uint16_t*)nullptr; const int m0 = (int)blockIdx.y * kTM; const int n0 = (int)blockIdx.x * kTN; const int rg = tid >> 4, cg = tid & 15; /* this lane's 8x8 square */ @@ -349,7 +350,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b * the scale is indexed by this staged row n, not the lane's output row. */ const uint2 c = *(const uint2*)(h.codes + (long long)n * h.code_row + k); uint32_t w[4]; - codes8_to_f16x4(c, h.cdt, r3d_tbl, w); + codes8_to_f16x4(c, h.cdt, r3d_tbl, w); const float sc = scale_at(h, n, k); staged = make_uint4(scale_pair(w[0], sc), scale_pair(w[1], sc), scale_pair(w[2], sc), scale_pair(w[3], sc)); @@ -421,7 +422,7 @@ gemm_tiled_kernel(const uint16_t* __restrict__ a, const uint16_t* __restrict__ b * ascending order. The activation tile is block-wide, so every thread stages it, including lanes * whose weight row is past the vocabulary; those lanes skip the dot and the store. */ -template +template __global__ void __launch_bounds__(kBlockThreads) R3D_WAVES(4) logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, HeadQ h, void* __restrict__ y, int M, int N, int K, int x_ld, int y_ld) @@ -431,8 +432,8 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ __shared__ __align__(16) uint16_t sX[MT * kChunkK]; /* f16, MT rows x chunk, swizzled */ __shared__ __align__(16) uint16_t sTbl[R3D_E4M3_TBL]; - if (WQ) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads); - const uint16_t* const r3d_tbl = WQ ? sTbl : (const uint16_t*)nullptr; + if (WQ && !ALU) r3d_e4m3_f16_init(sTbl, (int)threadIdx.x, kBlockThreads); + const uint16_t* const r3d_tbl = (WQ && !ALU) ? sTbl : (const uint16_t*)nullptr; const int lane = (int)threadIdx.x & (kWave - 1); const int warp = (int)threadIdx.x / kWave; @@ -467,7 +468,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ uint32_t w0, w1, w2, w3; if (WQ) { uint32_t q[4]; - codes8_to_f16x4(loadc8(cp + kc), h.cdt, r3d_tbl, q); + codes8_to_f16x4(loadc8(cp + kc), h.cdt, r3d_tbl, q); w0 = scale_pair(q[0], sc); w1 = scale_pair(q[1], sc); w2 = scale_pair(q[2], sc); w3 = scale_pair(q[3], sc); } else { @@ -498,7 +499,7 @@ logits_skinny_kernel(const uint16_t* __restrict__ x, const uint16_t* __restrict_ */ template int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ld, int sk, int kb, - int nt, long stream, const HeadQ* hq = nullptr) + int nt, long stream, const HeadQ* hq = nullptr, int alu = 1) { if (!xv || !wv || !yv) return -1; if (M < 1 || N < 1 || K < 1) return -2; @@ -538,18 +539,22 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ } if (M <= kSkinnyMax) { -#define R3D_SKINNY(MTV, NTV, WQV) \ +#define R3D_SKINNY(MTV, NTV, WQV, ALUV) \ do { \ const int klw = kWave / (MTV); \ const int per = kWaves * klw; \ const dim3 grid((unsigned)((N + per - 1) / per)), block(kBlockThreads); \ - R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel)), grid, block, s, x, w, \ + R3D_KLAUNCH(R3D_KNAME((logits_skinny_kernel)), grid, block, s, x, w, \ h, y, M, N, K, x_ld, y_ld); \ } while (0) #define R3D_SKINNY_MT(MTV) \ do { \ - if (wq) { if (nt) R3D_SKINNY(MTV, 1, 1); else R3D_SKINNY(MTV, 0, 1); } \ - else { if (nt) R3D_SKINNY(MTV, 1, 0); else R3D_SKINNY(MTV, 0, 0); } \ + if (wq) { \ + if (alu) { if (nt) R3D_SKINNY(MTV, 1, 1, 1); else R3D_SKINNY(MTV, 0, 1, 1); } \ + else { if (nt) R3D_SKINNY(MTV, 1, 1, 0); else R3D_SKINNY(MTV, 0, 1, 0); } \ + } else { \ + if (nt) R3D_SKINNY(MTV, 1, 0, 0); else R3D_SKINNY(MTV, 0, 0, 0); \ + } \ } while (0) if (M == 1) R3D_SKINNY_MT(1); else if (M <= 2) R3D_SKINNY_MT(2); @@ -561,11 +566,15 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ } else { const dim3 grid((unsigned)((N + kTN - 1) / kTN), (unsigned)((M + kTM - 1) / kTM)); const dim3 block(kBlockThreads); - if (wq) - R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, - N, K, x_ld, y_ld); - else - R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, + if (wq) { + if (alu) + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, + N, K, x_ld, y_ld); + else + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, + N, K, x_ld, y_ld); + } else + R3D_KLAUNCH(R3D_KNAME((gemm_tiled_kernel)), grid, block, s, x, w, h, y, M, N, K, x_ld, y_ld); } return hipGetLastError() == hipSuccess ? 0 : -4; @@ -574,7 +583,7 @@ int gemm_launch(long xv, long wv, long yv, int M, int N, int K, int x_ld, int y_ /* The shim body both ops share (ref_logits_gemm is gemm_nt_impl with the axes renamed). * `y_is_f32` is the op's output dtype; nkey/kkey are libref's axis names ("n_vocab"/"n_embd" or * "N"/"K"). */ -int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey) +int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const char* kkey, int alu) { if (a->n_t < 3 || !a->t[0].data || !a->t[1].data || !a->t[2].data) return R3D_NO(RAD_E_INVAL); @@ -663,9 +672,9 @@ int rad_gemm_run(const RadArgs* a, RadStream s, int y_is_f32, const char* nkey, const HeadQ* hp = joined ? &h : nullptr; const int e = y_is_f32 ? gemm_launch(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K, - (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp) + (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp, alu) : gemm_launch(r3d_addr(x), r3d_addr(w), r3d_addr(y), (int)M, (int)N, (int)K, - (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp); + (int)x_pitch, (int)y_pitch, sk, kb, nt, (long)(uintptr_t)s, hp, alu); if (e == 0) return RAD_OK; return R3D_NO(e == -1 ? RAD_E_INVAL : e == -2 ? RAD_E_SHAPE : e == -3 ? RAD_E_STRIDE : e == -5 ? RAD_E_ALIGN : RAD_E_DEVICE); @@ -714,15 +723,35 @@ extern "C" int r3d_gemm_nt_bf16_tiled(long a, long b, long y, int M, int N, int return gemm_launch(a, b, y, M, N, K, a_ld, y_ld, sk, kb, nt, stream); } +static int r3d_logits_gemm_bf16_dispatch(const RadArgs* a, RadStream s, int alu) +{ return rad_gemm_run(a, s, 1, "n_vocab", "n_embd", alu); } +static int r3d_gemm_nt_bf16_tiled_dispatch(const RadArgs* a, RadStream s, int alu) +{ return rad_gemm_run(a, s, 0, "N", "K", alu); } + +extern "C" int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs*, RadStream); +extern "C" int r3d_rad_gemm_nt_bf16_m64_wmma(const RadArgs*, RadStream); + +/* The rows' impl axis picks the kernel: the table decode (0) and the ALU decode (1) share the + * dispatch, and the bf16 tiled row's two wave-matrix arms (2 = the 128x128 tile, 3 = the + * 16-column-tile kernel) run through their own shims, which stay as entry points. */ extern "C" int r3d_rad_logits_gemm_bf16(const RadArgs* a, RadStream s) { - return rad_gemm_run(a, s, 1, "n_vocab", "n_embd"); + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + return r3d_logits_gemm_bf16_dispatch(a, s, c.impl); } - +extern "C" int r3d_rad_logits_gemm_bf16_alu(const RadArgs* a, RadStream s) +{ return r3d_logits_gemm_bf16_dispatch(a, s, 1); } extern "C" int r3d_rad_gemm_nt_bf16_tiled(const RadArgs* a, RadStream s) { - return rad_gemm_run(a, s, 0, "N", "K"); + R3dGemmCfg c; + r3d_cfg_gemm(a, &c); + if (c.impl <= 1) return r3d_gemm_nt_bf16_tiled_dispatch(a, s, c.impl); + if (c.impl == 2) return r3d_rad_gemm_nt_bf16_tiled_wmma(a, s); + return r3d_rad_gemm_nt_bf16_m64_wmma(a, s); } +extern "C" int r3d_rad_gemm_nt_bf16_tiled_alu(const RadArgs* a, RadStream s) +{ return r3d_gemm_nt_bf16_tiled_dispatch(a, s, 1); } /* The head's relayout writer. A layout query that answers RAD_OK promises the loader that * relayout will produce the described form (rad_abi.h). The container stores the quantiser's diff --git a/libr3d/r3d_vocab_bf16_wmma.hip b/libr3d/r3d_vocab_bf16_wmma.hip new file mode 100644 index 00000000..69bea796 --- /dev/null +++ b/libr3d/r3d_vocab_bf16_wmma.hip @@ -0,0 +1,152 @@ +/* r3d_vocab_bf16_wmma.hip -- the prefill tiled GEMM on the wave-matrix: the WMMA twin of the + * ALU fdot2 kernel in r3d_vocab_bf16.hip (the `gemm_nt_bf16_tiled` row's compute-dual). + * + * y[M,N] = a[M,K] @ w[N,K]^T, bf16 in, f32 accumulate, bf16 out (one narrowing at the store). + * + * The ALU arm owns 64 f32 accumulators a lane (an 8x8 square) and runs v_fdot2; this arm runs the + * same 128x128 tile on the wave-matrix, which is the matrix core at 512 FLOPS/clk/CU against the + * ALU's ~256, so it is the faster of the pair at prefill heights. The tile is split eight ways + * across the eight waves by column: wave w owns cols [w*16, w*16+16) and all 128 rows, so it + * accumulates eight 16x16 wave-matrix tiles (one per 16-row block) -- 64 f32 accumulators a wave, + * the same count the ALU arm keeps a lane. Every wave does unique work (the 16x128 wave-filling + * retile), so no wave re-runs a tile. + * + * K is walked in 32-deep chunks (two 16-wide wave-matrix steps); the operands stage to LDS as bf16 + * (16 dwords a row, +1 bank-free) and load straight into the bf16 wave-matrix fragments. + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_codecs.h" +#include "r3d_launch.h" + +namespace { + +constexpr int kThreads = 256; // eight waves +constexpr int kWaves = kThreads / kWave; +constexpr int kTM = 128; // activation rows a block +constexpr int kTN = 128; // weight cols a block +constexpr int kKC = 32; // k codes a chunk: two 16-wide wave-matrix steps +constexpr int kDW = kKC / 2; // dwords a row: 32 bf16 are 16 dwords (two bf16 a dword) +constexpr int kPitch = kDW + 1; // dwords a staged row: +1, bank-free + +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void vocab_bf16_wmma_kernel( + const uint16_t* __restrict__ a, + const uint16_t* __restrict__ w, + uint16_t* __restrict__ y, int M, int N, int K, int a_ld, int w_ld, int y_ld) +{ + __shared__ __align__(16) uint32_t sA[kTM * kPitch]; // 128 rows x 16 dwords + __shared__ __align__(16) uint32_t sB[kTN * kPitch]; // 128 cols x 16 dwords + + const uint32_t tid = threadIdx.x; + const uint32_t lane = tid & (kWave - 1); + const uint32_t wv = tid / kWave; // the wave index (0..7): owns cols wv*16..wv*16+16 + const uint32_t r = lane & 15; + + const uint32_t m0 = (uint32_t)blockIdx.y * kTM; + const uint32_t n0 = (uint32_t)blockIdx.x * kTN; + + // acc[8]: one 16x16 wave-matrix tile per 16-row block (128 rows / 16). + v8float acc[8]; + #pragma unroll + for (int i = 0; i < 8; ++i) acc[i] = v8float{ 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f }; + + for (int k0 = 0; k0 < K; k0 += kKC) { + // Stage 128 activation rows and 128 weight cols (16 dwords each), clamped at the edge. + for (int i = (int)tid; i < kTM * kDW; i += kThreads) { + const int row = i / kDW, d = i % kDW; + const int mm = (int)(m0 + row < (uint32_t)M ? m0 + row : (uint32_t)M - 1); + sA[row * kPitch + d] = *(const uint32_t*)(a + (size_t)mm * a_ld + k0 + 2 * d); + } + for (int i = (int)tid; i < kTN * kDW; i += kThreads) { + const int col = i / kDW, d = i % kDW; + const int nn = (int)(n0 + col < (uint32_t)N ? n0 + col : (uint32_t)N - 1); + sB[col * kPitch + d] = *(const uint32_t*)(w + (size_t)nn * w_ld + k0 + 2 * d); + } + group_barrier(); + + // Wave wv owns cols wv*16..wv*16+16, all eight 16-row blocks. + const uint32_t* wp = sB + (size_t)(wv * 16 + r) * kPitch; + #pragma unroll + for (int rb = 0; rb < 8; ++rb) { + const uint32_t* ap = sA + (size_t)(rb * 16 + r) * kPitch; + #pragma unroll + for (int k = 0; k < kKC; k += 16) { + v16short fa, fb; + #pragma unroll + for (int g = 0; g < 8; ++g) { + const uint32_t dw = ap[k / 2 + g]; + fa[2 * g] = (short)(dw & 0xffffu); fa[2 * g + 1] = (short)(dw >> 16); + const uint32_t dwb = wp[k / 2 + g]; + fb[2 * g] = (short)(dwb & 0xffffu); fb[2 * g + 1] = (short)(dwb >> 16); + } + acc[rb] = wmma_bf16(fa, fb, acc[rb]); + } + } + group_barrier(); + } + + // Store: C-frag lane l, VGPR g -> row 2*(l>>4)+g, col l&15; offset by the row block and wave. + #pragma unroll + for (int rb = 0; rb < 8; ++rb) + #pragma unroll + for (int g = 0; g < 8; ++g) { + const int m = m0 + rb * 16 + 2 * g + (lane >> 4); + const int n = n0 + wv * 16 + r; + if (m < M && n < N) y[m * y_ld + n] = f32_to_bf16(acc[rb][g]); + } +} + +int r3d_vocab_bf16_wmma(long av, long wv, long yv, int M, int N, int K, int a_ld, int w_ld, + int y_ld, long stream) +{ + if (!av || !wv || !yv) return -1; + if (M < 1 || N < 1 || K < 1) return -2; + if (K % kKC) return -2; // the tile's k-chunk; the M/N tails clamp and are dropped at the store + if (!a_ld) a_ld = K; + if (!w_ld) w_ld = K; + if (!y_ld) y_ld = N; + if (a_ld < K || w_ld < K || y_ld < N) return -3; + if ((av & 15) || (wv & 15) || (yv & 15)) return -5; + + const uint16_t* a = (const uint16_t*)(uintptr_t)av; + const uint16_t* w = (const uint16_t*)(uintptr_t)wv; + uint16_t* y = (uint16_t*)(uintptr_t)yv; + hipStream_t s = (hipStream_t)(uintptr_t)stream; + + dim3 grid((unsigned)(N + kTN - 1) / kTN, (unsigned)(M + kTM - 1) / kTM), blk(kThreads); + vocab_bf16_wmma_kernel<<>>(a, w, y, M, N, K, a_ld, w_ld, y_ld); + return (int)hipGetLastError(); +} + +} // namespace + +extern "C" { + +int r3d_gemm_nt_bf16_tiled_wmma(long a, long b, long y, int M, int N, int K, int a_ld, int w_ld, + int y_ld, long stream) +{ return r3d_vocab_bf16_wmma(a, b, y, M, N, K, a_ld, w_ld, y_ld, stream); } + +int r3d_rad_gemm_nt_bf16_tiled_wmma(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor* at = &a->t[0], *wt = &a->t[1], *yt = &a->t[2]; + if (!r3d_p(at) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL); + if (at->dtype != RAD_BF16 || wt->dtype != RAD_BF16 || yt->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); // the plain bf16 head; the quantised form is the ALU arm's + long long M = 0, K = 0; + if (r3d_rows_of(at, &M, &K) != 0) return R3D_NO(RAD_E_INVAL); + const long long N = (wt->rank >= 2) ? wt->shape[0] : 0; + if (M <= 0 || N <= 0 || K <= 0 || (K & 31)) + return R3D_NO(RAD_E_SHAPE); // the 128x128 tile, 32-deep k chunks; the M/N tails clamp + const int a_ld = (int)at->stride[0]; + const int w_ld = (int)wt->stride[0]; + const int y_ld = (int)yt->stride[0]; + return r3d_vocab_bf16_wmma((long)(uintptr_t)r3d_p(at), (long)(uintptr_t)r3d_p(wt), + (long)(uintptr_t)r3d_wp(yt), (int)M, (int)N, (int)K, a_ld, w_ld, + y_ld, (long)(uintptr_t)s); +} + +} // extern "C"